2 * Copyright (C) 2003 Jana Saout <jana@saout.de>
3 * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
4 * Copyright (C) 2006-2017 Red Hat, Inc. All rights reserved.
5 * Copyright (C) 2013-2017 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 <keys/user-type.h>
39 #include <linux/device-mapper.h>
41 #define DM_MSG_PREFIX "crypt"
44 * context holding the current state of a multi-part conversion
46 struct convert_context {
47 struct completion restart;
50 struct bvec_iter iter_in;
51 struct bvec_iter iter_out;
55 struct skcipher_request *req;
56 struct aead_request *req_aead;
62 * per bio private data
65 struct crypt_config *cc;
67 u8 *integrity_metadata;
68 bool integrity_metadata_from_pool;
69 struct work_struct work;
71 struct convert_context ctx;
77 struct rb_node rb_node;
78 } CRYPTO_MINALIGN_ATTR;
80 struct dm_crypt_request {
81 struct convert_context *ctx;
82 struct scatterlist sg_in[4];
83 struct scatterlist sg_out[4];
89 struct crypt_iv_operations {
90 int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
92 void (*dtr)(struct crypt_config *cc);
93 int (*init)(struct crypt_config *cc);
94 int (*wipe)(struct crypt_config *cc);
95 int (*generator)(struct crypt_config *cc, u8 *iv,
96 struct dm_crypt_request *dmreq);
97 int (*post)(struct crypt_config *cc, u8 *iv,
98 struct dm_crypt_request *dmreq);
101 struct iv_essiv_private {
102 struct crypto_ahash *hash_tfm;
106 struct iv_benbi_private {
110 #define LMK_SEED_SIZE 64 /* hash + 0 */
111 struct iv_lmk_private {
112 struct crypto_shash *hash_tfm;
116 #define TCW_WHITENING_SIZE 16
117 struct iv_tcw_private {
118 struct crypto_shash *crc32_tfm;
124 * Crypt: maps a linear range of a block device
125 * and encrypts / decrypts at the same time.
127 enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
128 DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD };
131 CRYPT_MODE_INTEGRITY_AEAD, /* Use authenticated mode for cihper */
132 CRYPT_MODE_INTEGRITY_HMAC, /* Compose authenticated mode from normal mode and HMAC */
136 * The fields in here must be read only after initialization.
138 struct crypt_config {
143 * pool for per bio private data, crypto requests,
144 * encryption requeusts/buffer pages and integrity tags
147 mempool_t *page_pool;
149 unsigned tag_pool_max_sectors;
152 struct mutex bio_alloc_lock;
154 struct workqueue_struct *io_queue;
155 struct workqueue_struct *crypt_queue;
157 struct task_struct *write_thread;
158 wait_queue_head_t write_thread_wait;
159 struct rb_root write_tree;
166 const struct crypt_iv_operations *iv_gen_ops;
168 struct iv_essiv_private essiv;
169 struct iv_benbi_private benbi;
170 struct iv_lmk_private lmk;
171 struct iv_tcw_private tcw;
174 unsigned int iv_size;
176 /* ESSIV: struct crypto_cipher *essiv_tfm */
179 struct crypto_skcipher **tfms;
180 struct crypto_aead **tfms_aead;
183 unsigned long cipher_flags;
186 * Layout of each crypto request:
188 * struct skcipher_request
191 * struct dm_crypt_request
195 * The padding is added so that dm_crypt_request and the IV are
198 unsigned int dmreq_start;
200 unsigned int per_bio_data_size;
203 unsigned int key_size;
204 unsigned int key_parts; /* independent parts in key buffer */
205 unsigned int key_extra_size; /* additional keys length */
206 unsigned int key_mac_size; /* MAC key size for authenc(...) */
208 unsigned int integrity_tag_size;
209 unsigned int integrity_iv_size;
210 unsigned int on_disk_tag_size;
212 u8 *authenc_key; /* space for keys in authenc() format (if used) */
217 #define MAX_TAG_SIZE 480
218 #define POOL_ENTRY_SIZE 512
220 static void clone_init(struct dm_crypt_io *, struct bio *);
221 static void kcryptd_queue_crypt(struct dm_crypt_io *io);
222 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
223 struct scatterlist *sg);
226 * Use this to access cipher attributes that are the same for each CPU.
228 static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
230 return cc->cipher_tfm.tfms[0];
233 static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
235 return cc->cipher_tfm.tfms_aead[0];
239 * Different IV generation algorithms:
241 * plain: the initial vector is the 32-bit little-endian version of the sector
242 * number, padded with zeros if necessary.
244 * plain64: the initial vector is the 64-bit little-endian version of the sector
245 * number, padded with zeros if necessary.
247 * essiv: "encrypted sector|salt initial vector", the sector number is
248 * encrypted with the bulk cipher using a salt as key. The salt
249 * should be derived from the bulk cipher's key via hashing.
251 * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
252 * (needed for LRW-32-AES and possible other narrow block modes)
254 * null: the initial vector is always zero. Provides compatibility with
255 * obsolete loop_fish2 devices. Do not use for new devices.
257 * lmk: Compatible implementation of the block chaining mode used
258 * by the Loop-AES block device encryption system
259 * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
260 * It operates on full 512 byte sectors and uses CBC
261 * with an IV derived from the sector number, the data and
262 * optionally extra IV seed.
263 * This means that after decryption the first block
264 * of sector must be tweaked according to decrypted data.
265 * Loop-AES can use three encryption schemes:
266 * version 1: is plain aes-cbc mode
267 * version 2: uses 64 multikey scheme with lmk IV generator
268 * version 3: the same as version 2 with additional IV seed
269 * (it uses 65 keys, last key is used as IV seed)
271 * tcw: Compatible implementation of the block chaining mode used
272 * by the TrueCrypt device encryption system (prior to version 4.1).
273 * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
274 * It operates on full 512 byte sectors and uses CBC
275 * with an IV derived from initial key and the sector number.
276 * In addition, whitening value is applied on every sector, whitening
277 * is calculated from initial key, sector number and mixed using CRC32.
278 * Note that this encryption scheme is vulnerable to watermarking attacks
279 * and should be used for old compatible containers access only.
281 * plumb: unimplemented, see:
282 * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
285 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
286 struct dm_crypt_request *dmreq)
288 memset(iv, 0, cc->iv_size);
289 *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
294 static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
295 struct dm_crypt_request *dmreq)
297 memset(iv, 0, cc->iv_size);
298 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
303 /* Initialise ESSIV - compute salt but no local memory allocations */
304 static int crypt_iv_essiv_init(struct crypt_config *cc)
306 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
307 AHASH_REQUEST_ON_STACK(req, essiv->hash_tfm);
308 struct scatterlist sg;
309 struct crypto_cipher *essiv_tfm;
312 sg_init_one(&sg, cc->key, cc->key_size);
313 ahash_request_set_tfm(req, essiv->hash_tfm);
314 ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP, NULL, NULL);
315 ahash_request_set_crypt(req, &sg, essiv->salt, cc->key_size);
317 err = crypto_ahash_digest(req);
318 ahash_request_zero(req);
322 essiv_tfm = cc->iv_private;
324 err = crypto_cipher_setkey(essiv_tfm, essiv->salt,
325 crypto_ahash_digestsize(essiv->hash_tfm));
332 /* Wipe salt and reset key derived from volume key */
333 static int crypt_iv_essiv_wipe(struct crypt_config *cc)
335 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
336 unsigned salt_size = crypto_ahash_digestsize(essiv->hash_tfm);
337 struct crypto_cipher *essiv_tfm;
340 memset(essiv->salt, 0, salt_size);
342 essiv_tfm = cc->iv_private;
343 r = crypto_cipher_setkey(essiv_tfm, essiv->salt, salt_size);
350 /* Set up per cpu cipher state */
351 static struct crypto_cipher *setup_essiv_cpu(struct crypt_config *cc,
352 struct dm_target *ti,
353 u8 *salt, unsigned saltsize)
355 struct crypto_cipher *essiv_tfm;
358 /* Setup the essiv_tfm with the given salt */
359 essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
360 if (IS_ERR(essiv_tfm)) {
361 ti->error = "Error allocating crypto tfm for ESSIV";
365 if (crypto_cipher_blocksize(essiv_tfm) != cc->iv_size) {
366 ti->error = "Block size of ESSIV cipher does "
367 "not match IV size of block cipher";
368 crypto_free_cipher(essiv_tfm);
369 return ERR_PTR(-EINVAL);
372 err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
374 ti->error = "Failed to set key for ESSIV cipher";
375 crypto_free_cipher(essiv_tfm);
382 static void crypt_iv_essiv_dtr(struct crypt_config *cc)
384 struct crypto_cipher *essiv_tfm;
385 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
387 crypto_free_ahash(essiv->hash_tfm);
388 essiv->hash_tfm = NULL;
393 essiv_tfm = cc->iv_private;
396 crypto_free_cipher(essiv_tfm);
398 cc->iv_private = NULL;
401 static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
404 struct crypto_cipher *essiv_tfm = NULL;
405 struct crypto_ahash *hash_tfm = NULL;
410 ti->error = "Digest algorithm missing for ESSIV mode";
414 /* Allocate hash algorithm */
415 hash_tfm = crypto_alloc_ahash(opts, 0, CRYPTO_ALG_ASYNC);
416 if (IS_ERR(hash_tfm)) {
417 ti->error = "Error initializing ESSIV hash";
418 err = PTR_ERR(hash_tfm);
422 salt = kzalloc(crypto_ahash_digestsize(hash_tfm), GFP_KERNEL);
424 ti->error = "Error kmallocing salt storage in ESSIV";
429 cc->iv_gen_private.essiv.salt = salt;
430 cc->iv_gen_private.essiv.hash_tfm = hash_tfm;
432 essiv_tfm = setup_essiv_cpu(cc, ti, salt,
433 crypto_ahash_digestsize(hash_tfm));
435 if (IS_ERR(essiv_tfm)) {
436 crypt_iv_essiv_dtr(cc);
437 return PTR_ERR(essiv_tfm);
439 cc->iv_private = essiv_tfm;
444 if (hash_tfm && !IS_ERR(hash_tfm))
445 crypto_free_ahash(hash_tfm);
450 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
451 struct dm_crypt_request *dmreq)
453 struct crypto_cipher *essiv_tfm = cc->iv_private;
455 memset(iv, 0, cc->iv_size);
456 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
457 crypto_cipher_encrypt_one(essiv_tfm, iv, iv);
462 static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
465 unsigned bs = crypto_skcipher_blocksize(any_tfm(cc));
468 /* we need to calculate how far we must shift the sector count
469 * to get the cipher block count, we use this shift in _gen */
471 if (1 << log != bs) {
472 ti->error = "cypher blocksize is not a power of 2";
477 ti->error = "cypher blocksize is > 512";
481 cc->iv_gen_private.benbi.shift = 9 - log;
486 static void crypt_iv_benbi_dtr(struct crypt_config *cc)
490 static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
491 struct dm_crypt_request *dmreq)
495 memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
497 val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
498 put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
503 static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
504 struct dm_crypt_request *dmreq)
506 memset(iv, 0, cc->iv_size);
511 static void crypt_iv_lmk_dtr(struct crypt_config *cc)
513 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
515 if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
516 crypto_free_shash(lmk->hash_tfm);
517 lmk->hash_tfm = NULL;
523 static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
526 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
528 lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
529 if (IS_ERR(lmk->hash_tfm)) {
530 ti->error = "Error initializing LMK hash";
531 return PTR_ERR(lmk->hash_tfm);
534 /* No seed in LMK version 2 */
535 if (cc->key_parts == cc->tfms_count) {
540 lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
542 crypt_iv_lmk_dtr(cc);
543 ti->error = "Error kmallocing seed storage in LMK";
550 static int crypt_iv_lmk_init(struct crypt_config *cc)
552 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
553 int subkey_size = cc->key_size / cc->key_parts;
555 /* LMK seed is on the position of LMK_KEYS + 1 key */
557 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
558 crypto_shash_digestsize(lmk->hash_tfm));
563 static int crypt_iv_lmk_wipe(struct crypt_config *cc)
565 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
568 memset(lmk->seed, 0, LMK_SEED_SIZE);
573 static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
574 struct dm_crypt_request *dmreq,
577 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
578 SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
579 struct md5_state md5state;
583 desc->tfm = lmk->hash_tfm;
584 desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
586 r = crypto_shash_init(desc);
591 r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
596 /* Sector is always 512B, block size 16, add data of blocks 1-31 */
597 r = crypto_shash_update(desc, data + 16, 16 * 31);
601 /* Sector is cropped to 56 bits here */
602 buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
603 buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
604 buf[2] = cpu_to_le32(4024);
606 r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
610 /* No MD5 padding here */
611 r = crypto_shash_export(desc, &md5state);
615 for (i = 0; i < MD5_HASH_WORDS; i++)
616 __cpu_to_le32s(&md5state.hash[i]);
617 memcpy(iv, &md5state.hash, cc->iv_size);
622 static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
623 struct dm_crypt_request *dmreq)
625 struct scatterlist *sg;
629 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
630 sg = crypt_get_sg_data(cc, dmreq->sg_in);
631 src = kmap_atomic(sg_page(sg));
632 r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
635 memset(iv, 0, cc->iv_size);
640 static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
641 struct dm_crypt_request *dmreq)
643 struct scatterlist *sg;
647 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
650 sg = crypt_get_sg_data(cc, dmreq->sg_out);
651 dst = kmap_atomic(sg_page(sg));
652 r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
654 /* Tweak the first block of plaintext sector */
656 crypto_xor(dst + sg->offset, iv, cc->iv_size);
662 static void crypt_iv_tcw_dtr(struct crypt_config *cc)
664 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
666 kzfree(tcw->iv_seed);
668 kzfree(tcw->whitening);
669 tcw->whitening = NULL;
671 if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
672 crypto_free_shash(tcw->crc32_tfm);
673 tcw->crc32_tfm = NULL;
676 static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
679 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
681 if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
682 ti->error = "Wrong key size for TCW";
686 tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
687 if (IS_ERR(tcw->crc32_tfm)) {
688 ti->error = "Error initializing CRC32 in TCW";
689 return PTR_ERR(tcw->crc32_tfm);
692 tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
693 tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
694 if (!tcw->iv_seed || !tcw->whitening) {
695 crypt_iv_tcw_dtr(cc);
696 ti->error = "Error allocating seed storage in TCW";
703 static int crypt_iv_tcw_init(struct crypt_config *cc)
705 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
706 int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
708 memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
709 memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
715 static int crypt_iv_tcw_wipe(struct crypt_config *cc)
717 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
719 memset(tcw->iv_seed, 0, cc->iv_size);
720 memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
725 static int crypt_iv_tcw_whitening(struct crypt_config *cc,
726 struct dm_crypt_request *dmreq,
729 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
730 __le64 sector = cpu_to_le64(dmreq->iv_sector);
731 u8 buf[TCW_WHITENING_SIZE];
732 SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
735 /* xor whitening with sector number */
736 memcpy(buf, tcw->whitening, TCW_WHITENING_SIZE);
737 crypto_xor(buf, (u8 *)§or, 8);
738 crypto_xor(&buf[8], (u8 *)§or, 8);
740 /* calculate crc32 for every 32bit part and xor it */
741 desc->tfm = tcw->crc32_tfm;
742 desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
743 for (i = 0; i < 4; i++) {
744 r = crypto_shash_init(desc);
747 r = crypto_shash_update(desc, &buf[i * 4], 4);
750 r = crypto_shash_final(desc, &buf[i * 4]);
754 crypto_xor(&buf[0], &buf[12], 4);
755 crypto_xor(&buf[4], &buf[8], 4);
757 /* apply whitening (8 bytes) to whole sector */
758 for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
759 crypto_xor(data + i * 8, buf, 8);
761 memzero_explicit(buf, sizeof(buf));
765 static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
766 struct dm_crypt_request *dmreq)
768 struct scatterlist *sg;
769 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
770 __le64 sector = cpu_to_le64(dmreq->iv_sector);
774 /* Remove whitening from ciphertext */
775 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
776 sg = crypt_get_sg_data(cc, dmreq->sg_in);
777 src = kmap_atomic(sg_page(sg));
778 r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
783 memcpy(iv, tcw->iv_seed, cc->iv_size);
784 crypto_xor(iv, (u8 *)§or, 8);
786 crypto_xor(&iv[8], (u8 *)§or, cc->iv_size - 8);
791 static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
792 struct dm_crypt_request *dmreq)
794 struct scatterlist *sg;
798 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
801 /* Apply whitening on ciphertext */
802 sg = crypt_get_sg_data(cc, dmreq->sg_out);
803 dst = kmap_atomic(sg_page(sg));
804 r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
810 static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
811 struct dm_crypt_request *dmreq)
813 /* Used only for writes, there must be an additional space to store IV */
814 get_random_bytes(iv, cc->iv_size);
818 static const struct crypt_iv_operations crypt_iv_plain_ops = {
819 .generator = crypt_iv_plain_gen
822 static const struct crypt_iv_operations crypt_iv_plain64_ops = {
823 .generator = crypt_iv_plain64_gen
826 static const struct crypt_iv_operations crypt_iv_essiv_ops = {
827 .ctr = crypt_iv_essiv_ctr,
828 .dtr = crypt_iv_essiv_dtr,
829 .init = crypt_iv_essiv_init,
830 .wipe = crypt_iv_essiv_wipe,
831 .generator = crypt_iv_essiv_gen
834 static const struct crypt_iv_operations crypt_iv_benbi_ops = {
835 .ctr = crypt_iv_benbi_ctr,
836 .dtr = crypt_iv_benbi_dtr,
837 .generator = crypt_iv_benbi_gen
840 static const struct crypt_iv_operations crypt_iv_null_ops = {
841 .generator = crypt_iv_null_gen
844 static const struct crypt_iv_operations crypt_iv_lmk_ops = {
845 .ctr = crypt_iv_lmk_ctr,
846 .dtr = crypt_iv_lmk_dtr,
847 .init = crypt_iv_lmk_init,
848 .wipe = crypt_iv_lmk_wipe,
849 .generator = crypt_iv_lmk_gen,
850 .post = crypt_iv_lmk_post
853 static const struct crypt_iv_operations crypt_iv_tcw_ops = {
854 .ctr = crypt_iv_tcw_ctr,
855 .dtr = crypt_iv_tcw_dtr,
856 .init = crypt_iv_tcw_init,
857 .wipe = crypt_iv_tcw_wipe,
858 .generator = crypt_iv_tcw_gen,
859 .post = crypt_iv_tcw_post
862 static struct crypt_iv_operations crypt_iv_random_ops = {
863 .generator = crypt_iv_random_gen
867 * Integrity extensions
869 static bool crypt_integrity_aead(struct crypt_config *cc)
871 return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
874 static bool crypt_integrity_hmac(struct crypt_config *cc)
876 return test_bit(CRYPT_MODE_INTEGRITY_HMAC, &cc->cipher_flags);
879 static bool crypt_integrity_mode(struct crypt_config *cc)
881 return crypt_integrity_aead(cc) || crypt_integrity_hmac(cc);
884 /* Get sg containing data */
885 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
886 struct scatterlist *sg)
888 if (unlikely(crypt_integrity_mode(cc)))
894 static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
896 struct bio_integrity_payload *bip;
897 unsigned int tag_len;
900 if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
903 bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
907 tag_len = io->cc->on_disk_tag_size * bio_sectors(bio);
909 bip->bip_iter.bi_size = tag_len;
910 bip->bip_iter.bi_sector = io->cc->start + io->sector;
912 /* We own the metadata, do not let bio_free to release it */
913 bip->bip_flags &= ~BIP_BLOCK_INTEGRITY;
915 ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
916 tag_len, offset_in_page(io->integrity_metadata));
917 if (unlikely(ret != tag_len))
923 static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
925 #ifdef CONFIG_BLK_DEV_INTEGRITY
926 struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
928 /* From now we require underlying device with our integrity profile */
929 if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
930 ti->error = "Integrity profile not supported.";
934 if (bi->tag_size != cc->on_disk_tag_size) {
935 ti->error = "Integrity profile tag size mismatch.";
939 if (crypt_integrity_mode(cc)) {
940 cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
941 DMINFO("Integrity AEAD, tag size %u, IV size %u.",
942 cc->integrity_tag_size, cc->integrity_iv_size);
944 if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
945 ti->error = "Integrity AEAD auth tag size is not supported.";
948 } else if (cc->integrity_iv_size)
949 DMINFO("Additional per-sector space %u bytes for IV.",
950 cc->integrity_iv_size);
952 if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
953 ti->error = "Not enough space for integrity tag in the profile.";
959 ti->error = "Integrity profile not supported.";
964 static void crypt_convert_init(struct crypt_config *cc,
965 struct convert_context *ctx,
966 struct bio *bio_out, struct bio *bio_in,
969 ctx->bio_in = bio_in;
970 ctx->bio_out = bio_out;
972 ctx->iter_in = bio_in->bi_iter;
974 ctx->iter_out = bio_out->bi_iter;
975 ctx->cc_sector = sector + cc->iv_offset;
976 init_completion(&ctx->restart);
979 static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
982 return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
985 static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
987 return (void *)((char *)dmreq - cc->dmreq_start);
990 static u8 *iv_of_dmreq(struct crypt_config *cc,
991 struct dm_crypt_request *dmreq)
993 if (crypt_integrity_mode(cc))
994 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
995 crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
997 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
998 crypto_skcipher_alignmask(any_tfm(cc)) + 1);
1001 static u8 *org_iv_of_dmreq(struct crypt_config *cc,
1002 struct dm_crypt_request *dmreq)
1004 return iv_of_dmreq(cc, dmreq) + cc->iv_size;
1007 static uint64_t *org_sector_of_dmreq(struct crypt_config *cc,
1008 struct dm_crypt_request *dmreq)
1010 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
1011 return (uint64_t*) ptr;
1014 static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
1015 struct dm_crypt_request *dmreq)
1017 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
1018 cc->iv_size + sizeof(uint64_t);
1019 return (unsigned int*)ptr;
1022 static void *tag_from_dmreq(struct crypt_config *cc,
1023 struct dm_crypt_request *dmreq)
1025 struct convert_context *ctx = dmreq->ctx;
1026 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1028 return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
1029 cc->on_disk_tag_size];
1032 static void *iv_tag_from_dmreq(struct crypt_config *cc,
1033 struct dm_crypt_request *dmreq)
1035 return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
1038 static int crypt_convert_block_aead(struct crypt_config *cc,
1039 struct convert_context *ctx,
1040 struct aead_request *req,
1041 unsigned int tag_offset)
1043 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1044 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1045 struct dm_crypt_request *dmreq;
1046 unsigned int data_len = 1 << SECTOR_SHIFT;
1047 u8 *iv, *org_iv, *tag_iv, *tag;
1051 BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
1053 dmreq = dmreq_of_req(cc, req);
1054 dmreq->iv_sector = ctx->cc_sector;
1057 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1059 sector = org_sector_of_dmreq(cc, dmreq);
1060 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1062 iv = iv_of_dmreq(cc, dmreq);
1063 org_iv = org_iv_of_dmreq(cc, dmreq);
1064 tag = tag_from_dmreq(cc, dmreq);
1065 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1068 * |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1069 * | (authenticated) | (auth+encryption) | |
1070 * | sector_LE | IV | sector in/out | tag in/out |
1072 sg_init_table(dmreq->sg_in, 4);
1073 sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
1074 sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
1075 sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, data_len, bv_in.bv_offset);
1076 sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
1078 sg_init_table(dmreq->sg_out, 4);
1079 sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
1080 sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
1081 sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, data_len, bv_out.bv_offset);
1082 sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
1084 if (cc->iv_gen_ops) {
1085 /* For READs use IV stored in integrity metadata */
1086 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1087 memcpy(org_iv, tag_iv, cc->iv_size);
1089 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1092 /* Store generated IV in integrity metadata */
1093 if (cc->integrity_iv_size)
1094 memcpy(tag_iv, org_iv, cc->iv_size);
1096 /* Working copy of IV, to be modified in crypto API */
1097 memcpy(iv, org_iv, cc->iv_size);
1100 aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
1101 if (bio_data_dir(ctx->bio_in) == WRITE) {
1102 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1104 r = crypto_aead_encrypt(req);
1105 if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
1106 memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
1107 cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
1109 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1110 data_len + cc->integrity_tag_size, iv);
1111 r = crypto_aead_decrypt(req);
1115 DMERR_LIMIT("INTEGRITY AEAD ERROR, sector %llu",
1116 (unsigned long long)le64_to_cpu(*sector));
1118 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1119 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1121 bio_advance_iter(ctx->bio_in, &ctx->iter_in, data_len);
1122 bio_advance_iter(ctx->bio_out, &ctx->iter_out, data_len);
1127 static int crypt_convert_block_skcipher(struct crypt_config *cc,
1128 struct convert_context *ctx,
1129 struct skcipher_request *req,
1130 unsigned int tag_offset)
1132 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1133 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1134 struct scatterlist *sg_in, *sg_out;
1135 struct dm_crypt_request *dmreq;
1136 unsigned int data_len = 1 << SECTOR_SHIFT;
1137 u8 *iv, *org_iv, *tag_iv;
1141 dmreq = dmreq_of_req(cc, req);
1142 dmreq->iv_sector = ctx->cc_sector;
1145 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1147 iv = iv_of_dmreq(cc, dmreq);
1148 org_iv = org_iv_of_dmreq(cc, dmreq);
1149 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1151 sector = org_sector_of_dmreq(cc, dmreq);
1152 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1154 /* For skcipher we use only the first sg item */
1155 sg_in = &dmreq->sg_in[0];
1156 sg_out = &dmreq->sg_out[0];
1158 sg_init_table(sg_in, 1);
1159 sg_set_page(sg_in, bv_in.bv_page, data_len, bv_in.bv_offset);
1161 sg_init_table(sg_out, 1);
1162 sg_set_page(sg_out, bv_out.bv_page, data_len, bv_out.bv_offset);
1164 if (cc->iv_gen_ops) {
1165 /* For READs use IV stored in integrity metadata */
1166 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1167 memcpy(org_iv, tag_iv, cc->integrity_iv_size);
1169 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1172 /* Store generated IV in integrity metadata */
1173 if (cc->integrity_iv_size)
1174 memcpy(tag_iv, org_iv, cc->integrity_iv_size);
1176 /* Working copy of IV, to be modified in crypto API */
1177 memcpy(iv, org_iv, cc->iv_size);
1180 skcipher_request_set_crypt(req, sg_in, sg_out, data_len, iv);
1182 if (bio_data_dir(ctx->bio_in) == WRITE)
1183 r = crypto_skcipher_encrypt(req);
1185 r = crypto_skcipher_decrypt(req);
1187 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1188 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1190 bio_advance_iter(ctx->bio_in, &ctx->iter_in, data_len);
1191 bio_advance_iter(ctx->bio_out, &ctx->iter_out, data_len);
1196 static void kcryptd_async_done(struct crypto_async_request *async_req,
1199 static void crypt_alloc_req_skcipher(struct crypt_config *cc,
1200 struct convert_context *ctx)
1202 unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
1205 ctx->r.req = mempool_alloc(cc->req_pool, GFP_NOIO);
1207 skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
1210 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1211 * requests if driver request queue is full.
1213 skcipher_request_set_callback(ctx->r.req,
1214 CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
1215 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
1218 static void crypt_alloc_req_aead(struct crypt_config *cc,
1219 struct convert_context *ctx)
1221 if (!ctx->r.req_aead)
1222 ctx->r.req_aead = mempool_alloc(cc->req_pool, GFP_NOIO);
1224 aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
1227 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1228 * requests if driver request queue is full.
1230 aead_request_set_callback(ctx->r.req_aead,
1231 CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
1232 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
1235 static void crypt_alloc_req(struct crypt_config *cc,
1236 struct convert_context *ctx)
1238 if (crypt_integrity_mode(cc))
1239 crypt_alloc_req_aead(cc, ctx);
1241 crypt_alloc_req_skcipher(cc, ctx);
1244 static void crypt_free_req_skcipher(struct crypt_config *cc,
1245 struct skcipher_request *req, struct bio *base_bio)
1247 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1249 if ((struct skcipher_request *)(io + 1) != req)
1250 mempool_free(req, cc->req_pool);
1253 static void crypt_free_req_aead(struct crypt_config *cc,
1254 struct aead_request *req, struct bio *base_bio)
1256 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1258 if ((struct aead_request *)(io + 1) != req)
1259 mempool_free(req, cc->req_pool);
1262 static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
1264 if (crypt_integrity_mode(cc))
1265 crypt_free_req_aead(cc, req, base_bio);
1267 crypt_free_req_skcipher(cc, req, base_bio);
1271 * Encrypt / decrypt data from one bio to another one (can be the same one)
1273 static int crypt_convert(struct crypt_config *cc,
1274 struct convert_context *ctx)
1276 unsigned int tag_offset = 0;
1279 atomic_set(&ctx->cc_pending, 1);
1281 while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
1283 crypt_alloc_req(cc, ctx);
1285 atomic_inc(&ctx->cc_pending);
1287 if (crypt_integrity_mode(cc))
1288 r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
1290 r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
1294 * The request was queued by a crypto driver
1295 * but the driver request queue is full, let's wait.
1298 wait_for_completion(&ctx->restart);
1299 reinit_completion(&ctx->restart);
1302 * The request is queued and processed asynchronously,
1303 * completion function kcryptd_async_done() will be called.
1311 * The request was already processed (synchronously).
1314 atomic_dec(&ctx->cc_pending);
1320 * There was a data integrity error.
1323 atomic_dec(&ctx->cc_pending);
1326 * There was an error while processing the request.
1329 atomic_dec(&ctx->cc_pending);
1337 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
1340 * Generate a new unfragmented bio with the given size
1341 * This should never violate the device limitations (but only because
1342 * max_segment_size is being constrained to PAGE_SIZE).
1344 * This function may be called concurrently. If we allocate from the mempool
1345 * concurrently, there is a possibility of deadlock. For example, if we have
1346 * mempool of 256 pages, two processes, each wanting 256, pages allocate from
1347 * the mempool concurrently, it may deadlock in a situation where both processes
1348 * have allocated 128 pages and the mempool is exhausted.
1350 * In order to avoid this scenario we allocate the pages under a mutex.
1352 * In order to not degrade performance with excessive locking, we try
1353 * non-blocking allocations without a mutex first but on failure we fallback
1354 * to blocking allocations with a mutex.
1356 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
1358 struct crypt_config *cc = io->cc;
1360 unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1361 gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
1362 unsigned i, len, remaining_size;
1366 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1367 mutex_lock(&cc->bio_alloc_lock);
1369 clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, cc->bs);
1373 clone_init(io, clone);
1375 remaining_size = size;
1377 for (i = 0; i < nr_iovecs; i++) {
1378 page = mempool_alloc(cc->page_pool, gfp_mask);
1380 crypt_free_buffer_pages(cc, clone);
1382 gfp_mask |= __GFP_DIRECT_RECLAIM;
1386 len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
1388 bio_add_page(clone, page, len, 0);
1390 remaining_size -= len;
1393 /* Allocate space for integrity tags */
1394 if (dm_crypt_integrity_io_alloc(io, clone)) {
1395 crypt_free_buffer_pages(cc, clone);
1400 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1401 mutex_unlock(&cc->bio_alloc_lock);
1406 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1411 bio_for_each_segment_all(bv, clone, i) {
1412 BUG_ON(!bv->bv_page);
1413 mempool_free(bv->bv_page, cc->page_pool);
1418 static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1419 struct bio *bio, sector_t sector)
1423 io->sector = sector;
1425 io->ctx.r.req = NULL;
1426 io->integrity_metadata = NULL;
1427 io->integrity_metadata_from_pool = false;
1428 atomic_set(&io->io_pending, 0);
1431 static void crypt_inc_pending(struct dm_crypt_io *io)
1433 atomic_inc(&io->io_pending);
1437 * One of the bios was finished. Check for completion of
1438 * the whole request and correctly clean up the buffer.
1440 static void crypt_dec_pending(struct dm_crypt_io *io)
1442 struct crypt_config *cc = io->cc;
1443 struct bio *base_bio = io->base_bio;
1444 int error = io->error;
1446 if (!atomic_dec_and_test(&io->io_pending))
1450 crypt_free_req(cc, io->ctx.r.req, base_bio);
1452 if (unlikely(io->integrity_metadata_from_pool))
1453 mempool_free(io->integrity_metadata, io->cc->tag_pool);
1455 kfree(io->integrity_metadata);
1457 base_bio->bi_error = error;
1458 bio_endio(base_bio);
1462 * kcryptd/kcryptd_io:
1464 * Needed because it would be very unwise to do decryption in an
1465 * interrupt context.
1467 * kcryptd performs the actual encryption or decryption.
1469 * kcryptd_io performs the IO submission.
1471 * They must be separated as otherwise the final stages could be
1472 * starved by new requests which can block in the first stages due
1473 * to memory allocation.
1475 * The work is done per CPU global for all dm-crypt instances.
1476 * They should not depend on each other and do not block.
1478 static void crypt_endio(struct bio *clone)
1480 struct dm_crypt_io *io = clone->bi_private;
1481 struct crypt_config *cc = io->cc;
1482 unsigned rw = bio_data_dir(clone);
1486 * free the processed pages
1489 crypt_free_buffer_pages(cc, clone);
1491 error = clone->bi_error;
1494 if (rw == READ && !error) {
1495 kcryptd_queue_crypt(io);
1499 if (unlikely(error))
1502 crypt_dec_pending(io);
1505 static void clone_init(struct dm_crypt_io *io, struct bio *clone)
1507 struct crypt_config *cc = io->cc;
1509 clone->bi_private = io;
1510 clone->bi_end_io = crypt_endio;
1511 clone->bi_bdev = cc->dev->bdev;
1512 clone->bi_opf = io->base_bio->bi_opf;
1515 static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
1517 struct crypt_config *cc = io->cc;
1521 * We need the original biovec array in order to decrypt
1522 * the whole bio data *afterwards* -- thanks to immutable
1523 * biovecs we don't need to worry about the block layer
1524 * modifying the biovec array; so leverage bio_clone_fast().
1526 clone = bio_clone_fast(io->base_bio, gfp, cc->bs);
1530 crypt_inc_pending(io);
1532 clone_init(io, clone);
1533 clone->bi_iter.bi_sector = cc->start + io->sector;
1535 if (dm_crypt_integrity_io_alloc(io, clone)) {
1536 crypt_dec_pending(io);
1541 generic_make_request(clone);
1545 static void kcryptd_io_read_work(struct work_struct *work)
1547 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1549 crypt_inc_pending(io);
1550 if (kcryptd_io_read(io, GFP_NOIO))
1551 io->error = -ENOMEM;
1552 crypt_dec_pending(io);
1555 static void kcryptd_queue_read(struct dm_crypt_io *io)
1557 struct crypt_config *cc = io->cc;
1559 INIT_WORK(&io->work, kcryptd_io_read_work);
1560 queue_work(cc->io_queue, &io->work);
1563 static void kcryptd_io_write(struct dm_crypt_io *io)
1565 struct bio *clone = io->ctx.bio_out;
1567 generic_make_request(clone);
1570 #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1572 static int dmcrypt_write(void *data)
1574 struct crypt_config *cc = data;
1575 struct dm_crypt_io *io;
1578 struct rb_root write_tree;
1579 struct blk_plug plug;
1581 DECLARE_WAITQUEUE(wait, current);
1583 spin_lock_irq(&cc->write_thread_wait.lock);
1586 if (!RB_EMPTY_ROOT(&cc->write_tree))
1589 set_current_state(TASK_INTERRUPTIBLE);
1590 __add_wait_queue(&cc->write_thread_wait, &wait);
1592 spin_unlock_irq(&cc->write_thread_wait.lock);
1594 if (unlikely(kthread_should_stop())) {
1595 set_current_state(TASK_RUNNING);
1596 remove_wait_queue(&cc->write_thread_wait, &wait);
1602 set_current_state(TASK_RUNNING);
1603 spin_lock_irq(&cc->write_thread_wait.lock);
1604 __remove_wait_queue(&cc->write_thread_wait, &wait);
1605 goto continue_locked;
1608 write_tree = cc->write_tree;
1609 cc->write_tree = RB_ROOT;
1610 spin_unlock_irq(&cc->write_thread_wait.lock);
1612 BUG_ON(rb_parent(write_tree.rb_node));
1615 * Note: we cannot walk the tree here with rb_next because
1616 * the structures may be freed when kcryptd_io_write is called.
1618 blk_start_plug(&plug);
1620 io = crypt_io_from_node(rb_first(&write_tree));
1621 rb_erase(&io->rb_node, &write_tree);
1622 kcryptd_io_write(io);
1623 } while (!RB_EMPTY_ROOT(&write_tree));
1624 blk_finish_plug(&plug);
1629 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
1631 struct bio *clone = io->ctx.bio_out;
1632 struct crypt_config *cc = io->cc;
1633 unsigned long flags;
1635 struct rb_node **rbp, *parent;
1637 if (unlikely(io->error < 0)) {
1638 crypt_free_buffer_pages(cc, clone);
1640 crypt_dec_pending(io);
1644 /* crypt_convert should have filled the clone bio */
1645 BUG_ON(io->ctx.iter_out.bi_size);
1647 clone->bi_iter.bi_sector = cc->start + io->sector;
1649 if (likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) {
1650 generic_make_request(clone);
1654 spin_lock_irqsave(&cc->write_thread_wait.lock, flags);
1655 rbp = &cc->write_tree.rb_node;
1657 sector = io->sector;
1660 if (sector < crypt_io_from_node(parent)->sector)
1661 rbp = &(*rbp)->rb_left;
1663 rbp = &(*rbp)->rb_right;
1665 rb_link_node(&io->rb_node, parent, rbp);
1666 rb_insert_color(&io->rb_node, &cc->write_tree);
1668 wake_up_locked(&cc->write_thread_wait);
1669 spin_unlock_irqrestore(&cc->write_thread_wait.lock, flags);
1672 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
1674 struct crypt_config *cc = io->cc;
1677 sector_t sector = io->sector;
1681 * Prevent io from disappearing until this function completes.
1683 crypt_inc_pending(io);
1684 crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
1686 clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
1687 if (unlikely(!clone)) {
1692 io->ctx.bio_out = clone;
1693 io->ctx.iter_out = clone->bi_iter;
1695 sector += bio_sectors(clone);
1697 crypt_inc_pending(io);
1698 r = crypt_convert(cc, &io->ctx);
1701 crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
1703 /* Encryption was already finished, submit io now */
1704 if (crypt_finished) {
1705 kcryptd_crypt_write_io_submit(io, 0);
1706 io->sector = sector;
1710 crypt_dec_pending(io);
1713 static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
1715 crypt_dec_pending(io);
1718 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
1720 struct crypt_config *cc = io->cc;
1723 crypt_inc_pending(io);
1725 crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
1728 r = crypt_convert(cc, &io->ctx);
1732 if (atomic_dec_and_test(&io->ctx.cc_pending))
1733 kcryptd_crypt_read_done(io);
1735 crypt_dec_pending(io);
1738 static void kcryptd_async_done(struct crypto_async_request *async_req,
1741 struct dm_crypt_request *dmreq = async_req->data;
1742 struct convert_context *ctx = dmreq->ctx;
1743 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1744 struct crypt_config *cc = io->cc;
1747 * A request from crypto driver backlog is going to be processed now,
1748 * finish the completion and continue in crypt_convert().
1749 * (Callback will be called for the second time for this request.)
1751 if (error == -EINPROGRESS) {
1752 complete(&ctx->restart);
1756 if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
1757 error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
1759 if (error == -EBADMSG) {
1760 DMERR_LIMIT("INTEGRITY AEAD ERROR, sector %llu",
1761 (unsigned long long)le64_to_cpu(*org_sector_of_dmreq(cc, dmreq)));
1762 io->error = -EILSEQ;
1763 } else if (error < 0)
1766 crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
1768 if (!atomic_dec_and_test(&ctx->cc_pending))
1771 if (bio_data_dir(io->base_bio) == READ)
1772 kcryptd_crypt_read_done(io);
1774 kcryptd_crypt_write_io_submit(io, 1);
1777 static void kcryptd_crypt(struct work_struct *work)
1779 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1781 if (bio_data_dir(io->base_bio) == READ)
1782 kcryptd_crypt_read_convert(io);
1784 kcryptd_crypt_write_convert(io);
1787 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
1789 struct crypt_config *cc = io->cc;
1791 INIT_WORK(&io->work, kcryptd_crypt);
1792 queue_work(cc->crypt_queue, &io->work);
1796 * Decode key from its hex representation
1798 static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
1805 for (i = 0; i < size; i++) {
1809 if (kstrtou8(buffer, 16, &key[i]))
1819 static void crypt_free_tfms_aead(struct crypt_config *cc)
1821 if (!cc->cipher_tfm.tfms_aead)
1824 if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
1825 crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
1826 cc->cipher_tfm.tfms_aead[0] = NULL;
1829 kfree(cc->cipher_tfm.tfms_aead);
1830 cc->cipher_tfm.tfms_aead = NULL;
1833 static void crypt_free_tfms_skcipher(struct crypt_config *cc)
1837 if (!cc->cipher_tfm.tfms)
1840 for (i = 0; i < cc->tfms_count; i++)
1841 if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
1842 crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
1843 cc->cipher_tfm.tfms[i] = NULL;
1846 kfree(cc->cipher_tfm.tfms);
1847 cc->cipher_tfm.tfms = NULL;
1850 static void crypt_free_tfms(struct crypt_config *cc)
1852 if (crypt_integrity_mode(cc))
1853 crypt_free_tfms_aead(cc);
1855 crypt_free_tfms_skcipher(cc);
1858 static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
1863 cc->cipher_tfm.tfms = kzalloc(cc->tfms_count *
1864 sizeof(struct crypto_skcipher *), GFP_KERNEL);
1865 if (!cc->cipher_tfm.tfms)
1868 for (i = 0; i < cc->tfms_count; i++) {
1869 cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0, 0);
1870 if (IS_ERR(cc->cipher_tfm.tfms[i])) {
1871 err = PTR_ERR(cc->cipher_tfm.tfms[i]);
1872 crypt_free_tfms(cc);
1880 static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
1882 char *authenc = NULL;
1885 cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
1886 if (!cc->cipher_tfm.tfms)
1889 /* Compose AEAD cipher with autenc(authenticator,cipher) structure */
1890 if (crypt_integrity_hmac(cc)) {
1891 authenc = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
1894 err = snprintf(authenc, CRYPTO_MAX_ALG_NAME,
1895 "authenc(%s,%s)", cc->cipher_auth, ciphermode);
1900 ciphermode = authenc;
1903 cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0, 0);
1904 if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
1905 err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
1906 crypt_free_tfms(cc);
1914 static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
1916 if (crypt_integrity_mode(cc))
1917 return crypt_alloc_tfms_aead(cc, ciphermode);
1919 return crypt_alloc_tfms_skcipher(cc, ciphermode);
1922 static unsigned crypt_subkey_size(struct crypt_config *cc)
1924 return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
1927 static unsigned crypt_authenckey_size(struct crypt_config *cc)
1929 return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
1933 * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
1934 * the key must be for some reason in special format.
1935 * This funcion converts cc->key to this special format.
1937 static void crypt_copy_authenckey(char *p, const void *key,
1938 unsigned enckeylen, unsigned authkeylen)
1940 struct crypto_authenc_key_param *param;
1943 rta = (struct rtattr *)p;
1944 param = RTA_DATA(rta);
1945 param->enckeylen = cpu_to_be32(enckeylen);
1946 rta->rta_len = RTA_LENGTH(sizeof(*param));
1947 rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
1948 p += RTA_SPACE(sizeof(*param));
1949 memcpy(p, key + enckeylen, authkeylen);
1951 memcpy(p, key, enckeylen);
1954 static int crypt_setkey(struct crypt_config *cc)
1956 unsigned subkey_size;
1959 /* Ignore extra keys (which are used for IV etc) */
1960 subkey_size = crypt_subkey_size(cc);
1962 if (crypt_integrity_hmac(cc))
1963 crypt_copy_authenckey(cc->authenc_key, cc->key,
1964 subkey_size - cc->key_mac_size,
1966 for (i = 0; i < cc->tfms_count; i++) {
1967 if (crypt_integrity_aead(cc))
1968 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
1969 cc->key + (i * subkey_size),
1971 else if (crypt_integrity_hmac(cc))
1972 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
1973 cc->authenc_key, crypt_authenckey_size(cc));
1975 r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
1976 cc->key + (i * subkey_size),
1982 if (crypt_integrity_hmac(cc))
1983 memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
1990 static bool contains_whitespace(const char *str)
1993 if (isspace(*str++))
1998 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2000 char *new_key_string, *key_desc;
2003 const struct user_key_payload *ukp;
2006 * Reject key_string with whitespace. dm core currently lacks code for
2007 * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2009 if (contains_whitespace(key_string)) {
2010 DMERR("whitespace chars not allowed in key string");
2014 /* look for next ':' separating key_type from key_description */
2015 key_desc = strpbrk(key_string, ":");
2016 if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2019 if (strncmp(key_string, "logon:", key_desc - key_string + 1) &&
2020 strncmp(key_string, "user:", key_desc - key_string + 1))
2023 new_key_string = kstrdup(key_string, GFP_KERNEL);
2024 if (!new_key_string)
2027 key = request_key(key_string[0] == 'l' ? &key_type_logon : &key_type_user,
2028 key_desc + 1, NULL);
2030 kzfree(new_key_string);
2031 return PTR_ERR(key);
2034 down_read(&key->sem);
2036 ukp = user_key_payload_locked(key);
2040 kzfree(new_key_string);
2041 return -EKEYREVOKED;
2044 if (cc->key_size != ukp->datalen) {
2047 kzfree(new_key_string);
2051 memcpy(cc->key, ukp->data, cc->key_size);
2056 /* clear the flag since following operations may invalidate previously valid key */
2057 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2059 ret = crypt_setkey(cc);
2061 /* wipe the kernel key payload copy in each case */
2062 memset(cc->key, 0, cc->key_size * sizeof(u8));
2065 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2066 kzfree(cc->key_string);
2067 cc->key_string = new_key_string;
2069 kzfree(new_key_string);
2074 static int get_key_size(char **key_string)
2079 if (*key_string[0] != ':')
2080 return strlen(*key_string) >> 1;
2082 /* look for next ':' in key string */
2083 colon = strpbrk(*key_string + 1, ":");
2087 if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2090 *key_string = colon;
2092 /* remaining key string should be :<logon|user>:<key_desc> */
2099 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2104 static int get_key_size(char **key_string)
2106 return (*key_string[0] == ':') ? -EINVAL : strlen(*key_string) >> 1;
2111 static int crypt_set_key(struct crypt_config *cc, char *key)
2114 int key_string_len = strlen(key);
2116 /* Hyphen (which gives a key_size of zero) means there is no key. */
2117 if (!cc->key_size && strcmp(key, "-"))
2120 /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2121 if (key[0] == ':') {
2122 r = crypt_set_keyring_key(cc, key + 1);
2126 /* clear the flag since following operations may invalidate previously valid key */
2127 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2129 /* wipe references to any kernel keyring key */
2130 kzfree(cc->key_string);
2131 cc->key_string = NULL;
2133 if (cc->key_size && crypt_decode_key(cc->key, key, cc->key_size) < 0)
2136 r = crypt_setkey(cc);
2138 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2141 /* Hex key string not needed after here, so wipe it. */
2142 memset(key, '0', key_string_len);
2147 static int crypt_wipe_key(struct crypt_config *cc)
2149 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2150 memset(&cc->key, 0, cc->key_size * sizeof(u8));
2151 kzfree(cc->key_string);
2152 cc->key_string = NULL;
2154 return crypt_setkey(cc);
2157 static void crypt_dtr(struct dm_target *ti)
2159 struct crypt_config *cc = ti->private;
2166 if (cc->write_thread)
2167 kthread_stop(cc->write_thread);
2170 destroy_workqueue(cc->io_queue);
2171 if (cc->crypt_queue)
2172 destroy_workqueue(cc->crypt_queue);
2174 crypt_free_tfms(cc);
2177 bioset_free(cc->bs);
2179 mempool_destroy(cc->page_pool);
2180 mempool_destroy(cc->req_pool);
2181 mempool_destroy(cc->tag_pool);
2183 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
2184 cc->iv_gen_ops->dtr(cc);
2187 dm_put_device(ti, cc->dev);
2190 kzfree(cc->cipher_string);
2191 kzfree(cc->key_string);
2192 kzfree(cc->cipher_auth);
2193 kzfree(cc->authenc_key);
2195 /* Must zero key material before freeing */
2199 static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
2201 struct crypt_config *cc = ti->private;
2203 if (crypt_integrity_mode(cc))
2204 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2206 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2208 if (crypt_integrity_hmac(cc)) {
2209 cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
2210 if (!cc->authenc_key) {
2211 ti->error = "Error allocating authenc key space";
2217 /* at least a 64 bit sector number should fit in our buffer */
2218 cc->iv_size = max(cc->iv_size,
2219 (unsigned int)(sizeof(u64) / sizeof(u8)));
2221 DMWARN("Selected cipher does not support IVs");
2225 /* Choose ivmode, see comments at iv code. */
2227 cc->iv_gen_ops = NULL;
2228 else if (strcmp(ivmode, "plain") == 0)
2229 cc->iv_gen_ops = &crypt_iv_plain_ops;
2230 else if (strcmp(ivmode, "plain64") == 0)
2231 cc->iv_gen_ops = &crypt_iv_plain64_ops;
2232 else if (strcmp(ivmode, "essiv") == 0)
2233 cc->iv_gen_ops = &crypt_iv_essiv_ops;
2234 else if (strcmp(ivmode, "benbi") == 0)
2235 cc->iv_gen_ops = &crypt_iv_benbi_ops;
2236 else if (strcmp(ivmode, "null") == 0)
2237 cc->iv_gen_ops = &crypt_iv_null_ops;
2238 else if (strcmp(ivmode, "lmk") == 0) {
2239 cc->iv_gen_ops = &crypt_iv_lmk_ops;
2241 * Version 2 and 3 is recognised according
2242 * to length of provided multi-key string.
2243 * If present (version 3), last key is used as IV seed.
2244 * All keys (including IV seed) are always the same size.
2246 if (cc->key_size % cc->key_parts) {
2248 cc->key_extra_size = cc->key_size / cc->key_parts;
2250 } else if (strcmp(ivmode, "tcw") == 0) {
2251 cc->iv_gen_ops = &crypt_iv_tcw_ops;
2252 cc->key_parts += 2; /* IV + whitening */
2253 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2254 } else if (strcmp(ivmode, "random") == 0) {
2255 cc->iv_gen_ops = &crypt_iv_random_ops;
2256 /* Need storage space in integrity fields. */
2257 cc->integrity_iv_size = cc->iv_size;
2259 ti->error = "Invalid IV mode";
2266 static int crypt_ctr_cipher(struct dm_target *ti,
2267 char *cipher_in, char *key)
2269 struct crypt_config *cc = ti->private;
2270 char *tmp, *cipher, *chainmode, *ivmode, *ivopts, *keycount;
2271 char *cipher_api = NULL;
2275 if (strchr(cipher_in, '(')) {
2276 ti->error = "Bad cipher specification";
2280 cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
2281 if (!cc->cipher_string)
2285 * Legacy dm-crypt cipher specification
2286 * cipher[:keycount]-mode-iv:ivopts
2289 keycount = strsep(&tmp, "-");
2290 cipher = strsep(&keycount, ":");
2294 else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
2295 !is_power_of_2(cc->tfms_count)) {
2296 ti->error = "Bad cipher key count specification";
2299 cc->key_parts = cc->tfms_count;
2301 cc->cipher = kstrdup(cipher, GFP_KERNEL);
2305 chainmode = strsep(&tmp, "-");
2306 ivopts = strsep(&tmp, "-");
2307 ivmode = strsep(&ivopts, ":");
2310 DMWARN("Ignoring unexpected additional cipher options");
2313 * For compatibility with the original dm-crypt mapping format, if
2314 * only the cipher name is supplied, use cbc-plain.
2316 if (!chainmode || (!strcmp(chainmode, "plain") && !ivmode)) {
2321 if (strcmp(chainmode, "ecb") && !ivmode) {
2322 ti->error = "IV mechanism required";
2326 cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
2330 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2331 "%s(%s)", chainmode, cipher);
2337 /* Allocate cipher */
2338 ret = crypt_alloc_tfms(cc, cipher_api);
2340 ti->error = "Error allocating crypto tfm";
2345 ret = crypt_ctr_ivmode(ti, ivmode);
2349 /* Initialize and set key */
2350 ret = crypt_set_key(cc, key);
2352 ti->error = "Error decoding and setting key";
2357 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
2358 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
2360 ti->error = "Error creating IV";
2365 /* Initialize IV (set keys for ESSIV etc) */
2366 if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
2367 ret = cc->iv_gen_ops->init(cc);
2369 ti->error = "Error initialising IV";
2380 ti->error = "Cannot allocate cipher strings";
2384 static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
2386 struct crypt_config *cc = ti->private;
2387 struct dm_arg_set as;
2388 static struct dm_arg _args[] = {
2389 {0, 3, "Invalid number of feature args"},
2391 unsigned int opt_params, val;
2392 const char *opt_string, *sval;
2395 /* Optional parameters */
2399 ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
2403 while (opt_params--) {
2404 opt_string = dm_shift_arg(&as);
2406 ti->error = "Not enough feature arguments";
2410 if (!strcasecmp(opt_string, "allow_discards"))
2411 ti->num_discard_bios = 1;
2413 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
2414 set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
2416 else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
2417 set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
2418 else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
2419 if (val == 0 || val > MAX_TAG_SIZE) {
2420 ti->error = "Invalid integrity arguments";
2423 cc->on_disk_tag_size = val;
2424 sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
2425 if (!strcasecmp(sval, "aead")) {
2426 set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
2427 } else if (!strncasecmp(sval, "hmac(", strlen("hmac("))) {
2428 struct crypto_ahash *hmac_tfm = crypto_alloc_ahash(sval, 0, 0);
2429 if (IS_ERR(hmac_tfm)) {
2430 ti->error = "Error initializing HMAC integrity hash.";
2431 return PTR_ERR(hmac_tfm);
2433 cc->key_mac_size = crypto_ahash_digestsize(hmac_tfm);
2434 crypto_free_ahash(hmac_tfm);
2435 set_bit(CRYPT_MODE_INTEGRITY_HMAC, &cc->cipher_flags);
2436 } else if (strcasecmp(sval, "none")) {
2437 ti->error = "Unknown integrity profile";
2441 cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
2442 if (!cc->cipher_auth)
2445 ti->error = "Invalid feature arguments";
2454 * Construct an encryption mapping:
2455 * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
2457 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
2459 struct crypt_config *cc;
2461 unsigned int align_mask;
2462 unsigned long long tmpll;
2464 size_t iv_size_padding, additional_req_size;
2468 ti->error = "Not enough arguments";
2472 key_size = get_key_size(&argv[1]);
2474 ti->error = "Cannot parse key size";
2478 cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
2480 ti->error = "Cannot allocate encryption context";
2483 cc->key_size = key_size;
2487 /* Optional parameters need to be read before cipher constructor */
2489 ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
2494 ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
2498 if (crypt_integrity_mode(cc)) {
2499 cc->dmreq_start = sizeof(struct aead_request);
2500 cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
2501 align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
2503 cc->dmreq_start = sizeof(struct skcipher_request);
2504 cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
2505 align_mask = crypto_skcipher_alignmask(any_tfm(cc));
2507 cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
2509 if (align_mask < CRYPTO_MINALIGN) {
2510 /* Allocate the padding exactly */
2511 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
2515 * If the cipher requires greater alignment than kmalloc
2516 * alignment, we don't know the exact position of the
2517 * initialization vector. We must assume worst case.
2519 iv_size_padding = align_mask;
2524 /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
2525 additional_req_size = sizeof(struct dm_crypt_request) +
2526 iv_size_padding + cc->iv_size +
2529 sizeof(unsigned int);
2531 cc->req_pool = mempool_create_kmalloc_pool(MIN_IOS, cc->dmreq_start + additional_req_size);
2532 if (!cc->req_pool) {
2533 ti->error = "Cannot allocate crypt request mempool";
2537 cc->per_bio_data_size = ti->per_io_data_size =
2538 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
2539 ARCH_KMALLOC_MINALIGN);
2541 cc->page_pool = mempool_create_page_pool(BIO_MAX_PAGES, 0);
2542 if (!cc->page_pool) {
2543 ti->error = "Cannot allocate page mempool";
2547 cc->bs = bioset_create(MIN_IOS, 0);
2549 ti->error = "Cannot allocate crypt bioset";
2553 mutex_init(&cc->bio_alloc_lock);
2556 if (sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) {
2557 ti->error = "Invalid iv_offset sector";
2560 cc->iv_offset = tmpll;
2562 ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
2564 ti->error = "Device lookup failed";
2569 if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1) {
2570 ti->error = "Invalid device sector";
2575 if (crypt_integrity_mode(cc) || cc->integrity_iv_size) {
2576 ret = crypt_integrity_ctr(cc, ti);
2580 cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
2581 if (!cc->tag_pool_max_sectors)
2582 cc->tag_pool_max_sectors = 1;
2584 cc->tag_pool = mempool_create_kmalloc_pool(MIN_IOS,
2585 cc->tag_pool_max_sectors * cc->on_disk_tag_size);
2586 if (!cc->tag_pool) {
2587 ti->error = "Cannot allocate integrity tags mempool";
2593 cc->io_queue = alloc_workqueue("kcryptd_io", WQ_MEM_RECLAIM, 1);
2594 if (!cc->io_queue) {
2595 ti->error = "Couldn't create kcryptd io queue";
2599 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
2600 cc->crypt_queue = alloc_workqueue("kcryptd", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM, 1);
2602 cc->crypt_queue = alloc_workqueue("kcryptd", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
2604 if (!cc->crypt_queue) {
2605 ti->error = "Couldn't create kcryptd queue";
2609 init_waitqueue_head(&cc->write_thread_wait);
2610 cc->write_tree = RB_ROOT;
2612 cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write");
2613 if (IS_ERR(cc->write_thread)) {
2614 ret = PTR_ERR(cc->write_thread);
2615 cc->write_thread = NULL;
2616 ti->error = "Couldn't spawn write thread";
2619 wake_up_process(cc->write_thread);
2621 ti->num_flush_bios = 1;
2622 ti->discard_zeroes_data_unsupported = true;
2631 static int crypt_map(struct dm_target *ti, struct bio *bio)
2633 struct dm_crypt_io *io;
2634 struct crypt_config *cc = ti->private;
2637 * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
2638 * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
2639 * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
2641 if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
2642 bio_op(bio) == REQ_OP_DISCARD)) {
2643 bio->bi_bdev = cc->dev->bdev;
2644 if (bio_sectors(bio))
2645 bio->bi_iter.bi_sector = cc->start +
2646 dm_target_offset(ti, bio->bi_iter.bi_sector);
2647 return DM_MAPIO_REMAPPED;
2651 * Check if bio is too large, split as needed.
2653 if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_PAGES << PAGE_SHIFT)) &&
2654 (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
2655 dm_accept_partial_bio(bio, ((BIO_MAX_PAGES << PAGE_SHIFT) >> SECTOR_SHIFT));
2657 io = dm_per_bio_data(bio, cc->per_bio_data_size);
2658 crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
2660 if (cc->on_disk_tag_size) {
2661 unsigned tag_len = cc->on_disk_tag_size * bio_sectors(bio);
2663 if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
2664 unlikely(!(io->integrity_metadata = kmalloc(tag_len,
2665 GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
2666 if (bio_sectors(bio) > cc->tag_pool_max_sectors)
2667 dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
2668 io->integrity_metadata = mempool_alloc(cc->tag_pool, GFP_NOIO);
2669 io->integrity_metadata_from_pool = true;
2673 if (crypt_integrity_mode(cc))
2674 io->ctx.r.req_aead = (struct aead_request *)(io + 1);
2676 io->ctx.r.req = (struct skcipher_request *)(io + 1);
2678 if (bio_data_dir(io->base_bio) == READ) {
2679 if (kcryptd_io_read(io, GFP_NOWAIT))
2680 kcryptd_queue_read(io);
2682 kcryptd_queue_crypt(io);
2684 return DM_MAPIO_SUBMITTED;
2687 static void crypt_status(struct dm_target *ti, status_type_t type,
2688 unsigned status_flags, char *result, unsigned maxlen)
2690 struct crypt_config *cc = ti->private;
2692 int num_feature_args = 0;
2695 case STATUSTYPE_INFO:
2699 case STATUSTYPE_TABLE:
2700 DMEMIT("%s ", cc->cipher_string);
2702 if (cc->key_size > 0) {
2704 DMEMIT(":%u:%s", cc->key_size, cc->key_string);
2706 for (i = 0; i < cc->key_size; i++)
2707 DMEMIT("%02x", cc->key[i]);
2711 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
2712 cc->dev->name, (unsigned long long)cc->start);
2714 num_feature_args += !!ti->num_discard_bios;
2715 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
2716 num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
2717 if (cc->on_disk_tag_size)
2719 if (num_feature_args) {
2720 DMEMIT(" %d", num_feature_args);
2721 if (ti->num_discard_bios)
2722 DMEMIT(" allow_discards");
2723 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
2724 DMEMIT(" same_cpu_crypt");
2725 if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
2726 DMEMIT(" submit_from_crypt_cpus");
2727 if (cc->on_disk_tag_size)
2728 DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
2735 static void crypt_postsuspend(struct dm_target *ti)
2737 struct crypt_config *cc = ti->private;
2739 set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
2742 static int crypt_preresume(struct dm_target *ti)
2744 struct crypt_config *cc = ti->private;
2746 if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
2747 DMERR("aborting resume - crypt key is not set.");
2754 static void crypt_resume(struct dm_target *ti)
2756 struct crypt_config *cc = ti->private;
2758 clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
2761 /* Message interface
2765 static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
2767 struct crypt_config *cc = ti->private;
2768 int key_size, ret = -EINVAL;
2773 if (!strcasecmp(argv[0], "key")) {
2774 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
2775 DMWARN("not suspended during key manipulation.");
2778 if (argc == 3 && !strcasecmp(argv[1], "set")) {
2779 /* The key size may not be changed. */
2780 key_size = get_key_size(&argv[2]);
2781 if (key_size < 0 || cc->key_size != key_size) {
2782 memset(argv[2], '0', strlen(argv[2]));
2786 ret = crypt_set_key(cc, argv[2]);
2789 if (cc->iv_gen_ops && cc->iv_gen_ops->init)
2790 ret = cc->iv_gen_ops->init(cc);
2793 if (argc == 2 && !strcasecmp(argv[1], "wipe")) {
2794 if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
2795 ret = cc->iv_gen_ops->wipe(cc);
2799 return crypt_wipe_key(cc);
2804 DMWARN("unrecognised message received.");
2808 static int crypt_iterate_devices(struct dm_target *ti,
2809 iterate_devices_callout_fn fn, void *data)
2811 struct crypt_config *cc = ti->private;
2813 return fn(ti, cc->dev, cc->start, ti->len, data);
2816 static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
2819 * Unfortunate constraint that is required to avoid the potential
2820 * for exceeding underlying device's max_segments limits -- due to
2821 * crypt_alloc_buffer() possibly allocating pages for the encryption
2822 * bio that are not as physically contiguous as the original bio.
2824 limits->max_segment_size = PAGE_SIZE;
2827 static struct target_type crypt_target = {
2829 .version = {1, 16, 0},
2830 .module = THIS_MODULE,
2834 .status = crypt_status,
2835 .postsuspend = crypt_postsuspend,
2836 .preresume = crypt_preresume,
2837 .resume = crypt_resume,
2838 .message = crypt_message,
2839 .iterate_devices = crypt_iterate_devices,
2840 .io_hints = crypt_io_hints,
2843 static int __init dm_crypt_init(void)
2847 r = dm_register_target(&crypt_target);
2849 DMERR("register failed %d", r);
2854 static void __exit dm_crypt_exit(void)
2856 dm_unregister_target(&crypt_target);
2859 module_init(dm_crypt_init);
2860 module_exit(dm_crypt_exit);
2862 MODULE_AUTHOR("Jana Saout <jana@saout.de>");
2863 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
2864 MODULE_LICENSE("GPL");