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