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