Merge tag 'kgdb-5.16-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/danielt...
[linux-2.6-microblaze.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-2020 Red Hat, Inc. All rights reserved.
5  * Copyright (C) 2013-2020 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/blk-integrity.h>
19 #include <linux/mempool.h>
20 #include <linux/slab.h>
21 #include <linux/crypto.h>
22 #include <linux/workqueue.h>
23 #include <linux/kthread.h>
24 #include <linux/backing-dev.h>
25 #include <linux/atomic.h>
26 #include <linux/scatterlist.h>
27 #include <linux/rbtree.h>
28 #include <linux/ctype.h>
29 #include <asm/page.h>
30 #include <asm/unaligned.h>
31 #include <crypto/hash.h>
32 #include <crypto/md5.h>
33 #include <crypto/algapi.h>
34 #include <crypto/skcipher.h>
35 #include <crypto/aead.h>
36 #include <crypto/authenc.h>
37 #include <linux/rtnetlink.h> /* for struct rtattr and RTA macros only */
38 #include <linux/key-type.h>
39 #include <keys/user-type.h>
40 #include <keys/encrypted-type.h>
41 #include <keys/trusted-type.h>
42
43 #include <linux/device-mapper.h>
44
45 #define DM_MSG_PREFIX "crypt"
46
47 /*
48  * context holding the current state of a multi-part conversion
49  */
50 struct convert_context {
51         struct completion restart;
52         struct bio *bio_in;
53         struct bio *bio_out;
54         struct bvec_iter iter_in;
55         struct bvec_iter iter_out;
56         u64 cc_sector;
57         atomic_t cc_pending;
58         union {
59                 struct skcipher_request *req;
60                 struct aead_request *req_aead;
61         } r;
62
63 };
64
65 /*
66  * per bio private data
67  */
68 struct dm_crypt_io {
69         struct crypt_config *cc;
70         struct bio *base_bio;
71         u8 *integrity_metadata;
72         bool integrity_metadata_from_pool;
73         struct work_struct work;
74         struct tasklet_struct tasklet;
75
76         struct convert_context ctx;
77
78         atomic_t io_pending;
79         blk_status_t error;
80         sector_t sector;
81
82         struct rb_node rb_node;
83 } CRYPTO_MINALIGN_ATTR;
84
85 struct dm_crypt_request {
86         struct convert_context *ctx;
87         struct scatterlist sg_in[4];
88         struct scatterlist sg_out[4];
89         u64 iv_sector;
90 };
91
92 struct crypt_config;
93
94 struct crypt_iv_operations {
95         int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
96                    const char *opts);
97         void (*dtr)(struct crypt_config *cc);
98         int (*init)(struct crypt_config *cc);
99         int (*wipe)(struct crypt_config *cc);
100         int (*generator)(struct crypt_config *cc, u8 *iv,
101                          struct dm_crypt_request *dmreq);
102         int (*post)(struct crypt_config *cc, u8 *iv,
103                     struct dm_crypt_request *dmreq);
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 #define ELEPHANT_MAX_KEY_SIZE 32
124 struct iv_elephant_private {
125         struct crypto_skcipher *tfm;
126 };
127
128 /*
129  * Crypt: maps a linear range of a block device
130  * and encrypts / decrypts at the same time.
131  */
132 enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
133              DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD,
134              DM_CRYPT_NO_READ_WORKQUEUE, DM_CRYPT_NO_WRITE_WORKQUEUE,
135              DM_CRYPT_WRITE_INLINE };
136
137 enum cipher_flags {
138         CRYPT_MODE_INTEGRITY_AEAD,      /* Use authenticated mode for cipher */
139         CRYPT_IV_LARGE_SECTORS,         /* Calculate IV from sector_size, not 512B sectors */
140         CRYPT_ENCRYPT_PREPROCESS,       /* Must preprocess data for encryption (elephant) */
141 };
142
143 /*
144  * The fields in here must be read only after initialization.
145  */
146 struct crypt_config {
147         struct dm_dev *dev;
148         sector_t start;
149
150         struct percpu_counter n_allocated_pages;
151
152         struct workqueue_struct *io_queue;
153         struct workqueue_struct *crypt_queue;
154
155         spinlock_t write_thread_lock;
156         struct task_struct *write_thread;
157         struct rb_root write_tree;
158
159         char *cipher_string;
160         char *cipher_auth;
161         char *key_string;
162
163         const struct crypt_iv_operations *iv_gen_ops;
164         union {
165                 struct iv_benbi_private benbi;
166                 struct iv_lmk_private lmk;
167                 struct iv_tcw_private tcw;
168                 struct iv_elephant_private elephant;
169         } iv_gen_private;
170         u64 iv_offset;
171         unsigned int iv_size;
172         unsigned short int sector_size;
173         unsigned char sector_shift;
174
175         union {
176                 struct crypto_skcipher **tfms;
177                 struct crypto_aead **tfms_aead;
178         } cipher_tfm;
179         unsigned tfms_count;
180         unsigned long cipher_flags;
181
182         /*
183          * Layout of each crypto request:
184          *
185          *   struct skcipher_request
186          *      context
187          *      padding
188          *   struct dm_crypt_request
189          *      padding
190          *   IV
191          *
192          * The padding is added so that dm_crypt_request and the IV are
193          * correctly aligned.
194          */
195         unsigned int dmreq_start;
196
197         unsigned int per_bio_data_size;
198
199         unsigned long flags;
200         unsigned int key_size;
201         unsigned int key_parts;      /* independent parts in key buffer */
202         unsigned int key_extra_size; /* additional keys length */
203         unsigned int key_mac_size;   /* MAC key size for authenc(...) */
204
205         unsigned int integrity_tag_size;
206         unsigned int integrity_iv_size;
207         unsigned int on_disk_tag_size;
208
209         /*
210          * pool for per bio private data, crypto requests,
211          * encryption requeusts/buffer pages and integrity tags
212          */
213         unsigned tag_pool_max_sectors;
214         mempool_t tag_pool;
215         mempool_t req_pool;
216         mempool_t page_pool;
217
218         struct bio_set bs;
219         struct mutex bio_alloc_lock;
220
221         u8 *authenc_key; /* space for keys in authenc() format (if used) */
222         u8 key[];
223 };
224
225 #define MIN_IOS         64
226 #define MAX_TAG_SIZE    480
227 #define POOL_ENTRY_SIZE 512
228
229 static DEFINE_SPINLOCK(dm_crypt_clients_lock);
230 static unsigned dm_crypt_clients_n = 0;
231 static volatile unsigned long dm_crypt_pages_per_client;
232 #define DM_CRYPT_MEMORY_PERCENT                 2
233 #define DM_CRYPT_MIN_PAGES_PER_CLIENT           (BIO_MAX_VECS * 16)
234
235 static void clone_init(struct dm_crypt_io *, struct bio *);
236 static void kcryptd_queue_crypt(struct dm_crypt_io *io);
237 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
238                                              struct scatterlist *sg);
239
240 static bool crypt_integrity_aead(struct crypt_config *cc);
241
242 /*
243  * Use this to access cipher attributes that are independent of the key.
244  */
245 static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
246 {
247         return cc->cipher_tfm.tfms[0];
248 }
249
250 static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
251 {
252         return cc->cipher_tfm.tfms_aead[0];
253 }
254
255 /*
256  * Different IV generation algorithms:
257  *
258  * plain: the initial vector is the 32-bit little-endian version of the sector
259  *        number, padded with zeros if necessary.
260  *
261  * plain64: the initial vector is the 64-bit little-endian version of the sector
262  *        number, padded with zeros if necessary.
263  *
264  * plain64be: the initial vector is the 64-bit big-endian version of the sector
265  *        number, padded with zeros if necessary.
266  *
267  * essiv: "encrypted sector|salt initial vector", the sector number is
268  *        encrypted with the bulk cipher using a salt as key. The salt
269  *        should be derived from the bulk cipher's key via hashing.
270  *
271  * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
272  *        (needed for LRW-32-AES and possible other narrow block modes)
273  *
274  * null: the initial vector is always zero.  Provides compatibility with
275  *       obsolete loop_fish2 devices.  Do not use for new devices.
276  *
277  * lmk:  Compatible implementation of the block chaining mode used
278  *       by the Loop-AES block device encryption system
279  *       designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
280  *       It operates on full 512 byte sectors and uses CBC
281  *       with an IV derived from the sector number, the data and
282  *       optionally extra IV seed.
283  *       This means that after decryption the first block
284  *       of sector must be tweaked according to decrypted data.
285  *       Loop-AES can use three encryption schemes:
286  *         version 1: is plain aes-cbc mode
287  *         version 2: uses 64 multikey scheme with lmk IV generator
288  *         version 3: the same as version 2 with additional IV seed
289  *                   (it uses 65 keys, last key is used as IV seed)
290  *
291  * tcw:  Compatible implementation of the block chaining mode used
292  *       by the TrueCrypt device encryption system (prior to version 4.1).
293  *       For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
294  *       It operates on full 512 byte sectors and uses CBC
295  *       with an IV derived from initial key and the sector number.
296  *       In addition, whitening value is applied on every sector, whitening
297  *       is calculated from initial key, sector number and mixed using CRC32.
298  *       Note that this encryption scheme is vulnerable to watermarking attacks
299  *       and should be used for old compatible containers access only.
300  *
301  * eboiv: Encrypted byte-offset IV (used in Bitlocker in CBC mode)
302  *        The IV is encrypted little-endian byte-offset (with the same key
303  *        and cipher as the volume).
304  *
305  * elephant: The extended version of eboiv with additional Elephant diffuser
306  *           used with Bitlocker CBC mode.
307  *           This mode was used in older Windows systems
308  *           https://download.microsoft.com/download/0/2/3/0238acaf-d3bf-4a6d-b3d6-0a0be4bbb36e/bitlockercipher200608.pdf
309  */
310
311 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
312                               struct dm_crypt_request *dmreq)
313 {
314         memset(iv, 0, cc->iv_size);
315         *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
316
317         return 0;
318 }
319
320 static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
321                                 struct dm_crypt_request *dmreq)
322 {
323         memset(iv, 0, cc->iv_size);
324         *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
325
326         return 0;
327 }
328
329 static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
330                                   struct dm_crypt_request *dmreq)
331 {
332         memset(iv, 0, cc->iv_size);
333         /* iv_size is at least of size u64; usually it is 16 bytes */
334         *(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
335
336         return 0;
337 }
338
339 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
340                               struct dm_crypt_request *dmreq)
341 {
342         /*
343          * ESSIV encryption of the IV is now handled by the crypto API,
344          * so just pass the plain sector number here.
345          */
346         memset(iv, 0, cc->iv_size);
347         *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
348
349         return 0;
350 }
351
352 static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
353                               const char *opts)
354 {
355         unsigned bs;
356         int log;
357
358         if (crypt_integrity_aead(cc))
359                 bs = crypto_aead_blocksize(any_tfm_aead(cc));
360         else
361                 bs = crypto_skcipher_blocksize(any_tfm(cc));
362         log = ilog2(bs);
363
364         /* we need to calculate how far we must shift the sector count
365          * to get the cipher block count, we use this shift in _gen */
366
367         if (1 << log != bs) {
368                 ti->error = "cypher blocksize is not a power of 2";
369                 return -EINVAL;
370         }
371
372         if (log > 9) {
373                 ti->error = "cypher blocksize is > 512";
374                 return -EINVAL;
375         }
376
377         cc->iv_gen_private.benbi.shift = 9 - log;
378
379         return 0;
380 }
381
382 static void crypt_iv_benbi_dtr(struct crypt_config *cc)
383 {
384 }
385
386 static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
387                               struct dm_crypt_request *dmreq)
388 {
389         __be64 val;
390
391         memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
392
393         val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
394         put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
395
396         return 0;
397 }
398
399 static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
400                              struct dm_crypt_request *dmreq)
401 {
402         memset(iv, 0, cc->iv_size);
403
404         return 0;
405 }
406
407 static void crypt_iv_lmk_dtr(struct crypt_config *cc)
408 {
409         struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
410
411         if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
412                 crypto_free_shash(lmk->hash_tfm);
413         lmk->hash_tfm = NULL;
414
415         kfree_sensitive(lmk->seed);
416         lmk->seed = NULL;
417 }
418
419 static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
420                             const char *opts)
421 {
422         struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
423
424         if (cc->sector_size != (1 << SECTOR_SHIFT)) {
425                 ti->error = "Unsupported sector size for LMK";
426                 return -EINVAL;
427         }
428
429         lmk->hash_tfm = crypto_alloc_shash("md5", 0,
430                                            CRYPTO_ALG_ALLOCATES_MEMORY);
431         if (IS_ERR(lmk->hash_tfm)) {
432                 ti->error = "Error initializing LMK hash";
433                 return PTR_ERR(lmk->hash_tfm);
434         }
435
436         /* No seed in LMK version 2 */
437         if (cc->key_parts == cc->tfms_count) {
438                 lmk->seed = NULL;
439                 return 0;
440         }
441
442         lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
443         if (!lmk->seed) {
444                 crypt_iv_lmk_dtr(cc);
445                 ti->error = "Error kmallocing seed storage in LMK";
446                 return -ENOMEM;
447         }
448
449         return 0;
450 }
451
452 static int crypt_iv_lmk_init(struct crypt_config *cc)
453 {
454         struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
455         int subkey_size = cc->key_size / cc->key_parts;
456
457         /* LMK seed is on the position of LMK_KEYS + 1 key */
458         if (lmk->seed)
459                 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
460                        crypto_shash_digestsize(lmk->hash_tfm));
461
462         return 0;
463 }
464
465 static int crypt_iv_lmk_wipe(struct crypt_config *cc)
466 {
467         struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
468
469         if (lmk->seed)
470                 memset(lmk->seed, 0, LMK_SEED_SIZE);
471
472         return 0;
473 }
474
475 static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
476                             struct dm_crypt_request *dmreq,
477                             u8 *data)
478 {
479         struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
480         SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
481         struct md5_state md5state;
482         __le32 buf[4];
483         int i, r;
484
485         desc->tfm = lmk->hash_tfm;
486
487         r = crypto_shash_init(desc);
488         if (r)
489                 return r;
490
491         if (lmk->seed) {
492                 r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
493                 if (r)
494                         return r;
495         }
496
497         /* Sector is always 512B, block size 16, add data of blocks 1-31 */
498         r = crypto_shash_update(desc, data + 16, 16 * 31);
499         if (r)
500                 return r;
501
502         /* Sector is cropped to 56 bits here */
503         buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
504         buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
505         buf[2] = cpu_to_le32(4024);
506         buf[3] = 0;
507         r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
508         if (r)
509                 return r;
510
511         /* No MD5 padding here */
512         r = crypto_shash_export(desc, &md5state);
513         if (r)
514                 return r;
515
516         for (i = 0; i < MD5_HASH_WORDS; i++)
517                 __cpu_to_le32s(&md5state.hash[i]);
518         memcpy(iv, &md5state.hash, cc->iv_size);
519
520         return 0;
521 }
522
523 static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
524                             struct dm_crypt_request *dmreq)
525 {
526         struct scatterlist *sg;
527         u8 *src;
528         int r = 0;
529
530         if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
531                 sg = crypt_get_sg_data(cc, dmreq->sg_in);
532                 src = kmap_atomic(sg_page(sg));
533                 r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
534                 kunmap_atomic(src);
535         } else
536                 memset(iv, 0, cc->iv_size);
537
538         return r;
539 }
540
541 static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
542                              struct dm_crypt_request *dmreq)
543 {
544         struct scatterlist *sg;
545         u8 *dst;
546         int r;
547
548         if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
549                 return 0;
550
551         sg = crypt_get_sg_data(cc, dmreq->sg_out);
552         dst = kmap_atomic(sg_page(sg));
553         r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
554
555         /* Tweak the first block of plaintext sector */
556         if (!r)
557                 crypto_xor(dst + sg->offset, iv, cc->iv_size);
558
559         kunmap_atomic(dst);
560         return r;
561 }
562
563 static void crypt_iv_tcw_dtr(struct crypt_config *cc)
564 {
565         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
566
567         kfree_sensitive(tcw->iv_seed);
568         tcw->iv_seed = NULL;
569         kfree_sensitive(tcw->whitening);
570         tcw->whitening = NULL;
571
572         if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
573                 crypto_free_shash(tcw->crc32_tfm);
574         tcw->crc32_tfm = NULL;
575 }
576
577 static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
578                             const char *opts)
579 {
580         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
581
582         if (cc->sector_size != (1 << SECTOR_SHIFT)) {
583                 ti->error = "Unsupported sector size for TCW";
584                 return -EINVAL;
585         }
586
587         if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
588                 ti->error = "Wrong key size for TCW";
589                 return -EINVAL;
590         }
591
592         tcw->crc32_tfm = crypto_alloc_shash("crc32", 0,
593                                             CRYPTO_ALG_ALLOCATES_MEMORY);
594         if (IS_ERR(tcw->crc32_tfm)) {
595                 ti->error = "Error initializing CRC32 in TCW";
596                 return PTR_ERR(tcw->crc32_tfm);
597         }
598
599         tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
600         tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
601         if (!tcw->iv_seed || !tcw->whitening) {
602                 crypt_iv_tcw_dtr(cc);
603                 ti->error = "Error allocating seed storage in TCW";
604                 return -ENOMEM;
605         }
606
607         return 0;
608 }
609
610 static int crypt_iv_tcw_init(struct crypt_config *cc)
611 {
612         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
613         int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
614
615         memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
616         memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
617                TCW_WHITENING_SIZE);
618
619         return 0;
620 }
621
622 static int crypt_iv_tcw_wipe(struct crypt_config *cc)
623 {
624         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
625
626         memset(tcw->iv_seed, 0, cc->iv_size);
627         memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
628
629         return 0;
630 }
631
632 static int crypt_iv_tcw_whitening(struct crypt_config *cc,
633                                   struct dm_crypt_request *dmreq,
634                                   u8 *data)
635 {
636         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
637         __le64 sector = cpu_to_le64(dmreq->iv_sector);
638         u8 buf[TCW_WHITENING_SIZE];
639         SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
640         int i, r;
641
642         /* xor whitening with sector number */
643         crypto_xor_cpy(buf, tcw->whitening, (u8 *)&sector, 8);
644         crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)&sector, 8);
645
646         /* calculate crc32 for every 32bit part and xor it */
647         desc->tfm = tcw->crc32_tfm;
648         for (i = 0; i < 4; i++) {
649                 r = crypto_shash_init(desc);
650                 if (r)
651                         goto out;
652                 r = crypto_shash_update(desc, &buf[i * 4], 4);
653                 if (r)
654                         goto out;
655                 r = crypto_shash_final(desc, &buf[i * 4]);
656                 if (r)
657                         goto out;
658         }
659         crypto_xor(&buf[0], &buf[12], 4);
660         crypto_xor(&buf[4], &buf[8], 4);
661
662         /* apply whitening (8 bytes) to whole sector */
663         for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
664                 crypto_xor(data + i * 8, buf, 8);
665 out:
666         memzero_explicit(buf, sizeof(buf));
667         return r;
668 }
669
670 static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
671                             struct dm_crypt_request *dmreq)
672 {
673         struct scatterlist *sg;
674         struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
675         __le64 sector = cpu_to_le64(dmreq->iv_sector);
676         u8 *src;
677         int r = 0;
678
679         /* Remove whitening from ciphertext */
680         if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
681                 sg = crypt_get_sg_data(cc, dmreq->sg_in);
682                 src = kmap_atomic(sg_page(sg));
683                 r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
684                 kunmap_atomic(src);
685         }
686
687         /* Calculate IV */
688         crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)&sector, 8);
689         if (cc->iv_size > 8)
690                 crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)&sector,
691                                cc->iv_size - 8);
692
693         return r;
694 }
695
696 static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
697                              struct dm_crypt_request *dmreq)
698 {
699         struct scatterlist *sg;
700         u8 *dst;
701         int r;
702
703         if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
704                 return 0;
705
706         /* Apply whitening on ciphertext */
707         sg = crypt_get_sg_data(cc, dmreq->sg_out);
708         dst = kmap_atomic(sg_page(sg));
709         r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
710         kunmap_atomic(dst);
711
712         return r;
713 }
714
715 static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
716                                 struct dm_crypt_request *dmreq)
717 {
718         /* Used only for writes, there must be an additional space to store IV */
719         get_random_bytes(iv, cc->iv_size);
720         return 0;
721 }
722
723 static int crypt_iv_eboiv_ctr(struct crypt_config *cc, struct dm_target *ti,
724                             const char *opts)
725 {
726         if (crypt_integrity_aead(cc)) {
727                 ti->error = "AEAD transforms not supported for EBOIV";
728                 return -EINVAL;
729         }
730
731         if (crypto_skcipher_blocksize(any_tfm(cc)) != cc->iv_size) {
732                 ti->error = "Block size of EBOIV cipher does "
733                             "not match IV size of block cipher";
734                 return -EINVAL;
735         }
736
737         return 0;
738 }
739
740 static int crypt_iv_eboiv_gen(struct crypt_config *cc, u8 *iv,
741                             struct dm_crypt_request *dmreq)
742 {
743         u8 buf[MAX_CIPHER_BLOCKSIZE] __aligned(__alignof__(__le64));
744         struct skcipher_request *req;
745         struct scatterlist src, dst;
746         DECLARE_CRYPTO_WAIT(wait);
747         int err;
748
749         req = skcipher_request_alloc(any_tfm(cc), GFP_NOIO);
750         if (!req)
751                 return -ENOMEM;
752
753         memset(buf, 0, cc->iv_size);
754         *(__le64 *)buf = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
755
756         sg_init_one(&src, page_address(ZERO_PAGE(0)), cc->iv_size);
757         sg_init_one(&dst, iv, cc->iv_size);
758         skcipher_request_set_crypt(req, &src, &dst, cc->iv_size, buf);
759         skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
760         err = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
761         skcipher_request_free(req);
762
763         return err;
764 }
765
766 static void crypt_iv_elephant_dtr(struct crypt_config *cc)
767 {
768         struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
769
770         crypto_free_skcipher(elephant->tfm);
771         elephant->tfm = NULL;
772 }
773
774 static int crypt_iv_elephant_ctr(struct crypt_config *cc, struct dm_target *ti,
775                             const char *opts)
776 {
777         struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
778         int r;
779
780         elephant->tfm = crypto_alloc_skcipher("ecb(aes)", 0,
781                                               CRYPTO_ALG_ALLOCATES_MEMORY);
782         if (IS_ERR(elephant->tfm)) {
783                 r = PTR_ERR(elephant->tfm);
784                 elephant->tfm = NULL;
785                 return r;
786         }
787
788         r = crypt_iv_eboiv_ctr(cc, ti, NULL);
789         if (r)
790                 crypt_iv_elephant_dtr(cc);
791         return r;
792 }
793
794 static void diffuser_disk_to_cpu(u32 *d, size_t n)
795 {
796 #ifndef __LITTLE_ENDIAN
797         int i;
798
799         for (i = 0; i < n; i++)
800                 d[i] = le32_to_cpu((__le32)d[i]);
801 #endif
802 }
803
804 static void diffuser_cpu_to_disk(__le32 *d, size_t n)
805 {
806 #ifndef __LITTLE_ENDIAN
807         int i;
808
809         for (i = 0; i < n; i++)
810                 d[i] = cpu_to_le32((u32)d[i]);
811 #endif
812 }
813
814 static void diffuser_a_decrypt(u32 *d, size_t n)
815 {
816         int i, i1, i2, i3;
817
818         for (i = 0; i < 5; i++) {
819                 i1 = 0;
820                 i2 = n - 2;
821                 i3 = n - 5;
822
823                 while (i1 < (n - 1)) {
824                         d[i1] += d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
825                         i1++; i2++; i3++;
826
827                         if (i3 >= n)
828                                 i3 -= n;
829
830                         d[i1] += d[i2] ^ d[i3];
831                         i1++; i2++; i3++;
832
833                         if (i2 >= n)
834                                 i2 -= n;
835
836                         d[i1] += d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
837                         i1++; i2++; i3++;
838
839                         d[i1] += d[i2] ^ d[i3];
840                         i1++; i2++; i3++;
841                 }
842         }
843 }
844
845 static void diffuser_a_encrypt(u32 *d, size_t n)
846 {
847         int i, i1, i2, i3;
848
849         for (i = 0; i < 5; i++) {
850                 i1 = n - 1;
851                 i2 = n - 2 - 1;
852                 i3 = n - 5 - 1;
853
854                 while (i1 > 0) {
855                         d[i1] -= d[i2] ^ d[i3];
856                         i1--; i2--; i3--;
857
858                         d[i1] -= d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
859                         i1--; i2--; i3--;
860
861                         if (i2 < 0)
862                                 i2 += n;
863
864                         d[i1] -= d[i2] ^ d[i3];
865                         i1--; i2--; i3--;
866
867                         if (i3 < 0)
868                                 i3 += n;
869
870                         d[i1] -= d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
871                         i1--; i2--; i3--;
872                 }
873         }
874 }
875
876 static void diffuser_b_decrypt(u32 *d, size_t n)
877 {
878         int i, i1, i2, i3;
879
880         for (i = 0; i < 3; i++) {
881                 i1 = 0;
882                 i2 = 2;
883                 i3 = 5;
884
885                 while (i1 < (n - 1)) {
886                         d[i1] += d[i2] ^ d[i3];
887                         i1++; i2++; i3++;
888
889                         d[i1] += d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
890                         i1++; i2++; i3++;
891
892                         if (i2 >= n)
893                                 i2 -= n;
894
895                         d[i1] += d[i2] ^ d[i3];
896                         i1++; i2++; i3++;
897
898                         if (i3 >= n)
899                                 i3 -= n;
900
901                         d[i1] += d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
902                         i1++; i2++; i3++;
903                 }
904         }
905 }
906
907 static void diffuser_b_encrypt(u32 *d, size_t n)
908 {
909         int i, i1, i2, i3;
910
911         for (i = 0; i < 3; i++) {
912                 i1 = n - 1;
913                 i2 = 2 - 1;
914                 i3 = 5 - 1;
915
916                 while (i1 > 0) {
917                         d[i1] -= d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
918                         i1--; i2--; i3--;
919
920                         if (i3 < 0)
921                                 i3 += n;
922
923                         d[i1] -= d[i2] ^ d[i3];
924                         i1--; i2--; i3--;
925
926                         if (i2 < 0)
927                                 i2 += n;
928
929                         d[i1] -= d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
930                         i1--; i2--; i3--;
931
932                         d[i1] -= d[i2] ^ d[i3];
933                         i1--; i2--; i3--;
934                 }
935         }
936 }
937
938 static int crypt_iv_elephant(struct crypt_config *cc, struct dm_crypt_request *dmreq)
939 {
940         struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
941         u8 *es, *ks, *data, *data2, *data_offset;
942         struct skcipher_request *req;
943         struct scatterlist *sg, *sg2, src, dst;
944         DECLARE_CRYPTO_WAIT(wait);
945         int i, r;
946
947         req = skcipher_request_alloc(elephant->tfm, GFP_NOIO);
948         es = kzalloc(16, GFP_NOIO); /* Key for AES */
949         ks = kzalloc(32, GFP_NOIO); /* Elephant sector key */
950
951         if (!req || !es || !ks) {
952                 r = -ENOMEM;
953                 goto out;
954         }
955
956         *(__le64 *)es = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
957
958         /* E(Ks, e(s)) */
959         sg_init_one(&src, es, 16);
960         sg_init_one(&dst, ks, 16);
961         skcipher_request_set_crypt(req, &src, &dst, 16, NULL);
962         skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
963         r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
964         if (r)
965                 goto out;
966
967         /* E(Ks, e'(s)) */
968         es[15] = 0x80;
969         sg_init_one(&dst, &ks[16], 16);
970         r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
971         if (r)
972                 goto out;
973
974         sg = crypt_get_sg_data(cc, dmreq->sg_out);
975         data = kmap_atomic(sg_page(sg));
976         data_offset = data + sg->offset;
977
978         /* Cannot modify original bio, copy to sg_out and apply Elephant to it */
979         if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
980                 sg2 = crypt_get_sg_data(cc, dmreq->sg_in);
981                 data2 = kmap_atomic(sg_page(sg2));
982                 memcpy(data_offset, data2 + sg2->offset, cc->sector_size);
983                 kunmap_atomic(data2);
984         }
985
986         if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
987                 diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
988                 diffuser_b_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
989                 diffuser_a_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
990                 diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
991         }
992
993         for (i = 0; i < (cc->sector_size / 32); i++)
994                 crypto_xor(data_offset + i * 32, ks, 32);
995
996         if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
997                 diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
998                 diffuser_a_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
999                 diffuser_b_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
1000                 diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
1001         }
1002
1003         kunmap_atomic(data);
1004 out:
1005         kfree_sensitive(ks);
1006         kfree_sensitive(es);
1007         skcipher_request_free(req);
1008         return r;
1009 }
1010
1011 static int crypt_iv_elephant_gen(struct crypt_config *cc, u8 *iv,
1012                             struct dm_crypt_request *dmreq)
1013 {
1014         int r;
1015
1016         if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
1017                 r = crypt_iv_elephant(cc, dmreq);
1018                 if (r)
1019                         return r;
1020         }
1021
1022         return crypt_iv_eboiv_gen(cc, iv, dmreq);
1023 }
1024
1025 static int crypt_iv_elephant_post(struct crypt_config *cc, u8 *iv,
1026                                   struct dm_crypt_request *dmreq)
1027 {
1028         if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
1029                 return crypt_iv_elephant(cc, dmreq);
1030
1031         return 0;
1032 }
1033
1034 static int crypt_iv_elephant_init(struct crypt_config *cc)
1035 {
1036         struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1037         int key_offset = cc->key_size - cc->key_extra_size;
1038
1039         return crypto_skcipher_setkey(elephant->tfm, &cc->key[key_offset], cc->key_extra_size);
1040 }
1041
1042 static int crypt_iv_elephant_wipe(struct crypt_config *cc)
1043 {
1044         struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1045         u8 key[ELEPHANT_MAX_KEY_SIZE];
1046
1047         memset(key, 0, cc->key_extra_size);
1048         return crypto_skcipher_setkey(elephant->tfm, key, cc->key_extra_size);
1049 }
1050
1051 static const struct crypt_iv_operations crypt_iv_plain_ops = {
1052         .generator = crypt_iv_plain_gen
1053 };
1054
1055 static const struct crypt_iv_operations crypt_iv_plain64_ops = {
1056         .generator = crypt_iv_plain64_gen
1057 };
1058
1059 static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
1060         .generator = crypt_iv_plain64be_gen
1061 };
1062
1063 static const struct crypt_iv_operations crypt_iv_essiv_ops = {
1064         .generator = crypt_iv_essiv_gen
1065 };
1066
1067 static const struct crypt_iv_operations crypt_iv_benbi_ops = {
1068         .ctr       = crypt_iv_benbi_ctr,
1069         .dtr       = crypt_iv_benbi_dtr,
1070         .generator = crypt_iv_benbi_gen
1071 };
1072
1073 static const struct crypt_iv_operations crypt_iv_null_ops = {
1074         .generator = crypt_iv_null_gen
1075 };
1076
1077 static const struct crypt_iv_operations crypt_iv_lmk_ops = {
1078         .ctr       = crypt_iv_lmk_ctr,
1079         .dtr       = crypt_iv_lmk_dtr,
1080         .init      = crypt_iv_lmk_init,
1081         .wipe      = crypt_iv_lmk_wipe,
1082         .generator = crypt_iv_lmk_gen,
1083         .post      = crypt_iv_lmk_post
1084 };
1085
1086 static const struct crypt_iv_operations crypt_iv_tcw_ops = {
1087         .ctr       = crypt_iv_tcw_ctr,
1088         .dtr       = crypt_iv_tcw_dtr,
1089         .init      = crypt_iv_tcw_init,
1090         .wipe      = crypt_iv_tcw_wipe,
1091         .generator = crypt_iv_tcw_gen,
1092         .post      = crypt_iv_tcw_post
1093 };
1094
1095 static const struct crypt_iv_operations crypt_iv_random_ops = {
1096         .generator = crypt_iv_random_gen
1097 };
1098
1099 static const struct crypt_iv_operations crypt_iv_eboiv_ops = {
1100         .ctr       = crypt_iv_eboiv_ctr,
1101         .generator = crypt_iv_eboiv_gen
1102 };
1103
1104 static const struct crypt_iv_operations crypt_iv_elephant_ops = {
1105         .ctr       = crypt_iv_elephant_ctr,
1106         .dtr       = crypt_iv_elephant_dtr,
1107         .init      = crypt_iv_elephant_init,
1108         .wipe      = crypt_iv_elephant_wipe,
1109         .generator = crypt_iv_elephant_gen,
1110         .post      = crypt_iv_elephant_post
1111 };
1112
1113 /*
1114  * Integrity extensions
1115  */
1116 static bool crypt_integrity_aead(struct crypt_config *cc)
1117 {
1118         return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
1119 }
1120
1121 static bool crypt_integrity_hmac(struct crypt_config *cc)
1122 {
1123         return crypt_integrity_aead(cc) && cc->key_mac_size;
1124 }
1125
1126 /* Get sg containing data */
1127 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
1128                                              struct scatterlist *sg)
1129 {
1130         if (unlikely(crypt_integrity_aead(cc)))
1131                 return &sg[2];
1132
1133         return sg;
1134 }
1135
1136 static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
1137 {
1138         struct bio_integrity_payload *bip;
1139         unsigned int tag_len;
1140         int ret;
1141
1142         if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
1143                 return 0;
1144
1145         bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
1146         if (IS_ERR(bip))
1147                 return PTR_ERR(bip);
1148
1149         tag_len = io->cc->on_disk_tag_size * (bio_sectors(bio) >> io->cc->sector_shift);
1150
1151         bip->bip_iter.bi_size = tag_len;
1152         bip->bip_iter.bi_sector = io->cc->start + io->sector;
1153
1154         ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
1155                                      tag_len, offset_in_page(io->integrity_metadata));
1156         if (unlikely(ret != tag_len))
1157                 return -ENOMEM;
1158
1159         return 0;
1160 }
1161
1162 static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
1163 {
1164 #ifdef CONFIG_BLK_DEV_INTEGRITY
1165         struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
1166         struct mapped_device *md = dm_table_get_md(ti->table);
1167
1168         /* From now we require underlying device with our integrity profile */
1169         if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
1170                 ti->error = "Integrity profile not supported.";
1171                 return -EINVAL;
1172         }
1173
1174         if (bi->tag_size != cc->on_disk_tag_size ||
1175             bi->tuple_size != cc->on_disk_tag_size) {
1176                 ti->error = "Integrity profile tag size mismatch.";
1177                 return -EINVAL;
1178         }
1179         if (1 << bi->interval_exp != cc->sector_size) {
1180                 ti->error = "Integrity profile sector size mismatch.";
1181                 return -EINVAL;
1182         }
1183
1184         if (crypt_integrity_aead(cc)) {
1185                 cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
1186                 DMDEBUG("%s: Integrity AEAD, tag size %u, IV size %u.", dm_device_name(md),
1187                        cc->integrity_tag_size, cc->integrity_iv_size);
1188
1189                 if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
1190                         ti->error = "Integrity AEAD auth tag size is not supported.";
1191                         return -EINVAL;
1192                 }
1193         } else if (cc->integrity_iv_size)
1194                 DMDEBUG("%s: Additional per-sector space %u bytes for IV.", dm_device_name(md),
1195                        cc->integrity_iv_size);
1196
1197         if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
1198                 ti->error = "Not enough space for integrity tag in the profile.";
1199                 return -EINVAL;
1200         }
1201
1202         return 0;
1203 #else
1204         ti->error = "Integrity profile not supported.";
1205         return -EINVAL;
1206 #endif
1207 }
1208
1209 static void crypt_convert_init(struct crypt_config *cc,
1210                                struct convert_context *ctx,
1211                                struct bio *bio_out, struct bio *bio_in,
1212                                sector_t sector)
1213 {
1214         ctx->bio_in = bio_in;
1215         ctx->bio_out = bio_out;
1216         if (bio_in)
1217                 ctx->iter_in = bio_in->bi_iter;
1218         if (bio_out)
1219                 ctx->iter_out = bio_out->bi_iter;
1220         ctx->cc_sector = sector + cc->iv_offset;
1221         init_completion(&ctx->restart);
1222 }
1223
1224 static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
1225                                              void *req)
1226 {
1227         return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
1228 }
1229
1230 static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
1231 {
1232         return (void *)((char *)dmreq - cc->dmreq_start);
1233 }
1234
1235 static u8 *iv_of_dmreq(struct crypt_config *cc,
1236                        struct dm_crypt_request *dmreq)
1237 {
1238         if (crypt_integrity_aead(cc))
1239                 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1240                         crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
1241         else
1242                 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1243                         crypto_skcipher_alignmask(any_tfm(cc)) + 1);
1244 }
1245
1246 static u8 *org_iv_of_dmreq(struct crypt_config *cc,
1247                        struct dm_crypt_request *dmreq)
1248 {
1249         return iv_of_dmreq(cc, dmreq) + cc->iv_size;
1250 }
1251
1252 static __le64 *org_sector_of_dmreq(struct crypt_config *cc,
1253                        struct dm_crypt_request *dmreq)
1254 {
1255         u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
1256         return (__le64 *) ptr;
1257 }
1258
1259 static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
1260                        struct dm_crypt_request *dmreq)
1261 {
1262         u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
1263                   cc->iv_size + sizeof(uint64_t);
1264         return (unsigned int*)ptr;
1265 }
1266
1267 static void *tag_from_dmreq(struct crypt_config *cc,
1268                                 struct dm_crypt_request *dmreq)
1269 {
1270         struct convert_context *ctx = dmreq->ctx;
1271         struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1272
1273         return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
1274                 cc->on_disk_tag_size];
1275 }
1276
1277 static void *iv_tag_from_dmreq(struct crypt_config *cc,
1278                                struct dm_crypt_request *dmreq)
1279 {
1280         return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
1281 }
1282
1283 static int crypt_convert_block_aead(struct crypt_config *cc,
1284                                      struct convert_context *ctx,
1285                                      struct aead_request *req,
1286                                      unsigned int tag_offset)
1287 {
1288         struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1289         struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1290         struct dm_crypt_request *dmreq;
1291         u8 *iv, *org_iv, *tag_iv, *tag;
1292         __le64 *sector;
1293         int r = 0;
1294
1295         BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
1296
1297         /* Reject unexpected unaligned bio. */
1298         if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1299                 return -EIO;
1300
1301         dmreq = dmreq_of_req(cc, req);
1302         dmreq->iv_sector = ctx->cc_sector;
1303         if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1304                 dmreq->iv_sector >>= cc->sector_shift;
1305         dmreq->ctx = ctx;
1306
1307         *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1308
1309         sector = org_sector_of_dmreq(cc, dmreq);
1310         *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1311
1312         iv = iv_of_dmreq(cc, dmreq);
1313         org_iv = org_iv_of_dmreq(cc, dmreq);
1314         tag = tag_from_dmreq(cc, dmreq);
1315         tag_iv = iv_tag_from_dmreq(cc, dmreq);
1316
1317         /* AEAD request:
1318          *  |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1319          *  | (authenticated) | (auth+encryption) |              |
1320          *  | sector_LE |  IV |  sector in/out    |  tag in/out  |
1321          */
1322         sg_init_table(dmreq->sg_in, 4);
1323         sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
1324         sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
1325         sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1326         sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
1327
1328         sg_init_table(dmreq->sg_out, 4);
1329         sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
1330         sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
1331         sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1332         sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
1333
1334         if (cc->iv_gen_ops) {
1335                 /* For READs use IV stored in integrity metadata */
1336                 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1337                         memcpy(org_iv, tag_iv, cc->iv_size);
1338                 } else {
1339                         r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1340                         if (r < 0)
1341                                 return r;
1342                         /* Store generated IV in integrity metadata */
1343                         if (cc->integrity_iv_size)
1344                                 memcpy(tag_iv, org_iv, cc->iv_size);
1345                 }
1346                 /* Working copy of IV, to be modified in crypto API */
1347                 memcpy(iv, org_iv, cc->iv_size);
1348         }
1349
1350         aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
1351         if (bio_data_dir(ctx->bio_in) == WRITE) {
1352                 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1353                                        cc->sector_size, iv);
1354                 r = crypto_aead_encrypt(req);
1355                 if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
1356                         memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
1357                                cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
1358         } else {
1359                 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1360                                        cc->sector_size + cc->integrity_tag_size, iv);
1361                 r = crypto_aead_decrypt(req);
1362         }
1363
1364         if (r == -EBADMSG) {
1365                 char b[BDEVNAME_SIZE];
1366                 DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx->bio_in, b),
1367                             (unsigned long long)le64_to_cpu(*sector));
1368         }
1369
1370         if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1371                 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1372
1373         bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1374         bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1375
1376         return r;
1377 }
1378
1379 static int crypt_convert_block_skcipher(struct crypt_config *cc,
1380                                         struct convert_context *ctx,
1381                                         struct skcipher_request *req,
1382                                         unsigned int tag_offset)
1383 {
1384         struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1385         struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1386         struct scatterlist *sg_in, *sg_out;
1387         struct dm_crypt_request *dmreq;
1388         u8 *iv, *org_iv, *tag_iv;
1389         __le64 *sector;
1390         int r = 0;
1391
1392         /* Reject unexpected unaligned bio. */
1393         if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1394                 return -EIO;
1395
1396         dmreq = dmreq_of_req(cc, req);
1397         dmreq->iv_sector = ctx->cc_sector;
1398         if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1399                 dmreq->iv_sector >>= cc->sector_shift;
1400         dmreq->ctx = ctx;
1401
1402         *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1403
1404         iv = iv_of_dmreq(cc, dmreq);
1405         org_iv = org_iv_of_dmreq(cc, dmreq);
1406         tag_iv = iv_tag_from_dmreq(cc, dmreq);
1407
1408         sector = org_sector_of_dmreq(cc, dmreq);
1409         *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1410
1411         /* For skcipher we use only the first sg item */
1412         sg_in  = &dmreq->sg_in[0];
1413         sg_out = &dmreq->sg_out[0];
1414
1415         sg_init_table(sg_in, 1);
1416         sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1417
1418         sg_init_table(sg_out, 1);
1419         sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1420
1421         if (cc->iv_gen_ops) {
1422                 /* For READs use IV stored in integrity metadata */
1423                 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1424                         memcpy(org_iv, tag_iv, cc->integrity_iv_size);
1425                 } else {
1426                         r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1427                         if (r < 0)
1428                                 return r;
1429                         /* Data can be already preprocessed in generator */
1430                         if (test_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags))
1431                                 sg_in = sg_out;
1432                         /* Store generated IV in integrity metadata */
1433                         if (cc->integrity_iv_size)
1434                                 memcpy(tag_iv, org_iv, cc->integrity_iv_size);
1435                 }
1436                 /* Working copy of IV, to be modified in crypto API */
1437                 memcpy(iv, org_iv, cc->iv_size);
1438         }
1439
1440         skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
1441
1442         if (bio_data_dir(ctx->bio_in) == WRITE)
1443                 r = crypto_skcipher_encrypt(req);
1444         else
1445                 r = crypto_skcipher_decrypt(req);
1446
1447         if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1448                 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1449
1450         bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1451         bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1452
1453         return r;
1454 }
1455
1456 static void kcryptd_async_done(struct crypto_async_request *async_req,
1457                                int error);
1458
1459 static int crypt_alloc_req_skcipher(struct crypt_config *cc,
1460                                      struct convert_context *ctx)
1461 {
1462         unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
1463
1464         if (!ctx->r.req) {
1465                 ctx->r.req = mempool_alloc(&cc->req_pool, in_interrupt() ? GFP_ATOMIC : GFP_NOIO);
1466                 if (!ctx->r.req)
1467                         return -ENOMEM;
1468         }
1469
1470         skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
1471
1472         /*
1473          * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1474          * requests if driver request queue is full.
1475          */
1476         skcipher_request_set_callback(ctx->r.req,
1477             CRYPTO_TFM_REQ_MAY_BACKLOG,
1478             kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
1479
1480         return 0;
1481 }
1482
1483 static int crypt_alloc_req_aead(struct crypt_config *cc,
1484                                  struct convert_context *ctx)
1485 {
1486         if (!ctx->r.req_aead) {
1487                 ctx->r.req_aead = mempool_alloc(&cc->req_pool, in_interrupt() ? GFP_ATOMIC : GFP_NOIO);
1488                 if (!ctx->r.req_aead)
1489                         return -ENOMEM;
1490         }
1491
1492         aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
1493
1494         /*
1495          * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1496          * requests if driver request queue is full.
1497          */
1498         aead_request_set_callback(ctx->r.req_aead,
1499             CRYPTO_TFM_REQ_MAY_BACKLOG,
1500             kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
1501
1502         return 0;
1503 }
1504
1505 static int crypt_alloc_req(struct crypt_config *cc,
1506                             struct convert_context *ctx)
1507 {
1508         if (crypt_integrity_aead(cc))
1509                 return crypt_alloc_req_aead(cc, ctx);
1510         else
1511                 return crypt_alloc_req_skcipher(cc, ctx);
1512 }
1513
1514 static void crypt_free_req_skcipher(struct crypt_config *cc,
1515                                     struct skcipher_request *req, struct bio *base_bio)
1516 {
1517         struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1518
1519         if ((struct skcipher_request *)(io + 1) != req)
1520                 mempool_free(req, &cc->req_pool);
1521 }
1522
1523 static void crypt_free_req_aead(struct crypt_config *cc,
1524                                 struct aead_request *req, struct bio *base_bio)
1525 {
1526         struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1527
1528         if ((struct aead_request *)(io + 1) != req)
1529                 mempool_free(req, &cc->req_pool);
1530 }
1531
1532 static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
1533 {
1534         if (crypt_integrity_aead(cc))
1535                 crypt_free_req_aead(cc, req, base_bio);
1536         else
1537                 crypt_free_req_skcipher(cc, req, base_bio);
1538 }
1539
1540 /*
1541  * Encrypt / decrypt data from one bio to another one (can be the same one)
1542  */
1543 static blk_status_t crypt_convert(struct crypt_config *cc,
1544                          struct convert_context *ctx, bool atomic, bool reset_pending)
1545 {
1546         unsigned int tag_offset = 0;
1547         unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
1548         int r;
1549
1550         /*
1551          * if reset_pending is set we are dealing with the bio for the first time,
1552          * else we're continuing to work on the previous bio, so don't mess with
1553          * the cc_pending counter
1554          */
1555         if (reset_pending)
1556                 atomic_set(&ctx->cc_pending, 1);
1557
1558         while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
1559
1560                 r = crypt_alloc_req(cc, ctx);
1561                 if (r) {
1562                         complete(&ctx->restart);
1563                         return BLK_STS_DEV_RESOURCE;
1564                 }
1565
1566                 atomic_inc(&ctx->cc_pending);
1567
1568                 if (crypt_integrity_aead(cc))
1569                         r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
1570                 else
1571                         r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
1572
1573                 switch (r) {
1574                 /*
1575                  * The request was queued by a crypto driver
1576                  * but the driver request queue is full, let's wait.
1577                  */
1578                 case -EBUSY:
1579                         if (in_interrupt()) {
1580                                 if (try_wait_for_completion(&ctx->restart)) {
1581                                         /*
1582                                          * we don't have to block to wait for completion,
1583                                          * so proceed
1584                                          */
1585                                 } else {
1586                                         /*
1587                                          * we can't wait for completion without blocking
1588                                          * exit and continue processing in a workqueue
1589                                          */
1590                                         ctx->r.req = NULL;
1591                                         ctx->cc_sector += sector_step;
1592                                         tag_offset++;
1593                                         return BLK_STS_DEV_RESOURCE;
1594                                 }
1595                         } else {
1596                                 wait_for_completion(&ctx->restart);
1597                         }
1598                         reinit_completion(&ctx->restart);
1599                         fallthrough;
1600                 /*
1601                  * The request is queued and processed asynchronously,
1602                  * completion function kcryptd_async_done() will be called.
1603                  */
1604                 case -EINPROGRESS:
1605                         ctx->r.req = NULL;
1606                         ctx->cc_sector += sector_step;
1607                         tag_offset++;
1608                         continue;
1609                 /*
1610                  * The request was already processed (synchronously).
1611                  */
1612                 case 0:
1613                         atomic_dec(&ctx->cc_pending);
1614                         ctx->cc_sector += sector_step;
1615                         tag_offset++;
1616                         if (!atomic)
1617                                 cond_resched();
1618                         continue;
1619                 /*
1620                  * There was a data integrity error.
1621                  */
1622                 case -EBADMSG:
1623                         atomic_dec(&ctx->cc_pending);
1624                         return BLK_STS_PROTECTION;
1625                 /*
1626                  * There was an error while processing the request.
1627                  */
1628                 default:
1629                         atomic_dec(&ctx->cc_pending);
1630                         return BLK_STS_IOERR;
1631                 }
1632         }
1633
1634         return 0;
1635 }
1636
1637 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
1638
1639 /*
1640  * Generate a new unfragmented bio with the given size
1641  * This should never violate the device limitations (but only because
1642  * max_segment_size is being constrained to PAGE_SIZE).
1643  *
1644  * This function may be called concurrently. If we allocate from the mempool
1645  * concurrently, there is a possibility of deadlock. For example, if we have
1646  * mempool of 256 pages, two processes, each wanting 256, pages allocate from
1647  * the mempool concurrently, it may deadlock in a situation where both processes
1648  * have allocated 128 pages and the mempool is exhausted.
1649  *
1650  * In order to avoid this scenario we allocate the pages under a mutex.
1651  *
1652  * In order to not degrade performance with excessive locking, we try
1653  * non-blocking allocations without a mutex first but on failure we fallback
1654  * to blocking allocations with a mutex.
1655  */
1656 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
1657 {
1658         struct crypt_config *cc = io->cc;
1659         struct bio *clone;
1660         unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1661         gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
1662         unsigned i, len, remaining_size;
1663         struct page *page;
1664
1665 retry:
1666         if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1667                 mutex_lock(&cc->bio_alloc_lock);
1668
1669         clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, &cc->bs);
1670         if (!clone)
1671                 goto out;
1672
1673         clone_init(io, clone);
1674
1675         remaining_size = size;
1676
1677         for (i = 0; i < nr_iovecs; i++) {
1678                 page = mempool_alloc(&cc->page_pool, gfp_mask);
1679                 if (!page) {
1680                         crypt_free_buffer_pages(cc, clone);
1681                         bio_put(clone);
1682                         gfp_mask |= __GFP_DIRECT_RECLAIM;
1683                         goto retry;
1684                 }
1685
1686                 len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
1687
1688                 bio_add_page(clone, page, len, 0);
1689
1690                 remaining_size -= len;
1691         }
1692
1693         /* Allocate space for integrity tags */
1694         if (dm_crypt_integrity_io_alloc(io, clone)) {
1695                 crypt_free_buffer_pages(cc, clone);
1696                 bio_put(clone);
1697                 clone = NULL;
1698         }
1699 out:
1700         if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1701                 mutex_unlock(&cc->bio_alloc_lock);
1702
1703         return clone;
1704 }
1705
1706 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1707 {
1708         struct bio_vec *bv;
1709         struct bvec_iter_all iter_all;
1710
1711         bio_for_each_segment_all(bv, clone, iter_all) {
1712                 BUG_ON(!bv->bv_page);
1713                 mempool_free(bv->bv_page, &cc->page_pool);
1714         }
1715 }
1716
1717 static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1718                           struct bio *bio, sector_t sector)
1719 {
1720         io->cc = cc;
1721         io->base_bio = bio;
1722         io->sector = sector;
1723         io->error = 0;
1724         io->ctx.r.req = NULL;
1725         io->integrity_metadata = NULL;
1726         io->integrity_metadata_from_pool = false;
1727         atomic_set(&io->io_pending, 0);
1728 }
1729
1730 static void crypt_inc_pending(struct dm_crypt_io *io)
1731 {
1732         atomic_inc(&io->io_pending);
1733 }
1734
1735 static void kcryptd_io_bio_endio(struct work_struct *work)
1736 {
1737         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1738         bio_endio(io->base_bio);
1739 }
1740
1741 /*
1742  * One of the bios was finished. Check for completion of
1743  * the whole request and correctly clean up the buffer.
1744  */
1745 static void crypt_dec_pending(struct dm_crypt_io *io)
1746 {
1747         struct crypt_config *cc = io->cc;
1748         struct bio *base_bio = io->base_bio;
1749         blk_status_t error = io->error;
1750
1751         if (!atomic_dec_and_test(&io->io_pending))
1752                 return;
1753
1754         if (io->ctx.r.req)
1755                 crypt_free_req(cc, io->ctx.r.req, base_bio);
1756
1757         if (unlikely(io->integrity_metadata_from_pool))
1758                 mempool_free(io->integrity_metadata, &io->cc->tag_pool);
1759         else
1760                 kfree(io->integrity_metadata);
1761
1762         base_bio->bi_status = error;
1763
1764         /*
1765          * If we are running this function from our tasklet,
1766          * we can't call bio_endio() here, because it will call
1767          * clone_endio() from dm.c, which in turn will
1768          * free the current struct dm_crypt_io structure with
1769          * our tasklet. In this case we need to delay bio_endio()
1770          * execution to after the tasklet is done and dequeued.
1771          */
1772         if (tasklet_trylock(&io->tasklet)) {
1773                 tasklet_unlock(&io->tasklet);
1774                 bio_endio(base_bio);
1775                 return;
1776         }
1777
1778         INIT_WORK(&io->work, kcryptd_io_bio_endio);
1779         queue_work(cc->io_queue, &io->work);
1780 }
1781
1782 /*
1783  * kcryptd/kcryptd_io:
1784  *
1785  * Needed because it would be very unwise to do decryption in an
1786  * interrupt context.
1787  *
1788  * kcryptd performs the actual encryption or decryption.
1789  *
1790  * kcryptd_io performs the IO submission.
1791  *
1792  * They must be separated as otherwise the final stages could be
1793  * starved by new requests which can block in the first stages due
1794  * to memory allocation.
1795  *
1796  * The work is done per CPU global for all dm-crypt instances.
1797  * They should not depend on each other and do not block.
1798  */
1799 static void crypt_endio(struct bio *clone)
1800 {
1801         struct dm_crypt_io *io = clone->bi_private;
1802         struct crypt_config *cc = io->cc;
1803         unsigned rw = bio_data_dir(clone);
1804         blk_status_t error;
1805
1806         /*
1807          * free the processed pages
1808          */
1809         if (rw == WRITE)
1810                 crypt_free_buffer_pages(cc, clone);
1811
1812         error = clone->bi_status;
1813         bio_put(clone);
1814
1815         if (rw == READ && !error) {
1816                 kcryptd_queue_crypt(io);
1817                 return;
1818         }
1819
1820         if (unlikely(error))
1821                 io->error = error;
1822
1823         crypt_dec_pending(io);
1824 }
1825
1826 static void clone_init(struct dm_crypt_io *io, struct bio *clone)
1827 {
1828         struct crypt_config *cc = io->cc;
1829
1830         clone->bi_private = io;
1831         clone->bi_end_io  = crypt_endio;
1832         bio_set_dev(clone, cc->dev->bdev);
1833         clone->bi_opf     = io->base_bio->bi_opf;
1834 }
1835
1836 static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
1837 {
1838         struct crypt_config *cc = io->cc;
1839         struct bio *clone;
1840
1841         /*
1842          * We need the original biovec array in order to decrypt
1843          * the whole bio data *afterwards* -- thanks to immutable
1844          * biovecs we don't need to worry about the block layer
1845          * modifying the biovec array; so leverage bio_clone_fast().
1846          */
1847         clone = bio_clone_fast(io->base_bio, gfp, &cc->bs);
1848         if (!clone)
1849                 return 1;
1850
1851         crypt_inc_pending(io);
1852
1853         clone_init(io, clone);
1854         clone->bi_iter.bi_sector = cc->start + io->sector;
1855
1856         if (dm_crypt_integrity_io_alloc(io, clone)) {
1857                 crypt_dec_pending(io);
1858                 bio_put(clone);
1859                 return 1;
1860         }
1861
1862         submit_bio_noacct(clone);
1863         return 0;
1864 }
1865
1866 static void kcryptd_io_read_work(struct work_struct *work)
1867 {
1868         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1869
1870         crypt_inc_pending(io);
1871         if (kcryptd_io_read(io, GFP_NOIO))
1872                 io->error = BLK_STS_RESOURCE;
1873         crypt_dec_pending(io);
1874 }
1875
1876 static void kcryptd_queue_read(struct dm_crypt_io *io)
1877 {
1878         struct crypt_config *cc = io->cc;
1879
1880         INIT_WORK(&io->work, kcryptd_io_read_work);
1881         queue_work(cc->io_queue, &io->work);
1882 }
1883
1884 static void kcryptd_io_write(struct dm_crypt_io *io)
1885 {
1886         struct bio *clone = io->ctx.bio_out;
1887
1888         submit_bio_noacct(clone);
1889 }
1890
1891 #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1892
1893 static int dmcrypt_write(void *data)
1894 {
1895         struct crypt_config *cc = data;
1896         struct dm_crypt_io *io;
1897
1898         while (1) {
1899                 struct rb_root write_tree;
1900                 struct blk_plug plug;
1901
1902                 spin_lock_irq(&cc->write_thread_lock);
1903 continue_locked:
1904
1905                 if (!RB_EMPTY_ROOT(&cc->write_tree))
1906                         goto pop_from_list;
1907
1908                 set_current_state(TASK_INTERRUPTIBLE);
1909
1910                 spin_unlock_irq(&cc->write_thread_lock);
1911
1912                 if (unlikely(kthread_should_stop())) {
1913                         set_current_state(TASK_RUNNING);
1914                         break;
1915                 }
1916
1917                 schedule();
1918
1919                 set_current_state(TASK_RUNNING);
1920                 spin_lock_irq(&cc->write_thread_lock);
1921                 goto continue_locked;
1922
1923 pop_from_list:
1924                 write_tree = cc->write_tree;
1925                 cc->write_tree = RB_ROOT;
1926                 spin_unlock_irq(&cc->write_thread_lock);
1927
1928                 BUG_ON(rb_parent(write_tree.rb_node));
1929
1930                 /*
1931                  * Note: we cannot walk the tree here with rb_next because
1932                  * the structures may be freed when kcryptd_io_write is called.
1933                  */
1934                 blk_start_plug(&plug);
1935                 do {
1936                         io = crypt_io_from_node(rb_first(&write_tree));
1937                         rb_erase(&io->rb_node, &write_tree);
1938                         kcryptd_io_write(io);
1939                 } while (!RB_EMPTY_ROOT(&write_tree));
1940                 blk_finish_plug(&plug);
1941         }
1942         return 0;
1943 }
1944
1945 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
1946 {
1947         struct bio *clone = io->ctx.bio_out;
1948         struct crypt_config *cc = io->cc;
1949         unsigned long flags;
1950         sector_t sector;
1951         struct rb_node **rbp, *parent;
1952
1953         if (unlikely(io->error)) {
1954                 crypt_free_buffer_pages(cc, clone);
1955                 bio_put(clone);
1956                 crypt_dec_pending(io);
1957                 return;
1958         }
1959
1960         /* crypt_convert should have filled the clone bio */
1961         BUG_ON(io->ctx.iter_out.bi_size);
1962
1963         clone->bi_iter.bi_sector = cc->start + io->sector;
1964
1965         if ((likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) ||
1966             test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags)) {
1967                 submit_bio_noacct(clone);
1968                 return;
1969         }
1970
1971         spin_lock_irqsave(&cc->write_thread_lock, flags);
1972         if (RB_EMPTY_ROOT(&cc->write_tree))
1973                 wake_up_process(cc->write_thread);
1974         rbp = &cc->write_tree.rb_node;
1975         parent = NULL;
1976         sector = io->sector;
1977         while (*rbp) {
1978                 parent = *rbp;
1979                 if (sector < crypt_io_from_node(parent)->sector)
1980                         rbp = &(*rbp)->rb_left;
1981                 else
1982                         rbp = &(*rbp)->rb_right;
1983         }
1984         rb_link_node(&io->rb_node, parent, rbp);
1985         rb_insert_color(&io->rb_node, &cc->write_tree);
1986         spin_unlock_irqrestore(&cc->write_thread_lock, flags);
1987 }
1988
1989 static bool kcryptd_crypt_write_inline(struct crypt_config *cc,
1990                                        struct convert_context *ctx)
1991
1992 {
1993         if (!test_bit(DM_CRYPT_WRITE_INLINE, &cc->flags))
1994                 return false;
1995
1996         /*
1997          * Note: zone append writes (REQ_OP_ZONE_APPEND) do not have ordering
1998          * constraints so they do not need to be issued inline by
1999          * kcryptd_crypt_write_convert().
2000          */
2001         switch (bio_op(ctx->bio_in)) {
2002         case REQ_OP_WRITE:
2003         case REQ_OP_WRITE_SAME:
2004         case REQ_OP_WRITE_ZEROES:
2005                 return true;
2006         default:
2007                 return false;
2008         }
2009 }
2010
2011 static void kcryptd_crypt_write_continue(struct work_struct *work)
2012 {
2013         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2014         struct crypt_config *cc = io->cc;
2015         struct convert_context *ctx = &io->ctx;
2016         int crypt_finished;
2017         sector_t sector = io->sector;
2018         blk_status_t r;
2019
2020         wait_for_completion(&ctx->restart);
2021         reinit_completion(&ctx->restart);
2022
2023         r = crypt_convert(cc, &io->ctx, true, false);
2024         if (r)
2025                 io->error = r;
2026         crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
2027         if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
2028                 /* Wait for completion signaled by kcryptd_async_done() */
2029                 wait_for_completion(&ctx->restart);
2030                 crypt_finished = 1;
2031         }
2032
2033         /* Encryption was already finished, submit io now */
2034         if (crypt_finished) {
2035                 kcryptd_crypt_write_io_submit(io, 0);
2036                 io->sector = sector;
2037         }
2038
2039         crypt_dec_pending(io);
2040 }
2041
2042 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
2043 {
2044         struct crypt_config *cc = io->cc;
2045         struct convert_context *ctx = &io->ctx;
2046         struct bio *clone;
2047         int crypt_finished;
2048         sector_t sector = io->sector;
2049         blk_status_t r;
2050
2051         /*
2052          * Prevent io from disappearing until this function completes.
2053          */
2054         crypt_inc_pending(io);
2055         crypt_convert_init(cc, ctx, NULL, io->base_bio, sector);
2056
2057         clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
2058         if (unlikely(!clone)) {
2059                 io->error = BLK_STS_IOERR;
2060                 goto dec;
2061         }
2062
2063         io->ctx.bio_out = clone;
2064         io->ctx.iter_out = clone->bi_iter;
2065
2066         sector += bio_sectors(clone);
2067
2068         crypt_inc_pending(io);
2069         r = crypt_convert(cc, ctx,
2070                           test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags), true);
2071         /*
2072          * Crypto API backlogged the request, because its queue was full
2073          * and we're in softirq context, so continue from a workqueue
2074          * (TODO: is it actually possible to be in softirq in the write path?)
2075          */
2076         if (r == BLK_STS_DEV_RESOURCE) {
2077                 INIT_WORK(&io->work, kcryptd_crypt_write_continue);
2078                 queue_work(cc->crypt_queue, &io->work);
2079                 return;
2080         }
2081         if (r)
2082                 io->error = r;
2083         crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
2084         if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
2085                 /* Wait for completion signaled by kcryptd_async_done() */
2086                 wait_for_completion(&ctx->restart);
2087                 crypt_finished = 1;
2088         }
2089
2090         /* Encryption was already finished, submit io now */
2091         if (crypt_finished) {
2092                 kcryptd_crypt_write_io_submit(io, 0);
2093                 io->sector = sector;
2094         }
2095
2096 dec:
2097         crypt_dec_pending(io);
2098 }
2099
2100 static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
2101 {
2102         crypt_dec_pending(io);
2103 }
2104
2105 static void kcryptd_crypt_read_continue(struct work_struct *work)
2106 {
2107         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2108         struct crypt_config *cc = io->cc;
2109         blk_status_t r;
2110
2111         wait_for_completion(&io->ctx.restart);
2112         reinit_completion(&io->ctx.restart);
2113
2114         r = crypt_convert(cc, &io->ctx, true, false);
2115         if (r)
2116                 io->error = r;
2117
2118         if (atomic_dec_and_test(&io->ctx.cc_pending))
2119                 kcryptd_crypt_read_done(io);
2120
2121         crypt_dec_pending(io);
2122 }
2123
2124 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
2125 {
2126         struct crypt_config *cc = io->cc;
2127         blk_status_t r;
2128
2129         crypt_inc_pending(io);
2130
2131         crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
2132                            io->sector);
2133
2134         r = crypt_convert(cc, &io->ctx,
2135                           test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags), true);
2136         /*
2137          * Crypto API backlogged the request, because its queue was full
2138          * and we're in softirq context, so continue from a workqueue
2139          */
2140         if (r == BLK_STS_DEV_RESOURCE) {
2141                 INIT_WORK(&io->work, kcryptd_crypt_read_continue);
2142                 queue_work(cc->crypt_queue, &io->work);
2143                 return;
2144         }
2145         if (r)
2146                 io->error = r;
2147
2148         if (atomic_dec_and_test(&io->ctx.cc_pending))
2149                 kcryptd_crypt_read_done(io);
2150
2151         crypt_dec_pending(io);
2152 }
2153
2154 static void kcryptd_async_done(struct crypto_async_request *async_req,
2155                                int error)
2156 {
2157         struct dm_crypt_request *dmreq = async_req->data;
2158         struct convert_context *ctx = dmreq->ctx;
2159         struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
2160         struct crypt_config *cc = io->cc;
2161
2162         /*
2163          * A request from crypto driver backlog is going to be processed now,
2164          * finish the completion and continue in crypt_convert().
2165          * (Callback will be called for the second time for this request.)
2166          */
2167         if (error == -EINPROGRESS) {
2168                 complete(&ctx->restart);
2169                 return;
2170         }
2171
2172         if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
2173                 error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
2174
2175         if (error == -EBADMSG) {
2176                 char b[BDEVNAME_SIZE];
2177                 DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx->bio_in, b),
2178                             (unsigned long long)le64_to_cpu(*org_sector_of_dmreq(cc, dmreq)));
2179                 io->error = BLK_STS_PROTECTION;
2180         } else if (error < 0)
2181                 io->error = BLK_STS_IOERR;
2182
2183         crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
2184
2185         if (!atomic_dec_and_test(&ctx->cc_pending))
2186                 return;
2187
2188         /*
2189          * The request is fully completed: for inline writes, let
2190          * kcryptd_crypt_write_convert() do the IO submission.
2191          */
2192         if (bio_data_dir(io->base_bio) == READ) {
2193                 kcryptd_crypt_read_done(io);
2194                 return;
2195         }
2196
2197         if (kcryptd_crypt_write_inline(cc, ctx)) {
2198                 complete(&ctx->restart);
2199                 return;
2200         }
2201
2202         kcryptd_crypt_write_io_submit(io, 1);
2203 }
2204
2205 static void kcryptd_crypt(struct work_struct *work)
2206 {
2207         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2208
2209         if (bio_data_dir(io->base_bio) == READ)
2210                 kcryptd_crypt_read_convert(io);
2211         else
2212                 kcryptd_crypt_write_convert(io);
2213 }
2214
2215 static void kcryptd_crypt_tasklet(unsigned long work)
2216 {
2217         kcryptd_crypt((struct work_struct *)work);
2218 }
2219
2220 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
2221 {
2222         struct crypt_config *cc = io->cc;
2223
2224         if ((bio_data_dir(io->base_bio) == READ && test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags)) ||
2225             (bio_data_dir(io->base_bio) == WRITE && test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))) {
2226                 /*
2227                  * in_hardirq(): Crypto API's skcipher_walk_first() refuses to work in hard IRQ context.
2228                  * irqs_disabled(): the kernel may run some IO completion from the idle thread, but
2229                  * it is being executed with irqs disabled.
2230                  */
2231                 if (in_hardirq() || irqs_disabled()) {
2232                         tasklet_init(&io->tasklet, kcryptd_crypt_tasklet, (unsigned long)&io->work);
2233                         tasklet_schedule(&io->tasklet);
2234                         return;
2235                 }
2236
2237                 kcryptd_crypt(&io->work);
2238                 return;
2239         }
2240
2241         INIT_WORK(&io->work, kcryptd_crypt);
2242         queue_work(cc->crypt_queue, &io->work);
2243 }
2244
2245 static void crypt_free_tfms_aead(struct crypt_config *cc)
2246 {
2247         if (!cc->cipher_tfm.tfms_aead)
2248                 return;
2249
2250         if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2251                 crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
2252                 cc->cipher_tfm.tfms_aead[0] = NULL;
2253         }
2254
2255         kfree(cc->cipher_tfm.tfms_aead);
2256         cc->cipher_tfm.tfms_aead = NULL;
2257 }
2258
2259 static void crypt_free_tfms_skcipher(struct crypt_config *cc)
2260 {
2261         unsigned i;
2262
2263         if (!cc->cipher_tfm.tfms)
2264                 return;
2265
2266         for (i = 0; i < cc->tfms_count; i++)
2267                 if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
2268                         crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
2269                         cc->cipher_tfm.tfms[i] = NULL;
2270                 }
2271
2272         kfree(cc->cipher_tfm.tfms);
2273         cc->cipher_tfm.tfms = NULL;
2274 }
2275
2276 static void crypt_free_tfms(struct crypt_config *cc)
2277 {
2278         if (crypt_integrity_aead(cc))
2279                 crypt_free_tfms_aead(cc);
2280         else
2281                 crypt_free_tfms_skcipher(cc);
2282 }
2283
2284 static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
2285 {
2286         unsigned i;
2287         int err;
2288
2289         cc->cipher_tfm.tfms = kcalloc(cc->tfms_count,
2290                                       sizeof(struct crypto_skcipher *),
2291                                       GFP_KERNEL);
2292         if (!cc->cipher_tfm.tfms)
2293                 return -ENOMEM;
2294
2295         for (i = 0; i < cc->tfms_count; i++) {
2296                 cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0,
2297                                                 CRYPTO_ALG_ALLOCATES_MEMORY);
2298                 if (IS_ERR(cc->cipher_tfm.tfms[i])) {
2299                         err = PTR_ERR(cc->cipher_tfm.tfms[i]);
2300                         crypt_free_tfms(cc);
2301                         return err;
2302                 }
2303         }
2304
2305         /*
2306          * dm-crypt performance can vary greatly depending on which crypto
2307          * algorithm implementation is used.  Help people debug performance
2308          * problems by logging the ->cra_driver_name.
2309          */
2310         DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2311                crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
2312         return 0;
2313 }
2314
2315 static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
2316 {
2317         int err;
2318
2319         cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
2320         if (!cc->cipher_tfm.tfms)
2321                 return -ENOMEM;
2322
2323         cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0,
2324                                                 CRYPTO_ALG_ALLOCATES_MEMORY);
2325         if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2326                 err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
2327                 crypt_free_tfms(cc);
2328                 return err;
2329         }
2330
2331         DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2332                crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
2333         return 0;
2334 }
2335
2336 static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
2337 {
2338         if (crypt_integrity_aead(cc))
2339                 return crypt_alloc_tfms_aead(cc, ciphermode);
2340         else
2341                 return crypt_alloc_tfms_skcipher(cc, ciphermode);
2342 }
2343
2344 static unsigned crypt_subkey_size(struct crypt_config *cc)
2345 {
2346         return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
2347 }
2348
2349 static unsigned crypt_authenckey_size(struct crypt_config *cc)
2350 {
2351         return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
2352 }
2353
2354 /*
2355  * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
2356  * the key must be for some reason in special format.
2357  * This funcion converts cc->key to this special format.
2358  */
2359 static void crypt_copy_authenckey(char *p, const void *key,
2360                                   unsigned enckeylen, unsigned authkeylen)
2361 {
2362         struct crypto_authenc_key_param *param;
2363         struct rtattr *rta;
2364
2365         rta = (struct rtattr *)p;
2366         param = RTA_DATA(rta);
2367         param->enckeylen = cpu_to_be32(enckeylen);
2368         rta->rta_len = RTA_LENGTH(sizeof(*param));
2369         rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
2370         p += RTA_SPACE(sizeof(*param));
2371         memcpy(p, key + enckeylen, authkeylen);
2372         p += authkeylen;
2373         memcpy(p, key, enckeylen);
2374 }
2375
2376 static int crypt_setkey(struct crypt_config *cc)
2377 {
2378         unsigned subkey_size;
2379         int err = 0, i, r;
2380
2381         /* Ignore extra keys (which are used for IV etc) */
2382         subkey_size = crypt_subkey_size(cc);
2383
2384         if (crypt_integrity_hmac(cc)) {
2385                 if (subkey_size < cc->key_mac_size)
2386                         return -EINVAL;
2387
2388                 crypt_copy_authenckey(cc->authenc_key, cc->key,
2389                                       subkey_size - cc->key_mac_size,
2390                                       cc->key_mac_size);
2391         }
2392
2393         for (i = 0; i < cc->tfms_count; i++) {
2394                 if (crypt_integrity_hmac(cc))
2395                         r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2396                                 cc->authenc_key, crypt_authenckey_size(cc));
2397                 else if (crypt_integrity_aead(cc))
2398                         r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2399                                                cc->key + (i * subkey_size),
2400                                                subkey_size);
2401                 else
2402                         r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
2403                                                    cc->key + (i * subkey_size),
2404                                                    subkey_size);
2405                 if (r)
2406                         err = r;
2407         }
2408
2409         if (crypt_integrity_hmac(cc))
2410                 memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
2411
2412         return err;
2413 }
2414
2415 #ifdef CONFIG_KEYS
2416
2417 static bool contains_whitespace(const char *str)
2418 {
2419         while (*str)
2420                 if (isspace(*str++))
2421                         return true;
2422         return false;
2423 }
2424
2425 static int set_key_user(struct crypt_config *cc, struct key *key)
2426 {
2427         const struct user_key_payload *ukp;
2428
2429         ukp = user_key_payload_locked(key);
2430         if (!ukp)
2431                 return -EKEYREVOKED;
2432
2433         if (cc->key_size != ukp->datalen)
2434                 return -EINVAL;
2435
2436         memcpy(cc->key, ukp->data, cc->key_size);
2437
2438         return 0;
2439 }
2440
2441 static int set_key_encrypted(struct crypt_config *cc, struct key *key)
2442 {
2443         const struct encrypted_key_payload *ekp;
2444
2445         ekp = key->payload.data[0];
2446         if (!ekp)
2447                 return -EKEYREVOKED;
2448
2449         if (cc->key_size != ekp->decrypted_datalen)
2450                 return -EINVAL;
2451
2452         memcpy(cc->key, ekp->decrypted_data, cc->key_size);
2453
2454         return 0;
2455 }
2456
2457 static int set_key_trusted(struct crypt_config *cc, struct key *key)
2458 {
2459         const struct trusted_key_payload *tkp;
2460
2461         tkp = key->payload.data[0];
2462         if (!tkp)
2463                 return -EKEYREVOKED;
2464
2465         if (cc->key_size != tkp->key_len)
2466                 return -EINVAL;
2467
2468         memcpy(cc->key, tkp->key, cc->key_size);
2469
2470         return 0;
2471 }
2472
2473 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2474 {
2475         char *new_key_string, *key_desc;
2476         int ret;
2477         struct key_type *type;
2478         struct key *key;
2479         int (*set_key)(struct crypt_config *cc, struct key *key);
2480
2481         /*
2482          * Reject key_string with whitespace. dm core currently lacks code for
2483          * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2484          */
2485         if (contains_whitespace(key_string)) {
2486                 DMERR("whitespace chars not allowed in key string");
2487                 return -EINVAL;
2488         }
2489
2490         /* look for next ':' separating key_type from key_description */
2491         key_desc = strpbrk(key_string, ":");
2492         if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2493                 return -EINVAL;
2494
2495         if (!strncmp(key_string, "logon:", key_desc - key_string + 1)) {
2496                 type = &key_type_logon;
2497                 set_key = set_key_user;
2498         } else if (!strncmp(key_string, "user:", key_desc - key_string + 1)) {
2499                 type = &key_type_user;
2500                 set_key = set_key_user;
2501         } else if (IS_ENABLED(CONFIG_ENCRYPTED_KEYS) &&
2502                    !strncmp(key_string, "encrypted:", key_desc - key_string + 1)) {
2503                 type = &key_type_encrypted;
2504                 set_key = set_key_encrypted;
2505         } else if (IS_ENABLED(CONFIG_TRUSTED_KEYS) &&
2506                    !strncmp(key_string, "trusted:", key_desc - key_string + 1)) {
2507                 type = &key_type_trusted;
2508                 set_key = set_key_trusted;
2509         } else {
2510                 return -EINVAL;
2511         }
2512
2513         new_key_string = kstrdup(key_string, GFP_KERNEL);
2514         if (!new_key_string)
2515                 return -ENOMEM;
2516
2517         key = request_key(type, key_desc + 1, NULL);
2518         if (IS_ERR(key)) {
2519                 kfree_sensitive(new_key_string);
2520                 return PTR_ERR(key);
2521         }
2522
2523         down_read(&key->sem);
2524
2525         ret = set_key(cc, key);
2526         if (ret < 0) {
2527                 up_read(&key->sem);
2528                 key_put(key);
2529                 kfree_sensitive(new_key_string);
2530                 return ret;
2531         }
2532
2533         up_read(&key->sem);
2534         key_put(key);
2535
2536         /* clear the flag since following operations may invalidate previously valid key */
2537         clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2538
2539         ret = crypt_setkey(cc);
2540
2541         if (!ret) {
2542                 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2543                 kfree_sensitive(cc->key_string);
2544                 cc->key_string = new_key_string;
2545         } else
2546                 kfree_sensitive(new_key_string);
2547
2548         return ret;
2549 }
2550
2551 static int get_key_size(char **key_string)
2552 {
2553         char *colon, dummy;
2554         int ret;
2555
2556         if (*key_string[0] != ':')
2557                 return strlen(*key_string) >> 1;
2558
2559         /* look for next ':' in key string */
2560         colon = strpbrk(*key_string + 1, ":");
2561         if (!colon)
2562                 return -EINVAL;
2563
2564         if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2565                 return -EINVAL;
2566
2567         *key_string = colon;
2568
2569         /* remaining key string should be :<logon|user>:<key_desc> */
2570
2571         return ret;
2572 }
2573
2574 #else
2575
2576 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2577 {
2578         return -EINVAL;
2579 }
2580
2581 static int get_key_size(char **key_string)
2582 {
2583         return (*key_string[0] == ':') ? -EINVAL : strlen(*key_string) >> 1;
2584 }
2585
2586 #endif /* CONFIG_KEYS */
2587
2588 static int crypt_set_key(struct crypt_config *cc, char *key)
2589 {
2590         int r = -EINVAL;
2591         int key_string_len = strlen(key);
2592
2593         /* Hyphen (which gives a key_size of zero) means there is no key. */
2594         if (!cc->key_size && strcmp(key, "-"))
2595                 goto out;
2596
2597         /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2598         if (key[0] == ':') {
2599                 r = crypt_set_keyring_key(cc, key + 1);
2600                 goto out;
2601         }
2602
2603         /* clear the flag since following operations may invalidate previously valid key */
2604         clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2605
2606         /* wipe references to any kernel keyring key */
2607         kfree_sensitive(cc->key_string);
2608         cc->key_string = NULL;
2609
2610         /* Decode key from its hex representation. */
2611         if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
2612                 goto out;
2613
2614         r = crypt_setkey(cc);
2615         if (!r)
2616                 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2617
2618 out:
2619         /* Hex key string not needed after here, so wipe it. */
2620         memset(key, '0', key_string_len);
2621
2622         return r;
2623 }
2624
2625 static int crypt_wipe_key(struct crypt_config *cc)
2626 {
2627         int r;
2628
2629         clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2630         get_random_bytes(&cc->key, cc->key_size);
2631
2632         /* Wipe IV private keys */
2633         if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
2634                 r = cc->iv_gen_ops->wipe(cc);
2635                 if (r)
2636                         return r;
2637         }
2638
2639         kfree_sensitive(cc->key_string);
2640         cc->key_string = NULL;
2641         r = crypt_setkey(cc);
2642         memset(&cc->key, 0, cc->key_size * sizeof(u8));
2643
2644         return r;
2645 }
2646
2647 static void crypt_calculate_pages_per_client(void)
2648 {
2649         unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
2650
2651         if (!dm_crypt_clients_n)
2652                 return;
2653
2654         pages /= dm_crypt_clients_n;
2655         if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
2656                 pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
2657         dm_crypt_pages_per_client = pages;
2658 }
2659
2660 static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
2661 {
2662         struct crypt_config *cc = pool_data;
2663         struct page *page;
2664
2665         /*
2666          * Note, percpu_counter_read_positive() may over (and under) estimate
2667          * the current usage by at most (batch - 1) * num_online_cpus() pages,
2668          * but avoids potential spinlock contention of an exact result.
2669          */
2670         if (unlikely(percpu_counter_read_positive(&cc->n_allocated_pages) >= dm_crypt_pages_per_client) &&
2671             likely(gfp_mask & __GFP_NORETRY))
2672                 return NULL;
2673
2674         page = alloc_page(gfp_mask);
2675         if (likely(page != NULL))
2676                 percpu_counter_add(&cc->n_allocated_pages, 1);
2677
2678         return page;
2679 }
2680
2681 static void crypt_page_free(void *page, void *pool_data)
2682 {
2683         struct crypt_config *cc = pool_data;
2684
2685         __free_page(page);
2686         percpu_counter_sub(&cc->n_allocated_pages, 1);
2687 }
2688
2689 static void crypt_dtr(struct dm_target *ti)
2690 {
2691         struct crypt_config *cc = ti->private;
2692
2693         ti->private = NULL;
2694
2695         if (!cc)
2696                 return;
2697
2698         if (cc->write_thread)
2699                 kthread_stop(cc->write_thread);
2700
2701         if (cc->io_queue)
2702                 destroy_workqueue(cc->io_queue);
2703         if (cc->crypt_queue)
2704                 destroy_workqueue(cc->crypt_queue);
2705
2706         crypt_free_tfms(cc);
2707
2708         bioset_exit(&cc->bs);
2709
2710         mempool_exit(&cc->page_pool);
2711         mempool_exit(&cc->req_pool);
2712         mempool_exit(&cc->tag_pool);
2713
2714         WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
2715         percpu_counter_destroy(&cc->n_allocated_pages);
2716
2717         if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
2718                 cc->iv_gen_ops->dtr(cc);
2719
2720         if (cc->dev)
2721                 dm_put_device(ti, cc->dev);
2722
2723         kfree_sensitive(cc->cipher_string);
2724         kfree_sensitive(cc->key_string);
2725         kfree_sensitive(cc->cipher_auth);
2726         kfree_sensitive(cc->authenc_key);
2727
2728         mutex_destroy(&cc->bio_alloc_lock);
2729
2730         /* Must zero key material before freeing */
2731         kfree_sensitive(cc);
2732
2733         spin_lock(&dm_crypt_clients_lock);
2734         WARN_ON(!dm_crypt_clients_n);
2735         dm_crypt_clients_n--;
2736         crypt_calculate_pages_per_client();
2737         spin_unlock(&dm_crypt_clients_lock);
2738 }
2739
2740 static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
2741 {
2742         struct crypt_config *cc = ti->private;
2743
2744         if (crypt_integrity_aead(cc))
2745                 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2746         else
2747                 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2748
2749         if (cc->iv_size)
2750                 /* at least a 64 bit sector number should fit in our buffer */
2751                 cc->iv_size = max(cc->iv_size,
2752                                   (unsigned int)(sizeof(u64) / sizeof(u8)));
2753         else if (ivmode) {
2754                 DMWARN("Selected cipher does not support IVs");
2755                 ivmode = NULL;
2756         }
2757
2758         /* Choose ivmode, see comments at iv code. */
2759         if (ivmode == NULL)
2760                 cc->iv_gen_ops = NULL;
2761         else if (strcmp(ivmode, "plain") == 0)
2762                 cc->iv_gen_ops = &crypt_iv_plain_ops;
2763         else if (strcmp(ivmode, "plain64") == 0)
2764                 cc->iv_gen_ops = &crypt_iv_plain64_ops;
2765         else if (strcmp(ivmode, "plain64be") == 0)
2766                 cc->iv_gen_ops = &crypt_iv_plain64be_ops;
2767         else if (strcmp(ivmode, "essiv") == 0)
2768                 cc->iv_gen_ops = &crypt_iv_essiv_ops;
2769         else if (strcmp(ivmode, "benbi") == 0)
2770                 cc->iv_gen_ops = &crypt_iv_benbi_ops;
2771         else if (strcmp(ivmode, "null") == 0)
2772                 cc->iv_gen_ops = &crypt_iv_null_ops;
2773         else if (strcmp(ivmode, "eboiv") == 0)
2774                 cc->iv_gen_ops = &crypt_iv_eboiv_ops;
2775         else if (strcmp(ivmode, "elephant") == 0) {
2776                 cc->iv_gen_ops = &crypt_iv_elephant_ops;
2777                 cc->key_parts = 2;
2778                 cc->key_extra_size = cc->key_size / 2;
2779                 if (cc->key_extra_size > ELEPHANT_MAX_KEY_SIZE)
2780                         return -EINVAL;
2781                 set_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags);
2782         } else if (strcmp(ivmode, "lmk") == 0) {
2783                 cc->iv_gen_ops = &crypt_iv_lmk_ops;
2784                 /*
2785                  * Version 2 and 3 is recognised according
2786                  * to length of provided multi-key string.
2787                  * If present (version 3), last key is used as IV seed.
2788                  * All keys (including IV seed) are always the same size.
2789                  */
2790                 if (cc->key_size % cc->key_parts) {
2791                         cc->key_parts++;
2792                         cc->key_extra_size = cc->key_size / cc->key_parts;
2793                 }
2794         } else if (strcmp(ivmode, "tcw") == 0) {
2795                 cc->iv_gen_ops = &crypt_iv_tcw_ops;
2796                 cc->key_parts += 2; /* IV + whitening */
2797                 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2798         } else if (strcmp(ivmode, "random") == 0) {
2799                 cc->iv_gen_ops = &crypt_iv_random_ops;
2800                 /* Need storage space in integrity fields. */
2801                 cc->integrity_iv_size = cc->iv_size;
2802         } else {
2803                 ti->error = "Invalid IV mode";
2804                 return -EINVAL;
2805         }
2806
2807         return 0;
2808 }
2809
2810 /*
2811  * Workaround to parse HMAC algorithm from AEAD crypto API spec.
2812  * The HMAC is needed to calculate tag size (HMAC digest size).
2813  * This should be probably done by crypto-api calls (once available...)
2814  */
2815 static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
2816 {
2817         char *start, *end, *mac_alg = NULL;
2818         struct crypto_ahash *mac;
2819
2820         if (!strstarts(cipher_api, "authenc("))
2821                 return 0;
2822
2823         start = strchr(cipher_api, '(');
2824         end = strchr(cipher_api, ',');
2825         if (!start || !end || ++start > end)
2826                 return -EINVAL;
2827
2828         mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
2829         if (!mac_alg)
2830                 return -ENOMEM;
2831         strncpy(mac_alg, start, end - start);
2832
2833         mac = crypto_alloc_ahash(mac_alg, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
2834         kfree(mac_alg);
2835
2836         if (IS_ERR(mac))
2837                 return PTR_ERR(mac);
2838
2839         cc->key_mac_size = crypto_ahash_digestsize(mac);
2840         crypto_free_ahash(mac);
2841
2842         cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
2843         if (!cc->authenc_key)
2844                 return -ENOMEM;
2845
2846         return 0;
2847 }
2848
2849 static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
2850                                 char **ivmode, char **ivopts)
2851 {
2852         struct crypt_config *cc = ti->private;
2853         char *tmp, *cipher_api, buf[CRYPTO_MAX_ALG_NAME];
2854         int ret = -EINVAL;
2855
2856         cc->tfms_count = 1;
2857
2858         /*
2859          * New format (capi: prefix)
2860          * capi:cipher_api_spec-iv:ivopts
2861          */
2862         tmp = &cipher_in[strlen("capi:")];
2863
2864         /* Separate IV options if present, it can contain another '-' in hash name */
2865         *ivopts = strrchr(tmp, ':');
2866         if (*ivopts) {
2867                 **ivopts = '\0';
2868                 (*ivopts)++;
2869         }
2870         /* Parse IV mode */
2871         *ivmode = strrchr(tmp, '-');
2872         if (*ivmode) {
2873                 **ivmode = '\0';
2874                 (*ivmode)++;
2875         }
2876         /* The rest is crypto API spec */
2877         cipher_api = tmp;
2878
2879         /* Alloc AEAD, can be used only in new format. */
2880         if (crypt_integrity_aead(cc)) {
2881                 ret = crypt_ctr_auth_cipher(cc, cipher_api);
2882                 if (ret < 0) {
2883                         ti->error = "Invalid AEAD cipher spec";
2884                         return -ENOMEM;
2885                 }
2886         }
2887
2888         if (*ivmode && !strcmp(*ivmode, "lmk"))
2889                 cc->tfms_count = 64;
2890
2891         if (*ivmode && !strcmp(*ivmode, "essiv")) {
2892                 if (!*ivopts) {
2893                         ti->error = "Digest algorithm missing for ESSIV mode";
2894                         return -EINVAL;
2895                 }
2896                 ret = snprintf(buf, CRYPTO_MAX_ALG_NAME, "essiv(%s,%s)",
2897                                cipher_api, *ivopts);
2898                 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2899                         ti->error = "Cannot allocate cipher string";
2900                         return -ENOMEM;
2901                 }
2902                 cipher_api = buf;
2903         }
2904
2905         cc->key_parts = cc->tfms_count;
2906
2907         /* Allocate cipher */
2908         ret = crypt_alloc_tfms(cc, cipher_api);
2909         if (ret < 0) {
2910                 ti->error = "Error allocating crypto tfm";
2911                 return ret;
2912         }
2913
2914         if (crypt_integrity_aead(cc))
2915                 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2916         else
2917                 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2918
2919         return 0;
2920 }
2921
2922 static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
2923                                 char **ivmode, char **ivopts)
2924 {
2925         struct crypt_config *cc = ti->private;
2926         char *tmp, *cipher, *chainmode, *keycount;
2927         char *cipher_api = NULL;
2928         int ret = -EINVAL;
2929         char dummy;
2930
2931         if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
2932                 ti->error = "Bad cipher specification";
2933                 return -EINVAL;
2934         }
2935
2936         /*
2937          * Legacy dm-crypt cipher specification
2938          * cipher[:keycount]-mode-iv:ivopts
2939          */
2940         tmp = cipher_in;
2941         keycount = strsep(&tmp, "-");
2942         cipher = strsep(&keycount, ":");
2943
2944         if (!keycount)
2945                 cc->tfms_count = 1;
2946         else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
2947                  !is_power_of_2(cc->tfms_count)) {
2948                 ti->error = "Bad cipher key count specification";
2949                 return -EINVAL;
2950         }
2951         cc->key_parts = cc->tfms_count;
2952
2953         chainmode = strsep(&tmp, "-");
2954         *ivmode = strsep(&tmp, ":");
2955         *ivopts = tmp;
2956
2957         /*
2958          * For compatibility with the original dm-crypt mapping format, if
2959          * only the cipher name is supplied, use cbc-plain.
2960          */
2961         if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
2962                 chainmode = "cbc";
2963                 *ivmode = "plain";
2964         }
2965
2966         if (strcmp(chainmode, "ecb") && !*ivmode) {
2967                 ti->error = "IV mechanism required";
2968                 return -EINVAL;
2969         }
2970
2971         cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
2972         if (!cipher_api)
2973                 goto bad_mem;
2974
2975         if (*ivmode && !strcmp(*ivmode, "essiv")) {
2976                 if (!*ivopts) {
2977                         ti->error = "Digest algorithm missing for ESSIV mode";
2978                         kfree(cipher_api);
2979                         return -EINVAL;
2980                 }
2981                 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2982                                "essiv(%s(%s),%s)", chainmode, cipher, *ivopts);
2983         } else {
2984                 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2985                                "%s(%s)", chainmode, cipher);
2986         }
2987         if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2988                 kfree(cipher_api);
2989                 goto bad_mem;
2990         }
2991
2992         /* Allocate cipher */
2993         ret = crypt_alloc_tfms(cc, cipher_api);
2994         if (ret < 0) {
2995                 ti->error = "Error allocating crypto tfm";
2996                 kfree(cipher_api);
2997                 return ret;
2998         }
2999         kfree(cipher_api);
3000
3001         return 0;
3002 bad_mem:
3003         ti->error = "Cannot allocate cipher strings";
3004         return -ENOMEM;
3005 }
3006
3007 static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
3008 {
3009         struct crypt_config *cc = ti->private;
3010         char *ivmode = NULL, *ivopts = NULL;
3011         int ret;
3012
3013         cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
3014         if (!cc->cipher_string) {
3015                 ti->error = "Cannot allocate cipher strings";
3016                 return -ENOMEM;
3017         }
3018
3019         if (strstarts(cipher_in, "capi:"))
3020                 ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
3021         else
3022                 ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
3023         if (ret)
3024                 return ret;
3025
3026         /* Initialize IV */
3027         ret = crypt_ctr_ivmode(ti, ivmode);
3028         if (ret < 0)
3029                 return ret;
3030
3031         /* Initialize and set key */
3032         ret = crypt_set_key(cc, key);
3033         if (ret < 0) {
3034                 ti->error = "Error decoding and setting key";
3035                 return ret;
3036         }
3037
3038         /* Allocate IV */
3039         if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
3040                 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
3041                 if (ret < 0) {
3042                         ti->error = "Error creating IV";
3043                         return ret;
3044                 }
3045         }
3046
3047         /* Initialize IV (set keys for ESSIV etc) */
3048         if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
3049                 ret = cc->iv_gen_ops->init(cc);
3050                 if (ret < 0) {
3051                         ti->error = "Error initialising IV";
3052                         return ret;
3053                 }
3054         }
3055
3056         /* wipe the kernel key payload copy */
3057         if (cc->key_string)
3058                 memset(cc->key, 0, cc->key_size * sizeof(u8));
3059
3060         return ret;
3061 }
3062
3063 static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
3064 {
3065         struct crypt_config *cc = ti->private;
3066         struct dm_arg_set as;
3067         static const struct dm_arg _args[] = {
3068                 {0, 8, "Invalid number of feature args"},
3069         };
3070         unsigned int opt_params, val;
3071         const char *opt_string, *sval;
3072         char dummy;
3073         int ret;
3074
3075         /* Optional parameters */
3076         as.argc = argc;
3077         as.argv = argv;
3078
3079         ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
3080         if (ret)
3081                 return ret;
3082
3083         while (opt_params--) {
3084                 opt_string = dm_shift_arg(&as);
3085                 if (!opt_string) {
3086                         ti->error = "Not enough feature arguments";
3087                         return -EINVAL;
3088                 }
3089
3090                 if (!strcasecmp(opt_string, "allow_discards"))
3091                         ti->num_discard_bios = 1;
3092
3093                 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
3094                         set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3095
3096                 else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
3097                         set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3098                 else if (!strcasecmp(opt_string, "no_read_workqueue"))
3099                         set_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3100                 else if (!strcasecmp(opt_string, "no_write_workqueue"))
3101                         set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3102                 else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
3103                         if (val == 0 || val > MAX_TAG_SIZE) {
3104                                 ti->error = "Invalid integrity arguments";
3105                                 return -EINVAL;
3106                         }
3107                         cc->on_disk_tag_size = val;
3108                         sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
3109                         if (!strcasecmp(sval, "aead")) {
3110                                 set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
3111                         } else  if (strcasecmp(sval, "none")) {
3112                                 ti->error = "Unknown integrity profile";
3113                                 return -EINVAL;
3114                         }
3115
3116                         cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
3117                         if (!cc->cipher_auth)
3118                                 return -ENOMEM;
3119                 } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
3120                         if (cc->sector_size < (1 << SECTOR_SHIFT) ||
3121                             cc->sector_size > 4096 ||
3122                             (cc->sector_size & (cc->sector_size - 1))) {
3123                                 ti->error = "Invalid feature value for sector_size";
3124                                 return -EINVAL;
3125                         }
3126                         if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
3127                                 ti->error = "Device size is not multiple of sector_size feature";
3128                                 return -EINVAL;
3129                         }
3130                         cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
3131                 } else if (!strcasecmp(opt_string, "iv_large_sectors"))
3132                         set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3133                 else {
3134                         ti->error = "Invalid feature arguments";
3135                         return -EINVAL;
3136                 }
3137         }
3138
3139         return 0;
3140 }
3141
3142 #ifdef CONFIG_BLK_DEV_ZONED
3143 static int crypt_report_zones(struct dm_target *ti,
3144                 struct dm_report_zones_args *args, unsigned int nr_zones)
3145 {
3146         struct crypt_config *cc = ti->private;
3147
3148         return dm_report_zones(cc->dev->bdev, cc->start,
3149                         cc->start + dm_target_offset(ti, args->next_sector),
3150                         args, nr_zones);
3151 }
3152 #else
3153 #define crypt_report_zones NULL
3154 #endif
3155
3156 /*
3157  * Construct an encryption mapping:
3158  * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
3159  */
3160 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
3161 {
3162         struct crypt_config *cc;
3163         const char *devname = dm_table_device_name(ti->table);
3164         int key_size;
3165         unsigned int align_mask;
3166         unsigned long long tmpll;
3167         int ret;
3168         size_t iv_size_padding, additional_req_size;
3169         char dummy;
3170
3171         if (argc < 5) {
3172                 ti->error = "Not enough arguments";
3173                 return -EINVAL;
3174         }
3175
3176         key_size = get_key_size(&argv[1]);
3177         if (key_size < 0) {
3178                 ti->error = "Cannot parse key size";
3179                 return -EINVAL;
3180         }
3181
3182         cc = kzalloc(struct_size(cc, key, key_size), GFP_KERNEL);
3183         if (!cc) {
3184                 ti->error = "Cannot allocate encryption context";
3185                 return -ENOMEM;
3186         }
3187         cc->key_size = key_size;
3188         cc->sector_size = (1 << SECTOR_SHIFT);
3189         cc->sector_shift = 0;
3190
3191         ti->private = cc;
3192
3193         spin_lock(&dm_crypt_clients_lock);
3194         dm_crypt_clients_n++;
3195         crypt_calculate_pages_per_client();
3196         spin_unlock(&dm_crypt_clients_lock);
3197
3198         ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
3199         if (ret < 0)
3200                 goto bad;
3201
3202         /* Optional parameters need to be read before cipher constructor */
3203         if (argc > 5) {
3204                 ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
3205                 if (ret)
3206                         goto bad;
3207         }
3208
3209         ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
3210         if (ret < 0)
3211                 goto bad;
3212
3213         if (crypt_integrity_aead(cc)) {
3214                 cc->dmreq_start = sizeof(struct aead_request);
3215                 cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
3216                 align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
3217         } else {
3218                 cc->dmreq_start = sizeof(struct skcipher_request);
3219                 cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
3220                 align_mask = crypto_skcipher_alignmask(any_tfm(cc));
3221         }
3222         cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
3223
3224         if (align_mask < CRYPTO_MINALIGN) {
3225                 /* Allocate the padding exactly */
3226                 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
3227                                 & align_mask;
3228         } else {
3229                 /*
3230                  * If the cipher requires greater alignment than kmalloc
3231                  * alignment, we don't know the exact position of the
3232                  * initialization vector. We must assume worst case.
3233                  */
3234                 iv_size_padding = align_mask;
3235         }
3236
3237         /*  ...| IV + padding | original IV | original sec. number | bio tag offset | */
3238         additional_req_size = sizeof(struct dm_crypt_request) +
3239                 iv_size_padding + cc->iv_size +
3240                 cc->iv_size +
3241                 sizeof(uint64_t) +
3242                 sizeof(unsigned int);
3243
3244         ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
3245         if (ret) {
3246                 ti->error = "Cannot allocate crypt request mempool";
3247                 goto bad;
3248         }
3249
3250         cc->per_bio_data_size = ti->per_io_data_size =
3251                 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
3252                       ARCH_KMALLOC_MINALIGN);
3253
3254         ret = mempool_init(&cc->page_pool, BIO_MAX_VECS, crypt_page_alloc, crypt_page_free, cc);
3255         if (ret) {
3256                 ti->error = "Cannot allocate page mempool";
3257                 goto bad;
3258         }
3259
3260         ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
3261         if (ret) {
3262                 ti->error = "Cannot allocate crypt bioset";
3263                 goto bad;
3264         }
3265
3266         mutex_init(&cc->bio_alloc_lock);
3267
3268         ret = -EINVAL;
3269         if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
3270             (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
3271                 ti->error = "Invalid iv_offset sector";
3272                 goto bad;
3273         }
3274         cc->iv_offset = tmpll;
3275
3276         ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
3277         if (ret) {
3278                 ti->error = "Device lookup failed";
3279                 goto bad;
3280         }
3281
3282         ret = -EINVAL;
3283         if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
3284                 ti->error = "Invalid device sector";
3285                 goto bad;
3286         }
3287         cc->start = tmpll;
3288
3289         if (bdev_is_zoned(cc->dev->bdev)) {
3290                 /*
3291                  * For zoned block devices, we need to preserve the issuer write
3292                  * ordering. To do so, disable write workqueues and force inline
3293                  * encryption completion.
3294                  */
3295                 set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3296                 set_bit(DM_CRYPT_WRITE_INLINE, &cc->flags);
3297
3298                 /*
3299                  * All zone append writes to a zone of a zoned block device will
3300                  * have the same BIO sector, the start of the zone. When the
3301                  * cypher IV mode uses sector values, all data targeting a
3302                  * zone will be encrypted using the first sector numbers of the
3303                  * zone. This will not result in write errors but will
3304                  * cause most reads to fail as reads will use the sector values
3305                  * for the actual data locations, resulting in IV mismatch.
3306                  * To avoid this problem, ask DM core to emulate zone append
3307                  * operations with regular writes.
3308                  */
3309                 DMDEBUG("Zone append operations will be emulated");
3310                 ti->emulate_zone_append = true;
3311         }
3312
3313         if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
3314                 ret = crypt_integrity_ctr(cc, ti);
3315                 if (ret)
3316                         goto bad;
3317
3318                 cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
3319                 if (!cc->tag_pool_max_sectors)
3320                         cc->tag_pool_max_sectors = 1;
3321
3322                 ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
3323                         cc->tag_pool_max_sectors * cc->on_disk_tag_size);
3324                 if (ret) {
3325                         ti->error = "Cannot allocate integrity tags mempool";
3326                         goto bad;
3327                 }
3328
3329                 cc->tag_pool_max_sectors <<= cc->sector_shift;
3330         }
3331
3332         ret = -ENOMEM;
3333         cc->io_queue = alloc_workqueue("kcryptd_io/%s", WQ_MEM_RECLAIM, 1, devname);
3334         if (!cc->io_queue) {
3335                 ti->error = "Couldn't create kcryptd io queue";
3336                 goto bad;
3337         }
3338
3339         if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3340                 cc->crypt_queue = alloc_workqueue("kcryptd/%s", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM,
3341                                                   1, devname);
3342         else
3343                 cc->crypt_queue = alloc_workqueue("kcryptd/%s",
3344                                                   WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
3345                                                   num_online_cpus(), devname);
3346         if (!cc->crypt_queue) {
3347                 ti->error = "Couldn't create kcryptd queue";
3348                 goto bad;
3349         }
3350
3351         spin_lock_init(&cc->write_thread_lock);
3352         cc->write_tree = RB_ROOT;
3353
3354         cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
3355         if (IS_ERR(cc->write_thread)) {
3356                 ret = PTR_ERR(cc->write_thread);
3357                 cc->write_thread = NULL;
3358                 ti->error = "Couldn't spawn write thread";
3359                 goto bad;
3360         }
3361         wake_up_process(cc->write_thread);
3362
3363         ti->num_flush_bios = 1;
3364         ti->limit_swap_bios = true;
3365
3366         return 0;
3367
3368 bad:
3369         crypt_dtr(ti);
3370         return ret;
3371 }
3372
3373 static int crypt_map(struct dm_target *ti, struct bio *bio)
3374 {
3375         struct dm_crypt_io *io;
3376         struct crypt_config *cc = ti->private;
3377
3378         /*
3379          * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
3380          * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
3381          * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
3382          */
3383         if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
3384             bio_op(bio) == REQ_OP_DISCARD)) {
3385                 bio_set_dev(bio, cc->dev->bdev);
3386                 if (bio_sectors(bio))
3387                         bio->bi_iter.bi_sector = cc->start +
3388                                 dm_target_offset(ti, bio->bi_iter.bi_sector);
3389                 return DM_MAPIO_REMAPPED;
3390         }
3391
3392         /*
3393          * Check if bio is too large, split as needed.
3394          */
3395         if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_VECS << PAGE_SHIFT)) &&
3396             (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
3397                 dm_accept_partial_bio(bio, ((BIO_MAX_VECS << PAGE_SHIFT) >> SECTOR_SHIFT));
3398
3399         /*
3400          * Ensure that bio is a multiple of internal sector encryption size
3401          * and is aligned to this size as defined in IO hints.
3402          */
3403         if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
3404                 return DM_MAPIO_KILL;
3405
3406         if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
3407                 return DM_MAPIO_KILL;
3408
3409         io = dm_per_bio_data(bio, cc->per_bio_data_size);
3410         crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
3411
3412         if (cc->on_disk_tag_size) {
3413                 unsigned tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
3414
3415                 if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
3416                     unlikely(!(io->integrity_metadata = kmalloc(tag_len,
3417                                 GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
3418                         if (bio_sectors(bio) > cc->tag_pool_max_sectors)
3419                                 dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
3420                         io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
3421                         io->integrity_metadata_from_pool = true;
3422                 }
3423         }
3424
3425         if (crypt_integrity_aead(cc))
3426                 io->ctx.r.req_aead = (struct aead_request *)(io + 1);
3427         else
3428                 io->ctx.r.req = (struct skcipher_request *)(io + 1);
3429
3430         if (bio_data_dir(io->base_bio) == READ) {
3431                 if (kcryptd_io_read(io, GFP_NOWAIT))
3432                         kcryptd_queue_read(io);
3433         } else
3434                 kcryptd_queue_crypt(io);
3435
3436         return DM_MAPIO_SUBMITTED;
3437 }
3438
3439 static void crypt_status(struct dm_target *ti, status_type_t type,
3440                          unsigned status_flags, char *result, unsigned maxlen)
3441 {
3442         struct crypt_config *cc = ti->private;
3443         unsigned i, sz = 0;
3444         int num_feature_args = 0;
3445
3446         switch (type) {
3447         case STATUSTYPE_INFO:
3448                 result[0] = '\0';
3449                 break;
3450
3451         case STATUSTYPE_TABLE:
3452                 DMEMIT("%s ", cc->cipher_string);
3453
3454                 if (cc->key_size > 0) {
3455                         if (cc->key_string)
3456                                 DMEMIT(":%u:%s", cc->key_size, cc->key_string);
3457                         else
3458                                 for (i = 0; i < cc->key_size; i++)
3459                                         DMEMIT("%02x", cc->key[i]);
3460                 } else
3461                         DMEMIT("-");
3462
3463                 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
3464                                 cc->dev->name, (unsigned long long)cc->start);
3465
3466                 num_feature_args += !!ti->num_discard_bios;
3467                 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3468                 num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3469                 num_feature_args += test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3470                 num_feature_args += test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3471                 num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
3472                 num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3473                 if (cc->on_disk_tag_size)
3474                         num_feature_args++;
3475                 if (num_feature_args) {
3476                         DMEMIT(" %d", num_feature_args);
3477                         if (ti->num_discard_bios)
3478                                 DMEMIT(" allow_discards");
3479                         if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3480                                 DMEMIT(" same_cpu_crypt");
3481                         if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
3482                                 DMEMIT(" submit_from_crypt_cpus");
3483                         if (test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags))
3484                                 DMEMIT(" no_read_workqueue");
3485                         if (test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))
3486                                 DMEMIT(" no_write_workqueue");
3487                         if (cc->on_disk_tag_size)
3488                                 DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
3489                         if (cc->sector_size != (1 << SECTOR_SHIFT))
3490                                 DMEMIT(" sector_size:%d", cc->sector_size);
3491                         if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
3492                                 DMEMIT(" iv_large_sectors");
3493                 }
3494                 break;
3495
3496         case STATUSTYPE_IMA:
3497                 DMEMIT_TARGET_NAME_VERSION(ti->type);
3498                 DMEMIT(",allow_discards=%c", ti->num_discard_bios ? 'y' : 'n');
3499                 DMEMIT(",same_cpu_crypt=%c", test_bit(DM_CRYPT_SAME_CPU, &cc->flags) ? 'y' : 'n');
3500                 DMEMIT(",submit_from_crypt_cpus=%c", test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags) ?
3501                        'y' : 'n');
3502                 DMEMIT(",no_read_workqueue=%c", test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags) ?
3503                        'y' : 'n');
3504                 DMEMIT(",no_write_workqueue=%c", test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags) ?
3505                        'y' : 'n');
3506                 DMEMIT(",iv_large_sectors=%c", test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags) ?
3507                        'y' : 'n');
3508
3509                 if (cc->on_disk_tag_size)
3510                         DMEMIT(",integrity_tag_size=%u,cipher_auth=%s",
3511                                cc->on_disk_tag_size, cc->cipher_auth);
3512                 if (cc->sector_size != (1 << SECTOR_SHIFT))
3513                         DMEMIT(",sector_size=%d", cc->sector_size);
3514                 if (cc->cipher_string)
3515                         DMEMIT(",cipher_string=%s", cc->cipher_string);
3516
3517                 DMEMIT(",key_size=%u", cc->key_size);
3518                 DMEMIT(",key_parts=%u", cc->key_parts);
3519                 DMEMIT(",key_extra_size=%u", cc->key_extra_size);
3520                 DMEMIT(",key_mac_size=%u", cc->key_mac_size);
3521                 DMEMIT(";");
3522                 break;
3523         }
3524 }
3525
3526 static void crypt_postsuspend(struct dm_target *ti)
3527 {
3528         struct crypt_config *cc = ti->private;
3529
3530         set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3531 }
3532
3533 static int crypt_preresume(struct dm_target *ti)
3534 {
3535         struct crypt_config *cc = ti->private;
3536
3537         if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
3538                 DMERR("aborting resume - crypt key is not set.");
3539                 return -EAGAIN;
3540         }
3541
3542         return 0;
3543 }
3544
3545 static void crypt_resume(struct dm_target *ti)
3546 {
3547         struct crypt_config *cc = ti->private;
3548
3549         clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3550 }
3551
3552 /* Message interface
3553  *      key set <key>
3554  *      key wipe
3555  */
3556 static int crypt_message(struct dm_target *ti, unsigned argc, char **argv,
3557                          char *result, unsigned maxlen)
3558 {
3559         struct crypt_config *cc = ti->private;
3560         int key_size, ret = -EINVAL;
3561
3562         if (argc < 2)
3563                 goto error;
3564
3565         if (!strcasecmp(argv[0], "key")) {
3566                 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
3567                         DMWARN("not suspended during key manipulation.");
3568                         return -EINVAL;
3569                 }
3570                 if (argc == 3 && !strcasecmp(argv[1], "set")) {
3571                         /* The key size may not be changed. */
3572                         key_size = get_key_size(&argv[2]);
3573                         if (key_size < 0 || cc->key_size != key_size) {
3574                                 memset(argv[2], '0', strlen(argv[2]));
3575                                 return -EINVAL;
3576                         }
3577
3578                         ret = crypt_set_key(cc, argv[2]);
3579                         if (ret)
3580                                 return ret;
3581                         if (cc->iv_gen_ops && cc->iv_gen_ops->init)
3582                                 ret = cc->iv_gen_ops->init(cc);
3583                         /* wipe the kernel key payload copy */
3584                         if (cc->key_string)
3585                                 memset(cc->key, 0, cc->key_size * sizeof(u8));
3586                         return ret;
3587                 }
3588                 if (argc == 2 && !strcasecmp(argv[1], "wipe"))
3589                         return crypt_wipe_key(cc);
3590         }
3591
3592 error:
3593         DMWARN("unrecognised message received.");
3594         return -EINVAL;
3595 }
3596
3597 static int crypt_iterate_devices(struct dm_target *ti,
3598                                  iterate_devices_callout_fn fn, void *data)
3599 {
3600         struct crypt_config *cc = ti->private;
3601
3602         return fn(ti, cc->dev, cc->start, ti->len, data);
3603 }
3604
3605 static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
3606 {
3607         struct crypt_config *cc = ti->private;
3608
3609         /*
3610          * Unfortunate constraint that is required to avoid the potential
3611          * for exceeding underlying device's max_segments limits -- due to
3612          * crypt_alloc_buffer() possibly allocating pages for the encryption
3613          * bio that are not as physically contiguous as the original bio.
3614          */
3615         limits->max_segment_size = PAGE_SIZE;
3616
3617         limits->logical_block_size =
3618                 max_t(unsigned, limits->logical_block_size, cc->sector_size);
3619         limits->physical_block_size =
3620                 max_t(unsigned, limits->physical_block_size, cc->sector_size);
3621         limits->io_min = max_t(unsigned, limits->io_min, cc->sector_size);
3622 }
3623
3624 static struct target_type crypt_target = {
3625         .name   = "crypt",
3626         .version = {1, 23, 0},
3627         .module = THIS_MODULE,
3628         .ctr    = crypt_ctr,
3629         .dtr    = crypt_dtr,
3630         .features = DM_TARGET_ZONED_HM,
3631         .report_zones = crypt_report_zones,
3632         .map    = crypt_map,
3633         .status = crypt_status,
3634         .postsuspend = crypt_postsuspend,
3635         .preresume = crypt_preresume,
3636         .resume = crypt_resume,
3637         .message = crypt_message,
3638         .iterate_devices = crypt_iterate_devices,
3639         .io_hints = crypt_io_hints,
3640 };
3641
3642 static int __init dm_crypt_init(void)
3643 {
3644         int r;
3645
3646         r = dm_register_target(&crypt_target);
3647         if (r < 0)
3648                 DMERR("register failed %d", r);
3649
3650         return r;
3651 }
3652
3653 static void __exit dm_crypt_exit(void)
3654 {
3655         dm_unregister_target(&crypt_target);
3656 }
3657
3658 module_init(dm_crypt_init);
3659 module_exit(dm_crypt_exit);
3660
3661 MODULE_AUTHOR("Jana Saout <jana@saout.de>");
3662 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
3663 MODULE_LICENSE("GPL");