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