2 * Copyright (C) 2003 Jana Saout <jana@saout.de>
3 * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
4 * Copyright (C) 2006-2009 Red Hat, Inc. All rights reserved.
5 * Copyright (C) 2013 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/bio.h>
16 #include <linux/blkdev.h>
17 #include <linux/mempool.h>
18 #include <linux/slab.h>
19 #include <linux/crypto.h>
20 #include <linux/workqueue.h>
21 #include <linux/backing-dev.h>
22 #include <linux/atomic.h>
23 #include <linux/scatterlist.h>
25 #include <asm/unaligned.h>
26 #include <crypto/hash.h>
27 #include <crypto/md5.h>
28 #include <crypto/algapi.h>
30 #include <linux/device-mapper.h>
32 #define DM_MSG_PREFIX "crypt"
35 * context holding the current state of a multi-part conversion
37 struct convert_context {
38 struct completion restart;
41 struct bvec_iter iter_in;
42 struct bvec_iter iter_out;
45 struct ablkcipher_request *req;
49 * per bio private data
52 struct crypt_config *cc;
54 struct work_struct work;
56 struct convert_context ctx;
61 } CRYPTO_MINALIGN_ATTR;
63 struct dm_crypt_request {
64 struct convert_context *ctx;
65 struct scatterlist sg_in;
66 struct scatterlist sg_out;
72 struct crypt_iv_operations {
73 int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
75 void (*dtr)(struct crypt_config *cc);
76 int (*init)(struct crypt_config *cc);
77 int (*wipe)(struct crypt_config *cc);
78 int (*generator)(struct crypt_config *cc, u8 *iv,
79 struct dm_crypt_request *dmreq);
80 int (*post)(struct crypt_config *cc, u8 *iv,
81 struct dm_crypt_request *dmreq);
84 struct iv_essiv_private {
85 struct crypto_hash *hash_tfm;
89 struct iv_benbi_private {
93 #define LMK_SEED_SIZE 64 /* hash + 0 */
94 struct iv_lmk_private {
95 struct crypto_shash *hash_tfm;
99 #define TCW_WHITENING_SIZE 16
100 struct iv_tcw_private {
101 struct crypto_shash *crc32_tfm;
107 * Crypt: maps a linear range of a block device
108 * and encrypts / decrypts at the same time.
110 enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID, DM_CRYPT_SAME_CPU };
113 * The fields in here must be read only after initialization.
115 struct crypt_config {
120 * pool for per bio private data, crypto requests and
121 * encryption requeusts/buffer pages
125 mempool_t *page_pool;
127 struct mutex bio_alloc_lock;
129 struct workqueue_struct *io_queue;
130 struct workqueue_struct *crypt_queue;
135 struct crypt_iv_operations *iv_gen_ops;
137 struct iv_essiv_private essiv;
138 struct iv_benbi_private benbi;
139 struct iv_lmk_private lmk;
140 struct iv_tcw_private tcw;
143 unsigned int iv_size;
145 /* ESSIV: struct crypto_cipher *essiv_tfm */
147 struct crypto_ablkcipher **tfms;
151 * Layout of each crypto request:
153 * struct ablkcipher_request
156 * struct dm_crypt_request
160 * The padding is added so that dm_crypt_request and the IV are
163 unsigned int dmreq_start;
165 unsigned int per_bio_data_size;
168 unsigned int key_size;
169 unsigned int key_parts; /* independent parts in key buffer */
170 unsigned int key_extra_size; /* additional keys length */
176 static struct kmem_cache *_crypt_io_pool;
178 static void clone_init(struct dm_crypt_io *, struct bio *);
179 static void kcryptd_queue_crypt(struct dm_crypt_io *io);
180 static u8 *iv_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq);
183 * Use this to access cipher attributes that are the same for each CPU.
185 static struct crypto_ablkcipher *any_tfm(struct crypt_config *cc)
191 * Different IV generation algorithms:
193 * plain: the initial vector is the 32-bit little-endian version of the sector
194 * number, padded with zeros if necessary.
196 * plain64: the initial vector is the 64-bit little-endian version of the sector
197 * number, padded with zeros if necessary.
199 * essiv: "encrypted sector|salt initial vector", the sector number is
200 * encrypted with the bulk cipher using a salt as key. The salt
201 * should be derived from the bulk cipher's key via hashing.
203 * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
204 * (needed for LRW-32-AES and possible other narrow block modes)
206 * null: the initial vector is always zero. Provides compatibility with
207 * obsolete loop_fish2 devices. Do not use for new devices.
209 * lmk: Compatible implementation of the block chaining mode used
210 * by the Loop-AES block device encryption system
211 * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
212 * It operates on full 512 byte sectors and uses CBC
213 * with an IV derived from the sector number, the data and
214 * optionally extra IV seed.
215 * This means that after decryption the first block
216 * of sector must be tweaked according to decrypted data.
217 * Loop-AES can use three encryption schemes:
218 * version 1: is plain aes-cbc mode
219 * version 2: uses 64 multikey scheme with lmk IV generator
220 * version 3: the same as version 2 with additional IV seed
221 * (it uses 65 keys, last key is used as IV seed)
223 * tcw: Compatible implementation of the block chaining mode used
224 * by the TrueCrypt device encryption system (prior to version 4.1).
225 * For more info see: http://www.truecrypt.org
226 * It operates on full 512 byte sectors and uses CBC
227 * with an IV derived from initial key and the sector number.
228 * In addition, whitening value is applied on every sector, whitening
229 * is calculated from initial key, sector number and mixed using CRC32.
230 * Note that this encryption scheme is vulnerable to watermarking attacks
231 * and should be used for old compatible containers access only.
233 * plumb: unimplemented, see:
234 * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
237 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
238 struct dm_crypt_request *dmreq)
240 memset(iv, 0, cc->iv_size);
241 *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
246 static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
247 struct dm_crypt_request *dmreq)
249 memset(iv, 0, cc->iv_size);
250 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
255 /* Initialise ESSIV - compute salt but no local memory allocations */
256 static int crypt_iv_essiv_init(struct crypt_config *cc)
258 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
259 struct hash_desc desc;
260 struct scatterlist sg;
261 struct crypto_cipher *essiv_tfm;
264 sg_init_one(&sg, cc->key, cc->key_size);
265 desc.tfm = essiv->hash_tfm;
266 desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
268 err = crypto_hash_digest(&desc, &sg, cc->key_size, essiv->salt);
272 essiv_tfm = cc->iv_private;
274 err = crypto_cipher_setkey(essiv_tfm, essiv->salt,
275 crypto_hash_digestsize(essiv->hash_tfm));
282 /* Wipe salt and reset key derived from volume key */
283 static int crypt_iv_essiv_wipe(struct crypt_config *cc)
285 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
286 unsigned salt_size = crypto_hash_digestsize(essiv->hash_tfm);
287 struct crypto_cipher *essiv_tfm;
290 memset(essiv->salt, 0, salt_size);
292 essiv_tfm = cc->iv_private;
293 r = crypto_cipher_setkey(essiv_tfm, essiv->salt, salt_size);
300 /* Set up per cpu cipher state */
301 static struct crypto_cipher *setup_essiv_cpu(struct crypt_config *cc,
302 struct dm_target *ti,
303 u8 *salt, unsigned saltsize)
305 struct crypto_cipher *essiv_tfm;
308 /* Setup the essiv_tfm with the given salt */
309 essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
310 if (IS_ERR(essiv_tfm)) {
311 ti->error = "Error allocating crypto tfm for ESSIV";
315 if (crypto_cipher_blocksize(essiv_tfm) !=
316 crypto_ablkcipher_ivsize(any_tfm(cc))) {
317 ti->error = "Block size of ESSIV cipher does "
318 "not match IV size of block cipher";
319 crypto_free_cipher(essiv_tfm);
320 return ERR_PTR(-EINVAL);
323 err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
325 ti->error = "Failed to set key for ESSIV cipher";
326 crypto_free_cipher(essiv_tfm);
333 static void crypt_iv_essiv_dtr(struct crypt_config *cc)
335 struct crypto_cipher *essiv_tfm;
336 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
338 crypto_free_hash(essiv->hash_tfm);
339 essiv->hash_tfm = NULL;
344 essiv_tfm = cc->iv_private;
347 crypto_free_cipher(essiv_tfm);
349 cc->iv_private = NULL;
352 static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
355 struct crypto_cipher *essiv_tfm = NULL;
356 struct crypto_hash *hash_tfm = NULL;
361 ti->error = "Digest algorithm missing for ESSIV mode";
365 /* Allocate hash algorithm */
366 hash_tfm = crypto_alloc_hash(opts, 0, CRYPTO_ALG_ASYNC);
367 if (IS_ERR(hash_tfm)) {
368 ti->error = "Error initializing ESSIV hash";
369 err = PTR_ERR(hash_tfm);
373 salt = kzalloc(crypto_hash_digestsize(hash_tfm), GFP_KERNEL);
375 ti->error = "Error kmallocing salt storage in ESSIV";
380 cc->iv_gen_private.essiv.salt = salt;
381 cc->iv_gen_private.essiv.hash_tfm = hash_tfm;
383 essiv_tfm = setup_essiv_cpu(cc, ti, salt,
384 crypto_hash_digestsize(hash_tfm));
385 if (IS_ERR(essiv_tfm)) {
386 crypt_iv_essiv_dtr(cc);
387 return PTR_ERR(essiv_tfm);
389 cc->iv_private = essiv_tfm;
394 if (hash_tfm && !IS_ERR(hash_tfm))
395 crypto_free_hash(hash_tfm);
400 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
401 struct dm_crypt_request *dmreq)
403 struct crypto_cipher *essiv_tfm = cc->iv_private;
405 memset(iv, 0, cc->iv_size);
406 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
407 crypto_cipher_encrypt_one(essiv_tfm, iv, iv);
412 static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
415 unsigned bs = crypto_ablkcipher_blocksize(any_tfm(cc));
418 /* we need to calculate how far we must shift the sector count
419 * to get the cipher block count, we use this shift in _gen */
421 if (1 << log != bs) {
422 ti->error = "cypher blocksize is not a power of 2";
427 ti->error = "cypher blocksize is > 512";
431 cc->iv_gen_private.benbi.shift = 9 - log;
436 static void crypt_iv_benbi_dtr(struct crypt_config *cc)
440 static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
441 struct dm_crypt_request *dmreq)
445 memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
447 val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
448 put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
453 static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
454 struct dm_crypt_request *dmreq)
456 memset(iv, 0, cc->iv_size);
461 static void crypt_iv_lmk_dtr(struct crypt_config *cc)
463 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
465 if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
466 crypto_free_shash(lmk->hash_tfm);
467 lmk->hash_tfm = NULL;
473 static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
476 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
478 lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
479 if (IS_ERR(lmk->hash_tfm)) {
480 ti->error = "Error initializing LMK hash";
481 return PTR_ERR(lmk->hash_tfm);
484 /* No seed in LMK version 2 */
485 if (cc->key_parts == cc->tfms_count) {
490 lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
492 crypt_iv_lmk_dtr(cc);
493 ti->error = "Error kmallocing seed storage in LMK";
500 static int crypt_iv_lmk_init(struct crypt_config *cc)
502 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
503 int subkey_size = cc->key_size / cc->key_parts;
505 /* LMK seed is on the position of LMK_KEYS + 1 key */
507 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
508 crypto_shash_digestsize(lmk->hash_tfm));
513 static int crypt_iv_lmk_wipe(struct crypt_config *cc)
515 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
518 memset(lmk->seed, 0, LMK_SEED_SIZE);
523 static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
524 struct dm_crypt_request *dmreq,
527 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
528 SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
529 struct md5_state md5state;
533 desc->tfm = lmk->hash_tfm;
534 desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
536 r = crypto_shash_init(desc);
541 r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
546 /* Sector is always 512B, block size 16, add data of blocks 1-31 */
547 r = crypto_shash_update(desc, data + 16, 16 * 31);
551 /* Sector is cropped to 56 bits here */
552 buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
553 buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
554 buf[2] = cpu_to_le32(4024);
556 r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
560 /* No MD5 padding here */
561 r = crypto_shash_export(desc, &md5state);
565 for (i = 0; i < MD5_HASH_WORDS; i++)
566 __cpu_to_le32s(&md5state.hash[i]);
567 memcpy(iv, &md5state.hash, cc->iv_size);
572 static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
573 struct dm_crypt_request *dmreq)
578 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
579 src = kmap_atomic(sg_page(&dmreq->sg_in));
580 r = crypt_iv_lmk_one(cc, iv, dmreq, src + dmreq->sg_in.offset);
583 memset(iv, 0, cc->iv_size);
588 static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
589 struct dm_crypt_request *dmreq)
594 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
597 dst = kmap_atomic(sg_page(&dmreq->sg_out));
598 r = crypt_iv_lmk_one(cc, iv, dmreq, dst + dmreq->sg_out.offset);
600 /* Tweak the first block of plaintext sector */
602 crypto_xor(dst + dmreq->sg_out.offset, iv, cc->iv_size);
608 static void crypt_iv_tcw_dtr(struct crypt_config *cc)
610 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
612 kzfree(tcw->iv_seed);
614 kzfree(tcw->whitening);
615 tcw->whitening = NULL;
617 if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
618 crypto_free_shash(tcw->crc32_tfm);
619 tcw->crc32_tfm = NULL;
622 static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
625 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
627 if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
628 ti->error = "Wrong key size for TCW";
632 tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
633 if (IS_ERR(tcw->crc32_tfm)) {
634 ti->error = "Error initializing CRC32 in TCW";
635 return PTR_ERR(tcw->crc32_tfm);
638 tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
639 tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
640 if (!tcw->iv_seed || !tcw->whitening) {
641 crypt_iv_tcw_dtr(cc);
642 ti->error = "Error allocating seed storage in TCW";
649 static int crypt_iv_tcw_init(struct crypt_config *cc)
651 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
652 int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
654 memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
655 memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
661 static int crypt_iv_tcw_wipe(struct crypt_config *cc)
663 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
665 memset(tcw->iv_seed, 0, cc->iv_size);
666 memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
671 static int crypt_iv_tcw_whitening(struct crypt_config *cc,
672 struct dm_crypt_request *dmreq,
675 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
676 u64 sector = cpu_to_le64((u64)dmreq->iv_sector);
677 u8 buf[TCW_WHITENING_SIZE];
678 SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
681 /* xor whitening with sector number */
682 memcpy(buf, tcw->whitening, TCW_WHITENING_SIZE);
683 crypto_xor(buf, (u8 *)§or, 8);
684 crypto_xor(&buf[8], (u8 *)§or, 8);
686 /* calculate crc32 for every 32bit part and xor it */
687 desc->tfm = tcw->crc32_tfm;
688 desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
689 for (i = 0; i < 4; i++) {
690 r = crypto_shash_init(desc);
693 r = crypto_shash_update(desc, &buf[i * 4], 4);
696 r = crypto_shash_final(desc, &buf[i * 4]);
700 crypto_xor(&buf[0], &buf[12], 4);
701 crypto_xor(&buf[4], &buf[8], 4);
703 /* apply whitening (8 bytes) to whole sector */
704 for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
705 crypto_xor(data + i * 8, buf, 8);
707 memzero_explicit(buf, sizeof(buf));
711 static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
712 struct dm_crypt_request *dmreq)
714 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
715 u64 sector = cpu_to_le64((u64)dmreq->iv_sector);
719 /* Remove whitening from ciphertext */
720 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
721 src = kmap_atomic(sg_page(&dmreq->sg_in));
722 r = crypt_iv_tcw_whitening(cc, dmreq, src + dmreq->sg_in.offset);
727 memcpy(iv, tcw->iv_seed, cc->iv_size);
728 crypto_xor(iv, (u8 *)§or, 8);
730 crypto_xor(&iv[8], (u8 *)§or, cc->iv_size - 8);
735 static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
736 struct dm_crypt_request *dmreq)
741 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
744 /* Apply whitening on ciphertext */
745 dst = kmap_atomic(sg_page(&dmreq->sg_out));
746 r = crypt_iv_tcw_whitening(cc, dmreq, dst + dmreq->sg_out.offset);
752 static struct crypt_iv_operations crypt_iv_plain_ops = {
753 .generator = crypt_iv_plain_gen
756 static struct crypt_iv_operations crypt_iv_plain64_ops = {
757 .generator = crypt_iv_plain64_gen
760 static struct crypt_iv_operations crypt_iv_essiv_ops = {
761 .ctr = crypt_iv_essiv_ctr,
762 .dtr = crypt_iv_essiv_dtr,
763 .init = crypt_iv_essiv_init,
764 .wipe = crypt_iv_essiv_wipe,
765 .generator = crypt_iv_essiv_gen
768 static struct crypt_iv_operations crypt_iv_benbi_ops = {
769 .ctr = crypt_iv_benbi_ctr,
770 .dtr = crypt_iv_benbi_dtr,
771 .generator = crypt_iv_benbi_gen
774 static struct crypt_iv_operations crypt_iv_null_ops = {
775 .generator = crypt_iv_null_gen
778 static struct crypt_iv_operations crypt_iv_lmk_ops = {
779 .ctr = crypt_iv_lmk_ctr,
780 .dtr = crypt_iv_lmk_dtr,
781 .init = crypt_iv_lmk_init,
782 .wipe = crypt_iv_lmk_wipe,
783 .generator = crypt_iv_lmk_gen,
784 .post = crypt_iv_lmk_post
787 static struct crypt_iv_operations crypt_iv_tcw_ops = {
788 .ctr = crypt_iv_tcw_ctr,
789 .dtr = crypt_iv_tcw_dtr,
790 .init = crypt_iv_tcw_init,
791 .wipe = crypt_iv_tcw_wipe,
792 .generator = crypt_iv_tcw_gen,
793 .post = crypt_iv_tcw_post
796 static void crypt_convert_init(struct crypt_config *cc,
797 struct convert_context *ctx,
798 struct bio *bio_out, struct bio *bio_in,
801 ctx->bio_in = bio_in;
802 ctx->bio_out = bio_out;
804 ctx->iter_in = bio_in->bi_iter;
806 ctx->iter_out = bio_out->bi_iter;
807 ctx->cc_sector = sector + cc->iv_offset;
808 init_completion(&ctx->restart);
811 static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
812 struct ablkcipher_request *req)
814 return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
817 static struct ablkcipher_request *req_of_dmreq(struct crypt_config *cc,
818 struct dm_crypt_request *dmreq)
820 return (struct ablkcipher_request *)((char *)dmreq - cc->dmreq_start);
823 static u8 *iv_of_dmreq(struct crypt_config *cc,
824 struct dm_crypt_request *dmreq)
826 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
827 crypto_ablkcipher_alignmask(any_tfm(cc)) + 1);
830 static int crypt_convert_block(struct crypt_config *cc,
831 struct convert_context *ctx,
832 struct ablkcipher_request *req)
834 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
835 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
836 struct dm_crypt_request *dmreq;
840 dmreq = dmreq_of_req(cc, req);
841 iv = iv_of_dmreq(cc, dmreq);
843 dmreq->iv_sector = ctx->cc_sector;
845 sg_init_table(&dmreq->sg_in, 1);
846 sg_set_page(&dmreq->sg_in, bv_in.bv_page, 1 << SECTOR_SHIFT,
849 sg_init_table(&dmreq->sg_out, 1);
850 sg_set_page(&dmreq->sg_out, bv_out.bv_page, 1 << SECTOR_SHIFT,
853 bio_advance_iter(ctx->bio_in, &ctx->iter_in, 1 << SECTOR_SHIFT);
854 bio_advance_iter(ctx->bio_out, &ctx->iter_out, 1 << SECTOR_SHIFT);
856 if (cc->iv_gen_ops) {
857 r = cc->iv_gen_ops->generator(cc, iv, dmreq);
862 ablkcipher_request_set_crypt(req, &dmreq->sg_in, &dmreq->sg_out,
863 1 << SECTOR_SHIFT, iv);
865 if (bio_data_dir(ctx->bio_in) == WRITE)
866 r = crypto_ablkcipher_encrypt(req);
868 r = crypto_ablkcipher_decrypt(req);
870 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
871 r = cc->iv_gen_ops->post(cc, iv, dmreq);
876 static void kcryptd_async_done(struct crypto_async_request *async_req,
879 static void crypt_alloc_req(struct crypt_config *cc,
880 struct convert_context *ctx)
882 unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
885 ctx->req = mempool_alloc(cc->req_pool, GFP_NOIO);
887 ablkcipher_request_set_tfm(ctx->req, cc->tfms[key_index]);
888 ablkcipher_request_set_callback(ctx->req,
889 CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
890 kcryptd_async_done, dmreq_of_req(cc, ctx->req));
893 static void crypt_free_req(struct crypt_config *cc,
894 struct ablkcipher_request *req, struct bio *base_bio)
896 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
898 if ((struct ablkcipher_request *)(io + 1) != req)
899 mempool_free(req, cc->req_pool);
903 * Encrypt / decrypt data from one bio to another one (can be the same one)
905 static int crypt_convert(struct crypt_config *cc,
906 struct convert_context *ctx)
910 atomic_set(&ctx->cc_pending, 1);
912 while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
914 crypt_alloc_req(cc, ctx);
916 atomic_inc(&ctx->cc_pending);
918 r = crypt_convert_block(cc, ctx, ctx->req);
923 wait_for_completion(&ctx->restart);
924 reinit_completion(&ctx->restart);
933 atomic_dec(&ctx->cc_pending);
940 atomic_dec(&ctx->cc_pending);
948 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
951 * Generate a new unfragmented bio with the given size
952 * This should never violate the device limitations
954 * This function may be called concurrently. If we allocate from the mempool
955 * concurrently, there is a possibility of deadlock. For example, if we have
956 * mempool of 256 pages, two processes, each wanting 256, pages allocate from
957 * the mempool concurrently, it may deadlock in a situation where both processes
958 * have allocated 128 pages and the mempool is exhausted.
960 * In order to avoid this scenario we allocate the pages under a mutex.
962 * In order to not degrade performance with excessive locking, we try
963 * non-blocking allocations without a mutex first but on failure we fallback
964 * to blocking allocations with a mutex.
966 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
968 struct crypt_config *cc = io->cc;
970 unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
971 gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
972 unsigned i, len, remaining_size;
974 struct bio_vec *bvec;
977 if (unlikely(gfp_mask & __GFP_WAIT))
978 mutex_lock(&cc->bio_alloc_lock);
980 clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, cc->bs);
984 clone_init(io, clone);
986 remaining_size = size;
988 for (i = 0; i < nr_iovecs; i++) {
989 page = mempool_alloc(cc->page_pool, gfp_mask);
991 crypt_free_buffer_pages(cc, clone);
993 gfp_mask |= __GFP_WAIT;
997 len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
999 bvec = &clone->bi_io_vec[clone->bi_vcnt++];
1000 bvec->bv_page = page;
1002 bvec->bv_offset = 0;
1004 clone->bi_iter.bi_size += len;
1006 remaining_size -= len;
1010 if (unlikely(gfp_mask & __GFP_WAIT))
1011 mutex_unlock(&cc->bio_alloc_lock);
1016 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1021 bio_for_each_segment_all(bv, clone, i) {
1022 BUG_ON(!bv->bv_page);
1023 mempool_free(bv->bv_page, cc->page_pool);
1028 static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1029 struct bio *bio, sector_t sector)
1033 io->sector = sector;
1036 atomic_set(&io->io_pending, 0);
1039 static void crypt_inc_pending(struct dm_crypt_io *io)
1041 atomic_inc(&io->io_pending);
1045 * One of the bios was finished. Check for completion of
1046 * the whole request and correctly clean up the buffer.
1048 static void crypt_dec_pending(struct dm_crypt_io *io)
1050 struct crypt_config *cc = io->cc;
1051 struct bio *base_bio = io->base_bio;
1052 int error = io->error;
1054 if (!atomic_dec_and_test(&io->io_pending))
1058 crypt_free_req(cc, io->ctx.req, base_bio);
1059 if (io != dm_per_bio_data(base_bio, cc->per_bio_data_size))
1060 mempool_free(io, cc->io_pool);
1062 bio_endio(base_bio, error);
1066 * kcryptd/kcryptd_io:
1068 * Needed because it would be very unwise to do decryption in an
1069 * interrupt context.
1071 * kcryptd performs the actual encryption or decryption.
1073 * kcryptd_io performs the IO submission.
1075 * They must be separated as otherwise the final stages could be
1076 * starved by new requests which can block in the first stages due
1077 * to memory allocation.
1079 * The work is done per CPU global for all dm-crypt instances.
1080 * They should not depend on each other and do not block.
1082 static void crypt_endio(struct bio *clone, int error)
1084 struct dm_crypt_io *io = clone->bi_private;
1085 struct crypt_config *cc = io->cc;
1086 unsigned rw = bio_data_dir(clone);
1088 if (unlikely(!bio_flagged(clone, BIO_UPTODATE) && !error))
1092 * free the processed pages
1095 crypt_free_buffer_pages(cc, clone);
1099 if (rw == READ && !error) {
1100 kcryptd_queue_crypt(io);
1104 if (unlikely(error))
1107 crypt_dec_pending(io);
1110 static void clone_init(struct dm_crypt_io *io, struct bio *clone)
1112 struct crypt_config *cc = io->cc;
1114 clone->bi_private = io;
1115 clone->bi_end_io = crypt_endio;
1116 clone->bi_bdev = cc->dev->bdev;
1117 clone->bi_rw = io->base_bio->bi_rw;
1120 static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
1122 struct crypt_config *cc = io->cc;
1123 struct bio *base_bio = io->base_bio;
1127 * The block layer might modify the bvec array, so always
1128 * copy the required bvecs because we need the original
1129 * one in order to decrypt the whole bio data *afterwards*.
1131 clone = bio_clone_bioset(base_bio, gfp, cc->bs);
1135 crypt_inc_pending(io);
1137 clone_init(io, clone);
1138 clone->bi_iter.bi_sector = cc->start + io->sector;
1140 generic_make_request(clone);
1144 static void kcryptd_io_write(struct dm_crypt_io *io)
1146 struct bio *clone = io->ctx.bio_out;
1147 generic_make_request(clone);
1150 static void kcryptd_io(struct work_struct *work)
1152 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1154 if (bio_data_dir(io->base_bio) == READ) {
1155 crypt_inc_pending(io);
1156 if (kcryptd_io_read(io, GFP_NOIO))
1157 io->error = -ENOMEM;
1158 crypt_dec_pending(io);
1160 kcryptd_io_write(io);
1163 static void kcryptd_queue_io(struct dm_crypt_io *io)
1165 struct crypt_config *cc = io->cc;
1167 INIT_WORK(&io->work, kcryptd_io);
1168 queue_work(cc->io_queue, &io->work);
1171 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
1173 struct bio *clone = io->ctx.bio_out;
1174 struct crypt_config *cc = io->cc;
1176 if (unlikely(io->error < 0)) {
1177 crypt_free_buffer_pages(cc, clone);
1179 crypt_dec_pending(io);
1183 /* crypt_convert should have filled the clone bio */
1184 BUG_ON(io->ctx.iter_out.bi_size);
1186 clone->bi_iter.bi_sector = cc->start + io->sector;
1189 kcryptd_queue_io(io);
1191 generic_make_request(clone);
1194 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
1196 struct crypt_config *cc = io->cc;
1199 sector_t sector = io->sector;
1203 * Prevent io from disappearing until this function completes.
1205 crypt_inc_pending(io);
1206 crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
1208 clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
1209 if (unlikely(!clone)) {
1214 io->ctx.bio_out = clone;
1215 io->ctx.iter_out = clone->bi_iter;
1217 sector += bio_sectors(clone);
1219 crypt_inc_pending(io);
1220 r = crypt_convert(cc, &io->ctx);
1223 crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
1225 /* Encryption was already finished, submit io now */
1226 if (crypt_finished) {
1227 kcryptd_crypt_write_io_submit(io, 0);
1228 io->sector = sector;
1232 crypt_dec_pending(io);
1235 static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
1237 crypt_dec_pending(io);
1240 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
1242 struct crypt_config *cc = io->cc;
1245 crypt_inc_pending(io);
1247 crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
1250 r = crypt_convert(cc, &io->ctx);
1254 if (atomic_dec_and_test(&io->ctx.cc_pending))
1255 kcryptd_crypt_read_done(io);
1257 crypt_dec_pending(io);
1260 static void kcryptd_async_done(struct crypto_async_request *async_req,
1263 struct dm_crypt_request *dmreq = async_req->data;
1264 struct convert_context *ctx = dmreq->ctx;
1265 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1266 struct crypt_config *cc = io->cc;
1268 if (error == -EINPROGRESS) {
1269 complete(&ctx->restart);
1273 if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
1274 error = cc->iv_gen_ops->post(cc, iv_of_dmreq(cc, dmreq), dmreq);
1279 crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
1281 if (!atomic_dec_and_test(&ctx->cc_pending))
1284 if (bio_data_dir(io->base_bio) == READ)
1285 kcryptd_crypt_read_done(io);
1287 kcryptd_crypt_write_io_submit(io, 1);
1290 static void kcryptd_crypt(struct work_struct *work)
1292 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1294 if (bio_data_dir(io->base_bio) == READ)
1295 kcryptd_crypt_read_convert(io);
1297 kcryptd_crypt_write_convert(io);
1300 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
1302 struct crypt_config *cc = io->cc;
1304 INIT_WORK(&io->work, kcryptd_crypt);
1305 queue_work(cc->crypt_queue, &io->work);
1309 * Decode key from its hex representation
1311 static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
1318 for (i = 0; i < size; i++) {
1322 if (kstrtou8(buffer, 16, &key[i]))
1332 static void crypt_free_tfms(struct crypt_config *cc)
1339 for (i = 0; i < cc->tfms_count; i++)
1340 if (cc->tfms[i] && !IS_ERR(cc->tfms[i])) {
1341 crypto_free_ablkcipher(cc->tfms[i]);
1349 static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
1354 cc->tfms = kmalloc(cc->tfms_count * sizeof(struct crypto_ablkcipher *),
1359 for (i = 0; i < cc->tfms_count; i++) {
1360 cc->tfms[i] = crypto_alloc_ablkcipher(ciphermode, 0, 0);
1361 if (IS_ERR(cc->tfms[i])) {
1362 err = PTR_ERR(cc->tfms[i]);
1363 crypt_free_tfms(cc);
1371 static int crypt_setkey_allcpus(struct crypt_config *cc)
1373 unsigned subkey_size;
1376 /* Ignore extra keys (which are used for IV etc) */
1377 subkey_size = (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
1379 for (i = 0; i < cc->tfms_count; i++) {
1380 r = crypto_ablkcipher_setkey(cc->tfms[i],
1381 cc->key + (i * subkey_size),
1390 static int crypt_set_key(struct crypt_config *cc, char *key)
1393 int key_string_len = strlen(key);
1395 /* The key size may not be changed. */
1396 if (cc->key_size != (key_string_len >> 1))
1399 /* Hyphen (which gives a key_size of zero) means there is no key. */
1400 if (!cc->key_size && strcmp(key, "-"))
1403 if (cc->key_size && crypt_decode_key(cc->key, key, cc->key_size) < 0)
1406 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
1408 r = crypt_setkey_allcpus(cc);
1411 /* Hex key string not needed after here, so wipe it. */
1412 memset(key, '0', key_string_len);
1417 static int crypt_wipe_key(struct crypt_config *cc)
1419 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
1420 memset(&cc->key, 0, cc->key_size * sizeof(u8));
1422 return crypt_setkey_allcpus(cc);
1425 static void crypt_dtr(struct dm_target *ti)
1427 struct crypt_config *cc = ti->private;
1435 destroy_workqueue(cc->io_queue);
1436 if (cc->crypt_queue)
1437 destroy_workqueue(cc->crypt_queue);
1439 crypt_free_tfms(cc);
1442 bioset_free(cc->bs);
1445 mempool_destroy(cc->page_pool);
1447 mempool_destroy(cc->req_pool);
1449 mempool_destroy(cc->io_pool);
1451 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
1452 cc->iv_gen_ops->dtr(cc);
1455 dm_put_device(ti, cc->dev);
1458 kzfree(cc->cipher_string);
1460 /* Must zero key material before freeing */
1464 static int crypt_ctr_cipher(struct dm_target *ti,
1465 char *cipher_in, char *key)
1467 struct crypt_config *cc = ti->private;
1468 char *tmp, *cipher, *chainmode, *ivmode, *ivopts, *keycount;
1469 char *cipher_api = NULL;
1473 /* Convert to crypto api definition? */
1474 if (strchr(cipher_in, '(')) {
1475 ti->error = "Bad cipher specification";
1479 cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
1480 if (!cc->cipher_string)
1484 * Legacy dm-crypt cipher specification
1485 * cipher[:keycount]-mode-iv:ivopts
1488 keycount = strsep(&tmp, "-");
1489 cipher = strsep(&keycount, ":");
1493 else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
1494 !is_power_of_2(cc->tfms_count)) {
1495 ti->error = "Bad cipher key count specification";
1498 cc->key_parts = cc->tfms_count;
1499 cc->key_extra_size = 0;
1501 cc->cipher = kstrdup(cipher, GFP_KERNEL);
1505 chainmode = strsep(&tmp, "-");
1506 ivopts = strsep(&tmp, "-");
1507 ivmode = strsep(&ivopts, ":");
1510 DMWARN("Ignoring unexpected additional cipher options");
1513 * For compatibility with the original dm-crypt mapping format, if
1514 * only the cipher name is supplied, use cbc-plain.
1516 if (!chainmode || (!strcmp(chainmode, "plain") && !ivmode)) {
1521 if (strcmp(chainmode, "ecb") && !ivmode) {
1522 ti->error = "IV mechanism required";
1526 cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
1530 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
1531 "%s(%s)", chainmode, cipher);
1537 /* Allocate cipher */
1538 ret = crypt_alloc_tfms(cc, cipher_api);
1540 ti->error = "Error allocating crypto tfm";
1545 cc->iv_size = crypto_ablkcipher_ivsize(any_tfm(cc));
1547 /* at least a 64 bit sector number should fit in our buffer */
1548 cc->iv_size = max(cc->iv_size,
1549 (unsigned int)(sizeof(u64) / sizeof(u8)));
1551 DMWARN("Selected cipher does not support IVs");
1555 /* Choose ivmode, see comments at iv code. */
1557 cc->iv_gen_ops = NULL;
1558 else if (strcmp(ivmode, "plain") == 0)
1559 cc->iv_gen_ops = &crypt_iv_plain_ops;
1560 else if (strcmp(ivmode, "plain64") == 0)
1561 cc->iv_gen_ops = &crypt_iv_plain64_ops;
1562 else if (strcmp(ivmode, "essiv") == 0)
1563 cc->iv_gen_ops = &crypt_iv_essiv_ops;
1564 else if (strcmp(ivmode, "benbi") == 0)
1565 cc->iv_gen_ops = &crypt_iv_benbi_ops;
1566 else if (strcmp(ivmode, "null") == 0)
1567 cc->iv_gen_ops = &crypt_iv_null_ops;
1568 else if (strcmp(ivmode, "lmk") == 0) {
1569 cc->iv_gen_ops = &crypt_iv_lmk_ops;
1571 * Version 2 and 3 is recognised according
1572 * to length of provided multi-key string.
1573 * If present (version 3), last key is used as IV seed.
1574 * All keys (including IV seed) are always the same size.
1576 if (cc->key_size % cc->key_parts) {
1578 cc->key_extra_size = cc->key_size / cc->key_parts;
1580 } else if (strcmp(ivmode, "tcw") == 0) {
1581 cc->iv_gen_ops = &crypt_iv_tcw_ops;
1582 cc->key_parts += 2; /* IV + whitening */
1583 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
1586 ti->error = "Invalid IV mode";
1590 /* Initialize and set key */
1591 ret = crypt_set_key(cc, key);
1593 ti->error = "Error decoding and setting key";
1598 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
1599 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
1601 ti->error = "Error creating IV";
1606 /* Initialize IV (set keys for ESSIV etc) */
1607 if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
1608 ret = cc->iv_gen_ops->init(cc);
1610 ti->error = "Error initialising IV";
1621 ti->error = "Cannot allocate cipher strings";
1626 * Construct an encryption mapping:
1627 * <cipher> <key> <iv_offset> <dev_path> <start>
1629 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
1631 struct crypt_config *cc;
1632 unsigned int key_size, opt_params;
1633 unsigned long long tmpll;
1635 size_t iv_size_padding;
1636 struct dm_arg_set as;
1637 const char *opt_string;
1640 static struct dm_arg _args[] = {
1641 {0, 2, "Invalid number of feature args"},
1645 ti->error = "Not enough arguments";
1649 key_size = strlen(argv[1]) >> 1;
1651 cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
1653 ti->error = "Cannot allocate encryption context";
1656 cc->key_size = key_size;
1659 ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
1664 cc->io_pool = mempool_create_slab_pool(MIN_IOS, _crypt_io_pool);
1666 ti->error = "Cannot allocate crypt io mempool";
1670 cc->dmreq_start = sizeof(struct ablkcipher_request);
1671 cc->dmreq_start += crypto_ablkcipher_reqsize(any_tfm(cc));
1672 cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
1674 if (crypto_ablkcipher_alignmask(any_tfm(cc)) < CRYPTO_MINALIGN) {
1675 /* Allocate the padding exactly */
1676 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
1677 & crypto_ablkcipher_alignmask(any_tfm(cc));
1680 * If the cipher requires greater alignment than kmalloc
1681 * alignment, we don't know the exact position of the
1682 * initialization vector. We must assume worst case.
1684 iv_size_padding = crypto_ablkcipher_alignmask(any_tfm(cc));
1687 cc->req_pool = mempool_create_kmalloc_pool(MIN_IOS, cc->dmreq_start +
1688 sizeof(struct dm_crypt_request) + iv_size_padding + cc->iv_size);
1689 if (!cc->req_pool) {
1690 ti->error = "Cannot allocate crypt request mempool";
1694 cc->per_bio_data_size = ti->per_bio_data_size =
1695 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start +
1696 sizeof(struct dm_crypt_request) + iv_size_padding + cc->iv_size,
1697 ARCH_KMALLOC_MINALIGN);
1699 cc->page_pool = mempool_create_page_pool(BIO_MAX_PAGES, 0);
1700 if (!cc->page_pool) {
1701 ti->error = "Cannot allocate page mempool";
1705 cc->bs = bioset_create(MIN_IOS, 0);
1707 ti->error = "Cannot allocate crypt bioset";
1711 mutex_init(&cc->bio_alloc_lock);
1714 if (sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) {
1715 ti->error = "Invalid iv_offset sector";
1718 cc->iv_offset = tmpll;
1720 if (dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev)) {
1721 ti->error = "Device lookup failed";
1725 if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1) {
1726 ti->error = "Invalid device sector";
1734 /* Optional parameters */
1739 ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
1743 while (opt_params--) {
1744 opt_string = dm_shift_arg(&as);
1746 ti->error = "Not enough feature arguments";
1750 if (!strcasecmp(opt_string, "allow_discards"))
1751 ti->num_discard_bios = 1;
1753 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
1754 set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
1757 ti->error = "Invalid feature arguments";
1764 cc->io_queue = alloc_workqueue("kcryptd_io", WQ_MEM_RECLAIM, 1);
1765 if (!cc->io_queue) {
1766 ti->error = "Couldn't create kcryptd io queue";
1770 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
1771 cc->crypt_queue = alloc_workqueue("kcryptd", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM, 1);
1773 cc->crypt_queue = alloc_workqueue("kcryptd", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
1775 if (!cc->crypt_queue) {
1776 ti->error = "Couldn't create kcryptd queue";
1780 ti->num_flush_bios = 1;
1781 ti->discard_zeroes_data_unsupported = true;
1790 static int crypt_map(struct dm_target *ti, struct bio *bio)
1792 struct dm_crypt_io *io;
1793 struct crypt_config *cc = ti->private;
1796 * If bio is REQ_FLUSH or REQ_DISCARD, just bypass crypt queues.
1797 * - for REQ_FLUSH device-mapper core ensures that no IO is in-flight
1798 * - for REQ_DISCARD caller must use flush if IO ordering matters
1800 if (unlikely(bio->bi_rw & (REQ_FLUSH | REQ_DISCARD))) {
1801 bio->bi_bdev = cc->dev->bdev;
1802 if (bio_sectors(bio))
1803 bio->bi_iter.bi_sector = cc->start +
1804 dm_target_offset(ti, bio->bi_iter.bi_sector);
1805 return DM_MAPIO_REMAPPED;
1808 io = dm_per_bio_data(bio, cc->per_bio_data_size);
1809 crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
1810 io->ctx.req = (struct ablkcipher_request *)(io + 1);
1812 if (bio_data_dir(io->base_bio) == READ) {
1813 if (kcryptd_io_read(io, GFP_NOWAIT))
1814 kcryptd_queue_io(io);
1816 kcryptd_queue_crypt(io);
1818 return DM_MAPIO_SUBMITTED;
1821 static void crypt_status(struct dm_target *ti, status_type_t type,
1822 unsigned status_flags, char *result, unsigned maxlen)
1824 struct crypt_config *cc = ti->private;
1826 int num_feature_args = 0;
1829 case STATUSTYPE_INFO:
1833 case STATUSTYPE_TABLE:
1834 DMEMIT("%s ", cc->cipher_string);
1836 if (cc->key_size > 0)
1837 for (i = 0; i < cc->key_size; i++)
1838 DMEMIT("%02x", cc->key[i]);
1842 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
1843 cc->dev->name, (unsigned long long)cc->start);
1845 num_feature_args += !!ti->num_discard_bios;
1846 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
1847 if (num_feature_args) {
1848 DMEMIT(" %d", num_feature_args);
1849 if (ti->num_discard_bios)
1850 DMEMIT(" allow_discards");
1851 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
1852 DMEMIT(" same_cpu_crypt");
1859 static void crypt_postsuspend(struct dm_target *ti)
1861 struct crypt_config *cc = ti->private;
1863 set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
1866 static int crypt_preresume(struct dm_target *ti)
1868 struct crypt_config *cc = ti->private;
1870 if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
1871 DMERR("aborting resume - crypt key is not set.");
1878 static void crypt_resume(struct dm_target *ti)
1880 struct crypt_config *cc = ti->private;
1882 clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
1885 /* Message interface
1889 static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
1891 struct crypt_config *cc = ti->private;
1897 if (!strcasecmp(argv[0], "key")) {
1898 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
1899 DMWARN("not suspended during key manipulation.");
1902 if (argc == 3 && !strcasecmp(argv[1], "set")) {
1903 ret = crypt_set_key(cc, argv[2]);
1906 if (cc->iv_gen_ops && cc->iv_gen_ops->init)
1907 ret = cc->iv_gen_ops->init(cc);
1910 if (argc == 2 && !strcasecmp(argv[1], "wipe")) {
1911 if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
1912 ret = cc->iv_gen_ops->wipe(cc);
1916 return crypt_wipe_key(cc);
1921 DMWARN("unrecognised message received.");
1925 static int crypt_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
1926 struct bio_vec *biovec, int max_size)
1928 struct crypt_config *cc = ti->private;
1929 struct request_queue *q = bdev_get_queue(cc->dev->bdev);
1931 if (!q->merge_bvec_fn)
1934 bvm->bi_bdev = cc->dev->bdev;
1935 bvm->bi_sector = cc->start + dm_target_offset(ti, bvm->bi_sector);
1937 return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
1940 static int crypt_iterate_devices(struct dm_target *ti,
1941 iterate_devices_callout_fn fn, void *data)
1943 struct crypt_config *cc = ti->private;
1945 return fn(ti, cc->dev, cc->start, ti->len, data);
1948 static struct target_type crypt_target = {
1950 .version = {1, 14, 0},
1951 .module = THIS_MODULE,
1955 .status = crypt_status,
1956 .postsuspend = crypt_postsuspend,
1957 .preresume = crypt_preresume,
1958 .resume = crypt_resume,
1959 .message = crypt_message,
1960 .merge = crypt_merge,
1961 .iterate_devices = crypt_iterate_devices,
1964 static int __init dm_crypt_init(void)
1968 _crypt_io_pool = KMEM_CACHE(dm_crypt_io, 0);
1969 if (!_crypt_io_pool)
1972 r = dm_register_target(&crypt_target);
1974 DMERR("register failed %d", r);
1975 kmem_cache_destroy(_crypt_io_pool);
1981 static void __exit dm_crypt_exit(void)
1983 dm_unregister_target(&crypt_target);
1984 kmem_cache_destroy(_crypt_io_pool);
1987 module_init(dm_crypt_init);
1988 module_exit(dm_crypt_exit);
1990 MODULE_AUTHOR("Jana Saout <jana@saout.de>");
1991 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
1992 MODULE_LICENSE("GPL");