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_shash *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_IV_LARGE_SECTORS, /* Calculate IV from sector_size, not 512B sectors */
136 * The fields in here must be read only after initialization.
138 struct crypt_config {
142 struct percpu_counter n_allocated_pages;
144 struct workqueue_struct *io_queue;
145 struct workqueue_struct *crypt_queue;
147 spinlock_t write_thread_lock;
148 struct task_struct *write_thread;
149 struct rb_root write_tree;
156 const struct crypt_iv_operations *iv_gen_ops;
158 struct iv_essiv_private essiv;
159 struct iv_benbi_private benbi;
160 struct iv_lmk_private lmk;
161 struct iv_tcw_private tcw;
164 unsigned int iv_size;
165 unsigned short int sector_size;
166 unsigned char sector_shift;
168 /* ESSIV: struct crypto_cipher *essiv_tfm */
171 struct crypto_skcipher **tfms;
172 struct crypto_aead **tfms_aead;
175 unsigned long cipher_flags;
178 * Layout of each crypto request:
180 * struct skcipher_request
183 * struct dm_crypt_request
187 * The padding is added so that dm_crypt_request and the IV are
190 unsigned int dmreq_start;
192 unsigned int per_bio_data_size;
195 unsigned int key_size;
196 unsigned int key_parts; /* independent parts in key buffer */
197 unsigned int key_extra_size; /* additional keys length */
198 unsigned int key_mac_size; /* MAC key size for authenc(...) */
200 unsigned int integrity_tag_size;
201 unsigned int integrity_iv_size;
202 unsigned int on_disk_tag_size;
205 * pool for per bio private data, crypto requests,
206 * encryption requeusts/buffer pages and integrity tags
208 unsigned tag_pool_max_sectors;
214 struct mutex bio_alloc_lock;
216 u8 *authenc_key; /* space for keys in authenc() format (if used) */
221 #define MAX_TAG_SIZE 480
222 #define POOL_ENTRY_SIZE 512
224 static DEFINE_SPINLOCK(dm_crypt_clients_lock);
225 static unsigned dm_crypt_clients_n = 0;
226 static volatile unsigned long dm_crypt_pages_per_client;
227 #define DM_CRYPT_MEMORY_PERCENT 2
228 #define DM_CRYPT_MIN_PAGES_PER_CLIENT (BIO_MAX_PAGES * 16)
230 static void clone_init(struct dm_crypt_io *, struct bio *);
231 static void kcryptd_queue_crypt(struct dm_crypt_io *io);
232 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
233 struct scatterlist *sg);
236 * Use this to access cipher attributes that are independent of the key.
238 static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
240 return cc->cipher_tfm.tfms[0];
243 static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
245 return cc->cipher_tfm.tfms_aead[0];
249 * Different IV generation algorithms:
251 * plain: the initial vector is the 32-bit little-endian version of the sector
252 * number, padded with zeros if necessary.
254 * plain64: the initial vector is the 64-bit little-endian version of the sector
255 * number, padded with zeros if necessary.
257 * plain64be: the initial vector is the 64-bit big-endian version of the sector
258 * number, padded with zeros if necessary.
260 * essiv: "encrypted sector|salt initial vector", the sector number is
261 * encrypted with the bulk cipher using a salt as key. The salt
262 * should be derived from the bulk cipher's key via hashing.
264 * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
265 * (needed for LRW-32-AES and possible other narrow block modes)
267 * null: the initial vector is always zero. Provides compatibility with
268 * obsolete loop_fish2 devices. Do not use for new devices.
270 * lmk: Compatible implementation of the block chaining mode used
271 * by the Loop-AES block device encryption system
272 * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
273 * It operates on full 512 byte sectors and uses CBC
274 * with an IV derived from the sector number, the data and
275 * optionally extra IV seed.
276 * This means that after decryption the first block
277 * of sector must be tweaked according to decrypted data.
278 * Loop-AES can use three encryption schemes:
279 * version 1: is plain aes-cbc mode
280 * version 2: uses 64 multikey scheme with lmk IV generator
281 * version 3: the same as version 2 with additional IV seed
282 * (it uses 65 keys, last key is used as IV seed)
284 * tcw: Compatible implementation of the block chaining mode used
285 * by the TrueCrypt device encryption system (prior to version 4.1).
286 * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
287 * It operates on full 512 byte sectors and uses CBC
288 * with an IV derived from initial key and the sector number.
289 * In addition, whitening value is applied on every sector, whitening
290 * is calculated from initial key, sector number and mixed using CRC32.
291 * Note that this encryption scheme is vulnerable to watermarking attacks
292 * and should be used for old compatible containers access only.
294 * plumb: unimplemented, see:
295 * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
298 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
299 struct dm_crypt_request *dmreq)
301 memset(iv, 0, cc->iv_size);
302 *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
307 static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
308 struct dm_crypt_request *dmreq)
310 memset(iv, 0, cc->iv_size);
311 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
316 static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
317 struct dm_crypt_request *dmreq)
319 memset(iv, 0, cc->iv_size);
320 /* iv_size is at least of size u64; usually it is 16 bytes */
321 *(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
326 /* Initialise ESSIV - compute salt but no local memory allocations */
327 static int crypt_iv_essiv_init(struct crypt_config *cc)
329 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
330 SHASH_DESC_ON_STACK(desc, essiv->hash_tfm);
331 struct crypto_cipher *essiv_tfm;
334 desc->tfm = essiv->hash_tfm;
336 err = crypto_shash_digest(desc, cc->key, cc->key_size, essiv->salt);
337 shash_desc_zero(desc);
341 essiv_tfm = cc->iv_private;
343 err = crypto_cipher_setkey(essiv_tfm, essiv->salt,
344 crypto_shash_digestsize(essiv->hash_tfm));
351 /* Wipe salt and reset key derived from volume key */
352 static int crypt_iv_essiv_wipe(struct crypt_config *cc)
354 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
355 unsigned salt_size = crypto_shash_digestsize(essiv->hash_tfm);
356 struct crypto_cipher *essiv_tfm;
359 memset(essiv->salt, 0, salt_size);
361 essiv_tfm = cc->iv_private;
362 r = crypto_cipher_setkey(essiv_tfm, essiv->salt, salt_size);
369 /* Allocate the cipher for ESSIV */
370 static struct crypto_cipher *alloc_essiv_cipher(struct crypt_config *cc,
371 struct dm_target *ti,
373 unsigned int saltsize)
375 struct crypto_cipher *essiv_tfm;
378 /* Setup the essiv_tfm with the given salt */
379 essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, 0);
380 if (IS_ERR(essiv_tfm)) {
381 ti->error = "Error allocating crypto tfm for ESSIV";
385 if (crypto_cipher_blocksize(essiv_tfm) != cc->iv_size) {
386 ti->error = "Block size of ESSIV cipher does "
387 "not match IV size of block cipher";
388 crypto_free_cipher(essiv_tfm);
389 return ERR_PTR(-EINVAL);
392 err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
394 ti->error = "Failed to set key for ESSIV cipher";
395 crypto_free_cipher(essiv_tfm);
402 static void crypt_iv_essiv_dtr(struct crypt_config *cc)
404 struct crypto_cipher *essiv_tfm;
405 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
407 crypto_free_shash(essiv->hash_tfm);
408 essiv->hash_tfm = NULL;
413 essiv_tfm = cc->iv_private;
416 crypto_free_cipher(essiv_tfm);
418 cc->iv_private = NULL;
421 static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
424 struct crypto_cipher *essiv_tfm = NULL;
425 struct crypto_shash *hash_tfm = NULL;
430 ti->error = "Digest algorithm missing for ESSIV mode";
434 /* Allocate hash algorithm */
435 hash_tfm = crypto_alloc_shash(opts, 0, 0);
436 if (IS_ERR(hash_tfm)) {
437 ti->error = "Error initializing ESSIV hash";
438 err = PTR_ERR(hash_tfm);
442 salt = kzalloc(crypto_shash_digestsize(hash_tfm), GFP_KERNEL);
444 ti->error = "Error kmallocing salt storage in ESSIV";
449 cc->iv_gen_private.essiv.salt = salt;
450 cc->iv_gen_private.essiv.hash_tfm = hash_tfm;
452 essiv_tfm = alloc_essiv_cipher(cc, ti, salt,
453 crypto_shash_digestsize(hash_tfm));
454 if (IS_ERR(essiv_tfm)) {
455 crypt_iv_essiv_dtr(cc);
456 return PTR_ERR(essiv_tfm);
458 cc->iv_private = essiv_tfm;
463 if (hash_tfm && !IS_ERR(hash_tfm))
464 crypto_free_shash(hash_tfm);
469 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
470 struct dm_crypt_request *dmreq)
472 struct crypto_cipher *essiv_tfm = cc->iv_private;
474 memset(iv, 0, cc->iv_size);
475 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
476 crypto_cipher_encrypt_one(essiv_tfm, iv, iv);
481 static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
484 unsigned bs = crypto_skcipher_blocksize(any_tfm(cc));
487 /* we need to calculate how far we must shift the sector count
488 * to get the cipher block count, we use this shift in _gen */
490 if (1 << log != bs) {
491 ti->error = "cypher blocksize is not a power of 2";
496 ti->error = "cypher blocksize is > 512";
500 cc->iv_gen_private.benbi.shift = 9 - log;
505 static void crypt_iv_benbi_dtr(struct crypt_config *cc)
509 static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
510 struct dm_crypt_request *dmreq)
514 memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
516 val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
517 put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
522 static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
523 struct dm_crypt_request *dmreq)
525 memset(iv, 0, cc->iv_size);
530 static void crypt_iv_lmk_dtr(struct crypt_config *cc)
532 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
534 if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
535 crypto_free_shash(lmk->hash_tfm);
536 lmk->hash_tfm = NULL;
542 static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
545 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
547 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
548 ti->error = "Unsupported sector size for LMK";
552 lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
553 if (IS_ERR(lmk->hash_tfm)) {
554 ti->error = "Error initializing LMK hash";
555 return PTR_ERR(lmk->hash_tfm);
558 /* No seed in LMK version 2 */
559 if (cc->key_parts == cc->tfms_count) {
564 lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
566 crypt_iv_lmk_dtr(cc);
567 ti->error = "Error kmallocing seed storage in LMK";
574 static int crypt_iv_lmk_init(struct crypt_config *cc)
576 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
577 int subkey_size = cc->key_size / cc->key_parts;
579 /* LMK seed is on the position of LMK_KEYS + 1 key */
581 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
582 crypto_shash_digestsize(lmk->hash_tfm));
587 static int crypt_iv_lmk_wipe(struct crypt_config *cc)
589 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
592 memset(lmk->seed, 0, LMK_SEED_SIZE);
597 static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
598 struct dm_crypt_request *dmreq,
601 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
602 SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
603 struct md5_state md5state;
607 desc->tfm = lmk->hash_tfm;
609 r = crypto_shash_init(desc);
614 r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
619 /* Sector is always 512B, block size 16, add data of blocks 1-31 */
620 r = crypto_shash_update(desc, data + 16, 16 * 31);
624 /* Sector is cropped to 56 bits here */
625 buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
626 buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
627 buf[2] = cpu_to_le32(4024);
629 r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
633 /* No MD5 padding here */
634 r = crypto_shash_export(desc, &md5state);
638 for (i = 0; i < MD5_HASH_WORDS; i++)
639 __cpu_to_le32s(&md5state.hash[i]);
640 memcpy(iv, &md5state.hash, cc->iv_size);
645 static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
646 struct dm_crypt_request *dmreq)
648 struct scatterlist *sg;
652 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
653 sg = crypt_get_sg_data(cc, dmreq->sg_in);
654 src = kmap_atomic(sg_page(sg));
655 r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
658 memset(iv, 0, cc->iv_size);
663 static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
664 struct dm_crypt_request *dmreq)
666 struct scatterlist *sg;
670 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
673 sg = crypt_get_sg_data(cc, dmreq->sg_out);
674 dst = kmap_atomic(sg_page(sg));
675 r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
677 /* Tweak the first block of plaintext sector */
679 crypto_xor(dst + sg->offset, iv, cc->iv_size);
685 static void crypt_iv_tcw_dtr(struct crypt_config *cc)
687 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
689 kzfree(tcw->iv_seed);
691 kzfree(tcw->whitening);
692 tcw->whitening = NULL;
694 if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
695 crypto_free_shash(tcw->crc32_tfm);
696 tcw->crc32_tfm = NULL;
699 static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
702 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
704 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
705 ti->error = "Unsupported sector size for TCW";
709 if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
710 ti->error = "Wrong key size for TCW";
714 tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
715 if (IS_ERR(tcw->crc32_tfm)) {
716 ti->error = "Error initializing CRC32 in TCW";
717 return PTR_ERR(tcw->crc32_tfm);
720 tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
721 tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
722 if (!tcw->iv_seed || !tcw->whitening) {
723 crypt_iv_tcw_dtr(cc);
724 ti->error = "Error allocating seed storage in TCW";
731 static int crypt_iv_tcw_init(struct crypt_config *cc)
733 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
734 int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
736 memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
737 memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
743 static int crypt_iv_tcw_wipe(struct crypt_config *cc)
745 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
747 memset(tcw->iv_seed, 0, cc->iv_size);
748 memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
753 static int crypt_iv_tcw_whitening(struct crypt_config *cc,
754 struct dm_crypt_request *dmreq,
757 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
758 __le64 sector = cpu_to_le64(dmreq->iv_sector);
759 u8 buf[TCW_WHITENING_SIZE];
760 SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
763 /* xor whitening with sector number */
764 crypto_xor_cpy(buf, tcw->whitening, (u8 *)§or, 8);
765 crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)§or, 8);
767 /* calculate crc32 for every 32bit part and xor it */
768 desc->tfm = tcw->crc32_tfm;
769 for (i = 0; i < 4; i++) {
770 r = crypto_shash_init(desc);
773 r = crypto_shash_update(desc, &buf[i * 4], 4);
776 r = crypto_shash_final(desc, &buf[i * 4]);
780 crypto_xor(&buf[0], &buf[12], 4);
781 crypto_xor(&buf[4], &buf[8], 4);
783 /* apply whitening (8 bytes) to whole sector */
784 for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
785 crypto_xor(data + i * 8, buf, 8);
787 memzero_explicit(buf, sizeof(buf));
791 static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
792 struct dm_crypt_request *dmreq)
794 struct scatterlist *sg;
795 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
796 __le64 sector = cpu_to_le64(dmreq->iv_sector);
800 /* Remove whitening from ciphertext */
801 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
802 sg = crypt_get_sg_data(cc, dmreq->sg_in);
803 src = kmap_atomic(sg_page(sg));
804 r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
809 crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)§or, 8);
811 crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)§or,
817 static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
818 struct dm_crypt_request *dmreq)
820 struct scatterlist *sg;
824 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
827 /* Apply whitening on ciphertext */
828 sg = crypt_get_sg_data(cc, dmreq->sg_out);
829 dst = kmap_atomic(sg_page(sg));
830 r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
836 static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
837 struct dm_crypt_request *dmreq)
839 /* Used only for writes, there must be an additional space to store IV */
840 get_random_bytes(iv, cc->iv_size);
844 static const struct crypt_iv_operations crypt_iv_plain_ops = {
845 .generator = crypt_iv_plain_gen
848 static const struct crypt_iv_operations crypt_iv_plain64_ops = {
849 .generator = crypt_iv_plain64_gen
852 static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
853 .generator = crypt_iv_plain64be_gen
856 static const struct crypt_iv_operations crypt_iv_essiv_ops = {
857 .ctr = crypt_iv_essiv_ctr,
858 .dtr = crypt_iv_essiv_dtr,
859 .init = crypt_iv_essiv_init,
860 .wipe = crypt_iv_essiv_wipe,
861 .generator = crypt_iv_essiv_gen
864 static const struct crypt_iv_operations crypt_iv_benbi_ops = {
865 .ctr = crypt_iv_benbi_ctr,
866 .dtr = crypt_iv_benbi_dtr,
867 .generator = crypt_iv_benbi_gen
870 static const struct crypt_iv_operations crypt_iv_null_ops = {
871 .generator = crypt_iv_null_gen
874 static const struct crypt_iv_operations crypt_iv_lmk_ops = {
875 .ctr = crypt_iv_lmk_ctr,
876 .dtr = crypt_iv_lmk_dtr,
877 .init = crypt_iv_lmk_init,
878 .wipe = crypt_iv_lmk_wipe,
879 .generator = crypt_iv_lmk_gen,
880 .post = crypt_iv_lmk_post
883 static const struct crypt_iv_operations crypt_iv_tcw_ops = {
884 .ctr = crypt_iv_tcw_ctr,
885 .dtr = crypt_iv_tcw_dtr,
886 .init = crypt_iv_tcw_init,
887 .wipe = crypt_iv_tcw_wipe,
888 .generator = crypt_iv_tcw_gen,
889 .post = crypt_iv_tcw_post
892 static struct crypt_iv_operations crypt_iv_random_ops = {
893 .generator = crypt_iv_random_gen
897 * Integrity extensions
899 static bool crypt_integrity_aead(struct crypt_config *cc)
901 return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
904 static bool crypt_integrity_hmac(struct crypt_config *cc)
906 return crypt_integrity_aead(cc) && cc->key_mac_size;
909 /* Get sg containing data */
910 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
911 struct scatterlist *sg)
913 if (unlikely(crypt_integrity_aead(cc)))
919 static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
921 struct bio_integrity_payload *bip;
922 unsigned int tag_len;
925 if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
928 bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
932 tag_len = io->cc->on_disk_tag_size * (bio_sectors(bio) >> io->cc->sector_shift);
934 bip->bip_iter.bi_size = tag_len;
935 bip->bip_iter.bi_sector = io->cc->start + io->sector;
937 ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
938 tag_len, offset_in_page(io->integrity_metadata));
939 if (unlikely(ret != tag_len))
945 static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
947 #ifdef CONFIG_BLK_DEV_INTEGRITY
948 struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
950 /* From now we require underlying device with our integrity profile */
951 if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
952 ti->error = "Integrity profile not supported.";
956 if (bi->tag_size != cc->on_disk_tag_size ||
957 bi->tuple_size != cc->on_disk_tag_size) {
958 ti->error = "Integrity profile tag size mismatch.";
961 if (1 << bi->interval_exp != cc->sector_size) {
962 ti->error = "Integrity profile sector size mismatch.";
966 if (crypt_integrity_aead(cc)) {
967 cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
968 DMINFO("Integrity AEAD, tag size %u, IV size %u.",
969 cc->integrity_tag_size, cc->integrity_iv_size);
971 if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
972 ti->error = "Integrity AEAD auth tag size is not supported.";
975 } else if (cc->integrity_iv_size)
976 DMINFO("Additional per-sector space %u bytes for IV.",
977 cc->integrity_iv_size);
979 if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
980 ti->error = "Not enough space for integrity tag in the profile.";
986 ti->error = "Integrity profile not supported.";
991 static void crypt_convert_init(struct crypt_config *cc,
992 struct convert_context *ctx,
993 struct bio *bio_out, struct bio *bio_in,
996 ctx->bio_in = bio_in;
997 ctx->bio_out = bio_out;
999 ctx->iter_in = bio_in->bi_iter;
1001 ctx->iter_out = bio_out->bi_iter;
1002 ctx->cc_sector = sector + cc->iv_offset;
1003 init_completion(&ctx->restart);
1006 static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
1009 return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
1012 static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
1014 return (void *)((char *)dmreq - cc->dmreq_start);
1017 static u8 *iv_of_dmreq(struct crypt_config *cc,
1018 struct dm_crypt_request *dmreq)
1020 if (crypt_integrity_aead(cc))
1021 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1022 crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
1024 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1025 crypto_skcipher_alignmask(any_tfm(cc)) + 1);
1028 static u8 *org_iv_of_dmreq(struct crypt_config *cc,
1029 struct dm_crypt_request *dmreq)
1031 return iv_of_dmreq(cc, dmreq) + cc->iv_size;
1034 static uint64_t *org_sector_of_dmreq(struct crypt_config *cc,
1035 struct dm_crypt_request *dmreq)
1037 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
1038 return (uint64_t*) ptr;
1041 static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
1042 struct dm_crypt_request *dmreq)
1044 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
1045 cc->iv_size + sizeof(uint64_t);
1046 return (unsigned int*)ptr;
1049 static void *tag_from_dmreq(struct crypt_config *cc,
1050 struct dm_crypt_request *dmreq)
1052 struct convert_context *ctx = dmreq->ctx;
1053 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1055 return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
1056 cc->on_disk_tag_size];
1059 static void *iv_tag_from_dmreq(struct crypt_config *cc,
1060 struct dm_crypt_request *dmreq)
1062 return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
1065 static int crypt_convert_block_aead(struct crypt_config *cc,
1066 struct convert_context *ctx,
1067 struct aead_request *req,
1068 unsigned int tag_offset)
1070 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1071 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1072 struct dm_crypt_request *dmreq;
1073 u8 *iv, *org_iv, *tag_iv, *tag;
1077 BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
1079 /* Reject unexpected unaligned bio. */
1080 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1083 dmreq = dmreq_of_req(cc, req);
1084 dmreq->iv_sector = ctx->cc_sector;
1085 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1086 dmreq->iv_sector >>= cc->sector_shift;
1089 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1091 sector = org_sector_of_dmreq(cc, dmreq);
1092 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1094 iv = iv_of_dmreq(cc, dmreq);
1095 org_iv = org_iv_of_dmreq(cc, dmreq);
1096 tag = tag_from_dmreq(cc, dmreq);
1097 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1100 * |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1101 * | (authenticated) | (auth+encryption) | |
1102 * | sector_LE | IV | sector in/out | tag in/out |
1104 sg_init_table(dmreq->sg_in, 4);
1105 sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
1106 sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
1107 sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1108 sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
1110 sg_init_table(dmreq->sg_out, 4);
1111 sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
1112 sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
1113 sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1114 sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
1116 if (cc->iv_gen_ops) {
1117 /* For READs use IV stored in integrity metadata */
1118 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1119 memcpy(org_iv, tag_iv, cc->iv_size);
1121 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1124 /* Store generated IV in integrity metadata */
1125 if (cc->integrity_iv_size)
1126 memcpy(tag_iv, org_iv, cc->iv_size);
1128 /* Working copy of IV, to be modified in crypto API */
1129 memcpy(iv, org_iv, cc->iv_size);
1132 aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
1133 if (bio_data_dir(ctx->bio_in) == WRITE) {
1134 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1135 cc->sector_size, iv);
1136 r = crypto_aead_encrypt(req);
1137 if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
1138 memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
1139 cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
1141 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1142 cc->sector_size + cc->integrity_tag_size, iv);
1143 r = crypto_aead_decrypt(req);
1147 DMERR_LIMIT("INTEGRITY AEAD ERROR, sector %llu",
1148 (unsigned long long)le64_to_cpu(*sector));
1150 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1151 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1153 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1154 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1159 static int crypt_convert_block_skcipher(struct crypt_config *cc,
1160 struct convert_context *ctx,
1161 struct skcipher_request *req,
1162 unsigned int tag_offset)
1164 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1165 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1166 struct scatterlist *sg_in, *sg_out;
1167 struct dm_crypt_request *dmreq;
1168 u8 *iv, *org_iv, *tag_iv;
1172 /* Reject unexpected unaligned bio. */
1173 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1176 dmreq = dmreq_of_req(cc, req);
1177 dmreq->iv_sector = ctx->cc_sector;
1178 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1179 dmreq->iv_sector >>= cc->sector_shift;
1182 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1184 iv = iv_of_dmreq(cc, dmreq);
1185 org_iv = org_iv_of_dmreq(cc, dmreq);
1186 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1188 sector = org_sector_of_dmreq(cc, dmreq);
1189 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1191 /* For skcipher we use only the first sg item */
1192 sg_in = &dmreq->sg_in[0];
1193 sg_out = &dmreq->sg_out[0];
1195 sg_init_table(sg_in, 1);
1196 sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1198 sg_init_table(sg_out, 1);
1199 sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1201 if (cc->iv_gen_ops) {
1202 /* For READs use IV stored in integrity metadata */
1203 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1204 memcpy(org_iv, tag_iv, cc->integrity_iv_size);
1206 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1209 /* Store generated IV in integrity metadata */
1210 if (cc->integrity_iv_size)
1211 memcpy(tag_iv, org_iv, cc->integrity_iv_size);
1213 /* Working copy of IV, to be modified in crypto API */
1214 memcpy(iv, org_iv, cc->iv_size);
1217 skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
1219 if (bio_data_dir(ctx->bio_in) == WRITE)
1220 r = crypto_skcipher_encrypt(req);
1222 r = crypto_skcipher_decrypt(req);
1224 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1225 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1227 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1228 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1233 static void kcryptd_async_done(struct crypto_async_request *async_req,
1236 static void crypt_alloc_req_skcipher(struct crypt_config *cc,
1237 struct convert_context *ctx)
1239 unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
1242 ctx->r.req = mempool_alloc(&cc->req_pool, GFP_NOIO);
1244 skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
1247 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1248 * requests if driver request queue is full.
1250 skcipher_request_set_callback(ctx->r.req,
1251 CRYPTO_TFM_REQ_MAY_BACKLOG,
1252 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
1255 static void crypt_alloc_req_aead(struct crypt_config *cc,
1256 struct convert_context *ctx)
1258 if (!ctx->r.req_aead)
1259 ctx->r.req_aead = mempool_alloc(&cc->req_pool, GFP_NOIO);
1261 aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
1264 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1265 * requests if driver request queue is full.
1267 aead_request_set_callback(ctx->r.req_aead,
1268 CRYPTO_TFM_REQ_MAY_BACKLOG,
1269 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
1272 static void crypt_alloc_req(struct crypt_config *cc,
1273 struct convert_context *ctx)
1275 if (crypt_integrity_aead(cc))
1276 crypt_alloc_req_aead(cc, ctx);
1278 crypt_alloc_req_skcipher(cc, ctx);
1281 static void crypt_free_req_skcipher(struct crypt_config *cc,
1282 struct skcipher_request *req, struct bio *base_bio)
1284 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1286 if ((struct skcipher_request *)(io + 1) != req)
1287 mempool_free(req, &cc->req_pool);
1290 static void crypt_free_req_aead(struct crypt_config *cc,
1291 struct aead_request *req, struct bio *base_bio)
1293 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1295 if ((struct aead_request *)(io + 1) != req)
1296 mempool_free(req, &cc->req_pool);
1299 static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
1301 if (crypt_integrity_aead(cc))
1302 crypt_free_req_aead(cc, req, base_bio);
1304 crypt_free_req_skcipher(cc, req, base_bio);
1308 * Encrypt / decrypt data from one bio to another one (can be the same one)
1310 static blk_status_t crypt_convert(struct crypt_config *cc,
1311 struct convert_context *ctx)
1313 unsigned int tag_offset = 0;
1314 unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
1317 atomic_set(&ctx->cc_pending, 1);
1319 while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
1321 crypt_alloc_req(cc, ctx);
1322 atomic_inc(&ctx->cc_pending);
1324 if (crypt_integrity_aead(cc))
1325 r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
1327 r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
1331 * The request was queued by a crypto driver
1332 * but the driver request queue is full, let's wait.
1335 wait_for_completion(&ctx->restart);
1336 reinit_completion(&ctx->restart);
1339 * The request is queued and processed asynchronously,
1340 * completion function kcryptd_async_done() will be called.
1344 ctx->cc_sector += sector_step;
1348 * The request was already processed (synchronously).
1351 atomic_dec(&ctx->cc_pending);
1352 ctx->cc_sector += sector_step;
1357 * There was a data integrity error.
1360 atomic_dec(&ctx->cc_pending);
1361 return BLK_STS_PROTECTION;
1363 * There was an error while processing the request.
1366 atomic_dec(&ctx->cc_pending);
1367 return BLK_STS_IOERR;
1374 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
1377 * Generate a new unfragmented bio with the given size
1378 * This should never violate the device limitations (but only because
1379 * max_segment_size is being constrained to PAGE_SIZE).
1381 * This function may be called concurrently. If we allocate from the mempool
1382 * concurrently, there is a possibility of deadlock. For example, if we have
1383 * mempool of 256 pages, two processes, each wanting 256, pages allocate from
1384 * the mempool concurrently, it may deadlock in a situation where both processes
1385 * have allocated 128 pages and the mempool is exhausted.
1387 * In order to avoid this scenario we allocate the pages under a mutex.
1389 * In order to not degrade performance with excessive locking, we try
1390 * non-blocking allocations without a mutex first but on failure we fallback
1391 * to blocking allocations with a mutex.
1393 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
1395 struct crypt_config *cc = io->cc;
1397 unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1398 gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
1399 unsigned i, len, remaining_size;
1403 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1404 mutex_lock(&cc->bio_alloc_lock);
1406 clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, &cc->bs);
1410 clone_init(io, clone);
1412 remaining_size = size;
1414 for (i = 0; i < nr_iovecs; i++) {
1415 page = mempool_alloc(&cc->page_pool, gfp_mask);
1417 crypt_free_buffer_pages(cc, clone);
1419 gfp_mask |= __GFP_DIRECT_RECLAIM;
1423 len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
1425 bio_add_page(clone, page, len, 0);
1427 remaining_size -= len;
1430 /* Allocate space for integrity tags */
1431 if (dm_crypt_integrity_io_alloc(io, clone)) {
1432 crypt_free_buffer_pages(cc, clone);
1437 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1438 mutex_unlock(&cc->bio_alloc_lock);
1443 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1446 struct bvec_iter_all iter_all;
1448 bio_for_each_segment_all(bv, clone, iter_all) {
1449 BUG_ON(!bv->bv_page);
1450 mempool_free(bv->bv_page, &cc->page_pool);
1454 static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1455 struct bio *bio, sector_t sector)
1459 io->sector = sector;
1461 io->ctx.r.req = NULL;
1462 io->integrity_metadata = NULL;
1463 io->integrity_metadata_from_pool = false;
1464 atomic_set(&io->io_pending, 0);
1467 static void crypt_inc_pending(struct dm_crypt_io *io)
1469 atomic_inc(&io->io_pending);
1473 * One of the bios was finished. Check for completion of
1474 * the whole request and correctly clean up the buffer.
1476 static void crypt_dec_pending(struct dm_crypt_io *io)
1478 struct crypt_config *cc = io->cc;
1479 struct bio *base_bio = io->base_bio;
1480 blk_status_t error = io->error;
1482 if (!atomic_dec_and_test(&io->io_pending))
1486 crypt_free_req(cc, io->ctx.r.req, base_bio);
1488 if (unlikely(io->integrity_metadata_from_pool))
1489 mempool_free(io->integrity_metadata, &io->cc->tag_pool);
1491 kfree(io->integrity_metadata);
1493 base_bio->bi_status = error;
1494 bio_endio(base_bio);
1498 * kcryptd/kcryptd_io:
1500 * Needed because it would be very unwise to do decryption in an
1501 * interrupt context.
1503 * kcryptd performs the actual encryption or decryption.
1505 * kcryptd_io performs the IO submission.
1507 * They must be separated as otherwise the final stages could be
1508 * starved by new requests which can block in the first stages due
1509 * to memory allocation.
1511 * The work is done per CPU global for all dm-crypt instances.
1512 * They should not depend on each other and do not block.
1514 static void crypt_endio(struct bio *clone)
1516 struct dm_crypt_io *io = clone->bi_private;
1517 struct crypt_config *cc = io->cc;
1518 unsigned rw = bio_data_dir(clone);
1522 * free the processed pages
1525 crypt_free_buffer_pages(cc, clone);
1527 error = clone->bi_status;
1530 if (rw == READ && !error) {
1531 kcryptd_queue_crypt(io);
1535 if (unlikely(error))
1538 crypt_dec_pending(io);
1541 static void clone_init(struct dm_crypt_io *io, struct bio *clone)
1543 struct crypt_config *cc = io->cc;
1545 clone->bi_private = io;
1546 clone->bi_end_io = crypt_endio;
1547 bio_set_dev(clone, cc->dev->bdev);
1548 clone->bi_opf = io->base_bio->bi_opf;
1551 static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
1553 struct crypt_config *cc = io->cc;
1557 * We need the original biovec array in order to decrypt
1558 * the whole bio data *afterwards* -- thanks to immutable
1559 * biovecs we don't need to worry about the block layer
1560 * modifying the biovec array; so leverage bio_clone_fast().
1562 clone = bio_clone_fast(io->base_bio, gfp, &cc->bs);
1566 crypt_inc_pending(io);
1568 clone_init(io, clone);
1569 clone->bi_iter.bi_sector = cc->start + io->sector;
1571 if (dm_crypt_integrity_io_alloc(io, clone)) {
1572 crypt_dec_pending(io);
1577 generic_make_request(clone);
1581 static void kcryptd_io_read_work(struct work_struct *work)
1583 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1585 crypt_inc_pending(io);
1586 if (kcryptd_io_read(io, GFP_NOIO))
1587 io->error = BLK_STS_RESOURCE;
1588 crypt_dec_pending(io);
1591 static void kcryptd_queue_read(struct dm_crypt_io *io)
1593 struct crypt_config *cc = io->cc;
1595 INIT_WORK(&io->work, kcryptd_io_read_work);
1596 queue_work(cc->io_queue, &io->work);
1599 static void kcryptd_io_write(struct dm_crypt_io *io)
1601 struct bio *clone = io->ctx.bio_out;
1603 generic_make_request(clone);
1606 #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1608 static int dmcrypt_write(void *data)
1610 struct crypt_config *cc = data;
1611 struct dm_crypt_io *io;
1614 struct rb_root write_tree;
1615 struct blk_plug plug;
1617 spin_lock_irq(&cc->write_thread_lock);
1620 if (!RB_EMPTY_ROOT(&cc->write_tree))
1623 set_current_state(TASK_INTERRUPTIBLE);
1625 spin_unlock_irq(&cc->write_thread_lock);
1627 if (unlikely(kthread_should_stop())) {
1628 set_current_state(TASK_RUNNING);
1634 set_current_state(TASK_RUNNING);
1635 spin_lock_irq(&cc->write_thread_lock);
1636 goto continue_locked;
1639 write_tree = cc->write_tree;
1640 cc->write_tree = RB_ROOT;
1641 spin_unlock_irq(&cc->write_thread_lock);
1643 BUG_ON(rb_parent(write_tree.rb_node));
1646 * Note: we cannot walk the tree here with rb_next because
1647 * the structures may be freed when kcryptd_io_write is called.
1649 blk_start_plug(&plug);
1651 io = crypt_io_from_node(rb_first(&write_tree));
1652 rb_erase(&io->rb_node, &write_tree);
1653 kcryptd_io_write(io);
1654 } while (!RB_EMPTY_ROOT(&write_tree));
1655 blk_finish_plug(&plug);
1660 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
1662 struct bio *clone = io->ctx.bio_out;
1663 struct crypt_config *cc = io->cc;
1664 unsigned long flags;
1666 struct rb_node **rbp, *parent;
1668 if (unlikely(io->error)) {
1669 crypt_free_buffer_pages(cc, clone);
1671 crypt_dec_pending(io);
1675 /* crypt_convert should have filled the clone bio */
1676 BUG_ON(io->ctx.iter_out.bi_size);
1678 clone->bi_iter.bi_sector = cc->start + io->sector;
1680 if (likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) {
1681 generic_make_request(clone);
1685 spin_lock_irqsave(&cc->write_thread_lock, flags);
1686 if (RB_EMPTY_ROOT(&cc->write_tree))
1687 wake_up_process(cc->write_thread);
1688 rbp = &cc->write_tree.rb_node;
1690 sector = io->sector;
1693 if (sector < crypt_io_from_node(parent)->sector)
1694 rbp = &(*rbp)->rb_left;
1696 rbp = &(*rbp)->rb_right;
1698 rb_link_node(&io->rb_node, parent, rbp);
1699 rb_insert_color(&io->rb_node, &cc->write_tree);
1700 spin_unlock_irqrestore(&cc->write_thread_lock, flags);
1703 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
1705 struct crypt_config *cc = io->cc;
1708 sector_t sector = io->sector;
1712 * Prevent io from disappearing until this function completes.
1714 crypt_inc_pending(io);
1715 crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
1717 clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
1718 if (unlikely(!clone)) {
1719 io->error = BLK_STS_IOERR;
1723 io->ctx.bio_out = clone;
1724 io->ctx.iter_out = clone->bi_iter;
1726 sector += bio_sectors(clone);
1728 crypt_inc_pending(io);
1729 r = crypt_convert(cc, &io->ctx);
1732 crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
1734 /* Encryption was already finished, submit io now */
1735 if (crypt_finished) {
1736 kcryptd_crypt_write_io_submit(io, 0);
1737 io->sector = sector;
1741 crypt_dec_pending(io);
1744 static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
1746 crypt_dec_pending(io);
1749 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
1751 struct crypt_config *cc = io->cc;
1754 crypt_inc_pending(io);
1756 crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
1759 r = crypt_convert(cc, &io->ctx);
1763 if (atomic_dec_and_test(&io->ctx.cc_pending))
1764 kcryptd_crypt_read_done(io);
1766 crypt_dec_pending(io);
1769 static void kcryptd_async_done(struct crypto_async_request *async_req,
1772 struct dm_crypt_request *dmreq = async_req->data;
1773 struct convert_context *ctx = dmreq->ctx;
1774 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1775 struct crypt_config *cc = io->cc;
1778 * A request from crypto driver backlog is going to be processed now,
1779 * finish the completion and continue in crypt_convert().
1780 * (Callback will be called for the second time for this request.)
1782 if (error == -EINPROGRESS) {
1783 complete(&ctx->restart);
1787 if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
1788 error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
1790 if (error == -EBADMSG) {
1791 DMERR_LIMIT("INTEGRITY AEAD ERROR, sector %llu",
1792 (unsigned long long)le64_to_cpu(*org_sector_of_dmreq(cc, dmreq)));
1793 io->error = BLK_STS_PROTECTION;
1794 } else if (error < 0)
1795 io->error = BLK_STS_IOERR;
1797 crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
1799 if (!atomic_dec_and_test(&ctx->cc_pending))
1802 if (bio_data_dir(io->base_bio) == READ)
1803 kcryptd_crypt_read_done(io);
1805 kcryptd_crypt_write_io_submit(io, 1);
1808 static void kcryptd_crypt(struct work_struct *work)
1810 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1812 if (bio_data_dir(io->base_bio) == READ)
1813 kcryptd_crypt_read_convert(io);
1815 kcryptd_crypt_write_convert(io);
1818 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
1820 struct crypt_config *cc = io->cc;
1822 INIT_WORK(&io->work, kcryptd_crypt);
1823 queue_work(cc->crypt_queue, &io->work);
1826 static void crypt_free_tfms_aead(struct crypt_config *cc)
1828 if (!cc->cipher_tfm.tfms_aead)
1831 if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
1832 crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
1833 cc->cipher_tfm.tfms_aead[0] = NULL;
1836 kfree(cc->cipher_tfm.tfms_aead);
1837 cc->cipher_tfm.tfms_aead = NULL;
1840 static void crypt_free_tfms_skcipher(struct crypt_config *cc)
1844 if (!cc->cipher_tfm.tfms)
1847 for (i = 0; i < cc->tfms_count; i++)
1848 if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
1849 crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
1850 cc->cipher_tfm.tfms[i] = NULL;
1853 kfree(cc->cipher_tfm.tfms);
1854 cc->cipher_tfm.tfms = NULL;
1857 static void crypt_free_tfms(struct crypt_config *cc)
1859 if (crypt_integrity_aead(cc))
1860 crypt_free_tfms_aead(cc);
1862 crypt_free_tfms_skcipher(cc);
1865 static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
1870 cc->cipher_tfm.tfms = kcalloc(cc->tfms_count,
1871 sizeof(struct crypto_skcipher *),
1873 if (!cc->cipher_tfm.tfms)
1876 for (i = 0; i < cc->tfms_count; i++) {
1877 cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0, 0);
1878 if (IS_ERR(cc->cipher_tfm.tfms[i])) {
1879 err = PTR_ERR(cc->cipher_tfm.tfms[i]);
1880 crypt_free_tfms(cc);
1886 * dm-crypt performance can vary greatly depending on which crypto
1887 * algorithm implementation is used. Help people debug performance
1888 * problems by logging the ->cra_driver_name.
1890 DMINFO("%s using implementation \"%s\"", ciphermode,
1891 crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
1895 static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
1899 cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
1900 if (!cc->cipher_tfm.tfms)
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);
1910 DMINFO("%s using implementation \"%s\"", ciphermode,
1911 crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
1915 static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
1917 if (crypt_integrity_aead(cc))
1918 return crypt_alloc_tfms_aead(cc, ciphermode);
1920 return crypt_alloc_tfms_skcipher(cc, ciphermode);
1923 static unsigned crypt_subkey_size(struct crypt_config *cc)
1925 return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
1928 static unsigned crypt_authenckey_size(struct crypt_config *cc)
1930 return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
1934 * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
1935 * the key must be for some reason in special format.
1936 * This funcion converts cc->key to this special format.
1938 static void crypt_copy_authenckey(char *p, const void *key,
1939 unsigned enckeylen, unsigned authkeylen)
1941 struct crypto_authenc_key_param *param;
1944 rta = (struct rtattr *)p;
1945 param = RTA_DATA(rta);
1946 param->enckeylen = cpu_to_be32(enckeylen);
1947 rta->rta_len = RTA_LENGTH(sizeof(*param));
1948 rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
1949 p += RTA_SPACE(sizeof(*param));
1950 memcpy(p, key + enckeylen, authkeylen);
1952 memcpy(p, key, enckeylen);
1955 static int crypt_setkey(struct crypt_config *cc)
1957 unsigned subkey_size;
1960 /* Ignore extra keys (which are used for IV etc) */
1961 subkey_size = crypt_subkey_size(cc);
1963 if (crypt_integrity_hmac(cc)) {
1964 if (subkey_size < cc->key_mac_size)
1967 crypt_copy_authenckey(cc->authenc_key, cc->key,
1968 subkey_size - cc->key_mac_size,
1972 for (i = 0; i < cc->tfms_count; i++) {
1973 if (crypt_integrity_hmac(cc))
1974 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
1975 cc->authenc_key, crypt_authenckey_size(cc));
1976 else if (crypt_integrity_aead(cc))
1977 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
1978 cc->key + (i * subkey_size),
1981 r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
1982 cc->key + (i * subkey_size),
1988 if (crypt_integrity_hmac(cc))
1989 memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
1996 static bool contains_whitespace(const char *str)
1999 if (isspace(*str++))
2004 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2006 char *new_key_string, *key_desc;
2009 const struct user_key_payload *ukp;
2012 * Reject key_string with whitespace. dm core currently lacks code for
2013 * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2015 if (contains_whitespace(key_string)) {
2016 DMERR("whitespace chars not allowed in key string");
2020 /* look for next ':' separating key_type from key_description */
2021 key_desc = strpbrk(key_string, ":");
2022 if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2025 if (strncmp(key_string, "logon:", key_desc - key_string + 1) &&
2026 strncmp(key_string, "user:", key_desc - key_string + 1))
2029 new_key_string = kstrdup(key_string, GFP_KERNEL);
2030 if (!new_key_string)
2033 key = request_key(key_string[0] == 'l' ? &key_type_logon : &key_type_user,
2034 key_desc + 1, NULL);
2036 kzfree(new_key_string);
2037 return PTR_ERR(key);
2040 down_read(&key->sem);
2042 ukp = user_key_payload_locked(key);
2046 kzfree(new_key_string);
2047 return -EKEYREVOKED;
2050 if (cc->key_size != ukp->datalen) {
2053 kzfree(new_key_string);
2057 memcpy(cc->key, ukp->data, cc->key_size);
2062 /* clear the flag since following operations may invalidate previously valid key */
2063 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2065 ret = crypt_setkey(cc);
2068 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2069 kzfree(cc->key_string);
2070 cc->key_string = new_key_string;
2072 kzfree(new_key_string);
2077 static int get_key_size(char **key_string)
2082 if (*key_string[0] != ':')
2083 return strlen(*key_string) >> 1;
2085 /* look for next ':' in key string */
2086 colon = strpbrk(*key_string + 1, ":");
2090 if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2093 *key_string = colon;
2095 /* remaining key string should be :<logon|user>:<key_desc> */
2102 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2107 static int get_key_size(char **key_string)
2109 return (*key_string[0] == ':') ? -EINVAL : strlen(*key_string) >> 1;
2114 static int crypt_set_key(struct crypt_config *cc, char *key)
2117 int key_string_len = strlen(key);
2119 /* Hyphen (which gives a key_size of zero) means there is no key. */
2120 if (!cc->key_size && strcmp(key, "-"))
2123 /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2124 if (key[0] == ':') {
2125 r = crypt_set_keyring_key(cc, key + 1);
2129 /* clear the flag since following operations may invalidate previously valid key */
2130 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2132 /* wipe references to any kernel keyring key */
2133 kzfree(cc->key_string);
2134 cc->key_string = NULL;
2136 /* Decode key from its hex representation. */
2137 if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
2140 r = crypt_setkey(cc);
2142 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2145 /* Hex key string not needed after here, so wipe it. */
2146 memset(key, '0', key_string_len);
2151 static int crypt_wipe_key(struct crypt_config *cc)
2155 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2156 get_random_bytes(&cc->key, cc->key_size);
2157 kzfree(cc->key_string);
2158 cc->key_string = NULL;
2159 r = crypt_setkey(cc);
2160 memset(&cc->key, 0, cc->key_size * sizeof(u8));
2165 static void crypt_calculate_pages_per_client(void)
2167 unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
2169 if (!dm_crypt_clients_n)
2172 pages /= dm_crypt_clients_n;
2173 if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
2174 pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
2175 dm_crypt_pages_per_client = pages;
2178 static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
2180 struct crypt_config *cc = pool_data;
2183 if (unlikely(percpu_counter_compare(&cc->n_allocated_pages, dm_crypt_pages_per_client) >= 0) &&
2184 likely(gfp_mask & __GFP_NORETRY))
2187 page = alloc_page(gfp_mask);
2188 if (likely(page != NULL))
2189 percpu_counter_add(&cc->n_allocated_pages, 1);
2194 static void crypt_page_free(void *page, void *pool_data)
2196 struct crypt_config *cc = pool_data;
2199 percpu_counter_sub(&cc->n_allocated_pages, 1);
2202 static void crypt_dtr(struct dm_target *ti)
2204 struct crypt_config *cc = ti->private;
2211 if (cc->write_thread)
2212 kthread_stop(cc->write_thread);
2215 destroy_workqueue(cc->io_queue);
2216 if (cc->crypt_queue)
2217 destroy_workqueue(cc->crypt_queue);
2219 crypt_free_tfms(cc);
2221 bioset_exit(&cc->bs);
2223 mempool_exit(&cc->page_pool);
2224 mempool_exit(&cc->req_pool);
2225 mempool_exit(&cc->tag_pool);
2227 WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
2228 percpu_counter_destroy(&cc->n_allocated_pages);
2230 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
2231 cc->iv_gen_ops->dtr(cc);
2234 dm_put_device(ti, cc->dev);
2237 kzfree(cc->cipher_string);
2238 kzfree(cc->key_string);
2239 kzfree(cc->cipher_auth);
2240 kzfree(cc->authenc_key);
2242 mutex_destroy(&cc->bio_alloc_lock);
2244 /* Must zero key material before freeing */
2247 spin_lock(&dm_crypt_clients_lock);
2248 WARN_ON(!dm_crypt_clients_n);
2249 dm_crypt_clients_n--;
2250 crypt_calculate_pages_per_client();
2251 spin_unlock(&dm_crypt_clients_lock);
2254 static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
2256 struct crypt_config *cc = ti->private;
2258 if (crypt_integrity_aead(cc))
2259 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2261 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2264 /* at least a 64 bit sector number should fit in our buffer */
2265 cc->iv_size = max(cc->iv_size,
2266 (unsigned int)(sizeof(u64) / sizeof(u8)));
2268 DMWARN("Selected cipher does not support IVs");
2272 /* Choose ivmode, see comments at iv code. */
2274 cc->iv_gen_ops = NULL;
2275 else if (strcmp(ivmode, "plain") == 0)
2276 cc->iv_gen_ops = &crypt_iv_plain_ops;
2277 else if (strcmp(ivmode, "plain64") == 0)
2278 cc->iv_gen_ops = &crypt_iv_plain64_ops;
2279 else if (strcmp(ivmode, "plain64be") == 0)
2280 cc->iv_gen_ops = &crypt_iv_plain64be_ops;
2281 else if (strcmp(ivmode, "essiv") == 0)
2282 cc->iv_gen_ops = &crypt_iv_essiv_ops;
2283 else if (strcmp(ivmode, "benbi") == 0)
2284 cc->iv_gen_ops = &crypt_iv_benbi_ops;
2285 else if (strcmp(ivmode, "null") == 0)
2286 cc->iv_gen_ops = &crypt_iv_null_ops;
2287 else if (strcmp(ivmode, "lmk") == 0) {
2288 cc->iv_gen_ops = &crypt_iv_lmk_ops;
2290 * Version 2 and 3 is recognised according
2291 * to length of provided multi-key string.
2292 * If present (version 3), last key is used as IV seed.
2293 * All keys (including IV seed) are always the same size.
2295 if (cc->key_size % cc->key_parts) {
2297 cc->key_extra_size = cc->key_size / cc->key_parts;
2299 } else if (strcmp(ivmode, "tcw") == 0) {
2300 cc->iv_gen_ops = &crypt_iv_tcw_ops;
2301 cc->key_parts += 2; /* IV + whitening */
2302 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2303 } else if (strcmp(ivmode, "random") == 0) {
2304 cc->iv_gen_ops = &crypt_iv_random_ops;
2305 /* Need storage space in integrity fields. */
2306 cc->integrity_iv_size = cc->iv_size;
2308 ti->error = "Invalid IV mode";
2316 * Workaround to parse cipher algorithm from crypto API spec.
2317 * The cc->cipher is currently used only in ESSIV.
2318 * This should be probably done by crypto-api calls (once available...)
2320 static int crypt_ctr_blkdev_cipher(struct crypt_config *cc)
2322 const char *alg_name = NULL;
2325 if (crypt_integrity_aead(cc)) {
2326 alg_name = crypto_tfm_alg_name(crypto_aead_tfm(any_tfm_aead(cc)));
2329 if (crypt_integrity_hmac(cc)) {
2330 alg_name = strchr(alg_name, ',');
2336 alg_name = crypto_tfm_alg_name(crypto_skcipher_tfm(any_tfm(cc)));
2341 start = strchr(alg_name, '(');
2342 end = strchr(alg_name, ')');
2344 if (!start && !end) {
2345 cc->cipher = kstrdup(alg_name, GFP_KERNEL);
2346 return cc->cipher ? 0 : -ENOMEM;
2349 if (!start || !end || ++start >= end)
2352 cc->cipher = kzalloc(end - start + 1, GFP_KERNEL);
2356 strncpy(cc->cipher, start, end - start);
2362 * Workaround to parse HMAC algorithm from AEAD crypto API spec.
2363 * The HMAC is needed to calculate tag size (HMAC digest size).
2364 * This should be probably done by crypto-api calls (once available...)
2366 static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
2368 char *start, *end, *mac_alg = NULL;
2369 struct crypto_ahash *mac;
2371 if (!strstarts(cipher_api, "authenc("))
2374 start = strchr(cipher_api, '(');
2375 end = strchr(cipher_api, ',');
2376 if (!start || !end || ++start > end)
2379 mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
2382 strncpy(mac_alg, start, end - start);
2384 mac = crypto_alloc_ahash(mac_alg, 0, 0);
2388 return PTR_ERR(mac);
2390 cc->key_mac_size = crypto_ahash_digestsize(mac);
2391 crypto_free_ahash(mac);
2393 cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
2394 if (!cc->authenc_key)
2400 static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
2401 char **ivmode, char **ivopts)
2403 struct crypt_config *cc = ti->private;
2404 char *tmp, *cipher_api;
2410 * New format (capi: prefix)
2411 * capi:cipher_api_spec-iv:ivopts
2413 tmp = &cipher_in[strlen("capi:")];
2415 /* Separate IV options if present, it can contain another '-' in hash name */
2416 *ivopts = strrchr(tmp, ':');
2422 *ivmode = strrchr(tmp, '-');
2427 /* The rest is crypto API spec */
2430 if (*ivmode && !strcmp(*ivmode, "lmk"))
2431 cc->tfms_count = 64;
2433 cc->key_parts = cc->tfms_count;
2435 /* Allocate cipher */
2436 ret = crypt_alloc_tfms(cc, cipher_api);
2438 ti->error = "Error allocating crypto tfm";
2442 /* Alloc AEAD, can be used only in new format. */
2443 if (crypt_integrity_aead(cc)) {
2444 ret = crypt_ctr_auth_cipher(cc, cipher_api);
2446 ti->error = "Invalid AEAD cipher spec";
2449 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2451 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2453 ret = crypt_ctr_blkdev_cipher(cc);
2455 ti->error = "Cannot allocate cipher string";
2462 static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
2463 char **ivmode, char **ivopts)
2465 struct crypt_config *cc = ti->private;
2466 char *tmp, *cipher, *chainmode, *keycount;
2467 char *cipher_api = NULL;
2471 if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
2472 ti->error = "Bad cipher specification";
2477 * Legacy dm-crypt cipher specification
2478 * cipher[:keycount]-mode-iv:ivopts
2481 keycount = strsep(&tmp, "-");
2482 cipher = strsep(&keycount, ":");
2486 else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
2487 !is_power_of_2(cc->tfms_count)) {
2488 ti->error = "Bad cipher key count specification";
2491 cc->key_parts = cc->tfms_count;
2493 cc->cipher = kstrdup(cipher, GFP_KERNEL);
2497 chainmode = strsep(&tmp, "-");
2498 *ivmode = strsep(&tmp, ":");
2502 * For compatibility with the original dm-crypt mapping format, if
2503 * only the cipher name is supplied, use cbc-plain.
2505 if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
2510 if (strcmp(chainmode, "ecb") && !*ivmode) {
2511 ti->error = "IV mechanism required";
2515 cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
2519 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2520 "%s(%s)", chainmode, cipher);
2526 /* Allocate cipher */
2527 ret = crypt_alloc_tfms(cc, cipher_api);
2529 ti->error = "Error allocating crypto tfm";
2537 ti->error = "Cannot allocate cipher strings";
2541 static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
2543 struct crypt_config *cc = ti->private;
2544 char *ivmode = NULL, *ivopts = NULL;
2547 cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
2548 if (!cc->cipher_string) {
2549 ti->error = "Cannot allocate cipher strings";
2553 if (strstarts(cipher_in, "capi:"))
2554 ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
2556 ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
2561 ret = crypt_ctr_ivmode(ti, ivmode);
2565 /* Initialize and set key */
2566 ret = crypt_set_key(cc, key);
2568 ti->error = "Error decoding and setting key";
2573 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
2574 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
2576 ti->error = "Error creating IV";
2581 /* Initialize IV (set keys for ESSIV etc) */
2582 if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
2583 ret = cc->iv_gen_ops->init(cc);
2585 ti->error = "Error initialising IV";
2590 /* wipe the kernel key payload copy */
2592 memset(cc->key, 0, cc->key_size * sizeof(u8));
2597 static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
2599 struct crypt_config *cc = ti->private;
2600 struct dm_arg_set as;
2601 static const struct dm_arg _args[] = {
2602 {0, 6, "Invalid number of feature args"},
2604 unsigned int opt_params, val;
2605 const char *opt_string, *sval;
2609 /* Optional parameters */
2613 ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
2617 while (opt_params--) {
2618 opt_string = dm_shift_arg(&as);
2620 ti->error = "Not enough feature arguments";
2624 if (!strcasecmp(opt_string, "allow_discards"))
2625 ti->num_discard_bios = 1;
2627 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
2628 set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
2630 else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
2631 set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
2632 else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
2633 if (val == 0 || val > MAX_TAG_SIZE) {
2634 ti->error = "Invalid integrity arguments";
2637 cc->on_disk_tag_size = val;
2638 sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
2639 if (!strcasecmp(sval, "aead")) {
2640 set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
2641 } else if (strcasecmp(sval, "none")) {
2642 ti->error = "Unknown integrity profile";
2646 cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
2647 if (!cc->cipher_auth)
2649 } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
2650 if (cc->sector_size < (1 << SECTOR_SHIFT) ||
2651 cc->sector_size > 4096 ||
2652 (cc->sector_size & (cc->sector_size - 1))) {
2653 ti->error = "Invalid feature value for sector_size";
2656 if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
2657 ti->error = "Device size is not multiple of sector_size feature";
2660 cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
2661 } else if (!strcasecmp(opt_string, "iv_large_sectors"))
2662 set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
2664 ti->error = "Invalid feature arguments";
2673 * Construct an encryption mapping:
2674 * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
2676 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
2678 struct crypt_config *cc;
2679 const char *devname = dm_table_device_name(ti->table);
2681 unsigned int align_mask;
2682 unsigned long long tmpll;
2684 size_t iv_size_padding, additional_req_size;
2688 ti->error = "Not enough arguments";
2692 key_size = get_key_size(&argv[1]);
2694 ti->error = "Cannot parse key size";
2698 cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
2700 ti->error = "Cannot allocate encryption context";
2703 cc->key_size = key_size;
2704 cc->sector_size = (1 << SECTOR_SHIFT);
2705 cc->sector_shift = 0;
2709 spin_lock(&dm_crypt_clients_lock);
2710 dm_crypt_clients_n++;
2711 crypt_calculate_pages_per_client();
2712 spin_unlock(&dm_crypt_clients_lock);
2714 ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
2718 /* Optional parameters need to be read before cipher constructor */
2720 ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
2725 ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
2729 if (crypt_integrity_aead(cc)) {
2730 cc->dmreq_start = sizeof(struct aead_request);
2731 cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
2732 align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
2734 cc->dmreq_start = sizeof(struct skcipher_request);
2735 cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
2736 align_mask = crypto_skcipher_alignmask(any_tfm(cc));
2738 cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
2740 if (align_mask < CRYPTO_MINALIGN) {
2741 /* Allocate the padding exactly */
2742 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
2746 * If the cipher requires greater alignment than kmalloc
2747 * alignment, we don't know the exact position of the
2748 * initialization vector. We must assume worst case.
2750 iv_size_padding = align_mask;
2753 /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
2754 additional_req_size = sizeof(struct dm_crypt_request) +
2755 iv_size_padding + cc->iv_size +
2758 sizeof(unsigned int);
2760 ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
2762 ti->error = "Cannot allocate crypt request mempool";
2766 cc->per_bio_data_size = ti->per_io_data_size =
2767 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
2768 ARCH_KMALLOC_MINALIGN);
2770 ret = mempool_init(&cc->page_pool, BIO_MAX_PAGES, crypt_page_alloc, crypt_page_free, cc);
2772 ti->error = "Cannot allocate page mempool";
2776 ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
2778 ti->error = "Cannot allocate crypt bioset";
2782 mutex_init(&cc->bio_alloc_lock);
2785 if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
2786 (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
2787 ti->error = "Invalid iv_offset sector";
2790 cc->iv_offset = tmpll;
2792 ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
2794 ti->error = "Device lookup failed";
2799 if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
2800 ti->error = "Invalid device sector";
2805 if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
2806 ret = crypt_integrity_ctr(cc, ti);
2810 cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
2811 if (!cc->tag_pool_max_sectors)
2812 cc->tag_pool_max_sectors = 1;
2814 ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
2815 cc->tag_pool_max_sectors * cc->on_disk_tag_size);
2817 ti->error = "Cannot allocate integrity tags mempool";
2821 cc->tag_pool_max_sectors <<= cc->sector_shift;
2825 cc->io_queue = alloc_workqueue("kcryptd_io/%s",
2826 WQ_HIGHPRI | WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM,
2828 if (!cc->io_queue) {
2829 ti->error = "Couldn't create kcryptd io queue";
2833 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
2834 cc->crypt_queue = alloc_workqueue("kcryptd/%s",
2835 WQ_HIGHPRI | WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM,
2838 cc->crypt_queue = alloc_workqueue("kcryptd/%s",
2839 WQ_HIGHPRI | WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
2840 num_online_cpus(), devname);
2841 if (!cc->crypt_queue) {
2842 ti->error = "Couldn't create kcryptd queue";
2846 spin_lock_init(&cc->write_thread_lock);
2847 cc->write_tree = RB_ROOT;
2849 cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
2850 if (IS_ERR(cc->write_thread)) {
2851 ret = PTR_ERR(cc->write_thread);
2852 cc->write_thread = NULL;
2853 ti->error = "Couldn't spawn write thread";
2856 wake_up_process(cc->write_thread);
2858 ti->num_flush_bios = 1;
2867 static int crypt_map(struct dm_target *ti, struct bio *bio)
2869 struct dm_crypt_io *io;
2870 struct crypt_config *cc = ti->private;
2873 * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
2874 * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
2875 * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
2877 if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
2878 bio_op(bio) == REQ_OP_DISCARD)) {
2879 bio_set_dev(bio, cc->dev->bdev);
2880 if (bio_sectors(bio))
2881 bio->bi_iter.bi_sector = cc->start +
2882 dm_target_offset(ti, bio->bi_iter.bi_sector);
2883 return DM_MAPIO_REMAPPED;
2887 * Check if bio is too large, split as needed.
2889 if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_PAGES << PAGE_SHIFT)) &&
2890 (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
2891 dm_accept_partial_bio(bio, ((BIO_MAX_PAGES << PAGE_SHIFT) >> SECTOR_SHIFT));
2894 * Ensure that bio is a multiple of internal sector encryption size
2895 * and is aligned to this size as defined in IO hints.
2897 if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
2898 return DM_MAPIO_KILL;
2900 if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
2901 return DM_MAPIO_KILL;
2903 io = dm_per_bio_data(bio, cc->per_bio_data_size);
2904 crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
2906 if (cc->on_disk_tag_size) {
2907 unsigned tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
2909 if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
2910 unlikely(!(io->integrity_metadata = kmalloc(tag_len,
2911 GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
2912 if (bio_sectors(bio) > cc->tag_pool_max_sectors)
2913 dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
2914 io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
2915 io->integrity_metadata_from_pool = true;
2919 if (crypt_integrity_aead(cc))
2920 io->ctx.r.req_aead = (struct aead_request *)(io + 1);
2922 io->ctx.r.req = (struct skcipher_request *)(io + 1);
2924 if (bio_data_dir(io->base_bio) == READ) {
2925 if (kcryptd_io_read(io, GFP_NOWAIT))
2926 kcryptd_queue_read(io);
2928 kcryptd_queue_crypt(io);
2930 return DM_MAPIO_SUBMITTED;
2933 static void crypt_status(struct dm_target *ti, status_type_t type,
2934 unsigned status_flags, char *result, unsigned maxlen)
2936 struct crypt_config *cc = ti->private;
2938 int num_feature_args = 0;
2941 case STATUSTYPE_INFO:
2945 case STATUSTYPE_TABLE:
2946 DMEMIT("%s ", cc->cipher_string);
2948 if (cc->key_size > 0) {
2950 DMEMIT(":%u:%s", cc->key_size, cc->key_string);
2952 for (i = 0; i < cc->key_size; i++)
2953 DMEMIT("%02x", cc->key[i]);
2957 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
2958 cc->dev->name, (unsigned long long)cc->start);
2960 num_feature_args += !!ti->num_discard_bios;
2961 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
2962 num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
2963 num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
2964 num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
2965 if (cc->on_disk_tag_size)
2967 if (num_feature_args) {
2968 DMEMIT(" %d", num_feature_args);
2969 if (ti->num_discard_bios)
2970 DMEMIT(" allow_discards");
2971 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
2972 DMEMIT(" same_cpu_crypt");
2973 if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
2974 DMEMIT(" submit_from_crypt_cpus");
2975 if (cc->on_disk_tag_size)
2976 DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
2977 if (cc->sector_size != (1 << SECTOR_SHIFT))
2978 DMEMIT(" sector_size:%d", cc->sector_size);
2979 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
2980 DMEMIT(" iv_large_sectors");
2987 static void crypt_postsuspend(struct dm_target *ti)
2989 struct crypt_config *cc = ti->private;
2991 set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
2994 static int crypt_preresume(struct dm_target *ti)
2996 struct crypt_config *cc = ti->private;
2998 if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
2999 DMERR("aborting resume - crypt key is not set.");
3006 static void crypt_resume(struct dm_target *ti)
3008 struct crypt_config *cc = ti->private;
3010 clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3013 /* Message interface
3017 static int crypt_message(struct dm_target *ti, unsigned argc, char **argv,
3018 char *result, unsigned maxlen)
3020 struct crypt_config *cc = ti->private;
3021 int key_size, ret = -EINVAL;
3026 if (!strcasecmp(argv[0], "key")) {
3027 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
3028 DMWARN("not suspended during key manipulation.");
3031 if (argc == 3 && !strcasecmp(argv[1], "set")) {
3032 /* The key size may not be changed. */
3033 key_size = get_key_size(&argv[2]);
3034 if (key_size < 0 || cc->key_size != key_size) {
3035 memset(argv[2], '0', strlen(argv[2]));
3039 ret = crypt_set_key(cc, argv[2]);
3042 if (cc->iv_gen_ops && cc->iv_gen_ops->init)
3043 ret = cc->iv_gen_ops->init(cc);
3044 /* wipe the kernel key payload copy */
3046 memset(cc->key, 0, cc->key_size * sizeof(u8));
3049 if (argc == 2 && !strcasecmp(argv[1], "wipe")) {
3050 if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
3051 ret = cc->iv_gen_ops->wipe(cc);
3055 return crypt_wipe_key(cc);
3060 DMWARN("unrecognised message received.");
3064 static int crypt_iterate_devices(struct dm_target *ti,
3065 iterate_devices_callout_fn fn, void *data)
3067 struct crypt_config *cc = ti->private;
3069 return fn(ti, cc->dev, cc->start, ti->len, data);
3072 static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
3074 struct crypt_config *cc = ti->private;
3077 * Unfortunate constraint that is required to avoid the potential
3078 * for exceeding underlying device's max_segments limits -- due to
3079 * crypt_alloc_buffer() possibly allocating pages for the encryption
3080 * bio that are not as physically contiguous as the original bio.
3082 limits->max_segment_size = PAGE_SIZE;
3084 limits->logical_block_size =
3085 max_t(unsigned short, limits->logical_block_size, cc->sector_size);
3086 limits->physical_block_size =
3087 max_t(unsigned, limits->physical_block_size, cc->sector_size);
3088 limits->io_min = max_t(unsigned, limits->io_min, cc->sector_size);
3091 static struct target_type crypt_target = {
3093 .version = {1, 18, 1},
3094 .module = THIS_MODULE,
3098 .status = crypt_status,
3099 .postsuspend = crypt_postsuspend,
3100 .preresume = crypt_preresume,
3101 .resume = crypt_resume,
3102 .message = crypt_message,
3103 .iterate_devices = crypt_iterate_devices,
3104 .io_hints = crypt_io_hints,
3107 static int __init dm_crypt_init(void)
3111 r = dm_register_target(&crypt_target);
3113 DMERR("register failed %d", r);
3118 static void __exit dm_crypt_exit(void)
3120 dm_unregister_target(&crypt_target);
3123 module_init(dm_crypt_init);
3124 module_exit(dm_crypt_exit);
3126 MODULE_AUTHOR("Jana Saout <jana@saout.de>");
3127 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
3128 MODULE_LICENSE("GPL");