]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/md/dm-crypt.c
dm crypt: factor IV constructor out to separate function
[karo-tx-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-2017 Red Hat, Inc. All rights reserved.
5  * Copyright (C) 2013-2017 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/key.h>
16 #include <linux/bio.h>
17 #include <linux/blkdev.h>
18 #include <linux/mempool.h>
19 #include <linux/slab.h>
20 #include <linux/crypto.h>
21 #include <linux/workqueue.h>
22 #include <linux/kthread.h>
23 #include <linux/backing-dev.h>
24 #include <linux/atomic.h>
25 #include <linux/scatterlist.h>
26 #include <linux/rbtree.h>
27 #include <linux/ctype.h>
28 #include <asm/page.h>
29 #include <asm/unaligned.h>
30 #include <crypto/hash.h>
31 #include <crypto/md5.h>
32 #include <crypto/algapi.h>
33 #include <crypto/skcipher.h>
34 #include <crypto/aead.h>
35 #include <crypto/authenc.h>
36 #include <linux/rtnetlink.h> /* for struct rtattr and RTA macros only */
37 #include <keys/user-type.h>
38
39 #include <linux/device-mapper.h>
40
41 #define DM_MSG_PREFIX "crypt"
42
43 /*
44  * context holding the current state of a multi-part conversion
45  */
46 struct convert_context {
47         struct completion restart;
48         struct bio *bio_in;
49         struct bio *bio_out;
50         struct bvec_iter iter_in;
51         struct bvec_iter iter_out;
52         sector_t cc_sector;
53         atomic_t cc_pending;
54         union {
55                 struct skcipher_request *req;
56                 struct aead_request *req_aead;
57         } r;
58
59 };
60
61 /*
62  * per bio private data
63  */
64 struct dm_crypt_io {
65         struct crypt_config *cc;
66         struct bio *base_bio;
67         u8 *integrity_metadata;
68         bool integrity_metadata_from_pool;
69         struct work_struct work;
70
71         struct convert_context ctx;
72
73         atomic_t io_pending;
74         int error;
75         sector_t sector;
76
77         struct rb_node rb_node;
78 } CRYPTO_MINALIGN_ATTR;
79
80 struct dm_crypt_request {
81         struct convert_context *ctx;
82         struct scatterlist sg_in[4];
83         struct scatterlist sg_out[4];
84         sector_t iv_sector;
85 };
86
87 struct crypt_config;
88
89 struct crypt_iv_operations {
90         int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
91                    const char *opts);
92         void (*dtr)(struct crypt_config *cc);
93         int (*init)(struct crypt_config *cc);
94         int (*wipe)(struct crypt_config *cc);
95         int (*generator)(struct crypt_config *cc, u8 *iv,
96                          struct dm_crypt_request *dmreq);
97         int (*post)(struct crypt_config *cc, u8 *iv,
98                     struct dm_crypt_request *dmreq);
99 };
100
101 struct iv_essiv_private {
102         struct crypto_ahash *hash_tfm;
103         u8 *salt;
104 };
105
106 struct iv_benbi_private {
107         int shift;
108 };
109
110 #define LMK_SEED_SIZE 64 /* hash + 0 */
111 struct iv_lmk_private {
112         struct crypto_shash *hash_tfm;
113         u8 *seed;
114 };
115
116 #define TCW_WHITENING_SIZE 16
117 struct iv_tcw_private {
118         struct crypto_shash *crc32_tfm;
119         u8 *iv_seed;
120         u8 *whitening;
121 };
122
123 /*
124  * Crypt: maps a linear range of a block device
125  * and encrypts / decrypts at the same time.
126  */
127 enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
128              DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD };
129
130 enum cipher_flags {
131         CRYPT_MODE_INTEGRITY_AEAD,      /* Use authenticated mode for cihper */
132         CRYPT_MODE_INTEGRITY_HMAC,      /* Compose authenticated mode from normal mode and HMAC */
133 };
134
135 /*
136  * The fields in here must be read only after initialization.
137  */
138 struct crypt_config {
139         struct dm_dev *dev;
140         sector_t start;
141
142         /*
143          * pool for per bio private data, crypto requests,
144          * encryption requeusts/buffer pages and integrity tags
145          */
146         mempool_t *req_pool;
147         mempool_t *page_pool;
148         mempool_t *tag_pool;
149         unsigned tag_pool_max_sectors;
150
151         struct bio_set *bs;
152         struct mutex bio_alloc_lock;
153
154         struct workqueue_struct *io_queue;
155         struct workqueue_struct *crypt_queue;
156
157         struct task_struct *write_thread;
158         wait_queue_head_t write_thread_wait;
159         struct rb_root write_tree;
160
161         char *cipher;
162         char *cipher_string;
163         char *cipher_auth;
164         char *key_string;
165
166         const struct crypt_iv_operations *iv_gen_ops;
167         union {
168                 struct iv_essiv_private essiv;
169                 struct iv_benbi_private benbi;
170                 struct iv_lmk_private lmk;
171                 struct iv_tcw_private tcw;
172         } iv_gen_private;
173         sector_t iv_offset;
174         unsigned int iv_size;
175
176         /* ESSIV: struct crypto_cipher *essiv_tfm */
177         void *iv_private;
178         union {
179                 struct crypto_skcipher **tfms;
180                 struct crypto_aead **tfms_aead;
181         } cipher_tfm;
182         unsigned tfms_count;
183         unsigned long cipher_flags;
184
185         /*
186          * Layout of each crypto request:
187          *
188          *   struct skcipher_request
189          *      context
190          *      padding
191          *   struct dm_crypt_request
192          *      padding
193          *   IV
194          *
195          * The padding is added so that dm_crypt_request and the IV are
196          * correctly aligned.
197          */
198         unsigned int dmreq_start;
199
200         unsigned int per_bio_data_size;
201
202         unsigned long flags;
203         unsigned int key_size;
204         unsigned int key_parts;      /* independent parts in key buffer */
205         unsigned int key_extra_size; /* additional keys length */
206         unsigned int key_mac_size;   /* MAC key size for authenc(...) */
207
208         unsigned int integrity_tag_size;
209         unsigned int integrity_iv_size;
210         unsigned int on_disk_tag_size;
211
212         u8 *authenc_key; /* space for keys in authenc() format (if used) */
213         u8 key[0];
214 };
215
216 #define MIN_IOS         64
217 #define MAX_TAG_SIZE    480
218 #define POOL_ENTRY_SIZE 512
219
220 static void clone_init(struct dm_crypt_io *, struct bio *);
221 static void kcryptd_queue_crypt(struct dm_crypt_io *io);
222 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
223                                              struct scatterlist *sg);
224
225 /*
226  * Use this to access cipher attributes that are the same for each CPU.
227  */
228 static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
229 {
230         return cc->cipher_tfm.tfms[0];
231 }
232
233 static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
234 {
235         return cc->cipher_tfm.tfms_aead[0];
236 }
237
238 /*
239  * Different IV generation algorithms:
240  *
241  * plain: the initial vector is the 32-bit little-endian version of the sector
242  *        number, padded with zeros if necessary.
243  *
244  * plain64: the initial vector is the 64-bit little-endian version of the sector
245  *        number, padded with zeros if necessary.
246  *
247  * essiv: "encrypted sector|salt initial vector", the sector number is
248  *        encrypted with the bulk cipher using a salt as key. The salt
249  *        should be derived from the bulk cipher's key via hashing.
250  *
251  * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
252  *        (needed for LRW-32-AES and possible other narrow block modes)
253  *
254  * null: the initial vector is always zero.  Provides compatibility with
255  *       obsolete loop_fish2 devices.  Do not use for new devices.
256  *
257  * lmk:  Compatible implementation of the block chaining mode used
258  *       by the Loop-AES block device encryption system
259  *       designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
260  *       It operates on full 512 byte sectors and uses CBC
261  *       with an IV derived from the sector number, the data and
262  *       optionally extra IV seed.
263  *       This means that after decryption the first block
264  *       of sector must be tweaked according to decrypted data.
265  *       Loop-AES can use three encryption schemes:
266  *         version 1: is plain aes-cbc mode
267  *         version 2: uses 64 multikey scheme with lmk IV generator
268  *         version 3: the same as version 2 with additional IV seed
269  *                   (it uses 65 keys, last key is used as IV seed)
270  *
271  * tcw:  Compatible implementation of the block chaining mode used
272  *       by the TrueCrypt device encryption system (prior to version 4.1).
273  *       For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
274  *       It operates on full 512 byte sectors and uses CBC
275  *       with an IV derived from initial key and the sector number.
276  *       In addition, whitening value is applied on every sector, whitening
277  *       is calculated from initial key, sector number and mixed using CRC32.
278  *       Note that this encryption scheme is vulnerable to watermarking attacks
279  *       and should be used for old compatible containers access only.
280  *
281  * plumb: unimplemented, see:
282  * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
283  */
284
285 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
286                               struct dm_crypt_request *dmreq)
287 {
288         memset(iv, 0, cc->iv_size);
289         *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
290
291         return 0;
292 }
293
294 static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
295                                 struct dm_crypt_request *dmreq)
296 {
297         memset(iv, 0, cc->iv_size);
298         *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
299
300         return 0;
301 }
302
303 /* Initialise ESSIV - compute salt but no local memory allocations */
304 static int crypt_iv_essiv_init(struct crypt_config *cc)
305 {
306         struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
307         AHASH_REQUEST_ON_STACK(req, essiv->hash_tfm);
308         struct scatterlist sg;
309         struct crypto_cipher *essiv_tfm;
310         int err;
311
312         sg_init_one(&sg, cc->key, cc->key_size);
313         ahash_request_set_tfm(req, essiv->hash_tfm);
314         ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP, NULL, NULL);
315         ahash_request_set_crypt(req, &sg, essiv->salt, cc->key_size);
316
317         err = crypto_ahash_digest(req);
318         ahash_request_zero(req);
319         if (err)
320                 return err;
321
322         essiv_tfm = cc->iv_private;
323
324         err = crypto_cipher_setkey(essiv_tfm, essiv->salt,
325                             crypto_ahash_digestsize(essiv->hash_tfm));
326         if (err)
327                 return err;
328
329         return 0;
330 }
331
332 /* Wipe salt and reset key derived from volume key */
333 static int crypt_iv_essiv_wipe(struct crypt_config *cc)
334 {
335         struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
336         unsigned salt_size = crypto_ahash_digestsize(essiv->hash_tfm);
337         struct crypto_cipher *essiv_tfm;
338         int r, err = 0;
339
340         memset(essiv->salt, 0, salt_size);
341
342         essiv_tfm = cc->iv_private;
343         r = crypto_cipher_setkey(essiv_tfm, essiv->salt, salt_size);
344         if (r)
345                 err = r;
346
347         return err;
348 }
349
350 /* Set up per cpu cipher state */
351 static struct crypto_cipher *setup_essiv_cpu(struct crypt_config *cc,
352                                              struct dm_target *ti,
353                                              u8 *salt, unsigned saltsize)
354 {
355         struct crypto_cipher *essiv_tfm;
356         int err;
357
358         /* Setup the essiv_tfm with the given salt */
359         essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
360         if (IS_ERR(essiv_tfm)) {
361                 ti->error = "Error allocating crypto tfm for ESSIV";
362                 return essiv_tfm;
363         }
364
365         if (crypto_cipher_blocksize(essiv_tfm) != cc->iv_size) {
366                 ti->error = "Block size of ESSIV cipher does "
367                             "not match IV size of block cipher";
368                 crypto_free_cipher(essiv_tfm);
369                 return ERR_PTR(-EINVAL);
370         }
371
372         err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
373         if (err) {
374                 ti->error = "Failed to set key for ESSIV cipher";
375                 crypto_free_cipher(essiv_tfm);
376                 return ERR_PTR(err);
377         }
378
379         return essiv_tfm;
380 }
381
382 static void crypt_iv_essiv_dtr(struct crypt_config *cc)
383 {
384         struct crypto_cipher *essiv_tfm;
385         struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
386
387         crypto_free_ahash(essiv->hash_tfm);
388         essiv->hash_tfm = NULL;
389
390         kzfree(essiv->salt);
391         essiv->salt = NULL;
392
393         essiv_tfm = cc->iv_private;
394
395         if (essiv_tfm)
396                 crypto_free_cipher(essiv_tfm);
397
398         cc->iv_private = NULL;
399 }
400
401 static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
402                               const char *opts)
403 {
404         struct crypto_cipher *essiv_tfm = NULL;
405         struct crypto_ahash *hash_tfm = NULL;
406         u8 *salt = NULL;
407         int err;
408
409         if (!opts) {
410                 ti->error = "Digest algorithm missing for ESSIV mode";
411                 return -EINVAL;
412         }
413
414         /* Allocate hash algorithm */
415         hash_tfm = crypto_alloc_ahash(opts, 0, CRYPTO_ALG_ASYNC);
416         if (IS_ERR(hash_tfm)) {
417                 ti->error = "Error initializing ESSIV hash";
418                 err = PTR_ERR(hash_tfm);
419                 goto bad;
420         }
421
422         salt = kzalloc(crypto_ahash_digestsize(hash_tfm), GFP_KERNEL);
423         if (!salt) {
424                 ti->error = "Error kmallocing salt storage in ESSIV";
425                 err = -ENOMEM;
426                 goto bad;
427         }
428
429         cc->iv_gen_private.essiv.salt = salt;
430         cc->iv_gen_private.essiv.hash_tfm = hash_tfm;
431
432         essiv_tfm = setup_essiv_cpu(cc, ti, salt,
433                                 crypto_ahash_digestsize(hash_tfm));
434
435         if (IS_ERR(essiv_tfm)) {
436                 crypt_iv_essiv_dtr(cc);
437                 return PTR_ERR(essiv_tfm);
438         }
439         cc->iv_private = essiv_tfm;
440
441         return 0;
442
443 bad:
444         if (hash_tfm && !IS_ERR(hash_tfm))
445                 crypto_free_ahash(hash_tfm);
446         kfree(salt);
447         return err;
448 }
449
450 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
451                               struct dm_crypt_request *dmreq)
452 {
453         struct crypto_cipher *essiv_tfm = cc->iv_private;
454
455         memset(iv, 0, cc->iv_size);
456         *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
457         crypto_cipher_encrypt_one(essiv_tfm, iv, iv);
458
459         return 0;
460 }
461
462 static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
463                               const char *opts)
464 {
465         unsigned bs = crypto_skcipher_blocksize(any_tfm(cc));
466         int log = ilog2(bs);
467
468         /* we need to calculate how far we must shift the sector count
469          * to get the cipher block count, we use this shift in _gen */
470
471         if (1 << log != bs) {
472                 ti->error = "cypher blocksize is not a power of 2";
473                 return -EINVAL;
474         }
475
476         if (log > 9) {
477                 ti->error = "cypher blocksize is > 512";
478                 return -EINVAL;
479         }
480
481         cc->iv_gen_private.benbi.shift = 9 - log;
482
483         return 0;
484 }
485
486 static void crypt_iv_benbi_dtr(struct crypt_config *cc)
487 {
488 }
489
490 static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
491                               struct dm_crypt_request *dmreq)
492 {
493         __be64 val;
494
495         memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
496
497         val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
498         put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
499
500         return 0;
501 }
502
503 static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
504                              struct dm_crypt_request *dmreq)
505 {
506         memset(iv, 0, cc->iv_size);
507
508         return 0;
509 }
510
511 static void crypt_iv_lmk_dtr(struct crypt_config *cc)
512 {
513         struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
514
515         if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
516                 crypto_free_shash(lmk->hash_tfm);
517         lmk->hash_tfm = NULL;
518
519         kzfree(lmk->seed);
520         lmk->seed = NULL;
521 }
522
523 static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
524                             const char *opts)
525 {
526         struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
527
528         lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
529         if (IS_ERR(lmk->hash_tfm)) {
530                 ti->error = "Error initializing LMK hash";
531                 return PTR_ERR(lmk->hash_tfm);
532         }
533
534         /* No seed in LMK version 2 */
535         if (cc->key_parts == cc->tfms_count) {
536                 lmk->seed = NULL;
537                 return 0;
538         }
539
540         lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
541         if (!lmk->seed) {
542                 crypt_iv_lmk_dtr(cc);
543                 ti->error = "Error kmallocing seed storage in LMK";
544                 return -ENOMEM;
545         }
546
547         return 0;
548 }
549
550 static int crypt_iv_lmk_init(struct crypt_config *cc)
551 {
552         struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
553         int subkey_size = cc->key_size / cc->key_parts;
554
555         /* LMK seed is on the position of LMK_KEYS + 1 key */
556         if (lmk->seed)
557                 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
558                        crypto_shash_digestsize(lmk->hash_tfm));
559
560         return 0;
561 }
562
563 static int crypt_iv_lmk_wipe(struct crypt_config *cc)
564 {
565         struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
566
567         if (lmk->seed)
568                 memset(lmk->seed, 0, LMK_SEED_SIZE);
569
570         return 0;
571 }
572
573 static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
574                             struct dm_crypt_request *dmreq,
575                             u8 *data)
576 {
577         struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
578         SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
579         struct md5_state md5state;
580         __le32 buf[4];
581         int i, r;
582
583         desc->tfm = lmk->hash_tfm;
584         desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
585
586         r = crypto_shash_init(desc);
587         if (r)
588                 return r;
589
590         if (lmk->seed) {
591                 r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
592                 if (r)
593                         return r;
594         }
595
596         /* Sector is always 512B, block size 16, add data of blocks 1-31 */
597         r = crypto_shash_update(desc, data + 16, 16 * 31);
598         if (r)
599                 return r;
600
601         /* Sector is cropped to 56 bits here */
602         buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
603         buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
604         buf[2] = cpu_to_le32(4024);
605         buf[3] = 0;
606         r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
607         if (r)
608                 return r;
609
610         /* No MD5 padding here */
611         r = crypto_shash_export(desc, &md5state);
612         if (r)
613                 return r;
614
615         for (i = 0; i < MD5_HASH_WORDS; i++)
616                 __cpu_to_le32s(&md5state.hash[i]);
617         memcpy(iv, &md5state.hash, cc->iv_size);
618
619         return 0;
620 }
621
622 static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
623                             struct dm_crypt_request *dmreq)
624 {
625         struct scatterlist *sg;
626         u8 *src;
627         int r = 0;
628
629         if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
630                 sg = crypt_get_sg_data(cc, dmreq->sg_in);
631                 src = kmap_atomic(sg_page(sg));
632                 r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
633                 kunmap_atomic(src);
634         } else
635                 memset(iv, 0, cc->iv_size);
636
637         return r;
638 }
639
640 static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
641                              struct dm_crypt_request *dmreq)
642 {
643         struct scatterlist *sg;
644         u8 *dst;
645         int r;
646
647         if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
648                 return 0;
649
650         sg = crypt_get_sg_data(cc, dmreq->sg_out);
651         dst = kmap_atomic(sg_page(sg));
652         r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
653
654         /* Tweak the first block of plaintext sector */
655         if (!r)
656                 crypto_xor(dst + sg->offset, iv, cc->iv_size);
657
658         kunmap_atomic(dst);
659         return r;
660 }
661
662 static void crypt_iv_tcw_dtr(struct crypt_config *cc)
663 {
664         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
665
666         kzfree(tcw->iv_seed);
667         tcw->iv_seed = NULL;
668         kzfree(tcw->whitening);
669         tcw->whitening = NULL;
670
671         if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
672                 crypto_free_shash(tcw->crc32_tfm);
673         tcw->crc32_tfm = NULL;
674 }
675
676 static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
677                             const char *opts)
678 {
679         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
680
681         if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
682                 ti->error = "Wrong key size for TCW";
683                 return -EINVAL;
684         }
685
686         tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
687         if (IS_ERR(tcw->crc32_tfm)) {
688                 ti->error = "Error initializing CRC32 in TCW";
689                 return PTR_ERR(tcw->crc32_tfm);
690         }
691
692         tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
693         tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
694         if (!tcw->iv_seed || !tcw->whitening) {
695                 crypt_iv_tcw_dtr(cc);
696                 ti->error = "Error allocating seed storage in TCW";
697                 return -ENOMEM;
698         }
699
700         return 0;
701 }
702
703 static int crypt_iv_tcw_init(struct crypt_config *cc)
704 {
705         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
706         int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
707
708         memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
709         memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
710                TCW_WHITENING_SIZE);
711
712         return 0;
713 }
714
715 static int crypt_iv_tcw_wipe(struct crypt_config *cc)
716 {
717         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
718
719         memset(tcw->iv_seed, 0, cc->iv_size);
720         memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
721
722         return 0;
723 }
724
725 static int crypt_iv_tcw_whitening(struct crypt_config *cc,
726                                   struct dm_crypt_request *dmreq,
727                                   u8 *data)
728 {
729         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
730         __le64 sector = cpu_to_le64(dmreq->iv_sector);
731         u8 buf[TCW_WHITENING_SIZE];
732         SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
733         int i, r;
734
735         /* xor whitening with sector number */
736         memcpy(buf, tcw->whitening, TCW_WHITENING_SIZE);
737         crypto_xor(buf, (u8 *)&sector, 8);
738         crypto_xor(&buf[8], (u8 *)&sector, 8);
739
740         /* calculate crc32 for every 32bit part and xor it */
741         desc->tfm = tcw->crc32_tfm;
742         desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
743         for (i = 0; i < 4; i++) {
744                 r = crypto_shash_init(desc);
745                 if (r)
746                         goto out;
747                 r = crypto_shash_update(desc, &buf[i * 4], 4);
748                 if (r)
749                         goto out;
750                 r = crypto_shash_final(desc, &buf[i * 4]);
751                 if (r)
752                         goto out;
753         }
754         crypto_xor(&buf[0], &buf[12], 4);
755         crypto_xor(&buf[4], &buf[8], 4);
756
757         /* apply whitening (8 bytes) to whole sector */
758         for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
759                 crypto_xor(data + i * 8, buf, 8);
760 out:
761         memzero_explicit(buf, sizeof(buf));
762         return r;
763 }
764
765 static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
766                             struct dm_crypt_request *dmreq)
767 {
768         struct scatterlist *sg;
769         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
770         __le64 sector = cpu_to_le64(dmreq->iv_sector);
771         u8 *src;
772         int r = 0;
773
774         /* Remove whitening from ciphertext */
775         if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
776                 sg = crypt_get_sg_data(cc, dmreq->sg_in);
777                 src = kmap_atomic(sg_page(sg));
778                 r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
779                 kunmap_atomic(src);
780         }
781
782         /* Calculate IV */
783         memcpy(iv, tcw->iv_seed, cc->iv_size);
784         crypto_xor(iv, (u8 *)&sector, 8);
785         if (cc->iv_size > 8)
786                 crypto_xor(&iv[8], (u8 *)&sector, cc->iv_size - 8);
787
788         return r;
789 }
790
791 static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
792                              struct dm_crypt_request *dmreq)
793 {
794         struct scatterlist *sg;
795         u8 *dst;
796         int r;
797
798         if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
799                 return 0;
800
801         /* Apply whitening on ciphertext */
802         sg = crypt_get_sg_data(cc, dmreq->sg_out);
803         dst = kmap_atomic(sg_page(sg));
804         r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
805         kunmap_atomic(dst);
806
807         return r;
808 }
809
810 static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
811                                 struct dm_crypt_request *dmreq)
812 {
813         /* Used only for writes, there must be an additional space to store IV */
814         get_random_bytes(iv, cc->iv_size);
815         return 0;
816 }
817
818 static const struct crypt_iv_operations crypt_iv_plain_ops = {
819         .generator = crypt_iv_plain_gen
820 };
821
822 static const struct crypt_iv_operations crypt_iv_plain64_ops = {
823         .generator = crypt_iv_plain64_gen
824 };
825
826 static const struct crypt_iv_operations crypt_iv_essiv_ops = {
827         .ctr       = crypt_iv_essiv_ctr,
828         .dtr       = crypt_iv_essiv_dtr,
829         .init      = crypt_iv_essiv_init,
830         .wipe      = crypt_iv_essiv_wipe,
831         .generator = crypt_iv_essiv_gen
832 };
833
834 static const struct crypt_iv_operations crypt_iv_benbi_ops = {
835         .ctr       = crypt_iv_benbi_ctr,
836         .dtr       = crypt_iv_benbi_dtr,
837         .generator = crypt_iv_benbi_gen
838 };
839
840 static const struct crypt_iv_operations crypt_iv_null_ops = {
841         .generator = crypt_iv_null_gen
842 };
843
844 static const struct crypt_iv_operations crypt_iv_lmk_ops = {
845         .ctr       = crypt_iv_lmk_ctr,
846         .dtr       = crypt_iv_lmk_dtr,
847         .init      = crypt_iv_lmk_init,
848         .wipe      = crypt_iv_lmk_wipe,
849         .generator = crypt_iv_lmk_gen,
850         .post      = crypt_iv_lmk_post
851 };
852
853 static const struct crypt_iv_operations crypt_iv_tcw_ops = {
854         .ctr       = crypt_iv_tcw_ctr,
855         .dtr       = crypt_iv_tcw_dtr,
856         .init      = crypt_iv_tcw_init,
857         .wipe      = crypt_iv_tcw_wipe,
858         .generator = crypt_iv_tcw_gen,
859         .post      = crypt_iv_tcw_post
860 };
861
862 static struct crypt_iv_operations crypt_iv_random_ops = {
863         .generator = crypt_iv_random_gen
864 };
865
866 /*
867  * Integrity extensions
868  */
869 static bool crypt_integrity_aead(struct crypt_config *cc)
870 {
871         return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
872 }
873
874 static bool crypt_integrity_hmac(struct crypt_config *cc)
875 {
876         return test_bit(CRYPT_MODE_INTEGRITY_HMAC, &cc->cipher_flags);
877 }
878
879 static bool crypt_integrity_mode(struct crypt_config *cc)
880 {
881         return crypt_integrity_aead(cc) || crypt_integrity_hmac(cc);
882 }
883
884 /* Get sg containing data */
885 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
886                                              struct scatterlist *sg)
887 {
888         if (unlikely(crypt_integrity_mode(cc)))
889                 return &sg[2];
890
891         return sg;
892 }
893
894 static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
895 {
896         struct bio_integrity_payload *bip;
897         unsigned int tag_len;
898         int ret;
899
900         if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
901                 return 0;
902
903         bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
904         if (IS_ERR(bip))
905                 return PTR_ERR(bip);
906
907         tag_len = io->cc->on_disk_tag_size * bio_sectors(bio);
908
909         bip->bip_iter.bi_size = tag_len;
910         bip->bip_iter.bi_sector = io->cc->start + io->sector;
911
912         /* We own the metadata, do not let bio_free to release it */
913         bip->bip_flags &= ~BIP_BLOCK_INTEGRITY;
914
915         ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
916                                      tag_len, offset_in_page(io->integrity_metadata));
917         if (unlikely(ret != tag_len))
918                 return -ENOMEM;
919
920         return 0;
921 }
922
923 static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
924 {
925 #ifdef CONFIG_BLK_DEV_INTEGRITY
926         struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
927
928         /* From now we require underlying device with our integrity profile */
929         if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
930                 ti->error = "Integrity profile not supported.";
931                 return -EINVAL;
932         }
933
934         if (bi->tag_size != cc->on_disk_tag_size) {
935                 ti->error = "Integrity profile tag size mismatch.";
936                 return -EINVAL;
937         }
938
939         if (crypt_integrity_mode(cc)) {
940                 cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
941                 DMINFO("Integrity AEAD, tag size %u, IV size %u.",
942                        cc->integrity_tag_size, cc->integrity_iv_size);
943
944                 if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
945                         ti->error = "Integrity AEAD auth tag size is not supported.";
946                         return -EINVAL;
947                 }
948         } else if (cc->integrity_iv_size)
949                 DMINFO("Additional per-sector space %u bytes for IV.",
950                        cc->integrity_iv_size);
951
952         if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
953                 ti->error = "Not enough space for integrity tag in the profile.";
954                 return -EINVAL;
955         }
956
957         return 0;
958 #else
959         ti->error = "Integrity profile not supported.";
960         return -EINVAL;
961 #endif
962 }
963
964 static void crypt_convert_init(struct crypt_config *cc,
965                                struct convert_context *ctx,
966                                struct bio *bio_out, struct bio *bio_in,
967                                sector_t sector)
968 {
969         ctx->bio_in = bio_in;
970         ctx->bio_out = bio_out;
971         if (bio_in)
972                 ctx->iter_in = bio_in->bi_iter;
973         if (bio_out)
974                 ctx->iter_out = bio_out->bi_iter;
975         ctx->cc_sector = sector + cc->iv_offset;
976         init_completion(&ctx->restart);
977 }
978
979 static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
980                                              void *req)
981 {
982         return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
983 }
984
985 static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
986 {
987         return (void *)((char *)dmreq - cc->dmreq_start);
988 }
989
990 static u8 *iv_of_dmreq(struct crypt_config *cc,
991                        struct dm_crypt_request *dmreq)
992 {
993         if (crypt_integrity_mode(cc))
994                 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
995                         crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
996         else
997                 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
998                         crypto_skcipher_alignmask(any_tfm(cc)) + 1);
999 }
1000
1001 static u8 *org_iv_of_dmreq(struct crypt_config *cc,
1002                        struct dm_crypt_request *dmreq)
1003 {
1004         return iv_of_dmreq(cc, dmreq) + cc->iv_size;
1005 }
1006
1007 static uint64_t *org_sector_of_dmreq(struct crypt_config *cc,
1008                        struct dm_crypt_request *dmreq)
1009 {
1010         u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
1011         return (uint64_t*) ptr;
1012 }
1013
1014 static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
1015                        struct dm_crypt_request *dmreq)
1016 {
1017         u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
1018                   cc->iv_size + sizeof(uint64_t);
1019         return (unsigned int*)ptr;
1020 }
1021
1022 static void *tag_from_dmreq(struct crypt_config *cc,
1023                                 struct dm_crypt_request *dmreq)
1024 {
1025         struct convert_context *ctx = dmreq->ctx;
1026         struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1027
1028         return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
1029                 cc->on_disk_tag_size];
1030 }
1031
1032 static void *iv_tag_from_dmreq(struct crypt_config *cc,
1033                                struct dm_crypt_request *dmreq)
1034 {
1035         return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
1036 }
1037
1038 static int crypt_convert_block_aead(struct crypt_config *cc,
1039                                      struct convert_context *ctx,
1040                                      struct aead_request *req,
1041                                      unsigned int tag_offset)
1042 {
1043         struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1044         struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1045         struct dm_crypt_request *dmreq;
1046         unsigned int data_len = 1 << SECTOR_SHIFT;
1047         u8 *iv, *org_iv, *tag_iv, *tag;
1048         uint64_t *sector;
1049         int r = 0;
1050
1051         BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
1052
1053         dmreq = dmreq_of_req(cc, req);
1054         dmreq->iv_sector = ctx->cc_sector;
1055         dmreq->ctx = ctx;
1056
1057         *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1058
1059         sector = org_sector_of_dmreq(cc, dmreq);
1060         *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1061
1062         iv = iv_of_dmreq(cc, dmreq);
1063         org_iv = org_iv_of_dmreq(cc, dmreq);
1064         tag = tag_from_dmreq(cc, dmreq);
1065         tag_iv = iv_tag_from_dmreq(cc, dmreq);
1066
1067         /* AEAD request:
1068          *  |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1069          *  | (authenticated) | (auth+encryption) |              |
1070          *  | sector_LE |  IV |  sector in/out    |  tag in/out  |
1071          */
1072         sg_init_table(dmreq->sg_in, 4);
1073         sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
1074         sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
1075         sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, data_len, bv_in.bv_offset);
1076         sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
1077
1078         sg_init_table(dmreq->sg_out, 4);
1079         sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
1080         sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
1081         sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, data_len, bv_out.bv_offset);
1082         sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
1083
1084         if (cc->iv_gen_ops) {
1085                 /* For READs use IV stored in integrity metadata */
1086                 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1087                         memcpy(org_iv, tag_iv, cc->iv_size);
1088                 } else {
1089                         r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1090                         if (r < 0)
1091                                 return r;
1092                         /* Store generated IV in integrity metadata */
1093                         if (cc->integrity_iv_size)
1094                                 memcpy(tag_iv, org_iv, cc->iv_size);
1095                 }
1096                 /* Working copy of IV, to be modified in crypto API */
1097                 memcpy(iv, org_iv, cc->iv_size);
1098         }
1099
1100         aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
1101         if (bio_data_dir(ctx->bio_in) == WRITE) {
1102                 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1103                                        data_len, iv);
1104                 r = crypto_aead_encrypt(req);
1105                 if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
1106                         memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
1107                                cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
1108         } else {
1109                 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1110                                        data_len + cc->integrity_tag_size, iv);
1111                 r = crypto_aead_decrypt(req);
1112         }
1113
1114         if (r == -EBADMSG)
1115                 DMERR_LIMIT("INTEGRITY AEAD ERROR, sector %llu",
1116                             (unsigned long long)le64_to_cpu(*sector));
1117
1118         if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1119                 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1120
1121         bio_advance_iter(ctx->bio_in, &ctx->iter_in, data_len);
1122         bio_advance_iter(ctx->bio_out, &ctx->iter_out, data_len);
1123
1124         return r;
1125 }
1126
1127 static int crypt_convert_block_skcipher(struct crypt_config *cc,
1128                                         struct convert_context *ctx,
1129                                         struct skcipher_request *req,
1130                                         unsigned int tag_offset)
1131 {
1132         struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1133         struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1134         struct scatterlist *sg_in, *sg_out;
1135         struct dm_crypt_request *dmreq;
1136         unsigned int data_len = 1 << SECTOR_SHIFT;
1137         u8 *iv, *org_iv, *tag_iv;
1138         uint64_t *sector;
1139         int r = 0;
1140
1141         dmreq = dmreq_of_req(cc, req);
1142         dmreq->iv_sector = ctx->cc_sector;
1143         dmreq->ctx = ctx;
1144
1145         *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1146
1147         iv = iv_of_dmreq(cc, dmreq);
1148         org_iv = org_iv_of_dmreq(cc, dmreq);
1149         tag_iv = iv_tag_from_dmreq(cc, dmreq);
1150
1151         sector = org_sector_of_dmreq(cc, dmreq);
1152         *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1153
1154         /* For skcipher we use only the first sg item */
1155         sg_in  = &dmreq->sg_in[0];
1156         sg_out = &dmreq->sg_out[0];
1157
1158         sg_init_table(sg_in, 1);
1159         sg_set_page(sg_in, bv_in.bv_page, data_len, bv_in.bv_offset);
1160
1161         sg_init_table(sg_out, 1);
1162         sg_set_page(sg_out, bv_out.bv_page, data_len, bv_out.bv_offset);
1163
1164         if (cc->iv_gen_ops) {
1165                 /* For READs use IV stored in integrity metadata */
1166                 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1167                         memcpy(org_iv, tag_iv, cc->integrity_iv_size);
1168                 } else {
1169                         r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1170                         if (r < 0)
1171                                 return r;
1172                         /* Store generated IV in integrity metadata */
1173                         if (cc->integrity_iv_size)
1174                                 memcpy(tag_iv, org_iv, cc->integrity_iv_size);
1175                 }
1176                 /* Working copy of IV, to be modified in crypto API */
1177                 memcpy(iv, org_iv, cc->iv_size);
1178         }
1179
1180         skcipher_request_set_crypt(req, sg_in, sg_out, data_len, iv);
1181
1182         if (bio_data_dir(ctx->bio_in) == WRITE)
1183                 r = crypto_skcipher_encrypt(req);
1184         else
1185                 r = crypto_skcipher_decrypt(req);
1186
1187         if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1188                 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1189
1190         bio_advance_iter(ctx->bio_in, &ctx->iter_in, data_len);
1191         bio_advance_iter(ctx->bio_out, &ctx->iter_out, data_len);
1192
1193         return r;
1194 }
1195
1196 static void kcryptd_async_done(struct crypto_async_request *async_req,
1197                                int error);
1198
1199 static void crypt_alloc_req_skcipher(struct crypt_config *cc,
1200                                      struct convert_context *ctx)
1201 {
1202         unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
1203
1204         if (!ctx->r.req)
1205                 ctx->r.req = mempool_alloc(cc->req_pool, GFP_NOIO);
1206
1207         skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
1208
1209         /*
1210          * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1211          * requests if driver request queue is full.
1212          */
1213         skcipher_request_set_callback(ctx->r.req,
1214             CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
1215             kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
1216 }
1217
1218 static void crypt_alloc_req_aead(struct crypt_config *cc,
1219                                  struct convert_context *ctx)
1220 {
1221         if (!ctx->r.req_aead)
1222                 ctx->r.req_aead = mempool_alloc(cc->req_pool, GFP_NOIO);
1223
1224         aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
1225
1226         /*
1227          * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1228          * requests if driver request queue is full.
1229          */
1230         aead_request_set_callback(ctx->r.req_aead,
1231             CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
1232             kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
1233 }
1234
1235 static void crypt_alloc_req(struct crypt_config *cc,
1236                             struct convert_context *ctx)
1237 {
1238         if (crypt_integrity_mode(cc))
1239                 crypt_alloc_req_aead(cc, ctx);
1240         else
1241                 crypt_alloc_req_skcipher(cc, ctx);
1242 }
1243
1244 static void crypt_free_req_skcipher(struct crypt_config *cc,
1245                                     struct skcipher_request *req, struct bio *base_bio)
1246 {
1247         struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1248
1249         if ((struct skcipher_request *)(io + 1) != req)
1250                 mempool_free(req, cc->req_pool);
1251 }
1252
1253 static void crypt_free_req_aead(struct crypt_config *cc,
1254                                 struct aead_request *req, struct bio *base_bio)
1255 {
1256         struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1257
1258         if ((struct aead_request *)(io + 1) != req)
1259                 mempool_free(req, cc->req_pool);
1260 }
1261
1262 static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
1263 {
1264         if (crypt_integrity_mode(cc))
1265                 crypt_free_req_aead(cc, req, base_bio);
1266         else
1267                 crypt_free_req_skcipher(cc, req, base_bio);
1268 }
1269
1270 /*
1271  * Encrypt / decrypt data from one bio to another one (can be the same one)
1272  */
1273 static int crypt_convert(struct crypt_config *cc,
1274                          struct convert_context *ctx)
1275 {
1276         unsigned int tag_offset = 0;
1277         int r;
1278
1279         atomic_set(&ctx->cc_pending, 1);
1280
1281         while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
1282
1283                 crypt_alloc_req(cc, ctx);
1284
1285                 atomic_inc(&ctx->cc_pending);
1286
1287                 if (crypt_integrity_mode(cc))
1288                         r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
1289                 else
1290                         r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
1291
1292                 switch (r) {
1293                 /*
1294                  * The request was queued by a crypto driver
1295                  * but the driver request queue is full, let's wait.
1296                  */
1297                 case -EBUSY:
1298                         wait_for_completion(&ctx->restart);
1299                         reinit_completion(&ctx->restart);
1300                         /* fall through */
1301                 /*
1302                  * The request is queued and processed asynchronously,
1303                  * completion function kcryptd_async_done() will be called.
1304                  */
1305                 case -EINPROGRESS:
1306                         ctx->r.req = NULL;
1307                         ctx->cc_sector++;
1308                         tag_offset++;
1309                         continue;
1310                 /*
1311                  * The request was already processed (synchronously).
1312                  */
1313                 case 0:
1314                         atomic_dec(&ctx->cc_pending);
1315                         ctx->cc_sector++;
1316                         tag_offset++;
1317                         cond_resched();
1318                         continue;
1319                 /*
1320                  * There was a data integrity error.
1321                  */
1322                 case -EBADMSG:
1323                         atomic_dec(&ctx->cc_pending);
1324                         return -EILSEQ;
1325                 /*
1326                  * There was an error while processing the request.
1327                  */
1328                 default:
1329                         atomic_dec(&ctx->cc_pending);
1330                         return -EIO;
1331                 }
1332         }
1333
1334         return 0;
1335 }
1336
1337 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
1338
1339 /*
1340  * Generate a new unfragmented bio with the given size
1341  * This should never violate the device limitations (but only because
1342  * max_segment_size is being constrained to PAGE_SIZE).
1343  *
1344  * This function may be called concurrently. If we allocate from the mempool
1345  * concurrently, there is a possibility of deadlock. For example, if we have
1346  * mempool of 256 pages, two processes, each wanting 256, pages allocate from
1347  * the mempool concurrently, it may deadlock in a situation where both processes
1348  * have allocated 128 pages and the mempool is exhausted.
1349  *
1350  * In order to avoid this scenario we allocate the pages under a mutex.
1351  *
1352  * In order to not degrade performance with excessive locking, we try
1353  * non-blocking allocations without a mutex first but on failure we fallback
1354  * to blocking allocations with a mutex.
1355  */
1356 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
1357 {
1358         struct crypt_config *cc = io->cc;
1359         struct bio *clone;
1360         unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1361         gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
1362         unsigned i, len, remaining_size;
1363         struct page *page;
1364
1365 retry:
1366         if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1367                 mutex_lock(&cc->bio_alloc_lock);
1368
1369         clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, cc->bs);
1370         if (!clone)
1371                 goto out;
1372
1373         clone_init(io, clone);
1374
1375         remaining_size = size;
1376
1377         for (i = 0; i < nr_iovecs; i++) {
1378                 page = mempool_alloc(cc->page_pool, gfp_mask);
1379                 if (!page) {
1380                         crypt_free_buffer_pages(cc, clone);
1381                         bio_put(clone);
1382                         gfp_mask |= __GFP_DIRECT_RECLAIM;
1383                         goto retry;
1384                 }
1385
1386                 len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
1387
1388                 bio_add_page(clone, page, len, 0);
1389
1390                 remaining_size -= len;
1391         }
1392
1393         /* Allocate space for integrity tags */
1394         if (dm_crypt_integrity_io_alloc(io, clone)) {
1395                 crypt_free_buffer_pages(cc, clone);
1396                 bio_put(clone);
1397                 clone = NULL;
1398         }
1399 out:
1400         if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1401                 mutex_unlock(&cc->bio_alloc_lock);
1402
1403         return clone;
1404 }
1405
1406 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1407 {
1408         unsigned int i;
1409         struct bio_vec *bv;
1410
1411         bio_for_each_segment_all(bv, clone, i) {
1412                 BUG_ON(!bv->bv_page);
1413                 mempool_free(bv->bv_page, cc->page_pool);
1414                 bv->bv_page = NULL;
1415         }
1416 }
1417
1418 static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1419                           struct bio *bio, sector_t sector)
1420 {
1421         io->cc = cc;
1422         io->base_bio = bio;
1423         io->sector = sector;
1424         io->error = 0;
1425         io->ctx.r.req = NULL;
1426         io->integrity_metadata = NULL;
1427         io->integrity_metadata_from_pool = false;
1428         atomic_set(&io->io_pending, 0);
1429 }
1430
1431 static void crypt_inc_pending(struct dm_crypt_io *io)
1432 {
1433         atomic_inc(&io->io_pending);
1434 }
1435
1436 /*
1437  * One of the bios was finished. Check for completion of
1438  * the whole request and correctly clean up the buffer.
1439  */
1440 static void crypt_dec_pending(struct dm_crypt_io *io)
1441 {
1442         struct crypt_config *cc = io->cc;
1443         struct bio *base_bio = io->base_bio;
1444         int error = io->error;
1445
1446         if (!atomic_dec_and_test(&io->io_pending))
1447                 return;
1448
1449         if (io->ctx.r.req)
1450                 crypt_free_req(cc, io->ctx.r.req, base_bio);
1451
1452         if (unlikely(io->integrity_metadata_from_pool))
1453                 mempool_free(io->integrity_metadata, io->cc->tag_pool);
1454         else
1455                 kfree(io->integrity_metadata);
1456
1457         base_bio->bi_error = error;
1458         bio_endio(base_bio);
1459 }
1460
1461 /*
1462  * kcryptd/kcryptd_io:
1463  *
1464  * Needed because it would be very unwise to do decryption in an
1465  * interrupt context.
1466  *
1467  * kcryptd performs the actual encryption or decryption.
1468  *
1469  * kcryptd_io performs the IO submission.
1470  *
1471  * They must be separated as otherwise the final stages could be
1472  * starved by new requests which can block in the first stages due
1473  * to memory allocation.
1474  *
1475  * The work is done per CPU global for all dm-crypt instances.
1476  * They should not depend on each other and do not block.
1477  */
1478 static void crypt_endio(struct bio *clone)
1479 {
1480         struct dm_crypt_io *io = clone->bi_private;
1481         struct crypt_config *cc = io->cc;
1482         unsigned rw = bio_data_dir(clone);
1483         int error;
1484
1485         /*
1486          * free the processed pages
1487          */
1488         if (rw == WRITE)
1489                 crypt_free_buffer_pages(cc, clone);
1490
1491         error = clone->bi_error;
1492         bio_put(clone);
1493
1494         if (rw == READ && !error) {
1495                 kcryptd_queue_crypt(io);
1496                 return;
1497         }
1498
1499         if (unlikely(error))
1500                 io->error = error;
1501
1502         crypt_dec_pending(io);
1503 }
1504
1505 static void clone_init(struct dm_crypt_io *io, struct bio *clone)
1506 {
1507         struct crypt_config *cc = io->cc;
1508
1509         clone->bi_private = io;
1510         clone->bi_end_io  = crypt_endio;
1511         clone->bi_bdev    = cc->dev->bdev;
1512         clone->bi_opf     = io->base_bio->bi_opf;
1513 }
1514
1515 static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
1516 {
1517         struct crypt_config *cc = io->cc;
1518         struct bio *clone;
1519
1520         /*
1521          * We need the original biovec array in order to decrypt
1522          * the whole bio data *afterwards* -- thanks to immutable
1523          * biovecs we don't need to worry about the block layer
1524          * modifying the biovec array; so leverage bio_clone_fast().
1525          */
1526         clone = bio_clone_fast(io->base_bio, gfp, cc->bs);
1527         if (!clone)
1528                 return 1;
1529
1530         crypt_inc_pending(io);
1531
1532         clone_init(io, clone);
1533         clone->bi_iter.bi_sector = cc->start + io->sector;
1534
1535         if (dm_crypt_integrity_io_alloc(io, clone)) {
1536                 crypt_dec_pending(io);
1537                 bio_put(clone);
1538                 return 1;
1539         }
1540
1541         generic_make_request(clone);
1542         return 0;
1543 }
1544
1545 static void kcryptd_io_read_work(struct work_struct *work)
1546 {
1547         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1548
1549         crypt_inc_pending(io);
1550         if (kcryptd_io_read(io, GFP_NOIO))
1551                 io->error = -ENOMEM;
1552         crypt_dec_pending(io);
1553 }
1554
1555 static void kcryptd_queue_read(struct dm_crypt_io *io)
1556 {
1557         struct crypt_config *cc = io->cc;
1558
1559         INIT_WORK(&io->work, kcryptd_io_read_work);
1560         queue_work(cc->io_queue, &io->work);
1561 }
1562
1563 static void kcryptd_io_write(struct dm_crypt_io *io)
1564 {
1565         struct bio *clone = io->ctx.bio_out;
1566
1567         generic_make_request(clone);
1568 }
1569
1570 #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1571
1572 static int dmcrypt_write(void *data)
1573 {
1574         struct crypt_config *cc = data;
1575         struct dm_crypt_io *io;
1576
1577         while (1) {
1578                 struct rb_root write_tree;
1579                 struct blk_plug plug;
1580
1581                 DECLARE_WAITQUEUE(wait, current);
1582
1583                 spin_lock_irq(&cc->write_thread_wait.lock);
1584 continue_locked:
1585
1586                 if (!RB_EMPTY_ROOT(&cc->write_tree))
1587                         goto pop_from_list;
1588
1589                 set_current_state(TASK_INTERRUPTIBLE);
1590                 __add_wait_queue(&cc->write_thread_wait, &wait);
1591
1592                 spin_unlock_irq(&cc->write_thread_wait.lock);
1593
1594                 if (unlikely(kthread_should_stop())) {
1595                         set_current_state(TASK_RUNNING);
1596                         remove_wait_queue(&cc->write_thread_wait, &wait);
1597                         break;
1598                 }
1599
1600                 schedule();
1601
1602                 set_current_state(TASK_RUNNING);
1603                 spin_lock_irq(&cc->write_thread_wait.lock);
1604                 __remove_wait_queue(&cc->write_thread_wait, &wait);
1605                 goto continue_locked;
1606
1607 pop_from_list:
1608                 write_tree = cc->write_tree;
1609                 cc->write_tree = RB_ROOT;
1610                 spin_unlock_irq(&cc->write_thread_wait.lock);
1611
1612                 BUG_ON(rb_parent(write_tree.rb_node));
1613
1614                 /*
1615                  * Note: we cannot walk the tree here with rb_next because
1616                  * the structures may be freed when kcryptd_io_write is called.
1617                  */
1618                 blk_start_plug(&plug);
1619                 do {
1620                         io = crypt_io_from_node(rb_first(&write_tree));
1621                         rb_erase(&io->rb_node, &write_tree);
1622                         kcryptd_io_write(io);
1623                 } while (!RB_EMPTY_ROOT(&write_tree));
1624                 blk_finish_plug(&plug);
1625         }
1626         return 0;
1627 }
1628
1629 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
1630 {
1631         struct bio *clone = io->ctx.bio_out;
1632         struct crypt_config *cc = io->cc;
1633         unsigned long flags;
1634         sector_t sector;
1635         struct rb_node **rbp, *parent;
1636
1637         if (unlikely(io->error < 0)) {
1638                 crypt_free_buffer_pages(cc, clone);
1639                 bio_put(clone);
1640                 crypt_dec_pending(io);
1641                 return;
1642         }
1643
1644         /* crypt_convert should have filled the clone bio */
1645         BUG_ON(io->ctx.iter_out.bi_size);
1646
1647         clone->bi_iter.bi_sector = cc->start + io->sector;
1648
1649         if (likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) {
1650                 generic_make_request(clone);
1651                 return;
1652         }
1653
1654         spin_lock_irqsave(&cc->write_thread_wait.lock, flags);
1655         rbp = &cc->write_tree.rb_node;
1656         parent = NULL;
1657         sector = io->sector;
1658         while (*rbp) {
1659                 parent = *rbp;
1660                 if (sector < crypt_io_from_node(parent)->sector)
1661                         rbp = &(*rbp)->rb_left;
1662                 else
1663                         rbp = &(*rbp)->rb_right;
1664         }
1665         rb_link_node(&io->rb_node, parent, rbp);
1666         rb_insert_color(&io->rb_node, &cc->write_tree);
1667
1668         wake_up_locked(&cc->write_thread_wait);
1669         spin_unlock_irqrestore(&cc->write_thread_wait.lock, flags);
1670 }
1671
1672 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
1673 {
1674         struct crypt_config *cc = io->cc;
1675         struct bio *clone;
1676         int crypt_finished;
1677         sector_t sector = io->sector;
1678         int r;
1679
1680         /*
1681          * Prevent io from disappearing until this function completes.
1682          */
1683         crypt_inc_pending(io);
1684         crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
1685
1686         clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
1687         if (unlikely(!clone)) {
1688                 io->error = -EIO;
1689                 goto dec;
1690         }
1691
1692         io->ctx.bio_out = clone;
1693         io->ctx.iter_out = clone->bi_iter;
1694
1695         sector += bio_sectors(clone);
1696
1697         crypt_inc_pending(io);
1698         r = crypt_convert(cc, &io->ctx);
1699         if (r < 0)
1700                 io->error = r;
1701         crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
1702
1703         /* Encryption was already finished, submit io now */
1704         if (crypt_finished) {
1705                 kcryptd_crypt_write_io_submit(io, 0);
1706                 io->sector = sector;
1707         }
1708
1709 dec:
1710         crypt_dec_pending(io);
1711 }
1712
1713 static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
1714 {
1715         crypt_dec_pending(io);
1716 }
1717
1718 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
1719 {
1720         struct crypt_config *cc = io->cc;
1721         int r = 0;
1722
1723         crypt_inc_pending(io);
1724
1725         crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
1726                            io->sector);
1727
1728         r = crypt_convert(cc, &io->ctx);
1729         if (r < 0)
1730                 io->error = r;
1731
1732         if (atomic_dec_and_test(&io->ctx.cc_pending))
1733                 kcryptd_crypt_read_done(io);
1734
1735         crypt_dec_pending(io);
1736 }
1737
1738 static void kcryptd_async_done(struct crypto_async_request *async_req,
1739                                int error)
1740 {
1741         struct dm_crypt_request *dmreq = async_req->data;
1742         struct convert_context *ctx = dmreq->ctx;
1743         struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1744         struct crypt_config *cc = io->cc;
1745
1746         /*
1747          * A request from crypto driver backlog is going to be processed now,
1748          * finish the completion and continue in crypt_convert().
1749          * (Callback will be called for the second time for this request.)
1750          */
1751         if (error == -EINPROGRESS) {
1752                 complete(&ctx->restart);
1753                 return;
1754         }
1755
1756         if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
1757                 error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
1758
1759         if (error == -EBADMSG) {
1760                 DMERR_LIMIT("INTEGRITY AEAD ERROR, sector %llu",
1761                             (unsigned long long)le64_to_cpu(*org_sector_of_dmreq(cc, dmreq)));
1762                 io->error = -EILSEQ;
1763         } else if (error < 0)
1764                 io->error = -EIO;
1765
1766         crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
1767
1768         if (!atomic_dec_and_test(&ctx->cc_pending))
1769                 return;
1770
1771         if (bio_data_dir(io->base_bio) == READ)
1772                 kcryptd_crypt_read_done(io);
1773         else
1774                 kcryptd_crypt_write_io_submit(io, 1);
1775 }
1776
1777 static void kcryptd_crypt(struct work_struct *work)
1778 {
1779         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1780
1781         if (bio_data_dir(io->base_bio) == READ)
1782                 kcryptd_crypt_read_convert(io);
1783         else
1784                 kcryptd_crypt_write_convert(io);
1785 }
1786
1787 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
1788 {
1789         struct crypt_config *cc = io->cc;
1790
1791         INIT_WORK(&io->work, kcryptd_crypt);
1792         queue_work(cc->crypt_queue, &io->work);
1793 }
1794
1795 /*
1796  * Decode key from its hex representation
1797  */
1798 static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
1799 {
1800         char buffer[3];
1801         unsigned int i;
1802
1803         buffer[2] = '\0';
1804
1805         for (i = 0; i < size; i++) {
1806                 buffer[0] = *hex++;
1807                 buffer[1] = *hex++;
1808
1809                 if (kstrtou8(buffer, 16, &key[i]))
1810                         return -EINVAL;
1811         }
1812
1813         if (*hex != '\0')
1814                 return -EINVAL;
1815
1816         return 0;
1817 }
1818
1819 static void crypt_free_tfms_aead(struct crypt_config *cc)
1820 {
1821         if (!cc->cipher_tfm.tfms_aead)
1822                 return;
1823
1824         if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
1825                 crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
1826                 cc->cipher_tfm.tfms_aead[0] = NULL;
1827         }
1828
1829         kfree(cc->cipher_tfm.tfms_aead);
1830         cc->cipher_tfm.tfms_aead = NULL;
1831 }
1832
1833 static void crypt_free_tfms_skcipher(struct crypt_config *cc)
1834 {
1835         unsigned i;
1836
1837         if (!cc->cipher_tfm.tfms)
1838                 return;
1839
1840         for (i = 0; i < cc->tfms_count; i++)
1841                 if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
1842                         crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
1843                         cc->cipher_tfm.tfms[i] = NULL;
1844                 }
1845
1846         kfree(cc->cipher_tfm.tfms);
1847         cc->cipher_tfm.tfms = NULL;
1848 }
1849
1850 static void crypt_free_tfms(struct crypt_config *cc)
1851 {
1852         if (crypt_integrity_mode(cc))
1853                 crypt_free_tfms_aead(cc);
1854         else
1855                 crypt_free_tfms_skcipher(cc);
1856 }
1857
1858 static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
1859 {
1860         unsigned i;
1861         int err;
1862
1863         cc->cipher_tfm.tfms = kzalloc(cc->tfms_count *
1864                                       sizeof(struct crypto_skcipher *), GFP_KERNEL);
1865         if (!cc->cipher_tfm.tfms)
1866                 return -ENOMEM;
1867
1868         for (i = 0; i < cc->tfms_count; i++) {
1869                 cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0, 0);
1870                 if (IS_ERR(cc->cipher_tfm.tfms[i])) {
1871                         err = PTR_ERR(cc->cipher_tfm.tfms[i]);
1872                         crypt_free_tfms(cc);
1873                         return err;
1874                 }
1875         }
1876
1877         return 0;
1878 }
1879
1880 static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
1881 {
1882         char *authenc = NULL;
1883         int err;
1884
1885         cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
1886         if (!cc->cipher_tfm.tfms)
1887                 return -ENOMEM;
1888
1889         /* Compose AEAD cipher with autenc(authenticator,cipher) structure */
1890         if (crypt_integrity_hmac(cc)) {
1891                 authenc = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
1892                 if (!authenc)
1893                         return -ENOMEM;
1894                 err = snprintf(authenc, CRYPTO_MAX_ALG_NAME,
1895                        "authenc(%s,%s)", cc->cipher_auth, ciphermode);
1896                 if (err < 0) {
1897                         kzfree(authenc);
1898                         return err;
1899                 }
1900                 ciphermode = authenc;
1901         }
1902
1903         cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0, 0);
1904         if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
1905                 err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
1906                 crypt_free_tfms(cc);
1907                 return err;
1908         }
1909
1910         kzfree(authenc);
1911         return 0;
1912 }
1913
1914 static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
1915 {
1916         if (crypt_integrity_mode(cc))
1917                 return crypt_alloc_tfms_aead(cc, ciphermode);
1918         else
1919                 return crypt_alloc_tfms_skcipher(cc, ciphermode);
1920 }
1921
1922 static unsigned crypt_subkey_size(struct crypt_config *cc)
1923 {
1924         return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
1925 }
1926
1927 static unsigned crypt_authenckey_size(struct crypt_config *cc)
1928 {
1929         return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
1930 }
1931
1932 /*
1933  * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
1934  * the key must be for some reason in special format.
1935  * This funcion converts cc->key to this special format.
1936  */
1937 static void crypt_copy_authenckey(char *p, const void *key,
1938                                   unsigned enckeylen, unsigned authkeylen)
1939 {
1940         struct crypto_authenc_key_param *param;
1941         struct rtattr *rta;
1942
1943         rta = (struct rtattr *)p;
1944         param = RTA_DATA(rta);
1945         param->enckeylen = cpu_to_be32(enckeylen);
1946         rta->rta_len = RTA_LENGTH(sizeof(*param));
1947         rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
1948         p += RTA_SPACE(sizeof(*param));
1949         memcpy(p, key + enckeylen, authkeylen);
1950         p += authkeylen;
1951         memcpy(p, key, enckeylen);
1952 }
1953
1954 static int crypt_setkey(struct crypt_config *cc)
1955 {
1956         unsigned subkey_size;
1957         int err = 0, i, r;
1958
1959         /* Ignore extra keys (which are used for IV etc) */
1960         subkey_size = crypt_subkey_size(cc);
1961
1962         if (crypt_integrity_hmac(cc))
1963                 crypt_copy_authenckey(cc->authenc_key, cc->key,
1964                                       subkey_size - cc->key_mac_size,
1965                                       cc->key_mac_size);
1966         for (i = 0; i < cc->tfms_count; i++) {
1967                 if (crypt_integrity_aead(cc))
1968                         r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
1969                                                    cc->key + (i * subkey_size),
1970                                                    subkey_size);
1971                 else if (crypt_integrity_hmac(cc))
1972                         r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
1973                                 cc->authenc_key, crypt_authenckey_size(cc));
1974                 else
1975                         r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
1976                                                    cc->key + (i * subkey_size),
1977                                                    subkey_size);
1978                 if (r)
1979                         err = r;
1980         }
1981
1982         if (crypt_integrity_hmac(cc))
1983                 memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
1984
1985         return err;
1986 }
1987
1988 #ifdef CONFIG_KEYS
1989
1990 static bool contains_whitespace(const char *str)
1991 {
1992         while (*str)
1993                 if (isspace(*str++))
1994                         return true;
1995         return false;
1996 }
1997
1998 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
1999 {
2000         char *new_key_string, *key_desc;
2001         int ret;
2002         struct key *key;
2003         const struct user_key_payload *ukp;
2004
2005         /*
2006          * Reject key_string with whitespace. dm core currently lacks code for
2007          * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2008          */
2009         if (contains_whitespace(key_string)) {
2010                 DMERR("whitespace chars not allowed in key string");
2011                 return -EINVAL;
2012         }
2013
2014         /* look for next ':' separating key_type from key_description */
2015         key_desc = strpbrk(key_string, ":");
2016         if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2017                 return -EINVAL;
2018
2019         if (strncmp(key_string, "logon:", key_desc - key_string + 1) &&
2020             strncmp(key_string, "user:", key_desc - key_string + 1))
2021                 return -EINVAL;
2022
2023         new_key_string = kstrdup(key_string, GFP_KERNEL);
2024         if (!new_key_string)
2025                 return -ENOMEM;
2026
2027         key = request_key(key_string[0] == 'l' ? &key_type_logon : &key_type_user,
2028                           key_desc + 1, NULL);
2029         if (IS_ERR(key)) {
2030                 kzfree(new_key_string);
2031                 return PTR_ERR(key);
2032         }
2033
2034         down_read(&key->sem);
2035
2036         ukp = user_key_payload_locked(key);
2037         if (!ukp) {
2038                 up_read(&key->sem);
2039                 key_put(key);
2040                 kzfree(new_key_string);
2041                 return -EKEYREVOKED;
2042         }
2043
2044         if (cc->key_size != ukp->datalen) {
2045                 up_read(&key->sem);
2046                 key_put(key);
2047                 kzfree(new_key_string);
2048                 return -EINVAL;
2049         }
2050
2051         memcpy(cc->key, ukp->data, cc->key_size);
2052
2053         up_read(&key->sem);
2054         key_put(key);
2055
2056         /* clear the flag since following operations may invalidate previously valid key */
2057         clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2058
2059         ret = crypt_setkey(cc);
2060
2061         /* wipe the kernel key payload copy in each case */
2062         memset(cc->key, 0, cc->key_size * sizeof(u8));
2063
2064         if (!ret) {
2065                 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2066                 kzfree(cc->key_string);
2067                 cc->key_string = new_key_string;
2068         } else
2069                 kzfree(new_key_string);
2070
2071         return ret;
2072 }
2073
2074 static int get_key_size(char **key_string)
2075 {
2076         char *colon, dummy;
2077         int ret;
2078
2079         if (*key_string[0] != ':')
2080                 return strlen(*key_string) >> 1;
2081
2082         /* look for next ':' in key string */
2083         colon = strpbrk(*key_string + 1, ":");
2084         if (!colon)
2085                 return -EINVAL;
2086
2087         if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2088                 return -EINVAL;
2089
2090         *key_string = colon;
2091
2092         /* remaining key string should be :<logon|user>:<key_desc> */
2093
2094         return ret;
2095 }
2096
2097 #else
2098
2099 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2100 {
2101         return -EINVAL;
2102 }
2103
2104 static int get_key_size(char **key_string)
2105 {
2106         return (*key_string[0] == ':') ? -EINVAL : strlen(*key_string) >> 1;
2107 }
2108
2109 #endif
2110
2111 static int crypt_set_key(struct crypt_config *cc, char *key)
2112 {
2113         int r = -EINVAL;
2114         int key_string_len = strlen(key);
2115
2116         /* Hyphen (which gives a key_size of zero) means there is no key. */
2117         if (!cc->key_size && strcmp(key, "-"))
2118                 goto out;
2119
2120         /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2121         if (key[0] == ':') {
2122                 r = crypt_set_keyring_key(cc, key + 1);
2123                 goto out;
2124         }
2125
2126         /* clear the flag since following operations may invalidate previously valid key */
2127         clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2128
2129         /* wipe references to any kernel keyring key */
2130         kzfree(cc->key_string);
2131         cc->key_string = NULL;
2132
2133         if (cc->key_size && crypt_decode_key(cc->key, key, cc->key_size) < 0)
2134                 goto out;
2135
2136         r = crypt_setkey(cc);
2137         if (!r)
2138                 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2139
2140 out:
2141         /* Hex key string not needed after here, so wipe it. */
2142         memset(key, '0', key_string_len);
2143
2144         return r;
2145 }
2146
2147 static int crypt_wipe_key(struct crypt_config *cc)
2148 {
2149         clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2150         memset(&cc->key, 0, cc->key_size * sizeof(u8));
2151         kzfree(cc->key_string);
2152         cc->key_string = NULL;
2153
2154         return crypt_setkey(cc);
2155 }
2156
2157 static void crypt_dtr(struct dm_target *ti)
2158 {
2159         struct crypt_config *cc = ti->private;
2160
2161         ti->private = NULL;
2162
2163         if (!cc)
2164                 return;
2165
2166         if (cc->write_thread)
2167                 kthread_stop(cc->write_thread);
2168
2169         if (cc->io_queue)
2170                 destroy_workqueue(cc->io_queue);
2171         if (cc->crypt_queue)
2172                 destroy_workqueue(cc->crypt_queue);
2173
2174         crypt_free_tfms(cc);
2175
2176         if (cc->bs)
2177                 bioset_free(cc->bs);
2178
2179         mempool_destroy(cc->page_pool);
2180         mempool_destroy(cc->req_pool);
2181         mempool_destroy(cc->tag_pool);
2182
2183         if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
2184                 cc->iv_gen_ops->dtr(cc);
2185
2186         if (cc->dev)
2187                 dm_put_device(ti, cc->dev);
2188
2189         kzfree(cc->cipher);
2190         kzfree(cc->cipher_string);
2191         kzfree(cc->key_string);
2192         kzfree(cc->cipher_auth);
2193         kzfree(cc->authenc_key);
2194
2195         /* Must zero key material before freeing */
2196         kzfree(cc);
2197 }
2198
2199 static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
2200 {
2201         struct crypt_config *cc = ti->private;
2202
2203         if (crypt_integrity_mode(cc))
2204                 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2205         else
2206                 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2207
2208         if (crypt_integrity_hmac(cc)) {
2209                 cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
2210                 if (!cc->authenc_key) {
2211                         ti->error = "Error allocating authenc key space";
2212                         return -ENOMEM;
2213                 }
2214         }
2215
2216         if (cc->iv_size)
2217                 /* at least a 64 bit sector number should fit in our buffer */
2218                 cc->iv_size = max(cc->iv_size,
2219                                   (unsigned int)(sizeof(u64) / sizeof(u8)));
2220         else if (ivmode) {
2221                 DMWARN("Selected cipher does not support IVs");
2222                 ivmode = NULL;
2223         }
2224
2225         /* Choose ivmode, see comments at iv code. */
2226         if (ivmode == NULL)
2227                 cc->iv_gen_ops = NULL;
2228         else if (strcmp(ivmode, "plain") == 0)
2229                 cc->iv_gen_ops = &crypt_iv_plain_ops;
2230         else if (strcmp(ivmode, "plain64") == 0)
2231                 cc->iv_gen_ops = &crypt_iv_plain64_ops;
2232         else if (strcmp(ivmode, "essiv") == 0)
2233                 cc->iv_gen_ops = &crypt_iv_essiv_ops;
2234         else if (strcmp(ivmode, "benbi") == 0)
2235                 cc->iv_gen_ops = &crypt_iv_benbi_ops;
2236         else if (strcmp(ivmode, "null") == 0)
2237                 cc->iv_gen_ops = &crypt_iv_null_ops;
2238         else if (strcmp(ivmode, "lmk") == 0) {
2239                 cc->iv_gen_ops = &crypt_iv_lmk_ops;
2240                 /*
2241                  * Version 2 and 3 is recognised according
2242                  * to length of provided multi-key string.
2243                  * If present (version 3), last key is used as IV seed.
2244                  * All keys (including IV seed) are always the same size.
2245                  */
2246                 if (cc->key_size % cc->key_parts) {
2247                         cc->key_parts++;
2248                         cc->key_extra_size = cc->key_size / cc->key_parts;
2249                 }
2250         } else if (strcmp(ivmode, "tcw") == 0) {
2251                 cc->iv_gen_ops = &crypt_iv_tcw_ops;
2252                 cc->key_parts += 2; /* IV + whitening */
2253                 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2254         } else if (strcmp(ivmode, "random") == 0) {
2255                 cc->iv_gen_ops = &crypt_iv_random_ops;
2256                 /* Need storage space in integrity fields. */
2257                 cc->integrity_iv_size = cc->iv_size;
2258         } else {
2259                 ti->error = "Invalid IV mode";
2260                 return -EINVAL;
2261         }
2262
2263         return 0;
2264 }
2265
2266 static int crypt_ctr_cipher(struct dm_target *ti,
2267                             char *cipher_in, char *key)
2268 {
2269         struct crypt_config *cc = ti->private;
2270         char *tmp, *cipher, *chainmode, *ivmode, *ivopts, *keycount;
2271         char *cipher_api = NULL;
2272         int ret = -EINVAL;
2273         char dummy;
2274
2275         if (strchr(cipher_in, '(')) {
2276                 ti->error = "Bad cipher specification";
2277                 return -EINVAL;
2278         }
2279
2280         cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
2281         if (!cc->cipher_string)
2282                 goto bad_mem;
2283
2284         /*
2285          * Legacy dm-crypt cipher specification
2286          * cipher[:keycount]-mode-iv:ivopts
2287          */
2288         tmp = cipher_in;
2289         keycount = strsep(&tmp, "-");
2290         cipher = strsep(&keycount, ":");
2291
2292         if (!keycount)
2293                 cc->tfms_count = 1;
2294         else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
2295                  !is_power_of_2(cc->tfms_count)) {
2296                 ti->error = "Bad cipher key count specification";
2297                 return -EINVAL;
2298         }
2299         cc->key_parts = cc->tfms_count;
2300
2301         cc->cipher = kstrdup(cipher, GFP_KERNEL);
2302         if (!cc->cipher)
2303                 goto bad_mem;
2304
2305         chainmode = strsep(&tmp, "-");
2306         ivopts = strsep(&tmp, "-");
2307         ivmode = strsep(&ivopts, ":");
2308
2309         if (tmp)
2310                 DMWARN("Ignoring unexpected additional cipher options");
2311
2312         /*
2313          * For compatibility with the original dm-crypt mapping format, if
2314          * only the cipher name is supplied, use cbc-plain.
2315          */
2316         if (!chainmode || (!strcmp(chainmode, "plain") && !ivmode)) {
2317                 chainmode = "cbc";
2318                 ivmode = "plain";
2319         }
2320
2321         if (strcmp(chainmode, "ecb") && !ivmode) {
2322                 ti->error = "IV mechanism required";
2323                 return -EINVAL;
2324         }
2325
2326         cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
2327         if (!cipher_api)
2328                 goto bad_mem;
2329
2330         ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2331                        "%s(%s)", chainmode, cipher);
2332         if (ret < 0) {
2333                 kfree(cipher_api);
2334                 goto bad_mem;
2335         }
2336
2337         /* Allocate cipher */
2338         ret = crypt_alloc_tfms(cc, cipher_api);
2339         if (ret < 0) {
2340                 ti->error = "Error allocating crypto tfm";
2341                 goto bad;
2342         }
2343
2344         /* Initialize IV */
2345         ret = crypt_ctr_ivmode(ti, ivmode);
2346         if (ret < 0)
2347                 goto bad;
2348
2349         /* Initialize and set key */
2350         ret = crypt_set_key(cc, key);
2351         if (ret < 0) {
2352                 ti->error = "Error decoding and setting key";
2353                 goto bad;
2354         }
2355
2356         /* Allocate IV */
2357         if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
2358                 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
2359                 if (ret < 0) {
2360                         ti->error = "Error creating IV";
2361                         goto bad;
2362                 }
2363         }
2364
2365         /* Initialize IV (set keys for ESSIV etc) */
2366         if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
2367                 ret = cc->iv_gen_ops->init(cc);
2368                 if (ret < 0) {
2369                         ti->error = "Error initialising IV";
2370                         goto bad;
2371                 }
2372         }
2373
2374         ret = 0;
2375 bad:
2376         kfree(cipher_api);
2377         return ret;
2378
2379 bad_mem:
2380         ti->error = "Cannot allocate cipher strings";
2381         return -ENOMEM;
2382 }
2383
2384 static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
2385 {
2386         struct crypt_config *cc = ti->private;
2387         struct dm_arg_set as;
2388         static struct dm_arg _args[] = {
2389                 {0, 3, "Invalid number of feature args"},
2390         };
2391         unsigned int opt_params, val;
2392         const char *opt_string, *sval;
2393         int ret;
2394
2395         /* Optional parameters */
2396         as.argc = argc;
2397         as.argv = argv;
2398
2399         ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
2400         if (ret)
2401                 return ret;
2402
2403         while (opt_params--) {
2404                 opt_string = dm_shift_arg(&as);
2405                 if (!opt_string) {
2406                         ti->error = "Not enough feature arguments";
2407                         return -EINVAL;
2408                 }
2409
2410                 if (!strcasecmp(opt_string, "allow_discards"))
2411                         ti->num_discard_bios = 1;
2412
2413                 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
2414                         set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
2415
2416                 else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
2417                         set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
2418                 else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
2419                         if (val == 0 || val > MAX_TAG_SIZE) {
2420                                 ti->error = "Invalid integrity arguments";
2421                                 return -EINVAL;
2422                         }
2423                         cc->on_disk_tag_size = val;
2424                         sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
2425                         if (!strcasecmp(sval, "aead")) {
2426                                 set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
2427                         } else  if (!strncasecmp(sval, "hmac(", strlen("hmac("))) {
2428                                 struct crypto_ahash *hmac_tfm = crypto_alloc_ahash(sval, 0, 0);
2429                                 if (IS_ERR(hmac_tfm)) {
2430                                         ti->error = "Error initializing HMAC integrity hash.";
2431                                         return PTR_ERR(hmac_tfm);
2432                                 }
2433                                 cc->key_mac_size = crypto_ahash_digestsize(hmac_tfm);
2434                                 crypto_free_ahash(hmac_tfm);
2435                                 set_bit(CRYPT_MODE_INTEGRITY_HMAC, &cc->cipher_flags);
2436                         } else  if (strcasecmp(sval, "none")) {
2437                                 ti->error = "Unknown integrity profile";
2438                                 return -EINVAL;
2439                         }
2440
2441                         cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
2442                         if (!cc->cipher_auth)
2443                                 return -ENOMEM;
2444                 }  else {
2445                         ti->error = "Invalid feature arguments";
2446                         return -EINVAL;
2447                 }
2448         }
2449
2450         return 0;
2451 }
2452
2453 /*
2454  * Construct an encryption mapping:
2455  * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
2456  */
2457 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
2458 {
2459         struct crypt_config *cc;
2460         int key_size;
2461         unsigned int align_mask;
2462         unsigned long long tmpll;
2463         int ret;
2464         size_t iv_size_padding, additional_req_size;
2465         char dummy;
2466
2467         if (argc < 5) {
2468                 ti->error = "Not enough arguments";
2469                 return -EINVAL;
2470         }
2471
2472         key_size = get_key_size(&argv[1]);
2473         if (key_size < 0) {
2474                 ti->error = "Cannot parse key size";
2475                 return -EINVAL;
2476         }
2477
2478         cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
2479         if (!cc) {
2480                 ti->error = "Cannot allocate encryption context";
2481                 return -ENOMEM;
2482         }
2483         cc->key_size = key_size;
2484
2485         ti->private = cc;
2486
2487         /* Optional parameters need to be read before cipher constructor */
2488         if (argc > 5) {
2489                 ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
2490                 if (ret)
2491                         goto bad;
2492         }
2493
2494         ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
2495         if (ret < 0)
2496                 goto bad;
2497
2498         if (crypt_integrity_mode(cc)) {
2499                 cc->dmreq_start = sizeof(struct aead_request);
2500                 cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
2501                 align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
2502         } else {
2503                 cc->dmreq_start = sizeof(struct skcipher_request);
2504                 cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
2505                 align_mask = crypto_skcipher_alignmask(any_tfm(cc));
2506         }
2507         cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
2508
2509         if (align_mask < CRYPTO_MINALIGN) {
2510                 /* Allocate the padding exactly */
2511                 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
2512                                 & align_mask;
2513         } else {
2514                 /*
2515                  * If the cipher requires greater alignment than kmalloc
2516                  * alignment, we don't know the exact position of the
2517                  * initialization vector. We must assume worst case.
2518                  */
2519                 iv_size_padding = align_mask;
2520         }
2521
2522         ret = -ENOMEM;
2523
2524         /*  ...| IV + padding | original IV | original sec. number | bio tag offset | */
2525         additional_req_size = sizeof(struct dm_crypt_request) +
2526                 iv_size_padding + cc->iv_size +
2527                 cc->iv_size +
2528                 sizeof(uint64_t) +
2529                 sizeof(unsigned int);
2530
2531         cc->req_pool = mempool_create_kmalloc_pool(MIN_IOS, cc->dmreq_start + additional_req_size);
2532         if (!cc->req_pool) {
2533                 ti->error = "Cannot allocate crypt request mempool";
2534                 goto bad;
2535         }
2536
2537         cc->per_bio_data_size = ti->per_io_data_size =
2538                 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
2539                       ARCH_KMALLOC_MINALIGN);
2540
2541         cc->page_pool = mempool_create_page_pool(BIO_MAX_PAGES, 0);
2542         if (!cc->page_pool) {
2543                 ti->error = "Cannot allocate page mempool";
2544                 goto bad;
2545         }
2546
2547         cc->bs = bioset_create(MIN_IOS, 0);
2548         if (!cc->bs) {
2549                 ti->error = "Cannot allocate crypt bioset";
2550                 goto bad;
2551         }
2552
2553         mutex_init(&cc->bio_alloc_lock);
2554
2555         ret = -EINVAL;
2556         if (sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) {
2557                 ti->error = "Invalid iv_offset sector";
2558                 goto bad;
2559         }
2560         cc->iv_offset = tmpll;
2561
2562         ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
2563         if (ret) {
2564                 ti->error = "Device lookup failed";
2565                 goto bad;
2566         }
2567
2568         ret = -EINVAL;
2569         if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1) {
2570                 ti->error = "Invalid device sector";
2571                 goto bad;
2572         }
2573         cc->start = tmpll;
2574
2575         if (crypt_integrity_mode(cc) || cc->integrity_iv_size) {
2576                 ret = crypt_integrity_ctr(cc, ti);
2577                 if (ret)
2578                         goto bad;
2579
2580                 cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
2581                 if (!cc->tag_pool_max_sectors)
2582                         cc->tag_pool_max_sectors = 1;
2583
2584                 cc->tag_pool = mempool_create_kmalloc_pool(MIN_IOS,
2585                         cc->tag_pool_max_sectors * cc->on_disk_tag_size);
2586                 if (!cc->tag_pool) {
2587                         ti->error = "Cannot allocate integrity tags mempool";
2588                         goto bad;
2589                 }
2590         }
2591
2592         ret = -ENOMEM;
2593         cc->io_queue = alloc_workqueue("kcryptd_io", WQ_MEM_RECLAIM, 1);
2594         if (!cc->io_queue) {
2595                 ti->error = "Couldn't create kcryptd io queue";
2596                 goto bad;
2597         }
2598
2599         if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
2600                 cc->crypt_queue = alloc_workqueue("kcryptd", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM, 1);
2601         else
2602                 cc->crypt_queue = alloc_workqueue("kcryptd", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
2603                                                   num_online_cpus());
2604         if (!cc->crypt_queue) {
2605                 ti->error = "Couldn't create kcryptd queue";
2606                 goto bad;
2607         }
2608
2609         init_waitqueue_head(&cc->write_thread_wait);
2610         cc->write_tree = RB_ROOT;
2611
2612         cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write");
2613         if (IS_ERR(cc->write_thread)) {
2614                 ret = PTR_ERR(cc->write_thread);
2615                 cc->write_thread = NULL;
2616                 ti->error = "Couldn't spawn write thread";
2617                 goto bad;
2618         }
2619         wake_up_process(cc->write_thread);
2620
2621         ti->num_flush_bios = 1;
2622         ti->discard_zeroes_data_unsupported = true;
2623
2624         return 0;
2625
2626 bad:
2627         crypt_dtr(ti);
2628         return ret;
2629 }
2630
2631 static int crypt_map(struct dm_target *ti, struct bio *bio)
2632 {
2633         struct dm_crypt_io *io;
2634         struct crypt_config *cc = ti->private;
2635
2636         /*
2637          * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
2638          * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
2639          * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
2640          */
2641         if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
2642             bio_op(bio) == REQ_OP_DISCARD)) {
2643                 bio->bi_bdev = cc->dev->bdev;
2644                 if (bio_sectors(bio))
2645                         bio->bi_iter.bi_sector = cc->start +
2646                                 dm_target_offset(ti, bio->bi_iter.bi_sector);
2647                 return DM_MAPIO_REMAPPED;
2648         }
2649
2650         /*
2651          * Check if bio is too large, split as needed.
2652          */
2653         if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_PAGES << PAGE_SHIFT)) &&
2654             (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
2655                 dm_accept_partial_bio(bio, ((BIO_MAX_PAGES << PAGE_SHIFT) >> SECTOR_SHIFT));
2656
2657         io = dm_per_bio_data(bio, cc->per_bio_data_size);
2658         crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
2659
2660         if (cc->on_disk_tag_size) {
2661                 unsigned tag_len = cc->on_disk_tag_size * bio_sectors(bio);
2662
2663                 if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
2664                     unlikely(!(io->integrity_metadata = kmalloc(tag_len,
2665                                 GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
2666                         if (bio_sectors(bio) > cc->tag_pool_max_sectors)
2667                                 dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
2668                         io->integrity_metadata = mempool_alloc(cc->tag_pool, GFP_NOIO);
2669                         io->integrity_metadata_from_pool = true;
2670                 }
2671         }
2672
2673         if (crypt_integrity_mode(cc))
2674                 io->ctx.r.req_aead = (struct aead_request *)(io + 1);
2675         else
2676                 io->ctx.r.req = (struct skcipher_request *)(io + 1);
2677
2678         if (bio_data_dir(io->base_bio) == READ) {
2679                 if (kcryptd_io_read(io, GFP_NOWAIT))
2680                         kcryptd_queue_read(io);
2681         } else
2682                 kcryptd_queue_crypt(io);
2683
2684         return DM_MAPIO_SUBMITTED;
2685 }
2686
2687 static void crypt_status(struct dm_target *ti, status_type_t type,
2688                          unsigned status_flags, char *result, unsigned maxlen)
2689 {
2690         struct crypt_config *cc = ti->private;
2691         unsigned i, sz = 0;
2692         int num_feature_args = 0;
2693
2694         switch (type) {
2695         case STATUSTYPE_INFO:
2696                 result[0] = '\0';
2697                 break;
2698
2699         case STATUSTYPE_TABLE:
2700                 DMEMIT("%s ", cc->cipher_string);
2701
2702                 if (cc->key_size > 0) {
2703                         if (cc->key_string)
2704                                 DMEMIT(":%u:%s", cc->key_size, cc->key_string);
2705                         else
2706                                 for (i = 0; i < cc->key_size; i++)
2707                                         DMEMIT("%02x", cc->key[i]);
2708                 } else
2709                         DMEMIT("-");
2710
2711                 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
2712                                 cc->dev->name, (unsigned long long)cc->start);
2713
2714                 num_feature_args += !!ti->num_discard_bios;
2715                 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
2716                 num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
2717                 if (cc->on_disk_tag_size)
2718                         num_feature_args++;
2719                 if (num_feature_args) {
2720                         DMEMIT(" %d", num_feature_args);
2721                         if (ti->num_discard_bios)
2722                                 DMEMIT(" allow_discards");
2723                         if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
2724                                 DMEMIT(" same_cpu_crypt");
2725                         if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
2726                                 DMEMIT(" submit_from_crypt_cpus");
2727                         if (cc->on_disk_tag_size)
2728                                 DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
2729                 }
2730
2731                 break;
2732         }
2733 }
2734
2735 static void crypt_postsuspend(struct dm_target *ti)
2736 {
2737         struct crypt_config *cc = ti->private;
2738
2739         set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
2740 }
2741
2742 static int crypt_preresume(struct dm_target *ti)
2743 {
2744         struct crypt_config *cc = ti->private;
2745
2746         if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
2747                 DMERR("aborting resume - crypt key is not set.");
2748                 return -EAGAIN;
2749         }
2750
2751         return 0;
2752 }
2753
2754 static void crypt_resume(struct dm_target *ti)
2755 {
2756         struct crypt_config *cc = ti->private;
2757
2758         clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
2759 }
2760
2761 /* Message interface
2762  *      key set <key>
2763  *      key wipe
2764  */
2765 static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
2766 {
2767         struct crypt_config *cc = ti->private;
2768         int key_size, ret = -EINVAL;
2769
2770         if (argc < 2)
2771                 goto error;
2772
2773         if (!strcasecmp(argv[0], "key")) {
2774                 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
2775                         DMWARN("not suspended during key manipulation.");
2776                         return -EINVAL;
2777                 }
2778                 if (argc == 3 && !strcasecmp(argv[1], "set")) {
2779                         /* The key size may not be changed. */
2780                         key_size = get_key_size(&argv[2]);
2781                         if (key_size < 0 || cc->key_size != key_size) {
2782                                 memset(argv[2], '0', strlen(argv[2]));
2783                                 return -EINVAL;
2784                         }
2785
2786                         ret = crypt_set_key(cc, argv[2]);
2787                         if (ret)
2788                                 return ret;
2789                         if (cc->iv_gen_ops && cc->iv_gen_ops->init)
2790                                 ret = cc->iv_gen_ops->init(cc);
2791                         return ret;
2792                 }
2793                 if (argc == 2 && !strcasecmp(argv[1], "wipe")) {
2794                         if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
2795                                 ret = cc->iv_gen_ops->wipe(cc);
2796                                 if (ret)
2797                                         return ret;
2798                         }
2799                         return crypt_wipe_key(cc);
2800                 }
2801         }
2802
2803 error:
2804         DMWARN("unrecognised message received.");
2805         return -EINVAL;
2806 }
2807
2808 static int crypt_iterate_devices(struct dm_target *ti,
2809                                  iterate_devices_callout_fn fn, void *data)
2810 {
2811         struct crypt_config *cc = ti->private;
2812
2813         return fn(ti, cc->dev, cc->start, ti->len, data);
2814 }
2815
2816 static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
2817 {
2818         /*
2819          * Unfortunate constraint that is required to avoid the potential
2820          * for exceeding underlying device's max_segments limits -- due to
2821          * crypt_alloc_buffer() possibly allocating pages for the encryption
2822          * bio that are not as physically contiguous as the original bio.
2823          */
2824         limits->max_segment_size = PAGE_SIZE;
2825 }
2826
2827 static struct target_type crypt_target = {
2828         .name   = "crypt",
2829         .version = {1, 16, 0},
2830         .module = THIS_MODULE,
2831         .ctr    = crypt_ctr,
2832         .dtr    = crypt_dtr,
2833         .map    = crypt_map,
2834         .status = crypt_status,
2835         .postsuspend = crypt_postsuspend,
2836         .preresume = crypt_preresume,
2837         .resume = crypt_resume,
2838         .message = crypt_message,
2839         .iterate_devices = crypt_iterate_devices,
2840         .io_hints = crypt_io_hints,
2841 };
2842
2843 static int __init dm_crypt_init(void)
2844 {
2845         int r;
2846
2847         r = dm_register_target(&crypt_target);
2848         if (r < 0)
2849                 DMERR("register failed %d", r);
2850
2851         return r;
2852 }
2853
2854 static void __exit dm_crypt_exit(void)
2855 {
2856         dm_unregister_target(&crypt_target);
2857 }
2858
2859 module_init(dm_crypt_init);
2860 module_exit(dm_crypt_exit);
2861
2862 MODULE_AUTHOR("Jana Saout <jana@saout.de>");
2863 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
2864 MODULE_LICENSE("GPL");