]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/md/dm-crypt.c
dm crypt: separate essiv allocation from initialisation
[karo-tx-linux.git] / drivers / md / dm-crypt.c
1 /*
2  * Copyright (C) 2003 Christophe Saout <christophe@saout.de>
3  * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
4  * Copyright (C) 2006-2008 Red Hat, Inc. All rights reserved.
5  *
6  * This file is released under the GPL.
7  */
8
9 #include <linux/completion.h>
10 #include <linux/err.h>
11 #include <linux/module.h>
12 #include <linux/init.h>
13 #include <linux/kernel.h>
14 #include <linux/bio.h>
15 #include <linux/blkdev.h>
16 #include <linux/mempool.h>
17 #include <linux/slab.h>
18 #include <linux/crypto.h>
19 #include <linux/workqueue.h>
20 #include <linux/backing-dev.h>
21 #include <asm/atomic.h>
22 #include <linux/scatterlist.h>
23 #include <asm/page.h>
24 #include <asm/unaligned.h>
25
26 #include <linux/device-mapper.h>
27
28 #define DM_MSG_PREFIX "crypt"
29 #define MESG_STR(x) x, sizeof(x)
30
31 /*
32  * context holding the current state of a multi-part conversion
33  */
34 struct convert_context {
35         struct completion restart;
36         struct bio *bio_in;
37         struct bio *bio_out;
38         unsigned int offset_in;
39         unsigned int offset_out;
40         unsigned int idx_in;
41         unsigned int idx_out;
42         sector_t sector;
43         atomic_t pending;
44 };
45
46 /*
47  * per bio private data
48  */
49 struct dm_crypt_io {
50         struct dm_target *target;
51         struct bio *base_bio;
52         struct work_struct work;
53
54         struct convert_context ctx;
55
56         atomic_t pending;
57         int error;
58         sector_t sector;
59         struct dm_crypt_io *base_io;
60 };
61
62 struct dm_crypt_request {
63         struct convert_context *ctx;
64         struct scatterlist sg_in;
65         struct scatterlist sg_out;
66 };
67
68 struct crypt_config;
69
70 struct crypt_iv_operations {
71         int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
72                    const char *opts);
73         void (*dtr)(struct crypt_config *cc);
74         int (*init)(struct crypt_config *cc);
75         int (*generator)(struct crypt_config *cc, u8 *iv, sector_t sector);
76 };
77
78 struct iv_essiv_private {
79         struct crypto_cipher *tfm;
80         struct crypto_hash *hash_tfm;
81         u8 *salt;
82 };
83
84 struct iv_benbi_private {
85         int shift;
86 };
87
88 /*
89  * Crypt: maps a linear range of a block device
90  * and encrypts / decrypts at the same time.
91  */
92 enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID };
93 struct crypt_config {
94         struct dm_dev *dev;
95         sector_t start;
96
97         /*
98          * pool for per bio private data, crypto requests and
99          * encryption requeusts/buffer pages
100          */
101         mempool_t *io_pool;
102         mempool_t *req_pool;
103         mempool_t *page_pool;
104         struct bio_set *bs;
105
106         struct workqueue_struct *io_queue;
107         struct workqueue_struct *crypt_queue;
108
109         /*
110          * crypto related data
111          */
112         struct crypt_iv_operations *iv_gen_ops;
113         char *iv_mode;
114         union {
115                 struct iv_essiv_private essiv;
116                 struct iv_benbi_private benbi;
117         } iv_gen_private;
118         sector_t iv_offset;
119         unsigned int iv_size;
120
121         /*
122          * Layout of each crypto request:
123          *
124          *   struct ablkcipher_request
125          *      context
126          *      padding
127          *   struct dm_crypt_request
128          *      padding
129          *   IV
130          *
131          * The padding is added so that dm_crypt_request and the IV are
132          * correctly aligned.
133          */
134         unsigned int dmreq_start;
135         struct ablkcipher_request *req;
136
137         char cipher[CRYPTO_MAX_ALG_NAME];
138         char chainmode[CRYPTO_MAX_ALG_NAME];
139         struct crypto_ablkcipher *tfm;
140         unsigned long flags;
141         unsigned int key_size;
142         u8 key[0];
143 };
144
145 #define MIN_IOS        16
146 #define MIN_POOL_PAGES 32
147 #define MIN_BIO_PAGES  8
148
149 static struct kmem_cache *_crypt_io_pool;
150
151 static void clone_init(struct dm_crypt_io *, struct bio *);
152 static void kcryptd_queue_crypt(struct dm_crypt_io *io);
153
154 /*
155  * Different IV generation algorithms:
156  *
157  * plain: the initial vector is the 32-bit little-endian version of the sector
158  *        number, padded with zeros if necessary.
159  *
160  * essiv: "encrypted sector|salt initial vector", the sector number is
161  *        encrypted with the bulk cipher using a salt as key. The salt
162  *        should be derived from the bulk cipher's key via hashing.
163  *
164  * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
165  *        (needed for LRW-32-AES and possible other narrow block modes)
166  *
167  * null: the initial vector is always zero.  Provides compatibility with
168  *       obsolete loop_fish2 devices.  Do not use for new devices.
169  *
170  * plumb: unimplemented, see:
171  * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
172  */
173
174 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
175 {
176         memset(iv, 0, cc->iv_size);
177         *(u32 *)iv = cpu_to_le32(sector & 0xffffffff);
178
179         return 0;
180 }
181
182 /* Initialise ESSIV - compute salt but no local memory allocations */
183 static int crypt_iv_essiv_init(struct crypt_config *cc)
184 {
185         struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
186         struct hash_desc desc;
187         struct scatterlist sg;
188         int err;
189
190         sg_init_one(&sg, cc->key, cc->key_size);
191         desc.tfm = essiv->hash_tfm;
192         desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
193
194         err = crypto_hash_digest(&desc, &sg, cc->key_size, essiv->salt);
195         if (err)
196                 return err;
197
198         return crypto_cipher_setkey(essiv->tfm, essiv->salt,
199                                     crypto_hash_digestsize(essiv->hash_tfm));
200 }
201
202 static void crypt_iv_essiv_dtr(struct crypt_config *cc)
203 {
204         struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
205
206         crypto_free_cipher(essiv->tfm);
207         essiv->tfm = NULL;
208
209         crypto_free_hash(essiv->hash_tfm);
210         essiv->hash_tfm = NULL;
211
212         kzfree(essiv->salt);
213         essiv->salt = NULL;
214 }
215
216 static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
217                               const char *opts)
218 {
219         struct crypto_cipher *essiv_tfm = NULL;
220         struct crypto_hash *hash_tfm = NULL;
221         u8 *salt = NULL;
222         int err;
223
224         if (!opts) {
225                 ti->error = "Digest algorithm missing for ESSIV mode";
226                 return -EINVAL;
227         }
228
229         /* Allocate hash algorithm */
230         hash_tfm = crypto_alloc_hash(opts, 0, CRYPTO_ALG_ASYNC);
231         if (IS_ERR(hash_tfm)) {
232                 ti->error = "Error initializing ESSIV hash";
233                 err = PTR_ERR(hash_tfm);
234                 goto bad;
235         }
236
237         salt = kzalloc(crypto_hash_digestsize(hash_tfm), GFP_KERNEL);
238         if (!salt) {
239                 ti->error = "Error kmallocing salt storage in ESSIV";
240                 err = -ENOMEM;
241                 goto bad;
242         }
243
244         /* Allocate essiv_tfm */
245         essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
246         if (IS_ERR(essiv_tfm)) {
247                 ti->error = "Error allocating crypto tfm for ESSIV";
248                 err = PTR_ERR(essiv_tfm);
249                 goto bad;
250         }
251         if (crypto_cipher_blocksize(essiv_tfm) !=
252             crypto_ablkcipher_ivsize(cc->tfm)) {
253                 ti->error = "Block size of ESSIV cipher does "
254                             "not match IV size of block cipher";
255                 err = -EINVAL;
256                 goto bad;
257         }
258
259         cc->iv_gen_private.essiv.salt = salt;
260         cc->iv_gen_private.essiv.tfm = essiv_tfm;
261         cc->iv_gen_private.essiv.hash_tfm = hash_tfm;
262
263         return 0;
264
265 bad:
266         if (essiv_tfm && !IS_ERR(essiv_tfm))
267                 crypto_free_cipher(essiv_tfm);
268         if (hash_tfm && !IS_ERR(hash_tfm))
269                 crypto_free_hash(hash_tfm);
270         kfree(salt);
271         return err;
272 }
273
274 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
275 {
276         memset(iv, 0, cc->iv_size);
277         *(u64 *)iv = cpu_to_le64(sector);
278         crypto_cipher_encrypt_one(cc->iv_gen_private.essiv.tfm, iv, iv);
279         return 0;
280 }
281
282 static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
283                               const char *opts)
284 {
285         unsigned bs = crypto_ablkcipher_blocksize(cc->tfm);
286         int log = ilog2(bs);
287
288         /* we need to calculate how far we must shift the sector count
289          * to get the cipher block count, we use this shift in _gen */
290
291         if (1 << log != bs) {
292                 ti->error = "cypher blocksize is not a power of 2";
293                 return -EINVAL;
294         }
295
296         if (log > 9) {
297                 ti->error = "cypher blocksize is > 512";
298                 return -EINVAL;
299         }
300
301         cc->iv_gen_private.benbi.shift = 9 - log;
302
303         return 0;
304 }
305
306 static void crypt_iv_benbi_dtr(struct crypt_config *cc)
307 {
308 }
309
310 static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
311 {
312         __be64 val;
313
314         memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
315
316         val = cpu_to_be64(((u64)sector << cc->iv_gen_private.benbi.shift) + 1);
317         put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
318
319         return 0;
320 }
321
322 static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
323 {
324         memset(iv, 0, cc->iv_size);
325
326         return 0;
327 }
328
329 static struct crypt_iv_operations crypt_iv_plain_ops = {
330         .generator = crypt_iv_plain_gen
331 };
332
333 static struct crypt_iv_operations crypt_iv_essiv_ops = {
334         .ctr       = crypt_iv_essiv_ctr,
335         .dtr       = crypt_iv_essiv_dtr,
336         .init      = crypt_iv_essiv_init,
337         .generator = crypt_iv_essiv_gen
338 };
339
340 static struct crypt_iv_operations crypt_iv_benbi_ops = {
341         .ctr       = crypt_iv_benbi_ctr,
342         .dtr       = crypt_iv_benbi_dtr,
343         .generator = crypt_iv_benbi_gen
344 };
345
346 static struct crypt_iv_operations crypt_iv_null_ops = {
347         .generator = crypt_iv_null_gen
348 };
349
350 static void crypt_convert_init(struct crypt_config *cc,
351                                struct convert_context *ctx,
352                                struct bio *bio_out, struct bio *bio_in,
353                                sector_t sector)
354 {
355         ctx->bio_in = bio_in;
356         ctx->bio_out = bio_out;
357         ctx->offset_in = 0;
358         ctx->offset_out = 0;
359         ctx->idx_in = bio_in ? bio_in->bi_idx : 0;
360         ctx->idx_out = bio_out ? bio_out->bi_idx : 0;
361         ctx->sector = sector + cc->iv_offset;
362         init_completion(&ctx->restart);
363 }
364
365 static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
366                                              struct ablkcipher_request *req)
367 {
368         return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
369 }
370
371 static struct ablkcipher_request *req_of_dmreq(struct crypt_config *cc,
372                                                struct dm_crypt_request *dmreq)
373 {
374         return (struct ablkcipher_request *)((char *)dmreq - cc->dmreq_start);
375 }
376
377 static int crypt_convert_block(struct crypt_config *cc,
378                                struct convert_context *ctx,
379                                struct ablkcipher_request *req)
380 {
381         struct bio_vec *bv_in = bio_iovec_idx(ctx->bio_in, ctx->idx_in);
382         struct bio_vec *bv_out = bio_iovec_idx(ctx->bio_out, ctx->idx_out);
383         struct dm_crypt_request *dmreq;
384         u8 *iv;
385         int r = 0;
386
387         dmreq = dmreq_of_req(cc, req);
388         iv = (u8 *)ALIGN((unsigned long)(dmreq + 1),
389                          crypto_ablkcipher_alignmask(cc->tfm) + 1);
390
391         dmreq->ctx = ctx;
392         sg_init_table(&dmreq->sg_in, 1);
393         sg_set_page(&dmreq->sg_in, bv_in->bv_page, 1 << SECTOR_SHIFT,
394                     bv_in->bv_offset + ctx->offset_in);
395
396         sg_init_table(&dmreq->sg_out, 1);
397         sg_set_page(&dmreq->sg_out, bv_out->bv_page, 1 << SECTOR_SHIFT,
398                     bv_out->bv_offset + ctx->offset_out);
399
400         ctx->offset_in += 1 << SECTOR_SHIFT;
401         if (ctx->offset_in >= bv_in->bv_len) {
402                 ctx->offset_in = 0;
403                 ctx->idx_in++;
404         }
405
406         ctx->offset_out += 1 << SECTOR_SHIFT;
407         if (ctx->offset_out >= bv_out->bv_len) {
408                 ctx->offset_out = 0;
409                 ctx->idx_out++;
410         }
411
412         if (cc->iv_gen_ops) {
413                 r = cc->iv_gen_ops->generator(cc, iv, ctx->sector);
414                 if (r < 0)
415                         return r;
416         }
417
418         ablkcipher_request_set_crypt(req, &dmreq->sg_in, &dmreq->sg_out,
419                                      1 << SECTOR_SHIFT, iv);
420
421         if (bio_data_dir(ctx->bio_in) == WRITE)
422                 r = crypto_ablkcipher_encrypt(req);
423         else
424                 r = crypto_ablkcipher_decrypt(req);
425
426         return r;
427 }
428
429 static void kcryptd_async_done(struct crypto_async_request *async_req,
430                                int error);
431 static void crypt_alloc_req(struct crypt_config *cc,
432                             struct convert_context *ctx)
433 {
434         if (!cc->req)
435                 cc->req = mempool_alloc(cc->req_pool, GFP_NOIO);
436         ablkcipher_request_set_tfm(cc->req, cc->tfm);
437         ablkcipher_request_set_callback(cc->req, CRYPTO_TFM_REQ_MAY_BACKLOG |
438                                         CRYPTO_TFM_REQ_MAY_SLEEP,
439                                         kcryptd_async_done,
440                                         dmreq_of_req(cc, cc->req));
441 }
442
443 /*
444  * Encrypt / decrypt data from one bio to another one (can be the same one)
445  */
446 static int crypt_convert(struct crypt_config *cc,
447                          struct convert_context *ctx)
448 {
449         int r;
450
451         atomic_set(&ctx->pending, 1);
452
453         while(ctx->idx_in < ctx->bio_in->bi_vcnt &&
454               ctx->idx_out < ctx->bio_out->bi_vcnt) {
455
456                 crypt_alloc_req(cc, ctx);
457
458                 atomic_inc(&ctx->pending);
459
460                 r = crypt_convert_block(cc, ctx, cc->req);
461
462                 switch (r) {
463                 /* async */
464                 case -EBUSY:
465                         wait_for_completion(&ctx->restart);
466                         INIT_COMPLETION(ctx->restart);
467                         /* fall through*/
468                 case -EINPROGRESS:
469                         cc->req = NULL;
470                         ctx->sector++;
471                         continue;
472
473                 /* sync */
474                 case 0:
475                         atomic_dec(&ctx->pending);
476                         ctx->sector++;
477                         cond_resched();
478                         continue;
479
480                 /* error */
481                 default:
482                         atomic_dec(&ctx->pending);
483                         return r;
484                 }
485         }
486
487         return 0;
488 }
489
490 static void dm_crypt_bio_destructor(struct bio *bio)
491 {
492         struct dm_crypt_io *io = bio->bi_private;
493         struct crypt_config *cc = io->target->private;
494
495         bio_free(bio, cc->bs);
496 }
497
498 /*
499  * Generate a new unfragmented bio with the given size
500  * This should never violate the device limitations
501  * May return a smaller bio when running out of pages, indicated by
502  * *out_of_pages set to 1.
503  */
504 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size,
505                                       unsigned *out_of_pages)
506 {
507         struct crypt_config *cc = io->target->private;
508         struct bio *clone;
509         unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
510         gfp_t gfp_mask = GFP_NOIO | __GFP_HIGHMEM;
511         unsigned i, len;
512         struct page *page;
513
514         clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, cc->bs);
515         if (!clone)
516                 return NULL;
517
518         clone_init(io, clone);
519         *out_of_pages = 0;
520
521         for (i = 0; i < nr_iovecs; i++) {
522                 page = mempool_alloc(cc->page_pool, gfp_mask);
523                 if (!page) {
524                         *out_of_pages = 1;
525                         break;
526                 }
527
528                 /*
529                  * if additional pages cannot be allocated without waiting,
530                  * return a partially allocated bio, the caller will then try
531                  * to allocate additional bios while submitting this partial bio
532                  */
533                 if (i == (MIN_BIO_PAGES - 1))
534                         gfp_mask = (gfp_mask | __GFP_NOWARN) & ~__GFP_WAIT;
535
536                 len = (size > PAGE_SIZE) ? PAGE_SIZE : size;
537
538                 if (!bio_add_page(clone, page, len, 0)) {
539                         mempool_free(page, cc->page_pool);
540                         break;
541                 }
542
543                 size -= len;
544         }
545
546         if (!clone->bi_size) {
547                 bio_put(clone);
548                 return NULL;
549         }
550
551         return clone;
552 }
553
554 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
555 {
556         unsigned int i;
557         struct bio_vec *bv;
558
559         for (i = 0; i < clone->bi_vcnt; i++) {
560                 bv = bio_iovec_idx(clone, i);
561                 BUG_ON(!bv->bv_page);
562                 mempool_free(bv->bv_page, cc->page_pool);
563                 bv->bv_page = NULL;
564         }
565 }
566
567 static struct dm_crypt_io *crypt_io_alloc(struct dm_target *ti,
568                                           struct bio *bio, sector_t sector)
569 {
570         struct crypt_config *cc = ti->private;
571         struct dm_crypt_io *io;
572
573         io = mempool_alloc(cc->io_pool, GFP_NOIO);
574         io->target = ti;
575         io->base_bio = bio;
576         io->sector = sector;
577         io->error = 0;
578         io->base_io = NULL;
579         atomic_set(&io->pending, 0);
580
581         return io;
582 }
583
584 static void crypt_inc_pending(struct dm_crypt_io *io)
585 {
586         atomic_inc(&io->pending);
587 }
588
589 /*
590  * One of the bios was finished. Check for completion of
591  * the whole request and correctly clean up the buffer.
592  * If base_io is set, wait for the last fragment to complete.
593  */
594 static void crypt_dec_pending(struct dm_crypt_io *io)
595 {
596         struct crypt_config *cc = io->target->private;
597         struct bio *base_bio = io->base_bio;
598         struct dm_crypt_io *base_io = io->base_io;
599         int error = io->error;
600
601         if (!atomic_dec_and_test(&io->pending))
602                 return;
603
604         mempool_free(io, cc->io_pool);
605
606         if (likely(!base_io))
607                 bio_endio(base_bio, error);
608         else {
609                 if (error && !base_io->error)
610                         base_io->error = error;
611                 crypt_dec_pending(base_io);
612         }
613 }
614
615 /*
616  * kcryptd/kcryptd_io:
617  *
618  * Needed because it would be very unwise to do decryption in an
619  * interrupt context.
620  *
621  * kcryptd performs the actual encryption or decryption.
622  *
623  * kcryptd_io performs the IO submission.
624  *
625  * They must be separated as otherwise the final stages could be
626  * starved by new requests which can block in the first stages due
627  * to memory allocation.
628  */
629 static void crypt_endio(struct bio *clone, int error)
630 {
631         struct dm_crypt_io *io = clone->bi_private;
632         struct crypt_config *cc = io->target->private;
633         unsigned rw = bio_data_dir(clone);
634
635         if (unlikely(!bio_flagged(clone, BIO_UPTODATE) && !error))
636                 error = -EIO;
637
638         /*
639          * free the processed pages
640          */
641         if (rw == WRITE)
642                 crypt_free_buffer_pages(cc, clone);
643
644         bio_put(clone);
645
646         if (rw == READ && !error) {
647                 kcryptd_queue_crypt(io);
648                 return;
649         }
650
651         if (unlikely(error))
652                 io->error = error;
653
654         crypt_dec_pending(io);
655 }
656
657 static void clone_init(struct dm_crypt_io *io, struct bio *clone)
658 {
659         struct crypt_config *cc = io->target->private;
660
661         clone->bi_private = io;
662         clone->bi_end_io  = crypt_endio;
663         clone->bi_bdev    = cc->dev->bdev;
664         clone->bi_rw      = io->base_bio->bi_rw;
665         clone->bi_destructor = dm_crypt_bio_destructor;
666 }
667
668 static void kcryptd_io_read(struct dm_crypt_io *io)
669 {
670         struct crypt_config *cc = io->target->private;
671         struct bio *base_bio = io->base_bio;
672         struct bio *clone;
673
674         crypt_inc_pending(io);
675
676         /*
677          * The block layer might modify the bvec array, so always
678          * copy the required bvecs because we need the original
679          * one in order to decrypt the whole bio data *afterwards*.
680          */
681         clone = bio_alloc_bioset(GFP_NOIO, bio_segments(base_bio), cc->bs);
682         if (unlikely(!clone)) {
683                 io->error = -ENOMEM;
684                 crypt_dec_pending(io);
685                 return;
686         }
687
688         clone_init(io, clone);
689         clone->bi_idx = 0;
690         clone->bi_vcnt = bio_segments(base_bio);
691         clone->bi_size = base_bio->bi_size;
692         clone->bi_sector = cc->start + io->sector;
693         memcpy(clone->bi_io_vec, bio_iovec(base_bio),
694                sizeof(struct bio_vec) * clone->bi_vcnt);
695
696         generic_make_request(clone);
697 }
698
699 static void kcryptd_io_write(struct dm_crypt_io *io)
700 {
701         struct bio *clone = io->ctx.bio_out;
702         generic_make_request(clone);
703 }
704
705 static void kcryptd_io(struct work_struct *work)
706 {
707         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
708
709         if (bio_data_dir(io->base_bio) == READ)
710                 kcryptd_io_read(io);
711         else
712                 kcryptd_io_write(io);
713 }
714
715 static void kcryptd_queue_io(struct dm_crypt_io *io)
716 {
717         struct crypt_config *cc = io->target->private;
718
719         INIT_WORK(&io->work, kcryptd_io);
720         queue_work(cc->io_queue, &io->work);
721 }
722
723 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io,
724                                           int error, int async)
725 {
726         struct bio *clone = io->ctx.bio_out;
727         struct crypt_config *cc = io->target->private;
728
729         if (unlikely(error < 0)) {
730                 crypt_free_buffer_pages(cc, clone);
731                 bio_put(clone);
732                 io->error = -EIO;
733                 crypt_dec_pending(io);
734                 return;
735         }
736
737         /* crypt_convert should have filled the clone bio */
738         BUG_ON(io->ctx.idx_out < clone->bi_vcnt);
739
740         clone->bi_sector = cc->start + io->sector;
741
742         if (async)
743                 kcryptd_queue_io(io);
744         else
745                 generic_make_request(clone);
746 }
747
748 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
749 {
750         struct crypt_config *cc = io->target->private;
751         struct bio *clone;
752         struct dm_crypt_io *new_io;
753         int crypt_finished;
754         unsigned out_of_pages = 0;
755         unsigned remaining = io->base_bio->bi_size;
756         sector_t sector = io->sector;
757         int r;
758
759         /*
760          * Prevent io from disappearing until this function completes.
761          */
762         crypt_inc_pending(io);
763         crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
764
765         /*
766          * The allocated buffers can be smaller than the whole bio,
767          * so repeat the whole process until all the data can be handled.
768          */
769         while (remaining) {
770                 clone = crypt_alloc_buffer(io, remaining, &out_of_pages);
771                 if (unlikely(!clone)) {
772                         io->error = -ENOMEM;
773                         break;
774                 }
775
776                 io->ctx.bio_out = clone;
777                 io->ctx.idx_out = 0;
778
779                 remaining -= clone->bi_size;
780                 sector += bio_sectors(clone);
781
782                 crypt_inc_pending(io);
783                 r = crypt_convert(cc, &io->ctx);
784                 crypt_finished = atomic_dec_and_test(&io->ctx.pending);
785
786                 /* Encryption was already finished, submit io now */
787                 if (crypt_finished) {
788                         kcryptd_crypt_write_io_submit(io, r, 0);
789
790                         /*
791                          * If there was an error, do not try next fragments.
792                          * For async, error is processed in async handler.
793                          */
794                         if (unlikely(r < 0))
795                                 break;
796
797                         io->sector = sector;
798                 }
799
800                 /*
801                  * Out of memory -> run queues
802                  * But don't wait if split was due to the io size restriction
803                  */
804                 if (unlikely(out_of_pages))
805                         congestion_wait(BLK_RW_ASYNC, HZ/100);
806
807                 /*
808                  * With async crypto it is unsafe to share the crypto context
809                  * between fragments, so switch to a new dm_crypt_io structure.
810                  */
811                 if (unlikely(!crypt_finished && remaining)) {
812                         new_io = crypt_io_alloc(io->target, io->base_bio,
813                                                 sector);
814                         crypt_inc_pending(new_io);
815                         crypt_convert_init(cc, &new_io->ctx, NULL,
816                                            io->base_bio, sector);
817                         new_io->ctx.idx_in = io->ctx.idx_in;
818                         new_io->ctx.offset_in = io->ctx.offset_in;
819
820                         /*
821                          * Fragments after the first use the base_io
822                          * pending count.
823                          */
824                         if (!io->base_io)
825                                 new_io->base_io = io;
826                         else {
827                                 new_io->base_io = io->base_io;
828                                 crypt_inc_pending(io->base_io);
829                                 crypt_dec_pending(io);
830                         }
831
832                         io = new_io;
833                 }
834         }
835
836         crypt_dec_pending(io);
837 }
838
839 static void kcryptd_crypt_read_done(struct dm_crypt_io *io, int error)
840 {
841         if (unlikely(error < 0))
842                 io->error = -EIO;
843
844         crypt_dec_pending(io);
845 }
846
847 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
848 {
849         struct crypt_config *cc = io->target->private;
850         int r = 0;
851
852         crypt_inc_pending(io);
853
854         crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
855                            io->sector);
856
857         r = crypt_convert(cc, &io->ctx);
858
859         if (atomic_dec_and_test(&io->ctx.pending))
860                 kcryptd_crypt_read_done(io, r);
861
862         crypt_dec_pending(io);
863 }
864
865 static void kcryptd_async_done(struct crypto_async_request *async_req,
866                                int error)
867 {
868         struct dm_crypt_request *dmreq = async_req->data;
869         struct convert_context *ctx = dmreq->ctx;
870         struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
871         struct crypt_config *cc = io->target->private;
872
873         if (error == -EINPROGRESS) {
874                 complete(&ctx->restart);
875                 return;
876         }
877
878         mempool_free(req_of_dmreq(cc, dmreq), cc->req_pool);
879
880         if (!atomic_dec_and_test(&ctx->pending))
881                 return;
882
883         if (bio_data_dir(io->base_bio) == READ)
884                 kcryptd_crypt_read_done(io, error);
885         else
886                 kcryptd_crypt_write_io_submit(io, error, 1);
887 }
888
889 static void kcryptd_crypt(struct work_struct *work)
890 {
891         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
892
893         if (bio_data_dir(io->base_bio) == READ)
894                 kcryptd_crypt_read_convert(io);
895         else
896                 kcryptd_crypt_write_convert(io);
897 }
898
899 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
900 {
901         struct crypt_config *cc = io->target->private;
902
903         INIT_WORK(&io->work, kcryptd_crypt);
904         queue_work(cc->crypt_queue, &io->work);
905 }
906
907 /*
908  * Decode key from its hex representation
909  */
910 static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
911 {
912         char buffer[3];
913         char *endp;
914         unsigned int i;
915
916         buffer[2] = '\0';
917
918         for (i = 0; i < size; i++) {
919                 buffer[0] = *hex++;
920                 buffer[1] = *hex++;
921
922                 key[i] = (u8)simple_strtoul(buffer, &endp, 16);
923
924                 if (endp != &buffer[2])
925                         return -EINVAL;
926         }
927
928         if (*hex != '\0')
929                 return -EINVAL;
930
931         return 0;
932 }
933
934 /*
935  * Encode key into its hex representation
936  */
937 static void crypt_encode_key(char *hex, u8 *key, unsigned int size)
938 {
939         unsigned int i;
940
941         for (i = 0; i < size; i++) {
942                 sprintf(hex, "%02x", *key);
943                 hex += 2;
944                 key++;
945         }
946 }
947
948 static int crypt_set_key(struct crypt_config *cc, char *key)
949 {
950         unsigned key_size = strlen(key) >> 1;
951
952         if (cc->key_size && cc->key_size != key_size)
953                 return -EINVAL;
954
955         cc->key_size = key_size; /* initial settings */
956
957         if ((!key_size && strcmp(key, "-")) ||
958            (key_size && crypt_decode_key(cc->key, key, key_size) < 0))
959                 return -EINVAL;
960
961         set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
962
963         return crypto_ablkcipher_setkey(cc->tfm, cc->key, cc->key_size);
964 }
965
966 static int crypt_wipe_key(struct crypt_config *cc)
967 {
968         clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
969         memset(&cc->key, 0, cc->key_size * sizeof(u8));
970         return crypto_ablkcipher_setkey(cc->tfm, cc->key, cc->key_size);
971 }
972
973 /*
974  * Construct an encryption mapping:
975  * <cipher> <key> <iv_offset> <dev_path> <start>
976  */
977 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
978 {
979         struct crypt_config *cc;
980         struct crypto_ablkcipher *tfm;
981         char *tmp;
982         char *cipher;
983         char *chainmode;
984         char *ivmode;
985         char *ivopts;
986         unsigned int key_size;
987         unsigned long long tmpll;
988
989         if (argc != 5) {
990                 ti->error = "Not enough arguments";
991                 return -EINVAL;
992         }
993
994         tmp = argv[0];
995         cipher = strsep(&tmp, "-");
996         chainmode = strsep(&tmp, "-");
997         ivopts = strsep(&tmp, "-");
998         ivmode = strsep(&ivopts, ":");
999
1000         if (tmp)
1001                 DMWARN("Unexpected additional cipher options");
1002
1003         key_size = strlen(argv[1]) >> 1;
1004
1005         cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
1006         if (cc == NULL) {
1007                 ti->error =
1008                         "Cannot allocate transparent encryption context";
1009                 return -ENOMEM;
1010         }
1011
1012         /* Compatibility mode for old dm-crypt cipher strings */
1013         if (!chainmode || (strcmp(chainmode, "plain") == 0 && !ivmode)) {
1014                 chainmode = "cbc";
1015                 ivmode = "plain";
1016         }
1017
1018         if (strcmp(chainmode, "ecb") && !ivmode) {
1019                 ti->error = "This chaining mode requires an IV mechanism";
1020                 goto bad_cipher;
1021         }
1022
1023         if (snprintf(cc->cipher, CRYPTO_MAX_ALG_NAME, "%s(%s)",
1024                      chainmode, cipher) >= CRYPTO_MAX_ALG_NAME) {
1025                 ti->error = "Chain mode + cipher name is too long";
1026                 goto bad_cipher;
1027         }
1028
1029         tfm = crypto_alloc_ablkcipher(cc->cipher, 0, 0);
1030         if (IS_ERR(tfm)) {
1031                 ti->error = "Error allocating crypto tfm";
1032                 goto bad_cipher;
1033         }
1034
1035         strcpy(cc->cipher, cipher);
1036         strcpy(cc->chainmode, chainmode);
1037         cc->tfm = tfm;
1038
1039         if (crypt_set_key(cc, argv[1]) < 0) {
1040                 ti->error = "Error decoding and setting key";
1041                 goto bad_ivmode;
1042         }
1043
1044         /*
1045          * Choose ivmode. Valid modes: "plain", "essiv:<esshash>", "benbi".
1046          * See comments at iv code
1047          */
1048
1049         if (ivmode == NULL)
1050                 cc->iv_gen_ops = NULL;
1051         else if (strcmp(ivmode, "plain") == 0)
1052                 cc->iv_gen_ops = &crypt_iv_plain_ops;
1053         else if (strcmp(ivmode, "essiv") == 0)
1054                 cc->iv_gen_ops = &crypt_iv_essiv_ops;
1055         else if (strcmp(ivmode, "benbi") == 0)
1056                 cc->iv_gen_ops = &crypt_iv_benbi_ops;
1057         else if (strcmp(ivmode, "null") == 0)
1058                 cc->iv_gen_ops = &crypt_iv_null_ops;
1059         else {
1060                 ti->error = "Invalid IV mode";
1061                 goto bad_ivmode;
1062         }
1063
1064         if (cc->iv_gen_ops && cc->iv_gen_ops->ctr &&
1065             cc->iv_gen_ops->ctr(cc, ti, ivopts) < 0)
1066                 goto bad_ivmode;
1067
1068         if (cc->iv_gen_ops && cc->iv_gen_ops->init &&
1069             cc->iv_gen_ops->init(cc) < 0) {
1070                 ti->error = "Error initialising IV";
1071                 goto bad_slab_pool;
1072         }
1073
1074         cc->iv_size = crypto_ablkcipher_ivsize(tfm);
1075         if (cc->iv_size)
1076                 /* at least a 64 bit sector number should fit in our buffer */
1077                 cc->iv_size = max(cc->iv_size,
1078                                   (unsigned int)(sizeof(u64) / sizeof(u8)));
1079         else {
1080                 if (cc->iv_gen_ops) {
1081                         DMWARN("Selected cipher does not support IVs");
1082                         if (cc->iv_gen_ops->dtr)
1083                                 cc->iv_gen_ops->dtr(cc);
1084                         cc->iv_gen_ops = NULL;
1085                 }
1086         }
1087
1088         cc->io_pool = mempool_create_slab_pool(MIN_IOS, _crypt_io_pool);
1089         if (!cc->io_pool) {
1090                 ti->error = "Cannot allocate crypt io mempool";
1091                 goto bad_slab_pool;
1092         }
1093
1094         cc->dmreq_start = sizeof(struct ablkcipher_request);
1095         cc->dmreq_start += crypto_ablkcipher_reqsize(tfm);
1096         cc->dmreq_start = ALIGN(cc->dmreq_start, crypto_tfm_ctx_alignment());
1097         cc->dmreq_start += crypto_ablkcipher_alignmask(tfm) &
1098                            ~(crypto_tfm_ctx_alignment() - 1);
1099
1100         cc->req_pool = mempool_create_kmalloc_pool(MIN_IOS, cc->dmreq_start +
1101                         sizeof(struct dm_crypt_request) + cc->iv_size);
1102         if (!cc->req_pool) {
1103                 ti->error = "Cannot allocate crypt request mempool";
1104                 goto bad_req_pool;
1105         }
1106         cc->req = NULL;
1107
1108         cc->page_pool = mempool_create_page_pool(MIN_POOL_PAGES, 0);
1109         if (!cc->page_pool) {
1110                 ti->error = "Cannot allocate page mempool";
1111                 goto bad_page_pool;
1112         }
1113
1114         cc->bs = bioset_create(MIN_IOS, 0);
1115         if (!cc->bs) {
1116                 ti->error = "Cannot allocate crypt bioset";
1117                 goto bad_bs;
1118         }
1119
1120         if (sscanf(argv[2], "%llu", &tmpll) != 1) {
1121                 ti->error = "Invalid iv_offset sector";
1122                 goto bad_device;
1123         }
1124         cc->iv_offset = tmpll;
1125
1126         if (sscanf(argv[4], "%llu", &tmpll) != 1) {
1127                 ti->error = "Invalid device sector";
1128                 goto bad_device;
1129         }
1130         cc->start = tmpll;
1131
1132         if (dm_get_device(ti, argv[3], cc->start, ti->len,
1133                           dm_table_get_mode(ti->table), &cc->dev)) {
1134                 ti->error = "Device lookup failed";
1135                 goto bad_device;
1136         }
1137
1138         if (ivmode && cc->iv_gen_ops) {
1139                 if (ivopts)
1140                         *(ivopts - 1) = ':';
1141                 cc->iv_mode = kmalloc(strlen(ivmode) + 1, GFP_KERNEL);
1142                 if (!cc->iv_mode) {
1143                         ti->error = "Error kmallocing iv_mode string";
1144                         goto bad_ivmode_string;
1145                 }
1146                 strcpy(cc->iv_mode, ivmode);
1147         } else
1148                 cc->iv_mode = NULL;
1149
1150         cc->io_queue = create_singlethread_workqueue("kcryptd_io");
1151         if (!cc->io_queue) {
1152                 ti->error = "Couldn't create kcryptd io queue";
1153                 goto bad_io_queue;
1154         }
1155
1156         cc->crypt_queue = create_singlethread_workqueue("kcryptd");
1157         if (!cc->crypt_queue) {
1158                 ti->error = "Couldn't create kcryptd queue";
1159                 goto bad_crypt_queue;
1160         }
1161
1162         ti->num_flush_requests = 1;
1163         ti->private = cc;
1164         return 0;
1165
1166 bad_crypt_queue:
1167         destroy_workqueue(cc->io_queue);
1168 bad_io_queue:
1169         kfree(cc->iv_mode);
1170 bad_ivmode_string:
1171         dm_put_device(ti, cc->dev);
1172 bad_device:
1173         bioset_free(cc->bs);
1174 bad_bs:
1175         mempool_destroy(cc->page_pool);
1176 bad_page_pool:
1177         mempool_destroy(cc->req_pool);
1178 bad_req_pool:
1179         mempool_destroy(cc->io_pool);
1180 bad_slab_pool:
1181         if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
1182                 cc->iv_gen_ops->dtr(cc);
1183 bad_ivmode:
1184         crypto_free_ablkcipher(tfm);
1185 bad_cipher:
1186         /* Must zero key material before freeing */
1187         kzfree(cc);
1188         return -EINVAL;
1189 }
1190
1191 static void crypt_dtr(struct dm_target *ti)
1192 {
1193         struct crypt_config *cc = (struct crypt_config *) ti->private;
1194
1195         destroy_workqueue(cc->io_queue);
1196         destroy_workqueue(cc->crypt_queue);
1197
1198         if (cc->req)
1199                 mempool_free(cc->req, cc->req_pool);
1200
1201         bioset_free(cc->bs);
1202         mempool_destroy(cc->page_pool);
1203         mempool_destroy(cc->req_pool);
1204         mempool_destroy(cc->io_pool);
1205
1206         kfree(cc->iv_mode);
1207         if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
1208                 cc->iv_gen_ops->dtr(cc);
1209         crypto_free_ablkcipher(cc->tfm);
1210         dm_put_device(ti, cc->dev);
1211
1212         /* Must zero key material before freeing */
1213         kzfree(cc);
1214 }
1215
1216 static int crypt_map(struct dm_target *ti, struct bio *bio,
1217                      union map_info *map_context)
1218 {
1219         struct dm_crypt_io *io;
1220         struct crypt_config *cc;
1221
1222         if (unlikely(bio_empty_barrier(bio))) {
1223                 cc = ti->private;
1224                 bio->bi_bdev = cc->dev->bdev;
1225                 return DM_MAPIO_REMAPPED;
1226         }
1227
1228         io = crypt_io_alloc(ti, bio, bio->bi_sector - ti->begin);
1229
1230         if (bio_data_dir(io->base_bio) == READ)
1231                 kcryptd_queue_io(io);
1232         else
1233                 kcryptd_queue_crypt(io);
1234
1235         return DM_MAPIO_SUBMITTED;
1236 }
1237
1238 static int crypt_status(struct dm_target *ti, status_type_t type,
1239                         char *result, unsigned int maxlen)
1240 {
1241         struct crypt_config *cc = (struct crypt_config *) ti->private;
1242         unsigned int sz = 0;
1243
1244         switch (type) {
1245         case STATUSTYPE_INFO:
1246                 result[0] = '\0';
1247                 break;
1248
1249         case STATUSTYPE_TABLE:
1250                 if (cc->iv_mode)
1251                         DMEMIT("%s-%s-%s ", cc->cipher, cc->chainmode,
1252                                cc->iv_mode);
1253                 else
1254                         DMEMIT("%s-%s ", cc->cipher, cc->chainmode);
1255
1256                 if (cc->key_size > 0) {
1257                         if ((maxlen - sz) < ((cc->key_size << 1) + 1))
1258                                 return -ENOMEM;
1259
1260                         crypt_encode_key(result + sz, cc->key, cc->key_size);
1261                         sz += cc->key_size << 1;
1262                 } else {
1263                         if (sz >= maxlen)
1264                                 return -ENOMEM;
1265                         result[sz++] = '-';
1266                 }
1267
1268                 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
1269                                 cc->dev->name, (unsigned long long)cc->start);
1270                 break;
1271         }
1272         return 0;
1273 }
1274
1275 static void crypt_postsuspend(struct dm_target *ti)
1276 {
1277         struct crypt_config *cc = ti->private;
1278
1279         set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
1280 }
1281
1282 static int crypt_preresume(struct dm_target *ti)
1283 {
1284         struct crypt_config *cc = ti->private;
1285
1286         if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
1287                 DMERR("aborting resume - crypt key is not set.");
1288                 return -EAGAIN;
1289         }
1290
1291         return 0;
1292 }
1293
1294 static void crypt_resume(struct dm_target *ti)
1295 {
1296         struct crypt_config *cc = ti->private;
1297
1298         clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
1299 }
1300
1301 /* Message interface
1302  *      key set <key>
1303  *      key wipe
1304  */
1305 static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
1306 {
1307         struct crypt_config *cc = ti->private;
1308
1309         if (argc < 2)
1310                 goto error;
1311
1312         if (!strnicmp(argv[0], MESG_STR("key"))) {
1313                 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
1314                         DMWARN("not suspended during key manipulation.");
1315                         return -EINVAL;
1316                 }
1317                 if (argc == 3 && !strnicmp(argv[1], MESG_STR("set")))
1318                         return crypt_set_key(cc, argv[2]);
1319                 if (argc == 2 && !strnicmp(argv[1], MESG_STR("wipe")))
1320                         return crypt_wipe_key(cc);
1321         }
1322
1323 error:
1324         DMWARN("unrecognised message received.");
1325         return -EINVAL;
1326 }
1327
1328 static int crypt_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
1329                        struct bio_vec *biovec, int max_size)
1330 {
1331         struct crypt_config *cc = ti->private;
1332         struct request_queue *q = bdev_get_queue(cc->dev->bdev);
1333
1334         if (!q->merge_bvec_fn)
1335                 return max_size;
1336
1337         bvm->bi_bdev = cc->dev->bdev;
1338         bvm->bi_sector = cc->start + bvm->bi_sector - ti->begin;
1339
1340         return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
1341 }
1342
1343 static int crypt_iterate_devices(struct dm_target *ti,
1344                                  iterate_devices_callout_fn fn, void *data)
1345 {
1346         struct crypt_config *cc = ti->private;
1347
1348         return fn(ti, cc->dev, cc->start, ti->len, data);
1349 }
1350
1351 static struct target_type crypt_target = {
1352         .name   = "crypt",
1353         .version = {1, 7, 0},
1354         .module = THIS_MODULE,
1355         .ctr    = crypt_ctr,
1356         .dtr    = crypt_dtr,
1357         .map    = crypt_map,
1358         .status = crypt_status,
1359         .postsuspend = crypt_postsuspend,
1360         .preresume = crypt_preresume,
1361         .resume = crypt_resume,
1362         .message = crypt_message,
1363         .merge  = crypt_merge,
1364         .iterate_devices = crypt_iterate_devices,
1365 };
1366
1367 static int __init dm_crypt_init(void)
1368 {
1369         int r;
1370
1371         _crypt_io_pool = KMEM_CACHE(dm_crypt_io, 0);
1372         if (!_crypt_io_pool)
1373                 return -ENOMEM;
1374
1375         r = dm_register_target(&crypt_target);
1376         if (r < 0) {
1377                 DMERR("register failed %d", r);
1378                 kmem_cache_destroy(_crypt_io_pool);
1379         }
1380
1381         return r;
1382 }
1383
1384 static void __exit dm_crypt_exit(void)
1385 {
1386         dm_unregister_target(&crypt_target);
1387         kmem_cache_destroy(_crypt_io_pool);
1388 }
1389
1390 module_init(dm_crypt_init);
1391 module_exit(dm_crypt_exit);
1392
1393 MODULE_AUTHOR("Christophe Saout <christophe@saout.de>");
1394 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
1395 MODULE_LICENSE("GPL");