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