i2c: rockchip: fix power off issue for rk818
[firefly-linux-kernel-4.4.55.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-2009 Red Hat, Inc. All rights reserved.
5  * Copyright (C) 2013 Milan Broz <gmazyland@gmail.com>
6  *
7  * This file is released under the GPL.
8  */
9
10 #include <linux/completion.h>
11 #include <linux/err.h>
12 #include <linux/module.h>
13 #include <linux/init.h>
14 #include <linux/kernel.h>
15 #include <linux/bio.h>
16 #include <linux/blkdev.h>
17 #include <linux/mempool.h>
18 #include <linux/slab.h>
19 #include <linux/crypto.h>
20 #include <linux/workqueue.h>
21 #include <linux/backing-dev.h>
22 #include <linux/atomic.h>
23 #include <linux/scatterlist.h>
24 #include <asm/page.h>
25 #include <asm/unaligned.h>
26 #include <crypto/hash.h>
27 #include <crypto/md5.h>
28 #include <crypto/algapi.h>
29
30 #include <linux/device-mapper.h>
31
32 #define DM_MSG_PREFIX "crypt"
33
34 /*
35  * context holding the current state of a multi-part conversion
36  */
37 struct convert_context {
38         struct completion restart;
39         struct bio *bio_in;
40         struct bio *bio_out;
41         unsigned int offset_in;
42         unsigned int offset_out;
43         unsigned int idx_in;
44         unsigned int idx_out;
45         sector_t cc_sector;
46         atomic_t cc_pending;
47         struct ablkcipher_request *req;
48 };
49
50 /*
51  * per bio private data
52  */
53 struct dm_crypt_io {
54         struct crypt_config *cc;
55         struct bio *base_bio;
56         struct work_struct work;
57
58         struct convert_context ctx;
59
60         atomic_t io_pending;
61         int error;
62         sector_t sector;
63         struct dm_crypt_io *base_io;
64 } CRYPTO_MINALIGN_ATTR;
65
66 struct dm_crypt_request {
67         struct convert_context *ctx;
68         struct scatterlist sg_in;
69         struct scatterlist sg_out;
70         sector_t iv_sector;
71 };
72
73 struct crypt_config;
74
75 struct crypt_iv_operations {
76         int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
77                    const char *opts);
78         void (*dtr)(struct crypt_config *cc);
79         int (*init)(struct crypt_config *cc);
80         int (*wipe)(struct crypt_config *cc);
81         int (*generator)(struct crypt_config *cc, u8 *iv,
82                          struct dm_crypt_request *dmreq);
83         int (*post)(struct crypt_config *cc, u8 *iv,
84                     struct dm_crypt_request *dmreq);
85 };
86
87 struct iv_essiv_private {
88         struct crypto_hash *hash_tfm;
89         u8 *salt;
90 };
91
92 struct iv_benbi_private {
93         int shift;
94 };
95
96 #define LMK_SEED_SIZE 64 /* hash + 0 */
97 struct iv_lmk_private {
98         struct crypto_shash *hash_tfm;
99         u8 *seed;
100 };
101
102 #define TCW_WHITENING_SIZE 16
103 struct iv_tcw_private {
104         struct crypto_shash *crc32_tfm;
105         u8 *iv_seed;
106         u8 *whitening;
107 };
108
109 /*
110  * Crypt: maps a linear range of a block device
111  * and encrypts / decrypts at the same time.
112  */
113 enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID, DM_CRYPT_SAME_CPU };
114
115 /*
116  * The fields in here must be read only after initialization.
117  */
118 struct crypt_config {
119         struct dm_dev *dev;
120         sector_t start;
121
122         /*
123          * pool for per bio private data, crypto requests and
124          * encryption requeusts/buffer pages
125          */
126         mempool_t *io_pool;
127         mempool_t *req_pool;
128         mempool_t *page_pool;
129         struct bio_set *bs;
130
131         struct workqueue_struct *io_queue;
132         struct workqueue_struct *crypt_queue;
133
134         char *cipher;
135         char *cipher_string;
136
137         struct crypt_iv_operations *iv_gen_ops;
138         union {
139                 struct iv_essiv_private essiv;
140                 struct iv_benbi_private benbi;
141                 struct iv_lmk_private lmk;
142                 struct iv_tcw_private tcw;
143         } iv_gen_private;
144         sector_t iv_offset;
145         unsigned int iv_size;
146
147         /* ESSIV: struct crypto_cipher *essiv_tfm */
148         void *iv_private;
149         struct crypto_ablkcipher **tfms;
150         unsigned tfms_count;
151
152         /*
153          * Layout of each crypto request:
154          *
155          *   struct ablkcipher_request
156          *      context
157          *      padding
158          *   struct dm_crypt_request
159          *      padding
160          *   IV
161          *
162          * The padding is added so that dm_crypt_request and the IV are
163          * correctly aligned.
164          */
165         unsigned int dmreq_start;
166
167         unsigned int per_bio_data_size;
168
169         unsigned long flags;
170         unsigned int key_size;
171         unsigned int key_parts;      /* independent parts in key buffer */
172         unsigned int key_extra_size; /* additional keys length */
173         u8 key[0];
174 };
175
176 #define MIN_IOS        16
177 #define MIN_POOL_PAGES 32
178
179 static struct kmem_cache *_crypt_io_pool;
180
181 static void clone_init(struct dm_crypt_io *, struct bio *);
182 static void kcryptd_queue_crypt(struct dm_crypt_io *io);
183 static u8 *iv_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq);
184
185 /*
186  * Use this to access cipher attributes that are the same for each CPU.
187  */
188 static struct crypto_ablkcipher *any_tfm(struct crypt_config *cc)
189 {
190         return cc->tfms[0];
191 }
192
193 /*
194  * Different IV generation algorithms:
195  *
196  * plain: the initial vector is the 32-bit little-endian version of the sector
197  *        number, padded with zeros if necessary.
198  *
199  * plain64: the initial vector is the 64-bit little-endian version of the sector
200  *        number, padded with zeros if necessary.
201  *
202  * essiv: "encrypted sector|salt initial vector", the sector number is
203  *        encrypted with the bulk cipher using a salt as key. The salt
204  *        should be derived from the bulk cipher's key via hashing.
205  *
206  * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
207  *        (needed for LRW-32-AES and possible other narrow block modes)
208  *
209  * null: the initial vector is always zero.  Provides compatibility with
210  *       obsolete loop_fish2 devices.  Do not use for new devices.
211  *
212  * lmk:  Compatible implementation of the block chaining mode used
213  *       by the Loop-AES block device encryption system
214  *       designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
215  *       It operates on full 512 byte sectors and uses CBC
216  *       with an IV derived from the sector number, the data and
217  *       optionally extra IV seed.
218  *       This means that after decryption the first block
219  *       of sector must be tweaked according to decrypted data.
220  *       Loop-AES can use three encryption schemes:
221  *         version 1: is plain aes-cbc mode
222  *         version 2: uses 64 multikey scheme with lmk IV generator
223  *         version 3: the same as version 2 with additional IV seed
224  *                   (it uses 65 keys, last key is used as IV seed)
225  *
226  * tcw:  Compatible implementation of the block chaining mode used
227  *       by the TrueCrypt device encryption system (prior to version 4.1).
228  *       For more info see: http://www.truecrypt.org
229  *       It operates on full 512 byte sectors and uses CBC
230  *       with an IV derived from initial key and the sector number.
231  *       In addition, whitening value is applied on every sector, whitening
232  *       is calculated from initial key, sector number and mixed using CRC32.
233  *       Note that this encryption scheme is vulnerable to watermarking attacks
234  *       and should be used for old compatible containers access only.
235  *
236  * plumb: unimplemented, see:
237  * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
238  */
239
240 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
241                               struct dm_crypt_request *dmreq)
242 {
243         memset(iv, 0, cc->iv_size);
244         *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
245
246         return 0;
247 }
248
249 static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
250                                 struct dm_crypt_request *dmreq)
251 {
252         memset(iv, 0, cc->iv_size);
253         *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
254
255         return 0;
256 }
257
258 /* Initialise ESSIV - compute salt but no local memory allocations */
259 static int crypt_iv_essiv_init(struct crypt_config *cc)
260 {
261         struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
262         struct hash_desc desc;
263         struct scatterlist sg;
264         struct crypto_cipher *essiv_tfm;
265         int err;
266
267         sg_init_one(&sg, cc->key, cc->key_size);
268         desc.tfm = essiv->hash_tfm;
269         desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
270
271         err = crypto_hash_digest(&desc, &sg, cc->key_size, essiv->salt);
272         if (err)
273                 return err;
274
275         essiv_tfm = cc->iv_private;
276
277         err = crypto_cipher_setkey(essiv_tfm, essiv->salt,
278                             crypto_hash_digestsize(essiv->hash_tfm));
279         if (err)
280                 return err;
281
282         return 0;
283 }
284
285 /* Wipe salt and reset key derived from volume key */
286 static int crypt_iv_essiv_wipe(struct crypt_config *cc)
287 {
288         struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
289         unsigned salt_size = crypto_hash_digestsize(essiv->hash_tfm);
290         struct crypto_cipher *essiv_tfm;
291         int r, err = 0;
292
293         memset(essiv->salt, 0, salt_size);
294
295         essiv_tfm = cc->iv_private;
296         r = crypto_cipher_setkey(essiv_tfm, essiv->salt, salt_size);
297         if (r)
298                 err = r;
299
300         return err;
301 }
302
303 /* Set up per cpu cipher state */
304 static struct crypto_cipher *setup_essiv_cpu(struct crypt_config *cc,
305                                              struct dm_target *ti,
306                                              u8 *salt, unsigned saltsize)
307 {
308         struct crypto_cipher *essiv_tfm;
309         int err;
310
311         /* Setup the essiv_tfm with the given salt */
312         essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
313         if (IS_ERR(essiv_tfm)) {
314                 ti->error = "Error allocating crypto tfm for ESSIV";
315                 return essiv_tfm;
316         }
317
318         if (crypto_cipher_blocksize(essiv_tfm) !=
319             crypto_ablkcipher_ivsize(any_tfm(cc))) {
320                 ti->error = "Block size of ESSIV cipher does "
321                             "not match IV size of block cipher";
322                 crypto_free_cipher(essiv_tfm);
323                 return ERR_PTR(-EINVAL);
324         }
325
326         err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
327         if (err) {
328                 ti->error = "Failed to set key for ESSIV cipher";
329                 crypto_free_cipher(essiv_tfm);
330                 return ERR_PTR(err);
331         }
332
333         return essiv_tfm;
334 }
335
336 static void crypt_iv_essiv_dtr(struct crypt_config *cc)
337 {
338         struct crypto_cipher *essiv_tfm;
339         struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
340
341         crypto_free_hash(essiv->hash_tfm);
342         essiv->hash_tfm = NULL;
343
344         kzfree(essiv->salt);
345         essiv->salt = NULL;
346
347         essiv_tfm = cc->iv_private;
348
349         if (essiv_tfm)
350                 crypto_free_cipher(essiv_tfm);
351
352         cc->iv_private = NULL;
353 }
354
355 static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
356                               const char *opts)
357 {
358         struct crypto_cipher *essiv_tfm = NULL;
359         struct crypto_hash *hash_tfm = NULL;
360         u8 *salt = NULL;
361         int err;
362
363         if (!opts) {
364                 ti->error = "Digest algorithm missing for ESSIV mode";
365                 return -EINVAL;
366         }
367
368         /* Allocate hash algorithm */
369         hash_tfm = crypto_alloc_hash(opts, 0, CRYPTO_ALG_ASYNC);
370         if (IS_ERR(hash_tfm)) {
371                 ti->error = "Error initializing ESSIV hash";
372                 err = PTR_ERR(hash_tfm);
373                 goto bad;
374         }
375
376         salt = kzalloc(crypto_hash_digestsize(hash_tfm), GFP_KERNEL);
377         if (!salt) {
378                 ti->error = "Error kmallocing salt storage in ESSIV";
379                 err = -ENOMEM;
380                 goto bad;
381         }
382
383         cc->iv_gen_private.essiv.salt = salt;
384         cc->iv_gen_private.essiv.hash_tfm = hash_tfm;
385
386         essiv_tfm = setup_essiv_cpu(cc, ti, salt,
387                                 crypto_hash_digestsize(hash_tfm));
388         if (IS_ERR(essiv_tfm)) {
389                 crypt_iv_essiv_dtr(cc);
390                 return PTR_ERR(essiv_tfm);
391         }
392         cc->iv_private = essiv_tfm;
393
394         return 0;
395
396 bad:
397         if (hash_tfm && !IS_ERR(hash_tfm))
398                 crypto_free_hash(hash_tfm);
399         kfree(salt);
400         return err;
401 }
402
403 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
404                               struct dm_crypt_request *dmreq)
405 {
406         struct crypto_cipher *essiv_tfm = cc->iv_private;
407
408         memset(iv, 0, cc->iv_size);
409         *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
410         crypto_cipher_encrypt_one(essiv_tfm, iv, iv);
411
412         return 0;
413 }
414
415 static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
416                               const char *opts)
417 {
418         unsigned bs = crypto_ablkcipher_blocksize(any_tfm(cc));
419         int log = ilog2(bs);
420
421         /* we need to calculate how far we must shift the sector count
422          * to get the cipher block count, we use this shift in _gen */
423
424         if (1 << log != bs) {
425                 ti->error = "cypher blocksize is not a power of 2";
426                 return -EINVAL;
427         }
428
429         if (log > 9) {
430                 ti->error = "cypher blocksize is > 512";
431                 return -EINVAL;
432         }
433
434         cc->iv_gen_private.benbi.shift = 9 - log;
435
436         return 0;
437 }
438
439 static void crypt_iv_benbi_dtr(struct crypt_config *cc)
440 {
441 }
442
443 static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
444                               struct dm_crypt_request *dmreq)
445 {
446         __be64 val;
447
448         memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
449
450         val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
451         put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
452
453         return 0;
454 }
455
456 static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
457                              struct dm_crypt_request *dmreq)
458 {
459         memset(iv, 0, cc->iv_size);
460
461         return 0;
462 }
463
464 static void crypt_iv_lmk_dtr(struct crypt_config *cc)
465 {
466         struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
467
468         if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
469                 crypto_free_shash(lmk->hash_tfm);
470         lmk->hash_tfm = NULL;
471
472         kzfree(lmk->seed);
473         lmk->seed = NULL;
474 }
475
476 static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
477                             const char *opts)
478 {
479         struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
480
481         lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
482         if (IS_ERR(lmk->hash_tfm)) {
483                 ti->error = "Error initializing LMK hash";
484                 return PTR_ERR(lmk->hash_tfm);
485         }
486
487         /* No seed in LMK version 2 */
488         if (cc->key_parts == cc->tfms_count) {
489                 lmk->seed = NULL;
490                 return 0;
491         }
492
493         lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
494         if (!lmk->seed) {
495                 crypt_iv_lmk_dtr(cc);
496                 ti->error = "Error kmallocing seed storage in LMK";
497                 return -ENOMEM;
498         }
499
500         return 0;
501 }
502
503 static int crypt_iv_lmk_init(struct crypt_config *cc)
504 {
505         struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
506         int subkey_size = cc->key_size / cc->key_parts;
507
508         /* LMK seed is on the position of LMK_KEYS + 1 key */
509         if (lmk->seed)
510                 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
511                        crypto_shash_digestsize(lmk->hash_tfm));
512
513         return 0;
514 }
515
516 static int crypt_iv_lmk_wipe(struct crypt_config *cc)
517 {
518         struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
519
520         if (lmk->seed)
521                 memset(lmk->seed, 0, LMK_SEED_SIZE);
522
523         return 0;
524 }
525
526 static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
527                             struct dm_crypt_request *dmreq,
528                             u8 *data)
529 {
530         struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
531         struct {
532                 struct shash_desc desc;
533                 char ctx[crypto_shash_descsize(lmk->hash_tfm)];
534         } sdesc;
535         struct md5_state md5state;
536         __le32 buf[4];
537         int i, r;
538
539         sdesc.desc.tfm = lmk->hash_tfm;
540         sdesc.desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
541
542         r = crypto_shash_init(&sdesc.desc);
543         if (r)
544                 return r;
545
546         if (lmk->seed) {
547                 r = crypto_shash_update(&sdesc.desc, lmk->seed, LMK_SEED_SIZE);
548                 if (r)
549                         return r;
550         }
551
552         /* Sector is always 512B, block size 16, add data of blocks 1-31 */
553         r = crypto_shash_update(&sdesc.desc, data + 16, 16 * 31);
554         if (r)
555                 return r;
556
557         /* Sector is cropped to 56 bits here */
558         buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
559         buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
560         buf[2] = cpu_to_le32(4024);
561         buf[3] = 0;
562         r = crypto_shash_update(&sdesc.desc, (u8 *)buf, sizeof(buf));
563         if (r)
564                 return r;
565
566         /* No MD5 padding here */
567         r = crypto_shash_export(&sdesc.desc, &md5state);
568         if (r)
569                 return r;
570
571         for (i = 0; i < MD5_HASH_WORDS; i++)
572                 __cpu_to_le32s(&md5state.hash[i]);
573         memcpy(iv, &md5state.hash, cc->iv_size);
574
575         return 0;
576 }
577
578 static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
579                             struct dm_crypt_request *dmreq)
580 {
581         u8 *src;
582         int r = 0;
583
584         if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
585                 src = kmap_atomic(sg_page(&dmreq->sg_in));
586                 r = crypt_iv_lmk_one(cc, iv, dmreq, src + dmreq->sg_in.offset);
587                 kunmap_atomic(src);
588         } else
589                 memset(iv, 0, cc->iv_size);
590
591         return r;
592 }
593
594 static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
595                              struct dm_crypt_request *dmreq)
596 {
597         u8 *dst;
598         int r;
599
600         if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
601                 return 0;
602
603         dst = kmap_atomic(sg_page(&dmreq->sg_out));
604         r = crypt_iv_lmk_one(cc, iv, dmreq, dst + dmreq->sg_out.offset);
605
606         /* Tweak the first block of plaintext sector */
607         if (!r)
608                 crypto_xor(dst + dmreq->sg_out.offset, iv, cc->iv_size);
609
610         kunmap_atomic(dst);
611         return r;
612 }
613
614 static void crypt_iv_tcw_dtr(struct crypt_config *cc)
615 {
616         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
617
618         kzfree(tcw->iv_seed);
619         tcw->iv_seed = NULL;
620         kzfree(tcw->whitening);
621         tcw->whitening = NULL;
622
623         if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
624                 crypto_free_shash(tcw->crc32_tfm);
625         tcw->crc32_tfm = NULL;
626 }
627
628 static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
629                             const char *opts)
630 {
631         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
632
633         if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
634                 ti->error = "Wrong key size for TCW";
635                 return -EINVAL;
636         }
637
638         tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
639         if (IS_ERR(tcw->crc32_tfm)) {
640                 ti->error = "Error initializing CRC32 in TCW";
641                 return PTR_ERR(tcw->crc32_tfm);
642         }
643
644         tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
645         tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
646         if (!tcw->iv_seed || !tcw->whitening) {
647                 crypt_iv_tcw_dtr(cc);
648                 ti->error = "Error allocating seed storage in TCW";
649                 return -ENOMEM;
650         }
651
652         return 0;
653 }
654
655 static int crypt_iv_tcw_init(struct crypt_config *cc)
656 {
657         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
658         int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
659
660         memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
661         memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
662                TCW_WHITENING_SIZE);
663
664         return 0;
665 }
666
667 static int crypt_iv_tcw_wipe(struct crypt_config *cc)
668 {
669         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
670
671         memset(tcw->iv_seed, 0, cc->iv_size);
672         memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
673
674         return 0;
675 }
676
677 static int crypt_iv_tcw_whitening(struct crypt_config *cc,
678                                   struct dm_crypt_request *dmreq,
679                                   u8 *data)
680 {
681         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
682         u64 sector = cpu_to_le64((u64)dmreq->iv_sector);
683         u8 buf[TCW_WHITENING_SIZE];
684         struct {
685                 struct shash_desc desc;
686                 char ctx[crypto_shash_descsize(tcw->crc32_tfm)];
687         } sdesc;
688         int i, r;
689
690         /* xor whitening with sector number */
691         memcpy(buf, tcw->whitening, TCW_WHITENING_SIZE);
692         crypto_xor(buf, (u8 *)&sector, 8);
693         crypto_xor(&buf[8], (u8 *)&sector, 8);
694
695         /* calculate crc32 for every 32bit part and xor it */
696         sdesc.desc.tfm = tcw->crc32_tfm;
697         sdesc.desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
698         for (i = 0; i < 4; i++) {
699                 r = crypto_shash_init(&sdesc.desc);
700                 if (r)
701                         goto out;
702                 r = crypto_shash_update(&sdesc.desc, &buf[i * 4], 4);
703                 if (r)
704                         goto out;
705                 r = crypto_shash_final(&sdesc.desc, &buf[i * 4]);
706                 if (r)
707                         goto out;
708         }
709         crypto_xor(&buf[0], &buf[12], 4);
710         crypto_xor(&buf[4], &buf[8], 4);
711
712         /* apply whitening (8 bytes) to whole sector */
713         for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
714                 crypto_xor(data + i * 8, buf, 8);
715 out:
716         memzero_explicit(buf, sizeof(buf));
717         return r;
718 }
719
720 static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
721                             struct dm_crypt_request *dmreq)
722 {
723         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
724         u64 sector = cpu_to_le64((u64)dmreq->iv_sector);
725         u8 *src;
726         int r = 0;
727
728         /* Remove whitening from ciphertext */
729         if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
730                 src = kmap_atomic(sg_page(&dmreq->sg_in));
731                 r = crypt_iv_tcw_whitening(cc, dmreq, src + dmreq->sg_in.offset);
732                 kunmap_atomic(src);
733         }
734
735         /* Calculate IV */
736         memcpy(iv, tcw->iv_seed, cc->iv_size);
737         crypto_xor(iv, (u8 *)&sector, 8);
738         if (cc->iv_size > 8)
739                 crypto_xor(&iv[8], (u8 *)&sector, cc->iv_size - 8);
740
741         return r;
742 }
743
744 static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
745                              struct dm_crypt_request *dmreq)
746 {
747         u8 *dst;
748         int r;
749
750         if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
751                 return 0;
752
753         /* Apply whitening on ciphertext */
754         dst = kmap_atomic(sg_page(&dmreq->sg_out));
755         r = crypt_iv_tcw_whitening(cc, dmreq, dst + dmreq->sg_out.offset);
756         kunmap_atomic(dst);
757
758         return r;
759 }
760
761 static struct crypt_iv_operations crypt_iv_plain_ops = {
762         .generator = crypt_iv_plain_gen
763 };
764
765 static struct crypt_iv_operations crypt_iv_plain64_ops = {
766         .generator = crypt_iv_plain64_gen
767 };
768
769 static struct crypt_iv_operations crypt_iv_essiv_ops = {
770         .ctr       = crypt_iv_essiv_ctr,
771         .dtr       = crypt_iv_essiv_dtr,
772         .init      = crypt_iv_essiv_init,
773         .wipe      = crypt_iv_essiv_wipe,
774         .generator = crypt_iv_essiv_gen
775 };
776
777 static struct crypt_iv_operations crypt_iv_benbi_ops = {
778         .ctr       = crypt_iv_benbi_ctr,
779         .dtr       = crypt_iv_benbi_dtr,
780         .generator = crypt_iv_benbi_gen
781 };
782
783 static struct crypt_iv_operations crypt_iv_null_ops = {
784         .generator = crypt_iv_null_gen
785 };
786
787 static struct crypt_iv_operations crypt_iv_lmk_ops = {
788         .ctr       = crypt_iv_lmk_ctr,
789         .dtr       = crypt_iv_lmk_dtr,
790         .init      = crypt_iv_lmk_init,
791         .wipe      = crypt_iv_lmk_wipe,
792         .generator = crypt_iv_lmk_gen,
793         .post      = crypt_iv_lmk_post
794 };
795
796 static struct crypt_iv_operations crypt_iv_tcw_ops = {
797         .ctr       = crypt_iv_tcw_ctr,
798         .dtr       = crypt_iv_tcw_dtr,
799         .init      = crypt_iv_tcw_init,
800         .wipe      = crypt_iv_tcw_wipe,
801         .generator = crypt_iv_tcw_gen,
802         .post      = crypt_iv_tcw_post
803 };
804
805 static void crypt_convert_init(struct crypt_config *cc,
806                                struct convert_context *ctx,
807                                struct bio *bio_out, struct bio *bio_in,
808                                sector_t sector)
809 {
810         ctx->bio_in = bio_in;
811         ctx->bio_out = bio_out;
812         ctx->offset_in = 0;
813         ctx->offset_out = 0;
814         ctx->idx_in = bio_in ? bio_in->bi_idx : 0;
815         ctx->idx_out = bio_out ? bio_out->bi_idx : 0;
816         ctx->cc_sector = sector + cc->iv_offset;
817         init_completion(&ctx->restart);
818 }
819
820 static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
821                                              struct ablkcipher_request *req)
822 {
823         return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
824 }
825
826 static struct ablkcipher_request *req_of_dmreq(struct crypt_config *cc,
827                                                struct dm_crypt_request *dmreq)
828 {
829         return (struct ablkcipher_request *)((char *)dmreq - cc->dmreq_start);
830 }
831
832 static u8 *iv_of_dmreq(struct crypt_config *cc,
833                        struct dm_crypt_request *dmreq)
834 {
835         return (u8 *)ALIGN((unsigned long)(dmreq + 1),
836                 crypto_ablkcipher_alignmask(any_tfm(cc)) + 1);
837 }
838
839 static int crypt_convert_block(struct crypt_config *cc,
840                                struct convert_context *ctx,
841                                struct ablkcipher_request *req)
842 {
843         struct bio_vec *bv_in = bio_iovec_idx(ctx->bio_in, ctx->idx_in);
844         struct bio_vec *bv_out = bio_iovec_idx(ctx->bio_out, ctx->idx_out);
845         struct dm_crypt_request *dmreq;
846         u8 *iv;
847         int r;
848
849         dmreq = dmreq_of_req(cc, req);
850         iv = iv_of_dmreq(cc, dmreq);
851
852         dmreq->iv_sector = ctx->cc_sector;
853         dmreq->ctx = ctx;
854         sg_init_table(&dmreq->sg_in, 1);
855         sg_set_page(&dmreq->sg_in, bv_in->bv_page, 1 << SECTOR_SHIFT,
856                     bv_in->bv_offset + ctx->offset_in);
857
858         sg_init_table(&dmreq->sg_out, 1);
859         sg_set_page(&dmreq->sg_out, bv_out->bv_page, 1 << SECTOR_SHIFT,
860                     bv_out->bv_offset + ctx->offset_out);
861
862         ctx->offset_in += 1 << SECTOR_SHIFT;
863         if (ctx->offset_in >= bv_in->bv_len) {
864                 ctx->offset_in = 0;
865                 ctx->idx_in++;
866         }
867
868         ctx->offset_out += 1 << SECTOR_SHIFT;
869         if (ctx->offset_out >= bv_out->bv_len) {
870                 ctx->offset_out = 0;
871                 ctx->idx_out++;
872         }
873
874         if (cc->iv_gen_ops) {
875                 r = cc->iv_gen_ops->generator(cc, iv, dmreq);
876                 if (r < 0)
877                         return r;
878         }
879
880         ablkcipher_request_set_crypt(req, &dmreq->sg_in, &dmreq->sg_out,
881                                      1 << SECTOR_SHIFT, iv);
882
883         if (bio_data_dir(ctx->bio_in) == WRITE)
884                 r = crypto_ablkcipher_encrypt(req);
885         else
886                 r = crypto_ablkcipher_decrypt(req);
887
888         if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
889                 r = cc->iv_gen_ops->post(cc, iv, dmreq);
890
891         return r;
892 }
893
894 static void kcryptd_async_done(struct crypto_async_request *async_req,
895                                int error);
896
897 static void crypt_alloc_req(struct crypt_config *cc,
898                             struct convert_context *ctx)
899 {
900         unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
901
902         if (!ctx->req)
903                 ctx->req = mempool_alloc(cc->req_pool, GFP_NOIO);
904
905         ablkcipher_request_set_tfm(ctx->req, cc->tfms[key_index]);
906         ablkcipher_request_set_callback(ctx->req,
907             CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
908             kcryptd_async_done, dmreq_of_req(cc, ctx->req));
909 }
910
911 static void crypt_free_req(struct crypt_config *cc,
912                            struct ablkcipher_request *req, struct bio *base_bio)
913 {
914         struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
915
916         if ((struct ablkcipher_request *)(io + 1) != req)
917                 mempool_free(req, cc->req_pool);
918 }
919
920 /*
921  * Encrypt / decrypt data from one bio to another one (can be the same one)
922  */
923 static int crypt_convert(struct crypt_config *cc,
924                          struct convert_context *ctx)
925 {
926         int r;
927
928         atomic_set(&ctx->cc_pending, 1);
929
930         while(ctx->idx_in < ctx->bio_in->bi_vcnt &&
931               ctx->idx_out < ctx->bio_out->bi_vcnt) {
932
933                 crypt_alloc_req(cc, ctx);
934
935                 atomic_inc(&ctx->cc_pending);
936
937                 r = crypt_convert_block(cc, ctx, ctx->req);
938
939                 switch (r) {
940                 /* async */
941                 case -EBUSY:
942                         wait_for_completion(&ctx->restart);
943                         INIT_COMPLETION(ctx->restart);
944                         /* fall through*/
945                 case -EINPROGRESS:
946                         ctx->req = NULL;
947                         ctx->cc_sector++;
948                         continue;
949
950                 /* sync */
951                 case 0:
952                         atomic_dec(&ctx->cc_pending);
953                         ctx->cc_sector++;
954                         cond_resched();
955                         continue;
956
957                 /* error */
958                 default:
959                         atomic_dec(&ctx->cc_pending);
960                         return r;
961                 }
962         }
963
964         return 0;
965 }
966
967 /*
968  * Generate a new unfragmented bio with the given size
969  * This should never violate the device limitations
970  * May return a smaller bio when running out of pages, indicated by
971  * *out_of_pages set to 1.
972  */
973 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size,
974                                       unsigned *out_of_pages)
975 {
976         struct crypt_config *cc = io->cc;
977         struct bio *clone;
978         unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
979         gfp_t gfp_mask = GFP_NOIO | __GFP_HIGHMEM;
980         unsigned i, len;
981         struct page *page;
982
983         clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, cc->bs);
984         if (!clone)
985                 return NULL;
986
987         clone_init(io, clone);
988         *out_of_pages = 0;
989
990         for (i = 0; i < nr_iovecs; i++) {
991                 page = mempool_alloc(cc->page_pool, gfp_mask);
992                 if (!page) {
993                         *out_of_pages = 1;
994                         break;
995                 }
996
997                 /*
998                  * If additional pages cannot be allocated without waiting,
999                  * return a partially-allocated bio.  The caller will then try
1000                  * to allocate more bios while submitting this partial bio.
1001                  */
1002                 gfp_mask = (gfp_mask | __GFP_NOWARN) & ~__GFP_WAIT;
1003
1004                 len = (size > PAGE_SIZE) ? PAGE_SIZE : size;
1005
1006                 if (!bio_add_page(clone, page, len, 0)) {
1007                         mempool_free(page, cc->page_pool);
1008                         break;
1009                 }
1010
1011                 size -= len;
1012         }
1013
1014         if (!clone->bi_size) {
1015                 bio_put(clone);
1016                 return NULL;
1017         }
1018
1019         return clone;
1020 }
1021
1022 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1023 {
1024         unsigned int i;
1025         struct bio_vec *bv;
1026
1027         bio_for_each_segment_all(bv, clone, i) {
1028                 BUG_ON(!bv->bv_page);
1029                 mempool_free(bv->bv_page, cc->page_pool);
1030                 bv->bv_page = NULL;
1031         }
1032 }
1033
1034 static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1035                           struct bio *bio, sector_t sector)
1036 {
1037         io->cc = cc;
1038         io->base_bio = bio;
1039         io->sector = sector;
1040         io->error = 0;
1041         io->base_io = NULL;
1042         io->ctx.req = NULL;
1043         atomic_set(&io->io_pending, 0);
1044 }
1045
1046 static void crypt_inc_pending(struct dm_crypt_io *io)
1047 {
1048         atomic_inc(&io->io_pending);
1049 }
1050
1051 /*
1052  * One of the bios was finished. Check for completion of
1053  * the whole request and correctly clean up the buffer.
1054  * If base_io is set, wait for the last fragment to complete.
1055  */
1056 static void crypt_dec_pending(struct dm_crypt_io *io)
1057 {
1058         struct crypt_config *cc = io->cc;
1059         struct bio *base_bio = io->base_bio;
1060         struct dm_crypt_io *base_io = io->base_io;
1061         int error = io->error;
1062
1063         if (!atomic_dec_and_test(&io->io_pending))
1064                 return;
1065
1066         if (io->ctx.req)
1067                 crypt_free_req(cc, io->ctx.req, base_bio);
1068         if (io != dm_per_bio_data(base_bio, cc->per_bio_data_size))
1069                 mempool_free(io, cc->io_pool);
1070
1071         if (likely(!base_io))
1072                 bio_endio(base_bio, error);
1073         else {
1074                 if (error && !base_io->error)
1075                         base_io->error = error;
1076                 crypt_dec_pending(base_io);
1077         }
1078 }
1079
1080 /*
1081  * kcryptd/kcryptd_io:
1082  *
1083  * Needed because it would be very unwise to do decryption in an
1084  * interrupt context.
1085  *
1086  * kcryptd performs the actual encryption or decryption.
1087  *
1088  * kcryptd_io performs the IO submission.
1089  *
1090  * They must be separated as otherwise the final stages could be
1091  * starved by new requests which can block in the first stages due
1092  * to memory allocation.
1093  *
1094  * The work is done per CPU global for all dm-crypt instances.
1095  * They should not depend on each other and do not block.
1096  */
1097 static void crypt_endio(struct bio *clone, int error)
1098 {
1099         struct dm_crypt_io *io = clone->bi_private;
1100         struct crypt_config *cc = io->cc;
1101         unsigned rw = bio_data_dir(clone);
1102
1103         if (unlikely(!bio_flagged(clone, BIO_UPTODATE) && !error))
1104                 error = -EIO;
1105
1106         /*
1107          * free the processed pages
1108          */
1109         if (rw == WRITE)
1110                 crypt_free_buffer_pages(cc, clone);
1111
1112         bio_put(clone);
1113
1114         if (rw == READ && !error) {
1115                 kcryptd_queue_crypt(io);
1116                 return;
1117         }
1118
1119         if (unlikely(error))
1120                 io->error = error;
1121
1122         crypt_dec_pending(io);
1123 }
1124
1125 static void clone_init(struct dm_crypt_io *io, struct bio *clone)
1126 {
1127         struct crypt_config *cc = io->cc;
1128
1129         clone->bi_private = io;
1130         clone->bi_end_io  = crypt_endio;
1131         clone->bi_bdev    = cc->dev->bdev;
1132         clone->bi_rw      = io->base_bio->bi_rw;
1133 }
1134
1135 static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
1136 {
1137         struct crypt_config *cc = io->cc;
1138         struct bio *base_bio = io->base_bio;
1139         struct bio *clone;
1140
1141         /*
1142          * The block layer might modify the bvec array, so always
1143          * copy the required bvecs because we need the original
1144          * one in order to decrypt the whole bio data *afterwards*.
1145          */
1146         clone = bio_clone_bioset(base_bio, gfp, cc->bs);
1147         if (!clone)
1148                 return 1;
1149
1150         crypt_inc_pending(io);
1151
1152         clone_init(io, clone);
1153         clone->bi_sector = cc->start + io->sector;
1154
1155         generic_make_request(clone);
1156         return 0;
1157 }
1158
1159 static void kcryptd_io_write(struct dm_crypt_io *io)
1160 {
1161         struct bio *clone = io->ctx.bio_out;
1162         generic_make_request(clone);
1163 }
1164
1165 static void kcryptd_io(struct work_struct *work)
1166 {
1167         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1168
1169         if (bio_data_dir(io->base_bio) == READ) {
1170                 crypt_inc_pending(io);
1171                 if (kcryptd_io_read(io, GFP_NOIO))
1172                         io->error = -ENOMEM;
1173                 crypt_dec_pending(io);
1174         } else
1175                 kcryptd_io_write(io);
1176 }
1177
1178 static void kcryptd_queue_io(struct dm_crypt_io *io)
1179 {
1180         struct crypt_config *cc = io->cc;
1181
1182         INIT_WORK(&io->work, kcryptd_io);
1183         queue_work(cc->io_queue, &io->work);
1184 }
1185
1186 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
1187 {
1188         struct bio *clone = io->ctx.bio_out;
1189         struct crypt_config *cc = io->cc;
1190
1191         if (unlikely(io->error < 0)) {
1192                 crypt_free_buffer_pages(cc, clone);
1193                 bio_put(clone);
1194                 crypt_dec_pending(io);
1195                 return;
1196         }
1197
1198         /* crypt_convert should have filled the clone bio */
1199         BUG_ON(io->ctx.idx_out < clone->bi_vcnt);
1200
1201         clone->bi_sector = cc->start + io->sector;
1202
1203         if (async)
1204                 kcryptd_queue_io(io);
1205         else
1206                 generic_make_request(clone);
1207 }
1208
1209 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
1210 {
1211         struct crypt_config *cc = io->cc;
1212         struct bio *clone;
1213         struct dm_crypt_io *new_io;
1214         int crypt_finished;
1215         unsigned out_of_pages = 0;
1216         unsigned remaining = io->base_bio->bi_size;
1217         sector_t sector = io->sector;
1218         int r;
1219
1220         /*
1221          * Prevent io from disappearing until this function completes.
1222          */
1223         crypt_inc_pending(io);
1224         crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
1225
1226         /*
1227          * The allocated buffers can be smaller than the whole bio,
1228          * so repeat the whole process until all the data can be handled.
1229          */
1230         while (remaining) {
1231                 clone = crypt_alloc_buffer(io, remaining, &out_of_pages);
1232                 if (unlikely(!clone)) {
1233                         io->error = -ENOMEM;
1234                         break;
1235                 }
1236
1237                 io->ctx.bio_out = clone;
1238                 io->ctx.idx_out = 0;
1239
1240                 remaining -= clone->bi_size;
1241                 sector += bio_sectors(clone);
1242
1243                 crypt_inc_pending(io);
1244
1245                 r = crypt_convert(cc, &io->ctx);
1246                 if (r < 0)
1247                         io->error = -EIO;
1248
1249                 crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
1250
1251                 /* Encryption was already finished, submit io now */
1252                 if (crypt_finished) {
1253                         kcryptd_crypt_write_io_submit(io, 0);
1254
1255                         /*
1256                          * If there was an error, do not try next fragments.
1257                          * For async, error is processed in async handler.
1258                          */
1259                         if (unlikely(r < 0))
1260                                 break;
1261
1262                         io->sector = sector;
1263                 }
1264
1265                 /*
1266                  * Out of memory -> run queues
1267                  * But don't wait if split was due to the io size restriction
1268                  */
1269                 if (unlikely(out_of_pages))
1270                         congestion_wait(BLK_RW_ASYNC, HZ/100);
1271
1272                 /*
1273                  * With async crypto it is unsafe to share the crypto context
1274                  * between fragments, so switch to a new dm_crypt_io structure.
1275                  */
1276                 if (unlikely(!crypt_finished && remaining)) {
1277                         new_io = mempool_alloc(cc->io_pool, GFP_NOIO);
1278                         crypt_io_init(new_io, io->cc, io->base_bio, sector);
1279                         crypt_inc_pending(new_io);
1280                         crypt_convert_init(cc, &new_io->ctx, NULL,
1281                                            io->base_bio, sector);
1282                         new_io->ctx.idx_in = io->ctx.idx_in;
1283                         new_io->ctx.offset_in = io->ctx.offset_in;
1284
1285                         /*
1286                          * Fragments after the first use the base_io
1287                          * pending count.
1288                          */
1289                         if (!io->base_io)
1290                                 new_io->base_io = io;
1291                         else {
1292                                 new_io->base_io = io->base_io;
1293                                 crypt_inc_pending(io->base_io);
1294                                 crypt_dec_pending(io);
1295                         }
1296
1297                         io = new_io;
1298                 }
1299         }
1300
1301         crypt_dec_pending(io);
1302 }
1303
1304 static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
1305 {
1306         crypt_dec_pending(io);
1307 }
1308
1309 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
1310 {
1311         struct crypt_config *cc = io->cc;
1312         int r = 0;
1313
1314         crypt_inc_pending(io);
1315
1316         crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
1317                            io->sector);
1318
1319         r = crypt_convert(cc, &io->ctx);
1320         if (r < 0)
1321                 io->error = -EIO;
1322
1323         if (atomic_dec_and_test(&io->ctx.cc_pending))
1324                 kcryptd_crypt_read_done(io);
1325
1326         crypt_dec_pending(io);
1327 }
1328
1329 static void kcryptd_async_done(struct crypto_async_request *async_req,
1330                                int error)
1331 {
1332         struct dm_crypt_request *dmreq = async_req->data;
1333         struct convert_context *ctx = dmreq->ctx;
1334         struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1335         struct crypt_config *cc = io->cc;
1336
1337         if (error == -EINPROGRESS) {
1338                 complete(&ctx->restart);
1339                 return;
1340         }
1341
1342         if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
1343                 error = cc->iv_gen_ops->post(cc, iv_of_dmreq(cc, dmreq), dmreq);
1344
1345         if (error < 0)
1346                 io->error = -EIO;
1347
1348         crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
1349
1350         if (!atomic_dec_and_test(&ctx->cc_pending))
1351                 return;
1352
1353         if (bio_data_dir(io->base_bio) == READ)
1354                 kcryptd_crypt_read_done(io);
1355         else
1356                 kcryptd_crypt_write_io_submit(io, 1);
1357 }
1358
1359 static void kcryptd_crypt(struct work_struct *work)
1360 {
1361         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1362
1363         if (bio_data_dir(io->base_bio) == READ)
1364                 kcryptd_crypt_read_convert(io);
1365         else
1366                 kcryptd_crypt_write_convert(io);
1367 }
1368
1369 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
1370 {
1371         struct crypt_config *cc = io->cc;
1372
1373         INIT_WORK(&io->work, kcryptd_crypt);
1374         queue_work(cc->crypt_queue, &io->work);
1375 }
1376
1377 /*
1378  * Decode key from its hex representation
1379  */
1380 static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
1381 {
1382         char buffer[3];
1383         unsigned int i;
1384
1385         buffer[2] = '\0';
1386
1387         for (i = 0; i < size; i++) {
1388                 buffer[0] = *hex++;
1389                 buffer[1] = *hex++;
1390
1391                 if (kstrtou8(buffer, 16, &key[i]))
1392                         return -EINVAL;
1393         }
1394
1395         if (*hex != '\0')
1396                 return -EINVAL;
1397
1398         return 0;
1399 }
1400
1401 static void crypt_free_tfms(struct crypt_config *cc)
1402 {
1403         unsigned i;
1404
1405         if (!cc->tfms)
1406                 return;
1407
1408         for (i = 0; i < cc->tfms_count; i++)
1409                 if (cc->tfms[i] && !IS_ERR(cc->tfms[i])) {
1410                         crypto_free_ablkcipher(cc->tfms[i]);
1411                         cc->tfms[i] = NULL;
1412                 }
1413
1414         kfree(cc->tfms);
1415         cc->tfms = NULL;
1416 }
1417
1418 static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
1419 {
1420         unsigned i;
1421         int err;
1422
1423         cc->tfms = kmalloc(cc->tfms_count * sizeof(struct crypto_ablkcipher *),
1424                            GFP_KERNEL);
1425         if (!cc->tfms)
1426                 return -ENOMEM;
1427
1428         for (i = 0; i < cc->tfms_count; i++) {
1429                 cc->tfms[i] = crypto_alloc_ablkcipher(ciphermode, 0, 0);
1430                 if (IS_ERR(cc->tfms[i])) {
1431                         err = PTR_ERR(cc->tfms[i]);
1432                         crypt_free_tfms(cc);
1433                         return err;
1434                 }
1435         }
1436
1437         return 0;
1438 }
1439
1440 static int crypt_setkey_allcpus(struct crypt_config *cc)
1441 {
1442         unsigned subkey_size;
1443         int err = 0, i, r;
1444
1445         /* Ignore extra keys (which are used for IV etc) */
1446         subkey_size = (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
1447
1448         for (i = 0; i < cc->tfms_count; i++) {
1449                 r = crypto_ablkcipher_setkey(cc->tfms[i],
1450                                              cc->key + (i * subkey_size),
1451                                              subkey_size);
1452                 if (r)
1453                         err = r;
1454         }
1455
1456         return err;
1457 }
1458
1459 static int crypt_set_key(struct crypt_config *cc, char *key)
1460 {
1461         int r = -EINVAL;
1462         int key_string_len = strlen(key);
1463
1464         /* The key size may not be changed. */
1465         if (cc->key_size != (key_string_len >> 1))
1466                 goto out;
1467
1468         /* Hyphen (which gives a key_size of zero) means there is no key. */
1469         if (!cc->key_size && strcmp(key, "-"))
1470                 goto out;
1471
1472         if (cc->key_size && crypt_decode_key(cc->key, key, cc->key_size) < 0)
1473                 goto out;
1474
1475         set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
1476
1477         r = crypt_setkey_allcpus(cc);
1478
1479 out:
1480         /* Hex key string not needed after here, so wipe it. */
1481         memset(key, '0', key_string_len);
1482
1483         return r;
1484 }
1485
1486 static int crypt_wipe_key(struct crypt_config *cc)
1487 {
1488         clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
1489         memset(&cc->key, 0, cc->key_size * sizeof(u8));
1490
1491         return crypt_setkey_allcpus(cc);
1492 }
1493
1494 static void crypt_dtr(struct dm_target *ti)
1495 {
1496         struct crypt_config *cc = ti->private;
1497
1498         ti->private = NULL;
1499
1500         if (!cc)
1501                 return;
1502
1503         if (cc->io_queue)
1504                 destroy_workqueue(cc->io_queue);
1505         if (cc->crypt_queue)
1506                 destroy_workqueue(cc->crypt_queue);
1507
1508         crypt_free_tfms(cc);
1509
1510         if (cc->bs)
1511                 bioset_free(cc->bs);
1512
1513         if (cc->page_pool)
1514                 mempool_destroy(cc->page_pool);
1515         if (cc->req_pool)
1516                 mempool_destroy(cc->req_pool);
1517         if (cc->io_pool)
1518                 mempool_destroy(cc->io_pool);
1519
1520         if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
1521                 cc->iv_gen_ops->dtr(cc);
1522
1523         if (cc->dev)
1524                 dm_put_device(ti, cc->dev);
1525
1526         kzfree(cc->cipher);
1527         kzfree(cc->cipher_string);
1528
1529         /* Must zero key material before freeing */
1530         kzfree(cc);
1531 }
1532
1533 static int crypt_ctr_cipher(struct dm_target *ti,
1534                             char *cipher_in, char *key)
1535 {
1536         struct crypt_config *cc = ti->private;
1537         char *tmp, *cipher, *chainmode, *ivmode, *ivopts, *keycount;
1538         char *cipher_api = NULL;
1539         int ret = -EINVAL;
1540         char dummy;
1541
1542         /* Convert to crypto api definition? */
1543         if (strchr(cipher_in, '(')) {
1544                 ti->error = "Bad cipher specification";
1545                 return -EINVAL;
1546         }
1547
1548         cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
1549         if (!cc->cipher_string)
1550                 goto bad_mem;
1551
1552         /*
1553          * Legacy dm-crypt cipher specification
1554          * cipher[:keycount]-mode-iv:ivopts
1555          */
1556         tmp = cipher_in;
1557         keycount = strsep(&tmp, "-");
1558         cipher = strsep(&keycount, ":");
1559
1560         if (!keycount)
1561                 cc->tfms_count = 1;
1562         else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
1563                  !is_power_of_2(cc->tfms_count)) {
1564                 ti->error = "Bad cipher key count specification";
1565                 return -EINVAL;
1566         }
1567         cc->key_parts = cc->tfms_count;
1568         cc->key_extra_size = 0;
1569
1570         cc->cipher = kstrdup(cipher, GFP_KERNEL);
1571         if (!cc->cipher)
1572                 goto bad_mem;
1573
1574         chainmode = strsep(&tmp, "-");
1575         ivopts = strsep(&tmp, "-");
1576         ivmode = strsep(&ivopts, ":");
1577
1578         if (tmp)
1579                 DMWARN("Ignoring unexpected additional cipher options");
1580
1581         /*
1582          * For compatibility with the original dm-crypt mapping format, if
1583          * only the cipher name is supplied, use cbc-plain.
1584          */
1585         if (!chainmode || (!strcmp(chainmode, "plain") && !ivmode)) {
1586                 chainmode = "cbc";
1587                 ivmode = "plain";
1588         }
1589
1590         if (strcmp(chainmode, "ecb") && !ivmode) {
1591                 ti->error = "IV mechanism required";
1592                 return -EINVAL;
1593         }
1594
1595         cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
1596         if (!cipher_api)
1597                 goto bad_mem;
1598
1599         ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
1600                        "%s(%s)", chainmode, cipher);
1601         if (ret < 0) {
1602                 kfree(cipher_api);
1603                 goto bad_mem;
1604         }
1605
1606         /* Allocate cipher */
1607         ret = crypt_alloc_tfms(cc, cipher_api);
1608         if (ret < 0) {
1609                 ti->error = "Error allocating crypto tfm";
1610                 goto bad;
1611         }
1612
1613         /* Initialize IV */
1614         cc->iv_size = crypto_ablkcipher_ivsize(any_tfm(cc));
1615         if (cc->iv_size)
1616                 /* at least a 64 bit sector number should fit in our buffer */
1617                 cc->iv_size = max(cc->iv_size,
1618                                   (unsigned int)(sizeof(u64) / sizeof(u8)));
1619         else if (ivmode) {
1620                 DMWARN("Selected cipher does not support IVs");
1621                 ivmode = NULL;
1622         }
1623
1624         /* Choose ivmode, see comments at iv code. */
1625         if (ivmode == NULL)
1626                 cc->iv_gen_ops = NULL;
1627         else if (strcmp(ivmode, "plain") == 0)
1628                 cc->iv_gen_ops = &crypt_iv_plain_ops;
1629         else if (strcmp(ivmode, "plain64") == 0)
1630                 cc->iv_gen_ops = &crypt_iv_plain64_ops;
1631         else if (strcmp(ivmode, "essiv") == 0)
1632                 cc->iv_gen_ops = &crypt_iv_essiv_ops;
1633         else if (strcmp(ivmode, "benbi") == 0)
1634                 cc->iv_gen_ops = &crypt_iv_benbi_ops;
1635         else if (strcmp(ivmode, "null") == 0)
1636                 cc->iv_gen_ops = &crypt_iv_null_ops;
1637         else if (strcmp(ivmode, "lmk") == 0) {
1638                 cc->iv_gen_ops = &crypt_iv_lmk_ops;
1639                 /*
1640                  * Version 2 and 3 is recognised according
1641                  * to length of provided multi-key string.
1642                  * If present (version 3), last key is used as IV seed.
1643                  * All keys (including IV seed) are always the same size.
1644                  */
1645                 if (cc->key_size % cc->key_parts) {
1646                         cc->key_parts++;
1647                         cc->key_extra_size = cc->key_size / cc->key_parts;
1648                 }
1649         } else if (strcmp(ivmode, "tcw") == 0) {
1650                 cc->iv_gen_ops = &crypt_iv_tcw_ops;
1651                 cc->key_parts += 2; /* IV + whitening */
1652                 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
1653         } else {
1654                 ret = -EINVAL;
1655                 ti->error = "Invalid IV mode";
1656                 goto bad;
1657         }
1658
1659         /* Initialize and set key */
1660         ret = crypt_set_key(cc, key);
1661         if (ret < 0) {
1662                 ti->error = "Error decoding and setting key";
1663                 goto bad;
1664         }
1665
1666         /* Allocate IV */
1667         if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
1668                 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
1669                 if (ret < 0) {
1670                         ti->error = "Error creating IV";
1671                         goto bad;
1672                 }
1673         }
1674
1675         /* Initialize IV (set keys for ESSIV etc) */
1676         if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
1677                 ret = cc->iv_gen_ops->init(cc);
1678                 if (ret < 0) {
1679                         ti->error = "Error initialising IV";
1680                         goto bad;
1681                 }
1682         }
1683
1684         ret = 0;
1685 bad:
1686         kfree(cipher_api);
1687         return ret;
1688
1689 bad_mem:
1690         ti->error = "Cannot allocate cipher strings";
1691         return -ENOMEM;
1692 }
1693
1694 /*
1695  * Construct an encryption mapping:
1696  * <cipher> <key> <iv_offset> <dev_path> <start>
1697  */
1698 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
1699 {
1700         struct crypt_config *cc;
1701         unsigned int key_size, opt_params;
1702         unsigned long long tmpll;
1703         int ret;
1704         size_t iv_size_padding;
1705         struct dm_arg_set as;
1706         const char *opt_string;
1707         char dummy;
1708
1709         static struct dm_arg _args[] = {
1710                 {0, 2, "Invalid number of feature args"},
1711         };
1712
1713         if (argc < 5) {
1714                 ti->error = "Not enough arguments";
1715                 return -EINVAL;
1716         }
1717
1718         key_size = strlen(argv[1]) >> 1;
1719
1720         cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
1721         if (!cc) {
1722                 ti->error = "Cannot allocate encryption context";
1723                 return -ENOMEM;
1724         }
1725         cc->key_size = key_size;
1726
1727         ti->private = cc;
1728         ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
1729         if (ret < 0)
1730                 goto bad;
1731
1732         ret = -ENOMEM;
1733         cc->io_pool = mempool_create_slab_pool(MIN_IOS, _crypt_io_pool);
1734         if (!cc->io_pool) {
1735                 ti->error = "Cannot allocate crypt io mempool";
1736                 goto bad;
1737         }
1738
1739         cc->dmreq_start = sizeof(struct ablkcipher_request);
1740         cc->dmreq_start += crypto_ablkcipher_reqsize(any_tfm(cc));
1741         cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
1742
1743         if (crypto_ablkcipher_alignmask(any_tfm(cc)) < CRYPTO_MINALIGN) {
1744                 /* Allocate the padding exactly */
1745                 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
1746                                 & crypto_ablkcipher_alignmask(any_tfm(cc));
1747         } else {
1748                 /*
1749                  * If the cipher requires greater alignment than kmalloc
1750                  * alignment, we don't know the exact position of the
1751                  * initialization vector. We must assume worst case.
1752                  */
1753                 iv_size_padding = crypto_ablkcipher_alignmask(any_tfm(cc));
1754         }
1755
1756         cc->req_pool = mempool_create_kmalloc_pool(MIN_IOS, cc->dmreq_start +
1757                         sizeof(struct dm_crypt_request) + iv_size_padding + cc->iv_size);
1758         if (!cc->req_pool) {
1759                 ti->error = "Cannot allocate crypt request mempool";
1760                 goto bad;
1761         }
1762
1763         cc->per_bio_data_size = ti->per_bio_data_size =
1764                                 sizeof(struct dm_crypt_io) + cc->dmreq_start +
1765                                 sizeof(struct dm_crypt_request) + cc->iv_size;
1766
1767         cc->page_pool = mempool_create_page_pool(MIN_POOL_PAGES, 0);
1768         if (!cc->page_pool) {
1769                 ti->error = "Cannot allocate page mempool";
1770                 goto bad;
1771         }
1772
1773         cc->bs = bioset_create(MIN_IOS, 0);
1774         if (!cc->bs) {
1775                 ti->error = "Cannot allocate crypt bioset";
1776                 goto bad;
1777         }
1778
1779         ret = -EINVAL;
1780         if (sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) {
1781                 ti->error = "Invalid iv_offset sector";
1782                 goto bad;
1783         }
1784         cc->iv_offset = tmpll;
1785
1786         if (dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev)) {
1787                 ti->error = "Device lookup failed";
1788                 goto bad;
1789         }
1790
1791         if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1) {
1792                 ti->error = "Invalid device sector";
1793                 goto bad;
1794         }
1795         cc->start = tmpll;
1796
1797         argv += 5;
1798         argc -= 5;
1799
1800         /* Optional parameters */
1801         if (argc) {
1802                 as.argc = argc;
1803                 as.argv = argv;
1804
1805                 ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
1806                 if (ret)
1807                         goto bad;
1808
1809                 while (opt_params--) {
1810                         opt_string = dm_shift_arg(&as);
1811                         if (!opt_string) {
1812                                 ti->error = "Not enough feature arguments";
1813                                 goto bad;
1814                         }
1815
1816                         if (!strcasecmp(opt_string, "allow_discards"))
1817                                 ti->num_discard_bios = 1;
1818
1819                         else if (!strcasecmp(opt_string, "same_cpu_crypt"))
1820                                 set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
1821
1822                         else {
1823                                 ti->error = "Invalid feature arguments";
1824                                 goto bad;
1825                         }
1826                 }
1827         }
1828
1829         ret = -ENOMEM;
1830         cc->io_queue = alloc_workqueue("kcryptd_io", WQ_MEM_RECLAIM, 1);
1831         if (!cc->io_queue) {
1832                 ti->error = "Couldn't create kcryptd io queue";
1833                 goto bad;
1834         }
1835
1836         if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
1837                 cc->crypt_queue = alloc_workqueue("kcryptd", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM, 1);
1838         else
1839                 cc->crypt_queue = alloc_workqueue("kcryptd", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
1840                                                   num_online_cpus());
1841         if (!cc->crypt_queue) {
1842                 ti->error = "Couldn't create kcryptd queue";
1843                 goto bad;
1844         }
1845
1846         ti->num_flush_bios = 1;
1847         ti->discard_zeroes_data_unsupported = true;
1848
1849         return 0;
1850
1851 bad:
1852         crypt_dtr(ti);
1853         return ret;
1854 }
1855
1856 static int crypt_map(struct dm_target *ti, struct bio *bio)
1857 {
1858         struct dm_crypt_io *io;
1859         struct crypt_config *cc = ti->private;
1860
1861         /*
1862          * If bio is REQ_FLUSH or REQ_DISCARD, just bypass crypt queues.
1863          * - for REQ_FLUSH device-mapper core ensures that no IO is in-flight
1864          * - for REQ_DISCARD caller must use flush if IO ordering matters
1865          */
1866         if (unlikely(bio->bi_rw & (REQ_FLUSH | REQ_DISCARD))) {
1867                 bio->bi_bdev = cc->dev->bdev;
1868                 if (bio_sectors(bio))
1869                         bio->bi_sector = cc->start + dm_target_offset(ti, bio->bi_sector);
1870                 return DM_MAPIO_REMAPPED;
1871         }
1872
1873         io = dm_per_bio_data(bio, cc->per_bio_data_size);
1874         crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_sector));
1875         io->ctx.req = (struct ablkcipher_request *)(io + 1);
1876
1877         if (bio_data_dir(io->base_bio) == READ) {
1878                 if (kcryptd_io_read(io, GFP_NOWAIT))
1879                         kcryptd_queue_io(io);
1880         } else
1881                 kcryptd_queue_crypt(io);
1882
1883         return DM_MAPIO_SUBMITTED;
1884 }
1885
1886 static void crypt_status(struct dm_target *ti, status_type_t type,
1887                          unsigned status_flags, char *result, unsigned maxlen)
1888 {
1889         struct crypt_config *cc = ti->private;
1890         unsigned i, sz = 0;
1891         int num_feature_args = 0;
1892
1893         switch (type) {
1894         case STATUSTYPE_INFO:
1895                 result[0] = '\0';
1896                 break;
1897
1898         case STATUSTYPE_TABLE:
1899                 DMEMIT("%s ", cc->cipher_string);
1900
1901                 if (cc->key_size > 0)
1902                         for (i = 0; i < cc->key_size; i++)
1903                                 DMEMIT("%02x", cc->key[i]);
1904                 else
1905                         DMEMIT("-");
1906
1907                 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
1908                                 cc->dev->name, (unsigned long long)cc->start);
1909
1910                 num_feature_args += !!ti->num_discard_bios;
1911                 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
1912                 if (num_feature_args) {
1913                         DMEMIT(" %d", num_feature_args);
1914                         if (ti->num_discard_bios)
1915                                 DMEMIT(" allow_discards");
1916                         if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
1917                                 DMEMIT(" same_cpu_crypt");
1918                 }
1919
1920                 break;
1921         }
1922 }
1923
1924 static void crypt_postsuspend(struct dm_target *ti)
1925 {
1926         struct crypt_config *cc = ti->private;
1927
1928         set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
1929 }
1930
1931 static int crypt_preresume(struct dm_target *ti)
1932 {
1933         struct crypt_config *cc = ti->private;
1934
1935         if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
1936                 DMERR("aborting resume - crypt key is not set.");
1937                 return -EAGAIN;
1938         }
1939
1940         return 0;
1941 }
1942
1943 static void crypt_resume(struct dm_target *ti)
1944 {
1945         struct crypt_config *cc = ti->private;
1946
1947         clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
1948 }
1949
1950 /* Message interface
1951  *      key set <key>
1952  *      key wipe
1953  */
1954 static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
1955 {
1956         struct crypt_config *cc = ti->private;
1957         int ret = -EINVAL;
1958
1959         if (argc < 2)
1960                 goto error;
1961
1962         if (!strcasecmp(argv[0], "key")) {
1963                 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
1964                         DMWARN("not suspended during key manipulation.");
1965                         return -EINVAL;
1966                 }
1967                 if (argc == 3 && !strcasecmp(argv[1], "set")) {
1968                         ret = crypt_set_key(cc, argv[2]);
1969                         if (ret)
1970                                 return ret;
1971                         if (cc->iv_gen_ops && cc->iv_gen_ops->init)
1972                                 ret = cc->iv_gen_ops->init(cc);
1973                         return ret;
1974                 }
1975                 if (argc == 2 && !strcasecmp(argv[1], "wipe")) {
1976                         if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
1977                                 ret = cc->iv_gen_ops->wipe(cc);
1978                                 if (ret)
1979                                         return ret;
1980                         }
1981                         return crypt_wipe_key(cc);
1982                 }
1983         }
1984
1985 error:
1986         DMWARN("unrecognised message received.");
1987         return -EINVAL;
1988 }
1989
1990 static int crypt_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
1991                        struct bio_vec *biovec, int max_size)
1992 {
1993         struct crypt_config *cc = ti->private;
1994         struct request_queue *q = bdev_get_queue(cc->dev->bdev);
1995
1996         if (!q->merge_bvec_fn)
1997                 return max_size;
1998
1999         bvm->bi_bdev = cc->dev->bdev;
2000         bvm->bi_sector = cc->start + dm_target_offset(ti, bvm->bi_sector);
2001
2002         return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
2003 }
2004
2005 static int crypt_iterate_devices(struct dm_target *ti,
2006                                  iterate_devices_callout_fn fn, void *data)
2007 {
2008         struct crypt_config *cc = ti->private;
2009
2010         return fn(ti, cc->dev, cc->start, ti->len, data);
2011 }
2012
2013 static struct target_type crypt_target = {
2014         .name   = "crypt",
2015         .version = {1, 14, 0},
2016         .module = THIS_MODULE,
2017         .ctr    = crypt_ctr,
2018         .dtr    = crypt_dtr,
2019         .map    = crypt_map,
2020         .status = crypt_status,
2021         .postsuspend = crypt_postsuspend,
2022         .preresume = crypt_preresume,
2023         .resume = crypt_resume,
2024         .message = crypt_message,
2025         .merge  = crypt_merge,
2026         .iterate_devices = crypt_iterate_devices,
2027 };
2028
2029 static int __init dm_crypt_init(void)
2030 {
2031         int r;
2032
2033         _crypt_io_pool = KMEM_CACHE(dm_crypt_io, 0);
2034         if (!_crypt_io_pool)
2035                 return -ENOMEM;
2036
2037         r = dm_register_target(&crypt_target);
2038         if (r < 0) {
2039                 DMERR("register failed %d", r);
2040                 kmem_cache_destroy(_crypt_io_pool);
2041         }
2042
2043         return r;
2044 }
2045
2046 static void __exit dm_crypt_exit(void)
2047 {
2048         dm_unregister_target(&crypt_target);
2049         kmem_cache_destroy(_crypt_io_pool);
2050 }
2051
2052 module_init(dm_crypt_init);
2053 module_exit(dm_crypt_exit);
2054
2055 MODULE_AUTHOR("Christophe Saout <christophe@saout.de>");
2056 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
2057 MODULE_LICENSE("GPL");