2 * Copyright (C) 2003 Jana Saout <jana@saout.de>
3 * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
4 * Copyright (C) 2006-2020 Red Hat, Inc. All rights reserved.
5 * Copyright (C) 2013-2020 Milan Broz <gmazyland@gmail.com>
7 * This file is released under the GPL.
10 #include <linux/completion.h>
11 #include <linux/err.h>
12 #include <linux/module.h>
13 #include <linux/init.h>
14 #include <linux/kernel.h>
15 #include <linux/key.h>
16 #include <linux/bio.h>
17 #include <linux/blkdev.h>
18 #include <linux/mempool.h>
19 #include <linux/slab.h>
20 #include <linux/crypto.h>
21 #include <linux/workqueue.h>
22 #include <linux/kthread.h>
23 #include <linux/backing-dev.h>
24 #include <linux/atomic.h>
25 #include <linux/scatterlist.h>
26 #include <linux/rbtree.h>
27 #include <linux/ctype.h>
29 #include <asm/unaligned.h>
30 #include <crypto/hash.h>
31 #include <crypto/md5.h>
32 #include <crypto/algapi.h>
33 #include <crypto/skcipher.h>
34 #include <crypto/aead.h>
35 #include <crypto/authenc.h>
36 #include <linux/rtnetlink.h> /* for struct rtattr and RTA macros only */
37 #include <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_benbi_private
{
105 #define LMK_SEED_SIZE 64 /* hash + 0 */
106 struct iv_lmk_private
{
107 struct crypto_shash
*hash_tfm
;
111 #define TCW_WHITENING_SIZE 16
112 struct iv_tcw_private
{
113 struct crypto_shash
*crc32_tfm
;
118 #define ELEPHANT_MAX_KEY_SIZE 32
119 struct iv_elephant_private
{
120 struct crypto_skcipher
*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 */
133 CRYPT_ENCRYPT_PREPROCESS
, /* Must preprocess data for encryption (elephant) */
137 * The fields in here must be read only after initialization.
139 struct crypt_config
{
143 struct percpu_counter n_allocated_pages
;
145 struct workqueue_struct
*io_queue
;
146 struct workqueue_struct
*crypt_queue
;
148 spinlock_t write_thread_lock
;
149 struct task_struct
*write_thread
;
150 struct rb_root write_tree
;
156 const struct crypt_iv_operations
*iv_gen_ops
;
158 struct iv_benbi_private benbi
;
159 struct iv_lmk_private lmk
;
160 struct iv_tcw_private tcw
;
161 struct iv_elephant_private elephant
;
164 unsigned int iv_size
;
165 unsigned short int sector_size
;
166 unsigned char sector_shift
;
169 struct crypto_skcipher
**tfms
;
170 struct crypto_aead
**tfms_aead
;
173 unsigned long cipher_flags
;
176 * Layout of each crypto request:
178 * struct skcipher_request
181 * struct dm_crypt_request
185 * The padding is added so that dm_crypt_request and the IV are
188 unsigned int dmreq_start
;
190 unsigned int per_bio_data_size
;
193 unsigned int key_size
;
194 unsigned int key_parts
; /* independent parts in key buffer */
195 unsigned int key_extra_size
; /* additional keys length */
196 unsigned int key_mac_size
; /* MAC key size for authenc(...) */
198 unsigned int integrity_tag_size
;
199 unsigned int integrity_iv_size
;
200 unsigned int on_disk_tag_size
;
203 * pool for per bio private data, crypto requests,
204 * encryption requeusts/buffer pages and integrity tags
206 unsigned tag_pool_max_sectors
;
212 struct mutex bio_alloc_lock
;
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 DEFINE_SPINLOCK(dm_crypt_clients_lock
);
223 static unsigned dm_crypt_clients_n
= 0;
224 static volatile unsigned long dm_crypt_pages_per_client
;
225 #define DM_CRYPT_MEMORY_PERCENT 2
226 #define DM_CRYPT_MIN_PAGES_PER_CLIENT (BIO_MAX_PAGES * 16)
228 static void clone_init(struct dm_crypt_io
*, struct bio
*);
229 static void kcryptd_queue_crypt(struct dm_crypt_io
*io
);
230 static struct scatterlist
*crypt_get_sg_data(struct crypt_config
*cc
,
231 struct scatterlist
*sg
);
233 static bool crypt_integrity_aead(struct crypt_config
*cc
);
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 * eboiv: Encrypted byte-offset IV (used in Bitlocker in CBC mode)
295 * The IV is encrypted little-endian byte-offset (with the same key
296 * and cipher as the volume).
298 * elephant: The extended version of eboiv with additional Elephant diffuser
299 * used with Bitlocker CBC mode.
300 * This mode was used in older Windows systems
301 * http://download.microsoft.com/download/0/2/3/0238acaf-d3bf-4a6d-b3d6-0a0be4bbb36e/bitlockercipher200608.pdf
304 static int crypt_iv_plain_gen(struct crypt_config
*cc
, u8
*iv
,
305 struct dm_crypt_request
*dmreq
)
307 memset(iv
, 0, cc
->iv_size
);
308 *(__le32
*)iv
= cpu_to_le32(dmreq
->iv_sector
& 0xffffffff);
313 static int crypt_iv_plain64_gen(struct crypt_config
*cc
, u8
*iv
,
314 struct dm_crypt_request
*dmreq
)
316 memset(iv
, 0, cc
->iv_size
);
317 *(__le64
*)iv
= cpu_to_le64(dmreq
->iv_sector
);
322 static int crypt_iv_plain64be_gen(struct crypt_config
*cc
, u8
*iv
,
323 struct dm_crypt_request
*dmreq
)
325 memset(iv
, 0, cc
->iv_size
);
326 /* iv_size is at least of size u64; usually it is 16 bytes */
327 *(__be64
*)&iv
[cc
->iv_size
- sizeof(u64
)] = cpu_to_be64(dmreq
->iv_sector
);
332 static int crypt_iv_essiv_gen(struct crypt_config
*cc
, u8
*iv
,
333 struct dm_crypt_request
*dmreq
)
336 * ESSIV encryption of the IV is now handled by the crypto API,
337 * so just pass the plain sector number here.
339 memset(iv
, 0, cc
->iv_size
);
340 *(__le64
*)iv
= cpu_to_le64(dmreq
->iv_sector
);
345 static int crypt_iv_benbi_ctr(struct crypt_config
*cc
, struct dm_target
*ti
,
351 if (crypt_integrity_aead(cc
))
352 bs
= crypto_aead_blocksize(any_tfm_aead(cc
));
354 bs
= crypto_skcipher_blocksize(any_tfm(cc
));
357 /* we need to calculate how far we must shift the sector count
358 * to get the cipher block count, we use this shift in _gen */
360 if (1 << log
!= bs
) {
361 ti
->error
= "cypher blocksize is not a power of 2";
366 ti
->error
= "cypher blocksize is > 512";
370 cc
->iv_gen_private
.benbi
.shift
= 9 - log
;
375 static void crypt_iv_benbi_dtr(struct crypt_config
*cc
)
379 static int crypt_iv_benbi_gen(struct crypt_config
*cc
, u8
*iv
,
380 struct dm_crypt_request
*dmreq
)
384 memset(iv
, 0, cc
->iv_size
- sizeof(u64
)); /* rest is cleared below */
386 val
= cpu_to_be64(((u64
)dmreq
->iv_sector
<< cc
->iv_gen_private
.benbi
.shift
) + 1);
387 put_unaligned(val
, (__be64
*)(iv
+ cc
->iv_size
- sizeof(u64
)));
392 static int crypt_iv_null_gen(struct crypt_config
*cc
, u8
*iv
,
393 struct dm_crypt_request
*dmreq
)
395 memset(iv
, 0, cc
->iv_size
);
400 static void crypt_iv_lmk_dtr(struct crypt_config
*cc
)
402 struct iv_lmk_private
*lmk
= &cc
->iv_gen_private
.lmk
;
404 if (lmk
->hash_tfm
&& !IS_ERR(lmk
->hash_tfm
))
405 crypto_free_shash(lmk
->hash_tfm
);
406 lmk
->hash_tfm
= NULL
;
412 static int crypt_iv_lmk_ctr(struct crypt_config
*cc
, struct dm_target
*ti
,
415 struct iv_lmk_private
*lmk
= &cc
->iv_gen_private
.lmk
;
417 if (cc
->sector_size
!= (1 << SECTOR_SHIFT
)) {
418 ti
->error
= "Unsupported sector size for LMK";
422 lmk
->hash_tfm
= crypto_alloc_shash("md5", 0, 0);
423 if (IS_ERR(lmk
->hash_tfm
)) {
424 ti
->error
= "Error initializing LMK hash";
425 return PTR_ERR(lmk
->hash_tfm
);
428 /* No seed in LMK version 2 */
429 if (cc
->key_parts
== cc
->tfms_count
) {
434 lmk
->seed
= kzalloc(LMK_SEED_SIZE
, GFP_KERNEL
);
436 crypt_iv_lmk_dtr(cc
);
437 ti
->error
= "Error kmallocing seed storage in LMK";
444 static int crypt_iv_lmk_init(struct crypt_config
*cc
)
446 struct iv_lmk_private
*lmk
= &cc
->iv_gen_private
.lmk
;
447 int subkey_size
= cc
->key_size
/ cc
->key_parts
;
449 /* LMK seed is on the position of LMK_KEYS + 1 key */
451 memcpy(lmk
->seed
, cc
->key
+ (cc
->tfms_count
* subkey_size
),
452 crypto_shash_digestsize(lmk
->hash_tfm
));
457 static int crypt_iv_lmk_wipe(struct crypt_config
*cc
)
459 struct iv_lmk_private
*lmk
= &cc
->iv_gen_private
.lmk
;
462 memset(lmk
->seed
, 0, LMK_SEED_SIZE
);
467 static int crypt_iv_lmk_one(struct crypt_config
*cc
, u8
*iv
,
468 struct dm_crypt_request
*dmreq
,
471 struct iv_lmk_private
*lmk
= &cc
->iv_gen_private
.lmk
;
472 SHASH_DESC_ON_STACK(desc
, lmk
->hash_tfm
);
473 struct md5_state md5state
;
477 desc
->tfm
= lmk
->hash_tfm
;
479 r
= crypto_shash_init(desc
);
484 r
= crypto_shash_update(desc
, lmk
->seed
, LMK_SEED_SIZE
);
489 /* Sector is always 512B, block size 16, add data of blocks 1-31 */
490 r
= crypto_shash_update(desc
, data
+ 16, 16 * 31);
494 /* Sector is cropped to 56 bits here */
495 buf
[0] = cpu_to_le32(dmreq
->iv_sector
& 0xFFFFFFFF);
496 buf
[1] = cpu_to_le32((((u64
)dmreq
->iv_sector
>> 32) & 0x00FFFFFF) | 0x80000000);
497 buf
[2] = cpu_to_le32(4024);
499 r
= crypto_shash_update(desc
, (u8
*)buf
, sizeof(buf
));
503 /* No MD5 padding here */
504 r
= crypto_shash_export(desc
, &md5state
);
508 for (i
= 0; i
< MD5_HASH_WORDS
; i
++)
509 __cpu_to_le32s(&md5state
.hash
[i
]);
510 memcpy(iv
, &md5state
.hash
, cc
->iv_size
);
515 static int crypt_iv_lmk_gen(struct crypt_config
*cc
, u8
*iv
,
516 struct dm_crypt_request
*dmreq
)
518 struct scatterlist
*sg
;
522 if (bio_data_dir(dmreq
->ctx
->bio_in
) == WRITE
) {
523 sg
= crypt_get_sg_data(cc
, dmreq
->sg_in
);
524 src
= kmap_atomic(sg_page(sg
));
525 r
= crypt_iv_lmk_one(cc
, iv
, dmreq
, src
+ sg
->offset
);
528 memset(iv
, 0, cc
->iv_size
);
533 static int crypt_iv_lmk_post(struct crypt_config
*cc
, u8
*iv
,
534 struct dm_crypt_request
*dmreq
)
536 struct scatterlist
*sg
;
540 if (bio_data_dir(dmreq
->ctx
->bio_in
) == WRITE
)
543 sg
= crypt_get_sg_data(cc
, dmreq
->sg_out
);
544 dst
= kmap_atomic(sg_page(sg
));
545 r
= crypt_iv_lmk_one(cc
, iv
, dmreq
, dst
+ sg
->offset
);
547 /* Tweak the first block of plaintext sector */
549 crypto_xor(dst
+ sg
->offset
, iv
, cc
->iv_size
);
555 static void crypt_iv_tcw_dtr(struct crypt_config
*cc
)
557 struct iv_tcw_private
*tcw
= &cc
->iv_gen_private
.tcw
;
559 kzfree(tcw
->iv_seed
);
561 kzfree(tcw
->whitening
);
562 tcw
->whitening
= NULL
;
564 if (tcw
->crc32_tfm
&& !IS_ERR(tcw
->crc32_tfm
))
565 crypto_free_shash(tcw
->crc32_tfm
);
566 tcw
->crc32_tfm
= NULL
;
569 static int crypt_iv_tcw_ctr(struct crypt_config
*cc
, struct dm_target
*ti
,
572 struct iv_tcw_private
*tcw
= &cc
->iv_gen_private
.tcw
;
574 if (cc
->sector_size
!= (1 << SECTOR_SHIFT
)) {
575 ti
->error
= "Unsupported sector size for TCW";
579 if (cc
->key_size
<= (cc
->iv_size
+ TCW_WHITENING_SIZE
)) {
580 ti
->error
= "Wrong key size for TCW";
584 tcw
->crc32_tfm
= crypto_alloc_shash("crc32", 0, 0);
585 if (IS_ERR(tcw
->crc32_tfm
)) {
586 ti
->error
= "Error initializing CRC32 in TCW";
587 return PTR_ERR(tcw
->crc32_tfm
);
590 tcw
->iv_seed
= kzalloc(cc
->iv_size
, GFP_KERNEL
);
591 tcw
->whitening
= kzalloc(TCW_WHITENING_SIZE
, GFP_KERNEL
);
592 if (!tcw
->iv_seed
|| !tcw
->whitening
) {
593 crypt_iv_tcw_dtr(cc
);
594 ti
->error
= "Error allocating seed storage in TCW";
601 static int crypt_iv_tcw_init(struct crypt_config
*cc
)
603 struct iv_tcw_private
*tcw
= &cc
->iv_gen_private
.tcw
;
604 int key_offset
= cc
->key_size
- cc
->iv_size
- TCW_WHITENING_SIZE
;
606 memcpy(tcw
->iv_seed
, &cc
->key
[key_offset
], cc
->iv_size
);
607 memcpy(tcw
->whitening
, &cc
->key
[key_offset
+ cc
->iv_size
],
613 static int crypt_iv_tcw_wipe(struct crypt_config
*cc
)
615 struct iv_tcw_private
*tcw
= &cc
->iv_gen_private
.tcw
;
617 memset(tcw
->iv_seed
, 0, cc
->iv_size
);
618 memset(tcw
->whitening
, 0, TCW_WHITENING_SIZE
);
623 static int crypt_iv_tcw_whitening(struct crypt_config
*cc
,
624 struct dm_crypt_request
*dmreq
,
627 struct iv_tcw_private
*tcw
= &cc
->iv_gen_private
.tcw
;
628 __le64 sector
= cpu_to_le64(dmreq
->iv_sector
);
629 u8 buf
[TCW_WHITENING_SIZE
];
630 SHASH_DESC_ON_STACK(desc
, tcw
->crc32_tfm
);
633 /* xor whitening with sector number */
634 crypto_xor_cpy(buf
, tcw
->whitening
, (u8
*)§or
, 8);
635 crypto_xor_cpy(&buf
[8], tcw
->whitening
+ 8, (u8
*)§or
, 8);
637 /* calculate crc32 for every 32bit part and xor it */
638 desc
->tfm
= tcw
->crc32_tfm
;
639 for (i
= 0; i
< 4; i
++) {
640 r
= crypto_shash_init(desc
);
643 r
= crypto_shash_update(desc
, &buf
[i
* 4], 4);
646 r
= crypto_shash_final(desc
, &buf
[i
* 4]);
650 crypto_xor(&buf
[0], &buf
[12], 4);
651 crypto_xor(&buf
[4], &buf
[8], 4);
653 /* apply whitening (8 bytes) to whole sector */
654 for (i
= 0; i
< ((1 << SECTOR_SHIFT
) / 8); i
++)
655 crypto_xor(data
+ i
* 8, buf
, 8);
657 memzero_explicit(buf
, sizeof(buf
));
661 static int crypt_iv_tcw_gen(struct crypt_config
*cc
, u8
*iv
,
662 struct dm_crypt_request
*dmreq
)
664 struct scatterlist
*sg
;
665 struct iv_tcw_private
*tcw
= &cc
->iv_gen_private
.tcw
;
666 __le64 sector
= cpu_to_le64(dmreq
->iv_sector
);
670 /* Remove whitening from ciphertext */
671 if (bio_data_dir(dmreq
->ctx
->bio_in
) != WRITE
) {
672 sg
= crypt_get_sg_data(cc
, dmreq
->sg_in
);
673 src
= kmap_atomic(sg_page(sg
));
674 r
= crypt_iv_tcw_whitening(cc
, dmreq
, src
+ sg
->offset
);
679 crypto_xor_cpy(iv
, tcw
->iv_seed
, (u8
*)§or
, 8);
681 crypto_xor_cpy(&iv
[8], tcw
->iv_seed
+ 8, (u8
*)§or
,
687 static int crypt_iv_tcw_post(struct crypt_config
*cc
, u8
*iv
,
688 struct dm_crypt_request
*dmreq
)
690 struct scatterlist
*sg
;
694 if (bio_data_dir(dmreq
->ctx
->bio_in
) != WRITE
)
697 /* Apply whitening on ciphertext */
698 sg
= crypt_get_sg_data(cc
, dmreq
->sg_out
);
699 dst
= kmap_atomic(sg_page(sg
));
700 r
= crypt_iv_tcw_whitening(cc
, dmreq
, dst
+ sg
->offset
);
706 static int crypt_iv_random_gen(struct crypt_config
*cc
, u8
*iv
,
707 struct dm_crypt_request
*dmreq
)
709 /* Used only for writes, there must be an additional space to store IV */
710 get_random_bytes(iv
, cc
->iv_size
);
714 static int crypt_iv_eboiv_ctr(struct crypt_config
*cc
, struct dm_target
*ti
,
717 if (crypt_integrity_aead(cc
)) {
718 ti
->error
= "AEAD transforms not supported for EBOIV";
722 if (crypto_skcipher_blocksize(any_tfm(cc
)) != cc
->iv_size
) {
723 ti
->error
= "Block size of EBOIV cipher does "
724 "not match IV size of block cipher";
731 static int crypt_iv_eboiv_gen(struct crypt_config
*cc
, u8
*iv
,
732 struct dm_crypt_request
*dmreq
)
734 u8 buf
[MAX_CIPHER_BLOCKSIZE
] __aligned(__alignof__(__le64
));
735 struct skcipher_request
*req
;
736 struct scatterlist src
, dst
;
737 struct crypto_wait wait
;
740 req
= skcipher_request_alloc(any_tfm(cc
), GFP_NOIO
);
744 memset(buf
, 0, cc
->iv_size
);
745 *(__le64
*)buf
= cpu_to_le64(dmreq
->iv_sector
* cc
->sector_size
);
747 sg_init_one(&src
, page_address(ZERO_PAGE(0)), cc
->iv_size
);
748 sg_init_one(&dst
, iv
, cc
->iv_size
);
749 skcipher_request_set_crypt(req
, &src
, &dst
, cc
->iv_size
, buf
);
750 skcipher_request_set_callback(req
, 0, crypto_req_done
, &wait
);
751 err
= crypto_wait_req(crypto_skcipher_encrypt(req
), &wait
);
752 skcipher_request_free(req
);
757 static void crypt_iv_elephant_dtr(struct crypt_config
*cc
)
759 struct iv_elephant_private
*elephant
= &cc
->iv_gen_private
.elephant
;
761 crypto_free_skcipher(elephant
->tfm
);
762 elephant
->tfm
= NULL
;
765 static int crypt_iv_elephant_ctr(struct crypt_config
*cc
, struct dm_target
*ti
,
768 struct iv_elephant_private
*elephant
= &cc
->iv_gen_private
.elephant
;
771 elephant
->tfm
= crypto_alloc_skcipher("ecb(aes)", 0, 0);
772 if (IS_ERR(elephant
->tfm
)) {
773 r
= PTR_ERR(elephant
->tfm
);
774 elephant
->tfm
= NULL
;
778 r
= crypt_iv_eboiv_ctr(cc
, ti
, NULL
);
780 crypt_iv_elephant_dtr(cc
);
784 static void diffuser_disk_to_cpu(u32
*d
, size_t n
)
786 #ifndef __LITTLE_ENDIAN
789 for (i
= 0; i
< n
; i
++)
790 d
[i
] = le32_to_cpu((__le32
)d
[i
]);
794 static void diffuser_cpu_to_disk(__le32
*d
, size_t n
)
796 #ifndef __LITTLE_ENDIAN
799 for (i
= 0; i
< n
; i
++)
800 d
[i
] = cpu_to_le32((u32
)d
[i
]);
804 static void diffuser_a_decrypt(u32
*d
, size_t n
)
808 for (i
= 0; i
< 5; i
++) {
813 while (i1
< (n
- 1)) {
814 d
[i1
] += d
[i2
] ^ (d
[i3
] << 9 | d
[i3
] >> 23);
820 d
[i1
] += d
[i2
] ^ d
[i3
];
826 d
[i1
] += d
[i2
] ^ (d
[i3
] << 13 | d
[i3
] >> 19);
829 d
[i1
] += d
[i2
] ^ d
[i3
];
835 static void diffuser_a_encrypt(u32
*d
, size_t n
)
839 for (i
= 0; i
< 5; i
++) {
845 d
[i1
] -= d
[i2
] ^ d
[i3
];
848 d
[i1
] -= d
[i2
] ^ (d
[i3
] << 13 | d
[i3
] >> 19);
854 d
[i1
] -= d
[i2
] ^ d
[i3
];
860 d
[i1
] -= d
[i2
] ^ (d
[i3
] << 9 | d
[i3
] >> 23);
866 static void diffuser_b_decrypt(u32
*d
, size_t n
)
870 for (i
= 0; i
< 3; i
++) {
875 while (i1
< (n
- 1)) {
876 d
[i1
] += d
[i2
] ^ d
[i3
];
879 d
[i1
] += d
[i2
] ^ (d
[i3
] << 10 | d
[i3
] >> 22);
885 d
[i1
] += d
[i2
] ^ d
[i3
];
891 d
[i1
] += d
[i2
] ^ (d
[i3
] << 25 | d
[i3
] >> 7);
897 static void diffuser_b_encrypt(u32
*d
, size_t n
)
901 for (i
= 0; i
< 3; i
++) {
907 d
[i1
] -= d
[i2
] ^ (d
[i3
] << 25 | d
[i3
] >> 7);
913 d
[i1
] -= d
[i2
] ^ d
[i3
];
919 d
[i1
] -= d
[i2
] ^ (d
[i3
] << 10 | d
[i3
] >> 22);
922 d
[i1
] -= d
[i2
] ^ d
[i3
];
928 static int crypt_iv_elephant(struct crypt_config
*cc
, struct dm_crypt_request
*dmreq
)
930 struct iv_elephant_private
*elephant
= &cc
->iv_gen_private
.elephant
;
931 u8
*es
, *ks
, *data
, *data2
, *data_offset
;
932 struct skcipher_request
*req
;
933 struct scatterlist
*sg
, *sg2
, src
, dst
;
934 struct crypto_wait wait
;
937 req
= skcipher_request_alloc(elephant
->tfm
, GFP_NOIO
);
938 es
= kzalloc(16, GFP_NOIO
); /* Key for AES */
939 ks
= kzalloc(32, GFP_NOIO
); /* Elephant sector key */
941 if (!req
|| !es
|| !ks
) {
946 *(__le64
*)es
= cpu_to_le64(dmreq
->iv_sector
* cc
->sector_size
);
949 sg_init_one(&src
, es
, 16);
950 sg_init_one(&dst
, ks
, 16);
951 skcipher_request_set_crypt(req
, &src
, &dst
, 16, NULL
);
952 skcipher_request_set_callback(req
, 0, crypto_req_done
, &wait
);
953 r
= crypto_wait_req(crypto_skcipher_encrypt(req
), &wait
);
959 sg_init_one(&dst
, &ks
[16], 16);
960 r
= crypto_wait_req(crypto_skcipher_encrypt(req
), &wait
);
964 sg
= crypt_get_sg_data(cc
, dmreq
->sg_out
);
965 data
= kmap_atomic(sg_page(sg
));
966 data_offset
= data
+ sg
->offset
;
968 /* Cannot modify original bio, copy to sg_out and apply Elephant to it */
969 if (bio_data_dir(dmreq
->ctx
->bio_in
) == WRITE
) {
970 sg2
= crypt_get_sg_data(cc
, dmreq
->sg_in
);
971 data2
= kmap_atomic(sg_page(sg2
));
972 memcpy(data_offset
, data2
+ sg2
->offset
, cc
->sector_size
);
973 kunmap_atomic(data2
);
976 if (bio_data_dir(dmreq
->ctx
->bio_in
) != WRITE
) {
977 diffuser_disk_to_cpu((u32
*)data_offset
, cc
->sector_size
/ sizeof(u32
));
978 diffuser_b_decrypt((u32
*)data_offset
, cc
->sector_size
/ sizeof(u32
));
979 diffuser_a_decrypt((u32
*)data_offset
, cc
->sector_size
/ sizeof(u32
));
980 diffuser_cpu_to_disk((__le32
*)data_offset
, cc
->sector_size
/ sizeof(u32
));
983 for (i
= 0; i
< (cc
->sector_size
/ 32); i
++)
984 crypto_xor(data_offset
+ i
* 32, ks
, 32);
986 if (bio_data_dir(dmreq
->ctx
->bio_in
) == WRITE
) {
987 diffuser_disk_to_cpu((u32
*)data_offset
, cc
->sector_size
/ sizeof(u32
));
988 diffuser_a_encrypt((u32
*)data_offset
, cc
->sector_size
/ sizeof(u32
));
989 diffuser_b_encrypt((u32
*)data_offset
, cc
->sector_size
/ sizeof(u32
));
990 diffuser_cpu_to_disk((__le32
*)data_offset
, cc
->sector_size
/ sizeof(u32
));
997 skcipher_request_free(req
);
1001 static int crypt_iv_elephant_gen(struct crypt_config
*cc
, u8
*iv
,
1002 struct dm_crypt_request
*dmreq
)
1006 if (bio_data_dir(dmreq
->ctx
->bio_in
) == WRITE
) {
1007 r
= crypt_iv_elephant(cc
, dmreq
);
1012 return crypt_iv_eboiv_gen(cc
, iv
, dmreq
);
1015 static int crypt_iv_elephant_post(struct crypt_config
*cc
, u8
*iv
,
1016 struct dm_crypt_request
*dmreq
)
1018 if (bio_data_dir(dmreq
->ctx
->bio_in
) != WRITE
)
1019 return crypt_iv_elephant(cc
, dmreq
);
1024 static int crypt_iv_elephant_init(struct crypt_config
*cc
)
1026 struct iv_elephant_private
*elephant
= &cc
->iv_gen_private
.elephant
;
1027 int key_offset
= cc
->key_size
- cc
->key_extra_size
;
1029 return crypto_skcipher_setkey(elephant
->tfm
, &cc
->key
[key_offset
], cc
->key_extra_size
);
1032 static int crypt_iv_elephant_wipe(struct crypt_config
*cc
)
1034 struct iv_elephant_private
*elephant
= &cc
->iv_gen_private
.elephant
;
1035 u8 key
[ELEPHANT_MAX_KEY_SIZE
];
1037 memset(key
, 0, cc
->key_extra_size
);
1038 return crypto_skcipher_setkey(elephant
->tfm
, key
, cc
->key_extra_size
);
1041 static const struct crypt_iv_operations crypt_iv_plain_ops
= {
1042 .generator
= crypt_iv_plain_gen
1045 static const struct crypt_iv_operations crypt_iv_plain64_ops
= {
1046 .generator
= crypt_iv_plain64_gen
1049 static const struct crypt_iv_operations crypt_iv_plain64be_ops
= {
1050 .generator
= crypt_iv_plain64be_gen
1053 static const struct crypt_iv_operations crypt_iv_essiv_ops
= {
1054 .generator
= crypt_iv_essiv_gen
1057 static const struct crypt_iv_operations crypt_iv_benbi_ops
= {
1058 .ctr
= crypt_iv_benbi_ctr
,
1059 .dtr
= crypt_iv_benbi_dtr
,
1060 .generator
= crypt_iv_benbi_gen
1063 static const struct crypt_iv_operations crypt_iv_null_ops
= {
1064 .generator
= crypt_iv_null_gen
1067 static const struct crypt_iv_operations crypt_iv_lmk_ops
= {
1068 .ctr
= crypt_iv_lmk_ctr
,
1069 .dtr
= crypt_iv_lmk_dtr
,
1070 .init
= crypt_iv_lmk_init
,
1071 .wipe
= crypt_iv_lmk_wipe
,
1072 .generator
= crypt_iv_lmk_gen
,
1073 .post
= crypt_iv_lmk_post
1076 static const struct crypt_iv_operations crypt_iv_tcw_ops
= {
1077 .ctr
= crypt_iv_tcw_ctr
,
1078 .dtr
= crypt_iv_tcw_dtr
,
1079 .init
= crypt_iv_tcw_init
,
1080 .wipe
= crypt_iv_tcw_wipe
,
1081 .generator
= crypt_iv_tcw_gen
,
1082 .post
= crypt_iv_tcw_post
1085 static struct crypt_iv_operations crypt_iv_random_ops
= {
1086 .generator
= crypt_iv_random_gen
1089 static struct crypt_iv_operations crypt_iv_eboiv_ops
= {
1090 .ctr
= crypt_iv_eboiv_ctr
,
1091 .generator
= crypt_iv_eboiv_gen
1094 static struct crypt_iv_operations crypt_iv_elephant_ops
= {
1095 .ctr
= crypt_iv_elephant_ctr
,
1096 .dtr
= crypt_iv_elephant_dtr
,
1097 .init
= crypt_iv_elephant_init
,
1098 .wipe
= crypt_iv_elephant_wipe
,
1099 .generator
= crypt_iv_elephant_gen
,
1100 .post
= crypt_iv_elephant_post
1104 * Integrity extensions
1106 static bool crypt_integrity_aead(struct crypt_config
*cc
)
1108 return test_bit(CRYPT_MODE_INTEGRITY_AEAD
, &cc
->cipher_flags
);
1111 static bool crypt_integrity_hmac(struct crypt_config
*cc
)
1113 return crypt_integrity_aead(cc
) && cc
->key_mac_size
;
1116 /* Get sg containing data */
1117 static struct scatterlist
*crypt_get_sg_data(struct crypt_config
*cc
,
1118 struct scatterlist
*sg
)
1120 if (unlikely(crypt_integrity_aead(cc
)))
1126 static int dm_crypt_integrity_io_alloc(struct dm_crypt_io
*io
, struct bio
*bio
)
1128 struct bio_integrity_payload
*bip
;
1129 unsigned int tag_len
;
1132 if (!bio_sectors(bio
) || !io
->cc
->on_disk_tag_size
)
1135 bip
= bio_integrity_alloc(bio
, GFP_NOIO
, 1);
1137 return PTR_ERR(bip
);
1139 tag_len
= io
->cc
->on_disk_tag_size
* (bio_sectors(bio
) >> io
->cc
->sector_shift
);
1141 bip
->bip_iter
.bi_size
= tag_len
;
1142 bip
->bip_iter
.bi_sector
= io
->cc
->start
+ io
->sector
;
1144 ret
= bio_integrity_add_page(bio
, virt_to_page(io
->integrity_metadata
),
1145 tag_len
, offset_in_page(io
->integrity_metadata
));
1146 if (unlikely(ret
!= tag_len
))
1152 static int crypt_integrity_ctr(struct crypt_config
*cc
, struct dm_target
*ti
)
1154 #ifdef CONFIG_BLK_DEV_INTEGRITY
1155 struct blk_integrity
*bi
= blk_get_integrity(cc
->dev
->bdev
->bd_disk
);
1156 struct mapped_device
*md
= dm_table_get_md(ti
->table
);
1158 /* From now we require underlying device with our integrity profile */
1159 if (!bi
|| strcasecmp(bi
->profile
->name
, "DM-DIF-EXT-TAG")) {
1160 ti
->error
= "Integrity profile not supported.";
1164 if (bi
->tag_size
!= cc
->on_disk_tag_size
||
1165 bi
->tuple_size
!= cc
->on_disk_tag_size
) {
1166 ti
->error
= "Integrity profile tag size mismatch.";
1169 if (1 << bi
->interval_exp
!= cc
->sector_size
) {
1170 ti
->error
= "Integrity profile sector size mismatch.";
1174 if (crypt_integrity_aead(cc
)) {
1175 cc
->integrity_tag_size
= cc
->on_disk_tag_size
- cc
->integrity_iv_size
;
1176 DMDEBUG("%s: Integrity AEAD, tag size %u, IV size %u.", dm_device_name(md
),
1177 cc
->integrity_tag_size
, cc
->integrity_iv_size
);
1179 if (crypto_aead_setauthsize(any_tfm_aead(cc
), cc
->integrity_tag_size
)) {
1180 ti
->error
= "Integrity AEAD auth tag size is not supported.";
1183 } else if (cc
->integrity_iv_size
)
1184 DMDEBUG("%s: Additional per-sector space %u bytes for IV.", dm_device_name(md
),
1185 cc
->integrity_iv_size
);
1187 if ((cc
->integrity_tag_size
+ cc
->integrity_iv_size
) != bi
->tag_size
) {
1188 ti
->error
= "Not enough space for integrity tag in the profile.";
1194 ti
->error
= "Integrity profile not supported.";
1199 static void crypt_convert_init(struct crypt_config
*cc
,
1200 struct convert_context
*ctx
,
1201 struct bio
*bio_out
, struct bio
*bio_in
,
1204 ctx
->bio_in
= bio_in
;
1205 ctx
->bio_out
= bio_out
;
1207 ctx
->iter_in
= bio_in
->bi_iter
;
1209 ctx
->iter_out
= bio_out
->bi_iter
;
1210 ctx
->cc_sector
= sector
+ cc
->iv_offset
;
1211 init_completion(&ctx
->restart
);
1214 static struct dm_crypt_request
*dmreq_of_req(struct crypt_config
*cc
,
1217 return (struct dm_crypt_request
*)((char *)req
+ cc
->dmreq_start
);
1220 static void *req_of_dmreq(struct crypt_config
*cc
, struct dm_crypt_request
*dmreq
)
1222 return (void *)((char *)dmreq
- cc
->dmreq_start
);
1225 static u8
*iv_of_dmreq(struct crypt_config
*cc
,
1226 struct dm_crypt_request
*dmreq
)
1228 if (crypt_integrity_aead(cc
))
1229 return (u8
*)ALIGN((unsigned long)(dmreq
+ 1),
1230 crypto_aead_alignmask(any_tfm_aead(cc
)) + 1);
1232 return (u8
*)ALIGN((unsigned long)(dmreq
+ 1),
1233 crypto_skcipher_alignmask(any_tfm(cc
)) + 1);
1236 static u8
*org_iv_of_dmreq(struct crypt_config
*cc
,
1237 struct dm_crypt_request
*dmreq
)
1239 return iv_of_dmreq(cc
, dmreq
) + cc
->iv_size
;
1242 static __le64
*org_sector_of_dmreq(struct crypt_config
*cc
,
1243 struct dm_crypt_request
*dmreq
)
1245 u8
*ptr
= iv_of_dmreq(cc
, dmreq
) + cc
->iv_size
+ cc
->iv_size
;
1246 return (__le64
*) ptr
;
1249 static unsigned int *org_tag_of_dmreq(struct crypt_config
*cc
,
1250 struct dm_crypt_request
*dmreq
)
1252 u8
*ptr
= iv_of_dmreq(cc
, dmreq
) + cc
->iv_size
+
1253 cc
->iv_size
+ sizeof(uint64_t);
1254 return (unsigned int*)ptr
;
1257 static void *tag_from_dmreq(struct crypt_config
*cc
,
1258 struct dm_crypt_request
*dmreq
)
1260 struct convert_context
*ctx
= dmreq
->ctx
;
1261 struct dm_crypt_io
*io
= container_of(ctx
, struct dm_crypt_io
, ctx
);
1263 return &io
->integrity_metadata
[*org_tag_of_dmreq(cc
, dmreq
) *
1264 cc
->on_disk_tag_size
];
1267 static void *iv_tag_from_dmreq(struct crypt_config
*cc
,
1268 struct dm_crypt_request
*dmreq
)
1270 return tag_from_dmreq(cc
, dmreq
) + cc
->integrity_tag_size
;
1273 static int crypt_convert_block_aead(struct crypt_config
*cc
,
1274 struct convert_context
*ctx
,
1275 struct aead_request
*req
,
1276 unsigned int tag_offset
)
1278 struct bio_vec bv_in
= bio_iter_iovec(ctx
->bio_in
, ctx
->iter_in
);
1279 struct bio_vec bv_out
= bio_iter_iovec(ctx
->bio_out
, ctx
->iter_out
);
1280 struct dm_crypt_request
*dmreq
;
1281 u8
*iv
, *org_iv
, *tag_iv
, *tag
;
1285 BUG_ON(cc
->integrity_iv_size
&& cc
->integrity_iv_size
!= cc
->iv_size
);
1287 /* Reject unexpected unaligned bio. */
1288 if (unlikely(bv_in
.bv_len
& (cc
->sector_size
- 1)))
1291 dmreq
= dmreq_of_req(cc
, req
);
1292 dmreq
->iv_sector
= ctx
->cc_sector
;
1293 if (test_bit(CRYPT_IV_LARGE_SECTORS
, &cc
->cipher_flags
))
1294 dmreq
->iv_sector
>>= cc
->sector_shift
;
1297 *org_tag_of_dmreq(cc
, dmreq
) = tag_offset
;
1299 sector
= org_sector_of_dmreq(cc
, dmreq
);
1300 *sector
= cpu_to_le64(ctx
->cc_sector
- cc
->iv_offset
);
1302 iv
= iv_of_dmreq(cc
, dmreq
);
1303 org_iv
= org_iv_of_dmreq(cc
, dmreq
);
1304 tag
= tag_from_dmreq(cc
, dmreq
);
1305 tag_iv
= iv_tag_from_dmreq(cc
, dmreq
);
1308 * |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1309 * | (authenticated) | (auth+encryption) | |
1310 * | sector_LE | IV | sector in/out | tag in/out |
1312 sg_init_table(dmreq
->sg_in
, 4);
1313 sg_set_buf(&dmreq
->sg_in
[0], sector
, sizeof(uint64_t));
1314 sg_set_buf(&dmreq
->sg_in
[1], org_iv
, cc
->iv_size
);
1315 sg_set_page(&dmreq
->sg_in
[2], bv_in
.bv_page
, cc
->sector_size
, bv_in
.bv_offset
);
1316 sg_set_buf(&dmreq
->sg_in
[3], tag
, cc
->integrity_tag_size
);
1318 sg_init_table(dmreq
->sg_out
, 4);
1319 sg_set_buf(&dmreq
->sg_out
[0], sector
, sizeof(uint64_t));
1320 sg_set_buf(&dmreq
->sg_out
[1], org_iv
, cc
->iv_size
);
1321 sg_set_page(&dmreq
->sg_out
[2], bv_out
.bv_page
, cc
->sector_size
, bv_out
.bv_offset
);
1322 sg_set_buf(&dmreq
->sg_out
[3], tag
, cc
->integrity_tag_size
);
1324 if (cc
->iv_gen_ops
) {
1325 /* For READs use IV stored in integrity metadata */
1326 if (cc
->integrity_iv_size
&& bio_data_dir(ctx
->bio_in
) != WRITE
) {
1327 memcpy(org_iv
, tag_iv
, cc
->iv_size
);
1329 r
= cc
->iv_gen_ops
->generator(cc
, org_iv
, dmreq
);
1332 /* Store generated IV in integrity metadata */
1333 if (cc
->integrity_iv_size
)
1334 memcpy(tag_iv
, org_iv
, cc
->iv_size
);
1336 /* Working copy of IV, to be modified in crypto API */
1337 memcpy(iv
, org_iv
, cc
->iv_size
);
1340 aead_request_set_ad(req
, sizeof(uint64_t) + cc
->iv_size
);
1341 if (bio_data_dir(ctx
->bio_in
) == WRITE
) {
1342 aead_request_set_crypt(req
, dmreq
->sg_in
, dmreq
->sg_out
,
1343 cc
->sector_size
, iv
);
1344 r
= crypto_aead_encrypt(req
);
1345 if (cc
->integrity_tag_size
+ cc
->integrity_iv_size
!= cc
->on_disk_tag_size
)
1346 memset(tag
+ cc
->integrity_tag_size
+ cc
->integrity_iv_size
, 0,
1347 cc
->on_disk_tag_size
- (cc
->integrity_tag_size
+ cc
->integrity_iv_size
));
1349 aead_request_set_crypt(req
, dmreq
->sg_in
, dmreq
->sg_out
,
1350 cc
->sector_size
+ cc
->integrity_tag_size
, iv
);
1351 r
= crypto_aead_decrypt(req
);
1354 if (r
== -EBADMSG
) {
1355 char b
[BDEVNAME_SIZE
];
1356 DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx
->bio_in
, b
),
1357 (unsigned long long)le64_to_cpu(*sector
));
1360 if (!r
&& cc
->iv_gen_ops
&& cc
->iv_gen_ops
->post
)
1361 r
= cc
->iv_gen_ops
->post(cc
, org_iv
, dmreq
);
1363 bio_advance_iter(ctx
->bio_in
, &ctx
->iter_in
, cc
->sector_size
);
1364 bio_advance_iter(ctx
->bio_out
, &ctx
->iter_out
, cc
->sector_size
);
1369 static int crypt_convert_block_skcipher(struct crypt_config
*cc
,
1370 struct convert_context
*ctx
,
1371 struct skcipher_request
*req
,
1372 unsigned int tag_offset
)
1374 struct bio_vec bv_in
= bio_iter_iovec(ctx
->bio_in
, ctx
->iter_in
);
1375 struct bio_vec bv_out
= bio_iter_iovec(ctx
->bio_out
, ctx
->iter_out
);
1376 struct scatterlist
*sg_in
, *sg_out
;
1377 struct dm_crypt_request
*dmreq
;
1378 u8
*iv
, *org_iv
, *tag_iv
;
1382 /* Reject unexpected unaligned bio. */
1383 if (unlikely(bv_in
.bv_len
& (cc
->sector_size
- 1)))
1386 dmreq
= dmreq_of_req(cc
, req
);
1387 dmreq
->iv_sector
= ctx
->cc_sector
;
1388 if (test_bit(CRYPT_IV_LARGE_SECTORS
, &cc
->cipher_flags
))
1389 dmreq
->iv_sector
>>= cc
->sector_shift
;
1392 *org_tag_of_dmreq(cc
, dmreq
) = tag_offset
;
1394 iv
= iv_of_dmreq(cc
, dmreq
);
1395 org_iv
= org_iv_of_dmreq(cc
, dmreq
);
1396 tag_iv
= iv_tag_from_dmreq(cc
, dmreq
);
1398 sector
= org_sector_of_dmreq(cc
, dmreq
);
1399 *sector
= cpu_to_le64(ctx
->cc_sector
- cc
->iv_offset
);
1401 /* For skcipher we use only the first sg item */
1402 sg_in
= &dmreq
->sg_in
[0];
1403 sg_out
= &dmreq
->sg_out
[0];
1405 sg_init_table(sg_in
, 1);
1406 sg_set_page(sg_in
, bv_in
.bv_page
, cc
->sector_size
, bv_in
.bv_offset
);
1408 sg_init_table(sg_out
, 1);
1409 sg_set_page(sg_out
, bv_out
.bv_page
, cc
->sector_size
, bv_out
.bv_offset
);
1411 if (cc
->iv_gen_ops
) {
1412 /* For READs use IV stored in integrity metadata */
1413 if (cc
->integrity_iv_size
&& bio_data_dir(ctx
->bio_in
) != WRITE
) {
1414 memcpy(org_iv
, tag_iv
, cc
->integrity_iv_size
);
1416 r
= cc
->iv_gen_ops
->generator(cc
, org_iv
, dmreq
);
1419 /* Data can be already preprocessed in generator */
1420 if (test_bit(CRYPT_ENCRYPT_PREPROCESS
, &cc
->cipher_flags
))
1422 /* Store generated IV in integrity metadata */
1423 if (cc
->integrity_iv_size
)
1424 memcpy(tag_iv
, org_iv
, cc
->integrity_iv_size
);
1426 /* Working copy of IV, to be modified in crypto API */
1427 memcpy(iv
, org_iv
, cc
->iv_size
);
1430 skcipher_request_set_crypt(req
, sg_in
, sg_out
, cc
->sector_size
, iv
);
1432 if (bio_data_dir(ctx
->bio_in
) == WRITE
)
1433 r
= crypto_skcipher_encrypt(req
);
1435 r
= crypto_skcipher_decrypt(req
);
1437 if (!r
&& cc
->iv_gen_ops
&& cc
->iv_gen_ops
->post
)
1438 r
= cc
->iv_gen_ops
->post(cc
, org_iv
, dmreq
);
1440 bio_advance_iter(ctx
->bio_in
, &ctx
->iter_in
, cc
->sector_size
);
1441 bio_advance_iter(ctx
->bio_out
, &ctx
->iter_out
, cc
->sector_size
);
1446 static void kcryptd_async_done(struct crypto_async_request
*async_req
,
1449 static void crypt_alloc_req_skcipher(struct crypt_config
*cc
,
1450 struct convert_context
*ctx
)
1452 unsigned key_index
= ctx
->cc_sector
& (cc
->tfms_count
- 1);
1455 ctx
->r
.req
= mempool_alloc(&cc
->req_pool
, GFP_NOIO
);
1457 skcipher_request_set_tfm(ctx
->r
.req
, cc
->cipher_tfm
.tfms
[key_index
]);
1460 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1461 * requests if driver request queue is full.
1463 skcipher_request_set_callback(ctx
->r
.req
,
1464 CRYPTO_TFM_REQ_MAY_BACKLOG
,
1465 kcryptd_async_done
, dmreq_of_req(cc
, ctx
->r
.req
));
1468 static void crypt_alloc_req_aead(struct crypt_config
*cc
,
1469 struct convert_context
*ctx
)
1471 if (!ctx
->r
.req_aead
)
1472 ctx
->r
.req_aead
= mempool_alloc(&cc
->req_pool
, GFP_NOIO
);
1474 aead_request_set_tfm(ctx
->r
.req_aead
, cc
->cipher_tfm
.tfms_aead
[0]);
1477 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1478 * requests if driver request queue is full.
1480 aead_request_set_callback(ctx
->r
.req_aead
,
1481 CRYPTO_TFM_REQ_MAY_BACKLOG
,
1482 kcryptd_async_done
, dmreq_of_req(cc
, ctx
->r
.req_aead
));
1485 static void crypt_alloc_req(struct crypt_config
*cc
,
1486 struct convert_context
*ctx
)
1488 if (crypt_integrity_aead(cc
))
1489 crypt_alloc_req_aead(cc
, ctx
);
1491 crypt_alloc_req_skcipher(cc
, ctx
);
1494 static void crypt_free_req_skcipher(struct crypt_config
*cc
,
1495 struct skcipher_request
*req
, struct bio
*base_bio
)
1497 struct dm_crypt_io
*io
= dm_per_bio_data(base_bio
, cc
->per_bio_data_size
);
1499 if ((struct skcipher_request
*)(io
+ 1) != req
)
1500 mempool_free(req
, &cc
->req_pool
);
1503 static void crypt_free_req_aead(struct crypt_config
*cc
,
1504 struct aead_request
*req
, struct bio
*base_bio
)
1506 struct dm_crypt_io
*io
= dm_per_bio_data(base_bio
, cc
->per_bio_data_size
);
1508 if ((struct aead_request
*)(io
+ 1) != req
)
1509 mempool_free(req
, &cc
->req_pool
);
1512 static void crypt_free_req(struct crypt_config
*cc
, void *req
, struct bio
*base_bio
)
1514 if (crypt_integrity_aead(cc
))
1515 crypt_free_req_aead(cc
, req
, base_bio
);
1517 crypt_free_req_skcipher(cc
, req
, base_bio
);
1521 * Encrypt / decrypt data from one bio to another one (can be the same one)
1523 static blk_status_t
crypt_convert(struct crypt_config
*cc
,
1524 struct convert_context
*ctx
)
1526 unsigned int tag_offset
= 0;
1527 unsigned int sector_step
= cc
->sector_size
>> SECTOR_SHIFT
;
1530 atomic_set(&ctx
->cc_pending
, 1);
1532 while (ctx
->iter_in
.bi_size
&& ctx
->iter_out
.bi_size
) {
1534 crypt_alloc_req(cc
, ctx
);
1535 atomic_inc(&ctx
->cc_pending
);
1537 if (crypt_integrity_aead(cc
))
1538 r
= crypt_convert_block_aead(cc
, ctx
, ctx
->r
.req_aead
, tag_offset
);
1540 r
= crypt_convert_block_skcipher(cc
, ctx
, ctx
->r
.req
, tag_offset
);
1544 * The request was queued by a crypto driver
1545 * but the driver request queue is full, let's wait.
1548 wait_for_completion(&ctx
->restart
);
1549 reinit_completion(&ctx
->restart
);
1552 * The request is queued and processed asynchronously,
1553 * completion function kcryptd_async_done() will be called.
1557 ctx
->cc_sector
+= sector_step
;
1561 * The request was already processed (synchronously).
1564 atomic_dec(&ctx
->cc_pending
);
1565 ctx
->cc_sector
+= sector_step
;
1570 * There was a data integrity error.
1573 atomic_dec(&ctx
->cc_pending
);
1574 return BLK_STS_PROTECTION
;
1576 * There was an error while processing the request.
1579 atomic_dec(&ctx
->cc_pending
);
1580 return BLK_STS_IOERR
;
1587 static void crypt_free_buffer_pages(struct crypt_config
*cc
, struct bio
*clone
);
1590 * Generate a new unfragmented bio with the given size
1591 * This should never violate the device limitations (but only because
1592 * max_segment_size is being constrained to PAGE_SIZE).
1594 * This function may be called concurrently. If we allocate from the mempool
1595 * concurrently, there is a possibility of deadlock. For example, if we have
1596 * mempool of 256 pages, two processes, each wanting 256, pages allocate from
1597 * the mempool concurrently, it may deadlock in a situation where both processes
1598 * have allocated 128 pages and the mempool is exhausted.
1600 * In order to avoid this scenario we allocate the pages under a mutex.
1602 * In order to not degrade performance with excessive locking, we try
1603 * non-blocking allocations without a mutex first but on failure we fallback
1604 * to blocking allocations with a mutex.
1606 static struct bio
*crypt_alloc_buffer(struct dm_crypt_io
*io
, unsigned size
)
1608 struct crypt_config
*cc
= io
->cc
;
1610 unsigned int nr_iovecs
= (size
+ PAGE_SIZE
- 1) >> PAGE_SHIFT
;
1611 gfp_t gfp_mask
= GFP_NOWAIT
| __GFP_HIGHMEM
;
1612 unsigned i
, len
, remaining_size
;
1616 if (unlikely(gfp_mask
& __GFP_DIRECT_RECLAIM
))
1617 mutex_lock(&cc
->bio_alloc_lock
);
1619 clone
= bio_alloc_bioset(GFP_NOIO
, nr_iovecs
, &cc
->bs
);
1623 clone_init(io
, clone
);
1625 remaining_size
= size
;
1627 for (i
= 0; i
< nr_iovecs
; i
++) {
1628 page
= mempool_alloc(&cc
->page_pool
, gfp_mask
);
1630 crypt_free_buffer_pages(cc
, clone
);
1632 gfp_mask
|= __GFP_DIRECT_RECLAIM
;
1636 len
= (remaining_size
> PAGE_SIZE
) ? PAGE_SIZE
: remaining_size
;
1638 bio_add_page(clone
, page
, len
, 0);
1640 remaining_size
-= len
;
1643 /* Allocate space for integrity tags */
1644 if (dm_crypt_integrity_io_alloc(io
, clone
)) {
1645 crypt_free_buffer_pages(cc
, clone
);
1650 if (unlikely(gfp_mask
& __GFP_DIRECT_RECLAIM
))
1651 mutex_unlock(&cc
->bio_alloc_lock
);
1656 static void crypt_free_buffer_pages(struct crypt_config
*cc
, struct bio
*clone
)
1659 struct bvec_iter_all iter_all
;
1661 bio_for_each_segment_all(bv
, clone
, iter_all
) {
1662 BUG_ON(!bv
->bv_page
);
1663 mempool_free(bv
->bv_page
, &cc
->page_pool
);
1667 static void crypt_io_init(struct dm_crypt_io
*io
, struct crypt_config
*cc
,
1668 struct bio
*bio
, sector_t sector
)
1672 io
->sector
= sector
;
1674 io
->ctx
.r
.req
= NULL
;
1675 io
->integrity_metadata
= NULL
;
1676 io
->integrity_metadata_from_pool
= false;
1677 atomic_set(&io
->io_pending
, 0);
1680 static void crypt_inc_pending(struct dm_crypt_io
*io
)
1682 atomic_inc(&io
->io_pending
);
1686 * One of the bios was finished. Check for completion of
1687 * the whole request and correctly clean up the buffer.
1689 static void crypt_dec_pending(struct dm_crypt_io
*io
)
1691 struct crypt_config
*cc
= io
->cc
;
1692 struct bio
*base_bio
= io
->base_bio
;
1693 blk_status_t error
= io
->error
;
1695 if (!atomic_dec_and_test(&io
->io_pending
))
1699 crypt_free_req(cc
, io
->ctx
.r
.req
, base_bio
);
1701 if (unlikely(io
->integrity_metadata_from_pool
))
1702 mempool_free(io
->integrity_metadata
, &io
->cc
->tag_pool
);
1704 kfree(io
->integrity_metadata
);
1706 base_bio
->bi_status
= error
;
1707 bio_endio(base_bio
);
1711 * kcryptd/kcryptd_io:
1713 * Needed because it would be very unwise to do decryption in an
1714 * interrupt context.
1716 * kcryptd performs the actual encryption or decryption.
1718 * kcryptd_io performs the IO submission.
1720 * They must be separated as otherwise the final stages could be
1721 * starved by new requests which can block in the first stages due
1722 * to memory allocation.
1724 * The work is done per CPU global for all dm-crypt instances.
1725 * They should not depend on each other and do not block.
1727 static void crypt_endio(struct bio
*clone
)
1729 struct dm_crypt_io
*io
= clone
->bi_private
;
1730 struct crypt_config
*cc
= io
->cc
;
1731 unsigned rw
= bio_data_dir(clone
);
1735 * free the processed pages
1738 crypt_free_buffer_pages(cc
, clone
);
1740 error
= clone
->bi_status
;
1743 if (rw
== READ
&& !error
) {
1744 kcryptd_queue_crypt(io
);
1748 if (unlikely(error
))
1751 crypt_dec_pending(io
);
1754 static void clone_init(struct dm_crypt_io
*io
, struct bio
*clone
)
1756 struct crypt_config
*cc
= io
->cc
;
1758 clone
->bi_private
= io
;
1759 clone
->bi_end_io
= crypt_endio
;
1760 bio_set_dev(clone
, cc
->dev
->bdev
);
1761 clone
->bi_opf
= io
->base_bio
->bi_opf
;
1764 static int kcryptd_io_read(struct dm_crypt_io
*io
, gfp_t gfp
)
1766 struct crypt_config
*cc
= io
->cc
;
1770 * We need the original biovec array in order to decrypt
1771 * the whole bio data *afterwards* -- thanks to immutable
1772 * biovecs we don't need to worry about the block layer
1773 * modifying the biovec array; so leverage bio_clone_fast().
1775 clone
= bio_clone_fast(io
->base_bio
, gfp
, &cc
->bs
);
1779 crypt_inc_pending(io
);
1781 clone_init(io
, clone
);
1782 clone
->bi_iter
.bi_sector
= cc
->start
+ io
->sector
;
1784 if (dm_crypt_integrity_io_alloc(io
, clone
)) {
1785 crypt_dec_pending(io
);
1790 generic_make_request(clone
);
1794 static void kcryptd_io_read_work(struct work_struct
*work
)
1796 struct dm_crypt_io
*io
= container_of(work
, struct dm_crypt_io
, work
);
1798 crypt_inc_pending(io
);
1799 if (kcryptd_io_read(io
, GFP_NOIO
))
1800 io
->error
= BLK_STS_RESOURCE
;
1801 crypt_dec_pending(io
);
1804 static void kcryptd_queue_read(struct dm_crypt_io
*io
)
1806 struct crypt_config
*cc
= io
->cc
;
1808 INIT_WORK(&io
->work
, kcryptd_io_read_work
);
1809 queue_work(cc
->io_queue
, &io
->work
);
1812 static void kcryptd_io_write(struct dm_crypt_io
*io
)
1814 struct bio
*clone
= io
->ctx
.bio_out
;
1816 generic_make_request(clone
);
1819 #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1821 static int dmcrypt_write(void *data
)
1823 struct crypt_config
*cc
= data
;
1824 struct dm_crypt_io
*io
;
1827 struct rb_root write_tree
;
1828 struct blk_plug plug
;
1830 spin_lock_irq(&cc
->write_thread_lock
);
1833 if (!RB_EMPTY_ROOT(&cc
->write_tree
))
1836 set_current_state(TASK_INTERRUPTIBLE
);
1838 spin_unlock_irq(&cc
->write_thread_lock
);
1840 if (unlikely(kthread_should_stop())) {
1841 set_current_state(TASK_RUNNING
);
1847 set_current_state(TASK_RUNNING
);
1848 spin_lock_irq(&cc
->write_thread_lock
);
1849 goto continue_locked
;
1852 write_tree
= cc
->write_tree
;
1853 cc
->write_tree
= RB_ROOT
;
1854 spin_unlock_irq(&cc
->write_thread_lock
);
1856 BUG_ON(rb_parent(write_tree
.rb_node
));
1859 * Note: we cannot walk the tree here with rb_next because
1860 * the structures may be freed when kcryptd_io_write is called.
1862 blk_start_plug(&plug
);
1864 io
= crypt_io_from_node(rb_first(&write_tree
));
1865 rb_erase(&io
->rb_node
, &write_tree
);
1866 kcryptd_io_write(io
);
1867 } while (!RB_EMPTY_ROOT(&write_tree
));
1868 blk_finish_plug(&plug
);
1873 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io
*io
, int async
)
1875 struct bio
*clone
= io
->ctx
.bio_out
;
1876 struct crypt_config
*cc
= io
->cc
;
1877 unsigned long flags
;
1879 struct rb_node
**rbp
, *parent
;
1881 if (unlikely(io
->error
)) {
1882 crypt_free_buffer_pages(cc
, clone
);
1884 crypt_dec_pending(io
);
1888 /* crypt_convert should have filled the clone bio */
1889 BUG_ON(io
->ctx
.iter_out
.bi_size
);
1891 clone
->bi_iter
.bi_sector
= cc
->start
+ io
->sector
;
1893 if (likely(!async
) && test_bit(DM_CRYPT_NO_OFFLOAD
, &cc
->flags
)) {
1894 generic_make_request(clone
);
1898 spin_lock_irqsave(&cc
->write_thread_lock
, flags
);
1899 if (RB_EMPTY_ROOT(&cc
->write_tree
))
1900 wake_up_process(cc
->write_thread
);
1901 rbp
= &cc
->write_tree
.rb_node
;
1903 sector
= io
->sector
;
1906 if (sector
< crypt_io_from_node(parent
)->sector
)
1907 rbp
= &(*rbp
)->rb_left
;
1909 rbp
= &(*rbp
)->rb_right
;
1911 rb_link_node(&io
->rb_node
, parent
, rbp
);
1912 rb_insert_color(&io
->rb_node
, &cc
->write_tree
);
1913 spin_unlock_irqrestore(&cc
->write_thread_lock
, flags
);
1916 static void kcryptd_crypt_write_convert(struct dm_crypt_io
*io
)
1918 struct crypt_config
*cc
= io
->cc
;
1921 sector_t sector
= io
->sector
;
1925 * Prevent io from disappearing until this function completes.
1927 crypt_inc_pending(io
);
1928 crypt_convert_init(cc
, &io
->ctx
, NULL
, io
->base_bio
, sector
);
1930 clone
= crypt_alloc_buffer(io
, io
->base_bio
->bi_iter
.bi_size
);
1931 if (unlikely(!clone
)) {
1932 io
->error
= BLK_STS_IOERR
;
1936 io
->ctx
.bio_out
= clone
;
1937 io
->ctx
.iter_out
= clone
->bi_iter
;
1939 sector
+= bio_sectors(clone
);
1941 crypt_inc_pending(io
);
1942 r
= crypt_convert(cc
, &io
->ctx
);
1945 crypt_finished
= atomic_dec_and_test(&io
->ctx
.cc_pending
);
1947 /* Encryption was already finished, submit io now */
1948 if (crypt_finished
) {
1949 kcryptd_crypt_write_io_submit(io
, 0);
1950 io
->sector
= sector
;
1954 crypt_dec_pending(io
);
1957 static void kcryptd_crypt_read_done(struct dm_crypt_io
*io
)
1959 crypt_dec_pending(io
);
1962 static void kcryptd_crypt_read_convert(struct dm_crypt_io
*io
)
1964 struct crypt_config
*cc
= io
->cc
;
1967 crypt_inc_pending(io
);
1969 crypt_convert_init(cc
, &io
->ctx
, io
->base_bio
, io
->base_bio
,
1972 r
= crypt_convert(cc
, &io
->ctx
);
1976 if (atomic_dec_and_test(&io
->ctx
.cc_pending
))
1977 kcryptd_crypt_read_done(io
);
1979 crypt_dec_pending(io
);
1982 static void kcryptd_async_done(struct crypto_async_request
*async_req
,
1985 struct dm_crypt_request
*dmreq
= async_req
->data
;
1986 struct convert_context
*ctx
= dmreq
->ctx
;
1987 struct dm_crypt_io
*io
= container_of(ctx
, struct dm_crypt_io
, ctx
);
1988 struct crypt_config
*cc
= io
->cc
;
1991 * A request from crypto driver backlog is going to be processed now,
1992 * finish the completion and continue in crypt_convert().
1993 * (Callback will be called for the second time for this request.)
1995 if (error
== -EINPROGRESS
) {
1996 complete(&ctx
->restart
);
2000 if (!error
&& cc
->iv_gen_ops
&& cc
->iv_gen_ops
->post
)
2001 error
= cc
->iv_gen_ops
->post(cc
, org_iv_of_dmreq(cc
, dmreq
), dmreq
);
2003 if (error
== -EBADMSG
) {
2004 char b
[BDEVNAME_SIZE
];
2005 DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx
->bio_in
, b
),
2006 (unsigned long long)le64_to_cpu(*org_sector_of_dmreq(cc
, dmreq
)));
2007 io
->error
= BLK_STS_PROTECTION
;
2008 } else if (error
< 0)
2009 io
->error
= BLK_STS_IOERR
;
2011 crypt_free_req(cc
, req_of_dmreq(cc
, dmreq
), io
->base_bio
);
2013 if (!atomic_dec_and_test(&ctx
->cc_pending
))
2016 if (bio_data_dir(io
->base_bio
) == READ
)
2017 kcryptd_crypt_read_done(io
);
2019 kcryptd_crypt_write_io_submit(io
, 1);
2022 static void kcryptd_crypt(struct work_struct
*work
)
2024 struct dm_crypt_io
*io
= container_of(work
, struct dm_crypt_io
, work
);
2026 if (bio_data_dir(io
->base_bio
) == READ
)
2027 kcryptd_crypt_read_convert(io
);
2029 kcryptd_crypt_write_convert(io
);
2032 static void kcryptd_queue_crypt(struct dm_crypt_io
*io
)
2034 struct crypt_config
*cc
= io
->cc
;
2036 INIT_WORK(&io
->work
, kcryptd_crypt
);
2037 queue_work(cc
->crypt_queue
, &io
->work
);
2040 static void crypt_free_tfms_aead(struct crypt_config
*cc
)
2042 if (!cc
->cipher_tfm
.tfms_aead
)
2045 if (cc
->cipher_tfm
.tfms_aead
[0] && !IS_ERR(cc
->cipher_tfm
.tfms_aead
[0])) {
2046 crypto_free_aead(cc
->cipher_tfm
.tfms_aead
[0]);
2047 cc
->cipher_tfm
.tfms_aead
[0] = NULL
;
2050 kfree(cc
->cipher_tfm
.tfms_aead
);
2051 cc
->cipher_tfm
.tfms_aead
= NULL
;
2054 static void crypt_free_tfms_skcipher(struct crypt_config
*cc
)
2058 if (!cc
->cipher_tfm
.tfms
)
2061 for (i
= 0; i
< cc
->tfms_count
; i
++)
2062 if (cc
->cipher_tfm
.tfms
[i
] && !IS_ERR(cc
->cipher_tfm
.tfms
[i
])) {
2063 crypto_free_skcipher(cc
->cipher_tfm
.tfms
[i
]);
2064 cc
->cipher_tfm
.tfms
[i
] = NULL
;
2067 kfree(cc
->cipher_tfm
.tfms
);
2068 cc
->cipher_tfm
.tfms
= NULL
;
2071 static void crypt_free_tfms(struct crypt_config
*cc
)
2073 if (crypt_integrity_aead(cc
))
2074 crypt_free_tfms_aead(cc
);
2076 crypt_free_tfms_skcipher(cc
);
2079 static int crypt_alloc_tfms_skcipher(struct crypt_config
*cc
, char *ciphermode
)
2084 cc
->cipher_tfm
.tfms
= kcalloc(cc
->tfms_count
,
2085 sizeof(struct crypto_skcipher
*),
2087 if (!cc
->cipher_tfm
.tfms
)
2090 for (i
= 0; i
< cc
->tfms_count
; i
++) {
2091 cc
->cipher_tfm
.tfms
[i
] = crypto_alloc_skcipher(ciphermode
, 0, 0);
2092 if (IS_ERR(cc
->cipher_tfm
.tfms
[i
])) {
2093 err
= PTR_ERR(cc
->cipher_tfm
.tfms
[i
]);
2094 crypt_free_tfms(cc
);
2100 * dm-crypt performance can vary greatly depending on which crypto
2101 * algorithm implementation is used. Help people debug performance
2102 * problems by logging the ->cra_driver_name.
2104 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode
,
2105 crypto_skcipher_alg(any_tfm(cc
))->base
.cra_driver_name
);
2109 static int crypt_alloc_tfms_aead(struct crypt_config
*cc
, char *ciphermode
)
2113 cc
->cipher_tfm
.tfms
= kmalloc(sizeof(struct crypto_aead
*), GFP_KERNEL
);
2114 if (!cc
->cipher_tfm
.tfms
)
2117 cc
->cipher_tfm
.tfms_aead
[0] = crypto_alloc_aead(ciphermode
, 0, 0);
2118 if (IS_ERR(cc
->cipher_tfm
.tfms_aead
[0])) {
2119 err
= PTR_ERR(cc
->cipher_tfm
.tfms_aead
[0]);
2120 crypt_free_tfms(cc
);
2124 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode
,
2125 crypto_aead_alg(any_tfm_aead(cc
))->base
.cra_driver_name
);
2129 static int crypt_alloc_tfms(struct crypt_config
*cc
, char *ciphermode
)
2131 if (crypt_integrity_aead(cc
))
2132 return crypt_alloc_tfms_aead(cc
, ciphermode
);
2134 return crypt_alloc_tfms_skcipher(cc
, ciphermode
);
2137 static unsigned crypt_subkey_size(struct crypt_config
*cc
)
2139 return (cc
->key_size
- cc
->key_extra_size
) >> ilog2(cc
->tfms_count
);
2142 static unsigned crypt_authenckey_size(struct crypt_config
*cc
)
2144 return crypt_subkey_size(cc
) + RTA_SPACE(sizeof(struct crypto_authenc_key_param
));
2148 * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
2149 * the key must be for some reason in special format.
2150 * This funcion converts cc->key to this special format.
2152 static void crypt_copy_authenckey(char *p
, const void *key
,
2153 unsigned enckeylen
, unsigned authkeylen
)
2155 struct crypto_authenc_key_param
*param
;
2158 rta
= (struct rtattr
*)p
;
2159 param
= RTA_DATA(rta
);
2160 param
->enckeylen
= cpu_to_be32(enckeylen
);
2161 rta
->rta_len
= RTA_LENGTH(sizeof(*param
));
2162 rta
->rta_type
= CRYPTO_AUTHENC_KEYA_PARAM
;
2163 p
+= RTA_SPACE(sizeof(*param
));
2164 memcpy(p
, key
+ enckeylen
, authkeylen
);
2166 memcpy(p
, key
, enckeylen
);
2169 static int crypt_setkey(struct crypt_config
*cc
)
2171 unsigned subkey_size
;
2174 /* Ignore extra keys (which are used for IV etc) */
2175 subkey_size
= crypt_subkey_size(cc
);
2177 if (crypt_integrity_hmac(cc
)) {
2178 if (subkey_size
< cc
->key_mac_size
)
2181 crypt_copy_authenckey(cc
->authenc_key
, cc
->key
,
2182 subkey_size
- cc
->key_mac_size
,
2186 for (i
= 0; i
< cc
->tfms_count
; i
++) {
2187 if (crypt_integrity_hmac(cc
))
2188 r
= crypto_aead_setkey(cc
->cipher_tfm
.tfms_aead
[i
],
2189 cc
->authenc_key
, crypt_authenckey_size(cc
));
2190 else if (crypt_integrity_aead(cc
))
2191 r
= crypto_aead_setkey(cc
->cipher_tfm
.tfms_aead
[i
],
2192 cc
->key
+ (i
* subkey_size
),
2195 r
= crypto_skcipher_setkey(cc
->cipher_tfm
.tfms
[i
],
2196 cc
->key
+ (i
* subkey_size
),
2202 if (crypt_integrity_hmac(cc
))
2203 memzero_explicit(cc
->authenc_key
, crypt_authenckey_size(cc
));
2210 static bool contains_whitespace(const char *str
)
2213 if (isspace(*str
++))
2218 static int crypt_set_keyring_key(struct crypt_config
*cc
, const char *key_string
)
2220 char *new_key_string
, *key_desc
;
2223 const struct user_key_payload
*ukp
;
2226 * Reject key_string with whitespace. dm core currently lacks code for
2227 * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2229 if (contains_whitespace(key_string
)) {
2230 DMERR("whitespace chars not allowed in key string");
2234 /* look for next ':' separating key_type from key_description */
2235 key_desc
= strpbrk(key_string
, ":");
2236 if (!key_desc
|| key_desc
== key_string
|| !strlen(key_desc
+ 1))
2239 if (strncmp(key_string
, "logon:", key_desc
- key_string
+ 1) &&
2240 strncmp(key_string
, "user:", key_desc
- key_string
+ 1))
2243 new_key_string
= kstrdup(key_string
, GFP_KERNEL
);
2244 if (!new_key_string
)
2247 key
= request_key(key_string
[0] == 'l' ? &key_type_logon
: &key_type_user
,
2248 key_desc
+ 1, NULL
);
2250 kzfree(new_key_string
);
2251 return PTR_ERR(key
);
2254 down_read(&key
->sem
);
2256 ukp
= user_key_payload_locked(key
);
2260 kzfree(new_key_string
);
2261 return -EKEYREVOKED
;
2264 if (cc
->key_size
!= ukp
->datalen
) {
2267 kzfree(new_key_string
);
2271 memcpy(cc
->key
, ukp
->data
, cc
->key_size
);
2276 /* clear the flag since following operations may invalidate previously valid key */
2277 clear_bit(DM_CRYPT_KEY_VALID
, &cc
->flags
);
2279 ret
= crypt_setkey(cc
);
2282 set_bit(DM_CRYPT_KEY_VALID
, &cc
->flags
);
2283 kzfree(cc
->key_string
);
2284 cc
->key_string
= new_key_string
;
2286 kzfree(new_key_string
);
2291 static int get_key_size(char **key_string
)
2296 if (*key_string
[0] != ':')
2297 return strlen(*key_string
) >> 1;
2299 /* look for next ':' in key string */
2300 colon
= strpbrk(*key_string
+ 1, ":");
2304 if (sscanf(*key_string
+ 1, "%u%c", &ret
, &dummy
) != 2 || dummy
!= ':')
2307 *key_string
= colon
;
2309 /* remaining key string should be :<logon|user>:<key_desc> */
2316 static int crypt_set_keyring_key(struct crypt_config
*cc
, const char *key_string
)
2321 static int get_key_size(char **key_string
)
2323 return (*key_string
[0] == ':') ? -EINVAL
: strlen(*key_string
) >> 1;
2328 static int crypt_set_key(struct crypt_config
*cc
, char *key
)
2331 int key_string_len
= strlen(key
);
2333 /* Hyphen (which gives a key_size of zero) means there is no key. */
2334 if (!cc
->key_size
&& strcmp(key
, "-"))
2337 /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2338 if (key
[0] == ':') {
2339 r
= crypt_set_keyring_key(cc
, key
+ 1);
2343 /* clear the flag since following operations may invalidate previously valid key */
2344 clear_bit(DM_CRYPT_KEY_VALID
, &cc
->flags
);
2346 /* wipe references to any kernel keyring key */
2347 kzfree(cc
->key_string
);
2348 cc
->key_string
= NULL
;
2350 /* Decode key from its hex representation. */
2351 if (cc
->key_size
&& hex2bin(cc
->key
, key
, cc
->key_size
) < 0)
2354 r
= crypt_setkey(cc
);
2356 set_bit(DM_CRYPT_KEY_VALID
, &cc
->flags
);
2359 /* Hex key string not needed after here, so wipe it. */
2360 memset(key
, '0', key_string_len
);
2365 static int crypt_wipe_key(struct crypt_config
*cc
)
2369 clear_bit(DM_CRYPT_KEY_VALID
, &cc
->flags
);
2370 get_random_bytes(&cc
->key
, cc
->key_size
);
2372 /* Wipe IV private keys */
2373 if (cc
->iv_gen_ops
&& cc
->iv_gen_ops
->wipe
) {
2374 r
= cc
->iv_gen_ops
->wipe(cc
);
2379 kzfree(cc
->key_string
);
2380 cc
->key_string
= NULL
;
2381 r
= crypt_setkey(cc
);
2382 memset(&cc
->key
, 0, cc
->key_size
* sizeof(u8
));
2387 static void crypt_calculate_pages_per_client(void)
2389 unsigned long pages
= (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT
/ 100;
2391 if (!dm_crypt_clients_n
)
2394 pages
/= dm_crypt_clients_n
;
2395 if (pages
< DM_CRYPT_MIN_PAGES_PER_CLIENT
)
2396 pages
= DM_CRYPT_MIN_PAGES_PER_CLIENT
;
2397 dm_crypt_pages_per_client
= pages
;
2400 static void *crypt_page_alloc(gfp_t gfp_mask
, void *pool_data
)
2402 struct crypt_config
*cc
= pool_data
;
2405 if (unlikely(percpu_counter_compare(&cc
->n_allocated_pages
, dm_crypt_pages_per_client
) >= 0) &&
2406 likely(gfp_mask
& __GFP_NORETRY
))
2409 page
= alloc_page(gfp_mask
);
2410 if (likely(page
!= NULL
))
2411 percpu_counter_add(&cc
->n_allocated_pages
, 1);
2416 static void crypt_page_free(void *page
, void *pool_data
)
2418 struct crypt_config
*cc
= pool_data
;
2421 percpu_counter_sub(&cc
->n_allocated_pages
, 1);
2424 static void crypt_dtr(struct dm_target
*ti
)
2426 struct crypt_config
*cc
= ti
->private;
2433 if (cc
->write_thread
)
2434 kthread_stop(cc
->write_thread
);
2437 destroy_workqueue(cc
->io_queue
);
2438 if (cc
->crypt_queue
)
2439 destroy_workqueue(cc
->crypt_queue
);
2441 crypt_free_tfms(cc
);
2443 bioset_exit(&cc
->bs
);
2445 mempool_exit(&cc
->page_pool
);
2446 mempool_exit(&cc
->req_pool
);
2447 mempool_exit(&cc
->tag_pool
);
2449 WARN_ON(percpu_counter_sum(&cc
->n_allocated_pages
) != 0);
2450 percpu_counter_destroy(&cc
->n_allocated_pages
);
2452 if (cc
->iv_gen_ops
&& cc
->iv_gen_ops
->dtr
)
2453 cc
->iv_gen_ops
->dtr(cc
);
2456 dm_put_device(ti
, cc
->dev
);
2458 kzfree(cc
->cipher_string
);
2459 kzfree(cc
->key_string
);
2460 kzfree(cc
->cipher_auth
);
2461 kzfree(cc
->authenc_key
);
2463 mutex_destroy(&cc
->bio_alloc_lock
);
2465 /* Must zero key material before freeing */
2468 spin_lock(&dm_crypt_clients_lock
);
2469 WARN_ON(!dm_crypt_clients_n
);
2470 dm_crypt_clients_n
--;
2471 crypt_calculate_pages_per_client();
2472 spin_unlock(&dm_crypt_clients_lock
);
2475 static int crypt_ctr_ivmode(struct dm_target
*ti
, const char *ivmode
)
2477 struct crypt_config
*cc
= ti
->private;
2479 if (crypt_integrity_aead(cc
))
2480 cc
->iv_size
= crypto_aead_ivsize(any_tfm_aead(cc
));
2482 cc
->iv_size
= crypto_skcipher_ivsize(any_tfm(cc
));
2485 /* at least a 64 bit sector number should fit in our buffer */
2486 cc
->iv_size
= max(cc
->iv_size
,
2487 (unsigned int)(sizeof(u64
) / sizeof(u8
)));
2489 DMWARN("Selected cipher does not support IVs");
2493 /* Choose ivmode, see comments at iv code. */
2495 cc
->iv_gen_ops
= NULL
;
2496 else if (strcmp(ivmode
, "plain") == 0)
2497 cc
->iv_gen_ops
= &crypt_iv_plain_ops
;
2498 else if (strcmp(ivmode
, "plain64") == 0)
2499 cc
->iv_gen_ops
= &crypt_iv_plain64_ops
;
2500 else if (strcmp(ivmode
, "plain64be") == 0)
2501 cc
->iv_gen_ops
= &crypt_iv_plain64be_ops
;
2502 else if (strcmp(ivmode
, "essiv") == 0)
2503 cc
->iv_gen_ops
= &crypt_iv_essiv_ops
;
2504 else if (strcmp(ivmode
, "benbi") == 0)
2505 cc
->iv_gen_ops
= &crypt_iv_benbi_ops
;
2506 else if (strcmp(ivmode
, "null") == 0)
2507 cc
->iv_gen_ops
= &crypt_iv_null_ops
;
2508 else if (strcmp(ivmode
, "eboiv") == 0)
2509 cc
->iv_gen_ops
= &crypt_iv_eboiv_ops
;
2510 else if (strcmp(ivmode
, "elephant") == 0) {
2511 cc
->iv_gen_ops
= &crypt_iv_elephant_ops
;
2513 cc
->key_extra_size
= cc
->key_size
/ 2;
2514 if (cc
->key_extra_size
> ELEPHANT_MAX_KEY_SIZE
)
2516 set_bit(CRYPT_ENCRYPT_PREPROCESS
, &cc
->cipher_flags
);
2517 } else if (strcmp(ivmode
, "lmk") == 0) {
2518 cc
->iv_gen_ops
= &crypt_iv_lmk_ops
;
2520 * Version 2 and 3 is recognised according
2521 * to length of provided multi-key string.
2522 * If present (version 3), last key is used as IV seed.
2523 * All keys (including IV seed) are always the same size.
2525 if (cc
->key_size
% cc
->key_parts
) {
2527 cc
->key_extra_size
= cc
->key_size
/ cc
->key_parts
;
2529 } else if (strcmp(ivmode
, "tcw") == 0) {
2530 cc
->iv_gen_ops
= &crypt_iv_tcw_ops
;
2531 cc
->key_parts
+= 2; /* IV + whitening */
2532 cc
->key_extra_size
= cc
->iv_size
+ TCW_WHITENING_SIZE
;
2533 } else if (strcmp(ivmode
, "random") == 0) {
2534 cc
->iv_gen_ops
= &crypt_iv_random_ops
;
2535 /* Need storage space in integrity fields. */
2536 cc
->integrity_iv_size
= cc
->iv_size
;
2538 ti
->error
= "Invalid IV mode";
2546 * Workaround to parse HMAC algorithm from AEAD crypto API spec.
2547 * The HMAC is needed to calculate tag size (HMAC digest size).
2548 * This should be probably done by crypto-api calls (once available...)
2550 static int crypt_ctr_auth_cipher(struct crypt_config
*cc
, char *cipher_api
)
2552 char *start
, *end
, *mac_alg
= NULL
;
2553 struct crypto_ahash
*mac
;
2555 if (!strstarts(cipher_api
, "authenc("))
2558 start
= strchr(cipher_api
, '(');
2559 end
= strchr(cipher_api
, ',');
2560 if (!start
|| !end
|| ++start
> end
)
2563 mac_alg
= kzalloc(end
- start
+ 1, GFP_KERNEL
);
2566 strncpy(mac_alg
, start
, end
- start
);
2568 mac
= crypto_alloc_ahash(mac_alg
, 0, 0);
2572 return PTR_ERR(mac
);
2574 cc
->key_mac_size
= crypto_ahash_digestsize(mac
);
2575 crypto_free_ahash(mac
);
2577 cc
->authenc_key
= kmalloc(crypt_authenckey_size(cc
), GFP_KERNEL
);
2578 if (!cc
->authenc_key
)
2584 static int crypt_ctr_cipher_new(struct dm_target
*ti
, char *cipher_in
, char *key
,
2585 char **ivmode
, char **ivopts
)
2587 struct crypt_config
*cc
= ti
->private;
2588 char *tmp
, *cipher_api
, buf
[CRYPTO_MAX_ALG_NAME
];
2594 * New format (capi: prefix)
2595 * capi:cipher_api_spec-iv:ivopts
2597 tmp
= &cipher_in
[strlen("capi:")];
2599 /* Separate IV options if present, it can contain another '-' in hash name */
2600 *ivopts
= strrchr(tmp
, ':');
2606 *ivmode
= strrchr(tmp
, '-');
2611 /* The rest is crypto API spec */
2614 /* Alloc AEAD, can be used only in new format. */
2615 if (crypt_integrity_aead(cc
)) {
2616 ret
= crypt_ctr_auth_cipher(cc
, cipher_api
);
2618 ti
->error
= "Invalid AEAD cipher spec";
2623 if (*ivmode
&& !strcmp(*ivmode
, "lmk"))
2624 cc
->tfms_count
= 64;
2626 if (*ivmode
&& !strcmp(*ivmode
, "essiv")) {
2628 ti
->error
= "Digest algorithm missing for ESSIV mode";
2631 ret
= snprintf(buf
, CRYPTO_MAX_ALG_NAME
, "essiv(%s,%s)",
2632 cipher_api
, *ivopts
);
2633 if (ret
< 0 || ret
>= CRYPTO_MAX_ALG_NAME
) {
2634 ti
->error
= "Cannot allocate cipher string";
2640 cc
->key_parts
= cc
->tfms_count
;
2642 /* Allocate cipher */
2643 ret
= crypt_alloc_tfms(cc
, cipher_api
);
2645 ti
->error
= "Error allocating crypto tfm";
2649 if (crypt_integrity_aead(cc
))
2650 cc
->iv_size
= crypto_aead_ivsize(any_tfm_aead(cc
));
2652 cc
->iv_size
= crypto_skcipher_ivsize(any_tfm(cc
));
2657 static int crypt_ctr_cipher_old(struct dm_target
*ti
, char *cipher_in
, char *key
,
2658 char **ivmode
, char **ivopts
)
2660 struct crypt_config
*cc
= ti
->private;
2661 char *tmp
, *cipher
, *chainmode
, *keycount
;
2662 char *cipher_api
= NULL
;
2666 if (strchr(cipher_in
, '(') || crypt_integrity_aead(cc
)) {
2667 ti
->error
= "Bad cipher specification";
2672 * Legacy dm-crypt cipher specification
2673 * cipher[:keycount]-mode-iv:ivopts
2676 keycount
= strsep(&tmp
, "-");
2677 cipher
= strsep(&keycount
, ":");
2681 else if (sscanf(keycount
, "%u%c", &cc
->tfms_count
, &dummy
) != 1 ||
2682 !is_power_of_2(cc
->tfms_count
)) {
2683 ti
->error
= "Bad cipher key count specification";
2686 cc
->key_parts
= cc
->tfms_count
;
2688 chainmode
= strsep(&tmp
, "-");
2689 *ivmode
= strsep(&tmp
, ":");
2693 * For compatibility with the original dm-crypt mapping format, if
2694 * only the cipher name is supplied, use cbc-plain.
2696 if (!chainmode
|| (!strcmp(chainmode
, "plain") && !*ivmode
)) {
2701 if (strcmp(chainmode
, "ecb") && !*ivmode
) {
2702 ti
->error
= "IV mechanism required";
2706 cipher_api
= kmalloc(CRYPTO_MAX_ALG_NAME
, GFP_KERNEL
);
2710 if (*ivmode
&& !strcmp(*ivmode
, "essiv")) {
2712 ti
->error
= "Digest algorithm missing for ESSIV mode";
2716 ret
= snprintf(cipher_api
, CRYPTO_MAX_ALG_NAME
,
2717 "essiv(%s(%s),%s)", chainmode
, cipher
, *ivopts
);
2719 ret
= snprintf(cipher_api
, CRYPTO_MAX_ALG_NAME
,
2720 "%s(%s)", chainmode
, cipher
);
2722 if (ret
< 0 || ret
>= CRYPTO_MAX_ALG_NAME
) {
2727 /* Allocate cipher */
2728 ret
= crypt_alloc_tfms(cc
, cipher_api
);
2730 ti
->error
= "Error allocating crypto tfm";
2738 ti
->error
= "Cannot allocate cipher strings";
2742 static int crypt_ctr_cipher(struct dm_target
*ti
, char *cipher_in
, char *key
)
2744 struct crypt_config
*cc
= ti
->private;
2745 char *ivmode
= NULL
, *ivopts
= NULL
;
2748 cc
->cipher_string
= kstrdup(cipher_in
, GFP_KERNEL
);
2749 if (!cc
->cipher_string
) {
2750 ti
->error
= "Cannot allocate cipher strings";
2754 if (strstarts(cipher_in
, "capi:"))
2755 ret
= crypt_ctr_cipher_new(ti
, cipher_in
, key
, &ivmode
, &ivopts
);
2757 ret
= crypt_ctr_cipher_old(ti
, cipher_in
, key
, &ivmode
, &ivopts
);
2762 ret
= crypt_ctr_ivmode(ti
, ivmode
);
2766 /* Initialize and set key */
2767 ret
= crypt_set_key(cc
, key
);
2769 ti
->error
= "Error decoding and setting key";
2774 if (cc
->iv_gen_ops
&& cc
->iv_gen_ops
->ctr
) {
2775 ret
= cc
->iv_gen_ops
->ctr(cc
, ti
, ivopts
);
2777 ti
->error
= "Error creating IV";
2782 /* Initialize IV (set keys for ESSIV etc) */
2783 if (cc
->iv_gen_ops
&& cc
->iv_gen_ops
->init
) {
2784 ret
= cc
->iv_gen_ops
->init(cc
);
2786 ti
->error
= "Error initialising IV";
2791 /* wipe the kernel key payload copy */
2793 memset(cc
->key
, 0, cc
->key_size
* sizeof(u8
));
2798 static int crypt_ctr_optional(struct dm_target
*ti
, unsigned int argc
, char **argv
)
2800 struct crypt_config
*cc
= ti
->private;
2801 struct dm_arg_set as
;
2802 static const struct dm_arg _args
[] = {
2803 {0, 6, "Invalid number of feature args"},
2805 unsigned int opt_params
, val
;
2806 const char *opt_string
, *sval
;
2810 /* Optional parameters */
2814 ret
= dm_read_arg_group(_args
, &as
, &opt_params
, &ti
->error
);
2818 while (opt_params
--) {
2819 opt_string
= dm_shift_arg(&as
);
2821 ti
->error
= "Not enough feature arguments";
2825 if (!strcasecmp(opt_string
, "allow_discards"))
2826 ti
->num_discard_bios
= 1;
2828 else if (!strcasecmp(opt_string
, "same_cpu_crypt"))
2829 set_bit(DM_CRYPT_SAME_CPU
, &cc
->flags
);
2831 else if (!strcasecmp(opt_string
, "submit_from_crypt_cpus"))
2832 set_bit(DM_CRYPT_NO_OFFLOAD
, &cc
->flags
);
2833 else if (sscanf(opt_string
, "integrity:%u:", &val
) == 1) {
2834 if (val
== 0 || val
> MAX_TAG_SIZE
) {
2835 ti
->error
= "Invalid integrity arguments";
2838 cc
->on_disk_tag_size
= val
;
2839 sval
= strchr(opt_string
+ strlen("integrity:"), ':') + 1;
2840 if (!strcasecmp(sval
, "aead")) {
2841 set_bit(CRYPT_MODE_INTEGRITY_AEAD
, &cc
->cipher_flags
);
2842 } else if (strcasecmp(sval
, "none")) {
2843 ti
->error
= "Unknown integrity profile";
2847 cc
->cipher_auth
= kstrdup(sval
, GFP_KERNEL
);
2848 if (!cc
->cipher_auth
)
2850 } else if (sscanf(opt_string
, "sector_size:%hu%c", &cc
->sector_size
, &dummy
) == 1) {
2851 if (cc
->sector_size
< (1 << SECTOR_SHIFT
) ||
2852 cc
->sector_size
> 4096 ||
2853 (cc
->sector_size
& (cc
->sector_size
- 1))) {
2854 ti
->error
= "Invalid feature value for sector_size";
2857 if (ti
->len
& ((cc
->sector_size
>> SECTOR_SHIFT
) - 1)) {
2858 ti
->error
= "Device size is not multiple of sector_size feature";
2861 cc
->sector_shift
= __ffs(cc
->sector_size
) - SECTOR_SHIFT
;
2862 } else if (!strcasecmp(opt_string
, "iv_large_sectors"))
2863 set_bit(CRYPT_IV_LARGE_SECTORS
, &cc
->cipher_flags
);
2865 ti
->error
= "Invalid feature arguments";
2874 * Construct an encryption mapping:
2875 * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
2877 static int crypt_ctr(struct dm_target
*ti
, unsigned int argc
, char **argv
)
2879 struct crypt_config
*cc
;
2880 const char *devname
= dm_table_device_name(ti
->table
);
2882 unsigned int align_mask
;
2883 unsigned long long tmpll
;
2885 size_t iv_size_padding
, additional_req_size
;
2889 ti
->error
= "Not enough arguments";
2893 key_size
= get_key_size(&argv
[1]);
2895 ti
->error
= "Cannot parse key size";
2899 cc
= kzalloc(struct_size(cc
, key
, key_size
), GFP_KERNEL
);
2901 ti
->error
= "Cannot allocate encryption context";
2904 cc
->key_size
= key_size
;
2905 cc
->sector_size
= (1 << SECTOR_SHIFT
);
2906 cc
->sector_shift
= 0;
2910 spin_lock(&dm_crypt_clients_lock
);
2911 dm_crypt_clients_n
++;
2912 crypt_calculate_pages_per_client();
2913 spin_unlock(&dm_crypt_clients_lock
);
2915 ret
= percpu_counter_init(&cc
->n_allocated_pages
, 0, GFP_KERNEL
);
2919 /* Optional parameters need to be read before cipher constructor */
2921 ret
= crypt_ctr_optional(ti
, argc
- 5, &argv
[5]);
2926 ret
= crypt_ctr_cipher(ti
, argv
[0], argv
[1]);
2930 if (crypt_integrity_aead(cc
)) {
2931 cc
->dmreq_start
= sizeof(struct aead_request
);
2932 cc
->dmreq_start
+= crypto_aead_reqsize(any_tfm_aead(cc
));
2933 align_mask
= crypto_aead_alignmask(any_tfm_aead(cc
));
2935 cc
->dmreq_start
= sizeof(struct skcipher_request
);
2936 cc
->dmreq_start
+= crypto_skcipher_reqsize(any_tfm(cc
));
2937 align_mask
= crypto_skcipher_alignmask(any_tfm(cc
));
2939 cc
->dmreq_start
= ALIGN(cc
->dmreq_start
, __alignof__(struct dm_crypt_request
));
2941 if (align_mask
< CRYPTO_MINALIGN
) {
2942 /* Allocate the padding exactly */
2943 iv_size_padding
= -(cc
->dmreq_start
+ sizeof(struct dm_crypt_request
))
2947 * If the cipher requires greater alignment than kmalloc
2948 * alignment, we don't know the exact position of the
2949 * initialization vector. We must assume worst case.
2951 iv_size_padding
= align_mask
;
2954 /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
2955 additional_req_size
= sizeof(struct dm_crypt_request
) +
2956 iv_size_padding
+ cc
->iv_size
+
2959 sizeof(unsigned int);
2961 ret
= mempool_init_kmalloc_pool(&cc
->req_pool
, MIN_IOS
, cc
->dmreq_start
+ additional_req_size
);
2963 ti
->error
= "Cannot allocate crypt request mempool";
2967 cc
->per_bio_data_size
= ti
->per_io_data_size
=
2968 ALIGN(sizeof(struct dm_crypt_io
) + cc
->dmreq_start
+ additional_req_size
,
2969 ARCH_KMALLOC_MINALIGN
);
2971 ret
= mempool_init(&cc
->page_pool
, BIO_MAX_PAGES
, crypt_page_alloc
, crypt_page_free
, cc
);
2973 ti
->error
= "Cannot allocate page mempool";
2977 ret
= bioset_init(&cc
->bs
, MIN_IOS
, 0, BIOSET_NEED_BVECS
);
2979 ti
->error
= "Cannot allocate crypt bioset";
2983 mutex_init(&cc
->bio_alloc_lock
);
2986 if ((sscanf(argv
[2], "%llu%c", &tmpll
, &dummy
) != 1) ||
2987 (tmpll
& ((cc
->sector_size
>> SECTOR_SHIFT
) - 1))) {
2988 ti
->error
= "Invalid iv_offset sector";
2991 cc
->iv_offset
= tmpll
;
2993 ret
= dm_get_device(ti
, argv
[3], dm_table_get_mode(ti
->table
), &cc
->dev
);
2995 ti
->error
= "Device lookup failed";
3000 if (sscanf(argv
[4], "%llu%c", &tmpll
, &dummy
) != 1 || tmpll
!= (sector_t
)tmpll
) {
3001 ti
->error
= "Invalid device sector";
3006 if (crypt_integrity_aead(cc
) || cc
->integrity_iv_size
) {
3007 ret
= crypt_integrity_ctr(cc
, ti
);
3011 cc
->tag_pool_max_sectors
= POOL_ENTRY_SIZE
/ cc
->on_disk_tag_size
;
3012 if (!cc
->tag_pool_max_sectors
)
3013 cc
->tag_pool_max_sectors
= 1;
3015 ret
= mempool_init_kmalloc_pool(&cc
->tag_pool
, MIN_IOS
,
3016 cc
->tag_pool_max_sectors
* cc
->on_disk_tag_size
);
3018 ti
->error
= "Cannot allocate integrity tags mempool";
3022 cc
->tag_pool_max_sectors
<<= cc
->sector_shift
;
3026 cc
->io_queue
= alloc_workqueue("kcryptd_io/%s", WQ_MEM_RECLAIM
, 1, devname
);
3027 if (!cc
->io_queue
) {
3028 ti
->error
= "Couldn't create kcryptd io queue";
3032 if (test_bit(DM_CRYPT_SAME_CPU
, &cc
->flags
))
3033 cc
->crypt_queue
= alloc_workqueue("kcryptd/%s", WQ_CPU_INTENSIVE
| WQ_MEM_RECLAIM
,
3036 cc
->crypt_queue
= alloc_workqueue("kcryptd/%s",
3037 WQ_CPU_INTENSIVE
| WQ_MEM_RECLAIM
| WQ_UNBOUND
,
3038 num_online_cpus(), devname
);
3039 if (!cc
->crypt_queue
) {
3040 ti
->error
= "Couldn't create kcryptd queue";
3044 spin_lock_init(&cc
->write_thread_lock
);
3045 cc
->write_tree
= RB_ROOT
;
3047 cc
->write_thread
= kthread_create(dmcrypt_write
, cc
, "dmcrypt_write/%s", devname
);
3048 if (IS_ERR(cc
->write_thread
)) {
3049 ret
= PTR_ERR(cc
->write_thread
);
3050 cc
->write_thread
= NULL
;
3051 ti
->error
= "Couldn't spawn write thread";
3054 wake_up_process(cc
->write_thread
);
3056 ti
->num_flush_bios
= 1;
3065 static int crypt_map(struct dm_target
*ti
, struct bio
*bio
)
3067 struct dm_crypt_io
*io
;
3068 struct crypt_config
*cc
= ti
->private;
3071 * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
3072 * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
3073 * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
3075 if (unlikely(bio
->bi_opf
& REQ_PREFLUSH
||
3076 bio_op(bio
) == REQ_OP_DISCARD
)) {
3077 bio_set_dev(bio
, cc
->dev
->bdev
);
3078 if (bio_sectors(bio
))
3079 bio
->bi_iter
.bi_sector
= cc
->start
+
3080 dm_target_offset(ti
, bio
->bi_iter
.bi_sector
);
3081 return DM_MAPIO_REMAPPED
;
3085 * Check if bio is too large, split as needed.
3087 if (unlikely(bio
->bi_iter
.bi_size
> (BIO_MAX_PAGES
<< PAGE_SHIFT
)) &&
3088 (bio_data_dir(bio
) == WRITE
|| cc
->on_disk_tag_size
))
3089 dm_accept_partial_bio(bio
, ((BIO_MAX_PAGES
<< PAGE_SHIFT
) >> SECTOR_SHIFT
));
3092 * Ensure that bio is a multiple of internal sector encryption size
3093 * and is aligned to this size as defined in IO hints.
3095 if (unlikely((bio
->bi_iter
.bi_sector
& ((cc
->sector_size
>> SECTOR_SHIFT
) - 1)) != 0))
3096 return DM_MAPIO_KILL
;
3098 if (unlikely(bio
->bi_iter
.bi_size
& (cc
->sector_size
- 1)))
3099 return DM_MAPIO_KILL
;
3101 io
= dm_per_bio_data(bio
, cc
->per_bio_data_size
);
3102 crypt_io_init(io
, cc
, bio
, dm_target_offset(ti
, bio
->bi_iter
.bi_sector
));
3104 if (cc
->on_disk_tag_size
) {
3105 unsigned tag_len
= cc
->on_disk_tag_size
* (bio_sectors(bio
) >> cc
->sector_shift
);
3107 if (unlikely(tag_len
> KMALLOC_MAX_SIZE
) ||
3108 unlikely(!(io
->integrity_metadata
= kmalloc(tag_len
,
3109 GFP_NOIO
| __GFP_NORETRY
| __GFP_NOMEMALLOC
| __GFP_NOWARN
)))) {
3110 if (bio_sectors(bio
) > cc
->tag_pool_max_sectors
)
3111 dm_accept_partial_bio(bio
, cc
->tag_pool_max_sectors
);
3112 io
->integrity_metadata
= mempool_alloc(&cc
->tag_pool
, GFP_NOIO
);
3113 io
->integrity_metadata_from_pool
= true;
3117 if (crypt_integrity_aead(cc
))
3118 io
->ctx
.r
.req_aead
= (struct aead_request
*)(io
+ 1);
3120 io
->ctx
.r
.req
= (struct skcipher_request
*)(io
+ 1);
3122 if (bio_data_dir(io
->base_bio
) == READ
) {
3123 if (kcryptd_io_read(io
, GFP_NOWAIT
))
3124 kcryptd_queue_read(io
);
3126 kcryptd_queue_crypt(io
);
3128 return DM_MAPIO_SUBMITTED
;
3131 static void crypt_status(struct dm_target
*ti
, status_type_t type
,
3132 unsigned status_flags
, char *result
, unsigned maxlen
)
3134 struct crypt_config
*cc
= ti
->private;
3136 int num_feature_args
= 0;
3139 case STATUSTYPE_INFO
:
3143 case STATUSTYPE_TABLE
:
3144 DMEMIT("%s ", cc
->cipher_string
);
3146 if (cc
->key_size
> 0) {
3148 DMEMIT(":%u:%s", cc
->key_size
, cc
->key_string
);
3150 for (i
= 0; i
< cc
->key_size
; i
++)
3151 DMEMIT("%02x", cc
->key
[i
]);
3155 DMEMIT(" %llu %s %llu", (unsigned long long)cc
->iv_offset
,
3156 cc
->dev
->name
, (unsigned long long)cc
->start
);
3158 num_feature_args
+= !!ti
->num_discard_bios
;
3159 num_feature_args
+= test_bit(DM_CRYPT_SAME_CPU
, &cc
->flags
);
3160 num_feature_args
+= test_bit(DM_CRYPT_NO_OFFLOAD
, &cc
->flags
);
3161 num_feature_args
+= cc
->sector_size
!= (1 << SECTOR_SHIFT
);
3162 num_feature_args
+= test_bit(CRYPT_IV_LARGE_SECTORS
, &cc
->cipher_flags
);
3163 if (cc
->on_disk_tag_size
)
3165 if (num_feature_args
) {
3166 DMEMIT(" %d", num_feature_args
);
3167 if (ti
->num_discard_bios
)
3168 DMEMIT(" allow_discards");
3169 if (test_bit(DM_CRYPT_SAME_CPU
, &cc
->flags
))
3170 DMEMIT(" same_cpu_crypt");
3171 if (test_bit(DM_CRYPT_NO_OFFLOAD
, &cc
->flags
))
3172 DMEMIT(" submit_from_crypt_cpus");
3173 if (cc
->on_disk_tag_size
)
3174 DMEMIT(" integrity:%u:%s", cc
->on_disk_tag_size
, cc
->cipher_auth
);
3175 if (cc
->sector_size
!= (1 << SECTOR_SHIFT
))
3176 DMEMIT(" sector_size:%d", cc
->sector_size
);
3177 if (test_bit(CRYPT_IV_LARGE_SECTORS
, &cc
->cipher_flags
))
3178 DMEMIT(" iv_large_sectors");
3185 static void crypt_postsuspend(struct dm_target
*ti
)
3187 struct crypt_config
*cc
= ti
->private;
3189 set_bit(DM_CRYPT_SUSPENDED
, &cc
->flags
);
3192 static int crypt_preresume(struct dm_target
*ti
)
3194 struct crypt_config
*cc
= ti
->private;
3196 if (!test_bit(DM_CRYPT_KEY_VALID
, &cc
->flags
)) {
3197 DMERR("aborting resume - crypt key is not set.");
3204 static void crypt_resume(struct dm_target
*ti
)
3206 struct crypt_config
*cc
= ti
->private;
3208 clear_bit(DM_CRYPT_SUSPENDED
, &cc
->flags
);
3211 /* Message interface
3215 static int crypt_message(struct dm_target
*ti
, unsigned argc
, char **argv
,
3216 char *result
, unsigned maxlen
)
3218 struct crypt_config
*cc
= ti
->private;
3219 int key_size
, ret
= -EINVAL
;
3224 if (!strcasecmp(argv
[0], "key")) {
3225 if (!test_bit(DM_CRYPT_SUSPENDED
, &cc
->flags
)) {
3226 DMWARN("not suspended during key manipulation.");
3229 if (argc
== 3 && !strcasecmp(argv
[1], "set")) {
3230 /* The key size may not be changed. */
3231 key_size
= get_key_size(&argv
[2]);
3232 if (key_size
< 0 || cc
->key_size
!= key_size
) {
3233 memset(argv
[2], '0', strlen(argv
[2]));
3237 ret
= crypt_set_key(cc
, argv
[2]);
3240 if (cc
->iv_gen_ops
&& cc
->iv_gen_ops
->init
)
3241 ret
= cc
->iv_gen_ops
->init(cc
);
3242 /* wipe the kernel key payload copy */
3244 memset(cc
->key
, 0, cc
->key_size
* sizeof(u8
));
3247 if (argc
== 2 && !strcasecmp(argv
[1], "wipe"))
3248 return crypt_wipe_key(cc
);
3252 DMWARN("unrecognised message received.");
3256 static int crypt_iterate_devices(struct dm_target
*ti
,
3257 iterate_devices_callout_fn fn
, void *data
)
3259 struct crypt_config
*cc
= ti
->private;
3261 return fn(ti
, cc
->dev
, cc
->start
, ti
->len
, data
);
3264 static void crypt_io_hints(struct dm_target
*ti
, struct queue_limits
*limits
)
3266 struct crypt_config
*cc
= ti
->private;
3269 * Unfortunate constraint that is required to avoid the potential
3270 * for exceeding underlying device's max_segments limits -- due to
3271 * crypt_alloc_buffer() possibly allocating pages for the encryption
3272 * bio that are not as physically contiguous as the original bio.
3274 limits
->max_segment_size
= PAGE_SIZE
;
3276 limits
->logical_block_size
=
3277 max_t(unsigned short, limits
->logical_block_size
, cc
->sector_size
);
3278 limits
->physical_block_size
=
3279 max_t(unsigned, limits
->physical_block_size
, cc
->sector_size
);
3280 limits
->io_min
= max_t(unsigned, limits
->io_min
, cc
->sector_size
);
3283 static struct target_type crypt_target
= {
3285 .version
= {1, 20, 0},
3286 .module
= THIS_MODULE
,
3290 .status
= crypt_status
,
3291 .postsuspend
= crypt_postsuspend
,
3292 .preresume
= crypt_preresume
,
3293 .resume
= crypt_resume
,
3294 .message
= crypt_message
,
3295 .iterate_devices
= crypt_iterate_devices
,
3296 .io_hints
= crypt_io_hints
,
3299 static int __init
dm_crypt_init(void)
3303 r
= dm_register_target(&crypt_target
);
3305 DMERR("register failed %d", r
);
3310 static void __exit
dm_crypt_exit(void)
3312 dm_unregister_target(&crypt_target
);
3315 module_init(dm_crypt_init
);
3316 module_exit(dm_crypt_exit
);
3318 MODULE_AUTHOR("Jana Saout <jana@saout.de>");
3319 MODULE_DESCRIPTION(DM_NAME
" target for transparent encryption / decryption");
3320 MODULE_LICENSE("GPL");