xref: /freebsd/sys/geom/geom_subr.c (revision 2e4311906d8c8dc7a7c726345268253bca6d4acc)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2002 Poul-Henning Kamp
5  * Copyright (c) 2002 Networks Associates Technology, Inc.
6  * All rights reserved.
7  *
8  * This software was developed for the FreeBSD Project by Poul-Henning Kamp
9  * and NAI Labs, the Security Research Division of Network Associates, Inc.
10  * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
11  * DARPA CHATS research program.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. The names of the authors may not be used to endorse or promote
22  *    products derived from this software without specific prior written
23  *    permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37 
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 #include "opt_ddb.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/devicestat.h>
46 #include <sys/kernel.h>
47 #include <sys/malloc.h>
48 #include <sys/bio.h>
49 #include <sys/sysctl.h>
50 #include <sys/proc.h>
51 #include <sys/kthread.h>
52 #include <sys/lock.h>
53 #include <sys/mutex.h>
54 #include <sys/errno.h>
55 #include <sys/sbuf.h>
56 #include <sys/sdt.h>
57 #include <geom/geom.h>
58 #include <geom/geom_dbg.h>
59 #include <geom/geom_int.h>
60 #include <machine/stdarg.h>
61 
62 #ifdef DDB
63 #include <ddb/ddb.h>
64 #endif
65 
66 #ifdef KDB
67 #include <sys/kdb.h>
68 #endif
69 
70 SDT_PROVIDER_DEFINE(geom);
71 
72 struct class_list_head g_classes = LIST_HEAD_INITIALIZER(g_classes);
73 static struct g_tailq_head geoms = TAILQ_HEAD_INITIALIZER(geoms);
74 char *g_wait_event, *g_wait_up, *g_wait_down;
75 
76 struct g_hh00 {
77 	struct g_class		*mp;
78 	struct g_provider	*pp;
79 	off_t			size;
80 	int			error;
81 	int			post;
82 };
83 
84 void
85 g_dbg_printf(const char *classname, int lvl, struct bio *bp,
86     const char *format,
87     ...)
88 {
89 #ifndef PRINTF_BUFR_SIZE
90 #define PRINTF_BUFR_SIZE 64
91 #endif
92 	char bufr[PRINTF_BUFR_SIZE];
93 	struct sbuf sb, *sbp __unused;
94 	va_list ap;
95 
96 	sbp = sbuf_new(&sb, bufr, sizeof(bufr), SBUF_FIXEDLEN);
97 	KASSERT(sbp != NULL, ("sbuf_new misused?"));
98 
99 	sbuf_set_drain(&sb, sbuf_printf_drain, NULL);
100 
101 	sbuf_cat(&sb, classname);
102 	if (lvl >= 0)
103 		sbuf_printf(&sb, "[%d]", lvl);
104 
105 	va_start(ap, format);
106 	sbuf_vprintf(&sb, format, ap);
107 	va_end(ap);
108 
109 	if (bp != NULL) {
110 		sbuf_putc(&sb, ' ');
111 		g_format_bio(&sb, bp);
112 	}
113 
114 	/* Terminate the debug line with a single '\n'. */
115 	sbuf_nl_terminate(&sb);
116 
117 	/* Flush line to printf. */
118 	sbuf_finish(&sb);
119 	sbuf_delete(&sb);
120 }
121 
122 /*
123  * This event offers a new class a chance to taste all preexisting providers.
124  */
125 static void
126 g_load_class(void *arg, int flag)
127 {
128 	struct g_hh00 *hh;
129 	struct g_class *mp2, *mp;
130 	struct g_geom *gp;
131 	struct g_provider *pp;
132 
133 	g_topology_assert();
134 	if (flag == EV_CANCEL)	/* XXX: can't happen ? */
135 		return;
136 	if (g_shutdown)
137 		return;
138 
139 	hh = arg;
140 	mp = hh->mp;
141 	hh->error = 0;
142 	if (hh->post) {
143 		g_free(hh);
144 		hh = NULL;
145 	}
146 	g_trace(G_T_TOPOLOGY, "g_load_class(%s)", mp->name);
147 	KASSERT(mp->name != NULL && *mp->name != '\0',
148 	    ("GEOM class has no name"));
149 	LIST_FOREACH(mp2, &g_classes, class) {
150 		if (mp2 == mp) {
151 			printf("The GEOM class %s is already loaded.\n",
152 			    mp2->name);
153 			if (hh != NULL)
154 				hh->error = EEXIST;
155 			return;
156 		} else if (strcmp(mp2->name, mp->name) == 0) {
157 			printf("A GEOM class %s is already loaded.\n",
158 			    mp2->name);
159 			if (hh != NULL)
160 				hh->error = EEXIST;
161 			return;
162 		}
163 	}
164 
165 	LIST_INIT(&mp->geom);
166 	LIST_INSERT_HEAD(&g_classes, mp, class);
167 	if (mp->init != NULL)
168 		mp->init(mp);
169 	if (mp->taste == NULL)
170 		return;
171 	LIST_FOREACH(mp2, &g_classes, class) {
172 		if (mp == mp2)
173 			continue;
174 		LIST_FOREACH(gp, &mp2->geom, geom) {
175 			LIST_FOREACH(pp, &gp->provider, provider) {
176 				mp->taste(mp, pp, 0);
177 				g_topology_assert();
178 			}
179 		}
180 	}
181 }
182 
183 static int
184 g_unload_class(struct g_class *mp)
185 {
186 	struct g_geom *gp;
187 	struct g_provider *pp;
188 	struct g_consumer *cp;
189 	int error;
190 
191 	g_topology_lock();
192 	g_trace(G_T_TOPOLOGY, "g_unload_class(%s)", mp->name);
193 retry:
194 	G_VALID_CLASS(mp);
195 	LIST_FOREACH(gp, &mp->geom, geom) {
196 		/* We refuse to unload if anything is open */
197 		LIST_FOREACH(pp, &gp->provider, provider)
198 			if (pp->acr || pp->acw || pp->ace) {
199 				g_topology_unlock();
200 				return (EBUSY);
201 			}
202 		LIST_FOREACH(cp, &gp->consumer, consumer)
203 			if (cp->acr || cp->acw || cp->ace) {
204 				g_topology_unlock();
205 				return (EBUSY);
206 			}
207 		/* If the geom is withering, wait for it to finish. */
208 		if (gp->flags & G_GEOM_WITHER) {
209 			g_topology_sleep(mp, 1);
210 			goto retry;
211 		}
212 	}
213 
214 	/*
215 	 * We allow unloading if we have no geoms, or a class
216 	 * method we can use to get rid of them.
217 	 */
218 	if (!LIST_EMPTY(&mp->geom) && mp->destroy_geom == NULL) {
219 		g_topology_unlock();
220 		return (EOPNOTSUPP);
221 	}
222 
223 	/* Bar new entries */
224 	mp->taste = NULL;
225 
226 	LIST_FOREACH(gp, &mp->geom, geom) {
227 		error = mp->destroy_geom(NULL, mp, gp);
228 		if (error != 0) {
229 			g_topology_unlock();
230 			return (error);
231 		}
232 	}
233 	/* Wait for withering to finish. */
234 	for (;;) {
235 		gp = LIST_FIRST(&mp->geom);
236 		if (gp == NULL)
237 			break;
238 		KASSERT(gp->flags & G_GEOM_WITHER,
239 		   ("Non-withering geom in class %s", mp->name));
240 		g_topology_sleep(mp, 1);
241 	}
242 	G_VALID_CLASS(mp);
243 	if (mp->fini != NULL)
244 		mp->fini(mp);
245 	LIST_REMOVE(mp, class);
246 	g_topology_unlock();
247 
248 	return (0);
249 }
250 
251 int
252 g_modevent(module_t mod, int type, void *data)
253 {
254 	struct g_hh00 *hh;
255 	int error;
256 	static int g_ignition;
257 	struct g_class *mp;
258 
259 	mp = data;
260 	if (mp->version != G_VERSION) {
261 		printf("GEOM class %s has Wrong version %x\n",
262 		    mp->name, mp->version);
263 		return (EINVAL);
264 	}
265 	if (!g_ignition) {
266 		g_ignition++;
267 		g_init();
268 	}
269 	error = EOPNOTSUPP;
270 	switch (type) {
271 	case MOD_LOAD:
272 		g_trace(G_T_TOPOLOGY, "g_modevent(%s, LOAD)", mp->name);
273 		hh = g_malloc(sizeof *hh, M_WAITOK | M_ZERO);
274 		hh->mp = mp;
275 		/*
276 		 * Once the system is not cold, MOD_LOAD calls will be
277 		 * from the userland and the g_event thread will be able
278 		 * to acknowledge their completion.
279 		 */
280 		if (cold) {
281 			hh->post = 1;
282 			error = g_post_event(g_load_class, hh, M_WAITOK, NULL);
283 		} else {
284 			error = g_waitfor_event(g_load_class, hh, M_WAITOK,
285 			    NULL);
286 			if (error == 0)
287 				error = hh->error;
288 			g_free(hh);
289 		}
290 		break;
291 	case MOD_UNLOAD:
292 		g_trace(G_T_TOPOLOGY, "g_modevent(%s, UNLOAD)", mp->name);
293 		error = g_unload_class(mp);
294 		if (error == 0) {
295 			KASSERT(LIST_EMPTY(&mp->geom),
296 			    ("Unloaded class (%s) still has geom", mp->name));
297 		}
298 		break;
299 	}
300 	return (error);
301 }
302 
303 static void
304 g_retaste_event(void *arg, int flag)
305 {
306 	struct g_class *mp, *mp2;
307 	struct g_geom *gp;
308 	struct g_hh00 *hh;
309 	struct g_provider *pp;
310 	struct g_consumer *cp;
311 
312 	g_topology_assert();
313 	if (flag == EV_CANCEL)  /* XXX: can't happen ? */
314 		return;
315 	if (g_shutdown || g_notaste)
316 		return;
317 
318 	hh = arg;
319 	mp = hh->mp;
320 	hh->error = 0;
321 	if (hh->post) {
322 		g_free(hh);
323 		hh = NULL;
324 	}
325 	g_trace(G_T_TOPOLOGY, "g_retaste(%s)", mp->name);
326 
327 	LIST_FOREACH(mp2, &g_classes, class) {
328 		LIST_FOREACH(gp, &mp2->geom, geom) {
329 			LIST_FOREACH(pp, &gp->provider, provider) {
330 				if (pp->acr || pp->acw || pp->ace)
331 					continue;
332 				LIST_FOREACH(cp, &pp->consumers, consumers) {
333 					if (cp->geom->class == mp &&
334 					    (cp->flags & G_CF_ORPHAN) == 0)
335 						break;
336 				}
337 				if (cp != NULL) {
338 					cp->flags |= G_CF_ORPHAN;
339 					g_wither_geom(cp->geom, ENXIO);
340 				}
341 				mp->taste(mp, pp, 0);
342 				g_topology_assert();
343 			}
344 		}
345 	}
346 }
347 
348 int
349 g_retaste(struct g_class *mp)
350 {
351 	struct g_hh00 *hh;
352 	int error;
353 
354 	if (mp->taste == NULL)
355 		return (EINVAL);
356 
357 	hh = g_malloc(sizeof *hh, M_WAITOK | M_ZERO);
358 	hh->mp = mp;
359 
360 	if (cold) {
361 		hh->post = 1;
362 		error = g_post_event(g_retaste_event, hh, M_WAITOK, NULL);
363 	} else {
364 		error = g_waitfor_event(g_retaste_event, hh, M_WAITOK, NULL);
365 		if (error == 0)
366 			error = hh->error;
367 		g_free(hh);
368 	}
369 
370 	return (error);
371 }
372 
373 struct g_geom *
374 g_new_geomf(struct g_class *mp, const char *fmt, ...)
375 {
376 	struct g_geom *gp;
377 	va_list ap;
378 	struct sbuf *sb;
379 
380 	g_topology_assert();
381 	G_VALID_CLASS(mp);
382 	sb = sbuf_new_auto();
383 	va_start(ap, fmt);
384 	sbuf_vprintf(sb, fmt, ap);
385 	va_end(ap);
386 	sbuf_finish(sb);
387 	gp = g_malloc(sizeof *gp, M_WAITOK | M_ZERO);
388 	gp->name = g_malloc(sbuf_len(sb) + 1, M_WAITOK | M_ZERO);
389 	gp->class = mp;
390 	gp->rank = 1;
391 	LIST_INIT(&gp->consumer);
392 	LIST_INIT(&gp->provider);
393 	LIST_INSERT_HEAD(&mp->geom, gp, geom);
394 	TAILQ_INSERT_HEAD(&geoms, gp, geoms);
395 	strcpy(gp->name, sbuf_data(sb));
396 	sbuf_delete(sb);
397 	/* Fill in defaults from class */
398 	gp->start = mp->start;
399 	gp->spoiled = mp->spoiled;
400 	gp->attrchanged = mp->attrchanged;
401 	gp->providergone = mp->providergone;
402 	gp->dumpconf = mp->dumpconf;
403 	gp->access = mp->access;
404 	gp->orphan = mp->orphan;
405 	gp->ioctl = mp->ioctl;
406 	gp->resize = mp->resize;
407 	return (gp);
408 }
409 
410 void
411 g_destroy_geom(struct g_geom *gp)
412 {
413 
414 	g_topology_assert();
415 	G_VALID_GEOM(gp);
416 	g_trace(G_T_TOPOLOGY, "g_destroy_geom(%p(%s))", gp, gp->name);
417 	KASSERT(LIST_EMPTY(&gp->consumer),
418 	    ("g_destroy_geom(%s) with consumer(s) [%p]",
419 	    gp->name, LIST_FIRST(&gp->consumer)));
420 	KASSERT(LIST_EMPTY(&gp->provider),
421 	    ("g_destroy_geom(%s) with provider(s) [%p]",
422 	    gp->name, LIST_FIRST(&gp->provider)));
423 	g_cancel_event(gp);
424 	LIST_REMOVE(gp, geom);
425 	TAILQ_REMOVE(&geoms, gp, geoms);
426 	g_free(gp->name);
427 	g_free(gp);
428 }
429 
430 /*
431  * This function is called (repeatedly) until the geom has withered away.
432  */
433 void
434 g_wither_geom(struct g_geom *gp, int error)
435 {
436 	struct g_provider *pp;
437 
438 	g_topology_assert();
439 	G_VALID_GEOM(gp);
440 	g_trace(G_T_TOPOLOGY, "g_wither_geom(%p(%s))", gp, gp->name);
441 	if (!(gp->flags & G_GEOM_WITHER)) {
442 		gp->flags |= G_GEOM_WITHER;
443 		LIST_FOREACH(pp, &gp->provider, provider)
444 			if (!(pp->flags & G_PF_ORPHAN))
445 				g_orphan_provider(pp, error);
446 	}
447 	g_do_wither();
448 }
449 
450 /*
451  * Convenience function to destroy a particular provider.
452  */
453 void
454 g_wither_provider(struct g_provider *pp, int error)
455 {
456 
457 	pp->flags |= G_PF_WITHER;
458 	if (!(pp->flags & G_PF_ORPHAN))
459 		g_orphan_provider(pp, error);
460 }
461 
462 /*
463  * This function is called (repeatedly) until the has withered away.
464  */
465 void
466 g_wither_geom_close(struct g_geom *gp, int error)
467 {
468 	struct g_consumer *cp;
469 
470 	g_topology_assert();
471 	G_VALID_GEOM(gp);
472 	g_trace(G_T_TOPOLOGY, "g_wither_geom_close(%p(%s))", gp, gp->name);
473 	LIST_FOREACH(cp, &gp->consumer, consumer)
474 		if (cp->acr || cp->acw || cp->ace)
475 			g_access(cp, -cp->acr, -cp->acw, -cp->ace);
476 	g_wither_geom(gp, error);
477 }
478 
479 /*
480  * This function is called (repeatedly) until we cant wash away more
481  * withered bits at present.
482  */
483 void
484 g_wither_washer()
485 {
486 	struct g_class *mp;
487 	struct g_geom *gp, *gp2;
488 	struct g_provider *pp, *pp2;
489 	struct g_consumer *cp, *cp2;
490 
491 	g_topology_assert();
492 	LIST_FOREACH(mp, &g_classes, class) {
493 		LIST_FOREACH_SAFE(gp, &mp->geom, geom, gp2) {
494 			LIST_FOREACH_SAFE(pp, &gp->provider, provider, pp2) {
495 				if (!(pp->flags & G_PF_WITHER))
496 					continue;
497 				if (LIST_EMPTY(&pp->consumers))
498 					g_destroy_provider(pp);
499 			}
500 			if (!(gp->flags & G_GEOM_WITHER))
501 				continue;
502 			LIST_FOREACH_SAFE(pp, &gp->provider, provider, pp2) {
503 				if (LIST_EMPTY(&pp->consumers))
504 					g_destroy_provider(pp);
505 			}
506 			LIST_FOREACH_SAFE(cp, &gp->consumer, consumer, cp2) {
507 				if (cp->acr || cp->acw || cp->ace)
508 					continue;
509 				if (cp->provider != NULL)
510 					g_detach(cp);
511 				g_destroy_consumer(cp);
512 			}
513 			if (LIST_EMPTY(&gp->provider) &&
514 			    LIST_EMPTY(&gp->consumer))
515 				g_destroy_geom(gp);
516 		}
517 	}
518 }
519 
520 struct g_consumer *
521 g_new_consumer(struct g_geom *gp)
522 {
523 	struct g_consumer *cp;
524 
525 	g_topology_assert();
526 	G_VALID_GEOM(gp);
527 	KASSERT(!(gp->flags & G_GEOM_WITHER),
528 	    ("g_new_consumer on WITHERing geom(%s) (class %s)",
529 	    gp->name, gp->class->name));
530 	KASSERT(gp->orphan != NULL,
531 	    ("g_new_consumer on geom(%s) (class %s) without orphan",
532 	    gp->name, gp->class->name));
533 
534 	cp = g_malloc(sizeof *cp, M_WAITOK | M_ZERO);
535 	cp->geom = gp;
536 	cp->stat = devstat_new_entry(cp, -1, 0, DEVSTAT_ALL_SUPPORTED,
537 	    DEVSTAT_TYPE_DIRECT, DEVSTAT_PRIORITY_MAX);
538 	LIST_INSERT_HEAD(&gp->consumer, cp, consumer);
539 	return(cp);
540 }
541 
542 void
543 g_destroy_consumer(struct g_consumer *cp)
544 {
545 	struct g_geom *gp;
546 
547 	g_topology_assert();
548 	G_VALID_CONSUMER(cp);
549 	g_trace(G_T_TOPOLOGY, "g_destroy_consumer(%p)", cp);
550 	KASSERT (cp->provider == NULL, ("g_destroy_consumer but attached"));
551 	KASSERT (cp->acr == 0, ("g_destroy_consumer with acr"));
552 	KASSERT (cp->acw == 0, ("g_destroy_consumer with acw"));
553 	KASSERT (cp->ace == 0, ("g_destroy_consumer with ace"));
554 	g_cancel_event(cp);
555 	gp = cp->geom;
556 	LIST_REMOVE(cp, consumer);
557 	devstat_remove_entry(cp->stat);
558 	g_free(cp);
559 	if (gp->flags & G_GEOM_WITHER)
560 		g_do_wither();
561 }
562 
563 static void
564 g_new_provider_event(void *arg, int flag)
565 {
566 	struct g_class *mp;
567 	struct g_provider *pp;
568 	struct g_consumer *cp, *next_cp;
569 
570 	g_topology_assert();
571 	if (flag == EV_CANCEL)
572 		return;
573 	if (g_shutdown)
574 		return;
575 	pp = arg;
576 	G_VALID_PROVIDER(pp);
577 	if ((pp->flags & G_PF_WITHER) != 0)
578 		return;
579 	LIST_FOREACH_SAFE(cp, &pp->consumers, consumers, next_cp) {
580 		if ((cp->flags & G_CF_ORPHAN) == 0 &&
581 		    cp->geom->attrchanged != NULL)
582 			cp->geom->attrchanged(cp, "GEOM::media");
583 	}
584 	if (g_notaste)
585 		return;
586 	LIST_FOREACH(mp, &g_classes, class) {
587 		if (mp->taste == NULL)
588 			continue;
589 		LIST_FOREACH(cp, &pp->consumers, consumers)
590 			if (cp->geom->class == mp &&
591 			    (cp->flags & G_CF_ORPHAN) == 0)
592 				break;
593 		if (cp != NULL)
594 			continue;
595 		mp->taste(mp, pp, 0);
596 		g_topology_assert();
597 	}
598 }
599 
600 struct g_provider *
601 g_new_providerf(struct g_geom *gp, const char *fmt, ...)
602 {
603 	struct g_provider *pp;
604 	struct sbuf *sb;
605 	va_list ap;
606 
607 	g_topology_assert();
608 	G_VALID_GEOM(gp);
609 	KASSERT(gp->access != NULL,
610 	    ("new provider on geom(%s) without ->access (class %s)",
611 	    gp->name, gp->class->name));
612 	KASSERT(gp->start != NULL,
613 	    ("new provider on geom(%s) without ->start (class %s)",
614 	    gp->name, gp->class->name));
615 	KASSERT(!(gp->flags & G_GEOM_WITHER),
616 	    ("new provider on WITHERing geom(%s) (class %s)",
617 	    gp->name, gp->class->name));
618 	sb = sbuf_new_auto();
619 	va_start(ap, fmt);
620 	sbuf_vprintf(sb, fmt, ap);
621 	va_end(ap);
622 	sbuf_finish(sb);
623 	pp = g_malloc(sizeof *pp + sbuf_len(sb) + 1, M_WAITOK | M_ZERO);
624 	pp->name = (char *)(pp + 1);
625 	strcpy(pp->name, sbuf_data(sb));
626 	sbuf_delete(sb);
627 	LIST_INIT(&pp->consumers);
628 	LIST_INIT(&pp->aliases);
629 	pp->error = ENXIO;
630 	pp->geom = gp;
631 	pp->stat = devstat_new_entry(pp, -1, 0, DEVSTAT_ALL_SUPPORTED,
632 	    DEVSTAT_TYPE_DIRECT, DEVSTAT_PRIORITY_MAX);
633 	LIST_INSERT_HEAD(&gp->provider, pp, provider);
634 	g_post_event(g_new_provider_event, pp, M_WAITOK, pp, gp, NULL);
635 	return (pp);
636 }
637 
638 void
639 g_provider_add_alias(struct g_provider *pp, const char *fmt, ...)
640 {
641 	struct sbuf *sb;
642 	struct g_geom_alias *gap;
643 	va_list ap;
644 
645 	/*
646 	 * Generate the alias string and save it in the list.
647 	 */
648 	sb = sbuf_new_auto();
649 	va_start(ap, fmt);
650 	sbuf_vprintf(sb, fmt, ap);
651 	va_end(ap);
652 	sbuf_finish(sb);
653 
654 	LIST_FOREACH(gap, &pp->aliases, ga_next) {
655 		if (strcmp(gap->ga_alias, sbuf_data(sb)) != 0)
656 			continue;
657 		/* Don't re-add the same alias. */
658 		sbuf_delete(sb);
659 		return;
660 	}
661 
662 	gap = g_malloc(sizeof(*gap) + sbuf_len(sb) + 1, M_WAITOK | M_ZERO);
663 	memcpy((char *)(gap + 1), sbuf_data(sb), sbuf_len(sb));
664 	sbuf_delete(sb);
665 	gap->ga_alias = (const char *)(gap + 1);
666 	LIST_INSERT_HEAD(&pp->aliases, gap, ga_next);
667 }
668 
669 void
670 g_error_provider(struct g_provider *pp, int error)
671 {
672 
673 	/* G_VALID_PROVIDER(pp);  We may not have g_topology */
674 	pp->error = error;
675 }
676 
677 static void
678 g_resize_provider_event(void *arg, int flag)
679 {
680 	struct g_hh00 *hh;
681 	struct g_class *mp;
682 	struct g_geom *gp;
683 	struct g_provider *pp;
684 	struct g_consumer *cp, *cp2;
685 	off_t size;
686 
687 	g_topology_assert();
688 	if (g_shutdown)
689 		return;
690 
691 	hh = arg;
692 	pp = hh->pp;
693 	size = hh->size;
694 	g_free(hh);
695 
696 	G_VALID_PROVIDER(pp);
697 	KASSERT(!(pp->flags & G_PF_WITHER),
698 	    ("g_resize_provider_event but withered"));
699 	g_trace(G_T_TOPOLOGY, "g_resize_provider_event(%p)", pp);
700 
701 	LIST_FOREACH_SAFE(cp, &pp->consumers, consumers, cp2) {
702 		gp = cp->geom;
703 		if (gp->resize == NULL && size < pp->mediasize) {
704 			/*
705 			 * XXX: g_dev_orphan method does deferred destroying
706 			 * and it is possible, that other event could already
707 			 * call the orphan method. Check consumer's flags to
708 			 * do not schedule it twice.
709 			 */
710 			if (cp->flags & G_CF_ORPHAN)
711 				continue;
712 			cp->flags |= G_CF_ORPHAN;
713 			cp->geom->orphan(cp);
714 		}
715 	}
716 
717 	pp->mediasize = size;
718 
719 	LIST_FOREACH_SAFE(cp, &pp->consumers, consumers, cp2) {
720 		gp = cp->geom;
721 		if ((gp->flags & G_GEOM_WITHER) == 0 && gp->resize != NULL)
722 			gp->resize(cp);
723 	}
724 
725 	/*
726 	 * After resizing, the previously invalid GEOM class metadata
727 	 * might become valid.  This means we should retaste.
728 	 */
729 	LIST_FOREACH(mp, &g_classes, class) {
730 		if (mp->taste == NULL)
731 			continue;
732 		LIST_FOREACH(cp, &pp->consumers, consumers)
733 			if (cp->geom->class == mp &&
734 			    (cp->flags & G_CF_ORPHAN) == 0)
735 				break;
736 		if (cp != NULL)
737 			continue;
738 		mp->taste(mp, pp, 0);
739 		g_topology_assert();
740 	}
741 }
742 
743 void
744 g_resize_provider(struct g_provider *pp, off_t size)
745 {
746 	struct g_hh00 *hh;
747 
748 	G_VALID_PROVIDER(pp);
749 	if (pp->flags & G_PF_WITHER)
750 		return;
751 
752 	if (size == pp->mediasize)
753 		return;
754 
755 	hh = g_malloc(sizeof *hh, M_WAITOK | M_ZERO);
756 	hh->pp = pp;
757 	hh->size = size;
758 	g_post_event(g_resize_provider_event, hh, M_WAITOK, NULL);
759 }
760 
761 struct g_provider *
762 g_provider_by_name(char const *arg)
763 {
764 	struct g_class *cp;
765 	struct g_geom *gp;
766 	struct g_provider *pp, *wpp;
767 
768 	if (strncmp(arg, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
769 		arg += sizeof(_PATH_DEV) - 1;
770 
771 	wpp = NULL;
772 	LIST_FOREACH(cp, &g_classes, class) {
773 		LIST_FOREACH(gp, &cp->geom, geom) {
774 			LIST_FOREACH(pp, &gp->provider, provider) {
775 				if (strcmp(arg, pp->name) != 0)
776 					continue;
777 				if ((gp->flags & G_GEOM_WITHER) == 0 &&
778 				    (pp->flags & G_PF_WITHER) == 0)
779 					return (pp);
780 				else
781 					wpp = pp;
782 			}
783 		}
784 	}
785 
786 	return (wpp);
787 }
788 
789 void
790 g_destroy_provider(struct g_provider *pp)
791 {
792 	struct g_geom *gp;
793 	struct g_geom_alias *gap, *gaptmp;
794 
795 	g_topology_assert();
796 	G_VALID_PROVIDER(pp);
797 	KASSERT(LIST_EMPTY(&pp->consumers),
798 	    ("g_destroy_provider but attached"));
799 	KASSERT (pp->acr == 0, ("g_destroy_provider with acr"));
800 	KASSERT (pp->acw == 0, ("g_destroy_provider with acw"));
801 	KASSERT (pp->ace == 0, ("g_destroy_provider with ace"));
802 	g_cancel_event(pp);
803 	LIST_REMOVE(pp, provider);
804 	gp = pp->geom;
805 	devstat_remove_entry(pp->stat);
806 	/*
807 	 * If a callback was provided, send notification that the provider
808 	 * is now gone.
809 	 */
810 	if (gp->providergone != NULL)
811 		gp->providergone(pp);
812 	LIST_FOREACH_SAFE(gap, &pp->aliases, ga_next, gaptmp)
813 		g_free(gap);
814 	g_free(pp);
815 	if ((gp->flags & G_GEOM_WITHER))
816 		g_do_wither();
817 }
818 
819 /*
820  * We keep the "geoms" list sorted by topological order (== increasing
821  * numerical rank) at all times.
822  * When an attach is done, the attaching geoms rank is invalidated
823  * and it is moved to the tail of the list.
824  * All geoms later in the sequence has their ranks reevaluated in
825  * sequence.  If we cannot assign rank to a geom because it's
826  * prerequisites do not have rank, we move that element to the tail
827  * of the sequence with invalid rank as well.
828  * At some point we encounter our original geom and if we stil fail
829  * to assign it a rank, there must be a loop and we fail back to
830  * g_attach() which detach again and calls redo_rank again
831  * to fix up the damage.
832  * It would be much simpler code wise to do it recursively, but we
833  * can't risk that on the kernel stack.
834  */
835 
836 static int
837 redo_rank(struct g_geom *gp)
838 {
839 	struct g_consumer *cp;
840 	struct g_geom *gp1, *gp2;
841 	int n, m;
842 
843 	g_topology_assert();
844 	G_VALID_GEOM(gp);
845 
846 	/* Invalidate this geoms rank and move it to the tail */
847 	gp1 = TAILQ_NEXT(gp, geoms);
848 	if (gp1 != NULL) {
849 		gp->rank = 0;
850 		TAILQ_REMOVE(&geoms, gp, geoms);
851 		TAILQ_INSERT_TAIL(&geoms, gp, geoms);
852 	} else {
853 		gp1 = gp;
854 	}
855 
856 	/* re-rank the rest of the sequence */
857 	for (; gp1 != NULL; gp1 = gp2) {
858 		gp1->rank = 0;
859 		m = 1;
860 		LIST_FOREACH(cp, &gp1->consumer, consumer) {
861 			if (cp->provider == NULL)
862 				continue;
863 			n = cp->provider->geom->rank;
864 			if (n == 0) {
865 				m = 0;
866 				break;
867 			} else if (n >= m)
868 				m = n + 1;
869 		}
870 		gp1->rank = m;
871 		gp2 = TAILQ_NEXT(gp1, geoms);
872 
873 		/* got a rank, moving on */
874 		if (m != 0)
875 			continue;
876 
877 		/* no rank to original geom means loop */
878 		if (gp == gp1)
879 			return (ELOOP);
880 
881 		/* no rank, put it at the end move on */
882 		TAILQ_REMOVE(&geoms, gp1, geoms);
883 		TAILQ_INSERT_TAIL(&geoms, gp1, geoms);
884 	}
885 	return (0);
886 }
887 
888 int
889 g_attach(struct g_consumer *cp, struct g_provider *pp)
890 {
891 	int error;
892 
893 	g_topology_assert();
894 	G_VALID_CONSUMER(cp);
895 	G_VALID_PROVIDER(pp);
896 	g_trace(G_T_TOPOLOGY, "g_attach(%p, %p)", cp, pp);
897 	KASSERT(cp->provider == NULL, ("attach but attached"));
898 	if ((pp->flags & (G_PF_ORPHAN | G_PF_WITHER)) != 0)
899 		return (ENXIO);
900 	cp->provider = pp;
901 	cp->flags &= ~G_CF_ORPHAN;
902 	LIST_INSERT_HEAD(&pp->consumers, cp, consumers);
903 	error = redo_rank(cp->geom);
904 	if (error) {
905 		LIST_REMOVE(cp, consumers);
906 		cp->provider = NULL;
907 		redo_rank(cp->geom);
908 	}
909 	return (error);
910 }
911 
912 void
913 g_detach(struct g_consumer *cp)
914 {
915 	struct g_provider *pp;
916 
917 	g_topology_assert();
918 	G_VALID_CONSUMER(cp);
919 	g_trace(G_T_TOPOLOGY, "g_detach(%p)", cp);
920 	KASSERT(cp->provider != NULL, ("detach but not attached"));
921 	KASSERT(cp->acr == 0, ("detach but nonzero acr"));
922 	KASSERT(cp->acw == 0, ("detach but nonzero acw"));
923 	KASSERT(cp->ace == 0, ("detach but nonzero ace"));
924 	KASSERT(cp->nstart == cp->nend,
925 	    ("detach with active requests"));
926 	pp = cp->provider;
927 	LIST_REMOVE(cp, consumers);
928 	cp->provider = NULL;
929 	if ((cp->geom->flags & G_GEOM_WITHER) ||
930 	    (pp->geom->flags & G_GEOM_WITHER) ||
931 	    (pp->flags & G_PF_WITHER))
932 		g_do_wither();
933 	redo_rank(cp->geom);
934 }
935 
936 /*
937  * g_access()
938  *
939  * Access-check with delta values.  The question asked is "can provider
940  * "cp" change the access counters by the relative amounts dc[rwe] ?"
941  */
942 
943 int
944 g_access(struct g_consumer *cp, int dcr, int dcw, int dce)
945 {
946 	struct g_provider *pp;
947 	struct g_geom *gp;
948 	int pw, pe;
949 #ifdef INVARIANTS
950 	int sr, sw, se;
951 #endif
952 	int error;
953 
954 	g_topology_assert();
955 	G_VALID_CONSUMER(cp);
956 	pp = cp->provider;
957 	KASSERT(pp != NULL, ("access but not attached"));
958 	G_VALID_PROVIDER(pp);
959 	gp = pp->geom;
960 
961 	g_trace(G_T_ACCESS, "g_access(%p(%s), %d, %d, %d)",
962 	    cp, pp->name, dcr, dcw, dce);
963 
964 	KASSERT(cp->acr + dcr >= 0, ("access resulting in negative acr"));
965 	KASSERT(cp->acw + dcw >= 0, ("access resulting in negative acw"));
966 	KASSERT(cp->ace + dce >= 0, ("access resulting in negative ace"));
967 	KASSERT(dcr != 0 || dcw != 0 || dce != 0, ("NOP access request"));
968 	KASSERT(cp->acr + dcr != 0 || cp->acw + dcw != 0 ||
969 	    cp->ace + dce != 0 || cp->nstart == cp->nend,
970 	    ("Last close with active requests"));
971 	KASSERT(gp->access != NULL, ("NULL geom->access"));
972 
973 	/*
974 	 * If our class cares about being spoiled, and we have been, we
975 	 * are probably just ahead of the event telling us that.  Fail
976 	 * now rather than having to unravel this later.
977 	 */
978 	if (cp->geom->spoiled != NULL && (cp->flags & G_CF_SPOILED) &&
979 	    (dcr > 0 || dcw > 0 || dce > 0))
980 		return (ENXIO);
981 
982 	/*
983 	 * A number of GEOM classes either need to perform an I/O on the first
984 	 * open or to acquire a different subsystem's lock.  To do that they
985 	 * may have to drop the topology lock.
986 	 * Other GEOM classes perform special actions when opening a lower rank
987 	 * geom for the first time.  As a result, more than one thread may
988 	 * end up performing the special actions.
989 	 * So, we prevent concurrent "first" opens by marking the consumer with
990 	 * special flag.
991 	 *
992 	 * Note that if the geom's access method never drops the topology lock,
993 	 * then we will never see G_GEOM_IN_ACCESS here.
994 	 */
995 	while ((gp->flags & G_GEOM_IN_ACCESS) != 0) {
996 		g_trace(G_T_ACCESS,
997 		    "%s: race on geom %s via provider %s and consumer of %s",
998 		    __func__, gp->name, pp->name, cp->geom->name);
999 		gp->flags |= G_GEOM_ACCESS_WAIT;
1000 		g_topology_sleep(gp, 0);
1001 	}
1002 
1003 	/*
1004 	 * Figure out what counts the provider would have had, if this
1005 	 * consumer had (r0w0e0) at this time.
1006 	 */
1007 	pw = pp->acw - cp->acw;
1008 	pe = pp->ace - cp->ace;
1009 
1010 	g_trace(G_T_ACCESS,
1011     "open delta:[r%dw%de%d] old:[r%dw%de%d] provider:[r%dw%de%d] %p(%s)",
1012 	    dcr, dcw, dce,
1013 	    cp->acr, cp->acw, cp->ace,
1014 	    pp->acr, pp->acw, pp->ace,
1015 	    pp, pp->name);
1016 
1017 	/* If foot-shooting is enabled, any open on rank#1 is OK */
1018 	if ((g_debugflags & G_F_FOOTSHOOTING) && gp->rank == 1)
1019 		;
1020 	/* If we try exclusive but already write: fail */
1021 	else if (dce > 0 && pw > 0)
1022 		return (EPERM);
1023 	/* If we try write but already exclusive: fail */
1024 	else if (dcw > 0 && pe > 0)
1025 		return (EPERM);
1026 	/* If we try to open more but provider is error'ed: fail */
1027 	else if ((dcr > 0 || dcw > 0 || dce > 0) && pp->error != 0) {
1028 		printf("%s(%d): provider %s has error %d set\n",
1029 		    __func__, __LINE__, pp->name, pp->error);
1030 		return (pp->error);
1031 	}
1032 
1033 	/* Ok then... */
1034 
1035 #ifdef INVARIANTS
1036 	sr = cp->acr;
1037 	sw = cp->acw;
1038 	se = cp->ace;
1039 #endif
1040 	gp->flags |= G_GEOM_IN_ACCESS;
1041 	error = gp->access(pp, dcr, dcw, dce);
1042 	KASSERT(dcr > 0 || dcw > 0 || dce > 0 || error == 0,
1043 	    ("Geom provider %s::%s dcr=%d dcw=%d dce=%d error=%d failed "
1044 	    "closing ->access()", gp->class->name, pp->name, dcr, dcw,
1045 	    dce, error));
1046 
1047 	g_topology_assert();
1048 	gp->flags &= ~G_GEOM_IN_ACCESS;
1049 	KASSERT(cp->acr == sr && cp->acw == sw && cp->ace == se,
1050 	    ("Access counts changed during geom->access"));
1051 	if ((gp->flags & G_GEOM_ACCESS_WAIT) != 0) {
1052 		gp->flags &= ~G_GEOM_ACCESS_WAIT;
1053 		wakeup(gp);
1054 	}
1055 
1056 	if (!error) {
1057 		/*
1058 		 * If we open first write, spoil any partner consumers.
1059 		 * If we close last write and provider is not errored,
1060 		 * trigger re-taste.
1061 		 */
1062 		if (pp->acw == 0 && dcw != 0)
1063 			g_spoil(pp, cp);
1064 		else if (pp->acw != 0 && pp->acw == -dcw && pp->error == 0 &&
1065 		    !(gp->flags & G_GEOM_WITHER))
1066 			g_post_event(g_new_provider_event, pp, M_WAITOK,
1067 			    pp, NULL);
1068 
1069 		pp->acr += dcr;
1070 		pp->acw += dcw;
1071 		pp->ace += dce;
1072 		cp->acr += dcr;
1073 		cp->acw += dcw;
1074 		cp->ace += dce;
1075 		if (pp->acr != 0 || pp->acw != 0 || pp->ace != 0)
1076 			KASSERT(pp->sectorsize > 0,
1077 			    ("Provider %s lacks sectorsize", pp->name));
1078 		if ((cp->geom->flags & G_GEOM_WITHER) &&
1079 		    cp->acr == 0 && cp->acw == 0 && cp->ace == 0)
1080 			g_do_wither();
1081 	}
1082 	return (error);
1083 }
1084 
1085 int
1086 g_handleattr_int(struct bio *bp, const char *attribute, int val)
1087 {
1088 
1089 	return (g_handleattr(bp, attribute, &val, sizeof val));
1090 }
1091 
1092 int
1093 g_handleattr_uint16_t(struct bio *bp, const char *attribute, uint16_t val)
1094 {
1095 
1096 	return (g_handleattr(bp, attribute, &val, sizeof val));
1097 }
1098 
1099 int
1100 g_handleattr_off_t(struct bio *bp, const char *attribute, off_t val)
1101 {
1102 
1103 	return (g_handleattr(bp, attribute, &val, sizeof val));
1104 }
1105 
1106 int
1107 g_handleattr_str(struct bio *bp, const char *attribute, const char *str)
1108 {
1109 
1110 	return (g_handleattr(bp, attribute, str, 0));
1111 }
1112 
1113 int
1114 g_handleattr(struct bio *bp, const char *attribute, const void *val, int len)
1115 {
1116 	int error = 0;
1117 
1118 	if (strcmp(bp->bio_attribute, attribute))
1119 		return (0);
1120 	if (len == 0) {
1121 		bzero(bp->bio_data, bp->bio_length);
1122 		if (strlcpy(bp->bio_data, val, bp->bio_length) >=
1123 		    bp->bio_length) {
1124 			printf("%s: %s %s bio_length %jd strlen %zu -> EFAULT\n",
1125 			    __func__, bp->bio_to->name, attribute,
1126 			    (intmax_t)bp->bio_length, strlen(val));
1127 			error = EFAULT;
1128 		}
1129 	} else if (bp->bio_length == len) {
1130 		bcopy(val, bp->bio_data, len);
1131 	} else {
1132 		printf("%s: %s %s bio_length %jd len %d -> EFAULT\n", __func__,
1133 		    bp->bio_to->name, attribute, (intmax_t)bp->bio_length, len);
1134 		error = EFAULT;
1135 	}
1136 	if (error == 0)
1137 		bp->bio_completed = bp->bio_length;
1138 	g_io_deliver(bp, error);
1139 	return (1);
1140 }
1141 
1142 int
1143 g_std_access(struct g_provider *pp,
1144 	int dr __unused, int dw __unused, int de __unused)
1145 {
1146 
1147 	g_topology_assert();
1148 	G_VALID_PROVIDER(pp);
1149         return (0);
1150 }
1151 
1152 void
1153 g_std_done(struct bio *bp)
1154 {
1155 	struct bio *bp2;
1156 
1157 	bp2 = bp->bio_parent;
1158 	if (bp2->bio_error == 0)
1159 		bp2->bio_error = bp->bio_error;
1160 	bp2->bio_completed += bp->bio_completed;
1161 	g_destroy_bio(bp);
1162 	bp2->bio_inbed++;
1163 	if (bp2->bio_children == bp2->bio_inbed) {
1164 		if (bp2->bio_cmd == BIO_SPEEDUP)
1165 			bp2->bio_completed = bp2->bio_length;
1166 		g_io_deliver(bp2, bp2->bio_error);
1167 	}
1168 }
1169 
1170 /* XXX: maybe this is only g_slice_spoiled */
1171 
1172 void
1173 g_std_spoiled(struct g_consumer *cp)
1174 {
1175 	struct g_geom *gp;
1176 	struct g_provider *pp;
1177 
1178 	g_topology_assert();
1179 	G_VALID_CONSUMER(cp);
1180 	g_trace(G_T_TOPOLOGY, "g_std_spoiled(%p)", cp);
1181 	cp->flags |= G_CF_ORPHAN;
1182 	g_detach(cp);
1183 	gp = cp->geom;
1184 	LIST_FOREACH(pp, &gp->provider, provider)
1185 		g_orphan_provider(pp, ENXIO);
1186 	g_destroy_consumer(cp);
1187 	if (LIST_EMPTY(&gp->provider) && LIST_EMPTY(&gp->consumer))
1188 		g_destroy_geom(gp);
1189 	else
1190 		gp->flags |= G_GEOM_WITHER;
1191 }
1192 
1193 /*
1194  * Spoiling happens when a provider is opened for writing, but consumers
1195  * which are configured by in-band data are attached (slicers for instance).
1196  * Since the write might potentially change the in-band data, such consumers
1197  * need to re-evaluate their existence after the writing session closes.
1198  * We do this by (offering to) tear them down when the open for write happens
1199  * in return for a re-taste when it closes again.
1200  * Together with the fact that such consumers grab an 'e' bit whenever they
1201  * are open, regardless of mode, this ends up DTRT.
1202  */
1203 
1204 static void
1205 g_spoil_event(void *arg, int flag)
1206 {
1207 	struct g_provider *pp;
1208 	struct g_consumer *cp, *cp2;
1209 
1210 	g_topology_assert();
1211 	if (flag == EV_CANCEL)
1212 		return;
1213 	pp = arg;
1214 	G_VALID_PROVIDER(pp);
1215 	g_trace(G_T_TOPOLOGY, "%s %p(%s:%s:%s)", __func__, pp,
1216 	    pp->geom->class->name, pp->geom->name, pp->name);
1217 	for (cp = LIST_FIRST(&pp->consumers); cp != NULL; cp = cp2) {
1218 		cp2 = LIST_NEXT(cp, consumers);
1219 		if ((cp->flags & G_CF_SPOILED) == 0)
1220 			continue;
1221 		cp->flags &= ~G_CF_SPOILED;
1222 		if (cp->geom->spoiled == NULL)
1223 			continue;
1224 		cp->geom->spoiled(cp);
1225 		g_topology_assert();
1226 	}
1227 }
1228 
1229 void
1230 g_spoil(struct g_provider *pp, struct g_consumer *cp)
1231 {
1232 	struct g_consumer *cp2;
1233 
1234 	g_topology_assert();
1235 	G_VALID_PROVIDER(pp);
1236 	G_VALID_CONSUMER(cp);
1237 
1238 	LIST_FOREACH(cp2, &pp->consumers, consumers) {
1239 		if (cp2 == cp)
1240 			continue;
1241 /*
1242 		KASSERT(cp2->acr == 0, ("spoiling cp->acr = %d", cp2->acr));
1243 		KASSERT(cp2->acw == 0, ("spoiling cp->acw = %d", cp2->acw));
1244 */
1245 		KASSERT(cp2->ace == 0, ("spoiling cp->ace = %d", cp2->ace));
1246 		cp2->flags |= G_CF_SPOILED;
1247 	}
1248 	g_post_event(g_spoil_event, pp, M_WAITOK, pp, NULL);
1249 }
1250 
1251 static void
1252 g_media_changed_event(void *arg, int flag)
1253 {
1254 	struct g_provider *pp;
1255 	int retaste;
1256 
1257 	g_topology_assert();
1258 	if (flag == EV_CANCEL)
1259 		return;
1260 	pp = arg;
1261 	G_VALID_PROVIDER(pp);
1262 
1263 	/*
1264 	 * If provider was not open for writing, queue retaste after spoiling.
1265 	 * If it was, retaste will happen automatically on close.
1266 	 */
1267 	retaste = (pp->acw == 0 && pp->error == 0 &&
1268 	    !(pp->geom->flags & G_GEOM_WITHER));
1269 	g_spoil_event(arg, flag);
1270 	if (retaste)
1271 		g_post_event(g_new_provider_event, pp, M_WAITOK, pp, NULL);
1272 }
1273 
1274 int
1275 g_media_changed(struct g_provider *pp, int flag)
1276 {
1277 	struct g_consumer *cp;
1278 
1279 	LIST_FOREACH(cp, &pp->consumers, consumers)
1280 		cp->flags |= G_CF_SPOILED;
1281 	return (g_post_event(g_media_changed_event, pp, flag, pp, NULL));
1282 }
1283 
1284 int
1285 g_media_gone(struct g_provider *pp, int flag)
1286 {
1287 	struct g_consumer *cp;
1288 
1289 	LIST_FOREACH(cp, &pp->consumers, consumers)
1290 		cp->flags |= G_CF_SPOILED;
1291 	return (g_post_event(g_spoil_event, pp, flag, pp, NULL));
1292 }
1293 
1294 int
1295 g_getattr__(const char *attr, struct g_consumer *cp, void *var, int len)
1296 {
1297 	int error, i;
1298 
1299 	i = len;
1300 	error = g_io_getattr(attr, cp, &i, var);
1301 	if (error)
1302 		return (error);
1303 	if (i != len)
1304 		return (EINVAL);
1305 	return (0);
1306 }
1307 
1308 static int
1309 g_get_device_prefix_len(const char *name)
1310 {
1311 	int len;
1312 
1313 	if (strncmp(name, "ada", 3) == 0)
1314 		len = 3;
1315 	else if (strncmp(name, "ad", 2) == 0)
1316 		len = 2;
1317 	else
1318 		return (0);
1319 	if (name[len] < '0' || name[len] > '9')
1320 		return (0);
1321 	do {
1322 		len++;
1323 	} while (name[len] >= '0' && name[len] <= '9');
1324 	return (len);
1325 }
1326 
1327 int
1328 g_compare_names(const char *namea, const char *nameb)
1329 {
1330 	int deva, devb;
1331 
1332 	if (strcmp(namea, nameb) == 0)
1333 		return (1);
1334 	deva = g_get_device_prefix_len(namea);
1335 	if (deva == 0)
1336 		return (0);
1337 	devb = g_get_device_prefix_len(nameb);
1338 	if (devb == 0)
1339 		return (0);
1340 	if (strcmp(namea + deva, nameb + devb) == 0)
1341 		return (1);
1342 	return (0);
1343 }
1344 
1345 #if defined(DIAGNOSTIC) || defined(DDB)
1346 /*
1347  * This function walks the mesh and returns a non-zero integer if it
1348  * finds the argument pointer is an object. The return value indicates
1349  * which type of object it is believed to be. If topology is not locked,
1350  * this function is potentially dangerous, but we don't assert that the
1351  * topology lock is held when called from debugger.
1352  */
1353 int
1354 g_valid_obj(void const *ptr)
1355 {
1356 	struct g_class *mp;
1357 	struct g_geom *gp;
1358 	struct g_consumer *cp;
1359 	struct g_provider *pp;
1360 
1361 #ifdef KDB
1362 	if (kdb_active == 0)
1363 #endif
1364 		g_topology_assert();
1365 
1366 	LIST_FOREACH(mp, &g_classes, class) {
1367 		if (ptr == mp)
1368 			return (1);
1369 		LIST_FOREACH(gp, &mp->geom, geom) {
1370 			if (ptr == gp)
1371 				return (2);
1372 			LIST_FOREACH(cp, &gp->consumer, consumer)
1373 				if (ptr == cp)
1374 					return (3);
1375 			LIST_FOREACH(pp, &gp->provider, provider)
1376 				if (ptr == pp)
1377 					return (4);
1378 		}
1379 	}
1380 	return(0);
1381 }
1382 #endif
1383 
1384 #ifdef DDB
1385 
1386 #define	gprintf(...)	do {						\
1387 	db_printf("%*s", indent, "");					\
1388 	db_printf(__VA_ARGS__);						\
1389 } while (0)
1390 #define	gprintln(...)	do {						\
1391 	gprintf(__VA_ARGS__);						\
1392 	db_printf("\n");						\
1393 } while (0)
1394 
1395 #define	ADDFLAG(obj, flag, sflag)	do {				\
1396 	if ((obj)->flags & (flag)) {					\
1397 		if (comma)						\
1398 			strlcat(str, ",", size);			\
1399 		strlcat(str, (sflag), size);				\
1400 		comma = 1;						\
1401 	}								\
1402 } while (0)
1403 
1404 static char *
1405 provider_flags_to_string(struct g_provider *pp, char *str, size_t size)
1406 {
1407 	int comma = 0;
1408 
1409 	bzero(str, size);
1410 	if (pp->flags == 0) {
1411 		strlcpy(str, "NONE", size);
1412 		return (str);
1413 	}
1414 	ADDFLAG(pp, G_PF_WITHER, "G_PF_WITHER");
1415 	ADDFLAG(pp, G_PF_ORPHAN, "G_PF_ORPHAN");
1416 	return (str);
1417 }
1418 
1419 static char *
1420 geom_flags_to_string(struct g_geom *gp, char *str, size_t size)
1421 {
1422 	int comma = 0;
1423 
1424 	bzero(str, size);
1425 	if (gp->flags == 0) {
1426 		strlcpy(str, "NONE", size);
1427 		return (str);
1428 	}
1429 	ADDFLAG(gp, G_GEOM_WITHER, "G_GEOM_WITHER");
1430 	return (str);
1431 }
1432 static void
1433 db_show_geom_consumer(int indent, struct g_consumer *cp)
1434 {
1435 
1436 	if (indent == 0) {
1437 		gprintln("consumer: %p", cp);
1438 		gprintln("  class:    %s (%p)", cp->geom->class->name,
1439 		    cp->geom->class);
1440 		gprintln("  geom:     %s (%p)", cp->geom->name, cp->geom);
1441 		if (cp->provider == NULL)
1442 			gprintln("  provider: none");
1443 		else {
1444 			gprintln("  provider: %s (%p)", cp->provider->name,
1445 			    cp->provider);
1446 		}
1447 		gprintln("  access:   r%dw%de%d", cp->acr, cp->acw, cp->ace);
1448 		gprintln("  flags:    0x%04x", cp->flags);
1449 #ifdef INVARIANTS
1450 		gprintln("  nstart:   %u", cp->nstart);
1451 		gprintln("  nend:     %u", cp->nend);
1452 #endif
1453 	} else {
1454 		gprintf("consumer: %p (%s), access=r%dw%de%d", cp,
1455 		    cp->provider != NULL ? cp->provider->name : "none",
1456 		    cp->acr, cp->acw, cp->ace);
1457 		if (cp->flags)
1458 			db_printf(", flags=0x%04x", cp->flags);
1459 		db_printf("\n");
1460 	}
1461 }
1462 
1463 static void
1464 db_show_geom_provider(int indent, struct g_provider *pp)
1465 {
1466 	struct g_consumer *cp;
1467 	char flags[64];
1468 
1469 	if (indent == 0) {
1470 		gprintln("provider: %s (%p)", pp->name, pp);
1471 		gprintln("  class:        %s (%p)", pp->geom->class->name,
1472 		    pp->geom->class);
1473 		gprintln("  geom:         %s (%p)", pp->geom->name, pp->geom);
1474 		gprintln("  mediasize:    %jd", (intmax_t)pp->mediasize);
1475 		gprintln("  sectorsize:   %u", pp->sectorsize);
1476 		gprintln("  stripesize:   %ju", (uintmax_t)pp->stripesize);
1477 		gprintln("  stripeoffset: %ju", (uintmax_t)pp->stripeoffset);
1478 		gprintln("  access:       r%dw%de%d", pp->acr, pp->acw,
1479 		    pp->ace);
1480 		gprintln("  flags:        %s (0x%04x)",
1481 		    provider_flags_to_string(pp, flags, sizeof(flags)),
1482 		    pp->flags);
1483 		gprintln("  error:        %d", pp->error);
1484 		if (LIST_EMPTY(&pp->consumers))
1485 			gprintln("  consumers:    none");
1486 	} else {
1487 		gprintf("provider: %s (%p), access=r%dw%de%d",
1488 		    pp->name, pp, pp->acr, pp->acw, pp->ace);
1489 		if (pp->flags != 0) {
1490 			db_printf(", flags=%s (0x%04x)",
1491 			    provider_flags_to_string(pp, flags, sizeof(flags)),
1492 			    pp->flags);
1493 		}
1494 		db_printf("\n");
1495 	}
1496 	if (!LIST_EMPTY(&pp->consumers)) {
1497 		LIST_FOREACH(cp, &pp->consumers, consumers) {
1498 			db_show_geom_consumer(indent + 2, cp);
1499 			if (db_pager_quit)
1500 				break;
1501 		}
1502 	}
1503 }
1504 
1505 static void
1506 db_show_geom_geom(int indent, struct g_geom *gp)
1507 {
1508 	struct g_provider *pp;
1509 	struct g_consumer *cp;
1510 	char flags[64];
1511 
1512 	if (indent == 0) {
1513 		gprintln("geom: %s (%p)", gp->name, gp);
1514 		gprintln("  class:     %s (%p)", gp->class->name, gp->class);
1515 		gprintln("  flags:     %s (0x%04x)",
1516 		    geom_flags_to_string(gp, flags, sizeof(flags)), gp->flags);
1517 		gprintln("  rank:      %d", gp->rank);
1518 		if (LIST_EMPTY(&gp->provider))
1519 			gprintln("  providers: none");
1520 		if (LIST_EMPTY(&gp->consumer))
1521 			gprintln("  consumers: none");
1522 	} else {
1523 		gprintf("geom: %s (%p), rank=%d", gp->name, gp, gp->rank);
1524 		if (gp->flags != 0) {
1525 			db_printf(", flags=%s (0x%04x)",
1526 			    geom_flags_to_string(gp, flags, sizeof(flags)),
1527 			    gp->flags);
1528 		}
1529 		db_printf("\n");
1530 	}
1531 	if (!LIST_EMPTY(&gp->provider)) {
1532 		LIST_FOREACH(pp, &gp->provider, provider) {
1533 			db_show_geom_provider(indent + 2, pp);
1534 			if (db_pager_quit)
1535 				break;
1536 		}
1537 	}
1538 	if (!LIST_EMPTY(&gp->consumer)) {
1539 		LIST_FOREACH(cp, &gp->consumer, consumer) {
1540 			db_show_geom_consumer(indent + 2, cp);
1541 			if (db_pager_quit)
1542 				break;
1543 		}
1544 	}
1545 }
1546 
1547 static void
1548 db_show_geom_class(struct g_class *mp)
1549 {
1550 	struct g_geom *gp;
1551 
1552 	db_printf("class: %s (%p)\n", mp->name, mp);
1553 	LIST_FOREACH(gp, &mp->geom, geom) {
1554 		db_show_geom_geom(2, gp);
1555 		if (db_pager_quit)
1556 			break;
1557 	}
1558 }
1559 
1560 /*
1561  * Print the GEOM topology or the given object.
1562  */
1563 DB_SHOW_COMMAND(geom, db_show_geom)
1564 {
1565 	struct g_class *mp;
1566 
1567 	if (!have_addr) {
1568 		/* No address given, print the entire topology. */
1569 		LIST_FOREACH(mp, &g_classes, class) {
1570 			db_show_geom_class(mp);
1571 			db_printf("\n");
1572 			if (db_pager_quit)
1573 				break;
1574 		}
1575 	} else {
1576 		switch (g_valid_obj((void *)addr)) {
1577 		case 1:
1578 			db_show_geom_class((struct g_class *)addr);
1579 			break;
1580 		case 2:
1581 			db_show_geom_geom(0, (struct g_geom *)addr);
1582 			break;
1583 		case 3:
1584 			db_show_geom_consumer(0, (struct g_consumer *)addr);
1585 			break;
1586 		case 4:
1587 			db_show_geom_provider(0, (struct g_provider *)addr);
1588 			break;
1589 		default:
1590 			db_printf("Not a GEOM object.\n");
1591 			break;
1592 		}
1593 	}
1594 }
1595 
1596 static void
1597 db_print_bio_cmd(struct bio *bp)
1598 {
1599 	db_printf("  cmd: ");
1600 	switch (bp->bio_cmd) {
1601 	case BIO_READ: db_printf("BIO_READ"); break;
1602 	case BIO_WRITE: db_printf("BIO_WRITE"); break;
1603 	case BIO_DELETE: db_printf("BIO_DELETE"); break;
1604 	case BIO_GETATTR: db_printf("BIO_GETATTR"); break;
1605 	case BIO_FLUSH: db_printf("BIO_FLUSH"); break;
1606 	case BIO_CMD0: db_printf("BIO_CMD0"); break;
1607 	case BIO_CMD1: db_printf("BIO_CMD1"); break;
1608 	case BIO_CMD2: db_printf("BIO_CMD2"); break;
1609 	case BIO_ZONE: db_printf("BIO_ZONE"); break;
1610 	default: db_printf("UNKNOWN"); break;
1611 	}
1612 	db_printf("\n");
1613 }
1614 
1615 static void
1616 db_print_bio_flags(struct bio *bp)
1617 {
1618 	int comma;
1619 
1620 	comma = 0;
1621 	db_printf("  flags: ");
1622 	if (bp->bio_flags & BIO_ERROR) {
1623 		db_printf("BIO_ERROR");
1624 		comma = 1;
1625 	}
1626 	if (bp->bio_flags & BIO_DONE) {
1627 		db_printf("%sBIO_DONE", (comma ? ", " : ""));
1628 		comma = 1;
1629 	}
1630 	if (bp->bio_flags & BIO_ONQUEUE)
1631 		db_printf("%sBIO_ONQUEUE", (comma ? ", " : ""));
1632 	db_printf("\n");
1633 }
1634 
1635 /*
1636  * Print useful information in a BIO
1637  */
1638 DB_SHOW_COMMAND(bio, db_show_bio)
1639 {
1640 	struct bio *bp;
1641 
1642 	if (have_addr) {
1643 		bp = (struct bio *)addr;
1644 		db_printf("BIO %p\n", bp);
1645 		db_print_bio_cmd(bp);
1646 		db_print_bio_flags(bp);
1647 		db_printf("  cflags: 0x%hx\n", bp->bio_cflags);
1648 		db_printf("  pflags: 0x%hx\n", bp->bio_pflags);
1649 		db_printf("  offset: %jd\n", (intmax_t)bp->bio_offset);
1650 		db_printf("  length: %jd\n", (intmax_t)bp->bio_length);
1651 		db_printf("  bcount: %ld\n", bp->bio_bcount);
1652 		db_printf("  resid: %ld\n", bp->bio_resid);
1653 		db_printf("  completed: %jd\n", (intmax_t)bp->bio_completed);
1654 		db_printf("  children: %u\n", bp->bio_children);
1655 		db_printf("  inbed: %u\n", bp->bio_inbed);
1656 		db_printf("  error: %d\n", bp->bio_error);
1657 		db_printf("  parent: %p\n", bp->bio_parent);
1658 		db_printf("  driver1: %p\n", bp->bio_driver1);
1659 		db_printf("  driver2: %p\n", bp->bio_driver2);
1660 		db_printf("  caller1: %p\n", bp->bio_caller1);
1661 		db_printf("  caller2: %p\n", bp->bio_caller2);
1662 		db_printf("  bio_from: %p\n", bp->bio_from);
1663 		db_printf("  bio_to: %p\n", bp->bio_to);
1664 
1665 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
1666 		db_printf("  bio_track_bp: %p\n", bp->bio_track_bp);
1667 #endif
1668 	}
1669 }
1670 
1671 #undef	gprintf
1672 #undef	gprintln
1673 #undef	ADDFLAG
1674 
1675 #endif	/* DDB */
1676