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