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