OSDN Git Service

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