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