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;
52 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;
71 struct work_struct work;
72 struct tasklet_struct tasklet;
74 struct convert_context ctx;
80 struct rb_node rb_node;
81 } CRYPTO_MINALIGN_ATTR;
83 struct dm_crypt_request {
84 struct convert_context *ctx;
85 struct scatterlist sg_in[4];
86 struct scatterlist sg_out[4];
92 struct crypt_iv_operations {
93 int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
95 void (*dtr)(struct crypt_config *cc);
96 int (*init)(struct crypt_config *cc);
97 int (*wipe)(struct crypt_config *cc);
98 int (*generator)(struct crypt_config *cc, u8 *iv,
99 struct dm_crypt_request *dmreq);
100 int (*post)(struct crypt_config *cc, u8 *iv,
101 struct dm_crypt_request *dmreq);
104 struct iv_benbi_private {
108 #define LMK_SEED_SIZE 64 /* hash + 0 */
109 struct iv_lmk_private {
110 struct crypto_shash *hash_tfm;
114 #define TCW_WHITENING_SIZE 16
115 struct iv_tcw_private {
116 struct crypto_shash *crc32_tfm;
121 #define ELEPHANT_MAX_KEY_SIZE 32
122 struct iv_elephant_private {
123 struct crypto_skcipher *tfm;
127 * Crypt: maps a linear range of a block device
128 * and encrypts / decrypts at the same time.
130 enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
131 DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD,
132 DM_CRYPT_NO_READ_WORKQUEUE, DM_CRYPT_NO_WRITE_WORKQUEUE };
135 CRYPT_MODE_INTEGRITY_AEAD, /* Use authenticated mode for cihper */
136 CRYPT_IV_LARGE_SECTORS, /* Calculate IV from sector_size, not 512B sectors */
137 CRYPT_ENCRYPT_PREPROCESS, /* Must preprocess data for encryption (elephant) */
141 * The fields in here must be read only after initialization.
143 struct crypt_config {
147 struct percpu_counter n_allocated_pages;
149 struct workqueue_struct *io_queue;
150 struct workqueue_struct *crypt_queue;
152 spinlock_t write_thread_lock;
153 struct task_struct *write_thread;
154 struct rb_root write_tree;
160 const struct crypt_iv_operations *iv_gen_ops;
162 struct iv_benbi_private benbi;
163 struct iv_lmk_private lmk;
164 struct iv_tcw_private tcw;
165 struct iv_elephant_private elephant;
168 unsigned int iv_size;
169 unsigned short int sector_size;
170 unsigned char sector_shift;
173 struct crypto_skcipher **tfms;
174 struct crypto_aead **tfms_aead;
177 unsigned long cipher_flags;
180 * Layout of each crypto request:
182 * struct skcipher_request
185 * struct dm_crypt_request
189 * The padding is added so that dm_crypt_request and the IV are
192 unsigned int dmreq_start;
194 unsigned int per_bio_data_size;
197 unsigned int key_size;
198 unsigned int key_parts; /* independent parts in key buffer */
199 unsigned int key_extra_size; /* additional keys length */
200 unsigned int key_mac_size; /* MAC key size for authenc(...) */
202 unsigned int integrity_tag_size;
203 unsigned int integrity_iv_size;
204 unsigned int on_disk_tag_size;
207 * pool for per bio private data, crypto requests,
208 * encryption requeusts/buffer pages and integrity tags
210 unsigned tag_pool_max_sectors;
216 struct mutex bio_alloc_lock;
218 u8 *authenc_key; /* space for keys in authenc() format (if used) */
223 #define MAX_TAG_SIZE 480
224 #define POOL_ENTRY_SIZE 512
226 static DEFINE_SPINLOCK(dm_crypt_clients_lock);
227 static unsigned dm_crypt_clients_n = 0;
228 static volatile unsigned long dm_crypt_pages_per_client;
229 #define DM_CRYPT_MEMORY_PERCENT 2
230 #define DM_CRYPT_MIN_PAGES_PER_CLIENT (BIO_MAX_PAGES * 16)
232 static void clone_init(struct dm_crypt_io *, struct bio *);
233 static void kcryptd_queue_crypt(struct dm_crypt_io *io);
234 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
235 struct scatterlist *sg);
237 static bool crypt_integrity_aead(struct crypt_config *cc);
240 * Use this to access cipher attributes that are independent of the key.
242 static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
244 return cc->cipher_tfm.tfms[0];
247 static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
249 return cc->cipher_tfm.tfms_aead[0];
253 * Different IV generation algorithms:
255 * plain: the initial vector is the 32-bit little-endian version of the sector
256 * number, padded with zeros if necessary.
258 * plain64: the initial vector is the 64-bit little-endian version of the sector
259 * number, padded with zeros if necessary.
261 * plain64be: the initial vector is the 64-bit big-endian version of the sector
262 * number, padded with zeros if necessary.
264 * essiv: "encrypted sector|salt initial vector", the sector number is
265 * encrypted with the bulk cipher using a salt as key. The salt
266 * should be derived from the bulk cipher's key via hashing.
268 * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
269 * (needed for LRW-32-AES and possible other narrow block modes)
271 * null: the initial vector is always zero. Provides compatibility with
272 * obsolete loop_fish2 devices. Do not use for new devices.
274 * lmk: Compatible implementation of the block chaining mode used
275 * by the Loop-AES block device encryption system
276 * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
277 * It operates on full 512 byte sectors and uses CBC
278 * with an IV derived from the sector number, the data and
279 * optionally extra IV seed.
280 * This means that after decryption the first block
281 * of sector must be tweaked according to decrypted data.
282 * Loop-AES can use three encryption schemes:
283 * version 1: is plain aes-cbc mode
284 * version 2: uses 64 multikey scheme with lmk IV generator
285 * version 3: the same as version 2 with additional IV seed
286 * (it uses 65 keys, last key is used as IV seed)
288 * tcw: Compatible implementation of the block chaining mode used
289 * by the TrueCrypt device encryption system (prior to version 4.1).
290 * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
291 * It operates on full 512 byte sectors and uses CBC
292 * with an IV derived from initial key and the sector number.
293 * In addition, whitening value is applied on every sector, whitening
294 * is calculated from initial key, sector number and mixed using CRC32.
295 * Note that this encryption scheme is vulnerable to watermarking attacks
296 * and should be used for old compatible containers access only.
298 * eboiv: Encrypted byte-offset IV (used in Bitlocker in CBC mode)
299 * The IV is encrypted little-endian byte-offset (with the same key
300 * and cipher as the volume).
302 * elephant: The extended version of eboiv with additional Elephant diffuser
303 * used with Bitlocker CBC mode.
304 * This mode was used in older Windows systems
305 * http://download.microsoft.com/download/0/2/3/0238acaf-d3bf-4a6d-b3d6-0a0be4bbb36e/bitlockercipher200608.pdf
308 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
309 struct dm_crypt_request *dmreq)
311 memset(iv, 0, cc->iv_size);
312 *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
317 static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
318 struct dm_crypt_request *dmreq)
320 memset(iv, 0, cc->iv_size);
321 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
326 static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
327 struct dm_crypt_request *dmreq)
329 memset(iv, 0, cc->iv_size);
330 /* iv_size is at least of size u64; usually it is 16 bytes */
331 *(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
336 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
337 struct dm_crypt_request *dmreq)
340 * ESSIV encryption of the IV is now handled by the crypto API,
341 * so just pass the plain sector number here.
343 memset(iv, 0, cc->iv_size);
344 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
349 static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
355 if (crypt_integrity_aead(cc))
356 bs = crypto_aead_blocksize(any_tfm_aead(cc));
358 bs = crypto_skcipher_blocksize(any_tfm(cc));
361 /* we need to calculate how far we must shift the sector count
362 * to get the cipher block count, we use this shift in _gen */
364 if (1 << log != bs) {
365 ti->error = "cypher blocksize is not a power of 2";
370 ti->error = "cypher blocksize is > 512";
374 cc->iv_gen_private.benbi.shift = 9 - log;
379 static void crypt_iv_benbi_dtr(struct crypt_config *cc)
383 static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
384 struct dm_crypt_request *dmreq)
388 memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
390 val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
391 put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
396 static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
397 struct dm_crypt_request *dmreq)
399 memset(iv, 0, cc->iv_size);
404 static void crypt_iv_lmk_dtr(struct crypt_config *cc)
406 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
408 if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
409 crypto_free_shash(lmk->hash_tfm);
410 lmk->hash_tfm = NULL;
416 static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
419 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
421 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
422 ti->error = "Unsupported sector size for LMK";
426 lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
427 if (IS_ERR(lmk->hash_tfm)) {
428 ti->error = "Error initializing LMK hash";
429 return PTR_ERR(lmk->hash_tfm);
432 /* No seed in LMK version 2 */
433 if (cc->key_parts == cc->tfms_count) {
438 lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
440 crypt_iv_lmk_dtr(cc);
441 ti->error = "Error kmallocing seed storage in LMK";
448 static int crypt_iv_lmk_init(struct crypt_config *cc)
450 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
451 int subkey_size = cc->key_size / cc->key_parts;
453 /* LMK seed is on the position of LMK_KEYS + 1 key */
455 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
456 crypto_shash_digestsize(lmk->hash_tfm));
461 static int crypt_iv_lmk_wipe(struct crypt_config *cc)
463 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
466 memset(lmk->seed, 0, LMK_SEED_SIZE);
471 static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
472 struct dm_crypt_request *dmreq,
475 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
476 SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
477 struct md5_state md5state;
481 desc->tfm = lmk->hash_tfm;
483 r = crypto_shash_init(desc);
488 r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
493 /* Sector is always 512B, block size 16, add data of blocks 1-31 */
494 r = crypto_shash_update(desc, data + 16, 16 * 31);
498 /* Sector is cropped to 56 bits here */
499 buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
500 buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
501 buf[2] = cpu_to_le32(4024);
503 r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
507 /* No MD5 padding here */
508 r = crypto_shash_export(desc, &md5state);
512 for (i = 0; i < MD5_HASH_WORDS; i++)
513 __cpu_to_le32s(&md5state.hash[i]);
514 memcpy(iv, &md5state.hash, cc->iv_size);
519 static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
520 struct dm_crypt_request *dmreq)
522 struct scatterlist *sg;
526 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
527 sg = crypt_get_sg_data(cc, dmreq->sg_in);
528 src = kmap_atomic(sg_page(sg));
529 r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
532 memset(iv, 0, cc->iv_size);
537 static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
538 struct dm_crypt_request *dmreq)
540 struct scatterlist *sg;
544 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
547 sg = crypt_get_sg_data(cc, dmreq->sg_out);
548 dst = kmap_atomic(sg_page(sg));
549 r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
551 /* Tweak the first block of plaintext sector */
553 crypto_xor(dst + sg->offset, iv, cc->iv_size);
559 static void crypt_iv_tcw_dtr(struct crypt_config *cc)
561 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
563 kzfree(tcw->iv_seed);
565 kzfree(tcw->whitening);
566 tcw->whitening = NULL;
568 if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
569 crypto_free_shash(tcw->crc32_tfm);
570 tcw->crc32_tfm = NULL;
573 static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
576 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
578 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
579 ti->error = "Unsupported sector size for TCW";
583 if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
584 ti->error = "Wrong key size for TCW";
588 tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
589 if (IS_ERR(tcw->crc32_tfm)) {
590 ti->error = "Error initializing CRC32 in TCW";
591 return PTR_ERR(tcw->crc32_tfm);
594 tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
595 tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
596 if (!tcw->iv_seed || !tcw->whitening) {
597 crypt_iv_tcw_dtr(cc);
598 ti->error = "Error allocating seed storage in TCW";
605 static int crypt_iv_tcw_init(struct crypt_config *cc)
607 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
608 int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
610 memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
611 memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
617 static int crypt_iv_tcw_wipe(struct crypt_config *cc)
619 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
621 memset(tcw->iv_seed, 0, cc->iv_size);
622 memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
627 static int crypt_iv_tcw_whitening(struct crypt_config *cc,
628 struct dm_crypt_request *dmreq,
631 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
632 __le64 sector = cpu_to_le64(dmreq->iv_sector);
633 u8 buf[TCW_WHITENING_SIZE];
634 SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
637 /* xor whitening with sector number */
638 crypto_xor_cpy(buf, tcw->whitening, (u8 *)§or, 8);
639 crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)§or, 8);
641 /* calculate crc32 for every 32bit part and xor it */
642 desc->tfm = tcw->crc32_tfm;
643 for (i = 0; i < 4; i++) {
644 r = crypto_shash_init(desc);
647 r = crypto_shash_update(desc, &buf[i * 4], 4);
650 r = crypto_shash_final(desc, &buf[i * 4]);
654 crypto_xor(&buf[0], &buf[12], 4);
655 crypto_xor(&buf[4], &buf[8], 4);
657 /* apply whitening (8 bytes) to whole sector */
658 for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
659 crypto_xor(data + i * 8, buf, 8);
661 memzero_explicit(buf, sizeof(buf));
665 static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
666 struct dm_crypt_request *dmreq)
668 struct scatterlist *sg;
669 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
670 __le64 sector = cpu_to_le64(dmreq->iv_sector);
674 /* Remove whitening from ciphertext */
675 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
676 sg = crypt_get_sg_data(cc, dmreq->sg_in);
677 src = kmap_atomic(sg_page(sg));
678 r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
683 crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)§or, 8);
685 crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)§or,
691 static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
692 struct dm_crypt_request *dmreq)
694 struct scatterlist *sg;
698 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
701 /* Apply whitening on ciphertext */
702 sg = crypt_get_sg_data(cc, dmreq->sg_out);
703 dst = kmap_atomic(sg_page(sg));
704 r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
710 static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
711 struct dm_crypt_request *dmreq)
713 /* Used only for writes, there must be an additional space to store IV */
714 get_random_bytes(iv, cc->iv_size);
718 static int crypt_iv_eboiv_ctr(struct crypt_config *cc, struct dm_target *ti,
721 if (crypt_integrity_aead(cc)) {
722 ti->error = "AEAD transforms not supported for EBOIV";
726 if (crypto_skcipher_blocksize(any_tfm(cc)) != cc->iv_size) {
727 ti->error = "Block size of EBOIV cipher does "
728 "not match IV size of block cipher";
735 static int crypt_iv_eboiv_gen(struct crypt_config *cc, u8 *iv,
736 struct dm_crypt_request *dmreq)
738 u8 buf[MAX_CIPHER_BLOCKSIZE] __aligned(__alignof__(__le64));
739 struct skcipher_request *req;
740 struct scatterlist src, dst;
741 struct crypto_wait wait;
744 req = skcipher_request_alloc(any_tfm(cc), GFP_NOIO);
748 memset(buf, 0, cc->iv_size);
749 *(__le64 *)buf = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
751 sg_init_one(&src, page_address(ZERO_PAGE(0)), cc->iv_size);
752 sg_init_one(&dst, iv, cc->iv_size);
753 skcipher_request_set_crypt(req, &src, &dst, cc->iv_size, buf);
754 skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
755 err = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
756 skcipher_request_free(req);
761 static void crypt_iv_elephant_dtr(struct crypt_config *cc)
763 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
765 crypto_free_skcipher(elephant->tfm);
766 elephant->tfm = NULL;
769 static int crypt_iv_elephant_ctr(struct crypt_config *cc, struct dm_target *ti,
772 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
775 elephant->tfm = crypto_alloc_skcipher("ecb(aes)", 0, 0);
776 if (IS_ERR(elephant->tfm)) {
777 r = PTR_ERR(elephant->tfm);
778 elephant->tfm = NULL;
782 r = crypt_iv_eboiv_ctr(cc, ti, NULL);
784 crypt_iv_elephant_dtr(cc);
788 static void diffuser_disk_to_cpu(u32 *d, size_t n)
790 #ifndef __LITTLE_ENDIAN
793 for (i = 0; i < n; i++)
794 d[i] = le32_to_cpu((__le32)d[i]);
798 static void diffuser_cpu_to_disk(__le32 *d, size_t n)
800 #ifndef __LITTLE_ENDIAN
803 for (i = 0; i < n; i++)
804 d[i] = cpu_to_le32((u32)d[i]);
808 static void diffuser_a_decrypt(u32 *d, size_t n)
812 for (i = 0; i < 5; i++) {
817 while (i1 < (n - 1)) {
818 d[i1] += d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
824 d[i1] += d[i2] ^ d[i3];
830 d[i1] += d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
833 d[i1] += d[i2] ^ d[i3];
839 static void diffuser_a_encrypt(u32 *d, size_t n)
843 for (i = 0; i < 5; i++) {
849 d[i1] -= d[i2] ^ d[i3];
852 d[i1] -= d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
858 d[i1] -= d[i2] ^ d[i3];
864 d[i1] -= d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
870 static void diffuser_b_decrypt(u32 *d, size_t n)
874 for (i = 0; i < 3; i++) {
879 while (i1 < (n - 1)) {
880 d[i1] += d[i2] ^ d[i3];
883 d[i1] += d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
889 d[i1] += d[i2] ^ d[i3];
895 d[i1] += d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
901 static void diffuser_b_encrypt(u32 *d, size_t n)
905 for (i = 0; i < 3; i++) {
911 d[i1] -= d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
917 d[i1] -= d[i2] ^ d[i3];
923 d[i1] -= d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
926 d[i1] -= d[i2] ^ d[i3];
932 static int crypt_iv_elephant(struct crypt_config *cc, struct dm_crypt_request *dmreq)
934 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
935 u8 *es, *ks, *data, *data2, *data_offset;
936 struct skcipher_request *req;
937 struct scatterlist *sg, *sg2, src, dst;
938 struct crypto_wait wait;
941 req = skcipher_request_alloc(elephant->tfm, GFP_NOIO);
942 es = kzalloc(16, GFP_NOIO); /* Key for AES */
943 ks = kzalloc(32, GFP_NOIO); /* Elephant sector key */
945 if (!req || !es || !ks) {
950 *(__le64 *)es = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
953 sg_init_one(&src, es, 16);
954 sg_init_one(&dst, ks, 16);
955 skcipher_request_set_crypt(req, &src, &dst, 16, NULL);
956 skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
957 r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
963 sg_init_one(&dst, &ks[16], 16);
964 r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
968 sg = crypt_get_sg_data(cc, dmreq->sg_out);
969 data = kmap_atomic(sg_page(sg));
970 data_offset = data + sg->offset;
972 /* Cannot modify original bio, copy to sg_out and apply Elephant to it */
973 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
974 sg2 = crypt_get_sg_data(cc, dmreq->sg_in);
975 data2 = kmap_atomic(sg_page(sg2));
976 memcpy(data_offset, data2 + sg2->offset, cc->sector_size);
977 kunmap_atomic(data2);
980 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
981 diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
982 diffuser_b_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
983 diffuser_a_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
984 diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
987 for (i = 0; i < (cc->sector_size / 32); i++)
988 crypto_xor(data_offset + i * 32, ks, 32);
990 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
991 diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
992 diffuser_a_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
993 diffuser_b_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
994 diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
1001 skcipher_request_free(req);
1005 static int crypt_iv_elephant_gen(struct crypt_config *cc, u8 *iv,
1006 struct dm_crypt_request *dmreq)
1010 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
1011 r = crypt_iv_elephant(cc, dmreq);
1016 return crypt_iv_eboiv_gen(cc, iv, dmreq);
1019 static int crypt_iv_elephant_post(struct crypt_config *cc, u8 *iv,
1020 struct dm_crypt_request *dmreq)
1022 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
1023 return crypt_iv_elephant(cc, dmreq);
1028 static int crypt_iv_elephant_init(struct crypt_config *cc)
1030 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1031 int key_offset = cc->key_size - cc->key_extra_size;
1033 return crypto_skcipher_setkey(elephant->tfm, &cc->key[key_offset], cc->key_extra_size);
1036 static int crypt_iv_elephant_wipe(struct crypt_config *cc)
1038 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1039 u8 key[ELEPHANT_MAX_KEY_SIZE];
1041 memset(key, 0, cc->key_extra_size);
1042 return crypto_skcipher_setkey(elephant->tfm, key, cc->key_extra_size);
1045 static const struct crypt_iv_operations crypt_iv_plain_ops = {
1046 .generator = crypt_iv_plain_gen
1049 static const struct crypt_iv_operations crypt_iv_plain64_ops = {
1050 .generator = crypt_iv_plain64_gen
1053 static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
1054 .generator = crypt_iv_plain64be_gen
1057 static const struct crypt_iv_operations crypt_iv_essiv_ops = {
1058 .generator = crypt_iv_essiv_gen
1061 static const struct crypt_iv_operations crypt_iv_benbi_ops = {
1062 .ctr = crypt_iv_benbi_ctr,
1063 .dtr = crypt_iv_benbi_dtr,
1064 .generator = crypt_iv_benbi_gen
1067 static const struct crypt_iv_operations crypt_iv_null_ops = {
1068 .generator = crypt_iv_null_gen
1071 static const struct crypt_iv_operations crypt_iv_lmk_ops = {
1072 .ctr = crypt_iv_lmk_ctr,
1073 .dtr = crypt_iv_lmk_dtr,
1074 .init = crypt_iv_lmk_init,
1075 .wipe = crypt_iv_lmk_wipe,
1076 .generator = crypt_iv_lmk_gen,
1077 .post = crypt_iv_lmk_post
1080 static const struct crypt_iv_operations crypt_iv_tcw_ops = {
1081 .ctr = crypt_iv_tcw_ctr,
1082 .dtr = crypt_iv_tcw_dtr,
1083 .init = crypt_iv_tcw_init,
1084 .wipe = crypt_iv_tcw_wipe,
1085 .generator = crypt_iv_tcw_gen,
1086 .post = crypt_iv_tcw_post
1089 static struct crypt_iv_operations crypt_iv_random_ops = {
1090 .generator = crypt_iv_random_gen
1093 static struct crypt_iv_operations crypt_iv_eboiv_ops = {
1094 .ctr = crypt_iv_eboiv_ctr,
1095 .generator = crypt_iv_eboiv_gen
1098 static struct crypt_iv_operations crypt_iv_elephant_ops = {
1099 .ctr = crypt_iv_elephant_ctr,
1100 .dtr = crypt_iv_elephant_dtr,
1101 .init = crypt_iv_elephant_init,
1102 .wipe = crypt_iv_elephant_wipe,
1103 .generator = crypt_iv_elephant_gen,
1104 .post = crypt_iv_elephant_post
1108 * Integrity extensions
1110 static bool crypt_integrity_aead(struct crypt_config *cc)
1112 return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
1115 static bool crypt_integrity_hmac(struct crypt_config *cc)
1117 return crypt_integrity_aead(cc) && cc->key_mac_size;
1120 /* Get sg containing data */
1121 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
1122 struct scatterlist *sg)
1124 if (unlikely(crypt_integrity_aead(cc)))
1130 static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
1132 struct bio_integrity_payload *bip;
1133 unsigned int tag_len;
1136 if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
1139 bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
1141 return PTR_ERR(bip);
1143 tag_len = io->cc->on_disk_tag_size * (bio_sectors(bio) >> io->cc->sector_shift);
1145 bip->bip_iter.bi_size = tag_len;
1146 bip->bip_iter.bi_sector = io->cc->start + io->sector;
1148 ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
1149 tag_len, offset_in_page(io->integrity_metadata));
1150 if (unlikely(ret != tag_len))
1156 static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
1158 #ifdef CONFIG_BLK_DEV_INTEGRITY
1159 struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
1160 struct mapped_device *md = dm_table_get_md(ti->table);
1162 /* From now we require underlying device with our integrity profile */
1163 if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
1164 ti->error = "Integrity profile not supported.";
1168 if (bi->tag_size != cc->on_disk_tag_size ||
1169 bi->tuple_size != cc->on_disk_tag_size) {
1170 ti->error = "Integrity profile tag size mismatch.";
1173 if (1 << bi->interval_exp != cc->sector_size) {
1174 ti->error = "Integrity profile sector size mismatch.";
1178 if (crypt_integrity_aead(cc)) {
1179 cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
1180 DMDEBUG("%s: Integrity AEAD, tag size %u, IV size %u.", dm_device_name(md),
1181 cc->integrity_tag_size, cc->integrity_iv_size);
1183 if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
1184 ti->error = "Integrity AEAD auth tag size is not supported.";
1187 } else if (cc->integrity_iv_size)
1188 DMDEBUG("%s: Additional per-sector space %u bytes for IV.", dm_device_name(md),
1189 cc->integrity_iv_size);
1191 if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
1192 ti->error = "Not enough space for integrity tag in the profile.";
1198 ti->error = "Integrity profile not supported.";
1203 static void crypt_convert_init(struct crypt_config *cc,
1204 struct convert_context *ctx,
1205 struct bio *bio_out, struct bio *bio_in,
1208 ctx->bio_in = bio_in;
1209 ctx->bio_out = bio_out;
1211 ctx->iter_in = bio_in->bi_iter;
1213 ctx->iter_out = bio_out->bi_iter;
1214 ctx->cc_sector = sector + cc->iv_offset;
1215 init_completion(&ctx->restart);
1218 static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
1221 return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
1224 static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
1226 return (void *)((char *)dmreq - cc->dmreq_start);
1229 static u8 *iv_of_dmreq(struct crypt_config *cc,
1230 struct dm_crypt_request *dmreq)
1232 if (crypt_integrity_aead(cc))
1233 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1234 crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
1236 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1237 crypto_skcipher_alignmask(any_tfm(cc)) + 1);
1240 static u8 *org_iv_of_dmreq(struct crypt_config *cc,
1241 struct dm_crypt_request *dmreq)
1243 return iv_of_dmreq(cc, dmreq) + cc->iv_size;
1246 static __le64 *org_sector_of_dmreq(struct crypt_config *cc,
1247 struct dm_crypt_request *dmreq)
1249 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
1250 return (__le64 *) ptr;
1253 static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
1254 struct dm_crypt_request *dmreq)
1256 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
1257 cc->iv_size + sizeof(uint64_t);
1258 return (unsigned int*)ptr;
1261 static void *tag_from_dmreq(struct crypt_config *cc,
1262 struct dm_crypt_request *dmreq)
1264 struct convert_context *ctx = dmreq->ctx;
1265 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1267 return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
1268 cc->on_disk_tag_size];
1271 static void *iv_tag_from_dmreq(struct crypt_config *cc,
1272 struct dm_crypt_request *dmreq)
1274 return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
1277 static int crypt_convert_block_aead(struct crypt_config *cc,
1278 struct convert_context *ctx,
1279 struct aead_request *req,
1280 unsigned int tag_offset)
1282 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1283 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1284 struct dm_crypt_request *dmreq;
1285 u8 *iv, *org_iv, *tag_iv, *tag;
1289 BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
1291 /* Reject unexpected unaligned bio. */
1292 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1295 dmreq = dmreq_of_req(cc, req);
1296 dmreq->iv_sector = ctx->cc_sector;
1297 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1298 dmreq->iv_sector >>= cc->sector_shift;
1301 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1303 sector = org_sector_of_dmreq(cc, dmreq);
1304 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1306 iv = iv_of_dmreq(cc, dmreq);
1307 org_iv = org_iv_of_dmreq(cc, dmreq);
1308 tag = tag_from_dmreq(cc, dmreq);
1309 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1312 * |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1313 * | (authenticated) | (auth+encryption) | |
1314 * | sector_LE | IV | sector in/out | tag in/out |
1316 sg_init_table(dmreq->sg_in, 4);
1317 sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
1318 sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
1319 sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1320 sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
1322 sg_init_table(dmreq->sg_out, 4);
1323 sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
1324 sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
1325 sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1326 sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
1328 if (cc->iv_gen_ops) {
1329 /* For READs use IV stored in integrity metadata */
1330 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1331 memcpy(org_iv, tag_iv, cc->iv_size);
1333 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1336 /* Store generated IV in integrity metadata */
1337 if (cc->integrity_iv_size)
1338 memcpy(tag_iv, org_iv, cc->iv_size);
1340 /* Working copy of IV, to be modified in crypto API */
1341 memcpy(iv, org_iv, cc->iv_size);
1344 aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
1345 if (bio_data_dir(ctx->bio_in) == WRITE) {
1346 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1347 cc->sector_size, iv);
1348 r = crypto_aead_encrypt(req);
1349 if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
1350 memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
1351 cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
1353 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1354 cc->sector_size + cc->integrity_tag_size, iv);
1355 r = crypto_aead_decrypt(req);
1358 if (r == -EBADMSG) {
1359 char b[BDEVNAME_SIZE];
1360 DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx->bio_in, b),
1361 (unsigned long long)le64_to_cpu(*sector));
1364 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1365 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1367 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1368 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1373 static int crypt_convert_block_skcipher(struct crypt_config *cc,
1374 struct convert_context *ctx,
1375 struct skcipher_request *req,
1376 unsigned int tag_offset)
1378 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1379 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1380 struct scatterlist *sg_in, *sg_out;
1381 struct dm_crypt_request *dmreq;
1382 u8 *iv, *org_iv, *tag_iv;
1386 /* Reject unexpected unaligned bio. */
1387 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1390 dmreq = dmreq_of_req(cc, req);
1391 dmreq->iv_sector = ctx->cc_sector;
1392 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1393 dmreq->iv_sector >>= cc->sector_shift;
1396 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1398 iv = iv_of_dmreq(cc, dmreq);
1399 org_iv = org_iv_of_dmreq(cc, dmreq);
1400 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1402 sector = org_sector_of_dmreq(cc, dmreq);
1403 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1405 /* For skcipher we use only the first sg item */
1406 sg_in = &dmreq->sg_in[0];
1407 sg_out = &dmreq->sg_out[0];
1409 sg_init_table(sg_in, 1);
1410 sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1412 sg_init_table(sg_out, 1);
1413 sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1415 if (cc->iv_gen_ops) {
1416 /* For READs use IV stored in integrity metadata */
1417 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1418 memcpy(org_iv, tag_iv, cc->integrity_iv_size);
1420 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1423 /* Data can be already preprocessed in generator */
1424 if (test_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags))
1426 /* Store generated IV in integrity metadata */
1427 if (cc->integrity_iv_size)
1428 memcpy(tag_iv, org_iv, cc->integrity_iv_size);
1430 /* Working copy of IV, to be modified in crypto API */
1431 memcpy(iv, org_iv, cc->iv_size);
1434 skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
1436 if (bio_data_dir(ctx->bio_in) == WRITE)
1437 r = crypto_skcipher_encrypt(req);
1439 r = crypto_skcipher_decrypt(req);
1441 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1442 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1444 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1445 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1450 static void kcryptd_async_done(struct crypto_async_request *async_req,
1453 static void crypt_alloc_req_skcipher(struct crypt_config *cc,
1454 struct convert_context *ctx)
1456 unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
1459 ctx->r.req = mempool_alloc(&cc->req_pool, GFP_NOIO);
1461 skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
1464 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1465 * requests if driver request queue is full.
1467 skcipher_request_set_callback(ctx->r.req,
1468 CRYPTO_TFM_REQ_MAY_BACKLOG,
1469 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
1472 static void crypt_alloc_req_aead(struct crypt_config *cc,
1473 struct convert_context *ctx)
1475 if (!ctx->r.req_aead)
1476 ctx->r.req_aead = mempool_alloc(&cc->req_pool, GFP_NOIO);
1478 aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
1481 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1482 * requests if driver request queue is full.
1484 aead_request_set_callback(ctx->r.req_aead,
1485 CRYPTO_TFM_REQ_MAY_BACKLOG,
1486 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
1489 static void crypt_alloc_req(struct crypt_config *cc,
1490 struct convert_context *ctx)
1492 if (crypt_integrity_aead(cc))
1493 crypt_alloc_req_aead(cc, ctx);
1495 crypt_alloc_req_skcipher(cc, ctx);
1498 static void crypt_free_req_skcipher(struct crypt_config *cc,
1499 struct skcipher_request *req, struct bio *base_bio)
1501 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1503 if ((struct skcipher_request *)(io + 1) != req)
1504 mempool_free(req, &cc->req_pool);
1507 static void crypt_free_req_aead(struct crypt_config *cc,
1508 struct aead_request *req, struct bio *base_bio)
1510 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1512 if ((struct aead_request *)(io + 1) != req)
1513 mempool_free(req, &cc->req_pool);
1516 static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
1518 if (crypt_integrity_aead(cc))
1519 crypt_free_req_aead(cc, req, base_bio);
1521 crypt_free_req_skcipher(cc, req, base_bio);
1525 * Encrypt / decrypt data from one bio to another one (can be the same one)
1527 static blk_status_t crypt_convert(struct crypt_config *cc,
1528 struct convert_context *ctx, bool atomic)
1530 unsigned int tag_offset = 0;
1531 unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
1534 atomic_set(&ctx->cc_pending, 1);
1536 while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
1538 crypt_alloc_req(cc, ctx);
1539 atomic_inc(&ctx->cc_pending);
1541 if (crypt_integrity_aead(cc))
1542 r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
1544 r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
1548 * The request was queued by a crypto driver
1549 * but the driver request queue is full, let's wait.
1552 wait_for_completion(&ctx->restart);
1553 reinit_completion(&ctx->restart);
1556 * The request is queued and processed asynchronously,
1557 * completion function kcryptd_async_done() will be called.
1561 ctx->cc_sector += sector_step;
1565 * The request was already processed (synchronously).
1568 atomic_dec(&ctx->cc_pending);
1569 ctx->cc_sector += sector_step;
1575 * There was a data integrity error.
1578 atomic_dec(&ctx->cc_pending);
1579 return BLK_STS_PROTECTION;
1581 * There was an error while processing the request.
1584 atomic_dec(&ctx->cc_pending);
1585 return BLK_STS_IOERR;
1592 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
1595 * Generate a new unfragmented bio with the given size
1596 * This should never violate the device limitations (but only because
1597 * max_segment_size is being constrained to PAGE_SIZE).
1599 * This function may be called concurrently. If we allocate from the mempool
1600 * concurrently, there is a possibility of deadlock. For example, if we have
1601 * mempool of 256 pages, two processes, each wanting 256, pages allocate from
1602 * the mempool concurrently, it may deadlock in a situation where both processes
1603 * have allocated 128 pages and the mempool is exhausted.
1605 * In order to avoid this scenario we allocate the pages under a mutex.
1607 * In order to not degrade performance with excessive locking, we try
1608 * non-blocking allocations without a mutex first but on failure we fallback
1609 * to blocking allocations with a mutex.
1611 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
1613 struct crypt_config *cc = io->cc;
1615 unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1616 gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
1617 unsigned i, len, remaining_size;
1621 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1622 mutex_lock(&cc->bio_alloc_lock);
1624 clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, &cc->bs);
1628 clone_init(io, clone);
1630 remaining_size = size;
1632 for (i = 0; i < nr_iovecs; i++) {
1633 page = mempool_alloc(&cc->page_pool, gfp_mask);
1635 crypt_free_buffer_pages(cc, clone);
1637 gfp_mask |= __GFP_DIRECT_RECLAIM;
1641 len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
1643 bio_add_page(clone, page, len, 0);
1645 remaining_size -= len;
1648 /* Allocate space for integrity tags */
1649 if (dm_crypt_integrity_io_alloc(io, clone)) {
1650 crypt_free_buffer_pages(cc, clone);
1655 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1656 mutex_unlock(&cc->bio_alloc_lock);
1661 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1664 struct bvec_iter_all iter_all;
1666 bio_for_each_segment_all(bv, clone, iter_all) {
1667 BUG_ON(!bv->bv_page);
1668 mempool_free(bv->bv_page, &cc->page_pool);
1672 static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1673 struct bio *bio, sector_t sector)
1677 io->sector = sector;
1679 io->ctx.r.req = NULL;
1680 io->integrity_metadata = NULL;
1681 io->integrity_metadata_from_pool = false;
1682 atomic_set(&io->io_pending, 0);
1685 static void crypt_inc_pending(struct dm_crypt_io *io)
1687 atomic_inc(&io->io_pending);
1691 * One of the bios was finished. Check for completion of
1692 * the whole request and correctly clean up the buffer.
1694 static void crypt_dec_pending(struct dm_crypt_io *io)
1696 struct crypt_config *cc = io->cc;
1697 struct bio *base_bio = io->base_bio;
1698 blk_status_t error = io->error;
1700 if (!atomic_dec_and_test(&io->io_pending))
1704 crypt_free_req(cc, io->ctx.r.req, base_bio);
1706 if (unlikely(io->integrity_metadata_from_pool))
1707 mempool_free(io->integrity_metadata, &io->cc->tag_pool);
1709 kfree(io->integrity_metadata);
1711 base_bio->bi_status = error;
1712 bio_endio(base_bio);
1716 * kcryptd/kcryptd_io:
1718 * Needed because it would be very unwise to do decryption in an
1719 * interrupt context.
1721 * kcryptd performs the actual encryption or decryption.
1723 * kcryptd_io performs the IO submission.
1725 * They must be separated as otherwise the final stages could be
1726 * starved by new requests which can block in the first stages due
1727 * to memory allocation.
1729 * The work is done per CPU global for all dm-crypt instances.
1730 * They should not depend on each other and do not block.
1732 static void crypt_endio(struct bio *clone)
1734 struct dm_crypt_io *io = clone->bi_private;
1735 struct crypt_config *cc = io->cc;
1736 unsigned rw = bio_data_dir(clone);
1740 * free the processed pages
1743 crypt_free_buffer_pages(cc, clone);
1745 error = clone->bi_status;
1748 if (rw == READ && !error) {
1749 kcryptd_queue_crypt(io);
1753 if (unlikely(error))
1756 crypt_dec_pending(io);
1759 static void clone_init(struct dm_crypt_io *io, struct bio *clone)
1761 struct crypt_config *cc = io->cc;
1763 clone->bi_private = io;
1764 clone->bi_end_io = crypt_endio;
1765 bio_set_dev(clone, cc->dev->bdev);
1766 clone->bi_opf = io->base_bio->bi_opf;
1769 static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
1771 struct crypt_config *cc = io->cc;
1775 * We need the original biovec array in order to decrypt
1776 * the whole bio data *afterwards* -- thanks to immutable
1777 * biovecs we don't need to worry about the block layer
1778 * modifying the biovec array; so leverage bio_clone_fast().
1780 clone = bio_clone_fast(io->base_bio, gfp, &cc->bs);
1784 crypt_inc_pending(io);
1786 clone_init(io, clone);
1787 clone->bi_iter.bi_sector = cc->start + io->sector;
1789 if (dm_crypt_integrity_io_alloc(io, clone)) {
1790 crypt_dec_pending(io);
1795 generic_make_request(clone);
1799 static void kcryptd_io_read_work(struct work_struct *work)
1801 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1803 crypt_inc_pending(io);
1804 if (kcryptd_io_read(io, GFP_NOIO))
1805 io->error = BLK_STS_RESOURCE;
1806 crypt_dec_pending(io);
1809 static void kcryptd_queue_read(struct dm_crypt_io *io)
1811 struct crypt_config *cc = io->cc;
1813 INIT_WORK(&io->work, kcryptd_io_read_work);
1814 queue_work(cc->io_queue, &io->work);
1817 static void kcryptd_io_write(struct dm_crypt_io *io)
1819 struct bio *clone = io->ctx.bio_out;
1821 generic_make_request(clone);
1824 #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1826 static int dmcrypt_write(void *data)
1828 struct crypt_config *cc = data;
1829 struct dm_crypt_io *io;
1832 struct rb_root write_tree;
1833 struct blk_plug plug;
1835 spin_lock_irq(&cc->write_thread_lock);
1838 if (!RB_EMPTY_ROOT(&cc->write_tree))
1841 set_current_state(TASK_INTERRUPTIBLE);
1843 spin_unlock_irq(&cc->write_thread_lock);
1845 if (unlikely(kthread_should_stop())) {
1846 set_current_state(TASK_RUNNING);
1852 set_current_state(TASK_RUNNING);
1853 spin_lock_irq(&cc->write_thread_lock);
1854 goto continue_locked;
1857 write_tree = cc->write_tree;
1858 cc->write_tree = RB_ROOT;
1859 spin_unlock_irq(&cc->write_thread_lock);
1861 BUG_ON(rb_parent(write_tree.rb_node));
1864 * Note: we cannot walk the tree here with rb_next because
1865 * the structures may be freed when kcryptd_io_write is called.
1867 blk_start_plug(&plug);
1869 io = crypt_io_from_node(rb_first(&write_tree));
1870 rb_erase(&io->rb_node, &write_tree);
1871 kcryptd_io_write(io);
1872 } while (!RB_EMPTY_ROOT(&write_tree));
1873 blk_finish_plug(&plug);
1878 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
1880 struct bio *clone = io->ctx.bio_out;
1881 struct crypt_config *cc = io->cc;
1882 unsigned long flags;
1884 struct rb_node **rbp, *parent;
1886 if (unlikely(io->error)) {
1887 crypt_free_buffer_pages(cc, clone);
1889 crypt_dec_pending(io);
1893 /* crypt_convert should have filled the clone bio */
1894 BUG_ON(io->ctx.iter_out.bi_size);
1896 clone->bi_iter.bi_sector = cc->start + io->sector;
1898 if ((likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) ||
1899 test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags)) {
1900 generic_make_request(clone);
1904 spin_lock_irqsave(&cc->write_thread_lock, flags);
1905 if (RB_EMPTY_ROOT(&cc->write_tree))
1906 wake_up_process(cc->write_thread);
1907 rbp = &cc->write_tree.rb_node;
1909 sector = io->sector;
1912 if (sector < crypt_io_from_node(parent)->sector)
1913 rbp = &(*rbp)->rb_left;
1915 rbp = &(*rbp)->rb_right;
1917 rb_link_node(&io->rb_node, parent, rbp);
1918 rb_insert_color(&io->rb_node, &cc->write_tree);
1919 spin_unlock_irqrestore(&cc->write_thread_lock, flags);
1922 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
1924 struct crypt_config *cc = io->cc;
1927 sector_t sector = io->sector;
1931 * Prevent io from disappearing until this function completes.
1933 crypt_inc_pending(io);
1934 crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
1936 clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
1937 if (unlikely(!clone)) {
1938 io->error = BLK_STS_IOERR;
1942 io->ctx.bio_out = clone;
1943 io->ctx.iter_out = clone->bi_iter;
1945 sector += bio_sectors(clone);
1947 crypt_inc_pending(io);
1948 r = crypt_convert(cc, &io->ctx,
1949 test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags));
1952 crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
1954 /* Encryption was already finished, submit io now */
1955 if (crypt_finished) {
1956 kcryptd_crypt_write_io_submit(io, 0);
1957 io->sector = sector;
1961 crypt_dec_pending(io);
1964 static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
1966 crypt_dec_pending(io);
1969 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
1971 struct crypt_config *cc = io->cc;
1974 crypt_inc_pending(io);
1976 crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
1979 r = crypt_convert(cc, &io->ctx,
1980 test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags));
1984 if (atomic_dec_and_test(&io->ctx.cc_pending))
1985 kcryptd_crypt_read_done(io);
1987 crypt_dec_pending(io);
1990 static void kcryptd_async_done(struct crypto_async_request *async_req,
1993 struct dm_crypt_request *dmreq = async_req->data;
1994 struct convert_context *ctx = dmreq->ctx;
1995 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1996 struct crypt_config *cc = io->cc;
1999 * A request from crypto driver backlog is going to be processed now,
2000 * finish the completion and continue in crypt_convert().
2001 * (Callback will be called for the second time for this request.)
2003 if (error == -EINPROGRESS) {
2004 complete(&ctx->restart);
2008 if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
2009 error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
2011 if (error == -EBADMSG) {
2012 char b[BDEVNAME_SIZE];
2013 DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx->bio_in, b),
2014 (unsigned long long)le64_to_cpu(*org_sector_of_dmreq(cc, dmreq)));
2015 io->error = BLK_STS_PROTECTION;
2016 } else if (error < 0)
2017 io->error = BLK_STS_IOERR;
2019 crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
2021 if (!atomic_dec_and_test(&ctx->cc_pending))
2024 if (bio_data_dir(io->base_bio) == READ)
2025 kcryptd_crypt_read_done(io);
2027 kcryptd_crypt_write_io_submit(io, 1);
2030 static void kcryptd_crypt(struct work_struct *work)
2032 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2034 if (bio_data_dir(io->base_bio) == READ)
2035 kcryptd_crypt_read_convert(io);
2037 kcryptd_crypt_write_convert(io);
2040 static void kcryptd_crypt_tasklet(unsigned long work)
2042 kcryptd_crypt((struct work_struct *)work);
2045 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
2047 struct crypt_config *cc = io->cc;
2049 if ((bio_data_dir(io->base_bio) == READ && test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags)) ||
2050 (bio_data_dir(io->base_bio) == WRITE && test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))) {
2052 /* Crypto API's "skcipher_walk_first() refuses to work in hard IRQ context */
2053 tasklet_init(&io->tasklet, kcryptd_crypt_tasklet, (unsigned long)&io->work);
2054 tasklet_schedule(&io->tasklet);
2058 kcryptd_crypt(&io->work);
2062 INIT_WORK(&io->work, kcryptd_crypt);
2063 queue_work(cc->crypt_queue, &io->work);
2066 static void crypt_free_tfms_aead(struct crypt_config *cc)
2068 if (!cc->cipher_tfm.tfms_aead)
2071 if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2072 crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
2073 cc->cipher_tfm.tfms_aead[0] = NULL;
2076 kfree(cc->cipher_tfm.tfms_aead);
2077 cc->cipher_tfm.tfms_aead = NULL;
2080 static void crypt_free_tfms_skcipher(struct crypt_config *cc)
2084 if (!cc->cipher_tfm.tfms)
2087 for (i = 0; i < cc->tfms_count; i++)
2088 if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
2089 crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
2090 cc->cipher_tfm.tfms[i] = NULL;
2093 kfree(cc->cipher_tfm.tfms);
2094 cc->cipher_tfm.tfms = NULL;
2097 static void crypt_free_tfms(struct crypt_config *cc)
2099 if (crypt_integrity_aead(cc))
2100 crypt_free_tfms_aead(cc);
2102 crypt_free_tfms_skcipher(cc);
2105 static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
2110 cc->cipher_tfm.tfms = kcalloc(cc->tfms_count,
2111 sizeof(struct crypto_skcipher *),
2113 if (!cc->cipher_tfm.tfms)
2116 for (i = 0; i < cc->tfms_count; i++) {
2117 cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0, 0);
2118 if (IS_ERR(cc->cipher_tfm.tfms[i])) {
2119 err = PTR_ERR(cc->cipher_tfm.tfms[i]);
2120 crypt_free_tfms(cc);
2126 * dm-crypt performance can vary greatly depending on which crypto
2127 * algorithm implementation is used. Help people debug performance
2128 * problems by logging the ->cra_driver_name.
2130 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2131 crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
2135 static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
2139 cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
2140 if (!cc->cipher_tfm.tfms)
2143 cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0, 0);
2144 if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2145 err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
2146 crypt_free_tfms(cc);
2150 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2151 crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
2155 static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
2157 if (crypt_integrity_aead(cc))
2158 return crypt_alloc_tfms_aead(cc, ciphermode);
2160 return crypt_alloc_tfms_skcipher(cc, ciphermode);
2163 static unsigned crypt_subkey_size(struct crypt_config *cc)
2165 return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
2168 static unsigned crypt_authenckey_size(struct crypt_config *cc)
2170 return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
2174 * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
2175 * the key must be for some reason in special format.
2176 * This funcion converts cc->key to this special format.
2178 static void crypt_copy_authenckey(char *p, const void *key,
2179 unsigned enckeylen, unsigned authkeylen)
2181 struct crypto_authenc_key_param *param;
2184 rta = (struct rtattr *)p;
2185 param = RTA_DATA(rta);
2186 param->enckeylen = cpu_to_be32(enckeylen);
2187 rta->rta_len = RTA_LENGTH(sizeof(*param));
2188 rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
2189 p += RTA_SPACE(sizeof(*param));
2190 memcpy(p, key + enckeylen, authkeylen);
2192 memcpy(p, key, enckeylen);
2195 static int crypt_setkey(struct crypt_config *cc)
2197 unsigned subkey_size;
2200 /* Ignore extra keys (which are used for IV etc) */
2201 subkey_size = crypt_subkey_size(cc);
2203 if (crypt_integrity_hmac(cc)) {
2204 if (subkey_size < cc->key_mac_size)
2207 crypt_copy_authenckey(cc->authenc_key, cc->key,
2208 subkey_size - cc->key_mac_size,
2212 for (i = 0; i < cc->tfms_count; i++) {
2213 if (crypt_integrity_hmac(cc))
2214 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2215 cc->authenc_key, crypt_authenckey_size(cc));
2216 else if (crypt_integrity_aead(cc))
2217 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2218 cc->key + (i * subkey_size),
2221 r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
2222 cc->key + (i * subkey_size),
2228 if (crypt_integrity_hmac(cc))
2229 memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
2236 static bool contains_whitespace(const char *str)
2239 if (isspace(*str++))
2244 static int set_key_user(struct crypt_config *cc, struct key *key)
2246 const struct user_key_payload *ukp;
2248 ukp = user_key_payload_locked(key);
2250 return -EKEYREVOKED;
2252 if (cc->key_size != ukp->datalen)
2255 memcpy(cc->key, ukp->data, cc->key_size);
2260 #if defined(CONFIG_ENCRYPTED_KEYS) || defined(CONFIG_ENCRYPTED_KEYS_MODULE)
2261 static int set_key_encrypted(struct crypt_config *cc, struct key *key)
2263 const struct encrypted_key_payload *ekp;
2265 ekp = key->payload.data[0];
2267 return -EKEYREVOKED;
2269 if (cc->key_size != ekp->decrypted_datalen)
2272 memcpy(cc->key, ekp->decrypted_data, cc->key_size);
2276 #endif /* CONFIG_ENCRYPTED_KEYS */
2278 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2280 char *new_key_string, *key_desc;
2282 struct key_type *type;
2284 int (*set_key)(struct crypt_config *cc, struct key *key);
2287 * Reject key_string with whitespace. dm core currently lacks code for
2288 * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2290 if (contains_whitespace(key_string)) {
2291 DMERR("whitespace chars not allowed in key string");
2295 /* look for next ':' separating key_type from key_description */
2296 key_desc = strpbrk(key_string, ":");
2297 if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2300 if (!strncmp(key_string, "logon:", key_desc - key_string + 1)) {
2301 type = &key_type_logon;
2302 set_key = set_key_user;
2303 } else if (!strncmp(key_string, "user:", key_desc - key_string + 1)) {
2304 type = &key_type_user;
2305 set_key = set_key_user;
2306 #if defined(CONFIG_ENCRYPTED_KEYS) || defined(CONFIG_ENCRYPTED_KEYS_MODULE)
2307 } else if (!strncmp(key_string, "encrypted:", key_desc - key_string + 1)) {
2308 type = &key_type_encrypted;
2309 set_key = set_key_encrypted;
2315 new_key_string = kstrdup(key_string, GFP_KERNEL);
2316 if (!new_key_string)
2319 key = request_key(type, key_desc + 1, NULL);
2321 kzfree(new_key_string);
2322 return PTR_ERR(key);
2325 down_read(&key->sem);
2327 ret = set_key(cc, key);
2331 kzfree(new_key_string);
2338 /* clear the flag since following operations may invalidate previously valid key */
2339 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2341 ret = crypt_setkey(cc);
2344 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2345 kzfree(cc->key_string);
2346 cc->key_string = new_key_string;
2348 kzfree(new_key_string);
2353 static int get_key_size(char **key_string)
2358 if (*key_string[0] != ':')
2359 return strlen(*key_string) >> 1;
2361 /* look for next ':' in key string */
2362 colon = strpbrk(*key_string + 1, ":");
2366 if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2369 *key_string = colon;
2371 /* remaining key string should be :<logon|user>:<key_desc> */
2378 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2383 static int get_key_size(char **key_string)
2385 return (*key_string[0] == ':') ? -EINVAL : strlen(*key_string) >> 1;
2388 #endif /* CONFIG_KEYS */
2390 static int crypt_set_key(struct crypt_config *cc, char *key)
2393 int key_string_len = strlen(key);
2395 /* Hyphen (which gives a key_size of zero) means there is no key. */
2396 if (!cc->key_size && strcmp(key, "-"))
2399 /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2400 if (key[0] == ':') {
2401 r = crypt_set_keyring_key(cc, key + 1);
2405 /* clear the flag since following operations may invalidate previously valid key */
2406 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2408 /* wipe references to any kernel keyring key */
2409 kzfree(cc->key_string);
2410 cc->key_string = NULL;
2412 /* Decode key from its hex representation. */
2413 if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
2416 r = crypt_setkey(cc);
2418 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2421 /* Hex key string not needed after here, so wipe it. */
2422 memset(key, '0', key_string_len);
2427 static int crypt_wipe_key(struct crypt_config *cc)
2431 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2432 get_random_bytes(&cc->key, cc->key_size);
2434 /* Wipe IV private keys */
2435 if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
2436 r = cc->iv_gen_ops->wipe(cc);
2441 kzfree(cc->key_string);
2442 cc->key_string = NULL;
2443 r = crypt_setkey(cc);
2444 memset(&cc->key, 0, cc->key_size * sizeof(u8));
2449 static void crypt_calculate_pages_per_client(void)
2451 unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
2453 if (!dm_crypt_clients_n)
2456 pages /= dm_crypt_clients_n;
2457 if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
2458 pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
2459 dm_crypt_pages_per_client = pages;
2462 static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
2464 struct crypt_config *cc = pool_data;
2467 if (unlikely(percpu_counter_compare(&cc->n_allocated_pages, dm_crypt_pages_per_client) >= 0) &&
2468 likely(gfp_mask & __GFP_NORETRY))
2471 page = alloc_page(gfp_mask);
2472 if (likely(page != NULL))
2473 percpu_counter_add(&cc->n_allocated_pages, 1);
2478 static void crypt_page_free(void *page, void *pool_data)
2480 struct crypt_config *cc = pool_data;
2483 percpu_counter_sub(&cc->n_allocated_pages, 1);
2486 static void crypt_dtr(struct dm_target *ti)
2488 struct crypt_config *cc = ti->private;
2495 if (cc->write_thread)
2496 kthread_stop(cc->write_thread);
2499 destroy_workqueue(cc->io_queue);
2500 if (cc->crypt_queue)
2501 destroy_workqueue(cc->crypt_queue);
2503 crypt_free_tfms(cc);
2505 bioset_exit(&cc->bs);
2507 mempool_exit(&cc->page_pool);
2508 mempool_exit(&cc->req_pool);
2509 mempool_exit(&cc->tag_pool);
2511 WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
2512 percpu_counter_destroy(&cc->n_allocated_pages);
2514 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
2515 cc->iv_gen_ops->dtr(cc);
2518 dm_put_device(ti, cc->dev);
2520 kzfree(cc->cipher_string);
2521 kzfree(cc->key_string);
2522 kzfree(cc->cipher_auth);
2523 kzfree(cc->authenc_key);
2525 mutex_destroy(&cc->bio_alloc_lock);
2527 /* Must zero key material before freeing */
2530 spin_lock(&dm_crypt_clients_lock);
2531 WARN_ON(!dm_crypt_clients_n);
2532 dm_crypt_clients_n--;
2533 crypt_calculate_pages_per_client();
2534 spin_unlock(&dm_crypt_clients_lock);
2537 static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
2539 struct crypt_config *cc = ti->private;
2541 if (crypt_integrity_aead(cc))
2542 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2544 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2547 /* at least a 64 bit sector number should fit in our buffer */
2548 cc->iv_size = max(cc->iv_size,
2549 (unsigned int)(sizeof(u64) / sizeof(u8)));
2551 DMWARN("Selected cipher does not support IVs");
2555 /* Choose ivmode, see comments at iv code. */
2557 cc->iv_gen_ops = NULL;
2558 else if (strcmp(ivmode, "plain") == 0)
2559 cc->iv_gen_ops = &crypt_iv_plain_ops;
2560 else if (strcmp(ivmode, "plain64") == 0)
2561 cc->iv_gen_ops = &crypt_iv_plain64_ops;
2562 else if (strcmp(ivmode, "plain64be") == 0)
2563 cc->iv_gen_ops = &crypt_iv_plain64be_ops;
2564 else if (strcmp(ivmode, "essiv") == 0)
2565 cc->iv_gen_ops = &crypt_iv_essiv_ops;
2566 else if (strcmp(ivmode, "benbi") == 0)
2567 cc->iv_gen_ops = &crypt_iv_benbi_ops;
2568 else if (strcmp(ivmode, "null") == 0)
2569 cc->iv_gen_ops = &crypt_iv_null_ops;
2570 else if (strcmp(ivmode, "eboiv") == 0)
2571 cc->iv_gen_ops = &crypt_iv_eboiv_ops;
2572 else if (strcmp(ivmode, "elephant") == 0) {
2573 cc->iv_gen_ops = &crypt_iv_elephant_ops;
2575 cc->key_extra_size = cc->key_size / 2;
2576 if (cc->key_extra_size > ELEPHANT_MAX_KEY_SIZE)
2578 set_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags);
2579 } else if (strcmp(ivmode, "lmk") == 0) {
2580 cc->iv_gen_ops = &crypt_iv_lmk_ops;
2582 * Version 2 and 3 is recognised according
2583 * to length of provided multi-key string.
2584 * If present (version 3), last key is used as IV seed.
2585 * All keys (including IV seed) are always the same size.
2587 if (cc->key_size % cc->key_parts) {
2589 cc->key_extra_size = cc->key_size / cc->key_parts;
2591 } else if (strcmp(ivmode, "tcw") == 0) {
2592 cc->iv_gen_ops = &crypt_iv_tcw_ops;
2593 cc->key_parts += 2; /* IV + whitening */
2594 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2595 } else if (strcmp(ivmode, "random") == 0) {
2596 cc->iv_gen_ops = &crypt_iv_random_ops;
2597 /* Need storage space in integrity fields. */
2598 cc->integrity_iv_size = cc->iv_size;
2600 ti->error = "Invalid IV mode";
2608 * Workaround to parse HMAC algorithm from AEAD crypto API spec.
2609 * The HMAC is needed to calculate tag size (HMAC digest size).
2610 * This should be probably done by crypto-api calls (once available...)
2612 static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
2614 char *start, *end, *mac_alg = NULL;
2615 struct crypto_ahash *mac;
2617 if (!strstarts(cipher_api, "authenc("))
2620 start = strchr(cipher_api, '(');
2621 end = strchr(cipher_api, ',');
2622 if (!start || !end || ++start > end)
2625 mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
2628 strncpy(mac_alg, start, end - start);
2630 mac = crypto_alloc_ahash(mac_alg, 0, 0);
2634 return PTR_ERR(mac);
2636 cc->key_mac_size = crypto_ahash_digestsize(mac);
2637 crypto_free_ahash(mac);
2639 cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
2640 if (!cc->authenc_key)
2646 static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
2647 char **ivmode, char **ivopts)
2649 struct crypt_config *cc = ti->private;
2650 char *tmp, *cipher_api, buf[CRYPTO_MAX_ALG_NAME];
2656 * New format (capi: prefix)
2657 * capi:cipher_api_spec-iv:ivopts
2659 tmp = &cipher_in[strlen("capi:")];
2661 /* Separate IV options if present, it can contain another '-' in hash name */
2662 *ivopts = strrchr(tmp, ':');
2668 *ivmode = strrchr(tmp, '-');
2673 /* The rest is crypto API spec */
2676 /* Alloc AEAD, can be used only in new format. */
2677 if (crypt_integrity_aead(cc)) {
2678 ret = crypt_ctr_auth_cipher(cc, cipher_api);
2680 ti->error = "Invalid AEAD cipher spec";
2685 if (*ivmode && !strcmp(*ivmode, "lmk"))
2686 cc->tfms_count = 64;
2688 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2690 ti->error = "Digest algorithm missing for ESSIV mode";
2693 ret = snprintf(buf, CRYPTO_MAX_ALG_NAME, "essiv(%s,%s)",
2694 cipher_api, *ivopts);
2695 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2696 ti->error = "Cannot allocate cipher string";
2702 cc->key_parts = cc->tfms_count;
2704 /* Allocate cipher */
2705 ret = crypt_alloc_tfms(cc, cipher_api);
2707 ti->error = "Error allocating crypto tfm";
2711 if (crypt_integrity_aead(cc))
2712 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2714 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2719 static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
2720 char **ivmode, char **ivopts)
2722 struct crypt_config *cc = ti->private;
2723 char *tmp, *cipher, *chainmode, *keycount;
2724 char *cipher_api = NULL;
2728 if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
2729 ti->error = "Bad cipher specification";
2734 * Legacy dm-crypt cipher specification
2735 * cipher[:keycount]-mode-iv:ivopts
2738 keycount = strsep(&tmp, "-");
2739 cipher = strsep(&keycount, ":");
2743 else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
2744 !is_power_of_2(cc->tfms_count)) {
2745 ti->error = "Bad cipher key count specification";
2748 cc->key_parts = cc->tfms_count;
2750 chainmode = strsep(&tmp, "-");
2751 *ivmode = strsep(&tmp, ":");
2755 * For compatibility with the original dm-crypt mapping format, if
2756 * only the cipher name is supplied, use cbc-plain.
2758 if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
2763 if (strcmp(chainmode, "ecb") && !*ivmode) {
2764 ti->error = "IV mechanism required";
2768 cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
2772 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2774 ti->error = "Digest algorithm missing for ESSIV mode";
2778 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2779 "essiv(%s(%s),%s)", chainmode, cipher, *ivopts);
2781 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2782 "%s(%s)", chainmode, cipher);
2784 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2789 /* Allocate cipher */
2790 ret = crypt_alloc_tfms(cc, cipher_api);
2792 ti->error = "Error allocating crypto tfm";
2800 ti->error = "Cannot allocate cipher strings";
2804 static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
2806 struct crypt_config *cc = ti->private;
2807 char *ivmode = NULL, *ivopts = NULL;
2810 cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
2811 if (!cc->cipher_string) {
2812 ti->error = "Cannot allocate cipher strings";
2816 if (strstarts(cipher_in, "capi:"))
2817 ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
2819 ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
2824 ret = crypt_ctr_ivmode(ti, ivmode);
2828 /* Initialize and set key */
2829 ret = crypt_set_key(cc, key);
2831 ti->error = "Error decoding and setting key";
2836 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
2837 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
2839 ti->error = "Error creating IV";
2844 /* Initialize IV (set keys for ESSIV etc) */
2845 if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
2846 ret = cc->iv_gen_ops->init(cc);
2848 ti->error = "Error initialising IV";
2853 /* wipe the kernel key payload copy */
2855 memset(cc->key, 0, cc->key_size * sizeof(u8));
2860 static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
2862 struct crypt_config *cc = ti->private;
2863 struct dm_arg_set as;
2864 static const struct dm_arg _args[] = {
2865 {0, 8, "Invalid number of feature args"},
2867 unsigned int opt_params, val;
2868 const char *opt_string, *sval;
2872 /* Optional parameters */
2876 ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
2880 while (opt_params--) {
2881 opt_string = dm_shift_arg(&as);
2883 ti->error = "Not enough feature arguments";
2887 if (!strcasecmp(opt_string, "allow_discards"))
2888 ti->num_discard_bios = 1;
2890 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
2891 set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
2893 else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
2894 set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
2895 else if (!strcasecmp(opt_string, "no_read_workqueue"))
2896 set_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
2897 else if (!strcasecmp(opt_string, "no_write_workqueue"))
2898 set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
2899 else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
2900 if (val == 0 || val > MAX_TAG_SIZE) {
2901 ti->error = "Invalid integrity arguments";
2904 cc->on_disk_tag_size = val;
2905 sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
2906 if (!strcasecmp(sval, "aead")) {
2907 set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
2908 } else if (strcasecmp(sval, "none")) {
2909 ti->error = "Unknown integrity profile";
2913 cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
2914 if (!cc->cipher_auth)
2916 } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
2917 if (cc->sector_size < (1 << SECTOR_SHIFT) ||
2918 cc->sector_size > 4096 ||
2919 (cc->sector_size & (cc->sector_size - 1))) {
2920 ti->error = "Invalid feature value for sector_size";
2923 if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
2924 ti->error = "Device size is not multiple of sector_size feature";
2927 cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
2928 } else if (!strcasecmp(opt_string, "iv_large_sectors"))
2929 set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
2931 ti->error = "Invalid feature arguments";
2940 * Construct an encryption mapping:
2941 * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
2943 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
2945 struct crypt_config *cc;
2946 const char *devname = dm_table_device_name(ti->table);
2948 unsigned int align_mask;
2949 unsigned long long tmpll;
2951 size_t iv_size_padding, additional_req_size;
2955 ti->error = "Not enough arguments";
2959 key_size = get_key_size(&argv[1]);
2961 ti->error = "Cannot parse key size";
2965 cc = kzalloc(struct_size(cc, key, key_size), GFP_KERNEL);
2967 ti->error = "Cannot allocate encryption context";
2970 cc->key_size = key_size;
2971 cc->sector_size = (1 << SECTOR_SHIFT);
2972 cc->sector_shift = 0;
2976 spin_lock(&dm_crypt_clients_lock);
2977 dm_crypt_clients_n++;
2978 crypt_calculate_pages_per_client();
2979 spin_unlock(&dm_crypt_clients_lock);
2981 ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
2985 /* Optional parameters need to be read before cipher constructor */
2987 ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
2992 ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
2996 if (crypt_integrity_aead(cc)) {
2997 cc->dmreq_start = sizeof(struct aead_request);
2998 cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
2999 align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
3001 cc->dmreq_start = sizeof(struct skcipher_request);
3002 cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
3003 align_mask = crypto_skcipher_alignmask(any_tfm(cc));
3005 cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
3007 if (align_mask < CRYPTO_MINALIGN) {
3008 /* Allocate the padding exactly */
3009 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
3013 * If the cipher requires greater alignment than kmalloc
3014 * alignment, we don't know the exact position of the
3015 * initialization vector. We must assume worst case.
3017 iv_size_padding = align_mask;
3020 /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
3021 additional_req_size = sizeof(struct dm_crypt_request) +
3022 iv_size_padding + cc->iv_size +
3025 sizeof(unsigned int);
3027 ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
3029 ti->error = "Cannot allocate crypt request mempool";
3033 cc->per_bio_data_size = ti->per_io_data_size =
3034 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
3035 ARCH_KMALLOC_MINALIGN);
3037 ret = mempool_init(&cc->page_pool, BIO_MAX_PAGES, crypt_page_alloc, crypt_page_free, cc);
3039 ti->error = "Cannot allocate page mempool";
3043 ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
3045 ti->error = "Cannot allocate crypt bioset";
3049 mutex_init(&cc->bio_alloc_lock);
3052 if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
3053 (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
3054 ti->error = "Invalid iv_offset sector";
3057 cc->iv_offset = tmpll;
3059 ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
3061 ti->error = "Device lookup failed";
3066 if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
3067 ti->error = "Invalid device sector";
3072 if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
3073 ret = crypt_integrity_ctr(cc, ti);
3077 cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
3078 if (!cc->tag_pool_max_sectors)
3079 cc->tag_pool_max_sectors = 1;
3081 ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
3082 cc->tag_pool_max_sectors * cc->on_disk_tag_size);
3084 ti->error = "Cannot allocate integrity tags mempool";
3088 cc->tag_pool_max_sectors <<= cc->sector_shift;
3092 cc->io_queue = alloc_workqueue("kcryptd_io/%s", WQ_MEM_RECLAIM, 1, devname);
3093 if (!cc->io_queue) {
3094 ti->error = "Couldn't create kcryptd io queue";
3098 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3099 cc->crypt_queue = alloc_workqueue("kcryptd/%s", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM,
3102 cc->crypt_queue = alloc_workqueue("kcryptd/%s",
3103 WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
3104 num_online_cpus(), devname);
3105 if (!cc->crypt_queue) {
3106 ti->error = "Couldn't create kcryptd queue";
3110 spin_lock_init(&cc->write_thread_lock);
3111 cc->write_tree = RB_ROOT;
3113 cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
3114 if (IS_ERR(cc->write_thread)) {
3115 ret = PTR_ERR(cc->write_thread);
3116 cc->write_thread = NULL;
3117 ti->error = "Couldn't spawn write thread";
3120 wake_up_process(cc->write_thread);
3122 ti->num_flush_bios = 1;
3131 static int crypt_map(struct dm_target *ti, struct bio *bio)
3133 struct dm_crypt_io *io;
3134 struct crypt_config *cc = ti->private;
3137 * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
3138 * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
3139 * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
3141 if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
3142 bio_op(bio) == REQ_OP_DISCARD)) {
3143 bio_set_dev(bio, cc->dev->bdev);
3144 if (bio_sectors(bio))
3145 bio->bi_iter.bi_sector = cc->start +
3146 dm_target_offset(ti, bio->bi_iter.bi_sector);
3147 return DM_MAPIO_REMAPPED;
3151 * Check if bio is too large, split as needed.
3153 if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_PAGES << PAGE_SHIFT)) &&
3154 (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
3155 dm_accept_partial_bio(bio, ((BIO_MAX_PAGES << PAGE_SHIFT) >> SECTOR_SHIFT));
3158 * Ensure that bio is a multiple of internal sector encryption size
3159 * and is aligned to this size as defined in IO hints.
3161 if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
3162 return DM_MAPIO_KILL;
3164 if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
3165 return DM_MAPIO_KILL;
3167 io = dm_per_bio_data(bio, cc->per_bio_data_size);
3168 crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
3170 if (cc->on_disk_tag_size) {
3171 unsigned tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
3173 if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
3174 unlikely(!(io->integrity_metadata = kmalloc(tag_len,
3175 GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
3176 if (bio_sectors(bio) > cc->tag_pool_max_sectors)
3177 dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
3178 io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
3179 io->integrity_metadata_from_pool = true;
3183 if (crypt_integrity_aead(cc))
3184 io->ctx.r.req_aead = (struct aead_request *)(io + 1);
3186 io->ctx.r.req = (struct skcipher_request *)(io + 1);
3188 if (bio_data_dir(io->base_bio) == READ) {
3189 if (kcryptd_io_read(io, GFP_NOWAIT))
3190 kcryptd_queue_read(io);
3192 kcryptd_queue_crypt(io);
3194 return DM_MAPIO_SUBMITTED;
3197 static void crypt_status(struct dm_target *ti, status_type_t type,
3198 unsigned status_flags, char *result, unsigned maxlen)
3200 struct crypt_config *cc = ti->private;
3202 int num_feature_args = 0;
3205 case STATUSTYPE_INFO:
3209 case STATUSTYPE_TABLE:
3210 DMEMIT("%s ", cc->cipher_string);
3212 if (cc->key_size > 0) {
3214 DMEMIT(":%u:%s", cc->key_size, cc->key_string);
3216 for (i = 0; i < cc->key_size; i++)
3217 DMEMIT("%02x", cc->key[i]);
3221 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
3222 cc->dev->name, (unsigned long long)cc->start);
3224 num_feature_args += !!ti->num_discard_bios;
3225 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3226 num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3227 num_feature_args += test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3228 num_feature_args += test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3229 num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
3230 num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3231 if (cc->on_disk_tag_size)
3233 if (num_feature_args) {
3234 DMEMIT(" %d", num_feature_args);
3235 if (ti->num_discard_bios)
3236 DMEMIT(" allow_discards");
3237 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3238 DMEMIT(" same_cpu_crypt");
3239 if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
3240 DMEMIT(" submit_from_crypt_cpus");
3241 if (test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags))
3242 DMEMIT(" no_read_workqueue");
3243 if (test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))
3244 DMEMIT(" no_write_workqueue");
3245 if (cc->on_disk_tag_size)
3246 DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
3247 if (cc->sector_size != (1 << SECTOR_SHIFT))
3248 DMEMIT(" sector_size:%d", cc->sector_size);
3249 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
3250 DMEMIT(" iv_large_sectors");
3257 static void crypt_postsuspend(struct dm_target *ti)
3259 struct crypt_config *cc = ti->private;
3261 set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3264 static int crypt_preresume(struct dm_target *ti)
3266 struct crypt_config *cc = ti->private;
3268 if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
3269 DMERR("aborting resume - crypt key is not set.");
3276 static void crypt_resume(struct dm_target *ti)
3278 struct crypt_config *cc = ti->private;
3280 clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3283 /* Message interface
3287 static int crypt_message(struct dm_target *ti, unsigned argc, char **argv,
3288 char *result, unsigned maxlen)
3290 struct crypt_config *cc = ti->private;
3291 int key_size, ret = -EINVAL;
3296 if (!strcasecmp(argv[0], "key")) {
3297 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
3298 DMWARN("not suspended during key manipulation.");
3301 if (argc == 3 && !strcasecmp(argv[1], "set")) {
3302 /* The key size may not be changed. */
3303 key_size = get_key_size(&argv[2]);
3304 if (key_size < 0 || cc->key_size != key_size) {
3305 memset(argv[2], '0', strlen(argv[2]));
3309 ret = crypt_set_key(cc, argv[2]);
3312 if (cc->iv_gen_ops && cc->iv_gen_ops->init)
3313 ret = cc->iv_gen_ops->init(cc);
3314 /* wipe the kernel key payload copy */
3316 memset(cc->key, 0, cc->key_size * sizeof(u8));
3319 if (argc == 2 && !strcasecmp(argv[1], "wipe"))
3320 return crypt_wipe_key(cc);
3324 DMWARN("unrecognised message received.");
3328 static int crypt_iterate_devices(struct dm_target *ti,
3329 iterate_devices_callout_fn fn, void *data)
3331 struct crypt_config *cc = ti->private;
3333 return fn(ti, cc->dev, cc->start, ti->len, data);
3336 static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
3338 struct crypt_config *cc = ti->private;
3341 * Unfortunate constraint that is required to avoid the potential
3342 * for exceeding underlying device's max_segments limits -- due to
3343 * crypt_alloc_buffer() possibly allocating pages for the encryption
3344 * bio that are not as physically contiguous as the original bio.
3346 limits->max_segment_size = PAGE_SIZE;
3348 limits->logical_block_size =
3349 max_t(unsigned, limits->logical_block_size, cc->sector_size);
3350 limits->physical_block_size =
3351 max_t(unsigned, limits->physical_block_size, cc->sector_size);
3352 limits->io_min = max_t(unsigned, limits->io_min, cc->sector_size);
3355 static struct target_type crypt_target = {
3357 .version = {1, 22, 0},
3358 .module = THIS_MODULE,
3362 .status = crypt_status,
3363 .postsuspend = crypt_postsuspend,
3364 .preresume = crypt_preresume,
3365 .resume = crypt_resume,
3366 .message = crypt_message,
3367 .iterate_devices = crypt_iterate_devices,
3368 .io_hints = crypt_io_hints,
3371 static int __init dm_crypt_init(void)
3375 r = dm_register_target(&crypt_target);
3377 DMERR("register failed %d", r);
3382 static void __exit dm_crypt_exit(void)
3384 dm_unregister_target(&crypt_target);
3387 module_init(dm_crypt_init);
3388 module_exit(dm_crypt_exit);
3390 MODULE_AUTHOR("Jana Saout <jana@saout.de>");
3391 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
3392 MODULE_LICENSE("GPL");