Merge branch 'vendor/GCC44'
[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 | MPF_CALLBACK, NULL, NULL, NULL);
176         mpipe_init(&dmtc_read_mpipe, M_DMCRYPT, DMTC_BUF_SIZE_READ,
177                    2, nmax, MPF_NOZERO | MPF_CALLBACK, NULL, NULL, 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_retry(void *arg1, void *arg2)
856 {
857         dm_target_crypt_config_t *priv = arg1;
858         struct bio *bio = arg2;
859
860         dmtc_crypto_read_start(priv, bio);
861 }
862
863 static void
864 dmtc_crypto_read_start(dm_target_crypt_config_t *priv, struct bio *bio)
865 {
866         struct dmtc_helper *dmtc;
867         struct cryptodesc *crd;
868         struct cryptop *crp;
869         struct cryptoini *cri;
870         int i, bytes, sectors, sz;
871         off_t isector;
872         u_char *ptr, *space;
873
874         cri = &priv->crypto_session;
875
876         /*
877          * Note: b_resid no good after read I/O, it will be 0, use
878          *       b_bcount.
879          */
880         bytes = bio->bio_buf->b_bcount;
881         isector = bio->bio_offset / DEV_BSIZE;  /* ivgen salt base? */
882         sectors = bytes / DEV_BSIZE;            /* Number of sectors */
883         sz = sectors * (sizeof(*crp) + sizeof(*crd));
884
885         /*
886          * For reads with bogus page we can't decrypt in place as stuff
887          * can get ripped out from under us.
888          *
889          * XXX actually it looks like we can, and in any case the initial
890          * read already completed and threw crypted data into the buffer
891          * cache buffer.  Disable for now.
892          */
893         space = mpipe_alloc_callback(&dmtc_read_mpipe,
894                                      dmtc_crypto_read_retry, priv, bio);
895         if (space == NULL)
896                 return;
897
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         bio->bio_caller_info2.ptr = dmtc;
904         bio->bio_buf->b_error = 0;
905
906         /*
907          * Load crypto descriptors (crp/crd loop)
908          */
909         bzero(space, sz);
910         ptr = space;
911         bio->bio_caller_info3.value = sectors;
912         cpu_sfence();
913 #if 0
914         kprintf("Read, bytes = %d (b_bcount), "
915                 "sectors = %d (bio = %p, b_cmd = %d)\n",
916                 bytes, sectors, bio, bio->bio_buf->b_cmd);
917 #endif
918         for (i = 0; i < sectors; i++) {
919                 crp = (struct cryptop *)ptr;
920                 ptr += sizeof(*crp);
921                 crd = (struct cryptodesc *)ptr;
922                 ptr += sizeof (*crd);
923
924                 crp->crp_buf = dmtc->data_buf + i * DEV_BSIZE;
925
926                 crp->crp_sid = priv->crypto_sid;
927                 crp->crp_ilen = crp->crp_olen = DEV_BSIZE;
928
929                 crp->crp_opaque = (void *)bio;
930
931                 crp->crp_callback = dmtc_crypto_cb_read_done;
932                 crp->crp_desc = crd;
933                 crp->crp_etype = 0;
934                 crp->crp_flags = CRYPTO_F_CBIFSYNC | CRYPTO_F_REL |
935                                  CRYPTO_F_BATCH;
936
937                 crd->crd_alg = priv->crypto_alg;
938 #if 0
939                 crd->crd_key = (caddr_t)priv->crypto_key;
940                 crd->crd_klen = priv->crypto_klen;
941 #endif
942
943                 crd->crd_skip = 0;
944                 crd->crd_len = DEV_BSIZE /* XXX */;
945                 crd->crd_flags = CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
946                 crd->crd_next = NULL;
947
948                 crd->crd_flags &= ~CRD_F_ENCRYPT;
949
950                 /*
951                  * Note: last argument is used to generate salt(?) and is
952                  *       a 64 bit value, but the original code passed an
953                  *       int.  Changing it now will break pre-existing
954                  *       crypt volumes.
955                  */
956                 priv->ivgen->gen_iv(priv, crd->crd_iv, sizeof(crd->crd_iv),
957                                     isector + i, crp);
958         }
959 }
960
961 /*
962  * STRATEGY READ PATH PART 3/3
963  */
964 static int
965 dmtc_crypto_cb_read_done(struct cryptop *crp)
966 {
967         struct dmtc_helper *dmtc;
968         struct bio *bio, *obio;
969         int n;
970
971         if (crp->crp_etype == EAGAIN)
972                 return crypto_dispatch(crp);
973
974         bio = (struct bio *)crp->crp_opaque;
975         KKASSERT(bio != NULL);
976
977         /*
978          * Cumulative error
979          */
980         if (crp->crp_etype) {
981                 kprintf("dm_target_crypt: dmtc_crypto_cb_read_done "
982                         "crp_etype = %d\n",
983                         crp->crp_etype);
984                 bio->bio_buf->b_error = crp->crp_etype;
985         }
986
987         /*
988          * On the last chunk of the decryption we do any required copybacks
989          * and complete the I/O.
990          */
991         n = atomic_fetchadd_int(&bio->bio_caller_info3.value, -1);
992 #if 0
993         kprintf("dmtc_crypto_cb_read_done %p, n = %d\n", bio, n);
994 #endif
995
996         if (n == 1) {
997                 /*
998                  * For the B_HASBOGUS case we didn't decrypt in place,
999                  * so we need to copy stuff back into the buf.
1000                  *
1001                  * (disabled for now).
1002                  */
1003                 dmtc = bio->bio_caller_info2.ptr;
1004                 if (bio->bio_buf->b_error) {
1005                         bio->bio_buf->b_flags |= B_ERROR;
1006                 }
1007 #if 0
1008                 else if (bio->bio_buf->b_flags & B_HASBOGUS) {
1009                         memcpy(bio->bio_buf->b_data, dmtc->data_buf,
1010                                bio->bio_buf->b_bcount);
1011                 }
1012 #endif
1013                 mpipe_free(&dmtc_read_mpipe, dmtc->free_addr);
1014                 obio = pop_bio(bio);
1015                 biodone(obio);
1016         }
1017         return 0;
1018 }
1019 /* END OF STRATEGY READ SECTION */
1020
1021 /*
1022  * STRATEGY WRITE PATH PART 1/3
1023  */
1024
1025 static void
1026 dmtc_crypto_write_retry(void *arg1, void *arg2)
1027 {
1028         dm_target_crypt_config_t *priv = arg1;
1029         struct bio *bio = arg2;
1030
1031         dmtc_crypto_write_start(priv, bio);
1032 }
1033
1034 static void
1035 dmtc_crypto_write_start(dm_target_crypt_config_t *priv, struct bio *bio)
1036 {
1037         struct dmtc_helper *dmtc;
1038         struct cryptodesc *crd;
1039         struct cryptop *crp;
1040         struct cryptoini *cri;
1041         int i, bytes, sectors, sz;
1042         off_t isector;
1043         u_char *ptr, *space;
1044
1045         cri = &priv->crypto_session;
1046
1047         /*
1048          * Use b_bcount for consistency
1049          */
1050         bytes = bio->bio_buf->b_bcount;
1051
1052         isector = bio->bio_offset / DEV_BSIZE;  /* ivgen salt base? */
1053         sectors = bytes / DEV_BSIZE;            /* Number of sectors */
1054         sz = sectors * (sizeof(*crp) + sizeof(*crd));
1055
1056         /*
1057          * For writes and reads with bogus page don't decrypt in place.
1058          */
1059         space = mpipe_alloc_callback(&dmtc_write_mpipe,
1060                                      dmtc_crypto_write_retry, priv, bio);
1061         if (space == NULL)
1062                 return;
1063
1064         dmtc = (struct dmtc_helper *)space;
1065         dmtc->free_addr = space;
1066         space += sizeof(struct dmtc_helper);
1067         memcpy(space + sz, bio->bio_buf->b_data, bytes);
1068
1069         bio->bio_caller_info2.ptr = dmtc;
1070         bio->bio_buf->b_error = 0;
1071
1072         dmtc->orig_buf = bio->bio_buf->b_data;
1073         dmtc->data_buf = space + sz;
1074
1075         /*
1076          * Load crypto descriptors (crp/crd loop)
1077          */
1078         bzero(space, sz);
1079         ptr = space;
1080         bio->bio_caller_info3.value = sectors;
1081         cpu_sfence();
1082 #if 0
1083         kprintf("Write, bytes = %d (b_bcount), "
1084                 "sectors = %d (bio = %p, b_cmd = %d)\n",
1085                 bytes, sectors, bio, bio->bio_buf->b_cmd);
1086 #endif
1087         for (i = 0; i < sectors; i++) {
1088                 crp = (struct cryptop *)ptr;
1089                 ptr += sizeof(*crp);
1090                 crd = (struct cryptodesc *)ptr;
1091                 ptr += sizeof (*crd);
1092
1093                 crp->crp_buf = dmtc->data_buf + i * DEV_BSIZE;
1094
1095                 crp->crp_sid = priv->crypto_sid;
1096                 crp->crp_ilen = crp->crp_olen = DEV_BSIZE;
1097
1098                 crp->crp_opaque = (void *)bio;
1099
1100                 crp->crp_callback = dmtc_crypto_cb_write_done;
1101                 crp->crp_desc = crd;
1102                 crp->crp_etype = 0;
1103                 crp->crp_flags = CRYPTO_F_CBIFSYNC | CRYPTO_F_REL |
1104                                  CRYPTO_F_BATCH;
1105
1106                 crd->crd_alg = priv->crypto_alg;
1107 #if 0
1108                 crd->crd_key = (caddr_t)priv->crypto_key;
1109                 crd->crd_klen = priv->crypto_klen;
1110 #endif
1111
1112                 crd->crd_skip = 0;
1113                 crd->crd_len = DEV_BSIZE /* XXX */;
1114                 crd->crd_flags = CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
1115                 crd->crd_next = NULL;
1116
1117                 crd->crd_flags |= CRD_F_ENCRYPT;
1118
1119                 /*
1120                  * Note: last argument is used to generate salt(?) and is
1121                  *       a 64 bit value, but the original code passed an
1122                  *       int.  Changing it now will break pre-existing
1123                  *       crypt volumes.
1124                  */
1125                 priv->ivgen->gen_iv(priv, crd->crd_iv, sizeof(crd->crd_iv),
1126                                     isector + i, crp);
1127         }
1128 }
1129
1130 /*
1131  * STRATEGY WRITE PATH PART 2/3
1132  */
1133 static int
1134 dmtc_crypto_cb_write_done(struct cryptop *crp)
1135 {
1136         struct dmtc_helper *dmtc;
1137         dm_target_crypt_config_t *priv;
1138         struct bio *bio, *obio;
1139         int n;
1140
1141         if (crp->crp_etype == EAGAIN)
1142                 return crypto_dispatch(crp);
1143
1144         bio = (struct bio *)crp->crp_opaque;
1145         KKASSERT(bio != NULL);
1146
1147         /*
1148          * Cumulative error
1149          */
1150         if (crp->crp_etype != 0) {
1151                 kprintf("dm_target_crypt: dmtc_crypto_cb_write_done "
1152                         "crp_etype = %d\n",
1153                 crp->crp_etype);
1154                 bio->bio_buf->b_error = crp->crp_etype;
1155         }
1156
1157         /*
1158          * On the last chunk of the encryption we issue the write
1159          */
1160         n = atomic_fetchadd_int(&bio->bio_caller_info3.value, -1);
1161 #if 0
1162         kprintf("dmtc_crypto_cb_write_done %p, n = %d\n", bio, n);
1163 #endif
1164
1165         if (n == 1) {
1166                 dmtc = bio->bio_caller_info2.ptr;
1167                 priv = (dm_target_crypt_config_t *)bio->bio_caller_info1.ptr;
1168
1169                 if (bio->bio_buf->b_error) {
1170                         bio->bio_buf->b_flags |= B_ERROR;
1171                         mpipe_free(&dmtc_write_mpipe, dmtc->free_addr);
1172                         obio = pop_bio(bio);
1173                         biodone(obio);
1174                 } else {
1175                         dmtc->orig_buf = bio->bio_buf->b_data;
1176                         bio->bio_buf->b_data = dmtc->data_buf;
1177                         bio->bio_done = dmtc_bio_write_done;
1178                         vn_strategy(priv->pdev->pdev_vnode, bio);
1179                 }
1180         }
1181         return 0;
1182 }
1183
1184 /*
1185  * STRATEGY WRITE PATH PART 3/3
1186  */
1187 static void
1188 dmtc_bio_write_done(struct bio *bio)
1189 {
1190         struct dmtc_helper *dmtc;
1191         struct bio *obio;
1192
1193         dmtc = bio->bio_caller_info2.ptr;
1194         bio->bio_buf->b_data = dmtc->orig_buf;
1195         mpipe_free(&dmtc_write_mpipe, dmtc->free_addr);
1196         obio = pop_bio(bio);
1197         biodone(obio);
1198 }
1199 /* END OF STRATEGY WRITE SECTION */
1200
1201
1202
1203 /* DUMPING MAGIC */
1204
1205 extern int tsleep_crypto_dump;
1206
1207 static int
1208 dm_target_crypt_dump(dm_table_entry_t *table_en, void *data, size_t length, off_t offset)
1209 {
1210         static struct dmtc_dump_helper dump_helper;
1211         dm_target_crypt_config_t *priv;
1212         int id;
1213         static int first_call = 1;
1214
1215         priv = table_en->target_config;
1216
1217         if (first_call) {
1218                 first_call = 0;
1219                 dump_reactivate_cpus();
1220         }
1221
1222         /* Magically enable tsleep */
1223         tsleep_crypto_dump = 1;
1224         id = 0;
1225
1226         /*
1227          * 0 length means flush buffers and return
1228          */
1229         if (length == 0) {
1230                 if (priv->pdev->pdev_vnode->v_rdev == NULL) {
1231                         tsleep_crypto_dump = 0;
1232                         return ENXIO;
1233                 }
1234                 dev_ddump(priv->pdev->pdev_vnode->v_rdev,
1235                     data, 0, offset, 0);
1236                 tsleep_crypto_dump = 0;
1237                 return 0;
1238         }
1239
1240         bzero(&dump_helper, sizeof(dump_helper));
1241         dump_helper.priv = priv;
1242         dump_helper.data = data;
1243         dump_helper.length = length;
1244         dump_helper.offset = offset +
1245             priv->block_offset * DEV_BSIZE;
1246         dump_helper.ident = &id;
1247         dmtc_crypto_dump_start(priv, &dump_helper);
1248
1249         /*
1250          * Hackery to make stuff appear synchronous. The crypto callback will
1251          * set id to 1 and call wakeup on it. If the request completed
1252          * synchronously, id will be 1 and we won't bother to sleep. If not,
1253          * the crypto request will complete asynchronously and we sleep until
1254          * it's done.
1255          */
1256         if (id == 0)
1257                 tsleep(&dump_helper, 0, "cryptdump", 0);
1258
1259         dump_helper.offset = dm_pdev_correct_dump_offset(priv->pdev,
1260             dump_helper.offset);
1261
1262         dev_ddump(priv->pdev->pdev_vnode->v_rdev,
1263             dump_helper.space, 0, dump_helper.offset,
1264             dump_helper.length);
1265
1266         tsleep_crypto_dump = 0;
1267         return 0;
1268 }
1269
1270 static void
1271 dmtc_crypto_dump_start(dm_target_crypt_config_t *priv, struct dmtc_dump_helper *dump_helper)
1272 {
1273         struct cryptodesc *crd;
1274         struct cryptop *crp;
1275         struct cryptoini *cri;
1276         int i, bytes, sectors;
1277         off_t isector;
1278
1279         cri = &priv->crypto_session;
1280
1281         bytes = dump_helper->length;
1282
1283         isector = dump_helper->offset / DEV_BSIZE;      /* ivgen salt base? */
1284         sectors = bytes / DEV_BSIZE;            /* Number of sectors */
1285         dump_helper->sectors = sectors;
1286 #if 0
1287         kprintf("Dump, bytes = %d, "
1288                 "sectors = %d, LENGTH=%zu\n", bytes, sectors, dump_helper->length);
1289 #endif
1290         KKASSERT(dump_helper->length <= 65536);
1291
1292         memcpy(dump_helper->space, dump_helper->data, bytes);
1293
1294         cpu_sfence();
1295
1296         for (i = 0; i < sectors; i++) {
1297                 crp = &dump_helper->crp[i];
1298                 crd = &dump_helper->crd[i];
1299
1300                 crp->crp_buf = dump_helper->space + i * DEV_BSIZE;
1301
1302                 crp->crp_sid = priv->crypto_sid;
1303                 crp->crp_ilen = crp->crp_olen = DEV_BSIZE;
1304
1305                 crp->crp_opaque = (void *)dump_helper;
1306
1307                 crp->crp_callback = dmtc_crypto_cb_dump_done;
1308                 crp->crp_desc = crd;
1309                 crp->crp_etype = 0;
1310                 crp->crp_flags = CRYPTO_F_CBIFSYNC | CRYPTO_F_REL |
1311                                  CRYPTO_F_BATCH;
1312
1313                 crd->crd_alg = priv->crypto_alg;
1314
1315                 crd->crd_skip = 0;
1316                 crd->crd_len = DEV_BSIZE /* XXX */;
1317                 crd->crd_flags = CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
1318                 crd->crd_next = NULL;
1319
1320                 crd->crd_flags |= CRD_F_ENCRYPT;
1321
1322                 /*
1323                  * Note: last argument is used to generate salt(?) and is
1324                  *       a 64 bit value, but the original code passed an
1325                  *       int.  Changing it now will break pre-existing
1326                  *       crypt volumes.
1327                  */
1328                 priv->ivgen->gen_iv(priv, crd->crd_iv, sizeof(crd->crd_iv),
1329                                     isector + i, crp);
1330         }
1331 }
1332
1333 static int
1334 dmtc_crypto_cb_dump_done(struct cryptop *crp)
1335 {
1336         struct dmtc_dump_helper *dump_helper;
1337         dm_target_crypt_config_t *priv;
1338         int n;
1339
1340         if (crp->crp_etype == EAGAIN)
1341                 return crypto_dispatch(crp);
1342
1343         dump_helper = (struct dmtc_dump_helper *)crp->crp_opaque;
1344         KKASSERT(dump_helper != NULL);
1345
1346         if (crp->crp_etype != 0) {
1347                 kprintf("dm_target_crypt: dmtc_crypto_cb_dump_done "
1348                         "crp_etype = %d\n",
1349                 crp->crp_etype);
1350                 return crp->crp_etype;
1351         }
1352
1353         /*
1354          * On the last chunk of the encryption we return control
1355          */
1356         n = atomic_fetchadd_int(&dump_helper->sectors, -1);
1357
1358         if (n == 1) {
1359                 priv = (dm_target_crypt_config_t *)dump_helper->priv;
1360                 atomic_add_int(dump_helper->ident, 1);
1361                 wakeup(dump_helper);
1362         }
1363
1364         return 0;
1365 }
1366
1367 static int
1368 dmtc_mod_handler(module_t mod, int type, void *unused)
1369 {
1370         dm_target_t *dmt = NULL;
1371         int err = 0;
1372
1373         switch (type) {
1374         case MOD_LOAD:
1375                 if ((dmt = dm_target_lookup("crypt")) != NULL) {
1376                         dm_target_unbusy(dmt);
1377                         return EEXIST;
1378                 }
1379                 dmt = dm_target_alloc("crypt");
1380                 dmt->version[0] = 1;
1381                 dmt->version[1] = 6;
1382                 dmt->version[2] = 0;
1383                 strlcpy(dmt->name, "crypt", DM_MAX_TYPE_NAME);
1384                 dmt->init = &dm_target_crypt_init;
1385                 dmt->status = &dm_target_crypt_status;
1386                 dmt->strategy = &dm_target_crypt_strategy;
1387                 dmt->deps = &dm_target_crypt_deps;
1388                 dmt->destroy = &dm_target_crypt_destroy;
1389                 dmt->upcall = &dm_target_crypt_upcall;
1390                 dmt->dump = &dm_target_crypt_dump;
1391
1392                 dmtc_init_mpipe();
1393
1394                 err = dm_target_insert(dmt);
1395                 if (err)
1396                         dmtc_destroy_mpipe();
1397                 else
1398                         kprintf("dm_target_crypt: Successfully initialized\n");
1399                 break;
1400
1401         case MOD_UNLOAD:
1402                 err = dm_target_rem("crypt");
1403                 if (err == 0) {
1404                         dmtc_destroy_mpipe();
1405                         kprintf("dm_target_crypt: unloaded\n");
1406                 }
1407                 break;
1408
1409         default:
1410                 break;
1411         }
1412
1413         return err;
1414 }
1415
1416 DM_TARGET_MODULE(dm_target_crypt, dmtc_mod_handler);