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