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