]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - drivers/md/dm-crypt.c
block: Kill bio_segments()/bi_vcnt usage
[mirror_ubuntu-bionic-kernel.git] / drivers / md / dm-crypt.c
CommitLineData
1da177e4
LT
1/*
2 * Copyright (C) 2003 Christophe Saout <christophe@saout.de>
3 * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
542da317 4 * Copyright (C) 2006-2009 Red Hat, Inc. All rights reserved.
ed04d981 5 * Copyright (C) 2013 Milan Broz <gmazyland@gmail.com>
1da177e4
LT
6 *
7 * This file is released under the GPL.
8 */
9
43d69034 10#include <linux/completion.h>
d1806f6a 11#include <linux/err.h>
1da177e4
LT
12#include <linux/module.h>
13#include <linux/init.h>
14#include <linux/kernel.h>
15#include <linux/bio.h>
16#include <linux/blkdev.h>
17#include <linux/mempool.h>
18#include <linux/slab.h>
19#include <linux/crypto.h>
20#include <linux/workqueue.h>
3fcfab16 21#include <linux/backing-dev.h>
c0297721 22#include <linux/percpu.h>
60063497 23#include <linux/atomic.h>
378f058c 24#include <linux/scatterlist.h>
1da177e4 25#include <asm/page.h>
48527fa7 26#include <asm/unaligned.h>
34745785
MB
27#include <crypto/hash.h>
28#include <crypto/md5.h>
29#include <crypto/algapi.h>
1da177e4 30
586e80e6 31#include <linux/device-mapper.h>
1da177e4 32
72d94861 33#define DM_MSG_PREFIX "crypt"
1da177e4 34
1da177e4
LT
35/*
36 * context holding the current state of a multi-part conversion
37 */
38struct convert_context {
43d69034 39 struct completion restart;
1da177e4
LT
40 struct bio *bio_in;
41 struct bio *bio_out;
42 unsigned int offset_in;
43 unsigned int offset_out;
44 unsigned int idx_in;
45 unsigned int idx_out;
c66029f4 46 sector_t cc_sector;
40b6229b 47 atomic_t cc_pending;
1da177e4
LT
48};
49
53017030
MB
50/*
51 * per bio private data
52 */
53struct dm_crypt_io {
49a8a920 54 struct crypt_config *cc;
53017030
MB
55 struct bio *base_bio;
56 struct work_struct work;
57
58 struct convert_context ctx;
59
40b6229b 60 atomic_t io_pending;
53017030 61 int error;
0c395b0f 62 sector_t sector;
393b47ef 63 struct dm_crypt_io *base_io;
53017030
MB
64};
65
01482b76 66struct dm_crypt_request {
b2174eeb 67 struct convert_context *ctx;
01482b76
MB
68 struct scatterlist sg_in;
69 struct scatterlist sg_out;
2dc5327d 70 sector_t iv_sector;
01482b76
MB
71};
72
1da177e4
LT
73struct crypt_config;
74
75struct crypt_iv_operations {
76 int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
d469f841 77 const char *opts);
1da177e4 78 void (*dtr)(struct crypt_config *cc);
b95bf2d3 79 int (*init)(struct crypt_config *cc);
542da317 80 int (*wipe)(struct crypt_config *cc);
2dc5327d
MB
81 int (*generator)(struct crypt_config *cc, u8 *iv,
82 struct dm_crypt_request *dmreq);
83 int (*post)(struct crypt_config *cc, u8 *iv,
84 struct dm_crypt_request *dmreq);
1da177e4
LT
85};
86
60473592 87struct iv_essiv_private {
b95bf2d3
MB
88 struct crypto_hash *hash_tfm;
89 u8 *salt;
60473592
MB
90};
91
92struct iv_benbi_private {
93 int shift;
94};
95
34745785
MB
96#define LMK_SEED_SIZE 64 /* hash + 0 */
97struct iv_lmk_private {
98 struct crypto_shash *hash_tfm;
99 u8 *seed;
100};
101
ed04d981
MB
102#define TCW_WHITENING_SIZE 16
103struct iv_tcw_private {
104 struct crypto_shash *crc32_tfm;
105 u8 *iv_seed;
106 u8 *whitening;
107};
108
1da177e4
LT
109/*
110 * Crypt: maps a linear range of a block device
111 * and encrypts / decrypts at the same time.
112 */
e48d4bbf 113enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID };
c0297721
AK
114
115/*
116 * Duplicated per-CPU state for cipher.
117 */
118struct crypt_cpu {
119 struct ablkcipher_request *req;
c0297721
AK
120};
121
122/*
123 * The fields in here must be read only after initialization,
124 * changing state should be in crypt_cpu.
125 */
1da177e4
LT
126struct crypt_config {
127 struct dm_dev *dev;
128 sector_t start;
129
130 /*
ddd42edf
MB
131 * pool for per bio private data, crypto requests and
132 * encryption requeusts/buffer pages
1da177e4
LT
133 */
134 mempool_t *io_pool;
ddd42edf 135 mempool_t *req_pool;
1da177e4 136 mempool_t *page_pool;
6a24c718 137 struct bio_set *bs;
1da177e4 138
cabf08e4
MB
139 struct workqueue_struct *io_queue;
140 struct workqueue_struct *crypt_queue;
3f1e9070 141
5ebaee6d 142 char *cipher;
7dbcd137 143 char *cipher_string;
5ebaee6d 144
1da177e4 145 struct crypt_iv_operations *iv_gen_ops;
79066ad3 146 union {
60473592
MB
147 struct iv_essiv_private essiv;
148 struct iv_benbi_private benbi;
34745785 149 struct iv_lmk_private lmk;
ed04d981 150 struct iv_tcw_private tcw;
79066ad3 151 } iv_gen_private;
1da177e4
LT
152 sector_t iv_offset;
153 unsigned int iv_size;
154
c0297721
AK
155 /*
156 * Duplicated per cpu state. Access through
157 * per_cpu_ptr() only.
158 */
159 struct crypt_cpu __percpu *cpu;
fd2d231f
MP
160
161 /* ESSIV: struct crypto_cipher *essiv_tfm */
162 void *iv_private;
163 struct crypto_ablkcipher **tfms;
d1f96423 164 unsigned tfms_count;
c0297721 165
ddd42edf
MB
166 /*
167 * Layout of each crypto request:
168 *
169 * struct ablkcipher_request
170 * context
171 * padding
172 * struct dm_crypt_request
173 * padding
174 * IV
175 *
176 * The padding is added so that dm_crypt_request and the IV are
177 * correctly aligned.
178 */
179 unsigned int dmreq_start;
ddd42edf 180
e48d4bbf 181 unsigned long flags;
1da177e4 182 unsigned int key_size;
da31a078
MB
183 unsigned int key_parts; /* independent parts in key buffer */
184 unsigned int key_extra_size; /* additional keys length */
1da177e4
LT
185 u8 key[0];
186};
187
6a24c718 188#define MIN_IOS 16
1da177e4 189#define MIN_POOL_PAGES 32
1da177e4 190
e18b890b 191static struct kmem_cache *_crypt_io_pool;
1da177e4 192
028867ac 193static void clone_init(struct dm_crypt_io *, struct bio *);
395b167c 194static void kcryptd_queue_crypt(struct dm_crypt_io *io);
2dc5327d 195static u8 *iv_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq);
027581f3 196
c0297721
AK
197static struct crypt_cpu *this_crypt_config(struct crypt_config *cc)
198{
199 return this_cpu_ptr(cc->cpu);
200}
201
202/*
203 * Use this to access cipher attributes that are the same for each CPU.
204 */
205static struct crypto_ablkcipher *any_tfm(struct crypt_config *cc)
206{
fd2d231f 207 return cc->tfms[0];
c0297721
AK
208}
209
1da177e4
LT
210/*
211 * Different IV generation algorithms:
212 *
3c164bd8 213 * plain: the initial vector is the 32-bit little-endian version of the sector
3a4fa0a2 214 * number, padded with zeros if necessary.
1da177e4 215 *
61afef61
MB
216 * plain64: the initial vector is the 64-bit little-endian version of the sector
217 * number, padded with zeros if necessary.
218 *
3c164bd8
RS
219 * essiv: "encrypted sector|salt initial vector", the sector number is
220 * encrypted with the bulk cipher using a salt as key. The salt
221 * should be derived from the bulk cipher's key via hashing.
1da177e4 222 *
48527fa7
RS
223 * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
224 * (needed for LRW-32-AES and possible other narrow block modes)
225 *
46b47730
LN
226 * null: the initial vector is always zero. Provides compatibility with
227 * obsolete loop_fish2 devices. Do not use for new devices.
228 *
34745785
MB
229 * lmk: Compatible implementation of the block chaining mode used
230 * by the Loop-AES block device encryption system
231 * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
232 * It operates on full 512 byte sectors and uses CBC
233 * with an IV derived from the sector number, the data and
234 * optionally extra IV seed.
235 * This means that after decryption the first block
236 * of sector must be tweaked according to decrypted data.
237 * Loop-AES can use three encryption schemes:
238 * version 1: is plain aes-cbc mode
239 * version 2: uses 64 multikey scheme with lmk IV generator
240 * version 3: the same as version 2 with additional IV seed
241 * (it uses 65 keys, last key is used as IV seed)
242 *
ed04d981
MB
243 * tcw: Compatible implementation of the block chaining mode used
244 * by the TrueCrypt device encryption system (prior to version 4.1).
245 * For more info see: http://www.truecrypt.org
246 * It operates on full 512 byte sectors and uses CBC
247 * with an IV derived from initial key and the sector number.
248 * In addition, whitening value is applied on every sector, whitening
249 * is calculated from initial key, sector number and mixed using CRC32.
250 * Note that this encryption scheme is vulnerable to watermarking attacks
251 * and should be used for old compatible containers access only.
252 *
1da177e4
LT
253 * plumb: unimplemented, see:
254 * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
255 */
256
2dc5327d
MB
257static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
258 struct dm_crypt_request *dmreq)
1da177e4
LT
259{
260 memset(iv, 0, cc->iv_size);
283a8328 261 *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
1da177e4
LT
262
263 return 0;
264}
265
61afef61 266static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
2dc5327d 267 struct dm_crypt_request *dmreq)
61afef61
MB
268{
269 memset(iv, 0, cc->iv_size);
283a8328 270 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
61afef61
MB
271
272 return 0;
273}
274
b95bf2d3
MB
275/* Initialise ESSIV - compute salt but no local memory allocations */
276static int crypt_iv_essiv_init(struct crypt_config *cc)
277{
278 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
279 struct hash_desc desc;
280 struct scatterlist sg;
c0297721 281 struct crypto_cipher *essiv_tfm;
fd2d231f 282 int err;
b95bf2d3
MB
283
284 sg_init_one(&sg, cc->key, cc->key_size);
285 desc.tfm = essiv->hash_tfm;
286 desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
287
288 err = crypto_hash_digest(&desc, &sg, cc->key_size, essiv->salt);
289 if (err)
290 return err;
291
fd2d231f 292 essiv_tfm = cc->iv_private;
c0297721 293
fd2d231f
MP
294 err = crypto_cipher_setkey(essiv_tfm, essiv->salt,
295 crypto_hash_digestsize(essiv->hash_tfm));
296 if (err)
297 return err;
c0297721
AK
298
299 return 0;
b95bf2d3
MB
300}
301
542da317
MB
302/* Wipe salt and reset key derived from volume key */
303static int crypt_iv_essiv_wipe(struct crypt_config *cc)
304{
305 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
306 unsigned salt_size = crypto_hash_digestsize(essiv->hash_tfm);
c0297721 307 struct crypto_cipher *essiv_tfm;
fd2d231f 308 int r, err = 0;
542da317
MB
309
310 memset(essiv->salt, 0, salt_size);
311
fd2d231f
MP
312 essiv_tfm = cc->iv_private;
313 r = crypto_cipher_setkey(essiv_tfm, essiv->salt, salt_size);
314 if (r)
315 err = r;
c0297721
AK
316
317 return err;
318}
319
320/* Set up per cpu cipher state */
321static struct crypto_cipher *setup_essiv_cpu(struct crypt_config *cc,
322 struct dm_target *ti,
323 u8 *salt, unsigned saltsize)
324{
325 struct crypto_cipher *essiv_tfm;
326 int err;
327
328 /* Setup the essiv_tfm with the given salt */
329 essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
330 if (IS_ERR(essiv_tfm)) {
331 ti->error = "Error allocating crypto tfm for ESSIV";
332 return essiv_tfm;
333 }
334
335 if (crypto_cipher_blocksize(essiv_tfm) !=
336 crypto_ablkcipher_ivsize(any_tfm(cc))) {
337 ti->error = "Block size of ESSIV cipher does "
338 "not match IV size of block cipher";
339 crypto_free_cipher(essiv_tfm);
340 return ERR_PTR(-EINVAL);
341 }
342
343 err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
344 if (err) {
345 ti->error = "Failed to set key for ESSIV cipher";
346 crypto_free_cipher(essiv_tfm);
347 return ERR_PTR(err);
348 }
349
350 return essiv_tfm;
542da317
MB
351}
352
60473592
MB
353static void crypt_iv_essiv_dtr(struct crypt_config *cc)
354{
c0297721 355 struct crypto_cipher *essiv_tfm;
60473592
MB
356 struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
357
b95bf2d3
MB
358 crypto_free_hash(essiv->hash_tfm);
359 essiv->hash_tfm = NULL;
360
361 kzfree(essiv->salt);
362 essiv->salt = NULL;
c0297721 363
fd2d231f 364 essiv_tfm = cc->iv_private;
c0297721 365
fd2d231f
MP
366 if (essiv_tfm)
367 crypto_free_cipher(essiv_tfm);
c0297721 368
fd2d231f 369 cc->iv_private = NULL;
60473592
MB
370}
371
1da177e4 372static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
d469f841 373 const char *opts)
1da177e4 374{
5861f1be
MB
375 struct crypto_cipher *essiv_tfm = NULL;
376 struct crypto_hash *hash_tfm = NULL;
5861f1be 377 u8 *salt = NULL;
fd2d231f 378 int err;
1da177e4 379
5861f1be 380 if (!opts) {
72d94861 381 ti->error = "Digest algorithm missing for ESSIV mode";
1da177e4
LT
382 return -EINVAL;
383 }
384
b95bf2d3 385 /* Allocate hash algorithm */
35058687
HX
386 hash_tfm = crypto_alloc_hash(opts, 0, CRYPTO_ALG_ASYNC);
387 if (IS_ERR(hash_tfm)) {
72d94861 388 ti->error = "Error initializing ESSIV hash";
5861f1be
MB
389 err = PTR_ERR(hash_tfm);
390 goto bad;
1da177e4
LT
391 }
392
b95bf2d3 393 salt = kzalloc(crypto_hash_digestsize(hash_tfm), GFP_KERNEL);
5861f1be 394 if (!salt) {
72d94861 395 ti->error = "Error kmallocing salt storage in ESSIV";
5861f1be
MB
396 err = -ENOMEM;
397 goto bad;
1da177e4
LT
398 }
399
b95bf2d3 400 cc->iv_gen_private.essiv.salt = salt;
b95bf2d3
MB
401 cc->iv_gen_private.essiv.hash_tfm = hash_tfm;
402
fd2d231f
MP
403 essiv_tfm = setup_essiv_cpu(cc, ti, salt,
404 crypto_hash_digestsize(hash_tfm));
405 if (IS_ERR(essiv_tfm)) {
406 crypt_iv_essiv_dtr(cc);
407 return PTR_ERR(essiv_tfm);
c0297721 408 }
fd2d231f 409 cc->iv_private = essiv_tfm;
c0297721 410
1da177e4 411 return 0;
5861f1be
MB
412
413bad:
5861f1be
MB
414 if (hash_tfm && !IS_ERR(hash_tfm))
415 crypto_free_hash(hash_tfm);
b95bf2d3 416 kfree(salt);
5861f1be 417 return err;
1da177e4
LT
418}
419
2dc5327d
MB
420static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
421 struct dm_crypt_request *dmreq)
1da177e4 422{
fd2d231f 423 struct crypto_cipher *essiv_tfm = cc->iv_private;
c0297721 424
1da177e4 425 memset(iv, 0, cc->iv_size);
283a8328 426 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
c0297721
AK
427 crypto_cipher_encrypt_one(essiv_tfm, iv, iv);
428
1da177e4
LT
429 return 0;
430}
431
48527fa7
RS
432static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
433 const char *opts)
434{
c0297721 435 unsigned bs = crypto_ablkcipher_blocksize(any_tfm(cc));
f0d1b0b3 436 int log = ilog2(bs);
48527fa7
RS
437
438 /* we need to calculate how far we must shift the sector count
439 * to get the cipher block count, we use this shift in _gen */
440
441 if (1 << log != bs) {
442 ti->error = "cypher blocksize is not a power of 2";
443 return -EINVAL;
444 }
445
446 if (log > 9) {
447 ti->error = "cypher blocksize is > 512";
448 return -EINVAL;
449 }
450
60473592 451 cc->iv_gen_private.benbi.shift = 9 - log;
48527fa7
RS
452
453 return 0;
454}
455
456static void crypt_iv_benbi_dtr(struct crypt_config *cc)
457{
48527fa7
RS
458}
459
2dc5327d
MB
460static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
461 struct dm_crypt_request *dmreq)
48527fa7 462{
79066ad3
HX
463 __be64 val;
464
48527fa7 465 memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
79066ad3 466
2dc5327d 467 val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
79066ad3 468 put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
48527fa7 469
1da177e4
LT
470 return 0;
471}
472
2dc5327d
MB
473static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
474 struct dm_crypt_request *dmreq)
46b47730
LN
475{
476 memset(iv, 0, cc->iv_size);
477
478 return 0;
479}
480
34745785
MB
481static void crypt_iv_lmk_dtr(struct crypt_config *cc)
482{
483 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
484
485 if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
486 crypto_free_shash(lmk->hash_tfm);
487 lmk->hash_tfm = NULL;
488
489 kzfree(lmk->seed);
490 lmk->seed = NULL;
491}
492
493static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
494 const char *opts)
495{
496 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
497
498 lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
499 if (IS_ERR(lmk->hash_tfm)) {
500 ti->error = "Error initializing LMK hash";
501 return PTR_ERR(lmk->hash_tfm);
502 }
503
504 /* No seed in LMK version 2 */
505 if (cc->key_parts == cc->tfms_count) {
506 lmk->seed = NULL;
507 return 0;
508 }
509
510 lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
511 if (!lmk->seed) {
512 crypt_iv_lmk_dtr(cc);
513 ti->error = "Error kmallocing seed storage in LMK";
514 return -ENOMEM;
515 }
516
517 return 0;
518}
519
520static int crypt_iv_lmk_init(struct crypt_config *cc)
521{
522 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
523 int subkey_size = cc->key_size / cc->key_parts;
524
525 /* LMK seed is on the position of LMK_KEYS + 1 key */
526 if (lmk->seed)
527 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
528 crypto_shash_digestsize(lmk->hash_tfm));
529
530 return 0;
531}
532
533static int crypt_iv_lmk_wipe(struct crypt_config *cc)
534{
535 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
536
537 if (lmk->seed)
538 memset(lmk->seed, 0, LMK_SEED_SIZE);
539
540 return 0;
541}
542
543static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
544 struct dm_crypt_request *dmreq,
545 u8 *data)
546{
547 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
548 struct {
549 struct shash_desc desc;
550 char ctx[crypto_shash_descsize(lmk->hash_tfm)];
551 } sdesc;
552 struct md5_state md5state;
da31a078 553 __le32 buf[4];
34745785
MB
554 int i, r;
555
556 sdesc.desc.tfm = lmk->hash_tfm;
557 sdesc.desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
558
559 r = crypto_shash_init(&sdesc.desc);
560 if (r)
561 return r;
562
563 if (lmk->seed) {
564 r = crypto_shash_update(&sdesc.desc, lmk->seed, LMK_SEED_SIZE);
565 if (r)
566 return r;
567 }
568
569 /* Sector is always 512B, block size 16, add data of blocks 1-31 */
570 r = crypto_shash_update(&sdesc.desc, data + 16, 16 * 31);
571 if (r)
572 return r;
573
574 /* Sector is cropped to 56 bits here */
575 buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
576 buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
577 buf[2] = cpu_to_le32(4024);
578 buf[3] = 0;
579 r = crypto_shash_update(&sdesc.desc, (u8 *)buf, sizeof(buf));
580 if (r)
581 return r;
582
583 /* No MD5 padding here */
584 r = crypto_shash_export(&sdesc.desc, &md5state);
585 if (r)
586 return r;
587
588 for (i = 0; i < MD5_HASH_WORDS; i++)
589 __cpu_to_le32s(&md5state.hash[i]);
590 memcpy(iv, &md5state.hash, cc->iv_size);
591
592 return 0;
593}
594
595static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
596 struct dm_crypt_request *dmreq)
597{
598 u8 *src;
599 int r = 0;
600
601 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
c2e022cb 602 src = kmap_atomic(sg_page(&dmreq->sg_in));
34745785 603 r = crypt_iv_lmk_one(cc, iv, dmreq, src + dmreq->sg_in.offset);
c2e022cb 604 kunmap_atomic(src);
34745785
MB
605 } else
606 memset(iv, 0, cc->iv_size);
607
608 return r;
609}
610
611static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
612 struct dm_crypt_request *dmreq)
613{
614 u8 *dst;
615 int r;
616
617 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
618 return 0;
619
c2e022cb 620 dst = kmap_atomic(sg_page(&dmreq->sg_out));
34745785
MB
621 r = crypt_iv_lmk_one(cc, iv, dmreq, dst + dmreq->sg_out.offset);
622
623 /* Tweak the first block of plaintext sector */
624 if (!r)
625 crypto_xor(dst + dmreq->sg_out.offset, iv, cc->iv_size);
626
c2e022cb 627 kunmap_atomic(dst);
34745785
MB
628 return r;
629}
630
ed04d981
MB
631static void crypt_iv_tcw_dtr(struct crypt_config *cc)
632{
633 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
634
635 kzfree(tcw->iv_seed);
636 tcw->iv_seed = NULL;
637 kzfree(tcw->whitening);
638 tcw->whitening = NULL;
639
640 if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
641 crypto_free_shash(tcw->crc32_tfm);
642 tcw->crc32_tfm = NULL;
643}
644
645static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
646 const char *opts)
647{
648 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
649
650 if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
651 ti->error = "Wrong key size for TCW";
652 return -EINVAL;
653 }
654
655 tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
656 if (IS_ERR(tcw->crc32_tfm)) {
657 ti->error = "Error initializing CRC32 in TCW";
658 return PTR_ERR(tcw->crc32_tfm);
659 }
660
661 tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
662 tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
663 if (!tcw->iv_seed || !tcw->whitening) {
664 crypt_iv_tcw_dtr(cc);
665 ti->error = "Error allocating seed storage in TCW";
666 return -ENOMEM;
667 }
668
669 return 0;
670}
671
672static int crypt_iv_tcw_init(struct crypt_config *cc)
673{
674 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
675 int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
676
677 memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
678 memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
679 TCW_WHITENING_SIZE);
680
681 return 0;
682}
683
684static int crypt_iv_tcw_wipe(struct crypt_config *cc)
685{
686 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
687
688 memset(tcw->iv_seed, 0, cc->iv_size);
689 memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
690
691 return 0;
692}
693
694static int crypt_iv_tcw_whitening(struct crypt_config *cc,
695 struct dm_crypt_request *dmreq,
696 u8 *data)
697{
698 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
699 u64 sector = cpu_to_le64((u64)dmreq->iv_sector);
700 u8 buf[TCW_WHITENING_SIZE];
701 struct {
702 struct shash_desc desc;
703 char ctx[crypto_shash_descsize(tcw->crc32_tfm)];
704 } sdesc;
705 int i, r;
706
707 /* xor whitening with sector number */
708 memcpy(buf, tcw->whitening, TCW_WHITENING_SIZE);
709 crypto_xor(buf, (u8 *)&sector, 8);
710 crypto_xor(&buf[8], (u8 *)&sector, 8);
711
712 /* calculate crc32 for every 32bit part and xor it */
713 sdesc.desc.tfm = tcw->crc32_tfm;
714 sdesc.desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
715 for (i = 0; i < 4; i++) {
716 r = crypto_shash_init(&sdesc.desc);
717 if (r)
718 goto out;
719 r = crypto_shash_update(&sdesc.desc, &buf[i * 4], 4);
720 if (r)
721 goto out;
722 r = crypto_shash_final(&sdesc.desc, &buf[i * 4]);
723 if (r)
724 goto out;
725 }
726 crypto_xor(&buf[0], &buf[12], 4);
727 crypto_xor(&buf[4], &buf[8], 4);
728
729 /* apply whitening (8 bytes) to whole sector */
730 for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
731 crypto_xor(data + i * 8, buf, 8);
732out:
733 memset(buf, 0, sizeof(buf));
734 return r;
735}
736
737static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
738 struct dm_crypt_request *dmreq)
739{
740 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
741 u64 sector = cpu_to_le64((u64)dmreq->iv_sector);
742 u8 *src;
743 int r = 0;
744
745 /* Remove whitening from ciphertext */
746 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
747 src = kmap_atomic(sg_page(&dmreq->sg_in));
748 r = crypt_iv_tcw_whitening(cc, dmreq, src + dmreq->sg_in.offset);
749 kunmap_atomic(src);
750 }
751
752 /* Calculate IV */
753 memcpy(iv, tcw->iv_seed, cc->iv_size);
754 crypto_xor(iv, (u8 *)&sector, 8);
755 if (cc->iv_size > 8)
756 crypto_xor(&iv[8], (u8 *)&sector, cc->iv_size - 8);
757
758 return r;
759}
760
761static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
762 struct dm_crypt_request *dmreq)
763{
764 u8 *dst;
765 int r;
766
767 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
768 return 0;
769
770 /* Apply whitening on ciphertext */
771 dst = kmap_atomic(sg_page(&dmreq->sg_out));
772 r = crypt_iv_tcw_whitening(cc, dmreq, dst + dmreq->sg_out.offset);
773 kunmap_atomic(dst);
774
775 return r;
776}
777
1da177e4
LT
778static struct crypt_iv_operations crypt_iv_plain_ops = {
779 .generator = crypt_iv_plain_gen
780};
781
61afef61
MB
782static struct crypt_iv_operations crypt_iv_plain64_ops = {
783 .generator = crypt_iv_plain64_gen
784};
785
1da177e4
LT
786static struct crypt_iv_operations crypt_iv_essiv_ops = {
787 .ctr = crypt_iv_essiv_ctr,
788 .dtr = crypt_iv_essiv_dtr,
b95bf2d3 789 .init = crypt_iv_essiv_init,
542da317 790 .wipe = crypt_iv_essiv_wipe,
1da177e4
LT
791 .generator = crypt_iv_essiv_gen
792};
793
48527fa7
RS
794static struct crypt_iv_operations crypt_iv_benbi_ops = {
795 .ctr = crypt_iv_benbi_ctr,
796 .dtr = crypt_iv_benbi_dtr,
797 .generator = crypt_iv_benbi_gen
798};
1da177e4 799
46b47730
LN
800static struct crypt_iv_operations crypt_iv_null_ops = {
801 .generator = crypt_iv_null_gen
802};
803
34745785
MB
804static struct crypt_iv_operations crypt_iv_lmk_ops = {
805 .ctr = crypt_iv_lmk_ctr,
806 .dtr = crypt_iv_lmk_dtr,
807 .init = crypt_iv_lmk_init,
808 .wipe = crypt_iv_lmk_wipe,
809 .generator = crypt_iv_lmk_gen,
810 .post = crypt_iv_lmk_post
811};
812
ed04d981
MB
813static struct crypt_iv_operations crypt_iv_tcw_ops = {
814 .ctr = crypt_iv_tcw_ctr,
815 .dtr = crypt_iv_tcw_dtr,
816 .init = crypt_iv_tcw_init,
817 .wipe = crypt_iv_tcw_wipe,
818 .generator = crypt_iv_tcw_gen,
819 .post = crypt_iv_tcw_post
820};
821
d469f841
MB
822static void crypt_convert_init(struct crypt_config *cc,
823 struct convert_context *ctx,
824 struct bio *bio_out, struct bio *bio_in,
fcd369da 825 sector_t sector)
1da177e4
LT
826{
827 ctx->bio_in = bio_in;
828 ctx->bio_out = bio_out;
829 ctx->offset_in = 0;
830 ctx->offset_out = 0;
4f024f37
KO
831 ctx->idx_in = bio_in ? bio_in->bi_iter.bi_idx : 0;
832 ctx->idx_out = bio_out ? bio_out->bi_iter.bi_idx : 0;
c66029f4 833 ctx->cc_sector = sector + cc->iv_offset;
43d69034 834 init_completion(&ctx->restart);
1da177e4
LT
835}
836
b2174eeb
HY
837static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
838 struct ablkcipher_request *req)
839{
840 return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
841}
842
843static struct ablkcipher_request *req_of_dmreq(struct crypt_config *cc,
844 struct dm_crypt_request *dmreq)
845{
846 return (struct ablkcipher_request *)((char *)dmreq - cc->dmreq_start);
847}
848
2dc5327d
MB
849static u8 *iv_of_dmreq(struct crypt_config *cc,
850 struct dm_crypt_request *dmreq)
851{
852 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
853 crypto_ablkcipher_alignmask(any_tfm(cc)) + 1);
854}
855
01482b76 856static int crypt_convert_block(struct crypt_config *cc,
3a7f6c99
MB
857 struct convert_context *ctx,
858 struct ablkcipher_request *req)
01482b76
MB
859{
860 struct bio_vec *bv_in = bio_iovec_idx(ctx->bio_in, ctx->idx_in);
861 struct bio_vec *bv_out = bio_iovec_idx(ctx->bio_out, ctx->idx_out);
3a7f6c99
MB
862 struct dm_crypt_request *dmreq;
863 u8 *iv;
40b6229b 864 int r;
3a7f6c99 865
b2174eeb 866 dmreq = dmreq_of_req(cc, req);
2dc5327d 867 iv = iv_of_dmreq(cc, dmreq);
01482b76 868
c66029f4 869 dmreq->iv_sector = ctx->cc_sector;
b2174eeb 870 dmreq->ctx = ctx;
3a7f6c99
MB
871 sg_init_table(&dmreq->sg_in, 1);
872 sg_set_page(&dmreq->sg_in, bv_in->bv_page, 1 << SECTOR_SHIFT,
01482b76
MB
873 bv_in->bv_offset + ctx->offset_in);
874
3a7f6c99
MB
875 sg_init_table(&dmreq->sg_out, 1);
876 sg_set_page(&dmreq->sg_out, bv_out->bv_page, 1 << SECTOR_SHIFT,
01482b76
MB
877 bv_out->bv_offset + ctx->offset_out);
878
879 ctx->offset_in += 1 << SECTOR_SHIFT;
880 if (ctx->offset_in >= bv_in->bv_len) {
881 ctx->offset_in = 0;
882 ctx->idx_in++;
883 }
884
885 ctx->offset_out += 1 << SECTOR_SHIFT;
886 if (ctx->offset_out >= bv_out->bv_len) {
887 ctx->offset_out = 0;
888 ctx->idx_out++;
889 }
890
3a7f6c99 891 if (cc->iv_gen_ops) {
2dc5327d 892 r = cc->iv_gen_ops->generator(cc, iv, dmreq);
3a7f6c99
MB
893 if (r < 0)
894 return r;
895 }
896
897 ablkcipher_request_set_crypt(req, &dmreq->sg_in, &dmreq->sg_out,
898 1 << SECTOR_SHIFT, iv);
899
900 if (bio_data_dir(ctx->bio_in) == WRITE)
901 r = crypto_ablkcipher_encrypt(req);
902 else
903 r = crypto_ablkcipher_decrypt(req);
904
2dc5327d
MB
905 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
906 r = cc->iv_gen_ops->post(cc, iv, dmreq);
907
3a7f6c99 908 return r;
01482b76
MB
909}
910
95497a96
MB
911static void kcryptd_async_done(struct crypto_async_request *async_req,
912 int error);
c0297721 913
ddd42edf
MB
914static void crypt_alloc_req(struct crypt_config *cc,
915 struct convert_context *ctx)
916{
c0297721 917 struct crypt_cpu *this_cc = this_crypt_config(cc);
c66029f4 918 unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
c0297721
AK
919
920 if (!this_cc->req)
921 this_cc->req = mempool_alloc(cc->req_pool, GFP_NOIO);
922
fd2d231f 923 ablkcipher_request_set_tfm(this_cc->req, cc->tfms[key_index]);
c0297721
AK
924 ablkcipher_request_set_callback(this_cc->req,
925 CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
926 kcryptd_async_done, dmreq_of_req(cc, this_cc->req));
ddd42edf
MB
927}
928
1da177e4
LT
929/*
930 * Encrypt / decrypt data from one bio to another one (can be the same one)
931 */
932static int crypt_convert(struct crypt_config *cc,
d469f841 933 struct convert_context *ctx)
1da177e4 934{
c0297721 935 struct crypt_cpu *this_cc = this_crypt_config(cc);
3f1e9070 936 int r;
1da177e4 937
40b6229b 938 atomic_set(&ctx->cc_pending, 1);
c8081618 939
1da177e4
LT
940 while(ctx->idx_in < ctx->bio_in->bi_vcnt &&
941 ctx->idx_out < ctx->bio_out->bi_vcnt) {
1da177e4 942
3a7f6c99
MB
943 crypt_alloc_req(cc, ctx);
944
40b6229b 945 atomic_inc(&ctx->cc_pending);
3f1e9070 946
c0297721 947 r = crypt_convert_block(cc, ctx, this_cc->req);
3a7f6c99
MB
948
949 switch (r) {
3f1e9070 950 /* async */
3a7f6c99
MB
951 case -EBUSY:
952 wait_for_completion(&ctx->restart);
16735d02 953 reinit_completion(&ctx->restart);
3a7f6c99
MB
954 /* fall through*/
955 case -EINPROGRESS:
c0297721 956 this_cc->req = NULL;
c66029f4 957 ctx->cc_sector++;
3f1e9070
MB
958 continue;
959
960 /* sync */
3a7f6c99 961 case 0:
40b6229b 962 atomic_dec(&ctx->cc_pending);
c66029f4 963 ctx->cc_sector++;
c7f1b204 964 cond_resched();
3a7f6c99 965 continue;
3a7f6c99 966
3f1e9070
MB
967 /* error */
968 default:
40b6229b 969 atomic_dec(&ctx->cc_pending);
3f1e9070
MB
970 return r;
971 }
1da177e4
LT
972 }
973
3f1e9070 974 return 0;
1da177e4
LT
975}
976
977/*
978 * Generate a new unfragmented bio with the given size
979 * This should never violate the device limitations
933f01d4
MB
980 * May return a smaller bio when running out of pages, indicated by
981 * *out_of_pages set to 1.
1da177e4 982 */
933f01d4
MB
983static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size,
984 unsigned *out_of_pages)
1da177e4 985{
49a8a920 986 struct crypt_config *cc = io->cc;
8b004457 987 struct bio *clone;
1da177e4 988 unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
b4e3ca1a 989 gfp_t gfp_mask = GFP_NOIO | __GFP_HIGHMEM;
91e10625
MB
990 unsigned i, len;
991 struct page *page;
1da177e4 992
2f9941b6 993 clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, cc->bs);
8b004457 994 if (!clone)
1da177e4 995 return NULL;
1da177e4 996
027581f3 997 clone_init(io, clone);
933f01d4 998 *out_of_pages = 0;
6a24c718 999
f97380bc 1000 for (i = 0; i < nr_iovecs; i++) {
91e10625 1001 page = mempool_alloc(cc->page_pool, gfp_mask);
933f01d4
MB
1002 if (!page) {
1003 *out_of_pages = 1;
1da177e4 1004 break;
933f01d4 1005 }
1da177e4
LT
1006
1007 /*
aeb2deae
MP
1008 * If additional pages cannot be allocated without waiting,
1009 * return a partially-allocated bio. The caller will then try
1010 * to allocate more bios while submitting this partial bio.
1da177e4 1011 */
aeb2deae 1012 gfp_mask = (gfp_mask | __GFP_NOWARN) & ~__GFP_WAIT;
1da177e4 1013
91e10625
MB
1014 len = (size > PAGE_SIZE) ? PAGE_SIZE : size;
1015
1016 if (!bio_add_page(clone, page, len, 0)) {
1017 mempool_free(page, cc->page_pool);
1018 break;
1019 }
1da177e4 1020
91e10625 1021 size -= len;
1da177e4
LT
1022 }
1023
4f024f37 1024 if (!clone->bi_iter.bi_size) {
8b004457 1025 bio_put(clone);
1da177e4
LT
1026 return NULL;
1027 }
1028
8b004457 1029 return clone;
1da177e4
LT
1030}
1031
644bd2f0 1032static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1da177e4 1033{
644bd2f0 1034 unsigned int i;
1da177e4
LT
1035 struct bio_vec *bv;
1036
cb34e057 1037 bio_for_each_segment_all(bv, clone, i) {
1da177e4
LT
1038 BUG_ON(!bv->bv_page);
1039 mempool_free(bv->bv_page, cc->page_pool);
1040 bv->bv_page = NULL;
1041 }
1042}
1043
49a8a920 1044static struct dm_crypt_io *crypt_io_alloc(struct crypt_config *cc,
dc440d1e
MB
1045 struct bio *bio, sector_t sector)
1046{
dc440d1e
MB
1047 struct dm_crypt_io *io;
1048
1049 io = mempool_alloc(cc->io_pool, GFP_NOIO);
49a8a920 1050 io->cc = cc;
dc440d1e
MB
1051 io->base_bio = bio;
1052 io->sector = sector;
1053 io->error = 0;
393b47ef 1054 io->base_io = NULL;
40b6229b 1055 atomic_set(&io->io_pending, 0);
dc440d1e
MB
1056
1057 return io;
1058}
1059
3e1a8bdd
MB
1060static void crypt_inc_pending(struct dm_crypt_io *io)
1061{
40b6229b 1062 atomic_inc(&io->io_pending);
3e1a8bdd
MB
1063}
1064
1da177e4
LT
1065/*
1066 * One of the bios was finished. Check for completion of
1067 * the whole request and correctly clean up the buffer.
393b47ef 1068 * If base_io is set, wait for the last fragment to complete.
1da177e4 1069 */
5742fd77 1070static void crypt_dec_pending(struct dm_crypt_io *io)
1da177e4 1071{
49a8a920 1072 struct crypt_config *cc = io->cc;
b35f8caa
MB
1073 struct bio *base_bio = io->base_bio;
1074 struct dm_crypt_io *base_io = io->base_io;
1075 int error = io->error;
1da177e4 1076
40b6229b 1077 if (!atomic_dec_and_test(&io->io_pending))
1da177e4
LT
1078 return;
1079
b35f8caa
MB
1080 mempool_free(io, cc->io_pool);
1081
1082 if (likely(!base_io))
1083 bio_endio(base_bio, error);
393b47ef 1084 else {
b35f8caa
MB
1085 if (error && !base_io->error)
1086 base_io->error = error;
1087 crypt_dec_pending(base_io);
393b47ef 1088 }
1da177e4
LT
1089}
1090
1091/*
cabf08e4 1092 * kcryptd/kcryptd_io:
1da177e4
LT
1093 *
1094 * Needed because it would be very unwise to do decryption in an
23541d2d 1095 * interrupt context.
cabf08e4
MB
1096 *
1097 * kcryptd performs the actual encryption or decryption.
1098 *
1099 * kcryptd_io performs the IO submission.
1100 *
1101 * They must be separated as otherwise the final stages could be
1102 * starved by new requests which can block in the first stages due
1103 * to memory allocation.
c0297721
AK
1104 *
1105 * The work is done per CPU global for all dm-crypt instances.
1106 * They should not depend on each other and do not block.
1da177e4 1107 */
6712ecf8 1108static void crypt_endio(struct bio *clone, int error)
8b004457 1109{
028867ac 1110 struct dm_crypt_io *io = clone->bi_private;
49a8a920 1111 struct crypt_config *cc = io->cc;
ee7a491e 1112 unsigned rw = bio_data_dir(clone);
8b004457 1113
adfe4770
MB
1114 if (unlikely(!bio_flagged(clone, BIO_UPTODATE) && !error))
1115 error = -EIO;
1116
8b004457 1117 /*
6712ecf8 1118 * free the processed pages
8b004457 1119 */
ee7a491e 1120 if (rw == WRITE)
644bd2f0 1121 crypt_free_buffer_pages(cc, clone);
8b004457
MB
1122
1123 bio_put(clone);
8b004457 1124
ee7a491e
MB
1125 if (rw == READ && !error) {
1126 kcryptd_queue_crypt(io);
1127 return;
1128 }
5742fd77
MB
1129
1130 if (unlikely(error))
1131 io->error = error;
1132
1133 crypt_dec_pending(io);
8b004457
MB
1134}
1135
028867ac 1136static void clone_init(struct dm_crypt_io *io, struct bio *clone)
8b004457 1137{
49a8a920 1138 struct crypt_config *cc = io->cc;
8b004457
MB
1139
1140 clone->bi_private = io;
1141 clone->bi_end_io = crypt_endio;
1142 clone->bi_bdev = cc->dev->bdev;
1143 clone->bi_rw = io->base_bio->bi_rw;
1144}
1145
20c82538 1146static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
8b004457 1147{
49a8a920 1148 struct crypt_config *cc = io->cc;
8b004457
MB
1149 struct bio *base_bio = io->base_bio;
1150 struct bio *clone;
93e605c2 1151
8b004457
MB
1152 /*
1153 * The block layer might modify the bvec array, so always
1154 * copy the required bvecs because we need the original
1155 * one in order to decrypt the whole bio data *afterwards*.
1156 */
bf800ef1 1157 clone = bio_clone_bioset(base_bio, gfp, cc->bs);
7eaceacc 1158 if (!clone)
20c82538 1159 return 1;
8b004457 1160
20c82538
MB
1161 crypt_inc_pending(io);
1162
8b004457 1163 clone_init(io, clone);
4f024f37 1164 clone->bi_iter.bi_sector = cc->start + io->sector;
8b004457 1165
93e605c2 1166 generic_make_request(clone);
20c82538 1167 return 0;
8b004457
MB
1168}
1169
4e4eef64
MB
1170static void kcryptd_io_write(struct dm_crypt_io *io)
1171{
95497a96 1172 struct bio *clone = io->ctx.bio_out;
95497a96 1173 generic_make_request(clone);
4e4eef64
MB
1174}
1175
395b167c
AK
1176static void kcryptd_io(struct work_struct *work)
1177{
1178 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1179
20c82538
MB
1180 if (bio_data_dir(io->base_bio) == READ) {
1181 crypt_inc_pending(io);
1182 if (kcryptd_io_read(io, GFP_NOIO))
1183 io->error = -ENOMEM;
1184 crypt_dec_pending(io);
1185 } else
395b167c
AK
1186 kcryptd_io_write(io);
1187}
1188
1189static void kcryptd_queue_io(struct dm_crypt_io *io)
1190{
49a8a920 1191 struct crypt_config *cc = io->cc;
395b167c
AK
1192
1193 INIT_WORK(&io->work, kcryptd_io);
1194 queue_work(cc->io_queue, &io->work);
1195}
1196
72c6e7af 1197static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
4e4eef64 1198{
dec1cedf 1199 struct bio *clone = io->ctx.bio_out;
49a8a920 1200 struct crypt_config *cc = io->cc;
dec1cedf 1201
72c6e7af 1202 if (unlikely(io->error < 0)) {
dec1cedf
MB
1203 crypt_free_buffer_pages(cc, clone);
1204 bio_put(clone);
6c031f41 1205 crypt_dec_pending(io);
dec1cedf
MB
1206 return;
1207 }
1208
1209 /* crypt_convert should have filled the clone bio */
1210 BUG_ON(io->ctx.idx_out < clone->bi_vcnt);
1211
4f024f37 1212 clone->bi_iter.bi_sector = cc->start + io->sector;
899c95d3 1213
95497a96
MB
1214 if (async)
1215 kcryptd_queue_io(io);
1e37bb8e 1216 else
95497a96 1217 generic_make_request(clone);
4e4eef64
MB
1218}
1219
fc5a5e9a 1220static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
8b004457 1221{
49a8a920 1222 struct crypt_config *cc = io->cc;
8b004457 1223 struct bio *clone;
393b47ef 1224 struct dm_crypt_io *new_io;
c8081618 1225 int crypt_finished;
933f01d4 1226 unsigned out_of_pages = 0;
4f024f37 1227 unsigned remaining = io->base_bio->bi_iter.bi_size;
b635b00e 1228 sector_t sector = io->sector;
dec1cedf 1229 int r;
8b004457 1230
fc5a5e9a
MB
1231 /*
1232 * Prevent io from disappearing until this function completes.
1233 */
1234 crypt_inc_pending(io);
b635b00e 1235 crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
fc5a5e9a 1236
93e605c2
MB
1237 /*
1238 * The allocated buffers can be smaller than the whole bio,
1239 * so repeat the whole process until all the data can be handled.
1240 */
1241 while (remaining) {
933f01d4 1242 clone = crypt_alloc_buffer(io, remaining, &out_of_pages);
23541d2d 1243 if (unlikely(!clone)) {
5742fd77 1244 io->error = -ENOMEM;
fc5a5e9a 1245 break;
23541d2d 1246 }
93e605c2 1247
53017030
MB
1248 io->ctx.bio_out = clone;
1249 io->ctx.idx_out = 0;
93e605c2 1250
4f024f37 1251 remaining -= clone->bi_iter.bi_size;
b635b00e 1252 sector += bio_sectors(clone);
93e605c2 1253
4e594098 1254 crypt_inc_pending(io);
72c6e7af 1255
dec1cedf 1256 r = crypt_convert(cc, &io->ctx);
72c6e7af
MP
1257 if (r < 0)
1258 io->error = -EIO;
1259
40b6229b 1260 crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
f97380bc 1261
c8081618
MB
1262 /* Encryption was already finished, submit io now */
1263 if (crypt_finished) {
72c6e7af 1264 kcryptd_crypt_write_io_submit(io, 0);
c8081618
MB
1265
1266 /*
1267 * If there was an error, do not try next fragments.
1268 * For async, error is processed in async handler.
1269 */
6c031f41 1270 if (unlikely(r < 0))
fc5a5e9a 1271 break;
b635b00e
MB
1272
1273 io->sector = sector;
4e594098 1274 }
93e605c2 1275
933f01d4
MB
1276 /*
1277 * Out of memory -> run queues
1278 * But don't wait if split was due to the io size restriction
1279 */
1280 if (unlikely(out_of_pages))
8aa7e847 1281 congestion_wait(BLK_RW_ASYNC, HZ/100);
933f01d4 1282
393b47ef
MB
1283 /*
1284 * With async crypto it is unsafe to share the crypto context
1285 * between fragments, so switch to a new dm_crypt_io structure.
1286 */
1287 if (unlikely(!crypt_finished && remaining)) {
49a8a920 1288 new_io = crypt_io_alloc(io->cc, io->base_bio,
393b47ef
MB
1289 sector);
1290 crypt_inc_pending(new_io);
1291 crypt_convert_init(cc, &new_io->ctx, NULL,
1292 io->base_bio, sector);
1293 new_io->ctx.idx_in = io->ctx.idx_in;
1294 new_io->ctx.offset_in = io->ctx.offset_in;
1295
1296 /*
1297 * Fragments after the first use the base_io
1298 * pending count.
1299 */
1300 if (!io->base_io)
1301 new_io->base_io = io;
1302 else {
1303 new_io->base_io = io->base_io;
1304 crypt_inc_pending(io->base_io);
1305 crypt_dec_pending(io);
1306 }
1307
1308 io = new_io;
1309 }
93e605c2 1310 }
899c95d3
MB
1311
1312 crypt_dec_pending(io);
84131db6
MB
1313}
1314
72c6e7af 1315static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
5742fd77 1316{
5742fd77
MB
1317 crypt_dec_pending(io);
1318}
1319
4e4eef64 1320static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
8b004457 1321{
49a8a920 1322 struct crypt_config *cc = io->cc;
5742fd77 1323 int r = 0;
1da177e4 1324
3e1a8bdd 1325 crypt_inc_pending(io);
3a7f6c99 1326
53017030 1327 crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
0c395b0f 1328 io->sector);
1da177e4 1329
5742fd77 1330 r = crypt_convert(cc, &io->ctx);
72c6e7af
MP
1331 if (r < 0)
1332 io->error = -EIO;
5742fd77 1333
40b6229b 1334 if (atomic_dec_and_test(&io->ctx.cc_pending))
72c6e7af 1335 kcryptd_crypt_read_done(io);
3a7f6c99
MB
1336
1337 crypt_dec_pending(io);
1da177e4
LT
1338}
1339
95497a96
MB
1340static void kcryptd_async_done(struct crypto_async_request *async_req,
1341 int error)
1342{
b2174eeb
HY
1343 struct dm_crypt_request *dmreq = async_req->data;
1344 struct convert_context *ctx = dmreq->ctx;
95497a96 1345 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
49a8a920 1346 struct crypt_config *cc = io->cc;
95497a96
MB
1347
1348 if (error == -EINPROGRESS) {
1349 complete(&ctx->restart);
1350 return;
1351 }
1352
2dc5327d
MB
1353 if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
1354 error = cc->iv_gen_ops->post(cc, iv_of_dmreq(cc, dmreq), dmreq);
1355
72c6e7af
MP
1356 if (error < 0)
1357 io->error = -EIO;
1358
b2174eeb 1359 mempool_free(req_of_dmreq(cc, dmreq), cc->req_pool);
95497a96 1360
40b6229b 1361 if (!atomic_dec_and_test(&ctx->cc_pending))
95497a96
MB
1362 return;
1363
1364 if (bio_data_dir(io->base_bio) == READ)
72c6e7af 1365 kcryptd_crypt_read_done(io);
95497a96 1366 else
72c6e7af 1367 kcryptd_crypt_write_io_submit(io, 1);
95497a96
MB
1368}
1369
395b167c 1370static void kcryptd_crypt(struct work_struct *work)
1da177e4 1371{
028867ac 1372 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
8b004457 1373
cabf08e4 1374 if (bio_data_dir(io->base_bio) == READ)
395b167c 1375 kcryptd_crypt_read_convert(io);
4e4eef64 1376 else
395b167c 1377 kcryptd_crypt_write_convert(io);
cabf08e4
MB
1378}
1379
395b167c 1380static void kcryptd_queue_crypt(struct dm_crypt_io *io)
cabf08e4 1381{
49a8a920 1382 struct crypt_config *cc = io->cc;
cabf08e4 1383
395b167c
AK
1384 INIT_WORK(&io->work, kcryptd_crypt);
1385 queue_work(cc->crypt_queue, &io->work);
1da177e4
LT
1386}
1387
1388/*
1389 * Decode key from its hex representation
1390 */
1391static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
1392{
1393 char buffer[3];
1da177e4
LT
1394 unsigned int i;
1395
1396 buffer[2] = '\0';
1397
8b004457 1398 for (i = 0; i < size; i++) {
1da177e4
LT
1399 buffer[0] = *hex++;
1400 buffer[1] = *hex++;
1401
1a66a08a 1402 if (kstrtou8(buffer, 16, &key[i]))
1da177e4
LT
1403 return -EINVAL;
1404 }
1405
1406 if (*hex != '\0')
1407 return -EINVAL;
1408
1409 return 0;
1410}
1411
fd2d231f 1412static void crypt_free_tfms(struct crypt_config *cc)
d1f96423 1413{
d1f96423
MB
1414 unsigned i;
1415
fd2d231f
MP
1416 if (!cc->tfms)
1417 return;
1418
d1f96423 1419 for (i = 0; i < cc->tfms_count; i++)
fd2d231f
MP
1420 if (cc->tfms[i] && !IS_ERR(cc->tfms[i])) {
1421 crypto_free_ablkcipher(cc->tfms[i]);
1422 cc->tfms[i] = NULL;
d1f96423 1423 }
fd2d231f
MP
1424
1425 kfree(cc->tfms);
1426 cc->tfms = NULL;
d1f96423
MB
1427}
1428
fd2d231f 1429static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
d1f96423 1430{
d1f96423
MB
1431 unsigned i;
1432 int err;
1433
fd2d231f
MP
1434 cc->tfms = kmalloc(cc->tfms_count * sizeof(struct crypto_ablkcipher *),
1435 GFP_KERNEL);
1436 if (!cc->tfms)
1437 return -ENOMEM;
1438
d1f96423 1439 for (i = 0; i < cc->tfms_count; i++) {
fd2d231f
MP
1440 cc->tfms[i] = crypto_alloc_ablkcipher(ciphermode, 0, 0);
1441 if (IS_ERR(cc->tfms[i])) {
1442 err = PTR_ERR(cc->tfms[i]);
1443 crypt_free_tfms(cc);
d1f96423
MB
1444 return err;
1445 }
1446 }
1447
1448 return 0;
1449}
1450
c0297721
AK
1451static int crypt_setkey_allcpus(struct crypt_config *cc)
1452{
da31a078 1453 unsigned subkey_size;
fd2d231f
MP
1454 int err = 0, i, r;
1455
da31a078
MB
1456 /* Ignore extra keys (which are used for IV etc) */
1457 subkey_size = (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
1458
fd2d231f
MP
1459 for (i = 0; i < cc->tfms_count; i++) {
1460 r = crypto_ablkcipher_setkey(cc->tfms[i],
1461 cc->key + (i * subkey_size),
1462 subkey_size);
1463 if (r)
1464 err = r;
c0297721
AK
1465 }
1466
1467 return err;
1468}
1469
e48d4bbf
MB
1470static int crypt_set_key(struct crypt_config *cc, char *key)
1471{
de8be5ac
MB
1472 int r = -EINVAL;
1473 int key_string_len = strlen(key);
1474
69a8cfcd 1475 /* The key size may not be changed. */
de8be5ac
MB
1476 if (cc->key_size != (key_string_len >> 1))
1477 goto out;
e48d4bbf 1478
69a8cfcd
MB
1479 /* Hyphen (which gives a key_size of zero) means there is no key. */
1480 if (!cc->key_size && strcmp(key, "-"))
de8be5ac 1481 goto out;
e48d4bbf 1482
69a8cfcd 1483 if (cc->key_size && crypt_decode_key(cc->key, key, cc->key_size) < 0)
de8be5ac 1484 goto out;
e48d4bbf
MB
1485
1486 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
1487
de8be5ac
MB
1488 r = crypt_setkey_allcpus(cc);
1489
1490out:
1491 /* Hex key string not needed after here, so wipe it. */
1492 memset(key, '0', key_string_len);
1493
1494 return r;
e48d4bbf
MB
1495}
1496
1497static int crypt_wipe_key(struct crypt_config *cc)
1498{
1499 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
1500 memset(&cc->key, 0, cc->key_size * sizeof(u8));
c0297721
AK
1501
1502 return crypt_setkey_allcpus(cc);
e48d4bbf
MB
1503}
1504
28513fcc
MB
1505static void crypt_dtr(struct dm_target *ti)
1506{
1507 struct crypt_config *cc = ti->private;
c0297721
AK
1508 struct crypt_cpu *cpu_cc;
1509 int cpu;
28513fcc
MB
1510
1511 ti->private = NULL;
1512
1513 if (!cc)
1514 return;
1515
1516 if (cc->io_queue)
1517 destroy_workqueue(cc->io_queue);
1518 if (cc->crypt_queue)
1519 destroy_workqueue(cc->crypt_queue);
1520
c0297721
AK
1521 if (cc->cpu)
1522 for_each_possible_cpu(cpu) {
1523 cpu_cc = per_cpu_ptr(cc->cpu, cpu);
1524 if (cpu_cc->req)
1525 mempool_free(cpu_cc->req, cc->req_pool);
c0297721
AK
1526 }
1527
fd2d231f
MP
1528 crypt_free_tfms(cc);
1529
28513fcc
MB
1530 if (cc->bs)
1531 bioset_free(cc->bs);
1532
1533 if (cc->page_pool)
1534 mempool_destroy(cc->page_pool);
1535 if (cc->req_pool)
1536 mempool_destroy(cc->req_pool);
1537 if (cc->io_pool)
1538 mempool_destroy(cc->io_pool);
1539
1540 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
1541 cc->iv_gen_ops->dtr(cc);
1542
28513fcc
MB
1543 if (cc->dev)
1544 dm_put_device(ti, cc->dev);
1545
c0297721
AK
1546 if (cc->cpu)
1547 free_percpu(cc->cpu);
1548
5ebaee6d 1549 kzfree(cc->cipher);
7dbcd137 1550 kzfree(cc->cipher_string);
28513fcc
MB
1551
1552 /* Must zero key material before freeing */
1553 kzfree(cc);
1554}
1555
5ebaee6d
MB
1556static int crypt_ctr_cipher(struct dm_target *ti,
1557 char *cipher_in, char *key)
1da177e4 1558{
5ebaee6d 1559 struct crypt_config *cc = ti->private;
d1f96423 1560 char *tmp, *cipher, *chainmode, *ivmode, *ivopts, *keycount;
5ebaee6d 1561 char *cipher_api = NULL;
fd2d231f 1562 int ret = -EINVAL;
31998ef1 1563 char dummy;
1da177e4 1564
5ebaee6d
MB
1565 /* Convert to crypto api definition? */
1566 if (strchr(cipher_in, '(')) {
1567 ti->error = "Bad cipher specification";
1da177e4
LT
1568 return -EINVAL;
1569 }
1570
7dbcd137
MB
1571 cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
1572 if (!cc->cipher_string)
1573 goto bad_mem;
1574
5ebaee6d
MB
1575 /*
1576 * Legacy dm-crypt cipher specification
d1f96423 1577 * cipher[:keycount]-mode-iv:ivopts
5ebaee6d
MB
1578 */
1579 tmp = cipher_in;
d1f96423
MB
1580 keycount = strsep(&tmp, "-");
1581 cipher = strsep(&keycount, ":");
1582
1583 if (!keycount)
1584 cc->tfms_count = 1;
31998ef1 1585 else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
d1f96423
MB
1586 !is_power_of_2(cc->tfms_count)) {
1587 ti->error = "Bad cipher key count specification";
1588 return -EINVAL;
1589 }
1590 cc->key_parts = cc->tfms_count;
da31a078 1591 cc->key_extra_size = 0;
5ebaee6d
MB
1592
1593 cc->cipher = kstrdup(cipher, GFP_KERNEL);
1594 if (!cc->cipher)
1595 goto bad_mem;
1596
1da177e4
LT
1597 chainmode = strsep(&tmp, "-");
1598 ivopts = strsep(&tmp, "-");
1599 ivmode = strsep(&ivopts, ":");
1600
1601 if (tmp)
5ebaee6d 1602 DMWARN("Ignoring unexpected additional cipher options");
1da177e4 1603
fd2d231f 1604 cc->cpu = __alloc_percpu(sizeof(*(cc->cpu)),
d1f96423 1605 __alignof__(struct crypt_cpu));
c0297721
AK
1606 if (!cc->cpu) {
1607 ti->error = "Cannot allocate per cpu state";
1608 goto bad_mem;
1609 }
1610
7dbcd137
MB
1611 /*
1612 * For compatibility with the original dm-crypt mapping format, if
1613 * only the cipher name is supplied, use cbc-plain.
1614 */
5ebaee6d 1615 if (!chainmode || (!strcmp(chainmode, "plain") && !ivmode)) {
1da177e4
LT
1616 chainmode = "cbc";
1617 ivmode = "plain";
1618 }
1619
d1806f6a 1620 if (strcmp(chainmode, "ecb") && !ivmode) {
5ebaee6d
MB
1621 ti->error = "IV mechanism required";
1622 return -EINVAL;
1da177e4
LT
1623 }
1624
5ebaee6d
MB
1625 cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
1626 if (!cipher_api)
1627 goto bad_mem;
1628
1629 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
1630 "%s(%s)", chainmode, cipher);
1631 if (ret < 0) {
1632 kfree(cipher_api);
1633 goto bad_mem;
1da177e4
LT
1634 }
1635
5ebaee6d 1636 /* Allocate cipher */
fd2d231f
MP
1637 ret = crypt_alloc_tfms(cc, cipher_api);
1638 if (ret < 0) {
1639 ti->error = "Error allocating crypto tfm";
1640 goto bad;
1da177e4 1641 }
1da177e4 1642
5ebaee6d 1643 /* Initialize IV */
c0297721 1644 cc->iv_size = crypto_ablkcipher_ivsize(any_tfm(cc));
5ebaee6d
MB
1645 if (cc->iv_size)
1646 /* at least a 64 bit sector number should fit in our buffer */
1647 cc->iv_size = max(cc->iv_size,
1648 (unsigned int)(sizeof(u64) / sizeof(u8)));
1649 else if (ivmode) {
1650 DMWARN("Selected cipher does not support IVs");
1651 ivmode = NULL;
1652 }
1653
1654 /* Choose ivmode, see comments at iv code. */
1da177e4
LT
1655 if (ivmode == NULL)
1656 cc->iv_gen_ops = NULL;
1657 else if (strcmp(ivmode, "plain") == 0)
1658 cc->iv_gen_ops = &crypt_iv_plain_ops;
61afef61
MB
1659 else if (strcmp(ivmode, "plain64") == 0)
1660 cc->iv_gen_ops = &crypt_iv_plain64_ops;
1da177e4
LT
1661 else if (strcmp(ivmode, "essiv") == 0)
1662 cc->iv_gen_ops = &crypt_iv_essiv_ops;
48527fa7
RS
1663 else if (strcmp(ivmode, "benbi") == 0)
1664 cc->iv_gen_ops = &crypt_iv_benbi_ops;
46b47730
LN
1665 else if (strcmp(ivmode, "null") == 0)
1666 cc->iv_gen_ops = &crypt_iv_null_ops;
34745785
MB
1667 else if (strcmp(ivmode, "lmk") == 0) {
1668 cc->iv_gen_ops = &crypt_iv_lmk_ops;
ed04d981
MB
1669 /*
1670 * Version 2 and 3 is recognised according
34745785
MB
1671 * to length of provided multi-key string.
1672 * If present (version 3), last key is used as IV seed.
ed04d981 1673 * All keys (including IV seed) are always the same size.
34745785 1674 */
da31a078 1675 if (cc->key_size % cc->key_parts) {
34745785 1676 cc->key_parts++;
da31a078
MB
1677 cc->key_extra_size = cc->key_size / cc->key_parts;
1678 }
ed04d981
MB
1679 } else if (strcmp(ivmode, "tcw") == 0) {
1680 cc->iv_gen_ops = &crypt_iv_tcw_ops;
1681 cc->key_parts += 2; /* IV + whitening */
1682 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
34745785 1683 } else {
5ebaee6d 1684 ret = -EINVAL;
72d94861 1685 ti->error = "Invalid IV mode";
28513fcc 1686 goto bad;
1da177e4
LT
1687 }
1688
da31a078
MB
1689 /* Initialize and set key */
1690 ret = crypt_set_key(cc, key);
1691 if (ret < 0) {
1692 ti->error = "Error decoding and setting key";
1693 goto bad;
1694 }
1695
28513fcc
MB
1696 /* Allocate IV */
1697 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
1698 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
1699 if (ret < 0) {
1700 ti->error = "Error creating IV";
1701 goto bad;
1702 }
1703 }
1da177e4 1704
28513fcc
MB
1705 /* Initialize IV (set keys for ESSIV etc) */
1706 if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
1707 ret = cc->iv_gen_ops->init(cc);
1708 if (ret < 0) {
1709 ti->error = "Error initialising IV";
1710 goto bad;
1711 }
b95bf2d3
MB
1712 }
1713
5ebaee6d
MB
1714 ret = 0;
1715bad:
1716 kfree(cipher_api);
1717 return ret;
1718
1719bad_mem:
1720 ti->error = "Cannot allocate cipher strings";
1721 return -ENOMEM;
1722}
1723
1724/*
1725 * Construct an encryption mapping:
1726 * <cipher> <key> <iv_offset> <dev_path> <start>
1727 */
1728static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
1729{
1730 struct crypt_config *cc;
772ae5f5 1731 unsigned int key_size, opt_params;
5ebaee6d
MB
1732 unsigned long long tmpll;
1733 int ret;
772ae5f5
MB
1734 struct dm_arg_set as;
1735 const char *opt_string;
31998ef1 1736 char dummy;
772ae5f5
MB
1737
1738 static struct dm_arg _args[] = {
1739 {0, 1, "Invalid number of feature args"},
1740 };
5ebaee6d 1741
772ae5f5 1742 if (argc < 5) {
5ebaee6d
MB
1743 ti->error = "Not enough arguments";
1744 return -EINVAL;
1da177e4
LT
1745 }
1746
5ebaee6d
MB
1747 key_size = strlen(argv[1]) >> 1;
1748
1749 cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
1750 if (!cc) {
1751 ti->error = "Cannot allocate encryption context";
1752 return -ENOMEM;
1753 }
69a8cfcd 1754 cc->key_size = key_size;
5ebaee6d
MB
1755
1756 ti->private = cc;
1757 ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
1758 if (ret < 0)
1759 goto bad;
1760
28513fcc 1761 ret = -ENOMEM;
93d2341c 1762 cc->io_pool = mempool_create_slab_pool(MIN_IOS, _crypt_io_pool);
1da177e4 1763 if (!cc->io_pool) {
72d94861 1764 ti->error = "Cannot allocate crypt io mempool";
28513fcc 1765 goto bad;
1da177e4
LT
1766 }
1767
ddd42edf 1768 cc->dmreq_start = sizeof(struct ablkcipher_request);
c0297721 1769 cc->dmreq_start += crypto_ablkcipher_reqsize(any_tfm(cc));
ddd42edf 1770 cc->dmreq_start = ALIGN(cc->dmreq_start, crypto_tfm_ctx_alignment());
c0297721 1771 cc->dmreq_start += crypto_ablkcipher_alignmask(any_tfm(cc)) &
3a7f6c99 1772 ~(crypto_tfm_ctx_alignment() - 1);
ddd42edf
MB
1773
1774 cc->req_pool = mempool_create_kmalloc_pool(MIN_IOS, cc->dmreq_start +
1775 sizeof(struct dm_crypt_request) + cc->iv_size);
1776 if (!cc->req_pool) {
1777 ti->error = "Cannot allocate crypt request mempool";
28513fcc 1778 goto bad;
ddd42edf 1779 }
ddd42edf 1780
a19b27ce 1781 cc->page_pool = mempool_create_page_pool(MIN_POOL_PAGES, 0);
1da177e4 1782 if (!cc->page_pool) {
72d94861 1783 ti->error = "Cannot allocate page mempool";
28513fcc 1784 goto bad;
1da177e4
LT
1785 }
1786
bb799ca0 1787 cc->bs = bioset_create(MIN_IOS, 0);
6a24c718
MB
1788 if (!cc->bs) {
1789 ti->error = "Cannot allocate crypt bioset";
28513fcc 1790 goto bad;
6a24c718
MB
1791 }
1792
28513fcc 1793 ret = -EINVAL;
31998ef1 1794 if (sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) {
72d94861 1795 ti->error = "Invalid iv_offset sector";
28513fcc 1796 goto bad;
1da177e4 1797 }
4ee218cd 1798 cc->iv_offset = tmpll;
1da177e4 1799
28513fcc
MB
1800 if (dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev)) {
1801 ti->error = "Device lookup failed";
1802 goto bad;
1803 }
1804
31998ef1 1805 if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1) {
72d94861 1806 ti->error = "Invalid device sector";
28513fcc 1807 goto bad;
1da177e4 1808 }
4ee218cd 1809 cc->start = tmpll;
1da177e4 1810
772ae5f5
MB
1811 argv += 5;
1812 argc -= 5;
1813
1814 /* Optional parameters */
1815 if (argc) {
1816 as.argc = argc;
1817 as.argv = argv;
1818
1819 ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
1820 if (ret)
1821 goto bad;
1822
1823 opt_string = dm_shift_arg(&as);
1824
1825 if (opt_params == 1 && opt_string &&
1826 !strcasecmp(opt_string, "allow_discards"))
55a62eef 1827 ti->num_discard_bios = 1;
772ae5f5
MB
1828 else if (opt_params) {
1829 ret = -EINVAL;
1830 ti->error = "Invalid feature arguments";
1831 goto bad;
1832 }
1833 }
1834
28513fcc 1835 ret = -ENOMEM;
670368a8 1836 cc->io_queue = alloc_workqueue("kcryptd_io", WQ_MEM_RECLAIM, 1);
cabf08e4
MB
1837 if (!cc->io_queue) {
1838 ti->error = "Couldn't create kcryptd io queue";
28513fcc 1839 goto bad;
cabf08e4
MB
1840 }
1841
c0297721 1842 cc->crypt_queue = alloc_workqueue("kcryptd",
670368a8 1843 WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM, 1);
cabf08e4 1844 if (!cc->crypt_queue) {
9934a8be 1845 ti->error = "Couldn't create kcryptd queue";
28513fcc 1846 goto bad;
9934a8be
MB
1847 }
1848
55a62eef 1849 ti->num_flush_bios = 1;
0ac55489 1850 ti->discard_zeroes_data_unsupported = true;
983c7db3 1851
1da177e4
LT
1852 return 0;
1853
28513fcc
MB
1854bad:
1855 crypt_dtr(ti);
1856 return ret;
1da177e4
LT
1857}
1858
7de3ee57 1859static int crypt_map(struct dm_target *ti, struct bio *bio)
1da177e4 1860{
028867ac 1861 struct dm_crypt_io *io;
49a8a920 1862 struct crypt_config *cc = ti->private;
647c7db1 1863
772ae5f5
MB
1864 /*
1865 * If bio is REQ_FLUSH or REQ_DISCARD, just bypass crypt queues.
1866 * - for REQ_FLUSH device-mapper core ensures that no IO is in-flight
1867 * - for REQ_DISCARD caller must use flush if IO ordering matters
1868 */
1869 if (unlikely(bio->bi_rw & (REQ_FLUSH | REQ_DISCARD))) {
647c7db1 1870 bio->bi_bdev = cc->dev->bdev;
772ae5f5 1871 if (bio_sectors(bio))
4f024f37
KO
1872 bio->bi_iter.bi_sector = cc->start +
1873 dm_target_offset(ti, bio->bi_iter.bi_sector);
647c7db1
MP
1874 return DM_MAPIO_REMAPPED;
1875 }
1da177e4 1876
4f024f37 1877 io = crypt_io_alloc(cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
cabf08e4 1878
20c82538
MB
1879 if (bio_data_dir(io->base_bio) == READ) {
1880 if (kcryptd_io_read(io, GFP_NOWAIT))
1881 kcryptd_queue_io(io);
1882 } else
cabf08e4 1883 kcryptd_queue_crypt(io);
1da177e4 1884
d2a7ad29 1885 return DM_MAPIO_SUBMITTED;
1da177e4
LT
1886}
1887
fd7c092e
MP
1888static void crypt_status(struct dm_target *ti, status_type_t type,
1889 unsigned status_flags, char *result, unsigned maxlen)
1da177e4 1890{
5ebaee6d 1891 struct crypt_config *cc = ti->private;
fd7c092e 1892 unsigned i, sz = 0;
1da177e4
LT
1893
1894 switch (type) {
1895 case STATUSTYPE_INFO:
1896 result[0] = '\0';
1897 break;
1898
1899 case STATUSTYPE_TABLE:
7dbcd137 1900 DMEMIT("%s ", cc->cipher_string);
1da177e4 1901
fd7c092e
MP
1902 if (cc->key_size > 0)
1903 for (i = 0; i < cc->key_size; i++)
1904 DMEMIT("%02x", cc->key[i]);
1905 else
1906 DMEMIT("-");
1da177e4 1907
4ee218cd
AM
1908 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
1909 cc->dev->name, (unsigned long long)cc->start);
772ae5f5 1910
55a62eef 1911 if (ti->num_discard_bios)
772ae5f5
MB
1912 DMEMIT(" 1 allow_discards");
1913
1da177e4
LT
1914 break;
1915 }
1da177e4
LT
1916}
1917
e48d4bbf
MB
1918static void crypt_postsuspend(struct dm_target *ti)
1919{
1920 struct crypt_config *cc = ti->private;
1921
1922 set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
1923}
1924
1925static int crypt_preresume(struct dm_target *ti)
1926{
1927 struct crypt_config *cc = ti->private;
1928
1929 if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
1930 DMERR("aborting resume - crypt key is not set.");
1931 return -EAGAIN;
1932 }
1933
1934 return 0;
1935}
1936
1937static void crypt_resume(struct dm_target *ti)
1938{
1939 struct crypt_config *cc = ti->private;
1940
1941 clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
1942}
1943
1944/* Message interface
1945 * key set <key>
1946 * key wipe
1947 */
1948static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
1949{
1950 struct crypt_config *cc = ti->private;
542da317 1951 int ret = -EINVAL;
e48d4bbf
MB
1952
1953 if (argc < 2)
1954 goto error;
1955
498f0103 1956 if (!strcasecmp(argv[0], "key")) {
e48d4bbf
MB
1957 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
1958 DMWARN("not suspended during key manipulation.");
1959 return -EINVAL;
1960 }
498f0103 1961 if (argc == 3 && !strcasecmp(argv[1], "set")) {
542da317
MB
1962 ret = crypt_set_key(cc, argv[2]);
1963 if (ret)
1964 return ret;
1965 if (cc->iv_gen_ops && cc->iv_gen_ops->init)
1966 ret = cc->iv_gen_ops->init(cc);
1967 return ret;
1968 }
498f0103 1969 if (argc == 2 && !strcasecmp(argv[1], "wipe")) {
542da317
MB
1970 if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
1971 ret = cc->iv_gen_ops->wipe(cc);
1972 if (ret)
1973 return ret;
1974 }
e48d4bbf 1975 return crypt_wipe_key(cc);
542da317 1976 }
e48d4bbf
MB
1977 }
1978
1979error:
1980 DMWARN("unrecognised message received.");
1981 return -EINVAL;
1982}
1983
d41e26b9
MB
1984static int crypt_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
1985 struct bio_vec *biovec, int max_size)
1986{
1987 struct crypt_config *cc = ti->private;
1988 struct request_queue *q = bdev_get_queue(cc->dev->bdev);
1989
1990 if (!q->merge_bvec_fn)
1991 return max_size;
1992
1993 bvm->bi_bdev = cc->dev->bdev;
b441a262 1994 bvm->bi_sector = cc->start + dm_target_offset(ti, bvm->bi_sector);
d41e26b9
MB
1995
1996 return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
1997}
1998
af4874e0
MS
1999static int crypt_iterate_devices(struct dm_target *ti,
2000 iterate_devices_callout_fn fn, void *data)
2001{
2002 struct crypt_config *cc = ti->private;
2003
5dea271b 2004 return fn(ti, cc->dev, cc->start, ti->len, data);
af4874e0
MS
2005}
2006
1da177e4
LT
2007static struct target_type crypt_target = {
2008 .name = "crypt",
ed04d981 2009 .version = {1, 13, 0},
1da177e4
LT
2010 .module = THIS_MODULE,
2011 .ctr = crypt_ctr,
2012 .dtr = crypt_dtr,
2013 .map = crypt_map,
2014 .status = crypt_status,
e48d4bbf
MB
2015 .postsuspend = crypt_postsuspend,
2016 .preresume = crypt_preresume,
2017 .resume = crypt_resume,
2018 .message = crypt_message,
d41e26b9 2019 .merge = crypt_merge,
af4874e0 2020 .iterate_devices = crypt_iterate_devices,
1da177e4
LT
2021};
2022
2023static int __init dm_crypt_init(void)
2024{
2025 int r;
2026
028867ac 2027 _crypt_io_pool = KMEM_CACHE(dm_crypt_io, 0);
1da177e4
LT
2028 if (!_crypt_io_pool)
2029 return -ENOMEM;
2030
1da177e4
LT
2031 r = dm_register_target(&crypt_target);
2032 if (r < 0) {
72d94861 2033 DMERR("register failed %d", r);
9934a8be 2034 kmem_cache_destroy(_crypt_io_pool);
1da177e4
LT
2035 }
2036
1da177e4
LT
2037 return r;
2038}
2039
2040static void __exit dm_crypt_exit(void)
2041{
10d3bd09 2042 dm_unregister_target(&crypt_target);
1da177e4
LT
2043 kmem_cache_destroy(_crypt_io_pool);
2044}
2045
2046module_init(dm_crypt_init);
2047module_exit(dm_crypt_exit);
2048
2049MODULE_AUTHOR("Christophe Saout <christophe@saout.de>");
2050MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
2051MODULE_LICENSE("GPL");