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