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