xref: /openbmc/linux/drivers/md/dm-crypt.c (revision 3fd53533)
11da177e4SLinus Torvalds /*
2bf14299fSJana Saout  * Copyright (C) 2003 Jana Saout <jana@saout.de>
31da177e4SLinus Torvalds  * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
4bbb16584SMilan Broz  * Copyright (C) 2006-2020 Red Hat, Inc. All rights reserved.
5bbb16584SMilan Broz  * Copyright (C) 2013-2020 Milan Broz <gmazyland@gmail.com>
61da177e4SLinus Torvalds  *
71da177e4SLinus Torvalds  * This file is released under the GPL.
81da177e4SLinus Torvalds  */
91da177e4SLinus Torvalds 
1043d69034SMilan Broz #include <linux/completion.h>
11d1806f6aSHerbert Xu #include <linux/err.h>
121da177e4SLinus Torvalds #include <linux/module.h>
131da177e4SLinus Torvalds #include <linux/init.h>
141da177e4SLinus Torvalds #include <linux/kernel.h>
15c538f6ecSOndrej Kozina #include <linux/key.h>
161da177e4SLinus Torvalds #include <linux/bio.h>
171da177e4SLinus Torvalds #include <linux/blkdev.h>
181da177e4SLinus Torvalds #include <linux/mempool.h>
191da177e4SLinus Torvalds #include <linux/slab.h>
201da177e4SLinus Torvalds #include <linux/crypto.h>
211da177e4SLinus Torvalds #include <linux/workqueue.h>
22dc267621SMikulas Patocka #include <linux/kthread.h>
233fcfab16SAndrew Morton #include <linux/backing-dev.h>
2460063497SArun Sharma #include <linux/atomic.h>
25378f058cSDavid Hardeman #include <linux/scatterlist.h>
26b3c5fd30SMikulas Patocka #include <linux/rbtree.h>
27027c431cSOndrej Kozina #include <linux/ctype.h>
281da177e4SLinus Torvalds #include <asm/page.h>
2948527fa7SRik Snel #include <asm/unaligned.h>
3034745785SMilan Broz #include <crypto/hash.h>
3134745785SMilan Broz #include <crypto/md5.h>
3234745785SMilan Broz #include <crypto/algapi.h>
33bbdb23b5SHerbert Xu #include <crypto/skcipher.h>
34ef43aa38SMilan Broz #include <crypto/aead.h>
35ef43aa38SMilan Broz #include <crypto/authenc.h>
36ef43aa38SMilan Broz #include <linux/rtnetlink.h> /* for struct rtattr and RTA macros only */
37c538f6ecSOndrej Kozina #include <keys/user-type.h>
381da177e4SLinus Torvalds 
39586e80e6SMikulas Patocka #include <linux/device-mapper.h>
401da177e4SLinus Torvalds 
4172d94861SAlasdair G Kergon #define DM_MSG_PREFIX "crypt"
421da177e4SLinus Torvalds 
431da177e4SLinus Torvalds /*
441da177e4SLinus Torvalds  * context holding the current state of a multi-part conversion
451da177e4SLinus Torvalds  */
461da177e4SLinus Torvalds struct convert_context {
4743d69034SMilan Broz 	struct completion restart;
481da177e4SLinus Torvalds 	struct bio *bio_in;
491da177e4SLinus Torvalds 	struct bio *bio_out;
50003b5c57SKent Overstreet 	struct bvec_iter iter_in;
51003b5c57SKent Overstreet 	struct bvec_iter iter_out;
528d683dcdSAliOS system security 	u64 cc_sector;
5340b6229bSMikulas Patocka 	atomic_t cc_pending;
54ef43aa38SMilan Broz 	union {
55bbdb23b5SHerbert Xu 		struct skcipher_request *req;
56ef43aa38SMilan Broz 		struct aead_request *req_aead;
57ef43aa38SMilan Broz 	} r;
58ef43aa38SMilan Broz 
591da177e4SLinus Torvalds };
601da177e4SLinus Torvalds 
6153017030SMilan Broz /*
6253017030SMilan Broz  * per bio private data
6353017030SMilan Broz  */
6453017030SMilan Broz struct dm_crypt_io {
6549a8a920SAlasdair G Kergon 	struct crypt_config *cc;
6653017030SMilan Broz 	struct bio *base_bio;
67ef43aa38SMilan Broz 	u8 *integrity_metadata;
68ef43aa38SMilan Broz 	bool integrity_metadata_from_pool;
6953017030SMilan Broz 	struct work_struct work;
7053017030SMilan Broz 
7153017030SMilan Broz 	struct convert_context ctx;
7253017030SMilan Broz 
7340b6229bSMikulas Patocka 	atomic_t io_pending;
744e4cbee9SChristoph Hellwig 	blk_status_t error;
750c395b0fSMilan Broz 	sector_t sector;
76dc267621SMikulas Patocka 
77b3c5fd30SMikulas Patocka 	struct rb_node rb_node;
78298a9fa0SMikulas Patocka } CRYPTO_MINALIGN_ATTR;
7953017030SMilan Broz 
8001482b76SMilan Broz struct dm_crypt_request {
81b2174eebSHuang Ying 	struct convert_context *ctx;
82ef43aa38SMilan Broz 	struct scatterlist sg_in[4];
83ef43aa38SMilan Broz 	struct scatterlist sg_out[4];
848d683dcdSAliOS system security 	u64 iv_sector;
8501482b76SMilan Broz };
8601482b76SMilan Broz 
871da177e4SLinus Torvalds struct crypt_config;
881da177e4SLinus Torvalds 
891da177e4SLinus Torvalds struct crypt_iv_operations {
901da177e4SLinus Torvalds 	int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
911da177e4SLinus Torvalds 		   const char *opts);
921da177e4SLinus Torvalds 	void (*dtr)(struct crypt_config *cc);
93b95bf2d3SMilan Broz 	int (*init)(struct crypt_config *cc);
94542da317SMilan Broz 	int (*wipe)(struct crypt_config *cc);
952dc5327dSMilan Broz 	int (*generator)(struct crypt_config *cc, u8 *iv,
962dc5327dSMilan Broz 			 struct dm_crypt_request *dmreq);
972dc5327dSMilan Broz 	int (*post)(struct crypt_config *cc, u8 *iv,
982dc5327dSMilan Broz 		    struct dm_crypt_request *dmreq);
991da177e4SLinus Torvalds };
1001da177e4SLinus Torvalds 
10160473592SMilan Broz struct iv_benbi_private {
10260473592SMilan Broz 	int shift;
10360473592SMilan Broz };
10460473592SMilan Broz 
10534745785SMilan Broz #define LMK_SEED_SIZE 64 /* hash + 0 */
10634745785SMilan Broz struct iv_lmk_private {
10734745785SMilan Broz 	struct crypto_shash *hash_tfm;
10834745785SMilan Broz 	u8 *seed;
10934745785SMilan Broz };
11034745785SMilan Broz 
111ed04d981SMilan Broz #define TCW_WHITENING_SIZE 16
112ed04d981SMilan Broz struct iv_tcw_private {
113ed04d981SMilan Broz 	struct crypto_shash *crc32_tfm;
114ed04d981SMilan Broz 	u8 *iv_seed;
115ed04d981SMilan Broz 	u8 *whitening;
116ed04d981SMilan Broz };
117ed04d981SMilan Broz 
118bbb16584SMilan Broz #define ELEPHANT_MAX_KEY_SIZE 32
119bbb16584SMilan Broz struct iv_elephant_private {
120bbb16584SMilan Broz 	struct crypto_skcipher *tfm;
121bbb16584SMilan Broz };
122bbb16584SMilan Broz 
1231da177e4SLinus Torvalds /*
1241da177e4SLinus Torvalds  * Crypt: maps a linear range of a block device
1251da177e4SLinus Torvalds  * and encrypts / decrypts at the same time.
1261da177e4SLinus Torvalds  */
1270f5d8e6eSMikulas Patocka enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
128f659b100SRabin Vincent 	     DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD };
129c0297721SAndi Kleen 
130ef43aa38SMilan Broz enum cipher_flags {
131ef43aa38SMilan Broz 	CRYPT_MODE_INTEGRITY_AEAD,	/* Use authenticated mode for cihper */
1328f0009a2SMilan Broz 	CRYPT_IV_LARGE_SECTORS,		/* Calculate IV from sector_size, not 512B sectors */
133bbb16584SMilan Broz 	CRYPT_ENCRYPT_PREPROCESS,	/* Must preprocess data for encryption (elephant) */
134ef43aa38SMilan Broz };
135ef43aa38SMilan Broz 
136c0297721SAndi Kleen /*
137610f2de3SMikulas Patocka  * The fields in here must be read only after initialization.
138c0297721SAndi Kleen  */
1391da177e4SLinus Torvalds struct crypt_config {
1401da177e4SLinus Torvalds 	struct dm_dev *dev;
1411da177e4SLinus Torvalds 	sector_t start;
1421da177e4SLinus Torvalds 
1435059353dSMikulas Patocka 	struct percpu_counter n_allocated_pages;
1445059353dSMikulas Patocka 
145cabf08e4SMilan Broz 	struct workqueue_struct *io_queue;
146cabf08e4SMilan Broz 	struct workqueue_struct *crypt_queue;
1473f1e9070SMilan Broz 
148c7329effSMikulas Patocka 	spinlock_t write_thread_lock;
14972d711c8SMike Snitzer 	struct task_struct *write_thread;
150b3c5fd30SMikulas Patocka 	struct rb_root write_tree;
151dc267621SMikulas Patocka 
1527dbcd137SMilan Broz 	char *cipher_string;
153ef43aa38SMilan Broz 	char *cipher_auth;
154c538f6ecSOndrej Kozina 	char *key_string;
1555ebaee6dSMilan Broz 
1561b1b58f5SJulia Lawall 	const struct crypt_iv_operations *iv_gen_ops;
15779066ad3SHerbert Xu 	union {
15860473592SMilan Broz 		struct iv_benbi_private benbi;
15934745785SMilan Broz 		struct iv_lmk_private lmk;
160ed04d981SMilan Broz 		struct iv_tcw_private tcw;
161bbb16584SMilan Broz 		struct iv_elephant_private elephant;
16279066ad3SHerbert Xu 	} iv_gen_private;
1638d683dcdSAliOS system security 	u64 iv_offset;
1641da177e4SLinus Torvalds 	unsigned int iv_size;
165ff3af92bSMikulas Patocka 	unsigned short int sector_size;
166ff3af92bSMikulas Patocka 	unsigned char sector_shift;
1671da177e4SLinus Torvalds 
168ef43aa38SMilan Broz 	union {
169bbdb23b5SHerbert Xu 		struct crypto_skcipher **tfms;
170ef43aa38SMilan Broz 		struct crypto_aead **tfms_aead;
171ef43aa38SMilan Broz 	} cipher_tfm;
172d1f96423SMilan Broz 	unsigned tfms_count;
173ef43aa38SMilan Broz 	unsigned long cipher_flags;
174c0297721SAndi Kleen 
175c0297721SAndi Kleen 	/*
176ddd42edfSMilan Broz 	 * Layout of each crypto request:
177ddd42edfSMilan Broz 	 *
178bbdb23b5SHerbert Xu 	 *   struct skcipher_request
179ddd42edfSMilan Broz 	 *      context
180ddd42edfSMilan Broz 	 *      padding
181ddd42edfSMilan Broz 	 *   struct dm_crypt_request
182ddd42edfSMilan Broz 	 *      padding
183ddd42edfSMilan Broz 	 *   IV
184ddd42edfSMilan Broz 	 *
185ddd42edfSMilan Broz 	 * The padding is added so that dm_crypt_request and the IV are
186ddd42edfSMilan Broz 	 * correctly aligned.
187ddd42edfSMilan Broz 	 */
188ddd42edfSMilan Broz 	unsigned int dmreq_start;
189ddd42edfSMilan Broz 
190298a9fa0SMikulas Patocka 	unsigned int per_bio_data_size;
191298a9fa0SMikulas Patocka 
192e48d4bbfSMilan Broz 	unsigned long flags;
1931da177e4SLinus Torvalds 	unsigned int key_size;
194da31a078SMilan Broz 	unsigned int key_parts;      /* independent parts in key buffer */
195da31a078SMilan Broz 	unsigned int key_extra_size; /* additional keys length */
196ef43aa38SMilan Broz 	unsigned int key_mac_size;   /* MAC key size for authenc(...) */
197ef43aa38SMilan Broz 
198ef43aa38SMilan Broz 	unsigned int integrity_tag_size;
199ef43aa38SMilan Broz 	unsigned int integrity_iv_size;
200ef43aa38SMilan Broz 	unsigned int on_disk_tag_size;
201ef43aa38SMilan Broz 
20272d711c8SMike Snitzer 	/*
20372d711c8SMike Snitzer 	 * pool for per bio private data, crypto requests,
20472d711c8SMike Snitzer 	 * encryption requeusts/buffer pages and integrity tags
20572d711c8SMike Snitzer 	 */
20672d711c8SMike Snitzer 	unsigned tag_pool_max_sectors;
20772d711c8SMike Snitzer 	mempool_t tag_pool;
20872d711c8SMike Snitzer 	mempool_t req_pool;
20972d711c8SMike Snitzer 	mempool_t page_pool;
21072d711c8SMike Snitzer 
21172d711c8SMike Snitzer 	struct bio_set bs;
21272d711c8SMike Snitzer 	struct mutex bio_alloc_lock;
21372d711c8SMike Snitzer 
214ef43aa38SMilan Broz 	u8 *authenc_key; /* space for keys in authenc() format (if used) */
2151da177e4SLinus Torvalds 	u8 key[0];
2161da177e4SLinus Torvalds };
2171da177e4SLinus Torvalds 
2180a83df6cSMikulas Patocka #define MIN_IOS		64
219ef43aa38SMilan Broz #define MAX_TAG_SIZE	480
220ef43aa38SMilan Broz #define POOL_ENTRY_SIZE	512
2211da177e4SLinus Torvalds 
2225059353dSMikulas Patocka static DEFINE_SPINLOCK(dm_crypt_clients_lock);
2235059353dSMikulas Patocka static unsigned dm_crypt_clients_n = 0;
2245059353dSMikulas Patocka static volatile unsigned long dm_crypt_pages_per_client;
2255059353dSMikulas Patocka #define DM_CRYPT_MEMORY_PERCENT			2
2265059353dSMikulas Patocka #define DM_CRYPT_MIN_PAGES_PER_CLIENT		(BIO_MAX_PAGES * 16)
2275059353dSMikulas Patocka 
228028867acSAlasdair G Kergon static void clone_init(struct dm_crypt_io *, struct bio *);
229395b167cSAlasdair G Kergon static void kcryptd_queue_crypt(struct dm_crypt_io *io);
230ef43aa38SMilan Broz static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
231ef43aa38SMilan Broz 					     struct scatterlist *sg);
232027581f3SOlaf Kirch 
2333fd53533SYang Yingliang static bool crypt_integrity_aead(struct crypt_config *cc);
2343fd53533SYang Yingliang 
235c0297721SAndi Kleen /*
23686f917adSEric Biggers  * Use this to access cipher attributes that are independent of the key.
237c0297721SAndi Kleen  */
238bbdb23b5SHerbert Xu static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
239c0297721SAndi Kleen {
240ef43aa38SMilan Broz 	return cc->cipher_tfm.tfms[0];
241ef43aa38SMilan Broz }
242ef43aa38SMilan Broz 
243ef43aa38SMilan Broz static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
244ef43aa38SMilan Broz {
245ef43aa38SMilan Broz 	return cc->cipher_tfm.tfms_aead[0];
246c0297721SAndi Kleen }
247c0297721SAndi Kleen 
2481da177e4SLinus Torvalds /*
2491da177e4SLinus Torvalds  * Different IV generation algorithms:
2501da177e4SLinus Torvalds  *
2513c164bd8SRik Snel  * plain: the initial vector is the 32-bit little-endian version of the sector
2523a4fa0a2SRobert P. J. Day  *        number, padded with zeros if necessary.
2531da177e4SLinus Torvalds  *
25461afef61SMilan Broz  * plain64: the initial vector is the 64-bit little-endian version of the sector
25561afef61SMilan Broz  *        number, padded with zeros if necessary.
25661afef61SMilan Broz  *
2577e3fd855SMilan Broz  * plain64be: the initial vector is the 64-bit big-endian version of the sector
2587e3fd855SMilan Broz  *        number, padded with zeros if necessary.
2597e3fd855SMilan Broz  *
2603c164bd8SRik Snel  * essiv: "encrypted sector|salt initial vector", the sector number is
2611da177e4SLinus Torvalds  *        encrypted with the bulk cipher using a salt as key. The salt
2621da177e4SLinus Torvalds  *        should be derived from the bulk cipher's key via hashing.
2631da177e4SLinus Torvalds  *
26448527fa7SRik Snel  * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
26548527fa7SRik Snel  *        (needed for LRW-32-AES and possible other narrow block modes)
26648527fa7SRik Snel  *
26746b47730SLudwig Nussel  * null: the initial vector is always zero.  Provides compatibility with
26846b47730SLudwig Nussel  *       obsolete loop_fish2 devices.  Do not use for new devices.
26946b47730SLudwig Nussel  *
27034745785SMilan Broz  * lmk:  Compatible implementation of the block chaining mode used
27134745785SMilan Broz  *       by the Loop-AES block device encryption system
27234745785SMilan Broz  *       designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
27334745785SMilan Broz  *       It operates on full 512 byte sectors and uses CBC
27434745785SMilan Broz  *       with an IV derived from the sector number, the data and
27534745785SMilan Broz  *       optionally extra IV seed.
27634745785SMilan Broz  *       This means that after decryption the first block
27734745785SMilan Broz  *       of sector must be tweaked according to decrypted data.
27834745785SMilan Broz  *       Loop-AES can use three encryption schemes:
27934745785SMilan Broz  *         version 1: is plain aes-cbc mode
28034745785SMilan Broz  *         version 2: uses 64 multikey scheme with lmk IV generator
28134745785SMilan Broz  *         version 3: the same as version 2 with additional IV seed
28234745785SMilan Broz  *                   (it uses 65 keys, last key is used as IV seed)
28334745785SMilan Broz  *
284ed04d981SMilan Broz  * tcw:  Compatible implementation of the block chaining mode used
285ed04d981SMilan Broz  *       by the TrueCrypt device encryption system (prior to version 4.1).
286e44f23b3SMilan Broz  *       For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
287ed04d981SMilan Broz  *       It operates on full 512 byte sectors and uses CBC
288ed04d981SMilan Broz  *       with an IV derived from initial key and the sector number.
289ed04d981SMilan Broz  *       In addition, whitening value is applied on every sector, whitening
290ed04d981SMilan Broz  *       is calculated from initial key, sector number and mixed using CRC32.
291ed04d981SMilan Broz  *       Note that this encryption scheme is vulnerable to watermarking attacks
292ed04d981SMilan Broz  *       and should be used for old compatible containers access only.
293b9411d73SMilan Broz  *
294b9411d73SMilan Broz  * eboiv: Encrypted byte-offset IV (used in Bitlocker in CBC mode)
295b9411d73SMilan Broz  *        The IV is encrypted little-endian byte-offset (with the same key
296b9411d73SMilan Broz  *        and cipher as the volume).
297bbb16584SMilan Broz  *
298bbb16584SMilan Broz  * elephant: The extended version of eboiv with additional Elephant diffuser
299bbb16584SMilan Broz  *           used with Bitlocker CBC mode.
300bbb16584SMilan Broz  *           This mode was used in older Windows systems
301bbb16584SMilan Broz  *           http://download.microsoft.com/download/0/2/3/0238acaf-d3bf-4a6d-b3d6-0a0be4bbb36e/bitlockercipher200608.pdf
3021da177e4SLinus Torvalds  */
3031da177e4SLinus Torvalds 
3042dc5327dSMilan Broz static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
3052dc5327dSMilan Broz 			      struct dm_crypt_request *dmreq)
3061da177e4SLinus Torvalds {
3071da177e4SLinus Torvalds 	memset(iv, 0, cc->iv_size);
308283a8328SAlasdair G Kergon 	*(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
3091da177e4SLinus Torvalds 
3101da177e4SLinus Torvalds 	return 0;
3111da177e4SLinus Torvalds }
3121da177e4SLinus Torvalds 
31361afef61SMilan Broz static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
3142dc5327dSMilan Broz 				struct dm_crypt_request *dmreq)
31561afef61SMilan Broz {
31661afef61SMilan Broz 	memset(iv, 0, cc->iv_size);
317283a8328SAlasdair G Kergon 	*(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
31861afef61SMilan Broz 
31961afef61SMilan Broz 	return 0;
32061afef61SMilan Broz }
32161afef61SMilan Broz 
3227e3fd855SMilan Broz static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
3237e3fd855SMilan Broz 				  struct dm_crypt_request *dmreq)
3247e3fd855SMilan Broz {
3257e3fd855SMilan Broz 	memset(iv, 0, cc->iv_size);
3267e3fd855SMilan Broz 	/* iv_size is at least of size u64; usually it is 16 bytes */
3277e3fd855SMilan Broz 	*(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
3287e3fd855SMilan Broz 
3297e3fd855SMilan Broz 	return 0;
3307e3fd855SMilan Broz }
3317e3fd855SMilan Broz 
3322dc5327dSMilan Broz static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
3332dc5327dSMilan Broz 			      struct dm_crypt_request *dmreq)
3341da177e4SLinus Torvalds {
335a1a262b6SArd Biesheuvel 	/*
336a1a262b6SArd Biesheuvel 	 * ESSIV encryption of the IV is now handled by the crypto API,
337a1a262b6SArd Biesheuvel 	 * so just pass the plain sector number here.
338a1a262b6SArd Biesheuvel 	 */
3391da177e4SLinus Torvalds 	memset(iv, 0, cc->iv_size);
340283a8328SAlasdair G Kergon 	*(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
341c0297721SAndi Kleen 
3421da177e4SLinus Torvalds 	return 0;
3431da177e4SLinus Torvalds }
3441da177e4SLinus Torvalds 
34548527fa7SRik Snel static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
34648527fa7SRik Snel 			      const char *opts)
34748527fa7SRik Snel {
3484ea9471fSMilan Broz 	unsigned bs;
3494ea9471fSMilan Broz 	int log;
3504ea9471fSMilan Broz 
3513fd53533SYang Yingliang 	if (crypt_integrity_aead(cc))
3524ea9471fSMilan Broz 		bs = crypto_aead_blocksize(any_tfm_aead(cc));
3534ea9471fSMilan Broz 	else
3544ea9471fSMilan Broz 		bs = crypto_skcipher_blocksize(any_tfm(cc));
3554ea9471fSMilan Broz 	log = ilog2(bs);
35648527fa7SRik Snel 
35748527fa7SRik Snel 	/* we need to calculate how far we must shift the sector count
35848527fa7SRik Snel 	 * to get the cipher block count, we use this shift in _gen */
35948527fa7SRik Snel 
36048527fa7SRik Snel 	if (1 << log != bs) {
36148527fa7SRik Snel 		ti->error = "cypher blocksize is not a power of 2";
36248527fa7SRik Snel 		return -EINVAL;
36348527fa7SRik Snel 	}
36448527fa7SRik Snel 
36548527fa7SRik Snel 	if (log > 9) {
36648527fa7SRik Snel 		ti->error = "cypher blocksize is > 512";
36748527fa7SRik Snel 		return -EINVAL;
36848527fa7SRik Snel 	}
36948527fa7SRik Snel 
37060473592SMilan Broz 	cc->iv_gen_private.benbi.shift = 9 - log;
37148527fa7SRik Snel 
37248527fa7SRik Snel 	return 0;
37348527fa7SRik Snel }
37448527fa7SRik Snel 
37548527fa7SRik Snel static void crypt_iv_benbi_dtr(struct crypt_config *cc)
37648527fa7SRik Snel {
37748527fa7SRik Snel }
37848527fa7SRik Snel 
3792dc5327dSMilan Broz static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
3802dc5327dSMilan Broz 			      struct dm_crypt_request *dmreq)
38148527fa7SRik Snel {
38279066ad3SHerbert Xu 	__be64 val;
38379066ad3SHerbert Xu 
38448527fa7SRik Snel 	memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
38579066ad3SHerbert Xu 
3862dc5327dSMilan Broz 	val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
38779066ad3SHerbert Xu 	put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
38848527fa7SRik Snel 
3891da177e4SLinus Torvalds 	return 0;
3901da177e4SLinus Torvalds }
3911da177e4SLinus Torvalds 
3922dc5327dSMilan Broz static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
3932dc5327dSMilan Broz 			     struct dm_crypt_request *dmreq)
39446b47730SLudwig Nussel {
39546b47730SLudwig Nussel 	memset(iv, 0, cc->iv_size);
39646b47730SLudwig Nussel 
39746b47730SLudwig Nussel 	return 0;
39846b47730SLudwig Nussel }
39946b47730SLudwig Nussel 
40034745785SMilan Broz static void crypt_iv_lmk_dtr(struct crypt_config *cc)
40134745785SMilan Broz {
40234745785SMilan Broz 	struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
40334745785SMilan Broz 
40434745785SMilan Broz 	if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
40534745785SMilan Broz 		crypto_free_shash(lmk->hash_tfm);
40634745785SMilan Broz 	lmk->hash_tfm = NULL;
40734745785SMilan Broz 
40834745785SMilan Broz 	kzfree(lmk->seed);
40934745785SMilan Broz 	lmk->seed = NULL;
41034745785SMilan Broz }
41134745785SMilan Broz 
41234745785SMilan Broz static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
41334745785SMilan Broz 			    const char *opts)
41434745785SMilan Broz {
41534745785SMilan Broz 	struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
41634745785SMilan Broz 
4178f0009a2SMilan Broz 	if (cc->sector_size != (1 << SECTOR_SHIFT)) {
4188f0009a2SMilan Broz 		ti->error = "Unsupported sector size for LMK";
4198f0009a2SMilan Broz 		return -EINVAL;
4208f0009a2SMilan Broz 	}
4218f0009a2SMilan Broz 
42234745785SMilan Broz 	lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
42334745785SMilan Broz 	if (IS_ERR(lmk->hash_tfm)) {
42434745785SMilan Broz 		ti->error = "Error initializing LMK hash";
42534745785SMilan Broz 		return PTR_ERR(lmk->hash_tfm);
42634745785SMilan Broz 	}
42734745785SMilan Broz 
42834745785SMilan Broz 	/* No seed in LMK version 2 */
42934745785SMilan Broz 	if (cc->key_parts == cc->tfms_count) {
43034745785SMilan Broz 		lmk->seed = NULL;
43134745785SMilan Broz 		return 0;
43234745785SMilan Broz 	}
43334745785SMilan Broz 
43434745785SMilan Broz 	lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
43534745785SMilan Broz 	if (!lmk->seed) {
43634745785SMilan Broz 		crypt_iv_lmk_dtr(cc);
43734745785SMilan Broz 		ti->error = "Error kmallocing seed storage in LMK";
43834745785SMilan Broz 		return -ENOMEM;
43934745785SMilan Broz 	}
44034745785SMilan Broz 
44134745785SMilan Broz 	return 0;
44234745785SMilan Broz }
44334745785SMilan Broz 
44434745785SMilan Broz static int crypt_iv_lmk_init(struct crypt_config *cc)
44534745785SMilan Broz {
44634745785SMilan Broz 	struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
44734745785SMilan Broz 	int subkey_size = cc->key_size / cc->key_parts;
44834745785SMilan Broz 
44934745785SMilan Broz 	/* LMK seed is on the position of LMK_KEYS + 1 key */
45034745785SMilan Broz 	if (lmk->seed)
45134745785SMilan Broz 		memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
45234745785SMilan Broz 		       crypto_shash_digestsize(lmk->hash_tfm));
45334745785SMilan Broz 
45434745785SMilan Broz 	return 0;
45534745785SMilan Broz }
45634745785SMilan Broz 
45734745785SMilan Broz static int crypt_iv_lmk_wipe(struct crypt_config *cc)
45834745785SMilan Broz {
45934745785SMilan Broz 	struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
46034745785SMilan Broz 
46134745785SMilan Broz 	if (lmk->seed)
46234745785SMilan Broz 		memset(lmk->seed, 0, LMK_SEED_SIZE);
46334745785SMilan Broz 
46434745785SMilan Broz 	return 0;
46534745785SMilan Broz }
46634745785SMilan Broz 
46734745785SMilan Broz static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
46834745785SMilan Broz 			    struct dm_crypt_request *dmreq,
46934745785SMilan Broz 			    u8 *data)
47034745785SMilan Broz {
47134745785SMilan Broz 	struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
472b6106265SJan-Simon Möller 	SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
47334745785SMilan Broz 	struct md5_state md5state;
474da31a078SMilan Broz 	__le32 buf[4];
47534745785SMilan Broz 	int i, r;
47634745785SMilan Broz 
477b6106265SJan-Simon Möller 	desc->tfm = lmk->hash_tfm;
47834745785SMilan Broz 
479b6106265SJan-Simon Möller 	r = crypto_shash_init(desc);
48034745785SMilan Broz 	if (r)
48134745785SMilan Broz 		return r;
48234745785SMilan Broz 
48334745785SMilan Broz 	if (lmk->seed) {
484b6106265SJan-Simon Möller 		r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
48534745785SMilan Broz 		if (r)
48634745785SMilan Broz 			return r;
48734745785SMilan Broz 	}
48834745785SMilan Broz 
48934745785SMilan Broz 	/* Sector is always 512B, block size 16, add data of blocks 1-31 */
490b6106265SJan-Simon Möller 	r = crypto_shash_update(desc, data + 16, 16 * 31);
49134745785SMilan Broz 	if (r)
49234745785SMilan Broz 		return r;
49334745785SMilan Broz 
49434745785SMilan Broz 	/* Sector is cropped to 56 bits here */
49534745785SMilan Broz 	buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
49634745785SMilan Broz 	buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
49734745785SMilan Broz 	buf[2] = cpu_to_le32(4024);
49834745785SMilan Broz 	buf[3] = 0;
499b6106265SJan-Simon Möller 	r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
50034745785SMilan Broz 	if (r)
50134745785SMilan Broz 		return r;
50234745785SMilan Broz 
50334745785SMilan Broz 	/* No MD5 padding here */
504b6106265SJan-Simon Möller 	r = crypto_shash_export(desc, &md5state);
50534745785SMilan Broz 	if (r)
50634745785SMilan Broz 		return r;
50734745785SMilan Broz 
50834745785SMilan Broz 	for (i = 0; i < MD5_HASH_WORDS; i++)
50934745785SMilan Broz 		__cpu_to_le32s(&md5state.hash[i]);
51034745785SMilan Broz 	memcpy(iv, &md5state.hash, cc->iv_size);
51134745785SMilan Broz 
51234745785SMilan Broz 	return 0;
51334745785SMilan Broz }
51434745785SMilan Broz 
51534745785SMilan Broz static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
51634745785SMilan Broz 			    struct dm_crypt_request *dmreq)
51734745785SMilan Broz {
518ef43aa38SMilan Broz 	struct scatterlist *sg;
51934745785SMilan Broz 	u8 *src;
52034745785SMilan Broz 	int r = 0;
52134745785SMilan Broz 
52234745785SMilan Broz 	if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
523ef43aa38SMilan Broz 		sg = crypt_get_sg_data(cc, dmreq->sg_in);
524ef43aa38SMilan Broz 		src = kmap_atomic(sg_page(sg));
525ef43aa38SMilan Broz 		r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
526c2e022cbSCong Wang 		kunmap_atomic(src);
52734745785SMilan Broz 	} else
52834745785SMilan Broz 		memset(iv, 0, cc->iv_size);
52934745785SMilan Broz 
53034745785SMilan Broz 	return r;
53134745785SMilan Broz }
53234745785SMilan Broz 
53334745785SMilan Broz static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
53434745785SMilan Broz 			     struct dm_crypt_request *dmreq)
53534745785SMilan Broz {
536ef43aa38SMilan Broz 	struct scatterlist *sg;
53734745785SMilan Broz 	u8 *dst;
53834745785SMilan Broz 	int r;
53934745785SMilan Broz 
54034745785SMilan Broz 	if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
54134745785SMilan Broz 		return 0;
54234745785SMilan Broz 
543ef43aa38SMilan Broz 	sg = crypt_get_sg_data(cc, dmreq->sg_out);
544ef43aa38SMilan Broz 	dst = kmap_atomic(sg_page(sg));
545ef43aa38SMilan Broz 	r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
54634745785SMilan Broz 
54734745785SMilan Broz 	/* Tweak the first block of plaintext sector */
54834745785SMilan Broz 	if (!r)
549ef43aa38SMilan Broz 		crypto_xor(dst + sg->offset, iv, cc->iv_size);
55034745785SMilan Broz 
551c2e022cbSCong Wang 	kunmap_atomic(dst);
55234745785SMilan Broz 	return r;
55334745785SMilan Broz }
55434745785SMilan Broz 
555ed04d981SMilan Broz static void crypt_iv_tcw_dtr(struct crypt_config *cc)
556ed04d981SMilan Broz {
557ed04d981SMilan Broz 	struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
558ed04d981SMilan Broz 
559ed04d981SMilan Broz 	kzfree(tcw->iv_seed);
560ed04d981SMilan Broz 	tcw->iv_seed = NULL;
561ed04d981SMilan Broz 	kzfree(tcw->whitening);
562ed04d981SMilan Broz 	tcw->whitening = NULL;
563ed04d981SMilan Broz 
564ed04d981SMilan Broz 	if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
565ed04d981SMilan Broz 		crypto_free_shash(tcw->crc32_tfm);
566ed04d981SMilan Broz 	tcw->crc32_tfm = NULL;
567ed04d981SMilan Broz }
568ed04d981SMilan Broz 
569ed04d981SMilan Broz static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
570ed04d981SMilan Broz 			    const char *opts)
571ed04d981SMilan Broz {
572ed04d981SMilan Broz 	struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
573ed04d981SMilan Broz 
5748f0009a2SMilan Broz 	if (cc->sector_size != (1 << SECTOR_SHIFT)) {
5758f0009a2SMilan Broz 		ti->error = "Unsupported sector size for TCW";
5768f0009a2SMilan Broz 		return -EINVAL;
5778f0009a2SMilan Broz 	}
5788f0009a2SMilan Broz 
579ed04d981SMilan Broz 	if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
580ed04d981SMilan Broz 		ti->error = "Wrong key size for TCW";
581ed04d981SMilan Broz 		return -EINVAL;
582ed04d981SMilan Broz 	}
583ed04d981SMilan Broz 
584ed04d981SMilan Broz 	tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
585ed04d981SMilan Broz 	if (IS_ERR(tcw->crc32_tfm)) {
586ed04d981SMilan Broz 		ti->error = "Error initializing CRC32 in TCW";
587ed04d981SMilan Broz 		return PTR_ERR(tcw->crc32_tfm);
588ed04d981SMilan Broz 	}
589ed04d981SMilan Broz 
590ed04d981SMilan Broz 	tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
591ed04d981SMilan Broz 	tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
592ed04d981SMilan Broz 	if (!tcw->iv_seed || !tcw->whitening) {
593ed04d981SMilan Broz 		crypt_iv_tcw_dtr(cc);
594ed04d981SMilan Broz 		ti->error = "Error allocating seed storage in TCW";
595ed04d981SMilan Broz 		return -ENOMEM;
596ed04d981SMilan Broz 	}
597ed04d981SMilan Broz 
598ed04d981SMilan Broz 	return 0;
599ed04d981SMilan Broz }
600ed04d981SMilan Broz 
601ed04d981SMilan Broz static int crypt_iv_tcw_init(struct crypt_config *cc)
602ed04d981SMilan Broz {
603ed04d981SMilan Broz 	struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
604ed04d981SMilan Broz 	int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
605ed04d981SMilan Broz 
606ed04d981SMilan Broz 	memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
607ed04d981SMilan Broz 	memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
608ed04d981SMilan Broz 	       TCW_WHITENING_SIZE);
609ed04d981SMilan Broz 
610ed04d981SMilan Broz 	return 0;
611ed04d981SMilan Broz }
612ed04d981SMilan Broz 
613ed04d981SMilan Broz static int crypt_iv_tcw_wipe(struct crypt_config *cc)
614ed04d981SMilan Broz {
615ed04d981SMilan Broz 	struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
616ed04d981SMilan Broz 
617ed04d981SMilan Broz 	memset(tcw->iv_seed, 0, cc->iv_size);
618ed04d981SMilan Broz 	memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
619ed04d981SMilan Broz 
620ed04d981SMilan Broz 	return 0;
621ed04d981SMilan Broz }
622ed04d981SMilan Broz 
623ed04d981SMilan Broz static int crypt_iv_tcw_whitening(struct crypt_config *cc,
624ed04d981SMilan Broz 				  struct dm_crypt_request *dmreq,
625ed04d981SMilan Broz 				  u8 *data)
626ed04d981SMilan Broz {
627ed04d981SMilan Broz 	struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
628350b5393SBart Van Assche 	__le64 sector = cpu_to_le64(dmreq->iv_sector);
629ed04d981SMilan Broz 	u8 buf[TCW_WHITENING_SIZE];
630b6106265SJan-Simon Möller 	SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
631ed04d981SMilan Broz 	int i, r;
632ed04d981SMilan Broz 
633ed04d981SMilan Broz 	/* xor whitening with sector number */
63445fe93dfSArd Biesheuvel 	crypto_xor_cpy(buf, tcw->whitening, (u8 *)&sector, 8);
63545fe93dfSArd Biesheuvel 	crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)&sector, 8);
636ed04d981SMilan Broz 
637ed04d981SMilan Broz 	/* calculate crc32 for every 32bit part and xor it */
638b6106265SJan-Simon Möller 	desc->tfm = tcw->crc32_tfm;
639ed04d981SMilan Broz 	for (i = 0; i < 4; i++) {
640b6106265SJan-Simon Möller 		r = crypto_shash_init(desc);
641ed04d981SMilan Broz 		if (r)
642ed04d981SMilan Broz 			goto out;
643b6106265SJan-Simon Möller 		r = crypto_shash_update(desc, &buf[i * 4], 4);
644ed04d981SMilan Broz 		if (r)
645ed04d981SMilan Broz 			goto out;
646b6106265SJan-Simon Möller 		r = crypto_shash_final(desc, &buf[i * 4]);
647ed04d981SMilan Broz 		if (r)
648ed04d981SMilan Broz 			goto out;
649ed04d981SMilan Broz 	}
650ed04d981SMilan Broz 	crypto_xor(&buf[0], &buf[12], 4);
651ed04d981SMilan Broz 	crypto_xor(&buf[4], &buf[8], 4);
652ed04d981SMilan Broz 
653ed04d981SMilan Broz 	/* apply whitening (8 bytes) to whole sector */
654ed04d981SMilan Broz 	for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
655ed04d981SMilan Broz 		crypto_xor(data + i * 8, buf, 8);
656ed04d981SMilan Broz out:
6571a71d6ffSMilan Broz 	memzero_explicit(buf, sizeof(buf));
658ed04d981SMilan Broz 	return r;
659ed04d981SMilan Broz }
660ed04d981SMilan Broz 
661ed04d981SMilan Broz static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
662ed04d981SMilan Broz 			    struct dm_crypt_request *dmreq)
663ed04d981SMilan Broz {
664ef43aa38SMilan Broz 	struct scatterlist *sg;
665ed04d981SMilan Broz 	struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
666350b5393SBart Van Assche 	__le64 sector = cpu_to_le64(dmreq->iv_sector);
667ed04d981SMilan Broz 	u8 *src;
668ed04d981SMilan Broz 	int r = 0;
669ed04d981SMilan Broz 
670ed04d981SMilan Broz 	/* Remove whitening from ciphertext */
671ed04d981SMilan Broz 	if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
672ef43aa38SMilan Broz 		sg = crypt_get_sg_data(cc, dmreq->sg_in);
673ef43aa38SMilan Broz 		src = kmap_atomic(sg_page(sg));
674ef43aa38SMilan Broz 		r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
675ed04d981SMilan Broz 		kunmap_atomic(src);
676ed04d981SMilan Broz 	}
677ed04d981SMilan Broz 
678ed04d981SMilan Broz 	/* Calculate IV */
67945fe93dfSArd Biesheuvel 	crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)&sector, 8);
680ed04d981SMilan Broz 	if (cc->iv_size > 8)
68145fe93dfSArd Biesheuvel 		crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)&sector,
68245fe93dfSArd Biesheuvel 			       cc->iv_size - 8);
683ed04d981SMilan Broz 
684ed04d981SMilan Broz 	return r;
685ed04d981SMilan Broz }
686ed04d981SMilan Broz 
687ed04d981SMilan Broz static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
688ed04d981SMilan Broz 			     struct dm_crypt_request *dmreq)
689ed04d981SMilan Broz {
690ef43aa38SMilan Broz 	struct scatterlist *sg;
691ed04d981SMilan Broz 	u8 *dst;
692ed04d981SMilan Broz 	int r;
693ed04d981SMilan Broz 
694ed04d981SMilan Broz 	if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
695ed04d981SMilan Broz 		return 0;
696ed04d981SMilan Broz 
697ed04d981SMilan Broz 	/* Apply whitening on ciphertext */
698ef43aa38SMilan Broz 	sg = crypt_get_sg_data(cc, dmreq->sg_out);
699ef43aa38SMilan Broz 	dst = kmap_atomic(sg_page(sg));
700ef43aa38SMilan Broz 	r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
701ed04d981SMilan Broz 	kunmap_atomic(dst);
702ed04d981SMilan Broz 
703ed04d981SMilan Broz 	return r;
704ed04d981SMilan Broz }
705ed04d981SMilan Broz 
706ef43aa38SMilan Broz static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
707ef43aa38SMilan Broz 				struct dm_crypt_request *dmreq)
708ef43aa38SMilan Broz {
709ef43aa38SMilan Broz 	/* Used only for writes, there must be an additional space to store IV */
710ef43aa38SMilan Broz 	get_random_bytes(iv, cc->iv_size);
711ef43aa38SMilan Broz 	return 0;
712ef43aa38SMilan Broz }
713ef43aa38SMilan Broz 
714b9411d73SMilan Broz static int crypt_iv_eboiv_ctr(struct crypt_config *cc, struct dm_target *ti,
715b9411d73SMilan Broz 			    const char *opts)
716b9411d73SMilan Broz {
7173fd53533SYang Yingliang 	if (crypt_integrity_aead(cc)) {
71839d13a1aSArd Biesheuvel 		ti->error = "AEAD transforms not supported for EBOIV";
719b9411d73SMilan Broz 		return -EINVAL;
720b9411d73SMilan Broz 	}
721b9411d73SMilan Broz 
72239d13a1aSArd Biesheuvel 	if (crypto_skcipher_blocksize(any_tfm(cc)) != cc->iv_size) {
72339d13a1aSArd Biesheuvel 		ti->error = "Block size of EBOIV cipher does "
72439d13a1aSArd Biesheuvel 			    "not match IV size of block cipher";
72539d13a1aSArd Biesheuvel 		return -EINVAL;
726b9411d73SMilan Broz 	}
727b9411d73SMilan Broz 
728b9411d73SMilan Broz 	return 0;
729b9411d73SMilan Broz }
730b9411d73SMilan Broz 
731b9411d73SMilan Broz static int crypt_iv_eboiv_gen(struct crypt_config *cc, u8 *iv,
732b9411d73SMilan Broz 			    struct dm_crypt_request *dmreq)
733b9411d73SMilan Broz {
73439d13a1aSArd Biesheuvel 	u8 buf[MAX_CIPHER_BLOCKSIZE] __aligned(__alignof__(__le64));
73539d13a1aSArd Biesheuvel 	struct skcipher_request *req;
73639d13a1aSArd Biesheuvel 	struct scatterlist src, dst;
73739d13a1aSArd Biesheuvel 	struct crypto_wait wait;
73839d13a1aSArd Biesheuvel 	int err;
739b9411d73SMilan Broz 
7409402e959SMikulas Patocka 	req = skcipher_request_alloc(any_tfm(cc), GFP_NOIO);
74139d13a1aSArd Biesheuvel 	if (!req)
74239d13a1aSArd Biesheuvel 		return -ENOMEM;
743b9411d73SMilan Broz 
74439d13a1aSArd Biesheuvel 	memset(buf, 0, cc->iv_size);
74539d13a1aSArd Biesheuvel 	*(__le64 *)buf = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
74639d13a1aSArd Biesheuvel 
74739d13a1aSArd Biesheuvel 	sg_init_one(&src, page_address(ZERO_PAGE(0)), cc->iv_size);
74839d13a1aSArd Biesheuvel 	sg_init_one(&dst, iv, cc->iv_size);
74939d13a1aSArd Biesheuvel 	skcipher_request_set_crypt(req, &src, &dst, cc->iv_size, buf);
75039d13a1aSArd Biesheuvel 	skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
75139d13a1aSArd Biesheuvel 	err = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
75239d13a1aSArd Biesheuvel 	skcipher_request_free(req);
75339d13a1aSArd Biesheuvel 
75439d13a1aSArd Biesheuvel 	return err;
755b9411d73SMilan Broz }
756b9411d73SMilan Broz 
757bbb16584SMilan Broz static void crypt_iv_elephant_dtr(struct crypt_config *cc)
758bbb16584SMilan Broz {
759bbb16584SMilan Broz 	struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
760bbb16584SMilan Broz 
761bbb16584SMilan Broz 	crypto_free_skcipher(elephant->tfm);
762bbb16584SMilan Broz 	elephant->tfm = NULL;
763bbb16584SMilan Broz }
764bbb16584SMilan Broz 
765bbb16584SMilan Broz static int crypt_iv_elephant_ctr(struct crypt_config *cc, struct dm_target *ti,
766bbb16584SMilan Broz 			    const char *opts)
767bbb16584SMilan Broz {
768bbb16584SMilan Broz 	struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
769bbb16584SMilan Broz 	int r;
770bbb16584SMilan Broz 
771bbb16584SMilan Broz 	elephant->tfm = crypto_alloc_skcipher("ecb(aes)", 0, 0);
772bbb16584SMilan Broz 	if (IS_ERR(elephant->tfm)) {
773bbb16584SMilan Broz 		r = PTR_ERR(elephant->tfm);
774bbb16584SMilan Broz 		elephant->tfm = NULL;
775bbb16584SMilan Broz 		return r;
776bbb16584SMilan Broz 	}
777bbb16584SMilan Broz 
778bbb16584SMilan Broz 	r = crypt_iv_eboiv_ctr(cc, ti, NULL);
779bbb16584SMilan Broz 	if (r)
780bbb16584SMilan Broz 		crypt_iv_elephant_dtr(cc);
781bbb16584SMilan Broz 	return r;
782bbb16584SMilan Broz }
783bbb16584SMilan Broz 
784bbb16584SMilan Broz static void diffuser_disk_to_cpu(u32 *d, size_t n)
785bbb16584SMilan Broz {
786bbb16584SMilan Broz #ifndef __LITTLE_ENDIAN
787bbb16584SMilan Broz 	int i;
788bbb16584SMilan Broz 
789bbb16584SMilan Broz 	for (i = 0; i < n; i++)
790bbb16584SMilan Broz 		d[i] = le32_to_cpu((__le32)d[i]);
791bbb16584SMilan Broz #endif
792bbb16584SMilan Broz }
793bbb16584SMilan Broz 
794bbb16584SMilan Broz static void diffuser_cpu_to_disk(__le32 *d, size_t n)
795bbb16584SMilan Broz {
796bbb16584SMilan Broz #ifndef __LITTLE_ENDIAN
797bbb16584SMilan Broz 	int i;
798bbb16584SMilan Broz 
799bbb16584SMilan Broz 	for (i = 0; i < n; i++)
800bbb16584SMilan Broz 		d[i] = cpu_to_le32((u32)d[i]);
801bbb16584SMilan Broz #endif
802bbb16584SMilan Broz }
803bbb16584SMilan Broz 
804bbb16584SMilan Broz static void diffuser_a_decrypt(u32 *d, size_t n)
805bbb16584SMilan Broz {
806bbb16584SMilan Broz 	int i, i1, i2, i3;
807bbb16584SMilan Broz 
808bbb16584SMilan Broz 	for (i = 0; i < 5; i++) {
809bbb16584SMilan Broz 		i1 = 0;
810bbb16584SMilan Broz 		i2 = n - 2;
811bbb16584SMilan Broz 		i3 = n - 5;
812bbb16584SMilan Broz 
813bbb16584SMilan Broz 		while (i1 < (n - 1)) {
814bbb16584SMilan Broz 			d[i1] += d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
815bbb16584SMilan Broz 			i1++; i2++; i3++;
816bbb16584SMilan Broz 
817bbb16584SMilan Broz 			if (i3 >= n)
818bbb16584SMilan Broz 				i3 -= n;
819bbb16584SMilan Broz 
820bbb16584SMilan Broz 			d[i1] += d[i2] ^ d[i3];
821bbb16584SMilan Broz 			i1++; i2++; i3++;
822bbb16584SMilan Broz 
823bbb16584SMilan Broz 			if (i2 >= n)
824bbb16584SMilan Broz 				i2 -= n;
825bbb16584SMilan Broz 
826bbb16584SMilan Broz 			d[i1] += d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
827bbb16584SMilan Broz 			i1++; i2++; i3++;
828bbb16584SMilan Broz 
829bbb16584SMilan Broz 			d[i1] += d[i2] ^ d[i3];
830bbb16584SMilan Broz 			i1++; i2++; i3++;
831bbb16584SMilan Broz 		}
832bbb16584SMilan Broz 	}
833bbb16584SMilan Broz }
834bbb16584SMilan Broz 
835bbb16584SMilan Broz static void diffuser_a_encrypt(u32 *d, size_t n)
836bbb16584SMilan Broz {
837bbb16584SMilan Broz 	int i, i1, i2, i3;
838bbb16584SMilan Broz 
839bbb16584SMilan Broz 	for (i = 0; i < 5; i++) {
840bbb16584SMilan Broz 		i1 = n - 1;
841bbb16584SMilan Broz 		i2 = n - 2 - 1;
842bbb16584SMilan Broz 		i3 = n - 5 - 1;
843bbb16584SMilan Broz 
844bbb16584SMilan Broz 		while (i1 > 0) {
845bbb16584SMilan Broz 			d[i1] -= d[i2] ^ d[i3];
846bbb16584SMilan Broz 			i1--; i2--; i3--;
847bbb16584SMilan Broz 
848bbb16584SMilan Broz 			d[i1] -= d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
849bbb16584SMilan Broz 			i1--; i2--; i3--;
850bbb16584SMilan Broz 
851bbb16584SMilan Broz 			if (i2 < 0)
852bbb16584SMilan Broz 				i2 += n;
853bbb16584SMilan Broz 
854bbb16584SMilan Broz 			d[i1] -= d[i2] ^ d[i3];
855bbb16584SMilan Broz 			i1--; i2--; i3--;
856bbb16584SMilan Broz 
857bbb16584SMilan Broz 			if (i3 < 0)
858bbb16584SMilan Broz 				i3 += n;
859bbb16584SMilan Broz 
860bbb16584SMilan Broz 			d[i1] -= d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
861bbb16584SMilan Broz 			i1--; i2--; i3--;
862bbb16584SMilan Broz 		}
863bbb16584SMilan Broz 	}
864bbb16584SMilan Broz }
865bbb16584SMilan Broz 
866bbb16584SMilan Broz static void diffuser_b_decrypt(u32 *d, size_t n)
867bbb16584SMilan Broz {
868bbb16584SMilan Broz 	int i, i1, i2, i3;
869bbb16584SMilan Broz 
870bbb16584SMilan Broz 	for (i = 0; i < 3; i++) {
871bbb16584SMilan Broz 		i1 = 0;
872bbb16584SMilan Broz 		i2 = 2;
873bbb16584SMilan Broz 		i3 = 5;
874bbb16584SMilan Broz 
875bbb16584SMilan Broz 		while (i1 < (n - 1)) {
876bbb16584SMilan Broz 			d[i1] += d[i2] ^ d[i3];
877bbb16584SMilan Broz 			i1++; i2++; i3++;
878bbb16584SMilan Broz 
879bbb16584SMilan Broz 			d[i1] += d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
880bbb16584SMilan Broz 			i1++; i2++; i3++;
881bbb16584SMilan Broz 
882bbb16584SMilan Broz 			if (i2 >= n)
883bbb16584SMilan Broz 				i2 -= n;
884bbb16584SMilan Broz 
885bbb16584SMilan Broz 			d[i1] += d[i2] ^ d[i3];
886bbb16584SMilan Broz 			i1++; i2++; i3++;
887bbb16584SMilan Broz 
888bbb16584SMilan Broz 			if (i3 >= n)
889bbb16584SMilan Broz 				i3 -= n;
890bbb16584SMilan Broz 
891bbb16584SMilan Broz 			d[i1] += d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
892bbb16584SMilan Broz 			i1++; i2++; i3++;
893bbb16584SMilan Broz 		}
894bbb16584SMilan Broz 	}
895bbb16584SMilan Broz }
896bbb16584SMilan Broz 
897bbb16584SMilan Broz static void diffuser_b_encrypt(u32 *d, size_t n)
898bbb16584SMilan Broz {
899bbb16584SMilan Broz 	int i, i1, i2, i3;
900bbb16584SMilan Broz 
901bbb16584SMilan Broz 	for (i = 0; i < 3; i++) {
902bbb16584SMilan Broz 		i1 = n - 1;
903bbb16584SMilan Broz 		i2 = 2 - 1;
904bbb16584SMilan Broz 		i3 = 5 - 1;
905bbb16584SMilan Broz 
906bbb16584SMilan Broz 		while (i1 > 0) {
907bbb16584SMilan Broz 			d[i1] -= d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
908bbb16584SMilan Broz 			i1--; i2--; i3--;
909bbb16584SMilan Broz 
910bbb16584SMilan Broz 			if (i3 < 0)
911bbb16584SMilan Broz 				i3 += n;
912bbb16584SMilan Broz 
913bbb16584SMilan Broz 			d[i1] -= d[i2] ^ d[i3];
914bbb16584SMilan Broz 			i1--; i2--; i3--;
915bbb16584SMilan Broz 
916bbb16584SMilan Broz 			if (i2 < 0)
917bbb16584SMilan Broz 				i2 += n;
918bbb16584SMilan Broz 
919bbb16584SMilan Broz 			d[i1] -= d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
920bbb16584SMilan Broz 			i1--; i2--; i3--;
921bbb16584SMilan Broz 
922bbb16584SMilan Broz 			d[i1] -= d[i2] ^ d[i3];
923bbb16584SMilan Broz 			i1--; i2--; i3--;
924bbb16584SMilan Broz 		}
925bbb16584SMilan Broz 	}
926bbb16584SMilan Broz }
927bbb16584SMilan Broz 
928bbb16584SMilan Broz static int crypt_iv_elephant(struct crypt_config *cc, struct dm_crypt_request *dmreq)
929bbb16584SMilan Broz {
930bbb16584SMilan Broz 	struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
931bbb16584SMilan Broz 	u8 *es, *ks, *data, *data2, *data_offset;
932bbb16584SMilan Broz 	struct skcipher_request *req;
933bbb16584SMilan Broz 	struct scatterlist *sg, *sg2, src, dst;
934bbb16584SMilan Broz 	struct crypto_wait wait;
935bbb16584SMilan Broz 	int i, r;
936bbb16584SMilan Broz 
937bbb16584SMilan Broz 	req = skcipher_request_alloc(elephant->tfm, GFP_NOIO);
938bbb16584SMilan Broz 	es = kzalloc(16, GFP_NOIO); /* Key for AES */
939bbb16584SMilan Broz 	ks = kzalloc(32, GFP_NOIO); /* Elephant sector key */
940bbb16584SMilan Broz 
941bbb16584SMilan Broz 	if (!req || !es || !ks) {
942bbb16584SMilan Broz 		r = -ENOMEM;
943bbb16584SMilan Broz 		goto out;
944bbb16584SMilan Broz 	}
945bbb16584SMilan Broz 
946bbb16584SMilan Broz 	*(__le64 *)es = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
947bbb16584SMilan Broz 
948bbb16584SMilan Broz 	/* E(Ks, e(s)) */
949bbb16584SMilan Broz 	sg_init_one(&src, es, 16);
950bbb16584SMilan Broz 	sg_init_one(&dst, ks, 16);
951bbb16584SMilan Broz 	skcipher_request_set_crypt(req, &src, &dst, 16, NULL);
952bbb16584SMilan Broz 	skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
953bbb16584SMilan Broz 	r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
954bbb16584SMilan Broz 	if (r)
955bbb16584SMilan Broz 		goto out;
956bbb16584SMilan Broz 
957bbb16584SMilan Broz 	/* E(Ks, e'(s)) */
958bbb16584SMilan Broz 	es[15] = 0x80;
959bbb16584SMilan Broz 	sg_init_one(&dst, &ks[16], 16);
960bbb16584SMilan Broz 	r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
961bbb16584SMilan Broz 	if (r)
962bbb16584SMilan Broz 		goto out;
963bbb16584SMilan Broz 
964bbb16584SMilan Broz 	sg = crypt_get_sg_data(cc, dmreq->sg_out);
965bbb16584SMilan Broz 	data = kmap_atomic(sg_page(sg));
966bbb16584SMilan Broz 	data_offset = data + sg->offset;
967bbb16584SMilan Broz 
968bbb16584SMilan Broz 	/* Cannot modify original bio, copy to sg_out and apply Elephant to it */
969bbb16584SMilan Broz 	if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
970bbb16584SMilan Broz 		sg2 = crypt_get_sg_data(cc, dmreq->sg_in);
971bbb16584SMilan Broz 		data2 = kmap_atomic(sg_page(sg2));
972bbb16584SMilan Broz 		memcpy(data_offset, data2 + sg2->offset, cc->sector_size);
973bbb16584SMilan Broz 		kunmap_atomic(data2);
974bbb16584SMilan Broz 	}
975bbb16584SMilan Broz 
976bbb16584SMilan Broz 	if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
977bbb16584SMilan Broz 		diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
978bbb16584SMilan Broz 		diffuser_b_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
979bbb16584SMilan Broz 		diffuser_a_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
980bbb16584SMilan Broz 		diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
981bbb16584SMilan Broz 	}
982bbb16584SMilan Broz 
983bbb16584SMilan Broz 	for (i = 0; i < (cc->sector_size / 32); i++)
984bbb16584SMilan Broz 		crypto_xor(data_offset + i * 32, ks, 32);
985bbb16584SMilan Broz 
986bbb16584SMilan Broz 	if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
987bbb16584SMilan Broz 		diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
988bbb16584SMilan Broz 		diffuser_a_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
989bbb16584SMilan Broz 		diffuser_b_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
990bbb16584SMilan Broz 		diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
991bbb16584SMilan Broz 	}
992bbb16584SMilan Broz 
993bbb16584SMilan Broz 	kunmap_atomic(data);
994bbb16584SMilan Broz out:
995bbb16584SMilan Broz 	kzfree(ks);
996bbb16584SMilan Broz 	kzfree(es);
997bbb16584SMilan Broz 	skcipher_request_free(req);
998bbb16584SMilan Broz 	return r;
999bbb16584SMilan Broz }
1000bbb16584SMilan Broz 
1001bbb16584SMilan Broz static int crypt_iv_elephant_gen(struct crypt_config *cc, u8 *iv,
1002bbb16584SMilan Broz 			    struct dm_crypt_request *dmreq)
1003bbb16584SMilan Broz {
1004bbb16584SMilan Broz 	int r;
1005bbb16584SMilan Broz 
1006bbb16584SMilan Broz 	if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
1007bbb16584SMilan Broz 		r = crypt_iv_elephant(cc, dmreq);
1008bbb16584SMilan Broz 		if (r)
1009bbb16584SMilan Broz 			return r;
1010bbb16584SMilan Broz 	}
1011bbb16584SMilan Broz 
1012bbb16584SMilan Broz 	return crypt_iv_eboiv_gen(cc, iv, dmreq);
1013bbb16584SMilan Broz }
1014bbb16584SMilan Broz 
1015bbb16584SMilan Broz static int crypt_iv_elephant_post(struct crypt_config *cc, u8 *iv,
1016bbb16584SMilan Broz 				  struct dm_crypt_request *dmreq)
1017bbb16584SMilan Broz {
1018bbb16584SMilan Broz 	if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
1019bbb16584SMilan Broz 		return crypt_iv_elephant(cc, dmreq);
1020bbb16584SMilan Broz 
1021bbb16584SMilan Broz 	return 0;
1022bbb16584SMilan Broz }
1023bbb16584SMilan Broz 
1024bbb16584SMilan Broz static int crypt_iv_elephant_init(struct crypt_config *cc)
1025bbb16584SMilan Broz {
1026bbb16584SMilan Broz 	struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1027bbb16584SMilan Broz 	int key_offset = cc->key_size - cc->key_extra_size;
1028bbb16584SMilan Broz 
1029bbb16584SMilan Broz 	return crypto_skcipher_setkey(elephant->tfm, &cc->key[key_offset], cc->key_extra_size);
1030bbb16584SMilan Broz }
1031bbb16584SMilan Broz 
1032bbb16584SMilan Broz static int crypt_iv_elephant_wipe(struct crypt_config *cc)
1033bbb16584SMilan Broz {
1034bbb16584SMilan Broz 	struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1035bbb16584SMilan Broz 	u8 key[ELEPHANT_MAX_KEY_SIZE];
1036bbb16584SMilan Broz 
1037bbb16584SMilan Broz 	memset(key, 0, cc->key_extra_size);
1038bbb16584SMilan Broz 	return crypto_skcipher_setkey(elephant->tfm, key, cc->key_extra_size);
1039bbb16584SMilan Broz }
1040bbb16584SMilan Broz 
10411b1b58f5SJulia Lawall static const struct crypt_iv_operations crypt_iv_plain_ops = {
10421da177e4SLinus Torvalds 	.generator = crypt_iv_plain_gen
10431da177e4SLinus Torvalds };
10441da177e4SLinus Torvalds 
10451b1b58f5SJulia Lawall static const struct crypt_iv_operations crypt_iv_plain64_ops = {
104661afef61SMilan Broz 	.generator = crypt_iv_plain64_gen
104761afef61SMilan Broz };
104861afef61SMilan Broz 
10497e3fd855SMilan Broz static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
10507e3fd855SMilan Broz 	.generator = crypt_iv_plain64be_gen
10517e3fd855SMilan Broz };
10527e3fd855SMilan Broz 
10531b1b58f5SJulia Lawall static const struct crypt_iv_operations crypt_iv_essiv_ops = {
10541da177e4SLinus Torvalds 	.generator = crypt_iv_essiv_gen
10551da177e4SLinus Torvalds };
10561da177e4SLinus Torvalds 
10571b1b58f5SJulia Lawall static const struct crypt_iv_operations crypt_iv_benbi_ops = {
105848527fa7SRik Snel 	.ctr	   = crypt_iv_benbi_ctr,
105948527fa7SRik Snel 	.dtr	   = crypt_iv_benbi_dtr,
106048527fa7SRik Snel 	.generator = crypt_iv_benbi_gen
106148527fa7SRik Snel };
10621da177e4SLinus Torvalds 
10631b1b58f5SJulia Lawall static const struct crypt_iv_operations crypt_iv_null_ops = {
106446b47730SLudwig Nussel 	.generator = crypt_iv_null_gen
106546b47730SLudwig Nussel };
106646b47730SLudwig Nussel 
10671b1b58f5SJulia Lawall static const struct crypt_iv_operations crypt_iv_lmk_ops = {
106834745785SMilan Broz 	.ctr	   = crypt_iv_lmk_ctr,
106934745785SMilan Broz 	.dtr	   = crypt_iv_lmk_dtr,
107034745785SMilan Broz 	.init	   = crypt_iv_lmk_init,
107134745785SMilan Broz 	.wipe	   = crypt_iv_lmk_wipe,
107234745785SMilan Broz 	.generator = crypt_iv_lmk_gen,
107334745785SMilan Broz 	.post	   = crypt_iv_lmk_post
107434745785SMilan Broz };
107534745785SMilan Broz 
10761b1b58f5SJulia Lawall static const struct crypt_iv_operations crypt_iv_tcw_ops = {
1077ed04d981SMilan Broz 	.ctr	   = crypt_iv_tcw_ctr,
1078ed04d981SMilan Broz 	.dtr	   = crypt_iv_tcw_dtr,
1079ed04d981SMilan Broz 	.init	   = crypt_iv_tcw_init,
1080ed04d981SMilan Broz 	.wipe	   = crypt_iv_tcw_wipe,
1081ed04d981SMilan Broz 	.generator = crypt_iv_tcw_gen,
1082ed04d981SMilan Broz 	.post	   = crypt_iv_tcw_post
1083ed04d981SMilan Broz };
1084ed04d981SMilan Broz 
1085ef43aa38SMilan Broz static struct crypt_iv_operations crypt_iv_random_ops = {
1086ef43aa38SMilan Broz 	.generator = crypt_iv_random_gen
1087ef43aa38SMilan Broz };
1088ef43aa38SMilan Broz 
1089b9411d73SMilan Broz static struct crypt_iv_operations crypt_iv_eboiv_ops = {
1090b9411d73SMilan Broz 	.ctr	   = crypt_iv_eboiv_ctr,
1091b9411d73SMilan Broz 	.generator = crypt_iv_eboiv_gen
1092b9411d73SMilan Broz };
1093b9411d73SMilan Broz 
1094bbb16584SMilan Broz static struct crypt_iv_operations crypt_iv_elephant_ops = {
1095bbb16584SMilan Broz 	.ctr	   = crypt_iv_elephant_ctr,
1096bbb16584SMilan Broz 	.dtr	   = crypt_iv_elephant_dtr,
1097bbb16584SMilan Broz 	.init	   = crypt_iv_elephant_init,
1098bbb16584SMilan Broz 	.wipe	   = crypt_iv_elephant_wipe,
1099bbb16584SMilan Broz 	.generator = crypt_iv_elephant_gen,
1100bbb16584SMilan Broz 	.post	   = crypt_iv_elephant_post
1101bbb16584SMilan Broz };
1102bbb16584SMilan Broz 
1103ef43aa38SMilan Broz /*
1104ef43aa38SMilan Broz  * Integrity extensions
1105ef43aa38SMilan Broz  */
1106ef43aa38SMilan Broz static bool crypt_integrity_aead(struct crypt_config *cc)
1107ef43aa38SMilan Broz {
1108ef43aa38SMilan Broz 	return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
1109ef43aa38SMilan Broz }
1110ef43aa38SMilan Broz 
1111ef43aa38SMilan Broz static bool crypt_integrity_hmac(struct crypt_config *cc)
1112ef43aa38SMilan Broz {
111333d2f09fSMilan Broz 	return crypt_integrity_aead(cc) && cc->key_mac_size;
1114ef43aa38SMilan Broz }
1115ef43aa38SMilan Broz 
1116ef43aa38SMilan Broz /* Get sg containing data */
1117ef43aa38SMilan Broz static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
1118ef43aa38SMilan Broz 					     struct scatterlist *sg)
1119ef43aa38SMilan Broz {
112033d2f09fSMilan Broz 	if (unlikely(crypt_integrity_aead(cc)))
1121ef43aa38SMilan Broz 		return &sg[2];
1122ef43aa38SMilan Broz 
1123ef43aa38SMilan Broz 	return sg;
1124ef43aa38SMilan Broz }
1125ef43aa38SMilan Broz 
1126ef43aa38SMilan Broz static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
1127ef43aa38SMilan Broz {
1128ef43aa38SMilan Broz 	struct bio_integrity_payload *bip;
1129ef43aa38SMilan Broz 	unsigned int tag_len;
1130ef43aa38SMilan Broz 	int ret;
1131ef43aa38SMilan Broz 
1132ef43aa38SMilan Broz 	if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
1133ef43aa38SMilan Broz 		return 0;
1134ef43aa38SMilan Broz 
1135ef43aa38SMilan Broz 	bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
1136ef43aa38SMilan Broz 	if (IS_ERR(bip))
1137ef43aa38SMilan Broz 		return PTR_ERR(bip);
1138ef43aa38SMilan Broz 
1139ff0c129dSMikulas Patocka 	tag_len = io->cc->on_disk_tag_size * (bio_sectors(bio) >> io->cc->sector_shift);
1140ef43aa38SMilan Broz 
1141ef43aa38SMilan Broz 	bip->bip_iter.bi_size = tag_len;
1142ef43aa38SMilan Broz 	bip->bip_iter.bi_sector = io->cc->start + io->sector;
1143ef43aa38SMilan Broz 
1144ef43aa38SMilan Broz 	ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
1145ef43aa38SMilan Broz 				     tag_len, offset_in_page(io->integrity_metadata));
1146ef43aa38SMilan Broz 	if (unlikely(ret != tag_len))
1147ef43aa38SMilan Broz 		return -ENOMEM;
1148ef43aa38SMilan Broz 
1149ef43aa38SMilan Broz 	return 0;
1150ef43aa38SMilan Broz }
1151ef43aa38SMilan Broz 
1152ef43aa38SMilan Broz static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
1153ef43aa38SMilan Broz {
1154ef43aa38SMilan Broz #ifdef CONFIG_BLK_DEV_INTEGRITY
1155ef43aa38SMilan Broz 	struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
11567a1cd723SMilan Broz 	struct mapped_device *md = dm_table_get_md(ti->table);
1157ef43aa38SMilan Broz 
1158ef43aa38SMilan Broz 	/* From now we require underlying device with our integrity profile */
1159ef43aa38SMilan Broz 	if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
1160ef43aa38SMilan Broz 		ti->error = "Integrity profile not supported.";
1161ef43aa38SMilan Broz 		return -EINVAL;
1162ef43aa38SMilan Broz 	}
1163ef43aa38SMilan Broz 
1164583fe747SMikulas Patocka 	if (bi->tag_size != cc->on_disk_tag_size ||
1165583fe747SMikulas Patocka 	    bi->tuple_size != cc->on_disk_tag_size) {
1166ef43aa38SMilan Broz 		ti->error = "Integrity profile tag size mismatch.";
1167ef43aa38SMilan Broz 		return -EINVAL;
1168ef43aa38SMilan Broz 	}
1169583fe747SMikulas Patocka 	if (1 << bi->interval_exp != cc->sector_size) {
1170583fe747SMikulas Patocka 		ti->error = "Integrity profile sector size mismatch.";
1171583fe747SMikulas Patocka 		return -EINVAL;
1172583fe747SMikulas Patocka 	}
1173ef43aa38SMilan Broz 
117433d2f09fSMilan Broz 	if (crypt_integrity_aead(cc)) {
1175ef43aa38SMilan Broz 		cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
11767a1cd723SMilan Broz 		DMDEBUG("%s: Integrity AEAD, tag size %u, IV size %u.", dm_device_name(md),
1177ef43aa38SMilan Broz 		       cc->integrity_tag_size, cc->integrity_iv_size);
1178ef43aa38SMilan Broz 
1179ef43aa38SMilan Broz 		if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
1180ef43aa38SMilan Broz 			ti->error = "Integrity AEAD auth tag size is not supported.";
1181ef43aa38SMilan Broz 			return -EINVAL;
1182ef43aa38SMilan Broz 		}
1183ef43aa38SMilan Broz 	} else if (cc->integrity_iv_size)
11847a1cd723SMilan Broz 		DMDEBUG("%s: Additional per-sector space %u bytes for IV.", dm_device_name(md),
1185ef43aa38SMilan Broz 		       cc->integrity_iv_size);
1186ef43aa38SMilan Broz 
1187ef43aa38SMilan Broz 	if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
1188ef43aa38SMilan Broz 		ti->error = "Not enough space for integrity tag in the profile.";
1189ef43aa38SMilan Broz 		return -EINVAL;
1190ef43aa38SMilan Broz 	}
1191ef43aa38SMilan Broz 
1192ef43aa38SMilan Broz 	return 0;
1193ef43aa38SMilan Broz #else
1194ef43aa38SMilan Broz 	ti->error = "Integrity profile not supported.";
1195ef43aa38SMilan Broz 	return -EINVAL;
1196ef43aa38SMilan Broz #endif
1197ef43aa38SMilan Broz }
1198ef43aa38SMilan Broz 
1199d469f841SMilan Broz static void crypt_convert_init(struct crypt_config *cc,
1200d469f841SMilan Broz 			       struct convert_context *ctx,
12011da177e4SLinus Torvalds 			       struct bio *bio_out, struct bio *bio_in,
1202fcd369daSMilan Broz 			       sector_t sector)
12031da177e4SLinus Torvalds {
12041da177e4SLinus Torvalds 	ctx->bio_in = bio_in;
12051da177e4SLinus Torvalds 	ctx->bio_out = bio_out;
1206003b5c57SKent Overstreet 	if (bio_in)
1207003b5c57SKent Overstreet 		ctx->iter_in = bio_in->bi_iter;
1208003b5c57SKent Overstreet 	if (bio_out)
1209003b5c57SKent Overstreet 		ctx->iter_out = bio_out->bi_iter;
1210c66029f4SMikulas Patocka 	ctx->cc_sector = sector + cc->iv_offset;
121143d69034SMilan Broz 	init_completion(&ctx->restart);
12121da177e4SLinus Torvalds }
12131da177e4SLinus Torvalds 
1214b2174eebSHuang Ying static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
1215ef43aa38SMilan Broz 					     void *req)
1216b2174eebSHuang Ying {
1217b2174eebSHuang Ying 	return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
1218b2174eebSHuang Ying }
1219b2174eebSHuang Ying 
1220ef43aa38SMilan Broz static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
1221b2174eebSHuang Ying {
1222ef43aa38SMilan Broz 	return (void *)((char *)dmreq - cc->dmreq_start);
1223b2174eebSHuang Ying }
1224b2174eebSHuang Ying 
12252dc5327dSMilan Broz static u8 *iv_of_dmreq(struct crypt_config *cc,
12262dc5327dSMilan Broz 		       struct dm_crypt_request *dmreq)
12272dc5327dSMilan Broz {
122833d2f09fSMilan Broz 	if (crypt_integrity_aead(cc))
1229ef43aa38SMilan Broz 		return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1230ef43aa38SMilan Broz 			crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
1231ef43aa38SMilan Broz 	else
12322dc5327dSMilan Broz 		return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1233bbdb23b5SHerbert Xu 			crypto_skcipher_alignmask(any_tfm(cc)) + 1);
12342dc5327dSMilan Broz }
12352dc5327dSMilan Broz 
1236ef43aa38SMilan Broz static u8 *org_iv_of_dmreq(struct crypt_config *cc,
1237ef43aa38SMilan Broz 		       struct dm_crypt_request *dmreq)
1238ef43aa38SMilan Broz {
1239ef43aa38SMilan Broz 	return iv_of_dmreq(cc, dmreq) + cc->iv_size;
1240ef43aa38SMilan Broz }
1241ef43aa38SMilan Broz 
1242c13b5487SChristoph Hellwig static __le64 *org_sector_of_dmreq(struct crypt_config *cc,
1243ef43aa38SMilan Broz 		       struct dm_crypt_request *dmreq)
1244ef43aa38SMilan Broz {
1245ef43aa38SMilan Broz 	u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
1246c13b5487SChristoph Hellwig 	return (__le64 *) ptr;
1247ef43aa38SMilan Broz }
1248ef43aa38SMilan Broz 
1249ef43aa38SMilan Broz static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
1250ef43aa38SMilan Broz 		       struct dm_crypt_request *dmreq)
1251ef43aa38SMilan Broz {
1252ef43aa38SMilan Broz 	u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
1253ef43aa38SMilan Broz 		  cc->iv_size + sizeof(uint64_t);
1254ef43aa38SMilan Broz 	return (unsigned int*)ptr;
1255ef43aa38SMilan Broz }
1256ef43aa38SMilan Broz 
1257ef43aa38SMilan Broz static void *tag_from_dmreq(struct crypt_config *cc,
1258ef43aa38SMilan Broz 				struct dm_crypt_request *dmreq)
1259ef43aa38SMilan Broz {
1260ef43aa38SMilan Broz 	struct convert_context *ctx = dmreq->ctx;
1261ef43aa38SMilan Broz 	struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1262ef43aa38SMilan Broz 
1263ef43aa38SMilan Broz 	return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
1264ef43aa38SMilan Broz 		cc->on_disk_tag_size];
1265ef43aa38SMilan Broz }
1266ef43aa38SMilan Broz 
1267ef43aa38SMilan Broz static void *iv_tag_from_dmreq(struct crypt_config *cc,
1268ef43aa38SMilan Broz 			       struct dm_crypt_request *dmreq)
1269ef43aa38SMilan Broz {
1270ef43aa38SMilan Broz 	return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
1271ef43aa38SMilan Broz }
1272ef43aa38SMilan Broz 
1273ef43aa38SMilan Broz static int crypt_convert_block_aead(struct crypt_config *cc,
12743a7f6c99SMilan Broz 				     struct convert_context *ctx,
1275ef43aa38SMilan Broz 				     struct aead_request *req,
1276ef43aa38SMilan Broz 				     unsigned int tag_offset)
127701482b76SMilan Broz {
1278003b5c57SKent Overstreet 	struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1279003b5c57SKent Overstreet 	struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
12803a7f6c99SMilan Broz 	struct dm_crypt_request *dmreq;
1281ef43aa38SMilan Broz 	u8 *iv, *org_iv, *tag_iv, *tag;
1282c13b5487SChristoph Hellwig 	__le64 *sector;
1283ef43aa38SMilan Broz 	int r = 0;
1284ef43aa38SMilan Broz 
1285ef43aa38SMilan Broz 	BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
128601482b76SMilan Broz 
12878f0009a2SMilan Broz 	/* Reject unexpected unaligned bio. */
12880440d5c0SMikulas Patocka 	if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
12898f0009a2SMilan Broz 		return -EIO;
129001482b76SMilan Broz 
1291b2174eebSHuang Ying 	dmreq = dmreq_of_req(cc, req);
1292c66029f4SMikulas Patocka 	dmreq->iv_sector = ctx->cc_sector;
12938f0009a2SMilan Broz 	if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1294ff3af92bSMikulas Patocka 		dmreq->iv_sector >>= cc->sector_shift;
1295b2174eebSHuang Ying 	dmreq->ctx = ctx;
129601482b76SMilan Broz 
1297ef43aa38SMilan Broz 	*org_tag_of_dmreq(cc, dmreq) = tag_offset;
129801482b76SMilan Broz 
1299ef43aa38SMilan Broz 	sector = org_sector_of_dmreq(cc, dmreq);
1300ef43aa38SMilan Broz 	*sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1301ef43aa38SMilan Broz 
1302ef43aa38SMilan Broz 	iv = iv_of_dmreq(cc, dmreq);
1303ef43aa38SMilan Broz 	org_iv = org_iv_of_dmreq(cc, dmreq);
1304ef43aa38SMilan Broz 	tag = tag_from_dmreq(cc, dmreq);
1305ef43aa38SMilan Broz 	tag_iv = iv_tag_from_dmreq(cc, dmreq);
1306ef43aa38SMilan Broz 
1307ef43aa38SMilan Broz 	/* AEAD request:
1308ef43aa38SMilan Broz 	 *  |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1309ef43aa38SMilan Broz 	 *  | (authenticated) | (auth+encryption) |              |
1310ef43aa38SMilan Broz 	 *  | sector_LE |  IV |  sector in/out    |  tag in/out  |
1311ef43aa38SMilan Broz 	 */
1312ef43aa38SMilan Broz 	sg_init_table(dmreq->sg_in, 4);
1313ef43aa38SMilan Broz 	sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
1314ef43aa38SMilan Broz 	sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
13158f0009a2SMilan Broz 	sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1316ef43aa38SMilan Broz 	sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
1317ef43aa38SMilan Broz 
1318ef43aa38SMilan Broz 	sg_init_table(dmreq->sg_out, 4);
1319ef43aa38SMilan Broz 	sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
1320ef43aa38SMilan Broz 	sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
13218f0009a2SMilan Broz 	sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1322ef43aa38SMilan Broz 	sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
132301482b76SMilan Broz 
13243a7f6c99SMilan Broz 	if (cc->iv_gen_ops) {
1325ef43aa38SMilan Broz 		/* For READs use IV stored in integrity metadata */
1326ef43aa38SMilan Broz 		if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1327ef43aa38SMilan Broz 			memcpy(org_iv, tag_iv, cc->iv_size);
1328ef43aa38SMilan Broz 		} else {
1329ef43aa38SMilan Broz 			r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
13303a7f6c99SMilan Broz 			if (r < 0)
13313a7f6c99SMilan Broz 				return r;
1332ef43aa38SMilan Broz 			/* Store generated IV in integrity metadata */
1333ef43aa38SMilan Broz 			if (cc->integrity_iv_size)
1334ef43aa38SMilan Broz 				memcpy(tag_iv, org_iv, cc->iv_size);
1335ef43aa38SMilan Broz 		}
1336ef43aa38SMilan Broz 		/* Working copy of IV, to be modified in crypto API */
1337ef43aa38SMilan Broz 		memcpy(iv, org_iv, cc->iv_size);
1338ef43aa38SMilan Broz 	}
1339ef43aa38SMilan Broz 
1340ef43aa38SMilan Broz 	aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
1341ef43aa38SMilan Broz 	if (bio_data_dir(ctx->bio_in) == WRITE) {
1342ef43aa38SMilan Broz 		aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
13438f0009a2SMilan Broz 				       cc->sector_size, iv);
1344ef43aa38SMilan Broz 		r = crypto_aead_encrypt(req);
1345ef43aa38SMilan Broz 		if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
1346ef43aa38SMilan Broz 			memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
1347ef43aa38SMilan Broz 			       cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
1348ef43aa38SMilan Broz 	} else {
1349ef43aa38SMilan Broz 		aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
13508f0009a2SMilan Broz 				       cc->sector_size + cc->integrity_tag_size, iv);
1351ef43aa38SMilan Broz 		r = crypto_aead_decrypt(req);
1352ef43aa38SMilan Broz 	}
1353ef43aa38SMilan Broz 
1354f710126cSMilan Broz 	if (r == -EBADMSG) {
1355f710126cSMilan Broz 		char b[BDEVNAME_SIZE];
1356f710126cSMilan Broz 		DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx->bio_in, b),
1357ef43aa38SMilan Broz 			    (unsigned long long)le64_to_cpu(*sector));
1358f710126cSMilan Broz 	}
1359ef43aa38SMilan Broz 
1360ef43aa38SMilan Broz 	if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1361ef43aa38SMilan Broz 		r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1362ef43aa38SMilan Broz 
13638f0009a2SMilan Broz 	bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
13648f0009a2SMilan Broz 	bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1365ef43aa38SMilan Broz 
1366ef43aa38SMilan Broz 	return r;
13673a7f6c99SMilan Broz }
13683a7f6c99SMilan Broz 
1369ef43aa38SMilan Broz static int crypt_convert_block_skcipher(struct crypt_config *cc,
1370ef43aa38SMilan Broz 					struct convert_context *ctx,
1371ef43aa38SMilan Broz 					struct skcipher_request *req,
1372ef43aa38SMilan Broz 					unsigned int tag_offset)
1373ef43aa38SMilan Broz {
1374ef43aa38SMilan Broz 	struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1375ef43aa38SMilan Broz 	struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1376ef43aa38SMilan Broz 	struct scatterlist *sg_in, *sg_out;
1377ef43aa38SMilan Broz 	struct dm_crypt_request *dmreq;
1378ef43aa38SMilan Broz 	u8 *iv, *org_iv, *tag_iv;
1379c13b5487SChristoph Hellwig 	__le64 *sector;
1380ef43aa38SMilan Broz 	int r = 0;
1381ef43aa38SMilan Broz 
13828f0009a2SMilan Broz 	/* Reject unexpected unaligned bio. */
13830440d5c0SMikulas Patocka 	if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
13848f0009a2SMilan Broz 		return -EIO;
13858f0009a2SMilan Broz 
1386ef43aa38SMilan Broz 	dmreq = dmreq_of_req(cc, req);
1387ef43aa38SMilan Broz 	dmreq->iv_sector = ctx->cc_sector;
13888f0009a2SMilan Broz 	if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1389ff3af92bSMikulas Patocka 		dmreq->iv_sector >>= cc->sector_shift;
1390ef43aa38SMilan Broz 	dmreq->ctx = ctx;
1391ef43aa38SMilan Broz 
1392ef43aa38SMilan Broz 	*org_tag_of_dmreq(cc, dmreq) = tag_offset;
1393ef43aa38SMilan Broz 
1394ef43aa38SMilan Broz 	iv = iv_of_dmreq(cc, dmreq);
1395ef43aa38SMilan Broz 	org_iv = org_iv_of_dmreq(cc, dmreq);
1396ef43aa38SMilan Broz 	tag_iv = iv_tag_from_dmreq(cc, dmreq);
1397ef43aa38SMilan Broz 
1398ef43aa38SMilan Broz 	sector = org_sector_of_dmreq(cc, dmreq);
1399ef43aa38SMilan Broz 	*sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1400ef43aa38SMilan Broz 
1401ef43aa38SMilan Broz 	/* For skcipher we use only the first sg item */
1402ef43aa38SMilan Broz 	sg_in  = &dmreq->sg_in[0];
1403ef43aa38SMilan Broz 	sg_out = &dmreq->sg_out[0];
1404ef43aa38SMilan Broz 
1405ef43aa38SMilan Broz 	sg_init_table(sg_in, 1);
14068f0009a2SMilan Broz 	sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1407ef43aa38SMilan Broz 
1408ef43aa38SMilan Broz 	sg_init_table(sg_out, 1);
14098f0009a2SMilan Broz 	sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1410ef43aa38SMilan Broz 
1411ef43aa38SMilan Broz 	if (cc->iv_gen_ops) {
1412ef43aa38SMilan Broz 		/* For READs use IV stored in integrity metadata */
1413ef43aa38SMilan Broz 		if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1414ef43aa38SMilan Broz 			memcpy(org_iv, tag_iv, cc->integrity_iv_size);
1415ef43aa38SMilan Broz 		} else {
1416ef43aa38SMilan Broz 			r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1417ef43aa38SMilan Broz 			if (r < 0)
1418ef43aa38SMilan Broz 				return r;
1419bbb16584SMilan Broz 			/* Data can be already preprocessed in generator */
1420bbb16584SMilan Broz 			if (test_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags))
1421bbb16584SMilan Broz 				sg_in = sg_out;
1422ef43aa38SMilan Broz 			/* Store generated IV in integrity metadata */
1423ef43aa38SMilan Broz 			if (cc->integrity_iv_size)
1424ef43aa38SMilan Broz 				memcpy(tag_iv, org_iv, cc->integrity_iv_size);
1425ef43aa38SMilan Broz 		}
1426ef43aa38SMilan Broz 		/* Working copy of IV, to be modified in crypto API */
1427ef43aa38SMilan Broz 		memcpy(iv, org_iv, cc->iv_size);
1428ef43aa38SMilan Broz 	}
1429ef43aa38SMilan Broz 
14308f0009a2SMilan Broz 	skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
14313a7f6c99SMilan Broz 
14323a7f6c99SMilan Broz 	if (bio_data_dir(ctx->bio_in) == WRITE)
1433bbdb23b5SHerbert Xu 		r = crypto_skcipher_encrypt(req);
14343a7f6c99SMilan Broz 	else
1435bbdb23b5SHerbert Xu 		r = crypto_skcipher_decrypt(req);
14363a7f6c99SMilan Broz 
14372dc5327dSMilan Broz 	if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1438ef43aa38SMilan Broz 		r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1439ef43aa38SMilan Broz 
14408f0009a2SMilan Broz 	bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
14418f0009a2SMilan Broz 	bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
14422dc5327dSMilan Broz 
14433a7f6c99SMilan Broz 	return r;
144401482b76SMilan Broz }
144501482b76SMilan Broz 
144695497a96SMilan Broz static void kcryptd_async_done(struct crypto_async_request *async_req,
144795497a96SMilan Broz 			       int error);
1448c0297721SAndi Kleen 
1449ef43aa38SMilan Broz static void crypt_alloc_req_skcipher(struct crypt_config *cc,
1450ddd42edfSMilan Broz 				     struct convert_context *ctx)
1451ddd42edfSMilan Broz {
1452c66029f4SMikulas Patocka 	unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
1453c0297721SAndi Kleen 
1454ef43aa38SMilan Broz 	if (!ctx->r.req)
14556f1c819cSKent Overstreet 		ctx->r.req = mempool_alloc(&cc->req_pool, GFP_NOIO);
1456c0297721SAndi Kleen 
1457ef43aa38SMilan Broz 	skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
145854cea3f6SMilan Broz 
145954cea3f6SMilan Broz 	/*
146054cea3f6SMilan Broz 	 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
146154cea3f6SMilan Broz 	 * requests if driver request queue is full.
146254cea3f6SMilan Broz 	 */
1463ef43aa38SMilan Broz 	skcipher_request_set_callback(ctx->r.req,
1464432061b3SMikulas Patocka 	    CRYPTO_TFM_REQ_MAY_BACKLOG,
1465ef43aa38SMilan Broz 	    kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
1466ddd42edfSMilan Broz }
1467ddd42edfSMilan Broz 
1468ef43aa38SMilan Broz static void crypt_alloc_req_aead(struct crypt_config *cc,
1469ef43aa38SMilan Broz 				 struct convert_context *ctx)
1470ef43aa38SMilan Broz {
1471ef43aa38SMilan Broz 	if (!ctx->r.req_aead)
14726f1c819cSKent Overstreet 		ctx->r.req_aead = mempool_alloc(&cc->req_pool, GFP_NOIO);
1473ef43aa38SMilan Broz 
1474ef43aa38SMilan Broz 	aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
1475ef43aa38SMilan Broz 
1476ef43aa38SMilan Broz 	/*
1477ef43aa38SMilan Broz 	 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1478ef43aa38SMilan Broz 	 * requests if driver request queue is full.
1479ef43aa38SMilan Broz 	 */
1480ef43aa38SMilan Broz 	aead_request_set_callback(ctx->r.req_aead,
1481432061b3SMikulas Patocka 	    CRYPTO_TFM_REQ_MAY_BACKLOG,
1482ef43aa38SMilan Broz 	    kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
1483ef43aa38SMilan Broz }
1484ef43aa38SMilan Broz 
1485ef43aa38SMilan Broz static void crypt_alloc_req(struct crypt_config *cc,
1486ef43aa38SMilan Broz 			    struct convert_context *ctx)
1487ef43aa38SMilan Broz {
148833d2f09fSMilan Broz 	if (crypt_integrity_aead(cc))
1489ef43aa38SMilan Broz 		crypt_alloc_req_aead(cc, ctx);
1490ef43aa38SMilan Broz 	else
1491ef43aa38SMilan Broz 		crypt_alloc_req_skcipher(cc, ctx);
1492ef43aa38SMilan Broz }
1493ef43aa38SMilan Broz 
1494ef43aa38SMilan Broz static void crypt_free_req_skcipher(struct crypt_config *cc,
1495bbdb23b5SHerbert Xu 				    struct skcipher_request *req, struct bio *base_bio)
1496298a9fa0SMikulas Patocka {
1497298a9fa0SMikulas Patocka 	struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1498298a9fa0SMikulas Patocka 
1499bbdb23b5SHerbert Xu 	if ((struct skcipher_request *)(io + 1) != req)
15006f1c819cSKent Overstreet 		mempool_free(req, &cc->req_pool);
1501298a9fa0SMikulas Patocka }
1502298a9fa0SMikulas Patocka 
1503ef43aa38SMilan Broz static void crypt_free_req_aead(struct crypt_config *cc,
1504ef43aa38SMilan Broz 				struct aead_request *req, struct bio *base_bio)
1505ef43aa38SMilan Broz {
1506ef43aa38SMilan Broz 	struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1507ef43aa38SMilan Broz 
1508ef43aa38SMilan Broz 	if ((struct aead_request *)(io + 1) != req)
15096f1c819cSKent Overstreet 		mempool_free(req, &cc->req_pool);
1510ef43aa38SMilan Broz }
1511ef43aa38SMilan Broz 
1512ef43aa38SMilan Broz static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
1513ef43aa38SMilan Broz {
151433d2f09fSMilan Broz 	if (crypt_integrity_aead(cc))
1515ef43aa38SMilan Broz 		crypt_free_req_aead(cc, req, base_bio);
1516ef43aa38SMilan Broz 	else
1517ef43aa38SMilan Broz 		crypt_free_req_skcipher(cc, req, base_bio);
1518ef43aa38SMilan Broz }
1519ef43aa38SMilan Broz 
15201da177e4SLinus Torvalds /*
15211da177e4SLinus Torvalds  * Encrypt / decrypt data from one bio to another one (can be the same one)
15221da177e4SLinus Torvalds  */
15234e4cbee9SChristoph Hellwig static blk_status_t crypt_convert(struct crypt_config *cc,
15241da177e4SLinus Torvalds 			 struct convert_context *ctx)
15251da177e4SLinus Torvalds {
1526ef43aa38SMilan Broz 	unsigned int tag_offset = 0;
1527ff3af92bSMikulas Patocka 	unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
15283f1e9070SMilan Broz 	int r;
15291da177e4SLinus Torvalds 
153040b6229bSMikulas Patocka 	atomic_set(&ctx->cc_pending, 1);
1531c8081618SMilan Broz 
1532003b5c57SKent Overstreet 	while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
15331da177e4SLinus Torvalds 
15343a7f6c99SMilan Broz 		crypt_alloc_req(cc, ctx);
153540b6229bSMikulas Patocka 		atomic_inc(&ctx->cc_pending);
15363f1e9070SMilan Broz 
153733d2f09fSMilan Broz 		if (crypt_integrity_aead(cc))
1538ef43aa38SMilan Broz 			r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
1539ef43aa38SMilan Broz 		else
1540ef43aa38SMilan Broz 			r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
15413a7f6c99SMilan Broz 
15423a7f6c99SMilan Broz 		switch (r) {
154354cea3f6SMilan Broz 		/*
154454cea3f6SMilan Broz 		 * The request was queued by a crypto driver
154554cea3f6SMilan Broz 		 * but the driver request queue is full, let's wait.
154654cea3f6SMilan Broz 		 */
15473a7f6c99SMilan Broz 		case -EBUSY:
15483a7f6c99SMilan Broz 			wait_for_completion(&ctx->restart);
154916735d02SWolfram Sang 			reinit_completion(&ctx->restart);
1550c0403ec0SRabin Vincent 			/* fall through */
155154cea3f6SMilan Broz 		/*
155254cea3f6SMilan Broz 		 * The request is queued and processed asynchronously,
155354cea3f6SMilan Broz 		 * completion function kcryptd_async_done() will be called.
155454cea3f6SMilan Broz 		 */
1555c0403ec0SRabin Vincent 		case -EINPROGRESS:
1556ef43aa38SMilan Broz 			ctx->r.req = NULL;
15578f0009a2SMilan Broz 			ctx->cc_sector += sector_step;
1558583fe747SMikulas Patocka 			tag_offset++;
15593a7f6c99SMilan Broz 			continue;
156054cea3f6SMilan Broz 		/*
156154cea3f6SMilan Broz 		 * The request was already processed (synchronously).
156254cea3f6SMilan Broz 		 */
15633f1e9070SMilan Broz 		case 0:
156440b6229bSMikulas Patocka 			atomic_dec(&ctx->cc_pending);
15658f0009a2SMilan Broz 			ctx->cc_sector += sector_step;
1566583fe747SMikulas Patocka 			tag_offset++;
1567c7f1b204SMilan Broz 			cond_resched();
15683f1e9070SMilan Broz 			continue;
1569ef43aa38SMilan Broz 		/*
1570ef43aa38SMilan Broz 		 * There was a data integrity error.
1571ef43aa38SMilan Broz 		 */
1572ef43aa38SMilan Broz 		case -EBADMSG:
1573ef43aa38SMilan Broz 			atomic_dec(&ctx->cc_pending);
15744e4cbee9SChristoph Hellwig 			return BLK_STS_PROTECTION;
1575ef43aa38SMilan Broz 		/*
1576ef43aa38SMilan Broz 		 * There was an error while processing the request.
1577ef43aa38SMilan Broz 		 */
15783f1e9070SMilan Broz 		default:
157940b6229bSMikulas Patocka 			atomic_dec(&ctx->cc_pending);
15804e4cbee9SChristoph Hellwig 			return BLK_STS_IOERR;
15811da177e4SLinus Torvalds 		}
15823f1e9070SMilan Broz 	}
15833f1e9070SMilan Broz 
15843f1e9070SMilan Broz 	return 0;
15853f1e9070SMilan Broz }
15861da177e4SLinus Torvalds 
1587cf2f1abfSMikulas Patocka static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
1588cf2f1abfSMikulas Patocka 
15891da177e4SLinus Torvalds /*
15901da177e4SLinus Torvalds  * Generate a new unfragmented bio with the given size
1591586b286bSMike Snitzer  * This should never violate the device limitations (but only because
1592586b286bSMike Snitzer  * max_segment_size is being constrained to PAGE_SIZE).
15937145c241SMikulas Patocka  *
15947145c241SMikulas Patocka  * This function may be called concurrently. If we allocate from the mempool
15957145c241SMikulas Patocka  * concurrently, there is a possibility of deadlock. For example, if we have
15967145c241SMikulas Patocka  * mempool of 256 pages, two processes, each wanting 256, pages allocate from
15977145c241SMikulas Patocka  * the mempool concurrently, it may deadlock in a situation where both processes
15987145c241SMikulas Patocka  * have allocated 128 pages and the mempool is exhausted.
15997145c241SMikulas Patocka  *
16007145c241SMikulas Patocka  * In order to avoid this scenario we allocate the pages under a mutex.
16017145c241SMikulas Patocka  *
16027145c241SMikulas Patocka  * In order to not degrade performance with excessive locking, we try
16037145c241SMikulas Patocka  * non-blocking allocations without a mutex first but on failure we fallback
16047145c241SMikulas Patocka  * to blocking allocations with a mutex.
16051da177e4SLinus Torvalds  */
1606cf2f1abfSMikulas Patocka static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
16071da177e4SLinus Torvalds {
160849a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
16098b004457SMilan Broz 	struct bio *clone;
16101da177e4SLinus Torvalds 	unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
16117145c241SMikulas Patocka 	gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
16127145c241SMikulas Patocka 	unsigned i, len, remaining_size;
161391e10625SMilan Broz 	struct page *page;
16141da177e4SLinus Torvalds 
16157145c241SMikulas Patocka retry:
1616d0164adcSMel Gorman 	if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
16177145c241SMikulas Patocka 		mutex_lock(&cc->bio_alloc_lock);
16187145c241SMikulas Patocka 
16196f1c819cSKent Overstreet 	clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, &cc->bs);
16208b004457SMilan Broz 	if (!clone)
1621ef43aa38SMilan Broz 		goto out;
16221da177e4SLinus Torvalds 
1623027581f3SOlaf Kirch 	clone_init(io, clone);
16246a24c718SMilan Broz 
16257145c241SMikulas Patocka 	remaining_size = size;
16267145c241SMikulas Patocka 
1627f97380bcSOlaf Kirch 	for (i = 0; i < nr_iovecs; i++) {
16286f1c819cSKent Overstreet 		page = mempool_alloc(&cc->page_pool, gfp_mask);
16297145c241SMikulas Patocka 		if (!page) {
16307145c241SMikulas Patocka 			crypt_free_buffer_pages(cc, clone);
16317145c241SMikulas Patocka 			bio_put(clone);
1632d0164adcSMel Gorman 			gfp_mask |= __GFP_DIRECT_RECLAIM;
16337145c241SMikulas Patocka 			goto retry;
16347145c241SMikulas Patocka 		}
16351da177e4SLinus Torvalds 
16367145c241SMikulas Patocka 		len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
16371da177e4SLinus Torvalds 
16380dae7fe5SMing Lei 		bio_add_page(clone, page, len, 0);
163991e10625SMilan Broz 
16407145c241SMikulas Patocka 		remaining_size -= len;
16411da177e4SLinus Torvalds 	}
16421da177e4SLinus Torvalds 
1643ef43aa38SMilan Broz 	/* Allocate space for integrity tags */
1644ef43aa38SMilan Broz 	if (dm_crypt_integrity_io_alloc(io, clone)) {
1645ef43aa38SMilan Broz 		crypt_free_buffer_pages(cc, clone);
1646ef43aa38SMilan Broz 		bio_put(clone);
1647ef43aa38SMilan Broz 		clone = NULL;
1648ef43aa38SMilan Broz 	}
1649ef43aa38SMilan Broz out:
1650d0164adcSMel Gorman 	if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
16517145c241SMikulas Patocka 		mutex_unlock(&cc->bio_alloc_lock);
16527145c241SMikulas Patocka 
16538b004457SMilan Broz 	return clone;
16541da177e4SLinus Torvalds }
16551da177e4SLinus Torvalds 
1656644bd2f0SNeil Brown static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
16571da177e4SLinus Torvalds {
16581da177e4SLinus Torvalds 	struct bio_vec *bv;
16596dc4f100SMing Lei 	struct bvec_iter_all iter_all;
16601da177e4SLinus Torvalds 
16612b070cfeSChristoph Hellwig 	bio_for_each_segment_all(bv, clone, iter_all) {
16621da177e4SLinus Torvalds 		BUG_ON(!bv->bv_page);
16636f1c819cSKent Overstreet 		mempool_free(bv->bv_page, &cc->page_pool);
16641da177e4SLinus Torvalds 	}
16651da177e4SLinus Torvalds }
16661da177e4SLinus Torvalds 
1667298a9fa0SMikulas Patocka static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1668dc440d1eSMilan Broz 			  struct bio *bio, sector_t sector)
1669dc440d1eSMilan Broz {
167049a8a920SAlasdair G Kergon 	io->cc = cc;
1671dc440d1eSMilan Broz 	io->base_bio = bio;
1672dc440d1eSMilan Broz 	io->sector = sector;
1673dc440d1eSMilan Broz 	io->error = 0;
1674ef43aa38SMilan Broz 	io->ctx.r.req = NULL;
1675ef43aa38SMilan Broz 	io->integrity_metadata = NULL;
1676ef43aa38SMilan Broz 	io->integrity_metadata_from_pool = false;
167740b6229bSMikulas Patocka 	atomic_set(&io->io_pending, 0);
1678dc440d1eSMilan Broz }
1679dc440d1eSMilan Broz 
16803e1a8bddSMilan Broz static void crypt_inc_pending(struct dm_crypt_io *io)
16813e1a8bddSMilan Broz {
168240b6229bSMikulas Patocka 	atomic_inc(&io->io_pending);
16833e1a8bddSMilan Broz }
16843e1a8bddSMilan Broz 
16851da177e4SLinus Torvalds /*
16861da177e4SLinus Torvalds  * One of the bios was finished. Check for completion of
16871da177e4SLinus Torvalds  * the whole request and correctly clean up the buffer.
16881da177e4SLinus Torvalds  */
16895742fd77SMilan Broz static void crypt_dec_pending(struct dm_crypt_io *io)
16901da177e4SLinus Torvalds {
169149a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
1692b35f8caaSMilan Broz 	struct bio *base_bio = io->base_bio;
16934e4cbee9SChristoph Hellwig 	blk_status_t error = io->error;
16941da177e4SLinus Torvalds 
169540b6229bSMikulas Patocka 	if (!atomic_dec_and_test(&io->io_pending))
16961da177e4SLinus Torvalds 		return;
16971da177e4SLinus Torvalds 
1698ef43aa38SMilan Broz 	if (io->ctx.r.req)
1699ef43aa38SMilan Broz 		crypt_free_req(cc, io->ctx.r.req, base_bio);
1700ef43aa38SMilan Broz 
1701ef43aa38SMilan Broz 	if (unlikely(io->integrity_metadata_from_pool))
17026f1c819cSKent Overstreet 		mempool_free(io->integrity_metadata, &io->cc->tag_pool);
1703ef43aa38SMilan Broz 	else
1704ef43aa38SMilan Broz 		kfree(io->integrity_metadata);
1705b35f8caaSMilan Broz 
17064e4cbee9SChristoph Hellwig 	base_bio->bi_status = error;
17074246a0b6SChristoph Hellwig 	bio_endio(base_bio);
17081da177e4SLinus Torvalds }
17091da177e4SLinus Torvalds 
17101da177e4SLinus Torvalds /*
1711cabf08e4SMilan Broz  * kcryptd/kcryptd_io:
17121da177e4SLinus Torvalds  *
17131da177e4SLinus Torvalds  * Needed because it would be very unwise to do decryption in an
171423541d2dSMilan Broz  * interrupt context.
1715cabf08e4SMilan Broz  *
1716cabf08e4SMilan Broz  * kcryptd performs the actual encryption or decryption.
1717cabf08e4SMilan Broz  *
1718cabf08e4SMilan Broz  * kcryptd_io performs the IO submission.
1719cabf08e4SMilan Broz  *
1720cabf08e4SMilan Broz  * They must be separated as otherwise the final stages could be
1721cabf08e4SMilan Broz  * starved by new requests which can block in the first stages due
1722cabf08e4SMilan Broz  * to memory allocation.
1723c0297721SAndi Kleen  *
1724c0297721SAndi Kleen  * The work is done per CPU global for all dm-crypt instances.
1725c0297721SAndi Kleen  * They should not depend on each other and do not block.
17261da177e4SLinus Torvalds  */
17274246a0b6SChristoph Hellwig static void crypt_endio(struct bio *clone)
17288b004457SMilan Broz {
1729028867acSAlasdair G Kergon 	struct dm_crypt_io *io = clone->bi_private;
173049a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
1731ee7a491eSMilan Broz 	unsigned rw = bio_data_dir(clone);
17324e4cbee9SChristoph Hellwig 	blk_status_t error;
17338b004457SMilan Broz 
17348b004457SMilan Broz 	/*
17356712ecf8SNeilBrown 	 * free the processed pages
17368b004457SMilan Broz 	 */
1737ee7a491eSMilan Broz 	if (rw == WRITE)
1738644bd2f0SNeil Brown 		crypt_free_buffer_pages(cc, clone);
17398b004457SMilan Broz 
17404e4cbee9SChristoph Hellwig 	error = clone->bi_status;
17418b004457SMilan Broz 	bio_put(clone);
1742ee7a491eSMilan Broz 
17439b81c842SSasha Levin 	if (rw == READ && !error) {
1744cabf08e4SMilan Broz 		kcryptd_queue_crypt(io);
17456712ecf8SNeilBrown 		return;
1746ee7a491eSMilan Broz 	}
17475742fd77SMilan Broz 
17489b81c842SSasha Levin 	if (unlikely(error))
17499b81c842SSasha Levin 		io->error = error;
17505742fd77SMilan Broz 
17515742fd77SMilan Broz 	crypt_dec_pending(io);
17528b004457SMilan Broz }
17538b004457SMilan Broz 
1754028867acSAlasdair G Kergon static void clone_init(struct dm_crypt_io *io, struct bio *clone)
17558b004457SMilan Broz {
175649a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
17578b004457SMilan Broz 
17588b004457SMilan Broz 	clone->bi_private = io;
17598b004457SMilan Broz 	clone->bi_end_io  = crypt_endio;
176074d46992SChristoph Hellwig 	bio_set_dev(clone, cc->dev->bdev);
1761ef295ecfSChristoph Hellwig 	clone->bi_opf	  = io->base_bio->bi_opf;
17628b004457SMilan Broz }
17638b004457SMilan Broz 
176420c82538SMilan Broz static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
17658b004457SMilan Broz {
176649a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
17678b004457SMilan Broz 	struct bio *clone;
176893e605c2SMilan Broz 
17698b004457SMilan Broz 	/*
177059779079SMike Snitzer 	 * We need the original biovec array in order to decrypt
177159779079SMike Snitzer 	 * the whole bio data *afterwards* -- thanks to immutable
177259779079SMike Snitzer 	 * biovecs we don't need to worry about the block layer
177359779079SMike Snitzer 	 * modifying the biovec array; so leverage bio_clone_fast().
17748b004457SMilan Broz 	 */
17756f1c819cSKent Overstreet 	clone = bio_clone_fast(io->base_bio, gfp, &cc->bs);
17767eaceaccSJens Axboe 	if (!clone)
177720c82538SMilan Broz 		return 1;
17788b004457SMilan Broz 
177920c82538SMilan Broz 	crypt_inc_pending(io);
178020c82538SMilan Broz 
17818b004457SMilan Broz 	clone_init(io, clone);
17824f024f37SKent Overstreet 	clone->bi_iter.bi_sector = cc->start + io->sector;
17838b004457SMilan Broz 
1784ef43aa38SMilan Broz 	if (dm_crypt_integrity_io_alloc(io, clone)) {
1785ef43aa38SMilan Broz 		crypt_dec_pending(io);
1786ef43aa38SMilan Broz 		bio_put(clone);
1787ef43aa38SMilan Broz 		return 1;
1788ef43aa38SMilan Broz 	}
1789ef43aa38SMilan Broz 
179093e605c2SMilan Broz 	generic_make_request(clone);
179120c82538SMilan Broz 	return 0;
17928b004457SMilan Broz }
17938b004457SMilan Broz 
1794dc267621SMikulas Patocka static void kcryptd_io_read_work(struct work_struct *work)
1795395b167cSAlasdair G Kergon {
1796395b167cSAlasdair G Kergon 	struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1797395b167cSAlasdair G Kergon 
179820c82538SMilan Broz 	crypt_inc_pending(io);
179920c82538SMilan Broz 	if (kcryptd_io_read(io, GFP_NOIO))
18004e4cbee9SChristoph Hellwig 		io->error = BLK_STS_RESOURCE;
180120c82538SMilan Broz 	crypt_dec_pending(io);
1802395b167cSAlasdair G Kergon }
1803395b167cSAlasdair G Kergon 
1804dc267621SMikulas Patocka static void kcryptd_queue_read(struct dm_crypt_io *io)
1805395b167cSAlasdair G Kergon {
180649a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
1807395b167cSAlasdair G Kergon 
1808dc267621SMikulas Patocka 	INIT_WORK(&io->work, kcryptd_io_read_work);
1809395b167cSAlasdair G Kergon 	queue_work(cc->io_queue, &io->work);
1810395b167cSAlasdair G Kergon }
1811395b167cSAlasdair G Kergon 
1812dc267621SMikulas Patocka static void kcryptd_io_write(struct dm_crypt_io *io)
1813dc267621SMikulas Patocka {
1814dc267621SMikulas Patocka 	struct bio *clone = io->ctx.bio_out;
1815dc267621SMikulas Patocka 
1816dc267621SMikulas Patocka 	generic_make_request(clone);
1817dc267621SMikulas Patocka }
1818dc267621SMikulas Patocka 
1819b3c5fd30SMikulas Patocka #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1820b3c5fd30SMikulas Patocka 
1821dc267621SMikulas Patocka static int dmcrypt_write(void *data)
1822dc267621SMikulas Patocka {
1823dc267621SMikulas Patocka 	struct crypt_config *cc = data;
1824b3c5fd30SMikulas Patocka 	struct dm_crypt_io *io;
1825b3c5fd30SMikulas Patocka 
1826dc267621SMikulas Patocka 	while (1) {
1827b3c5fd30SMikulas Patocka 		struct rb_root write_tree;
1828dc267621SMikulas Patocka 		struct blk_plug plug;
1829dc267621SMikulas Patocka 
1830c7329effSMikulas Patocka 		spin_lock_irq(&cc->write_thread_lock);
1831dc267621SMikulas Patocka continue_locked:
1832dc267621SMikulas Patocka 
1833b3c5fd30SMikulas Patocka 		if (!RB_EMPTY_ROOT(&cc->write_tree))
1834dc267621SMikulas Patocka 			goto pop_from_list;
1835dc267621SMikulas Patocka 
1836f659b100SRabin Vincent 		set_current_state(TASK_INTERRUPTIBLE);
1837dc267621SMikulas Patocka 
1838c7329effSMikulas Patocka 		spin_unlock_irq(&cc->write_thread_lock);
1839dc267621SMikulas Patocka 
1840f659b100SRabin Vincent 		if (unlikely(kthread_should_stop())) {
1841642fa448SDavidlohr Bueso 			set_current_state(TASK_RUNNING);
1842f659b100SRabin Vincent 			break;
1843f659b100SRabin Vincent 		}
1844f659b100SRabin Vincent 
1845dc267621SMikulas Patocka 		schedule();
1846dc267621SMikulas Patocka 
1847642fa448SDavidlohr Bueso 		set_current_state(TASK_RUNNING);
1848c7329effSMikulas Patocka 		spin_lock_irq(&cc->write_thread_lock);
1849dc267621SMikulas Patocka 		goto continue_locked;
1850dc267621SMikulas Patocka 
1851dc267621SMikulas Patocka pop_from_list:
1852b3c5fd30SMikulas Patocka 		write_tree = cc->write_tree;
1853b3c5fd30SMikulas Patocka 		cc->write_tree = RB_ROOT;
1854c7329effSMikulas Patocka 		spin_unlock_irq(&cc->write_thread_lock);
1855dc267621SMikulas Patocka 
1856b3c5fd30SMikulas Patocka 		BUG_ON(rb_parent(write_tree.rb_node));
1857b3c5fd30SMikulas Patocka 
1858b3c5fd30SMikulas Patocka 		/*
1859b3c5fd30SMikulas Patocka 		 * Note: we cannot walk the tree here with rb_next because
1860b3c5fd30SMikulas Patocka 		 * the structures may be freed when kcryptd_io_write is called.
1861b3c5fd30SMikulas Patocka 		 */
1862dc267621SMikulas Patocka 		blk_start_plug(&plug);
1863dc267621SMikulas Patocka 		do {
1864b3c5fd30SMikulas Patocka 			io = crypt_io_from_node(rb_first(&write_tree));
1865b3c5fd30SMikulas Patocka 			rb_erase(&io->rb_node, &write_tree);
1866dc267621SMikulas Patocka 			kcryptd_io_write(io);
1867b3c5fd30SMikulas Patocka 		} while (!RB_EMPTY_ROOT(&write_tree));
1868dc267621SMikulas Patocka 		blk_finish_plug(&plug);
1869dc267621SMikulas Patocka 	}
1870dc267621SMikulas Patocka 	return 0;
1871dc267621SMikulas Patocka }
1872dc267621SMikulas Patocka 
187372c6e7afSMikulas Patocka static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
18744e4eef64SMilan Broz {
1875dec1cedfSMilan Broz 	struct bio *clone = io->ctx.bio_out;
187649a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
1877dc267621SMikulas Patocka 	unsigned long flags;
1878b3c5fd30SMikulas Patocka 	sector_t sector;
1879b3c5fd30SMikulas Patocka 	struct rb_node **rbp, *parent;
1880dec1cedfSMilan Broz 
18814e4cbee9SChristoph Hellwig 	if (unlikely(io->error)) {
1882dec1cedfSMilan Broz 		crypt_free_buffer_pages(cc, clone);
1883dec1cedfSMilan Broz 		bio_put(clone);
18846c031f41SMilan Broz 		crypt_dec_pending(io);
1885dec1cedfSMilan Broz 		return;
1886dec1cedfSMilan Broz 	}
1887dec1cedfSMilan Broz 
1888dec1cedfSMilan Broz 	/* crypt_convert should have filled the clone bio */
1889003b5c57SKent Overstreet 	BUG_ON(io->ctx.iter_out.bi_size);
1890dec1cedfSMilan Broz 
18914f024f37SKent Overstreet 	clone->bi_iter.bi_sector = cc->start + io->sector;
1892899c95d3SMilan Broz 
18930f5d8e6eSMikulas Patocka 	if (likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) {
18940f5d8e6eSMikulas Patocka 		generic_make_request(clone);
18950f5d8e6eSMikulas Patocka 		return;
18960f5d8e6eSMikulas Patocka 	}
18970f5d8e6eSMikulas Patocka 
1898c7329effSMikulas Patocka 	spin_lock_irqsave(&cc->write_thread_lock, flags);
1899c7329effSMikulas Patocka 	if (RB_EMPTY_ROOT(&cc->write_tree))
1900c7329effSMikulas Patocka 		wake_up_process(cc->write_thread);
1901b3c5fd30SMikulas Patocka 	rbp = &cc->write_tree.rb_node;
1902b3c5fd30SMikulas Patocka 	parent = NULL;
1903b3c5fd30SMikulas Patocka 	sector = io->sector;
1904b3c5fd30SMikulas Patocka 	while (*rbp) {
1905b3c5fd30SMikulas Patocka 		parent = *rbp;
1906b3c5fd30SMikulas Patocka 		if (sector < crypt_io_from_node(parent)->sector)
1907b3c5fd30SMikulas Patocka 			rbp = &(*rbp)->rb_left;
1908b3c5fd30SMikulas Patocka 		else
1909b3c5fd30SMikulas Patocka 			rbp = &(*rbp)->rb_right;
1910b3c5fd30SMikulas Patocka 	}
1911b3c5fd30SMikulas Patocka 	rb_link_node(&io->rb_node, parent, rbp);
1912b3c5fd30SMikulas Patocka 	rb_insert_color(&io->rb_node, &cc->write_tree);
1913c7329effSMikulas Patocka 	spin_unlock_irqrestore(&cc->write_thread_lock, flags);
19144e4eef64SMilan Broz }
19154e4eef64SMilan Broz 
1916fc5a5e9aSMilan Broz static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
19178b004457SMilan Broz {
191849a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
19198b004457SMilan Broz 	struct bio *clone;
1920c8081618SMilan Broz 	int crypt_finished;
1921b635b00eSMilan Broz 	sector_t sector = io->sector;
19224e4cbee9SChristoph Hellwig 	blk_status_t r;
19238b004457SMilan Broz 
192493e605c2SMilan Broz 	/*
1925fc5a5e9aSMilan Broz 	 * Prevent io from disappearing until this function completes.
1926fc5a5e9aSMilan Broz 	 */
1927fc5a5e9aSMilan Broz 	crypt_inc_pending(io);
1928b635b00eSMilan Broz 	crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
1929fc5a5e9aSMilan Broz 
1930cf2f1abfSMikulas Patocka 	clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
193123541d2dSMilan Broz 	if (unlikely(!clone)) {
19324e4cbee9SChristoph Hellwig 		io->error = BLK_STS_IOERR;
1933cf2f1abfSMikulas Patocka 		goto dec;
193423541d2dSMilan Broz 	}
19358b004457SMilan Broz 
193653017030SMilan Broz 	io->ctx.bio_out = clone;
1937003b5c57SKent Overstreet 	io->ctx.iter_out = clone->bi_iter;
19388b004457SMilan Broz 
1939b635b00eSMilan Broz 	sector += bio_sectors(clone);
1940dec1cedfSMilan Broz 
19414e594098SMilan Broz 	crypt_inc_pending(io);
1942dec1cedfSMilan Broz 	r = crypt_convert(cc, &io->ctx);
19434e4cbee9SChristoph Hellwig 	if (r)
1944ef43aa38SMilan Broz 		io->error = r;
194540b6229bSMikulas Patocka 	crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
1946dec1cedfSMilan Broz 
1947c8081618SMilan Broz 	/* Encryption was already finished, submit io now */
1948c8081618SMilan Broz 	if (crypt_finished) {
194972c6e7afSMikulas Patocka 		kcryptd_crypt_write_io_submit(io, 0);
1950b635b00eSMilan Broz 		io->sector = sector;
19514e594098SMilan Broz 	}
195293e605c2SMilan Broz 
1953cf2f1abfSMikulas Patocka dec:
1954899c95d3SMilan Broz 	crypt_dec_pending(io);
195584131db6SMilan Broz }
195684131db6SMilan Broz 
195772c6e7afSMikulas Patocka static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
19585742fd77SMilan Broz {
19595742fd77SMilan Broz 	crypt_dec_pending(io);
19605742fd77SMilan Broz }
19615742fd77SMilan Broz 
19624e4eef64SMilan Broz static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
19638b004457SMilan Broz {
196449a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
19654e4cbee9SChristoph Hellwig 	blk_status_t r;
19668b004457SMilan Broz 
19673e1a8bddSMilan Broz 	crypt_inc_pending(io);
19683a7f6c99SMilan Broz 
196953017030SMilan Broz 	crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
19700c395b0fSMilan Broz 			   io->sector);
19718b004457SMilan Broz 
19725742fd77SMilan Broz 	r = crypt_convert(cc, &io->ctx);
19734e4cbee9SChristoph Hellwig 	if (r)
1974ef43aa38SMilan Broz 		io->error = r;
19755742fd77SMilan Broz 
197640b6229bSMikulas Patocka 	if (atomic_dec_and_test(&io->ctx.cc_pending))
197772c6e7afSMikulas Patocka 		kcryptd_crypt_read_done(io);
19783a7f6c99SMilan Broz 
19793a7f6c99SMilan Broz 	crypt_dec_pending(io);
19808b004457SMilan Broz }
19818b004457SMilan Broz 
198295497a96SMilan Broz static void kcryptd_async_done(struct crypto_async_request *async_req,
198395497a96SMilan Broz 			       int error)
198495497a96SMilan Broz {
1985b2174eebSHuang Ying 	struct dm_crypt_request *dmreq = async_req->data;
1986b2174eebSHuang Ying 	struct convert_context *ctx = dmreq->ctx;
198795497a96SMilan Broz 	struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
198849a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
198995497a96SMilan Broz 
199054cea3f6SMilan Broz 	/*
199154cea3f6SMilan Broz 	 * A request from crypto driver backlog is going to be processed now,
199254cea3f6SMilan Broz 	 * finish the completion and continue in crypt_convert().
199354cea3f6SMilan Broz 	 * (Callback will be called for the second time for this request.)
199454cea3f6SMilan Broz 	 */
1995c0403ec0SRabin Vincent 	if (error == -EINPROGRESS) {
1996c0403ec0SRabin Vincent 		complete(&ctx->restart);
199795497a96SMilan Broz 		return;
1998c0403ec0SRabin Vincent 	}
199995497a96SMilan Broz 
20002dc5327dSMilan Broz 	if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
2001ef43aa38SMilan Broz 		error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
20022dc5327dSMilan Broz 
2003ef43aa38SMilan Broz 	if (error == -EBADMSG) {
2004f710126cSMilan Broz 		char b[BDEVNAME_SIZE];
2005f710126cSMilan Broz 		DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx->bio_in, b),
2006ef43aa38SMilan Broz 			    (unsigned long long)le64_to_cpu(*org_sector_of_dmreq(cc, dmreq)));
20074e4cbee9SChristoph Hellwig 		io->error = BLK_STS_PROTECTION;
2008ef43aa38SMilan Broz 	} else if (error < 0)
20094e4cbee9SChristoph Hellwig 		io->error = BLK_STS_IOERR;
201072c6e7afSMikulas Patocka 
2011298a9fa0SMikulas Patocka 	crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
201295497a96SMilan Broz 
201340b6229bSMikulas Patocka 	if (!atomic_dec_and_test(&ctx->cc_pending))
2014c0403ec0SRabin Vincent 		return;
201595497a96SMilan Broz 
201695497a96SMilan Broz 	if (bio_data_dir(io->base_bio) == READ)
201772c6e7afSMikulas Patocka 		kcryptd_crypt_read_done(io);
201895497a96SMilan Broz 	else
201972c6e7afSMikulas Patocka 		kcryptd_crypt_write_io_submit(io, 1);
202095497a96SMilan Broz }
202195497a96SMilan Broz 
20224e4eef64SMilan Broz static void kcryptd_crypt(struct work_struct *work)
20234e4eef64SMilan Broz {
20244e4eef64SMilan Broz 	struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
20254e4eef64SMilan Broz 
20264e4eef64SMilan Broz 	if (bio_data_dir(io->base_bio) == READ)
20274e4eef64SMilan Broz 		kcryptd_crypt_read_convert(io);
20284e4eef64SMilan Broz 	else
20294e4eef64SMilan Broz 		kcryptd_crypt_write_convert(io);
20308b004457SMilan Broz }
20318b004457SMilan Broz 
2032395b167cSAlasdair G Kergon static void kcryptd_queue_crypt(struct dm_crypt_io *io)
2033395b167cSAlasdair G Kergon {
203449a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
2035395b167cSAlasdair G Kergon 
2036395b167cSAlasdair G Kergon 	INIT_WORK(&io->work, kcryptd_crypt);
2037395b167cSAlasdair G Kergon 	queue_work(cc->crypt_queue, &io->work);
2038395b167cSAlasdair G Kergon }
2039395b167cSAlasdair G Kergon 
2040ef43aa38SMilan Broz static void crypt_free_tfms_aead(struct crypt_config *cc)
20411da177e4SLinus Torvalds {
2042ef43aa38SMilan Broz 	if (!cc->cipher_tfm.tfms_aead)
2043ef43aa38SMilan Broz 		return;
20441da177e4SLinus Torvalds 
2045ef43aa38SMilan Broz 	if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2046ef43aa38SMilan Broz 		crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
2047ef43aa38SMilan Broz 		cc->cipher_tfm.tfms_aead[0] = NULL;
20481da177e4SLinus Torvalds 	}
20491da177e4SLinus Torvalds 
2050ef43aa38SMilan Broz 	kfree(cc->cipher_tfm.tfms_aead);
2051ef43aa38SMilan Broz 	cc->cipher_tfm.tfms_aead = NULL;
2052ef43aa38SMilan Broz }
20531da177e4SLinus Torvalds 
2054ef43aa38SMilan Broz static void crypt_free_tfms_skcipher(struct crypt_config *cc)
2055d1f96423SMilan Broz {
2056d1f96423SMilan Broz 	unsigned i;
2057d1f96423SMilan Broz 
2058ef43aa38SMilan Broz 	if (!cc->cipher_tfm.tfms)
2059fd2d231fSMikulas Patocka 		return;
2060fd2d231fSMikulas Patocka 
2061d1f96423SMilan Broz 	for (i = 0; i < cc->tfms_count; i++)
2062ef43aa38SMilan Broz 		if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
2063ef43aa38SMilan Broz 			crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
2064ef43aa38SMilan Broz 			cc->cipher_tfm.tfms[i] = NULL;
2065d1f96423SMilan Broz 		}
2066d1f96423SMilan Broz 
2067ef43aa38SMilan Broz 	kfree(cc->cipher_tfm.tfms);
2068ef43aa38SMilan Broz 	cc->cipher_tfm.tfms = NULL;
20691da177e4SLinus Torvalds }
20701da177e4SLinus Torvalds 
20711da177e4SLinus Torvalds static void crypt_free_tfms(struct crypt_config *cc)
2072d1f96423SMilan Broz {
207333d2f09fSMilan Broz 	if (crypt_integrity_aead(cc))
2074ef43aa38SMilan Broz 		crypt_free_tfms_aead(cc);
2075ef43aa38SMilan Broz 	else
2076ef43aa38SMilan Broz 		crypt_free_tfms_skcipher(cc);
2077d1f96423SMilan Broz }
2078d1f96423SMilan Broz 
2079ef43aa38SMilan Broz static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
2080d1f96423SMilan Broz {
2081d1f96423SMilan Broz 	unsigned i;
2082d1f96423SMilan Broz 	int err;
2083d1f96423SMilan Broz 
20846396bb22SKees Cook 	cc->cipher_tfm.tfms = kcalloc(cc->tfms_count,
20856396bb22SKees Cook 				      sizeof(struct crypto_skcipher *),
20866396bb22SKees Cook 				      GFP_KERNEL);
2087ef43aa38SMilan Broz 	if (!cc->cipher_tfm.tfms)
2088fd2d231fSMikulas Patocka 		return -ENOMEM;
2089fd2d231fSMikulas Patocka 
2090d1f96423SMilan Broz 	for (i = 0; i < cc->tfms_count; i++) {
2091ef43aa38SMilan Broz 		cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0, 0);
2092ef43aa38SMilan Broz 		if (IS_ERR(cc->cipher_tfm.tfms[i])) {
2093ef43aa38SMilan Broz 			err = PTR_ERR(cc->cipher_tfm.tfms[i]);
2094fd2d231fSMikulas Patocka 			crypt_free_tfms(cc);
2095d1f96423SMilan Broz 			return err;
2096d1f96423SMilan Broz 		}
2097d1f96423SMilan Broz 	}
2098d1f96423SMilan Broz 
2099af331ebaSEric Biggers 	/*
2100af331ebaSEric Biggers 	 * dm-crypt performance can vary greatly depending on which crypto
2101af331ebaSEric Biggers 	 * algorithm implementation is used.  Help people debug performance
2102af331ebaSEric Biggers 	 * problems by logging the ->cra_driver_name.
2103af331ebaSEric Biggers 	 */
21047a1cd723SMilan Broz 	DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2105af331ebaSEric Biggers 	       crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
2106d1f96423SMilan Broz 	return 0;
2107d1f96423SMilan Broz }
2108d1f96423SMilan Broz 
2109ef43aa38SMilan Broz static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
2110ef43aa38SMilan Broz {
2111ef43aa38SMilan Broz 	int err;
2112ef43aa38SMilan Broz 
2113ef43aa38SMilan Broz 	cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
2114ef43aa38SMilan Broz 	if (!cc->cipher_tfm.tfms)
2115ef43aa38SMilan Broz 		return -ENOMEM;
2116ef43aa38SMilan Broz 
2117ef43aa38SMilan Broz 	cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0, 0);
2118ef43aa38SMilan Broz 	if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2119ef43aa38SMilan Broz 		err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
2120ef43aa38SMilan Broz 		crypt_free_tfms(cc);
2121ef43aa38SMilan Broz 		return err;
2122ef43aa38SMilan Broz 	}
2123ef43aa38SMilan Broz 
21247a1cd723SMilan Broz 	DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2125af331ebaSEric Biggers 	       crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
2126ef43aa38SMilan Broz 	return 0;
2127ef43aa38SMilan Broz }
2128ef43aa38SMilan Broz 
2129ef43aa38SMilan Broz static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
2130ef43aa38SMilan Broz {
213133d2f09fSMilan Broz 	if (crypt_integrity_aead(cc))
2132ef43aa38SMilan Broz 		return crypt_alloc_tfms_aead(cc, ciphermode);
2133ef43aa38SMilan Broz 	else
2134ef43aa38SMilan Broz 		return crypt_alloc_tfms_skcipher(cc, ciphermode);
2135ef43aa38SMilan Broz }
2136ef43aa38SMilan Broz 
2137ef43aa38SMilan Broz static unsigned crypt_subkey_size(struct crypt_config *cc)
2138ef43aa38SMilan Broz {
2139ef43aa38SMilan Broz 	return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
2140ef43aa38SMilan Broz }
2141ef43aa38SMilan Broz 
2142ef43aa38SMilan Broz static unsigned crypt_authenckey_size(struct crypt_config *cc)
2143ef43aa38SMilan Broz {
2144ef43aa38SMilan Broz 	return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
2145ef43aa38SMilan Broz }
2146ef43aa38SMilan Broz 
2147ef43aa38SMilan Broz /*
2148ef43aa38SMilan Broz  * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
2149ef43aa38SMilan Broz  * the key must be for some reason in special format.
2150ef43aa38SMilan Broz  * This funcion converts cc->key to this special format.
2151ef43aa38SMilan Broz  */
2152ef43aa38SMilan Broz static void crypt_copy_authenckey(char *p, const void *key,
2153ef43aa38SMilan Broz 				  unsigned enckeylen, unsigned authkeylen)
2154ef43aa38SMilan Broz {
2155ef43aa38SMilan Broz 	struct crypto_authenc_key_param *param;
2156ef43aa38SMilan Broz 	struct rtattr *rta;
2157ef43aa38SMilan Broz 
2158ef43aa38SMilan Broz 	rta = (struct rtattr *)p;
2159ef43aa38SMilan Broz 	param = RTA_DATA(rta);
2160ef43aa38SMilan Broz 	param->enckeylen = cpu_to_be32(enckeylen);
2161ef43aa38SMilan Broz 	rta->rta_len = RTA_LENGTH(sizeof(*param));
2162ef43aa38SMilan Broz 	rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
2163ef43aa38SMilan Broz 	p += RTA_SPACE(sizeof(*param));
2164ef43aa38SMilan Broz 	memcpy(p, key + enckeylen, authkeylen);
2165ef43aa38SMilan Broz 	p += authkeylen;
2166ef43aa38SMilan Broz 	memcpy(p, key, enckeylen);
2167ef43aa38SMilan Broz }
2168ef43aa38SMilan Broz 
2169671ea6b4SMikulas Patocka static int crypt_setkey(struct crypt_config *cc)
2170c0297721SAndi Kleen {
2171da31a078SMilan Broz 	unsigned subkey_size;
2172fd2d231fSMikulas Patocka 	int err = 0, i, r;
2173c0297721SAndi Kleen 
2174da31a078SMilan Broz 	/* Ignore extra keys (which are used for IV etc) */
2175ef43aa38SMilan Broz 	subkey_size = crypt_subkey_size(cc);
2176da31a078SMilan Broz 
217727c70036SMilan Broz 	if (crypt_integrity_hmac(cc)) {
217827c70036SMilan Broz 		if (subkey_size < cc->key_mac_size)
217927c70036SMilan Broz 			return -EINVAL;
218027c70036SMilan Broz 
2181ef43aa38SMilan Broz 		crypt_copy_authenckey(cc->authenc_key, cc->key,
2182ef43aa38SMilan Broz 				      subkey_size - cc->key_mac_size,
2183ef43aa38SMilan Broz 				      cc->key_mac_size);
218427c70036SMilan Broz 	}
218527c70036SMilan Broz 
2186d1f96423SMilan Broz 	for (i = 0; i < cc->tfms_count; i++) {
218733d2f09fSMilan Broz 		if (crypt_integrity_hmac(cc))
218833d2f09fSMilan Broz 			r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
218933d2f09fSMilan Broz 				cc->authenc_key, crypt_authenckey_size(cc));
219033d2f09fSMilan Broz 		else if (crypt_integrity_aead(cc))
2191ef43aa38SMilan Broz 			r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2192ef43aa38SMilan Broz 					       cc->key + (i * subkey_size),
2193ef43aa38SMilan Broz 					       subkey_size);
2194ef43aa38SMilan Broz 		else
2195ef43aa38SMilan Broz 			r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
2196fd2d231fSMikulas Patocka 						   cc->key + (i * subkey_size),
2197fd2d231fSMikulas Patocka 						   subkey_size);
2198c0297721SAndi Kleen 		if (r)
2199c0297721SAndi Kleen 			err = r;
2200c0297721SAndi Kleen 	}
2201c0297721SAndi Kleen 
2202ef43aa38SMilan Broz 	if (crypt_integrity_hmac(cc))
2203ef43aa38SMilan Broz 		memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
2204ef43aa38SMilan Broz 
2205c0297721SAndi Kleen 	return err;
2206c0297721SAndi Kleen }
2207c0297721SAndi Kleen 
2208c538f6ecSOndrej Kozina #ifdef CONFIG_KEYS
2209c538f6ecSOndrej Kozina 
2210027c431cSOndrej Kozina static bool contains_whitespace(const char *str)
2211027c431cSOndrej Kozina {
2212027c431cSOndrej Kozina 	while (*str)
2213027c431cSOndrej Kozina 		if (isspace(*str++))
2214027c431cSOndrej Kozina 			return true;
2215027c431cSOndrej Kozina 	return false;
2216027c431cSOndrej Kozina }
2217027c431cSOndrej Kozina 
2218c538f6ecSOndrej Kozina static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2219c538f6ecSOndrej Kozina {
2220c538f6ecSOndrej Kozina 	char *new_key_string, *key_desc;
2221c538f6ecSOndrej Kozina 	int ret;
2222c538f6ecSOndrej Kozina 	struct key *key;
2223c538f6ecSOndrej Kozina 	const struct user_key_payload *ukp;
2224c538f6ecSOndrej Kozina 
2225027c431cSOndrej Kozina 	/*
2226027c431cSOndrej Kozina 	 * Reject key_string with whitespace. dm core currently lacks code for
2227027c431cSOndrej Kozina 	 * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2228027c431cSOndrej Kozina 	 */
2229027c431cSOndrej Kozina 	if (contains_whitespace(key_string)) {
2230027c431cSOndrej Kozina 		DMERR("whitespace chars not allowed in key string");
2231027c431cSOndrej Kozina 		return -EINVAL;
2232027c431cSOndrej Kozina 	}
2233027c431cSOndrej Kozina 
2234c538f6ecSOndrej Kozina 	/* look for next ':' separating key_type from key_description */
2235c538f6ecSOndrej Kozina 	key_desc = strpbrk(key_string, ":");
2236c538f6ecSOndrej Kozina 	if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2237c538f6ecSOndrej Kozina 		return -EINVAL;
2238c538f6ecSOndrej Kozina 
2239c538f6ecSOndrej Kozina 	if (strncmp(key_string, "logon:", key_desc - key_string + 1) &&
2240c538f6ecSOndrej Kozina 	    strncmp(key_string, "user:", key_desc - key_string + 1))
2241c538f6ecSOndrej Kozina 		return -EINVAL;
2242c538f6ecSOndrej Kozina 
2243c538f6ecSOndrej Kozina 	new_key_string = kstrdup(key_string, GFP_KERNEL);
2244c538f6ecSOndrej Kozina 	if (!new_key_string)
2245c538f6ecSOndrej Kozina 		return -ENOMEM;
2246c538f6ecSOndrej Kozina 
2247c538f6ecSOndrej Kozina 	key = request_key(key_string[0] == 'l' ? &key_type_logon : &key_type_user,
2248c538f6ecSOndrej Kozina 			  key_desc + 1, NULL);
2249c538f6ecSOndrej Kozina 	if (IS_ERR(key)) {
2250c538f6ecSOndrej Kozina 		kzfree(new_key_string);
2251c538f6ecSOndrej Kozina 		return PTR_ERR(key);
2252c538f6ecSOndrej Kozina 	}
2253c538f6ecSOndrej Kozina 
2254f5b0cba8SOndrej Kozina 	down_read(&key->sem);
2255c538f6ecSOndrej Kozina 
22560837e49aSDavid Howells 	ukp = user_key_payload_locked(key);
2257c538f6ecSOndrej Kozina 	if (!ukp) {
2258f5b0cba8SOndrej Kozina 		up_read(&key->sem);
2259c538f6ecSOndrej Kozina 		key_put(key);
2260c538f6ecSOndrej Kozina 		kzfree(new_key_string);
2261c538f6ecSOndrej Kozina 		return -EKEYREVOKED;
2262c538f6ecSOndrej Kozina 	}
2263c538f6ecSOndrej Kozina 
2264c538f6ecSOndrej Kozina 	if (cc->key_size != ukp->datalen) {
2265f5b0cba8SOndrej Kozina 		up_read(&key->sem);
2266c538f6ecSOndrej Kozina 		key_put(key);
2267c538f6ecSOndrej Kozina 		kzfree(new_key_string);
2268c538f6ecSOndrej Kozina 		return -EINVAL;
2269c538f6ecSOndrej Kozina 	}
2270c538f6ecSOndrej Kozina 
2271c538f6ecSOndrej Kozina 	memcpy(cc->key, ukp->data, cc->key_size);
2272c538f6ecSOndrej Kozina 
2273f5b0cba8SOndrej Kozina 	up_read(&key->sem);
2274c538f6ecSOndrej Kozina 	key_put(key);
2275c538f6ecSOndrej Kozina 
2276c538f6ecSOndrej Kozina 	/* clear the flag since following operations may invalidate previously valid key */
2277c538f6ecSOndrej Kozina 	clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2278c538f6ecSOndrej Kozina 
2279c538f6ecSOndrej Kozina 	ret = crypt_setkey(cc);
2280c538f6ecSOndrej Kozina 
2281c538f6ecSOndrej Kozina 	if (!ret) {
2282c538f6ecSOndrej Kozina 		set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2283c538f6ecSOndrej Kozina 		kzfree(cc->key_string);
2284c538f6ecSOndrej Kozina 		cc->key_string = new_key_string;
2285c538f6ecSOndrej Kozina 	} else
2286c538f6ecSOndrej Kozina 		kzfree(new_key_string);
2287c538f6ecSOndrej Kozina 
2288c538f6ecSOndrej Kozina 	return ret;
2289c538f6ecSOndrej Kozina }
2290c538f6ecSOndrej Kozina 
2291c538f6ecSOndrej Kozina static int get_key_size(char **key_string)
2292c538f6ecSOndrej Kozina {
2293c538f6ecSOndrej Kozina 	char *colon, dummy;
2294c538f6ecSOndrej Kozina 	int ret;
2295c538f6ecSOndrej Kozina 
2296c538f6ecSOndrej Kozina 	if (*key_string[0] != ':')
2297c538f6ecSOndrej Kozina 		return strlen(*key_string) >> 1;
2298c538f6ecSOndrej Kozina 
2299c538f6ecSOndrej Kozina 	/* look for next ':' in key string */
2300c538f6ecSOndrej Kozina 	colon = strpbrk(*key_string + 1, ":");
2301c538f6ecSOndrej Kozina 	if (!colon)
2302c538f6ecSOndrej Kozina 		return -EINVAL;
2303c538f6ecSOndrej Kozina 
2304c538f6ecSOndrej Kozina 	if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2305c538f6ecSOndrej Kozina 		return -EINVAL;
2306c538f6ecSOndrej Kozina 
2307c538f6ecSOndrej Kozina 	*key_string = colon;
2308c538f6ecSOndrej Kozina 
2309c538f6ecSOndrej Kozina 	/* remaining key string should be :<logon|user>:<key_desc> */
2310c538f6ecSOndrej Kozina 
2311c538f6ecSOndrej Kozina 	return ret;
2312c538f6ecSOndrej Kozina }
2313c538f6ecSOndrej Kozina 
2314c538f6ecSOndrej Kozina #else
2315c538f6ecSOndrej Kozina 
2316c538f6ecSOndrej Kozina static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2317c538f6ecSOndrej Kozina {
2318c538f6ecSOndrej Kozina 	return -EINVAL;
2319c538f6ecSOndrej Kozina }
2320c538f6ecSOndrej Kozina 
2321c538f6ecSOndrej Kozina static int get_key_size(char **key_string)
2322c538f6ecSOndrej Kozina {
2323c538f6ecSOndrej Kozina 	return (*key_string[0] == ':') ? -EINVAL : strlen(*key_string) >> 1;
2324c538f6ecSOndrej Kozina }
2325c538f6ecSOndrej Kozina 
2326c538f6ecSOndrej Kozina #endif
2327c538f6ecSOndrej Kozina 
2328e48d4bbfSMilan Broz static int crypt_set_key(struct crypt_config *cc, char *key)
2329e48d4bbfSMilan Broz {
2330de8be5acSMilan Broz 	int r = -EINVAL;
2331de8be5acSMilan Broz 	int key_string_len = strlen(key);
2332de8be5acSMilan Broz 
233369a8cfcdSMilan Broz 	/* Hyphen (which gives a key_size of zero) means there is no key. */
233469a8cfcdSMilan Broz 	if (!cc->key_size && strcmp(key, "-"))
2335de8be5acSMilan Broz 		goto out;
2336e48d4bbfSMilan Broz 
2337c538f6ecSOndrej Kozina 	/* ':' means the key is in kernel keyring, short-circuit normal key processing */
2338c538f6ecSOndrej Kozina 	if (key[0] == ':') {
2339c538f6ecSOndrej Kozina 		r = crypt_set_keyring_key(cc, key + 1);
2340c538f6ecSOndrej Kozina 		goto out;
2341c538f6ecSOndrej Kozina 	}
2342c538f6ecSOndrej Kozina 
2343265e9098SOndrej Kozina 	/* clear the flag since following operations may invalidate previously valid key */
2344265e9098SOndrej Kozina 	clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2345265e9098SOndrej Kozina 
2346c538f6ecSOndrej Kozina 	/* wipe references to any kernel keyring key */
2347c538f6ecSOndrej Kozina 	kzfree(cc->key_string);
2348c538f6ecSOndrej Kozina 	cc->key_string = NULL;
2349c538f6ecSOndrej Kozina 
2350e944e03eSAndy Shevchenko 	/* Decode key from its hex representation. */
2351e944e03eSAndy Shevchenko 	if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
2352de8be5acSMilan Broz 		goto out;
2353e48d4bbfSMilan Broz 
2354671ea6b4SMikulas Patocka 	r = crypt_setkey(cc);
2355265e9098SOndrej Kozina 	if (!r)
2356e48d4bbfSMilan Broz 		set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2357e48d4bbfSMilan Broz 
2358de8be5acSMilan Broz out:
2359de8be5acSMilan Broz 	/* Hex key string not needed after here, so wipe it. */
2360de8be5acSMilan Broz 	memset(key, '0', key_string_len);
2361de8be5acSMilan Broz 
2362de8be5acSMilan Broz 	return r;
2363e48d4bbfSMilan Broz }
2364e48d4bbfSMilan Broz 
2365e48d4bbfSMilan Broz static int crypt_wipe_key(struct crypt_config *cc)
2366e48d4bbfSMilan Broz {
2367c82feeecSOndrej Kozina 	int r;
2368c82feeecSOndrej Kozina 
2369e48d4bbfSMilan Broz 	clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2370c82feeecSOndrej Kozina 	get_random_bytes(&cc->key, cc->key_size);
23714a52ffc7SMilan Broz 
23724a52ffc7SMilan Broz 	/* Wipe IV private keys */
23734a52ffc7SMilan Broz 	if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
23744a52ffc7SMilan Broz 		r = cc->iv_gen_ops->wipe(cc);
23754a52ffc7SMilan Broz 		if (r)
23764a52ffc7SMilan Broz 			return r;
23774a52ffc7SMilan Broz 	}
23784a52ffc7SMilan Broz 
2379c538f6ecSOndrej Kozina 	kzfree(cc->key_string);
2380c538f6ecSOndrej Kozina 	cc->key_string = NULL;
2381c82feeecSOndrej Kozina 	r = crypt_setkey(cc);
2382c82feeecSOndrej Kozina 	memset(&cc->key, 0, cc->key_size * sizeof(u8));
2383c0297721SAndi Kleen 
2384c82feeecSOndrej Kozina 	return r;
2385e48d4bbfSMilan Broz }
2386e48d4bbfSMilan Broz 
23875059353dSMikulas Patocka static void crypt_calculate_pages_per_client(void)
23885059353dSMikulas Patocka {
2389ca79b0c2SArun KS 	unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
23905059353dSMikulas Patocka 
23915059353dSMikulas Patocka 	if (!dm_crypt_clients_n)
23925059353dSMikulas Patocka 		return;
23935059353dSMikulas Patocka 
23945059353dSMikulas Patocka 	pages /= dm_crypt_clients_n;
23955059353dSMikulas Patocka 	if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
23965059353dSMikulas Patocka 		pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
23975059353dSMikulas Patocka 	dm_crypt_pages_per_client = pages;
23985059353dSMikulas Patocka }
23995059353dSMikulas Patocka 
24005059353dSMikulas Patocka static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
24015059353dSMikulas Patocka {
24025059353dSMikulas Patocka 	struct crypt_config *cc = pool_data;
24035059353dSMikulas Patocka 	struct page *page;
24045059353dSMikulas Patocka 
24055059353dSMikulas Patocka 	if (unlikely(percpu_counter_compare(&cc->n_allocated_pages, dm_crypt_pages_per_client) >= 0) &&
24065059353dSMikulas Patocka 	    likely(gfp_mask & __GFP_NORETRY))
24075059353dSMikulas Patocka 		return NULL;
24085059353dSMikulas Patocka 
24095059353dSMikulas Patocka 	page = alloc_page(gfp_mask);
24105059353dSMikulas Patocka 	if (likely(page != NULL))
24115059353dSMikulas Patocka 		percpu_counter_add(&cc->n_allocated_pages, 1);
24125059353dSMikulas Patocka 
24135059353dSMikulas Patocka 	return page;
24145059353dSMikulas Patocka }
24155059353dSMikulas Patocka 
24165059353dSMikulas Patocka static void crypt_page_free(void *page, void *pool_data)
24175059353dSMikulas Patocka {
24185059353dSMikulas Patocka 	struct crypt_config *cc = pool_data;
24195059353dSMikulas Patocka 
24205059353dSMikulas Patocka 	__free_page(page);
24215059353dSMikulas Patocka 	percpu_counter_sub(&cc->n_allocated_pages, 1);
24225059353dSMikulas Patocka }
24235059353dSMikulas Patocka 
242428513fccSMilan Broz static void crypt_dtr(struct dm_target *ti)
242528513fccSMilan Broz {
242628513fccSMilan Broz 	struct crypt_config *cc = ti->private;
242728513fccSMilan Broz 
242828513fccSMilan Broz 	ti->private = NULL;
242928513fccSMilan Broz 
243028513fccSMilan Broz 	if (!cc)
243128513fccSMilan Broz 		return;
243228513fccSMilan Broz 
2433f659b100SRabin Vincent 	if (cc->write_thread)
2434dc267621SMikulas Patocka 		kthread_stop(cc->write_thread);
2435dc267621SMikulas Patocka 
243628513fccSMilan Broz 	if (cc->io_queue)
243728513fccSMilan Broz 		destroy_workqueue(cc->io_queue);
243828513fccSMilan Broz 	if (cc->crypt_queue)
243928513fccSMilan Broz 		destroy_workqueue(cc->crypt_queue);
244028513fccSMilan Broz 
2441fd2d231fSMikulas Patocka 	crypt_free_tfms(cc);
2442fd2d231fSMikulas Patocka 
24436f1c819cSKent Overstreet 	bioset_exit(&cc->bs);
244428513fccSMilan Broz 
24456f1c819cSKent Overstreet 	mempool_exit(&cc->page_pool);
24466f1c819cSKent Overstreet 	mempool_exit(&cc->req_pool);
24476f1c819cSKent Overstreet 	mempool_exit(&cc->tag_pool);
24486f1c819cSKent Overstreet 
2449d00a11dfSKent Overstreet 	WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
2450d00a11dfSKent Overstreet 	percpu_counter_destroy(&cc->n_allocated_pages);
2451d00a11dfSKent Overstreet 
245228513fccSMilan Broz 	if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
245328513fccSMilan Broz 		cc->iv_gen_ops->dtr(cc);
245428513fccSMilan Broz 
245528513fccSMilan Broz 	if (cc->dev)
245628513fccSMilan Broz 		dm_put_device(ti, cc->dev);
245728513fccSMilan Broz 
24587dbcd137SMilan Broz 	kzfree(cc->cipher_string);
2459c538f6ecSOndrej Kozina 	kzfree(cc->key_string);
2460ef43aa38SMilan Broz 	kzfree(cc->cipher_auth);
2461ef43aa38SMilan Broz 	kzfree(cc->authenc_key);
246228513fccSMilan Broz 
2463d5ffebddSMike Snitzer 	mutex_destroy(&cc->bio_alloc_lock);
2464d5ffebddSMike Snitzer 
246528513fccSMilan Broz 	/* Must zero key material before freeing */
246628513fccSMilan Broz 	kzfree(cc);
24675059353dSMikulas Patocka 
24685059353dSMikulas Patocka 	spin_lock(&dm_crypt_clients_lock);
24695059353dSMikulas Patocka 	WARN_ON(!dm_crypt_clients_n);
24705059353dSMikulas Patocka 	dm_crypt_clients_n--;
24715059353dSMikulas Patocka 	crypt_calculate_pages_per_client();
24725059353dSMikulas Patocka 	spin_unlock(&dm_crypt_clients_lock);
247328513fccSMilan Broz }
247428513fccSMilan Broz 
2475e889f97aSMilan Broz static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
24761da177e4SLinus Torvalds {
24775ebaee6dSMilan Broz 	struct crypt_config *cc = ti->private;
24781da177e4SLinus Torvalds 
247933d2f09fSMilan Broz 	if (crypt_integrity_aead(cc))
2480e889f97aSMilan Broz 		cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2481e889f97aSMilan Broz 	else
2482bbdb23b5SHerbert Xu 		cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2483e889f97aSMilan Broz 
24845ebaee6dSMilan Broz 	if (cc->iv_size)
24855ebaee6dSMilan Broz 		/* at least a 64 bit sector number should fit in our buffer */
24865ebaee6dSMilan Broz 		cc->iv_size = max(cc->iv_size,
24875ebaee6dSMilan Broz 				  (unsigned int)(sizeof(u64) / sizeof(u8)));
24885ebaee6dSMilan Broz 	else if (ivmode) {
24895ebaee6dSMilan Broz 		DMWARN("Selected cipher does not support IVs");
24905ebaee6dSMilan Broz 		ivmode = NULL;
24915ebaee6dSMilan Broz 	}
24925ebaee6dSMilan Broz 
24935ebaee6dSMilan Broz 	/* Choose ivmode, see comments at iv code. */
24941da177e4SLinus Torvalds 	if (ivmode == NULL)
24951da177e4SLinus Torvalds 		cc->iv_gen_ops = NULL;
24961da177e4SLinus Torvalds 	else if (strcmp(ivmode, "plain") == 0)
24971da177e4SLinus Torvalds 		cc->iv_gen_ops = &crypt_iv_plain_ops;
249861afef61SMilan Broz 	else if (strcmp(ivmode, "plain64") == 0)
249961afef61SMilan Broz 		cc->iv_gen_ops = &crypt_iv_plain64_ops;
25007e3fd855SMilan Broz 	else if (strcmp(ivmode, "plain64be") == 0)
25017e3fd855SMilan Broz 		cc->iv_gen_ops = &crypt_iv_plain64be_ops;
25021da177e4SLinus Torvalds 	else if (strcmp(ivmode, "essiv") == 0)
25031da177e4SLinus Torvalds 		cc->iv_gen_ops = &crypt_iv_essiv_ops;
250448527fa7SRik Snel 	else if (strcmp(ivmode, "benbi") == 0)
250548527fa7SRik Snel 		cc->iv_gen_ops = &crypt_iv_benbi_ops;
250646b47730SLudwig Nussel 	else if (strcmp(ivmode, "null") == 0)
250746b47730SLudwig Nussel 		cc->iv_gen_ops = &crypt_iv_null_ops;
2508b9411d73SMilan Broz 	else if (strcmp(ivmode, "eboiv") == 0)
2509b9411d73SMilan Broz 		cc->iv_gen_ops = &crypt_iv_eboiv_ops;
2510bbb16584SMilan Broz 	else if (strcmp(ivmode, "elephant") == 0) {
2511bbb16584SMilan Broz 		cc->iv_gen_ops = &crypt_iv_elephant_ops;
2512bbb16584SMilan Broz 		cc->key_parts = 2;
2513bbb16584SMilan Broz 		cc->key_extra_size = cc->key_size / 2;
2514bbb16584SMilan Broz 		if (cc->key_extra_size > ELEPHANT_MAX_KEY_SIZE)
2515bbb16584SMilan Broz 			return -EINVAL;
2516bbb16584SMilan Broz 		set_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags);
2517bbb16584SMilan Broz 	} else if (strcmp(ivmode, "lmk") == 0) {
251834745785SMilan Broz 		cc->iv_gen_ops = &crypt_iv_lmk_ops;
2519ed04d981SMilan Broz 		/*
2520ed04d981SMilan Broz 		 * Version 2 and 3 is recognised according
252134745785SMilan Broz 		 * to length of provided multi-key string.
252234745785SMilan Broz 		 * If present (version 3), last key is used as IV seed.
2523ed04d981SMilan Broz 		 * All keys (including IV seed) are always the same size.
252434745785SMilan Broz 		 */
2525da31a078SMilan Broz 		if (cc->key_size % cc->key_parts) {
252634745785SMilan Broz 			cc->key_parts++;
2527da31a078SMilan Broz 			cc->key_extra_size = cc->key_size / cc->key_parts;
2528da31a078SMilan Broz 		}
2529ed04d981SMilan Broz 	} else if (strcmp(ivmode, "tcw") == 0) {
2530ed04d981SMilan Broz 		cc->iv_gen_ops = &crypt_iv_tcw_ops;
2531ed04d981SMilan Broz 		cc->key_parts += 2; /* IV + whitening */
2532ed04d981SMilan Broz 		cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2533e889f97aSMilan Broz 	} else if (strcmp(ivmode, "random") == 0) {
2534e889f97aSMilan Broz 		cc->iv_gen_ops = &crypt_iv_random_ops;
2535e889f97aSMilan Broz 		/* Need storage space in integrity fields. */
2536e889f97aSMilan Broz 		cc->integrity_iv_size = cc->iv_size;
253734745785SMilan Broz 	} else {
253872d94861SAlasdair G Kergon 		ti->error = "Invalid IV mode";
2539e889f97aSMilan Broz 		return -EINVAL;
25401da177e4SLinus Torvalds 	}
25411da177e4SLinus Torvalds 
2542e889f97aSMilan Broz 	return 0;
2543e889f97aSMilan Broz }
2544e889f97aSMilan Broz 
254533d2f09fSMilan Broz /*
254633d2f09fSMilan Broz  * Workaround to parse HMAC algorithm from AEAD crypto API spec.
254733d2f09fSMilan Broz  * The HMAC is needed to calculate tag size (HMAC digest size).
254833d2f09fSMilan Broz  * This should be probably done by crypto-api calls (once available...)
254933d2f09fSMilan Broz  */
255033d2f09fSMilan Broz static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
255133d2f09fSMilan Broz {
255233d2f09fSMilan Broz 	char *start, *end, *mac_alg = NULL;
255333d2f09fSMilan Broz 	struct crypto_ahash *mac;
255433d2f09fSMilan Broz 
255533d2f09fSMilan Broz 	if (!strstarts(cipher_api, "authenc("))
255633d2f09fSMilan Broz 		return 0;
255733d2f09fSMilan Broz 
255833d2f09fSMilan Broz 	start = strchr(cipher_api, '(');
255933d2f09fSMilan Broz 	end = strchr(cipher_api, ',');
256033d2f09fSMilan Broz 	if (!start || !end || ++start > end)
256133d2f09fSMilan Broz 		return -EINVAL;
256233d2f09fSMilan Broz 
256333d2f09fSMilan Broz 	mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
256433d2f09fSMilan Broz 	if (!mac_alg)
256533d2f09fSMilan Broz 		return -ENOMEM;
256633d2f09fSMilan Broz 	strncpy(mac_alg, start, end - start);
256733d2f09fSMilan Broz 
256833d2f09fSMilan Broz 	mac = crypto_alloc_ahash(mac_alg, 0, 0);
256933d2f09fSMilan Broz 	kfree(mac_alg);
257033d2f09fSMilan Broz 
257133d2f09fSMilan Broz 	if (IS_ERR(mac))
257233d2f09fSMilan Broz 		return PTR_ERR(mac);
257333d2f09fSMilan Broz 
257433d2f09fSMilan Broz 	cc->key_mac_size = crypto_ahash_digestsize(mac);
257533d2f09fSMilan Broz 	crypto_free_ahash(mac);
257633d2f09fSMilan Broz 
257733d2f09fSMilan Broz 	cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
257833d2f09fSMilan Broz 	if (!cc->authenc_key)
257933d2f09fSMilan Broz 		return -ENOMEM;
258033d2f09fSMilan Broz 
258133d2f09fSMilan Broz 	return 0;
258233d2f09fSMilan Broz }
258333d2f09fSMilan Broz 
258433d2f09fSMilan Broz static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
258533d2f09fSMilan Broz 				char **ivmode, char **ivopts)
25861da177e4SLinus Torvalds {
25875ebaee6dSMilan Broz 	struct crypt_config *cc = ti->private;
2588a1a262b6SArd Biesheuvel 	char *tmp, *cipher_api, buf[CRYPTO_MAX_ALG_NAME];
258933d2f09fSMilan Broz 	int ret = -EINVAL;
259033d2f09fSMilan Broz 
259133d2f09fSMilan Broz 	cc->tfms_count = 1;
259233d2f09fSMilan Broz 
259333d2f09fSMilan Broz 	/*
259433d2f09fSMilan Broz 	 * New format (capi: prefix)
259533d2f09fSMilan Broz 	 * capi:cipher_api_spec-iv:ivopts
259633d2f09fSMilan Broz 	 */
259733d2f09fSMilan Broz 	tmp = &cipher_in[strlen("capi:")];
25981856b9f7SMilan Broz 
25991856b9f7SMilan Broz 	/* Separate IV options if present, it can contain another '-' in hash name */
26001856b9f7SMilan Broz 	*ivopts = strrchr(tmp, ':');
26011856b9f7SMilan Broz 	if (*ivopts) {
26021856b9f7SMilan Broz 		**ivopts = '\0';
26031856b9f7SMilan Broz 		(*ivopts)++;
26041856b9f7SMilan Broz 	}
26051856b9f7SMilan Broz 	/* Parse IV mode */
26061856b9f7SMilan Broz 	*ivmode = strrchr(tmp, '-');
26071856b9f7SMilan Broz 	if (*ivmode) {
26081856b9f7SMilan Broz 		**ivmode = '\0';
26091856b9f7SMilan Broz 		(*ivmode)++;
26101856b9f7SMilan Broz 	}
26111856b9f7SMilan Broz 	/* The rest is crypto API spec */
26121856b9f7SMilan Broz 	cipher_api = tmp;
261333d2f09fSMilan Broz 
2614a1a262b6SArd Biesheuvel 	/* Alloc AEAD, can be used only in new format. */
2615a1a262b6SArd Biesheuvel 	if (crypt_integrity_aead(cc)) {
2616a1a262b6SArd Biesheuvel 		ret = crypt_ctr_auth_cipher(cc, cipher_api);
2617a1a262b6SArd Biesheuvel 		if (ret < 0) {
2618a1a262b6SArd Biesheuvel 			ti->error = "Invalid AEAD cipher spec";
2619a1a262b6SArd Biesheuvel 			return -ENOMEM;
2620a1a262b6SArd Biesheuvel 		}
2621a1a262b6SArd Biesheuvel 	}
2622a1a262b6SArd Biesheuvel 
262333d2f09fSMilan Broz 	if (*ivmode && !strcmp(*ivmode, "lmk"))
262433d2f09fSMilan Broz 		cc->tfms_count = 64;
262533d2f09fSMilan Broz 
2626a1a262b6SArd Biesheuvel 	if (*ivmode && !strcmp(*ivmode, "essiv")) {
2627a1a262b6SArd Biesheuvel 		if (!*ivopts) {
2628a1a262b6SArd Biesheuvel 			ti->error = "Digest algorithm missing for ESSIV mode";
2629a1a262b6SArd Biesheuvel 			return -EINVAL;
2630a1a262b6SArd Biesheuvel 		}
2631a1a262b6SArd Biesheuvel 		ret = snprintf(buf, CRYPTO_MAX_ALG_NAME, "essiv(%s,%s)",
2632a1a262b6SArd Biesheuvel 			       cipher_api, *ivopts);
2633a1a262b6SArd Biesheuvel 		if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2634a1a262b6SArd Biesheuvel 			ti->error = "Cannot allocate cipher string";
2635a1a262b6SArd Biesheuvel 			return -ENOMEM;
2636a1a262b6SArd Biesheuvel 		}
2637a1a262b6SArd Biesheuvel 		cipher_api = buf;
2638a1a262b6SArd Biesheuvel 	}
2639a1a262b6SArd Biesheuvel 
264033d2f09fSMilan Broz 	cc->key_parts = cc->tfms_count;
264133d2f09fSMilan Broz 
264233d2f09fSMilan Broz 	/* Allocate cipher */
264333d2f09fSMilan Broz 	ret = crypt_alloc_tfms(cc, cipher_api);
264433d2f09fSMilan Broz 	if (ret < 0) {
264533d2f09fSMilan Broz 		ti->error = "Error allocating crypto tfm";
264633d2f09fSMilan Broz 		return ret;
264733d2f09fSMilan Broz 	}
264833d2f09fSMilan Broz 
2649a1a262b6SArd Biesheuvel 	if (crypt_integrity_aead(cc))
265033d2f09fSMilan Broz 		cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2651a1a262b6SArd Biesheuvel 	else
265233d2f09fSMilan Broz 		cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
265333d2f09fSMilan Broz 
265433d2f09fSMilan Broz 	return 0;
265533d2f09fSMilan Broz }
265633d2f09fSMilan Broz 
265733d2f09fSMilan Broz static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
265833d2f09fSMilan Broz 				char **ivmode, char **ivopts)
265933d2f09fSMilan Broz {
266033d2f09fSMilan Broz 	struct crypt_config *cc = ti->private;
266133d2f09fSMilan Broz 	char *tmp, *cipher, *chainmode, *keycount;
26625ebaee6dSMilan Broz 	char *cipher_api = NULL;
26635ebaee6dSMilan Broz 	int ret = -EINVAL;
26645ebaee6dSMilan Broz 	char dummy;
26655ebaee6dSMilan Broz 
266633d2f09fSMilan Broz 	if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
26675ebaee6dSMilan Broz 		ti->error = "Bad cipher specification";
26685ebaee6dSMilan Broz 		return -EINVAL;
26695ebaee6dSMilan Broz 	}
26705ebaee6dSMilan Broz 
26711da177e4SLinus Torvalds 	/*
26725ebaee6dSMilan Broz 	 * Legacy dm-crypt cipher specification
26735ebaee6dSMilan Broz 	 * cipher[:keycount]-mode-iv:ivopts
26745ebaee6dSMilan Broz 	 */
26755ebaee6dSMilan Broz 	tmp = cipher_in;
26765ebaee6dSMilan Broz 	keycount = strsep(&tmp, "-");
26775ebaee6dSMilan Broz 	cipher = strsep(&keycount, ":");
26785ebaee6dSMilan Broz 
267969a8cfcdSMilan Broz 	if (!keycount)
26805ebaee6dSMilan Broz 		cc->tfms_count = 1;
26815ebaee6dSMilan Broz 	else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
26825ebaee6dSMilan Broz 		 !is_power_of_2(cc->tfms_count)) {
26835ebaee6dSMilan Broz 		ti->error = "Bad cipher key count specification";
26845ebaee6dSMilan Broz 		return -EINVAL;
26855ebaee6dSMilan Broz 	}
268628513fccSMilan Broz 	cc->key_parts = cc->tfms_count;
26871da177e4SLinus Torvalds 
2688ddd42edfSMilan Broz 	chainmode = strsep(&tmp, "-");
26891856b9f7SMilan Broz 	*ivmode = strsep(&tmp, ":");
26901856b9f7SMilan Broz 	*ivopts = tmp;
2691ddd42edfSMilan Broz 
2692ddd42edfSMilan Broz 	/*
2693ddd42edfSMilan Broz 	 * For compatibility with the original dm-crypt mapping format, if
2694ddd42edfSMilan Broz 	 * only the cipher name is supplied, use cbc-plain.
269528513fccSMilan Broz 	 */
269633d2f09fSMilan Broz 	if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
2697cabf08e4SMilan Broz 		chainmode = "cbc";
269833d2f09fSMilan Broz 		*ivmode = "plain";
2699cabf08e4SMilan Broz 	}
2700cabf08e4SMilan Broz 
270133d2f09fSMilan Broz 	if (strcmp(chainmode, "ecb") && !*ivmode) {
2702c0297721SAndi Kleen 		ti->error = "IV mechanism required";
2703c0297721SAndi Kleen 		return -EINVAL;
2704c0297721SAndi Kleen 	}
2705c0297721SAndi Kleen 
2706cabf08e4SMilan Broz 	cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
27079934a8beSMilan Broz 	if (!cipher_api)
270828513fccSMilan Broz 		goto bad_mem;
27099934a8beSMilan Broz 
2710a1a262b6SArd Biesheuvel 	if (*ivmode && !strcmp(*ivmode, "essiv")) {
2711a1a262b6SArd Biesheuvel 		if (!*ivopts) {
2712a1a262b6SArd Biesheuvel 			ti->error = "Digest algorithm missing for ESSIV mode";
2713a1a262b6SArd Biesheuvel 			kfree(cipher_api);
2714a1a262b6SArd Biesheuvel 			return -EINVAL;
2715a1a262b6SArd Biesheuvel 		}
2716a1a262b6SArd Biesheuvel 		ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2717a1a262b6SArd Biesheuvel 			       "essiv(%s(%s),%s)", chainmode, cipher, *ivopts);
2718a1a262b6SArd Biesheuvel 	} else {
27199934a8beSMilan Broz 		ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2720647c7db1SMikulas Patocka 			       "%s(%s)", chainmode, cipher);
2721a1a262b6SArd Biesheuvel 	}
2722a1a262b6SArd Biesheuvel 	if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
27231da177e4SLinus Torvalds 		kfree(cipher_api);
272428513fccSMilan Broz 		goto bad_mem;
272528513fccSMilan Broz 	}
272628513fccSMilan Broz 
27271da177e4SLinus Torvalds 	/* Allocate cipher */
27281da177e4SLinus Torvalds 	ret = crypt_alloc_tfms(cc, cipher_api);
27291da177e4SLinus Torvalds 	if (ret < 0) {
27301da177e4SLinus Torvalds 		ti->error = "Error allocating crypto tfm";
273133d2f09fSMilan Broz 		kfree(cipher_api);
273233d2f09fSMilan Broz 		return ret;
2733028867acSAlasdair G Kergon 	}
2734bd86e320SJeffy Chen 	kfree(cipher_api);
2735647c7db1SMikulas Patocka 
273633d2f09fSMilan Broz 	return 0;
273733d2f09fSMilan Broz bad_mem:
273833d2f09fSMilan Broz 	ti->error = "Cannot allocate cipher strings";
273933d2f09fSMilan Broz 	return -ENOMEM;
274033d2f09fSMilan Broz }
274133d2f09fSMilan Broz 
274233d2f09fSMilan Broz static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
274333d2f09fSMilan Broz {
274433d2f09fSMilan Broz 	struct crypt_config *cc = ti->private;
274533d2f09fSMilan Broz 	char *ivmode = NULL, *ivopts = NULL;
274633d2f09fSMilan Broz 	int ret;
274733d2f09fSMilan Broz 
274833d2f09fSMilan Broz 	cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
274933d2f09fSMilan Broz 	if (!cc->cipher_string) {
275033d2f09fSMilan Broz 		ti->error = "Cannot allocate cipher strings";
275133d2f09fSMilan Broz 		return -ENOMEM;
275233d2f09fSMilan Broz 	}
275333d2f09fSMilan Broz 
275433d2f09fSMilan Broz 	if (strstarts(cipher_in, "capi:"))
275533d2f09fSMilan Broz 		ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
275633d2f09fSMilan Broz 	else
275733d2f09fSMilan Broz 		ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
275833d2f09fSMilan Broz 	if (ret)
275933d2f09fSMilan Broz 		return ret;
276033d2f09fSMilan Broz 
2761647c7db1SMikulas Patocka 	/* Initialize IV */
2762e889f97aSMilan Broz 	ret = crypt_ctr_ivmode(ti, ivmode);
2763e889f97aSMilan Broz 	if (ret < 0)
276433d2f09fSMilan Broz 		return ret;
27651da177e4SLinus Torvalds 
2766da31a078SMilan Broz 	/* Initialize and set key */
2767da31a078SMilan Broz 	ret = crypt_set_key(cc, key);
2768da31a078SMilan Broz 	if (ret < 0) {
2769da31a078SMilan Broz 		ti->error = "Error decoding and setting key";
277033d2f09fSMilan Broz 		return ret;
2771da31a078SMilan Broz 	}
2772da31a078SMilan Broz 
27731da177e4SLinus Torvalds 	/* Allocate IV */
27741da177e4SLinus Torvalds 	if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
27751da177e4SLinus Torvalds 		ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
27761da177e4SLinus Torvalds 		if (ret < 0) {
27771da177e4SLinus Torvalds 			ti->error = "Error creating IV";
277833d2f09fSMilan Broz 			return ret;
27791da177e4SLinus Torvalds 		}
27801da177e4SLinus Torvalds 	}
27811da177e4SLinus Torvalds 
27821da177e4SLinus Torvalds 	/* Initialize IV (set keys for ESSIV etc) */
27831da177e4SLinus Torvalds 	if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
27841da177e4SLinus Torvalds 		ret = cc->iv_gen_ops->init(cc);
27851da177e4SLinus Torvalds 		if (ret < 0) {
27861da177e4SLinus Torvalds 			ti->error = "Error initialising IV";
27871da177e4SLinus Torvalds 			return ret;
27881da177e4SLinus Torvalds 		}
27891da177e4SLinus Torvalds 	}
27901da177e4SLinus Torvalds 
2791dc94902bSOndrej Kozina 	/* wipe the kernel key payload copy */
2792dc94902bSOndrej Kozina 	if (cc->key_string)
2793dc94902bSOndrej Kozina 		memset(cc->key, 0, cc->key_size * sizeof(u8));
2794dc94902bSOndrej Kozina 
279533d2f09fSMilan Broz 	return ret;
27961da177e4SLinus Torvalds }
27971da177e4SLinus Torvalds 
2798ef43aa38SMilan Broz static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
2799ef43aa38SMilan Broz {
2800ef43aa38SMilan Broz 	struct crypt_config *cc = ti->private;
2801ef43aa38SMilan Broz 	struct dm_arg_set as;
28025916a22bSEric Biggers 	static const struct dm_arg _args[] = {
28038f0009a2SMilan Broz 		{0, 6, "Invalid number of feature args"},
2804ef43aa38SMilan Broz 	};
2805ef43aa38SMilan Broz 	unsigned int opt_params, val;
2806ef43aa38SMilan Broz 	const char *opt_string, *sval;
28078f0009a2SMilan Broz 	char dummy;
2808ef43aa38SMilan Broz 	int ret;
2809ef43aa38SMilan Broz 
2810ef43aa38SMilan Broz 	/* Optional parameters */
2811ef43aa38SMilan Broz 	as.argc = argc;
2812ef43aa38SMilan Broz 	as.argv = argv;
2813ef43aa38SMilan Broz 
2814ef43aa38SMilan Broz 	ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
2815ef43aa38SMilan Broz 	if (ret)
28161da177e4SLinus Torvalds 		return ret;
28171da177e4SLinus Torvalds 
2818ef43aa38SMilan Broz 	while (opt_params--) {
2819ef43aa38SMilan Broz 		opt_string = dm_shift_arg(&as);
2820ef43aa38SMilan Broz 		if (!opt_string) {
2821ef43aa38SMilan Broz 			ti->error = "Not enough feature arguments";
2822ef43aa38SMilan Broz 			return -EINVAL;
2823ef43aa38SMilan Broz 		}
2824ef43aa38SMilan Broz 
2825ef43aa38SMilan Broz 		if (!strcasecmp(opt_string, "allow_discards"))
2826ef43aa38SMilan Broz 			ti->num_discard_bios = 1;
2827ef43aa38SMilan Broz 
2828ef43aa38SMilan Broz 		else if (!strcasecmp(opt_string, "same_cpu_crypt"))
2829ef43aa38SMilan Broz 			set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
2830ef43aa38SMilan Broz 
2831ef43aa38SMilan Broz 		else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
2832ef43aa38SMilan Broz 			set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
2833ef43aa38SMilan Broz 		else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
2834ef43aa38SMilan Broz 			if (val == 0 || val > MAX_TAG_SIZE) {
2835ef43aa38SMilan Broz 				ti->error = "Invalid integrity arguments";
2836ef43aa38SMilan Broz 				return -EINVAL;
2837ef43aa38SMilan Broz 			}
2838ef43aa38SMilan Broz 			cc->on_disk_tag_size = val;
2839ef43aa38SMilan Broz 			sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
2840ef43aa38SMilan Broz 			if (!strcasecmp(sval, "aead")) {
2841ef43aa38SMilan Broz 				set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
2842ef43aa38SMilan Broz 			} else  if (strcasecmp(sval, "none")) {
2843ef43aa38SMilan Broz 				ti->error = "Unknown integrity profile";
2844ef43aa38SMilan Broz 				return -EINVAL;
2845ef43aa38SMilan Broz 			}
2846ef43aa38SMilan Broz 
2847ef43aa38SMilan Broz 			cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
2848ef43aa38SMilan Broz 			if (!cc->cipher_auth)
28491da177e4SLinus Torvalds 				return -ENOMEM;
2850ff3af92bSMikulas Patocka 		} else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
28518f0009a2SMilan Broz 			if (cc->sector_size < (1 << SECTOR_SHIFT) ||
28528f0009a2SMilan Broz 			    cc->sector_size > 4096 ||
2853ff3af92bSMikulas Patocka 			    (cc->sector_size & (cc->sector_size - 1))) {
28548f0009a2SMilan Broz 				ti->error = "Invalid feature value for sector_size";
28558f0009a2SMilan Broz 				return -EINVAL;
28568f0009a2SMilan Broz 			}
2857783874b0SMilan Broz 			if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
2858783874b0SMilan Broz 				ti->error = "Device size is not multiple of sector_size feature";
2859783874b0SMilan Broz 				return -EINVAL;
2860783874b0SMilan Broz 			}
2861ff3af92bSMikulas Patocka 			cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
28628f0009a2SMilan Broz 		} else if (!strcasecmp(opt_string, "iv_large_sectors"))
28638f0009a2SMilan Broz 			set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
28648f0009a2SMilan Broz 		else {
2865ef43aa38SMilan Broz 			ti->error = "Invalid feature arguments";
2866ef43aa38SMilan Broz 			return -EINVAL;
2867ef43aa38SMilan Broz 		}
2868ef43aa38SMilan Broz 	}
2869ef43aa38SMilan Broz 
2870ef43aa38SMilan Broz 	return 0;
28711da177e4SLinus Torvalds }
28721da177e4SLinus Torvalds 
28731da177e4SLinus Torvalds /*
28741da177e4SLinus Torvalds  * Construct an encryption mapping:
2875c538f6ecSOndrej Kozina  * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
28761da177e4SLinus Torvalds  */
28771da177e4SLinus Torvalds static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
28781da177e4SLinus Torvalds {
28791da177e4SLinus Torvalds 	struct crypt_config *cc;
2880ed0302e8SMichał Mirosław 	const char *devname = dm_table_device_name(ti->table);
2881c538f6ecSOndrej Kozina 	int key_size;
2882ef43aa38SMilan Broz 	unsigned int align_mask;
28831da177e4SLinus Torvalds 	unsigned long long tmpll;
28841da177e4SLinus Torvalds 	int ret;
2885ef43aa38SMilan Broz 	size_t iv_size_padding, additional_req_size;
288631998ef1SMikulas Patocka 	char dummy;
28871da177e4SLinus Torvalds 
2888772ae5f5SMilan Broz 	if (argc < 5) {
28891da177e4SLinus Torvalds 		ti->error = "Not enough arguments";
28901da177e4SLinus Torvalds 		return -EINVAL;
28911da177e4SLinus Torvalds 	}
28921da177e4SLinus Torvalds 
2893c538f6ecSOndrej Kozina 	key_size = get_key_size(&argv[1]);
2894c538f6ecSOndrej Kozina 	if (key_size < 0) {
2895c538f6ecSOndrej Kozina 		ti->error = "Cannot parse key size";
2896c538f6ecSOndrej Kozina 		return -EINVAL;
2897c538f6ecSOndrej Kozina 	}
28981da177e4SLinus Torvalds 
28999c81c99bSZhengyuan Liu 	cc = kzalloc(struct_size(cc, key, key_size), GFP_KERNEL);
29001da177e4SLinus Torvalds 	if (!cc) {
29011da177e4SLinus Torvalds 		ti->error = "Cannot allocate encryption context";
29021da177e4SLinus Torvalds 		return -ENOMEM;
29031da177e4SLinus Torvalds 	}
29041da177e4SLinus Torvalds 	cc->key_size = key_size;
29058f0009a2SMilan Broz 	cc->sector_size = (1 << SECTOR_SHIFT);
2906ff3af92bSMikulas Patocka 	cc->sector_shift = 0;
29071da177e4SLinus Torvalds 
29081da177e4SLinus Torvalds 	ti->private = cc;
2909ef43aa38SMilan Broz 
29105059353dSMikulas Patocka 	spin_lock(&dm_crypt_clients_lock);
29115059353dSMikulas Patocka 	dm_crypt_clients_n++;
29125059353dSMikulas Patocka 	crypt_calculate_pages_per_client();
29135059353dSMikulas Patocka 	spin_unlock(&dm_crypt_clients_lock);
29145059353dSMikulas Patocka 
29155059353dSMikulas Patocka 	ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
29165059353dSMikulas Patocka 	if (ret < 0)
29175059353dSMikulas Patocka 		goto bad;
29185059353dSMikulas Patocka 
2919ef43aa38SMilan Broz 	/* Optional parameters need to be read before cipher constructor */
2920ef43aa38SMilan Broz 	if (argc > 5) {
2921ef43aa38SMilan Broz 		ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
2922ef43aa38SMilan Broz 		if (ret)
2923ef43aa38SMilan Broz 			goto bad;
2924ef43aa38SMilan Broz 	}
2925ef43aa38SMilan Broz 
29261da177e4SLinus Torvalds 	ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
29271da177e4SLinus Torvalds 	if (ret < 0)
29281da177e4SLinus Torvalds 		goto bad;
29291da177e4SLinus Torvalds 
293033d2f09fSMilan Broz 	if (crypt_integrity_aead(cc)) {
2931ef43aa38SMilan Broz 		cc->dmreq_start = sizeof(struct aead_request);
2932ef43aa38SMilan Broz 		cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
2933ef43aa38SMilan Broz 		align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
2934ef43aa38SMilan Broz 	} else {
2935bbdb23b5SHerbert Xu 		cc->dmreq_start = sizeof(struct skcipher_request);
2936bbdb23b5SHerbert Xu 		cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
2937ef43aa38SMilan Broz 		align_mask = crypto_skcipher_alignmask(any_tfm(cc));
2938ef43aa38SMilan Broz 	}
2939d49ec52fSMikulas Patocka 	cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
2940d49ec52fSMikulas Patocka 
2941ef43aa38SMilan Broz 	if (align_mask < CRYPTO_MINALIGN) {
2942d49ec52fSMikulas Patocka 		/* Allocate the padding exactly */
2943d49ec52fSMikulas Patocka 		iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
2944ef43aa38SMilan Broz 				& align_mask;
2945d49ec52fSMikulas Patocka 	} else {
2946d49ec52fSMikulas Patocka 		/*
2947d49ec52fSMikulas Patocka 		 * If the cipher requires greater alignment than kmalloc
2948d49ec52fSMikulas Patocka 		 * alignment, we don't know the exact position of the
2949d49ec52fSMikulas Patocka 		 * initialization vector. We must assume worst case.
2950d49ec52fSMikulas Patocka 		 */
2951ef43aa38SMilan Broz 		iv_size_padding = align_mask;
2952d49ec52fSMikulas Patocka 	}
29531da177e4SLinus Torvalds 
2954ef43aa38SMilan Broz 	/*  ...| IV + padding | original IV | original sec. number | bio tag offset | */
2955ef43aa38SMilan Broz 	additional_req_size = sizeof(struct dm_crypt_request) +
2956ef43aa38SMilan Broz 		iv_size_padding + cc->iv_size +
2957ef43aa38SMilan Broz 		cc->iv_size +
2958ef43aa38SMilan Broz 		sizeof(uint64_t) +
2959ef43aa38SMilan Broz 		sizeof(unsigned int);
2960ef43aa38SMilan Broz 
29616f1c819cSKent Overstreet 	ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
29626f1c819cSKent Overstreet 	if (ret) {
29631da177e4SLinus Torvalds 		ti->error = "Cannot allocate crypt request mempool";
29641da177e4SLinus Torvalds 		goto bad;
29651da177e4SLinus Torvalds 	}
29661da177e4SLinus Torvalds 
296730187e1dSMike Snitzer 	cc->per_bio_data_size = ti->per_io_data_size =
2968ef43aa38SMilan Broz 		ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
2969d49ec52fSMikulas Patocka 		      ARCH_KMALLOC_MINALIGN);
2970298a9fa0SMikulas Patocka 
29716f1c819cSKent Overstreet 	ret = mempool_init(&cc->page_pool, BIO_MAX_PAGES, crypt_page_alloc, crypt_page_free, cc);
29726f1c819cSKent Overstreet 	if (ret) {
29738b004457SMilan Broz 		ti->error = "Cannot allocate page mempool";
2974e48d4bbfSMilan Broz 		goto bad;
29751da177e4SLinus Torvalds 	}
2976e48d4bbfSMilan Broz 
29776f1c819cSKent Overstreet 	ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
29786f1c819cSKent Overstreet 	if (ret) {
29790c395b0fSMilan Broz 		ti->error = "Cannot allocate crypt bioset";
2980cabf08e4SMilan Broz 		goto bad;
298193e605c2SMilan Broz 	}
2982cabf08e4SMilan Broz 
29837145c241SMikulas Patocka 	mutex_init(&cc->bio_alloc_lock);
29847145c241SMikulas Patocka 
2985cabf08e4SMilan Broz 	ret = -EINVAL;
29868f0009a2SMilan Broz 	if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
29878f0009a2SMilan Broz 	    (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
2988cabf08e4SMilan Broz 		ti->error = "Invalid iv_offset sector";
2989cabf08e4SMilan Broz 		goto bad;
29901da177e4SLinus Torvalds 	}
2991d2a7ad29SKiyoshi Ueda 	cc->iv_offset = tmpll;
29921da177e4SLinus Torvalds 
2993e80d1c80SVivek Goyal 	ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
2994e80d1c80SVivek Goyal 	if (ret) {
29951da177e4SLinus Torvalds 		ti->error = "Device lookup failed";
29961da177e4SLinus Torvalds 		goto bad;
29971da177e4SLinus Torvalds 	}
29981da177e4SLinus Torvalds 
2999e80d1c80SVivek Goyal 	ret = -EINVAL;
3000ef87bfc2SMilan Broz 	if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
30011da177e4SLinus Torvalds 		ti->error = "Invalid device sector";
30021da177e4SLinus Torvalds 		goto bad;
30031da177e4SLinus Torvalds 	}
30041da177e4SLinus Torvalds 	cc->start = tmpll;
30051da177e4SLinus Torvalds 
300633d2f09fSMilan Broz 	if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
3007ef43aa38SMilan Broz 		ret = crypt_integrity_ctr(cc, ti);
3008772ae5f5SMilan Broz 		if (ret)
3009772ae5f5SMilan Broz 			goto bad;
3010772ae5f5SMilan Broz 
3011ef43aa38SMilan Broz 		cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
3012ef43aa38SMilan Broz 		if (!cc->tag_pool_max_sectors)
3013ef43aa38SMilan Broz 			cc->tag_pool_max_sectors = 1;
3014ef43aa38SMilan Broz 
30156f1c819cSKent Overstreet 		ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
3016ef43aa38SMilan Broz 			cc->tag_pool_max_sectors * cc->on_disk_tag_size);
30176f1c819cSKent Overstreet 		if (ret) {
3018ef43aa38SMilan Broz 			ti->error = "Cannot allocate integrity tags mempool";
3019f3396c58SMikulas Patocka 			goto bad;
3020f3396c58SMikulas Patocka 		}
3021772ae5f5SMilan Broz 
3022583fe747SMikulas Patocka 		cc->tag_pool_max_sectors <<= cc->sector_shift;
3023f3396c58SMikulas Patocka 	}
3024772ae5f5SMilan Broz 
30251da177e4SLinus Torvalds 	ret = -ENOMEM;
3026f612b213SMike Snitzer 	cc->io_queue = alloc_workqueue("kcryptd_io/%s", WQ_MEM_RECLAIM, 1, devname);
30271da177e4SLinus Torvalds 	if (!cc->io_queue) {
30281da177e4SLinus Torvalds 		ti->error = "Couldn't create kcryptd io queue";
30291da177e4SLinus Torvalds 		goto bad;
30301da177e4SLinus Torvalds 	}
303137af6560SChristophe Saout 
3032f3396c58SMikulas Patocka 	if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3033f612b213SMike Snitzer 		cc->crypt_queue = alloc_workqueue("kcryptd/%s", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM,
3034ed0302e8SMichał Mirosław 						  1, devname);
3035f3396c58SMikulas Patocka 	else
3036ed0302e8SMichał Mirosław 		cc->crypt_queue = alloc_workqueue("kcryptd/%s",
3037f612b213SMike Snitzer 						  WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
3038ed0302e8SMichał Mirosław 						  num_online_cpus(), devname);
30391da177e4SLinus Torvalds 	if (!cc->crypt_queue) {
30401da177e4SLinus Torvalds 		ti->error = "Couldn't create kcryptd queue";
30411da177e4SLinus Torvalds 		goto bad;
30421da177e4SLinus Torvalds 	}
30431da177e4SLinus Torvalds 
3044c7329effSMikulas Patocka 	spin_lock_init(&cc->write_thread_lock);
3045b3c5fd30SMikulas Patocka 	cc->write_tree = RB_ROOT;
3046dc267621SMikulas Patocka 
3047ed0302e8SMichał Mirosław 	cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
3048dc267621SMikulas Patocka 	if (IS_ERR(cc->write_thread)) {
3049dc267621SMikulas Patocka 		ret = PTR_ERR(cc->write_thread);
3050dc267621SMikulas Patocka 		cc->write_thread = NULL;
3051dc267621SMikulas Patocka 		ti->error = "Couldn't spawn write thread";
3052dc267621SMikulas Patocka 		goto bad;
3053dc267621SMikulas Patocka 	}
3054dc267621SMikulas Patocka 	wake_up_process(cc->write_thread);
3055dc267621SMikulas Patocka 
305655a62eefSAlasdair G Kergon 	ti->num_flush_bios = 1;
3057983c7db3SMilan Broz 
30581da177e4SLinus Torvalds 	return 0;
30591da177e4SLinus Torvalds 
30601da177e4SLinus Torvalds bad:
30611da177e4SLinus Torvalds 	crypt_dtr(ti);
30621da177e4SLinus Torvalds 	return ret;
3063647c7db1SMikulas Patocka }
3064647c7db1SMikulas Patocka 
30657de3ee57SMikulas Patocka static int crypt_map(struct dm_target *ti, struct bio *bio)
30661da177e4SLinus Torvalds {
30671da177e4SLinus Torvalds 	struct dm_crypt_io *io;
306849a8a920SAlasdair G Kergon 	struct crypt_config *cc = ti->private;
3069647c7db1SMikulas Patocka 
3070772ae5f5SMilan Broz 	/*
307128a8f0d3SMike Christie 	 * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
307228a8f0d3SMike Christie 	 * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
3073e6047149SMike Christie 	 * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
3074772ae5f5SMilan Broz 	 */
30751eff9d32SJens Axboe 	if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
307628a8f0d3SMike Christie 	    bio_op(bio) == REQ_OP_DISCARD)) {
307774d46992SChristoph Hellwig 		bio_set_dev(bio, cc->dev->bdev);
3078772ae5f5SMilan Broz 		if (bio_sectors(bio))
30794f024f37SKent Overstreet 			bio->bi_iter.bi_sector = cc->start +
30804f024f37SKent Overstreet 				dm_target_offset(ti, bio->bi_iter.bi_sector);
3081647c7db1SMikulas Patocka 		return DM_MAPIO_REMAPPED;
3082647c7db1SMikulas Patocka 	}
30831da177e4SLinus Torvalds 
30844e870e94SMikulas Patocka 	/*
30854e870e94SMikulas Patocka 	 * Check if bio is too large, split as needed.
30864e870e94SMikulas Patocka 	 */
30874e870e94SMikulas Patocka 	if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_PAGES << PAGE_SHIFT)) &&
3088ef43aa38SMilan Broz 	    (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
30894e870e94SMikulas Patocka 		dm_accept_partial_bio(bio, ((BIO_MAX_PAGES << PAGE_SHIFT) >> SECTOR_SHIFT));
30904e870e94SMikulas Patocka 
30918f0009a2SMilan Broz 	/*
30928f0009a2SMilan Broz 	 * Ensure that bio is a multiple of internal sector encryption size
30938f0009a2SMilan Broz 	 * and is aligned to this size as defined in IO hints.
30948f0009a2SMilan Broz 	 */
30958f0009a2SMilan Broz 	if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
3096846785e6SChristoph Hellwig 		return DM_MAPIO_KILL;
30978f0009a2SMilan Broz 
30988f0009a2SMilan Broz 	if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
3099846785e6SChristoph Hellwig 		return DM_MAPIO_KILL;
31008f0009a2SMilan Broz 
3101298a9fa0SMikulas Patocka 	io = dm_per_bio_data(bio, cc->per_bio_data_size);
3102298a9fa0SMikulas Patocka 	crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
3103ef43aa38SMilan Broz 
3104ef43aa38SMilan Broz 	if (cc->on_disk_tag_size) {
3105583fe747SMikulas Patocka 		unsigned tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
3106ef43aa38SMilan Broz 
3107ef43aa38SMilan Broz 		if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
3108583fe747SMikulas Patocka 		    unlikely(!(io->integrity_metadata = kmalloc(tag_len,
3109ef43aa38SMilan Broz 				GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
3110ef43aa38SMilan Broz 			if (bio_sectors(bio) > cc->tag_pool_max_sectors)
3111ef43aa38SMilan Broz 				dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
31126f1c819cSKent Overstreet 			io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
3113ef43aa38SMilan Broz 			io->integrity_metadata_from_pool = true;
3114ef43aa38SMilan Broz 		}
3115ef43aa38SMilan Broz 	}
3116ef43aa38SMilan Broz 
311733d2f09fSMilan Broz 	if (crypt_integrity_aead(cc))
3118ef43aa38SMilan Broz 		io->ctx.r.req_aead = (struct aead_request *)(io + 1);
3119ef43aa38SMilan Broz 	else
3120ef43aa38SMilan Broz 		io->ctx.r.req = (struct skcipher_request *)(io + 1);
31211da177e4SLinus Torvalds 
312220c82538SMilan Broz 	if (bio_data_dir(io->base_bio) == READ) {
312320c82538SMilan Broz 		if (kcryptd_io_read(io, GFP_NOWAIT))
3124dc267621SMikulas Patocka 			kcryptd_queue_read(io);
312520c82538SMilan Broz 	} else
31264ee218cdSAndrew Morton 		kcryptd_queue_crypt(io);
31274ee218cdSAndrew Morton 
31281da177e4SLinus Torvalds 	return DM_MAPIO_SUBMITTED;
31291da177e4SLinus Torvalds }
31301da177e4SLinus Torvalds 
3131fd7c092eSMikulas Patocka static void crypt_status(struct dm_target *ti, status_type_t type,
31321f4e0ff0SAlasdair G Kergon 			 unsigned status_flags, char *result, unsigned maxlen)
31331da177e4SLinus Torvalds {
31345ebaee6dSMilan Broz 	struct crypt_config *cc = ti->private;
3135fd7c092eSMikulas Patocka 	unsigned i, sz = 0;
3136f3396c58SMikulas Patocka 	int num_feature_args = 0;
31371da177e4SLinus Torvalds 
31381da177e4SLinus Torvalds 	switch (type) {
31391da177e4SLinus Torvalds 	case STATUSTYPE_INFO:
31401da177e4SLinus Torvalds 		result[0] = '\0';
31411da177e4SLinus Torvalds 		break;
31421da177e4SLinus Torvalds 
31431da177e4SLinus Torvalds 	case STATUSTYPE_TABLE:
31447dbcd137SMilan Broz 		DMEMIT("%s ", cc->cipher_string);
31451da177e4SLinus Torvalds 
3146c538f6ecSOndrej Kozina 		if (cc->key_size > 0) {
3147c538f6ecSOndrej Kozina 			if (cc->key_string)
3148c538f6ecSOndrej Kozina 				DMEMIT(":%u:%s", cc->key_size, cc->key_string);
3149c538f6ecSOndrej Kozina 			else
3150fd7c092eSMikulas Patocka 				for (i = 0; i < cc->key_size; i++)
3151fd7c092eSMikulas Patocka 					DMEMIT("%02x", cc->key[i]);
3152c538f6ecSOndrej Kozina 		} else
3153fd7c092eSMikulas Patocka 			DMEMIT("-");
31541da177e4SLinus Torvalds 
31551da177e4SLinus Torvalds 		DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
31561da177e4SLinus Torvalds 				cc->dev->name, (unsigned long long)cc->start);
3157772ae5f5SMilan Broz 
3158f3396c58SMikulas Patocka 		num_feature_args += !!ti->num_discard_bios;
3159f3396c58SMikulas Patocka 		num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
31600f5d8e6eSMikulas Patocka 		num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3161ff3af92bSMikulas Patocka 		num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
31628f0009a2SMilan Broz 		num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3163ef43aa38SMilan Broz 		if (cc->on_disk_tag_size)
3164ef43aa38SMilan Broz 			num_feature_args++;
3165f3396c58SMikulas Patocka 		if (num_feature_args) {
3166f3396c58SMikulas Patocka 			DMEMIT(" %d", num_feature_args);
316755a62eefSAlasdair G Kergon 			if (ti->num_discard_bios)
3168f3396c58SMikulas Patocka 				DMEMIT(" allow_discards");
3169f3396c58SMikulas Patocka 			if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3170f3396c58SMikulas Patocka 				DMEMIT(" same_cpu_crypt");
31710f5d8e6eSMikulas Patocka 			if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
31720f5d8e6eSMikulas Patocka 				DMEMIT(" submit_from_crypt_cpus");
3173ef43aa38SMilan Broz 			if (cc->on_disk_tag_size)
3174ef43aa38SMilan Broz 				DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
31758f0009a2SMilan Broz 			if (cc->sector_size != (1 << SECTOR_SHIFT))
31768f0009a2SMilan Broz 				DMEMIT(" sector_size:%d", cc->sector_size);
31778f0009a2SMilan Broz 			if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
31788f0009a2SMilan Broz 				DMEMIT(" iv_large_sectors");
3179f3396c58SMikulas Patocka 		}
3180772ae5f5SMilan Broz 
31811da177e4SLinus Torvalds 		break;
31821da177e4SLinus Torvalds 	}
31831da177e4SLinus Torvalds }
31841da177e4SLinus Torvalds 
3185e48d4bbfSMilan Broz static void crypt_postsuspend(struct dm_target *ti)
3186e48d4bbfSMilan Broz {
3187e48d4bbfSMilan Broz 	struct crypt_config *cc = ti->private;
3188e48d4bbfSMilan Broz 
3189e48d4bbfSMilan Broz 	set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3190e48d4bbfSMilan Broz }
3191e48d4bbfSMilan Broz 
3192e48d4bbfSMilan Broz static int crypt_preresume(struct dm_target *ti)
3193e48d4bbfSMilan Broz {
3194e48d4bbfSMilan Broz 	struct crypt_config *cc = ti->private;
3195e48d4bbfSMilan Broz 
3196e48d4bbfSMilan Broz 	if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
3197e48d4bbfSMilan Broz 		DMERR("aborting resume - crypt key is not set.");
3198e48d4bbfSMilan Broz 		return -EAGAIN;
3199e48d4bbfSMilan Broz 	}
3200e48d4bbfSMilan Broz 
3201e48d4bbfSMilan Broz 	return 0;
3202e48d4bbfSMilan Broz }
3203e48d4bbfSMilan Broz 
3204e48d4bbfSMilan Broz static void crypt_resume(struct dm_target *ti)
3205e48d4bbfSMilan Broz {
3206e48d4bbfSMilan Broz 	struct crypt_config *cc = ti->private;
3207e48d4bbfSMilan Broz 
3208e48d4bbfSMilan Broz 	clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3209e48d4bbfSMilan Broz }
3210e48d4bbfSMilan Broz 
3211e48d4bbfSMilan Broz /* Message interface
3212e48d4bbfSMilan Broz  *	key set <key>
3213e48d4bbfSMilan Broz  *	key wipe
3214e48d4bbfSMilan Broz  */
32151eb5fa84SMike Snitzer static int crypt_message(struct dm_target *ti, unsigned argc, char **argv,
32161eb5fa84SMike Snitzer 			 char *result, unsigned maxlen)
3217e48d4bbfSMilan Broz {
3218e48d4bbfSMilan Broz 	struct crypt_config *cc = ti->private;
3219c538f6ecSOndrej Kozina 	int key_size, ret = -EINVAL;
3220e48d4bbfSMilan Broz 
3221e48d4bbfSMilan Broz 	if (argc < 2)
3222e48d4bbfSMilan Broz 		goto error;
3223e48d4bbfSMilan Broz 
3224498f0103SMike Snitzer 	if (!strcasecmp(argv[0], "key")) {
3225e48d4bbfSMilan Broz 		if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
3226e48d4bbfSMilan Broz 			DMWARN("not suspended during key manipulation.");
3227e48d4bbfSMilan Broz 			return -EINVAL;
3228e48d4bbfSMilan Broz 		}
3229498f0103SMike Snitzer 		if (argc == 3 && !strcasecmp(argv[1], "set")) {
3230c538f6ecSOndrej Kozina 			/* The key size may not be changed. */
3231c538f6ecSOndrej Kozina 			key_size = get_key_size(&argv[2]);
3232c538f6ecSOndrej Kozina 			if (key_size < 0 || cc->key_size != key_size) {
3233c538f6ecSOndrej Kozina 				memset(argv[2], '0', strlen(argv[2]));
3234c538f6ecSOndrej Kozina 				return -EINVAL;
3235c538f6ecSOndrej Kozina 			}
3236c538f6ecSOndrej Kozina 
3237542da317SMilan Broz 			ret = crypt_set_key(cc, argv[2]);
3238542da317SMilan Broz 			if (ret)
3239542da317SMilan Broz 				return ret;
3240542da317SMilan Broz 			if (cc->iv_gen_ops && cc->iv_gen_ops->init)
3241542da317SMilan Broz 				ret = cc->iv_gen_ops->init(cc);
3242dc94902bSOndrej Kozina 			/* wipe the kernel key payload copy */
3243dc94902bSOndrej Kozina 			if (cc->key_string)
3244dc94902bSOndrej Kozina 				memset(cc->key, 0, cc->key_size * sizeof(u8));
3245542da317SMilan Broz 			return ret;
3246542da317SMilan Broz 		}
32474a52ffc7SMilan Broz 		if (argc == 2 && !strcasecmp(argv[1], "wipe"))
3248e48d4bbfSMilan Broz 			return crypt_wipe_key(cc);
3249e48d4bbfSMilan Broz 	}
3250e48d4bbfSMilan Broz 
3251e48d4bbfSMilan Broz error:
3252e48d4bbfSMilan Broz 	DMWARN("unrecognised message received.");
3253e48d4bbfSMilan Broz 	return -EINVAL;
3254e48d4bbfSMilan Broz }
3255e48d4bbfSMilan Broz 
3256af4874e0SMike Snitzer static int crypt_iterate_devices(struct dm_target *ti,
3257af4874e0SMike Snitzer 				 iterate_devices_callout_fn fn, void *data)
3258af4874e0SMike Snitzer {
3259af4874e0SMike Snitzer 	struct crypt_config *cc = ti->private;
3260af4874e0SMike Snitzer 
32615dea271bSMike Snitzer 	return fn(ti, cc->dev, cc->start, ti->len, data);
3262af4874e0SMike Snitzer }
3263af4874e0SMike Snitzer 
3264586b286bSMike Snitzer static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
3265586b286bSMike Snitzer {
32668f0009a2SMilan Broz 	struct crypt_config *cc = ti->private;
32678f0009a2SMilan Broz 
3268586b286bSMike Snitzer 	/*
3269586b286bSMike Snitzer 	 * Unfortunate constraint that is required to avoid the potential
3270586b286bSMike Snitzer 	 * for exceeding underlying device's max_segments limits -- due to
3271586b286bSMike Snitzer 	 * crypt_alloc_buffer() possibly allocating pages for the encryption
3272586b286bSMike Snitzer 	 * bio that are not as physically contiguous as the original bio.
3273586b286bSMike Snitzer 	 */
3274586b286bSMike Snitzer 	limits->max_segment_size = PAGE_SIZE;
32758f0009a2SMilan Broz 
3276bc9e9cf0SMikulas Patocka 	limits->logical_block_size =
3277bc9e9cf0SMikulas Patocka 		max_t(unsigned short, limits->logical_block_size, cc->sector_size);
3278bc9e9cf0SMikulas Patocka 	limits->physical_block_size =
3279bc9e9cf0SMikulas Patocka 		max_t(unsigned, limits->physical_block_size, cc->sector_size);
3280bc9e9cf0SMikulas Patocka 	limits->io_min = max_t(unsigned, limits->io_min, cc->sector_size);
3281586b286bSMike Snitzer }
3282586b286bSMike Snitzer 
32831da177e4SLinus Torvalds static struct target_type crypt_target = {
32841da177e4SLinus Torvalds 	.name   = "crypt",
3285bbb16584SMilan Broz 	.version = {1, 20, 0},
32861da177e4SLinus Torvalds 	.module = THIS_MODULE,
32871da177e4SLinus Torvalds 	.ctr    = crypt_ctr,
32881da177e4SLinus Torvalds 	.dtr    = crypt_dtr,
32891da177e4SLinus Torvalds 	.map    = crypt_map,
32901da177e4SLinus Torvalds 	.status = crypt_status,
3291e48d4bbfSMilan Broz 	.postsuspend = crypt_postsuspend,
3292e48d4bbfSMilan Broz 	.preresume = crypt_preresume,
3293e48d4bbfSMilan Broz 	.resume = crypt_resume,
3294e48d4bbfSMilan Broz 	.message = crypt_message,
3295af4874e0SMike Snitzer 	.iterate_devices = crypt_iterate_devices,
3296586b286bSMike Snitzer 	.io_hints = crypt_io_hints,
32971da177e4SLinus Torvalds };
32981da177e4SLinus Torvalds 
32991da177e4SLinus Torvalds static int __init dm_crypt_init(void)
33001da177e4SLinus Torvalds {
33011da177e4SLinus Torvalds 	int r;
33021da177e4SLinus Torvalds 
33031da177e4SLinus Torvalds 	r = dm_register_target(&crypt_target);
330494f5e024SMikulas Patocka 	if (r < 0)
330572d94861SAlasdair G Kergon 		DMERR("register failed %d", r);
33061da177e4SLinus Torvalds 
33071da177e4SLinus Torvalds 	return r;
33081da177e4SLinus Torvalds }
33091da177e4SLinus Torvalds 
33101da177e4SLinus Torvalds static void __exit dm_crypt_exit(void)
33111da177e4SLinus Torvalds {
331210d3bd09SMikulas Patocka 	dm_unregister_target(&crypt_target);
33131da177e4SLinus Torvalds }
33141da177e4SLinus Torvalds 
33151da177e4SLinus Torvalds module_init(dm_crypt_init);
33161da177e4SLinus Torvalds module_exit(dm_crypt_exit);
33171da177e4SLinus Torvalds 
3318bf14299fSJana Saout MODULE_AUTHOR("Jana Saout <jana@saout.de>");
33191da177e4SLinus Torvalds MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
33201da177e4SLinus Torvalds MODULE_LICENSE("GPL");
3321