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