1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2003 Jana Saout <jana@saout.de>
4 * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
5 * Copyright (C) 2006-2020 Red Hat, Inc. All rights reserved.
6 * Copyright (C) 2013-2020 Milan Broz <gmazyland@gmail.com>
8 * This file is released under the GPL.
11 #include <linux/completion.h>
12 #include <linux/err.h>
13 #include <linux/module.h>
14 #include <linux/init.h>
15 #include <linux/kernel.h>
16 #include <linux/key.h>
17 #include <linux/bio.h>
18 #include <linux/blkdev.h>
19 #include <linux/blk-integrity.h>
20 #include <linux/mempool.h>
21 #include <linux/slab.h>
22 #include <linux/crypto.h>
23 #include <linux/workqueue.h>
24 #include <linux/kthread.h>
25 #include <linux/backing-dev.h>
26 #include <linux/atomic.h>
27 #include <linux/scatterlist.h>
28 #include <linux/rbtree.h>
29 #include <linux/ctype.h>
31 #include <asm/unaligned.h>
32 #include <crypto/hash.h>
33 #include <crypto/md5.h>
34 #include <crypto/algapi.h>
35 #include <crypto/skcipher.h>
36 #include <crypto/aead.h>
37 #include <crypto/authenc.h>
38 #include <linux/rtnetlink.h> /* for struct rtattr and RTA macros only */
39 #include <linux/key-type.h>
40 #include <keys/user-type.h>
41 #include <keys/encrypted-type.h>
42 #include <keys/trusted-type.h>
44 #include <linux/device-mapper.h>
48 #define DM_MSG_PREFIX "crypt"
51 * context holding the current state of a multi-part conversion
53 struct convert_context {
54 struct completion restart;
57 struct bvec_iter iter_in;
58 struct bvec_iter iter_out;
62 struct skcipher_request *req;
63 struct aead_request *req_aead;
69 * per bio private data
72 struct crypt_config *cc;
74 u8 *integrity_metadata;
75 bool integrity_metadata_from_pool:1;
78 struct work_struct work;
79 struct tasklet_struct tasklet;
81 struct convert_context ctx;
87 struct rb_node rb_node;
88 } CRYPTO_MINALIGN_ATTR;
90 struct dm_crypt_request {
91 struct convert_context *ctx;
92 struct scatterlist sg_in[4];
93 struct scatterlist sg_out[4];
99 struct crypt_iv_operations {
100 int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
102 void (*dtr)(struct crypt_config *cc);
103 int (*init)(struct crypt_config *cc);
104 int (*wipe)(struct crypt_config *cc);
105 int (*generator)(struct crypt_config *cc, u8 *iv,
106 struct dm_crypt_request *dmreq);
107 int (*post)(struct crypt_config *cc, u8 *iv,
108 struct dm_crypt_request *dmreq);
111 struct iv_benbi_private {
115 #define LMK_SEED_SIZE 64 /* hash + 0 */
116 struct iv_lmk_private {
117 struct crypto_shash *hash_tfm;
121 #define TCW_WHITENING_SIZE 16
122 struct iv_tcw_private {
123 struct crypto_shash *crc32_tfm;
128 #define ELEPHANT_MAX_KEY_SIZE 32
129 struct iv_elephant_private {
130 struct crypto_skcipher *tfm;
134 * Crypt: maps a linear range of a block device
135 * and encrypts / decrypts at the same time.
137 enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
138 DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD,
139 DM_CRYPT_NO_READ_WORKQUEUE, DM_CRYPT_NO_WRITE_WORKQUEUE,
140 DM_CRYPT_WRITE_INLINE };
143 CRYPT_MODE_INTEGRITY_AEAD, /* Use authenticated mode for cipher */
144 CRYPT_IV_LARGE_SECTORS, /* Calculate IV from sector_size, not 512B sectors */
145 CRYPT_ENCRYPT_PREPROCESS, /* Must preprocess data for encryption (elephant) */
149 * The fields in here must be read only after initialization.
151 struct crypt_config {
155 struct percpu_counter n_allocated_pages;
157 struct workqueue_struct *io_queue;
158 struct workqueue_struct *crypt_queue;
160 spinlock_t write_thread_lock;
161 struct task_struct *write_thread;
162 struct rb_root write_tree;
168 const struct crypt_iv_operations *iv_gen_ops;
170 struct iv_benbi_private benbi;
171 struct iv_lmk_private lmk;
172 struct iv_tcw_private tcw;
173 struct iv_elephant_private elephant;
176 unsigned int iv_size;
177 unsigned short sector_size;
178 unsigned char sector_shift;
181 struct crypto_skcipher **tfms;
182 struct crypto_aead **tfms_aead;
184 unsigned int tfms_count;
185 unsigned long cipher_flags;
188 * Layout of each crypto request:
190 * struct skcipher_request
193 * struct dm_crypt_request
197 * The padding is added so that dm_crypt_request and the IV are
200 unsigned int dmreq_start;
202 unsigned int per_bio_data_size;
205 unsigned int key_size;
206 unsigned int key_parts; /* independent parts in key buffer */
207 unsigned int key_extra_size; /* additional keys length */
208 unsigned int key_mac_size; /* MAC key size for authenc(...) */
210 unsigned int integrity_tag_size;
211 unsigned int integrity_iv_size;
212 unsigned int on_disk_tag_size;
215 * pool for per bio private data, crypto requests,
216 * encryption requeusts/buffer pages and integrity tags
218 unsigned int tag_pool_max_sectors;
224 struct mutex bio_alloc_lock;
226 u8 *authenc_key; /* space for keys in authenc() format (if used) */
231 #define MAX_TAG_SIZE 480
232 #define POOL_ENTRY_SIZE 512
234 static DEFINE_SPINLOCK(dm_crypt_clients_lock);
235 static unsigned int dm_crypt_clients_n;
236 static volatile unsigned long dm_crypt_pages_per_client;
237 #define DM_CRYPT_MEMORY_PERCENT 2
238 #define DM_CRYPT_MIN_PAGES_PER_CLIENT (BIO_MAX_VECS * 16)
240 static void crypt_endio(struct bio *clone);
241 static void kcryptd_queue_crypt(struct dm_crypt_io *io);
242 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
243 struct scatterlist *sg);
245 static bool crypt_integrity_aead(struct crypt_config *cc);
248 * Use this to access cipher attributes that are independent of the key.
250 static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
252 return cc->cipher_tfm.tfms[0];
255 static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
257 return cc->cipher_tfm.tfms_aead[0];
261 * Different IV generation algorithms:
263 * plain: the initial vector is the 32-bit little-endian version of the sector
264 * number, padded with zeros if necessary.
266 * plain64: the initial vector is the 64-bit little-endian version of the sector
267 * number, padded with zeros if necessary.
269 * plain64be: the initial vector is the 64-bit big-endian version of the sector
270 * number, padded with zeros if necessary.
272 * essiv: "encrypted sector|salt initial vector", the sector number is
273 * encrypted with the bulk cipher using a salt as key. The salt
274 * should be derived from the bulk cipher's key via hashing.
276 * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
277 * (needed for LRW-32-AES and possible other narrow block modes)
279 * null: the initial vector is always zero. Provides compatibility with
280 * obsolete loop_fish2 devices. Do not use for new devices.
282 * lmk: Compatible implementation of the block chaining mode used
283 * by the Loop-AES block device encryption system
284 * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
285 * It operates on full 512 byte sectors and uses CBC
286 * with an IV derived from the sector number, the data and
287 * optionally extra IV seed.
288 * This means that after decryption the first block
289 * of sector must be tweaked according to decrypted data.
290 * Loop-AES can use three encryption schemes:
291 * version 1: is plain aes-cbc mode
292 * version 2: uses 64 multikey scheme with lmk IV generator
293 * version 3: the same as version 2 with additional IV seed
294 * (it uses 65 keys, last key is used as IV seed)
296 * tcw: Compatible implementation of the block chaining mode used
297 * by the TrueCrypt device encryption system (prior to version 4.1).
298 * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
299 * It operates on full 512 byte sectors and uses CBC
300 * with an IV derived from initial key and the sector number.
301 * In addition, whitening value is applied on every sector, whitening
302 * is calculated from initial key, sector number and mixed using CRC32.
303 * Note that this encryption scheme is vulnerable to watermarking attacks
304 * and should be used for old compatible containers access only.
306 * eboiv: Encrypted byte-offset IV (used in Bitlocker in CBC mode)
307 * The IV is encrypted little-endian byte-offset (with the same key
308 * and cipher as the volume).
310 * elephant: The extended version of eboiv with additional Elephant diffuser
311 * used with Bitlocker CBC mode.
312 * This mode was used in older Windows systems
313 * https://download.microsoft.com/download/0/2/3/0238acaf-d3bf-4a6d-b3d6-0a0be4bbb36e/bitlockercipher200608.pdf
316 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
317 struct dm_crypt_request *dmreq)
319 memset(iv, 0, cc->iv_size);
320 *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
325 static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
326 struct dm_crypt_request *dmreq)
328 memset(iv, 0, cc->iv_size);
329 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
334 static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
335 struct dm_crypt_request *dmreq)
337 memset(iv, 0, cc->iv_size);
338 /* iv_size is at least of size u64; usually it is 16 bytes */
339 *(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
344 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
345 struct dm_crypt_request *dmreq)
348 * ESSIV encryption of the IV is now handled by the crypto API,
349 * so just pass the plain sector number here.
351 memset(iv, 0, cc->iv_size);
352 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
357 static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
363 if (crypt_integrity_aead(cc))
364 bs = crypto_aead_blocksize(any_tfm_aead(cc));
366 bs = crypto_skcipher_blocksize(any_tfm(cc));
370 * We need to calculate how far we must shift the sector count
371 * to get the cipher block count, we use this shift in _gen.
373 if (1 << log != bs) {
374 ti->error = "cypher blocksize is not a power of 2";
379 ti->error = "cypher blocksize is > 512";
383 cc->iv_gen_private.benbi.shift = 9 - log;
388 static void crypt_iv_benbi_dtr(struct crypt_config *cc)
392 static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
393 struct dm_crypt_request *dmreq)
397 memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
399 val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
400 put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
405 static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
406 struct dm_crypt_request *dmreq)
408 memset(iv, 0, cc->iv_size);
413 static void crypt_iv_lmk_dtr(struct crypt_config *cc)
415 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
417 if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
418 crypto_free_shash(lmk->hash_tfm);
419 lmk->hash_tfm = NULL;
421 kfree_sensitive(lmk->seed);
425 static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
428 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
430 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
431 ti->error = "Unsupported sector size for LMK";
435 lmk->hash_tfm = crypto_alloc_shash("md5", 0,
436 CRYPTO_ALG_ALLOCATES_MEMORY);
437 if (IS_ERR(lmk->hash_tfm)) {
438 ti->error = "Error initializing LMK hash";
439 return PTR_ERR(lmk->hash_tfm);
442 /* No seed in LMK version 2 */
443 if (cc->key_parts == cc->tfms_count) {
448 lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
450 crypt_iv_lmk_dtr(cc);
451 ti->error = "Error kmallocing seed storage in LMK";
458 static int crypt_iv_lmk_init(struct crypt_config *cc)
460 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
461 int subkey_size = cc->key_size / cc->key_parts;
463 /* LMK seed is on the position of LMK_KEYS + 1 key */
465 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
466 crypto_shash_digestsize(lmk->hash_tfm));
471 static int crypt_iv_lmk_wipe(struct crypt_config *cc)
473 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
476 memset(lmk->seed, 0, LMK_SEED_SIZE);
481 static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
482 struct dm_crypt_request *dmreq,
485 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
486 SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
487 struct md5_state md5state;
491 desc->tfm = lmk->hash_tfm;
493 r = crypto_shash_init(desc);
498 r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
503 /* Sector is always 512B, block size 16, add data of blocks 1-31 */
504 r = crypto_shash_update(desc, data + 16, 16 * 31);
508 /* Sector is cropped to 56 bits here */
509 buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
510 buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
511 buf[2] = cpu_to_le32(4024);
513 r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
517 /* No MD5 padding here */
518 r = crypto_shash_export(desc, &md5state);
522 for (i = 0; i < MD5_HASH_WORDS; i++)
523 __cpu_to_le32s(&md5state.hash[i]);
524 memcpy(iv, &md5state.hash, cc->iv_size);
529 static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
530 struct dm_crypt_request *dmreq)
532 struct scatterlist *sg;
536 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
537 sg = crypt_get_sg_data(cc, dmreq->sg_in);
538 src = kmap_local_page(sg_page(sg));
539 r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
542 memset(iv, 0, cc->iv_size);
547 static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
548 struct dm_crypt_request *dmreq)
550 struct scatterlist *sg;
554 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
557 sg = crypt_get_sg_data(cc, dmreq->sg_out);
558 dst = kmap_local_page(sg_page(sg));
559 r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
561 /* Tweak the first block of plaintext sector */
563 crypto_xor(dst + sg->offset, iv, cc->iv_size);
569 static void crypt_iv_tcw_dtr(struct crypt_config *cc)
571 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
573 kfree_sensitive(tcw->iv_seed);
575 kfree_sensitive(tcw->whitening);
576 tcw->whitening = NULL;
578 if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
579 crypto_free_shash(tcw->crc32_tfm);
580 tcw->crc32_tfm = NULL;
583 static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
586 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
588 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
589 ti->error = "Unsupported sector size for TCW";
593 if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
594 ti->error = "Wrong key size for TCW";
598 tcw->crc32_tfm = crypto_alloc_shash("crc32", 0,
599 CRYPTO_ALG_ALLOCATES_MEMORY);
600 if (IS_ERR(tcw->crc32_tfm)) {
601 ti->error = "Error initializing CRC32 in TCW";
602 return PTR_ERR(tcw->crc32_tfm);
605 tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
606 tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
607 if (!tcw->iv_seed || !tcw->whitening) {
608 crypt_iv_tcw_dtr(cc);
609 ti->error = "Error allocating seed storage in TCW";
616 static int crypt_iv_tcw_init(struct crypt_config *cc)
618 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
619 int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
621 memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
622 memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
628 static int crypt_iv_tcw_wipe(struct crypt_config *cc)
630 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
632 memset(tcw->iv_seed, 0, cc->iv_size);
633 memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
638 static int crypt_iv_tcw_whitening(struct crypt_config *cc,
639 struct dm_crypt_request *dmreq,
642 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
643 __le64 sector = cpu_to_le64(dmreq->iv_sector);
644 u8 buf[TCW_WHITENING_SIZE];
645 SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
648 /* xor whitening with sector number */
649 crypto_xor_cpy(buf, tcw->whitening, (u8 *)§or, 8);
650 crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)§or, 8);
652 /* calculate crc32 for every 32bit part and xor it */
653 desc->tfm = tcw->crc32_tfm;
654 for (i = 0; i < 4; i++) {
655 r = crypto_shash_init(desc);
658 r = crypto_shash_update(desc, &buf[i * 4], 4);
661 r = crypto_shash_final(desc, &buf[i * 4]);
665 crypto_xor(&buf[0], &buf[12], 4);
666 crypto_xor(&buf[4], &buf[8], 4);
668 /* apply whitening (8 bytes) to whole sector */
669 for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
670 crypto_xor(data + i * 8, buf, 8);
672 memzero_explicit(buf, sizeof(buf));
676 static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
677 struct dm_crypt_request *dmreq)
679 struct scatterlist *sg;
680 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
681 __le64 sector = cpu_to_le64(dmreq->iv_sector);
685 /* Remove whitening from ciphertext */
686 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
687 sg = crypt_get_sg_data(cc, dmreq->sg_in);
688 src = kmap_local_page(sg_page(sg));
689 r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
694 crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)§or, 8);
696 crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)§or,
702 static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
703 struct dm_crypt_request *dmreq)
705 struct scatterlist *sg;
709 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
712 /* Apply whitening on ciphertext */
713 sg = crypt_get_sg_data(cc, dmreq->sg_out);
714 dst = kmap_local_page(sg_page(sg));
715 r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
721 static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
722 struct dm_crypt_request *dmreq)
724 /* Used only for writes, there must be an additional space to store IV */
725 get_random_bytes(iv, cc->iv_size);
729 static int crypt_iv_eboiv_ctr(struct crypt_config *cc, struct dm_target *ti,
732 if (crypt_integrity_aead(cc)) {
733 ti->error = "AEAD transforms not supported for EBOIV";
737 if (crypto_skcipher_blocksize(any_tfm(cc)) != cc->iv_size) {
738 ti->error = "Block size of EBOIV cipher does not match IV size of block cipher";
745 static int crypt_iv_eboiv_gen(struct crypt_config *cc, u8 *iv,
746 struct dm_crypt_request *dmreq)
748 u8 buf[MAX_CIPHER_BLOCKSIZE] __aligned(__alignof__(__le64));
749 struct skcipher_request *req;
750 struct scatterlist src, dst;
751 DECLARE_CRYPTO_WAIT(wait);
754 req = skcipher_request_alloc(any_tfm(cc), GFP_NOIO);
758 memset(buf, 0, cc->iv_size);
759 *(__le64 *)buf = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
761 sg_init_one(&src, page_address(ZERO_PAGE(0)), cc->iv_size);
762 sg_init_one(&dst, iv, cc->iv_size);
763 skcipher_request_set_crypt(req, &src, &dst, cc->iv_size, buf);
764 skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
765 err = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
766 skcipher_request_free(req);
771 static void crypt_iv_elephant_dtr(struct crypt_config *cc)
773 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
775 crypto_free_skcipher(elephant->tfm);
776 elephant->tfm = NULL;
779 static int crypt_iv_elephant_ctr(struct crypt_config *cc, struct dm_target *ti,
782 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
785 elephant->tfm = crypto_alloc_skcipher("ecb(aes)", 0,
786 CRYPTO_ALG_ALLOCATES_MEMORY);
787 if (IS_ERR(elephant->tfm)) {
788 r = PTR_ERR(elephant->tfm);
789 elephant->tfm = NULL;
793 r = crypt_iv_eboiv_ctr(cc, ti, NULL);
795 crypt_iv_elephant_dtr(cc);
799 static void diffuser_disk_to_cpu(u32 *d, size_t n)
801 #ifndef __LITTLE_ENDIAN
804 for (i = 0; i < n; i++)
805 d[i] = le32_to_cpu((__le32)d[i]);
809 static void diffuser_cpu_to_disk(__le32 *d, size_t n)
811 #ifndef __LITTLE_ENDIAN
814 for (i = 0; i < n; i++)
815 d[i] = cpu_to_le32((u32)d[i]);
819 static void diffuser_a_decrypt(u32 *d, size_t n)
823 for (i = 0; i < 5; i++) {
828 while (i1 < (n - 1)) {
829 d[i1] += d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
835 d[i1] += d[i2] ^ d[i3];
841 d[i1] += d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
844 d[i1] += d[i2] ^ d[i3];
850 static void diffuser_a_encrypt(u32 *d, size_t n)
854 for (i = 0; i < 5; i++) {
860 d[i1] -= d[i2] ^ d[i3];
863 d[i1] -= d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
869 d[i1] -= d[i2] ^ d[i3];
875 d[i1] -= d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
881 static void diffuser_b_decrypt(u32 *d, size_t n)
885 for (i = 0; i < 3; i++) {
890 while (i1 < (n - 1)) {
891 d[i1] += d[i2] ^ d[i3];
894 d[i1] += d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
900 d[i1] += d[i2] ^ d[i3];
906 d[i1] += d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
912 static void diffuser_b_encrypt(u32 *d, size_t n)
916 for (i = 0; i < 3; i++) {
922 d[i1] -= d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
928 d[i1] -= d[i2] ^ d[i3];
934 d[i1] -= d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
937 d[i1] -= d[i2] ^ d[i3];
943 static int crypt_iv_elephant(struct crypt_config *cc, struct dm_crypt_request *dmreq)
945 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
946 u8 *es, *ks, *data, *data2, *data_offset;
947 struct skcipher_request *req;
948 struct scatterlist *sg, *sg2, src, dst;
949 DECLARE_CRYPTO_WAIT(wait);
952 req = skcipher_request_alloc(elephant->tfm, GFP_NOIO);
953 es = kzalloc(16, GFP_NOIO); /* Key for AES */
954 ks = kzalloc(32, GFP_NOIO); /* Elephant sector key */
956 if (!req || !es || !ks) {
961 *(__le64 *)es = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
964 sg_init_one(&src, es, 16);
965 sg_init_one(&dst, ks, 16);
966 skcipher_request_set_crypt(req, &src, &dst, 16, NULL);
967 skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
968 r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
974 sg_init_one(&dst, &ks[16], 16);
975 r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
979 sg = crypt_get_sg_data(cc, dmreq->sg_out);
980 data = kmap_local_page(sg_page(sg));
981 data_offset = data + sg->offset;
983 /* Cannot modify original bio, copy to sg_out and apply Elephant to it */
984 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
985 sg2 = crypt_get_sg_data(cc, dmreq->sg_in);
986 data2 = kmap_local_page(sg_page(sg2));
987 memcpy(data_offset, data2 + sg2->offset, cc->sector_size);
991 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
992 diffuser_disk_to_cpu((u32 *)data_offset, cc->sector_size / sizeof(u32));
993 diffuser_b_decrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
994 diffuser_a_decrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
995 diffuser_cpu_to_disk((__le32 *)data_offset, cc->sector_size / sizeof(u32));
998 for (i = 0; i < (cc->sector_size / 32); i++)
999 crypto_xor(data_offset + i * 32, ks, 32);
1001 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
1002 diffuser_disk_to_cpu((u32 *)data_offset, cc->sector_size / sizeof(u32));
1003 diffuser_a_encrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
1004 diffuser_b_encrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
1005 diffuser_cpu_to_disk((__le32 *)data_offset, cc->sector_size / sizeof(u32));
1010 kfree_sensitive(ks);
1011 kfree_sensitive(es);
1012 skcipher_request_free(req);
1016 static int crypt_iv_elephant_gen(struct crypt_config *cc, u8 *iv,
1017 struct dm_crypt_request *dmreq)
1021 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
1022 r = crypt_iv_elephant(cc, dmreq);
1027 return crypt_iv_eboiv_gen(cc, iv, dmreq);
1030 static int crypt_iv_elephant_post(struct crypt_config *cc, u8 *iv,
1031 struct dm_crypt_request *dmreq)
1033 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
1034 return crypt_iv_elephant(cc, dmreq);
1039 static int crypt_iv_elephant_init(struct crypt_config *cc)
1041 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1042 int key_offset = cc->key_size - cc->key_extra_size;
1044 return crypto_skcipher_setkey(elephant->tfm, &cc->key[key_offset], cc->key_extra_size);
1047 static int crypt_iv_elephant_wipe(struct crypt_config *cc)
1049 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1050 u8 key[ELEPHANT_MAX_KEY_SIZE];
1052 memset(key, 0, cc->key_extra_size);
1053 return crypto_skcipher_setkey(elephant->tfm, key, cc->key_extra_size);
1056 static const struct crypt_iv_operations crypt_iv_plain_ops = {
1057 .generator = crypt_iv_plain_gen
1060 static const struct crypt_iv_operations crypt_iv_plain64_ops = {
1061 .generator = crypt_iv_plain64_gen
1064 static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
1065 .generator = crypt_iv_plain64be_gen
1068 static const struct crypt_iv_operations crypt_iv_essiv_ops = {
1069 .generator = crypt_iv_essiv_gen
1072 static const struct crypt_iv_operations crypt_iv_benbi_ops = {
1073 .ctr = crypt_iv_benbi_ctr,
1074 .dtr = crypt_iv_benbi_dtr,
1075 .generator = crypt_iv_benbi_gen
1078 static const struct crypt_iv_operations crypt_iv_null_ops = {
1079 .generator = crypt_iv_null_gen
1082 static const struct crypt_iv_operations crypt_iv_lmk_ops = {
1083 .ctr = crypt_iv_lmk_ctr,
1084 .dtr = crypt_iv_lmk_dtr,
1085 .init = crypt_iv_lmk_init,
1086 .wipe = crypt_iv_lmk_wipe,
1087 .generator = crypt_iv_lmk_gen,
1088 .post = crypt_iv_lmk_post
1091 static const struct crypt_iv_operations crypt_iv_tcw_ops = {
1092 .ctr = crypt_iv_tcw_ctr,
1093 .dtr = crypt_iv_tcw_dtr,
1094 .init = crypt_iv_tcw_init,
1095 .wipe = crypt_iv_tcw_wipe,
1096 .generator = crypt_iv_tcw_gen,
1097 .post = crypt_iv_tcw_post
1100 static const struct crypt_iv_operations crypt_iv_random_ops = {
1101 .generator = crypt_iv_random_gen
1104 static const struct crypt_iv_operations crypt_iv_eboiv_ops = {
1105 .ctr = crypt_iv_eboiv_ctr,
1106 .generator = crypt_iv_eboiv_gen
1109 static const struct crypt_iv_operations crypt_iv_elephant_ops = {
1110 .ctr = crypt_iv_elephant_ctr,
1111 .dtr = crypt_iv_elephant_dtr,
1112 .init = crypt_iv_elephant_init,
1113 .wipe = crypt_iv_elephant_wipe,
1114 .generator = crypt_iv_elephant_gen,
1115 .post = crypt_iv_elephant_post
1119 * Integrity extensions
1121 static bool crypt_integrity_aead(struct crypt_config *cc)
1123 return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
1126 static bool crypt_integrity_hmac(struct crypt_config *cc)
1128 return crypt_integrity_aead(cc) && cc->key_mac_size;
1131 /* Get sg containing data */
1132 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
1133 struct scatterlist *sg)
1135 if (unlikely(crypt_integrity_aead(cc)))
1141 static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
1143 struct bio_integrity_payload *bip;
1144 unsigned int tag_len;
1147 if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
1150 bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
1152 return PTR_ERR(bip);
1154 tag_len = io->cc->on_disk_tag_size * (bio_sectors(bio) >> io->cc->sector_shift);
1156 bip->bip_iter.bi_size = tag_len;
1157 bip->bip_iter.bi_sector = io->cc->start + io->sector;
1159 ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
1160 tag_len, offset_in_page(io->integrity_metadata));
1161 if (unlikely(ret != tag_len))
1167 static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
1169 #ifdef CONFIG_BLK_DEV_INTEGRITY
1170 struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
1171 struct mapped_device *md = dm_table_get_md(ti->table);
1173 /* From now we require underlying device with our integrity profile */
1174 if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
1175 ti->error = "Integrity profile not supported.";
1179 if (bi->tag_size != cc->on_disk_tag_size ||
1180 bi->tuple_size != cc->on_disk_tag_size) {
1181 ti->error = "Integrity profile tag size mismatch.";
1184 if (1 << bi->interval_exp != cc->sector_size) {
1185 ti->error = "Integrity profile sector size mismatch.";
1189 if (crypt_integrity_aead(cc)) {
1190 cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
1191 DMDEBUG("%s: Integrity AEAD, tag size %u, IV size %u.", dm_device_name(md),
1192 cc->integrity_tag_size, cc->integrity_iv_size);
1194 if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
1195 ti->error = "Integrity AEAD auth tag size is not supported.";
1198 } else if (cc->integrity_iv_size)
1199 DMDEBUG("%s: Additional per-sector space %u bytes for IV.", dm_device_name(md),
1200 cc->integrity_iv_size);
1202 if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
1203 ti->error = "Not enough space for integrity tag in the profile.";
1209 ti->error = "Integrity profile not supported.";
1214 static void crypt_convert_init(struct crypt_config *cc,
1215 struct convert_context *ctx,
1216 struct bio *bio_out, struct bio *bio_in,
1219 ctx->bio_in = bio_in;
1220 ctx->bio_out = bio_out;
1222 ctx->iter_in = bio_in->bi_iter;
1224 ctx->iter_out = bio_out->bi_iter;
1225 ctx->cc_sector = sector + cc->iv_offset;
1226 init_completion(&ctx->restart);
1229 static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
1232 return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
1235 static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
1237 return (void *)((char *)dmreq - cc->dmreq_start);
1240 static u8 *iv_of_dmreq(struct crypt_config *cc,
1241 struct dm_crypt_request *dmreq)
1243 if (crypt_integrity_aead(cc))
1244 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1245 crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
1247 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1248 crypto_skcipher_alignmask(any_tfm(cc)) + 1);
1251 static u8 *org_iv_of_dmreq(struct crypt_config *cc,
1252 struct dm_crypt_request *dmreq)
1254 return iv_of_dmreq(cc, dmreq) + cc->iv_size;
1257 static __le64 *org_sector_of_dmreq(struct crypt_config *cc,
1258 struct dm_crypt_request *dmreq)
1260 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
1262 return (__le64 *) ptr;
1265 static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
1266 struct dm_crypt_request *dmreq)
1268 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
1269 cc->iv_size + sizeof(uint64_t);
1271 return (unsigned int *)ptr;
1274 static void *tag_from_dmreq(struct crypt_config *cc,
1275 struct dm_crypt_request *dmreq)
1277 struct convert_context *ctx = dmreq->ctx;
1278 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1280 return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
1281 cc->on_disk_tag_size];
1284 static void *iv_tag_from_dmreq(struct crypt_config *cc,
1285 struct dm_crypt_request *dmreq)
1287 return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
1290 static int crypt_convert_block_aead(struct crypt_config *cc,
1291 struct convert_context *ctx,
1292 struct aead_request *req,
1293 unsigned int tag_offset)
1295 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1296 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1297 struct dm_crypt_request *dmreq;
1298 u8 *iv, *org_iv, *tag_iv, *tag;
1302 BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
1304 /* Reject unexpected unaligned bio. */
1305 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1308 dmreq = dmreq_of_req(cc, req);
1309 dmreq->iv_sector = ctx->cc_sector;
1310 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1311 dmreq->iv_sector >>= cc->sector_shift;
1314 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1316 sector = org_sector_of_dmreq(cc, dmreq);
1317 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1319 iv = iv_of_dmreq(cc, dmreq);
1320 org_iv = org_iv_of_dmreq(cc, dmreq);
1321 tag = tag_from_dmreq(cc, dmreq);
1322 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1325 * |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1326 * | (authenticated) | (auth+encryption) | |
1327 * | sector_LE | IV | sector in/out | tag in/out |
1329 sg_init_table(dmreq->sg_in, 4);
1330 sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
1331 sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
1332 sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1333 sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
1335 sg_init_table(dmreq->sg_out, 4);
1336 sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
1337 sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
1338 sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1339 sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
1341 if (cc->iv_gen_ops) {
1342 /* For READs use IV stored in integrity metadata */
1343 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1344 memcpy(org_iv, tag_iv, cc->iv_size);
1346 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1349 /* Store generated IV in integrity metadata */
1350 if (cc->integrity_iv_size)
1351 memcpy(tag_iv, org_iv, cc->iv_size);
1353 /* Working copy of IV, to be modified in crypto API */
1354 memcpy(iv, org_iv, cc->iv_size);
1357 aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
1358 if (bio_data_dir(ctx->bio_in) == WRITE) {
1359 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1360 cc->sector_size, iv);
1361 r = crypto_aead_encrypt(req);
1362 if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
1363 memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
1364 cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
1366 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1367 cc->sector_size + cc->integrity_tag_size, iv);
1368 r = crypto_aead_decrypt(req);
1371 if (r == -EBADMSG) {
1372 sector_t s = le64_to_cpu(*sector);
1374 DMERR_LIMIT("%pg: INTEGRITY AEAD ERROR, sector %llu",
1375 ctx->bio_in->bi_bdev, s);
1376 dm_audit_log_bio(DM_MSG_PREFIX, "integrity-aead",
1380 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1381 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1383 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1384 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1389 static int crypt_convert_block_skcipher(struct crypt_config *cc,
1390 struct convert_context *ctx,
1391 struct skcipher_request *req,
1392 unsigned int tag_offset)
1394 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1395 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1396 struct scatterlist *sg_in, *sg_out;
1397 struct dm_crypt_request *dmreq;
1398 u8 *iv, *org_iv, *tag_iv;
1402 /* Reject unexpected unaligned bio. */
1403 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1406 dmreq = dmreq_of_req(cc, req);
1407 dmreq->iv_sector = ctx->cc_sector;
1408 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1409 dmreq->iv_sector >>= cc->sector_shift;
1412 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1414 iv = iv_of_dmreq(cc, dmreq);
1415 org_iv = org_iv_of_dmreq(cc, dmreq);
1416 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1418 sector = org_sector_of_dmreq(cc, dmreq);
1419 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1421 /* For skcipher we use only the first sg item */
1422 sg_in = &dmreq->sg_in[0];
1423 sg_out = &dmreq->sg_out[0];
1425 sg_init_table(sg_in, 1);
1426 sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1428 sg_init_table(sg_out, 1);
1429 sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1431 if (cc->iv_gen_ops) {
1432 /* For READs use IV stored in integrity metadata */
1433 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1434 memcpy(org_iv, tag_iv, cc->integrity_iv_size);
1436 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1439 /* Data can be already preprocessed in generator */
1440 if (test_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags))
1442 /* Store generated IV in integrity metadata */
1443 if (cc->integrity_iv_size)
1444 memcpy(tag_iv, org_iv, cc->integrity_iv_size);
1446 /* Working copy of IV, to be modified in crypto API */
1447 memcpy(iv, org_iv, cc->iv_size);
1450 skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
1452 if (bio_data_dir(ctx->bio_in) == WRITE)
1453 r = crypto_skcipher_encrypt(req);
1455 r = crypto_skcipher_decrypt(req);
1457 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1458 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1460 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1461 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1466 static void kcryptd_async_done(void *async_req, int error);
1468 static int crypt_alloc_req_skcipher(struct crypt_config *cc,
1469 struct convert_context *ctx)
1471 unsigned int key_index = ctx->cc_sector & (cc->tfms_count - 1);
1474 ctx->r.req = mempool_alloc(&cc->req_pool, in_interrupt() ? GFP_ATOMIC : GFP_NOIO);
1479 skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
1482 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1483 * requests if driver request queue is full.
1485 skcipher_request_set_callback(ctx->r.req,
1486 CRYPTO_TFM_REQ_MAY_BACKLOG,
1487 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
1492 static int crypt_alloc_req_aead(struct crypt_config *cc,
1493 struct convert_context *ctx)
1495 if (!ctx->r.req_aead) {
1496 ctx->r.req_aead = mempool_alloc(&cc->req_pool, in_interrupt() ? GFP_ATOMIC : GFP_NOIO);
1497 if (!ctx->r.req_aead)
1501 aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
1504 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1505 * requests if driver request queue is full.
1507 aead_request_set_callback(ctx->r.req_aead,
1508 CRYPTO_TFM_REQ_MAY_BACKLOG,
1509 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
1514 static int crypt_alloc_req(struct crypt_config *cc,
1515 struct convert_context *ctx)
1517 if (crypt_integrity_aead(cc))
1518 return crypt_alloc_req_aead(cc, ctx);
1520 return crypt_alloc_req_skcipher(cc, ctx);
1523 static void crypt_free_req_skcipher(struct crypt_config *cc,
1524 struct skcipher_request *req, struct bio *base_bio)
1526 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1528 if ((struct skcipher_request *)(io + 1) != req)
1529 mempool_free(req, &cc->req_pool);
1532 static void crypt_free_req_aead(struct crypt_config *cc,
1533 struct aead_request *req, struct bio *base_bio)
1535 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1537 if ((struct aead_request *)(io + 1) != req)
1538 mempool_free(req, &cc->req_pool);
1541 static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
1543 if (crypt_integrity_aead(cc))
1544 crypt_free_req_aead(cc, req, base_bio);
1546 crypt_free_req_skcipher(cc, req, base_bio);
1550 * Encrypt / decrypt data from one bio to another one (can be the same one)
1552 static blk_status_t crypt_convert(struct crypt_config *cc,
1553 struct convert_context *ctx, bool atomic, bool reset_pending)
1555 unsigned int tag_offset = 0;
1556 unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
1560 * if reset_pending is set we are dealing with the bio for the first time,
1561 * else we're continuing to work on the previous bio, so don't mess with
1562 * the cc_pending counter
1565 atomic_set(&ctx->cc_pending, 1);
1567 while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
1569 r = crypt_alloc_req(cc, ctx);
1571 complete(&ctx->restart);
1572 return BLK_STS_DEV_RESOURCE;
1575 atomic_inc(&ctx->cc_pending);
1577 if (crypt_integrity_aead(cc))
1578 r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
1580 r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
1584 * The request was queued by a crypto driver
1585 * but the driver request queue is full, let's wait.
1588 if (in_interrupt()) {
1589 if (try_wait_for_completion(&ctx->restart)) {
1591 * we don't have to block to wait for completion,
1596 * we can't wait for completion without blocking
1597 * exit and continue processing in a workqueue
1600 ctx->cc_sector += sector_step;
1602 return BLK_STS_DEV_RESOURCE;
1605 wait_for_completion(&ctx->restart);
1607 reinit_completion(&ctx->restart);
1610 * The request is queued and processed asynchronously,
1611 * completion function kcryptd_async_done() will be called.
1615 ctx->cc_sector += sector_step;
1619 * The request was already processed (synchronously).
1622 atomic_dec(&ctx->cc_pending);
1623 ctx->cc_sector += sector_step;
1629 * There was a data integrity error.
1632 atomic_dec(&ctx->cc_pending);
1633 return BLK_STS_PROTECTION;
1635 * There was an error while processing the request.
1638 atomic_dec(&ctx->cc_pending);
1639 return BLK_STS_IOERR;
1646 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
1649 * Generate a new unfragmented bio with the given size
1650 * This should never violate the device limitations (but only because
1651 * max_segment_size is being constrained to PAGE_SIZE).
1653 * This function may be called concurrently. If we allocate from the mempool
1654 * concurrently, there is a possibility of deadlock. For example, if we have
1655 * mempool of 256 pages, two processes, each wanting 256, pages allocate from
1656 * the mempool concurrently, it may deadlock in a situation where both processes
1657 * have allocated 128 pages and the mempool is exhausted.
1659 * In order to avoid this scenario we allocate the pages under a mutex.
1661 * In order to not degrade performance with excessive locking, we try
1662 * non-blocking allocations without a mutex first but on failure we fallback
1663 * to blocking allocations with a mutex.
1665 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned int size)
1667 struct crypt_config *cc = io->cc;
1669 unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1670 gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
1671 unsigned int i, len, remaining_size;
1675 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1676 mutex_lock(&cc->bio_alloc_lock);
1678 clone = bio_alloc_bioset(cc->dev->bdev, nr_iovecs, io->base_bio->bi_opf,
1680 clone->bi_private = io;
1681 clone->bi_end_io = crypt_endio;
1683 remaining_size = size;
1685 for (i = 0; i < nr_iovecs; i++) {
1686 page = mempool_alloc(&cc->page_pool, gfp_mask);
1688 crypt_free_buffer_pages(cc, clone);
1690 gfp_mask |= __GFP_DIRECT_RECLAIM;
1694 len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
1696 bio_add_page(clone, page, len, 0);
1698 remaining_size -= len;
1701 /* Allocate space for integrity tags */
1702 if (dm_crypt_integrity_io_alloc(io, clone)) {
1703 crypt_free_buffer_pages(cc, clone);
1708 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1709 mutex_unlock(&cc->bio_alloc_lock);
1714 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1717 struct bvec_iter_all iter_all;
1719 bio_for_each_segment_all(bv, clone, iter_all) {
1720 BUG_ON(!bv->bv_page);
1721 mempool_free(bv->bv_page, &cc->page_pool);
1725 static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1726 struct bio *bio, sector_t sector)
1730 io->sector = sector;
1732 io->ctx.r.req = NULL;
1733 io->integrity_metadata = NULL;
1734 io->integrity_metadata_from_pool = false;
1735 io->in_tasklet = false;
1736 atomic_set(&io->io_pending, 0);
1739 static void crypt_inc_pending(struct dm_crypt_io *io)
1741 atomic_inc(&io->io_pending);
1744 static void kcryptd_io_bio_endio(struct work_struct *work)
1746 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1748 bio_endio(io->base_bio);
1752 * One of the bios was finished. Check for completion of
1753 * the whole request and correctly clean up the buffer.
1755 static void crypt_dec_pending(struct dm_crypt_io *io)
1757 struct crypt_config *cc = io->cc;
1758 struct bio *base_bio = io->base_bio;
1759 blk_status_t error = io->error;
1761 if (!atomic_dec_and_test(&io->io_pending))
1765 crypt_free_req(cc, io->ctx.r.req, base_bio);
1767 if (unlikely(io->integrity_metadata_from_pool))
1768 mempool_free(io->integrity_metadata, &io->cc->tag_pool);
1770 kfree(io->integrity_metadata);
1772 base_bio->bi_status = error;
1775 * If we are running this function from our tasklet,
1776 * we can't call bio_endio() here, because it will call
1777 * clone_endio() from dm.c, which in turn will
1778 * free the current struct dm_crypt_io structure with
1779 * our tasklet. In this case we need to delay bio_endio()
1780 * execution to after the tasklet is done and dequeued.
1782 if (io->in_tasklet) {
1783 INIT_WORK(&io->work, kcryptd_io_bio_endio);
1784 queue_work(cc->io_queue, &io->work);
1788 bio_endio(base_bio);
1792 * kcryptd/kcryptd_io:
1794 * Needed because it would be very unwise to do decryption in an
1795 * interrupt context.
1797 * kcryptd performs the actual encryption or decryption.
1799 * kcryptd_io performs the IO submission.
1801 * They must be separated as otherwise the final stages could be
1802 * starved by new requests which can block in the first stages due
1803 * to memory allocation.
1805 * The work is done per CPU global for all dm-crypt instances.
1806 * They should not depend on each other and do not block.
1808 static void crypt_endio(struct bio *clone)
1810 struct dm_crypt_io *io = clone->bi_private;
1811 struct crypt_config *cc = io->cc;
1812 unsigned int rw = bio_data_dir(clone);
1816 * free the processed pages
1819 crypt_free_buffer_pages(cc, clone);
1821 error = clone->bi_status;
1824 if (rw == READ && !error) {
1825 kcryptd_queue_crypt(io);
1829 if (unlikely(error))
1832 crypt_dec_pending(io);
1835 #define CRYPT_MAP_READ_GFP GFP_NOWAIT
1837 static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
1839 struct crypt_config *cc = io->cc;
1843 * We need the original biovec array in order to decrypt the whole bio
1844 * data *afterwards* -- thanks to immutable biovecs we don't need to
1845 * worry about the block layer modifying the biovec array; so leverage
1846 * bio_alloc_clone().
1848 clone = bio_alloc_clone(cc->dev->bdev, io->base_bio, gfp, &cc->bs);
1851 clone->bi_private = io;
1852 clone->bi_end_io = crypt_endio;
1854 crypt_inc_pending(io);
1856 clone->bi_iter.bi_sector = cc->start + io->sector;
1858 if (dm_crypt_integrity_io_alloc(io, clone)) {
1859 crypt_dec_pending(io);
1864 dm_submit_bio_remap(io->base_bio, clone);
1868 static void kcryptd_io_read_work(struct work_struct *work)
1870 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1872 crypt_inc_pending(io);
1873 if (kcryptd_io_read(io, GFP_NOIO))
1874 io->error = BLK_STS_RESOURCE;
1875 crypt_dec_pending(io);
1878 static void kcryptd_queue_read(struct dm_crypt_io *io)
1880 struct crypt_config *cc = io->cc;
1882 INIT_WORK(&io->work, kcryptd_io_read_work);
1883 queue_work(cc->io_queue, &io->work);
1886 static void kcryptd_io_write(struct dm_crypt_io *io)
1888 struct bio *clone = io->ctx.bio_out;
1890 dm_submit_bio_remap(io->base_bio, clone);
1893 #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1895 static int dmcrypt_write(void *data)
1897 struct crypt_config *cc = data;
1898 struct dm_crypt_io *io;
1901 struct rb_root write_tree;
1902 struct blk_plug plug;
1904 spin_lock_irq(&cc->write_thread_lock);
1907 if (!RB_EMPTY_ROOT(&cc->write_tree))
1910 set_current_state(TASK_INTERRUPTIBLE);
1912 spin_unlock_irq(&cc->write_thread_lock);
1914 if (unlikely(kthread_should_stop())) {
1915 set_current_state(TASK_RUNNING);
1921 set_current_state(TASK_RUNNING);
1922 spin_lock_irq(&cc->write_thread_lock);
1923 goto continue_locked;
1926 write_tree = cc->write_tree;
1927 cc->write_tree = RB_ROOT;
1928 spin_unlock_irq(&cc->write_thread_lock);
1930 BUG_ON(rb_parent(write_tree.rb_node));
1933 * Note: we cannot walk the tree here with rb_next because
1934 * the structures may be freed when kcryptd_io_write is called.
1936 blk_start_plug(&plug);
1938 io = crypt_io_from_node(rb_first(&write_tree));
1939 rb_erase(&io->rb_node, &write_tree);
1940 kcryptd_io_write(io);
1942 } while (!RB_EMPTY_ROOT(&write_tree));
1943 blk_finish_plug(&plug);
1948 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
1950 struct bio *clone = io->ctx.bio_out;
1951 struct crypt_config *cc = io->cc;
1952 unsigned long flags;
1954 struct rb_node **rbp, *parent;
1956 if (unlikely(io->error)) {
1957 crypt_free_buffer_pages(cc, clone);
1959 crypt_dec_pending(io);
1963 /* crypt_convert should have filled the clone bio */
1964 BUG_ON(io->ctx.iter_out.bi_size);
1966 clone->bi_iter.bi_sector = cc->start + io->sector;
1968 if ((likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) ||
1969 test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags)) {
1970 dm_submit_bio_remap(io->base_bio, clone);
1974 spin_lock_irqsave(&cc->write_thread_lock, flags);
1975 if (RB_EMPTY_ROOT(&cc->write_tree))
1976 wake_up_process(cc->write_thread);
1977 rbp = &cc->write_tree.rb_node;
1979 sector = io->sector;
1982 if (sector < crypt_io_from_node(parent)->sector)
1983 rbp = &(*rbp)->rb_left;
1985 rbp = &(*rbp)->rb_right;
1987 rb_link_node(&io->rb_node, parent, rbp);
1988 rb_insert_color(&io->rb_node, &cc->write_tree);
1989 spin_unlock_irqrestore(&cc->write_thread_lock, flags);
1992 static bool kcryptd_crypt_write_inline(struct crypt_config *cc,
1993 struct convert_context *ctx)
1996 if (!test_bit(DM_CRYPT_WRITE_INLINE, &cc->flags))
2000 * Note: zone append writes (REQ_OP_ZONE_APPEND) do not have ordering
2001 * constraints so they do not need to be issued inline by
2002 * kcryptd_crypt_write_convert().
2004 switch (bio_op(ctx->bio_in)) {
2006 case REQ_OP_WRITE_ZEROES:
2013 static void kcryptd_crypt_write_continue(struct work_struct *work)
2015 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2016 struct crypt_config *cc = io->cc;
2017 struct convert_context *ctx = &io->ctx;
2019 sector_t sector = io->sector;
2022 wait_for_completion(&ctx->restart);
2023 reinit_completion(&ctx->restart);
2025 r = crypt_convert(cc, &io->ctx, true, false);
2028 crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
2029 if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
2030 /* Wait for completion signaled by kcryptd_async_done() */
2031 wait_for_completion(&ctx->restart);
2035 /* Encryption was already finished, submit io now */
2036 if (crypt_finished) {
2037 kcryptd_crypt_write_io_submit(io, 0);
2038 io->sector = sector;
2041 crypt_dec_pending(io);
2044 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
2046 struct crypt_config *cc = io->cc;
2047 struct convert_context *ctx = &io->ctx;
2050 sector_t sector = io->sector;
2054 * Prevent io from disappearing until this function completes.
2056 crypt_inc_pending(io);
2057 crypt_convert_init(cc, ctx, NULL, io->base_bio, sector);
2059 clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
2060 if (unlikely(!clone)) {
2061 io->error = BLK_STS_IOERR;
2065 io->ctx.bio_out = clone;
2066 io->ctx.iter_out = clone->bi_iter;
2068 sector += bio_sectors(clone);
2070 crypt_inc_pending(io);
2071 r = crypt_convert(cc, ctx,
2072 test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags), true);
2074 * Crypto API backlogged the request, because its queue was full
2075 * and we're in softirq context, so continue from a workqueue
2076 * (TODO: is it actually possible to be in softirq in the write path?)
2078 if (r == BLK_STS_DEV_RESOURCE) {
2079 INIT_WORK(&io->work, kcryptd_crypt_write_continue);
2080 queue_work(cc->crypt_queue, &io->work);
2085 crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
2086 if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
2087 /* Wait for completion signaled by kcryptd_async_done() */
2088 wait_for_completion(&ctx->restart);
2092 /* Encryption was already finished, submit io now */
2093 if (crypt_finished) {
2094 kcryptd_crypt_write_io_submit(io, 0);
2095 io->sector = sector;
2099 crypt_dec_pending(io);
2102 static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
2104 crypt_dec_pending(io);
2107 static void kcryptd_crypt_read_continue(struct work_struct *work)
2109 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2110 struct crypt_config *cc = io->cc;
2113 wait_for_completion(&io->ctx.restart);
2114 reinit_completion(&io->ctx.restart);
2116 r = crypt_convert(cc, &io->ctx, true, false);
2120 if (atomic_dec_and_test(&io->ctx.cc_pending))
2121 kcryptd_crypt_read_done(io);
2123 crypt_dec_pending(io);
2126 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
2128 struct crypt_config *cc = io->cc;
2131 crypt_inc_pending(io);
2133 crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
2136 r = crypt_convert(cc, &io->ctx,
2137 test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags), true);
2139 * Crypto API backlogged the request, because its queue was full
2140 * and we're in softirq context, so continue from a workqueue
2142 if (r == BLK_STS_DEV_RESOURCE) {
2143 INIT_WORK(&io->work, kcryptd_crypt_read_continue);
2144 queue_work(cc->crypt_queue, &io->work);
2150 if (atomic_dec_and_test(&io->ctx.cc_pending))
2151 kcryptd_crypt_read_done(io);
2153 crypt_dec_pending(io);
2156 static void kcryptd_async_done(void *data, int error)
2158 struct dm_crypt_request *dmreq = data;
2159 struct convert_context *ctx = dmreq->ctx;
2160 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
2161 struct crypt_config *cc = io->cc;
2164 * A request from crypto driver backlog is going to be processed now,
2165 * finish the completion and continue in crypt_convert().
2166 * (Callback will be called for the second time for this request.)
2168 if (error == -EINPROGRESS) {
2169 complete(&ctx->restart);
2173 if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
2174 error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
2176 if (error == -EBADMSG) {
2177 sector_t s = le64_to_cpu(*org_sector_of_dmreq(cc, dmreq));
2179 DMERR_LIMIT("%pg: INTEGRITY AEAD ERROR, sector %llu",
2180 ctx->bio_in->bi_bdev, s);
2181 dm_audit_log_bio(DM_MSG_PREFIX, "integrity-aead",
2183 io->error = BLK_STS_PROTECTION;
2184 } else if (error < 0)
2185 io->error = BLK_STS_IOERR;
2187 crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
2189 if (!atomic_dec_and_test(&ctx->cc_pending))
2193 * The request is fully completed: for inline writes, let
2194 * kcryptd_crypt_write_convert() do the IO submission.
2196 if (bio_data_dir(io->base_bio) == READ) {
2197 kcryptd_crypt_read_done(io);
2201 if (kcryptd_crypt_write_inline(cc, ctx)) {
2202 complete(&ctx->restart);
2206 kcryptd_crypt_write_io_submit(io, 1);
2209 static void kcryptd_crypt(struct work_struct *work)
2211 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2213 if (bio_data_dir(io->base_bio) == READ)
2214 kcryptd_crypt_read_convert(io);
2216 kcryptd_crypt_write_convert(io);
2219 static void kcryptd_crypt_tasklet(unsigned long work)
2221 kcryptd_crypt((struct work_struct *)work);
2224 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
2226 struct crypt_config *cc = io->cc;
2228 if ((bio_data_dir(io->base_bio) == READ && test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags)) ||
2229 (bio_data_dir(io->base_bio) == WRITE && test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))) {
2231 * in_hardirq(): Crypto API's skcipher_walk_first() refuses to work in hard IRQ context.
2232 * irqs_disabled(): the kernel may run some IO completion from the idle thread, but
2233 * it is being executed with irqs disabled.
2235 if (in_hardirq() || irqs_disabled()) {
2236 io->in_tasklet = true;
2237 tasklet_init(&io->tasklet, kcryptd_crypt_tasklet, (unsigned long)&io->work);
2238 tasklet_schedule(&io->tasklet);
2242 kcryptd_crypt(&io->work);
2246 INIT_WORK(&io->work, kcryptd_crypt);
2247 queue_work(cc->crypt_queue, &io->work);
2250 static void crypt_free_tfms_aead(struct crypt_config *cc)
2252 if (!cc->cipher_tfm.tfms_aead)
2255 if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2256 crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
2257 cc->cipher_tfm.tfms_aead[0] = NULL;
2260 kfree(cc->cipher_tfm.tfms_aead);
2261 cc->cipher_tfm.tfms_aead = NULL;
2264 static void crypt_free_tfms_skcipher(struct crypt_config *cc)
2268 if (!cc->cipher_tfm.tfms)
2271 for (i = 0; i < cc->tfms_count; i++)
2272 if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
2273 crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
2274 cc->cipher_tfm.tfms[i] = NULL;
2277 kfree(cc->cipher_tfm.tfms);
2278 cc->cipher_tfm.tfms = NULL;
2281 static void crypt_free_tfms(struct crypt_config *cc)
2283 if (crypt_integrity_aead(cc))
2284 crypt_free_tfms_aead(cc);
2286 crypt_free_tfms_skcipher(cc);
2289 static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
2294 cc->cipher_tfm.tfms = kcalloc(cc->tfms_count,
2295 sizeof(struct crypto_skcipher *),
2297 if (!cc->cipher_tfm.tfms)
2300 for (i = 0; i < cc->tfms_count; i++) {
2301 cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0,
2302 CRYPTO_ALG_ALLOCATES_MEMORY);
2303 if (IS_ERR(cc->cipher_tfm.tfms[i])) {
2304 err = PTR_ERR(cc->cipher_tfm.tfms[i]);
2305 crypt_free_tfms(cc);
2311 * dm-crypt performance can vary greatly depending on which crypto
2312 * algorithm implementation is used. Help people debug performance
2313 * problems by logging the ->cra_driver_name.
2315 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2316 crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
2320 static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
2324 cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
2325 if (!cc->cipher_tfm.tfms)
2328 cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0,
2329 CRYPTO_ALG_ALLOCATES_MEMORY);
2330 if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2331 err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
2332 crypt_free_tfms(cc);
2336 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2337 crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
2341 static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
2343 if (crypt_integrity_aead(cc))
2344 return crypt_alloc_tfms_aead(cc, ciphermode);
2346 return crypt_alloc_tfms_skcipher(cc, ciphermode);
2349 static unsigned int crypt_subkey_size(struct crypt_config *cc)
2351 return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
2354 static unsigned int crypt_authenckey_size(struct crypt_config *cc)
2356 return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
2360 * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
2361 * the key must be for some reason in special format.
2362 * This funcion converts cc->key to this special format.
2364 static void crypt_copy_authenckey(char *p, const void *key,
2365 unsigned int enckeylen, unsigned int authkeylen)
2367 struct crypto_authenc_key_param *param;
2370 rta = (struct rtattr *)p;
2371 param = RTA_DATA(rta);
2372 param->enckeylen = cpu_to_be32(enckeylen);
2373 rta->rta_len = RTA_LENGTH(sizeof(*param));
2374 rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
2375 p += RTA_SPACE(sizeof(*param));
2376 memcpy(p, key + enckeylen, authkeylen);
2378 memcpy(p, key, enckeylen);
2381 static int crypt_setkey(struct crypt_config *cc)
2383 unsigned int subkey_size;
2386 /* Ignore extra keys (which are used for IV etc) */
2387 subkey_size = crypt_subkey_size(cc);
2389 if (crypt_integrity_hmac(cc)) {
2390 if (subkey_size < cc->key_mac_size)
2393 crypt_copy_authenckey(cc->authenc_key, cc->key,
2394 subkey_size - cc->key_mac_size,
2398 for (i = 0; i < cc->tfms_count; i++) {
2399 if (crypt_integrity_hmac(cc))
2400 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2401 cc->authenc_key, crypt_authenckey_size(cc));
2402 else if (crypt_integrity_aead(cc))
2403 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2404 cc->key + (i * subkey_size),
2407 r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
2408 cc->key + (i * subkey_size),
2414 if (crypt_integrity_hmac(cc))
2415 memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
2422 static bool contains_whitespace(const char *str)
2425 if (isspace(*str++))
2430 static int set_key_user(struct crypt_config *cc, struct key *key)
2432 const struct user_key_payload *ukp;
2434 ukp = user_key_payload_locked(key);
2436 return -EKEYREVOKED;
2438 if (cc->key_size != ukp->datalen)
2441 memcpy(cc->key, ukp->data, cc->key_size);
2446 static int set_key_encrypted(struct crypt_config *cc, struct key *key)
2448 const struct encrypted_key_payload *ekp;
2450 ekp = key->payload.data[0];
2452 return -EKEYREVOKED;
2454 if (cc->key_size != ekp->decrypted_datalen)
2457 memcpy(cc->key, ekp->decrypted_data, cc->key_size);
2462 static int set_key_trusted(struct crypt_config *cc, struct key *key)
2464 const struct trusted_key_payload *tkp;
2466 tkp = key->payload.data[0];
2468 return -EKEYREVOKED;
2470 if (cc->key_size != tkp->key_len)
2473 memcpy(cc->key, tkp->key, cc->key_size);
2478 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2480 char *new_key_string, *key_desc;
2482 struct key_type *type;
2484 int (*set_key)(struct crypt_config *cc, struct key *key);
2487 * Reject key_string with whitespace. dm core currently lacks code for
2488 * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2490 if (contains_whitespace(key_string)) {
2491 DMERR("whitespace chars not allowed in key string");
2495 /* look for next ':' separating key_type from key_description */
2496 key_desc = strchr(key_string, ':');
2497 if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2500 if (!strncmp(key_string, "logon:", key_desc - key_string + 1)) {
2501 type = &key_type_logon;
2502 set_key = set_key_user;
2503 } else if (!strncmp(key_string, "user:", key_desc - key_string + 1)) {
2504 type = &key_type_user;
2505 set_key = set_key_user;
2506 } else if (IS_ENABLED(CONFIG_ENCRYPTED_KEYS) &&
2507 !strncmp(key_string, "encrypted:", key_desc - key_string + 1)) {
2508 type = &key_type_encrypted;
2509 set_key = set_key_encrypted;
2510 } else if (IS_ENABLED(CONFIG_TRUSTED_KEYS) &&
2511 !strncmp(key_string, "trusted:", key_desc - key_string + 1)) {
2512 type = &key_type_trusted;
2513 set_key = set_key_trusted;
2518 new_key_string = kstrdup(key_string, GFP_KERNEL);
2519 if (!new_key_string)
2522 key = request_key(type, key_desc + 1, NULL);
2524 kfree_sensitive(new_key_string);
2525 return PTR_ERR(key);
2528 down_read(&key->sem);
2530 ret = set_key(cc, key);
2534 kfree_sensitive(new_key_string);
2541 /* clear the flag since following operations may invalidate previously valid key */
2542 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2544 ret = crypt_setkey(cc);
2547 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2548 kfree_sensitive(cc->key_string);
2549 cc->key_string = new_key_string;
2551 kfree_sensitive(new_key_string);
2556 static int get_key_size(char **key_string)
2561 if (*key_string[0] != ':')
2562 return strlen(*key_string) >> 1;
2564 /* look for next ':' in key string */
2565 colon = strpbrk(*key_string + 1, ":");
2569 if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2572 *key_string = colon;
2574 /* remaining key string should be :<logon|user>:<key_desc> */
2581 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2586 static int get_key_size(char **key_string)
2588 return (*key_string[0] == ':') ? -EINVAL : (int)(strlen(*key_string) >> 1);
2591 #endif /* CONFIG_KEYS */
2593 static int crypt_set_key(struct crypt_config *cc, char *key)
2596 int key_string_len = strlen(key);
2598 /* Hyphen (which gives a key_size of zero) means there is no key. */
2599 if (!cc->key_size && strcmp(key, "-"))
2602 /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2603 if (key[0] == ':') {
2604 r = crypt_set_keyring_key(cc, key + 1);
2608 /* clear the flag since following operations may invalidate previously valid key */
2609 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2611 /* wipe references to any kernel keyring key */
2612 kfree_sensitive(cc->key_string);
2613 cc->key_string = NULL;
2615 /* Decode key from its hex representation. */
2616 if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
2619 r = crypt_setkey(cc);
2621 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2624 /* Hex key string not needed after here, so wipe it. */
2625 memset(key, '0', key_string_len);
2630 static int crypt_wipe_key(struct crypt_config *cc)
2634 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2635 get_random_bytes(&cc->key, cc->key_size);
2637 /* Wipe IV private keys */
2638 if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
2639 r = cc->iv_gen_ops->wipe(cc);
2644 kfree_sensitive(cc->key_string);
2645 cc->key_string = NULL;
2646 r = crypt_setkey(cc);
2647 memset(&cc->key, 0, cc->key_size * sizeof(u8));
2652 static void crypt_calculate_pages_per_client(void)
2654 unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
2656 if (!dm_crypt_clients_n)
2659 pages /= dm_crypt_clients_n;
2660 if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
2661 pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
2662 dm_crypt_pages_per_client = pages;
2665 static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
2667 struct crypt_config *cc = pool_data;
2671 * Note, percpu_counter_read_positive() may over (and under) estimate
2672 * the current usage by at most (batch - 1) * num_online_cpus() pages,
2673 * but avoids potential spinlock contention of an exact result.
2675 if (unlikely(percpu_counter_read_positive(&cc->n_allocated_pages) >= dm_crypt_pages_per_client) &&
2676 likely(gfp_mask & __GFP_NORETRY))
2679 page = alloc_page(gfp_mask);
2680 if (likely(page != NULL))
2681 percpu_counter_add(&cc->n_allocated_pages, 1);
2686 static void crypt_page_free(void *page, void *pool_data)
2688 struct crypt_config *cc = pool_data;
2691 percpu_counter_sub(&cc->n_allocated_pages, 1);
2694 static void crypt_dtr(struct dm_target *ti)
2696 struct crypt_config *cc = ti->private;
2703 if (cc->write_thread)
2704 kthread_stop(cc->write_thread);
2707 destroy_workqueue(cc->io_queue);
2708 if (cc->crypt_queue)
2709 destroy_workqueue(cc->crypt_queue);
2711 crypt_free_tfms(cc);
2713 bioset_exit(&cc->bs);
2715 mempool_exit(&cc->page_pool);
2716 mempool_exit(&cc->req_pool);
2717 mempool_exit(&cc->tag_pool);
2719 WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
2720 percpu_counter_destroy(&cc->n_allocated_pages);
2722 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
2723 cc->iv_gen_ops->dtr(cc);
2726 dm_put_device(ti, cc->dev);
2728 kfree_sensitive(cc->cipher_string);
2729 kfree_sensitive(cc->key_string);
2730 kfree_sensitive(cc->cipher_auth);
2731 kfree_sensitive(cc->authenc_key);
2733 mutex_destroy(&cc->bio_alloc_lock);
2735 /* Must zero key material before freeing */
2736 kfree_sensitive(cc);
2738 spin_lock(&dm_crypt_clients_lock);
2739 WARN_ON(!dm_crypt_clients_n);
2740 dm_crypt_clients_n--;
2741 crypt_calculate_pages_per_client();
2742 spin_unlock(&dm_crypt_clients_lock);
2744 dm_audit_log_dtr(DM_MSG_PREFIX, ti, 1);
2747 static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
2749 struct crypt_config *cc = ti->private;
2751 if (crypt_integrity_aead(cc))
2752 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2754 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2757 /* at least a 64 bit sector number should fit in our buffer */
2758 cc->iv_size = max(cc->iv_size,
2759 (unsigned int)(sizeof(u64) / sizeof(u8)));
2761 DMWARN("Selected cipher does not support IVs");
2765 /* Choose ivmode, see comments at iv code. */
2767 cc->iv_gen_ops = NULL;
2768 else if (strcmp(ivmode, "plain") == 0)
2769 cc->iv_gen_ops = &crypt_iv_plain_ops;
2770 else if (strcmp(ivmode, "plain64") == 0)
2771 cc->iv_gen_ops = &crypt_iv_plain64_ops;
2772 else if (strcmp(ivmode, "plain64be") == 0)
2773 cc->iv_gen_ops = &crypt_iv_plain64be_ops;
2774 else if (strcmp(ivmode, "essiv") == 0)
2775 cc->iv_gen_ops = &crypt_iv_essiv_ops;
2776 else if (strcmp(ivmode, "benbi") == 0)
2777 cc->iv_gen_ops = &crypt_iv_benbi_ops;
2778 else if (strcmp(ivmode, "null") == 0)
2779 cc->iv_gen_ops = &crypt_iv_null_ops;
2780 else if (strcmp(ivmode, "eboiv") == 0)
2781 cc->iv_gen_ops = &crypt_iv_eboiv_ops;
2782 else if (strcmp(ivmode, "elephant") == 0) {
2783 cc->iv_gen_ops = &crypt_iv_elephant_ops;
2785 cc->key_extra_size = cc->key_size / 2;
2786 if (cc->key_extra_size > ELEPHANT_MAX_KEY_SIZE)
2788 set_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags);
2789 } else if (strcmp(ivmode, "lmk") == 0) {
2790 cc->iv_gen_ops = &crypt_iv_lmk_ops;
2792 * Version 2 and 3 is recognised according
2793 * to length of provided multi-key string.
2794 * If present (version 3), last key is used as IV seed.
2795 * All keys (including IV seed) are always the same size.
2797 if (cc->key_size % cc->key_parts) {
2799 cc->key_extra_size = cc->key_size / cc->key_parts;
2801 } else if (strcmp(ivmode, "tcw") == 0) {
2802 cc->iv_gen_ops = &crypt_iv_tcw_ops;
2803 cc->key_parts += 2; /* IV + whitening */
2804 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2805 } else if (strcmp(ivmode, "random") == 0) {
2806 cc->iv_gen_ops = &crypt_iv_random_ops;
2807 /* Need storage space in integrity fields. */
2808 cc->integrity_iv_size = cc->iv_size;
2810 ti->error = "Invalid IV mode";
2818 * Workaround to parse HMAC algorithm from AEAD crypto API spec.
2819 * The HMAC is needed to calculate tag size (HMAC digest size).
2820 * This should be probably done by crypto-api calls (once available...)
2822 static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
2824 char *start, *end, *mac_alg = NULL;
2825 struct crypto_ahash *mac;
2827 if (!strstarts(cipher_api, "authenc("))
2830 start = strchr(cipher_api, '(');
2831 end = strchr(cipher_api, ',');
2832 if (!start || !end || ++start > end)
2835 mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
2838 strncpy(mac_alg, start, end - start);
2840 mac = crypto_alloc_ahash(mac_alg, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
2844 return PTR_ERR(mac);
2846 cc->key_mac_size = crypto_ahash_digestsize(mac);
2847 crypto_free_ahash(mac);
2849 cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
2850 if (!cc->authenc_key)
2856 static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
2857 char **ivmode, char **ivopts)
2859 struct crypt_config *cc = ti->private;
2860 char *tmp, *cipher_api, buf[CRYPTO_MAX_ALG_NAME];
2866 * New format (capi: prefix)
2867 * capi:cipher_api_spec-iv:ivopts
2869 tmp = &cipher_in[strlen("capi:")];
2871 /* Separate IV options if present, it can contain another '-' in hash name */
2872 *ivopts = strrchr(tmp, ':');
2878 *ivmode = strrchr(tmp, '-');
2883 /* The rest is crypto API spec */
2886 /* Alloc AEAD, can be used only in new format. */
2887 if (crypt_integrity_aead(cc)) {
2888 ret = crypt_ctr_auth_cipher(cc, cipher_api);
2890 ti->error = "Invalid AEAD cipher spec";
2895 if (*ivmode && !strcmp(*ivmode, "lmk"))
2896 cc->tfms_count = 64;
2898 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2900 ti->error = "Digest algorithm missing for ESSIV mode";
2903 ret = snprintf(buf, CRYPTO_MAX_ALG_NAME, "essiv(%s,%s)",
2904 cipher_api, *ivopts);
2905 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2906 ti->error = "Cannot allocate cipher string";
2912 cc->key_parts = cc->tfms_count;
2914 /* Allocate cipher */
2915 ret = crypt_alloc_tfms(cc, cipher_api);
2917 ti->error = "Error allocating crypto tfm";
2921 if (crypt_integrity_aead(cc))
2922 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2924 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2929 static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
2930 char **ivmode, char **ivopts)
2932 struct crypt_config *cc = ti->private;
2933 char *tmp, *cipher, *chainmode, *keycount;
2934 char *cipher_api = NULL;
2938 if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
2939 ti->error = "Bad cipher specification";
2944 * Legacy dm-crypt cipher specification
2945 * cipher[:keycount]-mode-iv:ivopts
2948 keycount = strsep(&tmp, "-");
2949 cipher = strsep(&keycount, ":");
2953 else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
2954 !is_power_of_2(cc->tfms_count)) {
2955 ti->error = "Bad cipher key count specification";
2958 cc->key_parts = cc->tfms_count;
2960 chainmode = strsep(&tmp, "-");
2961 *ivmode = strsep(&tmp, ":");
2965 * For compatibility with the original dm-crypt mapping format, if
2966 * only the cipher name is supplied, use cbc-plain.
2968 if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
2973 if (strcmp(chainmode, "ecb") && !*ivmode) {
2974 ti->error = "IV mechanism required";
2978 cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
2982 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2984 ti->error = "Digest algorithm missing for ESSIV mode";
2988 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2989 "essiv(%s(%s),%s)", chainmode, cipher, *ivopts);
2991 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2992 "%s(%s)", chainmode, cipher);
2994 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2999 /* Allocate cipher */
3000 ret = crypt_alloc_tfms(cc, cipher_api);
3002 ti->error = "Error allocating crypto tfm";
3010 ti->error = "Cannot allocate cipher strings";
3014 static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
3016 struct crypt_config *cc = ti->private;
3017 char *ivmode = NULL, *ivopts = NULL;
3020 cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
3021 if (!cc->cipher_string) {
3022 ti->error = "Cannot allocate cipher strings";
3026 if (strstarts(cipher_in, "capi:"))
3027 ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
3029 ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
3034 ret = crypt_ctr_ivmode(ti, ivmode);
3038 /* Initialize and set key */
3039 ret = crypt_set_key(cc, key);
3041 ti->error = "Error decoding and setting key";
3046 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
3047 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
3049 ti->error = "Error creating IV";
3054 /* Initialize IV (set keys for ESSIV etc) */
3055 if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
3056 ret = cc->iv_gen_ops->init(cc);
3058 ti->error = "Error initialising IV";
3063 /* wipe the kernel key payload copy */
3065 memset(cc->key, 0, cc->key_size * sizeof(u8));
3070 static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
3072 struct crypt_config *cc = ti->private;
3073 struct dm_arg_set as;
3074 static const struct dm_arg _args[] = {
3075 {0, 8, "Invalid number of feature args"},
3077 unsigned int opt_params, val;
3078 const char *opt_string, *sval;
3082 /* Optional parameters */
3086 ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
3090 while (opt_params--) {
3091 opt_string = dm_shift_arg(&as);
3093 ti->error = "Not enough feature arguments";
3097 if (!strcasecmp(opt_string, "allow_discards"))
3098 ti->num_discard_bios = 1;
3100 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
3101 set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3103 else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
3104 set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3105 else if (!strcasecmp(opt_string, "no_read_workqueue"))
3106 set_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3107 else if (!strcasecmp(opt_string, "no_write_workqueue"))
3108 set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3109 else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
3110 if (val == 0 || val > MAX_TAG_SIZE) {
3111 ti->error = "Invalid integrity arguments";
3114 cc->on_disk_tag_size = val;
3115 sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
3116 if (!strcasecmp(sval, "aead")) {
3117 set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
3118 } else if (strcasecmp(sval, "none")) {
3119 ti->error = "Unknown integrity profile";
3123 cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
3124 if (!cc->cipher_auth)
3126 } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
3127 if (cc->sector_size < (1 << SECTOR_SHIFT) ||
3128 cc->sector_size > 4096 ||
3129 (cc->sector_size & (cc->sector_size - 1))) {
3130 ti->error = "Invalid feature value for sector_size";
3133 if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
3134 ti->error = "Device size is not multiple of sector_size feature";
3137 cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
3138 } else if (!strcasecmp(opt_string, "iv_large_sectors"))
3139 set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3141 ti->error = "Invalid feature arguments";
3149 #ifdef CONFIG_BLK_DEV_ZONED
3150 static int crypt_report_zones(struct dm_target *ti,
3151 struct dm_report_zones_args *args, unsigned int nr_zones)
3153 struct crypt_config *cc = ti->private;
3155 return dm_report_zones(cc->dev->bdev, cc->start,
3156 cc->start + dm_target_offset(ti, args->next_sector),
3160 #define crypt_report_zones NULL
3164 * Construct an encryption mapping:
3165 * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
3167 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
3169 struct crypt_config *cc;
3170 const char *devname = dm_table_device_name(ti->table);
3172 unsigned int align_mask;
3173 unsigned long long tmpll;
3175 size_t iv_size_padding, additional_req_size;
3179 ti->error = "Not enough arguments";
3183 key_size = get_key_size(&argv[1]);
3185 ti->error = "Cannot parse key size";
3189 cc = kzalloc(struct_size(cc, key, key_size), GFP_KERNEL);
3191 ti->error = "Cannot allocate encryption context";
3194 cc->key_size = key_size;
3195 cc->sector_size = (1 << SECTOR_SHIFT);
3196 cc->sector_shift = 0;
3200 spin_lock(&dm_crypt_clients_lock);
3201 dm_crypt_clients_n++;
3202 crypt_calculate_pages_per_client();
3203 spin_unlock(&dm_crypt_clients_lock);
3205 ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
3209 /* Optional parameters need to be read before cipher constructor */
3211 ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
3216 ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
3220 if (crypt_integrity_aead(cc)) {
3221 cc->dmreq_start = sizeof(struct aead_request);
3222 cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
3223 align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
3225 cc->dmreq_start = sizeof(struct skcipher_request);
3226 cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
3227 align_mask = crypto_skcipher_alignmask(any_tfm(cc));
3229 cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
3231 if (align_mask < CRYPTO_MINALIGN) {
3232 /* Allocate the padding exactly */
3233 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
3237 * If the cipher requires greater alignment than kmalloc
3238 * alignment, we don't know the exact position of the
3239 * initialization vector. We must assume worst case.
3241 iv_size_padding = align_mask;
3244 /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
3245 additional_req_size = sizeof(struct dm_crypt_request) +
3246 iv_size_padding + cc->iv_size +
3249 sizeof(unsigned int);
3251 ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
3253 ti->error = "Cannot allocate crypt request mempool";
3257 cc->per_bio_data_size = ti->per_io_data_size =
3258 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
3261 ret = mempool_init(&cc->page_pool, BIO_MAX_VECS, crypt_page_alloc, crypt_page_free, cc);
3263 ti->error = "Cannot allocate page mempool";
3267 ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
3269 ti->error = "Cannot allocate crypt bioset";
3273 mutex_init(&cc->bio_alloc_lock);
3276 if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
3277 (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
3278 ti->error = "Invalid iv_offset sector";
3281 cc->iv_offset = tmpll;
3283 ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
3285 ti->error = "Device lookup failed";
3290 if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
3291 ti->error = "Invalid device sector";
3296 if (bdev_is_zoned(cc->dev->bdev)) {
3298 * For zoned block devices, we need to preserve the issuer write
3299 * ordering. To do so, disable write workqueues and force inline
3300 * encryption completion.
3302 set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3303 set_bit(DM_CRYPT_WRITE_INLINE, &cc->flags);
3306 * All zone append writes to a zone of a zoned block device will
3307 * have the same BIO sector, the start of the zone. When the
3308 * cypher IV mode uses sector values, all data targeting a
3309 * zone will be encrypted using the first sector numbers of the
3310 * zone. This will not result in write errors but will
3311 * cause most reads to fail as reads will use the sector values
3312 * for the actual data locations, resulting in IV mismatch.
3313 * To avoid this problem, ask DM core to emulate zone append
3314 * operations with regular writes.
3316 DMDEBUG("Zone append operations will be emulated");
3317 ti->emulate_zone_append = true;
3320 if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
3321 ret = crypt_integrity_ctr(cc, ti);
3325 cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
3326 if (!cc->tag_pool_max_sectors)
3327 cc->tag_pool_max_sectors = 1;
3329 ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
3330 cc->tag_pool_max_sectors * cc->on_disk_tag_size);
3332 ti->error = "Cannot allocate integrity tags mempool";
3336 cc->tag_pool_max_sectors <<= cc->sector_shift;
3340 cc->io_queue = alloc_workqueue("kcryptd_io/%s", WQ_MEM_RECLAIM, 1, devname);
3341 if (!cc->io_queue) {
3342 ti->error = "Couldn't create kcryptd io queue";
3346 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3347 cc->crypt_queue = alloc_workqueue("kcryptd/%s", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM,
3350 cc->crypt_queue = alloc_workqueue("kcryptd/%s",
3351 WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
3352 num_online_cpus(), devname);
3353 if (!cc->crypt_queue) {
3354 ti->error = "Couldn't create kcryptd queue";
3358 spin_lock_init(&cc->write_thread_lock);
3359 cc->write_tree = RB_ROOT;
3361 cc->write_thread = kthread_run(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
3362 if (IS_ERR(cc->write_thread)) {
3363 ret = PTR_ERR(cc->write_thread);
3364 cc->write_thread = NULL;
3365 ti->error = "Couldn't spawn write thread";
3369 ti->num_flush_bios = 1;
3370 ti->limit_swap_bios = true;
3371 ti->accounts_remapped_io = true;
3373 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 1);
3377 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 0);
3382 static int crypt_map(struct dm_target *ti, struct bio *bio)
3384 struct dm_crypt_io *io;
3385 struct crypt_config *cc = ti->private;
3388 * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
3389 * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
3390 * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
3392 if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
3393 bio_op(bio) == REQ_OP_DISCARD)) {
3394 bio_set_dev(bio, cc->dev->bdev);
3395 if (bio_sectors(bio))
3396 bio->bi_iter.bi_sector = cc->start +
3397 dm_target_offset(ti, bio->bi_iter.bi_sector);
3398 return DM_MAPIO_REMAPPED;
3402 * Check if bio is too large, split as needed.
3404 if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_VECS << PAGE_SHIFT)) &&
3405 (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
3406 dm_accept_partial_bio(bio, ((BIO_MAX_VECS << PAGE_SHIFT) >> SECTOR_SHIFT));
3409 * Ensure that bio is a multiple of internal sector encryption size
3410 * and is aligned to this size as defined in IO hints.
3412 if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
3413 return DM_MAPIO_KILL;
3415 if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
3416 return DM_MAPIO_KILL;
3418 io = dm_per_bio_data(bio, cc->per_bio_data_size);
3419 crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
3421 if (cc->on_disk_tag_size) {
3422 unsigned int tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
3424 if (unlikely(tag_len > KMALLOC_MAX_SIZE))
3425 io->integrity_metadata = NULL;
3427 io->integrity_metadata = kmalloc(tag_len, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
3429 if (unlikely(!io->integrity_metadata)) {
3430 if (bio_sectors(bio) > cc->tag_pool_max_sectors)
3431 dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
3432 io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
3433 io->integrity_metadata_from_pool = true;
3437 if (crypt_integrity_aead(cc))
3438 io->ctx.r.req_aead = (struct aead_request *)(io + 1);
3440 io->ctx.r.req = (struct skcipher_request *)(io + 1);
3442 if (bio_data_dir(io->base_bio) == READ) {
3443 if (kcryptd_io_read(io, CRYPT_MAP_READ_GFP))
3444 kcryptd_queue_read(io);
3446 kcryptd_queue_crypt(io);
3448 return DM_MAPIO_SUBMITTED;
3451 static char hex2asc(unsigned char c)
3453 return c + '0' + ((unsigned int)(9 - c) >> 4 & 0x27);
3456 static void crypt_status(struct dm_target *ti, status_type_t type,
3457 unsigned int status_flags, char *result, unsigned int maxlen)
3459 struct crypt_config *cc = ti->private;
3460 unsigned int i, sz = 0;
3461 int num_feature_args = 0;
3464 case STATUSTYPE_INFO:
3468 case STATUSTYPE_TABLE:
3469 DMEMIT("%s ", cc->cipher_string);
3471 if (cc->key_size > 0) {
3473 DMEMIT(":%u:%s", cc->key_size, cc->key_string);
3475 for (i = 0; i < cc->key_size; i++) {
3476 DMEMIT("%c%c", hex2asc(cc->key[i] >> 4),
3477 hex2asc(cc->key[i] & 0xf));
3483 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
3484 cc->dev->name, (unsigned long long)cc->start);
3486 num_feature_args += !!ti->num_discard_bios;
3487 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3488 num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3489 num_feature_args += test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3490 num_feature_args += test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3491 num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
3492 num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3493 if (cc->on_disk_tag_size)
3495 if (num_feature_args) {
3496 DMEMIT(" %d", num_feature_args);
3497 if (ti->num_discard_bios)
3498 DMEMIT(" allow_discards");
3499 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3500 DMEMIT(" same_cpu_crypt");
3501 if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
3502 DMEMIT(" submit_from_crypt_cpus");
3503 if (test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags))
3504 DMEMIT(" no_read_workqueue");
3505 if (test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))
3506 DMEMIT(" no_write_workqueue");
3507 if (cc->on_disk_tag_size)
3508 DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
3509 if (cc->sector_size != (1 << SECTOR_SHIFT))
3510 DMEMIT(" sector_size:%d", cc->sector_size);
3511 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
3512 DMEMIT(" iv_large_sectors");
3516 case STATUSTYPE_IMA:
3517 DMEMIT_TARGET_NAME_VERSION(ti->type);
3518 DMEMIT(",allow_discards=%c", ti->num_discard_bios ? 'y' : 'n');
3519 DMEMIT(",same_cpu_crypt=%c", test_bit(DM_CRYPT_SAME_CPU, &cc->flags) ? 'y' : 'n');
3520 DMEMIT(",submit_from_crypt_cpus=%c", test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags) ?
3522 DMEMIT(",no_read_workqueue=%c", test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags) ?
3524 DMEMIT(",no_write_workqueue=%c", test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags) ?
3526 DMEMIT(",iv_large_sectors=%c", test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags) ?
3529 if (cc->on_disk_tag_size)
3530 DMEMIT(",integrity_tag_size=%u,cipher_auth=%s",
3531 cc->on_disk_tag_size, cc->cipher_auth);
3532 if (cc->sector_size != (1 << SECTOR_SHIFT))
3533 DMEMIT(",sector_size=%d", cc->sector_size);
3534 if (cc->cipher_string)
3535 DMEMIT(",cipher_string=%s", cc->cipher_string);
3537 DMEMIT(",key_size=%u", cc->key_size);
3538 DMEMIT(",key_parts=%u", cc->key_parts);
3539 DMEMIT(",key_extra_size=%u", cc->key_extra_size);
3540 DMEMIT(",key_mac_size=%u", cc->key_mac_size);
3546 static void crypt_postsuspend(struct dm_target *ti)
3548 struct crypt_config *cc = ti->private;
3550 set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3553 static int crypt_preresume(struct dm_target *ti)
3555 struct crypt_config *cc = ti->private;
3557 if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
3558 DMERR("aborting resume - crypt key is not set.");
3565 static void crypt_resume(struct dm_target *ti)
3567 struct crypt_config *cc = ti->private;
3569 clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3572 /* Message interface
3576 static int crypt_message(struct dm_target *ti, unsigned int argc, char **argv,
3577 char *result, unsigned int maxlen)
3579 struct crypt_config *cc = ti->private;
3580 int key_size, ret = -EINVAL;
3585 if (!strcasecmp(argv[0], "key")) {
3586 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
3587 DMWARN("not suspended during key manipulation.");
3590 if (argc == 3 && !strcasecmp(argv[1], "set")) {
3591 /* The key size may not be changed. */
3592 key_size = get_key_size(&argv[2]);
3593 if (key_size < 0 || cc->key_size != key_size) {
3594 memset(argv[2], '0', strlen(argv[2]));
3598 ret = crypt_set_key(cc, argv[2]);
3601 if (cc->iv_gen_ops && cc->iv_gen_ops->init)
3602 ret = cc->iv_gen_ops->init(cc);
3603 /* wipe the kernel key payload copy */
3605 memset(cc->key, 0, cc->key_size * sizeof(u8));
3608 if (argc == 2 && !strcasecmp(argv[1], "wipe"))
3609 return crypt_wipe_key(cc);
3613 DMWARN("unrecognised message received.");
3617 static int crypt_iterate_devices(struct dm_target *ti,
3618 iterate_devices_callout_fn fn, void *data)
3620 struct crypt_config *cc = ti->private;
3622 return fn(ti, cc->dev, cc->start, ti->len, data);
3625 static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
3627 struct crypt_config *cc = ti->private;
3630 * Unfortunate constraint that is required to avoid the potential
3631 * for exceeding underlying device's max_segments limits -- due to
3632 * crypt_alloc_buffer() possibly allocating pages for the encryption
3633 * bio that are not as physically contiguous as the original bio.
3635 limits->max_segment_size = PAGE_SIZE;
3637 limits->logical_block_size =
3638 max_t(unsigned int, limits->logical_block_size, cc->sector_size);
3639 limits->physical_block_size =
3640 max_t(unsigned int, limits->physical_block_size, cc->sector_size);
3641 limits->io_min = max_t(unsigned int, limits->io_min, cc->sector_size);
3642 limits->dma_alignment = limits->logical_block_size - 1;
3645 static struct target_type crypt_target = {
3647 .version = {1, 24, 0},
3648 .module = THIS_MODULE,
3651 .features = DM_TARGET_ZONED_HM,
3652 .report_zones = crypt_report_zones,
3654 .status = crypt_status,
3655 .postsuspend = crypt_postsuspend,
3656 .preresume = crypt_preresume,
3657 .resume = crypt_resume,
3658 .message = crypt_message,
3659 .iterate_devices = crypt_iterate_devices,
3660 .io_hints = crypt_io_hints,
3664 MODULE_AUTHOR("Jana Saout <jana@saout.de>");
3665 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
3666 MODULE_LICENSE("GPL");