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;
73 struct convert_context ctx;
79 struct rb_node rb_node;
80 } CRYPTO_MINALIGN_ATTR;
82 struct dm_crypt_request {
83 struct convert_context *ctx;
84 struct scatterlist sg_in[4];
85 struct scatterlist sg_out[4];
91 struct crypt_iv_operations {
92 int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
94 void (*dtr)(struct crypt_config *cc);
95 int (*init)(struct crypt_config *cc);
96 int (*wipe)(struct crypt_config *cc);
97 int (*generator)(struct crypt_config *cc, u8 *iv,
98 struct dm_crypt_request *dmreq);
99 int (*post)(struct crypt_config *cc, u8 *iv,
100 struct dm_crypt_request *dmreq);
103 struct iv_benbi_private {
107 #define LMK_SEED_SIZE 64 /* hash + 0 */
108 struct iv_lmk_private {
109 struct crypto_shash *hash_tfm;
113 #define TCW_WHITENING_SIZE 16
114 struct iv_tcw_private {
115 struct crypto_shash *crc32_tfm;
120 #define ELEPHANT_MAX_KEY_SIZE 32
121 struct iv_elephant_private {
122 struct crypto_skcipher *tfm;
126 * Crypt: maps a linear range of a block device
127 * and encrypts / decrypts at the same time.
129 enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
130 DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD };
133 CRYPT_MODE_INTEGRITY_AEAD, /* Use authenticated mode for cihper */
134 CRYPT_IV_LARGE_SECTORS, /* Calculate IV from sector_size, not 512B sectors */
135 CRYPT_ENCRYPT_PREPROCESS, /* Must preprocess data for encryption (elephant) */
139 * The fields in here must be read only after initialization.
141 struct crypt_config {
145 struct percpu_counter n_allocated_pages;
147 struct workqueue_struct *io_queue;
148 struct workqueue_struct *crypt_queue;
150 spinlock_t write_thread_lock;
151 struct task_struct *write_thread;
152 struct rb_root write_tree;
158 const struct crypt_iv_operations *iv_gen_ops;
160 struct iv_benbi_private benbi;
161 struct iv_lmk_private lmk;
162 struct iv_tcw_private tcw;
163 struct iv_elephant_private elephant;
166 unsigned int iv_size;
167 unsigned short int sector_size;
168 unsigned char sector_shift;
171 struct crypto_skcipher **tfms;
172 struct crypto_aead **tfms_aead;
175 unsigned long cipher_flags;
178 * Layout of each crypto request:
180 * struct skcipher_request
183 * struct dm_crypt_request
187 * The padding is added so that dm_crypt_request and the IV are
190 unsigned int dmreq_start;
192 unsigned int per_bio_data_size;
195 unsigned int key_size;
196 unsigned int key_parts; /* independent parts in key buffer */
197 unsigned int key_extra_size; /* additional keys length */
198 unsigned int key_mac_size; /* MAC key size for authenc(...) */
200 unsigned int integrity_tag_size;
201 unsigned int integrity_iv_size;
202 unsigned int on_disk_tag_size;
205 * pool for per bio private data, crypto requests,
206 * encryption requeusts/buffer pages and integrity tags
208 unsigned tag_pool_max_sectors;
214 struct mutex bio_alloc_lock;
216 u8 *authenc_key; /* space for keys in authenc() format (if used) */
221 #define MAX_TAG_SIZE 480
222 #define POOL_ENTRY_SIZE 512
224 static DEFINE_SPINLOCK(dm_crypt_clients_lock);
225 static unsigned dm_crypt_clients_n = 0;
226 static volatile unsigned long dm_crypt_pages_per_client;
227 #define DM_CRYPT_MEMORY_PERCENT 2
228 #define DM_CRYPT_MIN_PAGES_PER_CLIENT (BIO_MAX_PAGES * 16)
230 static void clone_init(struct dm_crypt_io *, struct bio *);
231 static void kcryptd_queue_crypt(struct dm_crypt_io *io);
232 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
233 struct scatterlist *sg);
235 static bool crypt_integrity_aead(struct crypt_config *cc);
238 * Use this to access cipher attributes that are independent of the key.
240 static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
242 return cc->cipher_tfm.tfms[0];
245 static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
247 return cc->cipher_tfm.tfms_aead[0];
251 * Different IV generation algorithms:
253 * plain: the initial vector is the 32-bit little-endian version of the sector
254 * number, padded with zeros if necessary.
256 * plain64: the initial vector is the 64-bit little-endian version of the sector
257 * number, padded with zeros if necessary.
259 * plain64be: the initial vector is the 64-bit big-endian version of the sector
260 * number, padded with zeros if necessary.
262 * essiv: "encrypted sector|salt initial vector", the sector number is
263 * encrypted with the bulk cipher using a salt as key. The salt
264 * should be derived from the bulk cipher's key via hashing.
266 * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
267 * (needed for LRW-32-AES and possible other narrow block modes)
269 * null: the initial vector is always zero. Provides compatibility with
270 * obsolete loop_fish2 devices. Do not use for new devices.
272 * lmk: Compatible implementation of the block chaining mode used
273 * by the Loop-AES block device encryption system
274 * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
275 * It operates on full 512 byte sectors and uses CBC
276 * with an IV derived from the sector number, the data and
277 * optionally extra IV seed.
278 * This means that after decryption the first block
279 * of sector must be tweaked according to decrypted data.
280 * Loop-AES can use three encryption schemes:
281 * version 1: is plain aes-cbc mode
282 * version 2: uses 64 multikey scheme with lmk IV generator
283 * version 3: the same as version 2 with additional IV seed
284 * (it uses 65 keys, last key is used as IV seed)
286 * tcw: Compatible implementation of the block chaining mode used
287 * by the TrueCrypt device encryption system (prior to version 4.1).
288 * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
289 * It operates on full 512 byte sectors and uses CBC
290 * with an IV derived from initial key and the sector number.
291 * In addition, whitening value is applied on every sector, whitening
292 * is calculated from initial key, sector number and mixed using CRC32.
293 * Note that this encryption scheme is vulnerable to watermarking attacks
294 * and should be used for old compatible containers access only.
296 * eboiv: Encrypted byte-offset IV (used in Bitlocker in CBC mode)
297 * The IV is encrypted little-endian byte-offset (with the same key
298 * and cipher as the volume).
300 * elephant: The extended version of eboiv with additional Elephant diffuser
301 * used with Bitlocker CBC mode.
302 * This mode was used in older Windows systems
303 * http://download.microsoft.com/download/0/2/3/0238acaf-d3bf-4a6d-b3d6-0a0be4bbb36e/bitlockercipher200608.pdf
306 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
307 struct dm_crypt_request *dmreq)
309 memset(iv, 0, cc->iv_size);
310 *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
315 static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
316 struct dm_crypt_request *dmreq)
318 memset(iv, 0, cc->iv_size);
319 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
324 static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
325 struct dm_crypt_request *dmreq)
327 memset(iv, 0, cc->iv_size);
328 /* iv_size is at least of size u64; usually it is 16 bytes */
329 *(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
334 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
335 struct dm_crypt_request *dmreq)
338 * ESSIV encryption of the IV is now handled by the crypto API,
339 * so just pass the plain sector number here.
341 memset(iv, 0, cc->iv_size);
342 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
347 static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
353 if (crypt_integrity_aead(cc))
354 bs = crypto_aead_blocksize(any_tfm_aead(cc));
356 bs = crypto_skcipher_blocksize(any_tfm(cc));
359 /* we need to calculate how far we must shift the sector count
360 * to get the cipher block count, we use this shift in _gen */
362 if (1 << log != bs) {
363 ti->error = "cypher blocksize is not a power of 2";
368 ti->error = "cypher blocksize is > 512";
372 cc->iv_gen_private.benbi.shift = 9 - log;
377 static void crypt_iv_benbi_dtr(struct crypt_config *cc)
381 static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
382 struct dm_crypt_request *dmreq)
386 memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
388 val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
389 put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
394 static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
395 struct dm_crypt_request *dmreq)
397 memset(iv, 0, cc->iv_size);
402 static void crypt_iv_lmk_dtr(struct crypt_config *cc)
404 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
406 if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
407 crypto_free_shash(lmk->hash_tfm);
408 lmk->hash_tfm = NULL;
414 static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
417 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
419 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
420 ti->error = "Unsupported sector size for LMK";
424 lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
425 if (IS_ERR(lmk->hash_tfm)) {
426 ti->error = "Error initializing LMK hash";
427 return PTR_ERR(lmk->hash_tfm);
430 /* No seed in LMK version 2 */
431 if (cc->key_parts == cc->tfms_count) {
436 lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
438 crypt_iv_lmk_dtr(cc);
439 ti->error = "Error kmallocing seed storage in LMK";
446 static int crypt_iv_lmk_init(struct crypt_config *cc)
448 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
449 int subkey_size = cc->key_size / cc->key_parts;
451 /* LMK seed is on the position of LMK_KEYS + 1 key */
453 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
454 crypto_shash_digestsize(lmk->hash_tfm));
459 static int crypt_iv_lmk_wipe(struct crypt_config *cc)
461 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
464 memset(lmk->seed, 0, LMK_SEED_SIZE);
469 static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
470 struct dm_crypt_request *dmreq,
473 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
474 SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
475 struct md5_state md5state;
479 desc->tfm = lmk->hash_tfm;
481 r = crypto_shash_init(desc);
486 r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
491 /* Sector is always 512B, block size 16, add data of blocks 1-31 */
492 r = crypto_shash_update(desc, data + 16, 16 * 31);
496 /* Sector is cropped to 56 bits here */
497 buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
498 buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
499 buf[2] = cpu_to_le32(4024);
501 r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
505 /* No MD5 padding here */
506 r = crypto_shash_export(desc, &md5state);
510 for (i = 0; i < MD5_HASH_WORDS; i++)
511 __cpu_to_le32s(&md5state.hash[i]);
512 memcpy(iv, &md5state.hash, cc->iv_size);
517 static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
518 struct dm_crypt_request *dmreq)
520 struct scatterlist *sg;
524 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
525 sg = crypt_get_sg_data(cc, dmreq->sg_in);
526 src = kmap_atomic(sg_page(sg));
527 r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
530 memset(iv, 0, cc->iv_size);
535 static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
536 struct dm_crypt_request *dmreq)
538 struct scatterlist *sg;
542 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
545 sg = crypt_get_sg_data(cc, dmreq->sg_out);
546 dst = kmap_atomic(sg_page(sg));
547 r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
549 /* Tweak the first block of plaintext sector */
551 crypto_xor(dst + sg->offset, iv, cc->iv_size);
557 static void crypt_iv_tcw_dtr(struct crypt_config *cc)
559 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
561 kzfree(tcw->iv_seed);
563 kzfree(tcw->whitening);
564 tcw->whitening = NULL;
566 if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
567 crypto_free_shash(tcw->crc32_tfm);
568 tcw->crc32_tfm = NULL;
571 static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
574 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
576 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
577 ti->error = "Unsupported sector size for TCW";
581 if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
582 ti->error = "Wrong key size for TCW";
586 tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
587 if (IS_ERR(tcw->crc32_tfm)) {
588 ti->error = "Error initializing CRC32 in TCW";
589 return PTR_ERR(tcw->crc32_tfm);
592 tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
593 tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
594 if (!tcw->iv_seed || !tcw->whitening) {
595 crypt_iv_tcw_dtr(cc);
596 ti->error = "Error allocating seed storage in TCW";
603 static int crypt_iv_tcw_init(struct crypt_config *cc)
605 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
606 int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
608 memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
609 memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
615 static int crypt_iv_tcw_wipe(struct crypt_config *cc)
617 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
619 memset(tcw->iv_seed, 0, cc->iv_size);
620 memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
625 static int crypt_iv_tcw_whitening(struct crypt_config *cc,
626 struct dm_crypt_request *dmreq,
629 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
630 __le64 sector = cpu_to_le64(dmreq->iv_sector);
631 u8 buf[TCW_WHITENING_SIZE];
632 SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
635 /* xor whitening with sector number */
636 crypto_xor_cpy(buf, tcw->whitening, (u8 *)§or, 8);
637 crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)§or, 8);
639 /* calculate crc32 for every 32bit part and xor it */
640 desc->tfm = tcw->crc32_tfm;
641 for (i = 0; i < 4; i++) {
642 r = crypto_shash_init(desc);
645 r = crypto_shash_update(desc, &buf[i * 4], 4);
648 r = crypto_shash_final(desc, &buf[i * 4]);
652 crypto_xor(&buf[0], &buf[12], 4);
653 crypto_xor(&buf[4], &buf[8], 4);
655 /* apply whitening (8 bytes) to whole sector */
656 for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
657 crypto_xor(data + i * 8, buf, 8);
659 memzero_explicit(buf, sizeof(buf));
663 static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
664 struct dm_crypt_request *dmreq)
666 struct scatterlist *sg;
667 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
668 __le64 sector = cpu_to_le64(dmreq->iv_sector);
672 /* Remove whitening from ciphertext */
673 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
674 sg = crypt_get_sg_data(cc, dmreq->sg_in);
675 src = kmap_atomic(sg_page(sg));
676 r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
681 crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)§or, 8);
683 crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)§or,
689 static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
690 struct dm_crypt_request *dmreq)
692 struct scatterlist *sg;
696 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
699 /* Apply whitening on ciphertext */
700 sg = crypt_get_sg_data(cc, dmreq->sg_out);
701 dst = kmap_atomic(sg_page(sg));
702 r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
708 static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
709 struct dm_crypt_request *dmreq)
711 /* Used only for writes, there must be an additional space to store IV */
712 get_random_bytes(iv, cc->iv_size);
716 static int crypt_iv_eboiv_ctr(struct crypt_config *cc, struct dm_target *ti,
719 if (crypt_integrity_aead(cc)) {
720 ti->error = "AEAD transforms not supported for EBOIV";
724 if (crypto_skcipher_blocksize(any_tfm(cc)) != cc->iv_size) {
725 ti->error = "Block size of EBOIV cipher does "
726 "not match IV size of block cipher";
733 static int crypt_iv_eboiv_gen(struct crypt_config *cc, u8 *iv,
734 struct dm_crypt_request *dmreq)
736 u8 buf[MAX_CIPHER_BLOCKSIZE] __aligned(__alignof__(__le64));
737 struct skcipher_request *req;
738 struct scatterlist src, dst;
739 struct crypto_wait wait;
742 req = skcipher_request_alloc(any_tfm(cc), GFP_NOIO);
746 memset(buf, 0, cc->iv_size);
747 *(__le64 *)buf = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
749 sg_init_one(&src, page_address(ZERO_PAGE(0)), cc->iv_size);
750 sg_init_one(&dst, iv, cc->iv_size);
751 skcipher_request_set_crypt(req, &src, &dst, cc->iv_size, buf);
752 skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
753 err = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
754 skcipher_request_free(req);
759 static void crypt_iv_elephant_dtr(struct crypt_config *cc)
761 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
763 crypto_free_skcipher(elephant->tfm);
764 elephant->tfm = NULL;
767 static int crypt_iv_elephant_ctr(struct crypt_config *cc, struct dm_target *ti,
770 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
773 elephant->tfm = crypto_alloc_skcipher("ecb(aes)", 0, 0);
774 if (IS_ERR(elephant->tfm)) {
775 r = PTR_ERR(elephant->tfm);
776 elephant->tfm = NULL;
780 r = crypt_iv_eboiv_ctr(cc, ti, NULL);
782 crypt_iv_elephant_dtr(cc);
786 static void diffuser_disk_to_cpu(u32 *d, size_t n)
788 #ifndef __LITTLE_ENDIAN
791 for (i = 0; i < n; i++)
792 d[i] = le32_to_cpu((__le32)d[i]);
796 static void diffuser_cpu_to_disk(__le32 *d, size_t n)
798 #ifndef __LITTLE_ENDIAN
801 for (i = 0; i < n; i++)
802 d[i] = cpu_to_le32((u32)d[i]);
806 static void diffuser_a_decrypt(u32 *d, size_t n)
810 for (i = 0; i < 5; i++) {
815 while (i1 < (n - 1)) {
816 d[i1] += d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
822 d[i1] += d[i2] ^ d[i3];
828 d[i1] += d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
831 d[i1] += d[i2] ^ d[i3];
837 static void diffuser_a_encrypt(u32 *d, size_t n)
841 for (i = 0; i < 5; i++) {
847 d[i1] -= d[i2] ^ d[i3];
850 d[i1] -= d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
856 d[i1] -= d[i2] ^ d[i3];
862 d[i1] -= d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
868 static void diffuser_b_decrypt(u32 *d, size_t n)
872 for (i = 0; i < 3; i++) {
877 while (i1 < (n - 1)) {
878 d[i1] += d[i2] ^ d[i3];
881 d[i1] += d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
887 d[i1] += d[i2] ^ d[i3];
893 d[i1] += d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
899 static void diffuser_b_encrypt(u32 *d, size_t n)
903 for (i = 0; i < 3; i++) {
909 d[i1] -= d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
915 d[i1] -= d[i2] ^ d[i3];
921 d[i1] -= d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
924 d[i1] -= d[i2] ^ d[i3];
930 static int crypt_iv_elephant(struct crypt_config *cc, struct dm_crypt_request *dmreq)
932 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
933 u8 *es, *ks, *data, *data2, *data_offset;
934 struct skcipher_request *req;
935 struct scatterlist *sg, *sg2, src, dst;
936 struct crypto_wait wait;
939 req = skcipher_request_alloc(elephant->tfm, GFP_NOIO);
940 es = kzalloc(16, GFP_NOIO); /* Key for AES */
941 ks = kzalloc(32, GFP_NOIO); /* Elephant sector key */
943 if (!req || !es || !ks) {
948 *(__le64 *)es = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
951 sg_init_one(&src, es, 16);
952 sg_init_one(&dst, ks, 16);
953 skcipher_request_set_crypt(req, &src, &dst, 16, NULL);
954 skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
955 r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
961 sg_init_one(&dst, &ks[16], 16);
962 r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
966 sg = crypt_get_sg_data(cc, dmreq->sg_out);
967 data = kmap_atomic(sg_page(sg));
968 data_offset = data + sg->offset;
970 /* Cannot modify original bio, copy to sg_out and apply Elephant to it */
971 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
972 sg2 = crypt_get_sg_data(cc, dmreq->sg_in);
973 data2 = kmap_atomic(sg_page(sg2));
974 memcpy(data_offset, data2 + sg2->offset, cc->sector_size);
975 kunmap_atomic(data2);
978 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
979 diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
980 diffuser_b_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
981 diffuser_a_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
982 diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
985 for (i = 0; i < (cc->sector_size / 32); i++)
986 crypto_xor(data_offset + i * 32, ks, 32);
988 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
989 diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
990 diffuser_a_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
991 diffuser_b_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
992 diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
999 skcipher_request_free(req);
1003 static int crypt_iv_elephant_gen(struct crypt_config *cc, u8 *iv,
1004 struct dm_crypt_request *dmreq)
1008 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
1009 r = crypt_iv_elephant(cc, dmreq);
1014 return crypt_iv_eboiv_gen(cc, iv, dmreq);
1017 static int crypt_iv_elephant_post(struct crypt_config *cc, u8 *iv,
1018 struct dm_crypt_request *dmreq)
1020 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
1021 return crypt_iv_elephant(cc, dmreq);
1026 static int crypt_iv_elephant_init(struct crypt_config *cc)
1028 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1029 int key_offset = cc->key_size - cc->key_extra_size;
1031 return crypto_skcipher_setkey(elephant->tfm, &cc->key[key_offset], cc->key_extra_size);
1034 static int crypt_iv_elephant_wipe(struct crypt_config *cc)
1036 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1037 u8 key[ELEPHANT_MAX_KEY_SIZE];
1039 memset(key, 0, cc->key_extra_size);
1040 return crypto_skcipher_setkey(elephant->tfm, key, cc->key_extra_size);
1043 static const struct crypt_iv_operations crypt_iv_plain_ops = {
1044 .generator = crypt_iv_plain_gen
1047 static const struct crypt_iv_operations crypt_iv_plain64_ops = {
1048 .generator = crypt_iv_plain64_gen
1051 static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
1052 .generator = crypt_iv_plain64be_gen
1055 static const struct crypt_iv_operations crypt_iv_essiv_ops = {
1056 .generator = crypt_iv_essiv_gen
1059 static const struct crypt_iv_operations crypt_iv_benbi_ops = {
1060 .ctr = crypt_iv_benbi_ctr,
1061 .dtr = crypt_iv_benbi_dtr,
1062 .generator = crypt_iv_benbi_gen
1065 static const struct crypt_iv_operations crypt_iv_null_ops = {
1066 .generator = crypt_iv_null_gen
1069 static const struct crypt_iv_operations crypt_iv_lmk_ops = {
1070 .ctr = crypt_iv_lmk_ctr,
1071 .dtr = crypt_iv_lmk_dtr,
1072 .init = crypt_iv_lmk_init,
1073 .wipe = crypt_iv_lmk_wipe,
1074 .generator = crypt_iv_lmk_gen,
1075 .post = crypt_iv_lmk_post
1078 static const struct crypt_iv_operations crypt_iv_tcw_ops = {
1079 .ctr = crypt_iv_tcw_ctr,
1080 .dtr = crypt_iv_tcw_dtr,
1081 .init = crypt_iv_tcw_init,
1082 .wipe = crypt_iv_tcw_wipe,
1083 .generator = crypt_iv_tcw_gen,
1084 .post = crypt_iv_tcw_post
1087 static struct crypt_iv_operations crypt_iv_random_ops = {
1088 .generator = crypt_iv_random_gen
1091 static struct crypt_iv_operations crypt_iv_eboiv_ops = {
1092 .ctr = crypt_iv_eboiv_ctr,
1093 .generator = crypt_iv_eboiv_gen
1096 static struct crypt_iv_operations crypt_iv_elephant_ops = {
1097 .ctr = crypt_iv_elephant_ctr,
1098 .dtr = crypt_iv_elephant_dtr,
1099 .init = crypt_iv_elephant_init,
1100 .wipe = crypt_iv_elephant_wipe,
1101 .generator = crypt_iv_elephant_gen,
1102 .post = crypt_iv_elephant_post
1106 * Integrity extensions
1108 static bool crypt_integrity_aead(struct crypt_config *cc)
1110 return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
1113 static bool crypt_integrity_hmac(struct crypt_config *cc)
1115 return crypt_integrity_aead(cc) && cc->key_mac_size;
1118 /* Get sg containing data */
1119 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
1120 struct scatterlist *sg)
1122 if (unlikely(crypt_integrity_aead(cc)))
1128 static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
1130 struct bio_integrity_payload *bip;
1131 unsigned int tag_len;
1134 if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
1137 bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
1139 return PTR_ERR(bip);
1141 tag_len = io->cc->on_disk_tag_size * (bio_sectors(bio) >> io->cc->sector_shift);
1143 bip->bip_iter.bi_size = tag_len;
1144 bip->bip_iter.bi_sector = io->cc->start + io->sector;
1146 ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
1147 tag_len, offset_in_page(io->integrity_metadata));
1148 if (unlikely(ret != tag_len))
1154 static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
1156 #ifdef CONFIG_BLK_DEV_INTEGRITY
1157 struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
1158 struct mapped_device *md = dm_table_get_md(ti->table);
1160 /* From now we require underlying device with our integrity profile */
1161 if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
1162 ti->error = "Integrity profile not supported.";
1166 if (bi->tag_size != cc->on_disk_tag_size ||
1167 bi->tuple_size != cc->on_disk_tag_size) {
1168 ti->error = "Integrity profile tag size mismatch.";
1171 if (1 << bi->interval_exp != cc->sector_size) {
1172 ti->error = "Integrity profile sector size mismatch.";
1176 if (crypt_integrity_aead(cc)) {
1177 cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
1178 DMDEBUG("%s: Integrity AEAD, tag size %u, IV size %u.", dm_device_name(md),
1179 cc->integrity_tag_size, cc->integrity_iv_size);
1181 if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
1182 ti->error = "Integrity AEAD auth tag size is not supported.";
1185 } else if (cc->integrity_iv_size)
1186 DMDEBUG("%s: Additional per-sector space %u bytes for IV.", dm_device_name(md),
1187 cc->integrity_iv_size);
1189 if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
1190 ti->error = "Not enough space for integrity tag in the profile.";
1196 ti->error = "Integrity profile not supported.";
1201 static void crypt_convert_init(struct crypt_config *cc,
1202 struct convert_context *ctx,
1203 struct bio *bio_out, struct bio *bio_in,
1206 ctx->bio_in = bio_in;
1207 ctx->bio_out = bio_out;
1209 ctx->iter_in = bio_in->bi_iter;
1211 ctx->iter_out = bio_out->bi_iter;
1212 ctx->cc_sector = sector + cc->iv_offset;
1213 init_completion(&ctx->restart);
1216 static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
1219 return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
1222 static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
1224 return (void *)((char *)dmreq - cc->dmreq_start);
1227 static u8 *iv_of_dmreq(struct crypt_config *cc,
1228 struct dm_crypt_request *dmreq)
1230 if (crypt_integrity_aead(cc))
1231 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1232 crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
1234 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1235 crypto_skcipher_alignmask(any_tfm(cc)) + 1);
1238 static u8 *org_iv_of_dmreq(struct crypt_config *cc,
1239 struct dm_crypt_request *dmreq)
1241 return iv_of_dmreq(cc, dmreq) + cc->iv_size;
1244 static __le64 *org_sector_of_dmreq(struct crypt_config *cc,
1245 struct dm_crypt_request *dmreq)
1247 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
1248 return (__le64 *) ptr;
1251 static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
1252 struct dm_crypt_request *dmreq)
1254 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
1255 cc->iv_size + sizeof(uint64_t);
1256 return (unsigned int*)ptr;
1259 static void *tag_from_dmreq(struct crypt_config *cc,
1260 struct dm_crypt_request *dmreq)
1262 struct convert_context *ctx = dmreq->ctx;
1263 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1265 return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
1266 cc->on_disk_tag_size];
1269 static void *iv_tag_from_dmreq(struct crypt_config *cc,
1270 struct dm_crypt_request *dmreq)
1272 return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
1275 static int crypt_convert_block_aead(struct crypt_config *cc,
1276 struct convert_context *ctx,
1277 struct aead_request *req,
1278 unsigned int tag_offset)
1280 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1281 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1282 struct dm_crypt_request *dmreq;
1283 u8 *iv, *org_iv, *tag_iv, *tag;
1287 BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
1289 /* Reject unexpected unaligned bio. */
1290 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1293 dmreq = dmreq_of_req(cc, req);
1294 dmreq->iv_sector = ctx->cc_sector;
1295 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1296 dmreq->iv_sector >>= cc->sector_shift;
1299 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1301 sector = org_sector_of_dmreq(cc, dmreq);
1302 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1304 iv = iv_of_dmreq(cc, dmreq);
1305 org_iv = org_iv_of_dmreq(cc, dmreq);
1306 tag = tag_from_dmreq(cc, dmreq);
1307 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1310 * |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1311 * | (authenticated) | (auth+encryption) | |
1312 * | sector_LE | IV | sector in/out | tag in/out |
1314 sg_init_table(dmreq->sg_in, 4);
1315 sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
1316 sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
1317 sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1318 sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
1320 sg_init_table(dmreq->sg_out, 4);
1321 sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
1322 sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
1323 sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1324 sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
1326 if (cc->iv_gen_ops) {
1327 /* For READs use IV stored in integrity metadata */
1328 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1329 memcpy(org_iv, tag_iv, cc->iv_size);
1331 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1334 /* Store generated IV in integrity metadata */
1335 if (cc->integrity_iv_size)
1336 memcpy(tag_iv, org_iv, cc->iv_size);
1338 /* Working copy of IV, to be modified in crypto API */
1339 memcpy(iv, org_iv, cc->iv_size);
1342 aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
1343 if (bio_data_dir(ctx->bio_in) == WRITE) {
1344 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1345 cc->sector_size, iv);
1346 r = crypto_aead_encrypt(req);
1347 if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
1348 memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
1349 cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
1351 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1352 cc->sector_size + cc->integrity_tag_size, iv);
1353 r = crypto_aead_decrypt(req);
1356 if (r == -EBADMSG) {
1357 char b[BDEVNAME_SIZE];
1358 DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx->bio_in, b),
1359 (unsigned long long)le64_to_cpu(*sector));
1362 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1363 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1365 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1366 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1371 static int crypt_convert_block_skcipher(struct crypt_config *cc,
1372 struct convert_context *ctx,
1373 struct skcipher_request *req,
1374 unsigned int tag_offset)
1376 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1377 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1378 struct scatterlist *sg_in, *sg_out;
1379 struct dm_crypt_request *dmreq;
1380 u8 *iv, *org_iv, *tag_iv;
1384 /* Reject unexpected unaligned bio. */
1385 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1388 dmreq = dmreq_of_req(cc, req);
1389 dmreq->iv_sector = ctx->cc_sector;
1390 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1391 dmreq->iv_sector >>= cc->sector_shift;
1394 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1396 iv = iv_of_dmreq(cc, dmreq);
1397 org_iv = org_iv_of_dmreq(cc, dmreq);
1398 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1400 sector = org_sector_of_dmreq(cc, dmreq);
1401 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1403 /* For skcipher we use only the first sg item */
1404 sg_in = &dmreq->sg_in[0];
1405 sg_out = &dmreq->sg_out[0];
1407 sg_init_table(sg_in, 1);
1408 sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1410 sg_init_table(sg_out, 1);
1411 sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1413 if (cc->iv_gen_ops) {
1414 /* For READs use IV stored in integrity metadata */
1415 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1416 memcpy(org_iv, tag_iv, cc->integrity_iv_size);
1418 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1421 /* Data can be already preprocessed in generator */
1422 if (test_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags))
1424 /* Store generated IV in integrity metadata */
1425 if (cc->integrity_iv_size)
1426 memcpy(tag_iv, org_iv, cc->integrity_iv_size);
1428 /* Working copy of IV, to be modified in crypto API */
1429 memcpy(iv, org_iv, cc->iv_size);
1432 skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
1434 if (bio_data_dir(ctx->bio_in) == WRITE)
1435 r = crypto_skcipher_encrypt(req);
1437 r = crypto_skcipher_decrypt(req);
1439 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1440 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1442 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1443 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1448 static void kcryptd_async_done(struct crypto_async_request *async_req,
1451 static void crypt_alloc_req_skcipher(struct crypt_config *cc,
1452 struct convert_context *ctx)
1454 unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
1457 ctx->r.req = mempool_alloc(&cc->req_pool, GFP_NOIO);
1459 skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
1462 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1463 * requests if driver request queue is full.
1465 skcipher_request_set_callback(ctx->r.req,
1466 CRYPTO_TFM_REQ_MAY_BACKLOG,
1467 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
1470 static void crypt_alloc_req_aead(struct crypt_config *cc,
1471 struct convert_context *ctx)
1473 if (!ctx->r.req_aead)
1474 ctx->r.req_aead = mempool_alloc(&cc->req_pool, GFP_NOIO);
1476 aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
1479 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1480 * requests if driver request queue is full.
1482 aead_request_set_callback(ctx->r.req_aead,
1483 CRYPTO_TFM_REQ_MAY_BACKLOG,
1484 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
1487 static void crypt_alloc_req(struct crypt_config *cc,
1488 struct convert_context *ctx)
1490 if (crypt_integrity_aead(cc))
1491 crypt_alloc_req_aead(cc, ctx);
1493 crypt_alloc_req_skcipher(cc, ctx);
1496 static void crypt_free_req_skcipher(struct crypt_config *cc,
1497 struct skcipher_request *req, struct bio *base_bio)
1499 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1501 if ((struct skcipher_request *)(io + 1) != req)
1502 mempool_free(req, &cc->req_pool);
1505 static void crypt_free_req_aead(struct crypt_config *cc,
1506 struct aead_request *req, struct bio *base_bio)
1508 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1510 if ((struct aead_request *)(io + 1) != req)
1511 mempool_free(req, &cc->req_pool);
1514 static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
1516 if (crypt_integrity_aead(cc))
1517 crypt_free_req_aead(cc, req, base_bio);
1519 crypt_free_req_skcipher(cc, req, base_bio);
1523 * Encrypt / decrypt data from one bio to another one (can be the same one)
1525 static blk_status_t crypt_convert(struct crypt_config *cc,
1526 struct convert_context *ctx)
1528 unsigned int tag_offset = 0;
1529 unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
1532 atomic_set(&ctx->cc_pending, 1);
1534 while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
1536 crypt_alloc_req(cc, ctx);
1537 atomic_inc(&ctx->cc_pending);
1539 if (crypt_integrity_aead(cc))
1540 r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
1542 r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
1546 * The request was queued by a crypto driver
1547 * but the driver request queue is full, let's wait.
1550 wait_for_completion(&ctx->restart);
1551 reinit_completion(&ctx->restart);
1554 * The request is queued and processed asynchronously,
1555 * completion function kcryptd_async_done() will be called.
1559 ctx->cc_sector += sector_step;
1563 * The request was already processed (synchronously).
1566 atomic_dec(&ctx->cc_pending);
1567 ctx->cc_sector += sector_step;
1572 * There was a data integrity error.
1575 atomic_dec(&ctx->cc_pending);
1576 return BLK_STS_PROTECTION;
1578 * There was an error while processing the request.
1581 atomic_dec(&ctx->cc_pending);
1582 return BLK_STS_IOERR;
1589 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
1592 * Generate a new unfragmented bio with the given size
1593 * This should never violate the device limitations (but only because
1594 * max_segment_size is being constrained to PAGE_SIZE).
1596 * This function may be called concurrently. If we allocate from the mempool
1597 * concurrently, there is a possibility of deadlock. For example, if we have
1598 * mempool of 256 pages, two processes, each wanting 256, pages allocate from
1599 * the mempool concurrently, it may deadlock in a situation where both processes
1600 * have allocated 128 pages and the mempool is exhausted.
1602 * In order to avoid this scenario we allocate the pages under a mutex.
1604 * In order to not degrade performance with excessive locking, we try
1605 * non-blocking allocations without a mutex first but on failure we fallback
1606 * to blocking allocations with a mutex.
1608 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
1610 struct crypt_config *cc = io->cc;
1612 unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1613 gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
1614 unsigned i, len, remaining_size;
1618 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1619 mutex_lock(&cc->bio_alloc_lock);
1621 clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, &cc->bs);
1625 clone_init(io, clone);
1627 remaining_size = size;
1629 for (i = 0; i < nr_iovecs; i++) {
1630 page = mempool_alloc(&cc->page_pool, gfp_mask);
1632 crypt_free_buffer_pages(cc, clone);
1634 gfp_mask |= __GFP_DIRECT_RECLAIM;
1638 len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
1640 bio_add_page(clone, page, len, 0);
1642 remaining_size -= len;
1645 /* Allocate space for integrity tags */
1646 if (dm_crypt_integrity_io_alloc(io, clone)) {
1647 crypt_free_buffer_pages(cc, clone);
1652 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1653 mutex_unlock(&cc->bio_alloc_lock);
1658 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1661 struct bvec_iter_all iter_all;
1663 bio_for_each_segment_all(bv, clone, iter_all) {
1664 BUG_ON(!bv->bv_page);
1665 mempool_free(bv->bv_page, &cc->page_pool);
1669 static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1670 struct bio *bio, sector_t sector)
1674 io->sector = sector;
1676 io->ctx.r.req = NULL;
1677 io->integrity_metadata = NULL;
1678 io->integrity_metadata_from_pool = false;
1679 atomic_set(&io->io_pending, 0);
1682 static void crypt_inc_pending(struct dm_crypt_io *io)
1684 atomic_inc(&io->io_pending);
1688 * One of the bios was finished. Check for completion of
1689 * the whole request and correctly clean up the buffer.
1691 static void crypt_dec_pending(struct dm_crypt_io *io)
1693 struct crypt_config *cc = io->cc;
1694 struct bio *base_bio = io->base_bio;
1695 blk_status_t error = io->error;
1697 if (!atomic_dec_and_test(&io->io_pending))
1701 crypt_free_req(cc, io->ctx.r.req, base_bio);
1703 if (unlikely(io->integrity_metadata_from_pool))
1704 mempool_free(io->integrity_metadata, &io->cc->tag_pool);
1706 kfree(io->integrity_metadata);
1708 base_bio->bi_status = error;
1709 bio_endio(base_bio);
1713 * kcryptd/kcryptd_io:
1715 * Needed because it would be very unwise to do decryption in an
1716 * interrupt context.
1718 * kcryptd performs the actual encryption or decryption.
1720 * kcryptd_io performs the IO submission.
1722 * They must be separated as otherwise the final stages could be
1723 * starved by new requests which can block in the first stages due
1724 * to memory allocation.
1726 * The work is done per CPU global for all dm-crypt instances.
1727 * They should not depend on each other and do not block.
1729 static void crypt_endio(struct bio *clone)
1731 struct dm_crypt_io *io = clone->bi_private;
1732 struct crypt_config *cc = io->cc;
1733 unsigned rw = bio_data_dir(clone);
1737 * free the processed pages
1740 crypt_free_buffer_pages(cc, clone);
1742 error = clone->bi_status;
1745 if (rw == READ && !error) {
1746 kcryptd_queue_crypt(io);
1750 if (unlikely(error))
1753 crypt_dec_pending(io);
1756 static void clone_init(struct dm_crypt_io *io, struct bio *clone)
1758 struct crypt_config *cc = io->cc;
1760 clone->bi_private = io;
1761 clone->bi_end_io = crypt_endio;
1762 bio_set_dev(clone, cc->dev->bdev);
1763 clone->bi_opf = io->base_bio->bi_opf;
1766 static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
1768 struct crypt_config *cc = io->cc;
1772 * We need the original biovec array in order to decrypt
1773 * the whole bio data *afterwards* -- thanks to immutable
1774 * biovecs we don't need to worry about the block layer
1775 * modifying the biovec array; so leverage bio_clone_fast().
1777 clone = bio_clone_fast(io->base_bio, gfp, &cc->bs);
1781 crypt_inc_pending(io);
1783 clone_init(io, clone);
1784 clone->bi_iter.bi_sector = cc->start + io->sector;
1786 if (dm_crypt_integrity_io_alloc(io, clone)) {
1787 crypt_dec_pending(io);
1792 generic_make_request(clone);
1796 static void kcryptd_io_read_work(struct work_struct *work)
1798 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1800 crypt_inc_pending(io);
1801 if (kcryptd_io_read(io, GFP_NOIO))
1802 io->error = BLK_STS_RESOURCE;
1803 crypt_dec_pending(io);
1806 static void kcryptd_queue_read(struct dm_crypt_io *io)
1808 struct crypt_config *cc = io->cc;
1810 INIT_WORK(&io->work, kcryptd_io_read_work);
1811 queue_work(cc->io_queue, &io->work);
1814 static void kcryptd_io_write(struct dm_crypt_io *io)
1816 struct bio *clone = io->ctx.bio_out;
1818 generic_make_request(clone);
1821 #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1823 static int dmcrypt_write(void *data)
1825 struct crypt_config *cc = data;
1826 struct dm_crypt_io *io;
1829 struct rb_root write_tree;
1830 struct blk_plug plug;
1832 spin_lock_irq(&cc->write_thread_lock);
1835 if (!RB_EMPTY_ROOT(&cc->write_tree))
1838 set_current_state(TASK_INTERRUPTIBLE);
1840 spin_unlock_irq(&cc->write_thread_lock);
1842 if (unlikely(kthread_should_stop())) {
1843 set_current_state(TASK_RUNNING);
1849 set_current_state(TASK_RUNNING);
1850 spin_lock_irq(&cc->write_thread_lock);
1851 goto continue_locked;
1854 write_tree = cc->write_tree;
1855 cc->write_tree = RB_ROOT;
1856 spin_unlock_irq(&cc->write_thread_lock);
1858 BUG_ON(rb_parent(write_tree.rb_node));
1861 * Note: we cannot walk the tree here with rb_next because
1862 * the structures may be freed when kcryptd_io_write is called.
1864 blk_start_plug(&plug);
1866 io = crypt_io_from_node(rb_first(&write_tree));
1867 rb_erase(&io->rb_node, &write_tree);
1868 kcryptd_io_write(io);
1869 } while (!RB_EMPTY_ROOT(&write_tree));
1870 blk_finish_plug(&plug);
1875 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
1877 struct bio *clone = io->ctx.bio_out;
1878 struct crypt_config *cc = io->cc;
1879 unsigned long flags;
1881 struct rb_node **rbp, *parent;
1883 if (unlikely(io->error)) {
1884 crypt_free_buffer_pages(cc, clone);
1886 crypt_dec_pending(io);
1890 /* crypt_convert should have filled the clone bio */
1891 BUG_ON(io->ctx.iter_out.bi_size);
1893 clone->bi_iter.bi_sector = cc->start + io->sector;
1895 if (likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) {
1896 generic_make_request(clone);
1900 spin_lock_irqsave(&cc->write_thread_lock, flags);
1901 if (RB_EMPTY_ROOT(&cc->write_tree))
1902 wake_up_process(cc->write_thread);
1903 rbp = &cc->write_tree.rb_node;
1905 sector = io->sector;
1908 if (sector < crypt_io_from_node(parent)->sector)
1909 rbp = &(*rbp)->rb_left;
1911 rbp = &(*rbp)->rb_right;
1913 rb_link_node(&io->rb_node, parent, rbp);
1914 rb_insert_color(&io->rb_node, &cc->write_tree);
1915 spin_unlock_irqrestore(&cc->write_thread_lock, flags);
1918 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
1920 struct crypt_config *cc = io->cc;
1923 sector_t sector = io->sector;
1927 * Prevent io from disappearing until this function completes.
1929 crypt_inc_pending(io);
1930 crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
1932 clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
1933 if (unlikely(!clone)) {
1934 io->error = BLK_STS_IOERR;
1938 io->ctx.bio_out = clone;
1939 io->ctx.iter_out = clone->bi_iter;
1941 sector += bio_sectors(clone);
1943 crypt_inc_pending(io);
1944 r = crypt_convert(cc, &io->ctx);
1947 crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
1949 /* Encryption was already finished, submit io now */
1950 if (crypt_finished) {
1951 kcryptd_crypt_write_io_submit(io, 0);
1952 io->sector = sector;
1956 crypt_dec_pending(io);
1959 static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
1961 crypt_dec_pending(io);
1964 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
1966 struct crypt_config *cc = io->cc;
1969 crypt_inc_pending(io);
1971 crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
1974 r = crypt_convert(cc, &io->ctx);
1978 if (atomic_dec_and_test(&io->ctx.cc_pending))
1979 kcryptd_crypt_read_done(io);
1981 crypt_dec_pending(io);
1984 static void kcryptd_async_done(struct crypto_async_request *async_req,
1987 struct dm_crypt_request *dmreq = async_req->data;
1988 struct convert_context *ctx = dmreq->ctx;
1989 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1990 struct crypt_config *cc = io->cc;
1993 * A request from crypto driver backlog is going to be processed now,
1994 * finish the completion and continue in crypt_convert().
1995 * (Callback will be called for the second time for this request.)
1997 if (error == -EINPROGRESS) {
1998 complete(&ctx->restart);
2002 if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
2003 error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
2005 if (error == -EBADMSG) {
2006 char b[BDEVNAME_SIZE];
2007 DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx->bio_in, b),
2008 (unsigned long long)le64_to_cpu(*org_sector_of_dmreq(cc, dmreq)));
2009 io->error = BLK_STS_PROTECTION;
2010 } else if (error < 0)
2011 io->error = BLK_STS_IOERR;
2013 crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
2015 if (!atomic_dec_and_test(&ctx->cc_pending))
2018 if (bio_data_dir(io->base_bio) == READ)
2019 kcryptd_crypt_read_done(io);
2021 kcryptd_crypt_write_io_submit(io, 1);
2024 static void kcryptd_crypt(struct work_struct *work)
2026 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2028 if (bio_data_dir(io->base_bio) == READ)
2029 kcryptd_crypt_read_convert(io);
2031 kcryptd_crypt_write_convert(io);
2034 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
2036 struct crypt_config *cc = io->cc;
2038 INIT_WORK(&io->work, kcryptd_crypt);
2039 queue_work(cc->crypt_queue, &io->work);
2042 static void crypt_free_tfms_aead(struct crypt_config *cc)
2044 if (!cc->cipher_tfm.tfms_aead)
2047 if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2048 crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
2049 cc->cipher_tfm.tfms_aead[0] = NULL;
2052 kfree(cc->cipher_tfm.tfms_aead);
2053 cc->cipher_tfm.tfms_aead = NULL;
2056 static void crypt_free_tfms_skcipher(struct crypt_config *cc)
2060 if (!cc->cipher_tfm.tfms)
2063 for (i = 0; i < cc->tfms_count; i++)
2064 if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
2065 crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
2066 cc->cipher_tfm.tfms[i] = NULL;
2069 kfree(cc->cipher_tfm.tfms);
2070 cc->cipher_tfm.tfms = NULL;
2073 static void crypt_free_tfms(struct crypt_config *cc)
2075 if (crypt_integrity_aead(cc))
2076 crypt_free_tfms_aead(cc);
2078 crypt_free_tfms_skcipher(cc);
2081 static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
2086 cc->cipher_tfm.tfms = kcalloc(cc->tfms_count,
2087 sizeof(struct crypto_skcipher *),
2089 if (!cc->cipher_tfm.tfms)
2092 for (i = 0; i < cc->tfms_count; i++) {
2093 cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0, 0);
2094 if (IS_ERR(cc->cipher_tfm.tfms[i])) {
2095 err = PTR_ERR(cc->cipher_tfm.tfms[i]);
2096 crypt_free_tfms(cc);
2102 * dm-crypt performance can vary greatly depending on which crypto
2103 * algorithm implementation is used. Help people debug performance
2104 * problems by logging the ->cra_driver_name.
2106 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2107 crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
2111 static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
2115 cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
2116 if (!cc->cipher_tfm.tfms)
2119 cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0, 0);
2120 if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2121 err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
2122 crypt_free_tfms(cc);
2126 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2127 crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
2131 static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
2133 if (crypt_integrity_aead(cc))
2134 return crypt_alloc_tfms_aead(cc, ciphermode);
2136 return crypt_alloc_tfms_skcipher(cc, ciphermode);
2139 static unsigned crypt_subkey_size(struct crypt_config *cc)
2141 return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
2144 static unsigned crypt_authenckey_size(struct crypt_config *cc)
2146 return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
2150 * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
2151 * the key must be for some reason in special format.
2152 * This funcion converts cc->key to this special format.
2154 static void crypt_copy_authenckey(char *p, const void *key,
2155 unsigned enckeylen, unsigned authkeylen)
2157 struct crypto_authenc_key_param *param;
2160 rta = (struct rtattr *)p;
2161 param = RTA_DATA(rta);
2162 param->enckeylen = cpu_to_be32(enckeylen);
2163 rta->rta_len = RTA_LENGTH(sizeof(*param));
2164 rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
2165 p += RTA_SPACE(sizeof(*param));
2166 memcpy(p, key + enckeylen, authkeylen);
2168 memcpy(p, key, enckeylen);
2171 static int crypt_setkey(struct crypt_config *cc)
2173 unsigned subkey_size;
2176 /* Ignore extra keys (which are used for IV etc) */
2177 subkey_size = crypt_subkey_size(cc);
2179 if (crypt_integrity_hmac(cc)) {
2180 if (subkey_size < cc->key_mac_size)
2183 crypt_copy_authenckey(cc->authenc_key, cc->key,
2184 subkey_size - cc->key_mac_size,
2188 for (i = 0; i < cc->tfms_count; i++) {
2189 if (crypt_integrity_hmac(cc))
2190 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2191 cc->authenc_key, crypt_authenckey_size(cc));
2192 else if (crypt_integrity_aead(cc))
2193 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2194 cc->key + (i * subkey_size),
2197 r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
2198 cc->key + (i * subkey_size),
2204 if (crypt_integrity_hmac(cc))
2205 memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
2212 static bool contains_whitespace(const char *str)
2215 if (isspace(*str++))
2220 static int set_key_user(struct crypt_config *cc, struct key *key)
2222 const struct user_key_payload *ukp;
2224 ukp = user_key_payload_locked(key);
2226 return -EKEYREVOKED;
2228 if (cc->key_size != ukp->datalen)
2231 memcpy(cc->key, ukp->data, cc->key_size);
2236 #if defined(CONFIG_ENCRYPTED_KEYS) || defined(CONFIG_ENCRYPTED_KEYS_MODULE)
2237 static int set_key_encrypted(struct crypt_config *cc, struct key *key)
2239 const struct encrypted_key_payload *ekp;
2241 ekp = key->payload.data[0];
2243 return -EKEYREVOKED;
2245 if (cc->key_size != ekp->decrypted_datalen)
2248 memcpy(cc->key, ekp->decrypted_data, cc->key_size);
2252 #endif /* CONFIG_ENCRYPTED_KEYS */
2254 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2256 char *new_key_string, *key_desc;
2258 struct key_type *type;
2260 int (*set_key)(struct crypt_config *cc, struct key *key);
2263 * Reject key_string with whitespace. dm core currently lacks code for
2264 * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2266 if (contains_whitespace(key_string)) {
2267 DMERR("whitespace chars not allowed in key string");
2271 /* look for next ':' separating key_type from key_description */
2272 key_desc = strpbrk(key_string, ":");
2273 if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2276 if (!strncmp(key_string, "logon:", key_desc - key_string + 1)) {
2277 type = &key_type_logon;
2278 set_key = set_key_user;
2279 } else if (!strncmp(key_string, "user:", key_desc - key_string + 1)) {
2280 type = &key_type_user;
2281 set_key = set_key_user;
2282 #if defined(CONFIG_ENCRYPTED_KEYS) || defined(CONFIG_ENCRYPTED_KEYS_MODULE)
2283 } else if (!strncmp(key_string, "encrypted:", key_desc - key_string + 1)) {
2284 type = &key_type_encrypted;
2285 set_key = set_key_encrypted;
2291 new_key_string = kstrdup(key_string, GFP_KERNEL);
2292 if (!new_key_string)
2295 key = request_key(type, key_desc + 1, NULL);
2297 kzfree(new_key_string);
2298 return PTR_ERR(key);
2301 down_read(&key->sem);
2303 ret = set_key(cc, key);
2307 kzfree(new_key_string);
2314 /* clear the flag since following operations may invalidate previously valid key */
2315 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2317 ret = crypt_setkey(cc);
2320 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2321 kzfree(cc->key_string);
2322 cc->key_string = new_key_string;
2324 kzfree(new_key_string);
2329 static int get_key_size(char **key_string)
2334 if (*key_string[0] != ':')
2335 return strlen(*key_string) >> 1;
2337 /* look for next ':' in key string */
2338 colon = strpbrk(*key_string + 1, ":");
2342 if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2345 *key_string = colon;
2347 /* remaining key string should be :<logon|user>:<key_desc> */
2354 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2359 static int get_key_size(char **key_string)
2361 return (*key_string[0] == ':') ? -EINVAL : strlen(*key_string) >> 1;
2364 #endif /* CONFIG_KEYS */
2366 static int crypt_set_key(struct crypt_config *cc, char *key)
2369 int key_string_len = strlen(key);
2371 /* Hyphen (which gives a key_size of zero) means there is no key. */
2372 if (!cc->key_size && strcmp(key, "-"))
2375 /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2376 if (key[0] == ':') {
2377 r = crypt_set_keyring_key(cc, key + 1);
2381 /* clear the flag since following operations may invalidate previously valid key */
2382 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2384 /* wipe references to any kernel keyring key */
2385 kzfree(cc->key_string);
2386 cc->key_string = NULL;
2388 /* Decode key from its hex representation. */
2389 if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
2392 r = crypt_setkey(cc);
2394 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2397 /* Hex key string not needed after here, so wipe it. */
2398 memset(key, '0', key_string_len);
2403 static int crypt_wipe_key(struct crypt_config *cc)
2407 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2408 get_random_bytes(&cc->key, cc->key_size);
2410 /* Wipe IV private keys */
2411 if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
2412 r = cc->iv_gen_ops->wipe(cc);
2417 kzfree(cc->key_string);
2418 cc->key_string = NULL;
2419 r = crypt_setkey(cc);
2420 memset(&cc->key, 0, cc->key_size * sizeof(u8));
2425 static void crypt_calculate_pages_per_client(void)
2427 unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
2429 if (!dm_crypt_clients_n)
2432 pages /= dm_crypt_clients_n;
2433 if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
2434 pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
2435 dm_crypt_pages_per_client = pages;
2438 static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
2440 struct crypt_config *cc = pool_data;
2443 if (unlikely(percpu_counter_compare(&cc->n_allocated_pages, dm_crypt_pages_per_client) >= 0) &&
2444 likely(gfp_mask & __GFP_NORETRY))
2447 page = alloc_page(gfp_mask);
2448 if (likely(page != NULL))
2449 percpu_counter_add(&cc->n_allocated_pages, 1);
2454 static void crypt_page_free(void *page, void *pool_data)
2456 struct crypt_config *cc = pool_data;
2459 percpu_counter_sub(&cc->n_allocated_pages, 1);
2462 static void crypt_dtr(struct dm_target *ti)
2464 struct crypt_config *cc = ti->private;
2471 if (cc->write_thread)
2472 kthread_stop(cc->write_thread);
2475 destroy_workqueue(cc->io_queue);
2476 if (cc->crypt_queue)
2477 destroy_workqueue(cc->crypt_queue);
2479 crypt_free_tfms(cc);
2481 bioset_exit(&cc->bs);
2483 mempool_exit(&cc->page_pool);
2484 mempool_exit(&cc->req_pool);
2485 mempool_exit(&cc->tag_pool);
2487 WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
2488 percpu_counter_destroy(&cc->n_allocated_pages);
2490 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
2491 cc->iv_gen_ops->dtr(cc);
2494 dm_put_device(ti, cc->dev);
2496 kzfree(cc->cipher_string);
2497 kzfree(cc->key_string);
2498 kzfree(cc->cipher_auth);
2499 kzfree(cc->authenc_key);
2501 mutex_destroy(&cc->bio_alloc_lock);
2503 /* Must zero key material before freeing */
2506 spin_lock(&dm_crypt_clients_lock);
2507 WARN_ON(!dm_crypt_clients_n);
2508 dm_crypt_clients_n--;
2509 crypt_calculate_pages_per_client();
2510 spin_unlock(&dm_crypt_clients_lock);
2513 static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
2515 struct crypt_config *cc = ti->private;
2517 if (crypt_integrity_aead(cc))
2518 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2520 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2523 /* at least a 64 bit sector number should fit in our buffer */
2524 cc->iv_size = max(cc->iv_size,
2525 (unsigned int)(sizeof(u64) / sizeof(u8)));
2527 DMWARN("Selected cipher does not support IVs");
2531 /* Choose ivmode, see comments at iv code. */
2533 cc->iv_gen_ops = NULL;
2534 else if (strcmp(ivmode, "plain") == 0)
2535 cc->iv_gen_ops = &crypt_iv_plain_ops;
2536 else if (strcmp(ivmode, "plain64") == 0)
2537 cc->iv_gen_ops = &crypt_iv_plain64_ops;
2538 else if (strcmp(ivmode, "plain64be") == 0)
2539 cc->iv_gen_ops = &crypt_iv_plain64be_ops;
2540 else if (strcmp(ivmode, "essiv") == 0)
2541 cc->iv_gen_ops = &crypt_iv_essiv_ops;
2542 else if (strcmp(ivmode, "benbi") == 0)
2543 cc->iv_gen_ops = &crypt_iv_benbi_ops;
2544 else if (strcmp(ivmode, "null") == 0)
2545 cc->iv_gen_ops = &crypt_iv_null_ops;
2546 else if (strcmp(ivmode, "eboiv") == 0)
2547 cc->iv_gen_ops = &crypt_iv_eboiv_ops;
2548 else if (strcmp(ivmode, "elephant") == 0) {
2549 cc->iv_gen_ops = &crypt_iv_elephant_ops;
2551 cc->key_extra_size = cc->key_size / 2;
2552 if (cc->key_extra_size > ELEPHANT_MAX_KEY_SIZE)
2554 set_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags);
2555 } else if (strcmp(ivmode, "lmk") == 0) {
2556 cc->iv_gen_ops = &crypt_iv_lmk_ops;
2558 * Version 2 and 3 is recognised according
2559 * to length of provided multi-key string.
2560 * If present (version 3), last key is used as IV seed.
2561 * All keys (including IV seed) are always the same size.
2563 if (cc->key_size % cc->key_parts) {
2565 cc->key_extra_size = cc->key_size / cc->key_parts;
2567 } else if (strcmp(ivmode, "tcw") == 0) {
2568 cc->iv_gen_ops = &crypt_iv_tcw_ops;
2569 cc->key_parts += 2; /* IV + whitening */
2570 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2571 } else if (strcmp(ivmode, "random") == 0) {
2572 cc->iv_gen_ops = &crypt_iv_random_ops;
2573 /* Need storage space in integrity fields. */
2574 cc->integrity_iv_size = cc->iv_size;
2576 ti->error = "Invalid IV mode";
2584 * Workaround to parse HMAC algorithm from AEAD crypto API spec.
2585 * The HMAC is needed to calculate tag size (HMAC digest size).
2586 * This should be probably done by crypto-api calls (once available...)
2588 static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
2590 char *start, *end, *mac_alg = NULL;
2591 struct crypto_ahash *mac;
2593 if (!strstarts(cipher_api, "authenc("))
2596 start = strchr(cipher_api, '(');
2597 end = strchr(cipher_api, ',');
2598 if (!start || !end || ++start > end)
2601 mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
2604 strncpy(mac_alg, start, end - start);
2606 mac = crypto_alloc_ahash(mac_alg, 0, 0);
2610 return PTR_ERR(mac);
2612 cc->key_mac_size = crypto_ahash_digestsize(mac);
2613 crypto_free_ahash(mac);
2615 cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
2616 if (!cc->authenc_key)
2622 static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
2623 char **ivmode, char **ivopts)
2625 struct crypt_config *cc = ti->private;
2626 char *tmp, *cipher_api, buf[CRYPTO_MAX_ALG_NAME];
2632 * New format (capi: prefix)
2633 * capi:cipher_api_spec-iv:ivopts
2635 tmp = &cipher_in[strlen("capi:")];
2637 /* Separate IV options if present, it can contain another '-' in hash name */
2638 *ivopts = strrchr(tmp, ':');
2644 *ivmode = strrchr(tmp, '-');
2649 /* The rest is crypto API spec */
2652 /* Alloc AEAD, can be used only in new format. */
2653 if (crypt_integrity_aead(cc)) {
2654 ret = crypt_ctr_auth_cipher(cc, cipher_api);
2656 ti->error = "Invalid AEAD cipher spec";
2661 if (*ivmode && !strcmp(*ivmode, "lmk"))
2662 cc->tfms_count = 64;
2664 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2666 ti->error = "Digest algorithm missing for ESSIV mode";
2669 ret = snprintf(buf, CRYPTO_MAX_ALG_NAME, "essiv(%s,%s)",
2670 cipher_api, *ivopts);
2671 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2672 ti->error = "Cannot allocate cipher string";
2678 cc->key_parts = cc->tfms_count;
2680 /* Allocate cipher */
2681 ret = crypt_alloc_tfms(cc, cipher_api);
2683 ti->error = "Error allocating crypto tfm";
2687 if (crypt_integrity_aead(cc))
2688 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2690 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2695 static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
2696 char **ivmode, char **ivopts)
2698 struct crypt_config *cc = ti->private;
2699 char *tmp, *cipher, *chainmode, *keycount;
2700 char *cipher_api = NULL;
2704 if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
2705 ti->error = "Bad cipher specification";
2710 * Legacy dm-crypt cipher specification
2711 * cipher[:keycount]-mode-iv:ivopts
2714 keycount = strsep(&tmp, "-");
2715 cipher = strsep(&keycount, ":");
2719 else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
2720 !is_power_of_2(cc->tfms_count)) {
2721 ti->error = "Bad cipher key count specification";
2724 cc->key_parts = cc->tfms_count;
2726 chainmode = strsep(&tmp, "-");
2727 *ivmode = strsep(&tmp, ":");
2731 * For compatibility with the original dm-crypt mapping format, if
2732 * only the cipher name is supplied, use cbc-plain.
2734 if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
2739 if (strcmp(chainmode, "ecb") && !*ivmode) {
2740 ti->error = "IV mechanism required";
2744 cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
2748 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2750 ti->error = "Digest algorithm missing for ESSIV mode";
2754 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2755 "essiv(%s(%s),%s)", chainmode, cipher, *ivopts);
2757 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2758 "%s(%s)", chainmode, cipher);
2760 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2765 /* Allocate cipher */
2766 ret = crypt_alloc_tfms(cc, cipher_api);
2768 ti->error = "Error allocating crypto tfm";
2776 ti->error = "Cannot allocate cipher strings";
2780 static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
2782 struct crypt_config *cc = ti->private;
2783 char *ivmode = NULL, *ivopts = NULL;
2786 cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
2787 if (!cc->cipher_string) {
2788 ti->error = "Cannot allocate cipher strings";
2792 if (strstarts(cipher_in, "capi:"))
2793 ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
2795 ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
2800 ret = crypt_ctr_ivmode(ti, ivmode);
2804 /* Initialize and set key */
2805 ret = crypt_set_key(cc, key);
2807 ti->error = "Error decoding and setting key";
2812 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
2813 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
2815 ti->error = "Error creating IV";
2820 /* Initialize IV (set keys for ESSIV etc) */
2821 if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
2822 ret = cc->iv_gen_ops->init(cc);
2824 ti->error = "Error initialising IV";
2829 /* wipe the kernel key payload copy */
2831 memset(cc->key, 0, cc->key_size * sizeof(u8));
2836 static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
2838 struct crypt_config *cc = ti->private;
2839 struct dm_arg_set as;
2840 static const struct dm_arg _args[] = {
2841 {0, 6, "Invalid number of feature args"},
2843 unsigned int opt_params, val;
2844 const char *opt_string, *sval;
2848 /* Optional parameters */
2852 ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
2856 while (opt_params--) {
2857 opt_string = dm_shift_arg(&as);
2859 ti->error = "Not enough feature arguments";
2863 if (!strcasecmp(opt_string, "allow_discards"))
2864 ti->num_discard_bios = 1;
2866 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
2867 set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
2869 else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
2870 set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
2871 else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
2872 if (val == 0 || val > MAX_TAG_SIZE) {
2873 ti->error = "Invalid integrity arguments";
2876 cc->on_disk_tag_size = val;
2877 sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
2878 if (!strcasecmp(sval, "aead")) {
2879 set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
2880 } else if (strcasecmp(sval, "none")) {
2881 ti->error = "Unknown integrity profile";
2885 cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
2886 if (!cc->cipher_auth)
2888 } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
2889 if (cc->sector_size < (1 << SECTOR_SHIFT) ||
2890 cc->sector_size > 4096 ||
2891 (cc->sector_size & (cc->sector_size - 1))) {
2892 ti->error = "Invalid feature value for sector_size";
2895 if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
2896 ti->error = "Device size is not multiple of sector_size feature";
2899 cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
2900 } else if (!strcasecmp(opt_string, "iv_large_sectors"))
2901 set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
2903 ti->error = "Invalid feature arguments";
2912 * Construct an encryption mapping:
2913 * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
2915 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
2917 struct crypt_config *cc;
2918 const char *devname = dm_table_device_name(ti->table);
2920 unsigned int align_mask;
2921 unsigned long long tmpll;
2923 size_t iv_size_padding, additional_req_size;
2927 ti->error = "Not enough arguments";
2931 key_size = get_key_size(&argv[1]);
2933 ti->error = "Cannot parse key size";
2937 cc = kzalloc(struct_size(cc, key, key_size), GFP_KERNEL);
2939 ti->error = "Cannot allocate encryption context";
2942 cc->key_size = key_size;
2943 cc->sector_size = (1 << SECTOR_SHIFT);
2944 cc->sector_shift = 0;
2948 spin_lock(&dm_crypt_clients_lock);
2949 dm_crypt_clients_n++;
2950 crypt_calculate_pages_per_client();
2951 spin_unlock(&dm_crypt_clients_lock);
2953 ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
2957 /* Optional parameters need to be read before cipher constructor */
2959 ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
2964 ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
2968 if (crypt_integrity_aead(cc)) {
2969 cc->dmreq_start = sizeof(struct aead_request);
2970 cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
2971 align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
2973 cc->dmreq_start = sizeof(struct skcipher_request);
2974 cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
2975 align_mask = crypto_skcipher_alignmask(any_tfm(cc));
2977 cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
2979 if (align_mask < CRYPTO_MINALIGN) {
2980 /* Allocate the padding exactly */
2981 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
2985 * If the cipher requires greater alignment than kmalloc
2986 * alignment, we don't know the exact position of the
2987 * initialization vector. We must assume worst case.
2989 iv_size_padding = align_mask;
2992 /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
2993 additional_req_size = sizeof(struct dm_crypt_request) +
2994 iv_size_padding + cc->iv_size +
2997 sizeof(unsigned int);
2999 ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
3001 ti->error = "Cannot allocate crypt request mempool";
3005 cc->per_bio_data_size = ti->per_io_data_size =
3006 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
3007 ARCH_KMALLOC_MINALIGN);
3009 ret = mempool_init(&cc->page_pool, BIO_MAX_PAGES, crypt_page_alloc, crypt_page_free, cc);
3011 ti->error = "Cannot allocate page mempool";
3015 ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
3017 ti->error = "Cannot allocate crypt bioset";
3021 mutex_init(&cc->bio_alloc_lock);
3024 if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
3025 (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
3026 ti->error = "Invalid iv_offset sector";
3029 cc->iv_offset = tmpll;
3031 ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
3033 ti->error = "Device lookup failed";
3038 if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
3039 ti->error = "Invalid device sector";
3044 if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
3045 ret = crypt_integrity_ctr(cc, ti);
3049 cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
3050 if (!cc->tag_pool_max_sectors)
3051 cc->tag_pool_max_sectors = 1;
3053 ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
3054 cc->tag_pool_max_sectors * cc->on_disk_tag_size);
3056 ti->error = "Cannot allocate integrity tags mempool";
3060 cc->tag_pool_max_sectors <<= cc->sector_shift;
3064 cc->io_queue = alloc_workqueue("kcryptd_io/%s", WQ_MEM_RECLAIM, 1, devname);
3065 if (!cc->io_queue) {
3066 ti->error = "Couldn't create kcryptd io queue";
3070 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3071 cc->crypt_queue = alloc_workqueue("kcryptd/%s", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM,
3074 cc->crypt_queue = alloc_workqueue("kcryptd/%s",
3075 WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
3076 num_online_cpus(), devname);
3077 if (!cc->crypt_queue) {
3078 ti->error = "Couldn't create kcryptd queue";
3082 spin_lock_init(&cc->write_thread_lock);
3083 cc->write_tree = RB_ROOT;
3085 cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
3086 if (IS_ERR(cc->write_thread)) {
3087 ret = PTR_ERR(cc->write_thread);
3088 cc->write_thread = NULL;
3089 ti->error = "Couldn't spawn write thread";
3092 wake_up_process(cc->write_thread);
3094 ti->num_flush_bios = 1;
3103 static int crypt_map(struct dm_target *ti, struct bio *bio)
3105 struct dm_crypt_io *io;
3106 struct crypt_config *cc = ti->private;
3109 * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
3110 * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
3111 * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
3113 if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
3114 bio_op(bio) == REQ_OP_DISCARD)) {
3115 bio_set_dev(bio, cc->dev->bdev);
3116 if (bio_sectors(bio))
3117 bio->bi_iter.bi_sector = cc->start +
3118 dm_target_offset(ti, bio->bi_iter.bi_sector);
3119 return DM_MAPIO_REMAPPED;
3123 * Check if bio is too large, split as needed.
3125 if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_PAGES << PAGE_SHIFT)) &&
3126 (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
3127 dm_accept_partial_bio(bio, ((BIO_MAX_PAGES << PAGE_SHIFT) >> SECTOR_SHIFT));
3130 * Ensure that bio is a multiple of internal sector encryption size
3131 * and is aligned to this size as defined in IO hints.
3133 if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
3134 return DM_MAPIO_KILL;
3136 if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
3137 return DM_MAPIO_KILL;
3139 io = dm_per_bio_data(bio, cc->per_bio_data_size);
3140 crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
3142 if (cc->on_disk_tag_size) {
3143 unsigned tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
3145 if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
3146 unlikely(!(io->integrity_metadata = kmalloc(tag_len,
3147 GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
3148 if (bio_sectors(bio) > cc->tag_pool_max_sectors)
3149 dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
3150 io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
3151 io->integrity_metadata_from_pool = true;
3155 if (crypt_integrity_aead(cc))
3156 io->ctx.r.req_aead = (struct aead_request *)(io + 1);
3158 io->ctx.r.req = (struct skcipher_request *)(io + 1);
3160 if (bio_data_dir(io->base_bio) == READ) {
3161 if (kcryptd_io_read(io, GFP_NOWAIT))
3162 kcryptd_queue_read(io);
3164 kcryptd_queue_crypt(io);
3166 return DM_MAPIO_SUBMITTED;
3169 static void crypt_status(struct dm_target *ti, status_type_t type,
3170 unsigned status_flags, char *result, unsigned maxlen)
3172 struct crypt_config *cc = ti->private;
3174 int num_feature_args = 0;
3177 case STATUSTYPE_INFO:
3181 case STATUSTYPE_TABLE:
3182 DMEMIT("%s ", cc->cipher_string);
3184 if (cc->key_size > 0) {
3186 DMEMIT(":%u:%s", cc->key_size, cc->key_string);
3188 for (i = 0; i < cc->key_size; i++)
3189 DMEMIT("%02x", cc->key[i]);
3193 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
3194 cc->dev->name, (unsigned long long)cc->start);
3196 num_feature_args += !!ti->num_discard_bios;
3197 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3198 num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3199 num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
3200 num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3201 if (cc->on_disk_tag_size)
3203 if (num_feature_args) {
3204 DMEMIT(" %d", num_feature_args);
3205 if (ti->num_discard_bios)
3206 DMEMIT(" allow_discards");
3207 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3208 DMEMIT(" same_cpu_crypt");
3209 if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
3210 DMEMIT(" submit_from_crypt_cpus");
3211 if (cc->on_disk_tag_size)
3212 DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
3213 if (cc->sector_size != (1 << SECTOR_SHIFT))
3214 DMEMIT(" sector_size:%d", cc->sector_size);
3215 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
3216 DMEMIT(" iv_large_sectors");
3223 static void crypt_postsuspend(struct dm_target *ti)
3225 struct crypt_config *cc = ti->private;
3227 set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3230 static int crypt_preresume(struct dm_target *ti)
3232 struct crypt_config *cc = ti->private;
3234 if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
3235 DMERR("aborting resume - crypt key is not set.");
3242 static void crypt_resume(struct dm_target *ti)
3244 struct crypt_config *cc = ti->private;
3246 clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3249 /* Message interface
3253 static int crypt_message(struct dm_target *ti, unsigned argc, char **argv,
3254 char *result, unsigned maxlen)
3256 struct crypt_config *cc = ti->private;
3257 int key_size, ret = -EINVAL;
3262 if (!strcasecmp(argv[0], "key")) {
3263 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
3264 DMWARN("not suspended during key manipulation.");
3267 if (argc == 3 && !strcasecmp(argv[1], "set")) {
3268 /* The key size may not be changed. */
3269 key_size = get_key_size(&argv[2]);
3270 if (key_size < 0 || cc->key_size != key_size) {
3271 memset(argv[2], '0', strlen(argv[2]));
3275 ret = crypt_set_key(cc, argv[2]);
3278 if (cc->iv_gen_ops && cc->iv_gen_ops->init)
3279 ret = cc->iv_gen_ops->init(cc);
3280 /* wipe the kernel key payload copy */
3282 memset(cc->key, 0, cc->key_size * sizeof(u8));
3285 if (argc == 2 && !strcasecmp(argv[1], "wipe"))
3286 return crypt_wipe_key(cc);
3290 DMWARN("unrecognised message received.");
3294 static int crypt_iterate_devices(struct dm_target *ti,
3295 iterate_devices_callout_fn fn, void *data)
3297 struct crypt_config *cc = ti->private;
3299 return fn(ti, cc->dev, cc->start, ti->len, data);
3302 static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
3304 struct crypt_config *cc = ti->private;
3307 * Unfortunate constraint that is required to avoid the potential
3308 * for exceeding underlying device's max_segments limits -- due to
3309 * crypt_alloc_buffer() possibly allocating pages for the encryption
3310 * bio that are not as physically contiguous as the original bio.
3312 limits->max_segment_size = PAGE_SIZE;
3314 limits->logical_block_size =
3315 max_t(unsigned, limits->logical_block_size, cc->sector_size);
3316 limits->physical_block_size =
3317 max_t(unsigned, limits->physical_block_size, cc->sector_size);
3318 limits->io_min = max_t(unsigned, limits->io_min, cc->sector_size);
3321 static struct target_type crypt_target = {
3323 .version = {1, 21, 0},
3324 .module = THIS_MODULE,
3328 .status = crypt_status,
3329 .postsuspend = crypt_postsuspend,
3330 .preresume = crypt_preresume,
3331 .resume = crypt_resume,
3332 .message = crypt_message,
3333 .iterate_devices = crypt_iterate_devices,
3334 .io_hints = crypt_io_hints,
3337 static int __init dm_crypt_init(void)
3341 r = dm_register_target(&crypt_target);
3343 DMERR("register failed %d", r);
3348 static void __exit dm_crypt_exit(void)
3350 dm_unregister_target(&crypt_target);
3353 module_init(dm_crypt_init);
3354 module_exit(dm_crypt_exit);
3356 MODULE_AUTHOR("Jana Saout <jana@saout.de>");
3357 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
3358 MODULE_LICENSE("GPL");