xref: /freebsd/sys/geom/geom_disk.c (revision 6829dae12bb055451fa467da4589c43bd03b1e64)
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/bus.h>
49 #include <sys/ctype.h>
50 #include <sys/fcntl.h>
51 #include <sys/malloc.h>
52 #include <sys/sbuf.h>
53 #include <sys/devicestat.h>
54 #include <machine/md_var.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 mtx		 done_mtx;
68 	struct disk		*dp;
69 	struct sysctl_ctx_list	sysctl_ctx;
70 	struct sysctl_oid	*sysctl_tree;
71 	char			led[64];
72 	uint32_t		state;
73 	struct mtx		 start_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, 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 (sc == NULL || (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 	/* XXX: will witness accept a mix of Giant/unGiant drivers here ? */
236 	bp2 = bp->bio_parent;
237 	sc = bp2->bio_to->private;
238 	bp->bio_completed = bp->bio_length - bp->bio_resid;
239 	binuptime(&now);
240 	mtx_lock(&sc->done_mtx);
241 	if (bp2->bio_error == 0)
242 		bp2->bio_error = bp->bio_error;
243 	bp2->bio_completed += bp->bio_completed;
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->dp->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 	int error;
274 
275 	sc = pp->private;
276 	dp = sc->dp;
277 
278 	if (dp->d_ioctl == NULL)
279 		return (ENOIOCTL);
280 	error = dp->d_ioctl(dp, cmd, data, fflag, td);
281 	return (error);
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;
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 	if (sc == NULL || (dp = sc->dp) == NULL || dp->d_destroyed) {
436 		g_io_deliver(bp, ENXIO);
437 		return;
438 	}
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 		off = 0;
453 		bp3 = NULL;
454 		bp2 = g_clone_bio(bp);
455 		if (bp2 == NULL) {
456 			error = ENOMEM;
457 			break;
458 		}
459 		for (;;) {
460 			if (g_disk_limit(dp, bp2)) {
461 				off += bp2->bio_length;
462 
463 				/*
464 				 * To avoid a race, we need to grab the next bio
465 				 * before we schedule this one.  See "notes".
466 				 */
467 				bp3 = g_clone_bio(bp);
468 				if (bp3 == NULL)
469 					bp->bio_error = ENOMEM;
470 			}
471 			bp2->bio_done = g_disk_done;
472 			bp2->bio_pblkno = bp2->bio_offset / dp->d_sectorsize;
473 			bp2->bio_bcount = bp2->bio_length;
474 			bp2->bio_disk = dp;
475 			mtx_lock(&sc->start_mtx);
476 			devstat_start_transaction_bio(dp->d_devstat, bp2);
477 			mtx_unlock(&sc->start_mtx);
478 			dp->d_strategy(bp2);
479 
480 			if (bp3 == NULL)
481 				break;
482 
483 			bp2 = bp3;
484 			bp3 = NULL;
485 			g_disk_advance(dp, bp2, off);
486 		}
487 		break;
488 	case BIO_GETATTR:
489 		/* Give the driver a chance to override */
490 		if (dp->d_getattr != NULL) {
491 			if (bp->bio_disk == NULL)
492 				bp->bio_disk = dp;
493 			error = dp->d_getattr(bp);
494 			if (error != -1)
495 				break;
496 			error = EJUSTRETURN;
497 		}
498 		if (g_handleattr_int(bp, "GEOM::candelete",
499 		    (dp->d_flags & DISKFLAG_CANDELETE) != 0))
500 			break;
501 		else if (g_handleattr_int(bp, "GEOM::fwsectors",
502 		    dp->d_fwsectors))
503 			break;
504 		else if (g_handleattr_int(bp, "GEOM::fwheads", dp->d_fwheads))
505 			break;
506 		else if (g_handleattr_off_t(bp, "GEOM::frontstuff", 0))
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
532 			error = ENOIOCTL;
533 		break;
534 	case BIO_FLUSH:
535 		g_trace(G_T_BIO, "g_disk_flushcache(%s)",
536 		    bp->bio_to->name);
537 		if (!(dp->d_flags & DISKFLAG_CANFLUSHCACHE)) {
538 			error = EOPNOTSUPP;
539 			break;
540 		}
541 		/*FALLTHROUGH*/
542 	case BIO_ZONE:
543 		if (bp->bio_cmd == BIO_ZONE) {
544 			if (!(dp->d_flags & DISKFLAG_CANZONE)) {
545 				error = EOPNOTSUPP;
546 				break;
547 			}
548 			g_trace(G_T_BIO, "g_disk_zone(%s)",
549 			    bp->bio_to->name);
550 		}
551 		bp2 = g_clone_bio(bp);
552 		if (bp2 == NULL) {
553 			g_io_deliver(bp, ENOMEM);
554 			return;
555 		}
556 		bp2->bio_done = g_disk_done;
557 		bp2->bio_disk = dp;
558 		mtx_lock(&sc->start_mtx);
559 		devstat_start_transaction_bio(dp->d_devstat, bp2);
560 		mtx_unlock(&sc->start_mtx);
561 		dp->d_strategy(bp2);
562 		break;
563 	default:
564 		error = EOPNOTSUPP;
565 		break;
566 	}
567 	if (error != EJUSTRETURN)
568 		g_io_deliver(bp, error);
569 	return;
570 }
571 
572 static void
573 g_disk_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp, struct g_consumer *cp, struct g_provider *pp)
574 {
575 	struct bio *bp;
576 	struct disk *dp;
577 	struct g_disk_softc *sc;
578 	char *buf;
579 	int res = 0;
580 
581 	sc = gp->softc;
582 	if (sc == NULL || (dp = sc->dp) == NULL)
583 		return;
584 	if (indent == NULL) {
585 		sbuf_printf(sb, " hd %u", dp->d_fwheads);
586 		sbuf_printf(sb, " sc %u", dp->d_fwsectors);
587 		return;
588 	}
589 	if (pp != NULL) {
590 		sbuf_printf(sb, "%s<fwheads>%u</fwheads>\n",
591 		    indent, dp->d_fwheads);
592 		sbuf_printf(sb, "%s<fwsectors>%u</fwsectors>\n",
593 		    indent, dp->d_fwsectors);
594 
595 		/*
596 		 * "rotationrate" is a little complicated, because the value
597 		 * returned by the drive might not be the RPM; 0 and 1 are
598 		 * special cases, and there's also a valid range.
599 		 */
600 		sbuf_printf(sb, "%s<rotationrate>", indent);
601 		if (dp->d_rotation_rate == DISK_RR_UNKNOWN) /* Old drives */
602 			sbuf_printf(sb, "unknown");	/* don't report RPM. */
603 		else if (dp->d_rotation_rate == DISK_RR_NON_ROTATING)
604 			sbuf_printf(sb, "0");
605 		else if ((dp->d_rotation_rate >= DISK_RR_MIN) &&
606 		    (dp->d_rotation_rate <= DISK_RR_MAX))
607 			sbuf_printf(sb, "%u", dp->d_rotation_rate);
608 		else
609 			sbuf_printf(sb, "invalid");
610 		sbuf_printf(sb, "</rotationrate>\n");
611 		if (dp->d_getattr != NULL) {
612 			buf = g_malloc(DISK_IDENT_SIZE, M_WAITOK);
613 			bp = g_alloc_bio();
614 			bp->bio_disk = dp;
615 			bp->bio_attribute = "GEOM::ident";
616 			bp->bio_length = DISK_IDENT_SIZE;
617 			bp->bio_data = buf;
618 			res = dp->d_getattr(bp);
619 			sbuf_printf(sb, "%s<ident>", indent);
620 			g_conf_printf_escaped(sb, "%s",
621 			    res == 0 ? buf: dp->d_ident);
622 			sbuf_printf(sb, "</ident>\n");
623 			bp->bio_attribute = "GEOM::lunid";
624 			bp->bio_length = DISK_IDENT_SIZE;
625 			bp->bio_data = buf;
626 			if (dp->d_getattr(bp) == 0) {
627 				sbuf_printf(sb, "%s<lunid>", indent);
628 				g_conf_printf_escaped(sb, "%s", buf);
629 				sbuf_printf(sb, "</lunid>\n");
630 			}
631 			bp->bio_attribute = "GEOM::lunname";
632 			bp->bio_length = DISK_IDENT_SIZE;
633 			bp->bio_data = buf;
634 			if (dp->d_getattr(bp) == 0) {
635 				sbuf_printf(sb, "%s<lunname>", indent);
636 				g_conf_printf_escaped(sb, "%s", buf);
637 				sbuf_printf(sb, "</lunname>\n");
638 			}
639 			g_destroy_bio(bp);
640 			g_free(buf);
641 		} else {
642 			sbuf_printf(sb, "%s<ident>", indent);
643 			g_conf_printf_escaped(sb, "%s", dp->d_ident);
644 			sbuf_printf(sb, "</ident>\n");
645 		}
646 		sbuf_printf(sb, "%s<descr>", indent);
647 		g_conf_printf_escaped(sb, "%s", dp->d_descr);
648 		sbuf_printf(sb, "</descr>\n");
649 	}
650 }
651 
652 static void
653 g_disk_resize(void *ptr, int flag)
654 {
655 	struct disk *dp;
656 	struct g_geom *gp;
657 	struct g_provider *pp;
658 
659 	if (flag == EV_CANCEL)
660 		return;
661 	g_topology_assert();
662 
663 	dp = ptr;
664 	gp = dp->d_geom;
665 
666 	if (dp->d_destroyed || gp == NULL)
667 		return;
668 
669 	LIST_FOREACH(pp, &gp->provider, provider) {
670 		if (pp->sectorsize != 0 &&
671 		    pp->sectorsize != dp->d_sectorsize)
672 			g_wither_provider(pp, ENXIO);
673 		else
674 			g_resize_provider(pp, dp->d_mediasize);
675 	}
676 }
677 
678 static void
679 g_disk_create(void *arg, int flag)
680 {
681 	struct g_geom *gp;
682 	struct g_provider *pp;
683 	struct disk *dp;
684 	struct g_disk_softc *sc;
685 	struct disk_alias *dap;
686 	char tmpstr[80];
687 
688 	if (flag == EV_CANCEL)
689 		return;
690 	g_topology_assert();
691 	dp = arg;
692 
693 	mtx_pool_lock(mtxpool_sleep, dp);
694 	dp->d_init_level = DISK_INIT_START;
695 
696 	/*
697 	 * If the disk has already gone away, we can just stop here and
698 	 * call the user's callback to tell him we've cleaned things up.
699 	 */
700 	if (dp->d_goneflag != 0) {
701 		mtx_pool_unlock(mtxpool_sleep, dp);
702 		if (dp->d_gone != NULL)
703 			dp->d_gone(dp);
704 		return;
705 	}
706 	mtx_pool_unlock(mtxpool_sleep, dp);
707 
708 	sc = g_malloc(sizeof(*sc), M_WAITOK | M_ZERO);
709 	mtx_init(&sc->start_mtx, "g_disk_start", NULL, MTX_DEF);
710 	mtx_init(&sc->done_mtx, "g_disk_done", NULL, MTX_DEF);
711 	sc->dp = dp;
712 	gp = g_new_geomf(&g_disk_class, "%s%d", dp->d_name, dp->d_unit);
713 	gp->softc = sc;
714 	LIST_FOREACH(dap, &dp->d_aliases, da_next) {
715 		snprintf(tmpstr, sizeof(tmpstr), "%s%d", dap->da_alias, dp->d_unit);
716 		g_geom_add_alias(gp, tmpstr);
717 	}
718 	pp = g_new_providerf(gp, "%s", gp->name);
719 	devstat_remove_entry(pp->stat);
720 	pp->stat = NULL;
721 	dp->d_devstat->id = pp;
722 	pp->mediasize = dp->d_mediasize;
723 	pp->sectorsize = dp->d_sectorsize;
724 	pp->stripeoffset = dp->d_stripeoffset;
725 	pp->stripesize = dp->d_stripesize;
726 	if ((dp->d_flags & DISKFLAG_UNMAPPED_BIO) != 0)
727 		pp->flags |= G_PF_ACCEPT_UNMAPPED;
728 	if ((dp->d_flags & DISKFLAG_DIRECT_COMPLETION) != 0)
729 		pp->flags |= G_PF_DIRECT_SEND;
730 	pp->flags |= G_PF_DIRECT_RECEIVE;
731 	if (bootverbose)
732 		printf("GEOM: new disk %s\n", gp->name);
733 	sysctl_ctx_init(&sc->sysctl_ctx);
734 	snprintf(tmpstr, sizeof(tmpstr), "GEOM disk %s", gp->name);
735 	sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
736 		SYSCTL_STATIC_CHILDREN(_kern_geom_disk), OID_AUTO, gp->name,
737 		CTLFLAG_RD, 0, tmpstr);
738 	if (sc->sysctl_tree != NULL) {
739 		SYSCTL_ADD_STRING(&sc->sysctl_ctx,
740 		    SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO, "led",
741 		    CTLFLAG_RWTUN, sc->led, sizeof(sc->led),
742 		    "LED name");
743 		SYSCTL_ADD_PROC(&sc->sysctl_ctx,
744 		    SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO, "flags",
745 		    CTLTYPE_STRING | CTLFLAG_RD, dp, 0, g_disk_sysctl_flags,
746 		    "A", "Report disk flags");
747 	}
748 	pp->private = sc;
749 	dp->d_geom = gp;
750 	g_error_provider(pp, 0);
751 
752 	mtx_pool_lock(mtxpool_sleep, dp);
753 	dp->d_init_level = DISK_INIT_DONE;
754 
755 	/*
756 	 * If the disk has gone away at this stage, start the withering
757 	 * process for it.
758 	 */
759 	if (dp->d_goneflag != 0) {
760 		mtx_pool_unlock(mtxpool_sleep, dp);
761 		g_wither_provider(pp, ENXIO);
762 		return;
763 	}
764 	mtx_pool_unlock(mtxpool_sleep, dp);
765 
766 }
767 
768 /*
769  * We get this callback after all of the consumers have gone away, and just
770  * before the provider is freed.  If the disk driver provided a d_gone
771  * callback, let them know that it is okay to free resources -- they won't
772  * be getting any more accesses from GEOM.
773  */
774 static void
775 g_disk_providergone(struct g_provider *pp)
776 {
777 	struct disk *dp;
778 	struct g_disk_softc *sc;
779 
780 	sc = (struct g_disk_softc *)pp->private;
781 	dp = sc->dp;
782 	if (dp != NULL && dp->d_gone != NULL)
783 		dp->d_gone(dp);
784 	if (sc->sysctl_tree != NULL) {
785 		sysctl_ctx_free(&sc->sysctl_ctx);
786 		sc->sysctl_tree = NULL;
787 	}
788 	if (sc->led[0] != 0) {
789 		led_set(sc->led, "0");
790 		sc->led[0] = 0;
791 	}
792 	pp->private = NULL;
793 	pp->geom->softc = NULL;
794 	mtx_destroy(&sc->done_mtx);
795 	mtx_destroy(&sc->start_mtx);
796 	g_free(sc);
797 }
798 
799 static void
800 g_disk_destroy(void *ptr, int flag)
801 {
802 	struct disk *dp;
803 	struct g_geom *gp;
804 	struct g_disk_softc *sc;
805 	struct disk_alias *dap, *daptmp;
806 
807 	g_topology_assert();
808 	dp = ptr;
809 	gp = dp->d_geom;
810 	if (gp != NULL) {
811 		sc = gp->softc;
812 		if (sc != NULL)
813 			sc->dp = NULL;
814 		dp->d_geom = NULL;
815 		g_wither_geom(gp, ENXIO);
816 	}
817 	LIST_FOREACH_SAFE(dap, &dp->d_aliases, da_next, daptmp)
818 		g_free(dap);
819 
820 	g_free(dp);
821 }
822 
823 /*
824  * We only allow printable characters in disk ident,
825  * the rest is converted to 'x<HH>'.
826  */
827 static void
828 g_disk_ident_adjust(char *ident, size_t size)
829 {
830 	char *p, tmp[4], newid[DISK_IDENT_SIZE];
831 
832 	newid[0] = '\0';
833 	for (p = ident; *p != '\0'; p++) {
834 		if (isprint(*p)) {
835 			tmp[0] = *p;
836 			tmp[1] = '\0';
837 		} else {
838 			snprintf(tmp, sizeof(tmp), "x%02hhx",
839 			    *(unsigned char *)p);
840 		}
841 		if (strlcat(newid, tmp, sizeof(newid)) >= sizeof(newid))
842 			break;
843 	}
844 	bzero(ident, size);
845 	strlcpy(ident, newid, size);
846 }
847 
848 struct disk *
849 disk_alloc(void)
850 {
851 	struct disk *dp;
852 
853 	dp = g_malloc(sizeof(struct disk), M_WAITOK | M_ZERO);
854 	LIST_INIT(&dp->d_aliases);
855 	return (dp);
856 }
857 
858 void
859 disk_create(struct disk *dp, int version)
860 {
861 
862 	if (version != DISK_VERSION) {
863 		printf("WARNING: Attempt to add disk %s%d %s",
864 		    dp->d_name, dp->d_unit,
865 		    " using incompatible ABI version of disk(9)\n");
866 		printf("WARNING: Ignoring disk %s%d\n",
867 		    dp->d_name, dp->d_unit);
868 		return;
869 	}
870 	if (dp->d_flags & DISKFLAG_RESERVED) {
871 		printf("WARNING: Attempt to add non-MPSAFE disk %s%d\n",
872 		    dp->d_name, dp->d_unit);
873 		printf("WARNING: Ignoring disk %s%d\n",
874 		    dp->d_name, dp->d_unit);
875 		return;
876 	}
877 	KASSERT(dp->d_strategy != NULL, ("disk_create need d_strategy"));
878 	KASSERT(dp->d_name != NULL, ("disk_create need d_name"));
879 	KASSERT(*dp->d_name != 0, ("disk_create need d_name"));
880 	KASSERT(strlen(dp->d_name) < SPECNAMELEN - 4, ("disk name too long"));
881 	if (dp->d_devstat == NULL)
882 		dp->d_devstat = devstat_new_entry(dp->d_name, dp->d_unit,
883 		    dp->d_sectorsize, DEVSTAT_ALL_SUPPORTED,
884 		    DEVSTAT_TYPE_DIRECT, DEVSTAT_PRIORITY_MAX);
885 	dp->d_geom = NULL;
886 
887 	dp->d_init_level = DISK_INIT_NONE;
888 
889 	g_disk_ident_adjust(dp->d_ident, sizeof(dp->d_ident));
890 	g_post_event(g_disk_create, dp, M_WAITOK, dp, NULL);
891 }
892 
893 void
894 disk_destroy(struct disk *dp)
895 {
896 
897 	g_cancel_event(dp);
898 	dp->d_destroyed = 1;
899 	if (dp->d_devstat != NULL)
900 		devstat_remove_entry(dp->d_devstat);
901 	g_post_event(g_disk_destroy, dp, M_WAITOK, NULL);
902 }
903 
904 void
905 disk_add_alias(struct disk *dp, const char *name)
906 {
907 	struct disk_alias *dap;
908 
909 	dap = (struct disk_alias *)g_malloc(
910 		sizeof(struct disk_alias) + strlen(name) + 1, M_WAITOK);
911 	strcpy((char *)(dap + 1), name);
912 	dap->da_alias = (const char *)(dap + 1);
913 	LIST_INSERT_HEAD(&dp->d_aliases, dap, da_next);
914 }
915 
916 void
917 disk_gone(struct disk *dp)
918 {
919 	struct g_geom *gp;
920 	struct g_provider *pp;
921 
922 	mtx_pool_lock(mtxpool_sleep, dp);
923 	dp->d_goneflag = 1;
924 
925 	/*
926 	 * If we're still in the process of creating this disk (the
927 	 * g_disk_create() function is still queued, or is in
928 	 * progress), the init level will not yet be DISK_INIT_DONE.
929 	 *
930 	 * If that is the case, g_disk_create() will see d_goneflag
931 	 * and take care of cleaning things up.
932 	 *
933 	 * If the disk has already been created, we default to
934 	 * withering the provider as usual below.
935 	 *
936 	 * If the caller has not set a d_gone() callback, he will
937 	 * not be any worse off by returning here, because the geom
938 	 * has not been fully setup in any case.
939 	 */
940 	if (dp->d_init_level < DISK_INIT_DONE) {
941 		mtx_pool_unlock(mtxpool_sleep, dp);
942 		return;
943 	}
944 	mtx_pool_unlock(mtxpool_sleep, dp);
945 
946 	gp = dp->d_geom;
947 	if (gp != NULL) {
948 		pp = LIST_FIRST(&gp->provider);
949 		if (pp != NULL) {
950 			KASSERT(LIST_NEXT(pp, provider) == NULL,
951 			    ("geom %p has more than one provider", gp));
952 			g_wither_provider(pp, ENXIO);
953 		}
954 	}
955 }
956 
957 void
958 disk_attr_changed(struct disk *dp, const char *attr, int flag)
959 {
960 	struct g_geom *gp;
961 	struct g_provider *pp;
962 	char devnamebuf[128];
963 
964 	gp = dp->d_geom;
965 	if (gp != NULL)
966 		LIST_FOREACH(pp, &gp->provider, provider)
967 			(void)g_attr_changed(pp, attr, flag);
968 	snprintf(devnamebuf, sizeof(devnamebuf), "devname=%s%d", dp->d_name,
969 	    dp->d_unit);
970 	devctl_notify("GEOM", "disk", attr, devnamebuf);
971 }
972 
973 void
974 disk_media_changed(struct disk *dp, int flag)
975 {
976 	struct g_geom *gp;
977 	struct g_provider *pp;
978 
979 	gp = dp->d_geom;
980 	if (gp != NULL) {
981 		pp = LIST_FIRST(&gp->provider);
982 		if (pp != NULL) {
983 			KASSERT(LIST_NEXT(pp, provider) == NULL,
984 			    ("geom %p has more than one provider", gp));
985 			g_media_changed(pp, flag);
986 		}
987 	}
988 }
989 
990 void
991 disk_media_gone(struct disk *dp, int flag)
992 {
993 	struct g_geom *gp;
994 	struct g_provider *pp;
995 
996 	gp = dp->d_geom;
997 	if (gp != NULL) {
998 		pp = LIST_FIRST(&gp->provider);
999 		if (pp != NULL) {
1000 			KASSERT(LIST_NEXT(pp, provider) == NULL,
1001 			    ("geom %p has more than one provider", gp));
1002 			g_media_gone(pp, flag);
1003 		}
1004 	}
1005 }
1006 
1007 int
1008 disk_resize(struct disk *dp, int flag)
1009 {
1010 
1011 	if (dp->d_destroyed || dp->d_geom == NULL)
1012 		return (0);
1013 
1014 	return (g_post_event(g_disk_resize, dp, flag, NULL));
1015 }
1016 
1017 static void
1018 g_kern_disks(void *p, int flag __unused)
1019 {
1020 	struct sbuf *sb;
1021 	struct g_geom *gp;
1022 	char *sp;
1023 
1024 	sb = p;
1025 	sp = "";
1026 	g_topology_assert();
1027 	LIST_FOREACH(gp, &g_disk_class.geom, geom) {
1028 		sbuf_printf(sb, "%s%s", sp, gp->name);
1029 		sp = " ";
1030 	}
1031 	sbuf_finish(sb);
1032 }
1033 
1034 static int
1035 g_disk_sysctl_flags(SYSCTL_HANDLER_ARGS)
1036 {
1037 	struct disk *dp;
1038 	struct sbuf *sb;
1039 	int error;
1040 
1041 	sb = sbuf_new_auto();
1042 	dp = (struct disk *)arg1;
1043 	sbuf_printf(sb, "%b", dp->d_flags,
1044 		"\20"
1045 		"\2OPEN"
1046 		"\3CANDELETE"
1047 		"\4CANFLUSHCACHE"
1048 		"\5UNMAPPEDBIO"
1049 		"\6DIRECTCOMPLETION"
1050 		"\10CANZONE"
1051 		"\11WRITEPROTECT");
1052 
1053 	sbuf_finish(sb);
1054 	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
1055 	sbuf_delete(sb);
1056 	return (error);
1057 }
1058 
1059 static int
1060 sysctl_disks(SYSCTL_HANDLER_ARGS)
1061 {
1062 	int error;
1063 	struct sbuf *sb;
1064 
1065 	sb = sbuf_new_auto();
1066 	g_waitfor_event(g_kern_disks, sb, M_WAITOK, NULL);
1067 	error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1);
1068 	sbuf_delete(sb);
1069 	return error;
1070 }
1071 
1072 SYSCTL_PROC(_kern, OID_AUTO, disks,
1073     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
1074     sysctl_disks, "A", "names of available disks");
1075