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