75468c11a034ffc7e45c109be1ec6b5883d06f2e
[dragonfly.git] / sys / dev / disk / dm / targets / crypt / dm_target_crypt.c
1 /*
2  * Copyright (c) 2010 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Alex Hornung <ahornung@gmail.com>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 /*
36  * This file implements initial version of device-mapper crypt target.
37  */
38 #include <sys/types.h>
39 #include <sys/endian.h>
40
41 #include <sys/bio.h>
42 #include <sys/buf.h>
43 #include <sys/globaldata.h>
44 #include <sys/kerneldump.h>
45 #include <sys/malloc.h>
46 #include <sys/mpipe.h>
47 #include <sys/md5.h>
48 #include <sys/mutex2.h>
49 #include <sys/vnode.h>
50 #include <crypto/sha1.h>
51 #include <crypto/sha2/sha2.h>
52 #include <opencrypto/cryptodev.h>
53 #include <opencrypto/rmd160.h>
54 #include <machine/cpufunc.h>
55
56 #include <sys/ktr.h>
57
58 #include <dev/disk/dm/dm.h>
59 MALLOC_DEFINE(M_DMCRYPT, "dm_crypt", "Device Mapper Target Crypt");
60
61 KTR_INFO_MASTER(dmcrypt);
62
63 #if !defined(KTR_DMCRYPT)
64 #define KTR_DMCRYPT     KTR_ALL
65 #endif
66
67 KTR_INFO(KTR_DMCRYPT, dmcrypt, crypto_dispatch, 0,
68     "crypto_dispatch(%p)", struct cryptop *crp);
69 KTR_INFO(KTR_DMCRYPT, dmcrypt, crypt_strategy, 0,
70     "crypt_strategy(b_cmd = %d, bp = %p)", int cmd, struct buf *bp);
71 KTR_INFO(KTR_DMCRYPT, dmcrypt, crypto_write_start, 1,
72     "crypto_write_start(crp = %p, bp = %p, sector = %d/%d)",
73     struct cryptop *crp, struct buf *bp, int i, int sectors);
74 KTR_INFO(KTR_DMCRYPT, dmcrypt, crypto_cb_write_done, 1,
75     "crypto_cb_write_done(crp = %p, bp = %p, n = %d)",
76     struct cryptop *crp, struct buf *bp, int n);
77 KTR_INFO(KTR_DMCRYPT, dmcrypt, bio_write_done, 1,
78     "bio_write_done(bp = %p)", struct buf *bp);
79 KTR_INFO(KTR_DMCRYPT, dmcrypt, crypto_write_retry, 1,
80     "crypto_write_retry(crp = %p)", struct buf *bp);
81 KTR_INFO(KTR_DMCRYPT, dmcrypt, bio_read_done, 2,
82     "bio_read_done(bp = %p)", struct buf *bp);
83 KTR_INFO(KTR_DMCRYPT, dmcrypt, crypto_read_start, 2,
84     "crypto_read_start(crp = %p, bp = %p, sector = %d/%d)",
85     struct cryptop *crp, struct buf *bp, int i, int sectors);
86 KTR_INFO(KTR_DMCRYPT, dmcrypt, crypto_cb_read_done, 2,
87     "crypto_cb_read_done(crp = %p, bp = %p, n = %d)",
88     struct cryptop *crp, struct buf *bp, int n);
89
90 struct target_crypt_config;
91
92 typedef void dispatch_t(void *);
93 typedef void ivgen_t(struct target_crypt_config *, u_int8_t *, size_t, off_t,
94     void *);
95
96 typedef int ivgen_ctor_t(struct target_crypt_config *, char *, void **);
97 typedef int ivgen_dtor_t(struct target_crypt_config *, void *);
98
99 struct iv_generator {
100         const char      *name;
101         ivgen_ctor_t    *ctor;
102         ivgen_dtor_t    *dtor;
103         ivgen_t         *gen_iv;
104 };
105
106 struct essiv_ivgen_priv {
107         struct cryptoini        crypto_session;
108         struct objcache *crp_crd_cache;
109         u_int64_t       crypto_sid;
110         size_t          keyhash_len;
111         u_int8_t        crypto_keyhash[SHA512_DIGEST_LENGTH];
112 };
113
114 typedef struct target_crypt_config {
115         size_t  params_len;
116         dm_pdev_t *pdev;
117         char    *status_str;
118         int     crypto_alg;
119         int     crypto_klen;
120         u_int8_t        crypto_key[512>>3];
121
122         u_int64_t       crypto_sid;
123         u_int64_t       block_offset;
124         int64_t         iv_offset;
125         SHA512_CTX      essivsha512_ctx;
126
127         struct cryptoini        crypto_session;
128
129         struct iv_generator     *ivgen;
130         void    *ivgen_priv;
131
132         struct malloc_pipe      read_mpipe;
133         struct malloc_pipe      write_mpipe;
134 } dm_target_crypt_config_t;
135
136 struct dmtc_helper {
137         dm_target_crypt_config_t *priv;
138         caddr_t free_addr;
139         caddr_t orig_buf;
140         caddr_t data_buf;
141 };
142
143 struct dmtc_dump_helper {
144         dm_target_crypt_config_t *priv;
145         void *data;
146         size_t length;
147         off_t offset;
148
149         int sectors;
150         int *ident;
151
152         struct cryptodesc crd[128];
153         struct cryptop crp[128];
154         u_char space[65536];
155 };
156
157 #define DMTC_BUF_SIZE_WRITE \
158     MAXPHYS + sizeof(struct dmtc_helper) + \
159     MAXPHYS/DEV_BSIZE*(sizeof(struct cryptop) + sizeof(struct cryptodesc))
160 #define DMTC_BUF_SIZE_READ \
161     sizeof(struct dmtc_helper) + \
162     MAXPHYS/DEV_BSIZE*(sizeof(struct cryptop) + sizeof(struct cryptodesc))
163
164 static void dmtc_crypto_dispatch(void *arg);
165 static void dmtc_crypto_dump_start(dm_target_crypt_config_t *priv,
166                                 struct dmtc_dump_helper *dump_helper);
167 static void dmtc_crypto_read_start(dm_target_crypt_config_t *priv,
168                                 struct bio *bio);
169 static void dmtc_crypto_write_start(dm_target_crypt_config_t *priv,
170                                 struct bio *bio);
171 static void dmtc_bio_read_done(struct bio *bio);
172 static void dmtc_bio_write_done(struct bio *bio);
173 static int dmtc_crypto_cb_dump_done(struct cryptop *crp);
174 static int dmtc_crypto_cb_read_done(struct cryptop *crp);
175 static int dmtc_crypto_cb_write_done(struct cryptop *crp);
176
177 static ivgen_ctor_t     essiv_ivgen_ctor;
178 static ivgen_dtor_t     essiv_ivgen_dtor;
179 static ivgen_t          essiv_ivgen;
180 static ivgen_t          plain_ivgen;
181 static ivgen_t          plain64_ivgen;
182
183 static struct iv_generator ivgens[] = {
184         { .name = "essiv", .ctor = essiv_ivgen_ctor, .dtor = essiv_ivgen_dtor,
185             .gen_iv = essiv_ivgen },
186         { .name = "plain", .ctor = NULL, .dtor = NULL, .gen_iv = plain_ivgen },
187         { .name = "plain64", .ctor = NULL, .dtor = NULL, .gen_iv = plain64_ivgen },
188         { NULL, NULL, NULL, NULL }
189 };
190
191 struct objcache_malloc_args essiv_ivgen_malloc_args = {
192                 2*sizeof(void *) + (sizeof(struct cryptodesc) +
193                 sizeof(struct cryptop)), M_DMCRYPT };
194
195 static void
196 dmtc_init_mpipe(struct target_crypt_config *priv)
197 {
198         int nmax;
199
200         nmax = (physmem*2/1000*PAGE_SIZE)/(DMTC_BUF_SIZE_WRITE + DMTC_BUF_SIZE_READ) + 1;
201
202         if (nmax < 2)
203                 nmax = 2;
204
205         kprintf("dm_target_crypt: Setting min/max mpipe buffers: %d/%d\n", 2, nmax);
206
207         mpipe_init(&priv->write_mpipe, M_DMCRYPT, DMTC_BUF_SIZE_WRITE,
208                    2, nmax, MPF_NOZERO | MPF_CALLBACK, NULL, NULL, NULL);
209         mpipe_init(&priv->read_mpipe, M_DMCRYPT, DMTC_BUF_SIZE_READ,
210                    2, nmax, MPF_NOZERO | MPF_CALLBACK, NULL, NULL, NULL);
211 }
212
213 static void
214 dmtc_destroy_mpipe(struct target_crypt_config *priv)
215 {
216         mpipe_done(&priv->write_mpipe);
217         mpipe_done(&priv->read_mpipe);
218 }
219
220 /*
221  * Overwrite private information (in buf) to avoid leaking it
222  */
223 static void
224 dmtc_crypto_clear(void *buf, size_t len)
225 {
226         memset(buf, 0xFF, len);
227         bzero(buf, len);
228 }
229
230 /*
231  * ESSIV IV Generator Routines
232  */
233 static int
234 essiv_ivgen_ctor(struct target_crypt_config *priv, char *iv_hash, void **p_ivpriv)
235 {
236         struct essiv_ivgen_priv *ivpriv;
237         u_int8_t crypto_keyhash[SHA512_DIGEST_LENGTH];
238         unsigned int klen, hashlen;
239         int error;
240
241         klen = (priv->crypto_klen >> 3);
242
243         if (iv_hash == NULL)
244                 return EINVAL;
245
246         if (!strcmp(iv_hash, "sha1")) {
247                 SHA1_CTX ctx;
248
249                 hashlen = SHA1_RESULTLEN;
250                 SHA1Init(&ctx);
251                 SHA1Update(&ctx, priv->crypto_key, klen);
252                 SHA1Final(crypto_keyhash, &ctx);
253         } else if (!strcmp(iv_hash, "sha256")) {
254                 SHA256_CTX ctx;
255
256                 hashlen = SHA256_DIGEST_LENGTH;
257                 SHA256_Init(&ctx);
258                 SHA256_Update(&ctx, priv->crypto_key, klen);
259                 SHA256_Final(crypto_keyhash, &ctx);
260         } else if (!strcmp(iv_hash, "sha384")) {
261                 SHA384_CTX ctx;
262
263                 hashlen = SHA384_DIGEST_LENGTH;
264                 SHA384_Init(&ctx);
265                 SHA384_Update(&ctx, priv->crypto_key, klen);
266                 SHA384_Final(crypto_keyhash, &ctx);
267         } else if (!strcmp(iv_hash, "sha512")) {
268                 SHA512_CTX ctx;
269
270                 hashlen = SHA512_DIGEST_LENGTH;
271                 SHA512_Init(&ctx);
272                 SHA512_Update(&ctx, priv->crypto_key, klen);
273                 SHA512_Final(crypto_keyhash, &ctx);
274         } else if (!strcmp(iv_hash, "md5")) {
275                 MD5_CTX ctx;
276
277                 hashlen = MD5_DIGEST_LENGTH;
278                 MD5Init(&ctx);
279                 MD5Update(&ctx, priv->crypto_key, klen);
280                 MD5Final(crypto_keyhash, &ctx);
281         } else if (!strcmp(iv_hash, "rmd160") ||
282                    !strcmp(iv_hash, "ripemd160")) {
283                 RMD160_CTX ctx;
284
285                 hashlen = 160/8;
286                 RMD160Init(&ctx);
287                 RMD160Update(&ctx, priv->crypto_key, klen);
288                 RMD160Final(crypto_keyhash, &ctx);
289         } else {
290                 return EINVAL;
291         }
292
293         /* Convert hashlen to bits */
294         hashlen <<= 3;
295
296         ivpriv = kmalloc(sizeof(struct essiv_ivgen_priv), M_DMCRYPT,
297             M_WAITOK | M_ZERO);
298         memcpy(ivpriv->crypto_keyhash, crypto_keyhash, sizeof(crypto_keyhash));
299         ivpriv->keyhash_len = sizeof(crypto_keyhash);
300         dmtc_crypto_clear(crypto_keyhash, sizeof(crypto_keyhash));
301
302         ivpriv->crypto_session.cri_alg = priv->crypto_alg;
303         ivpriv->crypto_session.cri_key = (u_int8_t *)ivpriv->crypto_keyhash;
304         ivpriv->crypto_session.cri_klen = hashlen;
305         ivpriv->crypto_session.cri_mlen = 0;
306         ivpriv->crypto_session.cri_next = NULL;
307
308         /*
309          * XXX: in principle we also need to check if the block size of the
310          *      cipher is a valid iv size for the block cipher.
311          */
312
313         error = crypto_newsession(&ivpriv->crypto_sid,
314                                   &ivpriv->crypto_session,
315                                   CRYPTOCAP_F_SOFTWARE | CRYPTOCAP_F_HARDWARE);
316         if (error) {
317                 kprintf("dm_target_crypt: Error during crypto_newsession "
318                         "for essiv_ivgen, error = %d\n",
319                         error);
320                 dmtc_crypto_clear(ivpriv->crypto_keyhash, ivpriv->keyhash_len);
321                 kfree(ivpriv, M_DMCRYPT);
322                 return ENOTSUP;
323         }
324
325         ivpriv->crp_crd_cache = objcache_create(
326             "dmcrypt-essiv-cache", 0, 0,
327             NULL, NULL, NULL,
328             objcache_malloc_alloc,
329             objcache_malloc_free,
330             &essiv_ivgen_malloc_args );
331
332         *p_ivpriv = ivpriv;
333         return 0;
334 }
335
336 static int
337 essiv_ivgen_dtor(struct target_crypt_config *priv, void *arg)
338 {
339         struct essiv_ivgen_priv *ivpriv;
340
341         ivpriv = (struct essiv_ivgen_priv *)arg;
342         KKASSERT(ivpriv != NULL);
343
344         crypto_freesession(ivpriv->crypto_sid);
345
346         objcache_destroy(ivpriv->crp_crd_cache);
347
348         dmtc_crypto_clear(ivpriv->crypto_keyhash, ivpriv->keyhash_len);
349         kfree(ivpriv, M_DMCRYPT);
350
351         return 0;
352 }
353
354 static int
355 essiv_ivgen_done(struct cryptop *crp)
356 {
357         struct essiv_ivgen_priv *ivpriv;
358         void *free_addr;
359         void *opaque;
360
361
362         if (crp->crp_etype == EAGAIN)
363                 return crypto_dispatch(crp);
364
365         if (crp->crp_etype != 0) {
366                 kprintf("dm_target_crypt: essiv_ivgen_done, "
367                         "crp->crp_etype = %d\n", crp->crp_etype);
368         }
369
370         free_addr = crp->crp_opaque;
371         /*
372          * In-memory structure is:
373          * |  ivpriv  |  opaque  |     crp     |      crd      |
374          * | (void *) | (void *) |   (cryptop) |  (cryptodesc) |
375          */
376         ivpriv = *((struct essiv_ivgen_priv **)crp->crp_opaque);
377         crp->crp_opaque += sizeof(void *);
378         opaque = *((void **)crp->crp_opaque);
379
380         objcache_put(ivpriv->crp_crd_cache, free_addr);
381         dmtc_crypto_dispatch(opaque);
382         return 0;
383 }
384
385 static void
386 essiv_ivgen(dm_target_crypt_config_t *priv, u_int8_t *iv,
387             size_t iv_len, off_t sector, void *opaque)
388 {
389         struct essiv_ivgen_priv *ivpriv;
390         struct cryptodesc *crd;
391         struct cryptop *crp;
392         caddr_t space, alloc_addr;
393         int error;
394
395         ivpriv = priv->ivgen_priv;
396         KKASSERT(ivpriv != NULL);
397
398         /*
399          * In-memory structure is:
400          * |  ivpriv  |  opaque  |     crp     |      crd      |
401          * | (void *) | (void *) |   (cryptop) |  (cryptodesc) |
402          */
403         alloc_addr = space = objcache_get(ivpriv->crp_crd_cache, M_WAITOK);
404         *((struct essiv_ivgen_priv **)space) = ivpriv;
405         space += sizeof(void *);
406         *((void **)space) = opaque;
407         space += sizeof(void *);
408         crp = (struct cryptop *)space;
409         space += sizeof(struct cryptop);
410         crd = (struct cryptodesc *)space;
411
412         bzero(iv, iv_len);
413         bzero(crd, sizeof(struct cryptodesc));
414         bzero(crp, sizeof(struct cryptop));
415         *((off_t *)iv) = htole64(sector + priv->iv_offset);
416         crp->crp_buf = (caddr_t)iv;
417
418         crp->crp_sid = ivpriv->crypto_sid;
419         crp->crp_ilen = crp->crp_olen = iv_len;
420
421         crp->crp_opaque = alloc_addr;
422
423         crp->crp_callback = essiv_ivgen_done;
424
425         crp->crp_desc = crd;
426         crp->crp_etype = 0;
427         crp->crp_flags = CRYPTO_F_CBIFSYNC | CRYPTO_F_REL | CRYPTO_F_BATCH;
428
429         crd->crd_alg = priv->crypto_alg;
430 #if 0
431         crd->crd_key = (caddr_t)priv->crypto_keyhash;
432         crd->crd_klen = priv->crypto_klen;
433 #endif
434
435         bzero(crd->crd_iv, sizeof(crd->crd_iv));
436
437         crd->crd_skip = 0;
438         crd->crd_len = iv_len;
439         crd->crd_flags = CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
440         crd->crd_flags |= CRD_F_ENCRYPT;
441         crd->crd_next = NULL;
442
443         error = crypto_dispatch(crp);
444         if (error)
445                 kprintf("dm_target_crypt: essiv_ivgen, error = %d\n", error);
446 }
447
448
449 static void
450 plain_ivgen(dm_target_crypt_config_t *priv, u_int8_t *iv,
451             size_t iv_len, off_t sector, void *opaque)
452 {
453         bzero(iv, iv_len);
454         *((uint32_t *)iv) = htole32((uint32_t)(sector + priv->iv_offset));
455         dmtc_crypto_dispatch(opaque);
456 }
457
458 static void
459 plain64_ivgen(dm_target_crypt_config_t *priv, u_int8_t *iv,
460     size_t iv_len, off_t sector, void *opaque)
461 {
462         bzero(iv, iv_len);
463         *((uint64_t *)iv) = htole64((uint64_t)(sector + priv->iv_offset));
464         dmtc_crypto_dispatch(opaque);
465 }
466
467 #if 0
468 static void
469 geli_ivgen(dm_target_crypt_config_t *priv, u_int8_t *iv,
470            size_t iv_len, off_t sector, void *opaque)
471 {
472
473         SHA512_CTX      ctx512;
474         u_int8_t        md[SHA512_DIGEST_LENGTH]; /* Max. Digest Size */
475
476         memcpy(&ctx512, &priv->essivsha512_ctx, sizeof(SHA512_CTX));
477         SHA512_Update(&ctx512, (u_int8_t*)&sector, sizeof(off_t));
478         SHA512_Final(md, &ctx512);
479
480         memcpy(iv, md, iv_len);
481         dmtc_crypto_dispatch(opaque);
482 }
483 #endif
484
485 /*
486  * Init function called from dm_table_load_ioctl.
487  * cryptsetup actually passes us this:
488  * aes-cbc-essiv:sha256 7997f8af... 0 /dev/ad0s0a 8
489  */
490 static int
491 hex2key(char *hex, size_t key_len, u_int8_t *key)
492 {
493         char hex_buf[3];
494         size_t key_idx;
495
496         hex_buf[2] = 0;
497         for (key_idx = 0; key_idx < key_len; ++key_idx) {
498                 hex_buf[0] = *hex++;
499                 hex_buf[1] = *hex++;
500                 key[key_idx] = (u_int8_t)strtoul(hex_buf, NULL, 16);
501         }
502         hex_buf[0] = 0;
503         hex_buf[1] = 0;
504
505         return 0;
506 }
507
508 static int
509 dm_target_crypt_init(dm_table_entry_t *table_en, int argc, char **argv)
510 {
511         dm_target_crypt_config_t *priv;
512         size_t len;
513         char *crypto_alg, *crypto_mode, *iv_mode, *iv_opt, *key, *dev;
514         char *status_str;
515         int i, klen, error;
516         uint64_t iv_offset, block_offset;
517
518         if (argc != 5) {
519                 kprintf("dm_target_crypt: not enough arguments, "
520                         "need exactly 5\n");
521                 return EINVAL;
522         }
523
524         len = 0;
525         for (i = 0; i < argc; i++) {
526                 len += strlen(argv[i]);
527                 len++;
528         }
529         /* len is strlen() of input string +1 */
530         status_str = kmalloc(len, M_DMCRYPT, M_WAITOK);
531
532         crypto_alg = strsep(&argv[0], "-");
533         crypto_mode = strsep(&argv[0], "-");
534         iv_opt = strsep(&argv[0], "-");
535         iv_mode = strsep(&iv_opt, ":");
536         key = argv[1];
537         iv_offset = strtouq(argv[2], NULL, 0);
538         dev = argv[3];
539         block_offset = strtouq(argv[4], NULL, 0);
540         /* bits / 8 = bytes, 1 byte = 2 hexa chars, so << 2 */
541         klen = strlen(key) << 2;
542
543 #if 0
544         kprintf("dm_target_crypt - new: dev=%s, crypto_alg=%s, crypto_mode=%s, "
545                 "iv_mode=%s, iv_opt=%s, key=%s, iv_offset=%ju, "
546                 "block_offset=%ju\n",
547                 dev, crypto_alg, crypto_mode, iv_mode, iv_opt, key, iv_offset,
548                 block_offset);
549 #endif
550
551         priv = kmalloc(sizeof(dm_target_crypt_config_t), M_DMCRYPT, M_WAITOK);
552
553         /* Insert dmp to global pdev list */
554         if ((priv->pdev = dm_pdev_insert(dev)) == NULL) {
555                 kprintf("dm_target_crypt: dm_pdev_insert failed\n");
556                 kfree(status_str, M_DMCRYPT);
557                 return ENOENT;
558         }
559
560         /*
561          * This code checks for valid combinations of algorithm and mode.
562          * Currently supported options are:
563          *
564          * *-cbc
565          * aes-xts
566          * twofish-xts
567          * serpent-xts
568          */
569         if ((strcmp(crypto_mode, "cbc") != 0) &&
570             !((strcmp(crypto_mode, "xts") == 0) &&
571             ((strcmp(crypto_alg, "aes") == 0) ||
572             (strcmp(crypto_alg, "twofish") == 0) ||
573             (strcmp(crypto_alg, "serpent") == 0))))
574         {
575                 kprintf("dm_target_crypt: only support 'cbc' chaining mode,"
576                     " aes-xts, twofish-xts and serpent-xts, "
577                     "invalid mode '%s-%s'\n",
578                     crypto_alg, crypto_mode);
579                 goto notsup;
580         }
581
582         if (!strcmp(crypto_alg, "aes")) {
583                 if (!strcmp(crypto_mode, "xts")) {
584                         priv->crypto_alg = CRYPTO_AES_XTS;
585                         if (klen != 256 && klen != 512)
586                                 goto notsup;
587                 } else if (!strcmp(crypto_mode, "cbc")) {
588                         priv->crypto_alg = CRYPTO_AES_CBC;
589                         if (klen != 128 && klen != 192 && klen != 256)
590                                 goto notsup;
591                 } else {
592                         goto notsup;
593                 }
594                 priv->crypto_klen = klen;
595         } else if (!strcmp(crypto_alg, "twofish")) {
596                 if (!strcmp(crypto_mode, "xts")) {
597                         priv->crypto_alg = CRYPTO_TWOFISH_XTS;
598                         if (klen != 256 && klen != 512)
599                                 goto notsup;
600                 } else if (!strcmp(crypto_mode, "cbc")) {
601                         priv->crypto_alg = CRYPTO_TWOFISH_CBC;
602                         if (klen != 128 && klen != 192 && klen != 256)
603                                 goto notsup;
604                 } else {
605                         goto notsup;
606                 }
607                 priv->crypto_klen = klen;
608         } else if (!strcmp(crypto_alg, "serpent")) {
609                 if (!strcmp(crypto_mode, "xts")) {
610                         priv->crypto_alg = CRYPTO_SERPENT_XTS;
611                         if (klen != 256 && klen != 512)
612                                 goto notsup;
613                 } else if (!strcmp(crypto_mode, "cbc")) {
614                         priv->crypto_alg = CRYPTO_SERPENT_CBC;
615                         if (klen != 128 && klen != 192 && klen != 256)
616                                 goto notsup;
617                 } else {
618                         goto notsup;
619                 }
620                 priv->crypto_klen = klen;
621         } else if (!strcmp(crypto_alg, "blowfish")) {
622                 priv->crypto_alg = CRYPTO_BLF_CBC;
623                 if (klen < 128 || klen > 448 || (klen % 8) != 0)
624                         goto notsup;
625                 priv->crypto_klen = klen;
626         } else if (!strcmp(crypto_alg, "3des") ||
627                    !strncmp(crypto_alg, "des3", 4)) {
628                 priv->crypto_alg = CRYPTO_3DES_CBC;
629                 if (klen != 168)
630                         goto notsup;
631                 priv->crypto_klen = 168;
632         } else if (!strcmp(crypto_alg, "camellia")) {
633                 priv->crypto_alg = CRYPTO_CAMELLIA_CBC;
634                 if (klen != 128 && klen != 192 && klen != 256)
635                         goto notsup;
636                 priv->crypto_klen = klen;
637         } else if (!strcmp(crypto_alg, "skipjack")) {
638                 priv->crypto_alg = CRYPTO_SKIPJACK_CBC;
639                 if (klen != 80)
640                         goto notsup;
641                 priv->crypto_klen = 80;
642         } else if (!strcmp(crypto_alg, "cast5")) {
643                 priv->crypto_alg = CRYPTO_CAST_CBC;
644                 if (klen != 128)
645                         goto notsup;
646                 priv->crypto_klen = 128;
647         } else if (!strcmp(crypto_alg, "null")) {
648                 priv->crypto_alg = CRYPTO_NULL_CBC;
649                 if (klen != 128)
650                         goto notsup;
651                 priv->crypto_klen = 128;
652         } else {
653                 kprintf("dm_target_crypt: Unsupported crypto algorithm: %s\n",
654                         crypto_alg);
655                 goto notsup;
656         }
657
658         /* Save length of param string */
659         priv->params_len = len;
660         priv->block_offset = block_offset;
661         priv->iv_offset = iv_offset - block_offset;
662
663         dm_table_add_deps(table_en, priv->pdev);
664
665         dm_table_init_target(table_en, DM_CRYPTO_DEV, priv);
666
667         error = hex2key(key, priv->crypto_klen >> 3,
668                         (u_int8_t *)priv->crypto_key);
669
670         if (error) {
671                 kprintf("dm_target_crypt: hex2key failed, "
672                         "invalid key format\n");
673                 goto notsup;
674         }
675
676         /* Handle cmd */
677         for(i = 0; ivgens[i].name != NULL; i++) {
678                 if (!strcmp(iv_mode, ivgens[i].name))
679                         break;
680         }
681
682         if (ivgens[i].name == NULL) {
683                 kprintf("dm_target_crypt: iv_mode='%s' unsupported\n",
684                         iv_mode);
685                 goto notsup;
686         }
687
688         /* Call our ivgen constructor */
689         if (ivgens[i].ctor != NULL) {
690                 error = ivgens[i].ctor(priv, iv_opt,
691                     &priv->ivgen_priv);
692                 if (error) {
693                         kprintf("dm_target_crypt: ctor for '%s' failed\n",
694                             ivgens[i].name);
695                         goto notsup;
696                 }
697         }
698
699         priv->ivgen = &ivgens[i];
700
701         priv->crypto_session.cri_alg = priv->crypto_alg;
702         priv->crypto_session.cri_key = (u_int8_t *)priv->crypto_key;
703         priv->crypto_session.cri_klen = priv->crypto_klen;
704         priv->crypto_session.cri_mlen = 0;
705         priv->crypto_session.cri_next = NULL;
706
707         error = crypto_newsession(&priv->crypto_sid,
708                                   &priv->crypto_session,
709                                   CRYPTOCAP_F_SOFTWARE | CRYPTOCAP_F_HARDWARE);
710         if (error) {
711                 kprintf("dm_target_crypt: Error during crypto_newsession, "
712                         "error = %d\n",
713                         error);
714                 goto notsup;
715         }
716
717         memset(key, '0', strlen(key));
718         if (iv_opt) {
719                 ksprintf(status_str, "%s-%s-%s:%s %s %ju %s %ju",
720                     crypto_alg, crypto_mode, iv_mode, iv_opt,
721                     key, iv_offset, dev, block_offset);
722         } else {
723                 ksprintf(status_str, "%s-%s-%s %s %ju %s %ju",
724                     crypto_alg, crypto_mode, iv_mode,
725                     key, iv_offset, dev, block_offset);
726         }
727         priv->status_str = status_str;
728
729         /* Initialize mpipes */
730         dmtc_init_mpipe(priv);
731
732         return 0;
733
734 notsup:
735         kprintf("dm_target_crypt: ENOTSUP\n");
736         kfree(status_str, M_DMCRYPT);
737         return ENOTSUP;
738 }
739
740 /* Table routine called to get params string. */
741 static char *
742 dm_target_crypt_table(void *target_config)
743 {
744         dm_target_crypt_config_t *priv;
745         char *params;
746
747         priv = target_config;
748
749         params = dm_alloc_string(DM_MAX_PARAMS_SIZE);
750
751         ksnprintf(params, DM_MAX_PARAMS_SIZE, "%s",
752             priv->status_str);
753
754         return params;
755 }
756
757 static int
758 dm_target_crypt_destroy(dm_table_entry_t *table_en)
759 {
760         dm_target_crypt_config_t *priv;
761
762         /*
763          * Disconnect the crypt config before unbusying the target.
764          */
765         priv = table_en->target_config;
766         if (priv == NULL)
767                 return 0;
768         dm_pdev_decr(priv->pdev);
769
770         /*
771          * Clean up the crypt config
772          *
773          * Overwrite the private information before freeing memory to
774          * avoid leaking it.
775          */
776         if (priv->status_str) {
777                 dmtc_crypto_clear(priv->status_str, strlen(priv->status_str));
778                 kfree(priv->status_str, M_DMCRYPT);
779                 crypto_freesession(priv->crypto_sid);
780         }
781
782         if ((priv->ivgen) && (priv->ivgen->dtor != NULL)) {
783                 priv->ivgen->dtor(priv, priv->ivgen_priv);
784         }
785
786         /* Destroy mpipes */
787         dmtc_destroy_mpipe(priv);
788
789         dmtc_crypto_clear(priv, sizeof(dm_target_crypt_config_t));
790         kfree(priv, M_DMCRYPT);
791
792         return 0;
793 }
794
795 /************************************************************************
796  *                      STRATEGY SUPPORT FUNCTIONS                      *
797  ************************************************************************
798  *
799  * READ PATH:   doio -> bio_read_done -> crypto_work -> crypto_cb_read_done
800  * WRITE PATH:  crypto_work -> crypto_cb_write_done -> doio -> bio_write_done
801  */
802
803 /*
804  * Wrapper around crypto_dispatch() to match dispatch_t type
805  */
806 static void
807 dmtc_crypto_dispatch(void *arg)
808 {
809         struct cryptop *crp;
810
811         crp = (struct cryptop *)arg;
812         KKASSERT(crp != NULL);
813         KTR_LOG(dmcrypt_crypto_dispatch, crp);
814         crypto_dispatch(crp);
815 }
816
817 /*
818  * Start IO operation, called from dmstrategy routine.
819  */
820 static int
821 dm_target_crypt_strategy(dm_table_entry_t *table_en, struct buf *bp)
822 {
823         struct bio *bio;
824
825         dm_target_crypt_config_t *priv;
826         priv = table_en->target_config;
827
828         /* Get rid of stuff we can't really handle */
829         if ((bp->b_cmd == BUF_CMD_READ) || (bp->b_cmd == BUF_CMD_WRITE)) {
830                 if (((bp->b_bcount % DEV_BSIZE) != 0) || (bp->b_bcount == 0)) {
831                         kprintf("dm_target_crypt_strategy: can't really "
832                                 "handle bp->b_bcount = %d\n",
833                                 bp->b_bcount);
834                         bp->b_error = EINVAL;
835                         bp->b_flags |= B_ERROR | B_INVAL;
836                         biodone(&bp->b_bio1);
837                         return 0;
838                 }
839         }
840
841         KTR_LOG(dmcrypt_crypt_strategy, bp->b_cmd, bp);
842
843         switch (bp->b_cmd) {
844         case BUF_CMD_READ:
845                 bio = push_bio(&bp->b_bio1);
846                 bio->bio_offset = bp->b_bio1.bio_offset +
847                                   priv->block_offset * DEV_BSIZE;
848                 bio->bio_caller_info1.ptr = priv;
849                 bio->bio_done = dmtc_bio_read_done;
850                 vn_strategy(priv->pdev->pdev_vnode, bio);
851                 break;
852         case BUF_CMD_WRITE:
853                 bio = push_bio(&bp->b_bio1);
854                 bio->bio_offset = bp->b_bio1.bio_offset +
855                                   priv->block_offset * DEV_BSIZE;
856                 bio->bio_caller_info1.ptr = priv;
857                 dmtc_crypto_write_start(priv, bio);
858                 break;
859         default:
860                 vn_strategy(priv->pdev->pdev_vnode, &bp->b_bio1);
861                 break;
862         }
863         return 0;
864 }
865
866 /*
867  * STRATEGY READ PATH PART 1/3 (after read BIO completes)
868  */
869 static void
870 dmtc_bio_read_done(struct bio *bio)
871 {
872         struct bio *obio;
873
874         dm_target_crypt_config_t *priv;
875
876         KTR_LOG(dmcrypt_bio_read_done, bio->bio_buf);
877
878         /*
879          * If a read error occurs we shortcut the operation, otherwise
880          * go on to stage 2.
881          */
882         if (bio->bio_buf->b_flags & B_ERROR) {
883                 obio = pop_bio(bio);
884                 biodone(obio);
885         } else {
886                 priv = bio->bio_caller_info1.ptr;
887                 dmtc_crypto_read_start(priv, bio);
888         }
889 }
890
891 /*
892  * STRATEGY READ PATH PART 2/3
893  */
894 static void
895 dmtc_crypto_read_retry(void *arg1, void *arg2)
896 {
897         dm_target_crypt_config_t *priv = arg1;
898         struct bio *bio = arg2;
899
900         dmtc_crypto_read_start(priv, bio);
901 }
902
903 static void
904 dmtc_crypto_read_start(dm_target_crypt_config_t *priv, struct bio *bio)
905 {
906         struct dmtc_helper *dmtc;
907         struct cryptodesc *crd;
908         struct cryptop *crp;
909         int i, bytes, sectors, sz;
910         off_t isector;
911         u_char *ptr, *space;
912
913         /*
914          * Note: b_resid no good after read I/O, it will be 0, use
915          *       b_bcount.
916          */
917         bytes = bio->bio_buf->b_bcount;
918         isector = bio->bio_offset / DEV_BSIZE;  /* ivgen salt base? */
919         sectors = bytes / DEV_BSIZE;            /* Number of sectors */
920         sz = sectors * (sizeof(*crp) + sizeof(*crd));
921
922         /*
923          * For reads with bogus page we can't decrypt in place as stuff
924          * can get ripped out from under us.
925          *
926          * XXX actually it looks like we can, and in any case the initial
927          * read already completed and threw crypted data into the buffer
928          * cache buffer.  Disable for now.
929          */
930         space = mpipe_alloc_callback(&priv->read_mpipe,
931                                      dmtc_crypto_read_retry, priv, bio);
932         if (space == NULL)
933                 return;
934
935         dmtc = (struct dmtc_helper *)space;
936         dmtc->free_addr = space;
937         space += sizeof(struct dmtc_helper);
938         dmtc->orig_buf = NULL;
939         dmtc->data_buf = bio->bio_buf->b_data;
940         dmtc->priv = priv;
941         bio->bio_caller_info2.ptr = dmtc;
942         bio->bio_buf->b_error = 0;
943
944         /*
945          * Load crypto descriptors (crp/crd loop)
946          */
947         bzero(space, sz);
948         ptr = space;
949         bio->bio_caller_info3.value = sectors;
950         cpu_sfence();
951 #if 0
952         kprintf("Read, bytes = %d (b_bcount), "
953                 "sectors = %d (bio = %p, b_cmd = %d)\n",
954                 bytes, sectors, bio, bio->bio_buf->b_cmd);
955 #endif
956         for (i = 0; i < sectors; i++) {
957                 crp = (struct cryptop *)ptr;
958                 ptr += sizeof(*crp);
959                 crd = (struct cryptodesc *)ptr;
960                 ptr += sizeof (*crd);
961
962                 crp->crp_buf = dmtc->data_buf + i * DEV_BSIZE;
963
964                 crp->crp_sid = priv->crypto_sid;
965                 crp->crp_ilen = crp->crp_olen = DEV_BSIZE;
966
967                 crp->crp_opaque = (void *)bio;
968
969                 crp->crp_callback = dmtc_crypto_cb_read_done;
970                 crp->crp_desc = crd;
971                 crp->crp_etype = 0;
972                 crp->crp_flags = CRYPTO_F_CBIFSYNC | CRYPTO_F_REL |
973                                  CRYPTO_F_BATCH;
974
975                 crd->crd_alg = priv->crypto_alg;
976 #if 0
977                 crd->crd_key = (caddr_t)priv->crypto_key;
978                 crd->crd_klen = priv->crypto_klen;
979 #endif
980
981                 crd->crd_skip = 0;
982                 crd->crd_len = DEV_BSIZE /* XXX */;
983                 crd->crd_flags = CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
984                 crd->crd_next = NULL;
985
986                 crd->crd_flags &= ~CRD_F_ENCRYPT;
987
988                 KTR_LOG(dmcrypt_crypto_read_start, crp, bio->bio_buf, i,
989                     sectors);
990
991                 /*
992                  * Note: last argument is used to generate salt(?) and is
993                  *       a 64 bit value, but the original code passed an
994                  *       int.  Changing it now will break pre-existing
995                  *       crypt volumes.
996                  */
997                 priv->ivgen->gen_iv(priv, crd->crd_iv, sizeof(crd->crd_iv),
998                                     isector + i, crp);
999         }
1000 }
1001
1002 /*
1003  * STRATEGY READ PATH PART 3/3
1004  */
1005 static int
1006 dmtc_crypto_cb_read_done(struct cryptop *crp)
1007 {
1008         struct dmtc_helper *dmtc;
1009         struct bio *bio, *obio;
1010         int n;
1011
1012         if (crp->crp_etype == EAGAIN)
1013                 return crypto_dispatch(crp);
1014
1015         bio = (struct bio *)crp->crp_opaque;
1016         KKASSERT(bio != NULL);
1017
1018         /*
1019          * Cumulative error
1020          */
1021         if (crp->crp_etype) {
1022                 kprintf("dm_target_crypt: dmtc_crypto_cb_read_done "
1023                         "crp_etype = %d\n",
1024                         crp->crp_etype);
1025                 bio->bio_buf->b_error = crp->crp_etype;
1026         }
1027
1028         /*
1029          * On the last chunk of the decryption we do any required copybacks
1030          * and complete the I/O.
1031          */
1032         n = atomic_fetchadd_int(&bio->bio_caller_info3.value, -1);
1033 #if 0
1034         kprintf("dmtc_crypto_cb_read_done %p, n = %d\n", bio, n);
1035 #endif
1036
1037         KTR_LOG(dmcrypt_crypto_cb_read_done, crp, bio->bio_buf, n);
1038
1039         if (n == 1) {
1040                 /*
1041                  * For the B_HASBOGUS case we didn't decrypt in place,
1042                  * so we need to copy stuff back into the buf.
1043                  *
1044                  * (disabled for now).
1045                  */
1046                 dmtc = bio->bio_caller_info2.ptr;
1047                 if (bio->bio_buf->b_error) {
1048                         bio->bio_buf->b_flags |= B_ERROR;
1049                 }
1050 #if 0
1051                 else if (bio->bio_buf->b_flags & B_HASBOGUS) {
1052                         memcpy(bio->bio_buf->b_data, dmtc->data_buf,
1053                                bio->bio_buf->b_bcount);
1054                 }
1055 #endif
1056                 mpipe_free(&dmtc->priv->read_mpipe, dmtc->free_addr);
1057                 obio = pop_bio(bio);
1058                 biodone(obio);
1059         }
1060         return 0;
1061 }
1062 /* END OF STRATEGY READ SECTION */
1063
1064 /*
1065  * STRATEGY WRITE PATH PART 1/3
1066  */
1067
1068 static void
1069 dmtc_crypto_write_retry(void *arg1, void *arg2)
1070 {
1071         dm_target_crypt_config_t *priv = arg1;
1072         struct bio *bio = arg2;
1073
1074         KTR_LOG(dmcrypt_crypto_write_retry, bio->bio_buf);
1075
1076         dmtc_crypto_write_start(priv, bio);
1077 }
1078
1079 static void
1080 dmtc_crypto_write_start(dm_target_crypt_config_t *priv, struct bio *bio)
1081 {
1082         struct dmtc_helper *dmtc;
1083         struct cryptodesc *crd;
1084         struct cryptop *crp;
1085         int i, bytes, sectors, sz;
1086         off_t isector;
1087         u_char *ptr, *space;
1088
1089         /*
1090          * Use b_bcount for consistency
1091          */
1092         bytes = bio->bio_buf->b_bcount;
1093
1094         isector = bio->bio_offset / DEV_BSIZE;  /* ivgen salt base? */
1095         sectors = bytes / DEV_BSIZE;            /* Number of sectors */
1096         sz = sectors * (sizeof(*crp) + sizeof(*crd));
1097
1098         /*
1099          * For writes and reads with bogus page don't decrypt in place.
1100          */
1101         space = mpipe_alloc_callback(&priv->write_mpipe,
1102                                      dmtc_crypto_write_retry, priv, bio);
1103         if (space == NULL)
1104                 return;
1105
1106         dmtc = (struct dmtc_helper *)space;
1107         dmtc->free_addr = space;
1108         space += sizeof(struct dmtc_helper);
1109         memcpy(space + sz, bio->bio_buf->b_data, bytes);
1110
1111         bio->bio_caller_info2.ptr = dmtc;
1112         bio->bio_buf->b_error = 0;
1113
1114         dmtc->orig_buf = bio->bio_buf->b_data;
1115         dmtc->data_buf = space + sz;
1116         dmtc->priv = priv;
1117
1118         /*
1119          * Load crypto descriptors (crp/crd loop)
1120          */
1121         bzero(space, sz);
1122         ptr = space;
1123         bio->bio_caller_info3.value = sectors;
1124         cpu_sfence();
1125 #if 0
1126         kprintf("Write, bytes = %d (b_bcount), "
1127                 "sectors = %d (bio = %p, b_cmd = %d)\n",
1128                 bytes, sectors, bio, bio->bio_buf->b_cmd);
1129 #endif
1130         for (i = 0; i < sectors; i++) {
1131                 crp = (struct cryptop *)ptr;
1132                 ptr += sizeof(*crp);
1133                 crd = (struct cryptodesc *)ptr;
1134                 ptr += sizeof (*crd);
1135
1136                 crp->crp_buf = dmtc->data_buf + i * DEV_BSIZE;
1137
1138                 crp->crp_sid = priv->crypto_sid;
1139                 crp->crp_ilen = crp->crp_olen = DEV_BSIZE;
1140
1141                 crp->crp_opaque = (void *)bio;
1142
1143                 crp->crp_callback = dmtc_crypto_cb_write_done;
1144                 crp->crp_desc = crd;
1145                 crp->crp_etype = 0;
1146                 crp->crp_flags = CRYPTO_F_CBIFSYNC | CRYPTO_F_REL |
1147                                  CRYPTO_F_BATCH;
1148
1149                 crd->crd_alg = priv->crypto_alg;
1150 #if 0
1151                 crd->crd_key = (caddr_t)priv->crypto_key;
1152                 crd->crd_klen = priv->crypto_klen;
1153 #endif
1154
1155                 crd->crd_skip = 0;
1156                 crd->crd_len = DEV_BSIZE /* XXX */;
1157                 crd->crd_flags = CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
1158                 crd->crd_next = NULL;
1159
1160                 crd->crd_flags |= CRD_F_ENCRYPT;
1161
1162                 /*
1163                  * Note: last argument is used to generate salt(?) and is
1164                  *       a 64 bit value, but the original code passed an
1165                  *       int.  Changing it now will break pre-existing
1166                  *       crypt volumes.
1167                  */
1168
1169                 KTR_LOG(dmcrypt_crypto_write_start, crp, bio->bio_buf,
1170                     i, sectors);
1171
1172                 priv->ivgen->gen_iv(priv, crd->crd_iv, sizeof(crd->crd_iv),
1173                                     isector + i, crp);
1174         }
1175 }
1176
1177 /*
1178  * STRATEGY WRITE PATH PART 2/3
1179  */
1180 static int
1181 dmtc_crypto_cb_write_done(struct cryptop *crp)
1182 {
1183         struct dmtc_helper *dmtc;
1184         dm_target_crypt_config_t *priv;
1185         struct bio *bio, *obio;
1186         int n;
1187
1188         if (crp->crp_etype == EAGAIN)
1189                 return crypto_dispatch(crp);
1190
1191         bio = (struct bio *)crp->crp_opaque;
1192         KKASSERT(bio != NULL);
1193
1194         /*
1195          * Cumulative error
1196          */
1197         if (crp->crp_etype != 0) {
1198                 kprintf("dm_target_crypt: dmtc_crypto_cb_write_done "
1199                         "crp_etype = %d\n",
1200                 crp->crp_etype);
1201                 bio->bio_buf->b_error = crp->crp_etype;
1202         }
1203
1204         /*
1205          * On the last chunk of the encryption we issue the write
1206          */
1207         n = atomic_fetchadd_int(&bio->bio_caller_info3.value, -1);
1208 #if 0
1209         kprintf("dmtc_crypto_cb_write_done %p, n = %d\n", bio, n);
1210 #endif
1211
1212         KTR_LOG(dmcrypt_crypto_cb_write_done, crp, bio->bio_buf, n);
1213
1214         if (n == 1) {
1215                 dmtc = bio->bio_caller_info2.ptr;
1216                 priv = (dm_target_crypt_config_t *)bio->bio_caller_info1.ptr;
1217
1218                 if (bio->bio_buf->b_error) {
1219                         bio->bio_buf->b_flags |= B_ERROR;
1220                         mpipe_free(&dmtc->priv->write_mpipe, dmtc->free_addr);
1221                         obio = pop_bio(bio);
1222                         biodone(obio);
1223                 } else {
1224                         dmtc->orig_buf = bio->bio_buf->b_data;
1225                         bio->bio_buf->b_data = dmtc->data_buf;
1226                         bio->bio_done = dmtc_bio_write_done;
1227                         vn_strategy(priv->pdev->pdev_vnode, bio);
1228                 }
1229         }
1230         return 0;
1231 }
1232
1233 /*
1234  * STRATEGY WRITE PATH PART 3/3
1235  */
1236 static void
1237 dmtc_bio_write_done(struct bio *bio)
1238 {
1239         struct dmtc_helper *dmtc;
1240         struct bio *obio;
1241
1242         dmtc = bio->bio_caller_info2.ptr;
1243         bio->bio_buf->b_data = dmtc->orig_buf;
1244         mpipe_free(&dmtc->priv->write_mpipe, dmtc->free_addr);
1245
1246         KTR_LOG(dmcrypt_bio_write_done, bio->bio_buf);
1247
1248         obio = pop_bio(bio);
1249         biodone(obio);
1250 }
1251 /* END OF STRATEGY WRITE SECTION */
1252
1253
1254
1255 /* DUMPING MAGIC */
1256
1257 extern int tsleep_crypto_dump;
1258
1259 static int
1260 dm_target_crypt_dump(dm_table_entry_t *table_en, void *data, size_t length, off_t offset)
1261 {
1262         static struct dmtc_dump_helper dump_helper;
1263         dm_target_crypt_config_t *priv;
1264         int id;
1265         static int first_call = 1;
1266
1267         priv = table_en->target_config;
1268
1269         if (first_call) {
1270                 first_call = 0;
1271                 dump_reactivate_cpus();
1272         }
1273
1274         /* Magically enable tsleep */
1275         tsleep_crypto_dump = 1;
1276         id = 0;
1277
1278         /*
1279          * 0 length means flush buffers and return
1280          */
1281         if (length == 0) {
1282                 if (priv->pdev->pdev_vnode->v_rdev == NULL) {
1283                         tsleep_crypto_dump = 0;
1284                         return ENXIO;
1285                 }
1286                 dev_ddump(priv->pdev->pdev_vnode->v_rdev,
1287                     data, 0, offset, 0);
1288                 tsleep_crypto_dump = 0;
1289                 return 0;
1290         }
1291
1292         bzero(&dump_helper, sizeof(dump_helper));
1293         dump_helper.priv = priv;
1294         dump_helper.data = data;
1295         dump_helper.length = length;
1296         dump_helper.offset = offset +
1297             priv->block_offset * DEV_BSIZE;
1298         dump_helper.ident = &id;
1299         dmtc_crypto_dump_start(priv, &dump_helper);
1300
1301         /*
1302          * Hackery to make stuff appear synchronous. The crypto callback will
1303          * set id to 1 and call wakeup on it. If the request completed
1304          * synchronously, id will be 1 and we won't bother to sleep. If not,
1305          * the crypto request will complete asynchronously and we sleep until
1306          * it's done.
1307          */
1308         if (id == 0)
1309                 tsleep(&dump_helper, 0, "cryptdump", 0);
1310
1311         dump_helper.offset = dm_pdev_correct_dump_offset(priv->pdev,
1312             dump_helper.offset);
1313
1314         dev_ddump(priv->pdev->pdev_vnode->v_rdev,
1315             dump_helper.space, 0, dump_helper.offset,
1316             dump_helper.length);
1317
1318         tsleep_crypto_dump = 0;
1319         return 0;
1320 }
1321
1322 static void
1323 dmtc_crypto_dump_start(dm_target_crypt_config_t *priv, struct dmtc_dump_helper *dump_helper)
1324 {
1325         struct cryptodesc *crd;
1326         struct cryptop *crp;
1327         int i, bytes, sectors;
1328         off_t isector;
1329
1330         bytes = dump_helper->length;
1331
1332         isector = dump_helper->offset / DEV_BSIZE;      /* ivgen salt base? */
1333         sectors = bytes / DEV_BSIZE;            /* Number of sectors */
1334         dump_helper->sectors = sectors;
1335 #if 0
1336         kprintf("Dump, bytes = %d, "
1337                 "sectors = %d, LENGTH=%zu\n", bytes, sectors, dump_helper->length);
1338 #endif
1339         KKASSERT(dump_helper->length <= 65536);
1340
1341         memcpy(dump_helper->space, dump_helper->data, bytes);
1342
1343         cpu_sfence();
1344
1345         for (i = 0; i < sectors; i++) {
1346                 crp = &dump_helper->crp[i];
1347                 crd = &dump_helper->crd[i];
1348
1349                 crp->crp_buf = dump_helper->space + i * DEV_BSIZE;
1350
1351                 crp->crp_sid = priv->crypto_sid;
1352                 crp->crp_ilen = crp->crp_olen = DEV_BSIZE;
1353
1354                 crp->crp_opaque = (void *)dump_helper;
1355
1356                 crp->crp_callback = dmtc_crypto_cb_dump_done;
1357                 crp->crp_desc = crd;
1358                 crp->crp_etype = 0;
1359                 crp->crp_flags = CRYPTO_F_CBIFSYNC | CRYPTO_F_REL |
1360                                  CRYPTO_F_BATCH;
1361
1362                 crd->crd_alg = priv->crypto_alg;
1363
1364                 crd->crd_skip = 0;
1365                 crd->crd_len = DEV_BSIZE /* XXX */;
1366                 crd->crd_flags = CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
1367                 crd->crd_next = NULL;
1368
1369                 crd->crd_flags |= CRD_F_ENCRYPT;
1370
1371                 /*
1372                  * Note: last argument is used to generate salt(?) and is
1373                  *       a 64 bit value, but the original code passed an
1374                  *       int.  Changing it now will break pre-existing
1375                  *       crypt volumes.
1376                  */
1377                 priv->ivgen->gen_iv(priv, crd->crd_iv, sizeof(crd->crd_iv),
1378                                     isector + i, crp);
1379         }
1380 }
1381
1382 static int
1383 dmtc_crypto_cb_dump_done(struct cryptop *crp)
1384 {
1385         struct dmtc_dump_helper *dump_helper;
1386         int n;
1387
1388         if (crp->crp_etype == EAGAIN)
1389                 return crypto_dispatch(crp);
1390
1391         dump_helper = (struct dmtc_dump_helper *)crp->crp_opaque;
1392         KKASSERT(dump_helper != NULL);
1393
1394         if (crp->crp_etype != 0) {
1395                 kprintf("dm_target_crypt: dmtc_crypto_cb_dump_done "
1396                         "crp_etype = %d\n",
1397                 crp->crp_etype);
1398                 return crp->crp_etype;
1399         }
1400
1401         /*
1402          * On the last chunk of the encryption we return control
1403          */
1404         n = atomic_fetchadd_int(&dump_helper->sectors, -1);
1405
1406         if (n == 1) {
1407                 atomic_add_int(dump_helper->ident, 1);
1408                 wakeup(dump_helper);
1409         }
1410
1411         return 0;
1412 }
1413
1414 static int
1415 dmtc_mod_handler(module_t mod, int type, void *unused)
1416 {
1417         dm_target_t *dmt = NULL;
1418         int err = 0;
1419
1420         switch (type) {
1421         case MOD_LOAD:
1422                 if ((dmt = dm_target_lookup("crypt")) != NULL) {
1423                         dm_target_unbusy(dmt);
1424                         return EEXIST;
1425                 }
1426                 dmt = dm_target_alloc("crypt");
1427                 dmt->version[0] = 1;
1428                 dmt->version[1] = 6;
1429                 dmt->version[2] = 0;
1430                 dmt->init = &dm_target_crypt_init;
1431                 dmt->destroy = &dm_target_crypt_destroy;
1432                 dmt->strategy = &dm_target_crypt_strategy;
1433                 dmt->table = &dm_target_crypt_table;
1434                 dmt->dump = &dm_target_crypt_dump;
1435
1436                 err = dm_target_insert(dmt);
1437                 if (!err)
1438                         kprintf("dm_target_crypt: Successfully initialized\n");
1439                 break;
1440
1441         case MOD_UNLOAD:
1442                 err = dm_target_remove("crypt");
1443                 if (err == 0) {
1444                         kprintf("dm_target_crypt: unloaded\n");
1445                 }
1446                 break;
1447
1448         default:
1449                 break;
1450         }
1451
1452         return err;
1453 }
1454
1455 DM_TARGET_MODULE(dm_target_crypt, dmtc_mod_handler);