2 * Copyright (C) 2003 Jana Saout <jana@saout.de>
3 * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
4 * Copyright (C) 2006-2020 Red Hat, Inc. All rights reserved.
5 * Copyright (C) 2013-2020 Milan Broz <gmazyland@gmail.com>
7 * This file is released under the GPL.
10 #include <linux/completion.h>
11 #include <linux/err.h>
12 #include <linux/module.h>
13 #include <linux/init.h>
14 #include <linux/kernel.h>
15 #include <linux/key.h>
16 #include <linux/bio.h>
17 #include <linux/blkdev.h>
18 #include <linux/blk-integrity.h>
19 #include <linux/mempool.h>
20 #include <linux/slab.h>
21 #include <linux/crypto.h>
22 #include <linux/workqueue.h>
23 #include <linux/kthread.h>
24 #include <linux/backing-dev.h>
25 #include <linux/atomic.h>
26 #include <linux/scatterlist.h>
27 #include <linux/rbtree.h>
28 #include <linux/ctype.h>
30 #include <asm/unaligned.h>
31 #include <crypto/hash.h>
32 #include <crypto/md5.h>
33 #include <crypto/algapi.h>
34 #include <crypto/skcipher.h>
35 #include <crypto/aead.h>
36 #include <crypto/authenc.h>
37 #include <linux/rtnetlink.h> /* for struct rtattr and RTA macros only */
38 #include <linux/key-type.h>
39 #include <keys/user-type.h>
40 #include <keys/encrypted-type.h>
41 #include <keys/trusted-type.h>
43 #include <linux/device-mapper.h>
47 #define DM_MSG_PREFIX "crypt"
50 * context holding the current state of a multi-part conversion
52 struct convert_context {
53 struct completion restart;
56 struct bvec_iter iter_in;
57 struct bvec_iter iter_out;
61 struct skcipher_request *req;
62 struct aead_request *req_aead;
68 * per bio private data
71 struct crypt_config *cc;
73 u8 *integrity_metadata;
74 bool integrity_metadata_from_pool:1;
77 struct work_struct work;
78 struct tasklet_struct tasklet;
80 struct convert_context ctx;
86 struct rb_node rb_node;
87 } CRYPTO_MINALIGN_ATTR;
89 struct dm_crypt_request {
90 struct convert_context *ctx;
91 struct scatterlist sg_in[4];
92 struct scatterlist sg_out[4];
98 struct crypt_iv_operations {
99 int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
101 void (*dtr)(struct crypt_config *cc);
102 int (*init)(struct crypt_config *cc);
103 int (*wipe)(struct crypt_config *cc);
104 int (*generator)(struct crypt_config *cc, u8 *iv,
105 struct dm_crypt_request *dmreq);
106 int (*post)(struct crypt_config *cc, u8 *iv,
107 struct dm_crypt_request *dmreq);
110 struct iv_benbi_private {
114 #define LMK_SEED_SIZE 64 /* hash + 0 */
115 struct iv_lmk_private {
116 struct crypto_shash *hash_tfm;
120 #define TCW_WHITENING_SIZE 16
121 struct iv_tcw_private {
122 struct crypto_shash *crc32_tfm;
127 #define ELEPHANT_MAX_KEY_SIZE 32
128 struct iv_elephant_private {
129 struct crypto_skcipher *tfm;
133 * Crypt: maps a linear range of a block device
134 * and encrypts / decrypts at the same time.
136 enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
137 DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD,
138 DM_CRYPT_NO_READ_WORKQUEUE, DM_CRYPT_NO_WRITE_WORKQUEUE,
139 DM_CRYPT_WRITE_INLINE };
142 CRYPT_MODE_INTEGRITY_AEAD, /* Use authenticated mode for cipher */
143 CRYPT_IV_LARGE_SECTORS, /* Calculate IV from sector_size, not 512B sectors */
144 CRYPT_ENCRYPT_PREPROCESS, /* Must preprocess data for encryption (elephant) */
148 * The fields in here must be read only after initialization.
150 struct crypt_config {
154 struct percpu_counter n_allocated_pages;
156 struct workqueue_struct *io_queue;
157 struct workqueue_struct *crypt_queue;
159 spinlock_t write_thread_lock;
160 struct task_struct *write_thread;
161 struct rb_root write_tree;
167 const struct crypt_iv_operations *iv_gen_ops;
169 struct iv_benbi_private benbi;
170 struct iv_lmk_private lmk;
171 struct iv_tcw_private tcw;
172 struct iv_elephant_private elephant;
175 unsigned int iv_size;
176 unsigned short sector_size;
177 unsigned char sector_shift;
180 struct crypto_skcipher **tfms;
181 struct crypto_aead **tfms_aead;
183 unsigned int tfms_count;
184 unsigned long cipher_flags;
187 * Layout of each crypto request:
189 * struct skcipher_request
192 * struct dm_crypt_request
196 * The padding is added so that dm_crypt_request and the IV are
199 unsigned int dmreq_start;
201 unsigned int per_bio_data_size;
204 unsigned int key_size;
205 unsigned int key_parts; /* independent parts in key buffer */
206 unsigned int key_extra_size; /* additional keys length */
207 unsigned int key_mac_size; /* MAC key size for authenc(...) */
209 unsigned int integrity_tag_size;
210 unsigned int integrity_iv_size;
211 unsigned int on_disk_tag_size;
214 * pool for per bio private data, crypto requests,
215 * encryption requeusts/buffer pages and integrity tags
217 unsigned int tag_pool_max_sectors;
223 struct mutex bio_alloc_lock;
225 u8 *authenc_key; /* space for keys in authenc() format (if used) */
230 #define MAX_TAG_SIZE 480
231 #define POOL_ENTRY_SIZE 512
233 static DEFINE_SPINLOCK(dm_crypt_clients_lock);
234 static unsigned int dm_crypt_clients_n = 0;
235 static volatile unsigned long dm_crypt_pages_per_client;
236 #define DM_CRYPT_MEMORY_PERCENT 2
237 #define DM_CRYPT_MIN_PAGES_PER_CLIENT (BIO_MAX_VECS * 16)
239 static void crypt_endio(struct bio *clone);
240 static void kcryptd_queue_crypt(struct dm_crypt_io *io);
241 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
242 struct scatterlist *sg);
244 static bool crypt_integrity_aead(struct crypt_config *cc);
247 * Use this to access cipher attributes that are independent of the key.
249 static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
251 return cc->cipher_tfm.tfms[0];
254 static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
256 return cc->cipher_tfm.tfms_aead[0];
260 * Different IV generation algorithms:
262 * plain: the initial vector is the 32-bit little-endian version of the sector
263 * number, padded with zeros if necessary.
265 * plain64: the initial vector is the 64-bit little-endian version of the sector
266 * number, padded with zeros if necessary.
268 * plain64be: the initial vector is the 64-bit big-endian version of the sector
269 * number, padded with zeros if necessary.
271 * essiv: "encrypted sector|salt initial vector", the sector number is
272 * encrypted with the bulk cipher using a salt as key. The salt
273 * should be derived from the bulk cipher's key via hashing.
275 * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
276 * (needed for LRW-32-AES and possible other narrow block modes)
278 * null: the initial vector is always zero. Provides compatibility with
279 * obsolete loop_fish2 devices. Do not use for new devices.
281 * lmk: Compatible implementation of the block chaining mode used
282 * by the Loop-AES block device encryption system
283 * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
284 * It operates on full 512 byte sectors and uses CBC
285 * with an IV derived from the sector number, the data and
286 * optionally extra IV seed.
287 * This means that after decryption the first block
288 * of sector must be tweaked according to decrypted data.
289 * Loop-AES can use three encryption schemes:
290 * version 1: is plain aes-cbc mode
291 * version 2: uses 64 multikey scheme with lmk IV generator
292 * version 3: the same as version 2 with additional IV seed
293 * (it uses 65 keys, last key is used as IV seed)
295 * tcw: Compatible implementation of the block chaining mode used
296 * by the TrueCrypt device encryption system (prior to version 4.1).
297 * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
298 * It operates on full 512 byte sectors and uses CBC
299 * with an IV derived from initial key and the sector number.
300 * In addition, whitening value is applied on every sector, whitening
301 * is calculated from initial key, sector number and mixed using CRC32.
302 * Note that this encryption scheme is vulnerable to watermarking attacks
303 * and should be used for old compatible containers access only.
305 * eboiv: Encrypted byte-offset IV (used in Bitlocker in CBC mode)
306 * The IV is encrypted little-endian byte-offset (with the same key
307 * and cipher as the volume).
309 * elephant: The extended version of eboiv with additional Elephant diffuser
310 * used with Bitlocker CBC mode.
311 * This mode was used in older Windows systems
312 * https://download.microsoft.com/download/0/2/3/0238acaf-d3bf-4a6d-b3d6-0a0be4bbb36e/bitlockercipher200608.pdf
315 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
316 struct dm_crypt_request *dmreq)
318 memset(iv, 0, cc->iv_size);
319 *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
324 static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
325 struct dm_crypt_request *dmreq)
327 memset(iv, 0, cc->iv_size);
328 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
333 static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
334 struct dm_crypt_request *dmreq)
336 memset(iv, 0, cc->iv_size);
337 /* iv_size is at least of size u64; usually it is 16 bytes */
338 *(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
343 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
344 struct dm_crypt_request *dmreq)
347 * ESSIV encryption of the IV is now handled by the crypto API,
348 * so just pass the plain sector number here.
350 memset(iv, 0, cc->iv_size);
351 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
356 static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
362 if (crypt_integrity_aead(cc))
363 bs = crypto_aead_blocksize(any_tfm_aead(cc));
365 bs = crypto_skcipher_blocksize(any_tfm(cc));
368 /* we need to calculate how far we must shift the sector count
369 * to get the cipher block count, we use this shift in _gen */
371 if (1 << log != bs) {
372 ti->error = "cypher blocksize is not a power of 2";
377 ti->error = "cypher blocksize is > 512";
381 cc->iv_gen_private.benbi.shift = 9 - log;
386 static void crypt_iv_benbi_dtr(struct crypt_config *cc)
390 static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
391 struct dm_crypt_request *dmreq)
395 memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
397 val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
398 put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
403 static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
404 struct dm_crypt_request *dmreq)
406 memset(iv, 0, cc->iv_size);
411 static void crypt_iv_lmk_dtr(struct crypt_config *cc)
413 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
415 if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
416 crypto_free_shash(lmk->hash_tfm);
417 lmk->hash_tfm = NULL;
419 kfree_sensitive(lmk->seed);
423 static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
426 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
428 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
429 ti->error = "Unsupported sector size for LMK";
433 lmk->hash_tfm = crypto_alloc_shash("md5", 0,
434 CRYPTO_ALG_ALLOCATES_MEMORY);
435 if (IS_ERR(lmk->hash_tfm)) {
436 ti->error = "Error initializing LMK hash";
437 return PTR_ERR(lmk->hash_tfm);
440 /* No seed in LMK version 2 */
441 if (cc->key_parts == cc->tfms_count) {
446 lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
448 crypt_iv_lmk_dtr(cc);
449 ti->error = "Error kmallocing seed storage in LMK";
456 static int crypt_iv_lmk_init(struct crypt_config *cc)
458 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
459 int subkey_size = cc->key_size / cc->key_parts;
461 /* LMK seed is on the position of LMK_KEYS + 1 key */
463 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
464 crypto_shash_digestsize(lmk->hash_tfm));
469 static int crypt_iv_lmk_wipe(struct crypt_config *cc)
471 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
474 memset(lmk->seed, 0, LMK_SEED_SIZE);
479 static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
480 struct dm_crypt_request *dmreq,
483 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
484 SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
485 struct md5_state md5state;
489 desc->tfm = lmk->hash_tfm;
491 r = crypto_shash_init(desc);
496 r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
501 /* Sector is always 512B, block size 16, add data of blocks 1-31 */
502 r = crypto_shash_update(desc, data + 16, 16 * 31);
506 /* Sector is cropped to 56 bits here */
507 buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
508 buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
509 buf[2] = cpu_to_le32(4024);
511 r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
515 /* No MD5 padding here */
516 r = crypto_shash_export(desc, &md5state);
520 for (i = 0; i < MD5_HASH_WORDS; i++)
521 __cpu_to_le32s(&md5state.hash[i]);
522 memcpy(iv, &md5state.hash, cc->iv_size);
527 static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
528 struct dm_crypt_request *dmreq)
530 struct scatterlist *sg;
534 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
535 sg = crypt_get_sg_data(cc, dmreq->sg_in);
536 src = kmap_atomic(sg_page(sg));
537 r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
540 memset(iv, 0, cc->iv_size);
545 static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
546 struct dm_crypt_request *dmreq)
548 struct scatterlist *sg;
552 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
555 sg = crypt_get_sg_data(cc, dmreq->sg_out);
556 dst = kmap_atomic(sg_page(sg));
557 r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
559 /* Tweak the first block of plaintext sector */
561 crypto_xor(dst + sg->offset, iv, cc->iv_size);
567 static void crypt_iv_tcw_dtr(struct crypt_config *cc)
569 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
571 kfree_sensitive(tcw->iv_seed);
573 kfree_sensitive(tcw->whitening);
574 tcw->whitening = NULL;
576 if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
577 crypto_free_shash(tcw->crc32_tfm);
578 tcw->crc32_tfm = NULL;
581 static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
584 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
586 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
587 ti->error = "Unsupported sector size for TCW";
591 if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
592 ti->error = "Wrong key size for TCW";
596 tcw->crc32_tfm = crypto_alloc_shash("crc32", 0,
597 CRYPTO_ALG_ALLOCATES_MEMORY);
598 if (IS_ERR(tcw->crc32_tfm)) {
599 ti->error = "Error initializing CRC32 in TCW";
600 return PTR_ERR(tcw->crc32_tfm);
603 tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
604 tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
605 if (!tcw->iv_seed || !tcw->whitening) {
606 crypt_iv_tcw_dtr(cc);
607 ti->error = "Error allocating seed storage in TCW";
614 static int crypt_iv_tcw_init(struct crypt_config *cc)
616 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
617 int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
619 memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
620 memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
626 static int crypt_iv_tcw_wipe(struct crypt_config *cc)
628 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
630 memset(tcw->iv_seed, 0, cc->iv_size);
631 memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
636 static int crypt_iv_tcw_whitening(struct crypt_config *cc,
637 struct dm_crypt_request *dmreq,
640 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
641 __le64 sector = cpu_to_le64(dmreq->iv_sector);
642 u8 buf[TCW_WHITENING_SIZE];
643 SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
646 /* xor whitening with sector number */
647 crypto_xor_cpy(buf, tcw->whitening, (u8 *)§or, 8);
648 crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)§or, 8);
650 /* calculate crc32 for every 32bit part and xor it */
651 desc->tfm = tcw->crc32_tfm;
652 for (i = 0; i < 4; i++) {
653 r = crypto_shash_init(desc);
656 r = crypto_shash_update(desc, &buf[i * 4], 4);
659 r = crypto_shash_final(desc, &buf[i * 4]);
663 crypto_xor(&buf[0], &buf[12], 4);
664 crypto_xor(&buf[4], &buf[8], 4);
666 /* apply whitening (8 bytes) to whole sector */
667 for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
668 crypto_xor(data + i * 8, buf, 8);
670 memzero_explicit(buf, sizeof(buf));
674 static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
675 struct dm_crypt_request *dmreq)
677 struct scatterlist *sg;
678 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
679 __le64 sector = cpu_to_le64(dmreq->iv_sector);
683 /* Remove whitening from ciphertext */
684 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
685 sg = crypt_get_sg_data(cc, dmreq->sg_in);
686 src = kmap_atomic(sg_page(sg));
687 r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
692 crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)§or, 8);
694 crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)§or,
700 static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
701 struct dm_crypt_request *dmreq)
703 struct scatterlist *sg;
707 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
710 /* Apply whitening on ciphertext */
711 sg = crypt_get_sg_data(cc, dmreq->sg_out);
712 dst = kmap_atomic(sg_page(sg));
713 r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
719 static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
720 struct dm_crypt_request *dmreq)
722 /* Used only for writes, there must be an additional space to store IV */
723 get_random_bytes(iv, cc->iv_size);
727 static int crypt_iv_eboiv_ctr(struct crypt_config *cc, struct dm_target *ti,
730 if (crypt_integrity_aead(cc)) {
731 ti->error = "AEAD transforms not supported for EBOIV";
735 if (crypto_skcipher_blocksize(any_tfm(cc)) != cc->iv_size) {
736 ti->error = "Block size of EBOIV cipher does "
737 "not match IV size of block cipher";
744 static int crypt_iv_eboiv_gen(struct crypt_config *cc, u8 *iv,
745 struct dm_crypt_request *dmreq)
747 u8 buf[MAX_CIPHER_BLOCKSIZE] __aligned(__alignof__(__le64));
748 struct skcipher_request *req;
749 struct scatterlist src, dst;
750 DECLARE_CRYPTO_WAIT(wait);
753 req = skcipher_request_alloc(any_tfm(cc), GFP_NOIO);
757 memset(buf, 0, cc->iv_size);
758 *(__le64 *)buf = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
760 sg_init_one(&src, page_address(ZERO_PAGE(0)), cc->iv_size);
761 sg_init_one(&dst, iv, cc->iv_size);
762 skcipher_request_set_crypt(req, &src, &dst, cc->iv_size, buf);
763 skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
764 err = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
765 skcipher_request_free(req);
770 static void crypt_iv_elephant_dtr(struct crypt_config *cc)
772 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
774 crypto_free_skcipher(elephant->tfm);
775 elephant->tfm = NULL;
778 static int crypt_iv_elephant_ctr(struct crypt_config *cc, struct dm_target *ti,
781 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
784 elephant->tfm = crypto_alloc_skcipher("ecb(aes)", 0,
785 CRYPTO_ALG_ALLOCATES_MEMORY);
786 if (IS_ERR(elephant->tfm)) {
787 r = PTR_ERR(elephant->tfm);
788 elephant->tfm = NULL;
792 r = crypt_iv_eboiv_ctr(cc, ti, NULL);
794 crypt_iv_elephant_dtr(cc);
798 static void diffuser_disk_to_cpu(u32 *d, size_t n)
800 #ifndef __LITTLE_ENDIAN
803 for (i = 0; i < n; i++)
804 d[i] = le32_to_cpu((__le32)d[i]);
808 static void diffuser_cpu_to_disk(__le32 *d, size_t n)
810 #ifndef __LITTLE_ENDIAN
813 for (i = 0; i < n; i++)
814 d[i] = cpu_to_le32((u32)d[i]);
818 static void diffuser_a_decrypt(u32 *d, size_t n)
822 for (i = 0; i < 5; i++) {
827 while (i1 < (n - 1)) {
828 d[i1] += d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
834 d[i1] += d[i2] ^ d[i3];
840 d[i1] += d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
843 d[i1] += d[i2] ^ d[i3];
849 static void diffuser_a_encrypt(u32 *d, size_t n)
853 for (i = 0; i < 5; i++) {
859 d[i1] -= d[i2] ^ d[i3];
862 d[i1] -= d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
868 d[i1] -= d[i2] ^ d[i3];
874 d[i1] -= d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
880 static void diffuser_b_decrypt(u32 *d, size_t n)
884 for (i = 0; i < 3; i++) {
889 while (i1 < (n - 1)) {
890 d[i1] += d[i2] ^ d[i3];
893 d[i1] += d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
899 d[i1] += d[i2] ^ d[i3];
905 d[i1] += d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
911 static void diffuser_b_encrypt(u32 *d, size_t n)
915 for (i = 0; i < 3; i++) {
921 d[i1] -= d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
927 d[i1] -= d[i2] ^ d[i3];
933 d[i1] -= d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
936 d[i1] -= d[i2] ^ d[i3];
942 static int crypt_iv_elephant(struct crypt_config *cc, struct dm_crypt_request *dmreq)
944 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
945 u8 *es, *ks, *data, *data2, *data_offset;
946 struct skcipher_request *req;
947 struct scatterlist *sg, *sg2, src, dst;
948 DECLARE_CRYPTO_WAIT(wait);
951 req = skcipher_request_alloc(elephant->tfm, GFP_NOIO);
952 es = kzalloc(16, GFP_NOIO); /* Key for AES */
953 ks = kzalloc(32, GFP_NOIO); /* Elephant sector key */
955 if (!req || !es || !ks) {
960 *(__le64 *)es = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
963 sg_init_one(&src, es, 16);
964 sg_init_one(&dst, ks, 16);
965 skcipher_request_set_crypt(req, &src, &dst, 16, NULL);
966 skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
967 r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
973 sg_init_one(&dst, &ks[16], 16);
974 r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
978 sg = crypt_get_sg_data(cc, dmreq->sg_out);
979 data = kmap_atomic(sg_page(sg));
980 data_offset = data + sg->offset;
982 /* Cannot modify original bio, copy to sg_out and apply Elephant to it */
983 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
984 sg2 = crypt_get_sg_data(cc, dmreq->sg_in);
985 data2 = kmap_atomic(sg_page(sg2));
986 memcpy(data_offset, data2 + sg2->offset, cc->sector_size);
987 kunmap_atomic(data2);
990 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
991 diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
992 diffuser_b_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
993 diffuser_a_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
994 diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
997 for (i = 0; i < (cc->sector_size / 32); i++)
998 crypto_xor(data_offset + i * 32, ks, 32);
1000 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
1001 diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
1002 diffuser_a_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
1003 diffuser_b_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
1004 diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
1007 kunmap_atomic(data);
1009 kfree_sensitive(ks);
1010 kfree_sensitive(es);
1011 skcipher_request_free(req);
1015 static int crypt_iv_elephant_gen(struct crypt_config *cc, u8 *iv,
1016 struct dm_crypt_request *dmreq)
1020 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
1021 r = crypt_iv_elephant(cc, dmreq);
1026 return crypt_iv_eboiv_gen(cc, iv, dmreq);
1029 static int crypt_iv_elephant_post(struct crypt_config *cc, u8 *iv,
1030 struct dm_crypt_request *dmreq)
1032 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
1033 return crypt_iv_elephant(cc, dmreq);
1038 static int crypt_iv_elephant_init(struct crypt_config *cc)
1040 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1041 int key_offset = cc->key_size - cc->key_extra_size;
1043 return crypto_skcipher_setkey(elephant->tfm, &cc->key[key_offset], cc->key_extra_size);
1046 static int crypt_iv_elephant_wipe(struct crypt_config *cc)
1048 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1049 u8 key[ELEPHANT_MAX_KEY_SIZE];
1051 memset(key, 0, cc->key_extra_size);
1052 return crypto_skcipher_setkey(elephant->tfm, key, cc->key_extra_size);
1055 static const struct crypt_iv_operations crypt_iv_plain_ops = {
1056 .generator = crypt_iv_plain_gen
1059 static const struct crypt_iv_operations crypt_iv_plain64_ops = {
1060 .generator = crypt_iv_plain64_gen
1063 static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
1064 .generator = crypt_iv_plain64be_gen
1067 static const struct crypt_iv_operations crypt_iv_essiv_ops = {
1068 .generator = crypt_iv_essiv_gen
1071 static const struct crypt_iv_operations crypt_iv_benbi_ops = {
1072 .ctr = crypt_iv_benbi_ctr,
1073 .dtr = crypt_iv_benbi_dtr,
1074 .generator = crypt_iv_benbi_gen
1077 static const struct crypt_iv_operations crypt_iv_null_ops = {
1078 .generator = crypt_iv_null_gen
1081 static const struct crypt_iv_operations crypt_iv_lmk_ops = {
1082 .ctr = crypt_iv_lmk_ctr,
1083 .dtr = crypt_iv_lmk_dtr,
1084 .init = crypt_iv_lmk_init,
1085 .wipe = crypt_iv_lmk_wipe,
1086 .generator = crypt_iv_lmk_gen,
1087 .post = crypt_iv_lmk_post
1090 static const struct crypt_iv_operations crypt_iv_tcw_ops = {
1091 .ctr = crypt_iv_tcw_ctr,
1092 .dtr = crypt_iv_tcw_dtr,
1093 .init = crypt_iv_tcw_init,
1094 .wipe = crypt_iv_tcw_wipe,
1095 .generator = crypt_iv_tcw_gen,
1096 .post = crypt_iv_tcw_post
1099 static const struct crypt_iv_operations crypt_iv_random_ops = {
1100 .generator = crypt_iv_random_gen
1103 static const struct crypt_iv_operations crypt_iv_eboiv_ops = {
1104 .ctr = crypt_iv_eboiv_ctr,
1105 .generator = crypt_iv_eboiv_gen
1108 static const struct crypt_iv_operations crypt_iv_elephant_ops = {
1109 .ctr = crypt_iv_elephant_ctr,
1110 .dtr = crypt_iv_elephant_dtr,
1111 .init = crypt_iv_elephant_init,
1112 .wipe = crypt_iv_elephant_wipe,
1113 .generator = crypt_iv_elephant_gen,
1114 .post = crypt_iv_elephant_post
1118 * Integrity extensions
1120 static bool crypt_integrity_aead(struct crypt_config *cc)
1122 return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
1125 static bool crypt_integrity_hmac(struct crypt_config *cc)
1127 return crypt_integrity_aead(cc) && cc->key_mac_size;
1130 /* Get sg containing data */
1131 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
1132 struct scatterlist *sg)
1134 if (unlikely(crypt_integrity_aead(cc)))
1140 static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
1142 struct bio_integrity_payload *bip;
1143 unsigned int tag_len;
1146 if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
1149 bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
1151 return PTR_ERR(bip);
1153 tag_len = io->cc->on_disk_tag_size * (bio_sectors(bio) >> io->cc->sector_shift);
1155 bip->bip_iter.bi_size = tag_len;
1156 bip->bip_iter.bi_sector = io->cc->start + io->sector;
1158 ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
1159 tag_len, offset_in_page(io->integrity_metadata));
1160 if (unlikely(ret != tag_len))
1166 static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
1168 #ifdef CONFIG_BLK_DEV_INTEGRITY
1169 struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
1170 struct mapped_device *md = dm_table_get_md(ti->table);
1172 /* From now we require underlying device with our integrity profile */
1173 if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
1174 ti->error = "Integrity profile not supported.";
1178 if (bi->tag_size != cc->on_disk_tag_size ||
1179 bi->tuple_size != cc->on_disk_tag_size) {
1180 ti->error = "Integrity profile tag size mismatch.";
1183 if (1 << bi->interval_exp != cc->sector_size) {
1184 ti->error = "Integrity profile sector size mismatch.";
1188 if (crypt_integrity_aead(cc)) {
1189 cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
1190 DMDEBUG("%s: Integrity AEAD, tag size %u, IV size %u.", dm_device_name(md),
1191 cc->integrity_tag_size, cc->integrity_iv_size);
1193 if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
1194 ti->error = "Integrity AEAD auth tag size is not supported.";
1197 } else if (cc->integrity_iv_size)
1198 DMDEBUG("%s: Additional per-sector space %u bytes for IV.", dm_device_name(md),
1199 cc->integrity_iv_size);
1201 if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
1202 ti->error = "Not enough space for integrity tag in the profile.";
1208 ti->error = "Integrity profile not supported.";
1213 static void crypt_convert_init(struct crypt_config *cc,
1214 struct convert_context *ctx,
1215 struct bio *bio_out, struct bio *bio_in,
1218 ctx->bio_in = bio_in;
1219 ctx->bio_out = bio_out;
1221 ctx->iter_in = bio_in->bi_iter;
1223 ctx->iter_out = bio_out->bi_iter;
1224 ctx->cc_sector = sector + cc->iv_offset;
1225 init_completion(&ctx->restart);
1228 static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
1231 return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
1234 static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
1236 return (void *)((char *)dmreq - cc->dmreq_start);
1239 static u8 *iv_of_dmreq(struct crypt_config *cc,
1240 struct dm_crypt_request *dmreq)
1242 if (crypt_integrity_aead(cc))
1243 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1244 crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
1246 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1247 crypto_skcipher_alignmask(any_tfm(cc)) + 1);
1250 static u8 *org_iv_of_dmreq(struct crypt_config *cc,
1251 struct dm_crypt_request *dmreq)
1253 return iv_of_dmreq(cc, dmreq) + cc->iv_size;
1256 static __le64 *org_sector_of_dmreq(struct crypt_config *cc,
1257 struct dm_crypt_request *dmreq)
1259 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
1260 return (__le64 *) ptr;
1263 static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
1264 struct dm_crypt_request *dmreq)
1266 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
1267 cc->iv_size + sizeof(uint64_t);
1268 return (unsigned int*)ptr;
1271 static void *tag_from_dmreq(struct crypt_config *cc,
1272 struct dm_crypt_request *dmreq)
1274 struct convert_context *ctx = dmreq->ctx;
1275 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1277 return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
1278 cc->on_disk_tag_size];
1281 static void *iv_tag_from_dmreq(struct crypt_config *cc,
1282 struct dm_crypt_request *dmreq)
1284 return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
1287 static int crypt_convert_block_aead(struct crypt_config *cc,
1288 struct convert_context *ctx,
1289 struct aead_request *req,
1290 unsigned int tag_offset)
1292 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1293 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1294 struct dm_crypt_request *dmreq;
1295 u8 *iv, *org_iv, *tag_iv, *tag;
1299 BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
1301 /* Reject unexpected unaligned bio. */
1302 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1305 dmreq = dmreq_of_req(cc, req);
1306 dmreq->iv_sector = ctx->cc_sector;
1307 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1308 dmreq->iv_sector >>= cc->sector_shift;
1311 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1313 sector = org_sector_of_dmreq(cc, dmreq);
1314 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1316 iv = iv_of_dmreq(cc, dmreq);
1317 org_iv = org_iv_of_dmreq(cc, dmreq);
1318 tag = tag_from_dmreq(cc, dmreq);
1319 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1322 * |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1323 * | (authenticated) | (auth+encryption) | |
1324 * | sector_LE | IV | sector in/out | tag in/out |
1326 sg_init_table(dmreq->sg_in, 4);
1327 sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
1328 sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
1329 sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1330 sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
1332 sg_init_table(dmreq->sg_out, 4);
1333 sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
1334 sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
1335 sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1336 sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
1338 if (cc->iv_gen_ops) {
1339 /* For READs use IV stored in integrity metadata */
1340 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1341 memcpy(org_iv, tag_iv, cc->iv_size);
1343 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1346 /* Store generated IV in integrity metadata */
1347 if (cc->integrity_iv_size)
1348 memcpy(tag_iv, org_iv, cc->iv_size);
1350 /* Working copy of IV, to be modified in crypto API */
1351 memcpy(iv, org_iv, cc->iv_size);
1354 aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
1355 if (bio_data_dir(ctx->bio_in) == WRITE) {
1356 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1357 cc->sector_size, iv);
1358 r = crypto_aead_encrypt(req);
1359 if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
1360 memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
1361 cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
1363 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1364 cc->sector_size + cc->integrity_tag_size, iv);
1365 r = crypto_aead_decrypt(req);
1368 if (r == -EBADMSG) {
1369 sector_t s = le64_to_cpu(*sector);
1371 DMERR_LIMIT("%pg: INTEGRITY AEAD ERROR, sector %llu",
1372 ctx->bio_in->bi_bdev, s);
1373 dm_audit_log_bio(DM_MSG_PREFIX, "integrity-aead",
1377 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1378 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1380 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1381 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1386 static int crypt_convert_block_skcipher(struct crypt_config *cc,
1387 struct convert_context *ctx,
1388 struct skcipher_request *req,
1389 unsigned int tag_offset)
1391 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1392 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1393 struct scatterlist *sg_in, *sg_out;
1394 struct dm_crypt_request *dmreq;
1395 u8 *iv, *org_iv, *tag_iv;
1399 /* Reject unexpected unaligned bio. */
1400 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1403 dmreq = dmreq_of_req(cc, req);
1404 dmreq->iv_sector = ctx->cc_sector;
1405 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1406 dmreq->iv_sector >>= cc->sector_shift;
1409 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1411 iv = iv_of_dmreq(cc, dmreq);
1412 org_iv = org_iv_of_dmreq(cc, dmreq);
1413 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1415 sector = org_sector_of_dmreq(cc, dmreq);
1416 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1418 /* For skcipher we use only the first sg item */
1419 sg_in = &dmreq->sg_in[0];
1420 sg_out = &dmreq->sg_out[0];
1422 sg_init_table(sg_in, 1);
1423 sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1425 sg_init_table(sg_out, 1);
1426 sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1428 if (cc->iv_gen_ops) {
1429 /* For READs use IV stored in integrity metadata */
1430 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1431 memcpy(org_iv, tag_iv, cc->integrity_iv_size);
1433 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1436 /* Data can be already preprocessed in generator */
1437 if (test_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags))
1439 /* Store generated IV in integrity metadata */
1440 if (cc->integrity_iv_size)
1441 memcpy(tag_iv, org_iv, cc->integrity_iv_size);
1443 /* Working copy of IV, to be modified in crypto API */
1444 memcpy(iv, org_iv, cc->iv_size);
1447 skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
1449 if (bio_data_dir(ctx->bio_in) == WRITE)
1450 r = crypto_skcipher_encrypt(req);
1452 r = crypto_skcipher_decrypt(req);
1454 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1455 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1457 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1458 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1463 static void kcryptd_async_done(struct crypto_async_request *async_req,
1466 static int crypt_alloc_req_skcipher(struct crypt_config *cc,
1467 struct convert_context *ctx)
1469 unsigned int key_index = ctx->cc_sector & (cc->tfms_count - 1);
1472 ctx->r.req = mempool_alloc(&cc->req_pool, in_interrupt() ? GFP_ATOMIC : GFP_NOIO);
1477 skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
1480 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1481 * requests if driver request queue is full.
1483 skcipher_request_set_callback(ctx->r.req,
1484 CRYPTO_TFM_REQ_MAY_BACKLOG,
1485 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
1490 static int crypt_alloc_req_aead(struct crypt_config *cc,
1491 struct convert_context *ctx)
1493 if (!ctx->r.req_aead) {
1494 ctx->r.req_aead = mempool_alloc(&cc->req_pool, in_interrupt() ? GFP_ATOMIC : GFP_NOIO);
1495 if (!ctx->r.req_aead)
1499 aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
1502 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1503 * requests if driver request queue is full.
1505 aead_request_set_callback(ctx->r.req_aead,
1506 CRYPTO_TFM_REQ_MAY_BACKLOG,
1507 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
1512 static int crypt_alloc_req(struct crypt_config *cc,
1513 struct convert_context *ctx)
1515 if (crypt_integrity_aead(cc))
1516 return crypt_alloc_req_aead(cc, ctx);
1518 return crypt_alloc_req_skcipher(cc, ctx);
1521 static void crypt_free_req_skcipher(struct crypt_config *cc,
1522 struct skcipher_request *req, struct bio *base_bio)
1524 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1526 if ((struct skcipher_request *)(io + 1) != req)
1527 mempool_free(req, &cc->req_pool);
1530 static void crypt_free_req_aead(struct crypt_config *cc,
1531 struct aead_request *req, struct bio *base_bio)
1533 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1535 if ((struct aead_request *)(io + 1) != req)
1536 mempool_free(req, &cc->req_pool);
1539 static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
1541 if (crypt_integrity_aead(cc))
1542 crypt_free_req_aead(cc, req, base_bio);
1544 crypt_free_req_skcipher(cc, req, base_bio);
1548 * Encrypt / decrypt data from one bio to another one (can be the same one)
1550 static blk_status_t crypt_convert(struct crypt_config *cc,
1551 struct convert_context *ctx, bool atomic, bool reset_pending)
1553 unsigned int tag_offset = 0;
1554 unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
1558 * if reset_pending is set we are dealing with the bio for the first time,
1559 * else we're continuing to work on the previous bio, so don't mess with
1560 * the cc_pending counter
1563 atomic_set(&ctx->cc_pending, 1);
1565 while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
1567 r = crypt_alloc_req(cc, ctx);
1569 complete(&ctx->restart);
1570 return BLK_STS_DEV_RESOURCE;
1573 atomic_inc(&ctx->cc_pending);
1575 if (crypt_integrity_aead(cc))
1576 r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
1578 r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
1582 * The request was queued by a crypto driver
1583 * but the driver request queue is full, let's wait.
1586 if (in_interrupt()) {
1587 if (try_wait_for_completion(&ctx->restart)) {
1589 * we don't have to block to wait for completion,
1594 * we can't wait for completion without blocking
1595 * exit and continue processing in a workqueue
1598 ctx->cc_sector += sector_step;
1600 return BLK_STS_DEV_RESOURCE;
1603 wait_for_completion(&ctx->restart);
1605 reinit_completion(&ctx->restart);
1608 * The request is queued and processed asynchronously,
1609 * completion function kcryptd_async_done() will be called.
1613 ctx->cc_sector += sector_step;
1617 * The request was already processed (synchronously).
1620 atomic_dec(&ctx->cc_pending);
1621 ctx->cc_sector += sector_step;
1627 * There was a data integrity error.
1630 atomic_dec(&ctx->cc_pending);
1631 return BLK_STS_PROTECTION;
1633 * There was an error while processing the request.
1636 atomic_dec(&ctx->cc_pending);
1637 return BLK_STS_IOERR;
1644 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
1647 * Generate a new unfragmented bio with the given size
1648 * This should never violate the device limitations (but only because
1649 * max_segment_size is being constrained to PAGE_SIZE).
1651 * This function may be called concurrently. If we allocate from the mempool
1652 * concurrently, there is a possibility of deadlock. For example, if we have
1653 * mempool of 256 pages, two processes, each wanting 256, pages allocate from
1654 * the mempool concurrently, it may deadlock in a situation where both processes
1655 * have allocated 128 pages and the mempool is exhausted.
1657 * In order to avoid this scenario we allocate the pages under a mutex.
1659 * In order to not degrade performance with excessive locking, we try
1660 * non-blocking allocations without a mutex first but on failure we fallback
1661 * to blocking allocations with a mutex.
1663 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned int size)
1665 struct crypt_config *cc = io->cc;
1667 unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1668 gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
1669 unsigned int i, len, remaining_size;
1673 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1674 mutex_lock(&cc->bio_alloc_lock);
1676 clone = bio_alloc_bioset(cc->dev->bdev, nr_iovecs, io->base_bio->bi_opf,
1678 clone->bi_private = io;
1679 clone->bi_end_io = crypt_endio;
1681 remaining_size = size;
1683 for (i = 0; i < nr_iovecs; i++) {
1684 page = mempool_alloc(&cc->page_pool, gfp_mask);
1686 crypt_free_buffer_pages(cc, clone);
1688 gfp_mask |= __GFP_DIRECT_RECLAIM;
1692 len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
1694 bio_add_page(clone, page, len, 0);
1696 remaining_size -= len;
1699 /* Allocate space for integrity tags */
1700 if (dm_crypt_integrity_io_alloc(io, clone)) {
1701 crypt_free_buffer_pages(cc, clone);
1706 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1707 mutex_unlock(&cc->bio_alloc_lock);
1712 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1715 struct bvec_iter_all iter_all;
1717 bio_for_each_segment_all(bv, clone, iter_all) {
1718 BUG_ON(!bv->bv_page);
1719 mempool_free(bv->bv_page, &cc->page_pool);
1723 static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1724 struct bio *bio, sector_t sector)
1728 io->sector = sector;
1730 io->ctx.r.req = NULL;
1731 io->integrity_metadata = NULL;
1732 io->integrity_metadata_from_pool = false;
1733 io->in_tasklet = false;
1734 atomic_set(&io->io_pending, 0);
1737 static void crypt_inc_pending(struct dm_crypt_io *io)
1739 atomic_inc(&io->io_pending);
1742 static void kcryptd_io_bio_endio(struct work_struct *work)
1744 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1745 bio_endio(io->base_bio);
1749 * One of the bios was finished. Check for completion of
1750 * the whole request and correctly clean up the buffer.
1752 static void crypt_dec_pending(struct dm_crypt_io *io)
1754 struct crypt_config *cc = io->cc;
1755 struct bio *base_bio = io->base_bio;
1756 blk_status_t error = io->error;
1758 if (!atomic_dec_and_test(&io->io_pending))
1762 crypt_free_req(cc, io->ctx.r.req, base_bio);
1764 if (unlikely(io->integrity_metadata_from_pool))
1765 mempool_free(io->integrity_metadata, &io->cc->tag_pool);
1767 kfree(io->integrity_metadata);
1769 base_bio->bi_status = error;
1772 * If we are running this function from our tasklet,
1773 * we can't call bio_endio() here, because it will call
1774 * clone_endio() from dm.c, which in turn will
1775 * free the current struct dm_crypt_io structure with
1776 * our tasklet. In this case we need to delay bio_endio()
1777 * execution to after the tasklet is done and dequeued.
1779 if (io->in_tasklet) {
1780 INIT_WORK(&io->work, kcryptd_io_bio_endio);
1781 queue_work(cc->io_queue, &io->work);
1785 bio_endio(base_bio);
1789 * kcryptd/kcryptd_io:
1791 * Needed because it would be very unwise to do decryption in an
1792 * interrupt context.
1794 * kcryptd performs the actual encryption or decryption.
1796 * kcryptd_io performs the IO submission.
1798 * They must be separated as otherwise the final stages could be
1799 * starved by new requests which can block in the first stages due
1800 * to memory allocation.
1802 * The work is done per CPU global for all dm-crypt instances.
1803 * They should not depend on each other and do not block.
1805 static void crypt_endio(struct bio *clone)
1807 struct dm_crypt_io *io = clone->bi_private;
1808 struct crypt_config *cc = io->cc;
1809 unsigned int rw = bio_data_dir(clone);
1813 * free the processed pages
1816 crypt_free_buffer_pages(cc, clone);
1818 error = clone->bi_status;
1821 if (rw == READ && !error) {
1822 kcryptd_queue_crypt(io);
1826 if (unlikely(error))
1829 crypt_dec_pending(io);
1832 #define CRYPT_MAP_READ_GFP GFP_NOWAIT
1834 static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
1836 struct crypt_config *cc = io->cc;
1840 * We need the original biovec array in order to decrypt the whole bio
1841 * data *afterwards* -- thanks to immutable biovecs we don't need to
1842 * worry about the block layer modifying the biovec array; so leverage
1843 * bio_alloc_clone().
1845 clone = bio_alloc_clone(cc->dev->bdev, io->base_bio, gfp, &cc->bs);
1848 clone->bi_private = io;
1849 clone->bi_end_io = crypt_endio;
1851 crypt_inc_pending(io);
1853 clone->bi_iter.bi_sector = cc->start + io->sector;
1855 if (dm_crypt_integrity_io_alloc(io, clone)) {
1856 crypt_dec_pending(io);
1861 dm_submit_bio_remap(io->base_bio, clone);
1865 static void kcryptd_io_read_work(struct work_struct *work)
1867 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1869 crypt_inc_pending(io);
1870 if (kcryptd_io_read(io, GFP_NOIO))
1871 io->error = BLK_STS_RESOURCE;
1872 crypt_dec_pending(io);
1875 static void kcryptd_queue_read(struct dm_crypt_io *io)
1877 struct crypt_config *cc = io->cc;
1879 INIT_WORK(&io->work, kcryptd_io_read_work);
1880 queue_work(cc->io_queue, &io->work);
1883 static void kcryptd_io_write(struct dm_crypt_io *io)
1885 struct bio *clone = io->ctx.bio_out;
1887 dm_submit_bio_remap(io->base_bio, clone);
1890 #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1892 static int dmcrypt_write(void *data)
1894 struct crypt_config *cc = data;
1895 struct dm_crypt_io *io;
1898 struct rb_root write_tree;
1899 struct blk_plug plug;
1901 spin_lock_irq(&cc->write_thread_lock);
1904 if (!RB_EMPTY_ROOT(&cc->write_tree))
1907 set_current_state(TASK_INTERRUPTIBLE);
1909 spin_unlock_irq(&cc->write_thread_lock);
1911 if (unlikely(kthread_should_stop())) {
1912 set_current_state(TASK_RUNNING);
1918 set_current_state(TASK_RUNNING);
1919 spin_lock_irq(&cc->write_thread_lock);
1920 goto continue_locked;
1923 write_tree = cc->write_tree;
1924 cc->write_tree = RB_ROOT;
1925 spin_unlock_irq(&cc->write_thread_lock);
1927 BUG_ON(rb_parent(write_tree.rb_node));
1930 * Note: we cannot walk the tree here with rb_next because
1931 * the structures may be freed when kcryptd_io_write is called.
1933 blk_start_plug(&plug);
1935 io = crypt_io_from_node(rb_first(&write_tree));
1936 rb_erase(&io->rb_node, &write_tree);
1937 kcryptd_io_write(io);
1939 } while (!RB_EMPTY_ROOT(&write_tree));
1940 blk_finish_plug(&plug);
1945 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
1947 struct bio *clone = io->ctx.bio_out;
1948 struct crypt_config *cc = io->cc;
1949 unsigned long flags;
1951 struct rb_node **rbp, *parent;
1953 if (unlikely(io->error)) {
1954 crypt_free_buffer_pages(cc, clone);
1956 crypt_dec_pending(io);
1960 /* crypt_convert should have filled the clone bio */
1961 BUG_ON(io->ctx.iter_out.bi_size);
1963 clone->bi_iter.bi_sector = cc->start + io->sector;
1965 if ((likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) ||
1966 test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags)) {
1967 dm_submit_bio_remap(io->base_bio, clone);
1971 spin_lock_irqsave(&cc->write_thread_lock, flags);
1972 if (RB_EMPTY_ROOT(&cc->write_tree))
1973 wake_up_process(cc->write_thread);
1974 rbp = &cc->write_tree.rb_node;
1976 sector = io->sector;
1979 if (sector < crypt_io_from_node(parent)->sector)
1980 rbp = &(*rbp)->rb_left;
1982 rbp = &(*rbp)->rb_right;
1984 rb_link_node(&io->rb_node, parent, rbp);
1985 rb_insert_color(&io->rb_node, &cc->write_tree);
1986 spin_unlock_irqrestore(&cc->write_thread_lock, flags);
1989 static bool kcryptd_crypt_write_inline(struct crypt_config *cc,
1990 struct convert_context *ctx)
1993 if (!test_bit(DM_CRYPT_WRITE_INLINE, &cc->flags))
1997 * Note: zone append writes (REQ_OP_ZONE_APPEND) do not have ordering
1998 * constraints so they do not need to be issued inline by
1999 * kcryptd_crypt_write_convert().
2001 switch (bio_op(ctx->bio_in)) {
2003 case REQ_OP_WRITE_ZEROES:
2010 static void kcryptd_crypt_write_continue(struct work_struct *work)
2012 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2013 struct crypt_config *cc = io->cc;
2014 struct convert_context *ctx = &io->ctx;
2016 sector_t sector = io->sector;
2019 wait_for_completion(&ctx->restart);
2020 reinit_completion(&ctx->restart);
2022 r = crypt_convert(cc, &io->ctx, true, false);
2025 crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
2026 if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
2027 /* Wait for completion signaled by kcryptd_async_done() */
2028 wait_for_completion(&ctx->restart);
2032 /* Encryption was already finished, submit io now */
2033 if (crypt_finished) {
2034 kcryptd_crypt_write_io_submit(io, 0);
2035 io->sector = sector;
2038 crypt_dec_pending(io);
2041 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
2043 struct crypt_config *cc = io->cc;
2044 struct convert_context *ctx = &io->ctx;
2047 sector_t sector = io->sector;
2051 * Prevent io from disappearing until this function completes.
2053 crypt_inc_pending(io);
2054 crypt_convert_init(cc, ctx, NULL, io->base_bio, sector);
2056 clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
2057 if (unlikely(!clone)) {
2058 io->error = BLK_STS_IOERR;
2062 io->ctx.bio_out = clone;
2063 io->ctx.iter_out = clone->bi_iter;
2065 sector += bio_sectors(clone);
2067 crypt_inc_pending(io);
2068 r = crypt_convert(cc, ctx,
2069 test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags), true);
2071 * Crypto API backlogged the request, because its queue was full
2072 * and we're in softirq context, so continue from a workqueue
2073 * (TODO: is it actually possible to be in softirq in the write path?)
2075 if (r == BLK_STS_DEV_RESOURCE) {
2076 INIT_WORK(&io->work, kcryptd_crypt_write_continue);
2077 queue_work(cc->crypt_queue, &io->work);
2082 crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
2083 if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
2084 /* Wait for completion signaled by kcryptd_async_done() */
2085 wait_for_completion(&ctx->restart);
2089 /* Encryption was already finished, submit io now */
2090 if (crypt_finished) {
2091 kcryptd_crypt_write_io_submit(io, 0);
2092 io->sector = sector;
2096 crypt_dec_pending(io);
2099 static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
2101 crypt_dec_pending(io);
2104 static void kcryptd_crypt_read_continue(struct work_struct *work)
2106 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2107 struct crypt_config *cc = io->cc;
2110 wait_for_completion(&io->ctx.restart);
2111 reinit_completion(&io->ctx.restart);
2113 r = crypt_convert(cc, &io->ctx, true, false);
2117 if (atomic_dec_and_test(&io->ctx.cc_pending))
2118 kcryptd_crypt_read_done(io);
2120 crypt_dec_pending(io);
2123 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
2125 struct crypt_config *cc = io->cc;
2128 crypt_inc_pending(io);
2130 crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
2133 r = crypt_convert(cc, &io->ctx,
2134 test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags), true);
2136 * Crypto API backlogged the request, because its queue was full
2137 * and we're in softirq context, so continue from a workqueue
2139 if (r == BLK_STS_DEV_RESOURCE) {
2140 INIT_WORK(&io->work, kcryptd_crypt_read_continue);
2141 queue_work(cc->crypt_queue, &io->work);
2147 if (atomic_dec_and_test(&io->ctx.cc_pending))
2148 kcryptd_crypt_read_done(io);
2150 crypt_dec_pending(io);
2153 static void kcryptd_async_done(struct crypto_async_request *async_req,
2156 struct dm_crypt_request *dmreq = async_req->data;
2157 struct convert_context *ctx = dmreq->ctx;
2158 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
2159 struct crypt_config *cc = io->cc;
2162 * A request from crypto driver backlog is going to be processed now,
2163 * finish the completion and continue in crypt_convert().
2164 * (Callback will be called for the second time for this request.)
2166 if (error == -EINPROGRESS) {
2167 complete(&ctx->restart);
2171 if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
2172 error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
2174 if (error == -EBADMSG) {
2175 sector_t s = le64_to_cpu(*org_sector_of_dmreq(cc, dmreq));
2177 DMERR_LIMIT("%pg: INTEGRITY AEAD ERROR, sector %llu",
2178 ctx->bio_in->bi_bdev, s);
2179 dm_audit_log_bio(DM_MSG_PREFIX, "integrity-aead",
2181 io->error = BLK_STS_PROTECTION;
2182 } else if (error < 0)
2183 io->error = BLK_STS_IOERR;
2185 crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
2187 if (!atomic_dec_and_test(&ctx->cc_pending))
2191 * The request is fully completed: for inline writes, let
2192 * kcryptd_crypt_write_convert() do the IO submission.
2194 if (bio_data_dir(io->base_bio) == READ) {
2195 kcryptd_crypt_read_done(io);
2199 if (kcryptd_crypt_write_inline(cc, ctx)) {
2200 complete(&ctx->restart);
2204 kcryptd_crypt_write_io_submit(io, 1);
2207 static void kcryptd_crypt(struct work_struct *work)
2209 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2211 if (bio_data_dir(io->base_bio) == READ)
2212 kcryptd_crypt_read_convert(io);
2214 kcryptd_crypt_write_convert(io);
2217 static void kcryptd_crypt_tasklet(unsigned long work)
2219 kcryptd_crypt((struct work_struct *)work);
2222 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
2224 struct crypt_config *cc = io->cc;
2226 if ((bio_data_dir(io->base_bio) == READ && test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags)) ||
2227 (bio_data_dir(io->base_bio) == WRITE && test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))) {
2229 * in_hardirq(): Crypto API's skcipher_walk_first() refuses to work in hard IRQ context.
2230 * irqs_disabled(): the kernel may run some IO completion from the idle thread, but
2231 * it is being executed with irqs disabled.
2233 if (in_hardirq() || irqs_disabled()) {
2234 io->in_tasklet = true;
2235 tasklet_init(&io->tasklet, kcryptd_crypt_tasklet, (unsigned long)&io->work);
2236 tasklet_schedule(&io->tasklet);
2240 kcryptd_crypt(&io->work);
2244 INIT_WORK(&io->work, kcryptd_crypt);
2245 queue_work(cc->crypt_queue, &io->work);
2248 static void crypt_free_tfms_aead(struct crypt_config *cc)
2250 if (!cc->cipher_tfm.tfms_aead)
2253 if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2254 crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
2255 cc->cipher_tfm.tfms_aead[0] = NULL;
2258 kfree(cc->cipher_tfm.tfms_aead);
2259 cc->cipher_tfm.tfms_aead = NULL;
2262 static void crypt_free_tfms_skcipher(struct crypt_config *cc)
2266 if (!cc->cipher_tfm.tfms)
2269 for (i = 0; i < cc->tfms_count; i++)
2270 if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
2271 crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
2272 cc->cipher_tfm.tfms[i] = NULL;
2275 kfree(cc->cipher_tfm.tfms);
2276 cc->cipher_tfm.tfms = NULL;
2279 static void crypt_free_tfms(struct crypt_config *cc)
2281 if (crypt_integrity_aead(cc))
2282 crypt_free_tfms_aead(cc);
2284 crypt_free_tfms_skcipher(cc);
2287 static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
2292 cc->cipher_tfm.tfms = kcalloc(cc->tfms_count,
2293 sizeof(struct crypto_skcipher *),
2295 if (!cc->cipher_tfm.tfms)
2298 for (i = 0; i < cc->tfms_count; i++) {
2299 cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0,
2300 CRYPTO_ALG_ALLOCATES_MEMORY);
2301 if (IS_ERR(cc->cipher_tfm.tfms[i])) {
2302 err = PTR_ERR(cc->cipher_tfm.tfms[i]);
2303 crypt_free_tfms(cc);
2309 * dm-crypt performance can vary greatly depending on which crypto
2310 * algorithm implementation is used. Help people debug performance
2311 * problems by logging the ->cra_driver_name.
2313 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2314 crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
2318 static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
2322 cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
2323 if (!cc->cipher_tfm.tfms)
2326 cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0,
2327 CRYPTO_ALG_ALLOCATES_MEMORY);
2328 if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2329 err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
2330 crypt_free_tfms(cc);
2334 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2335 crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
2339 static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
2341 if (crypt_integrity_aead(cc))
2342 return crypt_alloc_tfms_aead(cc, ciphermode);
2344 return crypt_alloc_tfms_skcipher(cc, ciphermode);
2347 static unsigned int crypt_subkey_size(struct crypt_config *cc)
2349 return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
2352 static unsigned int crypt_authenckey_size(struct crypt_config *cc)
2354 return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
2358 * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
2359 * the key must be for some reason in special format.
2360 * This funcion converts cc->key to this special format.
2362 static void crypt_copy_authenckey(char *p, const void *key,
2363 unsigned int enckeylen, unsigned int authkeylen)
2365 struct crypto_authenc_key_param *param;
2368 rta = (struct rtattr *)p;
2369 param = RTA_DATA(rta);
2370 param->enckeylen = cpu_to_be32(enckeylen);
2371 rta->rta_len = RTA_LENGTH(sizeof(*param));
2372 rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
2373 p += RTA_SPACE(sizeof(*param));
2374 memcpy(p, key + enckeylen, authkeylen);
2376 memcpy(p, key, enckeylen);
2379 static int crypt_setkey(struct crypt_config *cc)
2381 unsigned int subkey_size;
2384 /* Ignore extra keys (which are used for IV etc) */
2385 subkey_size = crypt_subkey_size(cc);
2387 if (crypt_integrity_hmac(cc)) {
2388 if (subkey_size < cc->key_mac_size)
2391 crypt_copy_authenckey(cc->authenc_key, cc->key,
2392 subkey_size - cc->key_mac_size,
2396 for (i = 0; i < cc->tfms_count; i++) {
2397 if (crypt_integrity_hmac(cc))
2398 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2399 cc->authenc_key, crypt_authenckey_size(cc));
2400 else if (crypt_integrity_aead(cc))
2401 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2402 cc->key + (i * subkey_size),
2405 r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
2406 cc->key + (i * subkey_size),
2412 if (crypt_integrity_hmac(cc))
2413 memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
2420 static bool contains_whitespace(const char *str)
2423 if (isspace(*str++))
2428 static int set_key_user(struct crypt_config *cc, struct key *key)
2430 const struct user_key_payload *ukp;
2432 ukp = user_key_payload_locked(key);
2434 return -EKEYREVOKED;
2436 if (cc->key_size != ukp->datalen)
2439 memcpy(cc->key, ukp->data, cc->key_size);
2444 static int set_key_encrypted(struct crypt_config *cc, struct key *key)
2446 const struct encrypted_key_payload *ekp;
2448 ekp = key->payload.data[0];
2450 return -EKEYREVOKED;
2452 if (cc->key_size != ekp->decrypted_datalen)
2455 memcpy(cc->key, ekp->decrypted_data, cc->key_size);
2460 static int set_key_trusted(struct crypt_config *cc, struct key *key)
2462 const struct trusted_key_payload *tkp;
2464 tkp = key->payload.data[0];
2466 return -EKEYREVOKED;
2468 if (cc->key_size != tkp->key_len)
2471 memcpy(cc->key, tkp->key, cc->key_size);
2476 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2478 char *new_key_string, *key_desc;
2480 struct key_type *type;
2482 int (*set_key)(struct crypt_config *cc, struct key *key);
2485 * Reject key_string with whitespace. dm core currently lacks code for
2486 * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2488 if (contains_whitespace(key_string)) {
2489 DMERR("whitespace chars not allowed in key string");
2493 /* look for next ':' separating key_type from key_description */
2494 key_desc = strpbrk(key_string, ":");
2495 if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2498 if (!strncmp(key_string, "logon:", key_desc - key_string + 1)) {
2499 type = &key_type_logon;
2500 set_key = set_key_user;
2501 } else if (!strncmp(key_string, "user:", key_desc - key_string + 1)) {
2502 type = &key_type_user;
2503 set_key = set_key_user;
2504 } else if (IS_ENABLED(CONFIG_ENCRYPTED_KEYS) &&
2505 !strncmp(key_string, "encrypted:", key_desc - key_string + 1)) {
2506 type = &key_type_encrypted;
2507 set_key = set_key_encrypted;
2508 } else if (IS_ENABLED(CONFIG_TRUSTED_KEYS) &&
2509 !strncmp(key_string, "trusted:", key_desc - key_string + 1)) {
2510 type = &key_type_trusted;
2511 set_key = set_key_trusted;
2516 new_key_string = kstrdup(key_string, GFP_KERNEL);
2517 if (!new_key_string)
2520 key = request_key(type, key_desc + 1, NULL);
2522 kfree_sensitive(new_key_string);
2523 return PTR_ERR(key);
2526 down_read(&key->sem);
2528 ret = set_key(cc, key);
2532 kfree_sensitive(new_key_string);
2539 /* clear the flag since following operations may invalidate previously valid key */
2540 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2542 ret = crypt_setkey(cc);
2545 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2546 kfree_sensitive(cc->key_string);
2547 cc->key_string = new_key_string;
2549 kfree_sensitive(new_key_string);
2554 static int get_key_size(char **key_string)
2559 if (*key_string[0] != ':')
2560 return strlen(*key_string) >> 1;
2562 /* look for next ':' in key string */
2563 colon = strpbrk(*key_string + 1, ":");
2567 if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2570 *key_string = colon;
2572 /* remaining key string should be :<logon|user>:<key_desc> */
2579 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2584 static int get_key_size(char **key_string)
2586 return (*key_string[0] == ':') ? -EINVAL : (int)(strlen(*key_string) >> 1);
2589 #endif /* CONFIG_KEYS */
2591 static int crypt_set_key(struct crypt_config *cc, char *key)
2594 int key_string_len = strlen(key);
2596 /* Hyphen (which gives a key_size of zero) means there is no key. */
2597 if (!cc->key_size && strcmp(key, "-"))
2600 /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2601 if (key[0] == ':') {
2602 r = crypt_set_keyring_key(cc, key + 1);
2606 /* clear the flag since following operations may invalidate previously valid key */
2607 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2609 /* wipe references to any kernel keyring key */
2610 kfree_sensitive(cc->key_string);
2611 cc->key_string = NULL;
2613 /* Decode key from its hex representation. */
2614 if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
2617 r = crypt_setkey(cc);
2619 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2622 /* Hex key string not needed after here, so wipe it. */
2623 memset(key, '0', key_string_len);
2628 static int crypt_wipe_key(struct crypt_config *cc)
2632 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2633 get_random_bytes(&cc->key, cc->key_size);
2635 /* Wipe IV private keys */
2636 if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
2637 r = cc->iv_gen_ops->wipe(cc);
2642 kfree_sensitive(cc->key_string);
2643 cc->key_string = NULL;
2644 r = crypt_setkey(cc);
2645 memset(&cc->key, 0, cc->key_size * sizeof(u8));
2650 static void crypt_calculate_pages_per_client(void)
2652 unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
2654 if (!dm_crypt_clients_n)
2657 pages /= dm_crypt_clients_n;
2658 if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
2659 pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
2660 dm_crypt_pages_per_client = pages;
2663 static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
2665 struct crypt_config *cc = pool_data;
2669 * Note, percpu_counter_read_positive() may over (and under) estimate
2670 * the current usage by at most (batch - 1) * num_online_cpus() pages,
2671 * but avoids potential spinlock contention of an exact result.
2673 if (unlikely(percpu_counter_read_positive(&cc->n_allocated_pages) >= dm_crypt_pages_per_client) &&
2674 likely(gfp_mask & __GFP_NORETRY))
2677 page = alloc_page(gfp_mask);
2678 if (likely(page != NULL))
2679 percpu_counter_add(&cc->n_allocated_pages, 1);
2684 static void crypt_page_free(void *page, void *pool_data)
2686 struct crypt_config *cc = pool_data;
2689 percpu_counter_sub(&cc->n_allocated_pages, 1);
2692 static void crypt_dtr(struct dm_target *ti)
2694 struct crypt_config *cc = ti->private;
2701 if (cc->write_thread)
2702 kthread_stop(cc->write_thread);
2705 destroy_workqueue(cc->io_queue);
2706 if (cc->crypt_queue)
2707 destroy_workqueue(cc->crypt_queue);
2709 crypt_free_tfms(cc);
2711 bioset_exit(&cc->bs);
2713 mempool_exit(&cc->page_pool);
2714 mempool_exit(&cc->req_pool);
2715 mempool_exit(&cc->tag_pool);
2717 WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
2718 percpu_counter_destroy(&cc->n_allocated_pages);
2720 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
2721 cc->iv_gen_ops->dtr(cc);
2724 dm_put_device(ti, cc->dev);
2726 kfree_sensitive(cc->cipher_string);
2727 kfree_sensitive(cc->key_string);
2728 kfree_sensitive(cc->cipher_auth);
2729 kfree_sensitive(cc->authenc_key);
2731 mutex_destroy(&cc->bio_alloc_lock);
2733 /* Must zero key material before freeing */
2734 kfree_sensitive(cc);
2736 spin_lock(&dm_crypt_clients_lock);
2737 WARN_ON(!dm_crypt_clients_n);
2738 dm_crypt_clients_n--;
2739 crypt_calculate_pages_per_client();
2740 spin_unlock(&dm_crypt_clients_lock);
2742 dm_audit_log_dtr(DM_MSG_PREFIX, ti, 1);
2745 static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
2747 struct crypt_config *cc = ti->private;
2749 if (crypt_integrity_aead(cc))
2750 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2752 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2755 /* at least a 64 bit sector number should fit in our buffer */
2756 cc->iv_size = max(cc->iv_size,
2757 (unsigned int)(sizeof(u64) / sizeof(u8)));
2759 DMWARN("Selected cipher does not support IVs");
2763 /* Choose ivmode, see comments at iv code. */
2765 cc->iv_gen_ops = NULL;
2766 else if (strcmp(ivmode, "plain") == 0)
2767 cc->iv_gen_ops = &crypt_iv_plain_ops;
2768 else if (strcmp(ivmode, "plain64") == 0)
2769 cc->iv_gen_ops = &crypt_iv_plain64_ops;
2770 else if (strcmp(ivmode, "plain64be") == 0)
2771 cc->iv_gen_ops = &crypt_iv_plain64be_ops;
2772 else if (strcmp(ivmode, "essiv") == 0)
2773 cc->iv_gen_ops = &crypt_iv_essiv_ops;
2774 else if (strcmp(ivmode, "benbi") == 0)
2775 cc->iv_gen_ops = &crypt_iv_benbi_ops;
2776 else if (strcmp(ivmode, "null") == 0)
2777 cc->iv_gen_ops = &crypt_iv_null_ops;
2778 else if (strcmp(ivmode, "eboiv") == 0)
2779 cc->iv_gen_ops = &crypt_iv_eboiv_ops;
2780 else if (strcmp(ivmode, "elephant") == 0) {
2781 cc->iv_gen_ops = &crypt_iv_elephant_ops;
2783 cc->key_extra_size = cc->key_size / 2;
2784 if (cc->key_extra_size > ELEPHANT_MAX_KEY_SIZE)
2786 set_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags);
2787 } else if (strcmp(ivmode, "lmk") == 0) {
2788 cc->iv_gen_ops = &crypt_iv_lmk_ops;
2790 * Version 2 and 3 is recognised according
2791 * to length of provided multi-key string.
2792 * If present (version 3), last key is used as IV seed.
2793 * All keys (including IV seed) are always the same size.
2795 if (cc->key_size % cc->key_parts) {
2797 cc->key_extra_size = cc->key_size / cc->key_parts;
2799 } else if (strcmp(ivmode, "tcw") == 0) {
2800 cc->iv_gen_ops = &crypt_iv_tcw_ops;
2801 cc->key_parts += 2; /* IV + whitening */
2802 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2803 } else if (strcmp(ivmode, "random") == 0) {
2804 cc->iv_gen_ops = &crypt_iv_random_ops;
2805 /* Need storage space in integrity fields. */
2806 cc->integrity_iv_size = cc->iv_size;
2808 ti->error = "Invalid IV mode";
2816 * Workaround to parse HMAC algorithm from AEAD crypto API spec.
2817 * The HMAC is needed to calculate tag size (HMAC digest size).
2818 * This should be probably done by crypto-api calls (once available...)
2820 static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
2822 char *start, *end, *mac_alg = NULL;
2823 struct crypto_ahash *mac;
2825 if (!strstarts(cipher_api, "authenc("))
2828 start = strchr(cipher_api, '(');
2829 end = strchr(cipher_api, ',');
2830 if (!start || !end || ++start > end)
2833 mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
2836 strncpy(mac_alg, start, end - start);
2838 mac = crypto_alloc_ahash(mac_alg, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
2842 return PTR_ERR(mac);
2844 cc->key_mac_size = crypto_ahash_digestsize(mac);
2845 crypto_free_ahash(mac);
2847 cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
2848 if (!cc->authenc_key)
2854 static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
2855 char **ivmode, char **ivopts)
2857 struct crypt_config *cc = ti->private;
2858 char *tmp, *cipher_api, buf[CRYPTO_MAX_ALG_NAME];
2864 * New format (capi: prefix)
2865 * capi:cipher_api_spec-iv:ivopts
2867 tmp = &cipher_in[strlen("capi:")];
2869 /* Separate IV options if present, it can contain another '-' in hash name */
2870 *ivopts = strrchr(tmp, ':');
2876 *ivmode = strrchr(tmp, '-');
2881 /* The rest is crypto API spec */
2884 /* Alloc AEAD, can be used only in new format. */
2885 if (crypt_integrity_aead(cc)) {
2886 ret = crypt_ctr_auth_cipher(cc, cipher_api);
2888 ti->error = "Invalid AEAD cipher spec";
2893 if (*ivmode && !strcmp(*ivmode, "lmk"))
2894 cc->tfms_count = 64;
2896 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2898 ti->error = "Digest algorithm missing for ESSIV mode";
2901 ret = snprintf(buf, CRYPTO_MAX_ALG_NAME, "essiv(%s,%s)",
2902 cipher_api, *ivopts);
2903 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2904 ti->error = "Cannot allocate cipher string";
2910 cc->key_parts = cc->tfms_count;
2912 /* Allocate cipher */
2913 ret = crypt_alloc_tfms(cc, cipher_api);
2915 ti->error = "Error allocating crypto tfm";
2919 if (crypt_integrity_aead(cc))
2920 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2922 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2927 static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
2928 char **ivmode, char **ivopts)
2930 struct crypt_config *cc = ti->private;
2931 char *tmp, *cipher, *chainmode, *keycount;
2932 char *cipher_api = NULL;
2936 if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
2937 ti->error = "Bad cipher specification";
2942 * Legacy dm-crypt cipher specification
2943 * cipher[:keycount]-mode-iv:ivopts
2946 keycount = strsep(&tmp, "-");
2947 cipher = strsep(&keycount, ":");
2951 else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
2952 !is_power_of_2(cc->tfms_count)) {
2953 ti->error = "Bad cipher key count specification";
2956 cc->key_parts = cc->tfms_count;
2958 chainmode = strsep(&tmp, "-");
2959 *ivmode = strsep(&tmp, ":");
2963 * For compatibility with the original dm-crypt mapping format, if
2964 * only the cipher name is supplied, use cbc-plain.
2966 if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
2971 if (strcmp(chainmode, "ecb") && !*ivmode) {
2972 ti->error = "IV mechanism required";
2976 cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
2980 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2982 ti->error = "Digest algorithm missing for ESSIV mode";
2986 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2987 "essiv(%s(%s),%s)", chainmode, cipher, *ivopts);
2989 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2990 "%s(%s)", chainmode, cipher);
2992 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2997 /* Allocate cipher */
2998 ret = crypt_alloc_tfms(cc, cipher_api);
3000 ti->error = "Error allocating crypto tfm";
3008 ti->error = "Cannot allocate cipher strings";
3012 static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
3014 struct crypt_config *cc = ti->private;
3015 char *ivmode = NULL, *ivopts = NULL;
3018 cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
3019 if (!cc->cipher_string) {
3020 ti->error = "Cannot allocate cipher strings";
3024 if (strstarts(cipher_in, "capi:"))
3025 ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
3027 ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
3032 ret = crypt_ctr_ivmode(ti, ivmode);
3036 /* Initialize and set key */
3037 ret = crypt_set_key(cc, key);
3039 ti->error = "Error decoding and setting key";
3044 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
3045 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
3047 ti->error = "Error creating IV";
3052 /* Initialize IV (set keys for ESSIV etc) */
3053 if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
3054 ret = cc->iv_gen_ops->init(cc);
3056 ti->error = "Error initialising IV";
3061 /* wipe the kernel key payload copy */
3063 memset(cc->key, 0, cc->key_size * sizeof(u8));
3068 static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
3070 struct crypt_config *cc = ti->private;
3071 struct dm_arg_set as;
3072 static const struct dm_arg _args[] = {
3073 {0, 8, "Invalid number of feature args"},
3075 unsigned int opt_params, val;
3076 const char *opt_string, *sval;
3080 /* Optional parameters */
3084 ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
3088 while (opt_params--) {
3089 opt_string = dm_shift_arg(&as);
3091 ti->error = "Not enough feature arguments";
3095 if (!strcasecmp(opt_string, "allow_discards"))
3096 ti->num_discard_bios = 1;
3098 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
3099 set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3101 else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
3102 set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3103 else if (!strcasecmp(opt_string, "no_read_workqueue"))
3104 set_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3105 else if (!strcasecmp(opt_string, "no_write_workqueue"))
3106 set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3107 else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
3108 if (val == 0 || val > MAX_TAG_SIZE) {
3109 ti->error = "Invalid integrity arguments";
3112 cc->on_disk_tag_size = val;
3113 sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
3114 if (!strcasecmp(sval, "aead")) {
3115 set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
3116 } else if (strcasecmp(sval, "none")) {
3117 ti->error = "Unknown integrity profile";
3121 cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
3122 if (!cc->cipher_auth)
3124 } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
3125 if (cc->sector_size < (1 << SECTOR_SHIFT) ||
3126 cc->sector_size > 4096 ||
3127 (cc->sector_size & (cc->sector_size - 1))) {
3128 ti->error = "Invalid feature value for sector_size";
3131 if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
3132 ti->error = "Device size is not multiple of sector_size feature";
3135 cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
3136 } else if (!strcasecmp(opt_string, "iv_large_sectors"))
3137 set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3139 ti->error = "Invalid feature arguments";
3147 #ifdef CONFIG_BLK_DEV_ZONED
3148 static int crypt_report_zones(struct dm_target *ti,
3149 struct dm_report_zones_args *args, unsigned int nr_zones)
3151 struct crypt_config *cc = ti->private;
3153 return dm_report_zones(cc->dev->bdev, cc->start,
3154 cc->start + dm_target_offset(ti, args->next_sector),
3158 #define crypt_report_zones NULL
3162 * Construct an encryption mapping:
3163 * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
3165 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
3167 struct crypt_config *cc;
3168 const char *devname = dm_table_device_name(ti->table);
3170 unsigned int align_mask;
3171 unsigned long long tmpll;
3173 size_t iv_size_padding, additional_req_size;
3177 ti->error = "Not enough arguments";
3181 key_size = get_key_size(&argv[1]);
3183 ti->error = "Cannot parse key size";
3187 cc = kzalloc(struct_size(cc, key, key_size), GFP_KERNEL);
3189 ti->error = "Cannot allocate encryption context";
3192 cc->key_size = key_size;
3193 cc->sector_size = (1 << SECTOR_SHIFT);
3194 cc->sector_shift = 0;
3198 spin_lock(&dm_crypt_clients_lock);
3199 dm_crypt_clients_n++;
3200 crypt_calculate_pages_per_client();
3201 spin_unlock(&dm_crypt_clients_lock);
3203 ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
3207 /* Optional parameters need to be read before cipher constructor */
3209 ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
3214 ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
3218 if (crypt_integrity_aead(cc)) {
3219 cc->dmreq_start = sizeof(struct aead_request);
3220 cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
3221 align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
3223 cc->dmreq_start = sizeof(struct skcipher_request);
3224 cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
3225 align_mask = crypto_skcipher_alignmask(any_tfm(cc));
3227 cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
3229 if (align_mask < CRYPTO_MINALIGN) {
3230 /* Allocate the padding exactly */
3231 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
3235 * If the cipher requires greater alignment than kmalloc
3236 * alignment, we don't know the exact position of the
3237 * initialization vector. We must assume worst case.
3239 iv_size_padding = align_mask;
3242 /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
3243 additional_req_size = sizeof(struct dm_crypt_request) +
3244 iv_size_padding + cc->iv_size +
3247 sizeof(unsigned int);
3249 ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
3251 ti->error = "Cannot allocate crypt request mempool";
3255 cc->per_bio_data_size = ti->per_io_data_size =
3256 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
3257 ARCH_KMALLOC_MINALIGN);
3259 ret = mempool_init(&cc->page_pool, BIO_MAX_VECS, crypt_page_alloc, crypt_page_free, cc);
3261 ti->error = "Cannot allocate page mempool";
3265 ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
3267 ti->error = "Cannot allocate crypt bioset";
3271 mutex_init(&cc->bio_alloc_lock);
3274 if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
3275 (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
3276 ti->error = "Invalid iv_offset sector";
3279 cc->iv_offset = tmpll;
3281 ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
3283 ti->error = "Device lookup failed";
3288 if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
3289 ti->error = "Invalid device sector";
3294 if (bdev_is_zoned(cc->dev->bdev)) {
3296 * For zoned block devices, we need to preserve the issuer write
3297 * ordering. To do so, disable write workqueues and force inline
3298 * encryption completion.
3300 set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3301 set_bit(DM_CRYPT_WRITE_INLINE, &cc->flags);
3304 * All zone append writes to a zone of a zoned block device will
3305 * have the same BIO sector, the start of the zone. When the
3306 * cypher IV mode uses sector values, all data targeting a
3307 * zone will be encrypted using the first sector numbers of the
3308 * zone. This will not result in write errors but will
3309 * cause most reads to fail as reads will use the sector values
3310 * for the actual data locations, resulting in IV mismatch.
3311 * To avoid this problem, ask DM core to emulate zone append
3312 * operations with regular writes.
3314 DMDEBUG("Zone append operations will be emulated");
3315 ti->emulate_zone_append = true;
3318 if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
3319 ret = crypt_integrity_ctr(cc, ti);
3323 cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
3324 if (!cc->tag_pool_max_sectors)
3325 cc->tag_pool_max_sectors = 1;
3327 ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
3328 cc->tag_pool_max_sectors * cc->on_disk_tag_size);
3330 ti->error = "Cannot allocate integrity tags mempool";
3334 cc->tag_pool_max_sectors <<= cc->sector_shift;
3338 cc->io_queue = alloc_workqueue("kcryptd_io/%s", WQ_MEM_RECLAIM, 1, devname);
3339 if (!cc->io_queue) {
3340 ti->error = "Couldn't create kcryptd io queue";
3344 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3345 cc->crypt_queue = alloc_workqueue("kcryptd/%s", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM,
3348 cc->crypt_queue = alloc_workqueue("kcryptd/%s",
3349 WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
3350 num_online_cpus(), devname);
3351 if (!cc->crypt_queue) {
3352 ti->error = "Couldn't create kcryptd queue";
3356 spin_lock_init(&cc->write_thread_lock);
3357 cc->write_tree = RB_ROOT;
3359 cc->write_thread = kthread_run(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
3360 if (IS_ERR(cc->write_thread)) {
3361 ret = PTR_ERR(cc->write_thread);
3362 cc->write_thread = NULL;
3363 ti->error = "Couldn't spawn write thread";
3367 ti->num_flush_bios = 1;
3368 ti->limit_swap_bios = true;
3369 ti->accounts_remapped_io = true;
3371 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 1);
3375 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 0);
3380 static int crypt_map(struct dm_target *ti, struct bio *bio)
3382 struct dm_crypt_io *io;
3383 struct crypt_config *cc = ti->private;
3386 * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
3387 * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
3388 * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
3390 if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
3391 bio_op(bio) == REQ_OP_DISCARD)) {
3392 bio_set_dev(bio, cc->dev->bdev);
3393 if (bio_sectors(bio))
3394 bio->bi_iter.bi_sector = cc->start +
3395 dm_target_offset(ti, bio->bi_iter.bi_sector);
3396 return DM_MAPIO_REMAPPED;
3400 * Check if bio is too large, split as needed.
3402 if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_VECS << PAGE_SHIFT)) &&
3403 (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
3404 dm_accept_partial_bio(bio, ((BIO_MAX_VECS << PAGE_SHIFT) >> SECTOR_SHIFT));
3407 * Ensure that bio is a multiple of internal sector encryption size
3408 * and is aligned to this size as defined in IO hints.
3410 if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
3411 return DM_MAPIO_KILL;
3413 if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
3414 return DM_MAPIO_KILL;
3416 io = dm_per_bio_data(bio, cc->per_bio_data_size);
3417 crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
3419 if (cc->on_disk_tag_size) {
3420 unsigned int tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
3422 if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
3423 unlikely(!(io->integrity_metadata = kmalloc(tag_len,
3424 GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
3425 if (bio_sectors(bio) > cc->tag_pool_max_sectors)
3426 dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
3427 io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
3428 io->integrity_metadata_from_pool = true;
3432 if (crypt_integrity_aead(cc))
3433 io->ctx.r.req_aead = (struct aead_request *)(io + 1);
3435 io->ctx.r.req = (struct skcipher_request *)(io + 1);
3437 if (bio_data_dir(io->base_bio) == READ) {
3438 if (kcryptd_io_read(io, CRYPT_MAP_READ_GFP))
3439 kcryptd_queue_read(io);
3441 kcryptd_queue_crypt(io);
3443 return DM_MAPIO_SUBMITTED;
3446 static char hex2asc(unsigned char c)
3448 return c + '0' + ((unsigned int)(9 - c) >> 4 & 0x27);
3451 static void crypt_status(struct dm_target *ti, status_type_t type,
3452 unsigned int status_flags, char *result, unsigned int maxlen)
3454 struct crypt_config *cc = ti->private;
3455 unsigned int i, sz = 0;
3456 int num_feature_args = 0;
3459 case STATUSTYPE_INFO:
3463 case STATUSTYPE_TABLE:
3464 DMEMIT("%s ", cc->cipher_string);
3466 if (cc->key_size > 0) {
3468 DMEMIT(":%u:%s", cc->key_size, cc->key_string);
3470 for (i = 0; i < cc->key_size; i++) {
3471 DMEMIT("%c%c", hex2asc(cc->key[i] >> 4),
3472 hex2asc(cc->key[i] & 0xf));
3478 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
3479 cc->dev->name, (unsigned long long)cc->start);
3481 num_feature_args += !!ti->num_discard_bios;
3482 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3483 num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3484 num_feature_args += test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3485 num_feature_args += test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3486 num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
3487 num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3488 if (cc->on_disk_tag_size)
3490 if (num_feature_args) {
3491 DMEMIT(" %d", num_feature_args);
3492 if (ti->num_discard_bios)
3493 DMEMIT(" allow_discards");
3494 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3495 DMEMIT(" same_cpu_crypt");
3496 if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
3497 DMEMIT(" submit_from_crypt_cpus");
3498 if (test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags))
3499 DMEMIT(" no_read_workqueue");
3500 if (test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))
3501 DMEMIT(" no_write_workqueue");
3502 if (cc->on_disk_tag_size)
3503 DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
3504 if (cc->sector_size != (1 << SECTOR_SHIFT))
3505 DMEMIT(" sector_size:%d", cc->sector_size);
3506 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
3507 DMEMIT(" iv_large_sectors");
3511 case STATUSTYPE_IMA:
3512 DMEMIT_TARGET_NAME_VERSION(ti->type);
3513 DMEMIT(",allow_discards=%c", ti->num_discard_bios ? 'y' : 'n');
3514 DMEMIT(",same_cpu_crypt=%c", test_bit(DM_CRYPT_SAME_CPU, &cc->flags) ? 'y' : 'n');
3515 DMEMIT(",submit_from_crypt_cpus=%c", test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags) ?
3517 DMEMIT(",no_read_workqueue=%c", test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags) ?
3519 DMEMIT(",no_write_workqueue=%c", test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags) ?
3521 DMEMIT(",iv_large_sectors=%c", test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags) ?
3524 if (cc->on_disk_tag_size)
3525 DMEMIT(",integrity_tag_size=%u,cipher_auth=%s",
3526 cc->on_disk_tag_size, cc->cipher_auth);
3527 if (cc->sector_size != (1 << SECTOR_SHIFT))
3528 DMEMIT(",sector_size=%d", cc->sector_size);
3529 if (cc->cipher_string)
3530 DMEMIT(",cipher_string=%s", cc->cipher_string);
3532 DMEMIT(",key_size=%u", cc->key_size);
3533 DMEMIT(",key_parts=%u", cc->key_parts);
3534 DMEMIT(",key_extra_size=%u", cc->key_extra_size);
3535 DMEMIT(",key_mac_size=%u", cc->key_mac_size);
3541 static void crypt_postsuspend(struct dm_target *ti)
3543 struct crypt_config *cc = ti->private;
3545 set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3548 static int crypt_preresume(struct dm_target *ti)
3550 struct crypt_config *cc = ti->private;
3552 if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
3553 DMERR("aborting resume - crypt key is not set.");
3560 static void crypt_resume(struct dm_target *ti)
3562 struct crypt_config *cc = ti->private;
3564 clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3567 /* Message interface
3571 static int crypt_message(struct dm_target *ti, unsigned int argc, char **argv,
3572 char *result, unsigned int maxlen)
3574 struct crypt_config *cc = ti->private;
3575 int key_size, ret = -EINVAL;
3580 if (!strcasecmp(argv[0], "key")) {
3581 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
3582 DMWARN("not suspended during key manipulation.");
3585 if (argc == 3 && !strcasecmp(argv[1], "set")) {
3586 /* The key size may not be changed. */
3587 key_size = get_key_size(&argv[2]);
3588 if (key_size < 0 || cc->key_size != key_size) {
3589 memset(argv[2], '0', strlen(argv[2]));
3593 ret = crypt_set_key(cc, argv[2]);
3596 if (cc->iv_gen_ops && cc->iv_gen_ops->init)
3597 ret = cc->iv_gen_ops->init(cc);
3598 /* wipe the kernel key payload copy */
3600 memset(cc->key, 0, cc->key_size * sizeof(u8));
3603 if (argc == 2 && !strcasecmp(argv[1], "wipe"))
3604 return crypt_wipe_key(cc);
3608 DMWARN("unrecognised message received.");
3612 static int crypt_iterate_devices(struct dm_target *ti,
3613 iterate_devices_callout_fn fn, void *data)
3615 struct crypt_config *cc = ti->private;
3617 return fn(ti, cc->dev, cc->start, ti->len, data);
3620 static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
3622 struct crypt_config *cc = ti->private;
3625 * Unfortunate constraint that is required to avoid the potential
3626 * for exceeding underlying device's max_segments limits -- due to
3627 * crypt_alloc_buffer() possibly allocating pages for the encryption
3628 * bio that are not as physically contiguous as the original bio.
3630 limits->max_segment_size = PAGE_SIZE;
3632 limits->logical_block_size =
3633 max_t(unsigned int, limits->logical_block_size, cc->sector_size);
3634 limits->physical_block_size =
3635 max_t(unsigned int, limits->physical_block_size, cc->sector_size);
3636 limits->io_min = max_t(unsigned int, limits->io_min, cc->sector_size);
3637 limits->dma_alignment = limits->logical_block_size - 1;
3640 static struct target_type crypt_target = {
3642 .version = {1, 24, 0},
3643 .module = THIS_MODULE,
3646 .features = DM_TARGET_ZONED_HM,
3647 .report_zones = crypt_report_zones,
3649 .status = crypt_status,
3650 .postsuspend = crypt_postsuspend,
3651 .preresume = crypt_preresume,
3652 .resume = crypt_resume,
3653 .message = crypt_message,
3654 .iterate_devices = crypt_iterate_devices,
3655 .io_hints = crypt_io_hints,
3658 static int __init dm_crypt_init(void)
3662 r = dm_register_target(&crypt_target);
3664 DMERR("register failed %d", r);
3669 static void __exit dm_crypt_exit(void)
3671 dm_unregister_target(&crypt_target);
3674 module_init(dm_crypt_init);
3675 module_exit(dm_crypt_exit);
3677 MODULE_AUTHOR("Jana Saout <jana@saout.de>");
3678 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
3679 MODULE_LICENSE("GPL");