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