xref: /openbmc/linux/drivers/md/dm-crypt.c (revision 1856b9f7)
11da177e4SLinus Torvalds /*
2bf14299fSJana Saout  * Copyright (C) 2003 Jana Saout <jana@saout.de>
31da177e4SLinus Torvalds  * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
4ef43aa38SMilan Broz  * Copyright (C) 2006-2017 Red Hat, Inc. All rights reserved.
5ef43aa38SMilan Broz  * Copyright (C) 2013-2017 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_essiv_private {
102c07c88f5SKees Cook 	struct crypto_shash *hash_tfm;
103b95bf2d3SMilan Broz 	u8 *salt;
10460473592SMilan Broz };
10560473592SMilan Broz 
10660473592SMilan Broz struct iv_benbi_private {
10760473592SMilan Broz 	int shift;
10860473592SMilan Broz };
10960473592SMilan Broz 
11034745785SMilan Broz #define LMK_SEED_SIZE 64 /* hash + 0 */
11134745785SMilan Broz struct iv_lmk_private {
11234745785SMilan Broz 	struct crypto_shash *hash_tfm;
11334745785SMilan Broz 	u8 *seed;
11434745785SMilan Broz };
11534745785SMilan Broz 
116ed04d981SMilan Broz #define TCW_WHITENING_SIZE 16
117ed04d981SMilan Broz struct iv_tcw_private {
118ed04d981SMilan Broz 	struct crypto_shash *crc32_tfm;
119ed04d981SMilan Broz 	u8 *iv_seed;
120ed04d981SMilan Broz 	u8 *whitening;
121ed04d981SMilan Broz };
122ed04d981SMilan 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 */
133ef43aa38SMilan Broz };
134ef43aa38SMilan Broz 
135c0297721SAndi Kleen /*
136610f2de3SMikulas Patocka  * The fields in here must be read only after initialization.
137c0297721SAndi Kleen  */
1381da177e4SLinus Torvalds struct crypt_config {
1391da177e4SLinus Torvalds 	struct dm_dev *dev;
1401da177e4SLinus Torvalds 	sector_t start;
1411da177e4SLinus Torvalds 
1425059353dSMikulas Patocka 	struct percpu_counter n_allocated_pages;
1435059353dSMikulas Patocka 
144cabf08e4SMilan Broz 	struct workqueue_struct *io_queue;
145cabf08e4SMilan Broz 	struct workqueue_struct *crypt_queue;
1463f1e9070SMilan Broz 
147c7329effSMikulas Patocka 	spinlock_t write_thread_lock;
14872d711c8SMike Snitzer 	struct task_struct *write_thread;
149b3c5fd30SMikulas Patocka 	struct rb_root write_tree;
150dc267621SMikulas Patocka 
1515ebaee6dSMilan Broz 	char *cipher;
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_essiv_private essiv;
15960473592SMilan Broz 		struct iv_benbi_private benbi;
16034745785SMilan Broz 		struct iv_lmk_private lmk;
161ed04d981SMilan Broz 		struct iv_tcw_private tcw;
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 
168fd2d231fSMikulas Patocka 	/* ESSIV: struct crypto_cipher *essiv_tfm */
169fd2d231fSMikulas Patocka 	void *iv_private;
170ef43aa38SMilan Broz 	union {
171bbdb23b5SHerbert Xu 		struct crypto_skcipher **tfms;
172ef43aa38SMilan Broz 		struct crypto_aead **tfms_aead;
173ef43aa38SMilan Broz 	} cipher_tfm;
174d1f96423SMilan Broz 	unsigned tfms_count;
175ef43aa38SMilan Broz 	unsigned long cipher_flags;
176c0297721SAndi Kleen 
177c0297721SAndi Kleen 	/*
178ddd42edfSMilan Broz 	 * Layout of each crypto request:
179ddd42edfSMilan Broz 	 *
180bbdb23b5SHerbert Xu 	 *   struct skcipher_request
181ddd42edfSMilan Broz 	 *      context
182ddd42edfSMilan Broz 	 *      padding
183ddd42edfSMilan Broz 	 *   struct dm_crypt_request
184ddd42edfSMilan Broz 	 *      padding
185ddd42edfSMilan Broz 	 *   IV
186ddd42edfSMilan Broz 	 *
187ddd42edfSMilan Broz 	 * The padding is added so that dm_crypt_request and the IV are
188ddd42edfSMilan Broz 	 * correctly aligned.
189ddd42edfSMilan Broz 	 */
190ddd42edfSMilan Broz 	unsigned int dmreq_start;
191ddd42edfSMilan Broz 
192298a9fa0SMikulas Patocka 	unsigned int per_bio_data_size;
193298a9fa0SMikulas Patocka 
194e48d4bbfSMilan Broz 	unsigned long flags;
1951da177e4SLinus Torvalds 	unsigned int key_size;
196da31a078SMilan Broz 	unsigned int key_parts;      /* independent parts in key buffer */
197da31a078SMilan Broz 	unsigned int key_extra_size; /* additional keys length */
198ef43aa38SMilan Broz 	unsigned int key_mac_size;   /* MAC key size for authenc(...) */
199ef43aa38SMilan Broz 
200ef43aa38SMilan Broz 	unsigned int integrity_tag_size;
201ef43aa38SMilan Broz 	unsigned int integrity_iv_size;
202ef43aa38SMilan Broz 	unsigned int on_disk_tag_size;
203ef43aa38SMilan Broz 
20472d711c8SMike Snitzer 	/*
20572d711c8SMike Snitzer 	 * pool for per bio private data, crypto requests,
20672d711c8SMike Snitzer 	 * encryption requeusts/buffer pages and integrity tags
20772d711c8SMike Snitzer 	 */
20872d711c8SMike Snitzer 	unsigned tag_pool_max_sectors;
20972d711c8SMike Snitzer 	mempool_t tag_pool;
21072d711c8SMike Snitzer 	mempool_t req_pool;
21172d711c8SMike Snitzer 	mempool_t page_pool;
21272d711c8SMike Snitzer 
21372d711c8SMike Snitzer 	struct bio_set bs;
21472d711c8SMike Snitzer 	struct mutex bio_alloc_lock;
21572d711c8SMike Snitzer 
216ef43aa38SMilan Broz 	u8 *authenc_key; /* space for keys in authenc() format (if used) */
2171da177e4SLinus Torvalds 	u8 key[0];
2181da177e4SLinus Torvalds };
2191da177e4SLinus Torvalds 
2200a83df6cSMikulas Patocka #define MIN_IOS		64
221ef43aa38SMilan Broz #define MAX_TAG_SIZE	480
222ef43aa38SMilan Broz #define POOL_ENTRY_SIZE	512
2231da177e4SLinus Torvalds 
2245059353dSMikulas Patocka static DEFINE_SPINLOCK(dm_crypt_clients_lock);
2255059353dSMikulas Patocka static unsigned dm_crypt_clients_n = 0;
2265059353dSMikulas Patocka static volatile unsigned long dm_crypt_pages_per_client;
2275059353dSMikulas Patocka #define DM_CRYPT_MEMORY_PERCENT			2
2285059353dSMikulas Patocka #define DM_CRYPT_MIN_PAGES_PER_CLIENT		(BIO_MAX_PAGES * 16)
2295059353dSMikulas Patocka 
230028867acSAlasdair G Kergon static void clone_init(struct dm_crypt_io *, struct bio *);
231395b167cSAlasdair G Kergon static void kcryptd_queue_crypt(struct dm_crypt_io *io);
232ef43aa38SMilan Broz static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
233ef43aa38SMilan Broz 					     struct scatterlist *sg);
234027581f3SOlaf Kirch 
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.
293ed04d981SMilan Broz  *
2941da177e4SLinus Torvalds  * plumb: unimplemented, see:
2951da177e4SLinus Torvalds  * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
2961da177e4SLinus Torvalds  */
2971da177e4SLinus Torvalds 
2982dc5327dSMilan Broz static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
2992dc5327dSMilan Broz 			      struct dm_crypt_request *dmreq)
3001da177e4SLinus Torvalds {
3011da177e4SLinus Torvalds 	memset(iv, 0, cc->iv_size);
302283a8328SAlasdair G Kergon 	*(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
3031da177e4SLinus Torvalds 
3041da177e4SLinus Torvalds 	return 0;
3051da177e4SLinus Torvalds }
3061da177e4SLinus Torvalds 
30761afef61SMilan Broz static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
3082dc5327dSMilan Broz 				struct dm_crypt_request *dmreq)
30961afef61SMilan Broz {
31061afef61SMilan Broz 	memset(iv, 0, cc->iv_size);
311283a8328SAlasdair G Kergon 	*(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
31261afef61SMilan Broz 
31361afef61SMilan Broz 	return 0;
31461afef61SMilan Broz }
31561afef61SMilan Broz 
3167e3fd855SMilan Broz static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
3177e3fd855SMilan Broz 				  struct dm_crypt_request *dmreq)
3187e3fd855SMilan Broz {
3197e3fd855SMilan Broz 	memset(iv, 0, cc->iv_size);
3207e3fd855SMilan Broz 	/* iv_size is at least of size u64; usually it is 16 bytes */
3217e3fd855SMilan Broz 	*(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
3227e3fd855SMilan Broz 
3237e3fd855SMilan Broz 	return 0;
3247e3fd855SMilan Broz }
3257e3fd855SMilan Broz 
326b95bf2d3SMilan Broz /* Initialise ESSIV - compute salt but no local memory allocations */
327b95bf2d3SMilan Broz static int crypt_iv_essiv_init(struct crypt_config *cc)
328b95bf2d3SMilan Broz {
329b95bf2d3SMilan Broz 	struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
330c07c88f5SKees Cook 	SHASH_DESC_ON_STACK(desc, essiv->hash_tfm);
331c0297721SAndi Kleen 	struct crypto_cipher *essiv_tfm;
332fd2d231fSMikulas Patocka 	int err;
333b95bf2d3SMilan Broz 
334c07c88f5SKees Cook 	desc->tfm = essiv->hash_tfm;
335432061b3SMikulas Patocka 	desc->flags = 0;
336b95bf2d3SMilan Broz 
337c07c88f5SKees Cook 	err = crypto_shash_digest(desc, cc->key, cc->key_size, essiv->salt);
338c07c88f5SKees Cook 	shash_desc_zero(desc);
339b95bf2d3SMilan Broz 	if (err)
340b95bf2d3SMilan Broz 		return err;
341b95bf2d3SMilan Broz 
342fd2d231fSMikulas Patocka 	essiv_tfm = cc->iv_private;
343c0297721SAndi Kleen 
344c0297721SAndi Kleen 	err = crypto_cipher_setkey(essiv_tfm, essiv->salt,
345c07c88f5SKees Cook 			    crypto_shash_digestsize(essiv->hash_tfm));
346c0297721SAndi Kleen 	if (err)
347c0297721SAndi Kleen 		return err;
348c0297721SAndi Kleen 
349c0297721SAndi Kleen 	return 0;
350b95bf2d3SMilan Broz }
351b95bf2d3SMilan Broz 
352542da317SMilan Broz /* Wipe salt and reset key derived from volume key */
353542da317SMilan Broz static int crypt_iv_essiv_wipe(struct crypt_config *cc)
354542da317SMilan Broz {
355542da317SMilan Broz 	struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
356c07c88f5SKees Cook 	unsigned salt_size = crypto_shash_digestsize(essiv->hash_tfm);
357c0297721SAndi Kleen 	struct crypto_cipher *essiv_tfm;
358fd2d231fSMikulas Patocka 	int r, err = 0;
359542da317SMilan Broz 
360542da317SMilan Broz 	memset(essiv->salt, 0, salt_size);
361542da317SMilan Broz 
362fd2d231fSMikulas Patocka 	essiv_tfm = cc->iv_private;
363c0297721SAndi Kleen 	r = crypto_cipher_setkey(essiv_tfm, essiv->salt, salt_size);
364c0297721SAndi Kleen 	if (r)
365c0297721SAndi Kleen 		err = r;
366c0297721SAndi Kleen 
367c0297721SAndi Kleen 	return err;
368c0297721SAndi Kleen }
369c0297721SAndi Kleen 
37086f917adSEric Biggers /* Allocate the cipher for ESSIV */
37186f917adSEric Biggers static struct crypto_cipher *alloc_essiv_cipher(struct crypt_config *cc,
372c0297721SAndi Kleen 						struct dm_target *ti,
37386f917adSEric Biggers 						const u8 *salt,
37486f917adSEric Biggers 						unsigned int saltsize)
375c0297721SAndi Kleen {
376c0297721SAndi Kleen 	struct crypto_cipher *essiv_tfm;
377c0297721SAndi Kleen 	int err;
378c0297721SAndi Kleen 
379c0297721SAndi Kleen 	/* Setup the essiv_tfm with the given salt */
3801ad0f160SEric Biggers 	essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, 0);
381c0297721SAndi Kleen 	if (IS_ERR(essiv_tfm)) {
382c0297721SAndi Kleen 		ti->error = "Error allocating crypto tfm for ESSIV";
383c0297721SAndi Kleen 		return essiv_tfm;
384c0297721SAndi Kleen 	}
385c0297721SAndi Kleen 
386ef43aa38SMilan Broz 	if (crypto_cipher_blocksize(essiv_tfm) != cc->iv_size) {
387c0297721SAndi Kleen 		ti->error = "Block size of ESSIV cipher does "
388c0297721SAndi Kleen 			    "not match IV size of block cipher";
389c0297721SAndi Kleen 		crypto_free_cipher(essiv_tfm);
390c0297721SAndi Kleen 		return ERR_PTR(-EINVAL);
391c0297721SAndi Kleen 	}
392c0297721SAndi Kleen 
393c0297721SAndi Kleen 	err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
394c0297721SAndi Kleen 	if (err) {
395c0297721SAndi Kleen 		ti->error = "Failed to set key for ESSIV cipher";
396c0297721SAndi Kleen 		crypto_free_cipher(essiv_tfm);
397c0297721SAndi Kleen 		return ERR_PTR(err);
398c0297721SAndi Kleen 	}
399c0297721SAndi Kleen 
400c0297721SAndi Kleen 	return essiv_tfm;
401542da317SMilan Broz }
402542da317SMilan Broz 
40360473592SMilan Broz static void crypt_iv_essiv_dtr(struct crypt_config *cc)
40460473592SMilan Broz {
405c0297721SAndi Kleen 	struct crypto_cipher *essiv_tfm;
40660473592SMilan Broz 	struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
40760473592SMilan Broz 
408c07c88f5SKees Cook 	crypto_free_shash(essiv->hash_tfm);
409b95bf2d3SMilan Broz 	essiv->hash_tfm = NULL;
410b95bf2d3SMilan Broz 
411b95bf2d3SMilan Broz 	kzfree(essiv->salt);
412b95bf2d3SMilan Broz 	essiv->salt = NULL;
413c0297721SAndi Kleen 
414fd2d231fSMikulas Patocka 	essiv_tfm = cc->iv_private;
415c0297721SAndi Kleen 
416c0297721SAndi Kleen 	if (essiv_tfm)
417c0297721SAndi Kleen 		crypto_free_cipher(essiv_tfm);
418c0297721SAndi Kleen 
419fd2d231fSMikulas Patocka 	cc->iv_private = NULL;
42060473592SMilan Broz }
42160473592SMilan Broz 
4221da177e4SLinus Torvalds static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
4231da177e4SLinus Torvalds 			      const char *opts)
4241da177e4SLinus Torvalds {
4255861f1beSMilan Broz 	struct crypto_cipher *essiv_tfm = NULL;
426c07c88f5SKees Cook 	struct crypto_shash *hash_tfm = NULL;
4275861f1beSMilan Broz 	u8 *salt = NULL;
428fd2d231fSMikulas Patocka 	int err;
4291da177e4SLinus Torvalds 
4305861f1beSMilan Broz 	if (!opts) {
43172d94861SAlasdair G Kergon 		ti->error = "Digest algorithm missing for ESSIV mode";
4321da177e4SLinus Torvalds 		return -EINVAL;
4331da177e4SLinus Torvalds 	}
4341da177e4SLinus Torvalds 
435b95bf2d3SMilan Broz 	/* Allocate hash algorithm */
436c07c88f5SKees Cook 	hash_tfm = crypto_alloc_shash(opts, 0, 0);
43735058687SHerbert Xu 	if (IS_ERR(hash_tfm)) {
43872d94861SAlasdair G Kergon 		ti->error = "Error initializing ESSIV hash";
4395861f1beSMilan Broz 		err = PTR_ERR(hash_tfm);
4405861f1beSMilan Broz 		goto bad;
4411da177e4SLinus Torvalds 	}
4421da177e4SLinus Torvalds 
443c07c88f5SKees Cook 	salt = kzalloc(crypto_shash_digestsize(hash_tfm), GFP_KERNEL);
4445861f1beSMilan Broz 	if (!salt) {
44572d94861SAlasdair G Kergon 		ti->error = "Error kmallocing salt storage in ESSIV";
4465861f1beSMilan Broz 		err = -ENOMEM;
4475861f1beSMilan Broz 		goto bad;
4481da177e4SLinus Torvalds 	}
4491da177e4SLinus Torvalds 
450b95bf2d3SMilan Broz 	cc->iv_gen_private.essiv.salt = salt;
451b95bf2d3SMilan Broz 	cc->iv_gen_private.essiv.hash_tfm = hash_tfm;
452b95bf2d3SMilan Broz 
45386f917adSEric Biggers 	essiv_tfm = alloc_essiv_cipher(cc, ti, salt,
454c07c88f5SKees Cook 				       crypto_shash_digestsize(hash_tfm));
455c0297721SAndi Kleen 	if (IS_ERR(essiv_tfm)) {
456c0297721SAndi Kleen 		crypt_iv_essiv_dtr(cc);
457c0297721SAndi Kleen 		return PTR_ERR(essiv_tfm);
458c0297721SAndi Kleen 	}
459fd2d231fSMikulas Patocka 	cc->iv_private = essiv_tfm;
460c0297721SAndi Kleen 
4611da177e4SLinus Torvalds 	return 0;
4625861f1beSMilan Broz 
4635861f1beSMilan Broz bad:
4645861f1beSMilan Broz 	if (hash_tfm && !IS_ERR(hash_tfm))
465c07c88f5SKees Cook 		crypto_free_shash(hash_tfm);
466b95bf2d3SMilan Broz 	kfree(salt);
4675861f1beSMilan Broz 	return err;
4681da177e4SLinus Torvalds }
4691da177e4SLinus Torvalds 
4702dc5327dSMilan Broz static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
4712dc5327dSMilan Broz 			      struct dm_crypt_request *dmreq)
4721da177e4SLinus Torvalds {
473fd2d231fSMikulas Patocka 	struct crypto_cipher *essiv_tfm = cc->iv_private;
474c0297721SAndi Kleen 
4751da177e4SLinus Torvalds 	memset(iv, 0, cc->iv_size);
476283a8328SAlasdair G Kergon 	*(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
477c0297721SAndi Kleen 	crypto_cipher_encrypt_one(essiv_tfm, iv, iv);
478c0297721SAndi Kleen 
4791da177e4SLinus Torvalds 	return 0;
4801da177e4SLinus Torvalds }
4811da177e4SLinus Torvalds 
48248527fa7SRik Snel static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
48348527fa7SRik Snel 			      const char *opts)
48448527fa7SRik Snel {
485bbdb23b5SHerbert Xu 	unsigned bs = crypto_skcipher_blocksize(any_tfm(cc));
486f0d1b0b3SDavid Howells 	int log = ilog2(bs);
48748527fa7SRik Snel 
48848527fa7SRik Snel 	/* we need to calculate how far we must shift the sector count
48948527fa7SRik Snel 	 * to get the cipher block count, we use this shift in _gen */
49048527fa7SRik Snel 
49148527fa7SRik Snel 	if (1 << log != bs) {
49248527fa7SRik Snel 		ti->error = "cypher blocksize is not a power of 2";
49348527fa7SRik Snel 		return -EINVAL;
49448527fa7SRik Snel 	}
49548527fa7SRik Snel 
49648527fa7SRik Snel 	if (log > 9) {
49748527fa7SRik Snel 		ti->error = "cypher blocksize is > 512";
49848527fa7SRik Snel 		return -EINVAL;
49948527fa7SRik Snel 	}
50048527fa7SRik Snel 
50160473592SMilan Broz 	cc->iv_gen_private.benbi.shift = 9 - log;
50248527fa7SRik Snel 
50348527fa7SRik Snel 	return 0;
50448527fa7SRik Snel }
50548527fa7SRik Snel 
50648527fa7SRik Snel static void crypt_iv_benbi_dtr(struct crypt_config *cc)
50748527fa7SRik Snel {
50848527fa7SRik Snel }
50948527fa7SRik Snel 
5102dc5327dSMilan Broz static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
5112dc5327dSMilan Broz 			      struct dm_crypt_request *dmreq)
51248527fa7SRik Snel {
51379066ad3SHerbert Xu 	__be64 val;
51479066ad3SHerbert Xu 
51548527fa7SRik Snel 	memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
51679066ad3SHerbert Xu 
5172dc5327dSMilan Broz 	val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
51879066ad3SHerbert Xu 	put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
51948527fa7SRik Snel 
5201da177e4SLinus Torvalds 	return 0;
5211da177e4SLinus Torvalds }
5221da177e4SLinus Torvalds 
5232dc5327dSMilan Broz static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
5242dc5327dSMilan Broz 			     struct dm_crypt_request *dmreq)
52546b47730SLudwig Nussel {
52646b47730SLudwig Nussel 	memset(iv, 0, cc->iv_size);
52746b47730SLudwig Nussel 
52846b47730SLudwig Nussel 	return 0;
52946b47730SLudwig Nussel }
53046b47730SLudwig Nussel 
53134745785SMilan Broz static void crypt_iv_lmk_dtr(struct crypt_config *cc)
53234745785SMilan Broz {
53334745785SMilan Broz 	struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
53434745785SMilan Broz 
53534745785SMilan Broz 	if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
53634745785SMilan Broz 		crypto_free_shash(lmk->hash_tfm);
53734745785SMilan Broz 	lmk->hash_tfm = NULL;
53834745785SMilan Broz 
53934745785SMilan Broz 	kzfree(lmk->seed);
54034745785SMilan Broz 	lmk->seed = NULL;
54134745785SMilan Broz }
54234745785SMilan Broz 
54334745785SMilan Broz static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
54434745785SMilan Broz 			    const char *opts)
54534745785SMilan Broz {
54634745785SMilan Broz 	struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
54734745785SMilan Broz 
5488f0009a2SMilan Broz 	if (cc->sector_size != (1 << SECTOR_SHIFT)) {
5498f0009a2SMilan Broz 		ti->error = "Unsupported sector size for LMK";
5508f0009a2SMilan Broz 		return -EINVAL;
5518f0009a2SMilan Broz 	}
5528f0009a2SMilan Broz 
55334745785SMilan Broz 	lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
55434745785SMilan Broz 	if (IS_ERR(lmk->hash_tfm)) {
55534745785SMilan Broz 		ti->error = "Error initializing LMK hash";
55634745785SMilan Broz 		return PTR_ERR(lmk->hash_tfm);
55734745785SMilan Broz 	}
55834745785SMilan Broz 
55934745785SMilan Broz 	/* No seed in LMK version 2 */
56034745785SMilan Broz 	if (cc->key_parts == cc->tfms_count) {
56134745785SMilan Broz 		lmk->seed = NULL;
56234745785SMilan Broz 		return 0;
56334745785SMilan Broz 	}
56434745785SMilan Broz 
56534745785SMilan Broz 	lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
56634745785SMilan Broz 	if (!lmk->seed) {
56734745785SMilan Broz 		crypt_iv_lmk_dtr(cc);
56834745785SMilan Broz 		ti->error = "Error kmallocing seed storage in LMK";
56934745785SMilan Broz 		return -ENOMEM;
57034745785SMilan Broz 	}
57134745785SMilan Broz 
57234745785SMilan Broz 	return 0;
57334745785SMilan Broz }
57434745785SMilan Broz 
57534745785SMilan Broz static int crypt_iv_lmk_init(struct crypt_config *cc)
57634745785SMilan Broz {
57734745785SMilan Broz 	struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
57834745785SMilan Broz 	int subkey_size = cc->key_size / cc->key_parts;
57934745785SMilan Broz 
58034745785SMilan Broz 	/* LMK seed is on the position of LMK_KEYS + 1 key */
58134745785SMilan Broz 	if (lmk->seed)
58234745785SMilan Broz 		memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
58334745785SMilan Broz 		       crypto_shash_digestsize(lmk->hash_tfm));
58434745785SMilan Broz 
58534745785SMilan Broz 	return 0;
58634745785SMilan Broz }
58734745785SMilan Broz 
58834745785SMilan Broz static int crypt_iv_lmk_wipe(struct crypt_config *cc)
58934745785SMilan Broz {
59034745785SMilan Broz 	struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
59134745785SMilan Broz 
59234745785SMilan Broz 	if (lmk->seed)
59334745785SMilan Broz 		memset(lmk->seed, 0, LMK_SEED_SIZE);
59434745785SMilan Broz 
59534745785SMilan Broz 	return 0;
59634745785SMilan Broz }
59734745785SMilan Broz 
59834745785SMilan Broz static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
59934745785SMilan Broz 			    struct dm_crypt_request *dmreq,
60034745785SMilan Broz 			    u8 *data)
60134745785SMilan Broz {
60234745785SMilan Broz 	struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
603b6106265SJan-Simon Möller 	SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
60434745785SMilan Broz 	struct md5_state md5state;
605da31a078SMilan Broz 	__le32 buf[4];
60634745785SMilan Broz 	int i, r;
60734745785SMilan Broz 
608b6106265SJan-Simon Möller 	desc->tfm = lmk->hash_tfm;
609432061b3SMikulas Patocka 	desc->flags = 0;
61034745785SMilan Broz 
611b6106265SJan-Simon Möller 	r = crypto_shash_init(desc);
61234745785SMilan Broz 	if (r)
61334745785SMilan Broz 		return r;
61434745785SMilan Broz 
61534745785SMilan Broz 	if (lmk->seed) {
616b6106265SJan-Simon Möller 		r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
61734745785SMilan Broz 		if (r)
61834745785SMilan Broz 			return r;
61934745785SMilan Broz 	}
62034745785SMilan Broz 
62134745785SMilan Broz 	/* Sector is always 512B, block size 16, add data of blocks 1-31 */
622b6106265SJan-Simon Möller 	r = crypto_shash_update(desc, data + 16, 16 * 31);
62334745785SMilan Broz 	if (r)
62434745785SMilan Broz 		return r;
62534745785SMilan Broz 
62634745785SMilan Broz 	/* Sector is cropped to 56 bits here */
62734745785SMilan Broz 	buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
62834745785SMilan Broz 	buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
62934745785SMilan Broz 	buf[2] = cpu_to_le32(4024);
63034745785SMilan Broz 	buf[3] = 0;
631b6106265SJan-Simon Möller 	r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
63234745785SMilan Broz 	if (r)
63334745785SMilan Broz 		return r;
63434745785SMilan Broz 
63534745785SMilan Broz 	/* No MD5 padding here */
636b6106265SJan-Simon Möller 	r = crypto_shash_export(desc, &md5state);
63734745785SMilan Broz 	if (r)
63834745785SMilan Broz 		return r;
63934745785SMilan Broz 
64034745785SMilan Broz 	for (i = 0; i < MD5_HASH_WORDS; i++)
64134745785SMilan Broz 		__cpu_to_le32s(&md5state.hash[i]);
64234745785SMilan Broz 	memcpy(iv, &md5state.hash, cc->iv_size);
64334745785SMilan Broz 
64434745785SMilan Broz 	return 0;
64534745785SMilan Broz }
64634745785SMilan Broz 
64734745785SMilan Broz static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
64834745785SMilan Broz 			    struct dm_crypt_request *dmreq)
64934745785SMilan Broz {
650ef43aa38SMilan Broz 	struct scatterlist *sg;
65134745785SMilan Broz 	u8 *src;
65234745785SMilan Broz 	int r = 0;
65334745785SMilan Broz 
65434745785SMilan Broz 	if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
655ef43aa38SMilan Broz 		sg = crypt_get_sg_data(cc, dmreq->sg_in);
656ef43aa38SMilan Broz 		src = kmap_atomic(sg_page(sg));
657ef43aa38SMilan Broz 		r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
658c2e022cbSCong Wang 		kunmap_atomic(src);
65934745785SMilan Broz 	} else
66034745785SMilan Broz 		memset(iv, 0, cc->iv_size);
66134745785SMilan Broz 
66234745785SMilan Broz 	return r;
66334745785SMilan Broz }
66434745785SMilan Broz 
66534745785SMilan Broz static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
66634745785SMilan Broz 			     struct dm_crypt_request *dmreq)
66734745785SMilan Broz {
668ef43aa38SMilan Broz 	struct scatterlist *sg;
66934745785SMilan Broz 	u8 *dst;
67034745785SMilan Broz 	int r;
67134745785SMilan Broz 
67234745785SMilan Broz 	if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
67334745785SMilan Broz 		return 0;
67434745785SMilan Broz 
675ef43aa38SMilan Broz 	sg = crypt_get_sg_data(cc, dmreq->sg_out);
676ef43aa38SMilan Broz 	dst = kmap_atomic(sg_page(sg));
677ef43aa38SMilan Broz 	r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
67834745785SMilan Broz 
67934745785SMilan Broz 	/* Tweak the first block of plaintext sector */
68034745785SMilan Broz 	if (!r)
681ef43aa38SMilan Broz 		crypto_xor(dst + sg->offset, iv, cc->iv_size);
68234745785SMilan Broz 
683c2e022cbSCong Wang 	kunmap_atomic(dst);
68434745785SMilan Broz 	return r;
68534745785SMilan Broz }
68634745785SMilan Broz 
687ed04d981SMilan Broz static void crypt_iv_tcw_dtr(struct crypt_config *cc)
688ed04d981SMilan Broz {
689ed04d981SMilan Broz 	struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
690ed04d981SMilan Broz 
691ed04d981SMilan Broz 	kzfree(tcw->iv_seed);
692ed04d981SMilan Broz 	tcw->iv_seed = NULL;
693ed04d981SMilan Broz 	kzfree(tcw->whitening);
694ed04d981SMilan Broz 	tcw->whitening = NULL;
695ed04d981SMilan Broz 
696ed04d981SMilan Broz 	if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
697ed04d981SMilan Broz 		crypto_free_shash(tcw->crc32_tfm);
698ed04d981SMilan Broz 	tcw->crc32_tfm = NULL;
699ed04d981SMilan Broz }
700ed04d981SMilan Broz 
701ed04d981SMilan Broz static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
702ed04d981SMilan Broz 			    const char *opts)
703ed04d981SMilan Broz {
704ed04d981SMilan Broz 	struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
705ed04d981SMilan Broz 
7068f0009a2SMilan Broz 	if (cc->sector_size != (1 << SECTOR_SHIFT)) {
7078f0009a2SMilan Broz 		ti->error = "Unsupported sector size for TCW";
7088f0009a2SMilan Broz 		return -EINVAL;
7098f0009a2SMilan Broz 	}
7108f0009a2SMilan Broz 
711ed04d981SMilan Broz 	if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
712ed04d981SMilan Broz 		ti->error = "Wrong key size for TCW";
713ed04d981SMilan Broz 		return -EINVAL;
714ed04d981SMilan Broz 	}
715ed04d981SMilan Broz 
716ed04d981SMilan Broz 	tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
717ed04d981SMilan Broz 	if (IS_ERR(tcw->crc32_tfm)) {
718ed04d981SMilan Broz 		ti->error = "Error initializing CRC32 in TCW";
719ed04d981SMilan Broz 		return PTR_ERR(tcw->crc32_tfm);
720ed04d981SMilan Broz 	}
721ed04d981SMilan Broz 
722ed04d981SMilan Broz 	tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
723ed04d981SMilan Broz 	tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
724ed04d981SMilan Broz 	if (!tcw->iv_seed || !tcw->whitening) {
725ed04d981SMilan Broz 		crypt_iv_tcw_dtr(cc);
726ed04d981SMilan Broz 		ti->error = "Error allocating seed storage in TCW";
727ed04d981SMilan Broz 		return -ENOMEM;
728ed04d981SMilan Broz 	}
729ed04d981SMilan Broz 
730ed04d981SMilan Broz 	return 0;
731ed04d981SMilan Broz }
732ed04d981SMilan Broz 
733ed04d981SMilan Broz static int crypt_iv_tcw_init(struct crypt_config *cc)
734ed04d981SMilan Broz {
735ed04d981SMilan Broz 	struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
736ed04d981SMilan Broz 	int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
737ed04d981SMilan Broz 
738ed04d981SMilan Broz 	memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
739ed04d981SMilan Broz 	memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
740ed04d981SMilan Broz 	       TCW_WHITENING_SIZE);
741ed04d981SMilan Broz 
742ed04d981SMilan Broz 	return 0;
743ed04d981SMilan Broz }
744ed04d981SMilan Broz 
745ed04d981SMilan Broz static int crypt_iv_tcw_wipe(struct crypt_config *cc)
746ed04d981SMilan Broz {
747ed04d981SMilan Broz 	struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
748ed04d981SMilan Broz 
749ed04d981SMilan Broz 	memset(tcw->iv_seed, 0, cc->iv_size);
750ed04d981SMilan Broz 	memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
751ed04d981SMilan Broz 
752ed04d981SMilan Broz 	return 0;
753ed04d981SMilan Broz }
754ed04d981SMilan Broz 
755ed04d981SMilan Broz static int crypt_iv_tcw_whitening(struct crypt_config *cc,
756ed04d981SMilan Broz 				  struct dm_crypt_request *dmreq,
757ed04d981SMilan Broz 				  u8 *data)
758ed04d981SMilan Broz {
759ed04d981SMilan Broz 	struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
760350b5393SBart Van Assche 	__le64 sector = cpu_to_le64(dmreq->iv_sector);
761ed04d981SMilan Broz 	u8 buf[TCW_WHITENING_SIZE];
762b6106265SJan-Simon Möller 	SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
763ed04d981SMilan Broz 	int i, r;
764ed04d981SMilan Broz 
765ed04d981SMilan Broz 	/* xor whitening with sector number */
76645fe93dfSArd Biesheuvel 	crypto_xor_cpy(buf, tcw->whitening, (u8 *)&sector, 8);
76745fe93dfSArd Biesheuvel 	crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)&sector, 8);
768ed04d981SMilan Broz 
769ed04d981SMilan Broz 	/* calculate crc32 for every 32bit part and xor it */
770b6106265SJan-Simon Möller 	desc->tfm = tcw->crc32_tfm;
771432061b3SMikulas Patocka 	desc->flags = 0;
772ed04d981SMilan Broz 	for (i = 0; i < 4; i++) {
773b6106265SJan-Simon Möller 		r = crypto_shash_init(desc);
774ed04d981SMilan Broz 		if (r)
775ed04d981SMilan Broz 			goto out;
776b6106265SJan-Simon Möller 		r = crypto_shash_update(desc, &buf[i * 4], 4);
777ed04d981SMilan Broz 		if (r)
778ed04d981SMilan Broz 			goto out;
779b6106265SJan-Simon Möller 		r = crypto_shash_final(desc, &buf[i * 4]);
780ed04d981SMilan Broz 		if (r)
781ed04d981SMilan Broz 			goto out;
782ed04d981SMilan Broz 	}
783ed04d981SMilan Broz 	crypto_xor(&buf[0], &buf[12], 4);
784ed04d981SMilan Broz 	crypto_xor(&buf[4], &buf[8], 4);
785ed04d981SMilan Broz 
786ed04d981SMilan Broz 	/* apply whitening (8 bytes) to whole sector */
787ed04d981SMilan Broz 	for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
788ed04d981SMilan Broz 		crypto_xor(data + i * 8, buf, 8);
789ed04d981SMilan Broz out:
7901a71d6ffSMilan Broz 	memzero_explicit(buf, sizeof(buf));
791ed04d981SMilan Broz 	return r;
792ed04d981SMilan Broz }
793ed04d981SMilan Broz 
794ed04d981SMilan Broz static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
795ed04d981SMilan Broz 			    struct dm_crypt_request *dmreq)
796ed04d981SMilan Broz {
797ef43aa38SMilan Broz 	struct scatterlist *sg;
798ed04d981SMilan Broz 	struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
799350b5393SBart Van Assche 	__le64 sector = cpu_to_le64(dmreq->iv_sector);
800ed04d981SMilan Broz 	u8 *src;
801ed04d981SMilan Broz 	int r = 0;
802ed04d981SMilan Broz 
803ed04d981SMilan Broz 	/* Remove whitening from ciphertext */
804ed04d981SMilan Broz 	if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
805ef43aa38SMilan Broz 		sg = crypt_get_sg_data(cc, dmreq->sg_in);
806ef43aa38SMilan Broz 		src = kmap_atomic(sg_page(sg));
807ef43aa38SMilan Broz 		r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
808ed04d981SMilan Broz 		kunmap_atomic(src);
809ed04d981SMilan Broz 	}
810ed04d981SMilan Broz 
811ed04d981SMilan Broz 	/* Calculate IV */
81245fe93dfSArd Biesheuvel 	crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)&sector, 8);
813ed04d981SMilan Broz 	if (cc->iv_size > 8)
81445fe93dfSArd Biesheuvel 		crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)&sector,
81545fe93dfSArd Biesheuvel 			       cc->iv_size - 8);
816ed04d981SMilan Broz 
817ed04d981SMilan Broz 	return r;
818ed04d981SMilan Broz }
819ed04d981SMilan Broz 
820ed04d981SMilan Broz static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
821ed04d981SMilan Broz 			     struct dm_crypt_request *dmreq)
822ed04d981SMilan Broz {
823ef43aa38SMilan Broz 	struct scatterlist *sg;
824ed04d981SMilan Broz 	u8 *dst;
825ed04d981SMilan Broz 	int r;
826ed04d981SMilan Broz 
827ed04d981SMilan Broz 	if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
828ed04d981SMilan Broz 		return 0;
829ed04d981SMilan Broz 
830ed04d981SMilan Broz 	/* Apply whitening on ciphertext */
831ef43aa38SMilan Broz 	sg = crypt_get_sg_data(cc, dmreq->sg_out);
832ef43aa38SMilan Broz 	dst = kmap_atomic(sg_page(sg));
833ef43aa38SMilan Broz 	r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
834ed04d981SMilan Broz 	kunmap_atomic(dst);
835ed04d981SMilan Broz 
836ed04d981SMilan Broz 	return r;
837ed04d981SMilan Broz }
838ed04d981SMilan Broz 
839ef43aa38SMilan Broz static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
840ef43aa38SMilan Broz 				struct dm_crypt_request *dmreq)
841ef43aa38SMilan Broz {
842ef43aa38SMilan Broz 	/* Used only for writes, there must be an additional space to store IV */
843ef43aa38SMilan Broz 	get_random_bytes(iv, cc->iv_size);
844ef43aa38SMilan Broz 	return 0;
845ef43aa38SMilan Broz }
846ef43aa38SMilan Broz 
8471b1b58f5SJulia Lawall static const struct crypt_iv_operations crypt_iv_plain_ops = {
8481da177e4SLinus Torvalds 	.generator = crypt_iv_plain_gen
8491da177e4SLinus Torvalds };
8501da177e4SLinus Torvalds 
8511b1b58f5SJulia Lawall static const struct crypt_iv_operations crypt_iv_plain64_ops = {
85261afef61SMilan Broz 	.generator = crypt_iv_plain64_gen
85361afef61SMilan Broz };
85461afef61SMilan Broz 
8557e3fd855SMilan Broz static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
8567e3fd855SMilan Broz 	.generator = crypt_iv_plain64be_gen
8577e3fd855SMilan Broz };
8587e3fd855SMilan Broz 
8591b1b58f5SJulia Lawall static const struct crypt_iv_operations crypt_iv_essiv_ops = {
8601da177e4SLinus Torvalds 	.ctr       = crypt_iv_essiv_ctr,
8611da177e4SLinus Torvalds 	.dtr       = crypt_iv_essiv_dtr,
862b95bf2d3SMilan Broz 	.init      = crypt_iv_essiv_init,
863542da317SMilan Broz 	.wipe      = crypt_iv_essiv_wipe,
8641da177e4SLinus Torvalds 	.generator = crypt_iv_essiv_gen
8651da177e4SLinus Torvalds };
8661da177e4SLinus Torvalds 
8671b1b58f5SJulia Lawall static const struct crypt_iv_operations crypt_iv_benbi_ops = {
86848527fa7SRik Snel 	.ctr	   = crypt_iv_benbi_ctr,
86948527fa7SRik Snel 	.dtr	   = crypt_iv_benbi_dtr,
87048527fa7SRik Snel 	.generator = crypt_iv_benbi_gen
87148527fa7SRik Snel };
8721da177e4SLinus Torvalds 
8731b1b58f5SJulia Lawall static const struct crypt_iv_operations crypt_iv_null_ops = {
87446b47730SLudwig Nussel 	.generator = crypt_iv_null_gen
87546b47730SLudwig Nussel };
87646b47730SLudwig Nussel 
8771b1b58f5SJulia Lawall static const struct crypt_iv_operations crypt_iv_lmk_ops = {
87834745785SMilan Broz 	.ctr	   = crypt_iv_lmk_ctr,
87934745785SMilan Broz 	.dtr	   = crypt_iv_lmk_dtr,
88034745785SMilan Broz 	.init	   = crypt_iv_lmk_init,
88134745785SMilan Broz 	.wipe	   = crypt_iv_lmk_wipe,
88234745785SMilan Broz 	.generator = crypt_iv_lmk_gen,
88334745785SMilan Broz 	.post	   = crypt_iv_lmk_post
88434745785SMilan Broz };
88534745785SMilan Broz 
8861b1b58f5SJulia Lawall static const struct crypt_iv_operations crypt_iv_tcw_ops = {
887ed04d981SMilan Broz 	.ctr	   = crypt_iv_tcw_ctr,
888ed04d981SMilan Broz 	.dtr	   = crypt_iv_tcw_dtr,
889ed04d981SMilan Broz 	.init	   = crypt_iv_tcw_init,
890ed04d981SMilan Broz 	.wipe	   = crypt_iv_tcw_wipe,
891ed04d981SMilan Broz 	.generator = crypt_iv_tcw_gen,
892ed04d981SMilan Broz 	.post	   = crypt_iv_tcw_post
893ed04d981SMilan Broz };
894ed04d981SMilan Broz 
895ef43aa38SMilan Broz static struct crypt_iv_operations crypt_iv_random_ops = {
896ef43aa38SMilan Broz 	.generator = crypt_iv_random_gen
897ef43aa38SMilan Broz };
898ef43aa38SMilan Broz 
899ef43aa38SMilan Broz /*
900ef43aa38SMilan Broz  * Integrity extensions
901ef43aa38SMilan Broz  */
902ef43aa38SMilan Broz static bool crypt_integrity_aead(struct crypt_config *cc)
903ef43aa38SMilan Broz {
904ef43aa38SMilan Broz 	return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
905ef43aa38SMilan Broz }
906ef43aa38SMilan Broz 
907ef43aa38SMilan Broz static bool crypt_integrity_hmac(struct crypt_config *cc)
908ef43aa38SMilan Broz {
90933d2f09fSMilan Broz 	return crypt_integrity_aead(cc) && cc->key_mac_size;
910ef43aa38SMilan Broz }
911ef43aa38SMilan Broz 
912ef43aa38SMilan Broz /* Get sg containing data */
913ef43aa38SMilan Broz static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
914ef43aa38SMilan Broz 					     struct scatterlist *sg)
915ef43aa38SMilan Broz {
91633d2f09fSMilan Broz 	if (unlikely(crypt_integrity_aead(cc)))
917ef43aa38SMilan Broz 		return &sg[2];
918ef43aa38SMilan Broz 
919ef43aa38SMilan Broz 	return sg;
920ef43aa38SMilan Broz }
921ef43aa38SMilan Broz 
922ef43aa38SMilan Broz static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
923ef43aa38SMilan Broz {
924ef43aa38SMilan Broz 	struct bio_integrity_payload *bip;
925ef43aa38SMilan Broz 	unsigned int tag_len;
926ef43aa38SMilan Broz 	int ret;
927ef43aa38SMilan Broz 
928ef43aa38SMilan Broz 	if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
929ef43aa38SMilan Broz 		return 0;
930ef43aa38SMilan Broz 
931ef43aa38SMilan Broz 	bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
932ef43aa38SMilan Broz 	if (IS_ERR(bip))
933ef43aa38SMilan Broz 		return PTR_ERR(bip);
934ef43aa38SMilan Broz 
935ef43aa38SMilan Broz 	tag_len = io->cc->on_disk_tag_size * bio_sectors(bio);
936ef43aa38SMilan Broz 
937ef43aa38SMilan Broz 	bip->bip_iter.bi_size = tag_len;
938ef43aa38SMilan Broz 	bip->bip_iter.bi_sector = io->cc->start + io->sector;
939ef43aa38SMilan Broz 
940ef43aa38SMilan Broz 	ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
941ef43aa38SMilan Broz 				     tag_len, offset_in_page(io->integrity_metadata));
942ef43aa38SMilan Broz 	if (unlikely(ret != tag_len))
943ef43aa38SMilan Broz 		return -ENOMEM;
944ef43aa38SMilan Broz 
945ef43aa38SMilan Broz 	return 0;
946ef43aa38SMilan Broz }
947ef43aa38SMilan Broz 
948ef43aa38SMilan Broz static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
949ef43aa38SMilan Broz {
950ef43aa38SMilan Broz #ifdef CONFIG_BLK_DEV_INTEGRITY
951ef43aa38SMilan Broz 	struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
952ef43aa38SMilan Broz 
953ef43aa38SMilan Broz 	/* From now we require underlying device with our integrity profile */
954ef43aa38SMilan Broz 	if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
955ef43aa38SMilan Broz 		ti->error = "Integrity profile not supported.";
956ef43aa38SMilan Broz 		return -EINVAL;
957ef43aa38SMilan Broz 	}
958ef43aa38SMilan Broz 
959583fe747SMikulas Patocka 	if (bi->tag_size != cc->on_disk_tag_size ||
960583fe747SMikulas Patocka 	    bi->tuple_size != cc->on_disk_tag_size) {
961ef43aa38SMilan Broz 		ti->error = "Integrity profile tag size mismatch.";
962ef43aa38SMilan Broz 		return -EINVAL;
963ef43aa38SMilan Broz 	}
964583fe747SMikulas Patocka 	if (1 << bi->interval_exp != cc->sector_size) {
965583fe747SMikulas Patocka 		ti->error = "Integrity profile sector size mismatch.";
966583fe747SMikulas Patocka 		return -EINVAL;
967583fe747SMikulas Patocka 	}
968ef43aa38SMilan Broz 
96933d2f09fSMilan Broz 	if (crypt_integrity_aead(cc)) {
970ef43aa38SMilan Broz 		cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
971ef43aa38SMilan Broz 		DMINFO("Integrity AEAD, tag size %u, IV size %u.",
972ef43aa38SMilan Broz 		       cc->integrity_tag_size, cc->integrity_iv_size);
973ef43aa38SMilan Broz 
974ef43aa38SMilan Broz 		if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
975ef43aa38SMilan Broz 			ti->error = "Integrity AEAD auth tag size is not supported.";
976ef43aa38SMilan Broz 			return -EINVAL;
977ef43aa38SMilan Broz 		}
978ef43aa38SMilan Broz 	} else if (cc->integrity_iv_size)
979ef43aa38SMilan Broz 		DMINFO("Additional per-sector space %u bytes for IV.",
980ef43aa38SMilan Broz 		       cc->integrity_iv_size);
981ef43aa38SMilan Broz 
982ef43aa38SMilan Broz 	if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
983ef43aa38SMilan Broz 		ti->error = "Not enough space for integrity tag in the profile.";
984ef43aa38SMilan Broz 		return -EINVAL;
985ef43aa38SMilan Broz 	}
986ef43aa38SMilan Broz 
987ef43aa38SMilan Broz 	return 0;
988ef43aa38SMilan Broz #else
989ef43aa38SMilan Broz 	ti->error = "Integrity profile not supported.";
990ef43aa38SMilan Broz 	return -EINVAL;
991ef43aa38SMilan Broz #endif
992ef43aa38SMilan Broz }
993ef43aa38SMilan Broz 
994d469f841SMilan Broz static void crypt_convert_init(struct crypt_config *cc,
995d469f841SMilan Broz 			       struct convert_context *ctx,
9961da177e4SLinus Torvalds 			       struct bio *bio_out, struct bio *bio_in,
997fcd369daSMilan Broz 			       sector_t sector)
9981da177e4SLinus Torvalds {
9991da177e4SLinus Torvalds 	ctx->bio_in = bio_in;
10001da177e4SLinus Torvalds 	ctx->bio_out = bio_out;
1001003b5c57SKent Overstreet 	if (bio_in)
1002003b5c57SKent Overstreet 		ctx->iter_in = bio_in->bi_iter;
1003003b5c57SKent Overstreet 	if (bio_out)
1004003b5c57SKent Overstreet 		ctx->iter_out = bio_out->bi_iter;
1005c66029f4SMikulas Patocka 	ctx->cc_sector = sector + cc->iv_offset;
100643d69034SMilan Broz 	init_completion(&ctx->restart);
10071da177e4SLinus Torvalds }
10081da177e4SLinus Torvalds 
1009b2174eebSHuang Ying static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
1010ef43aa38SMilan Broz 					     void *req)
1011b2174eebSHuang Ying {
1012b2174eebSHuang Ying 	return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
1013b2174eebSHuang Ying }
1014b2174eebSHuang Ying 
1015ef43aa38SMilan Broz static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
1016b2174eebSHuang Ying {
1017ef43aa38SMilan Broz 	return (void *)((char *)dmreq - cc->dmreq_start);
1018b2174eebSHuang Ying }
1019b2174eebSHuang Ying 
10202dc5327dSMilan Broz static u8 *iv_of_dmreq(struct crypt_config *cc,
10212dc5327dSMilan Broz 		       struct dm_crypt_request *dmreq)
10222dc5327dSMilan Broz {
102333d2f09fSMilan Broz 	if (crypt_integrity_aead(cc))
1024ef43aa38SMilan Broz 		return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1025ef43aa38SMilan Broz 			crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
1026ef43aa38SMilan Broz 	else
10272dc5327dSMilan Broz 		return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1028bbdb23b5SHerbert Xu 			crypto_skcipher_alignmask(any_tfm(cc)) + 1);
10292dc5327dSMilan Broz }
10302dc5327dSMilan Broz 
1031ef43aa38SMilan Broz static u8 *org_iv_of_dmreq(struct crypt_config *cc,
1032ef43aa38SMilan Broz 		       struct dm_crypt_request *dmreq)
1033ef43aa38SMilan Broz {
1034ef43aa38SMilan Broz 	return iv_of_dmreq(cc, dmreq) + cc->iv_size;
1035ef43aa38SMilan Broz }
1036ef43aa38SMilan Broz 
1037ef43aa38SMilan Broz static uint64_t *org_sector_of_dmreq(struct crypt_config *cc,
1038ef43aa38SMilan Broz 		       struct dm_crypt_request *dmreq)
1039ef43aa38SMilan Broz {
1040ef43aa38SMilan Broz 	u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
1041ef43aa38SMilan Broz 	return (uint64_t*) ptr;
1042ef43aa38SMilan Broz }
1043ef43aa38SMilan Broz 
1044ef43aa38SMilan Broz static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
1045ef43aa38SMilan Broz 		       struct dm_crypt_request *dmreq)
1046ef43aa38SMilan Broz {
1047ef43aa38SMilan Broz 	u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
1048ef43aa38SMilan Broz 		  cc->iv_size + sizeof(uint64_t);
1049ef43aa38SMilan Broz 	return (unsigned int*)ptr;
1050ef43aa38SMilan Broz }
1051ef43aa38SMilan Broz 
1052ef43aa38SMilan Broz static void *tag_from_dmreq(struct crypt_config *cc,
1053ef43aa38SMilan Broz 				struct dm_crypt_request *dmreq)
1054ef43aa38SMilan Broz {
1055ef43aa38SMilan Broz 	struct convert_context *ctx = dmreq->ctx;
1056ef43aa38SMilan Broz 	struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1057ef43aa38SMilan Broz 
1058ef43aa38SMilan Broz 	return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
1059ef43aa38SMilan Broz 		cc->on_disk_tag_size];
1060ef43aa38SMilan Broz }
1061ef43aa38SMilan Broz 
1062ef43aa38SMilan Broz static void *iv_tag_from_dmreq(struct crypt_config *cc,
1063ef43aa38SMilan Broz 			       struct dm_crypt_request *dmreq)
1064ef43aa38SMilan Broz {
1065ef43aa38SMilan Broz 	return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
1066ef43aa38SMilan Broz }
1067ef43aa38SMilan Broz 
1068ef43aa38SMilan Broz static int crypt_convert_block_aead(struct crypt_config *cc,
10693a7f6c99SMilan Broz 				     struct convert_context *ctx,
1070ef43aa38SMilan Broz 				     struct aead_request *req,
1071ef43aa38SMilan Broz 				     unsigned int tag_offset)
107201482b76SMilan Broz {
1073003b5c57SKent Overstreet 	struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1074003b5c57SKent Overstreet 	struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
10753a7f6c99SMilan Broz 	struct dm_crypt_request *dmreq;
1076ef43aa38SMilan Broz 	u8 *iv, *org_iv, *tag_iv, *tag;
1077ef43aa38SMilan Broz 	uint64_t *sector;
1078ef43aa38SMilan Broz 	int r = 0;
1079ef43aa38SMilan Broz 
1080ef43aa38SMilan Broz 	BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
108101482b76SMilan Broz 
10828f0009a2SMilan Broz 	/* Reject unexpected unaligned bio. */
10830440d5c0SMikulas Patocka 	if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
10848f0009a2SMilan Broz 		return -EIO;
108501482b76SMilan Broz 
1086b2174eebSHuang Ying 	dmreq = dmreq_of_req(cc, req);
1087c66029f4SMikulas Patocka 	dmreq->iv_sector = ctx->cc_sector;
10888f0009a2SMilan Broz 	if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1089ff3af92bSMikulas Patocka 		dmreq->iv_sector >>= cc->sector_shift;
1090b2174eebSHuang Ying 	dmreq->ctx = ctx;
109101482b76SMilan Broz 
1092ef43aa38SMilan Broz 	*org_tag_of_dmreq(cc, dmreq) = tag_offset;
109301482b76SMilan Broz 
1094ef43aa38SMilan Broz 	sector = org_sector_of_dmreq(cc, dmreq);
1095ef43aa38SMilan Broz 	*sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1096ef43aa38SMilan Broz 
1097ef43aa38SMilan Broz 	iv = iv_of_dmreq(cc, dmreq);
1098ef43aa38SMilan Broz 	org_iv = org_iv_of_dmreq(cc, dmreq);
1099ef43aa38SMilan Broz 	tag = tag_from_dmreq(cc, dmreq);
1100ef43aa38SMilan Broz 	tag_iv = iv_tag_from_dmreq(cc, dmreq);
1101ef43aa38SMilan Broz 
1102ef43aa38SMilan Broz 	/* AEAD request:
1103ef43aa38SMilan Broz 	 *  |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1104ef43aa38SMilan Broz 	 *  | (authenticated) | (auth+encryption) |              |
1105ef43aa38SMilan Broz 	 *  | sector_LE |  IV |  sector in/out    |  tag in/out  |
1106ef43aa38SMilan Broz 	 */
1107ef43aa38SMilan Broz 	sg_init_table(dmreq->sg_in, 4);
1108ef43aa38SMilan Broz 	sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
1109ef43aa38SMilan Broz 	sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
11108f0009a2SMilan Broz 	sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1111ef43aa38SMilan Broz 	sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
1112ef43aa38SMilan Broz 
1113ef43aa38SMilan Broz 	sg_init_table(dmreq->sg_out, 4);
1114ef43aa38SMilan Broz 	sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
1115ef43aa38SMilan Broz 	sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
11168f0009a2SMilan Broz 	sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1117ef43aa38SMilan Broz 	sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
111801482b76SMilan Broz 
11193a7f6c99SMilan Broz 	if (cc->iv_gen_ops) {
1120ef43aa38SMilan Broz 		/* For READs use IV stored in integrity metadata */
1121ef43aa38SMilan Broz 		if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1122ef43aa38SMilan Broz 			memcpy(org_iv, tag_iv, cc->iv_size);
1123ef43aa38SMilan Broz 		} else {
1124ef43aa38SMilan Broz 			r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
11253a7f6c99SMilan Broz 			if (r < 0)
11263a7f6c99SMilan Broz 				return r;
1127ef43aa38SMilan Broz 			/* Store generated IV in integrity metadata */
1128ef43aa38SMilan Broz 			if (cc->integrity_iv_size)
1129ef43aa38SMilan Broz 				memcpy(tag_iv, org_iv, cc->iv_size);
1130ef43aa38SMilan Broz 		}
1131ef43aa38SMilan Broz 		/* Working copy of IV, to be modified in crypto API */
1132ef43aa38SMilan Broz 		memcpy(iv, org_iv, cc->iv_size);
1133ef43aa38SMilan Broz 	}
1134ef43aa38SMilan Broz 
1135ef43aa38SMilan Broz 	aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
1136ef43aa38SMilan Broz 	if (bio_data_dir(ctx->bio_in) == WRITE) {
1137ef43aa38SMilan Broz 		aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
11388f0009a2SMilan Broz 				       cc->sector_size, iv);
1139ef43aa38SMilan Broz 		r = crypto_aead_encrypt(req);
1140ef43aa38SMilan Broz 		if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
1141ef43aa38SMilan Broz 			memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
1142ef43aa38SMilan Broz 			       cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
1143ef43aa38SMilan Broz 	} else {
1144ef43aa38SMilan Broz 		aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
11458f0009a2SMilan Broz 				       cc->sector_size + cc->integrity_tag_size, iv);
1146ef43aa38SMilan Broz 		r = crypto_aead_decrypt(req);
1147ef43aa38SMilan Broz 	}
1148ef43aa38SMilan Broz 
1149ef43aa38SMilan Broz 	if (r == -EBADMSG)
1150ef43aa38SMilan Broz 		DMERR_LIMIT("INTEGRITY AEAD ERROR, sector %llu",
1151ef43aa38SMilan Broz 			    (unsigned long long)le64_to_cpu(*sector));
1152ef43aa38SMilan Broz 
1153ef43aa38SMilan Broz 	if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1154ef43aa38SMilan Broz 		r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1155ef43aa38SMilan Broz 
11568f0009a2SMilan Broz 	bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
11578f0009a2SMilan Broz 	bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1158ef43aa38SMilan Broz 
1159ef43aa38SMilan Broz 	return r;
11603a7f6c99SMilan Broz }
11613a7f6c99SMilan Broz 
1162ef43aa38SMilan Broz static int crypt_convert_block_skcipher(struct crypt_config *cc,
1163ef43aa38SMilan Broz 					struct convert_context *ctx,
1164ef43aa38SMilan Broz 					struct skcipher_request *req,
1165ef43aa38SMilan Broz 					unsigned int tag_offset)
1166ef43aa38SMilan Broz {
1167ef43aa38SMilan Broz 	struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1168ef43aa38SMilan Broz 	struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1169ef43aa38SMilan Broz 	struct scatterlist *sg_in, *sg_out;
1170ef43aa38SMilan Broz 	struct dm_crypt_request *dmreq;
1171ef43aa38SMilan Broz 	u8 *iv, *org_iv, *tag_iv;
1172ef43aa38SMilan Broz 	uint64_t *sector;
1173ef43aa38SMilan Broz 	int r = 0;
1174ef43aa38SMilan Broz 
11758f0009a2SMilan Broz 	/* Reject unexpected unaligned bio. */
11760440d5c0SMikulas Patocka 	if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
11778f0009a2SMilan Broz 		return -EIO;
11788f0009a2SMilan Broz 
1179ef43aa38SMilan Broz 	dmreq = dmreq_of_req(cc, req);
1180ef43aa38SMilan Broz 	dmreq->iv_sector = ctx->cc_sector;
11818f0009a2SMilan Broz 	if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1182ff3af92bSMikulas Patocka 		dmreq->iv_sector >>= cc->sector_shift;
1183ef43aa38SMilan Broz 	dmreq->ctx = ctx;
1184ef43aa38SMilan Broz 
1185ef43aa38SMilan Broz 	*org_tag_of_dmreq(cc, dmreq) = tag_offset;
1186ef43aa38SMilan Broz 
1187ef43aa38SMilan Broz 	iv = iv_of_dmreq(cc, dmreq);
1188ef43aa38SMilan Broz 	org_iv = org_iv_of_dmreq(cc, dmreq);
1189ef43aa38SMilan Broz 	tag_iv = iv_tag_from_dmreq(cc, dmreq);
1190ef43aa38SMilan Broz 
1191ef43aa38SMilan Broz 	sector = org_sector_of_dmreq(cc, dmreq);
1192ef43aa38SMilan Broz 	*sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1193ef43aa38SMilan Broz 
1194ef43aa38SMilan Broz 	/* For skcipher we use only the first sg item */
1195ef43aa38SMilan Broz 	sg_in  = &dmreq->sg_in[0];
1196ef43aa38SMilan Broz 	sg_out = &dmreq->sg_out[0];
1197ef43aa38SMilan Broz 
1198ef43aa38SMilan Broz 	sg_init_table(sg_in, 1);
11998f0009a2SMilan Broz 	sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1200ef43aa38SMilan Broz 
1201ef43aa38SMilan Broz 	sg_init_table(sg_out, 1);
12028f0009a2SMilan Broz 	sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1203ef43aa38SMilan Broz 
1204ef43aa38SMilan Broz 	if (cc->iv_gen_ops) {
1205ef43aa38SMilan Broz 		/* For READs use IV stored in integrity metadata */
1206ef43aa38SMilan Broz 		if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1207ef43aa38SMilan Broz 			memcpy(org_iv, tag_iv, cc->integrity_iv_size);
1208ef43aa38SMilan Broz 		} else {
1209ef43aa38SMilan Broz 			r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1210ef43aa38SMilan Broz 			if (r < 0)
1211ef43aa38SMilan Broz 				return r;
1212ef43aa38SMilan Broz 			/* Store generated IV in integrity metadata */
1213ef43aa38SMilan Broz 			if (cc->integrity_iv_size)
1214ef43aa38SMilan Broz 				memcpy(tag_iv, org_iv, cc->integrity_iv_size);
1215ef43aa38SMilan Broz 		}
1216ef43aa38SMilan Broz 		/* Working copy of IV, to be modified in crypto API */
1217ef43aa38SMilan Broz 		memcpy(iv, org_iv, cc->iv_size);
1218ef43aa38SMilan Broz 	}
1219ef43aa38SMilan Broz 
12208f0009a2SMilan Broz 	skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
12213a7f6c99SMilan Broz 
12223a7f6c99SMilan Broz 	if (bio_data_dir(ctx->bio_in) == WRITE)
1223bbdb23b5SHerbert Xu 		r = crypto_skcipher_encrypt(req);
12243a7f6c99SMilan Broz 	else
1225bbdb23b5SHerbert Xu 		r = crypto_skcipher_decrypt(req);
12263a7f6c99SMilan Broz 
12272dc5327dSMilan Broz 	if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1228ef43aa38SMilan Broz 		r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1229ef43aa38SMilan Broz 
12308f0009a2SMilan Broz 	bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
12318f0009a2SMilan Broz 	bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
12322dc5327dSMilan Broz 
12333a7f6c99SMilan Broz 	return r;
123401482b76SMilan Broz }
123501482b76SMilan Broz 
123695497a96SMilan Broz static void kcryptd_async_done(struct crypto_async_request *async_req,
123795497a96SMilan Broz 			       int error);
1238c0297721SAndi Kleen 
1239ef43aa38SMilan Broz static void crypt_alloc_req_skcipher(struct crypt_config *cc,
1240ddd42edfSMilan Broz 				     struct convert_context *ctx)
1241ddd42edfSMilan Broz {
1242c66029f4SMikulas Patocka 	unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
1243c0297721SAndi Kleen 
1244ef43aa38SMilan Broz 	if (!ctx->r.req)
12456f1c819cSKent Overstreet 		ctx->r.req = mempool_alloc(&cc->req_pool, GFP_NOIO);
1246c0297721SAndi Kleen 
1247ef43aa38SMilan Broz 	skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
124854cea3f6SMilan Broz 
124954cea3f6SMilan Broz 	/*
125054cea3f6SMilan Broz 	 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
125154cea3f6SMilan Broz 	 * requests if driver request queue is full.
125254cea3f6SMilan Broz 	 */
1253ef43aa38SMilan Broz 	skcipher_request_set_callback(ctx->r.req,
1254432061b3SMikulas Patocka 	    CRYPTO_TFM_REQ_MAY_BACKLOG,
1255ef43aa38SMilan Broz 	    kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
1256ddd42edfSMilan Broz }
1257ddd42edfSMilan Broz 
1258ef43aa38SMilan Broz static void crypt_alloc_req_aead(struct crypt_config *cc,
1259ef43aa38SMilan Broz 				 struct convert_context *ctx)
1260ef43aa38SMilan Broz {
1261ef43aa38SMilan Broz 	if (!ctx->r.req_aead)
12626f1c819cSKent Overstreet 		ctx->r.req_aead = mempool_alloc(&cc->req_pool, GFP_NOIO);
1263ef43aa38SMilan Broz 
1264ef43aa38SMilan Broz 	aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
1265ef43aa38SMilan Broz 
1266ef43aa38SMilan Broz 	/*
1267ef43aa38SMilan Broz 	 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1268ef43aa38SMilan Broz 	 * requests if driver request queue is full.
1269ef43aa38SMilan Broz 	 */
1270ef43aa38SMilan Broz 	aead_request_set_callback(ctx->r.req_aead,
1271432061b3SMikulas Patocka 	    CRYPTO_TFM_REQ_MAY_BACKLOG,
1272ef43aa38SMilan Broz 	    kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
1273ef43aa38SMilan Broz }
1274ef43aa38SMilan Broz 
1275ef43aa38SMilan Broz static void crypt_alloc_req(struct crypt_config *cc,
1276ef43aa38SMilan Broz 			    struct convert_context *ctx)
1277ef43aa38SMilan Broz {
127833d2f09fSMilan Broz 	if (crypt_integrity_aead(cc))
1279ef43aa38SMilan Broz 		crypt_alloc_req_aead(cc, ctx);
1280ef43aa38SMilan Broz 	else
1281ef43aa38SMilan Broz 		crypt_alloc_req_skcipher(cc, ctx);
1282ef43aa38SMilan Broz }
1283ef43aa38SMilan Broz 
1284ef43aa38SMilan Broz static void crypt_free_req_skcipher(struct crypt_config *cc,
1285bbdb23b5SHerbert Xu 				    struct skcipher_request *req, struct bio *base_bio)
1286298a9fa0SMikulas Patocka {
1287298a9fa0SMikulas Patocka 	struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1288298a9fa0SMikulas Patocka 
1289bbdb23b5SHerbert Xu 	if ((struct skcipher_request *)(io + 1) != req)
12906f1c819cSKent Overstreet 		mempool_free(req, &cc->req_pool);
1291298a9fa0SMikulas Patocka }
1292298a9fa0SMikulas Patocka 
1293ef43aa38SMilan Broz static void crypt_free_req_aead(struct crypt_config *cc,
1294ef43aa38SMilan Broz 				struct aead_request *req, struct bio *base_bio)
1295ef43aa38SMilan Broz {
1296ef43aa38SMilan Broz 	struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1297ef43aa38SMilan Broz 
1298ef43aa38SMilan Broz 	if ((struct aead_request *)(io + 1) != req)
12996f1c819cSKent Overstreet 		mempool_free(req, &cc->req_pool);
1300ef43aa38SMilan Broz }
1301ef43aa38SMilan Broz 
1302ef43aa38SMilan Broz static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
1303ef43aa38SMilan Broz {
130433d2f09fSMilan Broz 	if (crypt_integrity_aead(cc))
1305ef43aa38SMilan Broz 		crypt_free_req_aead(cc, req, base_bio);
1306ef43aa38SMilan Broz 	else
1307ef43aa38SMilan Broz 		crypt_free_req_skcipher(cc, req, base_bio);
1308ef43aa38SMilan Broz }
1309ef43aa38SMilan Broz 
13101da177e4SLinus Torvalds /*
13111da177e4SLinus Torvalds  * Encrypt / decrypt data from one bio to another one (can be the same one)
13121da177e4SLinus Torvalds  */
13134e4cbee9SChristoph Hellwig static blk_status_t crypt_convert(struct crypt_config *cc,
13141da177e4SLinus Torvalds 			 struct convert_context *ctx)
13151da177e4SLinus Torvalds {
1316ef43aa38SMilan Broz 	unsigned int tag_offset = 0;
1317ff3af92bSMikulas Patocka 	unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
13183f1e9070SMilan Broz 	int r;
13191da177e4SLinus Torvalds 
132040b6229bSMikulas Patocka 	atomic_set(&ctx->cc_pending, 1);
1321c8081618SMilan Broz 
1322003b5c57SKent Overstreet 	while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
13231da177e4SLinus Torvalds 
13243a7f6c99SMilan Broz 		crypt_alloc_req(cc, ctx);
132540b6229bSMikulas Patocka 		atomic_inc(&ctx->cc_pending);
13263f1e9070SMilan Broz 
132733d2f09fSMilan Broz 		if (crypt_integrity_aead(cc))
1328ef43aa38SMilan Broz 			r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
1329ef43aa38SMilan Broz 		else
1330ef43aa38SMilan Broz 			r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
13313a7f6c99SMilan Broz 
13323a7f6c99SMilan Broz 		switch (r) {
133354cea3f6SMilan Broz 		/*
133454cea3f6SMilan Broz 		 * The request was queued by a crypto driver
133554cea3f6SMilan Broz 		 * but the driver request queue is full, let's wait.
133654cea3f6SMilan Broz 		 */
13373a7f6c99SMilan Broz 		case -EBUSY:
13383a7f6c99SMilan Broz 			wait_for_completion(&ctx->restart);
133916735d02SWolfram Sang 			reinit_completion(&ctx->restart);
1340c0403ec0SRabin Vincent 			/* fall through */
134154cea3f6SMilan Broz 		/*
134254cea3f6SMilan Broz 		 * The request is queued and processed asynchronously,
134354cea3f6SMilan Broz 		 * completion function kcryptd_async_done() will be called.
134454cea3f6SMilan Broz 		 */
1345c0403ec0SRabin Vincent 		case -EINPROGRESS:
1346ef43aa38SMilan Broz 			ctx->r.req = NULL;
13478f0009a2SMilan Broz 			ctx->cc_sector += sector_step;
1348583fe747SMikulas Patocka 			tag_offset++;
13493a7f6c99SMilan Broz 			continue;
135054cea3f6SMilan Broz 		/*
135154cea3f6SMilan Broz 		 * The request was already processed (synchronously).
135254cea3f6SMilan Broz 		 */
13533f1e9070SMilan Broz 		case 0:
135440b6229bSMikulas Patocka 			atomic_dec(&ctx->cc_pending);
13558f0009a2SMilan Broz 			ctx->cc_sector += sector_step;
1356583fe747SMikulas Patocka 			tag_offset++;
1357c7f1b204SMilan Broz 			cond_resched();
13583f1e9070SMilan Broz 			continue;
1359ef43aa38SMilan Broz 		/*
1360ef43aa38SMilan Broz 		 * There was a data integrity error.
1361ef43aa38SMilan Broz 		 */
1362ef43aa38SMilan Broz 		case -EBADMSG:
1363ef43aa38SMilan Broz 			atomic_dec(&ctx->cc_pending);
13644e4cbee9SChristoph Hellwig 			return BLK_STS_PROTECTION;
1365ef43aa38SMilan Broz 		/*
1366ef43aa38SMilan Broz 		 * There was an error while processing the request.
1367ef43aa38SMilan Broz 		 */
13683f1e9070SMilan Broz 		default:
136940b6229bSMikulas Patocka 			atomic_dec(&ctx->cc_pending);
13704e4cbee9SChristoph Hellwig 			return BLK_STS_IOERR;
13711da177e4SLinus Torvalds 		}
13723f1e9070SMilan Broz 	}
13733f1e9070SMilan Broz 
13743f1e9070SMilan Broz 	return 0;
13753f1e9070SMilan Broz }
13761da177e4SLinus Torvalds 
1377cf2f1abfSMikulas Patocka static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
1378cf2f1abfSMikulas Patocka 
13791da177e4SLinus Torvalds /*
13801da177e4SLinus Torvalds  * Generate a new unfragmented bio with the given size
1381586b286bSMike Snitzer  * This should never violate the device limitations (but only because
1382586b286bSMike Snitzer  * max_segment_size is being constrained to PAGE_SIZE).
13837145c241SMikulas Patocka  *
13847145c241SMikulas Patocka  * This function may be called concurrently. If we allocate from the mempool
13857145c241SMikulas Patocka  * concurrently, there is a possibility of deadlock. For example, if we have
13867145c241SMikulas Patocka  * mempool of 256 pages, two processes, each wanting 256, pages allocate from
13877145c241SMikulas Patocka  * the mempool concurrently, it may deadlock in a situation where both processes
13887145c241SMikulas Patocka  * have allocated 128 pages and the mempool is exhausted.
13897145c241SMikulas Patocka  *
13907145c241SMikulas Patocka  * In order to avoid this scenario we allocate the pages under a mutex.
13917145c241SMikulas Patocka  *
13927145c241SMikulas Patocka  * In order to not degrade performance with excessive locking, we try
13937145c241SMikulas Patocka  * non-blocking allocations without a mutex first but on failure we fallback
13947145c241SMikulas Patocka  * to blocking allocations with a mutex.
13951da177e4SLinus Torvalds  */
1396cf2f1abfSMikulas Patocka static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
13971da177e4SLinus Torvalds {
139849a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
13998b004457SMilan Broz 	struct bio *clone;
14001da177e4SLinus Torvalds 	unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
14017145c241SMikulas Patocka 	gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
14027145c241SMikulas Patocka 	unsigned i, len, remaining_size;
140391e10625SMilan Broz 	struct page *page;
14041da177e4SLinus Torvalds 
14057145c241SMikulas Patocka retry:
1406d0164adcSMel Gorman 	if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
14077145c241SMikulas Patocka 		mutex_lock(&cc->bio_alloc_lock);
14087145c241SMikulas Patocka 
14096f1c819cSKent Overstreet 	clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, &cc->bs);
14108b004457SMilan Broz 	if (!clone)
1411ef43aa38SMilan Broz 		goto out;
14121da177e4SLinus Torvalds 
1413027581f3SOlaf Kirch 	clone_init(io, clone);
14146a24c718SMilan Broz 
14157145c241SMikulas Patocka 	remaining_size = size;
14167145c241SMikulas Patocka 
1417f97380bcSOlaf Kirch 	for (i = 0; i < nr_iovecs; i++) {
14186f1c819cSKent Overstreet 		page = mempool_alloc(&cc->page_pool, gfp_mask);
14197145c241SMikulas Patocka 		if (!page) {
14207145c241SMikulas Patocka 			crypt_free_buffer_pages(cc, clone);
14217145c241SMikulas Patocka 			bio_put(clone);
1422d0164adcSMel Gorman 			gfp_mask |= __GFP_DIRECT_RECLAIM;
14237145c241SMikulas Patocka 			goto retry;
14247145c241SMikulas Patocka 		}
14251da177e4SLinus Torvalds 
14267145c241SMikulas Patocka 		len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
14271da177e4SLinus Torvalds 
14280dae7fe5SMing Lei 		bio_add_page(clone, page, len, 0);
142991e10625SMilan Broz 
14307145c241SMikulas Patocka 		remaining_size -= len;
14311da177e4SLinus Torvalds 	}
14321da177e4SLinus Torvalds 
1433ef43aa38SMilan Broz 	/* Allocate space for integrity tags */
1434ef43aa38SMilan Broz 	if (dm_crypt_integrity_io_alloc(io, clone)) {
1435ef43aa38SMilan Broz 		crypt_free_buffer_pages(cc, clone);
1436ef43aa38SMilan Broz 		bio_put(clone);
1437ef43aa38SMilan Broz 		clone = NULL;
1438ef43aa38SMilan Broz 	}
1439ef43aa38SMilan Broz out:
1440d0164adcSMel Gorman 	if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
14417145c241SMikulas Patocka 		mutex_unlock(&cc->bio_alloc_lock);
14427145c241SMikulas Patocka 
14438b004457SMilan Broz 	return clone;
14441da177e4SLinus Torvalds }
14451da177e4SLinus Torvalds 
1446644bd2f0SNeil Brown static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
14471da177e4SLinus Torvalds {
1448644bd2f0SNeil Brown 	unsigned int i;
14491da177e4SLinus Torvalds 	struct bio_vec *bv;
14501da177e4SLinus Torvalds 
1451cb34e057SKent Overstreet 	bio_for_each_segment_all(bv, clone, i) {
14521da177e4SLinus Torvalds 		BUG_ON(!bv->bv_page);
14536f1c819cSKent Overstreet 		mempool_free(bv->bv_page, &cc->page_pool);
14541da177e4SLinus Torvalds 	}
14551da177e4SLinus Torvalds }
14561da177e4SLinus Torvalds 
1457298a9fa0SMikulas Patocka static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1458dc440d1eSMilan Broz 			  struct bio *bio, sector_t sector)
1459dc440d1eSMilan Broz {
146049a8a920SAlasdair G Kergon 	io->cc = cc;
1461dc440d1eSMilan Broz 	io->base_bio = bio;
1462dc440d1eSMilan Broz 	io->sector = sector;
1463dc440d1eSMilan Broz 	io->error = 0;
1464ef43aa38SMilan Broz 	io->ctx.r.req = NULL;
1465ef43aa38SMilan Broz 	io->integrity_metadata = NULL;
1466ef43aa38SMilan Broz 	io->integrity_metadata_from_pool = false;
146740b6229bSMikulas Patocka 	atomic_set(&io->io_pending, 0);
1468dc440d1eSMilan Broz }
1469dc440d1eSMilan Broz 
14703e1a8bddSMilan Broz static void crypt_inc_pending(struct dm_crypt_io *io)
14713e1a8bddSMilan Broz {
147240b6229bSMikulas Patocka 	atomic_inc(&io->io_pending);
14733e1a8bddSMilan Broz }
14743e1a8bddSMilan Broz 
14751da177e4SLinus Torvalds /*
14761da177e4SLinus Torvalds  * One of the bios was finished. Check for completion of
14771da177e4SLinus Torvalds  * the whole request and correctly clean up the buffer.
14781da177e4SLinus Torvalds  */
14795742fd77SMilan Broz static void crypt_dec_pending(struct dm_crypt_io *io)
14801da177e4SLinus Torvalds {
148149a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
1482b35f8caaSMilan Broz 	struct bio *base_bio = io->base_bio;
14834e4cbee9SChristoph Hellwig 	blk_status_t error = io->error;
14841da177e4SLinus Torvalds 
148540b6229bSMikulas Patocka 	if (!atomic_dec_and_test(&io->io_pending))
14861da177e4SLinus Torvalds 		return;
14871da177e4SLinus Torvalds 
1488ef43aa38SMilan Broz 	if (io->ctx.r.req)
1489ef43aa38SMilan Broz 		crypt_free_req(cc, io->ctx.r.req, base_bio);
1490ef43aa38SMilan Broz 
1491ef43aa38SMilan Broz 	if (unlikely(io->integrity_metadata_from_pool))
14926f1c819cSKent Overstreet 		mempool_free(io->integrity_metadata, &io->cc->tag_pool);
1493ef43aa38SMilan Broz 	else
1494ef43aa38SMilan Broz 		kfree(io->integrity_metadata);
1495b35f8caaSMilan Broz 
14964e4cbee9SChristoph Hellwig 	base_bio->bi_status = error;
14974246a0b6SChristoph Hellwig 	bio_endio(base_bio);
14981da177e4SLinus Torvalds }
14991da177e4SLinus Torvalds 
15001da177e4SLinus Torvalds /*
1501cabf08e4SMilan Broz  * kcryptd/kcryptd_io:
15021da177e4SLinus Torvalds  *
15031da177e4SLinus Torvalds  * Needed because it would be very unwise to do decryption in an
150423541d2dSMilan Broz  * interrupt context.
1505cabf08e4SMilan Broz  *
1506cabf08e4SMilan Broz  * kcryptd performs the actual encryption or decryption.
1507cabf08e4SMilan Broz  *
1508cabf08e4SMilan Broz  * kcryptd_io performs the IO submission.
1509cabf08e4SMilan Broz  *
1510cabf08e4SMilan Broz  * They must be separated as otherwise the final stages could be
1511cabf08e4SMilan Broz  * starved by new requests which can block in the first stages due
1512cabf08e4SMilan Broz  * to memory allocation.
1513c0297721SAndi Kleen  *
1514c0297721SAndi Kleen  * The work is done per CPU global for all dm-crypt instances.
1515c0297721SAndi Kleen  * They should not depend on each other and do not block.
15161da177e4SLinus Torvalds  */
15174246a0b6SChristoph Hellwig static void crypt_endio(struct bio *clone)
15188b004457SMilan Broz {
1519028867acSAlasdair G Kergon 	struct dm_crypt_io *io = clone->bi_private;
152049a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
1521ee7a491eSMilan Broz 	unsigned rw = bio_data_dir(clone);
15224e4cbee9SChristoph Hellwig 	blk_status_t error;
15238b004457SMilan Broz 
15248b004457SMilan Broz 	/*
15256712ecf8SNeilBrown 	 * free the processed pages
15268b004457SMilan Broz 	 */
1527ee7a491eSMilan Broz 	if (rw == WRITE)
1528644bd2f0SNeil Brown 		crypt_free_buffer_pages(cc, clone);
15298b004457SMilan Broz 
15304e4cbee9SChristoph Hellwig 	error = clone->bi_status;
15318b004457SMilan Broz 	bio_put(clone);
1532ee7a491eSMilan Broz 
15339b81c842SSasha Levin 	if (rw == READ && !error) {
1534cabf08e4SMilan Broz 		kcryptd_queue_crypt(io);
15356712ecf8SNeilBrown 		return;
1536ee7a491eSMilan Broz 	}
15375742fd77SMilan Broz 
15389b81c842SSasha Levin 	if (unlikely(error))
15399b81c842SSasha Levin 		io->error = error;
15405742fd77SMilan Broz 
15415742fd77SMilan Broz 	crypt_dec_pending(io);
15428b004457SMilan Broz }
15438b004457SMilan Broz 
1544028867acSAlasdair G Kergon static void clone_init(struct dm_crypt_io *io, struct bio *clone)
15458b004457SMilan Broz {
154649a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
15478b004457SMilan Broz 
15488b004457SMilan Broz 	clone->bi_private = io;
15498b004457SMilan Broz 	clone->bi_end_io  = crypt_endio;
155074d46992SChristoph Hellwig 	bio_set_dev(clone, cc->dev->bdev);
1551ef295ecfSChristoph Hellwig 	clone->bi_opf	  = io->base_bio->bi_opf;
15528b004457SMilan Broz }
15538b004457SMilan Broz 
155420c82538SMilan Broz static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
15558b004457SMilan Broz {
155649a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
15578b004457SMilan Broz 	struct bio *clone;
155893e605c2SMilan Broz 
15598b004457SMilan Broz 	/*
156059779079SMike Snitzer 	 * We need the original biovec array in order to decrypt
156159779079SMike Snitzer 	 * the whole bio data *afterwards* -- thanks to immutable
156259779079SMike Snitzer 	 * biovecs we don't need to worry about the block layer
156359779079SMike Snitzer 	 * modifying the biovec array; so leverage bio_clone_fast().
15648b004457SMilan Broz 	 */
15656f1c819cSKent Overstreet 	clone = bio_clone_fast(io->base_bio, gfp, &cc->bs);
15667eaceaccSJens Axboe 	if (!clone)
156720c82538SMilan Broz 		return 1;
15688b004457SMilan Broz 
156920c82538SMilan Broz 	crypt_inc_pending(io);
157020c82538SMilan Broz 
15718b004457SMilan Broz 	clone_init(io, clone);
15724f024f37SKent Overstreet 	clone->bi_iter.bi_sector = cc->start + io->sector;
15738b004457SMilan Broz 
1574ef43aa38SMilan Broz 	if (dm_crypt_integrity_io_alloc(io, clone)) {
1575ef43aa38SMilan Broz 		crypt_dec_pending(io);
1576ef43aa38SMilan Broz 		bio_put(clone);
1577ef43aa38SMilan Broz 		return 1;
1578ef43aa38SMilan Broz 	}
1579ef43aa38SMilan Broz 
158093e605c2SMilan Broz 	generic_make_request(clone);
158120c82538SMilan Broz 	return 0;
15828b004457SMilan Broz }
15838b004457SMilan Broz 
1584dc267621SMikulas Patocka static void kcryptd_io_read_work(struct work_struct *work)
1585395b167cSAlasdair G Kergon {
1586395b167cSAlasdair G Kergon 	struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1587395b167cSAlasdair G Kergon 
158820c82538SMilan Broz 	crypt_inc_pending(io);
158920c82538SMilan Broz 	if (kcryptd_io_read(io, GFP_NOIO))
15904e4cbee9SChristoph Hellwig 		io->error = BLK_STS_RESOURCE;
159120c82538SMilan Broz 	crypt_dec_pending(io);
1592395b167cSAlasdair G Kergon }
1593395b167cSAlasdair G Kergon 
1594dc267621SMikulas Patocka static void kcryptd_queue_read(struct dm_crypt_io *io)
1595395b167cSAlasdair G Kergon {
159649a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
1597395b167cSAlasdair G Kergon 
1598dc267621SMikulas Patocka 	INIT_WORK(&io->work, kcryptd_io_read_work);
1599395b167cSAlasdair G Kergon 	queue_work(cc->io_queue, &io->work);
1600395b167cSAlasdair G Kergon }
1601395b167cSAlasdair G Kergon 
1602dc267621SMikulas Patocka static void kcryptd_io_write(struct dm_crypt_io *io)
1603dc267621SMikulas Patocka {
1604dc267621SMikulas Patocka 	struct bio *clone = io->ctx.bio_out;
1605dc267621SMikulas Patocka 
1606dc267621SMikulas Patocka 	generic_make_request(clone);
1607dc267621SMikulas Patocka }
1608dc267621SMikulas Patocka 
1609b3c5fd30SMikulas Patocka #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1610b3c5fd30SMikulas Patocka 
1611dc267621SMikulas Patocka static int dmcrypt_write(void *data)
1612dc267621SMikulas Patocka {
1613dc267621SMikulas Patocka 	struct crypt_config *cc = data;
1614b3c5fd30SMikulas Patocka 	struct dm_crypt_io *io;
1615b3c5fd30SMikulas Patocka 
1616dc267621SMikulas Patocka 	while (1) {
1617b3c5fd30SMikulas Patocka 		struct rb_root write_tree;
1618dc267621SMikulas Patocka 		struct blk_plug plug;
1619dc267621SMikulas Patocka 
1620c7329effSMikulas Patocka 		spin_lock_irq(&cc->write_thread_lock);
1621dc267621SMikulas Patocka continue_locked:
1622dc267621SMikulas Patocka 
1623b3c5fd30SMikulas Patocka 		if (!RB_EMPTY_ROOT(&cc->write_tree))
1624dc267621SMikulas Patocka 			goto pop_from_list;
1625dc267621SMikulas Patocka 
1626f659b100SRabin Vincent 		set_current_state(TASK_INTERRUPTIBLE);
1627dc267621SMikulas Patocka 
1628c7329effSMikulas Patocka 		spin_unlock_irq(&cc->write_thread_lock);
1629dc267621SMikulas Patocka 
1630f659b100SRabin Vincent 		if (unlikely(kthread_should_stop())) {
1631642fa448SDavidlohr Bueso 			set_current_state(TASK_RUNNING);
1632f659b100SRabin Vincent 			break;
1633f659b100SRabin Vincent 		}
1634f659b100SRabin Vincent 
1635dc267621SMikulas Patocka 		schedule();
1636dc267621SMikulas Patocka 
1637642fa448SDavidlohr Bueso 		set_current_state(TASK_RUNNING);
1638c7329effSMikulas Patocka 		spin_lock_irq(&cc->write_thread_lock);
1639dc267621SMikulas Patocka 		goto continue_locked;
1640dc267621SMikulas Patocka 
1641dc267621SMikulas Patocka pop_from_list:
1642b3c5fd30SMikulas Patocka 		write_tree = cc->write_tree;
1643b3c5fd30SMikulas Patocka 		cc->write_tree = RB_ROOT;
1644c7329effSMikulas Patocka 		spin_unlock_irq(&cc->write_thread_lock);
1645dc267621SMikulas Patocka 
1646b3c5fd30SMikulas Patocka 		BUG_ON(rb_parent(write_tree.rb_node));
1647b3c5fd30SMikulas Patocka 
1648b3c5fd30SMikulas Patocka 		/*
1649b3c5fd30SMikulas Patocka 		 * Note: we cannot walk the tree here with rb_next because
1650b3c5fd30SMikulas Patocka 		 * the structures may be freed when kcryptd_io_write is called.
1651b3c5fd30SMikulas Patocka 		 */
1652dc267621SMikulas Patocka 		blk_start_plug(&plug);
1653dc267621SMikulas Patocka 		do {
1654b3c5fd30SMikulas Patocka 			io = crypt_io_from_node(rb_first(&write_tree));
1655b3c5fd30SMikulas Patocka 			rb_erase(&io->rb_node, &write_tree);
1656dc267621SMikulas Patocka 			kcryptd_io_write(io);
1657b3c5fd30SMikulas Patocka 		} while (!RB_EMPTY_ROOT(&write_tree));
1658dc267621SMikulas Patocka 		blk_finish_plug(&plug);
1659dc267621SMikulas Patocka 	}
1660dc267621SMikulas Patocka 	return 0;
1661dc267621SMikulas Patocka }
1662dc267621SMikulas Patocka 
166372c6e7afSMikulas Patocka static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
16644e4eef64SMilan Broz {
1665dec1cedfSMilan Broz 	struct bio *clone = io->ctx.bio_out;
166649a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
1667dc267621SMikulas Patocka 	unsigned long flags;
1668b3c5fd30SMikulas Patocka 	sector_t sector;
1669b3c5fd30SMikulas Patocka 	struct rb_node **rbp, *parent;
1670dec1cedfSMilan Broz 
16714e4cbee9SChristoph Hellwig 	if (unlikely(io->error)) {
1672dec1cedfSMilan Broz 		crypt_free_buffer_pages(cc, clone);
1673dec1cedfSMilan Broz 		bio_put(clone);
16746c031f41SMilan Broz 		crypt_dec_pending(io);
1675dec1cedfSMilan Broz 		return;
1676dec1cedfSMilan Broz 	}
1677dec1cedfSMilan Broz 
1678dec1cedfSMilan Broz 	/* crypt_convert should have filled the clone bio */
1679003b5c57SKent Overstreet 	BUG_ON(io->ctx.iter_out.bi_size);
1680dec1cedfSMilan Broz 
16814f024f37SKent Overstreet 	clone->bi_iter.bi_sector = cc->start + io->sector;
1682899c95d3SMilan Broz 
16830f5d8e6eSMikulas Patocka 	if (likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) {
16840f5d8e6eSMikulas Patocka 		generic_make_request(clone);
16850f5d8e6eSMikulas Patocka 		return;
16860f5d8e6eSMikulas Patocka 	}
16870f5d8e6eSMikulas Patocka 
1688c7329effSMikulas Patocka 	spin_lock_irqsave(&cc->write_thread_lock, flags);
1689c7329effSMikulas Patocka 	if (RB_EMPTY_ROOT(&cc->write_tree))
1690c7329effSMikulas Patocka 		wake_up_process(cc->write_thread);
1691b3c5fd30SMikulas Patocka 	rbp = &cc->write_tree.rb_node;
1692b3c5fd30SMikulas Patocka 	parent = NULL;
1693b3c5fd30SMikulas Patocka 	sector = io->sector;
1694b3c5fd30SMikulas Patocka 	while (*rbp) {
1695b3c5fd30SMikulas Patocka 		parent = *rbp;
1696b3c5fd30SMikulas Patocka 		if (sector < crypt_io_from_node(parent)->sector)
1697b3c5fd30SMikulas Patocka 			rbp = &(*rbp)->rb_left;
1698b3c5fd30SMikulas Patocka 		else
1699b3c5fd30SMikulas Patocka 			rbp = &(*rbp)->rb_right;
1700b3c5fd30SMikulas Patocka 	}
1701b3c5fd30SMikulas Patocka 	rb_link_node(&io->rb_node, parent, rbp);
1702b3c5fd30SMikulas Patocka 	rb_insert_color(&io->rb_node, &cc->write_tree);
1703c7329effSMikulas Patocka 	spin_unlock_irqrestore(&cc->write_thread_lock, flags);
17044e4eef64SMilan Broz }
17054e4eef64SMilan Broz 
1706fc5a5e9aSMilan Broz static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
17078b004457SMilan Broz {
170849a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
17098b004457SMilan Broz 	struct bio *clone;
1710c8081618SMilan Broz 	int crypt_finished;
1711b635b00eSMilan Broz 	sector_t sector = io->sector;
17124e4cbee9SChristoph Hellwig 	blk_status_t r;
17138b004457SMilan Broz 
171493e605c2SMilan Broz 	/*
1715fc5a5e9aSMilan Broz 	 * Prevent io from disappearing until this function completes.
1716fc5a5e9aSMilan Broz 	 */
1717fc5a5e9aSMilan Broz 	crypt_inc_pending(io);
1718b635b00eSMilan Broz 	crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
1719fc5a5e9aSMilan Broz 
1720cf2f1abfSMikulas Patocka 	clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
172123541d2dSMilan Broz 	if (unlikely(!clone)) {
17224e4cbee9SChristoph Hellwig 		io->error = BLK_STS_IOERR;
1723cf2f1abfSMikulas Patocka 		goto dec;
172423541d2dSMilan Broz 	}
17258b004457SMilan Broz 
172653017030SMilan Broz 	io->ctx.bio_out = clone;
1727003b5c57SKent Overstreet 	io->ctx.iter_out = clone->bi_iter;
17288b004457SMilan Broz 
1729b635b00eSMilan Broz 	sector += bio_sectors(clone);
1730dec1cedfSMilan Broz 
17314e594098SMilan Broz 	crypt_inc_pending(io);
1732dec1cedfSMilan Broz 	r = crypt_convert(cc, &io->ctx);
17334e4cbee9SChristoph Hellwig 	if (r)
1734ef43aa38SMilan Broz 		io->error = r;
173540b6229bSMikulas Patocka 	crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
1736dec1cedfSMilan Broz 
1737c8081618SMilan Broz 	/* Encryption was already finished, submit io now */
1738c8081618SMilan Broz 	if (crypt_finished) {
173972c6e7afSMikulas Patocka 		kcryptd_crypt_write_io_submit(io, 0);
1740b635b00eSMilan Broz 		io->sector = sector;
17414e594098SMilan Broz 	}
174293e605c2SMilan Broz 
1743cf2f1abfSMikulas Patocka dec:
1744899c95d3SMilan Broz 	crypt_dec_pending(io);
174584131db6SMilan Broz }
174684131db6SMilan Broz 
174772c6e7afSMikulas Patocka static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
17485742fd77SMilan Broz {
17495742fd77SMilan Broz 	crypt_dec_pending(io);
17505742fd77SMilan Broz }
17515742fd77SMilan Broz 
17524e4eef64SMilan Broz static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
17538b004457SMilan Broz {
175449a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
17554e4cbee9SChristoph Hellwig 	blk_status_t r;
17568b004457SMilan Broz 
17573e1a8bddSMilan Broz 	crypt_inc_pending(io);
17583a7f6c99SMilan Broz 
175953017030SMilan Broz 	crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
17600c395b0fSMilan Broz 			   io->sector);
17618b004457SMilan Broz 
17625742fd77SMilan Broz 	r = crypt_convert(cc, &io->ctx);
17634e4cbee9SChristoph Hellwig 	if (r)
1764ef43aa38SMilan Broz 		io->error = r;
17655742fd77SMilan Broz 
176640b6229bSMikulas Patocka 	if (atomic_dec_and_test(&io->ctx.cc_pending))
176772c6e7afSMikulas Patocka 		kcryptd_crypt_read_done(io);
17683a7f6c99SMilan Broz 
17693a7f6c99SMilan Broz 	crypt_dec_pending(io);
17708b004457SMilan Broz }
17718b004457SMilan Broz 
177295497a96SMilan Broz static void kcryptd_async_done(struct crypto_async_request *async_req,
177395497a96SMilan Broz 			       int error)
177495497a96SMilan Broz {
1775b2174eebSHuang Ying 	struct dm_crypt_request *dmreq = async_req->data;
1776b2174eebSHuang Ying 	struct convert_context *ctx = dmreq->ctx;
177795497a96SMilan Broz 	struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
177849a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
177995497a96SMilan Broz 
178054cea3f6SMilan Broz 	/*
178154cea3f6SMilan Broz 	 * A request from crypto driver backlog is going to be processed now,
178254cea3f6SMilan Broz 	 * finish the completion and continue in crypt_convert().
178354cea3f6SMilan Broz 	 * (Callback will be called for the second time for this request.)
178454cea3f6SMilan Broz 	 */
1785c0403ec0SRabin Vincent 	if (error == -EINPROGRESS) {
1786c0403ec0SRabin Vincent 		complete(&ctx->restart);
178795497a96SMilan Broz 		return;
1788c0403ec0SRabin Vincent 	}
178995497a96SMilan Broz 
17902dc5327dSMilan Broz 	if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
1791ef43aa38SMilan Broz 		error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
17922dc5327dSMilan Broz 
1793ef43aa38SMilan Broz 	if (error == -EBADMSG) {
1794ef43aa38SMilan Broz 		DMERR_LIMIT("INTEGRITY AEAD ERROR, sector %llu",
1795ef43aa38SMilan Broz 			    (unsigned long long)le64_to_cpu(*org_sector_of_dmreq(cc, dmreq)));
17964e4cbee9SChristoph Hellwig 		io->error = BLK_STS_PROTECTION;
1797ef43aa38SMilan Broz 	} else if (error < 0)
17984e4cbee9SChristoph Hellwig 		io->error = BLK_STS_IOERR;
179972c6e7afSMikulas Patocka 
1800298a9fa0SMikulas Patocka 	crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
180195497a96SMilan Broz 
180240b6229bSMikulas Patocka 	if (!atomic_dec_and_test(&ctx->cc_pending))
1803c0403ec0SRabin Vincent 		return;
180495497a96SMilan Broz 
180595497a96SMilan Broz 	if (bio_data_dir(io->base_bio) == READ)
180672c6e7afSMikulas Patocka 		kcryptd_crypt_read_done(io);
180795497a96SMilan Broz 	else
180872c6e7afSMikulas Patocka 		kcryptd_crypt_write_io_submit(io, 1);
180995497a96SMilan Broz }
181095497a96SMilan Broz 
18114e4eef64SMilan Broz static void kcryptd_crypt(struct work_struct *work)
18124e4eef64SMilan Broz {
18134e4eef64SMilan Broz 	struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
18144e4eef64SMilan Broz 
18154e4eef64SMilan Broz 	if (bio_data_dir(io->base_bio) == READ)
18164e4eef64SMilan Broz 		kcryptd_crypt_read_convert(io);
18174e4eef64SMilan Broz 	else
18184e4eef64SMilan Broz 		kcryptd_crypt_write_convert(io);
18198b004457SMilan Broz }
18208b004457SMilan Broz 
1821395b167cSAlasdair G Kergon static void kcryptd_queue_crypt(struct dm_crypt_io *io)
1822395b167cSAlasdair G Kergon {
182349a8a920SAlasdair G Kergon 	struct crypt_config *cc = io->cc;
1824395b167cSAlasdair G Kergon 
1825395b167cSAlasdair G Kergon 	INIT_WORK(&io->work, kcryptd_crypt);
1826395b167cSAlasdair G Kergon 	queue_work(cc->crypt_queue, &io->work);
1827395b167cSAlasdair G Kergon }
1828395b167cSAlasdair G Kergon 
1829ef43aa38SMilan Broz static void crypt_free_tfms_aead(struct crypt_config *cc)
18301da177e4SLinus Torvalds {
1831ef43aa38SMilan Broz 	if (!cc->cipher_tfm.tfms_aead)
1832ef43aa38SMilan Broz 		return;
18331da177e4SLinus Torvalds 
1834ef43aa38SMilan Broz 	if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
1835ef43aa38SMilan Broz 		crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
1836ef43aa38SMilan Broz 		cc->cipher_tfm.tfms_aead[0] = NULL;
18371da177e4SLinus Torvalds 	}
18381da177e4SLinus Torvalds 
1839ef43aa38SMilan Broz 	kfree(cc->cipher_tfm.tfms_aead);
1840ef43aa38SMilan Broz 	cc->cipher_tfm.tfms_aead = NULL;
1841ef43aa38SMilan Broz }
18421da177e4SLinus Torvalds 
1843ef43aa38SMilan Broz static void crypt_free_tfms_skcipher(struct crypt_config *cc)
1844d1f96423SMilan Broz {
1845d1f96423SMilan Broz 	unsigned i;
1846d1f96423SMilan Broz 
1847ef43aa38SMilan Broz 	if (!cc->cipher_tfm.tfms)
1848fd2d231fSMikulas Patocka 		return;
1849fd2d231fSMikulas Patocka 
1850d1f96423SMilan Broz 	for (i = 0; i < cc->tfms_count; i++)
1851ef43aa38SMilan Broz 		if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
1852ef43aa38SMilan Broz 			crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
1853ef43aa38SMilan Broz 			cc->cipher_tfm.tfms[i] = NULL;
1854d1f96423SMilan Broz 		}
1855d1f96423SMilan Broz 
1856ef43aa38SMilan Broz 	kfree(cc->cipher_tfm.tfms);
1857ef43aa38SMilan Broz 	cc->cipher_tfm.tfms = NULL;
18581da177e4SLinus Torvalds }
18591da177e4SLinus Torvalds 
18601da177e4SLinus Torvalds static void crypt_free_tfms(struct crypt_config *cc)
1861d1f96423SMilan Broz {
186233d2f09fSMilan Broz 	if (crypt_integrity_aead(cc))
1863ef43aa38SMilan Broz 		crypt_free_tfms_aead(cc);
1864ef43aa38SMilan Broz 	else
1865ef43aa38SMilan Broz 		crypt_free_tfms_skcipher(cc);
1866d1f96423SMilan Broz }
1867d1f96423SMilan Broz 
1868ef43aa38SMilan Broz static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
1869d1f96423SMilan Broz {
1870d1f96423SMilan Broz 	unsigned i;
1871d1f96423SMilan Broz 	int err;
1872d1f96423SMilan Broz 
18736396bb22SKees Cook 	cc->cipher_tfm.tfms = kcalloc(cc->tfms_count,
18746396bb22SKees Cook 				      sizeof(struct crypto_skcipher *),
18756396bb22SKees Cook 				      GFP_KERNEL);
1876ef43aa38SMilan Broz 	if (!cc->cipher_tfm.tfms)
1877fd2d231fSMikulas Patocka 		return -ENOMEM;
1878fd2d231fSMikulas Patocka 
1879d1f96423SMilan Broz 	for (i = 0; i < cc->tfms_count; i++) {
1880ef43aa38SMilan Broz 		cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0, 0);
1881ef43aa38SMilan Broz 		if (IS_ERR(cc->cipher_tfm.tfms[i])) {
1882ef43aa38SMilan Broz 			err = PTR_ERR(cc->cipher_tfm.tfms[i]);
1883fd2d231fSMikulas Patocka 			crypt_free_tfms(cc);
1884d1f96423SMilan Broz 			return err;
1885d1f96423SMilan Broz 		}
1886d1f96423SMilan Broz 	}
1887d1f96423SMilan Broz 
1888af331ebaSEric Biggers 	/*
1889af331ebaSEric Biggers 	 * dm-crypt performance can vary greatly depending on which crypto
1890af331ebaSEric Biggers 	 * algorithm implementation is used.  Help people debug performance
1891af331ebaSEric Biggers 	 * problems by logging the ->cra_driver_name.
1892af331ebaSEric Biggers 	 */
1893af331ebaSEric Biggers 	DMINFO("%s using implementation \"%s\"", ciphermode,
1894af331ebaSEric Biggers 	       crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
1895d1f96423SMilan Broz 	return 0;
1896d1f96423SMilan Broz }
1897d1f96423SMilan Broz 
1898ef43aa38SMilan Broz static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
1899ef43aa38SMilan Broz {
1900ef43aa38SMilan Broz 	int err;
1901ef43aa38SMilan Broz 
1902ef43aa38SMilan Broz 	cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
1903ef43aa38SMilan Broz 	if (!cc->cipher_tfm.tfms)
1904ef43aa38SMilan Broz 		return -ENOMEM;
1905ef43aa38SMilan Broz 
1906ef43aa38SMilan Broz 	cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0, 0);
1907ef43aa38SMilan Broz 	if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
1908ef43aa38SMilan Broz 		err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
1909ef43aa38SMilan Broz 		crypt_free_tfms(cc);
1910ef43aa38SMilan Broz 		return err;
1911ef43aa38SMilan Broz 	}
1912ef43aa38SMilan Broz 
1913af331ebaSEric Biggers 	DMINFO("%s using implementation \"%s\"", ciphermode,
1914af331ebaSEric Biggers 	       crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
1915ef43aa38SMilan Broz 	return 0;
1916ef43aa38SMilan Broz }
1917ef43aa38SMilan Broz 
1918ef43aa38SMilan Broz static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
1919ef43aa38SMilan Broz {
192033d2f09fSMilan Broz 	if (crypt_integrity_aead(cc))
1921ef43aa38SMilan Broz 		return crypt_alloc_tfms_aead(cc, ciphermode);
1922ef43aa38SMilan Broz 	else
1923ef43aa38SMilan Broz 		return crypt_alloc_tfms_skcipher(cc, ciphermode);
1924ef43aa38SMilan Broz }
1925ef43aa38SMilan Broz 
1926ef43aa38SMilan Broz static unsigned crypt_subkey_size(struct crypt_config *cc)
1927ef43aa38SMilan Broz {
1928ef43aa38SMilan Broz 	return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
1929ef43aa38SMilan Broz }
1930ef43aa38SMilan Broz 
1931ef43aa38SMilan Broz static unsigned crypt_authenckey_size(struct crypt_config *cc)
1932ef43aa38SMilan Broz {
1933ef43aa38SMilan Broz 	return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
1934ef43aa38SMilan Broz }
1935ef43aa38SMilan Broz 
1936ef43aa38SMilan Broz /*
1937ef43aa38SMilan Broz  * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
1938ef43aa38SMilan Broz  * the key must be for some reason in special format.
1939ef43aa38SMilan Broz  * This funcion converts cc->key to this special format.
1940ef43aa38SMilan Broz  */
1941ef43aa38SMilan Broz static void crypt_copy_authenckey(char *p, const void *key,
1942ef43aa38SMilan Broz 				  unsigned enckeylen, unsigned authkeylen)
1943ef43aa38SMilan Broz {
1944ef43aa38SMilan Broz 	struct crypto_authenc_key_param *param;
1945ef43aa38SMilan Broz 	struct rtattr *rta;
1946ef43aa38SMilan Broz 
1947ef43aa38SMilan Broz 	rta = (struct rtattr *)p;
1948ef43aa38SMilan Broz 	param = RTA_DATA(rta);
1949ef43aa38SMilan Broz 	param->enckeylen = cpu_to_be32(enckeylen);
1950ef43aa38SMilan Broz 	rta->rta_len = RTA_LENGTH(sizeof(*param));
1951ef43aa38SMilan Broz 	rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
1952ef43aa38SMilan Broz 	p += RTA_SPACE(sizeof(*param));
1953ef43aa38SMilan Broz 	memcpy(p, key + enckeylen, authkeylen);
1954ef43aa38SMilan Broz 	p += authkeylen;
1955ef43aa38SMilan Broz 	memcpy(p, key, enckeylen);
1956ef43aa38SMilan Broz }
1957ef43aa38SMilan Broz 
1958671ea6b4SMikulas Patocka static int crypt_setkey(struct crypt_config *cc)
1959c0297721SAndi Kleen {
1960da31a078SMilan Broz 	unsigned subkey_size;
1961fd2d231fSMikulas Patocka 	int err = 0, i, r;
1962c0297721SAndi Kleen 
1963da31a078SMilan Broz 	/* Ignore extra keys (which are used for IV etc) */
1964ef43aa38SMilan Broz 	subkey_size = crypt_subkey_size(cc);
1965da31a078SMilan Broz 
196627c70036SMilan Broz 	if (crypt_integrity_hmac(cc)) {
196727c70036SMilan Broz 		if (subkey_size < cc->key_mac_size)
196827c70036SMilan Broz 			return -EINVAL;
196927c70036SMilan Broz 
1970ef43aa38SMilan Broz 		crypt_copy_authenckey(cc->authenc_key, cc->key,
1971ef43aa38SMilan Broz 				      subkey_size - cc->key_mac_size,
1972ef43aa38SMilan Broz 				      cc->key_mac_size);
197327c70036SMilan Broz 	}
197427c70036SMilan Broz 
1975d1f96423SMilan Broz 	for (i = 0; i < cc->tfms_count; i++) {
197633d2f09fSMilan Broz 		if (crypt_integrity_hmac(cc))
197733d2f09fSMilan Broz 			r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
197833d2f09fSMilan Broz 				cc->authenc_key, crypt_authenckey_size(cc));
197933d2f09fSMilan Broz 		else if (crypt_integrity_aead(cc))
1980ef43aa38SMilan Broz 			r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
1981ef43aa38SMilan Broz 					       cc->key + (i * subkey_size),
1982ef43aa38SMilan Broz 					       subkey_size);
1983ef43aa38SMilan Broz 		else
1984ef43aa38SMilan Broz 			r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
1985fd2d231fSMikulas Patocka 						   cc->key + (i * subkey_size),
1986fd2d231fSMikulas Patocka 						   subkey_size);
1987c0297721SAndi Kleen 		if (r)
1988c0297721SAndi Kleen 			err = r;
1989c0297721SAndi Kleen 	}
1990c0297721SAndi Kleen 
1991ef43aa38SMilan Broz 	if (crypt_integrity_hmac(cc))
1992ef43aa38SMilan Broz 		memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
1993ef43aa38SMilan Broz 
1994c0297721SAndi Kleen 	return err;
1995c0297721SAndi Kleen }
1996c0297721SAndi Kleen 
1997c538f6ecSOndrej Kozina #ifdef CONFIG_KEYS
1998c538f6ecSOndrej Kozina 
1999027c431cSOndrej Kozina static bool contains_whitespace(const char *str)
2000027c431cSOndrej Kozina {
2001027c431cSOndrej Kozina 	while (*str)
2002027c431cSOndrej Kozina 		if (isspace(*str++))
2003027c431cSOndrej Kozina 			return true;
2004027c431cSOndrej Kozina 	return false;
2005027c431cSOndrej Kozina }
2006027c431cSOndrej Kozina 
2007c538f6ecSOndrej Kozina static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2008c538f6ecSOndrej Kozina {
2009c538f6ecSOndrej Kozina 	char *new_key_string, *key_desc;
2010c538f6ecSOndrej Kozina 	int ret;
2011c538f6ecSOndrej Kozina 	struct key *key;
2012c538f6ecSOndrej Kozina 	const struct user_key_payload *ukp;
2013c538f6ecSOndrej Kozina 
2014027c431cSOndrej Kozina 	/*
2015027c431cSOndrej Kozina 	 * Reject key_string with whitespace. dm core currently lacks code for
2016027c431cSOndrej Kozina 	 * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2017027c431cSOndrej Kozina 	 */
2018027c431cSOndrej Kozina 	if (contains_whitespace(key_string)) {
2019027c431cSOndrej Kozina 		DMERR("whitespace chars not allowed in key string");
2020027c431cSOndrej Kozina 		return -EINVAL;
2021027c431cSOndrej Kozina 	}
2022027c431cSOndrej Kozina 
2023c538f6ecSOndrej Kozina 	/* look for next ':' separating key_type from key_description */
2024c538f6ecSOndrej Kozina 	key_desc = strpbrk(key_string, ":");
2025c538f6ecSOndrej Kozina 	if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2026c538f6ecSOndrej Kozina 		return -EINVAL;
2027c538f6ecSOndrej Kozina 
2028c538f6ecSOndrej Kozina 	if (strncmp(key_string, "logon:", key_desc - key_string + 1) &&
2029c538f6ecSOndrej Kozina 	    strncmp(key_string, "user:", key_desc - key_string + 1))
2030c538f6ecSOndrej Kozina 		return -EINVAL;
2031c538f6ecSOndrej Kozina 
2032c538f6ecSOndrej Kozina 	new_key_string = kstrdup(key_string, GFP_KERNEL);
2033c538f6ecSOndrej Kozina 	if (!new_key_string)
2034c538f6ecSOndrej Kozina 		return -ENOMEM;
2035c538f6ecSOndrej Kozina 
2036c538f6ecSOndrej Kozina 	key = request_key(key_string[0] == 'l' ? &key_type_logon : &key_type_user,
2037c538f6ecSOndrej Kozina 			  key_desc + 1, NULL);
2038c538f6ecSOndrej Kozina 	if (IS_ERR(key)) {
2039c538f6ecSOndrej Kozina 		kzfree(new_key_string);
2040c538f6ecSOndrej Kozina 		return PTR_ERR(key);
2041c538f6ecSOndrej Kozina 	}
2042c538f6ecSOndrej Kozina 
2043f5b0cba8SOndrej Kozina 	down_read(&key->sem);
2044c538f6ecSOndrej Kozina 
20450837e49aSDavid Howells 	ukp = user_key_payload_locked(key);
2046c538f6ecSOndrej Kozina 	if (!ukp) {
2047f5b0cba8SOndrej Kozina 		up_read(&key->sem);
2048c538f6ecSOndrej Kozina 		key_put(key);
2049c538f6ecSOndrej Kozina 		kzfree(new_key_string);
2050c538f6ecSOndrej Kozina 		return -EKEYREVOKED;
2051c538f6ecSOndrej Kozina 	}
2052c538f6ecSOndrej Kozina 
2053c538f6ecSOndrej Kozina 	if (cc->key_size != ukp->datalen) {
2054f5b0cba8SOndrej Kozina 		up_read(&key->sem);
2055c538f6ecSOndrej Kozina 		key_put(key);
2056c538f6ecSOndrej Kozina 		kzfree(new_key_string);
2057c538f6ecSOndrej Kozina 		return -EINVAL;
2058c538f6ecSOndrej Kozina 	}
2059c538f6ecSOndrej Kozina 
2060c538f6ecSOndrej Kozina 	memcpy(cc->key, ukp->data, cc->key_size);
2061c538f6ecSOndrej Kozina 
2062f5b0cba8SOndrej Kozina 	up_read(&key->sem);
2063c538f6ecSOndrej Kozina 	key_put(key);
2064c538f6ecSOndrej Kozina 
2065c538f6ecSOndrej Kozina 	/* clear the flag since following operations may invalidate previously valid key */
2066c538f6ecSOndrej Kozina 	clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2067c538f6ecSOndrej Kozina 
2068c538f6ecSOndrej Kozina 	ret = crypt_setkey(cc);
2069c538f6ecSOndrej Kozina 
2070c538f6ecSOndrej Kozina 	if (!ret) {
2071c538f6ecSOndrej Kozina 		set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2072c538f6ecSOndrej Kozina 		kzfree(cc->key_string);
2073c538f6ecSOndrej Kozina 		cc->key_string = new_key_string;
2074c538f6ecSOndrej Kozina 	} else
2075c538f6ecSOndrej Kozina 		kzfree(new_key_string);
2076c538f6ecSOndrej Kozina 
2077c538f6ecSOndrej Kozina 	return ret;
2078c538f6ecSOndrej Kozina }
2079c538f6ecSOndrej Kozina 
2080c538f6ecSOndrej Kozina static int get_key_size(char **key_string)
2081c538f6ecSOndrej Kozina {
2082c538f6ecSOndrej Kozina 	char *colon, dummy;
2083c538f6ecSOndrej Kozina 	int ret;
2084c538f6ecSOndrej Kozina 
2085c538f6ecSOndrej Kozina 	if (*key_string[0] != ':')
2086c538f6ecSOndrej Kozina 		return strlen(*key_string) >> 1;
2087c538f6ecSOndrej Kozina 
2088c538f6ecSOndrej Kozina 	/* look for next ':' in key string */
2089c538f6ecSOndrej Kozina 	colon = strpbrk(*key_string + 1, ":");
2090c538f6ecSOndrej Kozina 	if (!colon)
2091c538f6ecSOndrej Kozina 		return -EINVAL;
2092c538f6ecSOndrej Kozina 
2093c538f6ecSOndrej Kozina 	if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2094c538f6ecSOndrej Kozina 		return -EINVAL;
2095c538f6ecSOndrej Kozina 
2096c538f6ecSOndrej Kozina 	*key_string = colon;
2097c538f6ecSOndrej Kozina 
2098c538f6ecSOndrej Kozina 	/* remaining key string should be :<logon|user>:<key_desc> */
2099c538f6ecSOndrej Kozina 
2100c538f6ecSOndrej Kozina 	return ret;
2101c538f6ecSOndrej Kozina }
2102c538f6ecSOndrej Kozina 
2103c538f6ecSOndrej Kozina #else
2104c538f6ecSOndrej Kozina 
2105c538f6ecSOndrej Kozina static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2106c538f6ecSOndrej Kozina {
2107c538f6ecSOndrej Kozina 	return -EINVAL;
2108c538f6ecSOndrej Kozina }
2109c538f6ecSOndrej Kozina 
2110c538f6ecSOndrej Kozina static int get_key_size(char **key_string)
2111c538f6ecSOndrej Kozina {
2112c538f6ecSOndrej Kozina 	return (*key_string[0] == ':') ? -EINVAL : strlen(*key_string) >> 1;
2113c538f6ecSOndrej Kozina }
2114c538f6ecSOndrej Kozina 
2115c538f6ecSOndrej Kozina #endif
2116c538f6ecSOndrej Kozina 
2117e48d4bbfSMilan Broz static int crypt_set_key(struct crypt_config *cc, char *key)
2118e48d4bbfSMilan Broz {
2119de8be5acSMilan Broz 	int r = -EINVAL;
2120de8be5acSMilan Broz 	int key_string_len = strlen(key);
2121de8be5acSMilan Broz 
212269a8cfcdSMilan Broz 	/* Hyphen (which gives a key_size of zero) means there is no key. */
212369a8cfcdSMilan Broz 	if (!cc->key_size && strcmp(key, "-"))
2124de8be5acSMilan Broz 		goto out;
2125e48d4bbfSMilan Broz 
2126c538f6ecSOndrej Kozina 	/* ':' means the key is in kernel keyring, short-circuit normal key processing */
2127c538f6ecSOndrej Kozina 	if (key[0] == ':') {
2128c538f6ecSOndrej Kozina 		r = crypt_set_keyring_key(cc, key + 1);
2129c538f6ecSOndrej Kozina 		goto out;
2130c538f6ecSOndrej Kozina 	}
2131c538f6ecSOndrej Kozina 
2132265e9098SOndrej Kozina 	/* clear the flag since following operations may invalidate previously valid key */
2133265e9098SOndrej Kozina 	clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2134265e9098SOndrej Kozina 
2135c538f6ecSOndrej Kozina 	/* wipe references to any kernel keyring key */
2136c538f6ecSOndrej Kozina 	kzfree(cc->key_string);
2137c538f6ecSOndrej Kozina 	cc->key_string = NULL;
2138c538f6ecSOndrej Kozina 
2139e944e03eSAndy Shevchenko 	/* Decode key from its hex representation. */
2140e944e03eSAndy Shevchenko 	if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
2141de8be5acSMilan Broz 		goto out;
2142e48d4bbfSMilan Broz 
2143671ea6b4SMikulas Patocka 	r = crypt_setkey(cc);
2144265e9098SOndrej Kozina 	if (!r)
2145e48d4bbfSMilan Broz 		set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2146e48d4bbfSMilan Broz 
2147de8be5acSMilan Broz out:
2148de8be5acSMilan Broz 	/* Hex key string not needed after here, so wipe it. */
2149de8be5acSMilan Broz 	memset(key, '0', key_string_len);
2150de8be5acSMilan Broz 
2151de8be5acSMilan Broz 	return r;
2152e48d4bbfSMilan Broz }
2153e48d4bbfSMilan Broz 
2154e48d4bbfSMilan Broz static int crypt_wipe_key(struct crypt_config *cc)
2155e48d4bbfSMilan Broz {
2156c82feeecSOndrej Kozina 	int r;
2157c82feeecSOndrej Kozina 
2158e48d4bbfSMilan Broz 	clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2159c82feeecSOndrej Kozina 	get_random_bytes(&cc->key, cc->key_size);
2160c538f6ecSOndrej Kozina 	kzfree(cc->key_string);
2161c538f6ecSOndrej Kozina 	cc->key_string = NULL;
2162c82feeecSOndrej Kozina 	r = crypt_setkey(cc);
2163c82feeecSOndrej Kozina 	memset(&cc->key, 0, cc->key_size * sizeof(u8));
2164c0297721SAndi Kleen 
2165c82feeecSOndrej Kozina 	return r;
2166e48d4bbfSMilan Broz }
2167e48d4bbfSMilan Broz 
21685059353dSMikulas Patocka static void crypt_calculate_pages_per_client(void)
21695059353dSMikulas Patocka {
2170ca79b0c2SArun KS 	unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
21715059353dSMikulas Patocka 
21725059353dSMikulas Patocka 	if (!dm_crypt_clients_n)
21735059353dSMikulas Patocka 		return;
21745059353dSMikulas Patocka 
21755059353dSMikulas Patocka 	pages /= dm_crypt_clients_n;
21765059353dSMikulas Patocka 	if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
21775059353dSMikulas Patocka 		pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
21785059353dSMikulas Patocka 	dm_crypt_pages_per_client = pages;
21795059353dSMikulas Patocka }
21805059353dSMikulas Patocka 
21815059353dSMikulas Patocka static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
21825059353dSMikulas Patocka {
21835059353dSMikulas Patocka 	struct crypt_config *cc = pool_data;
21845059353dSMikulas Patocka 	struct page *page;
21855059353dSMikulas Patocka 
21865059353dSMikulas Patocka 	if (unlikely(percpu_counter_compare(&cc->n_allocated_pages, dm_crypt_pages_per_client) >= 0) &&
21875059353dSMikulas Patocka 	    likely(gfp_mask & __GFP_NORETRY))
21885059353dSMikulas Patocka 		return NULL;
21895059353dSMikulas Patocka 
21905059353dSMikulas Patocka 	page = alloc_page(gfp_mask);
21915059353dSMikulas Patocka 	if (likely(page != NULL))
21925059353dSMikulas Patocka 		percpu_counter_add(&cc->n_allocated_pages, 1);
21935059353dSMikulas Patocka 
21945059353dSMikulas Patocka 	return page;
21955059353dSMikulas Patocka }
21965059353dSMikulas Patocka 
21975059353dSMikulas Patocka static void crypt_page_free(void *page, void *pool_data)
21985059353dSMikulas Patocka {
21995059353dSMikulas Patocka 	struct crypt_config *cc = pool_data;
22005059353dSMikulas Patocka 
22015059353dSMikulas Patocka 	__free_page(page);
22025059353dSMikulas Patocka 	percpu_counter_sub(&cc->n_allocated_pages, 1);
22035059353dSMikulas Patocka }
22045059353dSMikulas Patocka 
220528513fccSMilan Broz static void crypt_dtr(struct dm_target *ti)
220628513fccSMilan Broz {
220728513fccSMilan Broz 	struct crypt_config *cc = ti->private;
220828513fccSMilan Broz 
220928513fccSMilan Broz 	ti->private = NULL;
221028513fccSMilan Broz 
221128513fccSMilan Broz 	if (!cc)
221228513fccSMilan Broz 		return;
221328513fccSMilan Broz 
2214f659b100SRabin Vincent 	if (cc->write_thread)
2215dc267621SMikulas Patocka 		kthread_stop(cc->write_thread);
2216dc267621SMikulas Patocka 
221728513fccSMilan Broz 	if (cc->io_queue)
221828513fccSMilan Broz 		destroy_workqueue(cc->io_queue);
221928513fccSMilan Broz 	if (cc->crypt_queue)
222028513fccSMilan Broz 		destroy_workqueue(cc->crypt_queue);
222128513fccSMilan Broz 
2222fd2d231fSMikulas Patocka 	crypt_free_tfms(cc);
2223fd2d231fSMikulas Patocka 
22246f1c819cSKent Overstreet 	bioset_exit(&cc->bs);
222528513fccSMilan Broz 
22266f1c819cSKent Overstreet 	mempool_exit(&cc->page_pool);
22276f1c819cSKent Overstreet 	mempool_exit(&cc->req_pool);
22286f1c819cSKent Overstreet 	mempool_exit(&cc->tag_pool);
22296f1c819cSKent Overstreet 
2230d00a11dfSKent Overstreet 	WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
2231d00a11dfSKent Overstreet 	percpu_counter_destroy(&cc->n_allocated_pages);
2232d00a11dfSKent Overstreet 
223328513fccSMilan Broz 	if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
223428513fccSMilan Broz 		cc->iv_gen_ops->dtr(cc);
223528513fccSMilan Broz 
223628513fccSMilan Broz 	if (cc->dev)
223728513fccSMilan Broz 		dm_put_device(ti, cc->dev);
223828513fccSMilan Broz 
22395ebaee6dSMilan Broz 	kzfree(cc->cipher);
22407dbcd137SMilan Broz 	kzfree(cc->cipher_string);
2241c538f6ecSOndrej Kozina 	kzfree(cc->key_string);
2242ef43aa38SMilan Broz 	kzfree(cc->cipher_auth);
2243ef43aa38SMilan Broz 	kzfree(cc->authenc_key);
224428513fccSMilan Broz 
2245d5ffebddSMike Snitzer 	mutex_destroy(&cc->bio_alloc_lock);
2246d5ffebddSMike Snitzer 
224728513fccSMilan Broz 	/* Must zero key material before freeing */
224828513fccSMilan Broz 	kzfree(cc);
22495059353dSMikulas Patocka 
22505059353dSMikulas Patocka 	spin_lock(&dm_crypt_clients_lock);
22515059353dSMikulas Patocka 	WARN_ON(!dm_crypt_clients_n);
22525059353dSMikulas Patocka 	dm_crypt_clients_n--;
22535059353dSMikulas Patocka 	crypt_calculate_pages_per_client();
22545059353dSMikulas Patocka 	spin_unlock(&dm_crypt_clients_lock);
225528513fccSMilan Broz }
225628513fccSMilan Broz 
2257e889f97aSMilan Broz static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
22581da177e4SLinus Torvalds {
22595ebaee6dSMilan Broz 	struct crypt_config *cc = ti->private;
22601da177e4SLinus Torvalds 
226133d2f09fSMilan Broz 	if (crypt_integrity_aead(cc))
2262e889f97aSMilan Broz 		cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2263e889f97aSMilan Broz 	else
2264bbdb23b5SHerbert Xu 		cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2265e889f97aSMilan Broz 
22665ebaee6dSMilan Broz 	if (cc->iv_size)
22675ebaee6dSMilan Broz 		/* at least a 64 bit sector number should fit in our buffer */
22685ebaee6dSMilan Broz 		cc->iv_size = max(cc->iv_size,
22695ebaee6dSMilan Broz 				  (unsigned int)(sizeof(u64) / sizeof(u8)));
22705ebaee6dSMilan Broz 	else if (ivmode) {
22715ebaee6dSMilan Broz 		DMWARN("Selected cipher does not support IVs");
22725ebaee6dSMilan Broz 		ivmode = NULL;
22735ebaee6dSMilan Broz 	}
22745ebaee6dSMilan Broz 
22755ebaee6dSMilan Broz 	/* Choose ivmode, see comments at iv code. */
22761da177e4SLinus Torvalds 	if (ivmode == NULL)
22771da177e4SLinus Torvalds 		cc->iv_gen_ops = NULL;
22781da177e4SLinus Torvalds 	else if (strcmp(ivmode, "plain") == 0)
22791da177e4SLinus Torvalds 		cc->iv_gen_ops = &crypt_iv_plain_ops;
228061afef61SMilan Broz 	else if (strcmp(ivmode, "plain64") == 0)
228161afef61SMilan Broz 		cc->iv_gen_ops = &crypt_iv_plain64_ops;
22827e3fd855SMilan Broz 	else if (strcmp(ivmode, "plain64be") == 0)
22837e3fd855SMilan Broz 		cc->iv_gen_ops = &crypt_iv_plain64be_ops;
22841da177e4SLinus Torvalds 	else if (strcmp(ivmode, "essiv") == 0)
22851da177e4SLinus Torvalds 		cc->iv_gen_ops = &crypt_iv_essiv_ops;
228648527fa7SRik Snel 	else if (strcmp(ivmode, "benbi") == 0)
228748527fa7SRik Snel 		cc->iv_gen_ops = &crypt_iv_benbi_ops;
228846b47730SLudwig Nussel 	else if (strcmp(ivmode, "null") == 0)
228946b47730SLudwig Nussel 		cc->iv_gen_ops = &crypt_iv_null_ops;
229034745785SMilan Broz 	else if (strcmp(ivmode, "lmk") == 0) {
229134745785SMilan Broz 		cc->iv_gen_ops = &crypt_iv_lmk_ops;
2292ed04d981SMilan Broz 		/*
2293ed04d981SMilan Broz 		 * Version 2 and 3 is recognised according
229434745785SMilan Broz 		 * to length of provided multi-key string.
229534745785SMilan Broz 		 * If present (version 3), last key is used as IV seed.
2296ed04d981SMilan Broz 		 * All keys (including IV seed) are always the same size.
229734745785SMilan Broz 		 */
2298da31a078SMilan Broz 		if (cc->key_size % cc->key_parts) {
229934745785SMilan Broz 			cc->key_parts++;
2300da31a078SMilan Broz 			cc->key_extra_size = cc->key_size / cc->key_parts;
2301da31a078SMilan Broz 		}
2302ed04d981SMilan Broz 	} else if (strcmp(ivmode, "tcw") == 0) {
2303ed04d981SMilan Broz 		cc->iv_gen_ops = &crypt_iv_tcw_ops;
2304ed04d981SMilan Broz 		cc->key_parts += 2; /* IV + whitening */
2305ed04d981SMilan Broz 		cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2306e889f97aSMilan Broz 	} else if (strcmp(ivmode, "random") == 0) {
2307e889f97aSMilan Broz 		cc->iv_gen_ops = &crypt_iv_random_ops;
2308e889f97aSMilan Broz 		/* Need storage space in integrity fields. */
2309e889f97aSMilan Broz 		cc->integrity_iv_size = cc->iv_size;
231034745785SMilan Broz 	} else {
231172d94861SAlasdair G Kergon 		ti->error = "Invalid IV mode";
2312e889f97aSMilan Broz 		return -EINVAL;
23131da177e4SLinus Torvalds 	}
23141da177e4SLinus Torvalds 
2315e889f97aSMilan Broz 	return 0;
2316e889f97aSMilan Broz }
2317e889f97aSMilan Broz 
231833d2f09fSMilan Broz /*
231933d2f09fSMilan Broz  * Workaround to parse cipher algorithm from crypto API spec.
232033d2f09fSMilan Broz  * The cc->cipher is currently used only in ESSIV.
232133d2f09fSMilan Broz  * This should be probably done by crypto-api calls (once available...)
232233d2f09fSMilan Broz  */
232333d2f09fSMilan Broz static int crypt_ctr_blkdev_cipher(struct crypt_config *cc)
232433d2f09fSMilan Broz {
232533d2f09fSMilan Broz 	const char *alg_name = NULL;
232633d2f09fSMilan Broz 	char *start, *end;
232733d2f09fSMilan Broz 
232833d2f09fSMilan Broz 	if (crypt_integrity_aead(cc)) {
232933d2f09fSMilan Broz 		alg_name = crypto_tfm_alg_name(crypto_aead_tfm(any_tfm_aead(cc)));
233033d2f09fSMilan Broz 		if (!alg_name)
233133d2f09fSMilan Broz 			return -EINVAL;
233233d2f09fSMilan Broz 		if (crypt_integrity_hmac(cc)) {
233333d2f09fSMilan Broz 			alg_name = strchr(alg_name, ',');
233433d2f09fSMilan Broz 			if (!alg_name)
233533d2f09fSMilan Broz 				return -EINVAL;
233633d2f09fSMilan Broz 		}
233733d2f09fSMilan Broz 		alg_name++;
233833d2f09fSMilan Broz 	} else {
233933d2f09fSMilan Broz 		alg_name = crypto_tfm_alg_name(crypto_skcipher_tfm(any_tfm(cc)));
234033d2f09fSMilan Broz 		if (!alg_name)
234133d2f09fSMilan Broz 			return -EINVAL;
234233d2f09fSMilan Broz 	}
234333d2f09fSMilan Broz 
234433d2f09fSMilan Broz 	start = strchr(alg_name, '(');
234533d2f09fSMilan Broz 	end = strchr(alg_name, ')');
234633d2f09fSMilan Broz 
234733d2f09fSMilan Broz 	if (!start && !end) {
234833d2f09fSMilan Broz 		cc->cipher = kstrdup(alg_name, GFP_KERNEL);
234933d2f09fSMilan Broz 		return cc->cipher ? 0 : -ENOMEM;
235033d2f09fSMilan Broz 	}
235133d2f09fSMilan Broz 
235233d2f09fSMilan Broz 	if (!start || !end || ++start >= end)
235333d2f09fSMilan Broz 		return -EINVAL;
235433d2f09fSMilan Broz 
235533d2f09fSMilan Broz 	cc->cipher = kzalloc(end - start + 1, GFP_KERNEL);
235633d2f09fSMilan Broz 	if (!cc->cipher)
235733d2f09fSMilan Broz 		return -ENOMEM;
235833d2f09fSMilan Broz 
235933d2f09fSMilan Broz 	strncpy(cc->cipher, start, end - start);
236033d2f09fSMilan Broz 
236133d2f09fSMilan Broz 	return 0;
236233d2f09fSMilan Broz }
236333d2f09fSMilan Broz 
236433d2f09fSMilan Broz /*
236533d2f09fSMilan Broz  * Workaround to parse HMAC algorithm from AEAD crypto API spec.
236633d2f09fSMilan Broz  * The HMAC is needed to calculate tag size (HMAC digest size).
236733d2f09fSMilan Broz  * This should be probably done by crypto-api calls (once available...)
236833d2f09fSMilan Broz  */
236933d2f09fSMilan Broz static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
237033d2f09fSMilan Broz {
237133d2f09fSMilan Broz 	char *start, *end, *mac_alg = NULL;
237233d2f09fSMilan Broz 	struct crypto_ahash *mac;
237333d2f09fSMilan Broz 
237433d2f09fSMilan Broz 	if (!strstarts(cipher_api, "authenc("))
237533d2f09fSMilan Broz 		return 0;
237633d2f09fSMilan Broz 
237733d2f09fSMilan Broz 	start = strchr(cipher_api, '(');
237833d2f09fSMilan Broz 	end = strchr(cipher_api, ',');
237933d2f09fSMilan Broz 	if (!start || !end || ++start > end)
238033d2f09fSMilan Broz 		return -EINVAL;
238133d2f09fSMilan Broz 
238233d2f09fSMilan Broz 	mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
238333d2f09fSMilan Broz 	if (!mac_alg)
238433d2f09fSMilan Broz 		return -ENOMEM;
238533d2f09fSMilan Broz 	strncpy(mac_alg, start, end - start);
238633d2f09fSMilan Broz 
238733d2f09fSMilan Broz 	mac = crypto_alloc_ahash(mac_alg, 0, 0);
238833d2f09fSMilan Broz 	kfree(mac_alg);
238933d2f09fSMilan Broz 
239033d2f09fSMilan Broz 	if (IS_ERR(mac))
239133d2f09fSMilan Broz 		return PTR_ERR(mac);
239233d2f09fSMilan Broz 
239333d2f09fSMilan Broz 	cc->key_mac_size = crypto_ahash_digestsize(mac);
239433d2f09fSMilan Broz 	crypto_free_ahash(mac);
239533d2f09fSMilan Broz 
239633d2f09fSMilan Broz 	cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
239733d2f09fSMilan Broz 	if (!cc->authenc_key)
239833d2f09fSMilan Broz 		return -ENOMEM;
239933d2f09fSMilan Broz 
240033d2f09fSMilan Broz 	return 0;
240133d2f09fSMilan Broz }
240233d2f09fSMilan Broz 
240333d2f09fSMilan Broz static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
240433d2f09fSMilan Broz 				char **ivmode, char **ivopts)
24051da177e4SLinus Torvalds {
24065ebaee6dSMilan Broz 	struct crypt_config *cc = ti->private;
240733d2f09fSMilan Broz 	char *tmp, *cipher_api;
240833d2f09fSMilan Broz 	int ret = -EINVAL;
240933d2f09fSMilan Broz 
241033d2f09fSMilan Broz 	cc->tfms_count = 1;
241133d2f09fSMilan Broz 
241233d2f09fSMilan Broz 	/*
241333d2f09fSMilan Broz 	 * New format (capi: prefix)
241433d2f09fSMilan Broz 	 * capi:cipher_api_spec-iv:ivopts
241533d2f09fSMilan Broz 	 */
241633d2f09fSMilan Broz 	tmp = &cipher_in[strlen("capi:")];
24171856b9f7SMilan Broz 
24181856b9f7SMilan Broz 	/* Separate IV options if present, it can contain another '-' in hash name */
24191856b9f7SMilan Broz 	*ivopts = strrchr(tmp, ':');
24201856b9f7SMilan Broz 	if (*ivopts) {
24211856b9f7SMilan Broz 		**ivopts = '\0';
24221856b9f7SMilan Broz 		(*ivopts)++;
24231856b9f7SMilan Broz 	}
24241856b9f7SMilan Broz 	/* Parse IV mode */
24251856b9f7SMilan Broz 	*ivmode = strrchr(tmp, '-');
24261856b9f7SMilan Broz 	if (*ivmode) {
24271856b9f7SMilan Broz 		**ivmode = '\0';
24281856b9f7SMilan Broz 		(*ivmode)++;
24291856b9f7SMilan Broz 	}
24301856b9f7SMilan Broz 	/* The rest is crypto API spec */
24311856b9f7SMilan Broz 	cipher_api = tmp;
243233d2f09fSMilan Broz 
243333d2f09fSMilan Broz 	if (*ivmode && !strcmp(*ivmode, "lmk"))
243433d2f09fSMilan Broz 		cc->tfms_count = 64;
243533d2f09fSMilan Broz 
243633d2f09fSMilan Broz 	cc->key_parts = cc->tfms_count;
243733d2f09fSMilan Broz 
243833d2f09fSMilan Broz 	/* Allocate cipher */
243933d2f09fSMilan Broz 	ret = crypt_alloc_tfms(cc, cipher_api);
244033d2f09fSMilan Broz 	if (ret < 0) {
244133d2f09fSMilan Broz 		ti->error = "Error allocating crypto tfm";
244233d2f09fSMilan Broz 		return ret;
244333d2f09fSMilan Broz 	}
244433d2f09fSMilan Broz 
244533d2f09fSMilan Broz 	/* Alloc AEAD, can be used only in new format. */
244633d2f09fSMilan Broz 	if (crypt_integrity_aead(cc)) {
244733d2f09fSMilan Broz 		ret = crypt_ctr_auth_cipher(cc, cipher_api);
244833d2f09fSMilan Broz 		if (ret < 0) {
244933d2f09fSMilan Broz 			ti->error = "Invalid AEAD cipher spec";
245033d2f09fSMilan Broz 			return -ENOMEM;
245133d2f09fSMilan Broz 		}
245233d2f09fSMilan Broz 		cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
245333d2f09fSMilan Broz 	} else
245433d2f09fSMilan Broz 		cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
245533d2f09fSMilan Broz 
245633d2f09fSMilan Broz 	ret = crypt_ctr_blkdev_cipher(cc);
245733d2f09fSMilan Broz 	if (ret < 0) {
245833d2f09fSMilan Broz 		ti->error = "Cannot allocate cipher string";
245933d2f09fSMilan Broz 		return -ENOMEM;
246033d2f09fSMilan Broz 	}
246133d2f09fSMilan Broz 
246233d2f09fSMilan Broz 	return 0;
246333d2f09fSMilan Broz }
246433d2f09fSMilan Broz 
246533d2f09fSMilan Broz static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
246633d2f09fSMilan Broz 				char **ivmode, char **ivopts)
246733d2f09fSMilan Broz {
246833d2f09fSMilan Broz 	struct crypt_config *cc = ti->private;
246933d2f09fSMilan Broz 	char *tmp, *cipher, *chainmode, *keycount;
24705ebaee6dSMilan Broz 	char *cipher_api = NULL;
24715ebaee6dSMilan Broz 	int ret = -EINVAL;
24725ebaee6dSMilan Broz 	char dummy;
24735ebaee6dSMilan Broz 
247433d2f09fSMilan Broz 	if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
24755ebaee6dSMilan Broz 		ti->error = "Bad cipher specification";
24765ebaee6dSMilan Broz 		return -EINVAL;
24775ebaee6dSMilan Broz 	}
24785ebaee6dSMilan Broz 
24791da177e4SLinus Torvalds 	/*
24805ebaee6dSMilan Broz 	 * Legacy dm-crypt cipher specification
24815ebaee6dSMilan Broz 	 * cipher[:keycount]-mode-iv:ivopts
24825ebaee6dSMilan Broz 	 */
24835ebaee6dSMilan Broz 	tmp = cipher_in;
24845ebaee6dSMilan Broz 	keycount = strsep(&tmp, "-");
24855ebaee6dSMilan Broz 	cipher = strsep(&keycount, ":");
24865ebaee6dSMilan Broz 
248769a8cfcdSMilan Broz 	if (!keycount)
24885ebaee6dSMilan Broz 		cc->tfms_count = 1;
24895ebaee6dSMilan Broz 	else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
24905ebaee6dSMilan Broz 		 !is_power_of_2(cc->tfms_count)) {
24915ebaee6dSMilan Broz 		ti->error = "Bad cipher key count specification";
24925ebaee6dSMilan Broz 		return -EINVAL;
24935ebaee6dSMilan Broz 	}
249428513fccSMilan Broz 	cc->key_parts = cc->tfms_count;
24951da177e4SLinus Torvalds 
249672d94861SAlasdair G Kergon 	cc->cipher = kstrdup(cipher, GFP_KERNEL);
249728513fccSMilan Broz 	if (!cc->cipher)
24981da177e4SLinus Torvalds 		goto bad_mem;
24991da177e4SLinus Torvalds 
2500ddd42edfSMilan Broz 	chainmode = strsep(&tmp, "-");
25011856b9f7SMilan Broz 	*ivmode = strsep(&tmp, ":");
25021856b9f7SMilan Broz 	*ivopts = tmp;
2503ddd42edfSMilan Broz 
2504ddd42edfSMilan Broz 	/*
2505ddd42edfSMilan Broz 	 * For compatibility with the original dm-crypt mapping format, if
2506ddd42edfSMilan Broz 	 * only the cipher name is supplied, use cbc-plain.
250728513fccSMilan Broz 	 */
250833d2f09fSMilan Broz 	if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
2509cabf08e4SMilan Broz 		chainmode = "cbc";
251033d2f09fSMilan Broz 		*ivmode = "plain";
2511cabf08e4SMilan Broz 	}
2512cabf08e4SMilan Broz 
251333d2f09fSMilan Broz 	if (strcmp(chainmode, "ecb") && !*ivmode) {
2514c0297721SAndi Kleen 		ti->error = "IV mechanism required";
2515c0297721SAndi Kleen 		return -EINVAL;
2516c0297721SAndi Kleen 	}
2517c0297721SAndi Kleen 
2518cabf08e4SMilan Broz 	cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
25199934a8beSMilan Broz 	if (!cipher_api)
252028513fccSMilan Broz 		goto bad_mem;
25219934a8beSMilan Broz 
25229934a8beSMilan Broz 	ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2523647c7db1SMikulas Patocka 		       "%s(%s)", chainmode, cipher);
25241da177e4SLinus Torvalds 	if (ret < 0) {
25251da177e4SLinus Torvalds 		kfree(cipher_api);
252628513fccSMilan Broz 		goto bad_mem;
252728513fccSMilan Broz 	}
252828513fccSMilan Broz 
25291da177e4SLinus Torvalds 	/* Allocate cipher */
25301da177e4SLinus Torvalds 	ret = crypt_alloc_tfms(cc, cipher_api);
25311da177e4SLinus Torvalds 	if (ret < 0) {
25321da177e4SLinus Torvalds 		ti->error = "Error allocating crypto tfm";
253333d2f09fSMilan Broz 		kfree(cipher_api);
253433d2f09fSMilan Broz 		return ret;
2535028867acSAlasdair G Kergon 	}
2536bd86e320SJeffy Chen 	kfree(cipher_api);
2537647c7db1SMikulas Patocka 
253833d2f09fSMilan Broz 	return 0;
253933d2f09fSMilan Broz bad_mem:
254033d2f09fSMilan Broz 	ti->error = "Cannot allocate cipher strings";
254133d2f09fSMilan Broz 	return -ENOMEM;
254233d2f09fSMilan Broz }
254333d2f09fSMilan Broz 
254433d2f09fSMilan Broz static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
254533d2f09fSMilan Broz {
254633d2f09fSMilan Broz 	struct crypt_config *cc = ti->private;
254733d2f09fSMilan Broz 	char *ivmode = NULL, *ivopts = NULL;
254833d2f09fSMilan Broz 	int ret;
254933d2f09fSMilan Broz 
255033d2f09fSMilan Broz 	cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
255133d2f09fSMilan Broz 	if (!cc->cipher_string) {
255233d2f09fSMilan Broz 		ti->error = "Cannot allocate cipher strings";
255333d2f09fSMilan Broz 		return -ENOMEM;
255433d2f09fSMilan Broz 	}
255533d2f09fSMilan Broz 
255633d2f09fSMilan Broz 	if (strstarts(cipher_in, "capi:"))
255733d2f09fSMilan Broz 		ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
255833d2f09fSMilan Broz 	else
255933d2f09fSMilan Broz 		ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
256033d2f09fSMilan Broz 	if (ret)
256133d2f09fSMilan Broz 		return ret;
256233d2f09fSMilan Broz 
2563647c7db1SMikulas Patocka 	/* Initialize IV */
2564e889f97aSMilan Broz 	ret = crypt_ctr_ivmode(ti, ivmode);
2565e889f97aSMilan Broz 	if (ret < 0)
256633d2f09fSMilan Broz 		return ret;
25671da177e4SLinus Torvalds 
2568da31a078SMilan Broz 	/* Initialize and set key */
2569da31a078SMilan Broz 	ret = crypt_set_key(cc, key);
2570da31a078SMilan Broz 	if (ret < 0) {
2571da31a078SMilan Broz 		ti->error = "Error decoding and setting key";
257233d2f09fSMilan Broz 		return ret;
2573da31a078SMilan Broz 	}
2574da31a078SMilan Broz 
25751da177e4SLinus Torvalds 	/* Allocate IV */
25761da177e4SLinus Torvalds 	if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
25771da177e4SLinus Torvalds 		ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
25781da177e4SLinus Torvalds 		if (ret < 0) {
25791da177e4SLinus Torvalds 			ti->error = "Error creating IV";
258033d2f09fSMilan Broz 			return ret;
25811da177e4SLinus Torvalds 		}
25821da177e4SLinus Torvalds 	}
25831da177e4SLinus Torvalds 
25841da177e4SLinus Torvalds 	/* Initialize IV (set keys for ESSIV etc) */
25851da177e4SLinus Torvalds 	if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
25861da177e4SLinus Torvalds 		ret = cc->iv_gen_ops->init(cc);
25871da177e4SLinus Torvalds 		if (ret < 0) {
25881da177e4SLinus Torvalds 			ti->error = "Error initialising IV";
25891da177e4SLinus Torvalds 			return ret;
25901da177e4SLinus Torvalds 		}
25911da177e4SLinus Torvalds 	}
25921da177e4SLinus Torvalds 
2593dc94902bSOndrej Kozina 	/* wipe the kernel key payload copy */
2594dc94902bSOndrej Kozina 	if (cc->key_string)
2595dc94902bSOndrej Kozina 		memset(cc->key, 0, cc->key_size * sizeof(u8));
2596dc94902bSOndrej Kozina 
259733d2f09fSMilan Broz 	return ret;
25981da177e4SLinus Torvalds }
25991da177e4SLinus Torvalds 
2600ef43aa38SMilan Broz static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
2601ef43aa38SMilan Broz {
2602ef43aa38SMilan Broz 	struct crypt_config *cc = ti->private;
2603ef43aa38SMilan Broz 	struct dm_arg_set as;
26045916a22bSEric Biggers 	static const struct dm_arg _args[] = {
26058f0009a2SMilan Broz 		{0, 6, "Invalid number of feature args"},
2606ef43aa38SMilan Broz 	};
2607ef43aa38SMilan Broz 	unsigned int opt_params, val;
2608ef43aa38SMilan Broz 	const char *opt_string, *sval;
26098f0009a2SMilan Broz 	char dummy;
2610ef43aa38SMilan Broz 	int ret;
2611ef43aa38SMilan Broz 
2612ef43aa38SMilan Broz 	/* Optional parameters */
2613ef43aa38SMilan Broz 	as.argc = argc;
2614ef43aa38SMilan Broz 	as.argv = argv;
2615ef43aa38SMilan Broz 
2616ef43aa38SMilan Broz 	ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
2617ef43aa38SMilan Broz 	if (ret)
26181da177e4SLinus Torvalds 		return ret;
26191da177e4SLinus Torvalds 
2620ef43aa38SMilan Broz 	while (opt_params--) {
2621ef43aa38SMilan Broz 		opt_string = dm_shift_arg(&as);
2622ef43aa38SMilan Broz 		if (!opt_string) {
2623ef43aa38SMilan Broz 			ti->error = "Not enough feature arguments";
2624ef43aa38SMilan Broz 			return -EINVAL;
2625ef43aa38SMilan Broz 		}
2626ef43aa38SMilan Broz 
2627ef43aa38SMilan Broz 		if (!strcasecmp(opt_string, "allow_discards"))
2628ef43aa38SMilan Broz 			ti->num_discard_bios = 1;
2629ef43aa38SMilan Broz 
2630ef43aa38SMilan Broz 		else if (!strcasecmp(opt_string, "same_cpu_crypt"))
2631ef43aa38SMilan Broz 			set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
2632ef43aa38SMilan Broz 
2633ef43aa38SMilan Broz 		else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
2634ef43aa38SMilan Broz 			set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
2635ef43aa38SMilan Broz 		else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
2636ef43aa38SMilan Broz 			if (val == 0 || val > MAX_TAG_SIZE) {
2637ef43aa38SMilan Broz 				ti->error = "Invalid integrity arguments";
2638ef43aa38SMilan Broz 				return -EINVAL;
2639ef43aa38SMilan Broz 			}
2640ef43aa38SMilan Broz 			cc->on_disk_tag_size = val;
2641ef43aa38SMilan Broz 			sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
2642ef43aa38SMilan Broz 			if (!strcasecmp(sval, "aead")) {
2643ef43aa38SMilan Broz 				set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
2644ef43aa38SMilan Broz 			} else  if (strcasecmp(sval, "none")) {
2645ef43aa38SMilan Broz 				ti->error = "Unknown integrity profile";
2646ef43aa38SMilan Broz 				return -EINVAL;
2647ef43aa38SMilan Broz 			}
2648ef43aa38SMilan Broz 
2649ef43aa38SMilan Broz 			cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
2650ef43aa38SMilan Broz 			if (!cc->cipher_auth)
26511da177e4SLinus Torvalds 				return -ENOMEM;
2652ff3af92bSMikulas Patocka 		} else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
26538f0009a2SMilan Broz 			if (cc->sector_size < (1 << SECTOR_SHIFT) ||
26548f0009a2SMilan Broz 			    cc->sector_size > 4096 ||
2655ff3af92bSMikulas Patocka 			    (cc->sector_size & (cc->sector_size - 1))) {
26568f0009a2SMilan Broz 				ti->error = "Invalid feature value for sector_size";
26578f0009a2SMilan Broz 				return -EINVAL;
26588f0009a2SMilan Broz 			}
2659783874b0SMilan Broz 			if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
2660783874b0SMilan Broz 				ti->error = "Device size is not multiple of sector_size feature";
2661783874b0SMilan Broz 				return -EINVAL;
2662783874b0SMilan Broz 			}
2663ff3af92bSMikulas Patocka 			cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
26648f0009a2SMilan Broz 		} else if (!strcasecmp(opt_string, "iv_large_sectors"))
26658f0009a2SMilan Broz 			set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
26668f0009a2SMilan Broz 		else {
2667ef43aa38SMilan Broz 			ti->error = "Invalid feature arguments";
2668ef43aa38SMilan Broz 			return -EINVAL;
2669ef43aa38SMilan Broz 		}
2670ef43aa38SMilan Broz 	}
2671ef43aa38SMilan Broz 
2672ef43aa38SMilan Broz 	return 0;
26731da177e4SLinus Torvalds }
26741da177e4SLinus Torvalds 
26751da177e4SLinus Torvalds /*
26761da177e4SLinus Torvalds  * Construct an encryption mapping:
2677c538f6ecSOndrej Kozina  * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
26781da177e4SLinus Torvalds  */
26791da177e4SLinus Torvalds static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
26801da177e4SLinus Torvalds {
26811da177e4SLinus Torvalds 	struct crypt_config *cc;
2682ed0302e8SMichał Mirosław 	const char *devname = dm_table_device_name(ti->table);
2683c538f6ecSOndrej Kozina 	int key_size;
2684ef43aa38SMilan Broz 	unsigned int align_mask;
26851da177e4SLinus Torvalds 	unsigned long long tmpll;
26861da177e4SLinus Torvalds 	int ret;
2687ef43aa38SMilan Broz 	size_t iv_size_padding, additional_req_size;
268831998ef1SMikulas Patocka 	char dummy;
26891da177e4SLinus Torvalds 
2690772ae5f5SMilan Broz 	if (argc < 5) {
26911da177e4SLinus Torvalds 		ti->error = "Not enough arguments";
26921da177e4SLinus Torvalds 		return -EINVAL;
26931da177e4SLinus Torvalds 	}
26941da177e4SLinus Torvalds 
2695c538f6ecSOndrej Kozina 	key_size = get_key_size(&argv[1]);
2696c538f6ecSOndrej Kozina 	if (key_size < 0) {
2697c538f6ecSOndrej Kozina 		ti->error = "Cannot parse key size";
2698c538f6ecSOndrej Kozina 		return -EINVAL;
2699c538f6ecSOndrej Kozina 	}
27001da177e4SLinus Torvalds 
27011da177e4SLinus Torvalds 	cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
27021da177e4SLinus Torvalds 	if (!cc) {
27031da177e4SLinus Torvalds 		ti->error = "Cannot allocate encryption context";
27041da177e4SLinus Torvalds 		return -ENOMEM;
27051da177e4SLinus Torvalds 	}
27061da177e4SLinus Torvalds 	cc->key_size = key_size;
27078f0009a2SMilan Broz 	cc->sector_size = (1 << SECTOR_SHIFT);
2708ff3af92bSMikulas Patocka 	cc->sector_shift = 0;
27091da177e4SLinus Torvalds 
27101da177e4SLinus Torvalds 	ti->private = cc;
2711ef43aa38SMilan Broz 
27125059353dSMikulas Patocka 	spin_lock(&dm_crypt_clients_lock);
27135059353dSMikulas Patocka 	dm_crypt_clients_n++;
27145059353dSMikulas Patocka 	crypt_calculate_pages_per_client();
27155059353dSMikulas Patocka 	spin_unlock(&dm_crypt_clients_lock);
27165059353dSMikulas Patocka 
27175059353dSMikulas Patocka 	ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
27185059353dSMikulas Patocka 	if (ret < 0)
27195059353dSMikulas Patocka 		goto bad;
27205059353dSMikulas Patocka 
2721ef43aa38SMilan Broz 	/* Optional parameters need to be read before cipher constructor */
2722ef43aa38SMilan Broz 	if (argc > 5) {
2723ef43aa38SMilan Broz 		ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
2724ef43aa38SMilan Broz 		if (ret)
2725ef43aa38SMilan Broz 			goto bad;
2726ef43aa38SMilan Broz 	}
2727ef43aa38SMilan Broz 
27281da177e4SLinus Torvalds 	ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
27291da177e4SLinus Torvalds 	if (ret < 0)
27301da177e4SLinus Torvalds 		goto bad;
27311da177e4SLinus Torvalds 
273233d2f09fSMilan Broz 	if (crypt_integrity_aead(cc)) {
2733ef43aa38SMilan Broz 		cc->dmreq_start = sizeof(struct aead_request);
2734ef43aa38SMilan Broz 		cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
2735ef43aa38SMilan Broz 		align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
2736ef43aa38SMilan Broz 	} else {
2737bbdb23b5SHerbert Xu 		cc->dmreq_start = sizeof(struct skcipher_request);
2738bbdb23b5SHerbert Xu 		cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
2739ef43aa38SMilan Broz 		align_mask = crypto_skcipher_alignmask(any_tfm(cc));
2740ef43aa38SMilan Broz 	}
2741d49ec52fSMikulas Patocka 	cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
2742d49ec52fSMikulas Patocka 
2743ef43aa38SMilan Broz 	if (align_mask < CRYPTO_MINALIGN) {
2744d49ec52fSMikulas Patocka 		/* Allocate the padding exactly */
2745d49ec52fSMikulas Patocka 		iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
2746ef43aa38SMilan Broz 				& align_mask;
2747d49ec52fSMikulas Patocka 	} else {
2748d49ec52fSMikulas Patocka 		/*
2749d49ec52fSMikulas Patocka 		 * If the cipher requires greater alignment than kmalloc
2750d49ec52fSMikulas Patocka 		 * alignment, we don't know the exact position of the
2751d49ec52fSMikulas Patocka 		 * initialization vector. We must assume worst case.
2752d49ec52fSMikulas Patocka 		 */
2753ef43aa38SMilan Broz 		iv_size_padding = align_mask;
2754d49ec52fSMikulas Patocka 	}
27551da177e4SLinus Torvalds 
2756ef43aa38SMilan Broz 	/*  ...| IV + padding | original IV | original sec. number | bio tag offset | */
2757ef43aa38SMilan Broz 	additional_req_size = sizeof(struct dm_crypt_request) +
2758ef43aa38SMilan Broz 		iv_size_padding + cc->iv_size +
2759ef43aa38SMilan Broz 		cc->iv_size +
2760ef43aa38SMilan Broz 		sizeof(uint64_t) +
2761ef43aa38SMilan Broz 		sizeof(unsigned int);
2762ef43aa38SMilan Broz 
27636f1c819cSKent Overstreet 	ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
27646f1c819cSKent Overstreet 	if (ret) {
27651da177e4SLinus Torvalds 		ti->error = "Cannot allocate crypt request mempool";
27661da177e4SLinus Torvalds 		goto bad;
27671da177e4SLinus Torvalds 	}
27681da177e4SLinus Torvalds 
276930187e1dSMike Snitzer 	cc->per_bio_data_size = ti->per_io_data_size =
2770ef43aa38SMilan Broz 		ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
2771d49ec52fSMikulas Patocka 		      ARCH_KMALLOC_MINALIGN);
2772298a9fa0SMikulas Patocka 
27736f1c819cSKent Overstreet 	ret = mempool_init(&cc->page_pool, BIO_MAX_PAGES, crypt_page_alloc, crypt_page_free, cc);
27746f1c819cSKent Overstreet 	if (ret) {
27758b004457SMilan Broz 		ti->error = "Cannot allocate page mempool";
2776e48d4bbfSMilan Broz 		goto bad;
27771da177e4SLinus Torvalds 	}
2778e48d4bbfSMilan Broz 
27796f1c819cSKent Overstreet 	ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
27806f1c819cSKent Overstreet 	if (ret) {
27810c395b0fSMilan Broz 		ti->error = "Cannot allocate crypt bioset";
2782cabf08e4SMilan Broz 		goto bad;
278393e605c2SMilan Broz 	}
2784cabf08e4SMilan Broz 
27857145c241SMikulas Patocka 	mutex_init(&cc->bio_alloc_lock);
27867145c241SMikulas Patocka 
2787cabf08e4SMilan Broz 	ret = -EINVAL;
27888f0009a2SMilan Broz 	if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
27898f0009a2SMilan Broz 	    (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
2790cabf08e4SMilan Broz 		ti->error = "Invalid iv_offset sector";
2791cabf08e4SMilan Broz 		goto bad;
27921da177e4SLinus Torvalds 	}
2793d2a7ad29SKiyoshi Ueda 	cc->iv_offset = tmpll;
27941da177e4SLinus Torvalds 
2795e80d1c80SVivek Goyal 	ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
2796e80d1c80SVivek Goyal 	if (ret) {
27971da177e4SLinus Torvalds 		ti->error = "Device lookup failed";
27981da177e4SLinus Torvalds 		goto bad;
27991da177e4SLinus Torvalds 	}
28001da177e4SLinus Torvalds 
2801e80d1c80SVivek Goyal 	ret = -EINVAL;
2802ef87bfc2SMilan Broz 	if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
28031da177e4SLinus Torvalds 		ti->error = "Invalid device sector";
28041da177e4SLinus Torvalds 		goto bad;
28051da177e4SLinus Torvalds 	}
28061da177e4SLinus Torvalds 	cc->start = tmpll;
28071da177e4SLinus Torvalds 
280833d2f09fSMilan Broz 	if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
2809ef43aa38SMilan Broz 		ret = crypt_integrity_ctr(cc, ti);
2810772ae5f5SMilan Broz 		if (ret)
2811772ae5f5SMilan Broz 			goto bad;
2812772ae5f5SMilan Broz 
2813ef43aa38SMilan Broz 		cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
2814ef43aa38SMilan Broz 		if (!cc->tag_pool_max_sectors)
2815ef43aa38SMilan Broz 			cc->tag_pool_max_sectors = 1;
2816ef43aa38SMilan Broz 
28176f1c819cSKent Overstreet 		ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
2818ef43aa38SMilan Broz 			cc->tag_pool_max_sectors * cc->on_disk_tag_size);
28196f1c819cSKent Overstreet 		if (ret) {
2820ef43aa38SMilan Broz 			ti->error = "Cannot allocate integrity tags mempool";
2821f3396c58SMikulas Patocka 			goto bad;
2822f3396c58SMikulas Patocka 		}
2823772ae5f5SMilan Broz 
2824583fe747SMikulas Patocka 		cc->tag_pool_max_sectors <<= cc->sector_shift;
2825f3396c58SMikulas Patocka 	}
2826772ae5f5SMilan Broz 
28271da177e4SLinus Torvalds 	ret = -ENOMEM;
2828ed0302e8SMichał Mirosław 	cc->io_queue = alloc_workqueue("kcryptd_io/%s",
2829ed0302e8SMichał Mirosław 				       WQ_HIGHPRI | WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM,
2830ed0302e8SMichał Mirosław 				       1, devname);
28311da177e4SLinus Torvalds 	if (!cc->io_queue) {
28321da177e4SLinus Torvalds 		ti->error = "Couldn't create kcryptd io queue";
28331da177e4SLinus Torvalds 		goto bad;
28341da177e4SLinus Torvalds 	}
283537af6560SChristophe Saout 
2836f3396c58SMikulas Patocka 	if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
2837ed0302e8SMichał Mirosław 		cc->crypt_queue = alloc_workqueue("kcryptd/%s",
2838ed0302e8SMichał Mirosław 						  WQ_HIGHPRI | WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM,
2839ed0302e8SMichał Mirosław 						  1, devname);
2840f3396c58SMikulas Patocka 	else
2841ed0302e8SMichał Mirosław 		cc->crypt_queue = alloc_workqueue("kcryptd/%s",
2842a1b89132STim Murray 						  WQ_HIGHPRI | WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
2843ed0302e8SMichał Mirosław 						  num_online_cpus(), devname);
28441da177e4SLinus Torvalds 	if (!cc->crypt_queue) {
28451da177e4SLinus Torvalds 		ti->error = "Couldn't create kcryptd queue";
28461da177e4SLinus Torvalds 		goto bad;
28471da177e4SLinus Torvalds 	}
28481da177e4SLinus Torvalds 
2849c7329effSMikulas Patocka 	spin_lock_init(&cc->write_thread_lock);
2850b3c5fd30SMikulas Patocka 	cc->write_tree = RB_ROOT;
2851dc267621SMikulas Patocka 
2852ed0302e8SMichał Mirosław 	cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
2853dc267621SMikulas Patocka 	if (IS_ERR(cc->write_thread)) {
2854dc267621SMikulas Patocka 		ret = PTR_ERR(cc->write_thread);
2855dc267621SMikulas Patocka 		cc->write_thread = NULL;
2856dc267621SMikulas Patocka 		ti->error = "Couldn't spawn write thread";
2857dc267621SMikulas Patocka 		goto bad;
2858dc267621SMikulas Patocka 	}
2859dc267621SMikulas Patocka 	wake_up_process(cc->write_thread);
2860dc267621SMikulas Patocka 
286155a62eefSAlasdair G Kergon 	ti->num_flush_bios = 1;
2862983c7db3SMilan Broz 
28631da177e4SLinus Torvalds 	return 0;
28641da177e4SLinus Torvalds 
28651da177e4SLinus Torvalds bad:
28661da177e4SLinus Torvalds 	crypt_dtr(ti);
28671da177e4SLinus Torvalds 	return ret;
2868647c7db1SMikulas Patocka }
2869647c7db1SMikulas Patocka 
28707de3ee57SMikulas Patocka static int crypt_map(struct dm_target *ti, struct bio *bio)
28711da177e4SLinus Torvalds {
28721da177e4SLinus Torvalds 	struct dm_crypt_io *io;
287349a8a920SAlasdair G Kergon 	struct crypt_config *cc = ti->private;
2874647c7db1SMikulas Patocka 
2875772ae5f5SMilan Broz 	/*
287628a8f0d3SMike Christie 	 * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
287728a8f0d3SMike Christie 	 * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
2878e6047149SMike Christie 	 * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
2879772ae5f5SMilan Broz 	 */
28801eff9d32SJens Axboe 	if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
288128a8f0d3SMike Christie 	    bio_op(bio) == REQ_OP_DISCARD)) {
288274d46992SChristoph Hellwig 		bio_set_dev(bio, cc->dev->bdev);
2883772ae5f5SMilan Broz 		if (bio_sectors(bio))
28844f024f37SKent Overstreet 			bio->bi_iter.bi_sector = cc->start +
28854f024f37SKent Overstreet 				dm_target_offset(ti, bio->bi_iter.bi_sector);
2886647c7db1SMikulas Patocka 		return DM_MAPIO_REMAPPED;
2887647c7db1SMikulas Patocka 	}
28881da177e4SLinus Torvalds 
28894e870e94SMikulas Patocka 	/*
28904e870e94SMikulas Patocka 	 * Check if bio is too large, split as needed.
28914e870e94SMikulas Patocka 	 */
28924e870e94SMikulas Patocka 	if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_PAGES << PAGE_SHIFT)) &&
2893ef43aa38SMilan Broz 	    (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
28944e870e94SMikulas Patocka 		dm_accept_partial_bio(bio, ((BIO_MAX_PAGES << PAGE_SHIFT) >> SECTOR_SHIFT));
28954e870e94SMikulas Patocka 
28968f0009a2SMilan Broz 	/*
28978f0009a2SMilan Broz 	 * Ensure that bio is a multiple of internal sector encryption size
28988f0009a2SMilan Broz 	 * and is aligned to this size as defined in IO hints.
28998f0009a2SMilan Broz 	 */
29008f0009a2SMilan Broz 	if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
2901846785e6SChristoph Hellwig 		return DM_MAPIO_KILL;
29028f0009a2SMilan Broz 
29038f0009a2SMilan Broz 	if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
2904846785e6SChristoph Hellwig 		return DM_MAPIO_KILL;
29058f0009a2SMilan Broz 
2906298a9fa0SMikulas Patocka 	io = dm_per_bio_data(bio, cc->per_bio_data_size);
2907298a9fa0SMikulas Patocka 	crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
2908ef43aa38SMilan Broz 
2909ef43aa38SMilan Broz 	if (cc->on_disk_tag_size) {
2910583fe747SMikulas Patocka 		unsigned tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
2911ef43aa38SMilan Broz 
2912ef43aa38SMilan Broz 		if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
2913583fe747SMikulas Patocka 		    unlikely(!(io->integrity_metadata = kmalloc(tag_len,
2914ef43aa38SMilan Broz 				GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
2915ef43aa38SMilan Broz 			if (bio_sectors(bio) > cc->tag_pool_max_sectors)
2916ef43aa38SMilan Broz 				dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
29176f1c819cSKent Overstreet 			io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
2918ef43aa38SMilan Broz 			io->integrity_metadata_from_pool = true;
2919ef43aa38SMilan Broz 		}
2920ef43aa38SMilan Broz 	}
2921ef43aa38SMilan Broz 
292233d2f09fSMilan Broz 	if (crypt_integrity_aead(cc))
2923ef43aa38SMilan Broz 		io->ctx.r.req_aead = (struct aead_request *)(io + 1);
2924ef43aa38SMilan Broz 	else
2925ef43aa38SMilan Broz 		io->ctx.r.req = (struct skcipher_request *)(io + 1);
29261da177e4SLinus Torvalds 
292720c82538SMilan Broz 	if (bio_data_dir(io->base_bio) == READ) {
292820c82538SMilan Broz 		if (kcryptd_io_read(io, GFP_NOWAIT))
2929dc267621SMikulas Patocka 			kcryptd_queue_read(io);
293020c82538SMilan Broz 	} else
29314ee218cdSAndrew Morton 		kcryptd_queue_crypt(io);
29324ee218cdSAndrew Morton 
29331da177e4SLinus Torvalds 	return DM_MAPIO_SUBMITTED;
29341da177e4SLinus Torvalds }
29351da177e4SLinus Torvalds 
2936fd7c092eSMikulas Patocka static void crypt_status(struct dm_target *ti, status_type_t type,
29371f4e0ff0SAlasdair G Kergon 			 unsigned status_flags, char *result, unsigned maxlen)
29381da177e4SLinus Torvalds {
29395ebaee6dSMilan Broz 	struct crypt_config *cc = ti->private;
2940fd7c092eSMikulas Patocka 	unsigned i, sz = 0;
2941f3396c58SMikulas Patocka 	int num_feature_args = 0;
29421da177e4SLinus Torvalds 
29431da177e4SLinus Torvalds 	switch (type) {
29441da177e4SLinus Torvalds 	case STATUSTYPE_INFO:
29451da177e4SLinus Torvalds 		result[0] = '\0';
29461da177e4SLinus Torvalds 		break;
29471da177e4SLinus Torvalds 
29481da177e4SLinus Torvalds 	case STATUSTYPE_TABLE:
29497dbcd137SMilan Broz 		DMEMIT("%s ", cc->cipher_string);
29501da177e4SLinus Torvalds 
2951c538f6ecSOndrej Kozina 		if (cc->key_size > 0) {
2952c538f6ecSOndrej Kozina 			if (cc->key_string)
2953c538f6ecSOndrej Kozina 				DMEMIT(":%u:%s", cc->key_size, cc->key_string);
2954c538f6ecSOndrej Kozina 			else
2955fd7c092eSMikulas Patocka 				for (i = 0; i < cc->key_size; i++)
2956fd7c092eSMikulas Patocka 					DMEMIT("%02x", cc->key[i]);
2957c538f6ecSOndrej Kozina 		} else
2958fd7c092eSMikulas Patocka 			DMEMIT("-");
29591da177e4SLinus Torvalds 
29601da177e4SLinus Torvalds 		DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
29611da177e4SLinus Torvalds 				cc->dev->name, (unsigned long long)cc->start);
2962772ae5f5SMilan Broz 
2963f3396c58SMikulas Patocka 		num_feature_args += !!ti->num_discard_bios;
2964f3396c58SMikulas Patocka 		num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
29650f5d8e6eSMikulas Patocka 		num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
2966ff3af92bSMikulas Patocka 		num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
29678f0009a2SMilan Broz 		num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
2968ef43aa38SMilan Broz 		if (cc->on_disk_tag_size)
2969ef43aa38SMilan Broz 			num_feature_args++;
2970f3396c58SMikulas Patocka 		if (num_feature_args) {
2971f3396c58SMikulas Patocka 			DMEMIT(" %d", num_feature_args);
297255a62eefSAlasdair G Kergon 			if (ti->num_discard_bios)
2973f3396c58SMikulas Patocka 				DMEMIT(" allow_discards");
2974f3396c58SMikulas Patocka 			if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
2975f3396c58SMikulas Patocka 				DMEMIT(" same_cpu_crypt");
29760f5d8e6eSMikulas Patocka 			if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
29770f5d8e6eSMikulas Patocka 				DMEMIT(" submit_from_crypt_cpus");
2978ef43aa38SMilan Broz 			if (cc->on_disk_tag_size)
2979ef43aa38SMilan Broz 				DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
29808f0009a2SMilan Broz 			if (cc->sector_size != (1 << SECTOR_SHIFT))
29818f0009a2SMilan Broz 				DMEMIT(" sector_size:%d", cc->sector_size);
29828f0009a2SMilan Broz 			if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
29838f0009a2SMilan Broz 				DMEMIT(" iv_large_sectors");
2984f3396c58SMikulas Patocka 		}
2985772ae5f5SMilan Broz 
29861da177e4SLinus Torvalds 		break;
29871da177e4SLinus Torvalds 	}
29881da177e4SLinus Torvalds }
29891da177e4SLinus Torvalds 
2990e48d4bbfSMilan Broz static void crypt_postsuspend(struct dm_target *ti)
2991e48d4bbfSMilan Broz {
2992e48d4bbfSMilan Broz 	struct crypt_config *cc = ti->private;
2993e48d4bbfSMilan Broz 
2994e48d4bbfSMilan Broz 	set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
2995e48d4bbfSMilan Broz }
2996e48d4bbfSMilan Broz 
2997e48d4bbfSMilan Broz static int crypt_preresume(struct dm_target *ti)
2998e48d4bbfSMilan Broz {
2999e48d4bbfSMilan Broz 	struct crypt_config *cc = ti->private;
3000e48d4bbfSMilan Broz 
3001e48d4bbfSMilan Broz 	if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
3002e48d4bbfSMilan Broz 		DMERR("aborting resume - crypt key is not set.");
3003e48d4bbfSMilan Broz 		return -EAGAIN;
3004e48d4bbfSMilan Broz 	}
3005e48d4bbfSMilan Broz 
3006e48d4bbfSMilan Broz 	return 0;
3007e48d4bbfSMilan Broz }
3008e48d4bbfSMilan Broz 
3009e48d4bbfSMilan Broz static void crypt_resume(struct dm_target *ti)
3010e48d4bbfSMilan Broz {
3011e48d4bbfSMilan Broz 	struct crypt_config *cc = ti->private;
3012e48d4bbfSMilan Broz 
3013e48d4bbfSMilan Broz 	clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3014e48d4bbfSMilan Broz }
3015e48d4bbfSMilan Broz 
3016e48d4bbfSMilan Broz /* Message interface
3017e48d4bbfSMilan Broz  *	key set <key>
3018e48d4bbfSMilan Broz  *	key wipe
3019e48d4bbfSMilan Broz  */
30201eb5fa84SMike Snitzer static int crypt_message(struct dm_target *ti, unsigned argc, char **argv,
30211eb5fa84SMike Snitzer 			 char *result, unsigned maxlen)
3022e48d4bbfSMilan Broz {
3023e48d4bbfSMilan Broz 	struct crypt_config *cc = ti->private;
3024c538f6ecSOndrej Kozina 	int key_size, ret = -EINVAL;
3025e48d4bbfSMilan Broz 
3026e48d4bbfSMilan Broz 	if (argc < 2)
3027e48d4bbfSMilan Broz 		goto error;
3028e48d4bbfSMilan Broz 
3029498f0103SMike Snitzer 	if (!strcasecmp(argv[0], "key")) {
3030e48d4bbfSMilan Broz 		if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
3031e48d4bbfSMilan Broz 			DMWARN("not suspended during key manipulation.");
3032e48d4bbfSMilan Broz 			return -EINVAL;
3033e48d4bbfSMilan Broz 		}
3034498f0103SMike Snitzer 		if (argc == 3 && !strcasecmp(argv[1], "set")) {
3035c538f6ecSOndrej Kozina 			/* The key size may not be changed. */
3036c538f6ecSOndrej Kozina 			key_size = get_key_size(&argv[2]);
3037c538f6ecSOndrej Kozina 			if (key_size < 0 || cc->key_size != key_size) {
3038c538f6ecSOndrej Kozina 				memset(argv[2], '0', strlen(argv[2]));
3039c538f6ecSOndrej Kozina 				return -EINVAL;
3040c538f6ecSOndrej Kozina 			}
3041c538f6ecSOndrej Kozina 
3042542da317SMilan Broz 			ret = crypt_set_key(cc, argv[2]);
3043542da317SMilan Broz 			if (ret)
3044542da317SMilan Broz 				return ret;
3045542da317SMilan Broz 			if (cc->iv_gen_ops && cc->iv_gen_ops->init)
3046542da317SMilan Broz 				ret = cc->iv_gen_ops->init(cc);
3047dc94902bSOndrej Kozina 			/* wipe the kernel key payload copy */
3048dc94902bSOndrej Kozina 			if (cc->key_string)
3049dc94902bSOndrej Kozina 				memset(cc->key, 0, cc->key_size * sizeof(u8));
3050542da317SMilan Broz 			return ret;
3051542da317SMilan Broz 		}
3052498f0103SMike Snitzer 		if (argc == 2 && !strcasecmp(argv[1], "wipe")) {
3053542da317SMilan Broz 			if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
3054542da317SMilan Broz 				ret = cc->iv_gen_ops->wipe(cc);
3055542da317SMilan Broz 				if (ret)
3056542da317SMilan Broz 					return ret;
3057542da317SMilan Broz 			}
3058e48d4bbfSMilan Broz 			return crypt_wipe_key(cc);
3059e48d4bbfSMilan Broz 		}
3060542da317SMilan Broz 	}
3061e48d4bbfSMilan Broz 
3062e48d4bbfSMilan Broz error:
3063e48d4bbfSMilan Broz 	DMWARN("unrecognised message received.");
3064e48d4bbfSMilan Broz 	return -EINVAL;
3065e48d4bbfSMilan Broz }
3066e48d4bbfSMilan Broz 
3067af4874e0SMike Snitzer static int crypt_iterate_devices(struct dm_target *ti,
3068af4874e0SMike Snitzer 				 iterate_devices_callout_fn fn, void *data)
3069af4874e0SMike Snitzer {
3070af4874e0SMike Snitzer 	struct crypt_config *cc = ti->private;
3071af4874e0SMike Snitzer 
30725dea271bSMike Snitzer 	return fn(ti, cc->dev, cc->start, ti->len, data);
3073af4874e0SMike Snitzer }
3074af4874e0SMike Snitzer 
3075586b286bSMike Snitzer static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
3076586b286bSMike Snitzer {
30778f0009a2SMilan Broz 	struct crypt_config *cc = ti->private;
30788f0009a2SMilan Broz 
3079586b286bSMike Snitzer 	/*
3080586b286bSMike Snitzer 	 * Unfortunate constraint that is required to avoid the potential
3081586b286bSMike Snitzer 	 * for exceeding underlying device's max_segments limits -- due to
3082586b286bSMike Snitzer 	 * crypt_alloc_buffer() possibly allocating pages for the encryption
3083586b286bSMike Snitzer 	 * bio that are not as physically contiguous as the original bio.
3084586b286bSMike Snitzer 	 */
3085586b286bSMike Snitzer 	limits->max_segment_size = PAGE_SIZE;
30868f0009a2SMilan Broz 
3087bc9e9cf0SMikulas Patocka 	limits->logical_block_size =
3088bc9e9cf0SMikulas Patocka 		max_t(unsigned short, limits->logical_block_size, cc->sector_size);
3089bc9e9cf0SMikulas Patocka 	limits->physical_block_size =
3090bc9e9cf0SMikulas Patocka 		max_t(unsigned, limits->physical_block_size, cc->sector_size);
3091bc9e9cf0SMikulas Patocka 	limits->io_min = max_t(unsigned, limits->io_min, cc->sector_size);
3092586b286bSMike Snitzer }
3093586b286bSMike Snitzer 
30941da177e4SLinus Torvalds static struct target_type crypt_target = {
30951da177e4SLinus Torvalds 	.name   = "crypt",
3096dc94902bSOndrej Kozina 	.version = {1, 18, 1},
30971da177e4SLinus Torvalds 	.module = THIS_MODULE,
30981da177e4SLinus Torvalds 	.ctr    = crypt_ctr,
30991da177e4SLinus Torvalds 	.dtr    = crypt_dtr,
31001da177e4SLinus Torvalds 	.map    = crypt_map,
31011da177e4SLinus Torvalds 	.status = crypt_status,
3102e48d4bbfSMilan Broz 	.postsuspend = crypt_postsuspend,
3103e48d4bbfSMilan Broz 	.preresume = crypt_preresume,
3104e48d4bbfSMilan Broz 	.resume = crypt_resume,
3105e48d4bbfSMilan Broz 	.message = crypt_message,
3106af4874e0SMike Snitzer 	.iterate_devices = crypt_iterate_devices,
3107586b286bSMike Snitzer 	.io_hints = crypt_io_hints,
31081da177e4SLinus Torvalds };
31091da177e4SLinus Torvalds 
31101da177e4SLinus Torvalds static int __init dm_crypt_init(void)
31111da177e4SLinus Torvalds {
31121da177e4SLinus Torvalds 	int r;
31131da177e4SLinus Torvalds 
31141da177e4SLinus Torvalds 	r = dm_register_target(&crypt_target);
311594f5e024SMikulas Patocka 	if (r < 0)
311672d94861SAlasdair G Kergon 		DMERR("register failed %d", r);
31171da177e4SLinus Torvalds 
31181da177e4SLinus Torvalds 	return r;
31191da177e4SLinus Torvalds }
31201da177e4SLinus Torvalds 
31211da177e4SLinus Torvalds static void __exit dm_crypt_exit(void)
31221da177e4SLinus Torvalds {
312310d3bd09SMikulas Patocka 	dm_unregister_target(&crypt_target);
31241da177e4SLinus Torvalds }
31251da177e4SLinus Torvalds 
31261da177e4SLinus Torvalds module_init(dm_crypt_init);
31271da177e4SLinus Torvalds module_exit(dm_crypt_exit);
31281da177e4SLinus Torvalds 
3129bf14299fSJana Saout MODULE_AUTHOR("Jana Saout <jana@saout.de>");
31301da177e4SLinus Torvalds MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
31311da177e4SLinus Torvalds MODULE_LICENSE("GPL");
3132