blob: 6866aa2aade3bdf89877d57f604d92351703741b [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001/*
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>
6 *
7 * This file is released under the GPL.
8 */
9
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>
28#include <asm/page.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>
38
39#include <linux/device-mapper.h>
40
41#define DM_MSG_PREFIX "crypt"
42
43/*
44 * context holding the current state of a multi-part conversion
45 */
46struct convert_context {
47 struct completion restart;
48 struct bio *bio_in;
49 struct bvec_iter iter_in;
50 struct bio *bio_out;
51 struct bvec_iter iter_out;
52 atomic_t cc_pending;
53 u64 cc_sector;
54 union {
55 struct skcipher_request *req;
56 struct aead_request *req_aead;
57 } r;
58
59};
60
61/*
62 * per bio private data
63 */
64struct dm_crypt_io {
65 struct crypt_config *cc;
66 struct bio *base_bio;
67 u8 *integrity_metadata;
68 bool integrity_metadata_from_pool;
69 struct work_struct work;
70
71 struct convert_context ctx;
72
73 atomic_t io_pending;
74 blk_status_t error;
75 sector_t sector;
76
77 struct rb_node rb_node;
78} CRYPTO_MINALIGN_ATTR;
79
80struct dm_crypt_request {
81 struct convert_context *ctx;
82 struct scatterlist sg_in[4];
83 struct scatterlist sg_out[4];
84 u64 iv_sector;
85};
86
87struct crypt_config;
88
89struct crypt_iv_operations {
90 int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
91 const char *opts);
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);
99};
100
101struct iv_benbi_private {
102 int shift;
103};
104
105#define LMK_SEED_SIZE 64 /* hash + 0 */
106struct iv_lmk_private {
107 struct crypto_shash *hash_tfm;
108 u8 *seed;
109};
110
111#define TCW_WHITENING_SIZE 16
112struct iv_tcw_private {
113 struct crypto_shash *crc32_tfm;
114 u8 *iv_seed;
115 u8 *whitening;
116};
117
118/*
119 * Crypt: maps a linear range of a block device
120 * and encrypts / decrypts at the same time.
121 */
122enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
123 DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD };
124
125enum cipher_flags {
126 CRYPT_MODE_INTEGRITY_AEAD, /* Use authenticated mode for cihper */
127 CRYPT_IV_LARGE_SECTORS, /* Calculate IV from sector_size, not 512B sectors */
128};
129
130/*
131 * The fields in here must be read only after initialization.
132 */
133struct crypt_config {
134 struct dm_dev *dev;
135 sector_t start;
136
137 struct percpu_counter n_allocated_pages;
138
139 struct workqueue_struct *io_queue;
140 struct workqueue_struct *crypt_queue;
141
142 spinlock_t write_thread_lock;
143 struct task_struct *write_thread;
144 struct rb_root write_tree;
145
146 char *cipher_string;
147 char *cipher_auth;
148 char *key_string;
149
150 const struct crypt_iv_operations *iv_gen_ops;
151 union {
152 struct iv_benbi_private benbi;
153 struct iv_lmk_private lmk;
154 struct iv_tcw_private tcw;
155 } iv_gen_private;
156 u64 iv_offset;
157 unsigned int iv_size;
158 unsigned short int sector_size;
159 unsigned char sector_shift;
160
161 union {
162 struct crypto_skcipher **tfms;
163 struct crypto_aead **tfms_aead;
164 } cipher_tfm;
165 unsigned tfms_count;
166 unsigned long cipher_flags;
167
168 /*
169 * Layout of each crypto request:
170 *
171 * struct skcipher_request
172 * context
173 * padding
174 * struct dm_crypt_request
175 * padding
176 * IV
177 *
178 * The padding is added so that dm_crypt_request and the IV are
179 * correctly aligned.
180 */
181 unsigned int dmreq_start;
182
183 unsigned int per_bio_data_size;
184
185 unsigned long flags;
186 unsigned int key_size;
187 unsigned int key_parts; /* independent parts in key buffer */
188 unsigned int key_extra_size; /* additional keys length */
189 unsigned int key_mac_size; /* MAC key size for authenc(...) */
190
191 unsigned int integrity_tag_size;
192 unsigned int integrity_iv_size;
193 unsigned int on_disk_tag_size;
194
195 /*
196 * pool for per bio private data, crypto requests,
197 * encryption requeusts/buffer pages and integrity tags
198 */
199 unsigned tag_pool_max_sectors;
200 mempool_t tag_pool;
201 mempool_t req_pool;
202 mempool_t page_pool;
203
204 struct bio_set bs;
205 struct mutex bio_alloc_lock;
206
207 u8 *authenc_key; /* space for keys in authenc() format (if used) */
208 u8 key[0];
209};
210
211#define MIN_IOS 64
212#define MAX_TAG_SIZE 480
213#define POOL_ENTRY_SIZE 512
214
215static DEFINE_SPINLOCK(dm_crypt_clients_lock);
216static unsigned dm_crypt_clients_n = 0;
217static volatile unsigned long dm_crypt_pages_per_client;
218#define DM_CRYPT_MEMORY_PERCENT 2
219#define DM_CRYPT_MIN_PAGES_PER_CLIENT (BIO_MAX_PAGES * 16)
220
221static void clone_init(struct dm_crypt_io *, struct bio *);
222static void kcryptd_queue_crypt(struct dm_crypt_io *io);
223static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
224 struct scatterlist *sg);
225
226/*
227 * Use this to access cipher attributes that are independent of the key.
228 */
229static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
230{
231 return cc->cipher_tfm.tfms[0];
232}
233
234static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
235{
236 return cc->cipher_tfm.tfms_aead[0];
237}
238
239/*
240 * Different IV generation algorithms:
241 *
242 * plain: the initial vector is the 32-bit little-endian version of the sector
243 * number, padded with zeros if necessary.
244 *
245 * plain64: the initial vector is the 64-bit little-endian version of the sector
246 * number, padded with zeros if necessary.
247 *
248 * plain64be: the initial vector is the 64-bit big-endian version of the sector
249 * number, padded with zeros if necessary.
250 *
251 * essiv: "encrypted sector|salt initial vector", the sector number is
252 * encrypted with the bulk cipher using a salt as key. The salt
253 * should be derived from the bulk cipher's key via hashing.
254 *
255 * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
256 * (needed for LRW-32-AES and possible other narrow block modes)
257 *
258 * null: the initial vector is always zero. Provides compatibility with
259 * obsolete loop_fish2 devices. Do not use for new devices.
260 *
261 * lmk: Compatible implementation of the block chaining mode used
262 * by the Loop-AES block device encryption system
263 * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
264 * It operates on full 512 byte sectors and uses CBC
265 * with an IV derived from the sector number, the data and
266 * optionally extra IV seed.
267 * This means that after decryption the first block
268 * of sector must be tweaked according to decrypted data.
269 * Loop-AES can use three encryption schemes:
270 * version 1: is plain aes-cbc mode
271 * version 2: uses 64 multikey scheme with lmk IV generator
272 * version 3: the same as version 2 with additional IV seed
273 * (it uses 65 keys, last key is used as IV seed)
274 *
275 * tcw: Compatible implementation of the block chaining mode used
276 * by the TrueCrypt device encryption system (prior to version 4.1).
277 * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
278 * It operates on full 512 byte sectors and uses CBC
279 * with an IV derived from initial key and the sector number.
280 * In addition, whitening value is applied on every sector, whitening
281 * is calculated from initial key, sector number and mixed using CRC32.
282 * Note that this encryption scheme is vulnerable to watermarking attacks
283 * and should be used for old compatible containers access only.
284 *
285 * eboiv: Encrypted byte-offset IV (used in Bitlocker in CBC mode)
286 * The IV is encrypted little-endian byte-offset (with the same key
287 * and cipher as the volume).
288 */
289
290static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
291 struct dm_crypt_request *dmreq)
292{
293 memset(iv, 0, cc->iv_size);
294 *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
295
296 return 0;
297}
298
299static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
300 struct dm_crypt_request *dmreq)
301{
302 memset(iv, 0, cc->iv_size);
303 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
304
305 return 0;
306}
307
308static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
309 struct dm_crypt_request *dmreq)
310{
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);
314
315 return 0;
316}
317
318static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
319 struct dm_crypt_request *dmreq)
320{
321 /*
322 * ESSIV encryption of the IV is now handled by the crypto API,
323 * so just pass the plain sector number here.
324 */
325 memset(iv, 0, cc->iv_size);
326 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
327
328 return 0;
329}
330
331static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
332 const char *opts)
333{
334 unsigned bs;
335 int log;
336
337 if (test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags))
338 bs = crypto_aead_blocksize(any_tfm_aead(cc));
339 else
340 bs = crypto_skcipher_blocksize(any_tfm(cc));
341 log = ilog2(bs);
342
343 /* we need to calculate how far we must shift the sector count
344 * to get the cipher block count, we use this shift in _gen */
345
346 if (1 << log != bs) {
347 ti->error = "cypher blocksize is not a power of 2";
348 return -EINVAL;
349 }
350
351 if (log > 9) {
352 ti->error = "cypher blocksize is > 512";
353 return -EINVAL;
354 }
355
356 cc->iv_gen_private.benbi.shift = 9 - log;
357
358 return 0;
359}
360
361static void crypt_iv_benbi_dtr(struct crypt_config *cc)
362{
363}
364
365static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
366 struct dm_crypt_request *dmreq)
367{
368 __be64 val;
369
370 memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
371
372 val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
373 put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
374
375 return 0;
376}
377
378static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
379 struct dm_crypt_request *dmreq)
380{
381 memset(iv, 0, cc->iv_size);
382
383 return 0;
384}
385
386static void crypt_iv_lmk_dtr(struct crypt_config *cc)
387{
388 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
389
390 if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
391 crypto_free_shash(lmk->hash_tfm);
392 lmk->hash_tfm = NULL;
393
394 kzfree(lmk->seed);
395 lmk->seed = NULL;
396}
397
398static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
399 const char *opts)
400{
401 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
402
403 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
404 ti->error = "Unsupported sector size for LMK";
405 return -EINVAL;
406 }
407
408 lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
409 if (IS_ERR(lmk->hash_tfm)) {
410 ti->error = "Error initializing LMK hash";
411 return PTR_ERR(lmk->hash_tfm);
412 }
413
414 /* No seed in LMK version 2 */
415 if (cc->key_parts == cc->tfms_count) {
416 lmk->seed = NULL;
417 return 0;
418 }
419
420 lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
421 if (!lmk->seed) {
422 crypt_iv_lmk_dtr(cc);
423 ti->error = "Error kmallocing seed storage in LMK";
424 return -ENOMEM;
425 }
426
427 return 0;
428}
429
430static int crypt_iv_lmk_init(struct crypt_config *cc)
431{
432 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
433 int subkey_size = cc->key_size / cc->key_parts;
434
435 /* LMK seed is on the position of LMK_KEYS + 1 key */
436 if (lmk->seed)
437 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
438 crypto_shash_digestsize(lmk->hash_tfm));
439
440 return 0;
441}
442
443static int crypt_iv_lmk_wipe(struct crypt_config *cc)
444{
445 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
446
447 if (lmk->seed)
448 memset(lmk->seed, 0, LMK_SEED_SIZE);
449
450 return 0;
451}
452
453static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
454 struct dm_crypt_request *dmreq,
455 u8 *data)
456{
457 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
458 SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
459 struct md5_state md5state;
460 __le32 buf[4];
461 int i, r;
462
463 desc->tfm = lmk->hash_tfm;
464
465 r = crypto_shash_init(desc);
466 if (r)
467 return r;
468
469 if (lmk->seed) {
470 r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
471 if (r)
472 return r;
473 }
474
475 /* Sector is always 512B, block size 16, add data of blocks 1-31 */
476 r = crypto_shash_update(desc, data + 16, 16 * 31);
477 if (r)
478 return r;
479
480 /* Sector is cropped to 56 bits here */
481 buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
482 buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
483 buf[2] = cpu_to_le32(4024);
484 buf[3] = 0;
485 r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
486 if (r)
487 return r;
488
489 /* No MD5 padding here */
490 r = crypto_shash_export(desc, &md5state);
491 if (r)
492 return r;
493
494 for (i = 0; i < MD5_HASH_WORDS; i++)
495 __cpu_to_le32s(&md5state.hash[i]);
496 memcpy(iv, &md5state.hash, cc->iv_size);
497
498 return 0;
499}
500
501static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
502 struct dm_crypt_request *dmreq)
503{
504 struct scatterlist *sg;
505 u8 *src;
506 int r = 0;
507
508 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
509 sg = crypt_get_sg_data(cc, dmreq->sg_in);
510 src = kmap_atomic(sg_page(sg));
511 r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
512 kunmap_atomic(src);
513 } else
514 memset(iv, 0, cc->iv_size);
515
516 return r;
517}
518
519static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
520 struct dm_crypt_request *dmreq)
521{
522 struct scatterlist *sg;
523 u8 *dst;
524 int r;
525
526 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
527 return 0;
528
529 sg = crypt_get_sg_data(cc, dmreq->sg_out);
530 dst = kmap_atomic(sg_page(sg));
531 r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
532
533 /* Tweak the first block of plaintext sector */
534 if (!r)
535 crypto_xor(dst + sg->offset, iv, cc->iv_size);
536
537 kunmap_atomic(dst);
538 return r;
539}
540
541static void crypt_iv_tcw_dtr(struct crypt_config *cc)
542{
543 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
544
545 kzfree(tcw->iv_seed);
546 tcw->iv_seed = NULL;
547 kzfree(tcw->whitening);
548 tcw->whitening = NULL;
549
550 if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
551 crypto_free_shash(tcw->crc32_tfm);
552 tcw->crc32_tfm = NULL;
553}
554
555static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
556 const char *opts)
557{
558 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
559
560 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
561 ti->error = "Unsupported sector size for TCW";
562 return -EINVAL;
563 }
564
565 if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
566 ti->error = "Wrong key size for TCW";
567 return -EINVAL;
568 }
569
570 tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
571 if (IS_ERR(tcw->crc32_tfm)) {
572 ti->error = "Error initializing CRC32 in TCW";
573 return PTR_ERR(tcw->crc32_tfm);
574 }
575
576 tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
577 tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
578 if (!tcw->iv_seed || !tcw->whitening) {
579 crypt_iv_tcw_dtr(cc);
580 ti->error = "Error allocating seed storage in TCW";
581 return -ENOMEM;
582 }
583
584 return 0;
585}
586
587static int crypt_iv_tcw_init(struct crypt_config *cc)
588{
589 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
590 int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
591
592 memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
593 memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
594 TCW_WHITENING_SIZE);
595
596 return 0;
597}
598
599static int crypt_iv_tcw_wipe(struct crypt_config *cc)
600{
601 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
602
603 memset(tcw->iv_seed, 0, cc->iv_size);
604 memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
605
606 return 0;
607}
608
609static int crypt_iv_tcw_whitening(struct crypt_config *cc,
610 struct dm_crypt_request *dmreq,
611 u8 *data)
612{
613 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
614 __le64 sector = cpu_to_le64(dmreq->iv_sector);
615 u8 buf[TCW_WHITENING_SIZE];
616 SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
617 int i, r;
618
619 /* xor whitening with sector number */
620 crypto_xor_cpy(buf, tcw->whitening, (u8 *)&sector, 8);
621 crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)&sector, 8);
622
623 /* calculate crc32 for every 32bit part and xor it */
624 desc->tfm = tcw->crc32_tfm;
625 for (i = 0; i < 4; i++) {
626 r = crypto_shash_init(desc);
627 if (r)
628 goto out;
629 r = crypto_shash_update(desc, &buf[i * 4], 4);
630 if (r)
631 goto out;
632 r = crypto_shash_final(desc, &buf[i * 4]);
633 if (r)
634 goto out;
635 }
636 crypto_xor(&buf[0], &buf[12], 4);
637 crypto_xor(&buf[4], &buf[8], 4);
638
639 /* apply whitening (8 bytes) to whole sector */
640 for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
641 crypto_xor(data + i * 8, buf, 8);
642out:
643 memzero_explicit(buf, sizeof(buf));
644 return r;
645}
646
647static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
648 struct dm_crypt_request *dmreq)
649{
650 struct scatterlist *sg;
651 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
652 __le64 sector = cpu_to_le64(dmreq->iv_sector);
653 u8 *src;
654 int r = 0;
655
656 /* Remove whitening from ciphertext */
657 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
658 sg = crypt_get_sg_data(cc, dmreq->sg_in);
659 src = kmap_atomic(sg_page(sg));
660 r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
661 kunmap_atomic(src);
662 }
663
664 /* Calculate IV */
665 crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)&sector, 8);
666 if (cc->iv_size > 8)
667 crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)&sector,
668 cc->iv_size - 8);
669
670 return r;
671}
672
673static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
674 struct dm_crypt_request *dmreq)
675{
676 struct scatterlist *sg;
677 u8 *dst;
678 int r;
679
680 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
681 return 0;
682
683 /* Apply whitening on ciphertext */
684 sg = crypt_get_sg_data(cc, dmreq->sg_out);
685 dst = kmap_atomic(sg_page(sg));
686 r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
687 kunmap_atomic(dst);
688
689 return r;
690}
691
692static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
693 struct dm_crypt_request *dmreq)
694{
695 /* Used only for writes, there must be an additional space to store IV */
696 get_random_bytes(iv, cc->iv_size);
697 return 0;
698}
699
700static int crypt_iv_eboiv_ctr(struct crypt_config *cc, struct dm_target *ti,
701 const char *opts)
702{
703 if (test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags)) {
704 ti->error = "AEAD transforms not supported for EBOIV";
705 return -EINVAL;
706 }
707
708 if (crypto_skcipher_blocksize(any_tfm(cc)) != cc->iv_size) {
709 ti->error = "Block size of EBOIV cipher does "
710 "not match IV size of block cipher";
711 return -EINVAL;
712 }
713
714 return 0;
715}
716
717static int crypt_iv_eboiv_gen(struct crypt_config *cc, u8 *iv,
718 struct dm_crypt_request *dmreq)
719{
720 u8 buf[MAX_CIPHER_BLOCKSIZE] __aligned(__alignof__(__le64));
721 struct skcipher_request *req;
722 struct scatterlist src, dst;
723 DECLARE_CRYPTO_WAIT(wait);
724 int err;
725
726 req = skcipher_request_alloc(any_tfm(cc), GFP_NOIO);
727 if (!req)
728 return -ENOMEM;
729
730 memset(buf, 0, cc->iv_size);
731 *(__le64 *)buf = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
732
733 sg_init_one(&src, page_address(ZERO_PAGE(0)), cc->iv_size);
734 sg_init_one(&dst, iv, cc->iv_size);
735 skcipher_request_set_crypt(req, &src, &dst, cc->iv_size, buf);
736 skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
737 err = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
738 skcipher_request_free(req);
739
740 return err;
741}
742
743static const struct crypt_iv_operations crypt_iv_plain_ops = {
744 .generator = crypt_iv_plain_gen
745};
746
747static const struct crypt_iv_operations crypt_iv_plain64_ops = {
748 .generator = crypt_iv_plain64_gen
749};
750
751static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
752 .generator = crypt_iv_plain64be_gen
753};
754
755static const struct crypt_iv_operations crypt_iv_essiv_ops = {
756 .generator = crypt_iv_essiv_gen
757};
758
759static const struct crypt_iv_operations crypt_iv_benbi_ops = {
760 .ctr = crypt_iv_benbi_ctr,
761 .dtr = crypt_iv_benbi_dtr,
762 .generator = crypt_iv_benbi_gen
763};
764
765static const struct crypt_iv_operations crypt_iv_null_ops = {
766 .generator = crypt_iv_null_gen
767};
768
769static const struct crypt_iv_operations crypt_iv_lmk_ops = {
770 .ctr = crypt_iv_lmk_ctr,
771 .dtr = crypt_iv_lmk_dtr,
772 .init = crypt_iv_lmk_init,
773 .wipe = crypt_iv_lmk_wipe,
774 .generator = crypt_iv_lmk_gen,
775 .post = crypt_iv_lmk_post
776};
777
778static const struct crypt_iv_operations crypt_iv_tcw_ops = {
779 .ctr = crypt_iv_tcw_ctr,
780 .dtr = crypt_iv_tcw_dtr,
781 .init = crypt_iv_tcw_init,
782 .wipe = crypt_iv_tcw_wipe,
783 .generator = crypt_iv_tcw_gen,
784 .post = crypt_iv_tcw_post
785};
786
787static struct crypt_iv_operations crypt_iv_random_ops = {
788 .generator = crypt_iv_random_gen
789};
790
791static struct crypt_iv_operations crypt_iv_eboiv_ops = {
792 .ctr = crypt_iv_eboiv_ctr,
793 .generator = crypt_iv_eboiv_gen
794};
795
796/*
797 * Integrity extensions
798 */
799static bool crypt_integrity_aead(struct crypt_config *cc)
800{
801 return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
802}
803
804static bool crypt_integrity_hmac(struct crypt_config *cc)
805{
806 return crypt_integrity_aead(cc) && cc->key_mac_size;
807}
808
809/* Get sg containing data */
810static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
811 struct scatterlist *sg)
812{
813 if (unlikely(crypt_integrity_aead(cc)))
814 return &sg[2];
815
816 return sg;
817}
818
819static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
820{
821 struct bio_integrity_payload *bip;
822 unsigned int tag_len;
823 int ret;
824
825 if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
826 return 0;
827
828 bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
829 if (IS_ERR(bip))
830 return PTR_ERR(bip);
831
832 tag_len = io->cc->on_disk_tag_size * (bio_sectors(bio) >> io->cc->sector_shift);
833
834 bip->bip_iter.bi_size = tag_len;
835 bip->bip_iter.bi_sector = io->cc->start + io->sector;
836
837 ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
838 tag_len, offset_in_page(io->integrity_metadata));
839 if (unlikely(ret != tag_len))
840 return -ENOMEM;
841
842 return 0;
843}
844
845static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
846{
847#ifdef CONFIG_BLK_DEV_INTEGRITY
848 struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
849 struct mapped_device *md = dm_table_get_md(ti->table);
850
851 /* From now we require underlying device with our integrity profile */
852 if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
853 ti->error = "Integrity profile not supported.";
854 return -EINVAL;
855 }
856
857 if (bi->tag_size != cc->on_disk_tag_size ||
858 bi->tuple_size != cc->on_disk_tag_size) {
859 ti->error = "Integrity profile tag size mismatch.";
860 return -EINVAL;
861 }
862 if (1 << bi->interval_exp != cc->sector_size) {
863 ti->error = "Integrity profile sector size mismatch.";
864 return -EINVAL;
865 }
866
867 if (crypt_integrity_aead(cc)) {
868 cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
869 DMDEBUG("%s: Integrity AEAD, tag size %u, IV size %u.", dm_device_name(md),
870 cc->integrity_tag_size, cc->integrity_iv_size);
871
872 if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
873 ti->error = "Integrity AEAD auth tag size is not supported.";
874 return -EINVAL;
875 }
876 } else if (cc->integrity_iv_size)
877 DMDEBUG("%s: Additional per-sector space %u bytes for IV.", dm_device_name(md),
878 cc->integrity_iv_size);
879
880 if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
881 ti->error = "Not enough space for integrity tag in the profile.";
882 return -EINVAL;
883 }
884
885 return 0;
886#else
887 ti->error = "Integrity profile not supported.";
888 return -EINVAL;
889#endif
890}
891
892static void crypt_convert_init(struct crypt_config *cc,
893 struct convert_context *ctx,
894 struct bio *bio_out, struct bio *bio_in,
895 sector_t sector)
896{
897 ctx->bio_in = bio_in;
898 ctx->bio_out = bio_out;
899 if (bio_in)
900 ctx->iter_in = bio_in->bi_iter;
901 if (bio_out)
902 ctx->iter_out = bio_out->bi_iter;
903 ctx->cc_sector = sector + cc->iv_offset;
904 init_completion(&ctx->restart);
905}
906
907static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
908 void *req)
909{
910 return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
911}
912
913static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
914{
915 return (void *)((char *)dmreq - cc->dmreq_start);
916}
917
918static u8 *iv_of_dmreq(struct crypt_config *cc,
919 struct dm_crypt_request *dmreq)
920{
921 if (crypt_integrity_aead(cc))
922 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
923 crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
924 else
925 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
926 crypto_skcipher_alignmask(any_tfm(cc)) + 1);
927}
928
929static u8 *org_iv_of_dmreq(struct crypt_config *cc,
930 struct dm_crypt_request *dmreq)
931{
932 return iv_of_dmreq(cc, dmreq) + cc->iv_size;
933}
934
935static __le64 *org_sector_of_dmreq(struct crypt_config *cc,
936 struct dm_crypt_request *dmreq)
937{
938 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
939 return (__le64 *) ptr;
940}
941
942static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
943 struct dm_crypt_request *dmreq)
944{
945 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
946 cc->iv_size + sizeof(uint64_t);
947 return (unsigned int*)ptr;
948}
949
950static void *tag_from_dmreq(struct crypt_config *cc,
951 struct dm_crypt_request *dmreq)
952{
953 struct convert_context *ctx = dmreq->ctx;
954 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
955
956 return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
957 cc->on_disk_tag_size];
958}
959
960static void *iv_tag_from_dmreq(struct crypt_config *cc,
961 struct dm_crypt_request *dmreq)
962{
963 return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
964}
965
966static int crypt_convert_block_aead(struct crypt_config *cc,
967 struct convert_context *ctx,
968 struct aead_request *req,
969 unsigned int tag_offset)
970{
971 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
972 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
973 struct dm_crypt_request *dmreq;
974 u8 *iv, *org_iv, *tag_iv, *tag;
975 __le64 *sector;
976 int r = 0;
977
978 BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
979
980 /* Reject unexpected unaligned bio. */
981 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
982 return -EIO;
983
984 dmreq = dmreq_of_req(cc, req);
985 dmreq->iv_sector = ctx->cc_sector;
986 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
987 dmreq->iv_sector >>= cc->sector_shift;
988 dmreq->ctx = ctx;
989
990 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
991
992 sector = org_sector_of_dmreq(cc, dmreq);
993 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
994
995 iv = iv_of_dmreq(cc, dmreq);
996 org_iv = org_iv_of_dmreq(cc, dmreq);
997 tag = tag_from_dmreq(cc, dmreq);
998 tag_iv = iv_tag_from_dmreq(cc, dmreq);
999
1000 /* AEAD request:
1001 * |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1002 * | (authenticated) | (auth+encryption) | |
1003 * | sector_LE | IV | sector in/out | tag in/out |
1004 */
1005 sg_init_table(dmreq->sg_in, 4);
1006 sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
1007 sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
1008 sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1009 sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
1010
1011 sg_init_table(dmreq->sg_out, 4);
1012 sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
1013 sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
1014 sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1015 sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
1016
1017 if (cc->iv_gen_ops) {
1018 /* For READs use IV stored in integrity metadata */
1019 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1020 memcpy(org_iv, tag_iv, cc->iv_size);
1021 } else {
1022 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1023 if (r < 0)
1024 return r;
1025 /* Store generated IV in integrity metadata */
1026 if (cc->integrity_iv_size)
1027 memcpy(tag_iv, org_iv, cc->iv_size);
1028 }
1029 /* Working copy of IV, to be modified in crypto API */
1030 memcpy(iv, org_iv, cc->iv_size);
1031 }
1032
1033 aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
1034 if (bio_data_dir(ctx->bio_in) == WRITE) {
1035 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1036 cc->sector_size, iv);
1037 r = crypto_aead_encrypt(req);
1038 if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
1039 memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
1040 cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
1041 } else {
1042 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1043 cc->sector_size + cc->integrity_tag_size, iv);
1044 r = crypto_aead_decrypt(req);
1045 }
1046
1047 if (r == -EBADMSG) {
1048 char b[BDEVNAME_SIZE];
1049 DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx->bio_in, b),
1050 (unsigned long long)le64_to_cpu(*sector));
1051 }
1052
1053 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1054 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1055
1056 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1057 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1058
1059 return r;
1060}
1061
1062static int crypt_convert_block_skcipher(struct crypt_config *cc,
1063 struct convert_context *ctx,
1064 struct skcipher_request *req,
1065 unsigned int tag_offset)
1066{
1067 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1068 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1069 struct scatterlist *sg_in, *sg_out;
1070 struct dm_crypt_request *dmreq;
1071 u8 *iv, *org_iv, *tag_iv;
1072 __le64 *sector;
1073 int r = 0;
1074
1075 /* Reject unexpected unaligned bio. */
1076 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1077 return -EIO;
1078
1079 dmreq = dmreq_of_req(cc, req);
1080 dmreq->iv_sector = ctx->cc_sector;
1081 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1082 dmreq->iv_sector >>= cc->sector_shift;
1083 dmreq->ctx = ctx;
1084
1085 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1086
1087 iv = iv_of_dmreq(cc, dmreq);
1088 org_iv = org_iv_of_dmreq(cc, dmreq);
1089 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1090
1091 sector = org_sector_of_dmreq(cc, dmreq);
1092 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1093
1094 /* For skcipher we use only the first sg item */
1095 sg_in = &dmreq->sg_in[0];
1096 sg_out = &dmreq->sg_out[0];
1097
1098 sg_init_table(sg_in, 1);
1099 sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1100
1101 sg_init_table(sg_out, 1);
1102 sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1103
1104 if (cc->iv_gen_ops) {
1105 /* For READs use IV stored in integrity metadata */
1106 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1107 memcpy(org_iv, tag_iv, cc->integrity_iv_size);
1108 } else {
1109 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1110 if (r < 0)
1111 return r;
1112 /* Store generated IV in integrity metadata */
1113 if (cc->integrity_iv_size)
1114 memcpy(tag_iv, org_iv, cc->integrity_iv_size);
1115 }
1116 /* Working copy of IV, to be modified in crypto API */
1117 memcpy(iv, org_iv, cc->iv_size);
1118 }
1119
1120 skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
1121
1122 if (bio_data_dir(ctx->bio_in) == WRITE)
1123 r = crypto_skcipher_encrypt(req);
1124 else
1125 r = crypto_skcipher_decrypt(req);
1126
1127 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1128 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1129
1130 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1131 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1132
1133 return r;
1134}
1135
1136static void kcryptd_async_done(struct crypto_async_request *async_req,
1137 int error);
1138
1139static void crypt_alloc_req_skcipher(struct crypt_config *cc,
1140 struct convert_context *ctx)
1141{
1142 unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
1143
1144 if (!ctx->r.req)
1145 ctx->r.req = mempool_alloc(&cc->req_pool, GFP_NOIO);
1146
1147 skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
1148
1149 /*
1150 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1151 * requests if driver request queue is full.
1152 */
1153 skcipher_request_set_callback(ctx->r.req,
1154 CRYPTO_TFM_REQ_MAY_BACKLOG,
1155 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
1156}
1157
1158static void crypt_alloc_req_aead(struct crypt_config *cc,
1159 struct convert_context *ctx)
1160{
1161 if (!ctx->r.req_aead)
1162 ctx->r.req_aead = mempool_alloc(&cc->req_pool, GFP_NOIO);
1163
1164 aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
1165
1166 /*
1167 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1168 * requests if driver request queue is full.
1169 */
1170 aead_request_set_callback(ctx->r.req_aead,
1171 CRYPTO_TFM_REQ_MAY_BACKLOG,
1172 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
1173}
1174
1175static void crypt_alloc_req(struct crypt_config *cc,
1176 struct convert_context *ctx)
1177{
1178 if (crypt_integrity_aead(cc))
1179 crypt_alloc_req_aead(cc, ctx);
1180 else
1181 crypt_alloc_req_skcipher(cc, ctx);
1182}
1183
1184static void crypt_free_req_skcipher(struct crypt_config *cc,
1185 struct skcipher_request *req, struct bio *base_bio)
1186{
1187 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1188
1189 if ((struct skcipher_request *)(io + 1) != req)
1190 mempool_free(req, &cc->req_pool);
1191}
1192
1193static void crypt_free_req_aead(struct crypt_config *cc,
1194 struct aead_request *req, struct bio *base_bio)
1195{
1196 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1197
1198 if ((struct aead_request *)(io + 1) != req)
1199 mempool_free(req, &cc->req_pool);
1200}
1201
1202static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
1203{
1204 if (crypt_integrity_aead(cc))
1205 crypt_free_req_aead(cc, req, base_bio);
1206 else
1207 crypt_free_req_skcipher(cc, req, base_bio);
1208}
1209
1210/*
1211 * Encrypt / decrypt data from one bio to another one (can be the same one)
1212 */
1213static blk_status_t crypt_convert(struct crypt_config *cc,
1214 struct convert_context *ctx)
1215{
1216 unsigned int tag_offset = 0;
1217 unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
1218 int r;
1219
1220 atomic_set(&ctx->cc_pending, 1);
1221
1222 while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
1223
1224 crypt_alloc_req(cc, ctx);
1225 atomic_inc(&ctx->cc_pending);
1226
1227 if (crypt_integrity_aead(cc))
1228 r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
1229 else
1230 r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
1231
1232 switch (r) {
1233 /*
1234 * The request was queued by a crypto driver
1235 * but the driver request queue is full, let's wait.
1236 */
1237 case -EBUSY:
1238 wait_for_completion(&ctx->restart);
1239 reinit_completion(&ctx->restart);
1240 /* fall through */
1241 /*
1242 * The request is queued and processed asynchronously,
1243 * completion function kcryptd_async_done() will be called.
1244 */
1245 case -EINPROGRESS:
1246 ctx->r.req = NULL;
1247 ctx->cc_sector += sector_step;
1248 tag_offset++;
1249 continue;
1250 /*
1251 * The request was already processed (synchronously).
1252 */
1253 case 0:
1254 atomic_dec(&ctx->cc_pending);
1255 ctx->cc_sector += sector_step;
1256 tag_offset++;
1257 cond_resched();
1258 continue;
1259 /*
1260 * There was a data integrity error.
1261 */
1262 case -EBADMSG:
1263 atomic_dec(&ctx->cc_pending);
1264 return BLK_STS_PROTECTION;
1265 /*
1266 * There was an error while processing the request.
1267 */
1268 default:
1269 atomic_dec(&ctx->cc_pending);
1270 return BLK_STS_IOERR;
1271 }
1272 }
1273
1274 return 0;
1275}
1276
1277static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
1278
1279/*
1280 * Generate a new unfragmented bio with the given size
1281 * This should never violate the device limitations (but only because
1282 * max_segment_size is being constrained to PAGE_SIZE).
1283 *
1284 * This function may be called concurrently. If we allocate from the mempool
1285 * concurrently, there is a possibility of deadlock. For example, if we have
1286 * mempool of 256 pages, two processes, each wanting 256, pages allocate from
1287 * the mempool concurrently, it may deadlock in a situation where both processes
1288 * have allocated 128 pages and the mempool is exhausted.
1289 *
1290 * In order to avoid this scenario we allocate the pages under a mutex.
1291 *
1292 * In order to not degrade performance with excessive locking, we try
1293 * non-blocking allocations without a mutex first but on failure we fallback
1294 * to blocking allocations with a mutex.
1295 */
1296static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
1297{
1298 struct crypt_config *cc = io->cc;
1299 struct bio *clone;
1300 unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1301 gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
1302 unsigned i, len, remaining_size;
1303 struct page *page;
1304
1305retry:
1306 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1307 mutex_lock(&cc->bio_alloc_lock);
1308
1309 clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, &cc->bs);
1310 if (!clone)
1311 goto out;
1312
1313 clone_init(io, clone);
1314
1315 remaining_size = size;
1316
1317 for (i = 0; i < nr_iovecs; i++) {
1318 page = mempool_alloc(&cc->page_pool, gfp_mask);
1319 if (!page) {
1320 crypt_free_buffer_pages(cc, clone);
1321 bio_put(clone);
1322 gfp_mask |= __GFP_DIRECT_RECLAIM;
1323 goto retry;
1324 }
1325
1326 len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
1327
1328 bio_add_page(clone, page, len, 0);
1329
1330 remaining_size -= len;
1331 }
1332
1333 /* Allocate space for integrity tags */
1334 if (dm_crypt_integrity_io_alloc(io, clone)) {
1335 crypt_free_buffer_pages(cc, clone);
1336 bio_put(clone);
1337 clone = NULL;
1338 }
1339out:
1340 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1341 mutex_unlock(&cc->bio_alloc_lock);
1342
1343 return clone;
1344}
1345
1346static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1347{
1348 struct bio_vec *bv;
1349 struct bvec_iter_all iter_all;
1350
1351 bio_for_each_segment_all(bv, clone, iter_all) {
1352 BUG_ON(!bv->bv_page);
1353 mempool_free(bv->bv_page, &cc->page_pool);
1354 }
1355}
1356
1357static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1358 struct bio *bio, sector_t sector)
1359{
1360 io->cc = cc;
1361 io->base_bio = bio;
1362 io->sector = sector;
1363 io->error = 0;
1364 io->ctx.r.req = NULL;
1365 io->integrity_metadata = NULL;
1366 io->integrity_metadata_from_pool = false;
1367 atomic_set(&io->io_pending, 0);
1368}
1369
1370static void crypt_inc_pending(struct dm_crypt_io *io)
1371{
1372 atomic_inc(&io->io_pending);
1373}
1374
1375/*
1376 * One of the bios was finished. Check for completion of
1377 * the whole request and correctly clean up the buffer.
1378 */
1379static void crypt_dec_pending(struct dm_crypt_io *io)
1380{
1381 struct crypt_config *cc = io->cc;
1382 struct bio *base_bio = io->base_bio;
1383 blk_status_t error = io->error;
1384
1385 if (!atomic_dec_and_test(&io->io_pending))
1386 return;
1387
1388 if (io->ctx.r.req)
1389 crypt_free_req(cc, io->ctx.r.req, base_bio);
1390
1391 if (unlikely(io->integrity_metadata_from_pool))
1392 mempool_free(io->integrity_metadata, &io->cc->tag_pool);
1393 else
1394 kfree(io->integrity_metadata);
1395
1396 base_bio->bi_status = error;
1397 bio_endio(base_bio);
1398}
1399
1400/*
1401 * kcryptd/kcryptd_io:
1402 *
1403 * Needed because it would be very unwise to do decryption in an
1404 * interrupt context.
1405 *
1406 * kcryptd performs the actual encryption or decryption.
1407 *
1408 * kcryptd_io performs the IO submission.
1409 *
1410 * They must be separated as otherwise the final stages could be
1411 * starved by new requests which can block in the first stages due
1412 * to memory allocation.
1413 *
1414 * The work is done per CPU global for all dm-crypt instances.
1415 * They should not depend on each other and do not block.
1416 */
1417static void crypt_endio(struct bio *clone)
1418{
1419 struct dm_crypt_io *io = clone->bi_private;
1420 struct crypt_config *cc = io->cc;
1421 unsigned rw = bio_data_dir(clone);
1422 blk_status_t error;
1423
1424 /*
1425 * free the processed pages
1426 */
1427 if (rw == WRITE)
1428 crypt_free_buffer_pages(cc, clone);
1429
1430 error = clone->bi_status;
1431 bio_put(clone);
1432
1433 if (rw == READ && !error) {
1434 kcryptd_queue_crypt(io);
1435 return;
1436 }
1437
1438 if (unlikely(error))
1439 io->error = error;
1440
1441 crypt_dec_pending(io);
1442}
1443
1444static void clone_init(struct dm_crypt_io *io, struct bio *clone)
1445{
1446 struct crypt_config *cc = io->cc;
1447
1448 clone->bi_private = io;
1449 clone->bi_end_io = crypt_endio;
1450 bio_set_dev(clone, cc->dev->bdev);
1451 clone->bi_opf = io->base_bio->bi_opf;
1452}
1453
1454static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
1455{
1456 struct crypt_config *cc = io->cc;
1457 struct bio *clone;
1458
1459 /*
1460 * We need the original biovec array in order to decrypt
1461 * the whole bio data *afterwards* -- thanks to immutable
1462 * biovecs we don't need to worry about the block layer
1463 * modifying the biovec array; so leverage bio_clone_fast().
1464 */
1465 clone = bio_clone_fast(io->base_bio, gfp, &cc->bs);
1466 if (!clone)
1467 return 1;
1468
1469 crypt_inc_pending(io);
1470
1471 clone_init(io, clone);
1472 clone->bi_iter.bi_sector = cc->start + io->sector;
1473
1474 if (dm_crypt_integrity_io_alloc(io, clone)) {
1475 crypt_dec_pending(io);
1476 bio_put(clone);
1477 return 1;
1478 }
1479
1480 generic_make_request(clone);
1481 return 0;
1482}
1483
1484static void kcryptd_io_read_work(struct work_struct *work)
1485{
1486 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1487
1488 crypt_inc_pending(io);
1489 if (kcryptd_io_read(io, GFP_NOIO))
1490 io->error = BLK_STS_RESOURCE;
1491 crypt_dec_pending(io);
1492}
1493
1494static void kcryptd_queue_read(struct dm_crypt_io *io)
1495{
1496 struct crypt_config *cc = io->cc;
1497
1498 INIT_WORK(&io->work, kcryptd_io_read_work);
1499 queue_work(cc->io_queue, &io->work);
1500}
1501
1502static void kcryptd_io_write(struct dm_crypt_io *io)
1503{
1504 struct bio *clone = io->ctx.bio_out;
1505
1506 generic_make_request(clone);
1507}
1508
1509#define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1510
1511static int dmcrypt_write(void *data)
1512{
1513 struct crypt_config *cc = data;
1514 struct dm_crypt_io *io;
1515
1516 while (1) {
1517 struct rb_root write_tree;
1518 struct blk_plug plug;
1519
1520 spin_lock_irq(&cc->write_thread_lock);
1521continue_locked:
1522
1523 if (!RB_EMPTY_ROOT(&cc->write_tree))
1524 goto pop_from_list;
1525
1526 set_current_state(TASK_INTERRUPTIBLE);
1527
1528 spin_unlock_irq(&cc->write_thread_lock);
1529
1530 if (unlikely(kthread_should_stop())) {
1531 set_current_state(TASK_RUNNING);
1532 break;
1533 }
1534
1535 schedule();
1536
1537 set_current_state(TASK_RUNNING);
1538 spin_lock_irq(&cc->write_thread_lock);
1539 goto continue_locked;
1540
1541pop_from_list:
1542 write_tree = cc->write_tree;
1543 cc->write_tree = RB_ROOT;
1544 spin_unlock_irq(&cc->write_thread_lock);
1545
1546 BUG_ON(rb_parent(write_tree.rb_node));
1547
1548 /*
1549 * Note: we cannot walk the tree here with rb_next because
1550 * the structures may be freed when kcryptd_io_write is called.
1551 */
1552 blk_start_plug(&plug);
1553 do {
1554 io = crypt_io_from_node(rb_first(&write_tree));
1555 rb_erase(&io->rb_node, &write_tree);
1556 kcryptd_io_write(io);
1557 cond_resched();
1558 } while (!RB_EMPTY_ROOT(&write_tree));
1559 blk_finish_plug(&plug);
1560 }
1561 return 0;
1562}
1563
1564static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
1565{
1566 struct bio *clone = io->ctx.bio_out;
1567 struct crypt_config *cc = io->cc;
1568 unsigned long flags;
1569 sector_t sector;
1570 struct rb_node **rbp, *parent;
1571
1572 if (unlikely(io->error)) {
1573 crypt_free_buffer_pages(cc, clone);
1574 bio_put(clone);
1575 crypt_dec_pending(io);
1576 return;
1577 }
1578
1579 /* crypt_convert should have filled the clone bio */
1580 BUG_ON(io->ctx.iter_out.bi_size);
1581
1582 clone->bi_iter.bi_sector = cc->start + io->sector;
1583
1584 if (likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) {
1585 generic_make_request(clone);
1586 return;
1587 }
1588
1589 spin_lock_irqsave(&cc->write_thread_lock, flags);
1590 if (RB_EMPTY_ROOT(&cc->write_tree))
1591 wake_up_process(cc->write_thread);
1592 rbp = &cc->write_tree.rb_node;
1593 parent = NULL;
1594 sector = io->sector;
1595 while (*rbp) {
1596 parent = *rbp;
1597 if (sector < crypt_io_from_node(parent)->sector)
1598 rbp = &(*rbp)->rb_left;
1599 else
1600 rbp = &(*rbp)->rb_right;
1601 }
1602 rb_link_node(&io->rb_node, parent, rbp);
1603 rb_insert_color(&io->rb_node, &cc->write_tree);
1604 spin_unlock_irqrestore(&cc->write_thread_lock, flags);
1605}
1606
1607static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
1608{
1609 struct crypt_config *cc = io->cc;
1610 struct bio *clone;
1611 int crypt_finished;
1612 sector_t sector = io->sector;
1613 blk_status_t r;
1614
1615 /*
1616 * Prevent io from disappearing until this function completes.
1617 */
1618 crypt_inc_pending(io);
1619 crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
1620
1621 clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
1622 if (unlikely(!clone)) {
1623 io->error = BLK_STS_IOERR;
1624 goto dec;
1625 }
1626
1627 io->ctx.bio_out = clone;
1628 io->ctx.iter_out = clone->bi_iter;
1629
1630 if (crypt_integrity_aead(cc)) {
1631 bio_copy_data(clone, io->base_bio);
1632 io->ctx.bio_in = clone;
1633 io->ctx.iter_in = clone->bi_iter;
1634 }
1635
1636 sector += bio_sectors(clone);
1637
1638 crypt_inc_pending(io);
1639 r = crypt_convert(cc, &io->ctx);
1640 if (r)
1641 io->error = r;
1642 crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
1643
1644 /* Encryption was already finished, submit io now */
1645 if (crypt_finished) {
1646 kcryptd_crypt_write_io_submit(io, 0);
1647 io->sector = sector;
1648 }
1649
1650dec:
1651 crypt_dec_pending(io);
1652}
1653
1654static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
1655{
1656 crypt_dec_pending(io);
1657}
1658
1659static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
1660{
1661 struct crypt_config *cc = io->cc;
1662 blk_status_t r;
1663
1664 crypt_inc_pending(io);
1665
1666 crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
1667 io->sector);
1668
1669 r = crypt_convert(cc, &io->ctx);
1670 if (r)
1671 io->error = r;
1672
1673 if (atomic_dec_and_test(&io->ctx.cc_pending))
1674 kcryptd_crypt_read_done(io);
1675
1676 crypt_dec_pending(io);
1677}
1678
1679static void kcryptd_async_done(struct crypto_async_request *async_req,
1680 int error)
1681{
1682 struct dm_crypt_request *dmreq = async_req->data;
1683 struct convert_context *ctx = dmreq->ctx;
1684 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1685 struct crypt_config *cc = io->cc;
1686
1687 /*
1688 * A request from crypto driver backlog is going to be processed now,
1689 * finish the completion and continue in crypt_convert().
1690 * (Callback will be called for the second time for this request.)
1691 */
1692 if (error == -EINPROGRESS) {
1693 complete(&ctx->restart);
1694 return;
1695 }
1696
1697 if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
1698 error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
1699
1700 if (error == -EBADMSG) {
1701 char b[BDEVNAME_SIZE];
1702 DMERR_LIMIT("%s: INTEGRITY AEAD ERROR, sector %llu", bio_devname(ctx->bio_in, b),
1703 (unsigned long long)le64_to_cpu(*org_sector_of_dmreq(cc, dmreq)));
1704 io->error = BLK_STS_PROTECTION;
1705 } else if (error < 0)
1706 io->error = BLK_STS_IOERR;
1707
1708 crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
1709
1710 if (!atomic_dec_and_test(&ctx->cc_pending))
1711 return;
1712
1713 if (bio_data_dir(io->base_bio) == READ)
1714 kcryptd_crypt_read_done(io);
1715 else
1716 kcryptd_crypt_write_io_submit(io, 1);
1717}
1718
1719static void kcryptd_crypt(struct work_struct *work)
1720{
1721 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1722
1723 if (bio_data_dir(io->base_bio) == READ)
1724 kcryptd_crypt_read_convert(io);
1725 else
1726 kcryptd_crypt_write_convert(io);
1727}
1728
1729static void kcryptd_queue_crypt(struct dm_crypt_io *io)
1730{
1731 struct crypt_config *cc = io->cc;
1732
1733 INIT_WORK(&io->work, kcryptd_crypt);
1734 queue_work(cc->crypt_queue, &io->work);
1735}
1736
1737static void crypt_free_tfms_aead(struct crypt_config *cc)
1738{
1739 if (!cc->cipher_tfm.tfms_aead)
1740 return;
1741
1742 if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
1743 crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
1744 cc->cipher_tfm.tfms_aead[0] = NULL;
1745 }
1746
1747 kfree(cc->cipher_tfm.tfms_aead);
1748 cc->cipher_tfm.tfms_aead = NULL;
1749}
1750
1751static void crypt_free_tfms_skcipher(struct crypt_config *cc)
1752{
1753 unsigned i;
1754
1755 if (!cc->cipher_tfm.tfms)
1756 return;
1757
1758 for (i = 0; i < cc->tfms_count; i++)
1759 if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
1760 crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
1761 cc->cipher_tfm.tfms[i] = NULL;
1762 }
1763
1764 kfree(cc->cipher_tfm.tfms);
1765 cc->cipher_tfm.tfms = NULL;
1766}
1767
1768static void crypt_free_tfms(struct crypt_config *cc)
1769{
1770 if (crypt_integrity_aead(cc))
1771 crypt_free_tfms_aead(cc);
1772 else
1773 crypt_free_tfms_skcipher(cc);
1774}
1775
1776static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
1777{
1778 unsigned i;
1779 int err;
1780
1781 cc->cipher_tfm.tfms = kcalloc(cc->tfms_count,
1782 sizeof(struct crypto_skcipher *),
1783 GFP_KERNEL);
1784 if (!cc->cipher_tfm.tfms)
1785 return -ENOMEM;
1786
1787 for (i = 0; i < cc->tfms_count; i++) {
1788 cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0, 0);
1789 if (IS_ERR(cc->cipher_tfm.tfms[i])) {
1790 err = PTR_ERR(cc->cipher_tfm.tfms[i]);
1791 crypt_free_tfms(cc);
1792 return err;
1793 }
1794 }
1795
1796 /*
1797 * dm-crypt performance can vary greatly depending on which crypto
1798 * algorithm implementation is used. Help people debug performance
1799 * problems by logging the ->cra_driver_name.
1800 */
1801 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
1802 crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
1803 return 0;
1804}
1805
1806static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
1807{
1808 int err;
1809
1810 cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
1811 if (!cc->cipher_tfm.tfms)
1812 return -ENOMEM;
1813
1814 cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0, 0);
1815 if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
1816 err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
1817 crypt_free_tfms(cc);
1818 return err;
1819 }
1820
1821 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
1822 crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
1823 return 0;
1824}
1825
1826static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
1827{
1828 if (crypt_integrity_aead(cc))
1829 return crypt_alloc_tfms_aead(cc, ciphermode);
1830 else
1831 return crypt_alloc_tfms_skcipher(cc, ciphermode);
1832}
1833
1834static unsigned crypt_subkey_size(struct crypt_config *cc)
1835{
1836 return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
1837}
1838
1839static unsigned crypt_authenckey_size(struct crypt_config *cc)
1840{
1841 return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
1842}
1843
1844/*
1845 * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
1846 * the key must be for some reason in special format.
1847 * This funcion converts cc->key to this special format.
1848 */
1849static void crypt_copy_authenckey(char *p, const void *key,
1850 unsigned enckeylen, unsigned authkeylen)
1851{
1852 struct crypto_authenc_key_param *param;
1853 struct rtattr *rta;
1854
1855 rta = (struct rtattr *)p;
1856 param = RTA_DATA(rta);
1857 param->enckeylen = cpu_to_be32(enckeylen);
1858 rta->rta_len = RTA_LENGTH(sizeof(*param));
1859 rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
1860 p += RTA_SPACE(sizeof(*param));
1861 memcpy(p, key + enckeylen, authkeylen);
1862 p += authkeylen;
1863 memcpy(p, key, enckeylen);
1864}
1865
1866static int crypt_setkey(struct crypt_config *cc)
1867{
1868 unsigned subkey_size;
1869 int err = 0, i, r;
1870
1871 /* Ignore extra keys (which are used for IV etc) */
1872 subkey_size = crypt_subkey_size(cc);
1873
1874 if (crypt_integrity_hmac(cc)) {
1875 if (subkey_size < cc->key_mac_size)
1876 return -EINVAL;
1877
1878 crypt_copy_authenckey(cc->authenc_key, cc->key,
1879 subkey_size - cc->key_mac_size,
1880 cc->key_mac_size);
1881 }
1882
1883 for (i = 0; i < cc->tfms_count; i++) {
1884 if (crypt_integrity_hmac(cc))
1885 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
1886 cc->authenc_key, crypt_authenckey_size(cc));
1887 else if (crypt_integrity_aead(cc))
1888 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
1889 cc->key + (i * subkey_size),
1890 subkey_size);
1891 else
1892 r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
1893 cc->key + (i * subkey_size),
1894 subkey_size);
1895 if (r)
1896 err = r;
1897 }
1898
1899 if (crypt_integrity_hmac(cc))
1900 memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
1901
1902 return err;
1903}
1904
1905#ifdef CONFIG_KEYS
1906
1907static bool contains_whitespace(const char *str)
1908{
1909 while (*str)
1910 if (isspace(*str++))
1911 return true;
1912 return false;
1913}
1914
1915static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
1916{
1917 char *new_key_string, *key_desc;
1918 int ret;
1919 struct key *key;
1920 const struct user_key_payload *ukp;
1921
1922 /*
1923 * Reject key_string with whitespace. dm core currently lacks code for
1924 * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
1925 */
1926 if (contains_whitespace(key_string)) {
1927 DMERR("whitespace chars not allowed in key string");
1928 return -EINVAL;
1929 }
1930
1931 /* look for next ':' separating key_type from key_description */
1932 key_desc = strpbrk(key_string, ":");
1933 if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
1934 return -EINVAL;
1935
1936 if (strncmp(key_string, "logon:", key_desc - key_string + 1) &&
1937 strncmp(key_string, "user:", key_desc - key_string + 1))
1938 return -EINVAL;
1939
1940 new_key_string = kstrdup(key_string, GFP_KERNEL);
1941 if (!new_key_string)
1942 return -ENOMEM;
1943
1944 key = request_key(key_string[0] == 'l' ? &key_type_logon : &key_type_user,
1945 key_desc + 1, NULL);
1946 if (IS_ERR(key)) {
1947 kzfree(new_key_string);
1948 return PTR_ERR(key);
1949 }
1950
1951 down_read(&key->sem);
1952
1953 ukp = user_key_payload_locked(key);
1954 if (!ukp) {
1955 up_read(&key->sem);
1956 key_put(key);
1957 kzfree(new_key_string);
1958 return -EKEYREVOKED;
1959 }
1960
1961 if (cc->key_size != ukp->datalen) {
1962 up_read(&key->sem);
1963 key_put(key);
1964 kzfree(new_key_string);
1965 return -EINVAL;
1966 }
1967
1968 memcpy(cc->key, ukp->data, cc->key_size);
1969
1970 up_read(&key->sem);
1971 key_put(key);
1972
1973 /* clear the flag since following operations may invalidate previously valid key */
1974 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
1975
1976 ret = crypt_setkey(cc);
1977
1978 if (!ret) {
1979 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
1980 kzfree(cc->key_string);
1981 cc->key_string = new_key_string;
1982 } else
1983 kzfree(new_key_string);
1984
1985 return ret;
1986}
1987
1988static int get_key_size(char **key_string)
1989{
1990 char *colon, dummy;
1991 int ret;
1992
1993 if (*key_string[0] != ':')
1994 return strlen(*key_string) >> 1;
1995
1996 /* look for next ':' in key string */
1997 colon = strpbrk(*key_string + 1, ":");
1998 if (!colon)
1999 return -EINVAL;
2000
2001 if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2002 return -EINVAL;
2003
2004 *key_string = colon;
2005
2006 /* remaining key string should be :<logon|user>:<key_desc> */
2007
2008 return ret;
2009}
2010
2011#else
2012
2013static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2014{
2015 return -EINVAL;
2016}
2017
2018static int get_key_size(char **key_string)
2019{
2020 return (*key_string[0] == ':') ? -EINVAL : (int)(strlen(*key_string) >> 1);
2021}
2022
2023#endif
2024
2025static int crypt_set_key(struct crypt_config *cc, char *key)
2026{
2027 int r = -EINVAL;
2028 int key_string_len = strlen(key);
2029
2030 /* Hyphen (which gives a key_size of zero) means there is no key. */
2031 if (!cc->key_size && strcmp(key, "-"))
2032 goto out;
2033
2034 /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2035 if (key[0] == ':') {
2036 r = crypt_set_keyring_key(cc, key + 1);
2037 goto out;
2038 }
2039
2040 /* clear the flag since following operations may invalidate previously valid key */
2041 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2042
2043 /* wipe references to any kernel keyring key */
2044 kzfree(cc->key_string);
2045 cc->key_string = NULL;
2046
2047 /* Decode key from its hex representation. */
2048 if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
2049 goto out;
2050
2051 r = crypt_setkey(cc);
2052 if (!r)
2053 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2054
2055out:
2056 /* Hex key string not needed after here, so wipe it. */
2057 memset(key, '0', key_string_len);
2058
2059 return r;
2060}
2061
2062static int crypt_wipe_key(struct crypt_config *cc)
2063{
2064 int r;
2065
2066 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2067 get_random_bytes(&cc->key, cc->key_size);
2068
2069 /* Wipe IV private keys */
2070 if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
2071 r = cc->iv_gen_ops->wipe(cc);
2072 if (r)
2073 return r;
2074 }
2075
2076 kzfree(cc->key_string);
2077 cc->key_string = NULL;
2078 r = crypt_setkey(cc);
2079 memset(&cc->key, 0, cc->key_size * sizeof(u8));
2080
2081 return r;
2082}
2083
2084static void crypt_calculate_pages_per_client(void)
2085{
2086 unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
2087
2088 if (!dm_crypt_clients_n)
2089 return;
2090
2091 pages /= dm_crypt_clients_n;
2092 if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
2093 pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
2094 dm_crypt_pages_per_client = pages;
2095}
2096
2097static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
2098{
2099 struct crypt_config *cc = pool_data;
2100 struct page *page;
2101
2102 /*
2103 * Note, percpu_counter_read_positive() may over (and under) estimate
2104 * the current usage by at most (batch - 1) * num_online_cpus() pages,
2105 * but avoids potential spinlock contention of an exact result.
2106 */
2107 if (unlikely(percpu_counter_read_positive(&cc->n_allocated_pages) >= dm_crypt_pages_per_client) &&
2108 likely(gfp_mask & __GFP_NORETRY))
2109 return NULL;
2110
2111 page = alloc_page(gfp_mask);
2112 if (likely(page != NULL))
2113 percpu_counter_add(&cc->n_allocated_pages, 1);
2114
2115 return page;
2116}
2117
2118static void crypt_page_free(void *page, void *pool_data)
2119{
2120 struct crypt_config *cc = pool_data;
2121
2122 __free_page(page);
2123 percpu_counter_sub(&cc->n_allocated_pages, 1);
2124}
2125
2126static void crypt_dtr(struct dm_target *ti)
2127{
2128 struct crypt_config *cc = ti->private;
2129
2130 ti->private = NULL;
2131
2132 if (!cc)
2133 return;
2134
2135 if (cc->write_thread)
2136 kthread_stop(cc->write_thread);
2137
2138 if (cc->io_queue)
2139 destroy_workqueue(cc->io_queue);
2140 if (cc->crypt_queue)
2141 destroy_workqueue(cc->crypt_queue);
2142
2143 crypt_free_tfms(cc);
2144
2145 bioset_exit(&cc->bs);
2146
2147 mempool_exit(&cc->page_pool);
2148 mempool_exit(&cc->req_pool);
2149 mempool_exit(&cc->tag_pool);
2150
2151 WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
2152 percpu_counter_destroy(&cc->n_allocated_pages);
2153
2154 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
2155 cc->iv_gen_ops->dtr(cc);
2156
2157 if (cc->dev)
2158 dm_put_device(ti, cc->dev);
2159
2160 kzfree(cc->cipher_string);
2161 kzfree(cc->key_string);
2162 kzfree(cc->cipher_auth);
2163 kzfree(cc->authenc_key);
2164
2165 mutex_destroy(&cc->bio_alloc_lock);
2166
2167 /* Must zero key material before freeing */
2168 kzfree(cc);
2169
2170 spin_lock(&dm_crypt_clients_lock);
2171 WARN_ON(!dm_crypt_clients_n);
2172 dm_crypt_clients_n--;
2173 crypt_calculate_pages_per_client();
2174 spin_unlock(&dm_crypt_clients_lock);
2175}
2176
2177static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
2178{
2179 struct crypt_config *cc = ti->private;
2180
2181 if (crypt_integrity_aead(cc))
2182 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2183 else
2184 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2185
2186 if (cc->iv_size)
2187 /* at least a 64 bit sector number should fit in our buffer */
2188 cc->iv_size = max(cc->iv_size,
2189 (unsigned int)(sizeof(u64) / sizeof(u8)));
2190 else if (ivmode) {
2191 DMWARN("Selected cipher does not support IVs");
2192 ivmode = NULL;
2193 }
2194
2195 /* Choose ivmode, see comments at iv code. */
2196 if (ivmode == NULL)
2197 cc->iv_gen_ops = NULL;
2198 else if (strcmp(ivmode, "plain") == 0)
2199 cc->iv_gen_ops = &crypt_iv_plain_ops;
2200 else if (strcmp(ivmode, "plain64") == 0)
2201 cc->iv_gen_ops = &crypt_iv_plain64_ops;
2202 else if (strcmp(ivmode, "plain64be") == 0)
2203 cc->iv_gen_ops = &crypt_iv_plain64be_ops;
2204 else if (strcmp(ivmode, "essiv") == 0)
2205 cc->iv_gen_ops = &crypt_iv_essiv_ops;
2206 else if (strcmp(ivmode, "benbi") == 0)
2207 cc->iv_gen_ops = &crypt_iv_benbi_ops;
2208 else if (strcmp(ivmode, "null") == 0)
2209 cc->iv_gen_ops = &crypt_iv_null_ops;
2210 else if (strcmp(ivmode, "eboiv") == 0)
2211 cc->iv_gen_ops = &crypt_iv_eboiv_ops;
2212 else if (strcmp(ivmode, "lmk") == 0) {
2213 cc->iv_gen_ops = &crypt_iv_lmk_ops;
2214 /*
2215 * Version 2 and 3 is recognised according
2216 * to length of provided multi-key string.
2217 * If present (version 3), last key is used as IV seed.
2218 * All keys (including IV seed) are always the same size.
2219 */
2220 if (cc->key_size % cc->key_parts) {
2221 cc->key_parts++;
2222 cc->key_extra_size = cc->key_size / cc->key_parts;
2223 }
2224 } else if (strcmp(ivmode, "tcw") == 0) {
2225 cc->iv_gen_ops = &crypt_iv_tcw_ops;
2226 cc->key_parts += 2; /* IV + whitening */
2227 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2228 } else if (strcmp(ivmode, "random") == 0) {
2229 cc->iv_gen_ops = &crypt_iv_random_ops;
2230 /* Need storage space in integrity fields. */
2231 cc->integrity_iv_size = cc->iv_size;
2232 } else {
2233 ti->error = "Invalid IV mode";
2234 return -EINVAL;
2235 }
2236
2237 return 0;
2238}
2239
2240/*
2241 * Workaround to parse HMAC algorithm from AEAD crypto API spec.
2242 * The HMAC is needed to calculate tag size (HMAC digest size).
2243 * This should be probably done by crypto-api calls (once available...)
2244 */
2245static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
2246{
2247 char *start, *end, *mac_alg = NULL;
2248 struct crypto_ahash *mac;
2249
2250 if (!strstarts(cipher_api, "authenc("))
2251 return 0;
2252
2253 start = strchr(cipher_api, '(');
2254 end = strchr(cipher_api, ',');
2255 if (!start || !end || ++start > end)
2256 return -EINVAL;
2257
2258 mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
2259 if (!mac_alg)
2260 return -ENOMEM;
2261 strncpy(mac_alg, start, end - start);
2262
2263 mac = crypto_alloc_ahash(mac_alg, 0, 0);
2264 kfree(mac_alg);
2265
2266 if (IS_ERR(mac))
2267 return PTR_ERR(mac);
2268
2269 cc->key_mac_size = crypto_ahash_digestsize(mac);
2270 crypto_free_ahash(mac);
2271
2272 cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
2273 if (!cc->authenc_key)
2274 return -ENOMEM;
2275
2276 return 0;
2277}
2278
2279static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
2280 char **ivmode, char **ivopts)
2281{
2282 struct crypt_config *cc = ti->private;
2283 char *tmp, *cipher_api, buf[CRYPTO_MAX_ALG_NAME];
2284 int ret = -EINVAL;
2285
2286 cc->tfms_count = 1;
2287
2288 /*
2289 * New format (capi: prefix)
2290 * capi:cipher_api_spec-iv:ivopts
2291 */
2292 tmp = &cipher_in[strlen("capi:")];
2293
2294 /* Separate IV options if present, it can contain another '-' in hash name */
2295 *ivopts = strrchr(tmp, ':');
2296 if (*ivopts) {
2297 **ivopts = '\0';
2298 (*ivopts)++;
2299 }
2300 /* Parse IV mode */
2301 *ivmode = strrchr(tmp, '-');
2302 if (*ivmode) {
2303 **ivmode = '\0';
2304 (*ivmode)++;
2305 }
2306 /* The rest is crypto API spec */
2307 cipher_api = tmp;
2308
2309 /* Alloc AEAD, can be used only in new format. */
2310 if (crypt_integrity_aead(cc)) {
2311 ret = crypt_ctr_auth_cipher(cc, cipher_api);
2312 if (ret < 0) {
2313 ti->error = "Invalid AEAD cipher spec";
2314 return -ENOMEM;
2315 }
2316 }
2317
2318 if (*ivmode && !strcmp(*ivmode, "lmk"))
2319 cc->tfms_count = 64;
2320
2321 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2322 if (!*ivopts) {
2323 ti->error = "Digest algorithm missing for ESSIV mode";
2324 return -EINVAL;
2325 }
2326 ret = snprintf(buf, CRYPTO_MAX_ALG_NAME, "essiv(%s,%s)",
2327 cipher_api, *ivopts);
2328 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2329 ti->error = "Cannot allocate cipher string";
2330 return -ENOMEM;
2331 }
2332 cipher_api = buf;
2333 }
2334
2335 cc->key_parts = cc->tfms_count;
2336
2337 /* Allocate cipher */
2338 ret = crypt_alloc_tfms(cc, cipher_api);
2339 if (ret < 0) {
2340 ti->error = "Error allocating crypto tfm";
2341 return ret;
2342 }
2343
2344 if (crypt_integrity_aead(cc))
2345 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2346 else
2347 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2348
2349 return 0;
2350}
2351
2352static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
2353 char **ivmode, char **ivopts)
2354{
2355 struct crypt_config *cc = ti->private;
2356 char *tmp, *cipher, *chainmode, *keycount;
2357 char *cipher_api = NULL;
2358 int ret = -EINVAL;
2359 char dummy;
2360
2361 if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
2362 ti->error = "Bad cipher specification";
2363 return -EINVAL;
2364 }
2365
2366 /*
2367 * Legacy dm-crypt cipher specification
2368 * cipher[:keycount]-mode-iv:ivopts
2369 */
2370 tmp = cipher_in;
2371 keycount = strsep(&tmp, "-");
2372 cipher = strsep(&keycount, ":");
2373
2374 if (!keycount)
2375 cc->tfms_count = 1;
2376 else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
2377 !is_power_of_2(cc->tfms_count)) {
2378 ti->error = "Bad cipher key count specification";
2379 return -EINVAL;
2380 }
2381 cc->key_parts = cc->tfms_count;
2382
2383 chainmode = strsep(&tmp, "-");
2384 *ivmode = strsep(&tmp, ":");
2385 *ivopts = tmp;
2386
2387 /*
2388 * For compatibility with the original dm-crypt mapping format, if
2389 * only the cipher name is supplied, use cbc-plain.
2390 */
2391 if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
2392 chainmode = "cbc";
2393 *ivmode = "plain";
2394 }
2395
2396 if (strcmp(chainmode, "ecb") && !*ivmode) {
2397 ti->error = "IV mechanism required";
2398 return -EINVAL;
2399 }
2400
2401 cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
2402 if (!cipher_api)
2403 goto bad_mem;
2404
2405 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2406 if (!*ivopts) {
2407 ti->error = "Digest algorithm missing for ESSIV mode";
2408 kfree(cipher_api);
2409 return -EINVAL;
2410 }
2411 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2412 "essiv(%s(%s),%s)", chainmode, cipher, *ivopts);
2413 } else {
2414 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2415 "%s(%s)", chainmode, cipher);
2416 }
2417 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2418 kfree(cipher_api);
2419 goto bad_mem;
2420 }
2421
2422 /* Allocate cipher */
2423 ret = crypt_alloc_tfms(cc, cipher_api);
2424 if (ret < 0) {
2425 ti->error = "Error allocating crypto tfm";
2426 kfree(cipher_api);
2427 return ret;
2428 }
2429 kfree(cipher_api);
2430
2431 return 0;
2432bad_mem:
2433 ti->error = "Cannot allocate cipher strings";
2434 return -ENOMEM;
2435}
2436
2437static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
2438{
2439 struct crypt_config *cc = ti->private;
2440 char *ivmode = NULL, *ivopts = NULL;
2441 int ret;
2442
2443 cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
2444 if (!cc->cipher_string) {
2445 ti->error = "Cannot allocate cipher strings";
2446 return -ENOMEM;
2447 }
2448
2449 if (strstarts(cipher_in, "capi:"))
2450 ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
2451 else
2452 ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
2453 if (ret)
2454 return ret;
2455
2456 /* Initialize IV */
2457 ret = crypt_ctr_ivmode(ti, ivmode);
2458 if (ret < 0)
2459 return ret;
2460
2461 /* Initialize and set key */
2462 ret = crypt_set_key(cc, key);
2463 if (ret < 0) {
2464 ti->error = "Error decoding and setting key";
2465 return ret;
2466 }
2467
2468 /* Allocate IV */
2469 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
2470 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
2471 if (ret < 0) {
2472 ti->error = "Error creating IV";
2473 return ret;
2474 }
2475 }
2476
2477 /* Initialize IV (set keys for ESSIV etc) */
2478 if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
2479 ret = cc->iv_gen_ops->init(cc);
2480 if (ret < 0) {
2481 ti->error = "Error initialising IV";
2482 return ret;
2483 }
2484 }
2485
2486 /* wipe the kernel key payload copy */
2487 if (cc->key_string)
2488 memset(cc->key, 0, cc->key_size * sizeof(u8));
2489
2490 return ret;
2491}
2492
2493static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
2494{
2495 struct crypt_config *cc = ti->private;
2496 struct dm_arg_set as;
2497 static const struct dm_arg _args[] = {
2498 {0, 6, "Invalid number of feature args"},
2499 };
2500 unsigned int opt_params, val;
2501 const char *opt_string, *sval;
2502 char dummy;
2503 int ret;
2504
2505 /* Optional parameters */
2506 as.argc = argc;
2507 as.argv = argv;
2508
2509 ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
2510 if (ret)
2511 return ret;
2512
2513 while (opt_params--) {
2514 opt_string = dm_shift_arg(&as);
2515 if (!opt_string) {
2516 ti->error = "Not enough feature arguments";
2517 return -EINVAL;
2518 }
2519
2520 if (!strcasecmp(opt_string, "allow_discards"))
2521 ti->num_discard_bios = 1;
2522
2523 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
2524 set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
2525
2526 else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
2527 set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
2528 else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
2529 if (val == 0 || val > MAX_TAG_SIZE) {
2530 ti->error = "Invalid integrity arguments";
2531 return -EINVAL;
2532 }
2533 cc->on_disk_tag_size = val;
2534 sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
2535 if (!strcasecmp(sval, "aead")) {
2536 set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
2537 } else if (strcasecmp(sval, "none")) {
2538 ti->error = "Unknown integrity profile";
2539 return -EINVAL;
2540 }
2541
2542 cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
2543 if (!cc->cipher_auth)
2544 return -ENOMEM;
2545 } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
2546 if (cc->sector_size < (1 << SECTOR_SHIFT) ||
2547 cc->sector_size > 4096 ||
2548 (cc->sector_size & (cc->sector_size - 1))) {
2549 ti->error = "Invalid feature value for sector_size";
2550 return -EINVAL;
2551 }
2552 if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
2553 ti->error = "Device size is not multiple of sector_size feature";
2554 return -EINVAL;
2555 }
2556 cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
2557 } else if (!strcasecmp(opt_string, "iv_large_sectors"))
2558 set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
2559 else {
2560 ti->error = "Invalid feature arguments";
2561 return -EINVAL;
2562 }
2563 }
2564
2565 return 0;
2566}
2567
2568/*
2569 * Construct an encryption mapping:
2570 * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
2571 */
2572static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
2573{
2574 struct crypt_config *cc;
2575 const char *devname = dm_table_device_name(ti->table);
2576 int key_size;
2577 unsigned int align_mask;
2578 unsigned long long tmpll;
2579 int ret;
2580 size_t iv_size_padding, additional_req_size;
2581 char dummy;
2582
2583 if (argc < 5) {
2584 ti->error = "Not enough arguments";
2585 return -EINVAL;
2586 }
2587
2588 key_size = get_key_size(&argv[1]);
2589 if (key_size < 0) {
2590 ti->error = "Cannot parse key size";
2591 return -EINVAL;
2592 }
2593
2594 cc = kzalloc(struct_size(cc, key, key_size), GFP_KERNEL);
2595 if (!cc) {
2596 ti->error = "Cannot allocate encryption context";
2597 return -ENOMEM;
2598 }
2599 cc->key_size = key_size;
2600 cc->sector_size = (1 << SECTOR_SHIFT);
2601 cc->sector_shift = 0;
2602
2603 ti->private = cc;
2604
2605 spin_lock(&dm_crypt_clients_lock);
2606 dm_crypt_clients_n++;
2607 crypt_calculate_pages_per_client();
2608 spin_unlock(&dm_crypt_clients_lock);
2609
2610 ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
2611 if (ret < 0)
2612 goto bad;
2613
2614 /* Optional parameters need to be read before cipher constructor */
2615 if (argc > 5) {
2616 ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
2617 if (ret)
2618 goto bad;
2619 }
2620
2621 ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
2622 if (ret < 0)
2623 goto bad;
2624
2625 if (crypt_integrity_aead(cc)) {
2626 cc->dmreq_start = sizeof(struct aead_request);
2627 cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
2628 align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
2629 } else {
2630 cc->dmreq_start = sizeof(struct skcipher_request);
2631 cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
2632 align_mask = crypto_skcipher_alignmask(any_tfm(cc));
2633 }
2634 cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
2635
2636 if (align_mask < CRYPTO_MINALIGN) {
2637 /* Allocate the padding exactly */
2638 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
2639 & align_mask;
2640 } else {
2641 /*
2642 * If the cipher requires greater alignment than kmalloc
2643 * alignment, we don't know the exact position of the
2644 * initialization vector. We must assume worst case.
2645 */
2646 iv_size_padding = align_mask;
2647 }
2648
2649 /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
2650 additional_req_size = sizeof(struct dm_crypt_request) +
2651 iv_size_padding + cc->iv_size +
2652 cc->iv_size +
2653 sizeof(uint64_t) +
2654 sizeof(unsigned int);
2655
2656 ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
2657 if (ret) {
2658 ti->error = "Cannot allocate crypt request mempool";
2659 goto bad;
2660 }
2661
2662 cc->per_bio_data_size = ti->per_io_data_size =
2663 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
2664 ARCH_KMALLOC_MINALIGN);
2665
2666 ret = mempool_init(&cc->page_pool, BIO_MAX_PAGES, crypt_page_alloc, crypt_page_free, cc);
2667 if (ret) {
2668 ti->error = "Cannot allocate page mempool";
2669 goto bad;
2670 }
2671
2672 ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
2673 if (ret) {
2674 ti->error = "Cannot allocate crypt bioset";
2675 goto bad;
2676 }
2677
2678 mutex_init(&cc->bio_alloc_lock);
2679
2680 ret = -EINVAL;
2681 if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
2682 (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
2683 ti->error = "Invalid iv_offset sector";
2684 goto bad;
2685 }
2686 cc->iv_offset = tmpll;
2687
2688 ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
2689 if (ret) {
2690 ti->error = "Device lookup failed";
2691 goto bad;
2692 }
2693
2694 ret = -EINVAL;
2695 if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
2696 ti->error = "Invalid device sector";
2697 goto bad;
2698 }
2699 cc->start = tmpll;
2700
2701 if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
2702 ret = crypt_integrity_ctr(cc, ti);
2703 if (ret)
2704 goto bad;
2705
2706 cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
2707 if (!cc->tag_pool_max_sectors)
2708 cc->tag_pool_max_sectors = 1;
2709
2710 ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
2711 cc->tag_pool_max_sectors * cc->on_disk_tag_size);
2712 if (ret) {
2713 ti->error = "Cannot allocate integrity tags mempool";
2714 goto bad;
2715 }
2716
2717 cc->tag_pool_max_sectors <<= cc->sector_shift;
2718 }
2719
2720 ret = -ENOMEM;
2721 cc->io_queue = alloc_workqueue("kcryptd_io/%s", WQ_MEM_RECLAIM, 1, devname);
2722 if (!cc->io_queue) {
2723 ti->error = "Couldn't create kcryptd io queue";
2724 goto bad;
2725 }
2726
2727 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
2728 cc->crypt_queue = alloc_workqueue("kcryptd/%s", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM,
2729 1, devname);
2730 else
2731 cc->crypt_queue = alloc_workqueue("kcryptd/%s",
2732 WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
2733 num_online_cpus(), devname);
2734 if (!cc->crypt_queue) {
2735 ti->error = "Couldn't create kcryptd queue";
2736 goto bad;
2737 }
2738
2739 spin_lock_init(&cc->write_thread_lock);
2740 cc->write_tree = RB_ROOT;
2741
2742 cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
2743 if (IS_ERR(cc->write_thread)) {
2744 ret = PTR_ERR(cc->write_thread);
2745 cc->write_thread = NULL;
2746 ti->error = "Couldn't spawn write thread";
2747 goto bad;
2748 }
2749 wake_up_process(cc->write_thread);
2750
2751 ti->num_flush_bios = 1;
2752 ti->limit_swap_bios = true;
2753
2754 return 0;
2755
2756bad:
2757 crypt_dtr(ti);
2758 return ret;
2759}
2760
2761static int crypt_map(struct dm_target *ti, struct bio *bio)
2762{
2763 struct dm_crypt_io *io;
2764 struct crypt_config *cc = ti->private;
2765
2766 /*
2767 * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
2768 * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
2769 * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
2770 */
2771 if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
2772 bio_op(bio) == REQ_OP_DISCARD)) {
2773 bio_set_dev(bio, cc->dev->bdev);
2774 if (bio_sectors(bio))
2775 bio->bi_iter.bi_sector = cc->start +
2776 dm_target_offset(ti, bio->bi_iter.bi_sector);
2777 return DM_MAPIO_REMAPPED;
2778 }
2779
2780 /*
2781 * Check if bio is too large, split as needed.
2782 */
2783 if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_PAGES << PAGE_SHIFT)) &&
2784 (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
2785 dm_accept_partial_bio(bio, ((BIO_MAX_PAGES << PAGE_SHIFT) >> SECTOR_SHIFT));
2786
2787 /*
2788 * Ensure that bio is a multiple of internal sector encryption size
2789 * and is aligned to this size as defined in IO hints.
2790 */
2791 if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
2792 return DM_MAPIO_KILL;
2793
2794 if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
2795 return DM_MAPIO_KILL;
2796
2797 io = dm_per_bio_data(bio, cc->per_bio_data_size);
2798 crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
2799
2800 if (cc->on_disk_tag_size) {
2801 unsigned tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
2802
2803 if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
2804 unlikely(!(io->integrity_metadata = kmalloc(tag_len,
2805 GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
2806 if (bio_sectors(bio) > cc->tag_pool_max_sectors)
2807 dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
2808 io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
2809 io->integrity_metadata_from_pool = true;
2810 }
2811 }
2812
2813 if (crypt_integrity_aead(cc))
2814 io->ctx.r.req_aead = (struct aead_request *)(io + 1);
2815 else
2816 io->ctx.r.req = (struct skcipher_request *)(io + 1);
2817
2818 if (bio_data_dir(io->base_bio) == READ) {
2819 if (kcryptd_io_read(io, GFP_NOWAIT))
2820 kcryptd_queue_read(io);
2821 } else
2822 kcryptd_queue_crypt(io);
2823
2824 return DM_MAPIO_SUBMITTED;
2825}
2826
2827static char hex2asc(unsigned char c)
2828{
2829 return c + '0' + ((unsigned)(9 - c) >> 4 & 0x27);
2830}
2831
2832static void crypt_status(struct dm_target *ti, status_type_t type,
2833 unsigned status_flags, char *result, unsigned maxlen)
2834{
2835 struct crypt_config *cc = ti->private;
2836 unsigned i, sz = 0;
2837 int num_feature_args = 0;
2838
2839 switch (type) {
2840 case STATUSTYPE_INFO:
2841 result[0] = '\0';
2842 break;
2843
2844 case STATUSTYPE_TABLE:
2845 DMEMIT("%s ", cc->cipher_string);
2846
2847 if (cc->key_size > 0) {
2848 if (cc->key_string)
2849 DMEMIT(":%u:%s", cc->key_size, cc->key_string);
2850 else {
2851 for (i = 0; i < cc->key_size; i++) {
2852 DMEMIT("%c%c", hex2asc(cc->key[i] >> 4),
2853 hex2asc(cc->key[i] & 0xf));
2854 }
2855 }
2856 } else
2857 DMEMIT("-");
2858
2859 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
2860 cc->dev->name, (unsigned long long)cc->start);
2861
2862 num_feature_args += !!ti->num_discard_bios;
2863 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
2864 num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
2865 num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
2866 num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
2867 if (cc->on_disk_tag_size)
2868 num_feature_args++;
2869 if (num_feature_args) {
2870 DMEMIT(" %d", num_feature_args);
2871 if (ti->num_discard_bios)
2872 DMEMIT(" allow_discards");
2873 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
2874 DMEMIT(" same_cpu_crypt");
2875 if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
2876 DMEMIT(" submit_from_crypt_cpus");
2877 if (cc->on_disk_tag_size)
2878 DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
2879 if (cc->sector_size != (1 << SECTOR_SHIFT))
2880 DMEMIT(" sector_size:%d", cc->sector_size);
2881 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
2882 DMEMIT(" iv_large_sectors");
2883 }
2884
2885 break;
2886 }
2887}
2888
2889static void crypt_postsuspend(struct dm_target *ti)
2890{
2891 struct crypt_config *cc = ti->private;
2892
2893 set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
2894}
2895
2896static int crypt_preresume(struct dm_target *ti)
2897{
2898 struct crypt_config *cc = ti->private;
2899
2900 if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
2901 DMERR("aborting resume - crypt key is not set.");
2902 return -EAGAIN;
2903 }
2904
2905 return 0;
2906}
2907
2908static void crypt_resume(struct dm_target *ti)
2909{
2910 struct crypt_config *cc = ti->private;
2911
2912 clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
2913}
2914
2915/* Message interface
2916 * key set <key>
2917 * key wipe
2918 */
2919static int crypt_message(struct dm_target *ti, unsigned argc, char **argv,
2920 char *result, unsigned maxlen)
2921{
2922 struct crypt_config *cc = ti->private;
2923 int key_size, ret = -EINVAL;
2924
2925 if (argc < 2)
2926 goto error;
2927
2928 if (!strcasecmp(argv[0], "key")) {
2929 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
2930 DMWARN("not suspended during key manipulation.");
2931 return -EINVAL;
2932 }
2933 if (argc == 3 && !strcasecmp(argv[1], "set")) {
2934 /* The key size may not be changed. */
2935 key_size = get_key_size(&argv[2]);
2936 if (key_size < 0 || cc->key_size != key_size) {
2937 memset(argv[2], '0', strlen(argv[2]));
2938 return -EINVAL;
2939 }
2940
2941 ret = crypt_set_key(cc, argv[2]);
2942 if (ret)
2943 return ret;
2944 if (cc->iv_gen_ops && cc->iv_gen_ops->init)
2945 ret = cc->iv_gen_ops->init(cc);
2946 /* wipe the kernel key payload copy */
2947 if (cc->key_string)
2948 memset(cc->key, 0, cc->key_size * sizeof(u8));
2949 return ret;
2950 }
2951 if (argc == 2 && !strcasecmp(argv[1], "wipe"))
2952 return crypt_wipe_key(cc);
2953 }
2954
2955error:
2956 DMWARN("unrecognised message received.");
2957 return -EINVAL;
2958}
2959
2960static int crypt_iterate_devices(struct dm_target *ti,
2961 iterate_devices_callout_fn fn, void *data)
2962{
2963 struct crypt_config *cc = ti->private;
2964
2965 return fn(ti, cc->dev, cc->start, ti->len, data);
2966}
2967
2968static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
2969{
2970 struct crypt_config *cc = ti->private;
2971
2972 /*
2973 * Unfortunate constraint that is required to avoid the potential
2974 * for exceeding underlying device's max_segments limits -- due to
2975 * crypt_alloc_buffer() possibly allocating pages for the encryption
2976 * bio that are not as physically contiguous as the original bio.
2977 */
2978 limits->max_segment_size = PAGE_SIZE;
2979
2980 limits->logical_block_size =
2981 max_t(unsigned, limits->logical_block_size, cc->sector_size);
2982 limits->physical_block_size =
2983 max_t(unsigned, limits->physical_block_size, cc->sector_size);
2984 limits->io_min = max_t(unsigned, limits->io_min, cc->sector_size);
2985}
2986
2987static struct target_type crypt_target = {
2988 .name = "crypt",
2989 .version = {1, 19, 0},
2990 .module = THIS_MODULE,
2991 .ctr = crypt_ctr,
2992 .dtr = crypt_dtr,
2993 .map = crypt_map,
2994 .status = crypt_status,
2995 .postsuspend = crypt_postsuspend,
2996 .preresume = crypt_preresume,
2997 .resume = crypt_resume,
2998 .message = crypt_message,
2999 .iterate_devices = crypt_iterate_devices,
3000 .io_hints = crypt_io_hints,
3001};
3002
3003static int __init dm_crypt_init(void)
3004{
3005 int r;
3006
3007 r = dm_register_target(&crypt_target);
3008 if (r < 0)
3009 DMERR("register failed %d", r);
3010
3011 return r;
3012}
3013
3014static void __exit dm_crypt_exit(void)
3015{
3016 dm_unregister_target(&crypt_target);
3017}
3018
3019module_init(dm_crypt_init);
3020module_exit(dm_crypt_exit);
3021
3022MODULE_AUTHOR("Jana Saout <jana@saout.de>");
3023MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
3024MODULE_LICENSE("GPL");