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