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