drivers: media: cfe: Add more robust ISR handlers
[platform/kernel/linux-rpi.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 = sizeof(*req) + crypto_skcipher_reqsize(tfm);
757         reqsize = ALIGN(reqsize, __alignof__(__le64));
758
759         req = kmalloc(reqsize + cc->iv_size, GFP_NOIO);
760         if (!req)
761                 return -ENOMEM;
762
763         skcipher_request_set_tfm(req, tfm);
764
765         buf = (u8 *)req + reqsize;
766         memset(buf, 0, cc->iv_size);
767         *(__le64 *)buf = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
768
769         sg_init_one(&src, page_address(ZERO_PAGE(0)), cc->iv_size);
770         sg_init_one(&dst, iv, cc->iv_size);
771         skcipher_request_set_crypt(req, &src, &dst, cc->iv_size, buf);
772         skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
773         err = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
774         kfree_sensitive(req);
775
776         return err;
777 }
778
779 static void crypt_iv_elephant_dtr(struct crypt_config *cc)
780 {
781         struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
782
783         crypto_free_skcipher(elephant->tfm);
784         elephant->tfm = NULL;
785 }
786
787 static int crypt_iv_elephant_ctr(struct crypt_config *cc, struct dm_target *ti,
788                             const char *opts)
789 {
790         struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
791         int r;
792
793         elephant->tfm = crypto_alloc_skcipher("ecb(aes)", 0,
794                                               CRYPTO_ALG_ALLOCATES_MEMORY);
795         if (IS_ERR(elephant->tfm)) {
796                 r = PTR_ERR(elephant->tfm);
797                 elephant->tfm = NULL;
798                 return r;
799         }
800
801         r = crypt_iv_eboiv_ctr(cc, ti, NULL);
802         if (r)
803                 crypt_iv_elephant_dtr(cc);
804         return r;
805 }
806
807 static void diffuser_disk_to_cpu(u32 *d, size_t n)
808 {
809 #ifndef __LITTLE_ENDIAN
810         int i;
811
812         for (i = 0; i < n; i++)
813                 d[i] = le32_to_cpu((__le32)d[i]);
814 #endif
815 }
816
817 static void diffuser_cpu_to_disk(__le32 *d, size_t n)
818 {
819 #ifndef __LITTLE_ENDIAN
820         int i;
821
822         for (i = 0; i < n; i++)
823                 d[i] = cpu_to_le32((u32)d[i]);
824 #endif
825 }
826
827 static void diffuser_a_decrypt(u32 *d, size_t n)
828 {
829         int i, i1, i2, i3;
830
831         for (i = 0; i < 5; i++) {
832                 i1 = 0;
833                 i2 = n - 2;
834                 i3 = n - 5;
835
836                 while (i1 < (n - 1)) {
837                         d[i1] += d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
838                         i1++; i2++; i3++;
839
840                         if (i3 >= n)
841                                 i3 -= n;
842
843                         d[i1] += d[i2] ^ d[i3];
844                         i1++; i2++; i3++;
845
846                         if (i2 >= n)
847                                 i2 -= n;
848
849                         d[i1] += d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
850                         i1++; i2++; i3++;
851
852                         d[i1] += d[i2] ^ d[i3];
853                         i1++; i2++; i3++;
854                 }
855         }
856 }
857
858 static void diffuser_a_encrypt(u32 *d, size_t n)
859 {
860         int i, i1, i2, i3;
861
862         for (i = 0; i < 5; i++) {
863                 i1 = n - 1;
864                 i2 = n - 2 - 1;
865                 i3 = n - 5 - 1;
866
867                 while (i1 > 0) {
868                         d[i1] -= d[i2] ^ d[i3];
869                         i1--; i2--; i3--;
870
871                         d[i1] -= d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
872                         i1--; i2--; i3--;
873
874                         if (i2 < 0)
875                                 i2 += n;
876
877                         d[i1] -= d[i2] ^ d[i3];
878                         i1--; i2--; i3--;
879
880                         if (i3 < 0)
881                                 i3 += n;
882
883                         d[i1] -= d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
884                         i1--; i2--; i3--;
885                 }
886         }
887 }
888
889 static void diffuser_b_decrypt(u32 *d, size_t n)
890 {
891         int i, i1, i2, i3;
892
893         for (i = 0; i < 3; i++) {
894                 i1 = 0;
895                 i2 = 2;
896                 i3 = 5;
897
898                 while (i1 < (n - 1)) {
899                         d[i1] += d[i2] ^ d[i3];
900                         i1++; i2++; i3++;
901
902                         d[i1] += d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
903                         i1++; i2++; i3++;
904
905                         if (i2 >= n)
906                                 i2 -= n;
907
908                         d[i1] += d[i2] ^ d[i3];
909                         i1++; i2++; i3++;
910
911                         if (i3 >= n)
912                                 i3 -= n;
913
914                         d[i1] += d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
915                         i1++; i2++; i3++;
916                 }
917         }
918 }
919
920 static void diffuser_b_encrypt(u32 *d, size_t n)
921 {
922         int i, i1, i2, i3;
923
924         for (i = 0; i < 3; i++) {
925                 i1 = n - 1;
926                 i2 = 2 - 1;
927                 i3 = 5 - 1;
928
929                 while (i1 > 0) {
930                         d[i1] -= d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
931                         i1--; i2--; i3--;
932
933                         if (i3 < 0)
934                                 i3 += n;
935
936                         d[i1] -= d[i2] ^ d[i3];
937                         i1--; i2--; i3--;
938
939                         if (i2 < 0)
940                                 i2 += n;
941
942                         d[i1] -= d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
943                         i1--; i2--; i3--;
944
945                         d[i1] -= d[i2] ^ d[i3];
946                         i1--; i2--; i3--;
947                 }
948         }
949 }
950
951 static int crypt_iv_elephant(struct crypt_config *cc, struct dm_crypt_request *dmreq)
952 {
953         struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
954         u8 *es, *ks, *data, *data2, *data_offset;
955         struct skcipher_request *req;
956         struct scatterlist *sg, *sg2, src, dst;
957         DECLARE_CRYPTO_WAIT(wait);
958         int i, r;
959
960         req = skcipher_request_alloc(elephant->tfm, GFP_NOIO);
961         es = kzalloc(16, GFP_NOIO); /* Key for AES */
962         ks = kzalloc(32, GFP_NOIO); /* Elephant sector key */
963
964         if (!req || !es || !ks) {
965                 r = -ENOMEM;
966                 goto out;
967         }
968
969         *(__le64 *)es = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
970
971         /* E(Ks, e(s)) */
972         sg_init_one(&src, es, 16);
973         sg_init_one(&dst, ks, 16);
974         skcipher_request_set_crypt(req, &src, &dst, 16, NULL);
975         skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
976         r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
977         if (r)
978                 goto out;
979
980         /* E(Ks, e'(s)) */
981         es[15] = 0x80;
982         sg_init_one(&dst, &ks[16], 16);
983         r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
984         if (r)
985                 goto out;
986
987         sg = crypt_get_sg_data(cc, dmreq->sg_out);
988         data = kmap_local_page(sg_page(sg));
989         data_offset = data + sg->offset;
990
991         /* Cannot modify original bio, copy to sg_out and apply Elephant to it */
992         if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
993                 sg2 = crypt_get_sg_data(cc, dmreq->sg_in);
994                 data2 = kmap_local_page(sg_page(sg2));
995                 memcpy(data_offset, data2 + sg2->offset, cc->sector_size);
996                 kunmap_local(data2);
997         }
998
999         if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
1000                 diffuser_disk_to_cpu((u32 *)data_offset, cc->sector_size / sizeof(u32));
1001                 diffuser_b_decrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
1002                 diffuser_a_decrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
1003                 diffuser_cpu_to_disk((__le32 *)data_offset, cc->sector_size / sizeof(u32));
1004         }
1005
1006         for (i = 0; i < (cc->sector_size / 32); i++)
1007                 crypto_xor(data_offset + i * 32, ks, 32);
1008
1009         if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
1010                 diffuser_disk_to_cpu((u32 *)data_offset, cc->sector_size / sizeof(u32));
1011                 diffuser_a_encrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
1012                 diffuser_b_encrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
1013                 diffuser_cpu_to_disk((__le32 *)data_offset, cc->sector_size / sizeof(u32));
1014         }
1015
1016         kunmap_local(data);
1017 out:
1018         kfree_sensitive(ks);
1019         kfree_sensitive(es);
1020         skcipher_request_free(req);
1021         return r;
1022 }
1023
1024 static int crypt_iv_elephant_gen(struct crypt_config *cc, u8 *iv,
1025                             struct dm_crypt_request *dmreq)
1026 {
1027         int r;
1028
1029         if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
1030                 r = crypt_iv_elephant(cc, dmreq);
1031                 if (r)
1032                         return r;
1033         }
1034
1035         return crypt_iv_eboiv_gen(cc, iv, dmreq);
1036 }
1037
1038 static int crypt_iv_elephant_post(struct crypt_config *cc, u8 *iv,
1039                                   struct dm_crypt_request *dmreq)
1040 {
1041         if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
1042                 return crypt_iv_elephant(cc, dmreq);
1043
1044         return 0;
1045 }
1046
1047 static int crypt_iv_elephant_init(struct crypt_config *cc)
1048 {
1049         struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1050         int key_offset = cc->key_size - cc->key_extra_size;
1051
1052         return crypto_skcipher_setkey(elephant->tfm, &cc->key[key_offset], cc->key_extra_size);
1053 }
1054
1055 static int crypt_iv_elephant_wipe(struct crypt_config *cc)
1056 {
1057         struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1058         u8 key[ELEPHANT_MAX_KEY_SIZE];
1059
1060         memset(key, 0, cc->key_extra_size);
1061         return crypto_skcipher_setkey(elephant->tfm, key, cc->key_extra_size);
1062 }
1063
1064 static const struct crypt_iv_operations crypt_iv_plain_ops = {
1065         .generator = crypt_iv_plain_gen
1066 };
1067
1068 static const struct crypt_iv_operations crypt_iv_plain64_ops = {
1069         .generator = crypt_iv_plain64_gen
1070 };
1071
1072 static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
1073         .generator = crypt_iv_plain64be_gen
1074 };
1075
1076 static const struct crypt_iv_operations crypt_iv_essiv_ops = {
1077         .generator = crypt_iv_essiv_gen
1078 };
1079
1080 static const struct crypt_iv_operations crypt_iv_benbi_ops = {
1081         .ctr       = crypt_iv_benbi_ctr,
1082         .dtr       = crypt_iv_benbi_dtr,
1083         .generator = crypt_iv_benbi_gen
1084 };
1085
1086 static const struct crypt_iv_operations crypt_iv_null_ops = {
1087         .generator = crypt_iv_null_gen
1088 };
1089
1090 static const struct crypt_iv_operations crypt_iv_lmk_ops = {
1091         .ctr       = crypt_iv_lmk_ctr,
1092         .dtr       = crypt_iv_lmk_dtr,
1093         .init      = crypt_iv_lmk_init,
1094         .wipe      = crypt_iv_lmk_wipe,
1095         .generator = crypt_iv_lmk_gen,
1096         .post      = crypt_iv_lmk_post
1097 };
1098
1099 static const struct crypt_iv_operations crypt_iv_tcw_ops = {
1100         .ctr       = crypt_iv_tcw_ctr,
1101         .dtr       = crypt_iv_tcw_dtr,
1102         .init      = crypt_iv_tcw_init,
1103         .wipe      = crypt_iv_tcw_wipe,
1104         .generator = crypt_iv_tcw_gen,
1105         .post      = crypt_iv_tcw_post
1106 };
1107
1108 static const struct crypt_iv_operations crypt_iv_random_ops = {
1109         .generator = crypt_iv_random_gen
1110 };
1111
1112 static const struct crypt_iv_operations crypt_iv_eboiv_ops = {
1113         .ctr       = crypt_iv_eboiv_ctr,
1114         .generator = crypt_iv_eboiv_gen
1115 };
1116
1117 static const struct crypt_iv_operations crypt_iv_elephant_ops = {
1118         .ctr       = crypt_iv_elephant_ctr,
1119         .dtr       = crypt_iv_elephant_dtr,
1120         .init      = crypt_iv_elephant_init,
1121         .wipe      = crypt_iv_elephant_wipe,
1122         .generator = crypt_iv_elephant_gen,
1123         .post      = crypt_iv_elephant_post
1124 };
1125
1126 /*
1127  * Integrity extensions
1128  */
1129 static bool crypt_integrity_aead(struct crypt_config *cc)
1130 {
1131         return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
1132 }
1133
1134 static bool crypt_integrity_hmac(struct crypt_config *cc)
1135 {
1136         return crypt_integrity_aead(cc) && cc->key_mac_size;
1137 }
1138
1139 /* Get sg containing data */
1140 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
1141                                              struct scatterlist *sg)
1142 {
1143         if (unlikely(crypt_integrity_aead(cc)))
1144                 return &sg[2];
1145
1146         return sg;
1147 }
1148
1149 static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
1150 {
1151         struct bio_integrity_payload *bip;
1152         unsigned int tag_len;
1153         int ret;
1154
1155         if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
1156                 return 0;
1157
1158         bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
1159         if (IS_ERR(bip))
1160                 return PTR_ERR(bip);
1161
1162         tag_len = io->cc->on_disk_tag_size * (bio_sectors(bio) >> io->cc->sector_shift);
1163
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  * In order to reduce allocation overhead, we try to allocate compound pages in
1673  * the first pass. If they are not available, we fall back to the mempool.
1674  */
1675 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned int size)
1676 {
1677         struct crypt_config *cc = io->cc;
1678         struct bio *clone;
1679         unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1680         gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
1681         unsigned int remaining_size;
1682         unsigned int order = MAX_ORDER;
1683
1684 retry:
1685         if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1686                 mutex_lock(&cc->bio_alloc_lock);
1687
1688         clone = bio_alloc_bioset(cc->dev->bdev, nr_iovecs, io->base_bio->bi_opf,
1689                                  GFP_NOIO, &cc->bs);
1690         clone->bi_private = io;
1691         clone->bi_end_io = crypt_endio;
1692
1693         remaining_size = size;
1694
1695         while (remaining_size) {
1696                 struct page *pages;
1697                 unsigned size_to_add;
1698                 unsigned remaining_order = __fls((remaining_size + PAGE_SIZE - 1) >> PAGE_SHIFT);
1699                 order = min(order, remaining_order);
1700
1701                 while (order > 0) {
1702                         if (unlikely(percpu_counter_read_positive(&cc->n_allocated_pages) +
1703                                         (1 << order) > dm_crypt_pages_per_client))
1704                                 goto decrease_order;
1705                         pages = alloc_pages(gfp_mask
1706                                 | __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN | __GFP_COMP,
1707                                 order);
1708                         if (likely(pages != NULL)) {
1709                                 percpu_counter_add(&cc->n_allocated_pages, 1 << order);
1710                                 goto have_pages;
1711                         }
1712 decrease_order:
1713                         order--;
1714                 }
1715
1716                 pages = mempool_alloc(&cc->page_pool, gfp_mask);
1717                 if (!pages) {
1718                         crypt_free_buffer_pages(cc, clone);
1719                         bio_put(clone);
1720                         gfp_mask |= __GFP_DIRECT_RECLAIM;
1721                         order = 0;
1722                         goto retry;
1723                 }
1724
1725 have_pages:
1726                 size_to_add = min((unsigned)PAGE_SIZE << order, remaining_size);
1727                 __bio_add_page(clone, pages, size_to_add, 0);
1728                 remaining_size -= size_to_add;
1729         }
1730
1731         /* Allocate space for integrity tags */
1732         if (dm_crypt_integrity_io_alloc(io, clone)) {
1733                 crypt_free_buffer_pages(cc, clone);
1734                 bio_put(clone);
1735                 clone = NULL;
1736         }
1737
1738         if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1739                 mutex_unlock(&cc->bio_alloc_lock);
1740
1741         return clone;
1742 }
1743
1744 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1745 {
1746         struct folio_iter fi;
1747
1748         if (clone->bi_vcnt > 0) { /* bio_for_each_folio_all crashes with an empty bio */
1749                 bio_for_each_folio_all(fi, clone) {
1750                         if (folio_test_large(fi.folio)) {
1751                                 percpu_counter_sub(&cc->n_allocated_pages,
1752                                                 1 << folio_order(fi.folio));
1753                                 folio_put(fi.folio);
1754                         } else {
1755                                 mempool_free(&fi.folio->page, &cc->page_pool);
1756                         }
1757                 }
1758         }
1759 }
1760
1761 static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1762                           struct bio *bio, sector_t sector)
1763 {
1764         io->cc = cc;
1765         io->base_bio = bio;
1766         io->sector = sector;
1767         io->error = 0;
1768         io->ctx.r.req = NULL;
1769         io->integrity_metadata = NULL;
1770         io->integrity_metadata_from_pool = false;
1771         io->in_tasklet = false;
1772         atomic_set(&io->io_pending, 0);
1773 }
1774
1775 static void crypt_inc_pending(struct dm_crypt_io *io)
1776 {
1777         atomic_inc(&io->io_pending);
1778 }
1779
1780 static void kcryptd_io_bio_endio(struct work_struct *work)
1781 {
1782         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1783
1784         bio_endio(io->base_bio);
1785 }
1786
1787 /*
1788  * One of the bios was finished. Check for completion of
1789  * the whole request and correctly clean up the buffer.
1790  */
1791 static void crypt_dec_pending(struct dm_crypt_io *io)
1792 {
1793         struct crypt_config *cc = io->cc;
1794         struct bio *base_bio = io->base_bio;
1795         blk_status_t error = io->error;
1796
1797         if (!atomic_dec_and_test(&io->io_pending))
1798                 return;
1799
1800         if (io->ctx.r.req)
1801                 crypt_free_req(cc, io->ctx.r.req, base_bio);
1802
1803         if (unlikely(io->integrity_metadata_from_pool))
1804                 mempool_free(io->integrity_metadata, &io->cc->tag_pool);
1805         else
1806                 kfree(io->integrity_metadata);
1807
1808         base_bio->bi_status = error;
1809
1810         /*
1811          * If we are running this function from our tasklet,
1812          * we can't call bio_endio() here, because it will call
1813          * clone_endio() from dm.c, which in turn will
1814          * free the current struct dm_crypt_io structure with
1815          * our tasklet. In this case we need to delay bio_endio()
1816          * execution to after the tasklet is done and dequeued.
1817          */
1818         if (io->in_tasklet) {
1819                 INIT_WORK(&io->work, kcryptd_io_bio_endio);
1820                 queue_work(cc->io_queue, &io->work);
1821                 return;
1822         }
1823
1824         bio_endio(base_bio);
1825 }
1826
1827 /*
1828  * kcryptd/kcryptd_io:
1829  *
1830  * Needed because it would be very unwise to do decryption in an
1831  * interrupt context.
1832  *
1833  * kcryptd performs the actual encryption or decryption.
1834  *
1835  * kcryptd_io performs the IO submission.
1836  *
1837  * They must be separated as otherwise the final stages could be
1838  * starved by new requests which can block in the first stages due
1839  * to memory allocation.
1840  *
1841  * The work is done per CPU global for all dm-crypt instances.
1842  * They should not depend on each other and do not block.
1843  */
1844 static void crypt_endio(struct bio *clone)
1845 {
1846         struct dm_crypt_io *io = clone->bi_private;
1847         struct crypt_config *cc = io->cc;
1848         unsigned int rw = bio_data_dir(clone);
1849         blk_status_t error;
1850
1851         /*
1852          * free the processed pages
1853          */
1854         if (rw == WRITE)
1855                 crypt_free_buffer_pages(cc, clone);
1856
1857         error = clone->bi_status;
1858         bio_put(clone);
1859
1860         if (rw == READ && !error) {
1861                 kcryptd_queue_crypt(io);
1862                 return;
1863         }
1864
1865         if (unlikely(error))
1866                 io->error = error;
1867
1868         crypt_dec_pending(io);
1869 }
1870
1871 #define CRYPT_MAP_READ_GFP GFP_NOWAIT
1872
1873 static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
1874 {
1875         struct crypt_config *cc = io->cc;
1876         struct bio *clone;
1877
1878         /*
1879          * We need the original biovec array in order to decrypt the whole bio
1880          * data *afterwards* -- thanks to immutable biovecs we don't need to
1881          * worry about the block layer modifying the biovec array; so leverage
1882          * bio_alloc_clone().
1883          */
1884         clone = bio_alloc_clone(cc->dev->bdev, io->base_bio, gfp, &cc->bs);
1885         if (!clone)
1886                 return 1;
1887         clone->bi_private = io;
1888         clone->bi_end_io = crypt_endio;
1889
1890         crypt_inc_pending(io);
1891
1892         clone->bi_iter.bi_sector = cc->start + io->sector;
1893
1894         if (dm_crypt_integrity_io_alloc(io, clone)) {
1895                 crypt_dec_pending(io);
1896                 bio_put(clone);
1897                 return 1;
1898         }
1899
1900         dm_submit_bio_remap(io->base_bio, clone);
1901         return 0;
1902 }
1903
1904 static void kcryptd_io_read_work(struct work_struct *work)
1905 {
1906         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1907
1908         crypt_inc_pending(io);
1909         if (kcryptd_io_read(io, GFP_NOIO))
1910                 io->error = BLK_STS_RESOURCE;
1911         crypt_dec_pending(io);
1912 }
1913
1914 static void kcryptd_queue_read(struct dm_crypt_io *io)
1915 {
1916         struct crypt_config *cc = io->cc;
1917
1918         INIT_WORK(&io->work, kcryptd_io_read_work);
1919         queue_work(cc->io_queue, &io->work);
1920 }
1921
1922 static void kcryptd_io_write(struct dm_crypt_io *io)
1923 {
1924         struct bio *clone = io->ctx.bio_out;
1925
1926         dm_submit_bio_remap(io->base_bio, clone);
1927 }
1928
1929 #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1930
1931 static int dmcrypt_write(void *data)
1932 {
1933         struct crypt_config *cc = data;
1934         struct dm_crypt_io *io;
1935
1936         while (1) {
1937                 struct rb_root write_tree;
1938                 struct blk_plug plug;
1939
1940                 spin_lock_irq(&cc->write_thread_lock);
1941 continue_locked:
1942
1943                 if (!RB_EMPTY_ROOT(&cc->write_tree))
1944                         goto pop_from_list;
1945
1946                 set_current_state(TASK_INTERRUPTIBLE);
1947
1948                 spin_unlock_irq(&cc->write_thread_lock);
1949
1950                 if (unlikely(kthread_should_stop())) {
1951                         set_current_state(TASK_RUNNING);
1952                         break;
1953                 }
1954
1955                 schedule();
1956
1957                 set_current_state(TASK_RUNNING);
1958                 spin_lock_irq(&cc->write_thread_lock);
1959                 goto continue_locked;
1960
1961 pop_from_list:
1962                 write_tree = cc->write_tree;
1963                 cc->write_tree = RB_ROOT;
1964                 spin_unlock_irq(&cc->write_thread_lock);
1965
1966                 BUG_ON(rb_parent(write_tree.rb_node));
1967
1968                 /*
1969                  * Note: we cannot walk the tree here with rb_next because
1970                  * the structures may be freed when kcryptd_io_write is called.
1971                  */
1972                 blk_start_plug(&plug);
1973                 do {
1974                         io = crypt_io_from_node(rb_first(&write_tree));
1975                         rb_erase(&io->rb_node, &write_tree);
1976                         kcryptd_io_write(io);
1977                         cond_resched();
1978                 } while (!RB_EMPTY_ROOT(&write_tree));
1979                 blk_finish_plug(&plug);
1980         }
1981         return 0;
1982 }
1983
1984 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
1985 {
1986         struct bio *clone = io->ctx.bio_out;
1987         struct crypt_config *cc = io->cc;
1988         unsigned long flags;
1989         sector_t sector;
1990         struct rb_node **rbp, *parent;
1991
1992         if (unlikely(io->error)) {
1993                 crypt_free_buffer_pages(cc, clone);
1994                 bio_put(clone);
1995                 crypt_dec_pending(io);
1996                 return;
1997         }
1998
1999         /* crypt_convert should have filled the clone bio */
2000         BUG_ON(io->ctx.iter_out.bi_size);
2001
2002         clone->bi_iter.bi_sector = cc->start + io->sector;
2003
2004         if ((likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) ||
2005             test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags)) {
2006                 dm_submit_bio_remap(io->base_bio, clone);
2007                 return;
2008         }
2009
2010         spin_lock_irqsave(&cc->write_thread_lock, flags);
2011         if (RB_EMPTY_ROOT(&cc->write_tree))
2012                 wake_up_process(cc->write_thread);
2013         rbp = &cc->write_tree.rb_node;
2014         parent = NULL;
2015         sector = io->sector;
2016         while (*rbp) {
2017                 parent = *rbp;
2018                 if (sector < crypt_io_from_node(parent)->sector)
2019                         rbp = &(*rbp)->rb_left;
2020                 else
2021                         rbp = &(*rbp)->rb_right;
2022         }
2023         rb_link_node(&io->rb_node, parent, rbp);
2024         rb_insert_color(&io->rb_node, &cc->write_tree);
2025         spin_unlock_irqrestore(&cc->write_thread_lock, flags);
2026 }
2027
2028 static bool kcryptd_crypt_write_inline(struct crypt_config *cc,
2029                                        struct convert_context *ctx)
2030
2031 {
2032         if (!test_bit(DM_CRYPT_WRITE_INLINE, &cc->flags))
2033                 return false;
2034
2035         /*
2036          * Note: zone append writes (REQ_OP_ZONE_APPEND) do not have ordering
2037          * constraints so they do not need to be issued inline by
2038          * kcryptd_crypt_write_convert().
2039          */
2040         switch (bio_op(ctx->bio_in)) {
2041         case REQ_OP_WRITE:
2042         case REQ_OP_WRITE_ZEROES:
2043                 return true;
2044         default:
2045                 return false;
2046         }
2047 }
2048
2049 static void kcryptd_crypt_write_continue(struct work_struct *work)
2050 {
2051         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2052         struct crypt_config *cc = io->cc;
2053         struct convert_context *ctx = &io->ctx;
2054         int crypt_finished;
2055         sector_t sector = io->sector;
2056         blk_status_t r;
2057
2058         wait_for_completion(&ctx->restart);
2059         reinit_completion(&ctx->restart);
2060
2061         r = crypt_convert(cc, &io->ctx, true, false);
2062         if (r)
2063                 io->error = r;
2064         crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
2065         if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
2066                 /* Wait for completion signaled by kcryptd_async_done() */
2067                 wait_for_completion(&ctx->restart);
2068                 crypt_finished = 1;
2069         }
2070
2071         /* Encryption was already finished, submit io now */
2072         if (crypt_finished) {
2073                 kcryptd_crypt_write_io_submit(io, 0);
2074                 io->sector = sector;
2075         }
2076
2077         crypt_dec_pending(io);
2078 }
2079
2080 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
2081 {
2082         struct crypt_config *cc = io->cc;
2083         struct convert_context *ctx = &io->ctx;
2084         struct bio *clone;
2085         int crypt_finished;
2086         sector_t sector = io->sector;
2087         blk_status_t r;
2088
2089         /*
2090          * Prevent io from disappearing until this function completes.
2091          */
2092         crypt_inc_pending(io);
2093         crypt_convert_init(cc, ctx, NULL, io->base_bio, sector);
2094
2095         clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
2096         if (unlikely(!clone)) {
2097                 io->error = BLK_STS_IOERR;
2098                 goto dec;
2099         }
2100
2101         io->ctx.bio_out = clone;
2102         io->ctx.iter_out = clone->bi_iter;
2103
2104         sector += bio_sectors(clone);
2105
2106         crypt_inc_pending(io);
2107         r = crypt_convert(cc, ctx,
2108                           test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags), true);
2109         /*
2110          * Crypto API backlogged the request, because its queue was full
2111          * and we're in softirq context, so continue from a workqueue
2112          * (TODO: is it actually possible to be in softirq in the write path?)
2113          */
2114         if (r == BLK_STS_DEV_RESOURCE) {
2115                 INIT_WORK(&io->work, kcryptd_crypt_write_continue);
2116                 queue_work(cc->crypt_queue, &io->work);
2117                 return;
2118         }
2119         if (r)
2120                 io->error = r;
2121         crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
2122         if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
2123                 /* Wait for completion signaled by kcryptd_async_done() */
2124                 wait_for_completion(&ctx->restart);
2125                 crypt_finished = 1;
2126         }
2127
2128         /* Encryption was already finished, submit io now */
2129         if (crypt_finished) {
2130                 kcryptd_crypt_write_io_submit(io, 0);
2131                 io->sector = sector;
2132         }
2133
2134 dec:
2135         crypt_dec_pending(io);
2136 }
2137
2138 static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
2139 {
2140         crypt_dec_pending(io);
2141 }
2142
2143 static void kcryptd_crypt_read_continue(struct work_struct *work)
2144 {
2145         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2146         struct crypt_config *cc = io->cc;
2147         blk_status_t r;
2148
2149         wait_for_completion(&io->ctx.restart);
2150         reinit_completion(&io->ctx.restart);
2151
2152         r = crypt_convert(cc, &io->ctx, true, false);
2153         if (r)
2154                 io->error = r;
2155
2156         if (atomic_dec_and_test(&io->ctx.cc_pending))
2157                 kcryptd_crypt_read_done(io);
2158
2159         crypt_dec_pending(io);
2160 }
2161
2162 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
2163 {
2164         struct crypt_config *cc = io->cc;
2165         blk_status_t r;
2166
2167         crypt_inc_pending(io);
2168
2169         crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
2170                            io->sector);
2171
2172         r = crypt_convert(cc, &io->ctx,
2173                           test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags), true);
2174         /*
2175          * Crypto API backlogged the request, because its queue was full
2176          * and we're in softirq context, so continue from a workqueue
2177          */
2178         if (r == BLK_STS_DEV_RESOURCE) {
2179                 INIT_WORK(&io->work, kcryptd_crypt_read_continue);
2180                 queue_work(cc->crypt_queue, &io->work);
2181                 return;
2182         }
2183         if (r)
2184                 io->error = r;
2185
2186         if (atomic_dec_and_test(&io->ctx.cc_pending))
2187                 kcryptd_crypt_read_done(io);
2188
2189         crypt_dec_pending(io);
2190 }
2191
2192 static void kcryptd_async_done(void *data, int error)
2193 {
2194         struct dm_crypt_request *dmreq = data;
2195         struct convert_context *ctx = dmreq->ctx;
2196         struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
2197         struct crypt_config *cc = io->cc;
2198
2199         /*
2200          * A request from crypto driver backlog is going to be processed now,
2201          * finish the completion and continue in crypt_convert().
2202          * (Callback will be called for the second time for this request.)
2203          */
2204         if (error == -EINPROGRESS) {
2205                 complete(&ctx->restart);
2206                 return;
2207         }
2208
2209         if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
2210                 error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
2211
2212         if (error == -EBADMSG) {
2213                 sector_t s = le64_to_cpu(*org_sector_of_dmreq(cc, dmreq));
2214
2215                 DMERR_LIMIT("%pg: INTEGRITY AEAD ERROR, sector %llu",
2216                             ctx->bio_in->bi_bdev, s);
2217                 dm_audit_log_bio(DM_MSG_PREFIX, "integrity-aead",
2218                                  ctx->bio_in, s, 0);
2219                 io->error = BLK_STS_PROTECTION;
2220         } else if (error < 0)
2221                 io->error = BLK_STS_IOERR;
2222
2223         crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
2224
2225         if (!atomic_dec_and_test(&ctx->cc_pending))
2226                 return;
2227
2228         /*
2229          * The request is fully completed: for inline writes, let
2230          * kcryptd_crypt_write_convert() do the IO submission.
2231          */
2232         if (bio_data_dir(io->base_bio) == READ) {
2233                 kcryptd_crypt_read_done(io);
2234                 return;
2235         }
2236
2237         if (kcryptd_crypt_write_inline(cc, ctx)) {
2238                 complete(&ctx->restart);
2239                 return;
2240         }
2241
2242         kcryptd_crypt_write_io_submit(io, 1);
2243 }
2244
2245 static void kcryptd_crypt(struct work_struct *work)
2246 {
2247         struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2248
2249         if (bio_data_dir(io->base_bio) == READ)
2250                 kcryptd_crypt_read_convert(io);
2251         else
2252                 kcryptd_crypt_write_convert(io);
2253 }
2254
2255 static void kcryptd_crypt_tasklet(unsigned long work)
2256 {
2257         kcryptd_crypt((struct work_struct *)work);
2258 }
2259
2260 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
2261 {
2262         struct crypt_config *cc = io->cc;
2263
2264         if ((bio_data_dir(io->base_bio) == READ && test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags)) ||
2265             (bio_data_dir(io->base_bio) == WRITE && test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))) {
2266                 /*
2267                  * in_hardirq(): Crypto API's skcipher_walk_first() refuses to work in hard IRQ context.
2268                  * irqs_disabled(): the kernel may run some IO completion from the idle thread, but
2269                  * it is being executed with irqs disabled.
2270                  */
2271                 if (in_hardirq() || irqs_disabled()) {
2272                         io->in_tasklet = true;
2273                         tasklet_init(&io->tasklet, kcryptd_crypt_tasklet, (unsigned long)&io->work);
2274                         tasklet_schedule(&io->tasklet);
2275                         return;
2276                 }
2277
2278                 kcryptd_crypt(&io->work);
2279                 return;
2280         }
2281
2282         INIT_WORK(&io->work, kcryptd_crypt);
2283         queue_work(cc->crypt_queue, &io->work);
2284 }
2285
2286 static void crypt_free_tfms_aead(struct crypt_config *cc)
2287 {
2288         if (!cc->cipher_tfm.tfms_aead)
2289                 return;
2290
2291         if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2292                 crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
2293                 cc->cipher_tfm.tfms_aead[0] = NULL;
2294         }
2295
2296         kfree(cc->cipher_tfm.tfms_aead);
2297         cc->cipher_tfm.tfms_aead = NULL;
2298 }
2299
2300 static void crypt_free_tfms_skcipher(struct crypt_config *cc)
2301 {
2302         unsigned int i;
2303
2304         if (!cc->cipher_tfm.tfms)
2305                 return;
2306
2307         for (i = 0; i < cc->tfms_count; i++)
2308                 if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
2309                         crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
2310                         cc->cipher_tfm.tfms[i] = NULL;
2311                 }
2312
2313         kfree(cc->cipher_tfm.tfms);
2314         cc->cipher_tfm.tfms = NULL;
2315 }
2316
2317 static void crypt_free_tfms(struct crypt_config *cc)
2318 {
2319         if (crypt_integrity_aead(cc))
2320                 crypt_free_tfms_aead(cc);
2321         else
2322                 crypt_free_tfms_skcipher(cc);
2323 }
2324
2325 static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
2326 {
2327         unsigned int i;
2328         int err;
2329
2330         cc->cipher_tfm.tfms = kcalloc(cc->tfms_count,
2331                                       sizeof(struct crypto_skcipher *),
2332                                       GFP_KERNEL);
2333         if (!cc->cipher_tfm.tfms)
2334                 return -ENOMEM;
2335
2336         for (i = 0; i < cc->tfms_count; i++) {
2337                 cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0,
2338                                                 CRYPTO_ALG_ALLOCATES_MEMORY);
2339                 if (IS_ERR(cc->cipher_tfm.tfms[i])) {
2340                         err = PTR_ERR(cc->cipher_tfm.tfms[i]);
2341                         crypt_free_tfms(cc);
2342                         return err;
2343                 }
2344         }
2345
2346         /*
2347          * dm-crypt performance can vary greatly depending on which crypto
2348          * algorithm implementation is used.  Help people debug performance
2349          * problems by logging the ->cra_driver_name.
2350          */
2351         DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2352                crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
2353         return 0;
2354 }
2355
2356 static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
2357 {
2358         int err;
2359
2360         cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
2361         if (!cc->cipher_tfm.tfms)
2362                 return -ENOMEM;
2363
2364         cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0,
2365                                                 CRYPTO_ALG_ALLOCATES_MEMORY);
2366         if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2367                 err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
2368                 crypt_free_tfms(cc);
2369                 return err;
2370         }
2371
2372         DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2373                crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
2374         return 0;
2375 }
2376
2377 static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
2378 {
2379         if (crypt_integrity_aead(cc))
2380                 return crypt_alloc_tfms_aead(cc, ciphermode);
2381         else
2382                 return crypt_alloc_tfms_skcipher(cc, ciphermode);
2383 }
2384
2385 static unsigned int crypt_subkey_size(struct crypt_config *cc)
2386 {
2387         return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
2388 }
2389
2390 static unsigned int crypt_authenckey_size(struct crypt_config *cc)
2391 {
2392         return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
2393 }
2394
2395 /*
2396  * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
2397  * the key must be for some reason in special format.
2398  * This funcion converts cc->key to this special format.
2399  */
2400 static void crypt_copy_authenckey(char *p, const void *key,
2401                                   unsigned int enckeylen, unsigned int authkeylen)
2402 {
2403         struct crypto_authenc_key_param *param;
2404         struct rtattr *rta;
2405
2406         rta = (struct rtattr *)p;
2407         param = RTA_DATA(rta);
2408         param->enckeylen = cpu_to_be32(enckeylen);
2409         rta->rta_len = RTA_LENGTH(sizeof(*param));
2410         rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
2411         p += RTA_SPACE(sizeof(*param));
2412         memcpy(p, key + enckeylen, authkeylen);
2413         p += authkeylen;
2414         memcpy(p, key, enckeylen);
2415 }
2416
2417 static int crypt_setkey(struct crypt_config *cc)
2418 {
2419         unsigned int subkey_size;
2420         int err = 0, i, r;
2421
2422         /* Ignore extra keys (which are used for IV etc) */
2423         subkey_size = crypt_subkey_size(cc);
2424
2425         if (crypt_integrity_hmac(cc)) {
2426                 if (subkey_size < cc->key_mac_size)
2427                         return -EINVAL;
2428
2429                 crypt_copy_authenckey(cc->authenc_key, cc->key,
2430                                       subkey_size - cc->key_mac_size,
2431                                       cc->key_mac_size);
2432         }
2433
2434         for (i = 0; i < cc->tfms_count; i++) {
2435                 if (crypt_integrity_hmac(cc))
2436                         r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2437                                 cc->authenc_key, crypt_authenckey_size(cc));
2438                 else if (crypt_integrity_aead(cc))
2439                         r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2440                                                cc->key + (i * subkey_size),
2441                                                subkey_size);
2442                 else
2443                         r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
2444                                                    cc->key + (i * subkey_size),
2445                                                    subkey_size);
2446                 if (r)
2447                         err = r;
2448         }
2449
2450         if (crypt_integrity_hmac(cc))
2451                 memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
2452
2453         return err;
2454 }
2455
2456 #ifdef CONFIG_KEYS
2457
2458 static bool contains_whitespace(const char *str)
2459 {
2460         while (*str)
2461                 if (isspace(*str++))
2462                         return true;
2463         return false;
2464 }
2465
2466 static int set_key_user(struct crypt_config *cc, struct key *key)
2467 {
2468         const struct user_key_payload *ukp;
2469
2470         ukp = user_key_payload_locked(key);
2471         if (!ukp)
2472                 return -EKEYREVOKED;
2473
2474         if (cc->key_size != ukp->datalen)
2475                 return -EINVAL;
2476
2477         memcpy(cc->key, ukp->data, cc->key_size);
2478
2479         return 0;
2480 }
2481
2482 static int set_key_encrypted(struct crypt_config *cc, struct key *key)
2483 {
2484         const struct encrypted_key_payload *ekp;
2485
2486         ekp = key->payload.data[0];
2487         if (!ekp)
2488                 return -EKEYREVOKED;
2489
2490         if (cc->key_size != ekp->decrypted_datalen)
2491                 return -EINVAL;
2492
2493         memcpy(cc->key, ekp->decrypted_data, cc->key_size);
2494
2495         return 0;
2496 }
2497
2498 static int set_key_trusted(struct crypt_config *cc, struct key *key)
2499 {
2500         const struct trusted_key_payload *tkp;
2501
2502         tkp = key->payload.data[0];
2503         if (!tkp)
2504                 return -EKEYREVOKED;
2505
2506         if (cc->key_size != tkp->key_len)
2507                 return -EINVAL;
2508
2509         memcpy(cc->key, tkp->key, cc->key_size);
2510
2511         return 0;
2512 }
2513
2514 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2515 {
2516         char *new_key_string, *key_desc;
2517         int ret;
2518         struct key_type *type;
2519         struct key *key;
2520         int (*set_key)(struct crypt_config *cc, struct key *key);
2521
2522         /*
2523          * Reject key_string with whitespace. dm core currently lacks code for
2524          * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2525          */
2526         if (contains_whitespace(key_string)) {
2527                 DMERR("whitespace chars not allowed in key string");
2528                 return -EINVAL;
2529         }
2530
2531         /* look for next ':' separating key_type from key_description */
2532         key_desc = strchr(key_string, ':');
2533         if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2534                 return -EINVAL;
2535
2536         if (!strncmp(key_string, "logon:", key_desc - key_string + 1)) {
2537                 type = &key_type_logon;
2538                 set_key = set_key_user;
2539         } else if (!strncmp(key_string, "user:", key_desc - key_string + 1)) {
2540                 type = &key_type_user;
2541                 set_key = set_key_user;
2542         } else if (IS_ENABLED(CONFIG_ENCRYPTED_KEYS) &&
2543                    !strncmp(key_string, "encrypted:", key_desc - key_string + 1)) {
2544                 type = &key_type_encrypted;
2545                 set_key = set_key_encrypted;
2546         } else if (IS_ENABLED(CONFIG_TRUSTED_KEYS) &&
2547                    !strncmp(key_string, "trusted:", key_desc - key_string + 1)) {
2548                 type = &key_type_trusted;
2549                 set_key = set_key_trusted;
2550         } else {
2551                 return -EINVAL;
2552         }
2553
2554         new_key_string = kstrdup(key_string, GFP_KERNEL);
2555         if (!new_key_string)
2556                 return -ENOMEM;
2557
2558         key = request_key(type, key_desc + 1, NULL);
2559         if (IS_ERR(key)) {
2560                 kfree_sensitive(new_key_string);
2561                 return PTR_ERR(key);
2562         }
2563
2564         down_read(&key->sem);
2565
2566         ret = set_key(cc, key);
2567         if (ret < 0) {
2568                 up_read(&key->sem);
2569                 key_put(key);
2570                 kfree_sensitive(new_key_string);
2571                 return ret;
2572         }
2573
2574         up_read(&key->sem);
2575         key_put(key);
2576
2577         /* clear the flag since following operations may invalidate previously valid key */
2578         clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2579
2580         ret = crypt_setkey(cc);
2581
2582         if (!ret) {
2583                 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2584                 kfree_sensitive(cc->key_string);
2585                 cc->key_string = new_key_string;
2586         } else
2587                 kfree_sensitive(new_key_string);
2588
2589         return ret;
2590 }
2591
2592 static int get_key_size(char **key_string)
2593 {
2594         char *colon, dummy;
2595         int ret;
2596
2597         if (*key_string[0] != ':')
2598                 return strlen(*key_string) >> 1;
2599
2600         /* look for next ':' in key string */
2601         colon = strpbrk(*key_string + 1, ":");
2602         if (!colon)
2603                 return -EINVAL;
2604
2605         if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2606                 return -EINVAL;
2607
2608         *key_string = colon;
2609
2610         /* remaining key string should be :<logon|user>:<key_desc> */
2611
2612         return ret;
2613 }
2614
2615 #else
2616
2617 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2618 {
2619         return -EINVAL;
2620 }
2621
2622 static int get_key_size(char **key_string)
2623 {
2624         return (*key_string[0] == ':') ? -EINVAL : (int)(strlen(*key_string) >> 1);
2625 }
2626
2627 #endif /* CONFIG_KEYS */
2628
2629 static int crypt_set_key(struct crypt_config *cc, char *key)
2630 {
2631         int r = -EINVAL;
2632         int key_string_len = strlen(key);
2633
2634         /* Hyphen (which gives a key_size of zero) means there is no key. */
2635         if (!cc->key_size && strcmp(key, "-"))
2636                 goto out;
2637
2638         /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2639         if (key[0] == ':') {
2640                 r = crypt_set_keyring_key(cc, key + 1);
2641                 goto out;
2642         }
2643
2644         /* clear the flag since following operations may invalidate previously valid key */
2645         clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2646
2647         /* wipe references to any kernel keyring key */
2648         kfree_sensitive(cc->key_string);
2649         cc->key_string = NULL;
2650
2651         /* Decode key from its hex representation. */
2652         if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
2653                 goto out;
2654
2655         r = crypt_setkey(cc);
2656         if (!r)
2657                 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2658
2659 out:
2660         /* Hex key string not needed after here, so wipe it. */
2661         memset(key, '0', key_string_len);
2662
2663         return r;
2664 }
2665
2666 static int crypt_wipe_key(struct crypt_config *cc)
2667 {
2668         int r;
2669
2670         clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2671         get_random_bytes(&cc->key, cc->key_size);
2672
2673         /* Wipe IV private keys */
2674         if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
2675                 r = cc->iv_gen_ops->wipe(cc);
2676                 if (r)
2677                         return r;
2678         }
2679
2680         kfree_sensitive(cc->key_string);
2681         cc->key_string = NULL;
2682         r = crypt_setkey(cc);
2683         memset(&cc->key, 0, cc->key_size * sizeof(u8));
2684
2685         return r;
2686 }
2687
2688 static void crypt_calculate_pages_per_client(void)
2689 {
2690         unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
2691
2692         if (!dm_crypt_clients_n)
2693                 return;
2694
2695         pages /= dm_crypt_clients_n;
2696         if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
2697                 pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
2698         dm_crypt_pages_per_client = pages;
2699 }
2700
2701 static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
2702 {
2703         struct crypt_config *cc = pool_data;
2704         struct page *page;
2705
2706         /*
2707          * Note, percpu_counter_read_positive() may over (and under) estimate
2708          * the current usage by at most (batch - 1) * num_online_cpus() pages,
2709          * but avoids potential spinlock contention of an exact result.
2710          */
2711         if (unlikely(percpu_counter_read_positive(&cc->n_allocated_pages) >= dm_crypt_pages_per_client) &&
2712             likely(gfp_mask & __GFP_NORETRY))
2713                 return NULL;
2714
2715         page = alloc_page(gfp_mask);
2716         if (likely(page != NULL))
2717                 percpu_counter_add(&cc->n_allocated_pages, 1);
2718
2719         return page;
2720 }
2721
2722 static void crypt_page_free(void *page, void *pool_data)
2723 {
2724         struct crypt_config *cc = pool_data;
2725
2726         __free_page(page);
2727         percpu_counter_sub(&cc->n_allocated_pages, 1);
2728 }
2729
2730 static void crypt_dtr(struct dm_target *ti)
2731 {
2732         struct crypt_config *cc = ti->private;
2733
2734         ti->private = NULL;
2735
2736         if (!cc)
2737                 return;
2738
2739         if (cc->write_thread)
2740                 kthread_stop(cc->write_thread);
2741
2742         if (cc->io_queue)
2743                 destroy_workqueue(cc->io_queue);
2744         if (cc->crypt_queue)
2745                 destroy_workqueue(cc->crypt_queue);
2746
2747         crypt_free_tfms(cc);
2748
2749         bioset_exit(&cc->bs);
2750
2751         mempool_exit(&cc->page_pool);
2752         mempool_exit(&cc->req_pool);
2753         mempool_exit(&cc->tag_pool);
2754
2755         WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
2756         percpu_counter_destroy(&cc->n_allocated_pages);
2757
2758         if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
2759                 cc->iv_gen_ops->dtr(cc);
2760
2761         if (cc->dev)
2762                 dm_put_device(ti, cc->dev);
2763
2764         kfree_sensitive(cc->cipher_string);
2765         kfree_sensitive(cc->key_string);
2766         kfree_sensitive(cc->cipher_auth);
2767         kfree_sensitive(cc->authenc_key);
2768
2769         mutex_destroy(&cc->bio_alloc_lock);
2770
2771         /* Must zero key material before freeing */
2772         kfree_sensitive(cc);
2773
2774         spin_lock(&dm_crypt_clients_lock);
2775         WARN_ON(!dm_crypt_clients_n);
2776         dm_crypt_clients_n--;
2777         crypt_calculate_pages_per_client();
2778         spin_unlock(&dm_crypt_clients_lock);
2779
2780         dm_audit_log_dtr(DM_MSG_PREFIX, ti, 1);
2781 }
2782
2783 static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
2784 {
2785         struct crypt_config *cc = ti->private;
2786
2787         if (crypt_integrity_aead(cc))
2788                 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2789         else
2790                 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2791
2792         if (cc->iv_size)
2793                 /* at least a 64 bit sector number should fit in our buffer */
2794                 cc->iv_size = max(cc->iv_size,
2795                                   (unsigned int)(sizeof(u64) / sizeof(u8)));
2796         else if (ivmode) {
2797                 DMWARN("Selected cipher does not support IVs");
2798                 ivmode = NULL;
2799         }
2800
2801         /* Choose ivmode, see comments at iv code. */
2802         if (ivmode == NULL)
2803                 cc->iv_gen_ops = NULL;
2804         else if (strcmp(ivmode, "plain") == 0)
2805                 cc->iv_gen_ops = &crypt_iv_plain_ops;
2806         else if (strcmp(ivmode, "plain64") == 0)
2807                 cc->iv_gen_ops = &crypt_iv_plain64_ops;
2808         else if (strcmp(ivmode, "plain64be") == 0)
2809                 cc->iv_gen_ops = &crypt_iv_plain64be_ops;
2810         else if (strcmp(ivmode, "essiv") == 0)
2811                 cc->iv_gen_ops = &crypt_iv_essiv_ops;
2812         else if (strcmp(ivmode, "benbi") == 0)
2813                 cc->iv_gen_ops = &crypt_iv_benbi_ops;
2814         else if (strcmp(ivmode, "null") == 0)
2815                 cc->iv_gen_ops = &crypt_iv_null_ops;
2816         else if (strcmp(ivmode, "eboiv") == 0)
2817                 cc->iv_gen_ops = &crypt_iv_eboiv_ops;
2818         else if (strcmp(ivmode, "elephant") == 0) {
2819                 cc->iv_gen_ops = &crypt_iv_elephant_ops;
2820                 cc->key_parts = 2;
2821                 cc->key_extra_size = cc->key_size / 2;
2822                 if (cc->key_extra_size > ELEPHANT_MAX_KEY_SIZE)
2823                         return -EINVAL;
2824                 set_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags);
2825         } else if (strcmp(ivmode, "lmk") == 0) {
2826                 cc->iv_gen_ops = &crypt_iv_lmk_ops;
2827                 /*
2828                  * Version 2 and 3 is recognised according
2829                  * to length of provided multi-key string.
2830                  * If present (version 3), last key is used as IV seed.
2831                  * All keys (including IV seed) are always the same size.
2832                  */
2833                 if (cc->key_size % cc->key_parts) {
2834                         cc->key_parts++;
2835                         cc->key_extra_size = cc->key_size / cc->key_parts;
2836                 }
2837         } else if (strcmp(ivmode, "tcw") == 0) {
2838                 cc->iv_gen_ops = &crypt_iv_tcw_ops;
2839                 cc->key_parts += 2; /* IV + whitening */
2840                 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2841         } else if (strcmp(ivmode, "random") == 0) {
2842                 cc->iv_gen_ops = &crypt_iv_random_ops;
2843                 /* Need storage space in integrity fields. */
2844                 cc->integrity_iv_size = cc->iv_size;
2845         } else {
2846                 ti->error = "Invalid IV mode";
2847                 return -EINVAL;
2848         }
2849
2850         return 0;
2851 }
2852
2853 /*
2854  * Workaround to parse HMAC algorithm from AEAD crypto API spec.
2855  * The HMAC is needed to calculate tag size (HMAC digest size).
2856  * This should be probably done by crypto-api calls (once available...)
2857  */
2858 static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
2859 {
2860         char *start, *end, *mac_alg = NULL;
2861         struct crypto_ahash *mac;
2862
2863         if (!strstarts(cipher_api, "authenc("))
2864                 return 0;
2865
2866         start = strchr(cipher_api, '(');
2867         end = strchr(cipher_api, ',');
2868         if (!start || !end || ++start > end)
2869                 return -EINVAL;
2870
2871         mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
2872         if (!mac_alg)
2873                 return -ENOMEM;
2874         strncpy(mac_alg, start, end - start);
2875
2876         mac = crypto_alloc_ahash(mac_alg, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
2877         kfree(mac_alg);
2878
2879         if (IS_ERR(mac))
2880                 return PTR_ERR(mac);
2881
2882         cc->key_mac_size = crypto_ahash_digestsize(mac);
2883         crypto_free_ahash(mac);
2884
2885         cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
2886         if (!cc->authenc_key)
2887                 return -ENOMEM;
2888
2889         return 0;
2890 }
2891
2892 static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
2893                                 char **ivmode, char **ivopts)
2894 {
2895         struct crypt_config *cc = ti->private;
2896         char *tmp, *cipher_api, buf[CRYPTO_MAX_ALG_NAME];
2897         int ret = -EINVAL;
2898
2899         cc->tfms_count = 1;
2900
2901         /*
2902          * New format (capi: prefix)
2903          * capi:cipher_api_spec-iv:ivopts
2904          */
2905         tmp = &cipher_in[strlen("capi:")];
2906
2907         /* Separate IV options if present, it can contain another '-' in hash name */
2908         *ivopts = strrchr(tmp, ':');
2909         if (*ivopts) {
2910                 **ivopts = '\0';
2911                 (*ivopts)++;
2912         }
2913         /* Parse IV mode */
2914         *ivmode = strrchr(tmp, '-');
2915         if (*ivmode) {
2916                 **ivmode = '\0';
2917                 (*ivmode)++;
2918         }
2919         /* The rest is crypto API spec */
2920         cipher_api = tmp;
2921
2922         /* Alloc AEAD, can be used only in new format. */
2923         if (crypt_integrity_aead(cc)) {
2924                 ret = crypt_ctr_auth_cipher(cc, cipher_api);
2925                 if (ret < 0) {
2926                         ti->error = "Invalid AEAD cipher spec";
2927                         return ret;
2928                 }
2929         }
2930
2931         if (*ivmode && !strcmp(*ivmode, "lmk"))
2932                 cc->tfms_count = 64;
2933
2934         if (*ivmode && !strcmp(*ivmode, "essiv")) {
2935                 if (!*ivopts) {
2936                         ti->error = "Digest algorithm missing for ESSIV mode";
2937                         return -EINVAL;
2938                 }
2939                 ret = snprintf(buf, CRYPTO_MAX_ALG_NAME, "essiv(%s,%s)",
2940                                cipher_api, *ivopts);
2941                 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2942                         ti->error = "Cannot allocate cipher string";
2943                         return -ENOMEM;
2944                 }
2945                 cipher_api = buf;
2946         }
2947
2948         cc->key_parts = cc->tfms_count;
2949
2950         /* Allocate cipher */
2951         ret = crypt_alloc_tfms(cc, cipher_api);
2952         if (ret < 0) {
2953                 ti->error = "Error allocating crypto tfm";
2954                 return ret;
2955         }
2956
2957         if (crypt_integrity_aead(cc))
2958                 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2959         else
2960                 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2961
2962         return 0;
2963 }
2964
2965 static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
2966                                 char **ivmode, char **ivopts)
2967 {
2968         struct crypt_config *cc = ti->private;
2969         char *tmp, *cipher, *chainmode, *keycount;
2970         char *cipher_api = NULL;
2971         int ret = -EINVAL;
2972         char dummy;
2973
2974         if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
2975                 ti->error = "Bad cipher specification";
2976                 return -EINVAL;
2977         }
2978
2979         /*
2980          * Legacy dm-crypt cipher specification
2981          * cipher[:keycount]-mode-iv:ivopts
2982          */
2983         tmp = cipher_in;
2984         keycount = strsep(&tmp, "-");
2985         cipher = strsep(&keycount, ":");
2986
2987         if (!keycount)
2988                 cc->tfms_count = 1;
2989         else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
2990                  !is_power_of_2(cc->tfms_count)) {
2991                 ti->error = "Bad cipher key count specification";
2992                 return -EINVAL;
2993         }
2994         cc->key_parts = cc->tfms_count;
2995
2996         chainmode = strsep(&tmp, "-");
2997         *ivmode = strsep(&tmp, ":");
2998         *ivopts = tmp;
2999
3000         /*
3001          * For compatibility with the original dm-crypt mapping format, if
3002          * only the cipher name is supplied, use cbc-plain.
3003          */
3004         if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
3005                 chainmode = "cbc";
3006                 *ivmode = "plain";
3007         }
3008
3009         if (strcmp(chainmode, "ecb") && !*ivmode) {
3010                 ti->error = "IV mechanism required";
3011                 return -EINVAL;
3012         }
3013
3014         cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
3015         if (!cipher_api)
3016                 goto bad_mem;
3017
3018         if (*ivmode && !strcmp(*ivmode, "essiv")) {
3019                 if (!*ivopts) {
3020                         ti->error = "Digest algorithm missing for ESSIV mode";
3021                         kfree(cipher_api);
3022                         return -EINVAL;
3023                 }
3024                 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
3025                                "essiv(%s(%s),%s)", chainmode, cipher, *ivopts);
3026         } else {
3027                 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
3028                                "%s(%s)", chainmode, cipher);
3029         }
3030         if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
3031                 kfree(cipher_api);
3032                 goto bad_mem;
3033         }
3034
3035         /* Allocate cipher */
3036         ret = crypt_alloc_tfms(cc, cipher_api);
3037         if (ret < 0) {
3038                 ti->error = "Error allocating crypto tfm";
3039                 kfree(cipher_api);
3040                 return ret;
3041         }
3042         kfree(cipher_api);
3043
3044         return 0;
3045 bad_mem:
3046         ti->error = "Cannot allocate cipher strings";
3047         return -ENOMEM;
3048 }
3049
3050 static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
3051 {
3052         struct crypt_config *cc = ti->private;
3053         char *ivmode = NULL, *ivopts = NULL;
3054         int ret;
3055
3056         cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
3057         if (!cc->cipher_string) {
3058                 ti->error = "Cannot allocate cipher strings";
3059                 return -ENOMEM;
3060         }
3061
3062         if (strstarts(cipher_in, "capi:"))
3063                 ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
3064         else
3065                 ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
3066         if (ret)
3067                 return ret;
3068
3069         /* Initialize IV */
3070         ret = crypt_ctr_ivmode(ti, ivmode);
3071         if (ret < 0)
3072                 return ret;
3073
3074         /* Initialize and set key */
3075         ret = crypt_set_key(cc, key);
3076         if (ret < 0) {
3077                 ti->error = "Error decoding and setting key";
3078                 return ret;
3079         }
3080
3081         /* Allocate IV */
3082         if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
3083                 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
3084                 if (ret < 0) {
3085                         ti->error = "Error creating IV";
3086                         return ret;
3087                 }
3088         }
3089
3090         /* Initialize IV (set keys for ESSIV etc) */
3091         if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
3092                 ret = cc->iv_gen_ops->init(cc);
3093                 if (ret < 0) {
3094                         ti->error = "Error initialising IV";
3095                         return ret;
3096                 }
3097         }
3098
3099         /* wipe the kernel key payload copy */
3100         if (cc->key_string)
3101                 memset(cc->key, 0, cc->key_size * sizeof(u8));
3102
3103         return ret;
3104 }
3105
3106 static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
3107 {
3108         struct crypt_config *cc = ti->private;
3109         struct dm_arg_set as;
3110         static const struct dm_arg _args[] = {
3111                 {0, 8, "Invalid number of feature args"},
3112         };
3113         unsigned int opt_params, val;
3114         const char *opt_string, *sval;
3115         char dummy;
3116         int ret;
3117
3118         /* Optional parameters */
3119         as.argc = argc;
3120         as.argv = argv;
3121
3122         ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
3123         if (ret)
3124                 return ret;
3125
3126         while (opt_params--) {
3127                 opt_string = dm_shift_arg(&as);
3128                 if (!opt_string) {
3129                         ti->error = "Not enough feature arguments";
3130                         return -EINVAL;
3131                 }
3132
3133                 if (!strcasecmp(opt_string, "allow_discards"))
3134                         ti->num_discard_bios = 1;
3135
3136                 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
3137                         set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3138
3139                 else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
3140                         set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3141                 else if (!strcasecmp(opt_string, "no_read_workqueue"))
3142                         set_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3143                 else if (!strcasecmp(opt_string, "no_write_workqueue"))
3144                         set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3145                 else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
3146                         if (val == 0 || val > MAX_TAG_SIZE) {
3147                                 ti->error = "Invalid integrity arguments";
3148                                 return -EINVAL;
3149                         }
3150                         cc->on_disk_tag_size = val;
3151                         sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
3152                         if (!strcasecmp(sval, "aead")) {
3153                                 set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
3154                         } else  if (strcasecmp(sval, "none")) {
3155                                 ti->error = "Unknown integrity profile";
3156                                 return -EINVAL;
3157                         }
3158
3159                         cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
3160                         if (!cc->cipher_auth)
3161                                 return -ENOMEM;
3162                 } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
3163                         if (cc->sector_size < (1 << SECTOR_SHIFT) ||
3164                             cc->sector_size > 4096 ||
3165                             (cc->sector_size & (cc->sector_size - 1))) {
3166                                 ti->error = "Invalid feature value for sector_size";
3167                                 return -EINVAL;
3168                         }
3169                         if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
3170                                 ti->error = "Device size is not multiple of sector_size feature";
3171                                 return -EINVAL;
3172                         }
3173                         cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
3174                 } else if (!strcasecmp(opt_string, "iv_large_sectors"))
3175                         set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3176                 else {
3177                         ti->error = "Invalid feature arguments";
3178                         return -EINVAL;
3179                 }
3180         }
3181
3182         return 0;
3183 }
3184
3185 #ifdef CONFIG_BLK_DEV_ZONED
3186 static int crypt_report_zones(struct dm_target *ti,
3187                 struct dm_report_zones_args *args, unsigned int nr_zones)
3188 {
3189         struct crypt_config *cc = ti->private;
3190
3191         return dm_report_zones(cc->dev->bdev, cc->start,
3192                         cc->start + dm_target_offset(ti, args->next_sector),
3193                         args, nr_zones);
3194 }
3195 #else
3196 #define crypt_report_zones NULL
3197 #endif
3198
3199 /*
3200  * Construct an encryption mapping:
3201  * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
3202  */
3203 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
3204 {
3205         struct crypt_config *cc;
3206         const char *devname = dm_table_device_name(ti->table);
3207         int key_size;
3208         unsigned int align_mask;
3209         unsigned long long tmpll;
3210         int ret;
3211         size_t iv_size_padding, additional_req_size;
3212         char dummy;
3213
3214         if (argc < 5) {
3215                 ti->error = "Not enough arguments";
3216                 return -EINVAL;
3217         }
3218
3219         key_size = get_key_size(&argv[1]);
3220         if (key_size < 0) {
3221                 ti->error = "Cannot parse key size";
3222                 return -EINVAL;
3223         }
3224
3225         cc = kzalloc(struct_size(cc, key, key_size), GFP_KERNEL);
3226         if (!cc) {
3227                 ti->error = "Cannot allocate encryption context";
3228                 return -ENOMEM;
3229         }
3230         cc->key_size = key_size;
3231         cc->sector_size = (1 << SECTOR_SHIFT);
3232         cc->sector_shift = 0;
3233
3234         ti->private = cc;
3235
3236         spin_lock(&dm_crypt_clients_lock);
3237         dm_crypt_clients_n++;
3238         crypt_calculate_pages_per_client();
3239         spin_unlock(&dm_crypt_clients_lock);
3240
3241         ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
3242         if (ret < 0)
3243                 goto bad;
3244
3245         /* Optional parameters need to be read before cipher constructor */
3246         if (argc > 5) {
3247                 ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
3248                 if (ret)
3249                         goto bad;
3250         }
3251
3252         ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
3253         if (ret < 0)
3254                 goto bad;
3255
3256         if (crypt_integrity_aead(cc)) {
3257                 cc->dmreq_start = sizeof(struct aead_request);
3258                 cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
3259                 align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
3260         } else {
3261                 cc->dmreq_start = sizeof(struct skcipher_request);
3262                 cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
3263                 align_mask = crypto_skcipher_alignmask(any_tfm(cc));
3264         }
3265         cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
3266
3267         if (align_mask < CRYPTO_MINALIGN) {
3268                 /* Allocate the padding exactly */
3269                 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
3270                                 & align_mask;
3271         } else {
3272                 /*
3273                  * If the cipher requires greater alignment than kmalloc
3274                  * alignment, we don't know the exact position of the
3275                  * initialization vector. We must assume worst case.
3276                  */
3277                 iv_size_padding = align_mask;
3278         }
3279
3280         /*  ...| IV + padding | original IV | original sec. number | bio tag offset | */
3281         additional_req_size = sizeof(struct dm_crypt_request) +
3282                 iv_size_padding + cc->iv_size +
3283                 cc->iv_size +
3284                 sizeof(uint64_t) +
3285                 sizeof(unsigned int);
3286
3287         ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
3288         if (ret) {
3289                 ti->error = "Cannot allocate crypt request mempool";
3290                 goto bad;
3291         }
3292
3293         cc->per_bio_data_size = ti->per_io_data_size =
3294                 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
3295                       ARCH_DMA_MINALIGN);
3296
3297         ret = mempool_init(&cc->page_pool, BIO_MAX_VECS, crypt_page_alloc, crypt_page_free, cc);
3298         if (ret) {
3299                 ti->error = "Cannot allocate page mempool";
3300                 goto bad;
3301         }
3302
3303         ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
3304         if (ret) {
3305                 ti->error = "Cannot allocate crypt bioset";
3306                 goto bad;
3307         }
3308
3309         mutex_init(&cc->bio_alloc_lock);
3310
3311         ret = -EINVAL;
3312         if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
3313             (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
3314                 ti->error = "Invalid iv_offset sector";
3315                 goto bad;
3316         }
3317         cc->iv_offset = tmpll;
3318
3319         ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
3320         if (ret) {
3321                 ti->error = "Device lookup failed";
3322                 goto bad;
3323         }
3324
3325         ret = -EINVAL;
3326         if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
3327                 ti->error = "Invalid device sector";
3328                 goto bad;
3329         }
3330         cc->start = tmpll;
3331
3332         if (bdev_is_zoned(cc->dev->bdev)) {
3333                 /*
3334                  * For zoned block devices, we need to preserve the issuer write
3335                  * ordering. To do so, disable write workqueues and force inline
3336                  * encryption completion.
3337                  */
3338                 set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3339                 set_bit(DM_CRYPT_WRITE_INLINE, &cc->flags);
3340
3341                 /*
3342                  * All zone append writes to a zone of a zoned block device will
3343                  * have the same BIO sector, the start of the zone. When the
3344                  * cypher IV mode uses sector values, all data targeting a
3345                  * zone will be encrypted using the first sector numbers of the
3346                  * zone. This will not result in write errors but will
3347                  * cause most reads to fail as reads will use the sector values
3348                  * for the actual data locations, resulting in IV mismatch.
3349                  * To avoid this problem, ask DM core to emulate zone append
3350                  * operations with regular writes.
3351                  */
3352                 DMDEBUG("Zone append operations will be emulated");
3353                 ti->emulate_zone_append = true;
3354         }
3355
3356         if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
3357                 ret = crypt_integrity_ctr(cc, ti);
3358                 if (ret)
3359                         goto bad;
3360
3361                 cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
3362                 if (!cc->tag_pool_max_sectors)
3363                         cc->tag_pool_max_sectors = 1;
3364
3365                 ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
3366                         cc->tag_pool_max_sectors * cc->on_disk_tag_size);
3367                 if (ret) {
3368                         ti->error = "Cannot allocate integrity tags mempool";
3369                         goto bad;
3370                 }
3371
3372                 cc->tag_pool_max_sectors <<= cc->sector_shift;
3373         }
3374
3375         ret = -ENOMEM;
3376         cc->io_queue = alloc_workqueue("kcryptd_io/%s", WQ_MEM_RECLAIM, 1, devname);
3377         if (!cc->io_queue) {
3378                 ti->error = "Couldn't create kcryptd io queue";
3379                 goto bad;
3380         }
3381
3382         if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3383                 cc->crypt_queue = alloc_workqueue("kcryptd/%s", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM,
3384                                                   1, devname);
3385         else
3386                 cc->crypt_queue = alloc_workqueue("kcryptd/%s",
3387                                                   WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
3388                                                   num_online_cpus(), devname);
3389         if (!cc->crypt_queue) {
3390                 ti->error = "Couldn't create kcryptd queue";
3391                 goto bad;
3392         }
3393
3394         spin_lock_init(&cc->write_thread_lock);
3395         cc->write_tree = RB_ROOT;
3396
3397         cc->write_thread = kthread_run(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
3398         if (IS_ERR(cc->write_thread)) {
3399                 ret = PTR_ERR(cc->write_thread);
3400                 cc->write_thread = NULL;
3401                 ti->error = "Couldn't spawn write thread";
3402                 goto bad;
3403         }
3404
3405         ti->num_flush_bios = 1;
3406         ti->limit_swap_bios = true;
3407         ti->accounts_remapped_io = true;
3408
3409         dm_audit_log_ctr(DM_MSG_PREFIX, ti, 1);
3410         return 0;
3411
3412 bad:
3413         dm_audit_log_ctr(DM_MSG_PREFIX, ti, 0);
3414         crypt_dtr(ti);
3415         return ret;
3416 }
3417
3418 static int crypt_map(struct dm_target *ti, struct bio *bio)
3419 {
3420         struct dm_crypt_io *io;
3421         struct crypt_config *cc = ti->private;
3422
3423         /*
3424          * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
3425          * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
3426          * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
3427          */
3428         if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
3429             bio_op(bio) == REQ_OP_DISCARD)) {
3430                 bio_set_dev(bio, cc->dev->bdev);
3431                 if (bio_sectors(bio))
3432                         bio->bi_iter.bi_sector = cc->start +
3433                                 dm_target_offset(ti, bio->bi_iter.bi_sector);
3434                 return DM_MAPIO_REMAPPED;
3435         }
3436
3437         /*
3438          * Check if bio is too large, split as needed.
3439          */
3440         if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_VECS << PAGE_SHIFT)) &&
3441             (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
3442                 dm_accept_partial_bio(bio, ((BIO_MAX_VECS << PAGE_SHIFT) >> SECTOR_SHIFT));
3443
3444         /*
3445          * Ensure that bio is a multiple of internal sector encryption size
3446          * and is aligned to this size as defined in IO hints.
3447          */
3448         if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
3449                 return DM_MAPIO_KILL;
3450
3451         if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
3452                 return DM_MAPIO_KILL;
3453
3454         io = dm_per_bio_data(bio, cc->per_bio_data_size);
3455         crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
3456
3457         if (cc->on_disk_tag_size) {
3458                 unsigned int tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
3459
3460                 if (unlikely(tag_len > KMALLOC_MAX_SIZE))
3461                         io->integrity_metadata = NULL;
3462                 else
3463                         io->integrity_metadata = kmalloc(tag_len, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
3464
3465                 if (unlikely(!io->integrity_metadata)) {
3466                         if (bio_sectors(bio) > cc->tag_pool_max_sectors)
3467                                 dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
3468                         io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
3469                         io->integrity_metadata_from_pool = true;
3470                 }
3471         }
3472
3473         if (crypt_integrity_aead(cc))
3474                 io->ctx.r.req_aead = (struct aead_request *)(io + 1);
3475         else
3476                 io->ctx.r.req = (struct skcipher_request *)(io + 1);
3477
3478         if (bio_data_dir(io->base_bio) == READ) {
3479                 if (kcryptd_io_read(io, CRYPT_MAP_READ_GFP))
3480                         kcryptd_queue_read(io);
3481         } else
3482                 kcryptd_queue_crypt(io);
3483
3484         return DM_MAPIO_SUBMITTED;
3485 }
3486
3487 static char hex2asc(unsigned char c)
3488 {
3489         return c + '0' + ((unsigned int)(9 - c) >> 4 & 0x27);
3490 }
3491
3492 static void crypt_status(struct dm_target *ti, status_type_t type,
3493                          unsigned int status_flags, char *result, unsigned int maxlen)
3494 {
3495         struct crypt_config *cc = ti->private;
3496         unsigned int i, sz = 0;
3497         int num_feature_args = 0;
3498
3499         switch (type) {
3500         case STATUSTYPE_INFO:
3501                 result[0] = '\0';
3502                 break;
3503
3504         case STATUSTYPE_TABLE:
3505                 DMEMIT("%s ", cc->cipher_string);
3506
3507                 if (cc->key_size > 0) {
3508                         if (cc->key_string)
3509                                 DMEMIT(":%u:%s", cc->key_size, cc->key_string);
3510                         else {
3511                                 for (i = 0; i < cc->key_size; i++) {
3512                                         DMEMIT("%c%c", hex2asc(cc->key[i] >> 4),
3513                                                hex2asc(cc->key[i] & 0xf));
3514                                 }
3515                         }
3516                 } else
3517                         DMEMIT("-");
3518
3519                 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
3520                                 cc->dev->name, (unsigned long long)cc->start);
3521
3522                 num_feature_args += !!ti->num_discard_bios;
3523                 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3524                 num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3525                 num_feature_args += test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3526                 num_feature_args += test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3527                 num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
3528                 num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3529                 if (cc->on_disk_tag_size)
3530                         num_feature_args++;
3531                 if (num_feature_args) {
3532                         DMEMIT(" %d", num_feature_args);
3533                         if (ti->num_discard_bios)
3534                                 DMEMIT(" allow_discards");
3535                         if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3536                                 DMEMIT(" same_cpu_crypt");
3537                         if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
3538                                 DMEMIT(" submit_from_crypt_cpus");
3539                         if (test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags))
3540                                 DMEMIT(" no_read_workqueue");
3541                         if (test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))
3542                                 DMEMIT(" no_write_workqueue");
3543                         if (cc->on_disk_tag_size)
3544                                 DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
3545                         if (cc->sector_size != (1 << SECTOR_SHIFT))
3546                                 DMEMIT(" sector_size:%d", cc->sector_size);
3547                         if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
3548                                 DMEMIT(" iv_large_sectors");
3549                 }
3550                 break;
3551
3552         case STATUSTYPE_IMA:
3553                 DMEMIT_TARGET_NAME_VERSION(ti->type);
3554                 DMEMIT(",allow_discards=%c", ti->num_discard_bios ? 'y' : 'n');
3555                 DMEMIT(",same_cpu_crypt=%c", test_bit(DM_CRYPT_SAME_CPU, &cc->flags) ? 'y' : 'n');
3556                 DMEMIT(",submit_from_crypt_cpus=%c", test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags) ?
3557                        'y' : 'n');
3558                 DMEMIT(",no_read_workqueue=%c", test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags) ?
3559                        'y' : 'n');
3560                 DMEMIT(",no_write_workqueue=%c", test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags) ?
3561                        'y' : 'n');
3562                 DMEMIT(",iv_large_sectors=%c", test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags) ?
3563                        'y' : 'n');
3564
3565                 if (cc->on_disk_tag_size)
3566                         DMEMIT(",integrity_tag_size=%u,cipher_auth=%s",
3567                                cc->on_disk_tag_size, cc->cipher_auth);
3568                 if (cc->sector_size != (1 << SECTOR_SHIFT))
3569                         DMEMIT(",sector_size=%d", cc->sector_size);
3570                 if (cc->cipher_string)
3571                         DMEMIT(",cipher_string=%s", cc->cipher_string);
3572
3573                 DMEMIT(",key_size=%u", cc->key_size);
3574                 DMEMIT(",key_parts=%u", cc->key_parts);
3575                 DMEMIT(",key_extra_size=%u", cc->key_extra_size);
3576                 DMEMIT(",key_mac_size=%u", cc->key_mac_size);
3577                 DMEMIT(";");
3578                 break;
3579         }
3580 }
3581
3582 static void crypt_postsuspend(struct dm_target *ti)
3583 {
3584         struct crypt_config *cc = ti->private;
3585
3586         set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3587 }
3588
3589 static int crypt_preresume(struct dm_target *ti)
3590 {
3591         struct crypt_config *cc = ti->private;
3592
3593         if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
3594                 DMERR("aborting resume - crypt key is not set.");
3595                 return -EAGAIN;
3596         }
3597
3598         return 0;
3599 }
3600
3601 static void crypt_resume(struct dm_target *ti)
3602 {
3603         struct crypt_config *cc = ti->private;
3604
3605         clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3606 }
3607
3608 /* Message interface
3609  *      key set <key>
3610  *      key wipe
3611  */
3612 static int crypt_message(struct dm_target *ti, unsigned int argc, char **argv,
3613                          char *result, unsigned int maxlen)
3614 {
3615         struct crypt_config *cc = ti->private;
3616         int key_size, ret = -EINVAL;
3617
3618         if (argc < 2)
3619                 goto error;
3620
3621         if (!strcasecmp(argv[0], "key")) {
3622                 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
3623                         DMWARN("not suspended during key manipulation.");
3624                         return -EINVAL;
3625                 }
3626                 if (argc == 3 && !strcasecmp(argv[1], "set")) {
3627                         /* The key size may not be changed. */
3628                         key_size = get_key_size(&argv[2]);
3629                         if (key_size < 0 || cc->key_size != key_size) {
3630                                 memset(argv[2], '0', strlen(argv[2]));
3631                                 return -EINVAL;
3632                         }
3633
3634                         ret = crypt_set_key(cc, argv[2]);
3635                         if (ret)
3636                                 return ret;
3637                         if (cc->iv_gen_ops && cc->iv_gen_ops->init)
3638                                 ret = cc->iv_gen_ops->init(cc);
3639                         /* wipe the kernel key payload copy */
3640                         if (cc->key_string)
3641                                 memset(cc->key, 0, cc->key_size * sizeof(u8));
3642                         return ret;
3643                 }
3644                 if (argc == 2 && !strcasecmp(argv[1], "wipe"))
3645                         return crypt_wipe_key(cc);
3646         }
3647
3648 error:
3649         DMWARN("unrecognised message received.");
3650         return -EINVAL;
3651 }
3652
3653 static int crypt_iterate_devices(struct dm_target *ti,
3654                                  iterate_devices_callout_fn fn, void *data)
3655 {
3656         struct crypt_config *cc = ti->private;
3657
3658         return fn(ti, cc->dev, cc->start, ti->len, data);
3659 }
3660
3661 static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
3662 {
3663         struct crypt_config *cc = ti->private;
3664
3665         /*
3666          * Unfortunate constraint that is required to avoid the potential
3667          * for exceeding underlying device's max_segments limits -- due to
3668          * crypt_alloc_buffer() possibly allocating pages for the encryption
3669          * bio that are not as physically contiguous as the original bio.
3670          */
3671         limits->max_segment_size = PAGE_SIZE;
3672
3673         limits->logical_block_size =
3674                 max_t(unsigned int, limits->logical_block_size, cc->sector_size);
3675         limits->physical_block_size =
3676                 max_t(unsigned int, limits->physical_block_size, cc->sector_size);
3677         limits->io_min = max_t(unsigned int, limits->io_min, cc->sector_size);
3678         limits->dma_alignment = limits->logical_block_size - 1;
3679 }
3680
3681 static struct target_type crypt_target = {
3682         .name   = "crypt",
3683         .version = {1, 24, 0},
3684         .module = THIS_MODULE,
3685         .ctr    = crypt_ctr,
3686         .dtr    = crypt_dtr,
3687         .features = DM_TARGET_ZONED_HM,
3688         .report_zones = crypt_report_zones,
3689         .map    = crypt_map,
3690         .status = crypt_status,
3691         .postsuspend = crypt_postsuspend,
3692         .preresume = crypt_preresume,
3693         .resume = crypt_resume,
3694         .message = crypt_message,
3695         .iterate_devices = crypt_iterate_devices,
3696         .io_hints = crypt_io_hints,
3697 };
3698 module_dm(crypt);
3699
3700 MODULE_AUTHOR("Jana Saout <jana@saout.de>");
3701 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
3702 MODULE_LICENSE("GPL");