xref: /freebsd/sys/geom/geom_disk.c (revision d5b0e70f7e04d971691517ce1304d86a1e367e2e)
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 __diagused;
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 	if (dp->d_devstat == NULL) {
725 		dp->d_devstat = devstat_new_entry(dp->d_name, dp->d_unit,
726 		    dp->d_sectorsize, DEVSTAT_ALL_SUPPORTED,
727 		    DEVSTAT_TYPE_DIRECT, DEVSTAT_PRIORITY_MAX);
728 	}
729 	sc->d_devstat = dp->d_devstat;
730 	gp = g_new_geomf(&g_disk_class, "%s%d", dp->d_name, dp->d_unit);
731 	gp->softc = sc;
732 	pp = g_new_providerf(gp, "%s", gp->name);
733 	LIST_FOREACH(dap, &dp->d_aliases, da_next)
734 		g_provider_add_alias(pp, "%s%d", dap->da_alias, dp->d_unit);
735 	devstat_remove_entry(pp->stat);
736 	pp->stat = NULL;
737 	dp->d_devstat->id = pp;
738 	pp->mediasize = dp->d_mediasize;
739 	pp->sectorsize = dp->d_sectorsize;
740 	pp->stripeoffset = dp->d_stripeoffset;
741 	pp->stripesize = dp->d_stripesize;
742 	if ((dp->d_flags & DISKFLAG_UNMAPPED_BIO) != 0)
743 		pp->flags |= G_PF_ACCEPT_UNMAPPED;
744 	if ((dp->d_flags & DISKFLAG_DIRECT_COMPLETION) != 0)
745 		pp->flags |= G_PF_DIRECT_SEND;
746 	pp->flags |= G_PF_DIRECT_RECEIVE;
747 	if (bootverbose)
748 		printf("GEOM: new disk %s\n", gp->name);
749 	sysctl_ctx_init(&sc->sysctl_ctx);
750 	snprintf(tmpstr, sizeof(tmpstr), "GEOM disk %s", gp->name);
751 	sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
752 		SYSCTL_STATIC_CHILDREN(_kern_geom_disk), OID_AUTO, gp->name,
753 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, tmpstr);
754 	if (sc->sysctl_tree != NULL) {
755 		SYSCTL_ADD_STRING(&sc->sysctl_ctx,
756 		    SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO, "led",
757 		    CTLFLAG_RWTUN, sc->led, sizeof(sc->led),
758 		    "LED name");
759 		SYSCTL_ADD_PROC(&sc->sysctl_ctx,
760 		    SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO, "flags",
761 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, dp, 0,
762 		    g_disk_sysctl_flags, "A", "Report disk flags");
763 	}
764 	pp->private = sc;
765 	dp->d_geom = gp;
766 	g_error_provider(pp, 0);
767 
768 	mtx_pool_lock(mtxpool_sleep, dp);
769 	dp->d_init_level = DISK_INIT_DONE;
770 
771 	/*
772 	 * If the disk has gone away at this stage, start the withering
773 	 * process for it.
774 	 */
775 	if (dp->d_goneflag != 0) {
776 		mtx_pool_unlock(mtxpool_sleep, dp);
777 		g_wither_provider(pp, ENXIO);
778 		return;
779 	}
780 	mtx_pool_unlock(mtxpool_sleep, dp);
781 
782 }
783 
784 /*
785  * We get this callback after all of the consumers have gone away, and just
786  * before the provider is freed.  If the disk driver provided a d_gone
787  * callback, let them know that it is okay to free resources -- they won't
788  * be getting any more accesses from GEOM.
789  */
790 static void
791 g_disk_providergone(struct g_provider *pp)
792 {
793 	struct disk *dp;
794 	struct g_disk_softc *sc;
795 
796 	sc = (struct g_disk_softc *)pp->private;
797 	dp = sc->dp;
798 	if (dp != NULL && dp->d_gone != NULL)
799 		dp->d_gone(dp);
800 	if (sc->sysctl_tree != NULL) {
801 		sysctl_ctx_free(&sc->sysctl_ctx);
802 		sc->sysctl_tree = NULL;
803 	}
804 	if (sc->led[0] != 0) {
805 		led_set(sc->led, "0");
806 		sc->led[0] = 0;
807 	}
808 	pp->private = NULL;
809 	pp->geom->softc = NULL;
810 	mtx_destroy(&sc->done_mtx);
811 	g_free(sc);
812 }
813 
814 static void
815 g_disk_destroy(void *ptr, int flag)
816 {
817 	struct disk *dp;
818 	struct g_geom *gp;
819 	struct g_disk_softc *sc;
820 	struct disk_alias *dap, *daptmp;
821 
822 	g_topology_assert();
823 	dp = ptr;
824 	gp = dp->d_geom;
825 	if (gp != NULL) {
826 		sc = gp->softc;
827 		if (sc != NULL)
828 			sc->dp = NULL;
829 		dp->d_geom = NULL;
830 		g_wither_geom(gp, ENXIO);
831 	}
832 	LIST_FOREACH_SAFE(dap, &dp->d_aliases, da_next, daptmp)
833 		g_free(dap);
834 
835 	g_free(dp);
836 }
837 
838 /*
839  * We only allow printable characters in disk ident,
840  * the rest is converted to 'x<HH>'.
841  */
842 static void
843 g_disk_ident_adjust(char *ident, size_t size)
844 {
845 	char *p, tmp[4], newid[DISK_IDENT_SIZE];
846 
847 	newid[0] = '\0';
848 	for (p = ident; *p != '\0'; p++) {
849 		if (isprint(*p)) {
850 			tmp[0] = *p;
851 			tmp[1] = '\0';
852 		} else {
853 			snprintf(tmp, sizeof(tmp), "x%02hhx",
854 			    *(unsigned char *)p);
855 		}
856 		if (strlcat(newid, tmp, sizeof(newid)) >= sizeof(newid))
857 			break;
858 	}
859 	bzero(ident, size);
860 	strlcpy(ident, newid, size);
861 }
862 
863 struct disk *
864 disk_alloc(void)
865 {
866 	struct disk *dp;
867 
868 	dp = g_malloc(sizeof(struct disk), M_WAITOK | M_ZERO);
869 	LIST_INIT(&dp->d_aliases);
870 	dp->d_init_level = DISK_INIT_NONE;
871 	dp->d_cevent = g_alloc_event(M_WAITOK);
872 	dp->d_devent = g_alloc_event(M_WAITOK);
873 	return (dp);
874 }
875 
876 void
877 disk_create(struct disk *dp, int version)
878 {
879 
880 	if (version != DISK_VERSION) {
881 		printf("WARNING: Attempt to add disk %s%d %s",
882 		    dp->d_name, dp->d_unit,
883 		    " using incompatible ABI version of disk(9)\n");
884 		printf("WARNING: Ignoring disk %s%d\n",
885 		    dp->d_name, dp->d_unit);
886 		return;
887 	}
888 	if (dp->d_flags & DISKFLAG_RESERVED) {
889 		printf("WARNING: Attempt to add non-MPSAFE disk %s%d\n",
890 		    dp->d_name, dp->d_unit);
891 		printf("WARNING: Ignoring disk %s%d\n",
892 		    dp->d_name, dp->d_unit);
893 		return;
894 	}
895 	KASSERT(dp->d_strategy != NULL, ("disk_create need d_strategy"));
896 	KASSERT(dp->d_name != NULL, ("disk_create need d_name"));
897 	KASSERT(*dp->d_name != 0, ("disk_create need d_name"));
898 	KASSERT(strlen(dp->d_name) < SPECNAMELEN - 4, ("disk name too long"));
899 	g_disk_ident_adjust(dp->d_ident, sizeof(dp->d_ident));
900 
901 	dp->d_init_level = DISK_INIT_CREATE;
902 
903 	KASSERT(dp->d_cevent != NULL,
904 	    ("Disk create for %p with event NULL", dp));
905 	g_post_event_ep(g_disk_create, dp, dp->d_cevent, dp, NULL);
906 }
907 
908 void
909 disk_destroy(struct disk *dp)
910 {
911 	struct disk_alias *dap, *daptmp;
912 
913 	/* If disk_create() was never called, just free the resources. */
914 	if (dp->d_init_level < DISK_INIT_CREATE) {
915 		if (dp->d_devstat != NULL)
916 			devstat_remove_entry(dp->d_devstat);
917 		LIST_FOREACH_SAFE(dap, &dp->d_aliases, da_next, daptmp)
918 			g_free(dap);
919 		g_free(dp->d_cevent);
920 		g_free(dp->d_devent);
921 		g_free(dp);
922 		return;
923 	}
924 
925 	KASSERT(dp->d_devent != NULL,
926 	    ("Disk destroy for %p with event NULL", dp));
927 	disk_gone(dp);
928 	dp->d_destroyed = 1;
929 	g_cancel_event(dp);
930 	if (dp->d_devstat != NULL)
931 		devstat_remove_entry(dp->d_devstat);
932 	g_post_event_ep(g_disk_destroy, dp, dp->d_devent, NULL);
933 }
934 
935 void
936 disk_add_alias(struct disk *dp, const char *name)
937 {
938 	struct disk_alias *dap;
939 
940 	dap = (struct disk_alias *)g_malloc(
941 		sizeof(struct disk_alias) + strlen(name) + 1, M_WAITOK);
942 	strcpy((char *)(dap + 1), name);
943 	dap->da_alias = (const char *)(dap + 1);
944 	LIST_INSERT_HEAD(&dp->d_aliases, dap, da_next);
945 }
946 
947 void
948 disk_gone(struct disk *dp)
949 {
950 	struct g_geom *gp;
951 	struct g_provider *pp;
952 
953 	mtx_pool_lock(mtxpool_sleep, dp);
954 
955 	/*
956 	 * Second wither call makes no sense, plus we can not access the list
957 	 * of providers without topology lock after calling wither once.
958 	 */
959 	if (dp->d_goneflag != 0) {
960 		mtx_pool_unlock(mtxpool_sleep, dp);
961 		return;
962 	}
963 
964 	dp->d_goneflag = 1;
965 
966 	/*
967 	 * If we're still in the process of creating this disk (the
968 	 * g_disk_create() function is still queued, or is in
969 	 * progress), the init level will not yet be DISK_INIT_DONE.
970 	 *
971 	 * If that is the case, g_disk_create() will see d_goneflag
972 	 * and take care of cleaning things up.
973 	 *
974 	 * If the disk has already been created, we default to
975 	 * withering the provider as usual below.
976 	 *
977 	 * If the caller has not set a d_gone() callback, he will
978 	 * not be any worse off by returning here, because the geom
979 	 * has not been fully setup in any case.
980 	 */
981 	if (dp->d_init_level < DISK_INIT_DONE) {
982 		mtx_pool_unlock(mtxpool_sleep, dp);
983 		return;
984 	}
985 	mtx_pool_unlock(mtxpool_sleep, dp);
986 
987 	gp = dp->d_geom;
988 	pp = LIST_FIRST(&gp->provider);
989 	if (pp != NULL) {
990 		KASSERT(LIST_NEXT(pp, provider) == NULL,
991 		    ("geom %p has more than one provider", gp));
992 		g_wither_provider(pp, ENXIO);
993 	}
994 }
995 
996 void
997 disk_attr_changed(struct disk *dp, const char *attr, int flag)
998 {
999 	struct g_geom *gp = dp->d_geom;
1000 	struct g_provider *pp;
1001 	char devnamebuf[128];
1002 
1003 	if (gp == NULL)
1004 		return;
1005 	LIST_FOREACH(pp, &gp->provider, provider)
1006 		(void)g_attr_changed(pp, attr, flag);
1007 	snprintf(devnamebuf, sizeof(devnamebuf), "devname=%s%d", dp->d_name,
1008 	    dp->d_unit);
1009 	devctl_notify("GEOM", "disk", attr, devnamebuf);
1010 }
1011 
1012 void
1013 disk_media_changed(struct disk *dp, int flag)
1014 {
1015 	struct g_geom *gp = dp->d_geom;
1016 	struct g_provider *pp;
1017 
1018 	if (gp == NULL)
1019 		return;
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_changed(pp, flag);
1025 	}
1026 }
1027 
1028 void
1029 disk_media_gone(struct disk *dp, int flag)
1030 {
1031 	struct g_geom *gp = dp->d_geom;
1032 	struct g_provider *pp;
1033 
1034 	if (gp == NULL)
1035 		return;
1036 	pp = LIST_FIRST(&gp->provider);
1037 	if (pp != NULL) {
1038 		KASSERT(LIST_NEXT(pp, provider) == NULL,
1039 		    ("geom %p has more than one provider", gp));
1040 		g_media_gone(pp, flag);
1041 	}
1042 }
1043 
1044 int
1045 disk_resize(struct disk *dp, int flag)
1046 {
1047 
1048 	if (dp->d_destroyed || dp->d_geom == NULL)
1049 		return (0);
1050 
1051 	return (g_post_event(g_disk_resize, dp, flag, NULL));
1052 }
1053 
1054 static void
1055 g_kern_disks(void *p, int flag __unused)
1056 {
1057 	struct sbuf *sb;
1058 	struct g_geom *gp;
1059 	char *sp;
1060 
1061 	sb = p;
1062 	sp = "";
1063 	g_topology_assert();
1064 	LIST_FOREACH(gp, &g_disk_class.geom, geom) {
1065 		sbuf_printf(sb, "%s%s", sp, gp->name);
1066 		sp = " ";
1067 	}
1068 	sbuf_finish(sb);
1069 }
1070 
1071 static int
1072 g_disk_sysctl_flags(SYSCTL_HANDLER_ARGS)
1073 {
1074 	struct disk *dp;
1075 	struct sbuf *sb;
1076 	int error;
1077 
1078 	sb = sbuf_new_auto();
1079 	dp = (struct disk *)arg1;
1080 	sbuf_printf(sb, "%b", dp->d_flags,
1081 		"\20"
1082 		"\2OPEN"
1083 		"\3CANDELETE"
1084 		"\4CANFLUSHCACHE"
1085 		"\5UNMAPPEDBIO"
1086 		"\6DIRECTCOMPLETION"
1087 		"\10CANZONE"
1088 		"\11WRITEPROTECT");
1089 
1090 	sbuf_finish(sb);
1091 	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
1092 	sbuf_delete(sb);
1093 	return (error);
1094 }
1095 
1096 static int
1097 sysctl_disks(SYSCTL_HANDLER_ARGS)
1098 {
1099 	int error;
1100 	struct sbuf *sb;
1101 
1102 	sb = sbuf_new_auto();
1103 	g_waitfor_event(g_kern_disks, sb, M_WAITOK, NULL);
1104 	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
1105 	sbuf_delete(sb);
1106 	return error;
1107 }
1108 
1109 SYSCTL_PROC(_kern, OID_AUTO, disks,
1110     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
1111     sysctl_disks, "A", "names of available disks");
1112