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