xref: /freebsd/sys/geom/geom_disk.c (revision 2ed3236082a4473c1da8f72c1ebc071a7b54321f)
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_geom.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/kernel.h>
46 #include <sys/sysctl.h>
47 #include <sys/bio.h>
48 #include <sys/ctype.h>
49 #include <sys/devctl.h>
50 #include <sys/fcntl.h>
51 #include <sys/malloc.h>
52 #include <sys/sbuf.h>
53 #include <sys/devicestat.h>
54 
55 #include <sys/lock.h>
56 #include <sys/mutex.h>
57 #include <geom/geom.h>
58 #include <geom/geom_disk.h>
59 #include <geom/geom_int.h>
60 
61 #include <dev/led/led.h>
62 
63 #include <machine/bus.h>
64 
65 struct g_disk_softc {
66 	struct disk		*dp;
67 	struct devstat		*d_devstat;
68 	struct sysctl_ctx_list	sysctl_ctx;
69 	struct sysctl_oid	*sysctl_tree;
70 	char			led[64];
71 	uint32_t		state;
72 	struct mtx		 done_mtx;
73 };
74 
75 static g_access_t g_disk_access;
76 static g_start_t g_disk_start;
77 static g_ioctl_t g_disk_ioctl;
78 static g_dumpconf_t g_disk_dumpconf;
79 static g_provgone_t g_disk_providergone;
80 
81 static int g_disk_sysctl_flags(SYSCTL_HANDLER_ARGS);
82 
83 static struct g_class g_disk_class = {
84 	.name = G_DISK_CLASS_NAME,
85 	.version = G_VERSION,
86 	.start = g_disk_start,
87 	.access = g_disk_access,
88 	.ioctl = g_disk_ioctl,
89 	.providergone = g_disk_providergone,
90 	.dumpconf = g_disk_dumpconf,
91 };
92 
93 SYSCTL_DECL(_kern_geom);
94 static SYSCTL_NODE(_kern_geom, OID_AUTO, disk, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
95     "GEOM_DISK stuff");
96 
97 DECLARE_GEOM_CLASS(g_disk_class, g_disk);
98 
99 static int
100 g_disk_access(struct g_provider *pp, int r, int w, int e)
101 {
102 	struct disk *dp;
103 	struct g_disk_softc *sc;
104 	int error;
105 
106 	g_trace(G_T_ACCESS, "g_disk_access(%s, %d, %d, %d)",
107 	    pp->name, r, w, e);
108 	g_topology_assert();
109 	sc = pp->private;
110 	if ((dp = sc->dp) == NULL || dp->d_destroyed) {
111 		/*
112 		 * Allow decreasing access count even if disk is not
113 		 * available anymore.
114 		 */
115 		if (r <= 0 && w <= 0 && e <= 0)
116 			return (0);
117 		return (ENXIO);
118 	}
119 	r += pp->acr;
120 	w += pp->acw;
121 	e += pp->ace;
122 	error = 0;
123 	if ((pp->acr + pp->acw + pp->ace) == 0 && (r + w + e) > 0) {
124 		/*
125 		 * It would be better to defer this decision to d_open if
126 		 * it was able to take flags.
127 		 */
128 		if (w > 0 && (dp->d_flags & DISKFLAG_WRITE_PROTECT) != 0)
129 			error = EROFS;
130 		if (error == 0 && dp->d_open != NULL)
131 			error = dp->d_open(dp);
132 		if (bootverbose && error != 0)
133 			printf("Opened disk %s -> %d\n", pp->name, error);
134 		if (error != 0)
135 			return (error);
136 		pp->sectorsize = dp->d_sectorsize;
137 		if (dp->d_maxsize == 0) {
138 			printf("WARNING: Disk drive %s%d has no d_maxsize\n",
139 			    dp->d_name, dp->d_unit);
140 			dp->d_maxsize = DFLTPHYS;
141 		}
142 		if (dp->d_delmaxsize == 0) {
143 			if (bootverbose && dp->d_flags & DISKFLAG_CANDELETE) {
144 				printf("WARNING: Disk drive %s%d has no "
145 				    "d_delmaxsize\n", dp->d_name, dp->d_unit);
146 			}
147 			dp->d_delmaxsize = dp->d_maxsize;
148 		}
149 		pp->stripeoffset = dp->d_stripeoffset;
150 		pp->stripesize = dp->d_stripesize;
151 		dp->d_flags |= DISKFLAG_OPEN;
152 		/*
153 		 * Do not invoke resize event when initial size was zero.
154 		 * Some disks report its size only after first opening.
155 		 */
156 		if (pp->mediasize == 0)
157 			pp->mediasize = dp->d_mediasize;
158 		else
159 			g_resize_provider(pp, dp->d_mediasize);
160 	} else if ((pp->acr + pp->acw + pp->ace) > 0 && (r + w + e) == 0) {
161 		if (dp->d_close != NULL) {
162 			error = dp->d_close(dp);
163 			if (error != 0)
164 				printf("Closed disk %s -> %d\n",
165 				    pp->name, error);
166 		}
167 		sc->state = G_STATE_ACTIVE;
168 		if (sc->led[0] != 0)
169 			led_set(sc->led, "0");
170 		dp->d_flags &= ~DISKFLAG_OPEN;
171 	}
172 	return (error);
173 }
174 
175 static void
176 g_disk_kerneldump(struct bio *bp, struct disk *dp)
177 {
178 	struct g_kerneldump *gkd;
179 	struct g_geom *gp;
180 
181 	gkd = (struct g_kerneldump*)bp->bio_data;
182 	gp = bp->bio_to->geom;
183 	g_trace(G_T_TOPOLOGY, "g_disk_kerneldump(%s, %jd, %jd)",
184 		gp->name, (intmax_t)gkd->offset, (intmax_t)gkd->length);
185 	if (dp->d_dump == NULL) {
186 		g_io_deliver(bp, ENODEV);
187 		return;
188 	}
189 	gkd->di.dumper = dp->d_dump;
190 	gkd->di.priv = dp;
191 	gkd->di.blocksize = dp->d_sectorsize;
192 	gkd->di.maxiosize = dp->d_maxsize;
193 	gkd->di.mediaoffset = gkd->offset;
194 	if ((gkd->offset + gkd->length) > dp->d_mediasize)
195 		gkd->length = dp->d_mediasize - gkd->offset;
196 	gkd->di.mediasize = gkd->length;
197 	g_io_deliver(bp, 0);
198 }
199 
200 static void
201 g_disk_setstate(struct bio *bp, struct g_disk_softc *sc)
202 {
203 	const char *cmd;
204 
205 	memcpy(&sc->state, bp->bio_data, sizeof(sc->state));
206 	if (sc->led[0] != 0) {
207 		switch (sc->state) {
208 		case G_STATE_FAILED:
209 			cmd = "1";
210 			break;
211 		case G_STATE_REBUILD:
212 			cmd = "f5";
213 			break;
214 		case G_STATE_RESYNC:
215 			cmd = "f1";
216 			break;
217 		default:
218 			cmd = "0";
219 			break;
220 		}
221 		led_set(sc->led, cmd);
222 	}
223 	g_io_deliver(bp, 0);
224 }
225 
226 static void
227 g_disk_done(struct bio *bp)
228 {
229 	struct bintime now;
230 	struct bio *bp2;
231 	struct g_disk_softc *sc;
232 
233 	/* See "notes" for why we need a mutex here */
234 	sc = bp->bio_caller1;
235 	bp2 = bp->bio_parent;
236 	binuptime(&now);
237 	mtx_lock(&sc->done_mtx);
238 	if (bp2->bio_error == 0)
239 		bp2->bio_error = bp->bio_error;
240 	bp2->bio_completed += bp->bio_length - bp->bio_resid;
241 
242 	switch (bp->bio_cmd) {
243 	case BIO_ZONE:
244 		bcopy(&bp->bio_zone, &bp2->bio_zone, sizeof(bp->bio_zone));
245 		/*FALLTHROUGH*/
246 	case BIO_READ:
247 	case BIO_WRITE:
248 	case BIO_DELETE:
249 	case BIO_FLUSH:
250 		devstat_end_transaction_bio_bt(sc->d_devstat, bp, &now);
251 		break;
252 	default:
253 		break;
254 	}
255 	bp2->bio_inbed++;
256 	if (bp2->bio_children == bp2->bio_inbed) {
257 		mtx_unlock(&sc->done_mtx);
258 		bp2->bio_resid = bp2->bio_bcount - bp2->bio_completed;
259 		g_io_deliver(bp2, bp2->bio_error);
260 	} else
261 		mtx_unlock(&sc->done_mtx);
262 	g_destroy_bio(bp);
263 }
264 
265 static int
266 g_disk_ioctl(struct g_provider *pp, u_long cmd, void * data, int fflag, struct thread *td)
267 {
268 	struct disk *dp;
269 	struct g_disk_softc *sc;
270 
271 	sc = pp->private;
272 	dp = sc->dp;
273 	KASSERT(dp != NULL && !dp->d_destroyed,
274 	    ("g_disk_ioctl(%lx) on destroyed disk %s", cmd, pp->name));
275 
276 	if (dp->d_ioctl == NULL)
277 		return (ENOIOCTL);
278 	return (dp->d_ioctl(dp, cmd, data, fflag, td));
279 }
280 
281 static off_t
282 g_disk_maxsize(struct disk *dp, struct bio *bp)
283 {
284 	if (bp->bio_cmd == BIO_DELETE)
285 		return (dp->d_delmaxsize);
286 	return (dp->d_maxsize);
287 }
288 
289 static int
290 g_disk_maxsegs(struct disk *dp, struct bio *bp)
291 {
292 	return ((g_disk_maxsize(dp, bp) / PAGE_SIZE) + 1);
293 }
294 
295 static void
296 g_disk_advance(struct disk *dp, struct bio *bp, off_t off)
297 {
298 
299 	bp->bio_offset += off;
300 	bp->bio_length -= off;
301 
302 	if ((bp->bio_flags & BIO_VLIST) != 0) {
303 		bus_dma_segment_t *seg, *end;
304 
305 		seg = (bus_dma_segment_t *)bp->bio_data;
306 		end = (bus_dma_segment_t *)bp->bio_data + bp->bio_ma_n;
307 		off += bp->bio_ma_offset;
308 		while (off >= seg->ds_len) {
309 			KASSERT((seg != end),
310 			    ("vlist request runs off the end"));
311 			off -= seg->ds_len;
312 			seg++;
313 		}
314 		bp->bio_ma_offset = off;
315 		bp->bio_ma_n = end - seg;
316 		bp->bio_data = (void *)seg;
317 	} else if ((bp->bio_flags & BIO_UNMAPPED) != 0) {
318 		bp->bio_ma += off / PAGE_SIZE;
319 		bp->bio_ma_offset += off;
320 		bp->bio_ma_offset %= PAGE_SIZE;
321 		bp->bio_ma_n -= off / PAGE_SIZE;
322 	} else {
323 		bp->bio_data += off;
324 	}
325 }
326 
327 static void
328 g_disk_seg_limit(bus_dma_segment_t *seg, off_t *poffset,
329     off_t *plength, int *ppages)
330 {
331 	uintptr_t seg_page_base;
332 	uintptr_t seg_page_end;
333 	off_t offset;
334 	off_t length;
335 	int seg_pages;
336 
337 	offset = *poffset;
338 	length = *plength;
339 
340 	if (length > seg->ds_len - offset)
341 		length = seg->ds_len - offset;
342 
343 	seg_page_base = trunc_page(seg->ds_addr + offset);
344 	seg_page_end  = round_page(seg->ds_addr + offset + length);
345 	seg_pages = (seg_page_end - seg_page_base) >> PAGE_SHIFT;
346 
347 	if (seg_pages > *ppages) {
348 		seg_pages = *ppages;
349 		length = (seg_page_base + (seg_pages << PAGE_SHIFT)) -
350 		    (seg->ds_addr + offset);
351 	}
352 
353 	*poffset = 0;
354 	*plength -= length;
355 	*ppages -= seg_pages;
356 }
357 
358 static off_t
359 g_disk_vlist_limit(struct disk *dp, struct bio *bp, bus_dma_segment_t **pendseg)
360 {
361 	bus_dma_segment_t *seg, *end;
362 	off_t residual;
363 	off_t offset;
364 	int pages;
365 
366 	seg = (bus_dma_segment_t *)bp->bio_data;
367 	end = (bus_dma_segment_t *)bp->bio_data + bp->bio_ma_n;
368 	residual = bp->bio_length;
369 	offset = bp->bio_ma_offset;
370 	pages = g_disk_maxsegs(dp, bp);
371 	while (residual != 0 && pages != 0) {
372 		KASSERT((seg != end),
373 		    ("vlist limit runs off the end"));
374 		g_disk_seg_limit(seg, &offset, &residual, &pages);
375 		seg++;
376 	}
377 	if (pendseg != NULL)
378 		*pendseg = seg;
379 	return (residual);
380 }
381 
382 static bool
383 g_disk_limit(struct disk *dp, struct bio *bp)
384 {
385 	bool limited = false;
386 	off_t maxsz;
387 
388 	maxsz = g_disk_maxsize(dp, bp);
389 
390 	/*
391 	 * XXX: If we have a stripesize we should really use it here.
392 	 *      Care should be taken in the delete case if this is done
393 	 *      as deletes can be very sensitive to size given how they
394 	 *      are processed.
395 	 */
396 	if (bp->bio_length > maxsz) {
397 		bp->bio_length = maxsz;
398 		limited = true;
399 	}
400 
401 	if ((bp->bio_flags & BIO_VLIST) != 0) {
402 		bus_dma_segment_t *firstseg, *endseg;
403 		off_t residual;
404 
405 		firstseg = (bus_dma_segment_t*)bp->bio_data;
406 		residual = g_disk_vlist_limit(dp, bp, &endseg);
407 		if (residual != 0) {
408 			bp->bio_ma_n = endseg - firstseg;
409 			bp->bio_length -= residual;
410 			limited = true;
411 		}
412 	} else if ((bp->bio_flags & BIO_UNMAPPED) != 0) {
413 		bp->bio_ma_n =
414 		    howmany(bp->bio_ma_offset + bp->bio_length, PAGE_SIZE);
415 	}
416 
417 	return (limited);
418 }
419 
420 static void
421 g_disk_start(struct bio *bp)
422 {
423 	struct bio *bp2, *bp3;
424 	struct disk *dp;
425 	struct g_disk_softc *sc;
426 	int error;
427 	off_t off;
428 
429 	biotrack(bp, __func__);
430 
431 	sc = bp->bio_to->private;
432 	dp = sc->dp;
433 	KASSERT(dp != NULL && !dp->d_destroyed,
434 	    ("g_disk_start(%p) on destroyed disk %s", bp, bp->bio_to->name));
435 	error = EJUSTRETURN;
436 	switch(bp->bio_cmd) {
437 	case BIO_DELETE:
438 		if (!(dp->d_flags & DISKFLAG_CANDELETE)) {
439 			error = EOPNOTSUPP;
440 			break;
441 		}
442 		/* fall-through */
443 	case BIO_READ:
444 	case BIO_WRITE:
445 		KASSERT((dp->d_flags & DISKFLAG_UNMAPPED_BIO) != 0 ||
446 		    (bp->bio_flags & BIO_UNMAPPED) == 0,
447 		    ("unmapped bio not supported by disk %s", dp->d_name));
448 		off = 0;
449 		bp3 = NULL;
450 		bp2 = g_clone_bio(bp);
451 		if (bp2 == NULL) {
452 			error = ENOMEM;
453 			break;
454 		}
455 		for (;;) {
456 			if (g_disk_limit(dp, bp2)) {
457 				off += bp2->bio_length;
458 
459 				/*
460 				 * To avoid a race, we need to grab the next bio
461 				 * before we schedule this one.  See "notes".
462 				 */
463 				bp3 = g_clone_bio(bp);
464 				if (bp3 == NULL)
465 					bp->bio_error = ENOMEM;
466 			}
467 			bp2->bio_done = g_disk_done;
468 			bp2->bio_caller1 = sc;
469 			bp2->bio_pblkno = bp2->bio_offset / dp->d_sectorsize;
470 			bp2->bio_bcount = bp2->bio_length;
471 			bp2->bio_disk = dp;
472 			devstat_start_transaction_bio(dp->d_devstat, bp2);
473 			dp->d_strategy(bp2);
474 
475 			if (bp3 == NULL)
476 				break;
477 
478 			bp2 = bp3;
479 			bp3 = NULL;
480 			g_disk_advance(dp, bp2, off);
481 		}
482 		break;
483 	case BIO_GETATTR:
484 		/* Give the driver a chance to override */
485 		if (dp->d_getattr != NULL) {
486 			if (bp->bio_disk == NULL)
487 				bp->bio_disk = dp;
488 			error = dp->d_getattr(bp);
489 			if (error != -1)
490 				break;
491 			error = EJUSTRETURN;
492 		}
493 		if (g_handleattr_int(bp, "GEOM::candelete",
494 		    (dp->d_flags & DISKFLAG_CANDELETE) != 0))
495 			break;
496 		else if (g_handleattr_int(bp, "GEOM::fwsectors",
497 		    dp->d_fwsectors))
498 			break;
499 		else if (g_handleattr_int(bp, "GEOM::fwheads", dp->d_fwheads))
500 			break;
501 		else if (g_handleattr_off_t(bp, "GEOM::frontstuff", 0))
502 			break;
503 		else if (g_handleattr_str(bp, "GEOM::ident", dp->d_ident))
504 			break;
505 		else if (g_handleattr_str(bp, "GEOM::descr", dp->d_descr))
506 			break;
507 		else if (g_handleattr_uint16_t(bp, "GEOM::hba_vendor",
508 		    dp->d_hba_vendor))
509 			break;
510 		else if (g_handleattr_uint16_t(bp, "GEOM::hba_device",
511 		    dp->d_hba_device))
512 			break;
513 		else if (g_handleattr_uint16_t(bp, "GEOM::hba_subvendor",
514 		    dp->d_hba_subvendor))
515 			break;
516 		else if (g_handleattr_uint16_t(bp, "GEOM::hba_subdevice",
517 		    dp->d_hba_subdevice))
518 			break;
519 		else if (!strcmp(bp->bio_attribute, "GEOM::kerneldump"))
520 			g_disk_kerneldump(bp, dp);
521 		else if (!strcmp(bp->bio_attribute, "GEOM::setstate"))
522 			g_disk_setstate(bp, sc);
523 		else if (g_handleattr_uint16_t(bp, "GEOM::rotation_rate",
524 		    dp->d_rotation_rate))
525 			break;
526 		else if (g_handleattr_str(bp, "GEOM::attachment",
527 		    dp->d_attachment))
528 			break;
529 		else
530 			error = ENOIOCTL;
531 		break;
532 	case BIO_FLUSH:
533 		g_trace(G_T_BIO, "g_disk_flushcache(%s)",
534 		    bp->bio_to->name);
535 		if (!(dp->d_flags & DISKFLAG_CANFLUSHCACHE)) {
536 			error = EOPNOTSUPP;
537 			break;
538 		}
539 		/*FALLTHROUGH*/
540 	case BIO_ZONE:
541 		if (bp->bio_cmd == BIO_ZONE) {
542 			if (!(dp->d_flags & DISKFLAG_CANZONE)) {
543 				error = EOPNOTSUPP;
544 				break;
545 			}
546 			g_trace(G_T_BIO, "g_disk_zone(%s)",
547 			    bp->bio_to->name);
548 		}
549 		bp2 = g_clone_bio(bp);
550 		if (bp2 == NULL) {
551 			g_io_deliver(bp, ENOMEM);
552 			return;
553 		}
554 		bp2->bio_done = g_disk_done;
555 		bp2->bio_caller1 = sc;
556 		bp2->bio_disk = dp;
557 		devstat_start_transaction_bio(dp->d_devstat, bp2);
558 		dp->d_strategy(bp2);
559 		break;
560 	case BIO_SPEEDUP:
561 		bp2 = g_clone_bio(bp);
562 		if (bp2 == NULL) {
563 			g_io_deliver(bp, ENOMEM);
564 			return;
565 		}
566 		bp2->bio_done = g_disk_done;
567 		bp2->bio_caller1 = sc;
568 		bp2->bio_disk = dp;
569 		dp->d_strategy(bp2);
570 		break;
571 	default:
572 		error = EOPNOTSUPP;
573 		break;
574 	}
575 	if (error != EJUSTRETURN)
576 		g_io_deliver(bp, error);
577 	return;
578 }
579 
580 static void
581 g_disk_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp, struct g_consumer *cp, struct g_provider *pp)
582 {
583 	struct bio *bp;
584 	struct disk *dp;
585 	struct g_disk_softc *sc;
586 	char *buf;
587 	int res = 0;
588 
589 	sc = gp->softc;
590 	if (sc == NULL || (dp = sc->dp) == NULL)
591 		return;
592 	if (indent == NULL) {
593 		sbuf_printf(sb, " hd %u", dp->d_fwheads);
594 		sbuf_printf(sb, " sc %u", dp->d_fwsectors);
595 		return;
596 	}
597 	if (pp != NULL) {
598 		sbuf_printf(sb, "%s<fwheads>%u</fwheads>\n",
599 		    indent, dp->d_fwheads);
600 		sbuf_printf(sb, "%s<fwsectors>%u</fwsectors>\n",
601 		    indent, dp->d_fwsectors);
602 
603 		/*
604 		 * "rotationrate" is a little complicated, because the value
605 		 * returned by the drive might not be the RPM; 0 and 1 are
606 		 * special cases, and there's also a valid range.
607 		 */
608 		sbuf_printf(sb, "%s<rotationrate>", indent);
609 		if (dp->d_rotation_rate == DISK_RR_UNKNOWN) /* Old drives */
610 			sbuf_cat(sb, "unknown");	/* don't report RPM. */
611 		else if (dp->d_rotation_rate == DISK_RR_NON_ROTATING)
612 			sbuf_cat(sb, "0");
613 		else if ((dp->d_rotation_rate >= DISK_RR_MIN) &&
614 		    (dp->d_rotation_rate <= DISK_RR_MAX))
615 			sbuf_printf(sb, "%u", dp->d_rotation_rate);
616 		else
617 			sbuf_cat(sb, "invalid");
618 		sbuf_cat(sb, "</rotationrate>\n");
619 		if (dp->d_getattr != NULL) {
620 			buf = g_malloc(DISK_IDENT_SIZE, M_WAITOK);
621 			bp = g_alloc_bio();
622 			bp->bio_disk = dp;
623 			bp->bio_attribute = "GEOM::ident";
624 			bp->bio_length = DISK_IDENT_SIZE;
625 			bp->bio_data = buf;
626 			res = dp->d_getattr(bp);
627 			sbuf_printf(sb, "%s<ident>", indent);
628 			g_conf_cat_escaped(sb, res == 0 ? buf : dp->d_ident);
629 			sbuf_cat(sb, "</ident>\n");
630 			bp->bio_attribute = "GEOM::lunid";
631 			bp->bio_length = DISK_IDENT_SIZE;
632 			bp->bio_data = buf;
633 			if (dp->d_getattr(bp) == 0) {
634 				sbuf_printf(sb, "%s<lunid>", indent);
635 				g_conf_cat_escaped(sb, buf);
636 				sbuf_cat(sb, "</lunid>\n");
637 			}
638 			bp->bio_attribute = "GEOM::lunname";
639 			bp->bio_length = DISK_IDENT_SIZE;
640 			bp->bio_data = buf;
641 			if (dp->d_getattr(bp) == 0) {
642 				sbuf_printf(sb, "%s<lunname>", indent);
643 				g_conf_cat_escaped(sb, buf);
644 				sbuf_cat(sb, "</lunname>\n");
645 			}
646 			g_destroy_bio(bp);
647 			g_free(buf);
648 		} else {
649 			sbuf_printf(sb, "%s<ident>", indent);
650 			g_conf_cat_escaped(sb, dp->d_ident);
651 			sbuf_cat(sb, "</ident>\n");
652 		}
653 		sbuf_printf(sb, "%s<descr>", indent);
654 		g_conf_cat_escaped(sb, dp->d_descr);
655 		sbuf_cat(sb, "</descr>\n");
656 	}
657 }
658 
659 static void
660 g_disk_resize(void *ptr, int flag)
661 {
662 	struct disk *dp;
663 	struct g_geom *gp;
664 	struct g_provider *pp;
665 
666 	if (flag == EV_CANCEL)
667 		return;
668 	g_topology_assert();
669 
670 	dp = ptr;
671 	gp = dp->d_geom;
672 
673 	if (dp->d_destroyed || gp == NULL)
674 		return;
675 
676 	LIST_FOREACH(pp, &gp->provider, provider) {
677 		if (pp->sectorsize != 0 &&
678 		    pp->sectorsize != dp->d_sectorsize)
679 			g_wither_provider(pp, ENXIO);
680 		else
681 			g_resize_provider(pp, dp->d_mediasize);
682 	}
683 }
684 
685 static void
686 g_disk_create(void *arg, int flag)
687 {
688 	struct g_geom *gp;
689 	struct g_provider *pp;
690 	struct disk *dp;
691 	struct g_disk_softc *sc;
692 	struct disk_alias *dap;
693 	char tmpstr[80];
694 
695 	if (flag == EV_CANCEL)
696 		return;
697 	g_topology_assert();
698 	dp = arg;
699 
700 	mtx_pool_lock(mtxpool_sleep, dp);
701 	dp->d_init_level = DISK_INIT_START;
702 
703 	/*
704 	 * If the disk has already gone away, we can just stop here and
705 	 * call the user's callback to tell him we've cleaned things up.
706 	 */
707 	if (dp->d_goneflag != 0) {
708 		mtx_pool_unlock(mtxpool_sleep, dp);
709 		if (dp->d_gone != NULL)
710 			dp->d_gone(dp);
711 		return;
712 	}
713 	mtx_pool_unlock(mtxpool_sleep, dp);
714 
715 	sc = g_malloc(sizeof(*sc), M_WAITOK | M_ZERO);
716 	mtx_init(&sc->done_mtx, "g_disk_done", NULL, MTX_DEF);
717 	sc->dp = dp;
718 	sc->d_devstat = dp->d_devstat;
719 	gp = g_new_geomf(&g_disk_class, "%s%d", dp->d_name, dp->d_unit);
720 	gp->softc = sc;
721 	pp = g_new_providerf(gp, "%s", gp->name);
722 	LIST_FOREACH(dap, &dp->d_aliases, da_next)
723 		g_provider_add_alias(pp, "%s%d", dap->da_alias, dp->d_unit);
724 	devstat_remove_entry(pp->stat);
725 	pp->stat = NULL;
726 	dp->d_devstat->id = pp;
727 	pp->mediasize = dp->d_mediasize;
728 	pp->sectorsize = dp->d_sectorsize;
729 	pp->stripeoffset = dp->d_stripeoffset;
730 	pp->stripesize = dp->d_stripesize;
731 	if ((dp->d_flags & DISKFLAG_UNMAPPED_BIO) != 0)
732 		pp->flags |= G_PF_ACCEPT_UNMAPPED;
733 	if ((dp->d_flags & DISKFLAG_DIRECT_COMPLETION) != 0)
734 		pp->flags |= G_PF_DIRECT_SEND;
735 	pp->flags |= G_PF_DIRECT_RECEIVE;
736 	if (bootverbose)
737 		printf("GEOM: new disk %s\n", gp->name);
738 	sysctl_ctx_init(&sc->sysctl_ctx);
739 	snprintf(tmpstr, sizeof(tmpstr), "GEOM disk %s", gp->name);
740 	sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
741 		SYSCTL_STATIC_CHILDREN(_kern_geom_disk), OID_AUTO, gp->name,
742 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, tmpstr);
743 	if (sc->sysctl_tree != NULL) {
744 		SYSCTL_ADD_STRING(&sc->sysctl_ctx,
745 		    SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO, "led",
746 		    CTLFLAG_RWTUN, sc->led, sizeof(sc->led),
747 		    "LED name");
748 		SYSCTL_ADD_PROC(&sc->sysctl_ctx,
749 		    SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO, "flags",
750 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, dp, 0,
751 		    g_disk_sysctl_flags, "A", "Report disk flags");
752 	}
753 	pp->private = sc;
754 	dp->d_geom = gp;
755 	g_error_provider(pp, 0);
756 
757 	mtx_pool_lock(mtxpool_sleep, dp);
758 	dp->d_init_level = DISK_INIT_DONE;
759 
760 	/*
761 	 * If the disk has gone away at this stage, start the withering
762 	 * process for it.
763 	 */
764 	if (dp->d_goneflag != 0) {
765 		mtx_pool_unlock(mtxpool_sleep, dp);
766 		g_wither_provider(pp, ENXIO);
767 		return;
768 	}
769 	mtx_pool_unlock(mtxpool_sleep, dp);
770 
771 }
772 
773 /*
774  * We get this callback after all of the consumers have gone away, and just
775  * before the provider is freed.  If the disk driver provided a d_gone
776  * callback, let them know that it is okay to free resources -- they won't
777  * be getting any more accesses from GEOM.
778  */
779 static void
780 g_disk_providergone(struct g_provider *pp)
781 {
782 	struct disk *dp;
783 	struct g_disk_softc *sc;
784 
785 	sc = (struct g_disk_softc *)pp->private;
786 	dp = sc->dp;
787 	if (dp != NULL && dp->d_gone != NULL)
788 		dp->d_gone(dp);
789 	if (sc->sysctl_tree != NULL) {
790 		sysctl_ctx_free(&sc->sysctl_ctx);
791 		sc->sysctl_tree = NULL;
792 	}
793 	if (sc->led[0] != 0) {
794 		led_set(sc->led, "0");
795 		sc->led[0] = 0;
796 	}
797 	pp->private = NULL;
798 	pp->geom->softc = NULL;
799 	mtx_destroy(&sc->done_mtx);
800 	g_free(sc);
801 }
802 
803 static void
804 g_disk_destroy(void *ptr, int flag)
805 {
806 	struct disk *dp;
807 	struct g_geom *gp;
808 	struct g_disk_softc *sc;
809 	struct disk_alias *dap, *daptmp;
810 
811 	g_topology_assert();
812 	dp = ptr;
813 	gp = dp->d_geom;
814 	if (gp != NULL) {
815 		sc = gp->softc;
816 		if (sc != NULL)
817 			sc->dp = NULL;
818 		dp->d_geom = NULL;
819 		g_wither_geom(gp, ENXIO);
820 	}
821 	LIST_FOREACH_SAFE(dap, &dp->d_aliases, da_next, daptmp)
822 		g_free(dap);
823 
824 	g_free(dp);
825 }
826 
827 /*
828  * We only allow printable characters in disk ident,
829  * the rest is converted to 'x<HH>'.
830  */
831 static void
832 g_disk_ident_adjust(char *ident, size_t size)
833 {
834 	char *p, tmp[4], newid[DISK_IDENT_SIZE];
835 
836 	newid[0] = '\0';
837 	for (p = ident; *p != '\0'; p++) {
838 		if (isprint(*p)) {
839 			tmp[0] = *p;
840 			tmp[1] = '\0';
841 		} else {
842 			snprintf(tmp, sizeof(tmp), "x%02hhx",
843 			    *(unsigned char *)p);
844 		}
845 		if (strlcat(newid, tmp, sizeof(newid)) >= sizeof(newid))
846 			break;
847 	}
848 	bzero(ident, size);
849 	strlcpy(ident, newid, size);
850 }
851 
852 struct disk *
853 disk_alloc(void)
854 {
855 	struct disk *dp;
856 
857 	dp = g_malloc(sizeof(struct disk), M_WAITOK | M_ZERO);
858 	LIST_INIT(&dp->d_aliases);
859 	return (dp);
860 }
861 
862 void
863 disk_create(struct disk *dp, int version)
864 {
865 
866 	if (version != DISK_VERSION) {
867 		printf("WARNING: Attempt to add disk %s%d %s",
868 		    dp->d_name, dp->d_unit,
869 		    " using incompatible ABI version of disk(9)\n");
870 		printf("WARNING: Ignoring disk %s%d\n",
871 		    dp->d_name, dp->d_unit);
872 		return;
873 	}
874 	if (dp->d_flags & DISKFLAG_RESERVED) {
875 		printf("WARNING: Attempt to add non-MPSAFE disk %s%d\n",
876 		    dp->d_name, dp->d_unit);
877 		printf("WARNING: Ignoring disk %s%d\n",
878 		    dp->d_name, dp->d_unit);
879 		return;
880 	}
881 	KASSERT(dp->d_strategy != NULL, ("disk_create need d_strategy"));
882 	KASSERT(dp->d_name != NULL, ("disk_create need d_name"));
883 	KASSERT(*dp->d_name != 0, ("disk_create need d_name"));
884 	KASSERT(strlen(dp->d_name) < SPECNAMELEN - 4, ("disk name too long"));
885 	if (dp->d_devstat == NULL)
886 		dp->d_devstat = devstat_new_entry(dp->d_name, dp->d_unit,
887 		    dp->d_sectorsize, DEVSTAT_ALL_SUPPORTED,
888 		    DEVSTAT_TYPE_DIRECT, DEVSTAT_PRIORITY_MAX);
889 	dp->d_geom = NULL;
890 
891 	dp->d_init_level = DISK_INIT_NONE;
892 
893 	g_disk_ident_adjust(dp->d_ident, sizeof(dp->d_ident));
894 	g_post_event(g_disk_create, dp, M_WAITOK, dp, NULL);
895 }
896 
897 void
898 disk_destroy(struct disk *dp)
899 {
900 
901 	disk_gone(dp);
902 	dp->d_destroyed = 1;
903 	g_cancel_event(dp);
904 	if (dp->d_devstat != NULL)
905 		devstat_remove_entry(dp->d_devstat);
906 	g_post_event(g_disk_destroy, dp, M_WAITOK, NULL);
907 }
908 
909 void
910 disk_add_alias(struct disk *dp, const char *name)
911 {
912 	struct disk_alias *dap;
913 
914 	dap = (struct disk_alias *)g_malloc(
915 		sizeof(struct disk_alias) + strlen(name) + 1, M_WAITOK);
916 	strcpy((char *)(dap + 1), name);
917 	dap->da_alias = (const char *)(dap + 1);
918 	LIST_INSERT_HEAD(&dp->d_aliases, dap, da_next);
919 }
920 
921 void
922 disk_gone(struct disk *dp)
923 {
924 	struct g_geom *gp;
925 	struct g_provider *pp;
926 
927 	mtx_pool_lock(mtxpool_sleep, dp);
928 
929 	/*
930 	 * Second wither call makes no sense, plus we can not access the list
931 	 * of providers without topology lock after calling wither once.
932 	 */
933 	if (dp->d_goneflag != 0) {
934 		mtx_pool_unlock(mtxpool_sleep, dp);
935 		return;
936 	}
937 
938 	dp->d_goneflag = 1;
939 
940 	/*
941 	 * If we're still in the process of creating this disk (the
942 	 * g_disk_create() function is still queued, or is in
943 	 * progress), the init level will not yet be DISK_INIT_DONE.
944 	 *
945 	 * If that is the case, g_disk_create() will see d_goneflag
946 	 * and take care of cleaning things up.
947 	 *
948 	 * If the disk has already been created, we default to
949 	 * withering the provider as usual below.
950 	 *
951 	 * If the caller has not set a d_gone() callback, he will
952 	 * not be any worse off by returning here, because the geom
953 	 * has not been fully setup in any case.
954 	 */
955 	if (dp->d_init_level < DISK_INIT_DONE) {
956 		mtx_pool_unlock(mtxpool_sleep, dp);
957 		return;
958 	}
959 	mtx_pool_unlock(mtxpool_sleep, dp);
960 
961 	gp = dp->d_geom;
962 	pp = LIST_FIRST(&gp->provider);
963 	if (pp != NULL) {
964 		KASSERT(LIST_NEXT(pp, provider) == NULL,
965 		    ("geom %p has more than one provider", gp));
966 		g_wither_provider(pp, ENXIO);
967 	}
968 }
969 
970 void
971 disk_attr_changed(struct disk *dp, const char *attr, int flag)
972 {
973 	struct g_geom *gp;
974 	struct g_provider *pp;
975 	char devnamebuf[128];
976 
977 	gp = dp->d_geom;
978 	if (gp != NULL)
979 		LIST_FOREACH(pp, &gp->provider, provider)
980 			(void)g_attr_changed(pp, attr, flag);
981 	snprintf(devnamebuf, sizeof(devnamebuf), "devname=%s%d", dp->d_name,
982 	    dp->d_unit);
983 	devctl_notify("GEOM", "disk", attr, devnamebuf);
984 }
985 
986 void
987 disk_media_changed(struct disk *dp, int flag)
988 {
989 	struct g_geom *gp;
990 	struct g_provider *pp;
991 
992 	gp = dp->d_geom;
993 	if (gp != NULL) {
994 		pp = LIST_FIRST(&gp->provider);
995 		if (pp != NULL) {
996 			KASSERT(LIST_NEXT(pp, provider) == NULL,
997 			    ("geom %p has more than one provider", gp));
998 			g_media_changed(pp, flag);
999 		}
1000 	}
1001 }
1002 
1003 void
1004 disk_media_gone(struct disk *dp, int flag)
1005 {
1006 	struct g_geom *gp;
1007 	struct g_provider *pp;
1008 
1009 	gp = dp->d_geom;
1010 	if (gp != NULL) {
1011 		pp = LIST_FIRST(&gp->provider);
1012 		if (pp != NULL) {
1013 			KASSERT(LIST_NEXT(pp, provider) == NULL,
1014 			    ("geom %p has more than one provider", gp));
1015 			g_media_gone(pp, flag);
1016 		}
1017 	}
1018 }
1019 
1020 int
1021 disk_resize(struct disk *dp, int flag)
1022 {
1023 
1024 	if (dp->d_destroyed || dp->d_geom == NULL)
1025 		return (0);
1026 
1027 	return (g_post_event(g_disk_resize, dp, flag, NULL));
1028 }
1029 
1030 static void
1031 g_kern_disks(void *p, int flag __unused)
1032 {
1033 	struct sbuf *sb;
1034 	struct g_geom *gp;
1035 	char *sp;
1036 
1037 	sb = p;
1038 	sp = "";
1039 	g_topology_assert();
1040 	LIST_FOREACH(gp, &g_disk_class.geom, geom) {
1041 		sbuf_printf(sb, "%s%s", sp, gp->name);
1042 		sp = " ";
1043 	}
1044 	sbuf_finish(sb);
1045 }
1046 
1047 static int
1048 g_disk_sysctl_flags(SYSCTL_HANDLER_ARGS)
1049 {
1050 	struct disk *dp;
1051 	struct sbuf *sb;
1052 	int error;
1053 
1054 	sb = sbuf_new_auto();
1055 	dp = (struct disk *)arg1;
1056 	sbuf_printf(sb, "%b", dp->d_flags,
1057 		"\20"
1058 		"\2OPEN"
1059 		"\3CANDELETE"
1060 		"\4CANFLUSHCACHE"
1061 		"\5UNMAPPEDBIO"
1062 		"\6DIRECTCOMPLETION"
1063 		"\10CANZONE"
1064 		"\11WRITEPROTECT");
1065 
1066 	sbuf_finish(sb);
1067 	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
1068 	sbuf_delete(sb);
1069 	return (error);
1070 }
1071 
1072 static int
1073 sysctl_disks(SYSCTL_HANDLER_ARGS)
1074 {
1075 	int error;
1076 	struct sbuf *sb;
1077 
1078 	sb = sbuf_new_auto();
1079 	g_waitfor_event(g_kern_disks, sb, M_WAITOK, NULL);
1080 	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
1081 	sbuf_delete(sb);
1082 	return error;
1083 }
1084 
1085 SYSCTL_PROC(_kern, OID_AUTO, disks,
1086     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
1087     sysctl_disks, "A", "names of available disks");
1088