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/mempool.h>
19 #include <linux/slab.h>
20 #include <linux/crypto.h>
21 #include <linux/workqueue.h>
22 #include <linux/kthread.h>
23 #include <linux/backing-dev.h>
24 #include <linux/atomic.h>
25 #include <linux/scatterlist.h>
26 #include <linux/rbtree.h>
27 #include <linux/ctype.h>
29 #include <asm/unaligned.h>
30 #include <crypto/hash.h>
31 #include <crypto/md5.h>
32 #include <crypto/algapi.h>
33 #include <crypto/skcipher.h>
34 #include <crypto/aead.h>
35 #include <crypto/authenc.h>
36 #include <linux/rtnetlink.h> /* for struct rtattr and RTA macros only */
37 #include <linux/key-type.h>
38 #include <keys/user-type.h>
39 #include <keys/encrypted-type.h>
41 #include <linux/device-mapper.h>
43 #define DM_MSG_PREFIX "crypt"
46 * context holding the current state of a multi-part conversion
48 struct convert_context {
49 struct completion restart;
51 struct bvec_iter iter_in;
53 struct bvec_iter iter_out;
57 struct skcipher_request *req;
58 struct aead_request *req_aead;
64 * per bio private data
67 struct crypt_config *cc;
69 u8 *integrity_metadata;
70 bool integrity_metadata_from_pool:1;
73 struct work_struct work;
74 struct tasklet_struct tasklet;
76 struct convert_context ctx;
82 struct rb_node rb_node;
83 } CRYPTO_MINALIGN_ATTR;
85 struct dm_crypt_request {
86 struct convert_context *ctx;
87 struct scatterlist sg_in[4];
88 struct scatterlist sg_out[4];
94 struct crypt_iv_operations {
95 int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
97 void (*dtr)(struct crypt_config *cc);
98 int (*init)(struct crypt_config *cc);
99 int (*wipe)(struct crypt_config *cc);
100 int (*generator)(struct crypt_config *cc, u8 *iv,
101 struct dm_crypt_request *dmreq);
102 int (*post)(struct crypt_config *cc, u8 *iv,
103 struct dm_crypt_request *dmreq);
106 struct iv_benbi_private {
110 #define LMK_SEED_SIZE 64 /* hash + 0 */
111 struct iv_lmk_private {
112 struct crypto_shash *hash_tfm;
116 #define TCW_WHITENING_SIZE 16
117 struct iv_tcw_private {
118 struct crypto_shash *crc32_tfm;
123 #define ELEPHANT_MAX_KEY_SIZE 32
124 struct iv_elephant_private {
125 struct crypto_skcipher *tfm;
129 * Crypt: maps a linear range of a block device
130 * and encrypts / decrypts at the same time.
132 enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
133 DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD,
134 DM_CRYPT_NO_READ_WORKQUEUE, DM_CRYPT_NO_WRITE_WORKQUEUE,
135 DM_CRYPT_WRITE_INLINE };
138 CRYPT_MODE_INTEGRITY_AEAD, /* Use authenticated mode for cihper */
139 CRYPT_IV_LARGE_SECTORS, /* Calculate IV from sector_size, not 512B sectors */
140 CRYPT_ENCRYPT_PREPROCESS, /* Must preprocess data for encryption (elephant) */
144 * The fields in here must be read only after initialization.
146 struct crypt_config {
150 struct percpu_counter n_allocated_pages;
152 struct workqueue_struct *io_queue;
153 struct workqueue_struct *crypt_queue;
155 spinlock_t write_thread_lock;
156 struct task_struct *write_thread;
157 struct rb_root write_tree;
163 const struct crypt_iv_operations *iv_gen_ops;
165 struct iv_benbi_private benbi;
166 struct iv_lmk_private lmk;
167 struct iv_tcw_private tcw;
168 struct iv_elephant_private elephant;
171 unsigned int iv_size;
172 unsigned short int sector_size;
173 unsigned char sector_shift;
176 struct crypto_skcipher **tfms;
177 struct crypto_aead **tfms_aead;
180 unsigned long cipher_flags;
183 * Layout of each crypto request:
185 * struct skcipher_request
188 * struct dm_crypt_request
192 * The padding is added so that dm_crypt_request and the IV are
195 unsigned int dmreq_start;
197 unsigned int per_bio_data_size;
200 unsigned int key_size;
201 unsigned int key_parts; /* independent parts in key buffer */
202 unsigned int key_extra_size; /* additional keys length */
203 unsigned int key_mac_size; /* MAC key size for authenc(...) */
205 unsigned int integrity_tag_size;
206 unsigned int integrity_iv_size;
207 unsigned int on_disk_tag_size;
210 * pool for per bio private data, crypto requests,
211 * encryption requeusts/buffer pages and integrity tags
213 unsigned tag_pool_max_sectors;
219 struct mutex bio_alloc_lock;
221 u8 *authenc_key; /* space for keys in authenc() format (if used) */
226 #define MAX_TAG_SIZE 480
227 #define POOL_ENTRY_SIZE 512
229 static DEFINE_SPINLOCK(dm_crypt_clients_lock);
230 static unsigned dm_crypt_clients_n = 0;
231 static volatile unsigned long dm_crypt_pages_per_client;
232 #define DM_CRYPT_MEMORY_PERCENT 2
233 #define DM_CRYPT_MIN_PAGES_PER_CLIENT (BIO_MAX_PAGES * 16)
235 static void clone_init(struct dm_crypt_io *, struct bio *);
236 static void kcryptd_queue_crypt(struct dm_crypt_io *io);
237 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
238 struct scatterlist *sg);
240 static bool crypt_integrity_aead(struct crypt_config *cc);
243 * Use this to access cipher attributes that are independent of the key.
245 static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
247 return cc->cipher_tfm.tfms[0];
250 static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
252 return cc->cipher_tfm.tfms_aead[0];
256 * Different IV generation algorithms:
258 * plain: the initial vector is the 32-bit little-endian version of the sector
259 * number, padded with zeros if necessary.
261 * plain64: the initial vector is the 64-bit little-endian version of the sector
262 * number, padded with zeros if necessary.
264 * plain64be: the initial vector is the 64-bit big-endian version of the sector
265 * number, padded with zeros if necessary.
267 * essiv: "encrypted sector|salt initial vector", the sector number is
268 * encrypted with the bulk cipher using a salt as key. The salt
269 * should be derived from the bulk cipher's key via hashing.
271 * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
272 * (needed for LRW-32-AES and possible other narrow block modes)
274 * null: the initial vector is always zero. Provides compatibility with
275 * obsolete loop_fish2 devices. Do not use for new devices.
277 * lmk: Compatible implementation of the block chaining mode used
278 * by the Loop-AES block device encryption system
279 * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
280 * It operates on full 512 byte sectors and uses CBC
281 * with an IV derived from the sector number, the data and
282 * optionally extra IV seed.
283 * This means that after decryption the first block
284 * of sector must be tweaked according to decrypted data.
285 * Loop-AES can use three encryption schemes:
286 * version 1: is plain aes-cbc mode
287 * version 2: uses 64 multikey scheme with lmk IV generator
288 * version 3: the same as version 2 with additional IV seed
289 * (it uses 65 keys, last key is used as IV seed)
291 * tcw: Compatible implementation of the block chaining mode used
292 * by the TrueCrypt device encryption system (prior to version 4.1).
293 * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
294 * It operates on full 512 byte sectors and uses CBC
295 * with an IV derived from initial key and the sector number.
296 * In addition, whitening value is applied on every sector, whitening
297 * is calculated from initial key, sector number and mixed using CRC32.
298 * Note that this encryption scheme is vulnerable to watermarking attacks
299 * and should be used for old compatible containers access only.
301 * eboiv: Encrypted byte-offset IV (used in Bitlocker in CBC mode)
302 * The IV is encrypted little-endian byte-offset (with the same key
303 * and cipher as the volume).
305 * elephant: The extended version of eboiv with additional Elephant diffuser
306 * used with Bitlocker CBC mode.
307 * This mode was used in older Windows systems
308 * https://download.microsoft.com/download/0/2/3/0238acaf-d3bf-4a6d-b3d6-0a0be4bbb36e/bitlockercipher200608.pdf
311 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
312 struct dm_crypt_request *dmreq)
314 memset(iv, 0, cc->iv_size);
315 *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
320 static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
321 struct dm_crypt_request *dmreq)
323 memset(iv, 0, cc->iv_size);
324 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
329 static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
330 struct dm_crypt_request *dmreq)
332 memset(iv, 0, cc->iv_size);
333 /* iv_size is at least of size u64; usually it is 16 bytes */
334 *(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
339 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
340 struct dm_crypt_request *dmreq)
343 * ESSIV encryption of the IV is now handled by the crypto API,
344 * so just pass the plain sector number here.
346 memset(iv, 0, cc->iv_size);
347 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
352 static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
358 if (crypt_integrity_aead(cc))
359 bs = crypto_aead_blocksize(any_tfm_aead(cc));
361 bs = crypto_skcipher_blocksize(any_tfm(cc));
364 /* we need to calculate how far we must shift the sector count
365 * to get the cipher block count, we use this shift in _gen */
367 if (1 << log != bs) {
368 ti->error = "cypher blocksize is not a power of 2";
373 ti->error = "cypher blocksize is > 512";
377 cc->iv_gen_private.benbi.shift = 9 - log;
382 static void crypt_iv_benbi_dtr(struct crypt_config *cc)
386 static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
387 struct dm_crypt_request *dmreq)
391 memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
393 val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
394 put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
399 static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
400 struct dm_crypt_request *dmreq)
402 memset(iv, 0, cc->iv_size);
407 static void crypt_iv_lmk_dtr(struct crypt_config *cc)
409 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
411 if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
412 crypto_free_shash(lmk->hash_tfm);
413 lmk->hash_tfm = NULL;
415 kfree_sensitive(lmk->seed);
419 static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
422 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
424 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
425 ti->error = "Unsupported sector size for LMK";
429 lmk->hash_tfm = crypto_alloc_shash("md5", 0,
430 CRYPTO_ALG_ALLOCATES_MEMORY);
431 if (IS_ERR(lmk->hash_tfm)) {
432 ti->error = "Error initializing LMK hash";
433 return PTR_ERR(lmk->hash_tfm);
436 /* No seed in LMK version 2 */
437 if (cc->key_parts == cc->tfms_count) {
442 lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
444 crypt_iv_lmk_dtr(cc);
445 ti->error = "Error kmallocing seed storage in LMK";
452 static int crypt_iv_lmk_init(struct crypt_config *cc)
454 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
455 int subkey_size = cc->key_size / cc->key_parts;
457 /* LMK seed is on the position of LMK_KEYS + 1 key */
459 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
460 crypto_shash_digestsize(lmk->hash_tfm));
465 static int crypt_iv_lmk_wipe(struct crypt_config *cc)
467 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
470 memset(lmk->seed, 0, LMK_SEED_SIZE);
475 static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
476 struct dm_crypt_request *dmreq,
479 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
480 SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
481 struct md5_state md5state;
485 desc->tfm = lmk->hash_tfm;
487 r = crypto_shash_init(desc);
492 r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
497 /* Sector is always 512B, block size 16, add data of blocks 1-31 */
498 r = crypto_shash_update(desc, data + 16, 16 * 31);
502 /* Sector is cropped to 56 bits here */
503 buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
504 buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
505 buf[2] = cpu_to_le32(4024);
507 r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
511 /* No MD5 padding here */
512 r = crypto_shash_export(desc, &md5state);
516 for (i = 0; i < MD5_HASH_WORDS; i++)
517 __cpu_to_le32s(&md5state.hash[i]);
518 memcpy(iv, &md5state.hash, cc->iv_size);
523 static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
524 struct dm_crypt_request *dmreq)
526 struct scatterlist *sg;
530 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
531 sg = crypt_get_sg_data(cc, dmreq->sg_in);
532 src = kmap_atomic(sg_page(sg));
533 r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
536 memset(iv, 0, cc->iv_size);
541 static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
542 struct dm_crypt_request *dmreq)
544 struct scatterlist *sg;
548 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
551 sg = crypt_get_sg_data(cc, dmreq->sg_out);
552 dst = kmap_atomic(sg_page(sg));
553 r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
555 /* Tweak the first block of plaintext sector */
557 crypto_xor(dst + sg->offset, iv, cc->iv_size);
563 static void crypt_iv_tcw_dtr(struct crypt_config *cc)
565 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
567 kfree_sensitive(tcw->iv_seed);
569 kfree_sensitive(tcw->whitening);
570 tcw->whitening = NULL;
572 if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
573 crypto_free_shash(tcw->crc32_tfm);
574 tcw->crc32_tfm = NULL;
577 static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
580 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
582 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
583 ti->error = "Unsupported sector size for TCW";
587 if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
588 ti->error = "Wrong key size for TCW";
592 tcw->crc32_tfm = crypto_alloc_shash("crc32", 0,
593 CRYPTO_ALG_ALLOCATES_MEMORY);
594 if (IS_ERR(tcw->crc32_tfm)) {
595 ti->error = "Error initializing CRC32 in TCW";
596 return PTR_ERR(tcw->crc32_tfm);
599 tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
600 tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
601 if (!tcw->iv_seed || !tcw->whitening) {
602 crypt_iv_tcw_dtr(cc);
603 ti->error = "Error allocating seed storage in TCW";
610 static int crypt_iv_tcw_init(struct crypt_config *cc)
612 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
613 int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
615 memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
616 memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
622 static int crypt_iv_tcw_wipe(struct crypt_config *cc)
624 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
626 memset(tcw->iv_seed, 0, cc->iv_size);
627 memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
632 static int crypt_iv_tcw_whitening(struct crypt_config *cc,
633 struct dm_crypt_request *dmreq,
636 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
637 __le64 sector = cpu_to_le64(dmreq->iv_sector);
638 u8 buf[TCW_WHITENING_SIZE];
639 SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
642 /* xor whitening with sector number */
643 crypto_xor_cpy(buf, tcw->whitening, (u8 *)§or, 8);
644 crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)§or, 8);
646 /* calculate crc32 for every 32bit part and xor it */
647 desc->tfm = tcw->crc32_tfm;
648 for (i = 0; i < 4; i++) {
649 r = crypto_shash_init(desc);
652 r = crypto_shash_update(desc, &buf[i * 4], 4);
655 r = crypto_shash_final(desc, &buf[i * 4]);
659 crypto_xor(&buf[0], &buf[12], 4);
660 crypto_xor(&buf[4], &buf[8], 4);
662 /* apply whitening (8 bytes) to whole sector */
663 for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
664 crypto_xor(data + i * 8, buf, 8);
666 memzero_explicit(buf, sizeof(buf));
670 static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
671 struct dm_crypt_request *dmreq)
673 struct scatterlist *sg;
674 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
675 __le64 sector = cpu_to_le64(dmreq->iv_sector);
679 /* Remove whitening from ciphertext */
680 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
681 sg = crypt_get_sg_data(cc, dmreq->sg_in);
682 src = kmap_atomic(sg_page(sg));
683 r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
688 crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)§or, 8);
690 crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)§or,
696 static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
697 struct dm_crypt_request *dmreq)
699 struct scatterlist *sg;
703 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
706 /* Apply whitening on ciphertext */
707 sg = crypt_get_sg_data(cc, dmreq->sg_out);
708 dst = kmap_atomic(sg_page(sg));
709 r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
715 static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
716 struct dm_crypt_request *dmreq)
718 /* Used only for writes, there must be an additional space to store IV */
719 get_random_bytes(iv, cc->iv_size);
723 static int crypt_iv_eboiv_ctr(struct crypt_config *cc, struct dm_target *ti,
726 if (crypt_integrity_aead(cc)) {
727 ti->error = "AEAD transforms not supported for EBOIV";
731 if (crypto_skcipher_blocksize(any_tfm(cc)) != cc->iv_size) {
732 ti->error = "Block size of EBOIV cipher does "
733 "not match IV size of block cipher";
740 static int crypt_iv_eboiv_gen(struct crypt_config *cc, u8 *iv,
741 struct dm_crypt_request *dmreq)
743 u8 buf[MAX_CIPHER_BLOCKSIZE] __aligned(__alignof__(__le64));
744 struct skcipher_request *req;
745 struct scatterlist src, dst;
746 DECLARE_CRYPTO_WAIT(wait);
749 req = skcipher_request_alloc(any_tfm(cc), GFP_NOIO);
753 memset(buf, 0, cc->iv_size);
754 *(__le64 *)buf = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
756 sg_init_one(&src, page_address(ZERO_PAGE(0)), cc->iv_size);
757 sg_init_one(&dst, iv, cc->iv_size);
758 skcipher_request_set_crypt(req, &src, &dst, cc->iv_size, buf);
759 skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
760 err = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
761 skcipher_request_free(req);
766 static void crypt_iv_elephant_dtr(struct crypt_config *cc)
768 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
770 crypto_free_skcipher(elephant->tfm);
771 elephant->tfm = NULL;
774 static int crypt_iv_elephant_ctr(struct crypt_config *cc, struct dm_target *ti,
777 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
780 elephant->tfm = crypto_alloc_skcipher("ecb(aes)", 0,
781 CRYPTO_ALG_ALLOCATES_MEMORY);
782 if (IS_ERR(elephant->tfm)) {
783 r = PTR_ERR(elephant->tfm);
784 elephant->tfm = NULL;
788 r = crypt_iv_eboiv_ctr(cc, ti, NULL);
790 crypt_iv_elephant_dtr(cc);
794 static void diffuser_disk_to_cpu(u32 *d, size_t n)
796 #ifndef __LITTLE_ENDIAN
799 for (i = 0; i < n; i++)
800 d[i] = le32_to_cpu((__le32)d[i]);
804 static void diffuser_cpu_to_disk(__le32 *d, size_t n)
806 #ifndef __LITTLE_ENDIAN
809 for (i = 0; i < n; i++)
810 d[i] = cpu_to_le32((u32)d[i]);
814 static void diffuser_a_decrypt(u32 *d, size_t n)
818 for (i = 0; i < 5; i++) {
823 while (i1 < (n - 1)) {
824 d[i1] += d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
830 d[i1] += d[i2] ^ d[i3];
836 d[i1] += d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
839 d[i1] += d[i2] ^ d[i3];
845 static void diffuser_a_encrypt(u32 *d, size_t n)
849 for (i = 0; i < 5; i++) {
855 d[i1] -= d[i2] ^ d[i3];
858 d[i1] -= d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
864 d[i1] -= d[i2] ^ d[i3];
870 d[i1] -= d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
876 static void diffuser_b_decrypt(u32 *d, size_t n)
880 for (i = 0; i < 3; i++) {
885 while (i1 < (n - 1)) {
886 d[i1] += d[i2] ^ d[i3];
889 d[i1] += d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
895 d[i1] += d[i2] ^ d[i3];
901 d[i1] += d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
907 static void diffuser_b_encrypt(u32 *d, size_t n)
911 for (i = 0; i < 3; i++) {
917 d[i1] -= d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
923 d[i1] -= d[i2] ^ d[i3];
929 d[i1] -= d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
932 d[i1] -= d[i2] ^ d[i3];
938 static int crypt_iv_elephant(struct crypt_config *cc, struct dm_crypt_request *dmreq)
940 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
941 u8 *es, *ks, *data, *data2, *data_offset;
942 struct skcipher_request *req;
943 struct scatterlist *sg, *sg2, src, dst;
944 DECLARE_CRYPTO_WAIT(wait);
947 req = skcipher_request_alloc(elephant->tfm, GFP_NOIO);
948 es = kzalloc(16, GFP_NOIO); /* Key for AES */
949 ks = kzalloc(32, GFP_NOIO); /* Elephant sector key */
951 if (!req || !es || !ks) {
956 *(__le64 *)es = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
959 sg_init_one(&src, es, 16);
960 sg_init_one(&dst, ks, 16);
961 skcipher_request_set_crypt(req, &src, &dst, 16, NULL);
962 skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
963 r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
969 sg_init_one(&dst, &ks[16], 16);
970 r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
974 sg = crypt_get_sg_data(cc, dmreq->sg_out);
975 data = kmap_atomic(sg_page(sg));
976 data_offset = data + sg->offset;
978 /* Cannot modify original bio, copy to sg_out and apply Elephant to it */
979 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
980 sg2 = crypt_get_sg_data(cc, dmreq->sg_in);
981 data2 = kmap_atomic(sg_page(sg2));
982 memcpy(data_offset, data2 + sg2->offset, cc->sector_size);
983 kunmap_atomic(data2);
986 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
987 diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
988 diffuser_b_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
989 diffuser_a_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
990 diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
993 for (i = 0; i < (cc->sector_size / 32); i++)
994 crypto_xor(data_offset + i * 32, ks, 32);
996 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
997 diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
998 diffuser_a_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
999 diffuser_b_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
1000 diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
1003 kunmap_atomic(data);
1005 kfree_sensitive(ks);
1006 kfree_sensitive(es);
1007 skcipher_request_free(req);
1011 static int crypt_iv_elephant_gen(struct crypt_config *cc, u8 *iv,
1012 struct dm_crypt_request *dmreq)
1016 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
1017 r = crypt_iv_elephant(cc, dmreq);
1022 return crypt_iv_eboiv_gen(cc, iv, dmreq);
1025 static int crypt_iv_elephant_post(struct crypt_config *cc, u8 *iv,
1026 struct dm_crypt_request *dmreq)
1028 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
1029 return crypt_iv_elephant(cc, dmreq);
1034 static int crypt_iv_elephant_init(struct crypt_config *cc)
1036 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1037 int key_offset = cc->key_size - cc->key_extra_size;
1039 return crypto_skcipher_setkey(elephant->tfm, &cc->key[key_offset], cc->key_extra_size);
1042 static int crypt_iv_elephant_wipe(struct crypt_config *cc)
1044 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1045 u8 key[ELEPHANT_MAX_KEY_SIZE];
1047 memset(key, 0, cc->key_extra_size);
1048 return crypto_skcipher_setkey(elephant->tfm, key, cc->key_extra_size);
1051 static const struct crypt_iv_operations crypt_iv_plain_ops = {
1052 .generator = crypt_iv_plain_gen
1055 static const struct crypt_iv_operations crypt_iv_plain64_ops = {
1056 .generator = crypt_iv_plain64_gen
1059 static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
1060 .generator = crypt_iv_plain64be_gen
1063 static const struct crypt_iv_operations crypt_iv_essiv_ops = {
1064 .generator = crypt_iv_essiv_gen
1067 static const struct crypt_iv_operations crypt_iv_benbi_ops = {
1068 .ctr = crypt_iv_benbi_ctr,
1069 .dtr = crypt_iv_benbi_dtr,
1070 .generator = crypt_iv_benbi_gen
1073 static const struct crypt_iv_operations crypt_iv_null_ops = {
1074 .generator = crypt_iv_null_gen
1077 static const struct crypt_iv_operations crypt_iv_lmk_ops = {
1078 .ctr = crypt_iv_lmk_ctr,
1079 .dtr = crypt_iv_lmk_dtr,
1080 .init = crypt_iv_lmk_init,
1081 .wipe = crypt_iv_lmk_wipe,
1082 .generator = crypt_iv_lmk_gen,
1083 .post = crypt_iv_lmk_post
1086 static const struct crypt_iv_operations crypt_iv_tcw_ops = {
1087 .ctr = crypt_iv_tcw_ctr,
1088 .dtr = crypt_iv_tcw_dtr,
1089 .init = crypt_iv_tcw_init,
1090 .wipe = crypt_iv_tcw_wipe,
1091 .generator = crypt_iv_tcw_gen,
1092 .post = crypt_iv_tcw_post
1095 static struct crypt_iv_operations crypt_iv_random_ops = {
1096 .generator = crypt_iv_random_gen
1099 static struct crypt_iv_operations crypt_iv_eboiv_ops = {
1100 .ctr = crypt_iv_eboiv_ctr,
1101 .generator = crypt_iv_eboiv_gen
1104 static struct crypt_iv_operations crypt_iv_elephant_ops = {
1105 .ctr = crypt_iv_elephant_ctr,
1106 .dtr = crypt_iv_elephant_dtr,
1107 .init = crypt_iv_elephant_init,
1108 .wipe = crypt_iv_elephant_wipe,
1109 .generator = crypt_iv_elephant_gen,
1110 .post = crypt_iv_elephant_post
1114 * Integrity extensions
1116 static bool crypt_integrity_aead(struct crypt_config *cc)
1118 return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
1121 static bool crypt_integrity_hmac(struct crypt_config *cc)
1123 return crypt_integrity_aead(cc) && cc->key_mac_size;
1126 /* Get sg containing data */
1127 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
1128 struct scatterlist *sg)
1130 if (unlikely(crypt_integrity_aead(cc)))
1136 static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
1138 struct bio_integrity_payload *bip;
1139 unsigned int tag_len;
1142 if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
1145 bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
1147 return PTR_ERR(bip);
1149 tag_len = io->cc->on_disk_tag_size * (bio_sectors(bio) >> io->cc->sector_shift);
1151 bip->bip_iter.bi_size = tag_len;
1152 bip->bip_iter.bi_sector = io->cc->start + io->sector;
1154 ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
1155 tag_len, offset_in_page(io->integrity_metadata));
1156 if (unlikely(ret != tag_len))
1162 static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
1164 #ifdef CONFIG_BLK_DEV_INTEGRITY
1165 struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
1166 struct mapped_device *md = dm_table_get_md(ti->table);
1168 /* From now we require underlying device with our integrity profile */
1169 if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
1170 ti->error = "Integrity profile not supported.";
1174 if (bi->tag_size != cc->on_disk_tag_size ||
1175 bi->tuple_size != cc->on_disk_tag_size) {
1176 ti->error = "Integrity profile tag size mismatch.";
1179 if (1 << bi->interval_exp != cc->sector_size) {
1180 ti->error = "Integrity profile sector size mismatch.";
1184 if (crypt_integrity_aead(cc)) {
1185 cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
1186 DMDEBUG("%s: Integrity AEAD, tag size %u, IV size %u.", dm_device_name(md),
1187 cc->integrity_tag_size, cc->integrity_iv_size);
1189 if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
1190 ti->error = "Integrity AEAD auth tag size is not supported.";
1193 } else if (cc->integrity_iv_size)
1194 DMDEBUG("%s: Additional per-sector space %u bytes for IV.", dm_device_name(md),
1195 cc->integrity_iv_size);
1197 if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
1198 ti->error = "Not enough space for integrity tag in the profile.";
1204 ti->error = "Integrity profile not supported.";
1209 static void crypt_convert_init(struct crypt_config *cc,
1210 struct convert_context *ctx,
1211 struct bio *bio_out, struct bio *bio_in,
1214 ctx->bio_in = bio_in;
1215 ctx->bio_out = bio_out;
1217 ctx->iter_in = bio_in->bi_iter;
1219 ctx->iter_out = bio_out->bi_iter;
1220 ctx->cc_sector = sector + cc->iv_offset;
1221 init_completion(&ctx->restart);
1224 static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
1227 return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
1230 static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
1232 return (void *)((char *)dmreq - cc->dmreq_start);
1235 static u8 *iv_of_dmreq(struct crypt_config *cc,
1236 struct dm_crypt_request *dmreq)
1238 if (crypt_integrity_aead(cc))
1239 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1240 crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
1242 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1243 crypto_skcipher_alignmask(any_tfm(cc)) + 1);
1246 static u8 *org_iv_of_dmreq(struct crypt_config *cc,
1247 struct dm_crypt_request *dmreq)
1249 return iv_of_dmreq(cc, dmreq) + cc->iv_size;
1252 static __le64 *org_sector_of_dmreq(struct crypt_config *cc,
1253 struct dm_crypt_request *dmreq)
1255 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
1256 return (__le64 *) ptr;
1259 static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
1260 struct dm_crypt_request *dmreq)
1262 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
1263 cc->iv_size + sizeof(uint64_t);
1264 return (unsigned int*)ptr;
1267 static void *tag_from_dmreq(struct crypt_config *cc,
1268 struct dm_crypt_request *dmreq)
1270 struct convert_context *ctx = dmreq->ctx;
1271 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1273 return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
1274 cc->on_disk_tag_size];
1277 static void *iv_tag_from_dmreq(struct crypt_config *cc,
1278 struct dm_crypt_request *dmreq)
1280 return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
1283 static int crypt_convert_block_aead(struct crypt_config *cc,
1284 struct convert_context *ctx,
1285 struct aead_request *req,
1286 unsigned int tag_offset)
1288 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1289 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1290 struct dm_crypt_request *dmreq;
1291 u8 *iv, *org_iv, *tag_iv, *tag;
1295 BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
1297 /* Reject unexpected unaligned bio. */
1298 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1301 dmreq = dmreq_of_req(cc, req);
1302 dmreq->iv_sector = ctx->cc_sector;
1303 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1304 dmreq->iv_sector >>= cc->sector_shift;
1307 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1309 sector = org_sector_of_dmreq(cc, dmreq);
1310 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1312 iv = iv_of_dmreq(cc, dmreq);
1313 org_iv = org_iv_of_dmreq(cc, dmreq);
1314 tag = tag_from_dmreq(cc, dmreq);
1315 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1318 * |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1319 * | (authenticated) | (auth+encryption) | |
1320 * | sector_LE | IV | sector in/out | tag in/out |
1322 sg_init_table(dmreq->sg_in, 4);
1323 sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
1324 sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
1325 sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1326 sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
1328 sg_init_table(dmreq->sg_out, 4);
1329 sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
1330 sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
1331 sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1332 sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
1334 if (cc->iv_gen_ops) {
1335 /* For READs use IV stored in integrity metadata */
1336 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1337 memcpy(org_iv, tag_iv, cc->iv_size);
1339 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1342 /* Store generated IV in integrity metadata */
1343 if (cc->integrity_iv_size)
1344 memcpy(tag_iv, org_iv, cc->iv_size);
1346 /* Working copy of IV, to be modified in crypto API */
1347 memcpy(iv, org_iv, cc->iv_size);
1350 aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
1351 if (bio_data_dir(ctx->bio_in) == WRITE) {
1352 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1353 cc->sector_size, iv);
1354 r = crypto_aead_encrypt(req);
1355 if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
1356 memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
1357 cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
1359 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1360 cc->sector_size + cc->integrity_tag_size, iv);
1361 r = crypto_aead_decrypt(req);
1364 if (r == -EBADMSG) {
1365 char b[BDEVNAME_SIZE];
1366 DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx->bio_in, b),
1367 (unsigned long long)le64_to_cpu(*sector));
1370 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1371 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1373 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1374 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1379 static int crypt_convert_block_skcipher(struct crypt_config *cc,
1380 struct convert_context *ctx,
1381 struct skcipher_request *req,
1382 unsigned int tag_offset)
1384 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1385 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1386 struct scatterlist *sg_in, *sg_out;
1387 struct dm_crypt_request *dmreq;
1388 u8 *iv, *org_iv, *tag_iv;
1392 /* Reject unexpected unaligned bio. */
1393 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1396 dmreq = dmreq_of_req(cc, req);
1397 dmreq->iv_sector = ctx->cc_sector;
1398 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1399 dmreq->iv_sector >>= cc->sector_shift;
1402 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1404 iv = iv_of_dmreq(cc, dmreq);
1405 org_iv = org_iv_of_dmreq(cc, dmreq);
1406 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1408 sector = org_sector_of_dmreq(cc, dmreq);
1409 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1411 /* For skcipher we use only the first sg item */
1412 sg_in = &dmreq->sg_in[0];
1413 sg_out = &dmreq->sg_out[0];
1415 sg_init_table(sg_in, 1);
1416 sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1418 sg_init_table(sg_out, 1);
1419 sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1421 if (cc->iv_gen_ops) {
1422 /* For READs use IV stored in integrity metadata */
1423 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1424 memcpy(org_iv, tag_iv, cc->integrity_iv_size);
1426 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1429 /* Data can be already preprocessed in generator */
1430 if (test_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags))
1432 /* Store generated IV in integrity metadata */
1433 if (cc->integrity_iv_size)
1434 memcpy(tag_iv, org_iv, cc->integrity_iv_size);
1436 /* Working copy of IV, to be modified in crypto API */
1437 memcpy(iv, org_iv, cc->iv_size);
1440 skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
1442 if (bio_data_dir(ctx->bio_in) == WRITE)
1443 r = crypto_skcipher_encrypt(req);
1445 r = crypto_skcipher_decrypt(req);
1447 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1448 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1450 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1451 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1456 static void kcryptd_async_done(struct crypto_async_request *async_req,
1459 static int crypt_alloc_req_skcipher(struct crypt_config *cc,
1460 struct convert_context *ctx)
1462 unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
1465 ctx->r.req = mempool_alloc(&cc->req_pool, in_interrupt() ? GFP_ATOMIC : GFP_NOIO);
1470 skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
1473 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1474 * requests if driver request queue is full.
1476 skcipher_request_set_callback(ctx->r.req,
1477 CRYPTO_TFM_REQ_MAY_BACKLOG,
1478 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
1483 static int crypt_alloc_req_aead(struct crypt_config *cc,
1484 struct convert_context *ctx)
1486 if (!ctx->r.req_aead) {
1487 ctx->r.req_aead = mempool_alloc(&cc->req_pool, in_interrupt() ? GFP_ATOMIC : GFP_NOIO);
1488 if (!ctx->r.req_aead)
1492 aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
1495 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1496 * requests if driver request queue is full.
1498 aead_request_set_callback(ctx->r.req_aead,
1499 CRYPTO_TFM_REQ_MAY_BACKLOG,
1500 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
1505 static int crypt_alloc_req(struct crypt_config *cc,
1506 struct convert_context *ctx)
1508 if (crypt_integrity_aead(cc))
1509 return crypt_alloc_req_aead(cc, ctx);
1511 return crypt_alloc_req_skcipher(cc, ctx);
1514 static void crypt_free_req_skcipher(struct crypt_config *cc,
1515 struct skcipher_request *req, struct bio *base_bio)
1517 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1519 if ((struct skcipher_request *)(io + 1) != req)
1520 mempool_free(req, &cc->req_pool);
1523 static void crypt_free_req_aead(struct crypt_config *cc,
1524 struct aead_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 aead_request *)(io + 1) != req)
1529 mempool_free(req, &cc->req_pool);
1532 static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
1534 if (crypt_integrity_aead(cc))
1535 crypt_free_req_aead(cc, req, base_bio);
1537 crypt_free_req_skcipher(cc, req, base_bio);
1541 * Encrypt / decrypt data from one bio to another one (can be the same one)
1543 static blk_status_t crypt_convert(struct crypt_config *cc,
1544 struct convert_context *ctx, bool atomic, bool reset_pending)
1546 unsigned int tag_offset = 0;
1547 unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
1551 * if reset_pending is set we are dealing with the bio for the first time,
1552 * else we're continuing to work on the previous bio, so don't mess with
1553 * the cc_pending counter
1556 atomic_set(&ctx->cc_pending, 1);
1558 while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
1560 r = crypt_alloc_req(cc, ctx);
1562 complete(&ctx->restart);
1563 return BLK_STS_DEV_RESOURCE;
1566 atomic_inc(&ctx->cc_pending);
1568 if (crypt_integrity_aead(cc))
1569 r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
1571 r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
1575 * The request was queued by a crypto driver
1576 * but the driver request queue is full, let's wait.
1579 if (in_interrupt()) {
1580 if (try_wait_for_completion(&ctx->restart)) {
1582 * we don't have to block to wait for completion,
1587 * we can't wait for completion without blocking
1588 * exit and continue processing in a workqueue
1591 ctx->cc_sector += sector_step;
1593 return BLK_STS_DEV_RESOURCE;
1596 wait_for_completion(&ctx->restart);
1598 reinit_completion(&ctx->restart);
1601 * The request is queued and processed asynchronously,
1602 * completion function kcryptd_async_done() will be called.
1606 ctx->cc_sector += sector_step;
1610 * The request was already processed (synchronously).
1613 atomic_dec(&ctx->cc_pending);
1614 ctx->cc_sector += sector_step;
1620 * There was a data integrity error.
1623 atomic_dec(&ctx->cc_pending);
1624 return BLK_STS_PROTECTION;
1626 * There was an error while processing the request.
1629 atomic_dec(&ctx->cc_pending);
1630 return BLK_STS_IOERR;
1637 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
1640 * Generate a new unfragmented bio with the given size
1641 * This should never violate the device limitations (but only because
1642 * max_segment_size is being constrained to PAGE_SIZE).
1644 * This function may be called concurrently. If we allocate from the mempool
1645 * concurrently, there is a possibility of deadlock. For example, if we have
1646 * mempool of 256 pages, two processes, each wanting 256, pages allocate from
1647 * the mempool concurrently, it may deadlock in a situation where both processes
1648 * have allocated 128 pages and the mempool is exhausted.
1650 * In order to avoid this scenario we allocate the pages under a mutex.
1652 * In order to not degrade performance with excessive locking, we try
1653 * non-blocking allocations without a mutex first but on failure we fallback
1654 * to blocking allocations with a mutex.
1656 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
1658 struct crypt_config *cc = io->cc;
1660 unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1661 gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
1662 unsigned i, len, remaining_size;
1666 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1667 mutex_lock(&cc->bio_alloc_lock);
1669 clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, &cc->bs);
1673 clone_init(io, clone);
1675 remaining_size = size;
1677 for (i = 0; i < nr_iovecs; i++) {
1678 page = mempool_alloc(&cc->page_pool, gfp_mask);
1680 crypt_free_buffer_pages(cc, clone);
1682 gfp_mask |= __GFP_DIRECT_RECLAIM;
1686 len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
1688 bio_add_page(clone, page, len, 0);
1690 remaining_size -= len;
1693 /* Allocate space for integrity tags */
1694 if (dm_crypt_integrity_io_alloc(io, clone)) {
1695 crypt_free_buffer_pages(cc, clone);
1700 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1701 mutex_unlock(&cc->bio_alloc_lock);
1706 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1709 struct bvec_iter_all iter_all;
1711 bio_for_each_segment_all(bv, clone, iter_all) {
1712 BUG_ON(!bv->bv_page);
1713 mempool_free(bv->bv_page, &cc->page_pool);
1717 static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1718 struct bio *bio, sector_t sector)
1722 io->sector = sector;
1724 io->ctx.r.req = NULL;
1725 io->integrity_metadata = NULL;
1726 io->integrity_metadata_from_pool = false;
1727 io->in_tasklet = false;
1728 atomic_set(&io->io_pending, 0);
1731 static void crypt_inc_pending(struct dm_crypt_io *io)
1733 atomic_inc(&io->io_pending);
1736 static void kcryptd_io_bio_endio(struct work_struct *work)
1738 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1739 bio_endio(io->base_bio);
1743 * One of the bios was finished. Check for completion of
1744 * the whole request and correctly clean up the buffer.
1746 static void crypt_dec_pending(struct dm_crypt_io *io)
1748 struct crypt_config *cc = io->cc;
1749 struct bio *base_bio = io->base_bio;
1750 blk_status_t error = io->error;
1752 if (!atomic_dec_and_test(&io->io_pending))
1756 crypt_free_req(cc, io->ctx.r.req, base_bio);
1758 if (unlikely(io->integrity_metadata_from_pool))
1759 mempool_free(io->integrity_metadata, &io->cc->tag_pool);
1761 kfree(io->integrity_metadata);
1763 base_bio->bi_status = error;
1766 * If we are running this function from our tasklet,
1767 * we can't call bio_endio() here, because it will call
1768 * clone_endio() from dm.c, which in turn will
1769 * free the current struct dm_crypt_io structure with
1770 * our tasklet. In this case we need to delay bio_endio()
1771 * execution to after the tasklet is done and dequeued.
1773 if (io->in_tasklet) {
1774 INIT_WORK(&io->work, kcryptd_io_bio_endio);
1775 queue_work(cc->io_queue, &io->work);
1779 bio_endio(base_bio);
1783 * kcryptd/kcryptd_io:
1785 * Needed because it would be very unwise to do decryption in an
1786 * interrupt context.
1788 * kcryptd performs the actual encryption or decryption.
1790 * kcryptd_io performs the IO submission.
1792 * They must be separated as otherwise the final stages could be
1793 * starved by new requests which can block in the first stages due
1794 * to memory allocation.
1796 * The work is done per CPU global for all dm-crypt instances.
1797 * They should not depend on each other and do not block.
1799 static void crypt_endio(struct bio *clone)
1801 struct dm_crypt_io *io = clone->bi_private;
1802 struct crypt_config *cc = io->cc;
1803 unsigned rw = bio_data_dir(clone);
1807 * free the processed pages
1810 crypt_free_buffer_pages(cc, clone);
1812 error = clone->bi_status;
1815 if (rw == READ && !error) {
1816 kcryptd_queue_crypt(io);
1820 if (unlikely(error))
1823 crypt_dec_pending(io);
1826 static void clone_init(struct dm_crypt_io *io, struct bio *clone)
1828 struct crypt_config *cc = io->cc;
1830 clone->bi_private = io;
1831 clone->bi_end_io = crypt_endio;
1832 bio_set_dev(clone, cc->dev->bdev);
1833 clone->bi_opf = io->base_bio->bi_opf;
1836 static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
1838 struct crypt_config *cc = io->cc;
1842 * We need the original biovec array in order to decrypt
1843 * the whole bio data *afterwards* -- thanks to immutable
1844 * biovecs we don't need to worry about the block layer
1845 * modifying the biovec array; so leverage bio_clone_fast().
1847 clone = bio_clone_fast(io->base_bio, gfp, &cc->bs);
1851 crypt_inc_pending(io);
1853 clone_init(io, clone);
1854 clone->bi_iter.bi_sector = cc->start + io->sector;
1856 if (dm_crypt_integrity_io_alloc(io, clone)) {
1857 crypt_dec_pending(io);
1862 submit_bio_noacct(clone);
1866 static void kcryptd_io_read_work(struct work_struct *work)
1868 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1870 crypt_inc_pending(io);
1871 if (kcryptd_io_read(io, GFP_NOIO))
1872 io->error = BLK_STS_RESOURCE;
1873 crypt_dec_pending(io);
1876 static void kcryptd_queue_read(struct dm_crypt_io *io)
1878 struct crypt_config *cc = io->cc;
1880 INIT_WORK(&io->work, kcryptd_io_read_work);
1881 queue_work(cc->io_queue, &io->work);
1884 static void kcryptd_io_write(struct dm_crypt_io *io)
1886 struct bio *clone = io->ctx.bio_out;
1888 submit_bio_noacct(clone);
1891 #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1893 static int dmcrypt_write(void *data)
1895 struct crypt_config *cc = data;
1896 struct dm_crypt_io *io;
1899 struct rb_root write_tree;
1900 struct blk_plug plug;
1902 spin_lock_irq(&cc->write_thread_lock);
1905 if (!RB_EMPTY_ROOT(&cc->write_tree))
1908 set_current_state(TASK_INTERRUPTIBLE);
1910 spin_unlock_irq(&cc->write_thread_lock);
1912 if (unlikely(kthread_should_stop())) {
1913 set_current_state(TASK_RUNNING);
1919 set_current_state(TASK_RUNNING);
1920 spin_lock_irq(&cc->write_thread_lock);
1921 goto continue_locked;
1924 write_tree = cc->write_tree;
1925 cc->write_tree = RB_ROOT;
1926 spin_unlock_irq(&cc->write_thread_lock);
1928 BUG_ON(rb_parent(write_tree.rb_node));
1931 * Note: we cannot walk the tree here with rb_next because
1932 * the structures may be freed when kcryptd_io_write is called.
1934 blk_start_plug(&plug);
1936 io = crypt_io_from_node(rb_first(&write_tree));
1937 rb_erase(&io->rb_node, &write_tree);
1938 kcryptd_io_write(io);
1940 } while (!RB_EMPTY_ROOT(&write_tree));
1941 blk_finish_plug(&plug);
1946 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
1948 struct bio *clone = io->ctx.bio_out;
1949 struct crypt_config *cc = io->cc;
1950 unsigned long flags;
1952 struct rb_node **rbp, *parent;
1954 if (unlikely(io->error)) {
1955 crypt_free_buffer_pages(cc, clone);
1957 crypt_dec_pending(io);
1961 /* crypt_convert should have filled the clone bio */
1962 BUG_ON(io->ctx.iter_out.bi_size);
1964 clone->bi_iter.bi_sector = cc->start + io->sector;
1966 if ((likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) ||
1967 test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags)) {
1968 submit_bio_noacct(clone);
1972 spin_lock_irqsave(&cc->write_thread_lock, flags);
1973 if (RB_EMPTY_ROOT(&cc->write_tree))
1974 wake_up_process(cc->write_thread);
1975 rbp = &cc->write_tree.rb_node;
1977 sector = io->sector;
1980 if (sector < crypt_io_from_node(parent)->sector)
1981 rbp = &(*rbp)->rb_left;
1983 rbp = &(*rbp)->rb_right;
1985 rb_link_node(&io->rb_node, parent, rbp);
1986 rb_insert_color(&io->rb_node, &cc->write_tree);
1987 spin_unlock_irqrestore(&cc->write_thread_lock, flags);
1990 static bool kcryptd_crypt_write_inline(struct crypt_config *cc,
1991 struct convert_context *ctx)
1994 if (!test_bit(DM_CRYPT_WRITE_INLINE, &cc->flags))
1998 * Note: zone append writes (REQ_OP_ZONE_APPEND) do not have ordering
1999 * constraints so they do not need to be issued inline by
2000 * kcryptd_crypt_write_convert().
2002 switch (bio_op(ctx->bio_in)) {
2004 case REQ_OP_WRITE_SAME:
2005 case REQ_OP_WRITE_ZEROES:
2012 static void kcryptd_crypt_write_continue(struct work_struct *work)
2014 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2015 struct crypt_config *cc = io->cc;
2016 struct convert_context *ctx = &io->ctx;
2018 sector_t sector = io->sector;
2021 wait_for_completion(&ctx->restart);
2022 reinit_completion(&ctx->restart);
2024 r = crypt_convert(cc, &io->ctx, true, false);
2027 crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
2028 if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
2029 /* Wait for completion signaled by kcryptd_async_done() */
2030 wait_for_completion(&ctx->restart);
2034 /* Encryption was already finished, submit io now */
2035 if (crypt_finished) {
2036 kcryptd_crypt_write_io_submit(io, 0);
2037 io->sector = sector;
2040 crypt_dec_pending(io);
2043 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
2045 struct crypt_config *cc = io->cc;
2046 struct convert_context *ctx = &io->ctx;
2049 sector_t sector = io->sector;
2053 * Prevent io from disappearing until this function completes.
2055 crypt_inc_pending(io);
2056 crypt_convert_init(cc, ctx, NULL, io->base_bio, sector);
2058 clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
2059 if (unlikely(!clone)) {
2060 io->error = BLK_STS_IOERR;
2064 io->ctx.bio_out = clone;
2065 io->ctx.iter_out = clone->bi_iter;
2067 if (crypt_integrity_aead(cc)) {
2068 bio_copy_data(clone, io->base_bio);
2069 io->ctx.bio_in = clone;
2070 io->ctx.iter_in = clone->bi_iter;
2073 sector += bio_sectors(clone);
2075 crypt_inc_pending(io);
2076 r = crypt_convert(cc, ctx,
2077 test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags), true);
2079 * Crypto API backlogged the request, because its queue was full
2080 * and we're in softirq context, so continue from a workqueue
2081 * (TODO: is it actually possible to be in softirq in the write path?)
2083 if (r == BLK_STS_DEV_RESOURCE) {
2084 INIT_WORK(&io->work, kcryptd_crypt_write_continue);
2085 queue_work(cc->crypt_queue, &io->work);
2090 crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
2091 if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
2092 /* Wait for completion signaled by kcryptd_async_done() */
2093 wait_for_completion(&ctx->restart);
2097 /* Encryption was already finished, submit io now */
2098 if (crypt_finished) {
2099 kcryptd_crypt_write_io_submit(io, 0);
2100 io->sector = sector;
2104 crypt_dec_pending(io);
2107 static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
2109 crypt_dec_pending(io);
2112 static void kcryptd_crypt_read_continue(struct work_struct *work)
2114 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2115 struct crypt_config *cc = io->cc;
2118 wait_for_completion(&io->ctx.restart);
2119 reinit_completion(&io->ctx.restart);
2121 r = crypt_convert(cc, &io->ctx, true, false);
2125 if (atomic_dec_and_test(&io->ctx.cc_pending))
2126 kcryptd_crypt_read_done(io);
2128 crypt_dec_pending(io);
2131 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
2133 struct crypt_config *cc = io->cc;
2136 crypt_inc_pending(io);
2138 crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
2141 r = crypt_convert(cc, &io->ctx,
2142 test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags), true);
2144 * Crypto API backlogged the request, because its queue was full
2145 * and we're in softirq context, so continue from a workqueue
2147 if (r == BLK_STS_DEV_RESOURCE) {
2148 INIT_WORK(&io->work, kcryptd_crypt_read_continue);
2149 queue_work(cc->crypt_queue, &io->work);
2155 if (atomic_dec_and_test(&io->ctx.cc_pending))
2156 kcryptd_crypt_read_done(io);
2158 crypt_dec_pending(io);
2161 static void kcryptd_async_done(struct crypto_async_request *async_req,
2164 struct dm_crypt_request *dmreq = async_req->data;
2165 struct convert_context *ctx = dmreq->ctx;
2166 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
2167 struct crypt_config *cc = io->cc;
2170 * A request from crypto driver backlog is going to be processed now,
2171 * finish the completion and continue in crypt_convert().
2172 * (Callback will be called for the second time for this request.)
2174 if (error == -EINPROGRESS) {
2175 complete(&ctx->restart);
2179 if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
2180 error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
2182 if (error == -EBADMSG) {
2183 char b[BDEVNAME_SIZE];
2184 DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx->bio_in, b),
2185 (unsigned long long)le64_to_cpu(*org_sector_of_dmreq(cc, dmreq)));
2186 io->error = BLK_STS_PROTECTION;
2187 } else if (error < 0)
2188 io->error = BLK_STS_IOERR;
2190 crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
2192 if (!atomic_dec_and_test(&ctx->cc_pending))
2196 * The request is fully completed: for inline writes, let
2197 * kcryptd_crypt_write_convert() do the IO submission.
2199 if (bio_data_dir(io->base_bio) == READ) {
2200 kcryptd_crypt_read_done(io);
2204 if (kcryptd_crypt_write_inline(cc, ctx)) {
2205 complete(&ctx->restart);
2209 kcryptd_crypt_write_io_submit(io, 1);
2212 static void kcryptd_crypt(struct work_struct *work)
2214 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2216 if (bio_data_dir(io->base_bio) == READ)
2217 kcryptd_crypt_read_convert(io);
2219 kcryptd_crypt_write_convert(io);
2222 static void kcryptd_crypt_tasklet(unsigned long work)
2224 kcryptd_crypt((struct work_struct *)work);
2227 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
2229 struct crypt_config *cc = io->cc;
2231 if ((bio_data_dir(io->base_bio) == READ && test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags)) ||
2232 (bio_data_dir(io->base_bio) == WRITE && test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))) {
2234 * in_irq(): Crypto API's skcipher_walk_first() refuses to work in hard IRQ context.
2235 * irqs_disabled(): the kernel may run some IO completion from the idle thread, but
2236 * it is being executed with irqs disabled.
2238 if (in_irq() || irqs_disabled()) {
2239 io->in_tasklet = true;
2240 tasklet_init(&io->tasklet, kcryptd_crypt_tasklet, (unsigned long)&io->work);
2241 tasklet_schedule(&io->tasklet);
2245 kcryptd_crypt(&io->work);
2249 INIT_WORK(&io->work, kcryptd_crypt);
2250 queue_work(cc->crypt_queue, &io->work);
2253 static void crypt_free_tfms_aead(struct crypt_config *cc)
2255 if (!cc->cipher_tfm.tfms_aead)
2258 if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2259 crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
2260 cc->cipher_tfm.tfms_aead[0] = NULL;
2263 kfree(cc->cipher_tfm.tfms_aead);
2264 cc->cipher_tfm.tfms_aead = NULL;
2267 static void crypt_free_tfms_skcipher(struct crypt_config *cc)
2271 if (!cc->cipher_tfm.tfms)
2274 for (i = 0; i < cc->tfms_count; i++)
2275 if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
2276 crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
2277 cc->cipher_tfm.tfms[i] = NULL;
2280 kfree(cc->cipher_tfm.tfms);
2281 cc->cipher_tfm.tfms = NULL;
2284 static void crypt_free_tfms(struct crypt_config *cc)
2286 if (crypt_integrity_aead(cc))
2287 crypt_free_tfms_aead(cc);
2289 crypt_free_tfms_skcipher(cc);
2292 static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
2297 cc->cipher_tfm.tfms = kcalloc(cc->tfms_count,
2298 sizeof(struct crypto_skcipher *),
2300 if (!cc->cipher_tfm.tfms)
2303 for (i = 0; i < cc->tfms_count; i++) {
2304 cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0,
2305 CRYPTO_ALG_ALLOCATES_MEMORY);
2306 if (IS_ERR(cc->cipher_tfm.tfms[i])) {
2307 err = PTR_ERR(cc->cipher_tfm.tfms[i]);
2308 crypt_free_tfms(cc);
2314 * dm-crypt performance can vary greatly depending on which crypto
2315 * algorithm implementation is used. Help people debug performance
2316 * problems by logging the ->cra_driver_name.
2318 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2319 crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
2323 static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
2327 cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
2328 if (!cc->cipher_tfm.tfms)
2331 cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0,
2332 CRYPTO_ALG_ALLOCATES_MEMORY);
2333 if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2334 err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
2335 crypt_free_tfms(cc);
2339 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2340 crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
2344 static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
2346 if (crypt_integrity_aead(cc))
2347 return crypt_alloc_tfms_aead(cc, ciphermode);
2349 return crypt_alloc_tfms_skcipher(cc, ciphermode);
2352 static unsigned crypt_subkey_size(struct crypt_config *cc)
2354 return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
2357 static unsigned crypt_authenckey_size(struct crypt_config *cc)
2359 return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
2363 * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
2364 * the key must be for some reason in special format.
2365 * This funcion converts cc->key to this special format.
2367 static void crypt_copy_authenckey(char *p, const void *key,
2368 unsigned enckeylen, unsigned authkeylen)
2370 struct crypto_authenc_key_param *param;
2373 rta = (struct rtattr *)p;
2374 param = RTA_DATA(rta);
2375 param->enckeylen = cpu_to_be32(enckeylen);
2376 rta->rta_len = RTA_LENGTH(sizeof(*param));
2377 rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
2378 p += RTA_SPACE(sizeof(*param));
2379 memcpy(p, key + enckeylen, authkeylen);
2381 memcpy(p, key, enckeylen);
2384 static int crypt_setkey(struct crypt_config *cc)
2386 unsigned subkey_size;
2389 /* Ignore extra keys (which are used for IV etc) */
2390 subkey_size = crypt_subkey_size(cc);
2392 if (crypt_integrity_hmac(cc)) {
2393 if (subkey_size < cc->key_mac_size)
2396 crypt_copy_authenckey(cc->authenc_key, cc->key,
2397 subkey_size - cc->key_mac_size,
2401 for (i = 0; i < cc->tfms_count; i++) {
2402 if (crypt_integrity_hmac(cc))
2403 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2404 cc->authenc_key, crypt_authenckey_size(cc));
2405 else if (crypt_integrity_aead(cc))
2406 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2407 cc->key + (i * subkey_size),
2410 r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
2411 cc->key + (i * subkey_size),
2417 if (crypt_integrity_hmac(cc))
2418 memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
2425 static bool contains_whitespace(const char *str)
2428 if (isspace(*str++))
2433 static int set_key_user(struct crypt_config *cc, struct key *key)
2435 const struct user_key_payload *ukp;
2437 ukp = user_key_payload_locked(key);
2439 return -EKEYREVOKED;
2441 if (cc->key_size != ukp->datalen)
2444 memcpy(cc->key, ukp->data, cc->key_size);
2449 #if defined(CONFIG_ENCRYPTED_KEYS) || defined(CONFIG_ENCRYPTED_KEYS_MODULE)
2450 static int set_key_encrypted(struct crypt_config *cc, struct key *key)
2452 const struct encrypted_key_payload *ekp;
2454 ekp = key->payload.data[0];
2456 return -EKEYREVOKED;
2458 if (cc->key_size != ekp->decrypted_datalen)
2461 memcpy(cc->key, ekp->decrypted_data, cc->key_size);
2465 #endif /* CONFIG_ENCRYPTED_KEYS */
2467 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2469 char *new_key_string, *key_desc;
2471 struct key_type *type;
2473 int (*set_key)(struct crypt_config *cc, struct key *key);
2476 * Reject key_string with whitespace. dm core currently lacks code for
2477 * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2479 if (contains_whitespace(key_string)) {
2480 DMERR("whitespace chars not allowed in key string");
2484 /* look for next ':' separating key_type from key_description */
2485 key_desc = strpbrk(key_string, ":");
2486 if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2489 if (!strncmp(key_string, "logon:", key_desc - key_string + 1)) {
2490 type = &key_type_logon;
2491 set_key = set_key_user;
2492 } else if (!strncmp(key_string, "user:", key_desc - key_string + 1)) {
2493 type = &key_type_user;
2494 set_key = set_key_user;
2495 #if defined(CONFIG_ENCRYPTED_KEYS) || defined(CONFIG_ENCRYPTED_KEYS_MODULE)
2496 } else if (!strncmp(key_string, "encrypted:", key_desc - key_string + 1)) {
2497 type = &key_type_encrypted;
2498 set_key = set_key_encrypted;
2504 new_key_string = kstrdup(key_string, GFP_KERNEL);
2505 if (!new_key_string)
2508 key = request_key(type, key_desc + 1, NULL);
2510 kfree_sensitive(new_key_string);
2511 return PTR_ERR(key);
2514 down_read(&key->sem);
2516 ret = set_key(cc, key);
2520 kfree_sensitive(new_key_string);
2527 /* clear the flag since following operations may invalidate previously valid key */
2528 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2530 ret = crypt_setkey(cc);
2533 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2534 kfree_sensitive(cc->key_string);
2535 cc->key_string = new_key_string;
2537 kfree_sensitive(new_key_string);
2542 static int get_key_size(char **key_string)
2547 if (*key_string[0] != ':')
2548 return strlen(*key_string) >> 1;
2550 /* look for next ':' in key string */
2551 colon = strpbrk(*key_string + 1, ":");
2555 if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2558 *key_string = colon;
2560 /* remaining key string should be :<logon|user>:<key_desc> */
2567 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2572 static int get_key_size(char **key_string)
2574 return (*key_string[0] == ':') ? -EINVAL : (int)(strlen(*key_string) >> 1);
2577 #endif /* CONFIG_KEYS */
2579 static int crypt_set_key(struct crypt_config *cc, char *key)
2582 int key_string_len = strlen(key);
2584 /* Hyphen (which gives a key_size of zero) means there is no key. */
2585 if (!cc->key_size && strcmp(key, "-"))
2588 /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2589 if (key[0] == ':') {
2590 r = crypt_set_keyring_key(cc, key + 1);
2594 /* clear the flag since following operations may invalidate previously valid key */
2595 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2597 /* wipe references to any kernel keyring key */
2598 kfree_sensitive(cc->key_string);
2599 cc->key_string = NULL;
2601 /* Decode key from its hex representation. */
2602 if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
2605 r = crypt_setkey(cc);
2607 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2610 /* Hex key string not needed after here, so wipe it. */
2611 memset(key, '0', key_string_len);
2616 static int crypt_wipe_key(struct crypt_config *cc)
2620 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2621 get_random_bytes(&cc->key, cc->key_size);
2623 /* Wipe IV private keys */
2624 if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
2625 r = cc->iv_gen_ops->wipe(cc);
2630 kfree_sensitive(cc->key_string);
2631 cc->key_string = NULL;
2632 r = crypt_setkey(cc);
2633 memset(&cc->key, 0, cc->key_size * sizeof(u8));
2638 static void crypt_calculate_pages_per_client(void)
2640 unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
2642 if (!dm_crypt_clients_n)
2645 pages /= dm_crypt_clients_n;
2646 if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
2647 pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
2648 dm_crypt_pages_per_client = pages;
2651 static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
2653 struct crypt_config *cc = pool_data;
2657 * Note, percpu_counter_read_positive() may over (and under) estimate
2658 * the current usage by at most (batch - 1) * num_online_cpus() pages,
2659 * but avoids potential spinlock contention of an exact result.
2661 if (unlikely(percpu_counter_read_positive(&cc->n_allocated_pages) >= dm_crypt_pages_per_client) &&
2662 likely(gfp_mask & __GFP_NORETRY))
2665 page = alloc_page(gfp_mask);
2666 if (likely(page != NULL))
2667 percpu_counter_add(&cc->n_allocated_pages, 1);
2672 static void crypt_page_free(void *page, void *pool_data)
2674 struct crypt_config *cc = pool_data;
2677 percpu_counter_sub(&cc->n_allocated_pages, 1);
2680 static void crypt_dtr(struct dm_target *ti)
2682 struct crypt_config *cc = ti->private;
2689 if (cc->write_thread)
2690 kthread_stop(cc->write_thread);
2693 destroy_workqueue(cc->io_queue);
2694 if (cc->crypt_queue)
2695 destroy_workqueue(cc->crypt_queue);
2697 crypt_free_tfms(cc);
2699 bioset_exit(&cc->bs);
2701 mempool_exit(&cc->page_pool);
2702 mempool_exit(&cc->req_pool);
2703 mempool_exit(&cc->tag_pool);
2705 WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
2706 percpu_counter_destroy(&cc->n_allocated_pages);
2708 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
2709 cc->iv_gen_ops->dtr(cc);
2712 dm_put_device(ti, cc->dev);
2714 kfree_sensitive(cc->cipher_string);
2715 kfree_sensitive(cc->key_string);
2716 kfree_sensitive(cc->cipher_auth);
2717 kfree_sensitive(cc->authenc_key);
2719 mutex_destroy(&cc->bio_alloc_lock);
2721 /* Must zero key material before freeing */
2722 kfree_sensitive(cc);
2724 spin_lock(&dm_crypt_clients_lock);
2725 WARN_ON(!dm_crypt_clients_n);
2726 dm_crypt_clients_n--;
2727 crypt_calculate_pages_per_client();
2728 spin_unlock(&dm_crypt_clients_lock);
2731 static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
2733 struct crypt_config *cc = ti->private;
2735 if (crypt_integrity_aead(cc))
2736 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2738 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2741 /* at least a 64 bit sector number should fit in our buffer */
2742 cc->iv_size = max(cc->iv_size,
2743 (unsigned int)(sizeof(u64) / sizeof(u8)));
2745 DMWARN("Selected cipher does not support IVs");
2749 /* Choose ivmode, see comments at iv code. */
2751 cc->iv_gen_ops = NULL;
2752 else if (strcmp(ivmode, "plain") == 0)
2753 cc->iv_gen_ops = &crypt_iv_plain_ops;
2754 else if (strcmp(ivmode, "plain64") == 0)
2755 cc->iv_gen_ops = &crypt_iv_plain64_ops;
2756 else if (strcmp(ivmode, "plain64be") == 0)
2757 cc->iv_gen_ops = &crypt_iv_plain64be_ops;
2758 else if (strcmp(ivmode, "essiv") == 0)
2759 cc->iv_gen_ops = &crypt_iv_essiv_ops;
2760 else if (strcmp(ivmode, "benbi") == 0)
2761 cc->iv_gen_ops = &crypt_iv_benbi_ops;
2762 else if (strcmp(ivmode, "null") == 0)
2763 cc->iv_gen_ops = &crypt_iv_null_ops;
2764 else if (strcmp(ivmode, "eboiv") == 0)
2765 cc->iv_gen_ops = &crypt_iv_eboiv_ops;
2766 else if (strcmp(ivmode, "elephant") == 0) {
2767 cc->iv_gen_ops = &crypt_iv_elephant_ops;
2769 cc->key_extra_size = cc->key_size / 2;
2770 if (cc->key_extra_size > ELEPHANT_MAX_KEY_SIZE)
2772 set_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags);
2773 } else if (strcmp(ivmode, "lmk") == 0) {
2774 cc->iv_gen_ops = &crypt_iv_lmk_ops;
2776 * Version 2 and 3 is recognised according
2777 * to length of provided multi-key string.
2778 * If present (version 3), last key is used as IV seed.
2779 * All keys (including IV seed) are always the same size.
2781 if (cc->key_size % cc->key_parts) {
2783 cc->key_extra_size = cc->key_size / cc->key_parts;
2785 } else if (strcmp(ivmode, "tcw") == 0) {
2786 cc->iv_gen_ops = &crypt_iv_tcw_ops;
2787 cc->key_parts += 2; /* IV + whitening */
2788 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2789 } else if (strcmp(ivmode, "random") == 0) {
2790 cc->iv_gen_ops = &crypt_iv_random_ops;
2791 /* Need storage space in integrity fields. */
2792 cc->integrity_iv_size = cc->iv_size;
2794 ti->error = "Invalid IV mode";
2802 * Workaround to parse HMAC algorithm from AEAD crypto API spec.
2803 * The HMAC is needed to calculate tag size (HMAC digest size).
2804 * This should be probably done by crypto-api calls (once available...)
2806 static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
2808 char *start, *end, *mac_alg = NULL;
2809 struct crypto_ahash *mac;
2811 if (!strstarts(cipher_api, "authenc("))
2814 start = strchr(cipher_api, '(');
2815 end = strchr(cipher_api, ',');
2816 if (!start || !end || ++start > end)
2819 mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
2822 strncpy(mac_alg, start, end - start);
2824 mac = crypto_alloc_ahash(mac_alg, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
2828 return PTR_ERR(mac);
2830 cc->key_mac_size = crypto_ahash_digestsize(mac);
2831 crypto_free_ahash(mac);
2833 cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
2834 if (!cc->authenc_key)
2840 static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
2841 char **ivmode, char **ivopts)
2843 struct crypt_config *cc = ti->private;
2844 char *tmp, *cipher_api, buf[CRYPTO_MAX_ALG_NAME];
2850 * New format (capi: prefix)
2851 * capi:cipher_api_spec-iv:ivopts
2853 tmp = &cipher_in[strlen("capi:")];
2855 /* Separate IV options if present, it can contain another '-' in hash name */
2856 *ivopts = strrchr(tmp, ':');
2862 *ivmode = strrchr(tmp, '-');
2867 /* The rest is crypto API spec */
2870 /* Alloc AEAD, can be used only in new format. */
2871 if (crypt_integrity_aead(cc)) {
2872 ret = crypt_ctr_auth_cipher(cc, cipher_api);
2874 ti->error = "Invalid AEAD cipher spec";
2879 if (*ivmode && !strcmp(*ivmode, "lmk"))
2880 cc->tfms_count = 64;
2882 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2884 ti->error = "Digest algorithm missing for ESSIV mode";
2887 ret = snprintf(buf, CRYPTO_MAX_ALG_NAME, "essiv(%s,%s)",
2888 cipher_api, *ivopts);
2889 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2890 ti->error = "Cannot allocate cipher string";
2896 cc->key_parts = cc->tfms_count;
2898 /* Allocate cipher */
2899 ret = crypt_alloc_tfms(cc, cipher_api);
2901 ti->error = "Error allocating crypto tfm";
2905 if (crypt_integrity_aead(cc))
2906 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2908 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2913 static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
2914 char **ivmode, char **ivopts)
2916 struct crypt_config *cc = ti->private;
2917 char *tmp, *cipher, *chainmode, *keycount;
2918 char *cipher_api = NULL;
2922 if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
2923 ti->error = "Bad cipher specification";
2928 * Legacy dm-crypt cipher specification
2929 * cipher[:keycount]-mode-iv:ivopts
2932 keycount = strsep(&tmp, "-");
2933 cipher = strsep(&keycount, ":");
2937 else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
2938 !is_power_of_2(cc->tfms_count)) {
2939 ti->error = "Bad cipher key count specification";
2942 cc->key_parts = cc->tfms_count;
2944 chainmode = strsep(&tmp, "-");
2945 *ivmode = strsep(&tmp, ":");
2949 * For compatibility with the original dm-crypt mapping format, if
2950 * only the cipher name is supplied, use cbc-plain.
2952 if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
2957 if (strcmp(chainmode, "ecb") && !*ivmode) {
2958 ti->error = "IV mechanism required";
2962 cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
2966 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2968 ti->error = "Digest algorithm missing for ESSIV mode";
2972 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2973 "essiv(%s(%s),%s)", chainmode, cipher, *ivopts);
2975 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2976 "%s(%s)", chainmode, cipher);
2978 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2983 /* Allocate cipher */
2984 ret = crypt_alloc_tfms(cc, cipher_api);
2986 ti->error = "Error allocating crypto tfm";
2994 ti->error = "Cannot allocate cipher strings";
2998 static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
3000 struct crypt_config *cc = ti->private;
3001 char *ivmode = NULL, *ivopts = NULL;
3004 cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
3005 if (!cc->cipher_string) {
3006 ti->error = "Cannot allocate cipher strings";
3010 if (strstarts(cipher_in, "capi:"))
3011 ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
3013 ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
3018 ret = crypt_ctr_ivmode(ti, ivmode);
3022 /* Initialize and set key */
3023 ret = crypt_set_key(cc, key);
3025 ti->error = "Error decoding and setting key";
3030 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
3031 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
3033 ti->error = "Error creating IV";
3038 /* Initialize IV (set keys for ESSIV etc) */
3039 if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
3040 ret = cc->iv_gen_ops->init(cc);
3042 ti->error = "Error initialising IV";
3047 /* wipe the kernel key payload copy */
3049 memset(cc->key, 0, cc->key_size * sizeof(u8));
3054 static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
3056 struct crypt_config *cc = ti->private;
3057 struct dm_arg_set as;
3058 static const struct dm_arg _args[] = {
3059 {0, 8, "Invalid number of feature args"},
3061 unsigned int opt_params, val;
3062 const char *opt_string, *sval;
3066 /* Optional parameters */
3070 ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
3074 while (opt_params--) {
3075 opt_string = dm_shift_arg(&as);
3077 ti->error = "Not enough feature arguments";
3081 if (!strcasecmp(opt_string, "allow_discards"))
3082 ti->num_discard_bios = 1;
3084 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
3085 set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3087 else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
3088 set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3089 else if (!strcasecmp(opt_string, "no_read_workqueue"))
3090 set_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3091 else if (!strcasecmp(opt_string, "no_write_workqueue"))
3092 set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3093 else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
3094 if (val == 0 || val > MAX_TAG_SIZE) {
3095 ti->error = "Invalid integrity arguments";
3098 cc->on_disk_tag_size = val;
3099 sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
3100 if (!strcasecmp(sval, "aead")) {
3101 set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
3102 } else if (strcasecmp(sval, "none")) {
3103 ti->error = "Unknown integrity profile";
3107 cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
3108 if (!cc->cipher_auth)
3110 } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
3111 if (cc->sector_size < (1 << SECTOR_SHIFT) ||
3112 cc->sector_size > 4096 ||
3113 (cc->sector_size & (cc->sector_size - 1))) {
3114 ti->error = "Invalid feature value for sector_size";
3117 if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
3118 ti->error = "Device size is not multiple of sector_size feature";
3121 cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
3122 } else if (!strcasecmp(opt_string, "iv_large_sectors"))
3123 set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3125 ti->error = "Invalid feature arguments";
3133 #ifdef CONFIG_BLK_DEV_ZONED
3135 static int crypt_report_zones(struct dm_target *ti,
3136 struct dm_report_zones_args *args, unsigned int nr_zones)
3138 struct crypt_config *cc = ti->private;
3139 sector_t sector = cc->start + dm_target_offset(ti, args->next_sector);
3141 args->start = cc->start;
3142 return blkdev_report_zones(cc->dev->bdev, sector, nr_zones,
3143 dm_report_zones_cb, args);
3149 * Construct an encryption mapping:
3150 * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
3152 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
3154 struct crypt_config *cc;
3155 const char *devname = dm_table_device_name(ti->table);
3157 unsigned int align_mask;
3158 unsigned long long tmpll;
3160 size_t iv_size_padding, additional_req_size;
3164 ti->error = "Not enough arguments";
3168 key_size = get_key_size(&argv[1]);
3170 ti->error = "Cannot parse key size";
3174 cc = kzalloc(struct_size(cc, key, key_size), GFP_KERNEL);
3176 ti->error = "Cannot allocate encryption context";
3179 cc->key_size = key_size;
3180 cc->sector_size = (1 << SECTOR_SHIFT);
3181 cc->sector_shift = 0;
3185 spin_lock(&dm_crypt_clients_lock);
3186 dm_crypt_clients_n++;
3187 crypt_calculate_pages_per_client();
3188 spin_unlock(&dm_crypt_clients_lock);
3190 ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
3194 /* Optional parameters need to be read before cipher constructor */
3196 ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
3201 ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
3205 if (crypt_integrity_aead(cc)) {
3206 cc->dmreq_start = sizeof(struct aead_request);
3207 cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
3208 align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
3210 cc->dmreq_start = sizeof(struct skcipher_request);
3211 cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
3212 align_mask = crypto_skcipher_alignmask(any_tfm(cc));
3214 cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
3216 if (align_mask < CRYPTO_MINALIGN) {
3217 /* Allocate the padding exactly */
3218 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
3222 * If the cipher requires greater alignment than kmalloc
3223 * alignment, we don't know the exact position of the
3224 * initialization vector. We must assume worst case.
3226 iv_size_padding = align_mask;
3229 /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
3230 additional_req_size = sizeof(struct dm_crypt_request) +
3231 iv_size_padding + cc->iv_size +
3234 sizeof(unsigned int);
3236 ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
3238 ti->error = "Cannot allocate crypt request mempool";
3242 cc->per_bio_data_size = ti->per_io_data_size =
3243 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
3244 ARCH_KMALLOC_MINALIGN);
3246 ret = mempool_init(&cc->page_pool, BIO_MAX_PAGES, crypt_page_alloc, crypt_page_free, cc);
3248 ti->error = "Cannot allocate page mempool";
3252 ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
3254 ti->error = "Cannot allocate crypt bioset";
3258 mutex_init(&cc->bio_alloc_lock);
3261 if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
3262 (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
3263 ti->error = "Invalid iv_offset sector";
3266 cc->iv_offset = tmpll;
3268 ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
3270 ti->error = "Device lookup failed";
3275 if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
3276 ti->error = "Invalid device sector";
3282 * For zoned block devices, we need to preserve the issuer write
3283 * ordering. To do so, disable write workqueues and force inline
3284 * encryption completion.
3286 if (bdev_is_zoned(cc->dev->bdev)) {
3287 set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3288 set_bit(DM_CRYPT_WRITE_INLINE, &cc->flags);
3291 if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
3292 ret = crypt_integrity_ctr(cc, ti);
3296 cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
3297 if (!cc->tag_pool_max_sectors)
3298 cc->tag_pool_max_sectors = 1;
3300 ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
3301 cc->tag_pool_max_sectors * cc->on_disk_tag_size);
3303 ti->error = "Cannot allocate integrity tags mempool";
3307 cc->tag_pool_max_sectors <<= cc->sector_shift;
3311 cc->io_queue = alloc_workqueue("kcryptd_io/%s", WQ_MEM_RECLAIM, 1, devname);
3312 if (!cc->io_queue) {
3313 ti->error = "Couldn't create kcryptd io queue";
3317 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3318 cc->crypt_queue = alloc_workqueue("kcryptd/%s", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM,
3321 cc->crypt_queue = alloc_workqueue("kcryptd/%s",
3322 WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
3323 num_online_cpus(), devname);
3324 if (!cc->crypt_queue) {
3325 ti->error = "Couldn't create kcryptd queue";
3329 spin_lock_init(&cc->write_thread_lock);
3330 cc->write_tree = RB_ROOT;
3332 cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
3333 if (IS_ERR(cc->write_thread)) {
3334 ret = PTR_ERR(cc->write_thread);
3335 cc->write_thread = NULL;
3336 ti->error = "Couldn't spawn write thread";
3339 wake_up_process(cc->write_thread);
3341 ti->num_flush_bios = 1;
3342 ti->limit_swap_bios = true;
3351 static int crypt_map(struct dm_target *ti, struct bio *bio)
3353 struct dm_crypt_io *io;
3354 struct crypt_config *cc = ti->private;
3357 * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
3358 * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
3359 * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
3361 if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
3362 bio_op(bio) == REQ_OP_DISCARD)) {
3363 bio_set_dev(bio, cc->dev->bdev);
3364 if (bio_sectors(bio))
3365 bio->bi_iter.bi_sector = cc->start +
3366 dm_target_offset(ti, bio->bi_iter.bi_sector);
3367 return DM_MAPIO_REMAPPED;
3371 * Check if bio is too large, split as needed.
3373 if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_PAGES << PAGE_SHIFT)) &&
3374 (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
3375 dm_accept_partial_bio(bio, ((BIO_MAX_PAGES << PAGE_SHIFT) >> SECTOR_SHIFT));
3378 * Ensure that bio is a multiple of internal sector encryption size
3379 * and is aligned to this size as defined in IO hints.
3381 if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
3382 return DM_MAPIO_KILL;
3384 if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
3385 return DM_MAPIO_KILL;
3387 io = dm_per_bio_data(bio, cc->per_bio_data_size);
3388 crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
3390 if (cc->on_disk_tag_size) {
3391 unsigned tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
3393 if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
3394 unlikely(!(io->integrity_metadata = kmalloc(tag_len,
3395 GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
3396 if (bio_sectors(bio) > cc->tag_pool_max_sectors)
3397 dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
3398 io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
3399 io->integrity_metadata_from_pool = true;
3403 if (crypt_integrity_aead(cc))
3404 io->ctx.r.req_aead = (struct aead_request *)(io + 1);
3406 io->ctx.r.req = (struct skcipher_request *)(io + 1);
3408 if (bio_data_dir(io->base_bio) == READ) {
3409 if (kcryptd_io_read(io, GFP_NOWAIT))
3410 kcryptd_queue_read(io);
3412 kcryptd_queue_crypt(io);
3414 return DM_MAPIO_SUBMITTED;
3417 static char hex2asc(unsigned char c)
3419 return c + '0' + ((unsigned)(9 - c) >> 4 & 0x27);
3422 static void crypt_status(struct dm_target *ti, status_type_t type,
3423 unsigned status_flags, char *result, unsigned maxlen)
3425 struct crypt_config *cc = ti->private;
3427 int num_feature_args = 0;
3430 case STATUSTYPE_INFO:
3434 case STATUSTYPE_TABLE:
3435 DMEMIT("%s ", cc->cipher_string);
3437 if (cc->key_size > 0) {
3439 DMEMIT(":%u:%s", cc->key_size, cc->key_string);
3441 for (i = 0; i < cc->key_size; i++) {
3442 DMEMIT("%c%c", hex2asc(cc->key[i] >> 4),
3443 hex2asc(cc->key[i] & 0xf));
3449 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
3450 cc->dev->name, (unsigned long long)cc->start);
3452 num_feature_args += !!ti->num_discard_bios;
3453 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3454 num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3455 num_feature_args += test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3456 num_feature_args += test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3457 num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
3458 num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3459 if (cc->on_disk_tag_size)
3461 if (num_feature_args) {
3462 DMEMIT(" %d", num_feature_args);
3463 if (ti->num_discard_bios)
3464 DMEMIT(" allow_discards");
3465 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3466 DMEMIT(" same_cpu_crypt");
3467 if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
3468 DMEMIT(" submit_from_crypt_cpus");
3469 if (test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags))
3470 DMEMIT(" no_read_workqueue");
3471 if (test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))
3472 DMEMIT(" no_write_workqueue");
3473 if (cc->on_disk_tag_size)
3474 DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
3475 if (cc->sector_size != (1 << SECTOR_SHIFT))
3476 DMEMIT(" sector_size:%d", cc->sector_size);
3477 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
3478 DMEMIT(" iv_large_sectors");
3485 static void crypt_postsuspend(struct dm_target *ti)
3487 struct crypt_config *cc = ti->private;
3489 set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3492 static int crypt_preresume(struct dm_target *ti)
3494 struct crypt_config *cc = ti->private;
3496 if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
3497 DMERR("aborting resume - crypt key is not set.");
3504 static void crypt_resume(struct dm_target *ti)
3506 struct crypt_config *cc = ti->private;
3508 clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3511 /* Message interface
3515 static int crypt_message(struct dm_target *ti, unsigned argc, char **argv,
3516 char *result, unsigned maxlen)
3518 struct crypt_config *cc = ti->private;
3519 int key_size, ret = -EINVAL;
3524 if (!strcasecmp(argv[0], "key")) {
3525 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
3526 DMWARN("not suspended during key manipulation.");
3529 if (argc == 3 && !strcasecmp(argv[1], "set")) {
3530 /* The key size may not be changed. */
3531 key_size = get_key_size(&argv[2]);
3532 if (key_size < 0 || cc->key_size != key_size) {
3533 memset(argv[2], '0', strlen(argv[2]));
3537 ret = crypt_set_key(cc, argv[2]);
3540 if (cc->iv_gen_ops && cc->iv_gen_ops->init)
3541 ret = cc->iv_gen_ops->init(cc);
3542 /* wipe the kernel key payload copy */
3544 memset(cc->key, 0, cc->key_size * sizeof(u8));
3547 if (argc == 2 && !strcasecmp(argv[1], "wipe"))
3548 return crypt_wipe_key(cc);
3552 DMWARN("unrecognised message received.");
3556 static int crypt_iterate_devices(struct dm_target *ti,
3557 iterate_devices_callout_fn fn, void *data)
3559 struct crypt_config *cc = ti->private;
3561 return fn(ti, cc->dev, cc->start, ti->len, data);
3564 static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
3566 struct crypt_config *cc = ti->private;
3569 * Unfortunate constraint that is required to avoid the potential
3570 * for exceeding underlying device's max_segments limits -- due to
3571 * crypt_alloc_buffer() possibly allocating pages for the encryption
3572 * bio that are not as physically contiguous as the original bio.
3574 limits->max_segment_size = PAGE_SIZE;
3576 limits->logical_block_size =
3577 max_t(unsigned, limits->logical_block_size, cc->sector_size);
3578 limits->physical_block_size =
3579 max_t(unsigned, limits->physical_block_size, cc->sector_size);
3580 limits->io_min = max_t(unsigned, limits->io_min, cc->sector_size);
3583 static struct target_type crypt_target = {
3585 .version = {1, 22, 0},
3586 .module = THIS_MODULE,
3589 #ifdef CONFIG_BLK_DEV_ZONED
3590 .features = DM_TARGET_ZONED_HM,
3591 .report_zones = crypt_report_zones,
3594 .status = crypt_status,
3595 .postsuspend = crypt_postsuspend,
3596 .preresume = crypt_preresume,
3597 .resume = crypt_resume,
3598 .message = crypt_message,
3599 .iterate_devices = crypt_iterate_devices,
3600 .io_hints = crypt_io_hints,
3603 static int __init dm_crypt_init(void)
3607 r = dm_register_target(&crypt_target);
3609 DMERR("register failed %d", r);
3614 static void __exit dm_crypt_exit(void)
3616 dm_unregister_target(&crypt_target);
3619 module_init(dm_crypt_init);
3620 module_exit(dm_crypt_exit);
3622 MODULE_AUTHOR("Jana Saout <jana@saout.de>");
3623 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
3624 MODULE_LICENSE("GPL");