2 * Copyright (C) 2003 Jana Saout <jana@saout.de>
3 * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
4 * Copyright (C) 2006-2017 Red Hat, Inc. All rights reserved.
5 * Copyright (C) 2013-2017 Milan Broz <gmazyland@gmail.com>
7 * This file is released under the GPL.
10 #include <linux/completion.h>
11 #include <linux/err.h>
12 #include <linux/module.h>
13 #include <linux/init.h>
14 #include <linux/kernel.h>
15 #include <linux/key.h>
16 #include <linux/bio.h>
17 #include <linux/blkdev.h>
18 #include <linux/mempool.h>
19 #include <linux/slab.h>
20 #include <linux/crypto.h>
21 #include <linux/workqueue.h>
22 #include <linux/kthread.h>
23 #include <linux/backing-dev.h>
24 #include <linux/atomic.h>
25 #include <linux/scatterlist.h>
26 #include <linux/rbtree.h>
27 #include <linux/ctype.h>
29 #include <asm/unaligned.h>
30 #include <crypto/hash.h>
31 #include <crypto/md5.h>
32 #include <crypto/algapi.h>
33 #include <crypto/skcipher.h>
34 #include <crypto/aead.h>
35 #include <crypto/authenc.h>
36 #include <linux/rtnetlink.h> /* for struct rtattr and RTA macros only */
37 #include <keys/user-type.h>
39 #include <linux/device-mapper.h>
41 #define DM_MSG_PREFIX "crypt"
44 * context holding the current state of a multi-part conversion
46 struct convert_context {
47 struct completion restart;
50 struct bvec_iter iter_in;
51 struct bvec_iter iter_out;
55 struct skcipher_request *req;
56 struct aead_request *req_aead;
62 * per bio private data
65 struct crypt_config *cc;
67 u8 *integrity_metadata;
68 bool integrity_metadata_from_pool;
69 struct work_struct work;
71 struct convert_context ctx;
77 struct rb_node rb_node;
78 } CRYPTO_MINALIGN_ATTR;
80 struct dm_crypt_request {
81 struct convert_context *ctx;
82 struct scatterlist sg_in[4];
83 struct scatterlist sg_out[4];
89 struct crypt_iv_operations {
90 int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
92 void (*dtr)(struct crypt_config *cc);
93 int (*init)(struct crypt_config *cc);
94 int (*wipe)(struct crypt_config *cc);
95 int (*generator)(struct crypt_config *cc, u8 *iv,
96 struct dm_crypt_request *dmreq);
97 int (*post)(struct crypt_config *cc, u8 *iv,
98 struct dm_crypt_request *dmreq);
101 struct iv_essiv_private {
102 struct crypto_ahash *hash_tfm;
106 struct iv_benbi_private {
110 #define LMK_SEED_SIZE 64 /* hash + 0 */
111 struct iv_lmk_private {
112 struct crypto_shash *hash_tfm;
116 #define TCW_WHITENING_SIZE 16
117 struct iv_tcw_private {
118 struct crypto_shash *crc32_tfm;
124 * Crypt: maps a linear range of a block device
125 * and encrypts / decrypts at the same time.
127 enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
128 DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD };
131 CRYPT_MODE_INTEGRITY_AEAD, /* Use authenticated mode for cihper */
132 CRYPT_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 {
143 * pool for per bio private data, crypto requests,
144 * encryption requeusts/buffer pages and integrity tags
147 mempool_t *page_pool;
149 unsigned tag_pool_max_sectors;
152 struct mutex bio_alloc_lock;
154 struct workqueue_struct *io_queue;
155 struct workqueue_struct *crypt_queue;
157 struct task_struct *write_thread;
158 wait_queue_head_t write_thread_wait;
159 struct rb_root write_tree;
166 const struct crypt_iv_operations *iv_gen_ops;
168 struct iv_essiv_private essiv;
169 struct iv_benbi_private benbi;
170 struct iv_lmk_private lmk;
171 struct iv_tcw_private tcw;
174 unsigned int iv_size;
175 unsigned short int sector_size;
176 unsigned char sector_shift;
178 /* ESSIV: struct crypto_cipher *essiv_tfm */
181 struct crypto_skcipher **tfms;
182 struct crypto_aead **tfms_aead;
185 unsigned long cipher_flags;
188 * Layout of each crypto request:
190 * struct skcipher_request
193 * struct dm_crypt_request
197 * The padding is added so that dm_crypt_request and the IV are
200 unsigned int dmreq_start;
202 unsigned int per_bio_data_size;
205 unsigned int key_size;
206 unsigned int key_parts; /* independent parts in key buffer */
207 unsigned int key_extra_size; /* additional keys length */
208 unsigned int key_mac_size; /* MAC key size for authenc(...) */
210 unsigned int integrity_tag_size;
211 unsigned int integrity_iv_size;
212 unsigned int on_disk_tag_size;
214 u8 *authenc_key; /* space for keys in authenc() format (if used) */
219 #define MAX_TAG_SIZE 480
220 #define POOL_ENTRY_SIZE 512
222 static void clone_init(struct dm_crypt_io *, struct bio *);
223 static void kcryptd_queue_crypt(struct dm_crypt_io *io);
224 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
225 struct scatterlist *sg);
228 * Use this to access cipher attributes that are independent of the key.
230 static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
232 return cc->cipher_tfm.tfms[0];
235 static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
237 return cc->cipher_tfm.tfms_aead[0];
241 * Different IV generation algorithms:
243 * plain: the initial vector is the 32-bit little-endian version of the sector
244 * number, padded with zeros if necessary.
246 * plain64: the initial vector is the 64-bit little-endian version of the sector
247 * number, padded with zeros if necessary.
249 * plain64be: the initial vector is the 64-bit big-endian version of the sector
250 * number, padded with zeros if necessary.
252 * essiv: "encrypted sector|salt initial vector", the sector number is
253 * encrypted with the bulk cipher using a salt as key. The salt
254 * should be derived from the bulk cipher's key via hashing.
256 * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
257 * (needed for LRW-32-AES and possible other narrow block modes)
259 * null: the initial vector is always zero. Provides compatibility with
260 * obsolete loop_fish2 devices. Do not use for new devices.
262 * lmk: Compatible implementation of the block chaining mode used
263 * by the Loop-AES block device encryption system
264 * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
265 * It operates on full 512 byte sectors and uses CBC
266 * with an IV derived from the sector number, the data and
267 * optionally extra IV seed.
268 * This means that after decryption the first block
269 * of sector must be tweaked according to decrypted data.
270 * Loop-AES can use three encryption schemes:
271 * version 1: is plain aes-cbc mode
272 * version 2: uses 64 multikey scheme with lmk IV generator
273 * version 3: the same as version 2 with additional IV seed
274 * (it uses 65 keys, last key is used as IV seed)
276 * tcw: Compatible implementation of the block chaining mode used
277 * by the TrueCrypt device encryption system (prior to version 4.1).
278 * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
279 * It operates on full 512 byte sectors and uses CBC
280 * with an IV derived from initial key and the sector number.
281 * In addition, whitening value is applied on every sector, whitening
282 * is calculated from initial key, sector number and mixed using CRC32.
283 * Note that this encryption scheme is vulnerable to watermarking attacks
284 * and should be used for old compatible containers access only.
286 * plumb: unimplemented, see:
287 * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
290 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
291 struct dm_crypt_request *dmreq)
293 memset(iv, 0, cc->iv_size);
294 *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
299 static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
300 struct dm_crypt_request *dmreq)
302 memset(iv, 0, cc->iv_size);
303 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
308 static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
309 struct dm_crypt_request *dmreq)
311 memset(iv, 0, cc->iv_size);
312 /* iv_size is at least of size u64; usually it is 16 bytes */
313 *(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
318 /* Initialise ESSIV - compute salt but no local memory allocations */
319 static int crypt_iv_essiv_init(struct crypt_config *cc)
321 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
322 AHASH_REQUEST_ON_STACK(req, essiv->hash_tfm);
323 struct scatterlist sg;
324 struct crypto_cipher *essiv_tfm;
327 sg_init_one(&sg, cc->key, cc->key_size);
328 ahash_request_set_tfm(req, essiv->hash_tfm);
329 ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP, NULL, NULL);
330 ahash_request_set_crypt(req, &sg, essiv->salt, cc->key_size);
332 err = crypto_ahash_digest(req);
333 ahash_request_zero(req);
337 essiv_tfm = cc->iv_private;
339 err = crypto_cipher_setkey(essiv_tfm, essiv->salt,
340 crypto_ahash_digestsize(essiv->hash_tfm));
347 /* Wipe salt and reset key derived from volume key */
348 static int crypt_iv_essiv_wipe(struct crypt_config *cc)
350 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
351 unsigned salt_size = crypto_ahash_digestsize(essiv->hash_tfm);
352 struct crypto_cipher *essiv_tfm;
355 memset(essiv->salt, 0, salt_size);
357 essiv_tfm = cc->iv_private;
358 r = crypto_cipher_setkey(essiv_tfm, essiv->salt, salt_size);
365 /* Allocate the cipher for ESSIV */
366 static struct crypto_cipher *alloc_essiv_cipher(struct crypt_config *cc,
367 struct dm_target *ti,
369 unsigned int saltsize)
371 struct crypto_cipher *essiv_tfm;
374 /* Setup the essiv_tfm with the given salt */
375 essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
376 if (IS_ERR(essiv_tfm)) {
377 ti->error = "Error allocating crypto tfm for ESSIV";
381 if (crypto_cipher_blocksize(essiv_tfm) != cc->iv_size) {
382 ti->error = "Block size of ESSIV cipher does "
383 "not match IV size of block cipher";
384 crypto_free_cipher(essiv_tfm);
385 return ERR_PTR(-EINVAL);
388 err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
390 ti->error = "Failed to set key for ESSIV cipher";
391 crypto_free_cipher(essiv_tfm);
398 static void crypt_iv_essiv_dtr(struct crypt_config *cc)
400 struct crypto_cipher *essiv_tfm;
401 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
403 crypto_free_ahash(essiv->hash_tfm);
404 essiv->hash_tfm = NULL;
409 essiv_tfm = cc->iv_private;
412 crypto_free_cipher(essiv_tfm);
414 cc->iv_private = NULL;
417 static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
420 struct crypto_cipher *essiv_tfm = NULL;
421 struct crypto_ahash *hash_tfm = NULL;
426 ti->error = "Digest algorithm missing for ESSIV mode";
430 /* Allocate hash algorithm */
431 hash_tfm = crypto_alloc_ahash(opts, 0, CRYPTO_ALG_ASYNC);
432 if (IS_ERR(hash_tfm)) {
433 ti->error = "Error initializing ESSIV hash";
434 err = PTR_ERR(hash_tfm);
438 salt = kzalloc(crypto_ahash_digestsize(hash_tfm), GFP_KERNEL);
440 ti->error = "Error kmallocing salt storage in ESSIV";
445 cc->iv_gen_private.essiv.salt = salt;
446 cc->iv_gen_private.essiv.hash_tfm = hash_tfm;
448 essiv_tfm = alloc_essiv_cipher(cc, ti, salt,
449 crypto_ahash_digestsize(hash_tfm));
450 if (IS_ERR(essiv_tfm)) {
451 crypt_iv_essiv_dtr(cc);
452 return PTR_ERR(essiv_tfm);
454 cc->iv_private = essiv_tfm;
459 if (hash_tfm && !IS_ERR(hash_tfm))
460 crypto_free_ahash(hash_tfm);
465 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
466 struct dm_crypt_request *dmreq)
468 struct crypto_cipher *essiv_tfm = cc->iv_private;
470 memset(iv, 0, cc->iv_size);
471 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
472 crypto_cipher_encrypt_one(essiv_tfm, iv, iv);
477 static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
480 unsigned bs = crypto_skcipher_blocksize(any_tfm(cc));
483 /* we need to calculate how far we must shift the sector count
484 * to get the cipher block count, we use this shift in _gen */
486 if (1 << log != bs) {
487 ti->error = "cypher blocksize is not a power of 2";
492 ti->error = "cypher blocksize is > 512";
496 cc->iv_gen_private.benbi.shift = 9 - log;
501 static void crypt_iv_benbi_dtr(struct crypt_config *cc)
505 static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
506 struct dm_crypt_request *dmreq)
510 memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
512 val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
513 put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
518 static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
519 struct dm_crypt_request *dmreq)
521 memset(iv, 0, cc->iv_size);
526 static void crypt_iv_lmk_dtr(struct crypt_config *cc)
528 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
530 if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
531 crypto_free_shash(lmk->hash_tfm);
532 lmk->hash_tfm = NULL;
538 static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
541 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
543 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
544 ti->error = "Unsupported sector size for LMK";
548 lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
549 if (IS_ERR(lmk->hash_tfm)) {
550 ti->error = "Error initializing LMK hash";
551 return PTR_ERR(lmk->hash_tfm);
554 /* No seed in LMK version 2 */
555 if (cc->key_parts == cc->tfms_count) {
560 lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
562 crypt_iv_lmk_dtr(cc);
563 ti->error = "Error kmallocing seed storage in LMK";
570 static int crypt_iv_lmk_init(struct crypt_config *cc)
572 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
573 int subkey_size = cc->key_size / cc->key_parts;
575 /* LMK seed is on the position of LMK_KEYS + 1 key */
577 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
578 crypto_shash_digestsize(lmk->hash_tfm));
583 static int crypt_iv_lmk_wipe(struct crypt_config *cc)
585 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
588 memset(lmk->seed, 0, LMK_SEED_SIZE);
593 static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
594 struct dm_crypt_request *dmreq,
597 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
598 SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
599 struct md5_state md5state;
603 desc->tfm = lmk->hash_tfm;
604 desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
606 r = crypto_shash_init(desc);
611 r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
616 /* Sector is always 512B, block size 16, add data of blocks 1-31 */
617 r = crypto_shash_update(desc, data + 16, 16 * 31);
621 /* Sector is cropped to 56 bits here */
622 buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
623 buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
624 buf[2] = cpu_to_le32(4024);
626 r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
630 /* No MD5 padding here */
631 r = crypto_shash_export(desc, &md5state);
635 for (i = 0; i < MD5_HASH_WORDS; i++)
636 __cpu_to_le32s(&md5state.hash[i]);
637 memcpy(iv, &md5state.hash, cc->iv_size);
642 static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
643 struct dm_crypt_request *dmreq)
645 struct scatterlist *sg;
649 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
650 sg = crypt_get_sg_data(cc, dmreq->sg_in);
651 src = kmap_atomic(sg_page(sg));
652 r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
655 memset(iv, 0, cc->iv_size);
660 static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
661 struct dm_crypt_request *dmreq)
663 struct scatterlist *sg;
667 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
670 sg = crypt_get_sg_data(cc, dmreq->sg_out);
671 dst = kmap_atomic(sg_page(sg));
672 r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
674 /* Tweak the first block of plaintext sector */
676 crypto_xor(dst + sg->offset, iv, cc->iv_size);
682 static void crypt_iv_tcw_dtr(struct crypt_config *cc)
684 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
686 kzfree(tcw->iv_seed);
688 kzfree(tcw->whitening);
689 tcw->whitening = NULL;
691 if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
692 crypto_free_shash(tcw->crc32_tfm);
693 tcw->crc32_tfm = NULL;
696 static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
699 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
701 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
702 ti->error = "Unsupported sector size for TCW";
706 if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
707 ti->error = "Wrong key size for TCW";
711 tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
712 if (IS_ERR(tcw->crc32_tfm)) {
713 ti->error = "Error initializing CRC32 in TCW";
714 return PTR_ERR(tcw->crc32_tfm);
717 tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
718 tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
719 if (!tcw->iv_seed || !tcw->whitening) {
720 crypt_iv_tcw_dtr(cc);
721 ti->error = "Error allocating seed storage in TCW";
728 static int crypt_iv_tcw_init(struct crypt_config *cc)
730 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
731 int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
733 memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
734 memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
740 static int crypt_iv_tcw_wipe(struct crypt_config *cc)
742 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
744 memset(tcw->iv_seed, 0, cc->iv_size);
745 memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
750 static int crypt_iv_tcw_whitening(struct crypt_config *cc,
751 struct dm_crypt_request *dmreq,
754 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
755 __le64 sector = cpu_to_le64(dmreq->iv_sector);
756 u8 buf[TCW_WHITENING_SIZE];
757 SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
760 /* xor whitening with sector number */
761 crypto_xor_cpy(buf, tcw->whitening, (u8 *)§or, 8);
762 crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)§or, 8);
764 /* calculate crc32 for every 32bit part and xor it */
765 desc->tfm = tcw->crc32_tfm;
766 desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
767 for (i = 0; i < 4; i++) {
768 r = crypto_shash_init(desc);
771 r = crypto_shash_update(desc, &buf[i * 4], 4);
774 r = crypto_shash_final(desc, &buf[i * 4]);
778 crypto_xor(&buf[0], &buf[12], 4);
779 crypto_xor(&buf[4], &buf[8], 4);
781 /* apply whitening (8 bytes) to whole sector */
782 for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
783 crypto_xor(data + i * 8, buf, 8);
785 memzero_explicit(buf, sizeof(buf));
789 static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
790 struct dm_crypt_request *dmreq)
792 struct scatterlist *sg;
793 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
794 __le64 sector = cpu_to_le64(dmreq->iv_sector);
798 /* Remove whitening from ciphertext */
799 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
800 sg = crypt_get_sg_data(cc, dmreq->sg_in);
801 src = kmap_atomic(sg_page(sg));
802 r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
807 crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)§or, 8);
809 crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)§or,
815 static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
816 struct dm_crypt_request *dmreq)
818 struct scatterlist *sg;
822 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
825 /* Apply whitening on ciphertext */
826 sg = crypt_get_sg_data(cc, dmreq->sg_out);
827 dst = kmap_atomic(sg_page(sg));
828 r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
834 static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
835 struct dm_crypt_request *dmreq)
837 /* Used only for writes, there must be an additional space to store IV */
838 get_random_bytes(iv, cc->iv_size);
842 static const struct crypt_iv_operations crypt_iv_plain_ops = {
843 .generator = crypt_iv_plain_gen
846 static const struct crypt_iv_operations crypt_iv_plain64_ops = {
847 .generator = crypt_iv_plain64_gen
850 static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
851 .generator = crypt_iv_plain64be_gen
854 static const struct crypt_iv_operations crypt_iv_essiv_ops = {
855 .ctr = crypt_iv_essiv_ctr,
856 .dtr = crypt_iv_essiv_dtr,
857 .init = crypt_iv_essiv_init,
858 .wipe = crypt_iv_essiv_wipe,
859 .generator = crypt_iv_essiv_gen
862 static const struct crypt_iv_operations crypt_iv_benbi_ops = {
863 .ctr = crypt_iv_benbi_ctr,
864 .dtr = crypt_iv_benbi_dtr,
865 .generator = crypt_iv_benbi_gen
868 static const struct crypt_iv_operations crypt_iv_null_ops = {
869 .generator = crypt_iv_null_gen
872 static const struct crypt_iv_operations crypt_iv_lmk_ops = {
873 .ctr = crypt_iv_lmk_ctr,
874 .dtr = crypt_iv_lmk_dtr,
875 .init = crypt_iv_lmk_init,
876 .wipe = crypt_iv_lmk_wipe,
877 .generator = crypt_iv_lmk_gen,
878 .post = crypt_iv_lmk_post
881 static const struct crypt_iv_operations crypt_iv_tcw_ops = {
882 .ctr = crypt_iv_tcw_ctr,
883 .dtr = crypt_iv_tcw_dtr,
884 .init = crypt_iv_tcw_init,
885 .wipe = crypt_iv_tcw_wipe,
886 .generator = crypt_iv_tcw_gen,
887 .post = crypt_iv_tcw_post
890 static struct crypt_iv_operations crypt_iv_random_ops = {
891 .generator = crypt_iv_random_gen
895 * Integrity extensions
897 static bool crypt_integrity_aead(struct crypt_config *cc)
899 return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
902 static bool crypt_integrity_hmac(struct crypt_config *cc)
904 return crypt_integrity_aead(cc) && cc->key_mac_size;
907 /* Get sg containing data */
908 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
909 struct scatterlist *sg)
911 if (unlikely(crypt_integrity_aead(cc)))
917 static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
919 struct bio_integrity_payload *bip;
920 unsigned int tag_len;
923 if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
926 bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
930 tag_len = io->cc->on_disk_tag_size * bio_sectors(bio);
932 bip->bip_iter.bi_size = tag_len;
933 bip->bip_iter.bi_sector = io->cc->start + io->sector;
935 ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
936 tag_len, offset_in_page(io->integrity_metadata));
937 if (unlikely(ret != tag_len))
943 static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
945 #ifdef CONFIG_BLK_DEV_INTEGRITY
946 struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
948 /* From now we require underlying device with our integrity profile */
949 if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
950 ti->error = "Integrity profile not supported.";
954 if (bi->tag_size != cc->on_disk_tag_size ||
955 bi->tuple_size != cc->on_disk_tag_size) {
956 ti->error = "Integrity profile tag size mismatch.";
959 if (1 << bi->interval_exp != cc->sector_size) {
960 ti->error = "Integrity profile sector size mismatch.";
964 if (crypt_integrity_aead(cc)) {
965 cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
966 DMINFO("Integrity AEAD, tag size %u, IV size %u.",
967 cc->integrity_tag_size, cc->integrity_iv_size);
969 if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
970 ti->error = "Integrity AEAD auth tag size is not supported.";
973 } else if (cc->integrity_iv_size)
974 DMINFO("Additional per-sector space %u bytes for IV.",
975 cc->integrity_iv_size);
977 if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
978 ti->error = "Not enough space for integrity tag in the profile.";
984 ti->error = "Integrity profile not supported.";
989 static void crypt_convert_init(struct crypt_config *cc,
990 struct convert_context *ctx,
991 struct bio *bio_out, struct bio *bio_in,
994 ctx->bio_in = bio_in;
995 ctx->bio_out = bio_out;
997 ctx->iter_in = bio_in->bi_iter;
999 ctx->iter_out = bio_out->bi_iter;
1000 ctx->cc_sector = sector + cc->iv_offset;
1001 init_completion(&ctx->restart);
1004 static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
1007 return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
1010 static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
1012 return (void *)((char *)dmreq - cc->dmreq_start);
1015 static u8 *iv_of_dmreq(struct crypt_config *cc,
1016 struct dm_crypt_request *dmreq)
1018 if (crypt_integrity_aead(cc))
1019 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1020 crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
1022 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1023 crypto_skcipher_alignmask(any_tfm(cc)) + 1);
1026 static u8 *org_iv_of_dmreq(struct crypt_config *cc,
1027 struct dm_crypt_request *dmreq)
1029 return iv_of_dmreq(cc, dmreq) + cc->iv_size;
1032 static uint64_t *org_sector_of_dmreq(struct crypt_config *cc,
1033 struct dm_crypt_request *dmreq)
1035 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
1036 return (uint64_t*) ptr;
1039 static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
1040 struct dm_crypt_request *dmreq)
1042 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
1043 cc->iv_size + sizeof(uint64_t);
1044 return (unsigned int*)ptr;
1047 static void *tag_from_dmreq(struct crypt_config *cc,
1048 struct dm_crypt_request *dmreq)
1050 struct convert_context *ctx = dmreq->ctx;
1051 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1053 return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
1054 cc->on_disk_tag_size];
1057 static void *iv_tag_from_dmreq(struct crypt_config *cc,
1058 struct dm_crypt_request *dmreq)
1060 return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
1063 static int crypt_convert_block_aead(struct crypt_config *cc,
1064 struct convert_context *ctx,
1065 struct aead_request *req,
1066 unsigned int tag_offset)
1068 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1069 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1070 struct dm_crypt_request *dmreq;
1071 u8 *iv, *org_iv, *tag_iv, *tag;
1075 BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
1077 /* Reject unexpected unaligned bio. */
1078 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1081 dmreq = dmreq_of_req(cc, req);
1082 dmreq->iv_sector = ctx->cc_sector;
1083 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1084 dmreq->iv_sector >>= cc->sector_shift;
1087 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1089 sector = org_sector_of_dmreq(cc, dmreq);
1090 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1092 iv = iv_of_dmreq(cc, dmreq);
1093 org_iv = org_iv_of_dmreq(cc, dmreq);
1094 tag = tag_from_dmreq(cc, dmreq);
1095 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1098 * |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1099 * | (authenticated) | (auth+encryption) | |
1100 * | sector_LE | IV | sector in/out | tag in/out |
1102 sg_init_table(dmreq->sg_in, 4);
1103 sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
1104 sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
1105 sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1106 sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
1108 sg_init_table(dmreq->sg_out, 4);
1109 sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
1110 sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
1111 sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1112 sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
1114 if (cc->iv_gen_ops) {
1115 /* For READs use IV stored in integrity metadata */
1116 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1117 memcpy(org_iv, tag_iv, cc->iv_size);
1119 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1122 /* Store generated IV in integrity metadata */
1123 if (cc->integrity_iv_size)
1124 memcpy(tag_iv, org_iv, cc->iv_size);
1126 /* Working copy of IV, to be modified in crypto API */
1127 memcpy(iv, org_iv, cc->iv_size);
1130 aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
1131 if (bio_data_dir(ctx->bio_in) == WRITE) {
1132 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1133 cc->sector_size, iv);
1134 r = crypto_aead_encrypt(req);
1135 if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
1136 memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
1137 cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
1139 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1140 cc->sector_size + cc->integrity_tag_size, iv);
1141 r = crypto_aead_decrypt(req);
1145 DMERR_LIMIT("INTEGRITY AEAD ERROR, sector %llu",
1146 (unsigned long long)le64_to_cpu(*sector));
1148 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1149 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1151 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1152 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1157 static int crypt_convert_block_skcipher(struct crypt_config *cc,
1158 struct convert_context *ctx,
1159 struct skcipher_request *req,
1160 unsigned int tag_offset)
1162 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1163 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1164 struct scatterlist *sg_in, *sg_out;
1165 struct dm_crypt_request *dmreq;
1166 u8 *iv, *org_iv, *tag_iv;
1170 /* Reject unexpected unaligned bio. */
1171 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1174 dmreq = dmreq_of_req(cc, req);
1175 dmreq->iv_sector = ctx->cc_sector;
1176 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1177 dmreq->iv_sector >>= cc->sector_shift;
1180 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1182 iv = iv_of_dmreq(cc, dmreq);
1183 org_iv = org_iv_of_dmreq(cc, dmreq);
1184 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1186 sector = org_sector_of_dmreq(cc, dmreq);
1187 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1189 /* For skcipher we use only the first sg item */
1190 sg_in = &dmreq->sg_in[0];
1191 sg_out = &dmreq->sg_out[0];
1193 sg_init_table(sg_in, 1);
1194 sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1196 sg_init_table(sg_out, 1);
1197 sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1199 if (cc->iv_gen_ops) {
1200 /* For READs use IV stored in integrity metadata */
1201 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1202 memcpy(org_iv, tag_iv, cc->integrity_iv_size);
1204 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1207 /* Store generated IV in integrity metadata */
1208 if (cc->integrity_iv_size)
1209 memcpy(tag_iv, org_iv, cc->integrity_iv_size);
1211 /* Working copy of IV, to be modified in crypto API */
1212 memcpy(iv, org_iv, cc->iv_size);
1215 skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
1217 if (bio_data_dir(ctx->bio_in) == WRITE)
1218 r = crypto_skcipher_encrypt(req);
1220 r = crypto_skcipher_decrypt(req);
1222 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1223 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1225 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1226 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1231 static void kcryptd_async_done(struct crypto_async_request *async_req,
1234 static void crypt_alloc_req_skcipher(struct crypt_config *cc,
1235 struct convert_context *ctx)
1237 unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
1240 ctx->r.req = mempool_alloc(cc->req_pool, GFP_NOIO);
1242 skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
1245 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1246 * requests if driver request queue is full.
1248 skcipher_request_set_callback(ctx->r.req,
1249 CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
1250 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
1253 static void crypt_alloc_req_aead(struct crypt_config *cc,
1254 struct convert_context *ctx)
1256 if (!ctx->r.req_aead)
1257 ctx->r.req_aead = mempool_alloc(cc->req_pool, GFP_NOIO);
1259 aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
1262 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1263 * requests if driver request queue is full.
1265 aead_request_set_callback(ctx->r.req_aead,
1266 CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
1267 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
1270 static void crypt_alloc_req(struct crypt_config *cc,
1271 struct convert_context *ctx)
1273 if (crypt_integrity_aead(cc))
1274 crypt_alloc_req_aead(cc, ctx);
1276 crypt_alloc_req_skcipher(cc, ctx);
1279 static void crypt_free_req_skcipher(struct crypt_config *cc,
1280 struct skcipher_request *req, struct bio *base_bio)
1282 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1284 if ((struct skcipher_request *)(io + 1) != req)
1285 mempool_free(req, cc->req_pool);
1288 static void crypt_free_req_aead(struct crypt_config *cc,
1289 struct aead_request *req, struct bio *base_bio)
1291 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1293 if ((struct aead_request *)(io + 1) != req)
1294 mempool_free(req, cc->req_pool);
1297 static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
1299 if (crypt_integrity_aead(cc))
1300 crypt_free_req_aead(cc, req, base_bio);
1302 crypt_free_req_skcipher(cc, req, base_bio);
1306 * Encrypt / decrypt data from one bio to another one (can be the same one)
1308 static blk_status_t crypt_convert(struct crypt_config *cc,
1309 struct convert_context *ctx)
1311 unsigned int tag_offset = 0;
1312 unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
1315 atomic_set(&ctx->cc_pending, 1);
1317 while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
1319 crypt_alloc_req(cc, ctx);
1320 atomic_inc(&ctx->cc_pending);
1322 if (crypt_integrity_aead(cc))
1323 r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
1325 r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
1329 * The request was queued by a crypto driver
1330 * but the driver request queue is full, let's wait.
1333 wait_for_completion(&ctx->restart);
1334 reinit_completion(&ctx->restart);
1337 * The request is queued and processed asynchronously,
1338 * completion function kcryptd_async_done() will be called.
1342 ctx->cc_sector += sector_step;
1346 * The request was already processed (synchronously).
1349 atomic_dec(&ctx->cc_pending);
1350 ctx->cc_sector += sector_step;
1355 * There was a data integrity error.
1358 atomic_dec(&ctx->cc_pending);
1359 return BLK_STS_PROTECTION;
1361 * There was an error while processing the request.
1364 atomic_dec(&ctx->cc_pending);
1365 return BLK_STS_IOERR;
1372 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
1375 * Generate a new unfragmented bio with the given size
1376 * This should never violate the device limitations (but only because
1377 * max_segment_size is being constrained to PAGE_SIZE).
1379 * This function may be called concurrently. If we allocate from the mempool
1380 * concurrently, there is a possibility of deadlock. For example, if we have
1381 * mempool of 256 pages, two processes, each wanting 256, pages allocate from
1382 * the mempool concurrently, it may deadlock in a situation where both processes
1383 * have allocated 128 pages and the mempool is exhausted.
1385 * In order to avoid this scenario we allocate the pages under a mutex.
1387 * In order to not degrade performance with excessive locking, we try
1388 * non-blocking allocations without a mutex first but on failure we fallback
1389 * to blocking allocations with a mutex.
1391 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
1393 struct crypt_config *cc = io->cc;
1395 unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1396 gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
1397 unsigned i, len, remaining_size;
1401 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1402 mutex_lock(&cc->bio_alloc_lock);
1404 clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, cc->bs);
1408 clone_init(io, clone);
1410 remaining_size = size;
1412 for (i = 0; i < nr_iovecs; i++) {
1413 page = mempool_alloc(cc->page_pool, gfp_mask);
1415 crypt_free_buffer_pages(cc, clone);
1417 gfp_mask |= __GFP_DIRECT_RECLAIM;
1421 len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
1423 bio_add_page(clone, page, len, 0);
1425 remaining_size -= len;
1428 /* Allocate space for integrity tags */
1429 if (dm_crypt_integrity_io_alloc(io, clone)) {
1430 crypt_free_buffer_pages(cc, clone);
1435 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1436 mutex_unlock(&cc->bio_alloc_lock);
1441 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1446 bio_for_each_segment_all(bv, clone, i) {
1447 BUG_ON(!bv->bv_page);
1448 mempool_free(bv->bv_page, cc->page_pool);
1452 static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1453 struct bio *bio, sector_t sector)
1457 io->sector = sector;
1459 io->ctx.r.req = NULL;
1460 io->integrity_metadata = NULL;
1461 io->integrity_metadata_from_pool = false;
1462 atomic_set(&io->io_pending, 0);
1465 static void crypt_inc_pending(struct dm_crypt_io *io)
1467 atomic_inc(&io->io_pending);
1471 * One of the bios was finished. Check for completion of
1472 * the whole request and correctly clean up the buffer.
1474 static void crypt_dec_pending(struct dm_crypt_io *io)
1476 struct crypt_config *cc = io->cc;
1477 struct bio *base_bio = io->base_bio;
1478 blk_status_t error = io->error;
1480 if (!atomic_dec_and_test(&io->io_pending))
1484 crypt_free_req(cc, io->ctx.r.req, base_bio);
1486 if (unlikely(io->integrity_metadata_from_pool))
1487 mempool_free(io->integrity_metadata, io->cc->tag_pool);
1489 kfree(io->integrity_metadata);
1491 base_bio->bi_status = error;
1492 bio_endio(base_bio);
1496 * kcryptd/kcryptd_io:
1498 * Needed because it would be very unwise to do decryption in an
1499 * interrupt context.
1501 * kcryptd performs the actual encryption or decryption.
1503 * kcryptd_io performs the IO submission.
1505 * They must be separated as otherwise the final stages could be
1506 * starved by new requests which can block in the first stages due
1507 * to memory allocation.
1509 * The work is done per CPU global for all dm-crypt instances.
1510 * They should not depend on each other and do not block.
1512 static void crypt_endio(struct bio *clone)
1514 struct dm_crypt_io *io = clone->bi_private;
1515 struct crypt_config *cc = io->cc;
1516 unsigned rw = bio_data_dir(clone);
1520 * free the processed pages
1523 crypt_free_buffer_pages(cc, clone);
1525 error = clone->bi_status;
1528 if (rw == READ && !error) {
1529 kcryptd_queue_crypt(io);
1533 if (unlikely(error))
1536 crypt_dec_pending(io);
1539 static void clone_init(struct dm_crypt_io *io, struct bio *clone)
1541 struct crypt_config *cc = io->cc;
1543 clone->bi_private = io;
1544 clone->bi_end_io = crypt_endio;
1545 bio_set_dev(clone, cc->dev->bdev);
1546 clone->bi_opf = io->base_bio->bi_opf;
1549 static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
1551 struct crypt_config *cc = io->cc;
1555 * We need the original biovec array in order to decrypt
1556 * the whole bio data *afterwards* -- thanks to immutable
1557 * biovecs we don't need to worry about the block layer
1558 * modifying the biovec array; so leverage bio_clone_fast().
1560 clone = bio_clone_fast(io->base_bio, gfp, cc->bs);
1564 crypt_inc_pending(io);
1566 clone_init(io, clone);
1567 clone->bi_iter.bi_sector = cc->start + io->sector;
1569 if (dm_crypt_integrity_io_alloc(io, clone)) {
1570 crypt_dec_pending(io);
1575 generic_make_request(clone);
1579 static void kcryptd_io_read_work(struct work_struct *work)
1581 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1583 crypt_inc_pending(io);
1584 if (kcryptd_io_read(io, GFP_NOIO))
1585 io->error = BLK_STS_RESOURCE;
1586 crypt_dec_pending(io);
1589 static void kcryptd_queue_read(struct dm_crypt_io *io)
1591 struct crypt_config *cc = io->cc;
1593 INIT_WORK(&io->work, kcryptd_io_read_work);
1594 queue_work(cc->io_queue, &io->work);
1597 static void kcryptd_io_write(struct dm_crypt_io *io)
1599 struct bio *clone = io->ctx.bio_out;
1601 generic_make_request(clone);
1604 #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1606 static int dmcrypt_write(void *data)
1608 struct crypt_config *cc = data;
1609 struct dm_crypt_io *io;
1612 struct rb_root write_tree;
1613 struct blk_plug plug;
1615 DECLARE_WAITQUEUE(wait, current);
1617 spin_lock_irq(&cc->write_thread_wait.lock);
1620 if (!RB_EMPTY_ROOT(&cc->write_tree))
1623 set_current_state(TASK_INTERRUPTIBLE);
1624 __add_wait_queue(&cc->write_thread_wait, &wait);
1626 spin_unlock_irq(&cc->write_thread_wait.lock);
1628 if (unlikely(kthread_should_stop())) {
1629 set_current_state(TASK_RUNNING);
1630 remove_wait_queue(&cc->write_thread_wait, &wait);
1636 set_current_state(TASK_RUNNING);
1637 spin_lock_irq(&cc->write_thread_wait.lock);
1638 __remove_wait_queue(&cc->write_thread_wait, &wait);
1639 goto continue_locked;
1642 write_tree = cc->write_tree;
1643 cc->write_tree = RB_ROOT;
1644 spin_unlock_irq(&cc->write_thread_wait.lock);
1646 BUG_ON(rb_parent(write_tree.rb_node));
1649 * Note: we cannot walk the tree here with rb_next because
1650 * the structures may be freed when kcryptd_io_write is called.
1652 blk_start_plug(&plug);
1654 io = crypt_io_from_node(rb_first(&write_tree));
1655 rb_erase(&io->rb_node, &write_tree);
1656 kcryptd_io_write(io);
1657 } while (!RB_EMPTY_ROOT(&write_tree));
1658 blk_finish_plug(&plug);
1663 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
1665 struct bio *clone = io->ctx.bio_out;
1666 struct crypt_config *cc = io->cc;
1667 unsigned long flags;
1669 struct rb_node **rbp, *parent;
1671 if (unlikely(io->error)) {
1672 crypt_free_buffer_pages(cc, clone);
1674 crypt_dec_pending(io);
1678 /* crypt_convert should have filled the clone bio */
1679 BUG_ON(io->ctx.iter_out.bi_size);
1681 clone->bi_iter.bi_sector = cc->start + io->sector;
1683 if (likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) {
1684 generic_make_request(clone);
1688 spin_lock_irqsave(&cc->write_thread_wait.lock, flags);
1689 rbp = &cc->write_tree.rb_node;
1691 sector = io->sector;
1694 if (sector < crypt_io_from_node(parent)->sector)
1695 rbp = &(*rbp)->rb_left;
1697 rbp = &(*rbp)->rb_right;
1699 rb_link_node(&io->rb_node, parent, rbp);
1700 rb_insert_color(&io->rb_node, &cc->write_tree);
1702 wake_up_locked(&cc->write_thread_wait);
1703 spin_unlock_irqrestore(&cc->write_thread_wait.lock, flags);
1706 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
1708 struct crypt_config *cc = io->cc;
1711 sector_t sector = io->sector;
1715 * Prevent io from disappearing until this function completes.
1717 crypt_inc_pending(io);
1718 crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
1720 clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
1721 if (unlikely(!clone)) {
1722 io->error = BLK_STS_IOERR;
1726 io->ctx.bio_out = clone;
1727 io->ctx.iter_out = clone->bi_iter;
1729 sector += bio_sectors(clone);
1731 crypt_inc_pending(io);
1732 r = crypt_convert(cc, &io->ctx);
1735 crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
1737 /* Encryption was already finished, submit io now */
1738 if (crypt_finished) {
1739 kcryptd_crypt_write_io_submit(io, 0);
1740 io->sector = sector;
1744 crypt_dec_pending(io);
1747 static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
1749 crypt_dec_pending(io);
1752 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
1754 struct crypt_config *cc = io->cc;
1757 crypt_inc_pending(io);
1759 crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
1762 r = crypt_convert(cc, &io->ctx);
1766 if (atomic_dec_and_test(&io->ctx.cc_pending))
1767 kcryptd_crypt_read_done(io);
1769 crypt_dec_pending(io);
1772 static void kcryptd_async_done(struct crypto_async_request *async_req,
1775 struct dm_crypt_request *dmreq = async_req->data;
1776 struct convert_context *ctx = dmreq->ctx;
1777 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1778 struct crypt_config *cc = io->cc;
1781 * A request from crypto driver backlog is going to be processed now,
1782 * finish the completion and continue in crypt_convert().
1783 * (Callback will be called for the second time for this request.)
1785 if (error == -EINPROGRESS) {
1786 complete(&ctx->restart);
1790 if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
1791 error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
1793 if (error == -EBADMSG) {
1794 DMERR_LIMIT("INTEGRITY AEAD ERROR, sector %llu",
1795 (unsigned long long)le64_to_cpu(*org_sector_of_dmreq(cc, dmreq)));
1796 io->error = BLK_STS_PROTECTION;
1797 } else if (error < 0)
1798 io->error = BLK_STS_IOERR;
1800 crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
1802 if (!atomic_dec_and_test(&ctx->cc_pending))
1805 if (bio_data_dir(io->base_bio) == READ)
1806 kcryptd_crypt_read_done(io);
1808 kcryptd_crypt_write_io_submit(io, 1);
1811 static void kcryptd_crypt(struct work_struct *work)
1813 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1815 if (bio_data_dir(io->base_bio) == READ)
1816 kcryptd_crypt_read_convert(io);
1818 kcryptd_crypt_write_convert(io);
1821 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
1823 struct crypt_config *cc = io->cc;
1825 INIT_WORK(&io->work, kcryptd_crypt);
1826 queue_work(cc->crypt_queue, &io->work);
1829 static void crypt_free_tfms_aead(struct crypt_config *cc)
1831 if (!cc->cipher_tfm.tfms_aead)
1834 if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
1835 crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
1836 cc->cipher_tfm.tfms_aead[0] = NULL;
1839 kfree(cc->cipher_tfm.tfms_aead);
1840 cc->cipher_tfm.tfms_aead = NULL;
1843 static void crypt_free_tfms_skcipher(struct crypt_config *cc)
1847 if (!cc->cipher_tfm.tfms)
1850 for (i = 0; i < cc->tfms_count; i++)
1851 if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
1852 crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
1853 cc->cipher_tfm.tfms[i] = NULL;
1856 kfree(cc->cipher_tfm.tfms);
1857 cc->cipher_tfm.tfms = NULL;
1860 static void crypt_free_tfms(struct crypt_config *cc)
1862 if (crypt_integrity_aead(cc))
1863 crypt_free_tfms_aead(cc);
1865 crypt_free_tfms_skcipher(cc);
1868 static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
1873 cc->cipher_tfm.tfms = kzalloc(cc->tfms_count *
1874 sizeof(struct crypto_skcipher *), GFP_KERNEL);
1875 if (!cc->cipher_tfm.tfms)
1878 for (i = 0; i < cc->tfms_count; i++) {
1879 cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0, 0);
1880 if (IS_ERR(cc->cipher_tfm.tfms[i])) {
1881 err = PTR_ERR(cc->cipher_tfm.tfms[i]);
1882 crypt_free_tfms(cc);
1890 static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
1894 cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
1895 if (!cc->cipher_tfm.tfms)
1898 cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0, 0);
1899 if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
1900 err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
1901 crypt_free_tfms(cc);
1908 static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
1910 if (crypt_integrity_aead(cc))
1911 return crypt_alloc_tfms_aead(cc, ciphermode);
1913 return crypt_alloc_tfms_skcipher(cc, ciphermode);
1916 static unsigned crypt_subkey_size(struct crypt_config *cc)
1918 return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
1921 static unsigned crypt_authenckey_size(struct crypt_config *cc)
1923 return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
1927 * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
1928 * the key must be for some reason in special format.
1929 * This funcion converts cc->key to this special format.
1931 static void crypt_copy_authenckey(char *p, const void *key,
1932 unsigned enckeylen, unsigned authkeylen)
1934 struct crypto_authenc_key_param *param;
1937 rta = (struct rtattr *)p;
1938 param = RTA_DATA(rta);
1939 param->enckeylen = cpu_to_be32(enckeylen);
1940 rta->rta_len = RTA_LENGTH(sizeof(*param));
1941 rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
1942 p += RTA_SPACE(sizeof(*param));
1943 memcpy(p, key + enckeylen, authkeylen);
1945 memcpy(p, key, enckeylen);
1948 static int crypt_setkey(struct crypt_config *cc)
1950 unsigned subkey_size;
1953 /* Ignore extra keys (which are used for IV etc) */
1954 subkey_size = crypt_subkey_size(cc);
1956 if (crypt_integrity_hmac(cc)) {
1957 if (subkey_size < cc->key_mac_size)
1960 crypt_copy_authenckey(cc->authenc_key, cc->key,
1961 subkey_size - cc->key_mac_size,
1965 for (i = 0; i < cc->tfms_count; i++) {
1966 if (crypt_integrity_hmac(cc))
1967 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
1968 cc->authenc_key, crypt_authenckey_size(cc));
1969 else if (crypt_integrity_aead(cc))
1970 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
1971 cc->key + (i * subkey_size),
1974 r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
1975 cc->key + (i * subkey_size),
1981 if (crypt_integrity_hmac(cc))
1982 memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
1989 static bool contains_whitespace(const char *str)
1992 if (isspace(*str++))
1997 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
1999 char *new_key_string, *key_desc;
2002 const struct user_key_payload *ukp;
2005 * Reject key_string with whitespace. dm core currently lacks code for
2006 * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2008 if (contains_whitespace(key_string)) {
2009 DMERR("whitespace chars not allowed in key string");
2013 /* look for next ':' separating key_type from key_description */
2014 key_desc = strpbrk(key_string, ":");
2015 if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2018 if (strncmp(key_string, "logon:", key_desc - key_string + 1) &&
2019 strncmp(key_string, "user:", key_desc - key_string + 1))
2022 new_key_string = kstrdup(key_string, GFP_KERNEL);
2023 if (!new_key_string)
2026 key = request_key(key_string[0] == 'l' ? &key_type_logon : &key_type_user,
2027 key_desc + 1, NULL);
2029 kzfree(new_key_string);
2030 return PTR_ERR(key);
2033 down_read(&key->sem);
2035 ukp = user_key_payload_locked(key);
2039 kzfree(new_key_string);
2040 return -EKEYREVOKED;
2043 if (cc->key_size != ukp->datalen) {
2046 kzfree(new_key_string);
2050 memcpy(cc->key, ukp->data, cc->key_size);
2055 /* clear the flag since following operations may invalidate previously valid key */
2056 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2058 ret = crypt_setkey(cc);
2061 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2062 kzfree(cc->key_string);
2063 cc->key_string = new_key_string;
2065 kzfree(new_key_string);
2070 static int get_key_size(char **key_string)
2075 if (*key_string[0] != ':')
2076 return strlen(*key_string) >> 1;
2078 /* look for next ':' in key string */
2079 colon = strpbrk(*key_string + 1, ":");
2083 if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2086 *key_string = colon;
2088 /* remaining key string should be :<logon|user>:<key_desc> */
2095 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2100 static int get_key_size(char **key_string)
2102 return (*key_string[0] == ':') ? -EINVAL : strlen(*key_string) >> 1;
2107 static int crypt_set_key(struct crypt_config *cc, char *key)
2110 int key_string_len = strlen(key);
2112 /* Hyphen (which gives a key_size of zero) means there is no key. */
2113 if (!cc->key_size && strcmp(key, "-"))
2116 /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2117 if (key[0] == ':') {
2118 r = crypt_set_keyring_key(cc, key + 1);
2122 /* clear the flag since following operations may invalidate previously valid key */
2123 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2125 /* wipe references to any kernel keyring key */
2126 kzfree(cc->key_string);
2127 cc->key_string = NULL;
2129 /* Decode key from its hex representation. */
2130 if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
2133 r = crypt_setkey(cc);
2135 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2138 /* Hex key string not needed after here, so wipe it. */
2139 memset(key, '0', key_string_len);
2144 static int crypt_wipe_key(struct crypt_config *cc)
2148 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2149 get_random_bytes(&cc->key, cc->key_size);
2150 kzfree(cc->key_string);
2151 cc->key_string = NULL;
2152 r = crypt_setkey(cc);
2153 memset(&cc->key, 0, cc->key_size * sizeof(u8));
2158 static void crypt_dtr(struct dm_target *ti)
2160 struct crypt_config *cc = ti->private;
2167 if (cc->write_thread)
2168 kthread_stop(cc->write_thread);
2171 destroy_workqueue(cc->io_queue);
2172 if (cc->crypt_queue)
2173 destroy_workqueue(cc->crypt_queue);
2175 crypt_free_tfms(cc);
2178 bioset_free(cc->bs);
2180 mempool_destroy(cc->page_pool);
2181 mempool_destroy(cc->req_pool);
2182 mempool_destroy(cc->tag_pool);
2184 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
2185 cc->iv_gen_ops->dtr(cc);
2188 dm_put_device(ti, cc->dev);
2191 kzfree(cc->cipher_string);
2192 kzfree(cc->key_string);
2193 kzfree(cc->cipher_auth);
2194 kzfree(cc->authenc_key);
2196 mutex_destroy(&cc->bio_alloc_lock);
2198 /* Must zero key material before freeing */
2202 static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
2204 struct crypt_config *cc = ti->private;
2206 if (crypt_integrity_aead(cc))
2207 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2209 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2212 /* at least a 64 bit sector number should fit in our buffer */
2213 cc->iv_size = max(cc->iv_size,
2214 (unsigned int)(sizeof(u64) / sizeof(u8)));
2216 DMWARN("Selected cipher does not support IVs");
2220 /* Choose ivmode, see comments at iv code. */
2222 cc->iv_gen_ops = NULL;
2223 else if (strcmp(ivmode, "plain") == 0)
2224 cc->iv_gen_ops = &crypt_iv_plain_ops;
2225 else if (strcmp(ivmode, "plain64") == 0)
2226 cc->iv_gen_ops = &crypt_iv_plain64_ops;
2227 else if (strcmp(ivmode, "plain64be") == 0)
2228 cc->iv_gen_ops = &crypt_iv_plain64be_ops;
2229 else if (strcmp(ivmode, "essiv") == 0)
2230 cc->iv_gen_ops = &crypt_iv_essiv_ops;
2231 else if (strcmp(ivmode, "benbi") == 0)
2232 cc->iv_gen_ops = &crypt_iv_benbi_ops;
2233 else if (strcmp(ivmode, "null") == 0)
2234 cc->iv_gen_ops = &crypt_iv_null_ops;
2235 else if (strcmp(ivmode, "lmk") == 0) {
2236 cc->iv_gen_ops = &crypt_iv_lmk_ops;
2238 * Version 2 and 3 is recognised according
2239 * to length of provided multi-key string.
2240 * If present (version 3), last key is used as IV seed.
2241 * All keys (including IV seed) are always the same size.
2243 if (cc->key_size % cc->key_parts) {
2245 cc->key_extra_size = cc->key_size / cc->key_parts;
2247 } else if (strcmp(ivmode, "tcw") == 0) {
2248 cc->iv_gen_ops = &crypt_iv_tcw_ops;
2249 cc->key_parts += 2; /* IV + whitening */
2250 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2251 } else if (strcmp(ivmode, "random") == 0) {
2252 cc->iv_gen_ops = &crypt_iv_random_ops;
2253 /* Need storage space in integrity fields. */
2254 cc->integrity_iv_size = cc->iv_size;
2256 ti->error = "Invalid IV mode";
2264 * Workaround to parse cipher algorithm from crypto API spec.
2265 * The cc->cipher is currently used only in ESSIV.
2266 * This should be probably done by crypto-api calls (once available...)
2268 static int crypt_ctr_blkdev_cipher(struct crypt_config *cc)
2270 const char *alg_name = NULL;
2273 if (crypt_integrity_aead(cc)) {
2274 alg_name = crypto_tfm_alg_name(crypto_aead_tfm(any_tfm_aead(cc)));
2277 if (crypt_integrity_hmac(cc)) {
2278 alg_name = strchr(alg_name, ',');
2284 alg_name = crypto_tfm_alg_name(crypto_skcipher_tfm(any_tfm(cc)));
2289 start = strchr(alg_name, '(');
2290 end = strchr(alg_name, ')');
2292 if (!start && !end) {
2293 cc->cipher = kstrdup(alg_name, GFP_KERNEL);
2294 return cc->cipher ? 0 : -ENOMEM;
2297 if (!start || !end || ++start >= end)
2300 cc->cipher = kzalloc(end - start + 1, GFP_KERNEL);
2304 strncpy(cc->cipher, start, end - start);
2310 * Workaround to parse HMAC algorithm from AEAD crypto API spec.
2311 * The HMAC is needed to calculate tag size (HMAC digest size).
2312 * This should be probably done by crypto-api calls (once available...)
2314 static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
2316 char *start, *end, *mac_alg = NULL;
2317 struct crypto_ahash *mac;
2319 if (!strstarts(cipher_api, "authenc("))
2322 start = strchr(cipher_api, '(');
2323 end = strchr(cipher_api, ',');
2324 if (!start || !end || ++start > end)
2327 mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
2330 strncpy(mac_alg, start, end - start);
2332 mac = crypto_alloc_ahash(mac_alg, 0, 0);
2336 return PTR_ERR(mac);
2338 cc->key_mac_size = crypto_ahash_digestsize(mac);
2339 crypto_free_ahash(mac);
2341 cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
2342 if (!cc->authenc_key)
2348 static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
2349 char **ivmode, char **ivopts)
2351 struct crypt_config *cc = ti->private;
2352 char *tmp, *cipher_api;
2358 * New format (capi: prefix)
2359 * capi:cipher_api_spec-iv:ivopts
2361 tmp = &cipher_in[strlen("capi:")];
2362 cipher_api = strsep(&tmp, "-");
2363 *ivmode = strsep(&tmp, ":");
2366 if (*ivmode && !strcmp(*ivmode, "lmk"))
2367 cc->tfms_count = 64;
2369 cc->key_parts = cc->tfms_count;
2371 /* Allocate cipher */
2372 ret = crypt_alloc_tfms(cc, cipher_api);
2374 ti->error = "Error allocating crypto tfm";
2378 /* Alloc AEAD, can be used only in new format. */
2379 if (crypt_integrity_aead(cc)) {
2380 ret = crypt_ctr_auth_cipher(cc, cipher_api);
2382 ti->error = "Invalid AEAD cipher spec";
2385 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2387 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2389 ret = crypt_ctr_blkdev_cipher(cc);
2391 ti->error = "Cannot allocate cipher string";
2398 static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
2399 char **ivmode, char **ivopts)
2401 struct crypt_config *cc = ti->private;
2402 char *tmp, *cipher, *chainmode, *keycount;
2403 char *cipher_api = NULL;
2407 if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
2408 ti->error = "Bad cipher specification";
2413 * Legacy dm-crypt cipher specification
2414 * cipher[:keycount]-mode-iv:ivopts
2417 keycount = strsep(&tmp, "-");
2418 cipher = strsep(&keycount, ":");
2422 else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
2423 !is_power_of_2(cc->tfms_count)) {
2424 ti->error = "Bad cipher key count specification";
2427 cc->key_parts = cc->tfms_count;
2429 cc->cipher = kstrdup(cipher, GFP_KERNEL);
2433 chainmode = strsep(&tmp, "-");
2434 *ivopts = strsep(&tmp, "-");
2435 *ivmode = strsep(&*ivopts, ":");
2438 DMWARN("Ignoring unexpected additional cipher options");
2441 * For compatibility with the original dm-crypt mapping format, if
2442 * only the cipher name is supplied, use cbc-plain.
2444 if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
2449 if (strcmp(chainmode, "ecb") && !*ivmode) {
2450 ti->error = "IV mechanism required";
2454 cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
2458 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2459 "%s(%s)", chainmode, cipher);
2465 /* Allocate cipher */
2466 ret = crypt_alloc_tfms(cc, cipher_api);
2468 ti->error = "Error allocating crypto tfm";
2476 ti->error = "Cannot allocate cipher strings";
2480 static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
2482 struct crypt_config *cc = ti->private;
2483 char *ivmode = NULL, *ivopts = NULL;
2486 cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
2487 if (!cc->cipher_string) {
2488 ti->error = "Cannot allocate cipher strings";
2492 if (strstarts(cipher_in, "capi:"))
2493 ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
2495 ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
2500 ret = crypt_ctr_ivmode(ti, ivmode);
2504 /* Initialize and set key */
2505 ret = crypt_set_key(cc, key);
2507 ti->error = "Error decoding and setting key";
2512 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
2513 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
2515 ti->error = "Error creating IV";
2520 /* Initialize IV (set keys for ESSIV etc) */
2521 if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
2522 ret = cc->iv_gen_ops->init(cc);
2524 ti->error = "Error initialising IV";
2529 /* wipe the kernel key payload copy */
2531 memset(cc->key, 0, cc->key_size * sizeof(u8));
2536 static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
2538 struct crypt_config *cc = ti->private;
2539 struct dm_arg_set as;
2540 static const struct dm_arg _args[] = {
2541 {0, 6, "Invalid number of feature args"},
2543 unsigned int opt_params, val;
2544 const char *opt_string, *sval;
2548 /* Optional parameters */
2552 ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
2556 while (opt_params--) {
2557 opt_string = dm_shift_arg(&as);
2559 ti->error = "Not enough feature arguments";
2563 if (!strcasecmp(opt_string, "allow_discards"))
2564 ti->num_discard_bios = 1;
2566 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
2567 set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
2569 else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
2570 set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
2571 else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
2572 if (val == 0 || val > MAX_TAG_SIZE) {
2573 ti->error = "Invalid integrity arguments";
2576 cc->on_disk_tag_size = val;
2577 sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
2578 if (!strcasecmp(sval, "aead")) {
2579 set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
2580 } else if (strcasecmp(sval, "none")) {
2581 ti->error = "Unknown integrity profile";
2585 cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
2586 if (!cc->cipher_auth)
2588 } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
2589 if (cc->sector_size < (1 << SECTOR_SHIFT) ||
2590 cc->sector_size > 4096 ||
2591 (cc->sector_size & (cc->sector_size - 1))) {
2592 ti->error = "Invalid feature value for sector_size";
2595 if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
2596 ti->error = "Device size is not multiple of sector_size feature";
2599 cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
2600 } else if (!strcasecmp(opt_string, "iv_large_sectors"))
2601 set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
2603 ti->error = "Invalid feature arguments";
2612 * Construct an encryption mapping:
2613 * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
2615 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
2617 struct crypt_config *cc;
2619 unsigned int align_mask;
2620 unsigned long long tmpll;
2622 size_t iv_size_padding, additional_req_size;
2626 ti->error = "Not enough arguments";
2630 key_size = get_key_size(&argv[1]);
2632 ti->error = "Cannot parse key size";
2636 cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
2638 ti->error = "Cannot allocate encryption context";
2641 cc->key_size = key_size;
2642 cc->sector_size = (1 << SECTOR_SHIFT);
2643 cc->sector_shift = 0;
2647 /* Optional parameters need to be read before cipher constructor */
2649 ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
2654 ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
2658 if (crypt_integrity_aead(cc)) {
2659 cc->dmreq_start = sizeof(struct aead_request);
2660 cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
2661 align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
2663 cc->dmreq_start = sizeof(struct skcipher_request);
2664 cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
2665 align_mask = crypto_skcipher_alignmask(any_tfm(cc));
2667 cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
2669 if (align_mask < CRYPTO_MINALIGN) {
2670 /* Allocate the padding exactly */
2671 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
2675 * If the cipher requires greater alignment than kmalloc
2676 * alignment, we don't know the exact position of the
2677 * initialization vector. We must assume worst case.
2679 iv_size_padding = align_mask;
2684 /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
2685 additional_req_size = sizeof(struct dm_crypt_request) +
2686 iv_size_padding + cc->iv_size +
2689 sizeof(unsigned int);
2691 cc->req_pool = mempool_create_kmalloc_pool(MIN_IOS, cc->dmreq_start + additional_req_size);
2692 if (!cc->req_pool) {
2693 ti->error = "Cannot allocate crypt request mempool";
2697 cc->per_bio_data_size = ti->per_io_data_size =
2698 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
2699 ARCH_KMALLOC_MINALIGN);
2701 cc->page_pool = mempool_create_page_pool(BIO_MAX_PAGES, 0);
2702 if (!cc->page_pool) {
2703 ti->error = "Cannot allocate page mempool";
2707 cc->bs = bioset_create(MIN_IOS, 0, BIOSET_NEED_BVECS);
2709 ti->error = "Cannot allocate crypt bioset";
2713 mutex_init(&cc->bio_alloc_lock);
2716 if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
2717 (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
2718 ti->error = "Invalid iv_offset sector";
2721 cc->iv_offset = tmpll;
2723 ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
2725 ti->error = "Device lookup failed";
2730 if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1) {
2731 ti->error = "Invalid device sector";
2736 if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
2737 ret = crypt_integrity_ctr(cc, ti);
2741 cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
2742 if (!cc->tag_pool_max_sectors)
2743 cc->tag_pool_max_sectors = 1;
2745 cc->tag_pool = mempool_create_kmalloc_pool(MIN_IOS,
2746 cc->tag_pool_max_sectors * cc->on_disk_tag_size);
2747 if (!cc->tag_pool) {
2748 ti->error = "Cannot allocate integrity tags mempool";
2753 cc->tag_pool_max_sectors <<= cc->sector_shift;
2757 cc->io_queue = alloc_workqueue("kcryptd_io", WQ_HIGHPRI | WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM, 1);
2758 if (!cc->io_queue) {
2759 ti->error = "Couldn't create kcryptd io queue";
2763 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
2764 cc->crypt_queue = alloc_workqueue("kcryptd", WQ_HIGHPRI | WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM, 1);
2766 cc->crypt_queue = alloc_workqueue("kcryptd",
2767 WQ_HIGHPRI | WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
2769 if (!cc->crypt_queue) {
2770 ti->error = "Couldn't create kcryptd queue";
2774 init_waitqueue_head(&cc->write_thread_wait);
2775 cc->write_tree = RB_ROOT;
2777 cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write");
2778 if (IS_ERR(cc->write_thread)) {
2779 ret = PTR_ERR(cc->write_thread);
2780 cc->write_thread = NULL;
2781 ti->error = "Couldn't spawn write thread";
2784 wake_up_process(cc->write_thread);
2786 ti->num_flush_bios = 1;
2795 static int crypt_map(struct dm_target *ti, struct bio *bio)
2797 struct dm_crypt_io *io;
2798 struct crypt_config *cc = ti->private;
2801 * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
2802 * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
2803 * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
2805 if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
2806 bio_op(bio) == REQ_OP_DISCARD)) {
2807 bio_set_dev(bio, cc->dev->bdev);
2808 if (bio_sectors(bio))
2809 bio->bi_iter.bi_sector = cc->start +
2810 dm_target_offset(ti, bio->bi_iter.bi_sector);
2811 return DM_MAPIO_REMAPPED;
2815 * Check if bio is too large, split as needed.
2817 if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_PAGES << PAGE_SHIFT)) &&
2818 (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
2819 dm_accept_partial_bio(bio, ((BIO_MAX_PAGES << PAGE_SHIFT) >> SECTOR_SHIFT));
2822 * Ensure that bio is a multiple of internal sector encryption size
2823 * and is aligned to this size as defined in IO hints.
2825 if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
2826 return DM_MAPIO_KILL;
2828 if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
2829 return DM_MAPIO_KILL;
2831 io = dm_per_bio_data(bio, cc->per_bio_data_size);
2832 crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
2834 if (cc->on_disk_tag_size) {
2835 unsigned tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
2837 if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
2838 unlikely(!(io->integrity_metadata = kmalloc(tag_len,
2839 GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
2840 if (bio_sectors(bio) > cc->tag_pool_max_sectors)
2841 dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
2842 io->integrity_metadata = mempool_alloc(cc->tag_pool, GFP_NOIO);
2843 io->integrity_metadata_from_pool = true;
2847 if (crypt_integrity_aead(cc))
2848 io->ctx.r.req_aead = (struct aead_request *)(io + 1);
2850 io->ctx.r.req = (struct skcipher_request *)(io + 1);
2852 if (bio_data_dir(io->base_bio) == READ) {
2853 if (kcryptd_io_read(io, GFP_NOWAIT))
2854 kcryptd_queue_read(io);
2856 kcryptd_queue_crypt(io);
2858 return DM_MAPIO_SUBMITTED;
2861 static void crypt_status(struct dm_target *ti, status_type_t type,
2862 unsigned status_flags, char *result, unsigned maxlen)
2864 struct crypt_config *cc = ti->private;
2866 int num_feature_args = 0;
2869 case STATUSTYPE_INFO:
2873 case STATUSTYPE_TABLE:
2874 DMEMIT("%s ", cc->cipher_string);
2876 if (cc->key_size > 0) {
2878 DMEMIT(":%u:%s", cc->key_size, cc->key_string);
2880 for (i = 0; i < cc->key_size; i++)
2881 DMEMIT("%02x", cc->key[i]);
2885 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
2886 cc->dev->name, (unsigned long long)cc->start);
2888 num_feature_args += !!ti->num_discard_bios;
2889 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
2890 num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
2891 num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
2892 num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
2893 if (cc->on_disk_tag_size)
2895 if (num_feature_args) {
2896 DMEMIT(" %d", num_feature_args);
2897 if (ti->num_discard_bios)
2898 DMEMIT(" allow_discards");
2899 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
2900 DMEMIT(" same_cpu_crypt");
2901 if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
2902 DMEMIT(" submit_from_crypt_cpus");
2903 if (cc->on_disk_tag_size)
2904 DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
2905 if (cc->sector_size != (1 << SECTOR_SHIFT))
2906 DMEMIT(" sector_size:%d", cc->sector_size);
2907 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
2908 DMEMIT(" iv_large_sectors");
2915 static void crypt_postsuspend(struct dm_target *ti)
2917 struct crypt_config *cc = ti->private;
2919 set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
2922 static int crypt_preresume(struct dm_target *ti)
2924 struct crypt_config *cc = ti->private;
2926 if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
2927 DMERR("aborting resume - crypt key is not set.");
2934 static void crypt_resume(struct dm_target *ti)
2936 struct crypt_config *cc = ti->private;
2938 clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
2941 /* Message interface
2945 static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
2947 struct crypt_config *cc = ti->private;
2948 int key_size, ret = -EINVAL;
2953 if (!strcasecmp(argv[0], "key")) {
2954 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
2955 DMWARN("not suspended during key manipulation.");
2958 if (argc == 3 && !strcasecmp(argv[1], "set")) {
2959 /* The key size may not be changed. */
2960 key_size = get_key_size(&argv[2]);
2961 if (key_size < 0 || cc->key_size != key_size) {
2962 memset(argv[2], '0', strlen(argv[2]));
2966 ret = crypt_set_key(cc, argv[2]);
2969 if (cc->iv_gen_ops && cc->iv_gen_ops->init)
2970 ret = cc->iv_gen_ops->init(cc);
2971 /* wipe the kernel key payload copy */
2973 memset(cc->key, 0, cc->key_size * sizeof(u8));
2976 if (argc == 2 && !strcasecmp(argv[1], "wipe")) {
2977 if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
2978 ret = cc->iv_gen_ops->wipe(cc);
2982 return crypt_wipe_key(cc);
2987 DMWARN("unrecognised message received.");
2991 static int crypt_iterate_devices(struct dm_target *ti,
2992 iterate_devices_callout_fn fn, void *data)
2994 struct crypt_config *cc = ti->private;
2996 return fn(ti, cc->dev, cc->start, ti->len, data);
2999 static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
3001 struct crypt_config *cc = ti->private;
3004 * Unfortunate constraint that is required to avoid the potential
3005 * for exceeding underlying device's max_segments limits -- due to
3006 * crypt_alloc_buffer() possibly allocating pages for the encryption
3007 * bio that are not as physically contiguous as the original bio.
3009 limits->max_segment_size = PAGE_SIZE;
3011 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
3012 limits->logical_block_size = cc->sector_size;
3013 limits->physical_block_size = cc->sector_size;
3014 blk_limits_io_min(limits, cc->sector_size);
3018 static struct target_type crypt_target = {
3020 .version = {1, 18, 1},
3021 .module = THIS_MODULE,
3025 .status = crypt_status,
3026 .postsuspend = crypt_postsuspend,
3027 .preresume = crypt_preresume,
3028 .resume = crypt_resume,
3029 .message = crypt_message,
3030 .iterate_devices = crypt_iterate_devices,
3031 .io_hints = crypt_io_hints,
3034 static int __init dm_crypt_init(void)
3038 r = dm_register_target(&crypt_target);
3040 DMERR("register failed %d", r);
3045 static void __exit dm_crypt_exit(void)
3047 dm_unregister_target(&crypt_target);
3050 module_init(dm_crypt_init);
3051 module_exit(dm_crypt_exit);
3053 MODULE_AUTHOR("Jana Saout <jana@saout.de>");
3054 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
3055 MODULE_LICENSE("GPL");