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