xref: /freebsd/sys/geom/eli/g_eli.c (revision aa0a1e58)
1 /*-
2  * Copyright (c) 2005-2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/linker.h>
34 #include <sys/module.h>
35 #include <sys/lock.h>
36 #include <sys/mutex.h>
37 #include <sys/bio.h>
38 #include <sys/sysctl.h>
39 #include <sys/malloc.h>
40 #include <sys/eventhandler.h>
41 #include <sys/kthread.h>
42 #include <sys/proc.h>
43 #include <sys/sched.h>
44 #include <sys/smp.h>
45 #include <sys/uio.h>
46 #include <sys/vnode.h>
47 
48 #include <vm/uma.h>
49 
50 #include <geom/geom.h>
51 #include <geom/eli/g_eli.h>
52 #include <geom/eli/pkcs5v2.h>
53 
54 FEATURE(geom_eli, "GEOM crypto module");
55 
56 MALLOC_DEFINE(M_ELI, "eli data", "GEOM_ELI Data");
57 
58 SYSCTL_DECL(_kern_geom);
59 SYSCTL_NODE(_kern_geom, OID_AUTO, eli, CTLFLAG_RW, 0, "GEOM_ELI stuff");
60 int g_eli_debug = 0;
61 TUNABLE_INT("kern.geom.eli.debug", &g_eli_debug);
62 SYSCTL_INT(_kern_geom_eli, OID_AUTO, debug, CTLFLAG_RW, &g_eli_debug, 0,
63     "Debug level");
64 static u_int g_eli_tries = 3;
65 TUNABLE_INT("kern.geom.eli.tries", &g_eli_tries);
66 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, tries, CTLFLAG_RW, &g_eli_tries, 0,
67     "Number of tries for entering the passphrase");
68 static u_int g_eli_visible_passphrase = GETS_NOECHO;
69 TUNABLE_INT("kern.geom.eli.visible_passphrase", &g_eli_visible_passphrase);
70 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, visible_passphrase, CTLFLAG_RW,
71     &g_eli_visible_passphrase, 0,
72     "Visibility of passphrase prompt (0 = invisible, 1 = visible, 2 = asterisk)");
73 u_int g_eli_overwrites = G_ELI_OVERWRITES;
74 TUNABLE_INT("kern.geom.eli.overwrites", &g_eli_overwrites);
75 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, overwrites, CTLFLAG_RW, &g_eli_overwrites,
76     0, "Number of times on-disk keys should be overwritten when destroying them");
77 static u_int g_eli_threads = 0;
78 TUNABLE_INT("kern.geom.eli.threads", &g_eli_threads);
79 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, threads, CTLFLAG_RW, &g_eli_threads, 0,
80     "Number of threads doing crypto work");
81 u_int g_eli_batch = 0;
82 TUNABLE_INT("kern.geom.eli.batch", &g_eli_batch);
83 SYSCTL_UINT(_kern_geom_eli, OID_AUTO, batch, CTLFLAG_RW, &g_eli_batch, 0,
84     "Use crypto operations batching");
85 
86 static eventhandler_tag g_eli_pre_sync = NULL;
87 
88 static int g_eli_destroy_geom(struct gctl_req *req, struct g_class *mp,
89     struct g_geom *gp);
90 static void g_eli_init(struct g_class *mp);
91 static void g_eli_fini(struct g_class *mp);
92 
93 static g_taste_t g_eli_taste;
94 static g_dumpconf_t g_eli_dumpconf;
95 
96 struct g_class g_eli_class = {
97 	.name = G_ELI_CLASS_NAME,
98 	.version = G_VERSION,
99 	.ctlreq = g_eli_config,
100 	.taste = g_eli_taste,
101 	.destroy_geom = g_eli_destroy_geom,
102 	.init = g_eli_init,
103 	.fini = g_eli_fini
104 };
105 
106 
107 /*
108  * Code paths:
109  * BIO_READ:
110  *	g_eli_start -> g_eli_crypto_read -> g_io_request -> g_eli_read_done -> g_eli_crypto_run -> g_eli_crypto_read_done -> g_io_deliver
111  * BIO_WRITE:
112  *	g_eli_start -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> g_eli_write_done -> g_io_deliver
113  */
114 
115 
116 /*
117  * EAGAIN from crypto(9) means, that we were probably balanced to another crypto
118  * accelerator or something like this.
119  * The function updates the SID and rerun the operation.
120  */
121 int
122 g_eli_crypto_rerun(struct cryptop *crp)
123 {
124 	struct g_eli_softc *sc;
125 	struct g_eli_worker *wr;
126 	struct bio *bp;
127 	int error;
128 
129 	bp = (struct bio *)crp->crp_opaque;
130 	sc = bp->bio_to->geom->softc;
131 	LIST_FOREACH(wr, &sc->sc_workers, w_next) {
132 		if (wr->w_number == bp->bio_pflags)
133 			break;
134 	}
135 	KASSERT(wr != NULL, ("Invalid worker (%u).", bp->bio_pflags));
136 	G_ELI_DEBUG(1, "Rerunning crypto %s request (sid: %ju -> %ju).",
137 	    bp->bio_cmd == BIO_READ ? "READ" : "WRITE", (uintmax_t)wr->w_sid,
138 	    (uintmax_t)crp->crp_sid);
139 	wr->w_sid = crp->crp_sid;
140 	crp->crp_etype = 0;
141 	error = crypto_dispatch(crp);
142 	if (error == 0)
143 		return (0);
144 	G_ELI_DEBUG(1, "%s: crypto_dispatch() returned %d.", __func__, error);
145 	crp->crp_etype = error;
146 	return (error);
147 }
148 
149 /*
150  * The function is called afer reading encrypted data from the provider.
151  *
152  * g_eli_start -> g_eli_crypto_read -> g_io_request -> G_ELI_READ_DONE -> g_eli_crypto_run -> g_eli_crypto_read_done -> g_io_deliver
153  */
154 void
155 g_eli_read_done(struct bio *bp)
156 {
157 	struct g_eli_softc *sc;
158 	struct bio *pbp;
159 
160 	G_ELI_LOGREQ(2, bp, "Request done.");
161 	pbp = bp->bio_parent;
162 	if (pbp->bio_error == 0)
163 		pbp->bio_error = bp->bio_error;
164 	/*
165 	 * Do we have all sectors already?
166 	 */
167 	pbp->bio_inbed++;
168 	if (pbp->bio_inbed < pbp->bio_children)
169 		return;
170 	g_destroy_bio(bp);
171 	sc = pbp->bio_to->geom->softc;
172 	if (pbp->bio_error != 0) {
173 		G_ELI_LOGREQ(0, pbp, "%s() failed", __func__);
174 		pbp->bio_completed = 0;
175 		if (pbp->bio_driver2 != NULL) {
176 			free(pbp->bio_driver2, M_ELI);
177 			pbp->bio_driver2 = NULL;
178 		}
179 		g_io_deliver(pbp, pbp->bio_error);
180 		atomic_subtract_int(&sc->sc_inflight, 1);
181 		return;
182 	}
183 	mtx_lock(&sc->sc_queue_mtx);
184 	bioq_insert_tail(&sc->sc_queue, pbp);
185 	mtx_unlock(&sc->sc_queue_mtx);
186 	wakeup(sc);
187 }
188 
189 /*
190  * The function is called after we encrypt and write data.
191  *
192  * g_eli_start -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> G_ELI_WRITE_DONE -> g_io_deliver
193  */
194 void
195 g_eli_write_done(struct bio *bp)
196 {
197 	struct g_eli_softc *sc;
198 	struct bio *pbp;
199 
200 	G_ELI_LOGREQ(2, bp, "Request done.");
201 	pbp = bp->bio_parent;
202 	if (pbp->bio_error == 0) {
203 		if (bp->bio_error != 0)
204 			pbp->bio_error = bp->bio_error;
205 	}
206 	/*
207 	 * Do we have all sectors already?
208 	 */
209 	pbp->bio_inbed++;
210 	if (pbp->bio_inbed < pbp->bio_children)
211 		return;
212 	free(pbp->bio_driver2, M_ELI);
213 	pbp->bio_driver2 = NULL;
214 	if (pbp->bio_error != 0) {
215 		G_ELI_LOGREQ(0, pbp, "Crypto WRITE request failed (error=%d).",
216 		    pbp->bio_error);
217 		pbp->bio_completed = 0;
218 	}
219 	g_destroy_bio(bp);
220 	/*
221 	 * Write is finished, send it up.
222 	 */
223 	pbp->bio_completed = pbp->bio_length;
224 	sc = pbp->bio_to->geom->softc;
225 	g_io_deliver(pbp, pbp->bio_error);
226 	atomic_subtract_int(&sc->sc_inflight, 1);
227 }
228 
229 /*
230  * This function should never be called, but GEOM made as it set ->orphan()
231  * method for every geom.
232  */
233 static void
234 g_eli_orphan_spoil_assert(struct g_consumer *cp)
235 {
236 
237 	panic("Function %s() called for %s.", __func__, cp->geom->name);
238 }
239 
240 static void
241 g_eli_orphan(struct g_consumer *cp)
242 {
243 	struct g_eli_softc *sc;
244 
245 	g_topology_assert();
246 	sc = cp->geom->softc;
247 	if (sc == NULL)
248 		return;
249 	g_eli_destroy(sc, TRUE);
250 }
251 
252 /*
253  * BIO_READ:
254  *	G_ELI_START -> g_eli_crypto_read -> g_io_request -> g_eli_read_done -> g_eli_crypto_run -> g_eli_crypto_read_done -> g_io_deliver
255  * BIO_WRITE:
256  *	G_ELI_START -> g_eli_crypto_run -> g_eli_crypto_write_done -> g_io_request -> g_eli_write_done -> g_io_deliver
257  */
258 static void
259 g_eli_start(struct bio *bp)
260 {
261 	struct g_eli_softc *sc;
262 	struct g_consumer *cp;
263 	struct bio *cbp;
264 
265 	sc = bp->bio_to->geom->softc;
266 	KASSERT(sc != NULL,
267 	    ("Provider's error should be set (error=%d)(device=%s).",
268 	    bp->bio_to->error, bp->bio_to->name));
269 	G_ELI_LOGREQ(2, bp, "Request received.");
270 
271 	switch (bp->bio_cmd) {
272 	case BIO_READ:
273 	case BIO_WRITE:
274 	case BIO_GETATTR:
275 	case BIO_FLUSH:
276 		break;
277 	case BIO_DELETE:
278 		/*
279 		 * We could eventually support BIO_DELETE request.
280 		 * It could be done by overwritting requested sector with
281 		 * random data g_eli_overwrites number of times.
282 		 */
283 	default:
284 		g_io_deliver(bp, EOPNOTSUPP);
285 		return;
286 	}
287 	cbp = g_clone_bio(bp);
288 	if (cbp == NULL) {
289 		g_io_deliver(bp, ENOMEM);
290 		return;
291 	}
292 	bp->bio_driver1 = cbp;
293 	bp->bio_pflags = G_ELI_NEW_BIO;
294 	switch (bp->bio_cmd) {
295 	case BIO_READ:
296 		if (!(sc->sc_flags & G_ELI_FLAG_AUTH)) {
297 			g_eli_crypto_read(sc, bp, 0);
298 			break;
299 		}
300 		/* FALLTHROUGH */
301 	case BIO_WRITE:
302 		mtx_lock(&sc->sc_queue_mtx);
303 		bioq_insert_tail(&sc->sc_queue, bp);
304 		mtx_unlock(&sc->sc_queue_mtx);
305 		wakeup(sc);
306 		break;
307 	case BIO_GETATTR:
308 	case BIO_FLUSH:
309 		cbp->bio_done = g_std_done;
310 		cp = LIST_FIRST(&sc->sc_geom->consumer);
311 		cbp->bio_to = cp->provider;
312 		G_ELI_LOGREQ(2, cbp, "Sending request.");
313 		g_io_request(cbp, cp);
314 		break;
315 	}
316 }
317 
318 static int
319 g_eli_newsession(struct g_eli_worker *wr)
320 {
321 	struct g_eli_softc *sc;
322 	struct cryptoini crie, cria;
323 	int error;
324 
325 	sc = wr->w_softc;
326 
327 	bzero(&crie, sizeof(crie));
328 	crie.cri_alg = sc->sc_ealgo;
329 	crie.cri_klen = sc->sc_ekeylen;
330 	if (sc->sc_ealgo == CRYPTO_AES_XTS)
331 		crie.cri_klen <<= 1;
332 	crie.cri_key = sc->sc_ekeys[0];
333 	if (sc->sc_flags & G_ELI_FLAG_AUTH) {
334 		bzero(&cria, sizeof(cria));
335 		cria.cri_alg = sc->sc_aalgo;
336 		cria.cri_klen = sc->sc_akeylen;
337 		cria.cri_key = sc->sc_akey;
338 		crie.cri_next = &cria;
339 	}
340 
341 	switch (sc->sc_crypto) {
342 	case G_ELI_CRYPTO_SW:
343 		error = crypto_newsession(&wr->w_sid, &crie,
344 		    CRYPTOCAP_F_SOFTWARE);
345 		break;
346 	case G_ELI_CRYPTO_HW:
347 		error = crypto_newsession(&wr->w_sid, &crie,
348 		    CRYPTOCAP_F_HARDWARE);
349 		break;
350 	case G_ELI_CRYPTO_UNKNOWN:
351 		error = crypto_newsession(&wr->w_sid, &crie,
352 		    CRYPTOCAP_F_HARDWARE);
353 		if (error == 0) {
354 			mtx_lock(&sc->sc_queue_mtx);
355 			if (sc->sc_crypto == G_ELI_CRYPTO_UNKNOWN)
356 				sc->sc_crypto = G_ELI_CRYPTO_HW;
357 			mtx_unlock(&sc->sc_queue_mtx);
358 		} else {
359 			error = crypto_newsession(&wr->w_sid, &crie,
360 			    CRYPTOCAP_F_SOFTWARE);
361 			mtx_lock(&sc->sc_queue_mtx);
362 			if (sc->sc_crypto == G_ELI_CRYPTO_UNKNOWN)
363 				sc->sc_crypto = G_ELI_CRYPTO_SW;
364 			mtx_unlock(&sc->sc_queue_mtx);
365 		}
366 		break;
367 	default:
368 		panic("%s: invalid condition", __func__);
369 	}
370 
371 	return (error);
372 }
373 
374 static void
375 g_eli_freesession(struct g_eli_worker *wr)
376 {
377 
378 	crypto_freesession(wr->w_sid);
379 }
380 
381 static void
382 g_eli_cancel(struct g_eli_softc *sc)
383 {
384 	struct bio *bp;
385 
386 	mtx_assert(&sc->sc_queue_mtx, MA_OWNED);
387 
388 	while ((bp = bioq_takefirst(&sc->sc_queue)) != NULL) {
389 		KASSERT(bp->bio_pflags == G_ELI_NEW_BIO,
390 		    ("Not new bio when canceling (bp=%p).", bp));
391 		g_io_deliver(bp, ENXIO);
392 	}
393 }
394 
395 static struct bio *
396 g_eli_takefirst(struct g_eli_softc *sc)
397 {
398 	struct bio *bp;
399 
400 	mtx_assert(&sc->sc_queue_mtx, MA_OWNED);
401 
402 	if (!(sc->sc_flags & G_ELI_FLAG_SUSPEND))
403 		return (bioq_takefirst(&sc->sc_queue));
404 	/*
405 	 * Device suspended, so we skip new I/O requests.
406 	 */
407 	TAILQ_FOREACH(bp, &sc->sc_queue.queue, bio_queue) {
408 		if (bp->bio_pflags != G_ELI_NEW_BIO)
409 			break;
410 	}
411 	if (bp != NULL)
412 		bioq_remove(&sc->sc_queue, bp);
413 	return (bp);
414 }
415 
416 /*
417  * This is the main function for kernel worker thread when we don't have
418  * hardware acceleration and we have to do cryptography in software.
419  * Dedicated thread is needed, so we don't slow down g_up/g_down GEOM
420  * threads with crypto work.
421  */
422 static void
423 g_eli_worker(void *arg)
424 {
425 	struct g_eli_softc *sc;
426 	struct g_eli_worker *wr;
427 	struct bio *bp;
428 	int error;
429 
430 	wr = arg;
431 	sc = wr->w_softc;
432 #ifdef SMP
433 	/* Before sched_bind() to a CPU, wait for all CPUs to go on-line. */
434 	if (mp_ncpus > 1 && sc->sc_crypto == G_ELI_CRYPTO_SW &&
435 	    g_eli_threads == 0) {
436 		while (!smp_started)
437 			tsleep(wr, 0, "geli:smp", hz / 4);
438 	}
439 #endif
440 	thread_lock(curthread);
441 	sched_prio(curthread, PUSER);
442 	if (sc->sc_crypto == G_ELI_CRYPTO_SW && g_eli_threads == 0)
443 		sched_bind(curthread, wr->w_number);
444 	thread_unlock(curthread);
445 
446 	G_ELI_DEBUG(1, "Thread %s started.", curthread->td_proc->p_comm);
447 
448 	for (;;) {
449 		mtx_lock(&sc->sc_queue_mtx);
450 again:
451 		bp = g_eli_takefirst(sc);
452 		if (bp == NULL) {
453 			if (sc->sc_flags & G_ELI_FLAG_DESTROY) {
454 				g_eli_cancel(sc);
455 				LIST_REMOVE(wr, w_next);
456 				g_eli_freesession(wr);
457 				free(wr, M_ELI);
458 				G_ELI_DEBUG(1, "Thread %s exiting.",
459 				    curthread->td_proc->p_comm);
460 				wakeup(&sc->sc_workers);
461 				mtx_unlock(&sc->sc_queue_mtx);
462 				kproc_exit(0);
463 			}
464 			while (sc->sc_flags & G_ELI_FLAG_SUSPEND) {
465 				if (sc->sc_inflight > 0) {
466 					G_ELI_DEBUG(0, "inflight=%d", sc->sc_inflight);
467 					/*
468 					 * We still have inflight BIOs, so
469 					 * sleep and retry.
470 					 */
471 					msleep(sc, &sc->sc_queue_mtx, PRIBIO,
472 					    "geli:inf", hz / 5);
473 					goto again;
474 				}
475 				/*
476 				 * Suspend requested, mark the worker as
477 				 * suspended and go to sleep.
478 				 */
479 				if (wr->w_active) {
480 					g_eli_freesession(wr);
481 					wr->w_active = FALSE;
482 				}
483 				wakeup(&sc->sc_workers);
484 				msleep(sc, &sc->sc_queue_mtx, PRIBIO,
485 				    "geli:suspend", 0);
486 				if (!wr->w_active &&
487 				    !(sc->sc_flags & G_ELI_FLAG_SUSPEND)) {
488 					error = g_eli_newsession(wr);
489 					KASSERT(error == 0,
490 					    ("g_eli_newsession() failed on resume (error=%d)",
491 					    error));
492 					wr->w_active = TRUE;
493 				}
494 				goto again;
495 			}
496 			msleep(sc, &sc->sc_queue_mtx, PDROP, "geli:w", 0);
497 			continue;
498 		}
499 		if (bp->bio_pflags == G_ELI_NEW_BIO)
500 			atomic_add_int(&sc->sc_inflight, 1);
501 		mtx_unlock(&sc->sc_queue_mtx);
502 		if (bp->bio_pflags == G_ELI_NEW_BIO) {
503 			bp->bio_pflags = 0;
504 			if (sc->sc_flags & G_ELI_FLAG_AUTH) {
505 				if (bp->bio_cmd == BIO_READ)
506 					g_eli_auth_read(sc, bp);
507 				else
508 					g_eli_auth_run(wr, bp);
509 			} else {
510 				if (bp->bio_cmd == BIO_READ)
511 					g_eli_crypto_read(sc, bp, 1);
512 				else
513 					g_eli_crypto_run(wr, bp);
514 			}
515 		} else {
516 			if (sc->sc_flags & G_ELI_FLAG_AUTH)
517 				g_eli_auth_run(wr, bp);
518 			else
519 				g_eli_crypto_run(wr, bp);
520 		}
521 	}
522 }
523 
524 /*
525  * Select encryption key. If G_ELI_FLAG_SINGLE_KEY is present we only have one
526  * key available for all the data. If the flag is not present select the key
527  * based on data offset.
528  */
529 uint8_t *
530 g_eli_crypto_key(struct g_eli_softc *sc, off_t offset, size_t blocksize)
531 {
532 	u_int nkey;
533 
534 	if (sc->sc_nekeys == 1)
535 		return (sc->sc_ekeys[0]);
536 
537 	KASSERT(sc->sc_nekeys > 1, ("%s: sc_nekeys=%u", __func__,
538 	    sc->sc_nekeys));
539 	KASSERT((sc->sc_flags & G_ELI_FLAG_SINGLE_KEY) == 0,
540 	    ("%s: SINGLE_KEY flag set, but sc_nekeys=%u", __func__,
541 	    sc->sc_nekeys));
542 
543 	/* We switch key every 2^G_ELI_KEY_SHIFT blocks. */
544 	nkey = (offset >> G_ELI_KEY_SHIFT) / blocksize;
545 
546 	KASSERT(nkey < sc->sc_nekeys, ("%s: nkey=%u >= sc_nekeys=%u", __func__,
547 	    nkey, sc->sc_nekeys));
548 
549 	return (sc->sc_ekeys[nkey]);
550 }
551 
552 /*
553  * Here we generate IV. It is unique for every sector.
554  */
555 void
556 g_eli_crypto_ivgen(struct g_eli_softc *sc, off_t offset, u_char *iv,
557     size_t size)
558 {
559 	uint8_t off[8];
560 
561 	if ((sc->sc_flags & G_ELI_FLAG_NATIVE_BYTE_ORDER) != 0)
562 		bcopy(&offset, off, sizeof(off));
563 	else
564 		le64enc(off, (uint64_t)offset);
565 
566 	switch (sc->sc_ealgo) {
567 	case CRYPTO_AES_XTS:
568 		bcopy(off, iv, sizeof(off));
569 		bzero(iv + sizeof(off), size - sizeof(off));
570 		break;
571 	default:
572 	    {
573 		u_char hash[SHA256_DIGEST_LENGTH];
574 		SHA256_CTX ctx;
575 
576 		/* Copy precalculated SHA256 context for IV-Key. */
577 		bcopy(&sc->sc_ivctx, &ctx, sizeof(ctx));
578 		SHA256_Update(&ctx, off, sizeof(off));
579 		SHA256_Final(hash, &ctx);
580 		bcopy(hash, iv, MIN(sizeof(hash), size));
581 		break;
582 	    }
583 	}
584 }
585 
586 int
587 g_eli_read_metadata(struct g_class *mp, struct g_provider *pp,
588     struct g_eli_metadata *md)
589 {
590 	struct g_geom *gp;
591 	struct g_consumer *cp;
592 	u_char *buf = NULL;
593 	int error;
594 
595 	g_topology_assert();
596 
597 	gp = g_new_geomf(mp, "eli:taste");
598 	gp->start = g_eli_start;
599 	gp->access = g_std_access;
600 	/*
601 	 * g_eli_read_metadata() is always called from the event thread.
602 	 * Our geom is created and destroyed in the same event, so there
603 	 * could be no orphan nor spoil event in the meantime.
604 	 */
605 	gp->orphan = g_eli_orphan_spoil_assert;
606 	gp->spoiled = g_eli_orphan_spoil_assert;
607 	cp = g_new_consumer(gp);
608 	error = g_attach(cp, pp);
609 	if (error != 0)
610 		goto end;
611 	error = g_access(cp, 1, 0, 0);
612 	if (error != 0)
613 		goto end;
614 	g_topology_unlock();
615 	buf = g_read_data(cp, pp->mediasize - pp->sectorsize, pp->sectorsize,
616 	    &error);
617 	g_topology_lock();
618 	if (buf == NULL)
619 		goto end;
620 	eli_metadata_decode(buf, md);
621 end:
622 	if (buf != NULL)
623 		g_free(buf);
624 	if (cp->provider != NULL) {
625 		if (cp->acr == 1)
626 			g_access(cp, -1, 0, 0);
627 		g_detach(cp);
628 	}
629 	g_destroy_consumer(cp);
630 	g_destroy_geom(gp);
631 	return (error);
632 }
633 
634 /*
635  * The function is called when we had last close on provider and user requested
636  * to close it when this situation occur.
637  */
638 static void
639 g_eli_last_close(struct g_eli_softc *sc)
640 {
641 	struct g_geom *gp;
642 	struct g_provider *pp;
643 	char ppname[64];
644 	int error;
645 
646 	g_topology_assert();
647 	gp = sc->sc_geom;
648 	pp = LIST_FIRST(&gp->provider);
649 	strlcpy(ppname, pp->name, sizeof(ppname));
650 	error = g_eli_destroy(sc, TRUE);
651 	KASSERT(error == 0, ("Cannot detach %s on last close (error=%d).",
652 	    ppname, error));
653 	G_ELI_DEBUG(0, "Detached %s on last close.", ppname);
654 }
655 
656 int
657 g_eli_access(struct g_provider *pp, int dr, int dw, int de)
658 {
659 	struct g_eli_softc *sc;
660 	struct g_geom *gp;
661 
662 	gp = pp->geom;
663 	sc = gp->softc;
664 
665 	if (dw > 0) {
666 		if (sc->sc_flags & G_ELI_FLAG_RO) {
667 			/* Deny write attempts. */
668 			return (EROFS);
669 		}
670 		/* Someone is opening us for write, we need to remember that. */
671 		sc->sc_flags |= G_ELI_FLAG_WOPEN;
672 		return (0);
673 	}
674 	/* Is this the last close? */
675 	if (pp->acr + dr > 0 || pp->acw + dw > 0 || pp->ace + de > 0)
676 		return (0);
677 
678 	/*
679 	 * Automatically detach on last close if requested.
680 	 */
681 	if ((sc->sc_flags & G_ELI_FLAG_RW_DETACH) ||
682 	    (sc->sc_flags & G_ELI_FLAG_WOPEN)) {
683 		g_eli_last_close(sc);
684 	}
685 	return (0);
686 }
687 
688 static int
689 g_eli_cpu_is_disabled(int cpu)
690 {
691 #ifdef SMP
692 	return ((hlt_cpus_mask & (1 << cpu)) != 0);
693 #else
694 	return (0);
695 #endif
696 }
697 
698 struct g_geom *
699 g_eli_create(struct gctl_req *req, struct g_class *mp, struct g_provider *bpp,
700     const struct g_eli_metadata *md, const u_char *mkey, int nkey)
701 {
702 	struct g_eli_softc *sc;
703 	struct g_eli_worker *wr;
704 	struct g_geom *gp;
705 	struct g_provider *pp;
706 	struct g_consumer *cp;
707 	u_int i, threads;
708 	int error;
709 
710 	G_ELI_DEBUG(1, "Creating device %s%s.", bpp->name, G_ELI_SUFFIX);
711 
712 	gp = g_new_geomf(mp, "%s%s", bpp->name, G_ELI_SUFFIX);
713 	gp->softc = NULL;	/* for a moment */
714 
715 	sc = malloc(sizeof(*sc), M_ELI, M_WAITOK | M_ZERO);
716 	gp->start = g_eli_start;
717 	/*
718 	 * Spoiling cannot happen actually, because we keep provider open for
719 	 * writing all the time or provider is read-only.
720 	 */
721 	gp->spoiled = g_eli_orphan_spoil_assert;
722 	gp->orphan = g_eli_orphan;
723 	gp->dumpconf = g_eli_dumpconf;
724 	/*
725 	 * If detach-on-last-close feature is not enabled and we don't operate
726 	 * on read-only provider, we can simply use g_std_access().
727 	 */
728 	if (md->md_flags & (G_ELI_FLAG_WO_DETACH | G_ELI_FLAG_RO))
729 		gp->access = g_eli_access;
730 	else
731 		gp->access = g_std_access;
732 
733 	sc->sc_inflight = 0;
734 	sc->sc_crypto = G_ELI_CRYPTO_UNKNOWN;
735 	sc->sc_flags = md->md_flags;
736 	/* Backward compatibility. */
737 	if (md->md_version < 4)
738 		sc->sc_flags |= G_ELI_FLAG_NATIVE_BYTE_ORDER;
739 	if (md->md_version < 5)
740 		sc->sc_flags |= G_ELI_FLAG_SINGLE_KEY;
741 	sc->sc_ealgo = md->md_ealgo;
742 	sc->sc_nkey = nkey;
743 
744 	if (sc->sc_flags & G_ELI_FLAG_AUTH) {
745 		sc->sc_akeylen = sizeof(sc->sc_akey) * 8;
746 		sc->sc_aalgo = md->md_aalgo;
747 		sc->sc_alen = g_eli_hashlen(sc->sc_aalgo);
748 
749 		sc->sc_data_per_sector = bpp->sectorsize - sc->sc_alen;
750 		/*
751 		 * Some hash functions (like SHA1 and RIPEMD160) generates hash
752 		 * which length is not multiple of 128 bits, but we want data
753 		 * length to be multiple of 128, so we can encrypt without
754 		 * padding. The line below rounds down data length to multiple
755 		 * of 128 bits.
756 		 */
757 		sc->sc_data_per_sector -= sc->sc_data_per_sector % 16;
758 
759 		sc->sc_bytes_per_sector =
760 		    (md->md_sectorsize - 1) / sc->sc_data_per_sector + 1;
761 		sc->sc_bytes_per_sector *= bpp->sectorsize;
762 	}
763 
764 	gp->softc = sc;
765 	sc->sc_geom = gp;
766 
767 	bioq_init(&sc->sc_queue);
768 	mtx_init(&sc->sc_queue_mtx, "geli:queue", NULL, MTX_DEF);
769 
770 	pp = NULL;
771 	cp = g_new_consumer(gp);
772 	error = g_attach(cp, bpp);
773 	if (error != 0) {
774 		if (req != NULL) {
775 			gctl_error(req, "Cannot attach to %s (error=%d).",
776 			    bpp->name, error);
777 		} else {
778 			G_ELI_DEBUG(1, "Cannot attach to %s (error=%d).",
779 			    bpp->name, error);
780 		}
781 		goto failed;
782 	}
783 	/*
784 	 * Keep provider open all the time, so we can run critical tasks,
785 	 * like Master Keys deletion, without wondering if we can open
786 	 * provider or not.
787 	 * We don't open provider for writing only when user requested read-only
788 	 * access.
789 	 */
790 	if (sc->sc_flags & G_ELI_FLAG_RO)
791 		error = g_access(cp, 1, 0, 1);
792 	else
793 		error = g_access(cp, 1, 1, 1);
794 	if (error != 0) {
795 		if (req != NULL) {
796 			gctl_error(req, "Cannot access %s (error=%d).",
797 			    bpp->name, error);
798 		} else {
799 			G_ELI_DEBUG(1, "Cannot access %s (error=%d).",
800 			    bpp->name, error);
801 		}
802 		goto failed;
803 	}
804 
805 	sc->sc_sectorsize = md->md_sectorsize;
806 	sc->sc_mediasize = bpp->mediasize;
807 	if (!(sc->sc_flags & G_ELI_FLAG_ONETIME))
808 		sc->sc_mediasize -= bpp->sectorsize;
809 	if (!(sc->sc_flags & G_ELI_FLAG_AUTH))
810 		sc->sc_mediasize -= (sc->sc_mediasize % sc->sc_sectorsize);
811 	else {
812 		sc->sc_mediasize /= sc->sc_bytes_per_sector;
813 		sc->sc_mediasize *= sc->sc_sectorsize;
814 	}
815 
816 	/*
817 	 * Remember the keys in our softc structure.
818 	 */
819 	g_eli_mkey_propagate(sc, mkey);
820 	sc->sc_ekeylen = md->md_keylen;
821 
822 	LIST_INIT(&sc->sc_workers);
823 
824 	threads = g_eli_threads;
825 	if (threads == 0)
826 		threads = mp_ncpus;
827 	else if (threads > mp_ncpus) {
828 		/* There is really no need for too many worker threads. */
829 		threads = mp_ncpus;
830 		G_ELI_DEBUG(0, "Reducing number of threads to %u.", threads);
831 	}
832 	for (i = 0; i < threads; i++) {
833 		if (g_eli_cpu_is_disabled(i)) {
834 			G_ELI_DEBUG(1, "%s: CPU %u disabled, skipping.",
835 			    bpp->name, i);
836 			continue;
837 		}
838 		wr = malloc(sizeof(*wr), M_ELI, M_WAITOK | M_ZERO);
839 		wr->w_softc = sc;
840 		wr->w_number = i;
841 		wr->w_active = TRUE;
842 
843 		error = g_eli_newsession(wr);
844 		if (error != 0) {
845 			free(wr, M_ELI);
846 			if (req != NULL) {
847 				gctl_error(req, "Cannot set up crypto session "
848 				    "for %s (error=%d).", bpp->name, error);
849 			} else {
850 				G_ELI_DEBUG(1, "Cannot set up crypto session "
851 				    "for %s (error=%d).", bpp->name, error);
852 			}
853 			goto failed;
854 		}
855 
856 		error = kproc_create(g_eli_worker, wr, &wr->w_proc, 0, 0,
857 		    "g_eli[%u] %s", i, bpp->name);
858 		if (error != 0) {
859 			g_eli_freesession(wr);
860 			free(wr, M_ELI);
861 			if (req != NULL) {
862 				gctl_error(req, "Cannot create kernel thread "
863 				    "for %s (error=%d).", bpp->name, error);
864 			} else {
865 				G_ELI_DEBUG(1, "Cannot create kernel thread "
866 				    "for %s (error=%d).", bpp->name, error);
867 			}
868 			goto failed;
869 		}
870 		LIST_INSERT_HEAD(&sc->sc_workers, wr, w_next);
871 		/* If we have hardware support, one thread is enough. */
872 		if (sc->sc_crypto == G_ELI_CRYPTO_HW)
873 			break;
874 	}
875 
876 	/*
877 	 * Create decrypted provider.
878 	 */
879 	pp = g_new_providerf(gp, "%s%s", bpp->name, G_ELI_SUFFIX);
880 	pp->mediasize = sc->sc_mediasize;
881 	pp->sectorsize = sc->sc_sectorsize;
882 
883 	g_error_provider(pp, 0);
884 
885 	G_ELI_DEBUG(0, "Device %s created.", pp->name);
886 	G_ELI_DEBUG(0, "Encryption: %s %u", g_eli_algo2str(sc->sc_ealgo),
887 	    sc->sc_ekeylen);
888 	if (sc->sc_flags & G_ELI_FLAG_AUTH)
889 		G_ELI_DEBUG(0, " Integrity: %s", g_eli_algo2str(sc->sc_aalgo));
890 	G_ELI_DEBUG(0, "    Crypto: %s",
891 	    sc->sc_crypto == G_ELI_CRYPTO_SW ? "software" : "hardware");
892 	return (gp);
893 failed:
894 	mtx_lock(&sc->sc_queue_mtx);
895 	sc->sc_flags |= G_ELI_FLAG_DESTROY;
896 	wakeup(sc);
897 	/*
898 	 * Wait for kernel threads self destruction.
899 	 */
900 	while (!LIST_EMPTY(&sc->sc_workers)) {
901 		msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
902 		    "geli:destroy", 0);
903 	}
904 	mtx_destroy(&sc->sc_queue_mtx);
905 	if (cp->provider != NULL) {
906 		if (cp->acr == 1)
907 			g_access(cp, -1, -1, -1);
908 		g_detach(cp);
909 	}
910 	g_destroy_consumer(cp);
911 	g_destroy_geom(gp);
912 	if (sc->sc_ekeys != NULL) {
913 		bzero(sc->sc_ekeys,
914 		    sc->sc_nekeys * (sizeof(uint8_t *) + G_ELI_DATAKEYLEN));
915 		free(sc->sc_ekeys, M_ELI);
916 	}
917 	bzero(sc, sizeof(*sc));
918 	free(sc, M_ELI);
919 	return (NULL);
920 }
921 
922 int
923 g_eli_destroy(struct g_eli_softc *sc, boolean_t force)
924 {
925 	struct g_geom *gp;
926 	struct g_provider *pp;
927 
928 	g_topology_assert();
929 
930 	if (sc == NULL)
931 		return (ENXIO);
932 
933 	gp = sc->sc_geom;
934 	pp = LIST_FIRST(&gp->provider);
935 	if (pp != NULL && (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)) {
936 		if (force) {
937 			G_ELI_DEBUG(1, "Device %s is still open, so it "
938 			    "cannot be definitely removed.", pp->name);
939 		} else {
940 			G_ELI_DEBUG(1,
941 			    "Device %s is still open (r%dw%de%d).", pp->name,
942 			    pp->acr, pp->acw, pp->ace);
943 			return (EBUSY);
944 		}
945 	}
946 
947 	mtx_lock(&sc->sc_queue_mtx);
948 	sc->sc_flags |= G_ELI_FLAG_DESTROY;
949 	wakeup(sc);
950 	while (!LIST_EMPTY(&sc->sc_workers)) {
951 		msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
952 		    "geli:destroy", 0);
953 	}
954 	mtx_destroy(&sc->sc_queue_mtx);
955 	gp->softc = NULL;
956 	if (sc->sc_ekeys != NULL) {
957 		/* The sc_ekeys field can be NULL is device is suspended. */
958 		bzero(sc->sc_ekeys,
959 		    sc->sc_nekeys * (sizeof(uint8_t *) + G_ELI_DATAKEYLEN));
960 		free(sc->sc_ekeys, M_ELI);
961 	}
962 	bzero(sc, sizeof(*sc));
963 	free(sc, M_ELI);
964 
965 	if (pp == NULL || (pp->acr == 0 && pp->acw == 0 && pp->ace == 0))
966 		G_ELI_DEBUG(0, "Device %s destroyed.", gp->name);
967 	g_wither_geom_close(gp, ENXIO);
968 
969 	return (0);
970 }
971 
972 static int
973 g_eli_destroy_geom(struct gctl_req *req __unused,
974     struct g_class *mp __unused, struct g_geom *gp)
975 {
976 	struct g_eli_softc *sc;
977 
978 	sc = gp->softc;
979 	return (g_eli_destroy(sc, FALSE));
980 }
981 
982 static int
983 g_eli_keyfiles_load(struct hmac_ctx *ctx, const char *provider)
984 {
985 	u_char *keyfile, *data;
986 	char *file, name[64];
987 	size_t size;
988 	int i;
989 
990 	for (i = 0; ; i++) {
991 		snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
992 		keyfile = preload_search_by_type(name);
993 		if (keyfile == NULL)
994 			return (i);	/* Return number of loaded keyfiles. */
995 		data = preload_fetch_addr(keyfile);
996 		if (data == NULL) {
997 			G_ELI_DEBUG(0, "Cannot find key file data for %s.",
998 			    name);
999 			return (0);
1000 		}
1001 		size = preload_fetch_size(keyfile);
1002 		if (size == 0) {
1003 			G_ELI_DEBUG(0, "Cannot find key file size for %s.",
1004 			    name);
1005 			return (0);
1006 		}
1007 		file = preload_search_info(keyfile, MODINFO_NAME);
1008 		if (file == NULL) {
1009 			G_ELI_DEBUG(0, "Cannot find key file name for %s.",
1010 			    name);
1011 			return (0);
1012 		}
1013 		G_ELI_DEBUG(1, "Loaded keyfile %s for %s (type: %s).", file,
1014 		    provider, name);
1015 		g_eli_crypto_hmac_update(ctx, data, size);
1016 	}
1017 }
1018 
1019 static void
1020 g_eli_keyfiles_clear(const char *provider)
1021 {
1022 	u_char *keyfile, *data;
1023 	char name[64];
1024 	size_t size;
1025 	int i;
1026 
1027 	for (i = 0; ; i++) {
1028 		snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
1029 		keyfile = preload_search_by_type(name);
1030 		if (keyfile == NULL)
1031 			return;
1032 		data = preload_fetch_addr(keyfile);
1033 		size = preload_fetch_size(keyfile);
1034 		if (data != NULL && size != 0)
1035 			bzero(data, size);
1036 	}
1037 }
1038 
1039 /*
1040  * Tasting is only made on boot.
1041  * We detect providers which should be attached before root is mounted.
1042  */
1043 static struct g_geom *
1044 g_eli_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
1045 {
1046 	struct g_eli_metadata md;
1047 	struct g_geom *gp;
1048 	struct hmac_ctx ctx;
1049 	char passphrase[256];
1050 	u_char key[G_ELI_USERKEYLEN], mkey[G_ELI_DATAIVKEYLEN];
1051 	u_int i, nkey, nkeyfiles, tries;
1052 	int error;
1053 
1054 	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
1055 	g_topology_assert();
1056 
1057 	if (root_mounted() || g_eli_tries == 0)
1058 		return (NULL);
1059 
1060 	G_ELI_DEBUG(3, "Tasting %s.", pp->name);
1061 
1062 	error = g_eli_read_metadata(mp, pp, &md);
1063 	if (error != 0)
1064 		return (NULL);
1065 	gp = NULL;
1066 
1067 	if (strcmp(md.md_magic, G_ELI_MAGIC) != 0)
1068 		return (NULL);
1069 	if (md.md_version > G_ELI_VERSION) {
1070 		printf("geom_eli.ko module is too old to handle %s.\n",
1071 		    pp->name);
1072 		return (NULL);
1073 	}
1074 	if (md.md_provsize != pp->mediasize)
1075 		return (NULL);
1076 	/* Should we attach it on boot? */
1077 	if (!(md.md_flags & G_ELI_FLAG_BOOT))
1078 		return (NULL);
1079 	if (md.md_keys == 0x00) {
1080 		G_ELI_DEBUG(0, "No valid keys on %s.", pp->name);
1081 		return (NULL);
1082 	}
1083 	if (md.md_iterations == -1) {
1084 		/* If there is no passphrase, we try only once. */
1085 		tries = 1;
1086 	} else {
1087 		/* Ask for the passphrase no more than g_eli_tries times. */
1088 		tries = g_eli_tries;
1089 	}
1090 
1091 	for (i = 0; i < tries; i++) {
1092 		g_eli_crypto_hmac_init(&ctx, NULL, 0);
1093 
1094 		/*
1095 		 * Load all key files.
1096 		 */
1097 		nkeyfiles = g_eli_keyfiles_load(&ctx, pp->name);
1098 
1099 		if (nkeyfiles == 0 && md.md_iterations == -1) {
1100 			/*
1101 			 * No key files and no passphrase, something is
1102 			 * definitely wrong here.
1103 			 * geli(8) doesn't allow for such situation, so assume
1104 			 * that there was really no passphrase and in that case
1105 			 * key files are no properly defined in loader.conf.
1106 			 */
1107 			G_ELI_DEBUG(0,
1108 			    "Found no key files in loader.conf for %s.",
1109 			    pp->name);
1110 			return (NULL);
1111 		}
1112 
1113 		/* Ask for the passphrase if defined. */
1114 		if (md.md_iterations >= 0) {
1115 			printf("Enter passphrase for %s: ", pp->name);
1116 			gets(passphrase, sizeof(passphrase),
1117 			    g_eli_visible_passphrase);
1118 		}
1119 
1120 		/*
1121 		 * Prepare Derived-Key from the user passphrase.
1122 		 */
1123 		if (md.md_iterations == 0) {
1124 			g_eli_crypto_hmac_update(&ctx, md.md_salt,
1125 			    sizeof(md.md_salt));
1126 			g_eli_crypto_hmac_update(&ctx, passphrase,
1127 			    strlen(passphrase));
1128 			bzero(passphrase, sizeof(passphrase));
1129 		} else if (md.md_iterations > 0) {
1130 			u_char dkey[G_ELI_USERKEYLEN];
1131 
1132 			pkcs5v2_genkey(dkey, sizeof(dkey), md.md_salt,
1133 			    sizeof(md.md_salt), passphrase, md.md_iterations);
1134 			bzero(passphrase, sizeof(passphrase));
1135 			g_eli_crypto_hmac_update(&ctx, dkey, sizeof(dkey));
1136 			bzero(dkey, sizeof(dkey));
1137 		}
1138 
1139 		g_eli_crypto_hmac_final(&ctx, key, 0);
1140 
1141 		/*
1142 		 * Decrypt Master-Key.
1143 		 */
1144 		error = g_eli_mkey_decrypt(&md, key, mkey, &nkey);
1145 		bzero(key, sizeof(key));
1146 		if (error == -1) {
1147 			if (i == tries - 1) {
1148 				G_ELI_DEBUG(0,
1149 				    "Wrong key for %s. No tries left.",
1150 				    pp->name);
1151 				g_eli_keyfiles_clear(pp->name);
1152 				return (NULL);
1153 			}
1154 			G_ELI_DEBUG(0, "Wrong key for %s. Tries left: %u.",
1155 			    pp->name, tries - i - 1);
1156 			/* Try again. */
1157 			continue;
1158 		} else if (error > 0) {
1159 			G_ELI_DEBUG(0, "Cannot decrypt Master Key for %s (error=%d).",
1160 			    pp->name, error);
1161 			g_eli_keyfiles_clear(pp->name);
1162 			return (NULL);
1163 		}
1164 		G_ELI_DEBUG(1, "Using Master Key %u for %s.", nkey, pp->name);
1165 		break;
1166 	}
1167 
1168 	/*
1169 	 * We have correct key, let's attach provider.
1170 	 */
1171 	gp = g_eli_create(NULL, mp, pp, &md, mkey, nkey);
1172 	bzero(mkey, sizeof(mkey));
1173 	bzero(&md, sizeof(md));
1174 	if (gp == NULL) {
1175 		G_ELI_DEBUG(0, "Cannot create device %s%s.", pp->name,
1176 		    G_ELI_SUFFIX);
1177 		return (NULL);
1178 	}
1179 	return (gp);
1180 }
1181 
1182 static void
1183 g_eli_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
1184     struct g_consumer *cp, struct g_provider *pp)
1185 {
1186 	struct g_eli_softc *sc;
1187 
1188 	g_topology_assert();
1189 	sc = gp->softc;
1190 	if (sc == NULL)
1191 		return;
1192 	if (pp != NULL || cp != NULL)
1193 		return;	/* Nothing here. */
1194 	sbuf_printf(sb, "%s<Flags>", indent);
1195 	if (sc->sc_flags == 0)
1196 		sbuf_printf(sb, "NONE");
1197 	else {
1198 		int first = 1;
1199 
1200 #define ADD_FLAG(flag, name)	do {					\
1201 	if (sc->sc_flags & (flag)) {					\
1202 		if (!first)						\
1203 			sbuf_printf(sb, ", ");				\
1204 		else							\
1205 			first = 0;					\
1206 		sbuf_printf(sb, name);					\
1207 	}								\
1208 } while (0)
1209 		ADD_FLAG(G_ELI_FLAG_SUSPEND, "SUSPEND");
1210 		ADD_FLAG(G_ELI_FLAG_SINGLE_KEY, "SINGLE-KEY");
1211 		ADD_FLAG(G_ELI_FLAG_NATIVE_BYTE_ORDER, "NATIVE-BYTE-ORDER");
1212 		ADD_FLAG(G_ELI_FLAG_ONETIME, "ONETIME");
1213 		ADD_FLAG(G_ELI_FLAG_BOOT, "BOOT");
1214 		ADD_FLAG(G_ELI_FLAG_WO_DETACH, "W-DETACH");
1215 		ADD_FLAG(G_ELI_FLAG_RW_DETACH, "RW-DETACH");
1216 		ADD_FLAG(G_ELI_FLAG_AUTH, "AUTH");
1217 		ADD_FLAG(G_ELI_FLAG_WOPEN, "W-OPEN");
1218 		ADD_FLAG(G_ELI_FLAG_DESTROY, "DESTROY");
1219 		ADD_FLAG(G_ELI_FLAG_RO, "READ-ONLY");
1220 #undef  ADD_FLAG
1221 	}
1222 	sbuf_printf(sb, "</Flags>\n");
1223 
1224 	if (!(sc->sc_flags & G_ELI_FLAG_ONETIME)) {
1225 		sbuf_printf(sb, "%s<UsedKey>%u</UsedKey>\n", indent,
1226 		    sc->sc_nkey);
1227 	}
1228 	sbuf_printf(sb, "%s<Crypto>", indent);
1229 	switch (sc->sc_crypto) {
1230 	case G_ELI_CRYPTO_HW:
1231 		sbuf_printf(sb, "hardware");
1232 		break;
1233 	case G_ELI_CRYPTO_SW:
1234 		sbuf_printf(sb, "software");
1235 		break;
1236 	default:
1237 		sbuf_printf(sb, "UNKNOWN");
1238 		break;
1239 	}
1240 	sbuf_printf(sb, "</Crypto>\n");
1241 	if (sc->sc_flags & G_ELI_FLAG_AUTH) {
1242 		sbuf_printf(sb,
1243 		    "%s<AuthenticationAlgorithm>%s</AuthenticationAlgorithm>\n",
1244 		    indent, g_eli_algo2str(sc->sc_aalgo));
1245 	}
1246 	sbuf_printf(sb, "%s<KeyLength>%u</KeyLength>\n", indent,
1247 	    sc->sc_ekeylen);
1248 	sbuf_printf(sb, "%s<EncryptionAlgorithm>%s</EncryptionAlgorithm>\n", indent,
1249 	    g_eli_algo2str(sc->sc_ealgo));
1250 	sbuf_printf(sb, "%s<State>%s</State>\n", indent,
1251 	    (sc->sc_flags & G_ELI_FLAG_SUSPEND) ? "SUSPENDED" : "ACTIVE");
1252 }
1253 
1254 static void
1255 g_eli_shutdown_pre_sync(void *arg, int howto)
1256 {
1257 	struct g_class *mp;
1258 	struct g_geom *gp, *gp2;
1259 	struct g_provider *pp;
1260 	struct g_eli_softc *sc;
1261 	int error;
1262 
1263 	mp = arg;
1264 	DROP_GIANT();
1265 	g_topology_lock();
1266 	LIST_FOREACH_SAFE(gp, &mp->geom, geom, gp2) {
1267 		sc = gp->softc;
1268 		if (sc == NULL)
1269 			continue;
1270 		pp = LIST_FIRST(&gp->provider);
1271 		KASSERT(pp != NULL, ("No provider? gp=%p (%s)", gp, gp->name));
1272 		if (pp->acr + pp->acw + pp->ace == 0)
1273 			error = g_eli_destroy(sc, TRUE);
1274 		else {
1275 			sc->sc_flags |= G_ELI_FLAG_RW_DETACH;
1276 			gp->access = g_eli_access;
1277 		}
1278 	}
1279 	g_topology_unlock();
1280 	PICKUP_GIANT();
1281 }
1282 
1283 static void
1284 g_eli_init(struct g_class *mp)
1285 {
1286 
1287 	g_eli_pre_sync = EVENTHANDLER_REGISTER(shutdown_pre_sync,
1288 	    g_eli_shutdown_pre_sync, mp, SHUTDOWN_PRI_FIRST);
1289 	if (g_eli_pre_sync == NULL)
1290 		G_ELI_DEBUG(0, "Warning! Cannot register shutdown event.");
1291 }
1292 
1293 static void
1294 g_eli_fini(struct g_class *mp)
1295 {
1296 
1297 	if (g_eli_pre_sync != NULL)
1298 		EVENTHANDLER_DEREGISTER(shutdown_pre_sync, g_eli_pre_sync);
1299 }
1300 
1301 DECLARE_GEOM_CLASS(g_eli_class, g_eli);
1302 MODULE_DEPEND(g_eli, crypto, 1, 1, 1);
1303