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