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