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