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