sys/dev/disk/dm: Check if target has registered handlers
[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         table_en->target_config = NULL;
769         dm_pdev_decr(priv->pdev);
770
771         /*
772          * Clean up the crypt config
773          *
774          * Overwrite the private information before freeing memory to
775          * avoid leaking it.
776          */
777         if (priv->status_str) {
778                 dmtc_crypto_clear(priv->status_str, strlen(priv->status_str));
779                 kfree(priv->status_str, M_DMCRYPT);
780                 crypto_freesession(priv->crypto_sid);
781         }
782
783         if ((priv->ivgen) && (priv->ivgen->dtor != NULL)) {
784                 priv->ivgen->dtor(priv, priv->ivgen_priv);
785         }
786
787         /* Destroy mpipes */
788         dmtc_destroy_mpipe(priv);
789
790         dmtc_crypto_clear(priv, sizeof(dm_target_crypt_config_t));
791         kfree(priv, M_DMCRYPT);
792
793         return 0;
794 }
795
796 /************************************************************************
797  *                      STRATEGY SUPPORT FUNCTIONS                      *
798  ************************************************************************
799  *
800  * READ PATH:   doio -> bio_read_done -> crypto_work -> crypto_cb_read_done
801  * WRITE PATH:  crypto_work -> crypto_cb_write_done -> doio -> bio_write_done
802  */
803
804 /*
805  * Wrapper around crypto_dispatch() to match dispatch_t type
806  */
807 static void
808 dmtc_crypto_dispatch(void *arg)
809 {
810         struct cryptop *crp;
811
812         crp = (struct cryptop *)arg;
813         KKASSERT(crp != NULL);
814         KTR_LOG(dmcrypt_crypto_dispatch, crp);
815         crypto_dispatch(crp);
816 }
817
818 /*
819  * Start IO operation, called from dmstrategy routine.
820  */
821 static int
822 dm_target_crypt_strategy(dm_table_entry_t *table_en, struct buf *bp)
823 {
824         struct bio *bio;
825
826         dm_target_crypt_config_t *priv;
827         priv = table_en->target_config;
828
829         /* Get rid of stuff we can't really handle */
830         if ((bp->b_cmd == BUF_CMD_READ) || (bp->b_cmd == BUF_CMD_WRITE)) {
831                 if (((bp->b_bcount % DEV_BSIZE) != 0) || (bp->b_bcount == 0)) {
832                         kprintf("dm_target_crypt_strategy: can't really "
833                                 "handle bp->b_bcount = %d\n",
834                                 bp->b_bcount);
835                         bp->b_error = EINVAL;
836                         bp->b_flags |= B_ERROR | B_INVAL;
837                         biodone(&bp->b_bio1);
838                         return 0;
839                 }
840         }
841
842         KTR_LOG(dmcrypt_crypt_strategy, bp->b_cmd, bp);
843
844         switch (bp->b_cmd) {
845         case BUF_CMD_READ:
846                 bio = push_bio(&bp->b_bio1);
847                 bio->bio_offset = bp->b_bio1.bio_offset +
848                                   priv->block_offset * DEV_BSIZE;
849                 bio->bio_caller_info1.ptr = priv;
850                 bio->bio_done = dmtc_bio_read_done;
851                 vn_strategy(priv->pdev->pdev_vnode, bio);
852                 break;
853         case BUF_CMD_WRITE:
854                 bio = push_bio(&bp->b_bio1);
855                 bio->bio_offset = bp->b_bio1.bio_offset +
856                                   priv->block_offset * DEV_BSIZE;
857                 bio->bio_caller_info1.ptr = priv;
858                 dmtc_crypto_write_start(priv, bio);
859                 break;
860         default:
861                 vn_strategy(priv->pdev->pdev_vnode, &bp->b_bio1);
862                 break;
863         }
864         return 0;
865 }
866
867 /*
868  * STRATEGY READ PATH PART 1/3 (after read BIO completes)
869  */
870 static void
871 dmtc_bio_read_done(struct bio *bio)
872 {
873         struct bio *obio;
874
875         dm_target_crypt_config_t *priv;
876
877         KTR_LOG(dmcrypt_bio_read_done, bio->bio_buf);
878
879         /*
880          * If a read error occurs we shortcut the operation, otherwise
881          * go on to stage 2.
882          */
883         if (bio->bio_buf->b_flags & B_ERROR) {
884                 obio = pop_bio(bio);
885                 biodone(obio);
886         } else {
887                 priv = bio->bio_caller_info1.ptr;
888                 dmtc_crypto_read_start(priv, bio);
889         }
890 }
891
892 /*
893  * STRATEGY READ PATH PART 2/3
894  */
895 static void
896 dmtc_crypto_read_retry(void *arg1, void *arg2)
897 {
898         dm_target_crypt_config_t *priv = arg1;
899         struct bio *bio = arg2;
900
901         dmtc_crypto_read_start(priv, bio);
902 }
903
904 static void
905 dmtc_crypto_read_start(dm_target_crypt_config_t *priv, struct bio *bio)
906 {
907         struct dmtc_helper *dmtc;
908         struct cryptodesc *crd;
909         struct cryptop *crp;
910         int i, bytes, sectors, sz;
911         off_t isector;
912         u_char *ptr, *space;
913
914         /*
915          * Note: b_resid no good after read I/O, it will be 0, use
916          *       b_bcount.
917          */
918         bytes = bio->bio_buf->b_bcount;
919         isector = bio->bio_offset / DEV_BSIZE;  /* ivgen salt base? */
920         sectors = bytes / DEV_BSIZE;            /* Number of sectors */
921         sz = sectors * (sizeof(*crp) + sizeof(*crd));
922
923         /*
924          * For reads with bogus page we can't decrypt in place as stuff
925          * can get ripped out from under us.
926          *
927          * XXX actually it looks like we can, and in any case the initial
928          * read already completed and threw crypted data into the buffer
929          * cache buffer.  Disable for now.
930          */
931         space = mpipe_alloc_callback(&priv->read_mpipe,
932                                      dmtc_crypto_read_retry, priv, bio);
933         if (space == NULL)
934                 return;
935
936         dmtc = (struct dmtc_helper *)space;
937         dmtc->free_addr = space;
938         space += sizeof(struct dmtc_helper);
939         dmtc->orig_buf = NULL;
940         dmtc->data_buf = bio->bio_buf->b_data;
941         dmtc->priv = priv;
942         bio->bio_caller_info2.ptr = dmtc;
943         bio->bio_buf->b_error = 0;
944
945         /*
946          * Load crypto descriptors (crp/crd loop)
947          */
948         bzero(space, sz);
949         ptr = space;
950         bio->bio_caller_info3.value = sectors;
951         cpu_sfence();
952 #if 0
953         kprintf("Read, bytes = %d (b_bcount), "
954                 "sectors = %d (bio = %p, b_cmd = %d)\n",
955                 bytes, sectors, bio, bio->bio_buf->b_cmd);
956 #endif
957         for (i = 0; i < sectors; i++) {
958                 crp = (struct cryptop *)ptr;
959                 ptr += sizeof(*crp);
960                 crd = (struct cryptodesc *)ptr;
961                 ptr += sizeof (*crd);
962
963                 crp->crp_buf = dmtc->data_buf + i * DEV_BSIZE;
964
965                 crp->crp_sid = priv->crypto_sid;
966                 crp->crp_ilen = crp->crp_olen = DEV_BSIZE;
967
968                 crp->crp_opaque = (void *)bio;
969
970                 crp->crp_callback = dmtc_crypto_cb_read_done;
971                 crp->crp_desc = crd;
972                 crp->crp_etype = 0;
973                 crp->crp_flags = CRYPTO_F_CBIFSYNC | CRYPTO_F_REL |
974                                  CRYPTO_F_BATCH;
975
976                 crd->crd_alg = priv->crypto_alg;
977 #if 0
978                 crd->crd_key = (caddr_t)priv->crypto_key;
979                 crd->crd_klen = priv->crypto_klen;
980 #endif
981
982                 crd->crd_skip = 0;
983                 crd->crd_len = DEV_BSIZE /* XXX */;
984                 crd->crd_flags = CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
985                 crd->crd_next = NULL;
986
987                 crd->crd_flags &= ~CRD_F_ENCRYPT;
988
989                 KTR_LOG(dmcrypt_crypto_read_start, crp, bio->bio_buf, i,
990                     sectors);
991
992                 /*
993                  * Note: last argument is used to generate salt(?) and is
994                  *       a 64 bit value, but the original code passed an
995                  *       int.  Changing it now will break pre-existing
996                  *       crypt volumes.
997                  */
998                 priv->ivgen->gen_iv(priv, crd->crd_iv, sizeof(crd->crd_iv),
999                                     isector + i, crp);
1000         }
1001 }
1002
1003 /*
1004  * STRATEGY READ PATH PART 3/3
1005  */
1006 static int
1007 dmtc_crypto_cb_read_done(struct cryptop *crp)
1008 {
1009         struct dmtc_helper *dmtc;
1010         struct bio *bio, *obio;
1011         int n;
1012
1013         if (crp->crp_etype == EAGAIN)
1014                 return crypto_dispatch(crp);
1015
1016         bio = (struct bio *)crp->crp_opaque;
1017         KKASSERT(bio != NULL);
1018
1019         /*
1020          * Cumulative error
1021          */
1022         if (crp->crp_etype) {
1023                 kprintf("dm_target_crypt: dmtc_crypto_cb_read_done "
1024                         "crp_etype = %d\n",
1025                         crp->crp_etype);
1026                 bio->bio_buf->b_error = crp->crp_etype;
1027         }
1028
1029         /*
1030          * On the last chunk of the decryption we do any required copybacks
1031          * and complete the I/O.
1032          */
1033         n = atomic_fetchadd_int(&bio->bio_caller_info3.value, -1);
1034 #if 0
1035         kprintf("dmtc_crypto_cb_read_done %p, n = %d\n", bio, n);
1036 #endif
1037
1038         KTR_LOG(dmcrypt_crypto_cb_read_done, crp, bio->bio_buf, n);
1039
1040         if (n == 1) {
1041                 /*
1042                  * For the B_HASBOGUS case we didn't decrypt in place,
1043                  * so we need to copy stuff back into the buf.
1044                  *
1045                  * (disabled for now).
1046                  */
1047                 dmtc = bio->bio_caller_info2.ptr;
1048                 if (bio->bio_buf->b_error) {
1049                         bio->bio_buf->b_flags |= B_ERROR;
1050                 }
1051 #if 0
1052                 else if (bio->bio_buf->b_flags & B_HASBOGUS) {
1053                         memcpy(bio->bio_buf->b_data, dmtc->data_buf,
1054                                bio->bio_buf->b_bcount);
1055                 }
1056 #endif
1057                 mpipe_free(&dmtc->priv->read_mpipe, dmtc->free_addr);
1058                 obio = pop_bio(bio);
1059                 biodone(obio);
1060         }
1061         return 0;
1062 }
1063 /* END OF STRATEGY READ SECTION */
1064
1065 /*
1066  * STRATEGY WRITE PATH PART 1/3
1067  */
1068
1069 static void
1070 dmtc_crypto_write_retry(void *arg1, void *arg2)
1071 {
1072         dm_target_crypt_config_t *priv = arg1;
1073         struct bio *bio = arg2;
1074
1075         KTR_LOG(dmcrypt_crypto_write_retry, bio->bio_buf);
1076
1077         dmtc_crypto_write_start(priv, bio);
1078 }
1079
1080 static void
1081 dmtc_crypto_write_start(dm_target_crypt_config_t *priv, struct bio *bio)
1082 {
1083         struct dmtc_helper *dmtc;
1084         struct cryptodesc *crd;
1085         struct cryptop *crp;
1086         int i, bytes, sectors, sz;
1087         off_t isector;
1088         u_char *ptr, *space;
1089
1090         /*
1091          * Use b_bcount for consistency
1092          */
1093         bytes = bio->bio_buf->b_bcount;
1094
1095         isector = bio->bio_offset / DEV_BSIZE;  /* ivgen salt base? */
1096         sectors = bytes / DEV_BSIZE;            /* Number of sectors */
1097         sz = sectors * (sizeof(*crp) + sizeof(*crd));
1098
1099         /*
1100          * For writes and reads with bogus page don't decrypt in place.
1101          */
1102         space = mpipe_alloc_callback(&priv->write_mpipe,
1103                                      dmtc_crypto_write_retry, priv, bio);
1104         if (space == NULL)
1105                 return;
1106
1107         dmtc = (struct dmtc_helper *)space;
1108         dmtc->free_addr = space;
1109         space += sizeof(struct dmtc_helper);
1110         memcpy(space + sz, bio->bio_buf->b_data, bytes);
1111
1112         bio->bio_caller_info2.ptr = dmtc;
1113         bio->bio_buf->b_error = 0;
1114
1115         dmtc->orig_buf = bio->bio_buf->b_data;
1116         dmtc->data_buf = space + sz;
1117         dmtc->priv = priv;
1118
1119         /*
1120          * Load crypto descriptors (crp/crd loop)
1121          */
1122         bzero(space, sz);
1123         ptr = space;
1124         bio->bio_caller_info3.value = sectors;
1125         cpu_sfence();
1126 #if 0
1127         kprintf("Write, bytes = %d (b_bcount), "
1128                 "sectors = %d (bio = %p, b_cmd = %d)\n",
1129                 bytes, sectors, bio, bio->bio_buf->b_cmd);
1130 #endif
1131         for (i = 0; i < sectors; i++) {
1132                 crp = (struct cryptop *)ptr;
1133                 ptr += sizeof(*crp);
1134                 crd = (struct cryptodesc *)ptr;
1135                 ptr += sizeof (*crd);
1136
1137                 crp->crp_buf = dmtc->data_buf + i * DEV_BSIZE;
1138
1139                 crp->crp_sid = priv->crypto_sid;
1140                 crp->crp_ilen = crp->crp_olen = DEV_BSIZE;
1141
1142                 crp->crp_opaque = (void *)bio;
1143
1144                 crp->crp_callback = dmtc_crypto_cb_write_done;
1145                 crp->crp_desc = crd;
1146                 crp->crp_etype = 0;
1147                 crp->crp_flags = CRYPTO_F_CBIFSYNC | CRYPTO_F_REL |
1148                                  CRYPTO_F_BATCH;
1149
1150                 crd->crd_alg = priv->crypto_alg;
1151 #if 0
1152                 crd->crd_key = (caddr_t)priv->crypto_key;
1153                 crd->crd_klen = priv->crypto_klen;
1154 #endif
1155
1156                 crd->crd_skip = 0;
1157                 crd->crd_len = DEV_BSIZE /* XXX */;
1158                 crd->crd_flags = CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
1159                 crd->crd_next = NULL;
1160
1161                 crd->crd_flags |= CRD_F_ENCRYPT;
1162
1163                 /*
1164                  * Note: last argument is used to generate salt(?) and is
1165                  *       a 64 bit value, but the original code passed an
1166                  *       int.  Changing it now will break pre-existing
1167                  *       crypt volumes.
1168                  */
1169
1170                 KTR_LOG(dmcrypt_crypto_write_start, crp, bio->bio_buf,
1171                     i, sectors);
1172
1173                 priv->ivgen->gen_iv(priv, crd->crd_iv, sizeof(crd->crd_iv),
1174                                     isector + i, crp);
1175         }
1176 }
1177
1178 /*
1179  * STRATEGY WRITE PATH PART 2/3
1180  */
1181 static int
1182 dmtc_crypto_cb_write_done(struct cryptop *crp)
1183 {
1184         struct dmtc_helper *dmtc;
1185         dm_target_crypt_config_t *priv;
1186         struct bio *bio, *obio;
1187         int n;
1188
1189         if (crp->crp_etype == EAGAIN)
1190                 return crypto_dispatch(crp);
1191
1192         bio = (struct bio *)crp->crp_opaque;
1193         KKASSERT(bio != NULL);
1194
1195         /*
1196          * Cumulative error
1197          */
1198         if (crp->crp_etype != 0) {
1199                 kprintf("dm_target_crypt: dmtc_crypto_cb_write_done "
1200                         "crp_etype = %d\n",
1201                 crp->crp_etype);
1202                 bio->bio_buf->b_error = crp->crp_etype;
1203         }
1204
1205         /*
1206          * On the last chunk of the encryption we issue the write
1207          */
1208         n = atomic_fetchadd_int(&bio->bio_caller_info3.value, -1);
1209 #if 0
1210         kprintf("dmtc_crypto_cb_write_done %p, n = %d\n", bio, n);
1211 #endif
1212
1213         KTR_LOG(dmcrypt_crypto_cb_write_done, crp, bio->bio_buf, n);
1214
1215         if (n == 1) {
1216                 dmtc = bio->bio_caller_info2.ptr;
1217                 priv = (dm_target_crypt_config_t *)bio->bio_caller_info1.ptr;
1218
1219                 if (bio->bio_buf->b_error) {
1220                         bio->bio_buf->b_flags |= B_ERROR;
1221                         mpipe_free(&dmtc->priv->write_mpipe, dmtc->free_addr);
1222                         obio = pop_bio(bio);
1223                         biodone(obio);
1224                 } else {
1225                         dmtc->orig_buf = bio->bio_buf->b_data;
1226                         bio->bio_buf->b_data = dmtc->data_buf;
1227                         bio->bio_done = dmtc_bio_write_done;
1228                         vn_strategy(priv->pdev->pdev_vnode, bio);
1229                 }
1230         }
1231         return 0;
1232 }
1233
1234 /*
1235  * STRATEGY WRITE PATH PART 3/3
1236  */
1237 static void
1238 dmtc_bio_write_done(struct bio *bio)
1239 {
1240         struct dmtc_helper *dmtc;
1241         struct bio *obio;
1242
1243         dmtc = bio->bio_caller_info2.ptr;
1244         bio->bio_buf->b_data = dmtc->orig_buf;
1245         mpipe_free(&dmtc->priv->write_mpipe, dmtc->free_addr);
1246
1247         KTR_LOG(dmcrypt_bio_write_done, bio->bio_buf);
1248
1249         obio = pop_bio(bio);
1250         biodone(obio);
1251 }
1252 /* END OF STRATEGY WRITE SECTION */
1253
1254
1255
1256 /* DUMPING MAGIC */
1257
1258 extern int tsleep_crypto_dump;
1259
1260 static int
1261 dm_target_crypt_dump(dm_table_entry_t *table_en, void *data, size_t length, off_t offset)
1262 {
1263         static struct dmtc_dump_helper dump_helper;
1264         dm_target_crypt_config_t *priv;
1265         int id;
1266         static int first_call = 1;
1267
1268         priv = table_en->target_config;
1269
1270         if (first_call) {
1271                 first_call = 0;
1272                 dump_reactivate_cpus();
1273         }
1274
1275         /* Magically enable tsleep */
1276         tsleep_crypto_dump = 1;
1277         id = 0;
1278
1279         /*
1280          * 0 length means flush buffers and return
1281          */
1282         if (length == 0) {
1283                 if (priv->pdev->pdev_vnode->v_rdev == NULL) {
1284                         tsleep_crypto_dump = 0;
1285                         return ENXIO;
1286                 }
1287                 dev_ddump(priv->pdev->pdev_vnode->v_rdev,
1288                     data, 0, offset, 0);
1289                 tsleep_crypto_dump = 0;
1290                 return 0;
1291         }
1292
1293         bzero(&dump_helper, sizeof(dump_helper));
1294         dump_helper.priv = priv;
1295         dump_helper.data = data;
1296         dump_helper.length = length;
1297         dump_helper.offset = offset +
1298             priv->block_offset * DEV_BSIZE;
1299         dump_helper.ident = &id;
1300         dmtc_crypto_dump_start(priv, &dump_helper);
1301
1302         /*
1303          * Hackery to make stuff appear synchronous. The crypto callback will
1304          * set id to 1 and call wakeup on it. If the request completed
1305          * synchronously, id will be 1 and we won't bother to sleep. If not,
1306          * the crypto request will complete asynchronously and we sleep until
1307          * it's done.
1308          */
1309         if (id == 0)
1310                 tsleep(&dump_helper, 0, "cryptdump", 0);
1311
1312         dump_helper.offset = dm_pdev_correct_dump_offset(priv->pdev,
1313             dump_helper.offset);
1314
1315         dev_ddump(priv->pdev->pdev_vnode->v_rdev,
1316             dump_helper.space, 0, dump_helper.offset,
1317             dump_helper.length);
1318
1319         tsleep_crypto_dump = 0;
1320         return 0;
1321 }
1322
1323 static void
1324 dmtc_crypto_dump_start(dm_target_crypt_config_t *priv, struct dmtc_dump_helper *dump_helper)
1325 {
1326         struct cryptodesc *crd;
1327         struct cryptop *crp;
1328         int i, bytes, sectors;
1329         off_t isector;
1330
1331         bytes = dump_helper->length;
1332
1333         isector = dump_helper->offset / DEV_BSIZE;      /* ivgen salt base? */
1334         sectors = bytes / DEV_BSIZE;            /* Number of sectors */
1335         dump_helper->sectors = sectors;
1336 #if 0
1337         kprintf("Dump, bytes = %d, "
1338                 "sectors = %d, LENGTH=%zu\n", bytes, sectors, dump_helper->length);
1339 #endif
1340         KKASSERT(dump_helper->length <= 65536);
1341
1342         memcpy(dump_helper->space, dump_helper->data, bytes);
1343
1344         cpu_sfence();
1345
1346         for (i = 0; i < sectors; i++) {
1347                 crp = &dump_helper->crp[i];
1348                 crd = &dump_helper->crd[i];
1349
1350                 crp->crp_buf = dump_helper->space + i * DEV_BSIZE;
1351
1352                 crp->crp_sid = priv->crypto_sid;
1353                 crp->crp_ilen = crp->crp_olen = DEV_BSIZE;
1354
1355                 crp->crp_opaque = (void *)dump_helper;
1356
1357                 crp->crp_callback = dmtc_crypto_cb_dump_done;
1358                 crp->crp_desc = crd;
1359                 crp->crp_etype = 0;
1360                 crp->crp_flags = CRYPTO_F_CBIFSYNC | CRYPTO_F_REL |
1361                                  CRYPTO_F_BATCH;
1362
1363                 crd->crd_alg = priv->crypto_alg;
1364
1365                 crd->crd_skip = 0;
1366                 crd->crd_len = DEV_BSIZE /* XXX */;
1367                 crd->crd_flags = CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
1368                 crd->crd_next = NULL;
1369
1370                 crd->crd_flags |= CRD_F_ENCRYPT;
1371
1372                 /*
1373                  * Note: last argument is used to generate salt(?) and is
1374                  *       a 64 bit value, but the original code passed an
1375                  *       int.  Changing it now will break pre-existing
1376                  *       crypt volumes.
1377                  */
1378                 priv->ivgen->gen_iv(priv, crd->crd_iv, sizeof(crd->crd_iv),
1379                                     isector + i, crp);
1380         }
1381 }
1382
1383 static int
1384 dmtc_crypto_cb_dump_done(struct cryptop *crp)
1385 {
1386         struct dmtc_dump_helper *dump_helper;
1387         int n;
1388
1389         if (crp->crp_etype == EAGAIN)
1390                 return crypto_dispatch(crp);
1391
1392         dump_helper = (struct dmtc_dump_helper *)crp->crp_opaque;
1393         KKASSERT(dump_helper != NULL);
1394
1395         if (crp->crp_etype != 0) {
1396                 kprintf("dm_target_crypt: dmtc_crypto_cb_dump_done "
1397                         "crp_etype = %d\n",
1398                 crp->crp_etype);
1399                 return crp->crp_etype;
1400         }
1401
1402         /*
1403          * On the last chunk of the encryption we return control
1404          */
1405         n = atomic_fetchadd_int(&dump_helper->sectors, -1);
1406
1407         if (n == 1) {
1408                 atomic_add_int(dump_helper->ident, 1);
1409                 wakeup(dump_helper);
1410         }
1411
1412         return 0;
1413 }
1414
1415 static int
1416 dmtc_mod_handler(module_t mod, int type, void *unused)
1417 {
1418         dm_target_t *dmt = NULL;
1419         int err = 0;
1420
1421         switch (type) {
1422         case MOD_LOAD:
1423                 if ((dmt = dm_target_lookup("crypt")) != NULL) {
1424                         dm_target_unbusy(dmt);
1425                         return EEXIST;
1426                 }
1427                 dmt = dm_target_alloc("crypt");
1428                 dmt->version[0] = 1;
1429                 dmt->version[1] = 6;
1430                 dmt->version[2] = 0;
1431                 strlcpy(dmt->name, "crypt", DM_MAX_TYPE_NAME);
1432                 dmt->init = &dm_target_crypt_init;
1433                 dmt->destroy = &dm_target_crypt_destroy;
1434                 dmt->strategy = &dm_target_crypt_strategy;
1435                 dmt->table = &dm_target_crypt_table;
1436                 dmt->dump = &dm_target_crypt_dump;
1437
1438                 err = dm_target_insert(dmt);
1439                 if (!err)
1440                         kprintf("dm_target_crypt: Successfully initialized\n");
1441                 break;
1442
1443         case MOD_UNLOAD:
1444                 err = dm_target_rem("crypt");
1445                 if (err == 0) {
1446                         kprintf("dm_target_crypt: unloaded\n");
1447                 }
1448                 break;
1449
1450         default:
1451                 break;
1452         }
1453
1454         return err;
1455 }
1456
1457 DM_TARGET_MODULE(dm_target_crypt, dmtc_mod_handler);