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