]> err.no Git - linux-2.6/blob - drivers/md/dm-crypt.c
[PATCH] dm crypt: move io to workqueue
[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 Red Hat, Inc. All rights reserved.
5  *
6  * This file is released under the GPL.
7  */
8
9 #include <linux/err.h>
10 #include <linux/module.h>
11 #include <linux/init.h>
12 #include <linux/kernel.h>
13 #include <linux/bio.h>
14 #include <linux/blkdev.h>
15 #include <linux/mempool.h>
16 #include <linux/slab.h>
17 #include <linux/crypto.h>
18 #include <linux/workqueue.h>
19 #include <asm/atomic.h>
20 #include <linux/scatterlist.h>
21 #include <asm/page.h>
22
23 #include "dm.h"
24
25 #define DM_MSG_PREFIX "crypt"
26 #define MESG_STR(x) x, sizeof(x)
27
28 /*
29  * per bio private data
30  */
31 struct crypt_io {
32         struct dm_target *target;
33         struct bio *base_bio;
34         struct bio *first_clone;
35         struct work_struct work;
36         atomic_t pending;
37         int error;
38         int post_process;
39 };
40
41 /*
42  * context holding the current state of a multi-part conversion
43  */
44 struct convert_context {
45         struct bio *bio_in;
46         struct bio *bio_out;
47         unsigned int offset_in;
48         unsigned int offset_out;
49         unsigned int idx_in;
50         unsigned int idx_out;
51         sector_t sector;
52         int write;
53 };
54
55 struct crypt_config;
56
57 struct crypt_iv_operations {
58         int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
59                    const char *opts);
60         void (*dtr)(struct crypt_config *cc);
61         const char *(*status)(struct crypt_config *cc);
62         int (*generator)(struct crypt_config *cc, u8 *iv, sector_t sector);
63 };
64
65 /*
66  * Crypt: maps a linear range of a block device
67  * and encrypts / decrypts at the same time.
68  */
69 enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID };
70 struct crypt_config {
71         struct dm_dev *dev;
72         sector_t start;
73
74         /*
75          * pool for per bio private data and
76          * for encryption buffer pages
77          */
78         mempool_t *io_pool;
79         mempool_t *page_pool;
80
81         /*
82          * crypto related data
83          */
84         struct crypt_iv_operations *iv_gen_ops;
85         char *iv_mode;
86         struct crypto_cipher *iv_gen_private;
87         sector_t iv_offset;
88         unsigned int iv_size;
89
90         char cipher[CRYPTO_MAX_ALG_NAME];
91         char chainmode[CRYPTO_MAX_ALG_NAME];
92         struct crypto_blkcipher *tfm;
93         unsigned long flags;
94         unsigned int key_size;
95         u8 key[0];
96 };
97
98 #define MIN_IOS        256
99 #define MIN_POOL_PAGES 32
100 #define MIN_BIO_PAGES  8
101
102 static kmem_cache_t *_crypt_io_pool;
103
104 /*
105  * Different IV generation algorithms:
106  *
107  * plain: the initial vector is the 32-bit little-endian version of the sector
108  *        number, padded with zeros if neccessary.
109  *
110  * essiv: "encrypted sector|salt initial vector", the sector number is
111  *        encrypted with the bulk cipher using a salt as key. The salt
112  *        should be derived from the bulk cipher's key via hashing.
113  *
114  * plumb: unimplemented, see:
115  * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
116  */
117
118 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
119 {
120         memset(iv, 0, cc->iv_size);
121         *(u32 *)iv = cpu_to_le32(sector & 0xffffffff);
122
123         return 0;
124 }
125
126 static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
127                               const char *opts)
128 {
129         struct crypto_cipher *essiv_tfm;
130         struct crypto_hash *hash_tfm;
131         struct hash_desc desc;
132         struct scatterlist sg;
133         unsigned int saltsize;
134         u8 *salt;
135         int err;
136
137         if (opts == NULL) {
138                 ti->error = "Digest algorithm missing for ESSIV mode";
139                 return -EINVAL;
140         }
141
142         /* Hash the cipher key with the given hash algorithm */
143         hash_tfm = crypto_alloc_hash(opts, 0, CRYPTO_ALG_ASYNC);
144         if (IS_ERR(hash_tfm)) {
145                 ti->error = "Error initializing ESSIV hash";
146                 return PTR_ERR(hash_tfm);
147         }
148
149         saltsize = crypto_hash_digestsize(hash_tfm);
150         salt = kmalloc(saltsize, GFP_KERNEL);
151         if (salt == NULL) {
152                 ti->error = "Error kmallocing salt storage in ESSIV";
153                 crypto_free_hash(hash_tfm);
154                 return -ENOMEM;
155         }
156
157         sg_set_buf(&sg, cc->key, cc->key_size);
158         desc.tfm = hash_tfm;
159         desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
160         err = crypto_hash_digest(&desc, &sg, cc->key_size, salt);
161         crypto_free_hash(hash_tfm);
162
163         if (err) {
164                 ti->error = "Error calculating hash in ESSIV";
165                 return err;
166         }
167
168         /* Setup the essiv_tfm with the given salt */
169         essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
170         if (IS_ERR(essiv_tfm)) {
171                 ti->error = "Error allocating crypto tfm for ESSIV";
172                 kfree(salt);
173                 return PTR_ERR(essiv_tfm);
174         }
175         if (crypto_cipher_blocksize(essiv_tfm) !=
176             crypto_blkcipher_ivsize(cc->tfm)) {
177                 ti->error = "Block size of ESSIV cipher does "
178                                 "not match IV size of block cipher";
179                 crypto_free_cipher(essiv_tfm);
180                 kfree(salt);
181                 return -EINVAL;
182         }
183         err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
184         if (err) {
185                 ti->error = "Failed to set key for ESSIV cipher";
186                 crypto_free_cipher(essiv_tfm);
187                 kfree(salt);
188                 return err;
189         }
190         kfree(salt);
191
192         cc->iv_gen_private = essiv_tfm;
193         return 0;
194 }
195
196 static void crypt_iv_essiv_dtr(struct crypt_config *cc)
197 {
198         crypto_free_cipher(cc->iv_gen_private);
199         cc->iv_gen_private = NULL;
200 }
201
202 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
203 {
204         memset(iv, 0, cc->iv_size);
205         *(u64 *)iv = cpu_to_le64(sector);
206         crypto_cipher_encrypt_one(cc->iv_gen_private, iv, iv);
207         return 0;
208 }
209
210 static struct crypt_iv_operations crypt_iv_plain_ops = {
211         .generator = crypt_iv_plain_gen
212 };
213
214 static struct crypt_iv_operations crypt_iv_essiv_ops = {
215         .ctr       = crypt_iv_essiv_ctr,
216         .dtr       = crypt_iv_essiv_dtr,
217         .generator = crypt_iv_essiv_gen
218 };
219
220
221 static int
222 crypt_convert_scatterlist(struct crypt_config *cc, struct scatterlist *out,
223                           struct scatterlist *in, unsigned int length,
224                           int write, sector_t sector)
225 {
226         u8 iv[cc->iv_size];
227         struct blkcipher_desc desc = {
228                 .tfm = cc->tfm,
229                 .info = iv,
230                 .flags = CRYPTO_TFM_REQ_MAY_SLEEP,
231         };
232         int r;
233
234         if (cc->iv_gen_ops) {
235                 r = cc->iv_gen_ops->generator(cc, iv, sector);
236                 if (r < 0)
237                         return r;
238
239                 if (write)
240                         r = crypto_blkcipher_encrypt_iv(&desc, out, in, length);
241                 else
242                         r = crypto_blkcipher_decrypt_iv(&desc, out, in, length);
243         } else {
244                 if (write)
245                         r = crypto_blkcipher_encrypt(&desc, out, in, length);
246                 else
247                         r = crypto_blkcipher_decrypt(&desc, out, in, length);
248         }
249
250         return r;
251 }
252
253 static void
254 crypt_convert_init(struct crypt_config *cc, struct convert_context *ctx,
255                    struct bio *bio_out, struct bio *bio_in,
256                    sector_t sector, int write)
257 {
258         ctx->bio_in = bio_in;
259         ctx->bio_out = bio_out;
260         ctx->offset_in = 0;
261         ctx->offset_out = 0;
262         ctx->idx_in = bio_in ? bio_in->bi_idx : 0;
263         ctx->idx_out = bio_out ? bio_out->bi_idx : 0;
264         ctx->sector = sector + cc->iv_offset;
265         ctx->write = write;
266 }
267
268 /*
269  * Encrypt / decrypt data from one bio to another one (can be the same one)
270  */
271 static int crypt_convert(struct crypt_config *cc,
272                          struct convert_context *ctx)
273 {
274         int r = 0;
275
276         while(ctx->idx_in < ctx->bio_in->bi_vcnt &&
277               ctx->idx_out < ctx->bio_out->bi_vcnt) {
278                 struct bio_vec *bv_in = bio_iovec_idx(ctx->bio_in, ctx->idx_in);
279                 struct bio_vec *bv_out = bio_iovec_idx(ctx->bio_out, ctx->idx_out);
280                 struct scatterlist sg_in = {
281                         .page = bv_in->bv_page,
282                         .offset = bv_in->bv_offset + ctx->offset_in,
283                         .length = 1 << SECTOR_SHIFT
284                 };
285                 struct scatterlist sg_out = {
286                         .page = bv_out->bv_page,
287                         .offset = bv_out->bv_offset + ctx->offset_out,
288                         .length = 1 << SECTOR_SHIFT
289                 };
290
291                 ctx->offset_in += sg_in.length;
292                 if (ctx->offset_in >= bv_in->bv_len) {
293                         ctx->offset_in = 0;
294                         ctx->idx_in++;
295                 }
296
297                 ctx->offset_out += sg_out.length;
298                 if (ctx->offset_out >= bv_out->bv_len) {
299                         ctx->offset_out = 0;
300                         ctx->idx_out++;
301                 }
302
303                 r = crypt_convert_scatterlist(cc, &sg_out, &sg_in, sg_in.length,
304                                               ctx->write, ctx->sector);
305                 if (r < 0)
306                         break;
307
308                 ctx->sector++;
309         }
310
311         return r;
312 }
313
314 /*
315  * Generate a new unfragmented bio with the given size
316  * This should never violate the device limitations
317  * May return a smaller bio when running out of pages
318  */
319 static struct bio *
320 crypt_alloc_buffer(struct crypt_config *cc, unsigned int size,
321                    struct bio *base_bio, unsigned int *bio_vec_idx)
322 {
323         struct bio *clone;
324         unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
325         gfp_t gfp_mask = GFP_NOIO | __GFP_HIGHMEM;
326         unsigned int i;
327
328         /*
329          * Use __GFP_NOMEMALLOC to tell the VM to act less aggressively and
330          * to fail earlier.  This is not necessary but increases throughput.
331          * FIXME: Is this really intelligent?
332          */
333         if (base_bio)
334                 clone = bio_clone(base_bio, GFP_NOIO|__GFP_NOMEMALLOC);
335         else
336                 clone = bio_alloc(GFP_NOIO|__GFP_NOMEMALLOC, nr_iovecs);
337         if (!clone)
338                 return NULL;
339
340         /* if the last bio was not complete, continue where that one ended */
341         clone->bi_idx = *bio_vec_idx;
342         clone->bi_vcnt = *bio_vec_idx;
343         clone->bi_size = 0;
344         clone->bi_flags &= ~(1 << BIO_SEG_VALID);
345
346         /* clone->bi_idx pages have already been allocated */
347         size -= clone->bi_idx * PAGE_SIZE;
348
349         for (i = clone->bi_idx; i < nr_iovecs; i++) {
350                 struct bio_vec *bv = bio_iovec_idx(clone, i);
351
352                 bv->bv_page = mempool_alloc(cc->page_pool, gfp_mask);
353                 if (!bv->bv_page)
354                         break;
355
356                 /*
357                  * if additional pages cannot be allocated without waiting,
358                  * return a partially allocated bio, the caller will then try
359                  * to allocate additional bios while submitting this partial bio
360                  */
361                 if ((i - clone->bi_idx) == (MIN_BIO_PAGES - 1))
362                         gfp_mask = (gfp_mask | __GFP_NOWARN) & ~__GFP_WAIT;
363
364                 bv->bv_offset = 0;
365                 if (size > PAGE_SIZE)
366                         bv->bv_len = PAGE_SIZE;
367                 else
368                         bv->bv_len = size;
369
370                 clone->bi_size += bv->bv_len;
371                 clone->bi_vcnt++;
372                 size -= bv->bv_len;
373         }
374
375         if (!clone->bi_size) {
376                 bio_put(clone);
377                 return NULL;
378         }
379
380         /*
381          * Remember the last bio_vec allocated to be able
382          * to correctly continue after the splitting.
383          */
384         *bio_vec_idx = clone->bi_vcnt;
385
386         return clone;
387 }
388
389 static void crypt_free_buffer_pages(struct crypt_config *cc,
390                                     struct bio *clone, unsigned int bytes)
391 {
392         unsigned int i, start, end;
393         struct bio_vec *bv;
394
395         /*
396          * This is ugly, but Jens Axboe thinks that using bi_idx in the
397          * endio function is too dangerous at the moment, so I calculate the
398          * correct position using bi_vcnt and bi_size.
399          * The bv_offset and bv_len fields might already be modified but we
400          * know that we always allocated whole pages.
401          * A fix to the bi_idx issue in the kernel is in the works, so
402          * we will hopefully be able to revert to the cleaner solution soon.
403          */
404         i = clone->bi_vcnt - 1;
405         bv = bio_iovec_idx(clone, i);
406         end = (i << PAGE_SHIFT) + (bv->bv_offset + bv->bv_len) - clone->bi_size;
407         start = end - bytes;
408
409         start >>= PAGE_SHIFT;
410         if (!clone->bi_size)
411                 end = clone->bi_vcnt;
412         else
413                 end >>= PAGE_SHIFT;
414
415         for (i = start; i < end; i++) {
416                 bv = bio_iovec_idx(clone, i);
417                 BUG_ON(!bv->bv_page);
418                 mempool_free(bv->bv_page, cc->page_pool);
419                 bv->bv_page = NULL;
420         }
421 }
422
423 /*
424  * One of the bios was finished. Check for completion of
425  * the whole request and correctly clean up the buffer.
426  */
427 static void dec_pending(struct crypt_io *io, int error)
428 {
429         struct crypt_config *cc = (struct crypt_config *) io->target->private;
430
431         if (error < 0)
432                 io->error = error;
433
434         if (!atomic_dec_and_test(&io->pending))
435                 return;
436
437         if (io->first_clone)
438                 bio_put(io->first_clone);
439
440         bio_endio(io->base_bio, io->base_bio->bi_size, io->error);
441
442         mempool_free(io, cc->io_pool);
443 }
444
445 /*
446  * kcryptd:
447  *
448  * Needed because it would be very unwise to do decryption in an
449  * interrupt context.
450  */
451 static struct workqueue_struct *_kcryptd_workqueue;
452 static void kcryptd_do_work(void *data);
453
454 static void kcryptd_queue_io(struct crypt_io *io)
455 {
456         INIT_WORK(&io->work, kcryptd_do_work, io);
457         queue_work(_kcryptd_workqueue, &io->work);
458 }
459
460 static int crypt_endio(struct bio *clone, unsigned int done, int error)
461 {
462         struct crypt_io *io = clone->bi_private;
463         struct crypt_config *cc = io->target->private;
464         unsigned read_io = bio_data_dir(clone) == READ;
465
466         /*
467          * free the processed pages, even if
468          * it's only a partially completed write
469          */
470         if (!read_io)
471                 crypt_free_buffer_pages(cc, clone, done);
472
473         /* keep going - not finished yet */
474         if (unlikely(clone->bi_size))
475                 return 1;
476
477         if (!read_io)
478                 goto out;
479
480         if (unlikely(!bio_flagged(clone, BIO_UPTODATE))) {
481                 error = -EIO;
482                 goto out;
483         }
484
485         bio_put(clone);
486         io->post_process = 1;
487         kcryptd_queue_io(io);
488         return 0;
489
490 out:
491         bio_put(clone);
492         dec_pending(io, error);
493         return error;
494 }
495
496 static void clone_init(struct crypt_io *io, struct bio *clone)
497 {
498         struct crypt_config *cc = io->target->private;
499
500         clone->bi_private = io;
501         clone->bi_end_io  = crypt_endio;
502         clone->bi_bdev    = cc->dev->bdev;
503         clone->bi_rw      = io->base_bio->bi_rw;
504 }
505
506 static void process_read(struct crypt_io *io)
507 {
508         struct crypt_config *cc = io->target->private;
509         struct bio *base_bio = io->base_bio;
510         struct bio *clone;
511         sector_t sector = base_bio->bi_sector - io->target->begin;
512
513         atomic_inc(&io->pending);
514
515         /*
516          * The block layer might modify the bvec array, so always
517          * copy the required bvecs because we need the original
518          * one in order to decrypt the whole bio data *afterwards*.
519          */
520         clone = bio_alloc(GFP_NOIO, bio_segments(base_bio));
521         if (unlikely(!clone)) {
522                 dec_pending(io, -ENOMEM);
523                 return;
524         }
525
526         clone_init(io, clone);
527         clone->bi_idx = 0;
528         clone->bi_vcnt = bio_segments(base_bio);
529         clone->bi_size = base_bio->bi_size;
530         clone->bi_sector = cc->start + sector;
531         memcpy(clone->bi_io_vec, bio_iovec(base_bio),
532                sizeof(struct bio_vec) * clone->bi_vcnt);
533
534         generic_make_request(clone);
535 }
536
537 static void process_write(struct crypt_io *io)
538 {
539         struct crypt_config *cc = io->target->private;
540         struct bio *base_bio = io->base_bio;
541         struct bio *clone;
542         struct convert_context ctx;
543         unsigned remaining = base_bio->bi_size;
544         sector_t sector = base_bio->bi_sector - io->target->begin;
545         unsigned bvec_idx = 0;
546
547         atomic_inc(&io->pending);
548
549         crypt_convert_init(cc, &ctx, NULL, base_bio, sector, 1);
550
551         /*
552          * The allocated buffers can be smaller than the whole bio,
553          * so repeat the whole process until all the data can be handled.
554          */
555         while (remaining) {
556                 clone = crypt_alloc_buffer(cc, base_bio->bi_size,
557                                            io->first_clone, &bvec_idx);
558                 if (unlikely(!clone)) {
559                         dec_pending(io, -ENOMEM);
560                         return;
561                 }
562
563                 ctx.bio_out = clone;
564
565                 if (unlikely(crypt_convert(cc, &ctx) < 0)) {
566                         crypt_free_buffer_pages(cc, clone, clone->bi_size);
567                         bio_put(clone);
568                         dec_pending(io, -EIO);
569                         return;
570                 }
571
572                 clone_init(io, clone);
573                 clone->bi_sector = cc->start + sector;
574
575                 if (!io->first_clone) {
576                         /*
577                          * hold a reference to the first clone, because it
578                          * holds the bio_vec array and that can't be freed
579                          * before all other clones are released
580                          */
581                         bio_get(clone);
582                         io->first_clone = clone;
583                 }
584
585                 remaining -= clone->bi_size;
586                 sector += bio_sectors(clone);
587
588                 /* prevent bio_put of first_clone */
589                 if (remaining)
590                         atomic_inc(&io->pending);
591
592                 generic_make_request(clone);
593
594                 /* out of memory -> run queues */
595                 if (remaining)
596                         blk_congestion_wait(bio_data_dir(clone), HZ/100);
597
598         }
599 }
600
601 static void process_read_endio(struct crypt_io *io)
602 {
603         struct crypt_config *cc = io->target->private;
604         struct convert_context ctx;
605
606         crypt_convert_init(cc, &ctx, io->base_bio, io->base_bio,
607                            io->base_bio->bi_sector - io->target->begin, 0);
608
609         dec_pending(io, crypt_convert(cc, &ctx));
610 }
611
612 static void kcryptd_do_work(void *data)
613 {
614         struct crypt_io *io = data;
615
616         if (io->post_process)
617                 process_read_endio(io);
618         else if (bio_data_dir(io->base_bio) == READ)
619                 process_read(io);
620         else
621                 process_write(io);
622 }
623
624 /*
625  * Decode key from its hex representation
626  */
627 static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
628 {
629         char buffer[3];
630         char *endp;
631         unsigned int i;
632
633         buffer[2] = '\0';
634
635         for (i = 0; i < size; i++) {
636                 buffer[0] = *hex++;
637                 buffer[1] = *hex++;
638
639                 key[i] = (u8)simple_strtoul(buffer, &endp, 16);
640
641                 if (endp != &buffer[2])
642                         return -EINVAL;
643         }
644
645         if (*hex != '\0')
646                 return -EINVAL;
647
648         return 0;
649 }
650
651 /*
652  * Encode key into its hex representation
653  */
654 static void crypt_encode_key(char *hex, u8 *key, unsigned int size)
655 {
656         unsigned int i;
657
658         for (i = 0; i < size; i++) {
659                 sprintf(hex, "%02x", *key);
660                 hex += 2;
661                 key++;
662         }
663 }
664
665 static int crypt_set_key(struct crypt_config *cc, char *key)
666 {
667         unsigned key_size = strlen(key) >> 1;
668
669         if (cc->key_size && cc->key_size != key_size)
670                 return -EINVAL;
671
672         cc->key_size = key_size; /* initial settings */
673
674         if ((!key_size && strcmp(key, "-")) ||
675             (key_size && crypt_decode_key(cc->key, key, key_size) < 0))
676                 return -EINVAL;
677
678         set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
679
680         return 0;
681 }
682
683 static int crypt_wipe_key(struct crypt_config *cc)
684 {
685         clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
686         memset(&cc->key, 0, cc->key_size * sizeof(u8));
687         return 0;
688 }
689
690 /*
691  * Construct an encryption mapping:
692  * <cipher> <key> <iv_offset> <dev_path> <start>
693  */
694 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
695 {
696         struct crypt_config *cc;
697         struct crypto_blkcipher *tfm;
698         char *tmp;
699         char *cipher;
700         char *chainmode;
701         char *ivmode;
702         char *ivopts;
703         unsigned int key_size;
704         unsigned long long tmpll;
705
706         if (argc != 5) {
707                 ti->error = "Not enough arguments";
708                 return -EINVAL;
709         }
710
711         tmp = argv[0];
712         cipher = strsep(&tmp, "-");
713         chainmode = strsep(&tmp, "-");
714         ivopts = strsep(&tmp, "-");
715         ivmode = strsep(&ivopts, ":");
716
717         if (tmp)
718                 DMWARN("Unexpected additional cipher options");
719
720         key_size = strlen(argv[1]) >> 1;
721
722         cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
723         if (cc == NULL) {
724                 ti->error =
725                         "Cannot allocate transparent encryption context";
726                 return -ENOMEM;
727         }
728
729         if (crypt_set_key(cc, argv[1])) {
730                 ti->error = "Error decoding key";
731                 goto bad1;
732         }
733
734         /* Compatiblity mode for old dm-crypt cipher strings */
735         if (!chainmode || (strcmp(chainmode, "plain") == 0 && !ivmode)) {
736                 chainmode = "cbc";
737                 ivmode = "plain";
738         }
739
740         if (strcmp(chainmode, "ecb") && !ivmode) {
741                 ti->error = "This chaining mode requires an IV mechanism";
742                 goto bad1;
743         }
744
745         if (snprintf(cc->cipher, CRYPTO_MAX_ALG_NAME, "%s(%s)", chainmode, 
746                      cipher) >= CRYPTO_MAX_ALG_NAME) {
747                 ti->error = "Chain mode + cipher name is too long";
748                 goto bad1;
749         }
750
751         tfm = crypto_alloc_blkcipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
752         if (IS_ERR(tfm)) {
753                 ti->error = "Error allocating crypto tfm";
754                 goto bad1;
755         }
756
757         strcpy(cc->cipher, cipher);
758         strcpy(cc->chainmode, chainmode);
759         cc->tfm = tfm;
760
761         /*
762          * Choose ivmode. Valid modes: "plain", "essiv:<esshash>".
763          * See comments at iv code
764          */
765
766         if (ivmode == NULL)
767                 cc->iv_gen_ops = NULL;
768         else if (strcmp(ivmode, "plain") == 0)
769                 cc->iv_gen_ops = &crypt_iv_plain_ops;
770         else if (strcmp(ivmode, "essiv") == 0)
771                 cc->iv_gen_ops = &crypt_iv_essiv_ops;
772         else {
773                 ti->error = "Invalid IV mode";
774                 goto bad2;
775         }
776
777         if (cc->iv_gen_ops && cc->iv_gen_ops->ctr &&
778             cc->iv_gen_ops->ctr(cc, ti, ivopts) < 0)
779                 goto bad2;
780
781         cc->iv_size = crypto_blkcipher_ivsize(tfm);
782         if (cc->iv_size)
783                 /* at least a 64 bit sector number should fit in our buffer */
784                 cc->iv_size = max(cc->iv_size,
785                                   (unsigned int)(sizeof(u64) / sizeof(u8)));
786         else {
787                 if (cc->iv_gen_ops) {
788                         DMWARN("Selected cipher does not support IVs");
789                         if (cc->iv_gen_ops->dtr)
790                                 cc->iv_gen_ops->dtr(cc);
791                         cc->iv_gen_ops = NULL;
792                 }
793         }
794
795         cc->io_pool = mempool_create_slab_pool(MIN_IOS, _crypt_io_pool);
796         if (!cc->io_pool) {
797                 ti->error = "Cannot allocate crypt io mempool";
798                 goto bad3;
799         }
800
801         cc->page_pool = mempool_create_page_pool(MIN_POOL_PAGES, 0);
802         if (!cc->page_pool) {
803                 ti->error = "Cannot allocate page mempool";
804                 goto bad4;
805         }
806
807         if (crypto_blkcipher_setkey(tfm, cc->key, key_size) < 0) {
808                 ti->error = "Error setting key";
809                 goto bad5;
810         }
811
812         if (sscanf(argv[2], "%llu", &tmpll) != 1) {
813                 ti->error = "Invalid iv_offset sector";
814                 goto bad5;
815         }
816         cc->iv_offset = tmpll;
817
818         if (sscanf(argv[4], "%llu", &tmpll) != 1) {
819                 ti->error = "Invalid device sector";
820                 goto bad5;
821         }
822         cc->start = tmpll;
823
824         if (dm_get_device(ti, argv[3], cc->start, ti->len,
825                           dm_table_get_mode(ti->table), &cc->dev)) {
826                 ti->error = "Device lookup failed";
827                 goto bad5;
828         }
829
830         if (ivmode && cc->iv_gen_ops) {
831                 if (ivopts)
832                         *(ivopts - 1) = ':';
833                 cc->iv_mode = kmalloc(strlen(ivmode) + 1, GFP_KERNEL);
834                 if (!cc->iv_mode) {
835                         ti->error = "Error kmallocing iv_mode string";
836                         goto bad5;
837                 }
838                 strcpy(cc->iv_mode, ivmode);
839         } else
840                 cc->iv_mode = NULL;
841
842         ti->private = cc;
843         return 0;
844
845 bad5:
846         mempool_destroy(cc->page_pool);
847 bad4:
848         mempool_destroy(cc->io_pool);
849 bad3:
850         if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
851                 cc->iv_gen_ops->dtr(cc);
852 bad2:
853         crypto_free_blkcipher(tfm);
854 bad1:
855         /* Must zero key material before freeing */
856         memset(cc, 0, sizeof(*cc) + cc->key_size * sizeof(u8));
857         kfree(cc);
858         return -EINVAL;
859 }
860
861 static void crypt_dtr(struct dm_target *ti)
862 {
863         struct crypt_config *cc = (struct crypt_config *) ti->private;
864
865         mempool_destroy(cc->page_pool);
866         mempool_destroy(cc->io_pool);
867
868         kfree(cc->iv_mode);
869         if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
870                 cc->iv_gen_ops->dtr(cc);
871         crypto_free_blkcipher(cc->tfm);
872         dm_put_device(ti, cc->dev);
873
874         /* Must zero key material before freeing */
875         memset(cc, 0, sizeof(*cc) + cc->key_size * sizeof(u8));
876         kfree(cc);
877 }
878
879 static int crypt_map(struct dm_target *ti, struct bio *bio,
880                      union map_info *map_context)
881 {
882         struct crypt_config *cc = ti->private;
883         struct crypt_io *io;
884
885         io = mempool_alloc(cc->io_pool, GFP_NOIO);
886         io->target = ti;
887         io->base_bio = bio;
888         io->first_clone = NULL;
889         io->error = io->post_process = 0;
890         atomic_set(&io->pending, 0);
891         kcryptd_queue_io(io);
892
893         return 0;
894 }
895
896 static int crypt_status(struct dm_target *ti, status_type_t type,
897                         char *result, unsigned int maxlen)
898 {
899         struct crypt_config *cc = (struct crypt_config *) ti->private;
900         const char *cipher;
901         const char *chainmode = NULL;
902         unsigned int sz = 0;
903
904         switch (type) {
905         case STATUSTYPE_INFO:
906                 result[0] = '\0';
907                 break;
908
909         case STATUSTYPE_TABLE:
910                 cipher = crypto_blkcipher_name(cc->tfm);
911
912                 chainmode = cc->chainmode;
913
914                 if (cc->iv_mode)
915                         DMEMIT("%s-%s-%s ", cipher, chainmode, cc->iv_mode);
916                 else
917                         DMEMIT("%s-%s ", cipher, chainmode);
918
919                 if (cc->key_size > 0) {
920                         if ((maxlen - sz) < ((cc->key_size << 1) + 1))
921                                 return -ENOMEM;
922
923                         crypt_encode_key(result + sz, cc->key, cc->key_size);
924                         sz += cc->key_size << 1;
925                 } else {
926                         if (sz >= maxlen)
927                                 return -ENOMEM;
928                         result[sz++] = '-';
929                 }
930
931                 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
932                                 cc->dev->name, (unsigned long long)cc->start);
933                 break;
934         }
935         return 0;
936 }
937
938 static void crypt_postsuspend(struct dm_target *ti)
939 {
940         struct crypt_config *cc = ti->private;
941
942         set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
943 }
944
945 static int crypt_preresume(struct dm_target *ti)
946 {
947         struct crypt_config *cc = ti->private;
948
949         if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
950                 DMERR("aborting resume - crypt key is not set.");
951                 return -EAGAIN;
952         }
953
954         return 0;
955 }
956
957 static void crypt_resume(struct dm_target *ti)
958 {
959         struct crypt_config *cc = ti->private;
960
961         clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
962 }
963
964 /* Message interface
965  *      key set <key>
966  *      key wipe
967  */
968 static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
969 {
970         struct crypt_config *cc = ti->private;
971
972         if (argc < 2)
973                 goto error;
974
975         if (!strnicmp(argv[0], MESG_STR("key"))) {
976                 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
977                         DMWARN("not suspended during key manipulation.");
978                         return -EINVAL;
979                 }
980                 if (argc == 3 && !strnicmp(argv[1], MESG_STR("set")))
981                         return crypt_set_key(cc, argv[2]);
982                 if (argc == 2 && !strnicmp(argv[1], MESG_STR("wipe")))
983                         return crypt_wipe_key(cc);
984         }
985
986 error:
987         DMWARN("unrecognised message received.");
988         return -EINVAL;
989 }
990
991 static struct target_type crypt_target = {
992         .name   = "crypt",
993         .version= {1, 3, 0},
994         .module = THIS_MODULE,
995         .ctr    = crypt_ctr,
996         .dtr    = crypt_dtr,
997         .map    = crypt_map,
998         .status = crypt_status,
999         .postsuspend = crypt_postsuspend,
1000         .preresume = crypt_preresume,
1001         .resume = crypt_resume,
1002         .message = crypt_message,
1003 };
1004
1005 static int __init dm_crypt_init(void)
1006 {
1007         int r;
1008
1009         _crypt_io_pool = kmem_cache_create("dm-crypt_io",
1010                                            sizeof(struct crypt_io),
1011                                            0, 0, NULL, NULL);
1012         if (!_crypt_io_pool)
1013                 return -ENOMEM;
1014
1015         _kcryptd_workqueue = create_workqueue("kcryptd");
1016         if (!_kcryptd_workqueue) {
1017                 r = -ENOMEM;
1018                 DMERR("couldn't create kcryptd");
1019                 goto bad1;
1020         }
1021
1022         r = dm_register_target(&crypt_target);
1023         if (r < 0) {
1024                 DMERR("register failed %d", r);
1025                 goto bad2;
1026         }
1027
1028         return 0;
1029
1030 bad2:
1031         destroy_workqueue(_kcryptd_workqueue);
1032 bad1:
1033         kmem_cache_destroy(_crypt_io_pool);
1034         return r;
1035 }
1036
1037 static void __exit dm_crypt_exit(void)
1038 {
1039         int r = dm_unregister_target(&crypt_target);
1040
1041         if (r < 0)
1042                 DMERR("unregister failed %d", r);
1043
1044         destroy_workqueue(_kcryptd_workqueue);
1045         kmem_cache_destroy(_crypt_io_pool);
1046 }
1047
1048 module_init(dm_crypt_init);
1049 module_exit(dm_crypt_exit);
1050
1051 MODULE_AUTHOR("Christophe Saout <christophe@saout.de>");
1052 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
1053 MODULE_LICENSE("GPL");