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