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