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