dm: change "unsigned" to "unsigned int"
[linux-2.6-block.git] / drivers / md / dm-crypt.c
CommitLineData
3bd94003 1// SPDX-License-Identifier: GPL-2.0-only
1da177e4 2/*
bf14299f 3 * Copyright (C) 2003 Jana Saout <jana@saout.de>
1da177e4 4 * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
bbb16584
MB
5 * Copyright (C) 2006-2020 Red Hat, Inc. All rights reserved.
6 * Copyright (C) 2013-2020 Milan Broz <gmazyland@gmail.com>
1da177e4
LT
7 *
8 * This file is released under the GPL.
9 */
10
43d69034 11#include <linux/completion.h>
d1806f6a 12#include <linux/err.h>
1da177e4
LT
13#include <linux/module.h>
14#include <linux/init.h>
15#include <linux/kernel.h>
c538f6ec 16#include <linux/key.h>
1da177e4
LT
17#include <linux/bio.h>
18#include <linux/blkdev.h>
fe45e630 19#include <linux/blk-integrity.h>
1da177e4
LT
20#include <linux/mempool.h>
21#include <linux/slab.h>
22#include <linux/crypto.h>
23#include <linux/workqueue.h>
dc267621 24#include <linux/kthread.h>
3fcfab16 25#include <linux/backing-dev.h>
60063497 26#include <linux/atomic.h>
378f058c 27#include <linux/scatterlist.h>
b3c5fd30 28#include <linux/rbtree.h>
027c431c 29#include <linux/ctype.h>
1da177e4 30#include <asm/page.h>
48527fa7 31#include <asm/unaligned.h>
34745785
MB
32#include <crypto/hash.h>
33#include <crypto/md5.h>
34#include <crypto/algapi.h>
bbdb23b5 35#include <crypto/skcipher.h>
ef43aa38
MB
36#include <crypto/aead.h>
37#include <crypto/authenc.h>
38#include <linux/rtnetlink.h> /* for struct rtattr and RTA macros only */
27f5411a 39#include <linux/key-type.h>
c538f6ec 40#include <keys/user-type.h>
27f5411a 41#include <keys/encrypted-type.h>
363880c4 42#include <keys/trusted-type.h>
1da177e4 43
586e80e6 44#include <linux/device-mapper.h>
1da177e4 45
58d0f180
MW
46#include "dm-audit.h"
47
72d94861 48#define DM_MSG_PREFIX "crypt"
1da177e4 49
1da177e4
LT
50/*
51 * context holding the current state of a multi-part conversion
52 */
53struct convert_context {
43d69034 54 struct completion restart;
1da177e4
LT
55 struct bio *bio_in;
56 struct bio *bio_out;
003b5c57
KO
57 struct bvec_iter iter_in;
58 struct bvec_iter iter_out;
8d683dcd 59 u64 cc_sector;
40b6229b 60 atomic_t cc_pending;
ef43aa38
MB
61 union {
62 struct skcipher_request *req;
63 struct aead_request *req_aead;
64 } r;
65
1da177e4
LT
66};
67
53017030
MB
68/*
69 * per bio private data
70 */
71struct dm_crypt_io {
49a8a920 72 struct crypt_config *cc;
53017030 73 struct bio *base_bio;
ef43aa38
MB
74 u8 *integrity_metadata;
75 bool integrity_metadata_from_pool;
53017030 76 struct work_struct work;
39d42fa9 77 struct tasklet_struct tasklet;
53017030
MB
78
79 struct convert_context ctx;
80
40b6229b 81 atomic_t io_pending;
4e4cbee9 82 blk_status_t error;
0c395b0f 83 sector_t sector;
dc267621 84
b3c5fd30 85 struct rb_node rb_node;
298a9fa0 86} CRYPTO_MINALIGN_ATTR;
53017030 87
01482b76 88struct dm_crypt_request {
b2174eeb 89 struct convert_context *ctx;
ef43aa38
MB
90 struct scatterlist sg_in[4];
91 struct scatterlist sg_out[4];
8d683dcd 92 u64 iv_sector;
01482b76
MB
93};
94
1da177e4
LT
95struct crypt_config;
96
97struct crypt_iv_operations {
98 int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
d469f841 99 const char *opts);
1da177e4 100 void (*dtr)(struct crypt_config *cc);
b95bf2d3 101 int (*init)(struct crypt_config *cc);
542da317 102 int (*wipe)(struct crypt_config *cc);
2dc5327d
MB
103 int (*generator)(struct crypt_config *cc, u8 *iv,
104 struct dm_crypt_request *dmreq);
105 int (*post)(struct crypt_config *cc, u8 *iv,
106 struct dm_crypt_request *dmreq);
1da177e4
LT
107};
108
60473592
MB
109struct iv_benbi_private {
110 int shift;
111};
112
34745785
MB
113#define LMK_SEED_SIZE 64 /* hash + 0 */
114struct iv_lmk_private {
115 struct crypto_shash *hash_tfm;
116 u8 *seed;
117};
118
ed04d981
MB
119#define TCW_WHITENING_SIZE 16
120struct iv_tcw_private {
121 struct crypto_shash *crc32_tfm;
122 u8 *iv_seed;
123 u8 *whitening;
124};
125
bbb16584
MB
126#define ELEPHANT_MAX_KEY_SIZE 32
127struct iv_elephant_private {
128 struct crypto_skcipher *tfm;
129};
130
1da177e4
LT
131/*
132 * Crypt: maps a linear range of a block device
133 * and encrypts / decrypts at the same time.
134 */
0f5d8e6e 135enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
39d42fa9 136 DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD,
8e225f04
DLM
137 DM_CRYPT_NO_READ_WORKQUEUE, DM_CRYPT_NO_WRITE_WORKQUEUE,
138 DM_CRYPT_WRITE_INLINE };
c0297721 139
ef43aa38 140enum cipher_flags {
74d1da39 141 CRYPT_MODE_INTEGRITY_AEAD, /* Use authenticated mode for cipher */
8f0009a2 142 CRYPT_IV_LARGE_SECTORS, /* Calculate IV from sector_size, not 512B sectors */
bbb16584 143 CRYPT_ENCRYPT_PREPROCESS, /* Must preprocess data for encryption (elephant) */
ef43aa38
MB
144};
145
c0297721 146/*
610f2de3 147 * The fields in here must be read only after initialization.
c0297721 148 */
1da177e4
LT
149struct crypt_config {
150 struct dm_dev *dev;
151 sector_t start;
152
5059353d
MP
153 struct percpu_counter n_allocated_pages;
154
cabf08e4
MB
155 struct workqueue_struct *io_queue;
156 struct workqueue_struct *crypt_queue;
3f1e9070 157
c7329eff 158 spinlock_t write_thread_lock;
72d711c8 159 struct task_struct *write_thread;
b3c5fd30 160 struct rb_root write_tree;
dc267621 161
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 168 struct iv_benbi_private benbi;
34745785 169 struct iv_lmk_private lmk;
ed04d981 170 struct iv_tcw_private tcw;
bbb16584 171 struct iv_elephant_private elephant;
79066ad3 172 } iv_gen_private;
8d683dcd 173 u64 iv_offset;
1da177e4 174 unsigned int iv_size;
86a3238c 175 unsigned short sector_size;
ff3af92b 176 unsigned char sector_shift;
1da177e4 177
ef43aa38
MB
178 union {
179 struct crypto_skcipher **tfms;
180 struct crypto_aead **tfms_aead;
181 } cipher_tfm;
86a3238c 182 unsigned int tfms_count;
ef43aa38 183 unsigned long cipher_flags;
c0297721 184
ddd42edf
MB
185 /*
186 * Layout of each crypto request:
187 *
bbdb23b5 188 * struct skcipher_request
ddd42edf
MB
189 * context
190 * padding
191 * struct dm_crypt_request
192 * padding
193 * IV
194 *
195 * The padding is added so that dm_crypt_request and the IV are
196 * correctly aligned.
197 */
198 unsigned int dmreq_start;
ddd42edf 199
298a9fa0
MP
200 unsigned int per_bio_data_size;
201
e48d4bbf 202 unsigned long flags;
1da177e4 203 unsigned int key_size;
da31a078
MB
204 unsigned int key_parts; /* independent parts in key buffer */
205 unsigned int key_extra_size; /* additional keys length */
ef43aa38
MB
206 unsigned int key_mac_size; /* MAC key size for authenc(...) */
207
208 unsigned int integrity_tag_size;
209 unsigned int integrity_iv_size;
210 unsigned int on_disk_tag_size;
211
72d711c8
MS
212 /*
213 * pool for per bio private data, crypto requests,
214 * encryption requeusts/buffer pages and integrity tags
215 */
86a3238c 216 unsigned int tag_pool_max_sectors;
72d711c8
MS
217 mempool_t tag_pool;
218 mempool_t req_pool;
219 mempool_t page_pool;
220
221 struct bio_set bs;
222 struct mutex bio_alloc_lock;
223
ef43aa38 224 u8 *authenc_key; /* space for keys in authenc() format (if used) */
b18ae8dd 225 u8 key[];
1da177e4
LT
226};
227
ef43aa38
MB
228#define MIN_IOS 64
229#define MAX_TAG_SIZE 480
230#define POOL_ENTRY_SIZE 512
1da177e4 231
5059353d 232static DEFINE_SPINLOCK(dm_crypt_clients_lock);
86a3238c 233static unsigned int dm_crypt_clients_n = 0;
5059353d
MP
234static volatile unsigned long dm_crypt_pages_per_client;
235#define DM_CRYPT_MEMORY_PERCENT 2
a8affc03 236#define DM_CRYPT_MIN_PAGES_PER_CLIENT (BIO_MAX_VECS * 16)
5059353d 237
3f868c09 238static void crypt_endio(struct bio *clone);
395b167c 239static void kcryptd_queue_crypt(struct dm_crypt_io *io);
ef43aa38
MB
240static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
241 struct scatterlist *sg);
027581f3 242
3fd53533
YY
243static bool crypt_integrity_aead(struct crypt_config *cc);
244
c0297721 245/*
86f917ad 246 * Use this to access cipher attributes that are independent of the key.
c0297721 247 */
bbdb23b5 248static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
c0297721 249{
ef43aa38
MB
250 return cc->cipher_tfm.tfms[0];
251}
252
253static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
254{
255 return cc->cipher_tfm.tfms_aead[0];
c0297721
AK
256}
257
1da177e4
LT
258/*
259 * Different IV generation algorithms:
260 *
3c164bd8 261 * plain: the initial vector is the 32-bit little-endian version of the sector
3a4fa0a2 262 * number, padded with zeros if necessary.
1da177e4 263 *
61afef61
MB
264 * plain64: the initial vector is the 64-bit little-endian version of the sector
265 * number, padded with zeros if necessary.
266 *
7e3fd855
MB
267 * plain64be: the initial vector is the 64-bit big-endian version of the sector
268 * number, padded with zeros if necessary.
269 *
3c164bd8
RS
270 * essiv: "encrypted sector|salt initial vector", the sector number is
271 * encrypted with the bulk cipher using a salt as key. The salt
272 * should be derived from the bulk cipher's key via hashing.
1da177e4 273 *
48527fa7
RS
274 * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
275 * (needed for LRW-32-AES and possible other narrow block modes)
276 *
46b47730
LN
277 * null: the initial vector is always zero. Provides compatibility with
278 * obsolete loop_fish2 devices. Do not use for new devices.
279 *
34745785
MB
280 * lmk: Compatible implementation of the block chaining mode used
281 * by the Loop-AES block device encryption system
282 * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
283 * It operates on full 512 byte sectors and uses CBC
284 * with an IV derived from the sector number, the data and
285 * optionally extra IV seed.
286 * This means that after decryption the first block
287 * of sector must be tweaked according to decrypted data.
288 * Loop-AES can use three encryption schemes:
289 * version 1: is plain aes-cbc mode
290 * version 2: uses 64 multikey scheme with lmk IV generator
291 * version 3: the same as version 2 with additional IV seed
292 * (it uses 65 keys, last key is used as IV seed)
293 *
ed04d981
MB
294 * tcw: Compatible implementation of the block chaining mode used
295 * by the TrueCrypt device encryption system (prior to version 4.1).
e44f23b3 296 * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
ed04d981
MB
297 * It operates on full 512 byte sectors and uses CBC
298 * with an IV derived from initial key and the sector number.
299 * In addition, whitening value is applied on every sector, whitening
300 * is calculated from initial key, sector number and mixed using CRC32.
301 * Note that this encryption scheme is vulnerable to watermarking attacks
302 * and should be used for old compatible containers access only.
b9411d73
MB
303 *
304 * eboiv: Encrypted byte-offset IV (used in Bitlocker in CBC mode)
305 * The IV is encrypted little-endian byte-offset (with the same key
306 * and cipher as the volume).
bbb16584
MB
307 *
308 * elephant: The extended version of eboiv with additional Elephant diffuser
309 * used with Bitlocker CBC mode.
310 * This mode was used in older Windows systems
6f3bc22b 311 * https://download.microsoft.com/download/0/2/3/0238acaf-d3bf-4a6d-b3d6-0a0be4bbb36e/bitlockercipher200608.pdf
1da177e4
LT
312 */
313
2dc5327d
MB
314static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
315 struct dm_crypt_request *dmreq)
1da177e4
LT
316{
317 memset(iv, 0, cc->iv_size);
283a8328 318 *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
1da177e4
LT
319
320 return 0;
321}
322
61afef61 323static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
2dc5327d 324 struct dm_crypt_request *dmreq)
61afef61
MB
325{
326 memset(iv, 0, cc->iv_size);
283a8328 327 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
61afef61
MB
328
329 return 0;
330}
331
7e3fd855
MB
332static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
333 struct dm_crypt_request *dmreq)
334{
335 memset(iv, 0, cc->iv_size);
336 /* iv_size is at least of size u64; usually it is 16 bytes */
337 *(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
338
339 return 0;
340}
341
2dc5327d
MB
342static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
343 struct dm_crypt_request *dmreq)
1da177e4 344{
a1a262b6
AB
345 /*
346 * ESSIV encryption of the IV is now handled by the crypto API,
347 * so just pass the plain sector number here.
348 */
1da177e4 349 memset(iv, 0, cc->iv_size);
283a8328 350 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
c0297721 351
1da177e4
LT
352 return 0;
353}
354
48527fa7
RS
355static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
356 const char *opts)
357{
86a3238c 358 unsigned int bs;
4ea9471f
MB
359 int log;
360
3fd53533 361 if (crypt_integrity_aead(cc))
4ea9471f
MB
362 bs = crypto_aead_blocksize(any_tfm_aead(cc));
363 else
364 bs = crypto_skcipher_blocksize(any_tfm(cc));
365 log = ilog2(bs);
48527fa7
RS
366
367 /* we need to calculate how far we must shift the sector count
368 * to get the cipher block count, we use this shift in _gen */
369
370 if (1 << log != bs) {
371 ti->error = "cypher blocksize is not a power of 2";
372 return -EINVAL;
373 }
374
375 if (log > 9) {
376 ti->error = "cypher blocksize is > 512";
377 return -EINVAL;
378 }
379
60473592 380 cc->iv_gen_private.benbi.shift = 9 - log;
48527fa7
RS
381
382 return 0;
383}
384
385static void crypt_iv_benbi_dtr(struct crypt_config *cc)
386{
48527fa7
RS
387}
388
2dc5327d
MB
389static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
390 struct dm_crypt_request *dmreq)
48527fa7 391{
79066ad3
HX
392 __be64 val;
393
48527fa7 394 memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
79066ad3 395
2dc5327d 396 val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
79066ad3 397 put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
48527fa7 398
1da177e4
LT
399 return 0;
400}
401
2dc5327d
MB
402static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
403 struct dm_crypt_request *dmreq)
46b47730
LN
404{
405 memset(iv, 0, cc->iv_size);
406
407 return 0;
408}
409
34745785
MB
410static void crypt_iv_lmk_dtr(struct crypt_config *cc)
411{
412 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
413
414 if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
415 crypto_free_shash(lmk->hash_tfm);
416 lmk->hash_tfm = NULL;
417
453431a5 418 kfree_sensitive(lmk->seed);
34745785
MB
419 lmk->seed = NULL;
420}
421
422static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
423 const char *opts)
424{
425 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
426
8f0009a2
MB
427 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
428 ti->error = "Unsupported sector size for LMK";
429 return -EINVAL;
430 }
431
cd746938
MP
432 lmk->hash_tfm = crypto_alloc_shash("md5", 0,
433 CRYPTO_ALG_ALLOCATES_MEMORY);
34745785
MB
434 if (IS_ERR(lmk->hash_tfm)) {
435 ti->error = "Error initializing LMK hash";
436 return PTR_ERR(lmk->hash_tfm);
437 }
438
439 /* No seed in LMK version 2 */
440 if (cc->key_parts == cc->tfms_count) {
441 lmk->seed = NULL;
442 return 0;
443 }
444
445 lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
446 if (!lmk->seed) {
447 crypt_iv_lmk_dtr(cc);
448 ti->error = "Error kmallocing seed storage in LMK";
449 return -ENOMEM;
450 }
451
452 return 0;
453}
454
455static int crypt_iv_lmk_init(struct crypt_config *cc)
456{
457 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
458 int subkey_size = cc->key_size / cc->key_parts;
459
460 /* LMK seed is on the position of LMK_KEYS + 1 key */
461 if (lmk->seed)
462 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
463 crypto_shash_digestsize(lmk->hash_tfm));
464
465 return 0;
466}
467
468static int crypt_iv_lmk_wipe(struct crypt_config *cc)
469{
470 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
471
472 if (lmk->seed)
473 memset(lmk->seed, 0, LMK_SEED_SIZE);
474
475 return 0;
476}
477
478static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
479 struct dm_crypt_request *dmreq,
480 u8 *data)
481{
482 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
b6106265 483 SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
34745785 484 struct md5_state md5state;
da31a078 485 __le32 buf[4];
34745785
MB
486 int i, r;
487
b6106265 488 desc->tfm = lmk->hash_tfm;
34745785 489
b6106265 490 r = crypto_shash_init(desc);
34745785
MB
491 if (r)
492 return r;
493
494 if (lmk->seed) {
b6106265 495 r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
34745785
MB
496 if (r)
497 return r;
498 }
499
500 /* Sector is always 512B, block size 16, add data of blocks 1-31 */
b6106265 501 r = crypto_shash_update(desc, data + 16, 16 * 31);
34745785
MB
502 if (r)
503 return r;
504
505 /* Sector is cropped to 56 bits here */
506 buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
507 buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
508 buf[2] = cpu_to_le32(4024);
509 buf[3] = 0;
b6106265 510 r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
34745785
MB
511 if (r)
512 return r;
513
514 /* No MD5 padding here */
b6106265 515 r = crypto_shash_export(desc, &md5state);
34745785
MB
516 if (r)
517 return r;
518
519 for (i = 0; i < MD5_HASH_WORDS; i++)
520 __cpu_to_le32s(&md5state.hash[i]);
521 memcpy(iv, &md5state.hash, cc->iv_size);
522
523 return 0;
524}
525
526static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
527 struct dm_crypt_request *dmreq)
528{
ef43aa38 529 struct scatterlist *sg;
34745785
MB
530 u8 *src;
531 int r = 0;
532
533 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
ef43aa38 534 sg = crypt_get_sg_data(cc, dmreq->sg_in);
0d78954a 535 src = kmap_local_page(sg_page(sg));
ef43aa38 536 r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
0d78954a 537 kunmap_local(src);
34745785
MB
538 } else
539 memset(iv, 0, cc->iv_size);
540
541 return r;
542}
543
544static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
545 struct dm_crypt_request *dmreq)
546{
ef43aa38 547 struct scatterlist *sg;
34745785
MB
548 u8 *dst;
549 int r;
550
551 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
552 return 0;
553
ef43aa38 554 sg = crypt_get_sg_data(cc, dmreq->sg_out);
0d78954a 555 dst = kmap_local_page(sg_page(sg));
ef43aa38 556 r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
34745785
MB
557
558 /* Tweak the first block of plaintext sector */
559 if (!r)
ef43aa38 560 crypto_xor(dst + sg->offset, iv, cc->iv_size);
34745785 561
0d78954a 562 kunmap_local(dst);
34745785
MB
563 return r;
564}
565
ed04d981
MB
566static void crypt_iv_tcw_dtr(struct crypt_config *cc)
567{
568 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
569
453431a5 570 kfree_sensitive(tcw->iv_seed);
ed04d981 571 tcw->iv_seed = NULL;
453431a5 572 kfree_sensitive(tcw->whitening);
ed04d981
MB
573 tcw->whitening = NULL;
574
575 if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
576 crypto_free_shash(tcw->crc32_tfm);
577 tcw->crc32_tfm = NULL;
578}
579
580static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
581 const char *opts)
582{
583 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
584
8f0009a2
MB
585 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
586 ti->error = "Unsupported sector size for TCW";
587 return -EINVAL;
588 }
589
ed04d981
MB
590 if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
591 ti->error = "Wrong key size for TCW";
592 return -EINVAL;
593 }
594
cd746938
MP
595 tcw->crc32_tfm = crypto_alloc_shash("crc32", 0,
596 CRYPTO_ALG_ALLOCATES_MEMORY);
ed04d981
MB
597 if (IS_ERR(tcw->crc32_tfm)) {
598 ti->error = "Error initializing CRC32 in TCW";
599 return PTR_ERR(tcw->crc32_tfm);
600 }
601
602 tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
603 tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
604 if (!tcw->iv_seed || !tcw->whitening) {
605 crypt_iv_tcw_dtr(cc);
606 ti->error = "Error allocating seed storage in TCW";
607 return -ENOMEM;
608 }
609
610 return 0;
611}
612
613static int crypt_iv_tcw_init(struct crypt_config *cc)
614{
615 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
616 int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
617
618 memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
619 memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
620 TCW_WHITENING_SIZE);
621
622 return 0;
623}
624
625static int crypt_iv_tcw_wipe(struct crypt_config *cc)
626{
627 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
628
629 memset(tcw->iv_seed, 0, cc->iv_size);
630 memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
631
632 return 0;
633}
634
635static int crypt_iv_tcw_whitening(struct crypt_config *cc,
636 struct dm_crypt_request *dmreq,
637 u8 *data)
638{
639 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
350b5393 640 __le64 sector = cpu_to_le64(dmreq->iv_sector);
ed04d981 641 u8 buf[TCW_WHITENING_SIZE];
b6106265 642 SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
ed04d981
MB
643 int i, r;
644
645 /* xor whitening with sector number */
45fe93df
AB
646 crypto_xor_cpy(buf, tcw->whitening, (u8 *)&sector, 8);
647 crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)&sector, 8);
ed04d981
MB
648
649 /* calculate crc32 for every 32bit part and xor it */
b6106265 650 desc->tfm = tcw->crc32_tfm;
ed04d981 651 for (i = 0; i < 4; i++) {
b6106265 652 r = crypto_shash_init(desc);
ed04d981
MB
653 if (r)
654 goto out;
b6106265 655 r = crypto_shash_update(desc, &buf[i * 4], 4);
ed04d981
MB
656 if (r)
657 goto out;
b6106265 658 r = crypto_shash_final(desc, &buf[i * 4]);
ed04d981
MB
659 if (r)
660 goto out;
661 }
662 crypto_xor(&buf[0], &buf[12], 4);
663 crypto_xor(&buf[4], &buf[8], 4);
664
665 /* apply whitening (8 bytes) to whole sector */
666 for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
667 crypto_xor(data + i * 8, buf, 8);
668out:
1a71d6ff 669 memzero_explicit(buf, sizeof(buf));
ed04d981
MB
670 return r;
671}
672
673static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
674 struct dm_crypt_request *dmreq)
675{
ef43aa38 676 struct scatterlist *sg;
ed04d981 677 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
350b5393 678 __le64 sector = cpu_to_le64(dmreq->iv_sector);
ed04d981
MB
679 u8 *src;
680 int r = 0;
681
682 /* Remove whitening from ciphertext */
683 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
ef43aa38 684 sg = crypt_get_sg_data(cc, dmreq->sg_in);
0d78954a 685 src = kmap_local_page(sg_page(sg));
ef43aa38 686 r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
0d78954a 687 kunmap_local(src);
ed04d981
MB
688 }
689
690 /* Calculate IV */
45fe93df 691 crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)&sector, 8);
ed04d981 692 if (cc->iv_size > 8)
45fe93df
AB
693 crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)&sector,
694 cc->iv_size - 8);
ed04d981
MB
695
696 return r;
697}
698
699static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
700 struct dm_crypt_request *dmreq)
701{
ef43aa38 702 struct scatterlist *sg;
ed04d981
MB
703 u8 *dst;
704 int r;
705
706 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
707 return 0;
708
709 /* Apply whitening on ciphertext */
ef43aa38 710 sg = crypt_get_sg_data(cc, dmreq->sg_out);
0d78954a 711 dst = kmap_local_page(sg_page(sg));
ef43aa38 712 r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
0d78954a 713 kunmap_local(dst);
ed04d981
MB
714
715 return r;
716}
717
ef43aa38
MB
718static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
719 struct dm_crypt_request *dmreq)
720{
721 /* Used only for writes, there must be an additional space to store IV */
722 get_random_bytes(iv, cc->iv_size);
723 return 0;
724}
725
b9411d73
MB
726static int crypt_iv_eboiv_ctr(struct crypt_config *cc, struct dm_target *ti,
727 const char *opts)
728{
3fd53533 729 if (crypt_integrity_aead(cc)) {
39d13a1a
AB
730 ti->error = "AEAD transforms not supported for EBOIV";
731 return -EINVAL;
b9411d73
MB
732 }
733
39d13a1a 734 if (crypto_skcipher_blocksize(any_tfm(cc)) != cc->iv_size) {
b9411d73
MB
735 ti->error = "Block size of EBOIV cipher does "
736 "not match IV size of block cipher";
b9411d73
MB
737 return -EINVAL;
738 }
739
b9411d73
MB
740 return 0;
741}
742
39d13a1a
AB
743static int crypt_iv_eboiv_gen(struct crypt_config *cc, u8 *iv,
744 struct dm_crypt_request *dmreq)
b9411d73 745{
39d13a1a
AB
746 u8 buf[MAX_CIPHER_BLOCKSIZE] __aligned(__alignof__(__le64));
747 struct skcipher_request *req;
748 struct scatterlist src, dst;
7785a9e4 749 DECLARE_CRYPTO_WAIT(wait);
b9411d73
MB
750 int err;
751
9402e959 752 req = skcipher_request_alloc(any_tfm(cc), GFP_NOIO);
39d13a1a
AB
753 if (!req)
754 return -ENOMEM;
b9411d73 755
39d13a1a
AB
756 memset(buf, 0, cc->iv_size);
757 *(__le64 *)buf = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
b9411d73 758
39d13a1a
AB
759 sg_init_one(&src, page_address(ZERO_PAGE(0)), cc->iv_size);
760 sg_init_one(&dst, iv, cc->iv_size);
761 skcipher_request_set_crypt(req, &src, &dst, cc->iv_size, buf);
762 skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
763 err = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
764 skcipher_request_free(req);
b9411d73 765
39d13a1a 766 return err;
b9411d73
MB
767}
768
bbb16584
MB
769static void crypt_iv_elephant_dtr(struct crypt_config *cc)
770{
771 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
772
773 crypto_free_skcipher(elephant->tfm);
774 elephant->tfm = NULL;
775}
776
777static int crypt_iv_elephant_ctr(struct crypt_config *cc, struct dm_target *ti,
778 const char *opts)
779{
780 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
781 int r;
782
cd746938
MP
783 elephant->tfm = crypto_alloc_skcipher("ecb(aes)", 0,
784 CRYPTO_ALG_ALLOCATES_MEMORY);
bbb16584
MB
785 if (IS_ERR(elephant->tfm)) {
786 r = PTR_ERR(elephant->tfm);
787 elephant->tfm = NULL;
788 return r;
789 }
790
791 r = crypt_iv_eboiv_ctr(cc, ti, NULL);
792 if (r)
793 crypt_iv_elephant_dtr(cc);
794 return r;
795}
796
797static void diffuser_disk_to_cpu(u32 *d, size_t n)
798{
799#ifndef __LITTLE_ENDIAN
800 int i;
801
802 for (i = 0; i < n; i++)
803 d[i] = le32_to_cpu((__le32)d[i]);
804#endif
805}
806
807static void diffuser_cpu_to_disk(__le32 *d, size_t n)
808{
809#ifndef __LITTLE_ENDIAN
810 int i;
811
812 for (i = 0; i < n; i++)
813 d[i] = cpu_to_le32((u32)d[i]);
814#endif
815}
816
817static void diffuser_a_decrypt(u32 *d, size_t n)
818{
819 int i, i1, i2, i3;
820
821 for (i = 0; i < 5; i++) {
822 i1 = 0;
823 i2 = n - 2;
824 i3 = n - 5;
825
826 while (i1 < (n - 1)) {
827 d[i1] += d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
828 i1++; i2++; i3++;
829
830 if (i3 >= n)
831 i3 -= n;
832
833 d[i1] += d[i2] ^ d[i3];
834 i1++; i2++; i3++;
835
836 if (i2 >= n)
837 i2 -= n;
838
839 d[i1] += d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
840 i1++; i2++; i3++;
841
842 d[i1] += d[i2] ^ d[i3];
843 i1++; i2++; i3++;
844 }
845 }
846}
847
848static void diffuser_a_encrypt(u32 *d, size_t n)
849{
850 int i, i1, i2, i3;
851
852 for (i = 0; i < 5; i++) {
853 i1 = n - 1;
854 i2 = n - 2 - 1;
855 i3 = n - 5 - 1;
856
857 while (i1 > 0) {
858 d[i1] -= d[i2] ^ d[i3];
859 i1--; i2--; i3--;
860
861 d[i1] -= d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
862 i1--; i2--; i3--;
863
864 if (i2 < 0)
865 i2 += n;
866
867 d[i1] -= d[i2] ^ d[i3];
868 i1--; i2--; i3--;
869
870 if (i3 < 0)
871 i3 += n;
872
873 d[i1] -= d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
874 i1--; i2--; i3--;
875 }
876 }
877}
878
879static void diffuser_b_decrypt(u32 *d, size_t n)
880{
881 int i, i1, i2, i3;
882
883 for (i = 0; i < 3; i++) {
884 i1 = 0;
885 i2 = 2;
886 i3 = 5;
887
888 while (i1 < (n - 1)) {
889 d[i1] += d[i2] ^ d[i3];
890 i1++; i2++; i3++;
891
892 d[i1] += d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
893 i1++; i2++; i3++;
894
895 if (i2 >= n)
896 i2 -= n;
897
898 d[i1] += d[i2] ^ d[i3];
899 i1++; i2++; i3++;
900
901 if (i3 >= n)
902 i3 -= n;
903
904 d[i1] += d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
905 i1++; i2++; i3++;
906 }
907 }
908}
909
910static void diffuser_b_encrypt(u32 *d, size_t n)
911{
912 int i, i1, i2, i3;
913
914 for (i = 0; i < 3; i++) {
915 i1 = n - 1;
916 i2 = 2 - 1;
917 i3 = 5 - 1;
918
919 while (i1 > 0) {
920 d[i1] -= d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
921 i1--; i2--; i3--;
922
923 if (i3 < 0)
924 i3 += n;
925
926 d[i1] -= d[i2] ^ d[i3];
927 i1--; i2--; i3--;
928
929 if (i2 < 0)
930 i2 += n;
931
932 d[i1] -= d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
933 i1--; i2--; i3--;
934
935 d[i1] -= d[i2] ^ d[i3];
936 i1--; i2--; i3--;
937 }
938 }
939}
940
941static int crypt_iv_elephant(struct crypt_config *cc, struct dm_crypt_request *dmreq)
942{
943 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
944 u8 *es, *ks, *data, *data2, *data_offset;
945 struct skcipher_request *req;
946 struct scatterlist *sg, *sg2, src, dst;
7785a9e4 947 DECLARE_CRYPTO_WAIT(wait);
bbb16584
MB
948 int i, r;
949
950 req = skcipher_request_alloc(elephant->tfm, GFP_NOIO);
951 es = kzalloc(16, GFP_NOIO); /* Key for AES */
952 ks = kzalloc(32, GFP_NOIO); /* Elephant sector key */
953
954 if (!req || !es || !ks) {
955 r = -ENOMEM;
956 goto out;
957 }
958
959 *(__le64 *)es = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
960
961 /* E(Ks, e(s)) */
962 sg_init_one(&src, es, 16);
963 sg_init_one(&dst, ks, 16);
964 skcipher_request_set_crypt(req, &src, &dst, 16, NULL);
965 skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
966 r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
967 if (r)
968 goto out;
969
970 /* E(Ks, e'(s)) */
971 es[15] = 0x80;
972 sg_init_one(&dst, &ks[16], 16);
973 r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
974 if (r)
975 goto out;
976
977 sg = crypt_get_sg_data(cc, dmreq->sg_out);
0d78954a 978 data = kmap_local_page(sg_page(sg));
bbb16584
MB
979 data_offset = data + sg->offset;
980
981 /* Cannot modify original bio, copy to sg_out and apply Elephant to it */
982 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
983 sg2 = crypt_get_sg_data(cc, dmreq->sg_in);
0d78954a 984 data2 = kmap_local_page(sg_page(sg2));
bbb16584 985 memcpy(data_offset, data2 + sg2->offset, cc->sector_size);
0d78954a 986 kunmap_local(data2);
bbb16584
MB
987 }
988
989 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
990 diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
991 diffuser_b_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
992 diffuser_a_decrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
993 diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
994 }
995
996 for (i = 0; i < (cc->sector_size / 32); i++)
997 crypto_xor(data_offset + i * 32, ks, 32);
998
999 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
1000 diffuser_disk_to_cpu((u32*)data_offset, cc->sector_size / sizeof(u32));
1001 diffuser_a_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
1002 diffuser_b_encrypt((u32*)data_offset, cc->sector_size / sizeof(u32));
1003 diffuser_cpu_to_disk((__le32*)data_offset, cc->sector_size / sizeof(u32));
1004 }
1005
0d78954a 1006 kunmap_local(data);
bbb16584 1007out:
453431a5
WL
1008 kfree_sensitive(ks);
1009 kfree_sensitive(es);
bbb16584
MB
1010 skcipher_request_free(req);
1011 return r;
1012}
1013
1014static int crypt_iv_elephant_gen(struct crypt_config *cc, u8 *iv,
1015 struct dm_crypt_request *dmreq)
1016{
1017 int r;
1018
1019 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
1020 r = crypt_iv_elephant(cc, dmreq);
1021 if (r)
1022 return r;
1023 }
1024
1025 return crypt_iv_eboiv_gen(cc, iv, dmreq);
1026}
1027
1028static int crypt_iv_elephant_post(struct crypt_config *cc, u8 *iv,
1029 struct dm_crypt_request *dmreq)
1030{
1031 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
1032 return crypt_iv_elephant(cc, dmreq);
1033
1034 return 0;
1035}
1036
1037static int crypt_iv_elephant_init(struct crypt_config *cc)
1038{
1039 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1040 int key_offset = cc->key_size - cc->key_extra_size;
1041
1042 return crypto_skcipher_setkey(elephant->tfm, &cc->key[key_offset], cc->key_extra_size);
1043}
1044
1045static int crypt_iv_elephant_wipe(struct crypt_config *cc)
1046{
1047 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1048 u8 key[ELEPHANT_MAX_KEY_SIZE];
1049
1050 memset(key, 0, cc->key_extra_size);
1051 return crypto_skcipher_setkey(elephant->tfm, key, cc->key_extra_size);
1052}
1053
1b1b58f5 1054static const struct crypt_iv_operations crypt_iv_plain_ops = {
1da177e4
LT
1055 .generator = crypt_iv_plain_gen
1056};
1057
1b1b58f5 1058static const struct crypt_iv_operations crypt_iv_plain64_ops = {
61afef61
MB
1059 .generator = crypt_iv_plain64_gen
1060};
1061
7e3fd855
MB
1062static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
1063 .generator = crypt_iv_plain64be_gen
1064};
1065
1b1b58f5 1066static const struct crypt_iv_operations crypt_iv_essiv_ops = {
1da177e4
LT
1067 .generator = crypt_iv_essiv_gen
1068};
1069
1b1b58f5 1070static const struct crypt_iv_operations crypt_iv_benbi_ops = {
48527fa7
RS
1071 .ctr = crypt_iv_benbi_ctr,
1072 .dtr = crypt_iv_benbi_dtr,
1073 .generator = crypt_iv_benbi_gen
1074};
1da177e4 1075
1b1b58f5 1076static const struct crypt_iv_operations crypt_iv_null_ops = {
46b47730
LN
1077 .generator = crypt_iv_null_gen
1078};
1079
1b1b58f5 1080static const struct crypt_iv_operations crypt_iv_lmk_ops = {
34745785
MB
1081 .ctr = crypt_iv_lmk_ctr,
1082 .dtr = crypt_iv_lmk_dtr,
1083 .init = crypt_iv_lmk_init,
1084 .wipe = crypt_iv_lmk_wipe,
1085 .generator = crypt_iv_lmk_gen,
1086 .post = crypt_iv_lmk_post
1087};
1088
1b1b58f5 1089static const struct crypt_iv_operations crypt_iv_tcw_ops = {
ed04d981
MB
1090 .ctr = crypt_iv_tcw_ctr,
1091 .dtr = crypt_iv_tcw_dtr,
1092 .init = crypt_iv_tcw_init,
1093 .wipe = crypt_iv_tcw_wipe,
1094 .generator = crypt_iv_tcw_gen,
1095 .post = crypt_iv_tcw_post
1096};
1097
e8dc79d1 1098static const struct crypt_iv_operations crypt_iv_random_ops = {
ef43aa38
MB
1099 .generator = crypt_iv_random_gen
1100};
1101
e8dc79d1 1102static const struct crypt_iv_operations crypt_iv_eboiv_ops = {
b9411d73 1103 .ctr = crypt_iv_eboiv_ctr,
b9411d73
MB
1104 .generator = crypt_iv_eboiv_gen
1105};
1106
e8dc79d1 1107static const struct crypt_iv_operations crypt_iv_elephant_ops = {
bbb16584
MB
1108 .ctr = crypt_iv_elephant_ctr,
1109 .dtr = crypt_iv_elephant_dtr,
1110 .init = crypt_iv_elephant_init,
1111 .wipe = crypt_iv_elephant_wipe,
1112 .generator = crypt_iv_elephant_gen,
1113 .post = crypt_iv_elephant_post
1114};
1115
ef43aa38
MB
1116/*
1117 * Integrity extensions
1118 */
1119static bool crypt_integrity_aead(struct crypt_config *cc)
1120{
1121 return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
1122}
1123
1124static bool crypt_integrity_hmac(struct crypt_config *cc)
1125{
33d2f09f 1126 return crypt_integrity_aead(cc) && cc->key_mac_size;
ef43aa38
MB
1127}
1128
1129/* Get sg containing data */
1130static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
1131 struct scatterlist *sg)
1132{
33d2f09f 1133 if (unlikely(crypt_integrity_aead(cc)))
ef43aa38
MB
1134 return &sg[2];
1135
1136 return sg;
1137}
1138
1139static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
1140{
1141 struct bio_integrity_payload *bip;
1142 unsigned int tag_len;
1143 int ret;
1144
1145 if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
1146 return 0;
1147
1148 bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
1149 if (IS_ERR(bip))
1150 return PTR_ERR(bip);
1151
ff0c129d 1152 tag_len = io->cc->on_disk_tag_size * (bio_sectors(bio) >> io->cc->sector_shift);
ef43aa38
MB
1153
1154 bip->bip_iter.bi_size = tag_len;
1155 bip->bip_iter.bi_sector = io->cc->start + io->sector;
1156
ef43aa38
MB
1157 ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
1158 tag_len, offset_in_page(io->integrity_metadata));
1159 if (unlikely(ret != tag_len))
1160 return -ENOMEM;
1161
1162 return 0;
1163}
1164
1165static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
1166{
1167#ifdef CONFIG_BLK_DEV_INTEGRITY
1168 struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
7a1cd723 1169 struct mapped_device *md = dm_table_get_md(ti->table);
ef43aa38
MB
1170
1171 /* From now we require underlying device with our integrity profile */
1172 if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
1173 ti->error = "Integrity profile not supported.";
1174 return -EINVAL;
1175 }
1176
583fe747
MP
1177 if (bi->tag_size != cc->on_disk_tag_size ||
1178 bi->tuple_size != cc->on_disk_tag_size) {
ef43aa38
MB
1179 ti->error = "Integrity profile tag size mismatch.";
1180 return -EINVAL;
1181 }
583fe747
MP
1182 if (1 << bi->interval_exp != cc->sector_size) {
1183 ti->error = "Integrity profile sector size mismatch.";
1184 return -EINVAL;
1185 }
ef43aa38 1186
33d2f09f 1187 if (crypt_integrity_aead(cc)) {
ef43aa38 1188 cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
7a1cd723 1189 DMDEBUG("%s: Integrity AEAD, tag size %u, IV size %u.", dm_device_name(md),
ef43aa38
MB
1190 cc->integrity_tag_size, cc->integrity_iv_size);
1191
1192 if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
1193 ti->error = "Integrity AEAD auth tag size is not supported.";
1194 return -EINVAL;
1195 }
1196 } else if (cc->integrity_iv_size)
7a1cd723 1197 DMDEBUG("%s: Additional per-sector space %u bytes for IV.", dm_device_name(md),
ef43aa38
MB
1198 cc->integrity_iv_size);
1199
1200 if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
1201 ti->error = "Not enough space for integrity tag in the profile.";
1202 return -EINVAL;
1203 }
1204
1205 return 0;
1206#else
1207 ti->error = "Integrity profile not supported.";
1208 return -EINVAL;
1209#endif
1210}
1211
d469f841
MB
1212static void crypt_convert_init(struct crypt_config *cc,
1213 struct convert_context *ctx,
1214 struct bio *bio_out, struct bio *bio_in,
fcd369da 1215 sector_t sector)
1da177e4
LT
1216{
1217 ctx->bio_in = bio_in;
1218 ctx->bio_out = bio_out;
003b5c57
KO
1219 if (bio_in)
1220 ctx->iter_in = bio_in->bi_iter;
1221 if (bio_out)
1222 ctx->iter_out = bio_out->bi_iter;
c66029f4 1223 ctx->cc_sector = sector + cc->iv_offset;
43d69034 1224 init_completion(&ctx->restart);
1da177e4
LT
1225}
1226
b2174eeb 1227static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
ef43aa38 1228 void *req)
b2174eeb
HY
1229{
1230 return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
1231}
1232
ef43aa38 1233static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
b2174eeb 1234{
ef43aa38 1235 return (void *)((char *)dmreq - cc->dmreq_start);
b2174eeb
HY
1236}
1237
2dc5327d
MB
1238static u8 *iv_of_dmreq(struct crypt_config *cc,
1239 struct dm_crypt_request *dmreq)
1240{
33d2f09f 1241 if (crypt_integrity_aead(cc))
ef43aa38
MB
1242 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1243 crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
1244 else
1245 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1246 crypto_skcipher_alignmask(any_tfm(cc)) + 1);
2dc5327d
MB
1247}
1248
ef43aa38
MB
1249static u8 *org_iv_of_dmreq(struct crypt_config *cc,
1250 struct dm_crypt_request *dmreq)
1251{
1252 return iv_of_dmreq(cc, dmreq) + cc->iv_size;
1253}
1254
c13b5487 1255static __le64 *org_sector_of_dmreq(struct crypt_config *cc,
ef43aa38
MB
1256 struct dm_crypt_request *dmreq)
1257{
1258 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
c13b5487 1259 return (__le64 *) ptr;
ef43aa38
MB
1260}
1261
1262static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
1263 struct dm_crypt_request *dmreq)
1264{
1265 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
1266 cc->iv_size + sizeof(uint64_t);
1267 return (unsigned int*)ptr;
1268}
1269
1270static void *tag_from_dmreq(struct crypt_config *cc,
1271 struct dm_crypt_request *dmreq)
1272{
1273 struct convert_context *ctx = dmreq->ctx;
1274 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1275
1276 return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
1277 cc->on_disk_tag_size];
1278}
1279
1280static void *iv_tag_from_dmreq(struct crypt_config *cc,
1281 struct dm_crypt_request *dmreq)
1282{
1283 return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
1284}
1285
1286static int crypt_convert_block_aead(struct crypt_config *cc,
1287 struct convert_context *ctx,
1288 struct aead_request *req,
1289 unsigned int tag_offset)
01482b76 1290{
003b5c57
KO
1291 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1292 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
3a7f6c99 1293 struct dm_crypt_request *dmreq;
ef43aa38 1294 u8 *iv, *org_iv, *tag_iv, *tag;
c13b5487 1295 __le64 *sector;
ef43aa38
MB
1296 int r = 0;
1297
1298 BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
3a7f6c99 1299
8f0009a2 1300 /* Reject unexpected unaligned bio. */
0440d5c0 1301 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
8f0009a2 1302 return -EIO;
3a7f6c99 1303
b2174eeb 1304 dmreq = dmreq_of_req(cc, req);
ef43aa38 1305 dmreq->iv_sector = ctx->cc_sector;
8f0009a2 1306 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
ff3af92b 1307 dmreq->iv_sector >>= cc->sector_shift;
ef43aa38
MB
1308 dmreq->ctx = ctx;
1309
1310 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1311
1312 sector = org_sector_of_dmreq(cc, dmreq);
1313 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1314
2dc5327d 1315 iv = iv_of_dmreq(cc, dmreq);
ef43aa38
MB
1316 org_iv = org_iv_of_dmreq(cc, dmreq);
1317 tag = tag_from_dmreq(cc, dmreq);
1318 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1319
1320 /* AEAD request:
1321 * |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1322 * | (authenticated) | (auth+encryption) | |
1323 * | sector_LE | IV | sector in/out | tag in/out |
1324 */
1325 sg_init_table(dmreq->sg_in, 4);
1326 sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
1327 sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
8f0009a2 1328 sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
ef43aa38
MB
1329 sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
1330
1331 sg_init_table(dmreq->sg_out, 4);
1332 sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
1333 sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
8f0009a2 1334 sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
ef43aa38
MB
1335 sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
1336
1337 if (cc->iv_gen_ops) {
1338 /* For READs use IV stored in integrity metadata */
1339 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1340 memcpy(org_iv, tag_iv, cc->iv_size);
1341 } else {
1342 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1343 if (r < 0)
1344 return r;
1345 /* Store generated IV in integrity metadata */
1346 if (cc->integrity_iv_size)
1347 memcpy(tag_iv, org_iv, cc->iv_size);
1348 }
1349 /* Working copy of IV, to be modified in crypto API */
1350 memcpy(iv, org_iv, cc->iv_size);
1351 }
1352
1353 aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
1354 if (bio_data_dir(ctx->bio_in) == WRITE) {
1355 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
8f0009a2 1356 cc->sector_size, iv);
ef43aa38
MB
1357 r = crypto_aead_encrypt(req);
1358 if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
1359 memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
1360 cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
1361 } else {
1362 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
8f0009a2 1363 cc->sector_size + cc->integrity_tag_size, iv);
ef43aa38
MB
1364 r = crypto_aead_decrypt(req);
1365 }
1366
f710126c 1367 if (r == -EBADMSG) {
58d0f180
MW
1368 sector_t s = le64_to_cpu(*sector);
1369
66671719
CH
1370 DMERR_LIMIT("%pg: INTEGRITY AEAD ERROR, sector %llu",
1371 ctx->bio_in->bi_bdev, s);
58d0f180
MW
1372 dm_audit_log_bio(DM_MSG_PREFIX, "integrity-aead",
1373 ctx->bio_in, s, 0);
f710126c 1374 }
ef43aa38
MB
1375
1376 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1377 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1378
8f0009a2
MB
1379 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1380 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
01482b76 1381
ef43aa38
MB
1382 return r;
1383}
1384
1385static int crypt_convert_block_skcipher(struct crypt_config *cc,
1386 struct convert_context *ctx,
1387 struct skcipher_request *req,
1388 unsigned int tag_offset)
1389{
1390 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1391 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1392 struct scatterlist *sg_in, *sg_out;
1393 struct dm_crypt_request *dmreq;
ef43aa38 1394 u8 *iv, *org_iv, *tag_iv;
c13b5487 1395 __le64 *sector;
ef43aa38 1396 int r = 0;
01482b76 1397
8f0009a2 1398 /* Reject unexpected unaligned bio. */
0440d5c0 1399 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
8f0009a2
MB
1400 return -EIO;
1401
ef43aa38 1402 dmreq = dmreq_of_req(cc, req);
c66029f4 1403 dmreq->iv_sector = ctx->cc_sector;
8f0009a2 1404 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
ff3af92b 1405 dmreq->iv_sector >>= cc->sector_shift;
b2174eeb 1406 dmreq->ctx = ctx;
01482b76 1407
ef43aa38
MB
1408 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1409
1410 iv = iv_of_dmreq(cc, dmreq);
1411 org_iv = org_iv_of_dmreq(cc, dmreq);
1412 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1413
1414 sector = org_sector_of_dmreq(cc, dmreq);
1415 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1416
1417 /* For skcipher we use only the first sg item */
1418 sg_in = &dmreq->sg_in[0];
1419 sg_out = &dmreq->sg_out[0];
01482b76 1420
ef43aa38 1421 sg_init_table(sg_in, 1);
8f0009a2 1422 sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
ef43aa38
MB
1423
1424 sg_init_table(sg_out, 1);
8f0009a2 1425 sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
01482b76 1426
3a7f6c99 1427 if (cc->iv_gen_ops) {
ef43aa38
MB
1428 /* For READs use IV stored in integrity metadata */
1429 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1430 memcpy(org_iv, tag_iv, cc->integrity_iv_size);
1431 } else {
1432 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1433 if (r < 0)
1434 return r;
bbb16584
MB
1435 /* Data can be already preprocessed in generator */
1436 if (test_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags))
1437 sg_in = sg_out;
ef43aa38
MB
1438 /* Store generated IV in integrity metadata */
1439 if (cc->integrity_iv_size)
1440 memcpy(tag_iv, org_iv, cc->integrity_iv_size);
1441 }
1442 /* Working copy of IV, to be modified in crypto API */
1443 memcpy(iv, org_iv, cc->iv_size);
3a7f6c99
MB
1444 }
1445
8f0009a2 1446 skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
3a7f6c99
MB
1447
1448 if (bio_data_dir(ctx->bio_in) == WRITE)
bbdb23b5 1449 r = crypto_skcipher_encrypt(req);
3a7f6c99 1450 else
bbdb23b5 1451 r = crypto_skcipher_decrypt(req);
3a7f6c99 1452
2dc5327d 1453 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
ef43aa38
MB
1454 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1455
8f0009a2
MB
1456 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1457 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
2dc5327d 1458
3a7f6c99 1459 return r;
01482b76
MB
1460}
1461
95497a96
MB
1462static void kcryptd_async_done(struct crypto_async_request *async_req,
1463 int error);
c0297721 1464
d68b2958 1465static int crypt_alloc_req_skcipher(struct crypt_config *cc,
ef43aa38 1466 struct convert_context *ctx)
ddd42edf 1467{
86a3238c 1468 unsigned int key_index = ctx->cc_sector & (cc->tfms_count - 1);
c0297721 1469
d68b2958
IK
1470 if (!ctx->r.req) {
1471 ctx->r.req = mempool_alloc(&cc->req_pool, in_interrupt() ? GFP_ATOMIC : GFP_NOIO);
1472 if (!ctx->r.req)
1473 return -ENOMEM;
1474 }
c0297721 1475
ef43aa38 1476 skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
54cea3f6
MB
1477
1478 /*
1479 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1480 * requests if driver request queue is full.
1481 */
ef43aa38 1482 skcipher_request_set_callback(ctx->r.req,
432061b3 1483 CRYPTO_TFM_REQ_MAY_BACKLOG,
ef43aa38 1484 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
d68b2958
IK
1485
1486 return 0;
ddd42edf
MB
1487}
1488
d68b2958 1489static int crypt_alloc_req_aead(struct crypt_config *cc,
ef43aa38
MB
1490 struct convert_context *ctx)
1491{
004b8ae9
IK
1492 if (!ctx->r.req_aead) {
1493 ctx->r.req_aead = mempool_alloc(&cc->req_pool, in_interrupt() ? GFP_ATOMIC : GFP_NOIO);
1494 if (!ctx->r.req_aead)
d68b2958
IK
1495 return -ENOMEM;
1496 }
c0297721 1497
ef43aa38 1498 aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
54cea3f6
MB
1499
1500 /*
1501 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1502 * requests if driver request queue is full.
1503 */
ef43aa38 1504 aead_request_set_callback(ctx->r.req_aead,
432061b3 1505 CRYPTO_TFM_REQ_MAY_BACKLOG,
ef43aa38 1506 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
d68b2958
IK
1507
1508 return 0;
ef43aa38
MB
1509}
1510
d68b2958 1511static int crypt_alloc_req(struct crypt_config *cc,
ef43aa38
MB
1512 struct convert_context *ctx)
1513{
33d2f09f 1514 if (crypt_integrity_aead(cc))
d68b2958 1515 return crypt_alloc_req_aead(cc, ctx);
ef43aa38 1516 else
d68b2958 1517 return crypt_alloc_req_skcipher(cc, ctx);
ddd42edf
MB
1518}
1519
ef43aa38
MB
1520static void crypt_free_req_skcipher(struct crypt_config *cc,
1521 struct skcipher_request *req, struct bio *base_bio)
298a9fa0
MP
1522{
1523 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1524
bbdb23b5 1525 if ((struct skcipher_request *)(io + 1) != req)
6f1c819c 1526 mempool_free(req, &cc->req_pool);
298a9fa0
MP
1527}
1528
ef43aa38
MB
1529static void crypt_free_req_aead(struct crypt_config *cc,
1530 struct aead_request *req, struct bio *base_bio)
1531{
1532 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1533
1534 if ((struct aead_request *)(io + 1) != req)
6f1c819c 1535 mempool_free(req, &cc->req_pool);
ef43aa38
MB
1536}
1537
1538static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
1539{
33d2f09f 1540 if (crypt_integrity_aead(cc))
ef43aa38
MB
1541 crypt_free_req_aead(cc, req, base_bio);
1542 else
1543 crypt_free_req_skcipher(cc, req, base_bio);
1544}
1545
1da177e4
LT
1546/*
1547 * Encrypt / decrypt data from one bio to another one (can be the same one)
1548 */
4e4cbee9 1549static blk_status_t crypt_convert(struct crypt_config *cc,
8abec36d 1550 struct convert_context *ctx, bool atomic, bool reset_pending)
1da177e4 1551{
ef43aa38 1552 unsigned int tag_offset = 0;
ff3af92b 1553 unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
3f1e9070 1554 int r;
1da177e4 1555
8abec36d
IK
1556 /*
1557 * if reset_pending is set we are dealing with the bio for the first time,
1558 * else we're continuing to work on the previous bio, so don't mess with
1559 * the cc_pending counter
1560 */
1561 if (reset_pending)
1562 atomic_set(&ctx->cc_pending, 1);
c8081618 1563
003b5c57 1564 while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
1da177e4 1565
d68b2958
IK
1566 r = crypt_alloc_req(cc, ctx);
1567 if (r) {
1568 complete(&ctx->restart);
1569 return BLK_STS_DEV_RESOURCE;
1570 }
1571
40b6229b 1572 atomic_inc(&ctx->cc_pending);
3f1e9070 1573
33d2f09f 1574 if (crypt_integrity_aead(cc))
ef43aa38
MB
1575 r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
1576 else
1577 r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
3a7f6c99
MB
1578
1579 switch (r) {
54cea3f6
MB
1580 /*
1581 * The request was queued by a crypto driver
1582 * but the driver request queue is full, let's wait.
1583 */
3a7f6c99 1584 case -EBUSY:
8abec36d
IK
1585 if (in_interrupt()) {
1586 if (try_wait_for_completion(&ctx->restart)) {
1587 /*
1588 * we don't have to block to wait for completion,
1589 * so proceed
1590 */
1591 } else {
1592 /*
1593 * we can't wait for completion without blocking
1594 * exit and continue processing in a workqueue
1595 */
1596 ctx->r.req = NULL;
1597 ctx->cc_sector += sector_step;
1598 tag_offset++;
1599 return BLK_STS_DEV_RESOURCE;
1600 }
1601 } else {
1602 wait_for_completion(&ctx->restart);
1603 }
16735d02 1604 reinit_completion(&ctx->restart);
df561f66 1605 fallthrough;
54cea3f6
MB
1606 /*
1607 * The request is queued and processed asynchronously,
1608 * completion function kcryptd_async_done() will be called.
1609 */
c0403ec0 1610 case -EINPROGRESS:
ef43aa38 1611 ctx->r.req = NULL;
8f0009a2 1612 ctx->cc_sector += sector_step;
583fe747 1613 tag_offset++;
3f1e9070 1614 continue;
54cea3f6
MB
1615 /*
1616 * The request was already processed (synchronously).
1617 */
3a7f6c99 1618 case 0:
40b6229b 1619 atomic_dec(&ctx->cc_pending);
8f0009a2 1620 ctx->cc_sector += sector_step;
583fe747 1621 tag_offset++;
39d42fa9
IK
1622 if (!atomic)
1623 cond_resched();
3a7f6c99 1624 continue;
ef43aa38
MB
1625 /*
1626 * There was a data integrity error.
1627 */
1628 case -EBADMSG:
1629 atomic_dec(&ctx->cc_pending);
4e4cbee9 1630 return BLK_STS_PROTECTION;
ef43aa38
MB
1631 /*
1632 * There was an error while processing the request.
1633 */
3f1e9070 1634 default:
40b6229b 1635 atomic_dec(&ctx->cc_pending);
4e4cbee9 1636 return BLK_STS_IOERR;
3f1e9070 1637 }
1da177e4
LT
1638 }
1639
3f1e9070 1640 return 0;
1da177e4
LT
1641}
1642
cf2f1abf
MP
1643static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
1644
1da177e4
LT
1645/*
1646 * Generate a new unfragmented bio with the given size
586b286b
MS
1647 * This should never violate the device limitations (but only because
1648 * max_segment_size is being constrained to PAGE_SIZE).
7145c241
MP
1649 *
1650 * This function may be called concurrently. If we allocate from the mempool
1651 * concurrently, there is a possibility of deadlock. For example, if we have
1652 * mempool of 256 pages, two processes, each wanting 256, pages allocate from
1653 * the mempool concurrently, it may deadlock in a situation where both processes
1654 * have allocated 128 pages and the mempool is exhausted.
1655 *
1656 * In order to avoid this scenario we allocate the pages under a mutex.
1657 *
1658 * In order to not degrade performance with excessive locking, we try
1659 * non-blocking allocations without a mutex first but on failure we fallback
1660 * to blocking allocations with a mutex.
1da177e4 1661 */
86a3238c 1662static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned int size)
1da177e4 1663{
49a8a920 1664 struct crypt_config *cc = io->cc;
8b004457 1665 struct bio *clone;
1da177e4 1666 unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
7145c241 1667 gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
86a3238c 1668 unsigned int i, len, remaining_size;
91e10625 1669 struct page *page;
1da177e4 1670
7145c241 1671retry:
d0164adc 1672 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
7145c241
MP
1673 mutex_lock(&cc->bio_alloc_lock);
1674
609be106
CH
1675 clone = bio_alloc_bioset(cc->dev->bdev, nr_iovecs, io->base_bio->bi_opf,
1676 GFP_NOIO, &cc->bs);
3f868c09
CH
1677 clone->bi_private = io;
1678 clone->bi_end_io = crypt_endio;
6a24c718 1679
7145c241
MP
1680 remaining_size = size;
1681
f97380bc 1682 for (i = 0; i < nr_iovecs; i++) {
6f1c819c 1683 page = mempool_alloc(&cc->page_pool, gfp_mask);
7145c241
MP
1684 if (!page) {
1685 crypt_free_buffer_pages(cc, clone);
1686 bio_put(clone);
d0164adc 1687 gfp_mask |= __GFP_DIRECT_RECLAIM;
7145c241
MP
1688 goto retry;
1689 }
1da177e4 1690
7145c241 1691 len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
91e10625 1692
0dae7fe5 1693 bio_add_page(clone, page, len, 0);
1da177e4 1694
7145c241 1695 remaining_size -= len;
1da177e4
LT
1696 }
1697
ef43aa38
MB
1698 /* Allocate space for integrity tags */
1699 if (dm_crypt_integrity_io_alloc(io, clone)) {
1700 crypt_free_buffer_pages(cc, clone);
1701 bio_put(clone);
1702 clone = NULL;
1703 }
53db984e 1704
d0164adc 1705 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
7145c241
MP
1706 mutex_unlock(&cc->bio_alloc_lock);
1707
8b004457 1708 return clone;
1da177e4
LT
1709}
1710
644bd2f0 1711static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1da177e4 1712{
1da177e4 1713 struct bio_vec *bv;
6dc4f100 1714 struct bvec_iter_all iter_all;
1da177e4 1715
2b070cfe 1716 bio_for_each_segment_all(bv, clone, iter_all) {
1da177e4 1717 BUG_ON(!bv->bv_page);
6f1c819c 1718 mempool_free(bv->bv_page, &cc->page_pool);
1da177e4
LT
1719 }
1720}
1721
298a9fa0
MP
1722static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1723 struct bio *bio, sector_t sector)
dc440d1e 1724{
49a8a920 1725 io->cc = cc;
dc440d1e
MB
1726 io->base_bio = bio;
1727 io->sector = sector;
1728 io->error = 0;
ef43aa38
MB
1729 io->ctx.r.req = NULL;
1730 io->integrity_metadata = NULL;
1731 io->integrity_metadata_from_pool = false;
40b6229b 1732 atomic_set(&io->io_pending, 0);
dc440d1e
MB
1733}
1734
3e1a8bdd
MB
1735static void crypt_inc_pending(struct dm_crypt_io *io)
1736{
40b6229b 1737 atomic_inc(&io->io_pending);
3e1a8bdd
MB
1738}
1739
8e14f610
IK
1740static void kcryptd_io_bio_endio(struct work_struct *work)
1741{
1742 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1743 bio_endio(io->base_bio);
1744}
1745
1da177e4
LT
1746/*
1747 * One of the bios was finished. Check for completion of
1748 * the whole request and correctly clean up the buffer.
1749 */
5742fd77 1750static void crypt_dec_pending(struct dm_crypt_io *io)
1da177e4 1751{
49a8a920 1752 struct crypt_config *cc = io->cc;
b35f8caa 1753 struct bio *base_bio = io->base_bio;
4e4cbee9 1754 blk_status_t error = io->error;
1da177e4 1755
40b6229b 1756 if (!atomic_dec_and_test(&io->io_pending))
1da177e4
LT
1757 return;
1758
ef43aa38
MB
1759 if (io->ctx.r.req)
1760 crypt_free_req(cc, io->ctx.r.req, base_bio);
1761
1762 if (unlikely(io->integrity_metadata_from_pool))
6f1c819c 1763 mempool_free(io->integrity_metadata, &io->cc->tag_pool);
ef43aa38
MB
1764 else
1765 kfree(io->integrity_metadata);
b35f8caa 1766
4e4cbee9 1767 base_bio->bi_status = error;
8e14f610
IK
1768
1769 /*
1770 * If we are running this function from our tasklet,
1771 * we can't call bio_endio() here, because it will call
1772 * clone_endio() from dm.c, which in turn will
1773 * free the current struct dm_crypt_io structure with
1774 * our tasklet. In this case we need to delay bio_endio()
1775 * execution to after the tasklet is done and dequeued.
1776 */
1777 if (tasklet_trylock(&io->tasklet)) {
1778 tasklet_unlock(&io->tasklet);
1779 bio_endio(base_bio);
1780 return;
1781 }
1782
1783 INIT_WORK(&io->work, kcryptd_io_bio_endio);
1784 queue_work(cc->io_queue, &io->work);
1da177e4
LT
1785}
1786
1787/*
cabf08e4 1788 * kcryptd/kcryptd_io:
1da177e4
LT
1789 *
1790 * Needed because it would be very unwise to do decryption in an
23541d2d 1791 * interrupt context.
cabf08e4
MB
1792 *
1793 * kcryptd performs the actual encryption or decryption.
1794 *
1795 * kcryptd_io performs the IO submission.
1796 *
1797 * They must be separated as otherwise the final stages could be
1798 * starved by new requests which can block in the first stages due
1799 * to memory allocation.
c0297721
AK
1800 *
1801 * The work is done per CPU global for all dm-crypt instances.
1802 * They should not depend on each other and do not block.
1da177e4 1803 */
4246a0b6 1804static void crypt_endio(struct bio *clone)
8b004457 1805{
028867ac 1806 struct dm_crypt_io *io = clone->bi_private;
49a8a920 1807 struct crypt_config *cc = io->cc;
86a3238c 1808 unsigned int rw = bio_data_dir(clone);
4e4cbee9 1809 blk_status_t error;
8b004457
MB
1810
1811 /*
6712ecf8 1812 * free the processed pages
8b004457 1813 */
ee7a491e 1814 if (rw == WRITE)
644bd2f0 1815 crypt_free_buffer_pages(cc, clone);
8b004457 1816
4e4cbee9 1817 error = clone->bi_status;
8b004457 1818 bio_put(clone);
8b004457 1819
9b81c842 1820 if (rw == READ && !error) {
ee7a491e
MB
1821 kcryptd_queue_crypt(io);
1822 return;
1823 }
5742fd77 1824
9b81c842
SL
1825 if (unlikely(error))
1826 io->error = error;
5742fd77
MB
1827
1828 crypt_dec_pending(io);
8b004457
MB
1829}
1830
e5524e12
MS
1831#define CRYPT_MAP_READ_GFP GFP_NOWAIT
1832
20c82538 1833static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
8b004457 1834{
49a8a920 1835 struct crypt_config *cc = io->cc;
8b004457 1836 struct bio *clone;
93e605c2 1837
8b004457 1838 /*
abfc426d
CH
1839 * We need the original biovec array in order to decrypt the whole bio
1840 * data *afterwards* -- thanks to immutable biovecs we don't need to
1841 * worry about the block layer modifying the biovec array; so leverage
1842 * bio_alloc_clone().
8b004457 1843 */
abfc426d 1844 clone = bio_alloc_clone(cc->dev->bdev, io->base_bio, gfp, &cc->bs);
7eaceacc 1845 if (!clone)
20c82538 1846 return 1;
3f868c09
CH
1847 clone->bi_private = io;
1848 clone->bi_end_io = crypt_endio;
8b004457 1849
20c82538
MB
1850 crypt_inc_pending(io);
1851
4f024f37 1852 clone->bi_iter.bi_sector = cc->start + io->sector;
8b004457 1853
ef43aa38
MB
1854 if (dm_crypt_integrity_io_alloc(io, clone)) {
1855 crypt_dec_pending(io);
1856 bio_put(clone);
1857 return 1;
1858 }
1859
b7f8dff0 1860 dm_submit_bio_remap(io->base_bio, clone);
20c82538 1861 return 0;
8b004457
MB
1862}
1863
dc267621
MP
1864static void kcryptd_io_read_work(struct work_struct *work)
1865{
1866 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1867
1868 crypt_inc_pending(io);
1869 if (kcryptd_io_read(io, GFP_NOIO))
4e4cbee9 1870 io->error = BLK_STS_RESOURCE;
dc267621
MP
1871 crypt_dec_pending(io);
1872}
1873
1874static void kcryptd_queue_read(struct dm_crypt_io *io)
1875{
1876 struct crypt_config *cc = io->cc;
1877
1878 INIT_WORK(&io->work, kcryptd_io_read_work);
1879 queue_work(cc->io_queue, &io->work);
1880}
1881
4e4eef64
MB
1882static void kcryptd_io_write(struct dm_crypt_io *io)
1883{
95497a96 1884 struct bio *clone = io->ctx.bio_out;
dc267621 1885
b7f8dff0 1886 dm_submit_bio_remap(io->base_bio, clone);
4e4eef64
MB
1887}
1888
b3c5fd30
MP
1889#define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1890
dc267621 1891static int dmcrypt_write(void *data)
395b167c 1892{
dc267621 1893 struct crypt_config *cc = data;
b3c5fd30
MP
1894 struct dm_crypt_io *io;
1895
dc267621 1896 while (1) {
b3c5fd30 1897 struct rb_root write_tree;
dc267621 1898 struct blk_plug plug;
395b167c 1899
c7329eff 1900 spin_lock_irq(&cc->write_thread_lock);
dc267621 1901continue_locked:
395b167c 1902
b3c5fd30 1903 if (!RB_EMPTY_ROOT(&cc->write_tree))
dc267621
MP
1904 goto pop_from_list;
1905
f659b100 1906 set_current_state(TASK_INTERRUPTIBLE);
dc267621 1907
c7329eff 1908 spin_unlock_irq(&cc->write_thread_lock);
dc267621 1909
f659b100 1910 if (unlikely(kthread_should_stop())) {
642fa448 1911 set_current_state(TASK_RUNNING);
f659b100
RV
1912 break;
1913 }
1914
dc267621
MP
1915 schedule();
1916
642fa448 1917 set_current_state(TASK_RUNNING);
c7329eff 1918 spin_lock_irq(&cc->write_thread_lock);
dc267621
MP
1919 goto continue_locked;
1920
1921pop_from_list:
b3c5fd30
MP
1922 write_tree = cc->write_tree;
1923 cc->write_tree = RB_ROOT;
c7329eff 1924 spin_unlock_irq(&cc->write_thread_lock);
dc267621 1925
b3c5fd30
MP
1926 BUG_ON(rb_parent(write_tree.rb_node));
1927
1928 /*
1929 * Note: we cannot walk the tree here with rb_next because
1930 * the structures may be freed when kcryptd_io_write is called.
1931 */
dc267621
MP
1932 blk_start_plug(&plug);
1933 do {
b3c5fd30
MP
1934 io = crypt_io_from_node(rb_first(&write_tree));
1935 rb_erase(&io->rb_node, &write_tree);
dc267621 1936 kcryptd_io_write(io);
b3c5fd30 1937 } while (!RB_EMPTY_ROOT(&write_tree));
dc267621
MP
1938 blk_finish_plug(&plug);
1939 }
1940 return 0;
395b167c
AK
1941}
1942
72c6e7af 1943static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
4e4eef64 1944{
dec1cedf 1945 struct bio *clone = io->ctx.bio_out;
49a8a920 1946 struct crypt_config *cc = io->cc;
dc267621 1947 unsigned long flags;
b3c5fd30
MP
1948 sector_t sector;
1949 struct rb_node **rbp, *parent;
dec1cedf 1950
4e4cbee9 1951 if (unlikely(io->error)) {
dec1cedf
MB
1952 crypt_free_buffer_pages(cc, clone);
1953 bio_put(clone);
6c031f41 1954 crypt_dec_pending(io);
dec1cedf
MB
1955 return;
1956 }
1957
1958 /* crypt_convert should have filled the clone bio */
003b5c57 1959 BUG_ON(io->ctx.iter_out.bi_size);
dec1cedf 1960
4f024f37 1961 clone->bi_iter.bi_sector = cc->start + io->sector;
899c95d3 1962
39d42fa9
IK
1963 if ((likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) ||
1964 test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags)) {
b7f8dff0 1965 dm_submit_bio_remap(io->base_bio, clone);
0f5d8e6e
MP
1966 return;
1967 }
1968
c7329eff
MP
1969 spin_lock_irqsave(&cc->write_thread_lock, flags);
1970 if (RB_EMPTY_ROOT(&cc->write_tree))
1971 wake_up_process(cc->write_thread);
b3c5fd30
MP
1972 rbp = &cc->write_tree.rb_node;
1973 parent = NULL;
1974 sector = io->sector;
1975 while (*rbp) {
1976 parent = *rbp;
1977 if (sector < crypt_io_from_node(parent)->sector)
1978 rbp = &(*rbp)->rb_left;
1979 else
1980 rbp = &(*rbp)->rb_right;
1981 }
1982 rb_link_node(&io->rb_node, parent, rbp);
1983 rb_insert_color(&io->rb_node, &cc->write_tree);
c7329eff 1984 spin_unlock_irqrestore(&cc->write_thread_lock, flags);
4e4eef64
MB
1985}
1986
8e225f04
DLM
1987static bool kcryptd_crypt_write_inline(struct crypt_config *cc,
1988 struct convert_context *ctx)
1989
1990{
1991 if (!test_bit(DM_CRYPT_WRITE_INLINE, &cc->flags))
1992 return false;
1993
1994 /*
1995 * Note: zone append writes (REQ_OP_ZONE_APPEND) do not have ordering
1996 * constraints so they do not need to be issued inline by
1997 * kcryptd_crypt_write_convert().
1998 */
1999 switch (bio_op(ctx->bio_in)) {
2000 case REQ_OP_WRITE:
8e225f04
DLM
2001 case REQ_OP_WRITE_ZEROES:
2002 return true;
2003 default:
2004 return false;
2005 }
2006}
2007
8abec36d
IK
2008static void kcryptd_crypt_write_continue(struct work_struct *work)
2009{
2010 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2011 struct crypt_config *cc = io->cc;
2012 struct convert_context *ctx = &io->ctx;
2013 int crypt_finished;
2014 sector_t sector = io->sector;
2015 blk_status_t r;
2016
2017 wait_for_completion(&ctx->restart);
2018 reinit_completion(&ctx->restart);
2019
2020 r = crypt_convert(cc, &io->ctx, true, false);
2021 if (r)
2022 io->error = r;
2023 crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
2024 if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
2025 /* Wait for completion signaled by kcryptd_async_done() */
2026 wait_for_completion(&ctx->restart);
2027 crypt_finished = 1;
2028 }
2029
2030 /* Encryption was already finished, submit io now */
2031 if (crypt_finished) {
2032 kcryptd_crypt_write_io_submit(io, 0);
2033 io->sector = sector;
2034 }
2035
2036 crypt_dec_pending(io);
2037}
2038
fc5a5e9a 2039static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
8b004457 2040{
49a8a920 2041 struct crypt_config *cc = io->cc;
8e225f04 2042 struct convert_context *ctx = &io->ctx;
8b004457 2043 struct bio *clone;
c8081618 2044 int crypt_finished;
b635b00e 2045 sector_t sector = io->sector;
4e4cbee9 2046 blk_status_t r;
8b004457 2047
fc5a5e9a
MB
2048 /*
2049 * Prevent io from disappearing until this function completes.
2050 */
2051 crypt_inc_pending(io);
8e225f04 2052 crypt_convert_init(cc, ctx, NULL, io->base_bio, sector);
fc5a5e9a 2053
cf2f1abf
MP
2054 clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
2055 if (unlikely(!clone)) {
4e4cbee9 2056 io->error = BLK_STS_IOERR;
cf2f1abf
MP
2057 goto dec;
2058 }
c8081618 2059
cf2f1abf
MP
2060 io->ctx.bio_out = clone;
2061 io->ctx.iter_out = clone->bi_iter;
b635b00e 2062
cf2f1abf 2063 sector += bio_sectors(clone);
93e605c2 2064
cf2f1abf 2065 crypt_inc_pending(io);
8e225f04 2066 r = crypt_convert(cc, ctx,
8abec36d
IK
2067 test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags), true);
2068 /*
2069 * Crypto API backlogged the request, because its queue was full
2070 * and we're in softirq context, so continue from a workqueue
2071 * (TODO: is it actually possible to be in softirq in the write path?)
2072 */
2073 if (r == BLK_STS_DEV_RESOURCE) {
2074 INIT_WORK(&io->work, kcryptd_crypt_write_continue);
2075 queue_work(cc->crypt_queue, &io->work);
2076 return;
2077 }
4e4cbee9 2078 if (r)
ef43aa38 2079 io->error = r;
8e225f04
DLM
2080 crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
2081 if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
2082 /* Wait for completion signaled by kcryptd_async_done() */
2083 wait_for_completion(&ctx->restart);
2084 crypt_finished = 1;
2085 }
933f01d4 2086
cf2f1abf
MP
2087 /* Encryption was already finished, submit io now */
2088 if (crypt_finished) {
2089 kcryptd_crypt_write_io_submit(io, 0);
2090 io->sector = sector;
93e605c2 2091 }
899c95d3 2092
cf2f1abf 2093dec:
899c95d3 2094 crypt_dec_pending(io);
84131db6
MB
2095}
2096
72c6e7af 2097static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
5742fd77 2098{
5742fd77
MB
2099 crypt_dec_pending(io);
2100}
2101
8abec36d
IK
2102static void kcryptd_crypt_read_continue(struct work_struct *work)
2103{
2104 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2105 struct crypt_config *cc = io->cc;
2106 blk_status_t r;
2107
2108 wait_for_completion(&io->ctx.restart);
2109 reinit_completion(&io->ctx.restart);
2110
2111 r = crypt_convert(cc, &io->ctx, true, false);
2112 if (r)
2113 io->error = r;
2114
2115 if (atomic_dec_and_test(&io->ctx.cc_pending))
2116 kcryptd_crypt_read_done(io);
2117
2118 crypt_dec_pending(io);
2119}
2120
4e4eef64 2121static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
8b004457 2122{
49a8a920 2123 struct crypt_config *cc = io->cc;
4e4cbee9 2124 blk_status_t r;
1da177e4 2125
3e1a8bdd 2126 crypt_inc_pending(io);
3a7f6c99 2127
53017030 2128 crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
0c395b0f 2129 io->sector);
1da177e4 2130
39d42fa9 2131 r = crypt_convert(cc, &io->ctx,
8abec36d
IK
2132 test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags), true);
2133 /*
2134 * Crypto API backlogged the request, because its queue was full
2135 * and we're in softirq context, so continue from a workqueue
2136 */
2137 if (r == BLK_STS_DEV_RESOURCE) {
2138 INIT_WORK(&io->work, kcryptd_crypt_read_continue);
2139 queue_work(cc->crypt_queue, &io->work);
2140 return;
2141 }
4e4cbee9 2142 if (r)
ef43aa38 2143 io->error = r;
5742fd77 2144
40b6229b 2145 if (atomic_dec_and_test(&io->ctx.cc_pending))
72c6e7af 2146 kcryptd_crypt_read_done(io);
3a7f6c99
MB
2147
2148 crypt_dec_pending(io);
1da177e4
LT
2149}
2150
95497a96
MB
2151static void kcryptd_async_done(struct crypto_async_request *async_req,
2152 int error)
2153{
b2174eeb
HY
2154 struct dm_crypt_request *dmreq = async_req->data;
2155 struct convert_context *ctx = dmreq->ctx;
95497a96 2156 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
49a8a920 2157 struct crypt_config *cc = io->cc;
95497a96 2158
54cea3f6
MB
2159 /*
2160 * A request from crypto driver backlog is going to be processed now,
2161 * finish the completion and continue in crypt_convert().
2162 * (Callback will be called for the second time for this request.)
2163 */
c0403ec0
RV
2164 if (error == -EINPROGRESS) {
2165 complete(&ctx->restart);
95497a96 2166 return;
c0403ec0 2167 }
95497a96 2168
2dc5327d 2169 if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
ef43aa38 2170 error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
2dc5327d 2171
ef43aa38 2172 if (error == -EBADMSG) {
58d0f180
MW
2173 sector_t s = le64_to_cpu(*org_sector_of_dmreq(cc, dmreq));
2174
66671719
CH
2175 DMERR_LIMIT("%pg: INTEGRITY AEAD ERROR, sector %llu",
2176 ctx->bio_in->bi_bdev, s);
58d0f180
MW
2177 dm_audit_log_bio(DM_MSG_PREFIX, "integrity-aead",
2178 ctx->bio_in, s, 0);
4e4cbee9 2179 io->error = BLK_STS_PROTECTION;
ef43aa38 2180 } else if (error < 0)
4e4cbee9 2181 io->error = BLK_STS_IOERR;
72c6e7af 2182
298a9fa0 2183 crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
95497a96 2184
40b6229b 2185 if (!atomic_dec_and_test(&ctx->cc_pending))
c0403ec0 2186 return;
95497a96 2187
8e225f04
DLM
2188 /*
2189 * The request is fully completed: for inline writes, let
2190 * kcryptd_crypt_write_convert() do the IO submission.
2191 */
2192 if (bio_data_dir(io->base_bio) == READ) {
72c6e7af 2193 kcryptd_crypt_read_done(io);
8e225f04
DLM
2194 return;
2195 }
2196
2197 if (kcryptd_crypt_write_inline(cc, ctx)) {
2198 complete(&ctx->restart);
2199 return;
2200 }
2201
2202 kcryptd_crypt_write_io_submit(io, 1);
95497a96
MB
2203}
2204
395b167c 2205static void kcryptd_crypt(struct work_struct *work)
1da177e4 2206{
028867ac 2207 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
8b004457 2208
cabf08e4 2209 if (bio_data_dir(io->base_bio) == READ)
395b167c 2210 kcryptd_crypt_read_convert(io);
4e4eef64 2211 else
395b167c 2212 kcryptd_crypt_write_convert(io);
cabf08e4
MB
2213}
2214
39d42fa9
IK
2215static void kcryptd_crypt_tasklet(unsigned long work)
2216{
2217 kcryptd_crypt((struct work_struct *)work);
2218}
2219
395b167c 2220static void kcryptd_queue_crypt(struct dm_crypt_io *io)
cabf08e4 2221{
49a8a920 2222 struct crypt_config *cc = io->cc;
cabf08e4 2223
39d42fa9
IK
2224 if ((bio_data_dir(io->base_bio) == READ && test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags)) ||
2225 (bio_data_dir(io->base_bio) == WRITE && test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))) {
c87a95dc 2226 /*
d3703ef3 2227 * in_hardirq(): Crypto API's skcipher_walk_first() refuses to work in hard IRQ context.
c87a95dc
IK
2228 * irqs_disabled(): the kernel may run some IO completion from the idle thread, but
2229 * it is being executed with irqs disabled.
2230 */
d3703ef3 2231 if (in_hardirq() || irqs_disabled()) {
39d42fa9
IK
2232 tasklet_init(&io->tasklet, kcryptd_crypt_tasklet, (unsigned long)&io->work);
2233 tasklet_schedule(&io->tasklet);
2234 return;
2235 }
2236
2237 kcryptd_crypt(&io->work);
2238 return;
2239 }
2240
395b167c
AK
2241 INIT_WORK(&io->work, kcryptd_crypt);
2242 queue_work(cc->crypt_queue, &io->work);
1da177e4
LT
2243}
2244
ef43aa38 2245static void crypt_free_tfms_aead(struct crypt_config *cc)
1da177e4 2246{
ef43aa38
MB
2247 if (!cc->cipher_tfm.tfms_aead)
2248 return;
1da177e4 2249
ef43aa38
MB
2250 if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2251 crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
2252 cc->cipher_tfm.tfms_aead[0] = NULL;
1da177e4
LT
2253 }
2254
ef43aa38
MB
2255 kfree(cc->cipher_tfm.tfms_aead);
2256 cc->cipher_tfm.tfms_aead = NULL;
1da177e4
LT
2257}
2258
ef43aa38 2259static void crypt_free_tfms_skcipher(struct crypt_config *cc)
d1f96423 2260{
86a3238c 2261 unsigned int i;
d1f96423 2262
ef43aa38 2263 if (!cc->cipher_tfm.tfms)
fd2d231f
MP
2264 return;
2265
d1f96423 2266 for (i = 0; i < cc->tfms_count; i++)
ef43aa38
MB
2267 if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
2268 crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
2269 cc->cipher_tfm.tfms[i] = NULL;
d1f96423 2270 }
fd2d231f 2271
ef43aa38
MB
2272 kfree(cc->cipher_tfm.tfms);
2273 cc->cipher_tfm.tfms = NULL;
d1f96423
MB
2274}
2275
ef43aa38
MB
2276static void crypt_free_tfms(struct crypt_config *cc)
2277{
33d2f09f 2278 if (crypt_integrity_aead(cc))
ef43aa38
MB
2279 crypt_free_tfms_aead(cc);
2280 else
2281 crypt_free_tfms_skcipher(cc);
2282}
2283
2284static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
d1f96423 2285{
86a3238c 2286 unsigned int i;
d1f96423
MB
2287 int err;
2288
6396bb22
KC
2289 cc->cipher_tfm.tfms = kcalloc(cc->tfms_count,
2290 sizeof(struct crypto_skcipher *),
2291 GFP_KERNEL);
ef43aa38 2292 if (!cc->cipher_tfm.tfms)
fd2d231f
MP
2293 return -ENOMEM;
2294
d1f96423 2295 for (i = 0; i < cc->tfms_count; i++) {
cd746938
MP
2296 cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0,
2297 CRYPTO_ALG_ALLOCATES_MEMORY);
ef43aa38
MB
2298 if (IS_ERR(cc->cipher_tfm.tfms[i])) {
2299 err = PTR_ERR(cc->cipher_tfm.tfms[i]);
fd2d231f 2300 crypt_free_tfms(cc);
d1f96423
MB
2301 return err;
2302 }
2303 }
2304
af331eba
EB
2305 /*
2306 * dm-crypt performance can vary greatly depending on which crypto
2307 * algorithm implementation is used. Help people debug performance
2308 * problems by logging the ->cra_driver_name.
2309 */
7a1cd723 2310 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
af331eba 2311 crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
d1f96423
MB
2312 return 0;
2313}
2314
ef43aa38
MB
2315static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
2316{
ef43aa38
MB
2317 int err;
2318
2319 cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
2320 if (!cc->cipher_tfm.tfms)
2321 return -ENOMEM;
2322
cd746938
MP
2323 cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0,
2324 CRYPTO_ALG_ALLOCATES_MEMORY);
ef43aa38
MB
2325 if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2326 err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
2327 crypt_free_tfms(cc);
2328 return err;
2329 }
2330
7a1cd723 2331 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
af331eba 2332 crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
ef43aa38
MB
2333 return 0;
2334}
2335
2336static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
2337{
33d2f09f 2338 if (crypt_integrity_aead(cc))
ef43aa38
MB
2339 return crypt_alloc_tfms_aead(cc, ciphermode);
2340 else
2341 return crypt_alloc_tfms_skcipher(cc, ciphermode);
2342}
2343
86a3238c 2344static unsigned int crypt_subkey_size(struct crypt_config *cc)
ef43aa38
MB
2345{
2346 return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
2347}
2348
86a3238c 2349static unsigned int crypt_authenckey_size(struct crypt_config *cc)
ef43aa38
MB
2350{
2351 return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
2352}
2353
2354/*
2355 * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
2356 * the key must be for some reason in special format.
2357 * This funcion converts cc->key to this special format.
2358 */
2359static void crypt_copy_authenckey(char *p, const void *key,
86a3238c 2360 unsigned int enckeylen, unsigned int authkeylen)
ef43aa38
MB
2361{
2362 struct crypto_authenc_key_param *param;
2363 struct rtattr *rta;
2364
2365 rta = (struct rtattr *)p;
2366 param = RTA_DATA(rta);
2367 param->enckeylen = cpu_to_be32(enckeylen);
2368 rta->rta_len = RTA_LENGTH(sizeof(*param));
2369 rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
2370 p += RTA_SPACE(sizeof(*param));
2371 memcpy(p, key + enckeylen, authkeylen);
2372 p += authkeylen;
2373 memcpy(p, key, enckeylen);
2374}
2375
671ea6b4 2376static int crypt_setkey(struct crypt_config *cc)
c0297721 2377{
86a3238c 2378 unsigned int subkey_size;
fd2d231f
MP
2379 int err = 0, i, r;
2380
da31a078 2381 /* Ignore extra keys (which are used for IV etc) */
ef43aa38 2382 subkey_size = crypt_subkey_size(cc);
da31a078 2383
27c70036
MB
2384 if (crypt_integrity_hmac(cc)) {
2385 if (subkey_size < cc->key_mac_size)
2386 return -EINVAL;
2387
ef43aa38
MB
2388 crypt_copy_authenckey(cc->authenc_key, cc->key,
2389 subkey_size - cc->key_mac_size,
2390 cc->key_mac_size);
27c70036
MB
2391 }
2392
fd2d231f 2393 for (i = 0; i < cc->tfms_count; i++) {
33d2f09f 2394 if (crypt_integrity_hmac(cc))
ef43aa38
MB
2395 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2396 cc->authenc_key, crypt_authenckey_size(cc));
33d2f09f
MB
2397 else if (crypt_integrity_aead(cc))
2398 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2399 cc->key + (i * subkey_size),
2400 subkey_size);
ef43aa38
MB
2401 else
2402 r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
2403 cc->key + (i * subkey_size),
2404 subkey_size);
fd2d231f
MP
2405 if (r)
2406 err = r;
c0297721
AK
2407 }
2408
ef43aa38
MB
2409 if (crypt_integrity_hmac(cc))
2410 memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
2411
c0297721
AK
2412 return err;
2413}
2414
c538f6ec
OK
2415#ifdef CONFIG_KEYS
2416
027c431c
OK
2417static bool contains_whitespace(const char *str)
2418{
2419 while (*str)
2420 if (isspace(*str++))
2421 return true;
2422 return false;
2423}
2424
27f5411a
DB
2425static int set_key_user(struct crypt_config *cc, struct key *key)
2426{
2427 const struct user_key_payload *ukp;
2428
2429 ukp = user_key_payload_locked(key);
2430 if (!ukp)
2431 return -EKEYREVOKED;
2432
2433 if (cc->key_size != ukp->datalen)
2434 return -EINVAL;
2435
2436 memcpy(cc->key, ukp->data, cc->key_size);
2437
2438 return 0;
2439}
2440
27f5411a
DB
2441static int set_key_encrypted(struct crypt_config *cc, struct key *key)
2442{
2443 const struct encrypted_key_payload *ekp;
2444
2445 ekp = key->payload.data[0];
2446 if (!ekp)
2447 return -EKEYREVOKED;
2448
2449 if (cc->key_size != ekp->decrypted_datalen)
2450 return -EINVAL;
2451
2452 memcpy(cc->key, ekp->decrypted_data, cc->key_size);
2453
2454 return 0;
2455}
27f5411a 2456
363880c4
AF
2457static int set_key_trusted(struct crypt_config *cc, struct key *key)
2458{
2459 const struct trusted_key_payload *tkp;
2460
2461 tkp = key->payload.data[0];
2462 if (!tkp)
2463 return -EKEYREVOKED;
2464
2465 if (cc->key_size != tkp->key_len)
2466 return -EINVAL;
2467
2468 memcpy(cc->key, tkp->key, cc->key_size);
2469
2470 return 0;
2471}
2472
c538f6ec
OK
2473static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2474{
2475 char *new_key_string, *key_desc;
2476 int ret;
27f5411a 2477 struct key_type *type;
c538f6ec 2478 struct key *key;
27f5411a 2479 int (*set_key)(struct crypt_config *cc, struct key *key);
c538f6ec 2480
027c431c
OK
2481 /*
2482 * Reject key_string with whitespace. dm core currently lacks code for
2483 * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2484 */
2485 if (contains_whitespace(key_string)) {
2486 DMERR("whitespace chars not allowed in key string");
2487 return -EINVAL;
2488 }
2489
c538f6ec 2490 /* look for next ':' separating key_type from key_description */
fc772580 2491 key_desc = strchr(key_string, ':');
c538f6ec
OK
2492 if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2493 return -EINVAL;
2494
27f5411a
DB
2495 if (!strncmp(key_string, "logon:", key_desc - key_string + 1)) {
2496 type = &key_type_logon;
2497 set_key = set_key_user;
2498 } else if (!strncmp(key_string, "user:", key_desc - key_string + 1)) {
2499 type = &key_type_user;
2500 set_key = set_key_user;
831475cc
AF
2501 } else if (IS_ENABLED(CONFIG_ENCRYPTED_KEYS) &&
2502 !strncmp(key_string, "encrypted:", key_desc - key_string + 1)) {
27f5411a
DB
2503 type = &key_type_encrypted;
2504 set_key = set_key_encrypted;
363880c4
AF
2505 } else if (IS_ENABLED(CONFIG_TRUSTED_KEYS) &&
2506 !strncmp(key_string, "trusted:", key_desc - key_string + 1)) {
2507 type = &key_type_trusted;
2508 set_key = set_key_trusted;
27f5411a 2509 } else {
c538f6ec 2510 return -EINVAL;
27f5411a 2511 }
c538f6ec
OK
2512
2513 new_key_string = kstrdup(key_string, GFP_KERNEL);
2514 if (!new_key_string)
2515 return -ENOMEM;
2516
27f5411a 2517 key = request_key(type, key_desc + 1, NULL);
c538f6ec 2518 if (IS_ERR(key)) {
453431a5 2519 kfree_sensitive(new_key_string);
c538f6ec
OK
2520 return PTR_ERR(key);
2521 }
2522
f5b0cba8 2523 down_read(&key->sem);
c538f6ec 2524
27f5411a
DB
2525 ret = set_key(cc, key);
2526 if (ret < 0) {
f5b0cba8 2527 up_read(&key->sem);
c538f6ec 2528 key_put(key);
453431a5 2529 kfree_sensitive(new_key_string);
27f5411a 2530 return ret;
c538f6ec
OK
2531 }
2532
f5b0cba8 2533 up_read(&key->sem);
c538f6ec
OK
2534 key_put(key);
2535
2536 /* clear the flag since following operations may invalidate previously valid key */
2537 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2538
2539 ret = crypt_setkey(cc);
2540
c538f6ec
OK
2541 if (!ret) {
2542 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
453431a5 2543 kfree_sensitive(cc->key_string);
c538f6ec
OK
2544 cc->key_string = new_key_string;
2545 } else
453431a5 2546 kfree_sensitive(new_key_string);
c538f6ec
OK
2547
2548 return ret;
2549}
2550
2551static int get_key_size(char **key_string)
2552{
2553 char *colon, dummy;
2554 int ret;
2555
2556 if (*key_string[0] != ':')
2557 return strlen(*key_string) >> 1;
2558
2559 /* look for next ':' in key string */
2560 colon = strpbrk(*key_string + 1, ":");
2561 if (!colon)
2562 return -EINVAL;
2563
2564 if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2565 return -EINVAL;
2566
2567 *key_string = colon;
2568
2569 /* remaining key string should be :<logon|user>:<key_desc> */
2570
2571 return ret;
2572}
2573
2574#else
2575
2576static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2577{
2578 return -EINVAL;
2579}
2580
2581static int get_key_size(char **key_string)
2582{
6fc51504 2583 return (*key_string[0] == ':') ? -EINVAL : (int)(strlen(*key_string) >> 1);
c538f6ec
OK
2584}
2585
27f5411a 2586#endif /* CONFIG_KEYS */
c538f6ec 2587
e48d4bbf
MB
2588static int crypt_set_key(struct crypt_config *cc, char *key)
2589{
de8be5ac
MB
2590 int r = -EINVAL;
2591 int key_string_len = strlen(key);
2592
69a8cfcd
MB
2593 /* Hyphen (which gives a key_size of zero) means there is no key. */
2594 if (!cc->key_size && strcmp(key, "-"))
de8be5ac 2595 goto out;
e48d4bbf 2596
c538f6ec
OK
2597 /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2598 if (key[0] == ':') {
2599 r = crypt_set_keyring_key(cc, key + 1);
de8be5ac 2600 goto out;
c538f6ec 2601 }
e48d4bbf 2602
265e9098
OK
2603 /* clear the flag since following operations may invalidate previously valid key */
2604 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
e48d4bbf 2605
c538f6ec 2606 /* wipe references to any kernel keyring key */
453431a5 2607 kfree_sensitive(cc->key_string);
c538f6ec
OK
2608 cc->key_string = NULL;
2609
e944e03e
AS
2610 /* Decode key from its hex representation. */
2611 if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
de8be5ac 2612 goto out;
e48d4bbf 2613
671ea6b4 2614 r = crypt_setkey(cc);
265e9098
OK
2615 if (!r)
2616 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
de8be5ac
MB
2617
2618out:
2619 /* Hex key string not needed after here, so wipe it. */
2620 memset(key, '0', key_string_len);
2621
2622 return r;
e48d4bbf
MB
2623}
2624
2625static int crypt_wipe_key(struct crypt_config *cc)
2626{
c82feeec
OK
2627 int r;
2628
e48d4bbf 2629 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
c82feeec 2630 get_random_bytes(&cc->key, cc->key_size);
4a52ffc7
MB
2631
2632 /* Wipe IV private keys */
2633 if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
2634 r = cc->iv_gen_ops->wipe(cc);
2635 if (r)
2636 return r;
2637 }
2638
453431a5 2639 kfree_sensitive(cc->key_string);
c538f6ec 2640 cc->key_string = NULL;
c82feeec
OK
2641 r = crypt_setkey(cc);
2642 memset(&cc->key, 0, cc->key_size * sizeof(u8));
c0297721 2643
c82feeec 2644 return r;
e48d4bbf
MB
2645}
2646
5059353d
MP
2647static void crypt_calculate_pages_per_client(void)
2648{
ca79b0c2 2649 unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
5059353d
MP
2650
2651 if (!dm_crypt_clients_n)
2652 return;
2653
2654 pages /= dm_crypt_clients_n;
2655 if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
2656 pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
2657 dm_crypt_pages_per_client = pages;
2658}
2659
2660static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
2661{
2662 struct crypt_config *cc = pool_data;
2663 struct page *page;
2664
528b16bf
AW
2665 /*
2666 * Note, percpu_counter_read_positive() may over (and under) estimate
2667 * the current usage by at most (batch - 1) * num_online_cpus() pages,
2668 * but avoids potential spinlock contention of an exact result.
2669 */
2670 if (unlikely(percpu_counter_read_positive(&cc->n_allocated_pages) >= dm_crypt_pages_per_client) &&
5059353d
MP
2671 likely(gfp_mask & __GFP_NORETRY))
2672 return NULL;
2673
2674 page = alloc_page(gfp_mask);
2675 if (likely(page != NULL))
2676 percpu_counter_add(&cc->n_allocated_pages, 1);
2677
2678 return page;
2679}
2680
2681static void crypt_page_free(void *page, void *pool_data)
2682{
2683 struct crypt_config *cc = pool_data;
2684
2685 __free_page(page);
2686 percpu_counter_sub(&cc->n_allocated_pages, 1);
2687}
2688
28513fcc
MB
2689static void crypt_dtr(struct dm_target *ti)
2690{
2691 struct crypt_config *cc = ti->private;
2692
2693 ti->private = NULL;
2694
2695 if (!cc)
2696 return;
2697
f659b100 2698 if (cc->write_thread)
dc267621
MP
2699 kthread_stop(cc->write_thread);
2700
28513fcc
MB
2701 if (cc->io_queue)
2702 destroy_workqueue(cc->io_queue);
2703 if (cc->crypt_queue)
2704 destroy_workqueue(cc->crypt_queue);
2705
fd2d231f
MP
2706 crypt_free_tfms(cc);
2707
6f1c819c 2708 bioset_exit(&cc->bs);
28513fcc 2709
6f1c819c
KO
2710 mempool_exit(&cc->page_pool);
2711 mempool_exit(&cc->req_pool);
2712 mempool_exit(&cc->tag_pool);
2713
d00a11df
KO
2714 WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
2715 percpu_counter_destroy(&cc->n_allocated_pages);
2716
28513fcc
MB
2717 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
2718 cc->iv_gen_ops->dtr(cc);
2719
28513fcc
MB
2720 if (cc->dev)
2721 dm_put_device(ti, cc->dev);
2722
453431a5
WL
2723 kfree_sensitive(cc->cipher_string);
2724 kfree_sensitive(cc->key_string);
2725 kfree_sensitive(cc->cipher_auth);
2726 kfree_sensitive(cc->authenc_key);
28513fcc 2727
d5ffebdd
MS
2728 mutex_destroy(&cc->bio_alloc_lock);
2729
28513fcc 2730 /* Must zero key material before freeing */
453431a5 2731 kfree_sensitive(cc);
5059353d
MP
2732
2733 spin_lock(&dm_crypt_clients_lock);
2734 WARN_ON(!dm_crypt_clients_n);
2735 dm_crypt_clients_n--;
2736 crypt_calculate_pages_per_client();
2737 spin_unlock(&dm_crypt_clients_lock);
58d0f180
MW
2738
2739 dm_audit_log_dtr(DM_MSG_PREFIX, ti, 1);
28513fcc
MB
2740}
2741
e889f97a
MB
2742static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
2743{
2744 struct crypt_config *cc = ti->private;
2745
33d2f09f 2746 if (crypt_integrity_aead(cc))
e889f97a
MB
2747 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2748 else
2749 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2750
e889f97a
MB
2751 if (cc->iv_size)
2752 /* at least a 64 bit sector number should fit in our buffer */
2753 cc->iv_size = max(cc->iv_size,
2754 (unsigned int)(sizeof(u64) / sizeof(u8)));
2755 else if (ivmode) {
2756 DMWARN("Selected cipher does not support IVs");
2757 ivmode = NULL;
2758 }
2759
2760 /* Choose ivmode, see comments at iv code. */
2761 if (ivmode == NULL)
2762 cc->iv_gen_ops = NULL;
2763 else if (strcmp(ivmode, "plain") == 0)
2764 cc->iv_gen_ops = &crypt_iv_plain_ops;
2765 else if (strcmp(ivmode, "plain64") == 0)
2766 cc->iv_gen_ops = &crypt_iv_plain64_ops;
7e3fd855
MB
2767 else if (strcmp(ivmode, "plain64be") == 0)
2768 cc->iv_gen_ops = &crypt_iv_plain64be_ops;
e889f97a
MB
2769 else if (strcmp(ivmode, "essiv") == 0)
2770 cc->iv_gen_ops = &crypt_iv_essiv_ops;
2771 else if (strcmp(ivmode, "benbi") == 0)
2772 cc->iv_gen_ops = &crypt_iv_benbi_ops;
2773 else if (strcmp(ivmode, "null") == 0)
2774 cc->iv_gen_ops = &crypt_iv_null_ops;
b9411d73
MB
2775 else if (strcmp(ivmode, "eboiv") == 0)
2776 cc->iv_gen_ops = &crypt_iv_eboiv_ops;
bbb16584
MB
2777 else if (strcmp(ivmode, "elephant") == 0) {
2778 cc->iv_gen_ops = &crypt_iv_elephant_ops;
2779 cc->key_parts = 2;
2780 cc->key_extra_size = cc->key_size / 2;
2781 if (cc->key_extra_size > ELEPHANT_MAX_KEY_SIZE)
2782 return -EINVAL;
2783 set_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags);
2784 } else if (strcmp(ivmode, "lmk") == 0) {
e889f97a
MB
2785 cc->iv_gen_ops = &crypt_iv_lmk_ops;
2786 /*
2787 * Version 2 and 3 is recognised according
2788 * to length of provided multi-key string.
2789 * If present (version 3), last key is used as IV seed.
2790 * All keys (including IV seed) are always the same size.
2791 */
2792 if (cc->key_size % cc->key_parts) {
2793 cc->key_parts++;
2794 cc->key_extra_size = cc->key_size / cc->key_parts;
2795 }
2796 } else if (strcmp(ivmode, "tcw") == 0) {
2797 cc->iv_gen_ops = &crypt_iv_tcw_ops;
2798 cc->key_parts += 2; /* IV + whitening */
2799 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2800 } else if (strcmp(ivmode, "random") == 0) {
2801 cc->iv_gen_ops = &crypt_iv_random_ops;
2802 /* Need storage space in integrity fields. */
2803 cc->integrity_iv_size = cc->iv_size;
2804 } else {
2805 ti->error = "Invalid IV mode";
2806 return -EINVAL;
2807 }
2808
2809 return 0;
2810}
2811
33d2f09f
MB
2812/*
2813 * Workaround to parse HMAC algorithm from AEAD crypto API spec.
2814 * The HMAC is needed to calculate tag size (HMAC digest size).
2815 * This should be probably done by crypto-api calls (once available...)
2816 */
2817static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
2818{
2819 char *start, *end, *mac_alg = NULL;
2820 struct crypto_ahash *mac;
2821
2822 if (!strstarts(cipher_api, "authenc("))
2823 return 0;
2824
2825 start = strchr(cipher_api, '(');
2826 end = strchr(cipher_api, ',');
2827 if (!start || !end || ++start > end)
2828 return -EINVAL;
2829
2830 mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
2831 if (!mac_alg)
2832 return -ENOMEM;
2833 strncpy(mac_alg, start, end - start);
2834
cd746938 2835 mac = crypto_alloc_ahash(mac_alg, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
33d2f09f
MB
2836 kfree(mac_alg);
2837
2838 if (IS_ERR(mac))
2839 return PTR_ERR(mac);
2840
2841 cc->key_mac_size = crypto_ahash_digestsize(mac);
2842 crypto_free_ahash(mac);
2843
2844 cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
2845 if (!cc->authenc_key)
2846 return -ENOMEM;
2847
2848 return 0;
2849}
2850
2851static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
2852 char **ivmode, char **ivopts)
2853{
2854 struct crypt_config *cc = ti->private;
a1a262b6 2855 char *tmp, *cipher_api, buf[CRYPTO_MAX_ALG_NAME];
33d2f09f
MB
2856 int ret = -EINVAL;
2857
2858 cc->tfms_count = 1;
2859
2860 /*
2861 * New format (capi: prefix)
2862 * capi:cipher_api_spec-iv:ivopts
2863 */
2864 tmp = &cipher_in[strlen("capi:")];
1856b9f7
MB
2865
2866 /* Separate IV options if present, it can contain another '-' in hash name */
2867 *ivopts = strrchr(tmp, ':');
2868 if (*ivopts) {
2869 **ivopts = '\0';
2870 (*ivopts)++;
2871 }
2872 /* Parse IV mode */
2873 *ivmode = strrchr(tmp, '-');
2874 if (*ivmode) {
2875 **ivmode = '\0';
2876 (*ivmode)++;
2877 }
2878 /* The rest is crypto API spec */
2879 cipher_api = tmp;
33d2f09f 2880
a1a262b6
AB
2881 /* Alloc AEAD, can be used only in new format. */
2882 if (crypt_integrity_aead(cc)) {
2883 ret = crypt_ctr_auth_cipher(cc, cipher_api);
2884 if (ret < 0) {
2885 ti->error = "Invalid AEAD cipher spec";
2886 return -ENOMEM;
2887 }
2888 }
2889
33d2f09f
MB
2890 if (*ivmode && !strcmp(*ivmode, "lmk"))
2891 cc->tfms_count = 64;
2892
a1a262b6
AB
2893 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2894 if (!*ivopts) {
2895 ti->error = "Digest algorithm missing for ESSIV mode";
2896 return -EINVAL;
2897 }
2898 ret = snprintf(buf, CRYPTO_MAX_ALG_NAME, "essiv(%s,%s)",
2899 cipher_api, *ivopts);
2900 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2901 ti->error = "Cannot allocate cipher string";
2902 return -ENOMEM;
2903 }
2904 cipher_api = buf;
2905 }
2906
33d2f09f
MB
2907 cc->key_parts = cc->tfms_count;
2908
2909 /* Allocate cipher */
2910 ret = crypt_alloc_tfms(cc, cipher_api);
2911 if (ret < 0) {
2912 ti->error = "Error allocating crypto tfm";
2913 return ret;
2914 }
2915
a1a262b6 2916 if (crypt_integrity_aead(cc))
33d2f09f 2917 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
a1a262b6 2918 else
33d2f09f
MB
2919 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2920
33d2f09f
MB
2921 return 0;
2922}
2923
2924static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
2925 char **ivmode, char **ivopts)
1da177e4 2926{
5ebaee6d 2927 struct crypt_config *cc = ti->private;
33d2f09f 2928 char *tmp, *cipher, *chainmode, *keycount;
5ebaee6d 2929 char *cipher_api = NULL;
fd2d231f 2930 int ret = -EINVAL;
31998ef1 2931 char dummy;
1da177e4 2932
33d2f09f 2933 if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
5ebaee6d 2934 ti->error = "Bad cipher specification";
1da177e4
LT
2935 return -EINVAL;
2936 }
2937
5ebaee6d
MB
2938 /*
2939 * Legacy dm-crypt cipher specification
d1f96423 2940 * cipher[:keycount]-mode-iv:ivopts
5ebaee6d
MB
2941 */
2942 tmp = cipher_in;
d1f96423
MB
2943 keycount = strsep(&tmp, "-");
2944 cipher = strsep(&keycount, ":");
2945
2946 if (!keycount)
2947 cc->tfms_count = 1;
31998ef1 2948 else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
d1f96423
MB
2949 !is_power_of_2(cc->tfms_count)) {
2950 ti->error = "Bad cipher key count specification";
2951 return -EINVAL;
2952 }
2953 cc->key_parts = cc->tfms_count;
5ebaee6d 2954
1da177e4 2955 chainmode = strsep(&tmp, "-");
1856b9f7
MB
2956 *ivmode = strsep(&tmp, ":");
2957 *ivopts = tmp;
1da177e4 2958
7dbcd137
MB
2959 /*
2960 * For compatibility with the original dm-crypt mapping format, if
2961 * only the cipher name is supplied, use cbc-plain.
2962 */
33d2f09f 2963 if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
1da177e4 2964 chainmode = "cbc";
33d2f09f 2965 *ivmode = "plain";
1da177e4
LT
2966 }
2967
33d2f09f 2968 if (strcmp(chainmode, "ecb") && !*ivmode) {
5ebaee6d
MB
2969 ti->error = "IV mechanism required";
2970 return -EINVAL;
1da177e4
LT
2971 }
2972
5ebaee6d
MB
2973 cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
2974 if (!cipher_api)
2975 goto bad_mem;
2976
a1a262b6
AB
2977 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2978 if (!*ivopts) {
2979 ti->error = "Digest algorithm missing for ESSIV mode";
2980 kfree(cipher_api);
2981 return -EINVAL;
2982 }
2983 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2984 "essiv(%s(%s),%s)", chainmode, cipher, *ivopts);
2985 } else {
2986 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
2987 "%s(%s)", chainmode, cipher);
2988 }
2989 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
5ebaee6d
MB
2990 kfree(cipher_api);
2991 goto bad_mem;
1da177e4
LT
2992 }
2993
5ebaee6d 2994 /* Allocate cipher */
fd2d231f
MP
2995 ret = crypt_alloc_tfms(cc, cipher_api);
2996 if (ret < 0) {
2997 ti->error = "Error allocating crypto tfm";
33d2f09f
MB
2998 kfree(cipher_api);
2999 return ret;
1da177e4 3000 }
bd86e320 3001 kfree(cipher_api);
1da177e4 3002
33d2f09f
MB
3003 return 0;
3004bad_mem:
3005 ti->error = "Cannot allocate cipher strings";
3006 return -ENOMEM;
3007}
5ebaee6d 3008
33d2f09f
MB
3009static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
3010{
3011 struct crypt_config *cc = ti->private;
3012 char *ivmode = NULL, *ivopts = NULL;
3013 int ret;
3014
3015 cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
3016 if (!cc->cipher_string) {
3017 ti->error = "Cannot allocate cipher strings";
3018 return -ENOMEM;
1da177e4
LT
3019 }
3020
33d2f09f
MB
3021 if (strstarts(cipher_in, "capi:"))
3022 ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
3023 else
3024 ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
3025 if (ret)
3026 return ret;
3027
5ebaee6d 3028 /* Initialize IV */
e889f97a
MB
3029 ret = crypt_ctr_ivmode(ti, ivmode);
3030 if (ret < 0)
33d2f09f 3031 return ret;
1da177e4 3032
da31a078
MB
3033 /* Initialize and set key */
3034 ret = crypt_set_key(cc, key);
3035 if (ret < 0) {
3036 ti->error = "Error decoding and setting key";
33d2f09f 3037 return ret;
da31a078
MB
3038 }
3039
28513fcc
MB
3040 /* Allocate IV */
3041 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
3042 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
3043 if (ret < 0) {
3044 ti->error = "Error creating IV";
33d2f09f 3045 return ret;
28513fcc
MB
3046 }
3047 }
1da177e4 3048
28513fcc
MB
3049 /* Initialize IV (set keys for ESSIV etc) */
3050 if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
3051 ret = cc->iv_gen_ops->init(cc);
3052 if (ret < 0) {
3053 ti->error = "Error initialising IV";
33d2f09f 3054 return ret;
28513fcc 3055 }
b95bf2d3
MB
3056 }
3057
dc94902b
OK
3058 /* wipe the kernel key payload copy */
3059 if (cc->key_string)
3060 memset(cc->key, 0, cc->key_size * sizeof(u8));
3061
5ebaee6d 3062 return ret;
5ebaee6d 3063}
5ebaee6d 3064
ef43aa38
MB
3065static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
3066{
3067 struct crypt_config *cc = ti->private;
3068 struct dm_arg_set as;
5916a22b 3069 static const struct dm_arg _args[] = {
39d42fa9 3070 {0, 8, "Invalid number of feature args"},
ef43aa38
MB
3071 };
3072 unsigned int opt_params, val;
3073 const char *opt_string, *sval;
8f0009a2 3074 char dummy;
ef43aa38
MB
3075 int ret;
3076
3077 /* Optional parameters */
3078 as.argc = argc;
3079 as.argv = argv;
3080
3081 ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
3082 if (ret)
3083 return ret;
3084
3085 while (opt_params--) {
3086 opt_string = dm_shift_arg(&as);
3087 if (!opt_string) {
3088 ti->error = "Not enough feature arguments";
3089 return -EINVAL;
3090 }
3091
3092 if (!strcasecmp(opt_string, "allow_discards"))
3093 ti->num_discard_bios = 1;
3094
3095 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
3096 set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3097
3098 else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
3099 set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
39d42fa9
IK
3100 else if (!strcasecmp(opt_string, "no_read_workqueue"))
3101 set_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3102 else if (!strcasecmp(opt_string, "no_write_workqueue"))
3103 set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
ef43aa38
MB
3104 else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
3105 if (val == 0 || val > MAX_TAG_SIZE) {
3106 ti->error = "Invalid integrity arguments";
3107 return -EINVAL;
3108 }
3109 cc->on_disk_tag_size = val;
3110 sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
3111 if (!strcasecmp(sval, "aead")) {
3112 set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
ef43aa38
MB
3113 } else if (strcasecmp(sval, "none")) {
3114 ti->error = "Unknown integrity profile";
3115 return -EINVAL;
3116 }
3117
3118 cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
3119 if (!cc->cipher_auth)
3120 return -ENOMEM;
ff3af92b 3121 } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
8f0009a2
MB
3122 if (cc->sector_size < (1 << SECTOR_SHIFT) ||
3123 cc->sector_size > 4096 ||
ff3af92b 3124 (cc->sector_size & (cc->sector_size - 1))) {
8f0009a2
MB
3125 ti->error = "Invalid feature value for sector_size";
3126 return -EINVAL;
3127 }
783874b0
MB
3128 if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
3129 ti->error = "Device size is not multiple of sector_size feature";
3130 return -EINVAL;
3131 }
ff3af92b 3132 cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
8f0009a2
MB
3133 } else if (!strcasecmp(opt_string, "iv_large_sectors"))
3134 set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3135 else {
ef43aa38
MB
3136 ti->error = "Invalid feature arguments";
3137 return -EINVAL;
3138 }
3139 }
3140
3141 return 0;
5ebaee6d
MB
3142}
3143
8e225f04 3144#ifdef CONFIG_BLK_DEV_ZONED
8e225f04
DLM
3145static int crypt_report_zones(struct dm_target *ti,
3146 struct dm_report_zones_args *args, unsigned int nr_zones)
3147{
3148 struct crypt_config *cc = ti->private;
8e225f04 3149
912e8875
DLM
3150 return dm_report_zones(cc->dev->bdev, cc->start,
3151 cc->start + dm_target_offset(ti, args->next_sector),
3152 args, nr_zones);
8e225f04 3153}
e3290b94
MS
3154#else
3155#define crypt_report_zones NULL
8e225f04
DLM
3156#endif
3157
5ebaee6d
MB
3158/*
3159 * Construct an encryption mapping:
c538f6ec 3160 * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
5ebaee6d
MB
3161 */
3162static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
3163{
3164 struct crypt_config *cc;
ed0302e8 3165 const char *devname = dm_table_device_name(ti->table);
c538f6ec 3166 int key_size;
ef43aa38 3167 unsigned int align_mask;
5ebaee6d
MB
3168 unsigned long long tmpll;
3169 int ret;
ef43aa38 3170 size_t iv_size_padding, additional_req_size;
31998ef1 3171 char dummy;
772ae5f5 3172
772ae5f5 3173 if (argc < 5) {
5ebaee6d
MB
3174 ti->error = "Not enough arguments";
3175 return -EINVAL;
1da177e4
LT
3176 }
3177
c538f6ec
OK
3178 key_size = get_key_size(&argv[1]);
3179 if (key_size < 0) {
3180 ti->error = "Cannot parse key size";
3181 return -EINVAL;
3182 }
5ebaee6d 3183
9c81c99b 3184 cc = kzalloc(struct_size(cc, key, key_size), GFP_KERNEL);
5ebaee6d
MB
3185 if (!cc) {
3186 ti->error = "Cannot allocate encryption context";
3187 return -ENOMEM;
3188 }
69a8cfcd 3189 cc->key_size = key_size;
8f0009a2 3190 cc->sector_size = (1 << SECTOR_SHIFT);
ff3af92b 3191 cc->sector_shift = 0;
5ebaee6d
MB
3192
3193 ti->private = cc;
ef43aa38 3194
5059353d
MP
3195 spin_lock(&dm_crypt_clients_lock);
3196 dm_crypt_clients_n++;
3197 crypt_calculate_pages_per_client();
3198 spin_unlock(&dm_crypt_clients_lock);
3199
3200 ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
3201 if (ret < 0)
3202 goto bad;
3203
ef43aa38
MB
3204 /* Optional parameters need to be read before cipher constructor */
3205 if (argc > 5) {
3206 ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
3207 if (ret)
3208 goto bad;
3209 }
3210
5ebaee6d
MB
3211 ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
3212 if (ret < 0)
3213 goto bad;
3214
33d2f09f 3215 if (crypt_integrity_aead(cc)) {
ef43aa38
MB
3216 cc->dmreq_start = sizeof(struct aead_request);
3217 cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
3218 align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
3219 } else {
3220 cc->dmreq_start = sizeof(struct skcipher_request);
3221 cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
3222 align_mask = crypto_skcipher_alignmask(any_tfm(cc));
3223 }
d49ec52f
MP
3224 cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
3225
ef43aa38 3226 if (align_mask < CRYPTO_MINALIGN) {
d49ec52f
MP
3227 /* Allocate the padding exactly */
3228 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
ef43aa38 3229 & align_mask;
d49ec52f
MP
3230 } else {
3231 /*
3232 * If the cipher requires greater alignment than kmalloc
3233 * alignment, we don't know the exact position of the
3234 * initialization vector. We must assume worst case.
3235 */
ef43aa38 3236 iv_size_padding = align_mask;
d49ec52f 3237 }
ddd42edf 3238
ef43aa38
MB
3239 /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
3240 additional_req_size = sizeof(struct dm_crypt_request) +
3241 iv_size_padding + cc->iv_size +
3242 cc->iv_size +
3243 sizeof(uint64_t) +
3244 sizeof(unsigned int);
3245
6f1c819c
KO
3246 ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
3247 if (ret) {
ddd42edf 3248 ti->error = "Cannot allocate crypt request mempool";
28513fcc 3249 goto bad;
ddd42edf 3250 }
ddd42edf 3251
30187e1d 3252 cc->per_bio_data_size = ti->per_io_data_size =
ef43aa38 3253 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
d49ec52f 3254 ARCH_KMALLOC_MINALIGN);
298a9fa0 3255
a8affc03 3256 ret = mempool_init(&cc->page_pool, BIO_MAX_VECS, crypt_page_alloc, crypt_page_free, cc);
6f1c819c 3257 if (ret) {
72d94861 3258 ti->error = "Cannot allocate page mempool";
28513fcc 3259 goto bad;
1da177e4
LT
3260 }
3261
6f1c819c
KO
3262 ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
3263 if (ret) {
6a24c718 3264 ti->error = "Cannot allocate crypt bioset";
28513fcc 3265 goto bad;
6a24c718
MB
3266 }
3267
7145c241
MP
3268 mutex_init(&cc->bio_alloc_lock);
3269
28513fcc 3270 ret = -EINVAL;
8f0009a2
MB
3271 if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
3272 (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
72d94861 3273 ti->error = "Invalid iv_offset sector";
28513fcc 3274 goto bad;
1da177e4 3275 }
4ee218cd 3276 cc->iv_offset = tmpll;
1da177e4 3277
e80d1c80
VG
3278 ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
3279 if (ret) {
28513fcc
MB
3280 ti->error = "Device lookup failed";
3281 goto bad;
3282 }
3283
e80d1c80 3284 ret = -EINVAL;
ef87bfc2 3285 if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
72d94861 3286 ti->error = "Invalid device sector";
28513fcc 3287 goto bad;
1da177e4 3288 }
4ee218cd 3289 cc->start = tmpll;
1da177e4 3290
8e225f04 3291 if (bdev_is_zoned(cc->dev->bdev)) {
f34ee1dc
DLM
3292 /*
3293 * For zoned block devices, we need to preserve the issuer write
3294 * ordering. To do so, disable write workqueues and force inline
3295 * encryption completion.
3296 */
8e225f04
DLM
3297 set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3298 set_bit(DM_CRYPT_WRITE_INLINE, &cc->flags);
f34ee1dc
DLM
3299
3300 /*
3301 * All zone append writes to a zone of a zoned block device will
3302 * have the same BIO sector, the start of the zone. When the
3303 * cypher IV mode uses sector values, all data targeting a
3304 * zone will be encrypted using the first sector numbers of the
3305 * zone. This will not result in write errors but will
3306 * cause most reads to fail as reads will use the sector values
3307 * for the actual data locations, resulting in IV mismatch.
3308 * To avoid this problem, ask DM core to emulate zone append
3309 * operations with regular writes.
3310 */
3311 DMDEBUG("Zone append operations will be emulated");
3312 ti->emulate_zone_append = true;
8e225f04
DLM
3313 }
3314
33d2f09f 3315 if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
ef43aa38 3316 ret = crypt_integrity_ctr(cc, ti);
772ae5f5
MB
3317 if (ret)
3318 goto bad;
3319
ef43aa38
MB
3320 cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
3321 if (!cc->tag_pool_max_sectors)
3322 cc->tag_pool_max_sectors = 1;
f3396c58 3323
6f1c819c 3324 ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
ef43aa38 3325 cc->tag_pool_max_sectors * cc->on_disk_tag_size);
6f1c819c 3326 if (ret) {
ef43aa38
MB
3327 ti->error = "Cannot allocate integrity tags mempool";
3328 goto bad;
772ae5f5 3329 }
583fe747
MP
3330
3331 cc->tag_pool_max_sectors <<= cc->sector_shift;
772ae5f5
MB
3332 }
3333
28513fcc 3334 ret = -ENOMEM;
f612b213 3335 cc->io_queue = alloc_workqueue("kcryptd_io/%s", WQ_MEM_RECLAIM, 1, devname);
cabf08e4
MB
3336 if (!cc->io_queue) {
3337 ti->error = "Couldn't create kcryptd io queue";
28513fcc 3338 goto bad;
cabf08e4
MB
3339 }
3340
f3396c58 3341 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
48b0777c 3342 cc->crypt_queue = alloc_workqueue("kcryptd/%s", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM,
ed0302e8 3343 1, devname);
f3396c58 3344 else
48b0777c
MS
3345 cc->crypt_queue = alloc_workqueue("kcryptd/%s",
3346 WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
ed0302e8 3347 num_online_cpus(), devname);
cabf08e4 3348 if (!cc->crypt_queue) {
9934a8be 3349 ti->error = "Couldn't create kcryptd queue";
28513fcc 3350 goto bad;
9934a8be
MB
3351 }
3352
c7329eff 3353 spin_lock_init(&cc->write_thread_lock);
b3c5fd30 3354 cc->write_tree = RB_ROOT;
dc267621 3355
a5217c11 3356 cc->write_thread = kthread_run(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
dc267621
MP
3357 if (IS_ERR(cc->write_thread)) {
3358 ret = PTR_ERR(cc->write_thread);
3359 cc->write_thread = NULL;
3360 ti->error = "Couldn't spawn write thread";
3361 goto bad;
3362 }
dc267621 3363
55a62eef 3364 ti->num_flush_bios = 1;
a666e5c0 3365 ti->limit_swap_bios = true;
e5524e12 3366 ti->accounts_remapped_io = true;
983c7db3 3367
58d0f180 3368 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 1);
1da177e4
LT
3369 return 0;
3370
28513fcc 3371bad:
58d0f180 3372 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 0);
28513fcc
MB
3373 crypt_dtr(ti);
3374 return ret;
1da177e4
LT
3375}
3376
7de3ee57 3377static int crypt_map(struct dm_target *ti, struct bio *bio)
1da177e4 3378{
028867ac 3379 struct dm_crypt_io *io;
49a8a920 3380 struct crypt_config *cc = ti->private;
647c7db1 3381
772ae5f5 3382 /*
28a8f0d3
MC
3383 * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
3384 * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
e6047149 3385 * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
772ae5f5 3386 */
1eff9d32 3387 if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
28a8f0d3 3388 bio_op(bio) == REQ_OP_DISCARD)) {
74d46992 3389 bio_set_dev(bio, cc->dev->bdev);
772ae5f5 3390 if (bio_sectors(bio))
4f024f37
KO
3391 bio->bi_iter.bi_sector = cc->start +
3392 dm_target_offset(ti, bio->bi_iter.bi_sector);
647c7db1
MP
3393 return DM_MAPIO_REMAPPED;
3394 }
1da177e4 3395
4e870e94
MP
3396 /*
3397 * Check if bio is too large, split as needed.
3398 */
a8affc03 3399 if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_VECS << PAGE_SHIFT)) &&
ef43aa38 3400 (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
a8affc03 3401 dm_accept_partial_bio(bio, ((BIO_MAX_VECS << PAGE_SHIFT) >> SECTOR_SHIFT));
4e870e94 3402
8f0009a2
MB
3403 /*
3404 * Ensure that bio is a multiple of internal sector encryption size
3405 * and is aligned to this size as defined in IO hints.
3406 */
3407 if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
846785e6 3408 return DM_MAPIO_KILL;
8f0009a2
MB
3409
3410 if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
846785e6 3411 return DM_MAPIO_KILL;
8f0009a2 3412
298a9fa0
MP
3413 io = dm_per_bio_data(bio, cc->per_bio_data_size);
3414 crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
ef43aa38
MB
3415
3416 if (cc->on_disk_tag_size) {
86a3238c 3417 unsigned int tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
ef43aa38
MB
3418
3419 if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
583fe747 3420 unlikely(!(io->integrity_metadata = kmalloc(tag_len,
ef43aa38
MB
3421 GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
3422 if (bio_sectors(bio) > cc->tag_pool_max_sectors)
3423 dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
6f1c819c 3424 io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
ef43aa38
MB
3425 io->integrity_metadata_from_pool = true;
3426 }
3427 }
3428
33d2f09f 3429 if (crypt_integrity_aead(cc))
ef43aa38
MB
3430 io->ctx.r.req_aead = (struct aead_request *)(io + 1);
3431 else
3432 io->ctx.r.req = (struct skcipher_request *)(io + 1);
cabf08e4 3433
20c82538 3434 if (bio_data_dir(io->base_bio) == READ) {
e5524e12 3435 if (kcryptd_io_read(io, CRYPT_MAP_READ_GFP))
dc267621 3436 kcryptd_queue_read(io);
20c82538 3437 } else
cabf08e4 3438 kcryptd_queue_crypt(io);
1da177e4 3439
d2a7ad29 3440 return DM_MAPIO_SUBMITTED;
1da177e4
LT
3441}
3442
567dd8f3
MP
3443static char hex2asc(unsigned char c)
3444{
86a3238c 3445 return c + '0' + ((unsigned int)(9 - c) >> 4 & 0x27);
567dd8f3
MP
3446}
3447
fd7c092e 3448static void crypt_status(struct dm_target *ti, status_type_t type,
86a3238c 3449 unsigned int status_flags, char *result, unsigned int maxlen)
1da177e4 3450{
5ebaee6d 3451 struct crypt_config *cc = ti->private;
86a3238c 3452 unsigned int i, sz = 0;
f3396c58 3453 int num_feature_args = 0;
1da177e4
LT
3454
3455 switch (type) {
3456 case STATUSTYPE_INFO:
3457 result[0] = '\0';
3458 break;
3459
3460 case STATUSTYPE_TABLE:
7dbcd137 3461 DMEMIT("%s ", cc->cipher_string);
1da177e4 3462
c538f6ec
OK
3463 if (cc->key_size > 0) {
3464 if (cc->key_string)
3465 DMEMIT(":%u:%s", cc->key_size, cc->key_string);
567dd8f3
MP
3466 else {
3467 for (i = 0; i < cc->key_size; i++) {
3468 DMEMIT("%c%c", hex2asc(cc->key[i] >> 4),
3469 hex2asc(cc->key[i] & 0xf));
3470 }
3471 }
c538f6ec 3472 } else
fd7c092e 3473 DMEMIT("-");
1da177e4 3474
4ee218cd
AM
3475 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
3476 cc->dev->name, (unsigned long long)cc->start);
772ae5f5 3477
f3396c58
MP
3478 num_feature_args += !!ti->num_discard_bios;
3479 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
0f5d8e6e 3480 num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
39d42fa9
IK
3481 num_feature_args += test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3482 num_feature_args += test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
ff3af92b 3483 num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
8f0009a2 3484 num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
ef43aa38
MB
3485 if (cc->on_disk_tag_size)
3486 num_feature_args++;
f3396c58
MP
3487 if (num_feature_args) {
3488 DMEMIT(" %d", num_feature_args);
3489 if (ti->num_discard_bios)
3490 DMEMIT(" allow_discards");
3491 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3492 DMEMIT(" same_cpu_crypt");
0f5d8e6e
MP
3493 if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
3494 DMEMIT(" submit_from_crypt_cpus");
39d42fa9
IK
3495 if (test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags))
3496 DMEMIT(" no_read_workqueue");
3497 if (test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))
3498 DMEMIT(" no_write_workqueue");
ef43aa38
MB
3499 if (cc->on_disk_tag_size)
3500 DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
8f0009a2
MB
3501 if (cc->sector_size != (1 << SECTOR_SHIFT))
3502 DMEMIT(" sector_size:%d", cc->sector_size);
3503 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
3504 DMEMIT(" iv_large_sectors");
f3396c58 3505 }
8ec45662
TS
3506 break;
3507
3508 case STATUSTYPE_IMA:
3509 DMEMIT_TARGET_NAME_VERSION(ti->type);
3510 DMEMIT(",allow_discards=%c", ti->num_discard_bios ? 'y' : 'n');
3511 DMEMIT(",same_cpu_crypt=%c", test_bit(DM_CRYPT_SAME_CPU, &cc->flags) ? 'y' : 'n');
3512 DMEMIT(",submit_from_crypt_cpus=%c", test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags) ?
3513 'y' : 'n');
3514 DMEMIT(",no_read_workqueue=%c", test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags) ?
3515 'y' : 'n');
3516 DMEMIT(",no_write_workqueue=%c", test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags) ?
3517 'y' : 'n');
3518 DMEMIT(",iv_large_sectors=%c", test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags) ?
3519 'y' : 'n');
772ae5f5 3520
8ec45662
TS
3521 if (cc->on_disk_tag_size)
3522 DMEMIT(",integrity_tag_size=%u,cipher_auth=%s",
3523 cc->on_disk_tag_size, cc->cipher_auth);
3524 if (cc->sector_size != (1 << SECTOR_SHIFT))
3525 DMEMIT(",sector_size=%d", cc->sector_size);
3526 if (cc->cipher_string)
3527 DMEMIT(",cipher_string=%s", cc->cipher_string);
3528
3529 DMEMIT(",key_size=%u", cc->key_size);
3530 DMEMIT(",key_parts=%u", cc->key_parts);
3531 DMEMIT(",key_extra_size=%u", cc->key_extra_size);
3532 DMEMIT(",key_mac_size=%u", cc->key_mac_size);
3533 DMEMIT(";");
1da177e4
LT
3534 break;
3535 }
1da177e4
LT
3536}
3537
e48d4bbf
MB
3538static void crypt_postsuspend(struct dm_target *ti)
3539{
3540 struct crypt_config *cc = ti->private;
3541
3542 set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3543}
3544
3545static int crypt_preresume(struct dm_target *ti)
3546{
3547 struct crypt_config *cc = ti->private;
3548
3549 if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
3550 DMERR("aborting resume - crypt key is not set.");
3551 return -EAGAIN;
3552 }
3553
3554 return 0;
3555}
3556
3557static void crypt_resume(struct dm_target *ti)
3558{
3559 struct crypt_config *cc = ti->private;
3560
3561 clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3562}
3563
3564/* Message interface
3565 * key set <key>
3566 * key wipe
3567 */
86a3238c
HM
3568static int crypt_message(struct dm_target *ti, unsigned int argc, char **argv,
3569 char *result, unsigned int maxlen)
e48d4bbf
MB
3570{
3571 struct crypt_config *cc = ti->private;
c538f6ec 3572 int key_size, ret = -EINVAL;
e48d4bbf
MB
3573
3574 if (argc < 2)
3575 goto error;
3576
498f0103 3577 if (!strcasecmp(argv[0], "key")) {
e48d4bbf
MB
3578 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
3579 DMWARN("not suspended during key manipulation.");
3580 return -EINVAL;
3581 }
498f0103 3582 if (argc == 3 && !strcasecmp(argv[1], "set")) {
c538f6ec
OK
3583 /* The key size may not be changed. */
3584 key_size = get_key_size(&argv[2]);
3585 if (key_size < 0 || cc->key_size != key_size) {
3586 memset(argv[2], '0', strlen(argv[2]));
3587 return -EINVAL;
3588 }
3589
542da317
MB
3590 ret = crypt_set_key(cc, argv[2]);
3591 if (ret)
3592 return ret;
3593 if (cc->iv_gen_ops && cc->iv_gen_ops->init)
3594 ret = cc->iv_gen_ops->init(cc);
dc94902b
OK
3595 /* wipe the kernel key payload copy */
3596 if (cc->key_string)
3597 memset(cc->key, 0, cc->key_size * sizeof(u8));
542da317
MB
3598 return ret;
3599 }
4a52ffc7 3600 if (argc == 2 && !strcasecmp(argv[1], "wipe"))
e48d4bbf
MB
3601 return crypt_wipe_key(cc);
3602 }
3603
3604error:
3605 DMWARN("unrecognised message received.");
3606 return -EINVAL;
3607}
3608
af4874e0
MS
3609static int crypt_iterate_devices(struct dm_target *ti,
3610 iterate_devices_callout_fn fn, void *data)
3611{
3612 struct crypt_config *cc = ti->private;
3613
5dea271b 3614 return fn(ti, cc->dev, cc->start, ti->len, data);
af4874e0
MS
3615}
3616
586b286b
MS
3617static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
3618{
8f0009a2
MB
3619 struct crypt_config *cc = ti->private;
3620
586b286b
MS
3621 /*
3622 * Unfortunate constraint that is required to avoid the potential
3623 * for exceeding underlying device's max_segments limits -- due to
3624 * crypt_alloc_buffer() possibly allocating pages for the encryption
3625 * bio that are not as physically contiguous as the original bio.
3626 */
3627 limits->max_segment_size = PAGE_SIZE;
8f0009a2 3628
bc9e9cf0 3629 limits->logical_block_size =
86a3238c 3630 max_t(unsigned int, limits->logical_block_size, cc->sector_size);
bc9e9cf0 3631 limits->physical_block_size =
86a3238c
HM
3632 max_t(unsigned int, limits->physical_block_size, cc->sector_size);
3633 limits->io_min = max_t(unsigned int, limits->io_min, cc->sector_size);
86e4d3e8 3634 limits->dma_alignment = limits->logical_block_size - 1;
586b286b
MS
3635}
3636
1da177e4
LT
3637static struct target_type crypt_target = {
3638 .name = "crypt",
e5524e12 3639 .version = {1, 24, 0},
1da177e4
LT
3640 .module = THIS_MODULE,
3641 .ctr = crypt_ctr,
3642 .dtr = crypt_dtr,
8e225f04
DLM
3643 .features = DM_TARGET_ZONED_HM,
3644 .report_zones = crypt_report_zones,
1da177e4
LT
3645 .map = crypt_map,
3646 .status = crypt_status,
e48d4bbf
MB
3647 .postsuspend = crypt_postsuspend,
3648 .preresume = crypt_preresume,
3649 .resume = crypt_resume,
3650 .message = crypt_message,
af4874e0 3651 .iterate_devices = crypt_iterate_devices,
586b286b 3652 .io_hints = crypt_io_hints,
1da177e4
LT
3653};
3654
3655static int __init dm_crypt_init(void)
3656{
3657 int r;
3658
1da177e4 3659 r = dm_register_target(&crypt_target);
94f5e024 3660 if (r < 0)
72d94861 3661 DMERR("register failed %d", r);
1da177e4 3662
1da177e4
LT
3663 return r;
3664}
3665
3666static void __exit dm_crypt_exit(void)
3667{
10d3bd09 3668 dm_unregister_target(&crypt_target);
1da177e4
LT
3669}
3670
3671module_init(dm_crypt_init);
3672module_exit(dm_crypt_exit);
3673
bf14299f 3674MODULE_AUTHOR("Jana Saout <jana@saout.de>");
1da177e4
LT
3675MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
3676MODULE_LICENSE("GPL");