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