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