xref: /freebsd/sys/geom/eli/g_eli.c (revision 94a82666846d62cdff7d78f78d428df35412e50d)
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 crypto_session_params csp;
492 	uint32_t caps;
493 	int error, new_crypto;
494 	void *key;
495 
496 	sc = wr->w_softc;
497 
498 	memset(&csp, 0, sizeof(csp));
499 	csp.csp_mode = CSP_MODE_CIPHER;
500 	csp.csp_cipher_alg = sc->sc_ealgo;
501 	csp.csp_ivlen = g_eli_ivlen(sc->sc_ealgo);
502 	csp.csp_cipher_klen = sc->sc_ekeylen / 8;
503 	if (sc->sc_ealgo == CRYPTO_AES_XTS)
504 		csp.csp_cipher_klen <<= 1;
505 	if ((sc->sc_flags & G_ELI_FLAG_FIRST_KEY) != 0) {
506 		key = g_eli_key_hold(sc, 0,
507 		    LIST_FIRST(&sc->sc_geom->consumer)->provider->sectorsize);
508 		csp.csp_cipher_key = key;
509 	} else {
510 		key = NULL;
511 		csp.csp_cipher_key = sc->sc_ekey;
512 	}
513 	if (sc->sc_flags & G_ELI_FLAG_AUTH) {
514 		csp.csp_mode = CSP_MODE_ETA;
515 		csp.csp_auth_alg = sc->sc_aalgo;
516 		csp.csp_auth_klen = G_ELI_AUTH_SECKEYLEN;
517 	}
518 
519 	switch (sc->sc_crypto) {
520 	case G_ELI_CRYPTO_SW_ACCEL:
521 	case G_ELI_CRYPTO_SW:
522 		error = crypto_newsession(&wr->w_sid, &csp,
523 		    CRYPTOCAP_F_SOFTWARE);
524 		break;
525 	case G_ELI_CRYPTO_HW:
526 		error = crypto_newsession(&wr->w_sid, &csp,
527 		    CRYPTOCAP_F_HARDWARE);
528 		break;
529 	case G_ELI_CRYPTO_UNKNOWN:
530 		error = crypto_newsession(&wr->w_sid, &csp,
531 		    CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE);
532 		if (error == 0) {
533 			caps = crypto_ses2caps(wr->w_sid);
534 			if (caps & CRYPTOCAP_F_HARDWARE)
535 				new_crypto = G_ELI_CRYPTO_HW;
536 			else if (caps & CRYPTOCAP_F_ACCEL_SOFTWARE)
537 				new_crypto = G_ELI_CRYPTO_SW_ACCEL;
538 			else
539 				new_crypto = G_ELI_CRYPTO_SW;
540 			mtx_lock(&sc->sc_queue_mtx);
541 			if (sc->sc_crypto == G_ELI_CRYPTO_UNKNOWN)
542 				sc->sc_crypto = new_crypto;
543 			mtx_unlock(&sc->sc_queue_mtx);
544 		}
545 		break;
546 	default:
547 		panic("%s: invalid condition", __func__);
548 	}
549 
550 	if ((sc->sc_flags & G_ELI_FLAG_FIRST_KEY) != 0) {
551 		if (error)
552 			g_eli_key_drop(sc, key);
553 		else
554 			wr->w_first_key = key;
555 	}
556 
557 	return (error);
558 }
559 
560 static void
561 g_eli_freesession(struct g_eli_worker *wr)
562 {
563 	struct g_eli_softc *sc;
564 
565 	crypto_freesession(wr->w_sid);
566 	if (wr->w_first_key != NULL) {
567 		sc = wr->w_softc;
568 		g_eli_key_drop(sc, wr->w_first_key);
569 		wr->w_first_key = NULL;
570 	}
571 }
572 
573 static void
574 g_eli_cancel(struct g_eli_softc *sc)
575 {
576 	struct bio *bp;
577 
578 	mtx_assert(&sc->sc_queue_mtx, MA_OWNED);
579 
580 	while ((bp = bioq_takefirst(&sc->sc_queue)) != NULL) {
581 		KASSERT(bp->bio_pflags == G_ELI_NEW_BIO,
582 		    ("Not new bio when canceling (bp=%p).", bp));
583 		g_io_deliver(bp, ENXIO);
584 	}
585 }
586 
587 static struct bio *
588 g_eli_takefirst(struct g_eli_softc *sc)
589 {
590 	struct bio *bp;
591 
592 	mtx_assert(&sc->sc_queue_mtx, MA_OWNED);
593 
594 	if (!(sc->sc_flags & G_ELI_FLAG_SUSPEND))
595 		return (bioq_takefirst(&sc->sc_queue));
596 	/*
597 	 * Device suspended, so we skip new I/O requests.
598 	 */
599 	TAILQ_FOREACH(bp, &sc->sc_queue.queue, bio_queue) {
600 		if (bp->bio_pflags != G_ELI_NEW_BIO)
601 			break;
602 	}
603 	if (bp != NULL)
604 		bioq_remove(&sc->sc_queue, bp);
605 	return (bp);
606 }
607 
608 /*
609  * This is the main function for kernel worker thread when we don't have
610  * hardware acceleration and we have to do cryptography in software.
611  * Dedicated thread is needed, so we don't slow down g_up/g_down GEOM
612  * threads with crypto work.
613  */
614 static void
615 g_eli_worker(void *arg)
616 {
617 	struct g_eli_softc *sc;
618 	struct g_eli_worker *wr;
619 	struct bio *bp;
620 	int error;
621 
622 	wr = arg;
623 	sc = wr->w_softc;
624 #ifdef EARLY_AP_STARTUP
625 	MPASS(!sc->sc_cpubind || smp_started);
626 #elif defined(SMP)
627 	/* Before sched_bind() to a CPU, wait for all CPUs to go on-line. */
628 	if (sc->sc_cpubind) {
629 		while (!smp_started)
630 			tsleep(wr, 0, "geli:smp", hz / 4);
631 	}
632 #endif
633 	thread_lock(curthread);
634 	sched_prio(curthread, PUSER);
635 	if (sc->sc_cpubind)
636 		sched_bind(curthread, wr->w_number % mp_ncpus);
637 	thread_unlock(curthread);
638 
639 	G_ELI_DEBUG(1, "Thread %s started.", curthread->td_proc->p_comm);
640 
641 	for (;;) {
642 		mtx_lock(&sc->sc_queue_mtx);
643 again:
644 		bp = g_eli_takefirst(sc);
645 		if (bp == NULL) {
646 			if (sc->sc_flags & G_ELI_FLAG_DESTROY) {
647 				g_eli_cancel(sc);
648 				LIST_REMOVE(wr, w_next);
649 				g_eli_freesession(wr);
650 				free(wr, M_ELI);
651 				G_ELI_DEBUG(1, "Thread %s exiting.",
652 				    curthread->td_proc->p_comm);
653 				wakeup(&sc->sc_workers);
654 				mtx_unlock(&sc->sc_queue_mtx);
655 				kproc_exit(0);
656 			}
657 			while (sc->sc_flags & G_ELI_FLAG_SUSPEND) {
658 				if (sc->sc_inflight > 0) {
659 					G_ELI_DEBUG(0, "inflight=%d",
660 					    sc->sc_inflight);
661 					/*
662 					 * We still have inflight BIOs, so
663 					 * sleep and retry.
664 					 */
665 					msleep(sc, &sc->sc_queue_mtx, PRIBIO,
666 					    "geli:inf", hz / 5);
667 					goto again;
668 				}
669 				/*
670 				 * Suspend requested, mark the worker as
671 				 * suspended and go to sleep.
672 				 */
673 				if (wr->w_active) {
674 					g_eli_freesession(wr);
675 					wr->w_active = FALSE;
676 				}
677 				wakeup(&sc->sc_workers);
678 				msleep(sc, &sc->sc_queue_mtx, PRIBIO,
679 				    "geli:suspend", 0);
680 				if (!wr->w_active &&
681 				    !(sc->sc_flags & G_ELI_FLAG_SUSPEND)) {
682 					error = g_eli_newsession(wr);
683 					KASSERT(error == 0,
684 					    ("g_eli_newsession() failed on resume (error=%d)",
685 					    error));
686 					wr->w_active = TRUE;
687 				}
688 				goto again;
689 			}
690 			msleep(sc, &sc->sc_queue_mtx, PDROP, "geli:w", 0);
691 			continue;
692 		}
693 		if (bp->bio_pflags == G_ELI_NEW_BIO)
694 			atomic_add_int(&sc->sc_inflight, 1);
695 		mtx_unlock(&sc->sc_queue_mtx);
696 		if (bp->bio_pflags == G_ELI_NEW_BIO) {
697 			bp->bio_pflags = 0;
698 			if (sc->sc_flags & G_ELI_FLAG_AUTH) {
699 				if (bp->bio_cmd == BIO_READ)
700 					g_eli_auth_read(sc, bp);
701 				else
702 					g_eli_auth_run(wr, bp);
703 			} else {
704 				if (bp->bio_cmd == BIO_READ)
705 					g_eli_crypto_read(sc, bp, 1);
706 				else
707 					g_eli_crypto_run(wr, bp);
708 			}
709 		} else {
710 			if (sc->sc_flags & G_ELI_FLAG_AUTH)
711 				g_eli_auth_run(wr, bp);
712 			else
713 				g_eli_crypto_run(wr, bp);
714 		}
715 	}
716 }
717 
718 static int
719 g_eli_read_metadata_offset(struct g_class *mp, struct g_provider *pp,
720     off_t offset, struct g_eli_metadata *md)
721 {
722 	struct g_geom *gp;
723 	struct g_consumer *cp;
724 	u_char *buf = NULL;
725 	int error;
726 
727 	g_topology_assert();
728 
729 	gp = g_new_geomf(mp, "eli:taste");
730 	gp->start = g_eli_start;
731 	gp->access = g_std_access;
732 	/*
733 	 * g_eli_read_metadata() is always called from the event thread.
734 	 * Our geom is created and destroyed in the same event, so there
735 	 * could be no orphan nor spoil event in the meantime.
736 	 */
737 	gp->orphan = g_eli_orphan_spoil_assert;
738 	gp->spoiled = g_eli_orphan_spoil_assert;
739 	cp = g_new_consumer(gp);
740 	error = g_attach(cp, pp);
741 	if (error != 0)
742 		goto end;
743 	error = g_access(cp, 1, 0, 0);
744 	if (error != 0)
745 		goto end;
746 	g_topology_unlock();
747 	buf = g_read_data(cp, offset, pp->sectorsize, &error);
748 	g_topology_lock();
749 	if (buf == NULL)
750 		goto end;
751 	error = eli_metadata_decode(buf, md);
752 	if (error != 0)
753 		goto end;
754 	/* Metadata was read and decoded successfully. */
755 end:
756 	if (buf != NULL)
757 		g_free(buf);
758 	if (cp->provider != NULL) {
759 		if (cp->acr == 1)
760 			g_access(cp, -1, 0, 0);
761 		g_detach(cp);
762 	}
763 	g_destroy_consumer(cp);
764 	g_destroy_geom(gp);
765 	return (error);
766 }
767 
768 int
769 g_eli_read_metadata(struct g_class *mp, struct g_provider *pp,
770     struct g_eli_metadata *md)
771 {
772 
773 	return (g_eli_read_metadata_offset(mp, pp,
774 	    pp->mediasize - pp->sectorsize, md));
775 }
776 
777 /*
778  * The function is called when we had last close on provider and user requested
779  * to close it when this situation occur.
780  */
781 static void
782 g_eli_last_close(void *arg, int flags __unused)
783 {
784 	struct g_geom *gp;
785 	char gpname[64];
786 	int error;
787 
788 	g_topology_assert();
789 	gp = arg;
790 	strlcpy(gpname, gp->name, sizeof(gpname));
791 	error = g_eli_destroy(gp->softc, TRUE);
792 	KASSERT(error == 0, ("Cannot detach %s on last close (error=%d).",
793 	    gpname, error));
794 	G_ELI_DEBUG(0, "Detached %s on last close.", gpname);
795 }
796 
797 int
798 g_eli_access(struct g_provider *pp, int dr, int dw, int de)
799 {
800 	struct g_eli_softc *sc;
801 	struct g_geom *gp;
802 
803 	gp = pp->geom;
804 	sc = gp->softc;
805 
806 	if (dw > 0) {
807 		if (sc->sc_flags & G_ELI_FLAG_RO) {
808 			/* Deny write attempts. */
809 			return (EROFS);
810 		}
811 		/* Someone is opening us for write, we need to remember that. */
812 		sc->sc_flags |= G_ELI_FLAG_WOPEN;
813 		return (0);
814 	}
815 	/* Is this the last close? */
816 	if (pp->acr + dr > 0 || pp->acw + dw > 0 || pp->ace + de > 0)
817 		return (0);
818 
819 	/*
820 	 * Automatically detach on last close if requested.
821 	 */
822 	if ((sc->sc_flags & G_ELI_FLAG_RW_DETACH) ||
823 	    (sc->sc_flags & G_ELI_FLAG_WOPEN)) {
824 		g_post_event(g_eli_last_close, gp, M_WAITOK, NULL);
825 	}
826 	return (0);
827 }
828 
829 static int
830 g_eli_cpu_is_disabled(int cpu)
831 {
832 #ifdef SMP
833 	return (CPU_ISSET(cpu, &hlt_cpus_mask));
834 #else
835 	return (0);
836 #endif
837 }
838 
839 struct g_geom *
840 g_eli_create(struct gctl_req *req, struct g_class *mp, struct g_provider *bpp,
841     const struct g_eli_metadata *md, const u_char *mkey, int nkey)
842 {
843 	struct g_eli_softc *sc;
844 	struct g_eli_worker *wr;
845 	struct g_geom *gp;
846 	struct g_provider *pp;
847 	struct g_consumer *cp;
848 	struct g_geom_alias *gap;
849 	u_int i, threads;
850 	int dcw, error;
851 
852 	G_ELI_DEBUG(1, "Creating device %s%s.", bpp->name, G_ELI_SUFFIX);
853 	KASSERT(eli_metadata_crypto_supported(md),
854 	    ("%s: unsupported crypto for %s", __func__, bpp->name));
855 
856 	gp = g_new_geomf(mp, "%s%s", bpp->name, G_ELI_SUFFIX);
857 	sc = malloc(sizeof(*sc), M_ELI, M_WAITOK | M_ZERO);
858 	gp->start = g_eli_start;
859 	/*
860 	 * Spoiling can happen even though we have the provider open
861 	 * exclusively, e.g. through media change events.
862 	 */
863 	gp->spoiled = g_eli_orphan;
864 	gp->orphan = g_eli_orphan;
865 	gp->resize = g_eli_resize;
866 	gp->dumpconf = g_eli_dumpconf;
867 	/*
868 	 * If detach-on-last-close feature is not enabled and we don't operate
869 	 * on read-only provider, we can simply use g_std_access().
870 	 */
871 	if (md->md_flags & (G_ELI_FLAG_WO_DETACH | G_ELI_FLAG_RO))
872 		gp->access = g_eli_access;
873 	else
874 		gp->access = g_std_access;
875 
876 	eli_metadata_softc(sc, md, bpp->sectorsize, bpp->mediasize);
877 	sc->sc_nkey = nkey;
878 
879 	gp->softc = sc;
880 	sc->sc_geom = gp;
881 
882 	bioq_init(&sc->sc_queue);
883 	mtx_init(&sc->sc_queue_mtx, "geli:queue", NULL, MTX_DEF);
884 	mtx_init(&sc->sc_ekeys_lock, "geli:ekeys", NULL, MTX_DEF);
885 
886 	pp = NULL;
887 	cp = g_new_consumer(gp);
888 	error = g_attach(cp, bpp);
889 	if (error != 0) {
890 		if (req != NULL) {
891 			gctl_error(req, "Cannot attach to %s (error=%d).",
892 			    bpp->name, error);
893 		} else {
894 			G_ELI_DEBUG(1, "Cannot attach to %s (error=%d).",
895 			    bpp->name, error);
896 		}
897 		goto failed;
898 	}
899 	/*
900 	 * Keep provider open all the time, so we can run critical tasks,
901 	 * like Master Keys deletion, without wondering if we can open
902 	 * provider or not.
903 	 * We don't open provider for writing only when user requested read-only
904 	 * access.
905 	 */
906 	dcw = (sc->sc_flags & G_ELI_FLAG_RO) ? 0 : 1;
907 	error = g_access(cp, 1, dcw, 1);
908 	if (error != 0) {
909 		if (req != NULL) {
910 			gctl_error(req, "Cannot access %s (error=%d).",
911 			    bpp->name, error);
912 		} else {
913 			G_ELI_DEBUG(1, "Cannot access %s (error=%d).",
914 			    bpp->name, error);
915 		}
916 		goto failed;
917 	}
918 
919 	/*
920 	 * Remember the keys in our softc structure.
921 	 */
922 	g_eli_mkey_propagate(sc, mkey);
923 
924 	LIST_INIT(&sc->sc_workers);
925 
926 	threads = g_eli_threads;
927 	if (threads == 0)
928 		threads = mp_ncpus;
929 	sc->sc_cpubind = (mp_ncpus > 1 && threads == mp_ncpus);
930 	for (i = 0; i < threads; i++) {
931 		if (g_eli_cpu_is_disabled(i)) {
932 			G_ELI_DEBUG(1, "%s: CPU %u disabled, skipping.",
933 			    bpp->name, i);
934 			continue;
935 		}
936 		wr = malloc(sizeof(*wr), M_ELI, M_WAITOK | M_ZERO);
937 		wr->w_softc = sc;
938 		wr->w_number = i;
939 		wr->w_active = TRUE;
940 
941 		error = g_eli_newsession(wr);
942 		if (error != 0) {
943 			free(wr, M_ELI);
944 			if (req != NULL) {
945 				gctl_error(req, "Cannot set up crypto session "
946 				    "for %s (error=%d).", bpp->name, error);
947 			} else {
948 				G_ELI_DEBUG(1, "Cannot set up crypto session "
949 				    "for %s (error=%d).", bpp->name, error);
950 			}
951 			goto failed;
952 		}
953 
954 		error = kproc_create(g_eli_worker, wr, &wr->w_proc, 0, 0,
955 		    "g_eli[%u] %s", i, bpp->name);
956 		if (error != 0) {
957 			g_eli_freesession(wr);
958 			free(wr, M_ELI);
959 			if (req != NULL) {
960 				gctl_error(req, "Cannot create kernel thread "
961 				    "for %s (error=%d).", bpp->name, error);
962 			} else {
963 				G_ELI_DEBUG(1, "Cannot create kernel thread "
964 				    "for %s (error=%d).", bpp->name, error);
965 			}
966 			goto failed;
967 		}
968 		LIST_INSERT_HEAD(&sc->sc_workers, wr, w_next);
969 	}
970 
971 	/*
972 	 * Create decrypted provider.
973 	 */
974 	pp = g_new_providerf(gp, "%s%s", bpp->name, G_ELI_SUFFIX);
975 	pp->mediasize = sc->sc_mediasize;
976 	pp->sectorsize = sc->sc_sectorsize;
977 	LIST_FOREACH(gap, &bpp->aliases, ga_next)
978 		g_provider_add_alias(pp, "%s%s", gap->ga_alias, G_ELI_SUFFIX);
979 
980 	g_error_provider(pp, 0);
981 
982 	G_ELI_DEBUG(0, "Device %s created.", pp->name);
983 	G_ELI_DEBUG(0, "Encryption: %s %u", g_eli_algo2str(sc->sc_ealgo),
984 	    sc->sc_ekeylen);
985 	if (sc->sc_flags & G_ELI_FLAG_AUTH)
986 		G_ELI_DEBUG(0, " Integrity: %s", g_eli_algo2str(sc->sc_aalgo));
987 	G_ELI_DEBUG(0, "    Crypto: %s",
988 	    sc->sc_crypto == G_ELI_CRYPTO_SW_ACCEL ? "accelerated software" :
989 	    sc->sc_crypto == G_ELI_CRYPTO_SW ? "software" : "hardware");
990 	return (gp);
991 failed:
992 	mtx_lock(&sc->sc_queue_mtx);
993 	sc->sc_flags |= G_ELI_FLAG_DESTROY;
994 	wakeup(sc);
995 	/*
996 	 * Wait for kernel threads self destruction.
997 	 */
998 	while (!LIST_EMPTY(&sc->sc_workers)) {
999 		msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
1000 		    "geli:destroy", 0);
1001 	}
1002 	mtx_destroy(&sc->sc_queue_mtx);
1003 	if (cp->provider != NULL) {
1004 		if (cp->acr == 1)
1005 			g_access(cp, -1, -dcw, -1);
1006 		g_detach(cp);
1007 	}
1008 	g_destroy_consumer(cp);
1009 	g_destroy_geom(gp);
1010 	g_eli_key_destroy(sc);
1011 	bzero(sc, sizeof(*sc));
1012 	free(sc, M_ELI);
1013 	return (NULL);
1014 }
1015 
1016 int
1017 g_eli_destroy(struct g_eli_softc *sc, boolean_t force)
1018 {
1019 	struct g_geom *gp;
1020 	struct g_provider *pp;
1021 
1022 	g_topology_assert();
1023 
1024 	if (sc == NULL)
1025 		return (ENXIO);
1026 
1027 	gp = sc->sc_geom;
1028 	pp = LIST_FIRST(&gp->provider);
1029 	if (pp != NULL && (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)) {
1030 		if (force) {
1031 			G_ELI_DEBUG(1, "Device %s is still open, so it "
1032 			    "cannot be definitely removed.", pp->name);
1033 			sc->sc_flags |= G_ELI_FLAG_RW_DETACH;
1034 			gp->access = g_eli_access;
1035 			g_wither_provider(pp, ENXIO);
1036 			return (EBUSY);
1037 		} else {
1038 			G_ELI_DEBUG(1,
1039 			    "Device %s is still open (r%dw%de%d).", pp->name,
1040 			    pp->acr, pp->acw, pp->ace);
1041 			return (EBUSY);
1042 		}
1043 	}
1044 
1045 	mtx_lock(&sc->sc_queue_mtx);
1046 	sc->sc_flags |= G_ELI_FLAG_DESTROY;
1047 	wakeup(sc);
1048 	while (!LIST_EMPTY(&sc->sc_workers)) {
1049 		msleep(&sc->sc_workers, &sc->sc_queue_mtx, PRIBIO,
1050 		    "geli:destroy", 0);
1051 	}
1052 	mtx_destroy(&sc->sc_queue_mtx);
1053 	gp->softc = NULL;
1054 	g_eli_key_destroy(sc);
1055 	bzero(sc, sizeof(*sc));
1056 	free(sc, M_ELI);
1057 
1058 	G_ELI_DEBUG(0, "Device %s destroyed.", gp->name);
1059 	g_wither_geom_close(gp, ENXIO);
1060 
1061 	return (0);
1062 }
1063 
1064 static int
1065 g_eli_destroy_geom(struct gctl_req *req __unused,
1066     struct g_class *mp __unused, struct g_geom *gp)
1067 {
1068 	struct g_eli_softc *sc;
1069 
1070 	sc = gp->softc;
1071 	return (g_eli_destroy(sc, FALSE));
1072 }
1073 
1074 static int
1075 g_eli_keyfiles_load(struct hmac_ctx *ctx, const char *provider)
1076 {
1077 	u_char *keyfile, *data;
1078 	char *file, name[64];
1079 	size_t size;
1080 	int i;
1081 
1082 	for (i = 0; ; i++) {
1083 		snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
1084 		keyfile = preload_search_by_type(name);
1085 		if (keyfile == NULL && i == 0) {
1086 			/*
1087 			 * If there is only one keyfile, allow simpler name.
1088 			 */
1089 			snprintf(name, sizeof(name), "%s:geli_keyfile", provider);
1090 			keyfile = preload_search_by_type(name);
1091 		}
1092 		if (keyfile == NULL)
1093 			return (i);	/* Return number of loaded keyfiles. */
1094 		data = preload_fetch_addr(keyfile);
1095 		if (data == NULL) {
1096 			G_ELI_DEBUG(0, "Cannot find key file data for %s.",
1097 			    name);
1098 			return (0);
1099 		}
1100 		size = preload_fetch_size(keyfile);
1101 		if (size == 0) {
1102 			G_ELI_DEBUG(0, "Cannot find key file size for %s.",
1103 			    name);
1104 			return (0);
1105 		}
1106 		file = preload_search_info(keyfile, MODINFO_NAME);
1107 		if (file == NULL) {
1108 			G_ELI_DEBUG(0, "Cannot find key file name for %s.",
1109 			    name);
1110 			return (0);
1111 		}
1112 		G_ELI_DEBUG(1, "Loaded keyfile %s for %s (type: %s).", file,
1113 		    provider, name);
1114 		g_eli_crypto_hmac_update(ctx, data, size);
1115 	}
1116 }
1117 
1118 static void
1119 g_eli_keyfiles_clear(const char *provider)
1120 {
1121 	u_char *keyfile, *data;
1122 	char name[64];
1123 	size_t size;
1124 	int i;
1125 
1126 	for (i = 0; ; i++) {
1127 		snprintf(name, sizeof(name), "%s:geli_keyfile%d", provider, i);
1128 		keyfile = preload_search_by_type(name);
1129 		if (keyfile == NULL)
1130 			return;
1131 		data = preload_fetch_addr(keyfile);
1132 		size = preload_fetch_size(keyfile);
1133 		if (data != NULL && size != 0)
1134 			bzero(data, size);
1135 	}
1136 }
1137 
1138 /*
1139  * Tasting is only made on boot.
1140  * We detect providers which should be attached before root is mounted.
1141  */
1142 static struct g_geom *
1143 g_eli_taste(struct g_class *mp, struct g_provider *pp, int flags __unused)
1144 {
1145 	struct g_eli_metadata md;
1146 	struct g_geom *gp;
1147 	struct hmac_ctx ctx;
1148 	char passphrase[256];
1149 	u_char key[G_ELI_USERKEYLEN], mkey[G_ELI_DATAIVKEYLEN];
1150 	u_int i, nkey, nkeyfiles, tries, showpass;
1151 	int error;
1152         struct keybuf *keybuf;
1153 
1154 	g_trace(G_T_TOPOLOGY, "%s(%s, %s)", __func__, mp->name, pp->name);
1155 	g_topology_assert();
1156 
1157 	if (root_mounted() || g_eli_tries == 0)
1158 		return (NULL);
1159 
1160 	G_ELI_DEBUG(3, "Tasting %s.", pp->name);
1161 
1162 	error = g_eli_read_metadata(mp, pp, &md);
1163 	if (error != 0)
1164 		return (NULL);
1165 	gp = NULL;
1166 
1167 	if (strcmp(md.md_magic, G_ELI_MAGIC) != 0)
1168 		return (NULL);
1169 	if (md.md_version > G_ELI_VERSION) {
1170 		printf("geom_eli.ko module is too old to handle %s.\n",
1171 		    pp->name);
1172 		return (NULL);
1173 	}
1174 	if (md.md_provsize != pp->mediasize)
1175 		return (NULL);
1176 	/* Should we attach it on boot? */
1177 	if (!(md.md_flags & G_ELI_FLAG_BOOT) &&
1178 	    !(md.md_flags & G_ELI_FLAG_GELIBOOT))
1179 		return (NULL);
1180 	if (md.md_keys == 0x00) {
1181 		G_ELI_DEBUG(0, "No valid keys on %s.", pp->name);
1182 		return (NULL);
1183 	}
1184 	if (!eli_metadata_crypto_supported(&md)) {
1185 		G_ELI_DEBUG(0, "%s uses invalid or unsupported algorithms\n",
1186 		    pp->name);
1187 		return (NULL);
1188 	}
1189 	if (md.md_iterations == -1) {
1190 		/* If there is no passphrase, we try only once. */
1191 		tries = 1;
1192 	} else {
1193 		/* Ask for the passphrase no more than g_eli_tries times. */
1194 		tries = g_eli_tries;
1195 	}
1196 
1197         if ((keybuf = get_keybuf()) != NULL) {
1198                 /* Scan the key buffer, try all GELI keys. */
1199                 for (i = 0; i < keybuf->kb_nents; i++) {
1200                          if (keybuf->kb_ents[i].ke_type == KEYBUF_TYPE_GELI) {
1201                                  memcpy(key, keybuf->kb_ents[i].ke_data,
1202                                      sizeof(key));
1203 
1204                                  if (g_eli_mkey_decrypt_any(&md, key,
1205                                      mkey, &nkey) == 0 ) {
1206                                          explicit_bzero(key, sizeof(key));
1207                                          goto have_key;
1208                                  }
1209                          }
1210                 }
1211         }
1212 
1213         for (i = 0; i <= tries; i++) {
1214                 g_eli_crypto_hmac_init(&ctx, NULL, 0);
1215 
1216                 /*
1217                  * Load all key files.
1218                  */
1219                 nkeyfiles = g_eli_keyfiles_load(&ctx, pp->name);
1220 
1221                 if (nkeyfiles == 0 && md.md_iterations == -1) {
1222                         /*
1223                          * No key files and no passphrase, something is
1224                          * definitely wrong here.
1225                          * geli(8) doesn't allow for such situation, so assume
1226                          * that there was really no passphrase and in that case
1227                          * key files are no properly defined in loader.conf.
1228                          */
1229                         G_ELI_DEBUG(0,
1230                             "Found no key files in loader.conf for %s.",
1231                             pp->name);
1232                         return (NULL);
1233                 }
1234 
1235                 /* Ask for the passphrase if defined. */
1236                 if (md.md_iterations >= 0) {
1237                         /* Try first with cached passphrase. */
1238                         if (i == 0) {
1239                                 if (!g_eli_boot_passcache)
1240                                         continue;
1241                                 memcpy(passphrase, cached_passphrase,
1242                                     sizeof(passphrase));
1243                         } else {
1244                                 printf("Enter passphrase for %s: ", pp->name);
1245 				showpass = g_eli_visible_passphrase;
1246 				if ((md.md_flags & G_ELI_FLAG_GELIDISPLAYPASS) != 0)
1247 					showpass = GETS_ECHOPASS;
1248                                 cngets(passphrase, sizeof(passphrase),
1249 				    showpass);
1250                                 memcpy(cached_passphrase, passphrase,
1251                                     sizeof(passphrase));
1252                         }
1253                 }
1254 
1255                 /*
1256                  * Prepare Derived-Key from the user passphrase.
1257                  */
1258                 if (md.md_iterations == 0) {
1259                         g_eli_crypto_hmac_update(&ctx, md.md_salt,
1260                             sizeof(md.md_salt));
1261                         g_eli_crypto_hmac_update(&ctx, passphrase,
1262                             strlen(passphrase));
1263                         explicit_bzero(passphrase, sizeof(passphrase));
1264                 } else if (md.md_iterations > 0) {
1265                         u_char dkey[G_ELI_USERKEYLEN];
1266 
1267                         pkcs5v2_genkey(dkey, sizeof(dkey), md.md_salt,
1268                             sizeof(md.md_salt), passphrase, md.md_iterations);
1269                         bzero(passphrase, sizeof(passphrase));
1270                         g_eli_crypto_hmac_update(&ctx, dkey, sizeof(dkey));
1271                         explicit_bzero(dkey, sizeof(dkey));
1272                 }
1273 
1274                 g_eli_crypto_hmac_final(&ctx, key, 0);
1275 
1276                 /*
1277                  * Decrypt Master-Key.
1278                  */
1279                 error = g_eli_mkey_decrypt_any(&md, key, mkey, &nkey);
1280                 bzero(key, sizeof(key));
1281                 if (error == -1) {
1282                         if (i == tries) {
1283                                 G_ELI_DEBUG(0,
1284                                     "Wrong key for %s. No tries left.",
1285                                     pp->name);
1286                                 g_eli_keyfiles_clear(pp->name);
1287                                 return (NULL);
1288                         }
1289                         if (i > 0) {
1290                                 G_ELI_DEBUG(0,
1291                                     "Wrong key for %s. Tries left: %u.",
1292                                     pp->name, tries - i);
1293                         }
1294                         /* Try again. */
1295                         continue;
1296                 } else if (error > 0) {
1297                         G_ELI_DEBUG(0,
1298                             "Cannot decrypt Master Key for %s (error=%d).",
1299                             pp->name, error);
1300                         g_eli_keyfiles_clear(pp->name);
1301                         return (NULL);
1302                 }
1303                 g_eli_keyfiles_clear(pp->name);
1304                 G_ELI_DEBUG(1, "Using Master Key %u for %s.", nkey, pp->name);
1305                 break;
1306         }
1307 have_key:
1308 
1309 	/*
1310 	 * We have correct key, let's attach provider.
1311 	 */
1312 	gp = g_eli_create(NULL, mp, pp, &md, mkey, nkey);
1313 	bzero(mkey, sizeof(mkey));
1314 	bzero(&md, sizeof(md));
1315 	if (gp == NULL) {
1316 		G_ELI_DEBUG(0, "Cannot create device %s%s.", pp->name,
1317 		    G_ELI_SUFFIX);
1318 		return (NULL);
1319 	}
1320 	return (gp);
1321 }
1322 
1323 static void
1324 g_eli_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
1325     struct g_consumer *cp, struct g_provider *pp)
1326 {
1327 	struct g_eli_softc *sc;
1328 
1329 	g_topology_assert();
1330 	sc = gp->softc;
1331 	if (sc == NULL)
1332 		return;
1333 	if (pp != NULL || cp != NULL)
1334 		return;	/* Nothing here. */
1335 
1336 	sbuf_printf(sb, "%s<KeysTotal>%ju</KeysTotal>\n", indent,
1337 	    (uintmax_t)sc->sc_ekeys_total);
1338 	sbuf_printf(sb, "%s<KeysAllocated>%ju</KeysAllocated>\n", indent,
1339 	    (uintmax_t)sc->sc_ekeys_allocated);
1340 	sbuf_printf(sb, "%s<Flags>", indent);
1341 	if (sc->sc_flags == 0)
1342 		sbuf_cat(sb, "NONE");
1343 	else {
1344 		int first = 1;
1345 
1346 #define ADD_FLAG(flag, name)	do {					\
1347 	if (sc->sc_flags & (flag)) {					\
1348 		if (!first)						\
1349 			sbuf_cat(sb, ", ");				\
1350 		else							\
1351 			first = 0;					\
1352 		sbuf_cat(sb, name);					\
1353 	}								\
1354 } while (0)
1355 		ADD_FLAG(G_ELI_FLAG_SUSPEND, "SUSPEND");
1356 		ADD_FLAG(G_ELI_FLAG_SINGLE_KEY, "SINGLE-KEY");
1357 		ADD_FLAG(G_ELI_FLAG_NATIVE_BYTE_ORDER, "NATIVE-BYTE-ORDER");
1358 		ADD_FLAG(G_ELI_FLAG_ONETIME, "ONETIME");
1359 		ADD_FLAG(G_ELI_FLAG_BOOT, "BOOT");
1360 		ADD_FLAG(G_ELI_FLAG_WO_DETACH, "W-DETACH");
1361 		ADD_FLAG(G_ELI_FLAG_RW_DETACH, "RW-DETACH");
1362 		ADD_FLAG(G_ELI_FLAG_AUTH, "AUTH");
1363 		ADD_FLAG(G_ELI_FLAG_WOPEN, "W-OPEN");
1364 		ADD_FLAG(G_ELI_FLAG_DESTROY, "DESTROY");
1365 		ADD_FLAG(G_ELI_FLAG_RO, "READ-ONLY");
1366 		ADD_FLAG(G_ELI_FLAG_NODELETE, "NODELETE");
1367 		ADD_FLAG(G_ELI_FLAG_GELIBOOT, "GELIBOOT");
1368 		ADD_FLAG(G_ELI_FLAG_GELIDISPLAYPASS, "GELIDISPLAYPASS");
1369 		ADD_FLAG(G_ELI_FLAG_AUTORESIZE, "AUTORESIZE");
1370 #undef  ADD_FLAG
1371 	}
1372 	sbuf_cat(sb, "</Flags>\n");
1373 
1374 	if (!(sc->sc_flags & G_ELI_FLAG_ONETIME)) {
1375 		sbuf_printf(sb, "%s<UsedKey>%u</UsedKey>\n", indent,
1376 		    sc->sc_nkey);
1377 	}
1378 	sbuf_printf(sb, "%s<Version>%u</Version>\n", indent, sc->sc_version);
1379 	sbuf_printf(sb, "%s<Crypto>", indent);
1380 	switch (sc->sc_crypto) {
1381 	case G_ELI_CRYPTO_HW:
1382 		sbuf_cat(sb, "hardware");
1383 		break;
1384 	case G_ELI_CRYPTO_SW:
1385 		sbuf_cat(sb, "software");
1386 		break;
1387 	case G_ELI_CRYPTO_SW_ACCEL:
1388 		sbuf_cat(sb, "accelerated software");
1389 		break;
1390 	default:
1391 		sbuf_cat(sb, "UNKNOWN");
1392 		break;
1393 	}
1394 	sbuf_cat(sb, "</Crypto>\n");
1395 	if (sc->sc_flags & G_ELI_FLAG_AUTH) {
1396 		sbuf_printf(sb,
1397 		    "%s<AuthenticationAlgorithm>%s</AuthenticationAlgorithm>\n",
1398 		    indent, g_eli_algo2str(sc->sc_aalgo));
1399 	}
1400 	sbuf_printf(sb, "%s<KeyLength>%u</KeyLength>\n", indent,
1401 	    sc->sc_ekeylen);
1402 	sbuf_printf(sb, "%s<EncryptionAlgorithm>%s</EncryptionAlgorithm>\n",
1403 	    indent, g_eli_algo2str(sc->sc_ealgo));
1404 	sbuf_printf(sb, "%s<State>%s</State>\n", indent,
1405 	    (sc->sc_flags & G_ELI_FLAG_SUSPEND) ? "SUSPENDED" : "ACTIVE");
1406 }
1407 
1408 static void
1409 g_eli_shutdown_pre_sync(void *arg, int howto)
1410 {
1411 	struct g_class *mp;
1412 	struct g_geom *gp, *gp2;
1413 	struct g_provider *pp;
1414 	struct g_eli_softc *sc;
1415 	int error;
1416 
1417 	mp = arg;
1418 	g_topology_lock();
1419 	LIST_FOREACH_SAFE(gp, &mp->geom, geom, gp2) {
1420 		sc = gp->softc;
1421 		if (sc == NULL)
1422 			continue;
1423 		pp = LIST_FIRST(&gp->provider);
1424 		KASSERT(pp != NULL, ("No provider? gp=%p (%s)", gp, gp->name));
1425 		if (pp->acr != 0 || pp->acw != 0 || pp->ace != 0 ||
1426 		    SCHEDULER_STOPPED())
1427 		{
1428 			sc->sc_flags |= G_ELI_FLAG_RW_DETACH;
1429 			gp->access = g_eli_access;
1430 		} else {
1431 			error = g_eli_destroy(sc, TRUE);
1432 		}
1433 	}
1434 	g_topology_unlock();
1435 }
1436 
1437 static void
1438 g_eli_init(struct g_class *mp)
1439 {
1440 
1441 	g_eli_pre_sync = EVENTHANDLER_REGISTER(shutdown_pre_sync,
1442 	    g_eli_shutdown_pre_sync, mp, SHUTDOWN_PRI_FIRST);
1443 	if (g_eli_pre_sync == NULL)
1444 		G_ELI_DEBUG(0, "Warning! Cannot register shutdown event.");
1445 }
1446 
1447 static void
1448 g_eli_fini(struct g_class *mp)
1449 {
1450 
1451 	if (g_eli_pre_sync != NULL)
1452 		EVENTHANDLER_DEREGISTER(shutdown_pre_sync, g_eli_pre_sync);
1453 }
1454 
1455 DECLARE_GEOM_CLASS(g_eli_class, g_eli);
1456 MODULE_DEPEND(g_eli, crypto, 1, 1, 1);
1457 MODULE_VERSION(geom_eli, 0);
1458