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