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