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