xref: /freebsd/sys/geom/geom_dev.c (revision 2f513db72b034fd5ef7f080b11be5c711c15186a)
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 <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/malloc.h>
44 #include <sys/kernel.h>
45 #include <sys/conf.h>
46 #include <sys/ctype.h>
47 #include <sys/bio.h>
48 #include <sys/bus.h>
49 #include <sys/lock.h>
50 #include <sys/mutex.h>
51 #include <sys/proc.h>
52 #include <sys/errno.h>
53 #include <sys/time.h>
54 #include <sys/disk.h>
55 #include <sys/fcntl.h>
56 #include <sys/limits.h>
57 #include <sys/sysctl.h>
58 #include <geom/geom.h>
59 #include <geom/geom_int.h>
60 #include <machine/stdarg.h>
61 
62 struct g_dev_softc {
63 	struct mtx	 sc_mtx;
64 	struct cdev	*sc_dev;
65 	struct cdev	*sc_alias;
66 	int		 sc_open;
67 	u_int		 sc_active;
68 #define	SC_A_DESTROY	(1 << 31)
69 #define	SC_A_OPEN	(1 << 30)
70 #define	SC_A_ACTIVE	(SC_A_OPEN - 1)
71 };
72 
73 static d_open_t		g_dev_open;
74 static d_close_t	g_dev_close;
75 static d_strategy_t	g_dev_strategy;
76 static d_ioctl_t	g_dev_ioctl;
77 
78 static struct cdevsw g_dev_cdevsw = {
79 	.d_version =	D_VERSION,
80 	.d_open =	g_dev_open,
81 	.d_close =	g_dev_close,
82 	.d_read =	physread,
83 	.d_write =	physwrite,
84 	.d_ioctl =	g_dev_ioctl,
85 	.d_strategy =	g_dev_strategy,
86 	.d_name =	"g_dev",
87 	.d_flags =	D_DISK | D_TRACKCLOSE,
88 };
89 
90 static g_init_t g_dev_init;
91 static g_fini_t g_dev_fini;
92 static g_taste_t g_dev_taste;
93 static g_orphan_t g_dev_orphan;
94 static g_attrchanged_t g_dev_attrchanged;
95 static g_resize_t g_dev_resize;
96 
97 static struct g_class g_dev_class	= {
98 	.name = "DEV",
99 	.version = G_VERSION,
100 	.init = g_dev_init,
101 	.fini = g_dev_fini,
102 	.taste = g_dev_taste,
103 	.orphan = g_dev_orphan,
104 	.attrchanged = g_dev_attrchanged,
105 	.resize = g_dev_resize
106 };
107 
108 /*
109  * We target 262144 (8 x 32768) sectors by default as this significantly
110  * increases the throughput on commonly used SSD's with a marginal
111  * increase in non-interruptible request latency.
112  */
113 static uint64_t g_dev_del_max_sectors = 262144;
114 SYSCTL_DECL(_kern_geom);
115 SYSCTL_NODE(_kern_geom, OID_AUTO, dev, CTLFLAG_RW, 0, "GEOM_DEV stuff");
116 SYSCTL_QUAD(_kern_geom_dev, OID_AUTO, delete_max_sectors, CTLFLAG_RW,
117     &g_dev_del_max_sectors, 0, "Maximum number of sectors in a single "
118     "delete request sent to the provider. Larger requests are chunked "
119     "so they can be interrupted. (0 = disable chunking)");
120 
121 static char *dumpdev = NULL;
122 static void
123 g_dev_init(struct g_class *mp)
124 {
125 
126 	dumpdev = kern_getenv("dumpdev");
127 }
128 
129 static void
130 g_dev_fini(struct g_class *mp)
131 {
132 
133 	freeenv(dumpdev);
134 	dumpdev = NULL;
135 }
136 
137 static int
138 g_dev_setdumpdev(struct cdev *dev, struct diocskerneldump_arg *kda)
139 {
140 	struct g_kerneldump kd;
141 	struct g_consumer *cp;
142 	int error, len;
143 
144 	MPASS(dev != NULL && kda != NULL);
145 	MPASS(kda->kda_index != KDA_REMOVE);
146 
147 	cp = dev->si_drv2;
148 	len = sizeof(kd);
149 	memset(&kd, 0, len);
150 	kd.offset = 0;
151 	kd.length = OFF_MAX;
152 	error = g_io_getattr("GEOM::kerneldump", cp, &len, &kd);
153 	if (error != 0)
154 		return (error);
155 
156 	error = dumper_insert(&kd.di, devtoname(dev), kda);
157 	if (error == 0)
158 		dev->si_flags |= SI_DUMPDEV;
159 
160 	return (error);
161 }
162 
163 static int
164 init_dumpdev(struct cdev *dev)
165 {
166 	struct diocskerneldump_arg kda;
167 	struct g_consumer *cp;
168 	const char *devprefix = "/dev/", *devname;
169 	int error;
170 	size_t len;
171 
172 	bzero(&kda, sizeof(kda));
173 	kda.kda_index = KDA_APPEND;
174 
175 	if (dumpdev == NULL)
176 		return (0);
177 
178 	len = strlen(devprefix);
179 	devname = devtoname(dev);
180 	if (strcmp(devname, dumpdev) != 0 &&
181 	   (strncmp(dumpdev, devprefix, len) != 0 ||
182 	    strcmp(devname, dumpdev + len) != 0))
183 		return (0);
184 
185 	cp = (struct g_consumer *)dev->si_drv2;
186 	error = g_access(cp, 1, 0, 0);
187 	if (error != 0)
188 		return (error);
189 
190 	error = g_dev_setdumpdev(dev, &kda);
191 	if (error == 0) {
192 		freeenv(dumpdev);
193 		dumpdev = NULL;
194 	}
195 
196 	(void)g_access(cp, -1, 0, 0);
197 
198 	return (error);
199 }
200 
201 static void
202 g_dev_destroy(void *arg, int flags __unused)
203 {
204 	struct g_consumer *cp;
205 	struct g_geom *gp;
206 	struct g_dev_softc *sc;
207 	char buf[SPECNAMELEN + 6];
208 
209 	g_topology_assert();
210 	cp = arg;
211 	gp = cp->geom;
212 	sc = cp->private;
213 	g_trace(G_T_TOPOLOGY, "g_dev_destroy(%p(%s))", cp, gp->name);
214 	snprintf(buf, sizeof(buf), "cdev=%s", gp->name);
215 	devctl_notify_f("GEOM", "DEV", "DESTROY", buf, M_WAITOK);
216 	if (cp->acr > 0 || cp->acw > 0 || cp->ace > 0)
217 		g_access(cp, -cp->acr, -cp->acw, -cp->ace);
218 	g_detach(cp);
219 	g_destroy_consumer(cp);
220 	g_destroy_geom(gp);
221 	mtx_destroy(&sc->sc_mtx);
222 	g_free(sc);
223 }
224 
225 void
226 g_dev_print(void)
227 {
228 	struct g_geom *gp;
229 	char const *p = "";
230 
231 	LIST_FOREACH(gp, &g_dev_class.geom, geom) {
232 		printf("%s%s", p, gp->name);
233 		p = " ";
234 	}
235 	printf("\n");
236 }
237 
238 static void
239 g_dev_set_physpath(struct g_consumer *cp)
240 {
241 	struct g_dev_softc *sc;
242 	char *physpath;
243 	int error, physpath_len;
244 
245 	if (g_access(cp, 1, 0, 0) != 0)
246 		return;
247 
248 	sc = cp->private;
249 	physpath_len = MAXPATHLEN;
250 	physpath = g_malloc(physpath_len, M_WAITOK|M_ZERO);
251 	error = g_io_getattr("GEOM::physpath", cp, &physpath_len, physpath);
252 	g_access(cp, -1, 0, 0);
253 	if (error == 0 && strlen(physpath) != 0) {
254 		struct cdev *dev, *old_alias_dev;
255 		struct cdev **alias_devp;
256 
257 		dev = sc->sc_dev;
258 		old_alias_dev = sc->sc_alias;
259 		alias_devp = (struct cdev **)&sc->sc_alias;
260 		make_dev_physpath_alias(MAKEDEV_WAITOK, alias_devp, dev,
261 		    old_alias_dev, physpath);
262 	} else if (sc->sc_alias) {
263 		destroy_dev((struct cdev *)sc->sc_alias);
264 		sc->sc_alias = NULL;
265 	}
266 	g_free(physpath);
267 }
268 
269 static void
270 g_dev_set_media(struct g_consumer *cp)
271 {
272 	struct g_dev_softc *sc;
273 	struct cdev *dev;
274 	char buf[SPECNAMELEN + 6];
275 
276 	sc = cp->private;
277 	dev = sc->sc_dev;
278 	snprintf(buf, sizeof(buf), "cdev=%s", dev->si_name);
279 	devctl_notify_f("DEVFS", "CDEV", "MEDIACHANGE", buf, M_WAITOK);
280 	devctl_notify_f("GEOM", "DEV", "MEDIACHANGE", buf, M_WAITOK);
281 	dev = sc->sc_alias;
282 	if (dev != NULL) {
283 		snprintf(buf, sizeof(buf), "cdev=%s", dev->si_name);
284 		devctl_notify_f("DEVFS", "CDEV", "MEDIACHANGE", buf, M_WAITOK);
285 		devctl_notify_f("GEOM", "DEV", "MEDIACHANGE", buf, M_WAITOK);
286 	}
287 }
288 
289 static void
290 g_dev_attrchanged(struct g_consumer *cp, const char *attr)
291 {
292 
293 	if (strcmp(attr, "GEOM::media") == 0) {
294 		g_dev_set_media(cp);
295 		return;
296 	}
297 
298 	if (strcmp(attr, "GEOM::physpath") == 0) {
299 		g_dev_set_physpath(cp);
300 		return;
301 	}
302 }
303 
304 static void
305 g_dev_resize(struct g_consumer *cp)
306 {
307 	char buf[SPECNAMELEN + 6];
308 
309 	snprintf(buf, sizeof(buf), "cdev=%s", cp->provider->name);
310 	devctl_notify_f("GEOM", "DEV", "SIZECHANGE", buf, M_WAITOK);
311 }
312 
313 struct g_provider *
314 g_dev_getprovider(struct cdev *dev)
315 {
316 	struct g_consumer *cp;
317 
318 	g_topology_assert();
319 	if (dev == NULL)
320 		return (NULL);
321 	if (dev->si_devsw != &g_dev_cdevsw)
322 		return (NULL);
323 	cp = dev->si_drv2;
324 	return (cp->provider);
325 }
326 
327 static struct g_geom *
328 g_dev_taste(struct g_class *mp, struct g_provider *pp, int insist __unused)
329 {
330 	struct g_geom *gp;
331 	struct g_geom_alias *gap;
332 	struct g_consumer *cp;
333 	struct g_dev_softc *sc;
334 	int error;
335 	struct cdev *dev, *adev;
336 	char buf[SPECNAMELEN + 6];
337 	struct make_dev_args args;
338 
339 	g_trace(G_T_TOPOLOGY, "dev_taste(%s,%s)", mp->name, pp->name);
340 	g_topology_assert();
341 	gp = g_new_geomf(mp, "%s", pp->name);
342 	sc = g_malloc(sizeof(*sc), M_WAITOK | M_ZERO);
343 	mtx_init(&sc->sc_mtx, "g_dev", NULL, MTX_DEF);
344 	cp = g_new_consumer(gp);
345 	cp->private = sc;
346 	cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
347 	error = g_attach(cp, pp);
348 	KASSERT(error == 0,
349 	    ("g_dev_taste(%s) failed to g_attach, err=%d", pp->name, error));
350 
351 	make_dev_args_init(&args);
352 	args.mda_flags = MAKEDEV_CHECKNAME | MAKEDEV_WAITOK;
353 	args.mda_devsw = &g_dev_cdevsw;
354 	args.mda_cr = NULL;
355 	args.mda_uid = UID_ROOT;
356 	args.mda_gid = GID_OPERATOR;
357 	args.mda_mode = 0640;
358 	args.mda_si_drv1 = sc;
359 	args.mda_si_drv2 = cp;
360 	error = make_dev_s(&args, &sc->sc_dev, "%s", gp->name);
361 	if (error != 0) {
362 		printf("%s: make_dev_p() failed (gp->name=%s, error=%d)\n",
363 		    __func__, gp->name, error);
364 		g_detach(cp);
365 		g_destroy_consumer(cp);
366 		g_destroy_geom(gp);
367 		mtx_destroy(&sc->sc_mtx);
368 		g_free(sc);
369 		return (NULL);
370 	}
371 	dev = sc->sc_dev;
372 	dev->si_flags |= SI_UNMAPPED;
373 	dev->si_iosize_max = MAXPHYS;
374 	error = init_dumpdev(dev);
375 	if (error != 0)
376 		printf("%s: init_dumpdev() failed (gp->name=%s, error=%d)\n",
377 		    __func__, gp->name, error);
378 
379 	g_dev_attrchanged(cp, "GEOM::physpath");
380 	snprintf(buf, sizeof(buf), "cdev=%s", gp->name);
381 	devctl_notify_f("GEOM", "DEV", "CREATE", buf, M_WAITOK);
382 	/*
383 	 * Now add all the aliases for this drive
384 	 */
385 	LIST_FOREACH(gap, &pp->geom->aliases, ga_next) {
386 		error = make_dev_alias_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK, &adev, dev,
387 		    "%s", gap->ga_alias);
388 		if (error) {
389 			printf("%s: make_dev_alias_p() failed (name=%s, error=%d)\n",
390 			    __func__, gap->ga_alias, error);
391 			continue;
392 		}
393 		snprintf(buf, sizeof(buf), "cdev=%s", gap->ga_alias);
394 		devctl_notify_f("GEOM", "DEV", "CREATE", buf, M_WAITOK);
395 	}
396 
397 	return (gp);
398 }
399 
400 static int
401 g_dev_open(struct cdev *dev, int flags, int fmt, struct thread *td)
402 {
403 	struct g_consumer *cp;
404 	struct g_dev_softc *sc;
405 	int error, r, w, e;
406 
407 	cp = dev->si_drv2;
408 	g_trace(G_T_ACCESS, "g_dev_open(%s, %d, %d, %p)",
409 	    cp->geom->name, flags, fmt, td);
410 
411 	r = flags & FREAD ? 1 : 0;
412 	w = flags & FWRITE ? 1 : 0;
413 #ifdef notyet
414 	e = flags & O_EXCL ? 1 : 0;
415 #else
416 	e = 0;
417 #endif
418 
419 	/*
420 	 * This happens on attempt to open a device node with O_EXEC.
421 	 */
422 	if (r + w + e == 0)
423 		return (EINVAL);
424 
425 	if (w) {
426 		/*
427 		 * When running in very secure mode, do not allow
428 		 * opens for writing of any disks.
429 		 */
430 		error = securelevel_ge(td->td_ucred, 2);
431 		if (error)
432 			return (error);
433 	}
434 	g_topology_lock();
435 	error = g_access(cp, r, w, e);
436 	g_topology_unlock();
437 	if (error == 0) {
438 		sc = dev->si_drv1;
439 		mtx_lock(&sc->sc_mtx);
440 		if (sc->sc_open == 0 && (sc->sc_active & SC_A_ACTIVE) != 0)
441 			wakeup(&sc->sc_active);
442 		sc->sc_open += r + w + e;
443 		if (sc->sc_open == 0)
444 			atomic_clear_int(&sc->sc_active, SC_A_OPEN);
445 		else
446 			atomic_set_int(&sc->sc_active, SC_A_OPEN);
447 		mtx_unlock(&sc->sc_mtx);
448 	}
449 	return (error);
450 }
451 
452 static int
453 g_dev_close(struct cdev *dev, int flags, int fmt, struct thread *td)
454 {
455 	struct g_consumer *cp;
456 	struct g_dev_softc *sc;
457 	int error, r, w, e;
458 
459 	cp = dev->si_drv2;
460 	g_trace(G_T_ACCESS, "g_dev_close(%s, %d, %d, %p)",
461 	    cp->geom->name, flags, fmt, td);
462 
463 	r = flags & FREAD ? -1 : 0;
464 	w = flags & FWRITE ? -1 : 0;
465 #ifdef notyet
466 	e = flags & O_EXCL ? -1 : 0;
467 #else
468 	e = 0;
469 #endif
470 
471 	/*
472 	 * The vgonel(9) - caused by eg. forced unmount of devfs - calls
473 	 * VOP_CLOSE(9) on devfs vnode without any FREAD or FWRITE flags,
474 	 * which would result in zero deltas, which in turn would cause
475 	 * panic in g_access(9).
476 	 *
477 	 * Note that we cannot zero the counters (ie. do "r = cp->acr"
478 	 * etc) instead, because the consumer might be opened in another
479 	 * devfs instance.
480 	 */
481 	if (r + w + e == 0)
482 		return (EINVAL);
483 
484 	sc = dev->si_drv1;
485 	mtx_lock(&sc->sc_mtx);
486 	sc->sc_open += r + w + e;
487 	if (sc->sc_open == 0)
488 		atomic_clear_int(&sc->sc_active, SC_A_OPEN);
489 	else
490 		atomic_set_int(&sc->sc_active, SC_A_OPEN);
491 	while (sc->sc_open == 0 && (sc->sc_active & SC_A_ACTIVE) != 0)
492 		msleep(&sc->sc_active, &sc->sc_mtx, 0, "g_dev_close", hz / 10);
493 	mtx_unlock(&sc->sc_mtx);
494 	g_topology_lock();
495 	error = g_access(cp, r, w, e);
496 	g_topology_unlock();
497 	return (error);
498 }
499 
500 static int
501 g_dev_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td)
502 {
503 	struct g_consumer *cp;
504 	struct g_provider *pp;
505 	off_t offset, length, chunk, odd;
506 	int i, error;
507 #ifdef COMPAT_FREEBSD12
508 	struct diocskerneldump_arg kda_copy;
509 #endif
510 
511 	cp = dev->si_drv2;
512 	pp = cp->provider;
513 
514 	/* If consumer or provider is dying, don't disturb. */
515 	if (cp->flags & G_CF_ORPHAN)
516 		return (ENXIO);
517 	if (pp->error)
518 		return (pp->error);
519 
520 	error = 0;
521 	KASSERT(cp->acr || cp->acw,
522 	    ("Consumer with zero access count in g_dev_ioctl"));
523 
524 	i = IOCPARM_LEN(cmd);
525 	switch (cmd) {
526 	case DIOCGSECTORSIZE:
527 		*(u_int *)data = pp->sectorsize;
528 		if (*(u_int *)data == 0)
529 			error = ENOENT;
530 		break;
531 	case DIOCGMEDIASIZE:
532 		*(off_t *)data = pp->mediasize;
533 		if (*(off_t *)data == 0)
534 			error = ENOENT;
535 		break;
536 	case DIOCGFWSECTORS:
537 		error = g_io_getattr("GEOM::fwsectors", cp, &i, data);
538 		if (error == 0 && *(u_int *)data == 0)
539 			error = ENOENT;
540 		break;
541 	case DIOCGFWHEADS:
542 		error = g_io_getattr("GEOM::fwheads", cp, &i, data);
543 		if (error == 0 && *(u_int *)data == 0)
544 			error = ENOENT;
545 		break;
546 	case DIOCGFRONTSTUFF:
547 		error = g_io_getattr("GEOM::frontstuff", cp, &i, data);
548 		break;
549 #ifdef COMPAT_FREEBSD11
550 	case DIOCSKERNELDUMP_FREEBSD11:
551 	    {
552 		struct diocskerneldump_arg kda;
553 
554 		gone_in(13, "FreeBSD 11.x ABI compat");
555 
556 		bzero(&kda, sizeof(kda));
557 		kda.kda_encryption = KERNELDUMP_ENC_NONE;
558 		kda.kda_index = (*(u_int *)data ? 0 : KDA_REMOVE_ALL);
559 		if (kda.kda_index == KDA_REMOVE_ALL)
560 			error = dumper_remove(devtoname(dev), &kda);
561 		else
562 			error = g_dev_setdumpdev(dev, &kda);
563 		break;
564 	    }
565 #endif
566 #ifdef COMPAT_FREEBSD12
567 	case DIOCSKERNELDUMP_FREEBSD12:
568 	    {
569 		struct diocskerneldump_arg_freebsd12 *kda12;
570 
571 		gone_in(14, "FreeBSD 12.x ABI compat");
572 
573 		kda12 = (void *)data;
574 		memcpy(&kda_copy, kda12, sizeof(kda_copy));
575 		kda_copy.kda_index = (kda12->kda12_enable ?
576 		    0 : KDA_REMOVE_ALL);
577 
578 		explicit_bzero(kda12, sizeof(*kda12));
579 		/* Kludge to pass kda_copy to kda in fallthrough. */
580 		data = (void *)&kda_copy;
581 	    }
582 	    /* FALLTHROUGH */
583 #endif
584 	case DIOCSKERNELDUMP:
585 	    {
586 		struct diocskerneldump_arg *kda;
587 		uint8_t *encryptedkey;
588 
589 		kda = (struct diocskerneldump_arg *)data;
590 		if (kda->kda_index == KDA_REMOVE_ALL ||
591 		    kda->kda_index == KDA_REMOVE_DEV ||
592 		    kda->kda_index == KDA_REMOVE) {
593 			error = dumper_remove(devtoname(dev), kda);
594 			explicit_bzero(kda, sizeof(*kda));
595 			break;
596 		}
597 
598 		if (kda->kda_encryption != KERNELDUMP_ENC_NONE) {
599 			if (kda->kda_encryptedkeysize == 0 ||
600 			    kda->kda_encryptedkeysize >
601 			    KERNELDUMP_ENCKEY_MAX_SIZE) {
602 				explicit_bzero(kda, sizeof(*kda));
603 				return (EINVAL);
604 			}
605 			encryptedkey = malloc(kda->kda_encryptedkeysize, M_TEMP,
606 			    M_WAITOK);
607 			error = copyin(kda->kda_encryptedkey, encryptedkey,
608 			    kda->kda_encryptedkeysize);
609 		} else {
610 			encryptedkey = NULL;
611 		}
612 		if (error == 0) {
613 			kda->kda_encryptedkey = encryptedkey;
614 			error = g_dev_setdumpdev(dev, kda);
615 		}
616 		if (encryptedkey != NULL) {
617 			explicit_bzero(encryptedkey, kda->kda_encryptedkeysize);
618 			free(encryptedkey, M_TEMP);
619 		}
620 		explicit_bzero(kda, sizeof(*kda));
621 		break;
622 	    }
623 	case DIOCGFLUSH:
624 		error = g_io_flush(cp);
625 		break;
626 	case DIOCGDELETE:
627 		offset = ((off_t *)data)[0];
628 		length = ((off_t *)data)[1];
629 		if ((offset % pp->sectorsize) != 0 ||
630 		    (length % pp->sectorsize) != 0 || length <= 0) {
631 			printf("%s: offset=%jd length=%jd\n", __func__, offset,
632 			    length);
633 			error = EINVAL;
634 			break;
635 		}
636 		if ((pp->mediasize > 0) && (offset >= pp->mediasize)) {
637 			/*
638 			 * Catch out-of-bounds requests here. The problem is
639 			 * that due to historical GEOM I/O implementation
640 			 * peculatities, g_delete_data() would always return
641 			 * success for requests starting just the next byte
642 			 * after providers media boundary. Condition check on
643 			 * non-zero media size, since that condition would
644 			 * (most likely) cause ENXIO instead.
645 			 */
646 			error = EIO;
647 			break;
648 		}
649 		while (length > 0) {
650 			chunk = length;
651 			if (g_dev_del_max_sectors != 0 &&
652 			    chunk > g_dev_del_max_sectors * pp->sectorsize) {
653 				chunk = g_dev_del_max_sectors * pp->sectorsize;
654 				if (pp->stripesize > 0) {
655 					odd = (offset + chunk +
656 					    pp->stripeoffset) % pp->stripesize;
657 					if (chunk > odd)
658 						chunk -= odd;
659 				}
660 			}
661 			error = g_delete_data(cp, offset, chunk);
662 			length -= chunk;
663 			offset += chunk;
664 			if (error)
665 				break;
666 			/*
667 			 * Since the request size can be large, the service
668 			 * time can be is likewise.  We make this ioctl
669 			 * interruptible by checking for signals for each bio.
670 			 */
671 			if (SIGPENDING(td))
672 				break;
673 		}
674 		break;
675 	case DIOCGIDENT:
676 		error = g_io_getattr("GEOM::ident", cp, &i, data);
677 		break;
678 	case DIOCGPROVIDERNAME:
679 		strlcpy(data, pp->name, i);
680 		break;
681 	case DIOCGSTRIPESIZE:
682 		*(off_t *)data = pp->stripesize;
683 		break;
684 	case DIOCGSTRIPEOFFSET:
685 		*(off_t *)data = pp->stripeoffset;
686 		break;
687 	case DIOCGPHYSPATH:
688 		error = g_io_getattr("GEOM::physpath", cp, &i, data);
689 		if (error == 0 && *(char *)data == '\0')
690 			error = ENOENT;
691 		break;
692 	case DIOCGATTR: {
693 		struct diocgattr_arg *arg = (struct diocgattr_arg *)data;
694 
695 		if (arg->len > sizeof(arg->value)) {
696 			error = EINVAL;
697 			break;
698 		}
699 		error = g_io_getattr(arg->name, cp, &arg->len, &arg->value);
700 		break;
701 	}
702 	case DIOCZONECMD: {
703 		struct disk_zone_args *zone_args =(struct disk_zone_args *)data;
704 		struct disk_zone_rep_entry *new_entries, *old_entries;
705 		struct disk_zone_report *rep;
706 		size_t alloc_size;
707 
708 		old_entries = NULL;
709 		new_entries = NULL;
710 		rep = NULL;
711 		alloc_size = 0;
712 
713 		if (zone_args->zone_cmd == DISK_ZONE_REPORT_ZONES) {
714 			rep = &zone_args->zone_params.report;
715 #define	MAXENTRIES	(MAXPHYS / sizeof(struct disk_zone_rep_entry))
716 			if (rep->entries_allocated > MAXENTRIES)
717 				rep->entries_allocated = MAXENTRIES;
718 			alloc_size = rep->entries_allocated *
719 			    sizeof(struct disk_zone_rep_entry);
720 			if (alloc_size != 0)
721 				new_entries = g_malloc(alloc_size,
722 				    M_WAITOK| M_ZERO);
723 			old_entries = rep->entries;
724 			rep->entries = new_entries;
725 		}
726 		error = g_io_zonecmd(zone_args, cp);
727 		if (zone_args->zone_cmd == DISK_ZONE_REPORT_ZONES &&
728 		    alloc_size != 0 && error == 0)
729 			error = copyout(new_entries, old_entries, alloc_size);
730 		if (old_entries != NULL && rep != NULL)
731 			rep->entries = old_entries;
732 		if (new_entries != NULL)
733 			g_free(new_entries);
734 		break;
735 	}
736 	default:
737 		if (pp->geom->ioctl != NULL) {
738 			error = pp->geom->ioctl(pp, cmd, data, fflag, td);
739 		} else {
740 			error = ENOIOCTL;
741 		}
742 	}
743 
744 	return (error);
745 }
746 
747 static void
748 g_dev_done(struct bio *bp2)
749 {
750 	struct g_consumer *cp;
751 	struct g_dev_softc *sc;
752 	struct bio *bp;
753 	int active;
754 
755 	cp = bp2->bio_from;
756 	sc = cp->private;
757 	bp = bp2->bio_parent;
758 	bp->bio_error = bp2->bio_error;
759 	bp->bio_completed = bp2->bio_completed;
760 	bp->bio_resid = bp->bio_length - bp2->bio_completed;
761 	if (bp2->bio_cmd == BIO_ZONE)
762 		bcopy(&bp2->bio_zone, &bp->bio_zone, sizeof(bp->bio_zone));
763 
764 	if (bp2->bio_error != 0) {
765 		g_trace(G_T_BIO, "g_dev_done(%p) had error %d",
766 		    bp2, bp2->bio_error);
767 		bp->bio_flags |= BIO_ERROR;
768 	} else {
769 		g_trace(G_T_BIO, "g_dev_done(%p/%p) resid %ld completed %jd",
770 		    bp2, bp, bp2->bio_resid, (intmax_t)bp2->bio_completed);
771 	}
772 	g_destroy_bio(bp2);
773 	active = atomic_fetchadd_int(&sc->sc_active, -1) - 1;
774 	if ((active & SC_A_ACTIVE) == 0) {
775 		if ((active & SC_A_OPEN) == 0)
776 			wakeup(&sc->sc_active);
777 		if (active & SC_A_DESTROY)
778 			g_post_event(g_dev_destroy, cp, M_NOWAIT, NULL);
779 	}
780 	biodone(bp);
781 }
782 
783 static void
784 g_dev_strategy(struct bio *bp)
785 {
786 	struct g_consumer *cp;
787 	struct bio *bp2;
788 	struct cdev *dev;
789 	struct g_dev_softc *sc;
790 
791 	KASSERT(bp->bio_cmd == BIO_READ ||
792 	        bp->bio_cmd == BIO_WRITE ||
793 	        bp->bio_cmd == BIO_DELETE ||
794 		bp->bio_cmd == BIO_FLUSH ||
795 		bp->bio_cmd == BIO_ZONE,
796 		("Wrong bio_cmd bio=%p cmd=%d", bp, bp->bio_cmd));
797 	dev = bp->bio_dev;
798 	cp = dev->si_drv2;
799 	KASSERT(cp->acr || cp->acw,
800 	    ("Consumer with zero access count in g_dev_strategy"));
801 	biotrack(bp, __func__);
802 #ifdef INVARIANTS
803 	if ((bp->bio_offset % cp->provider->sectorsize) != 0 ||
804 	    (bp->bio_bcount % cp->provider->sectorsize) != 0) {
805 		bp->bio_resid = bp->bio_bcount;
806 		biofinish(bp, NULL, EINVAL);
807 		return;
808 	}
809 #endif
810 	sc = dev->si_drv1;
811 	KASSERT(sc->sc_open > 0, ("Closed device in g_dev_strategy"));
812 	atomic_add_int(&sc->sc_active, 1);
813 
814 	for (;;) {
815 		/*
816 		 * XXX: This is not an ideal solution, but I believe it to
817 		 * XXX: deadlock safely, all things considered.
818 		 */
819 		bp2 = g_clone_bio(bp);
820 		if (bp2 != NULL)
821 			break;
822 		pause("gdstrat", hz / 10);
823 	}
824 	KASSERT(bp2 != NULL, ("XXX: ENOMEM in a bad place"));
825 	bp2->bio_done = g_dev_done;
826 	g_trace(G_T_BIO,
827 	    "g_dev_strategy(%p/%p) offset %jd length %jd data %p cmd %d",
828 	    bp, bp2, (intmax_t)bp->bio_offset, (intmax_t)bp2->bio_length,
829 	    bp2->bio_data, bp2->bio_cmd);
830 	g_io_request(bp2, cp);
831 	KASSERT(cp->acr || cp->acw,
832 	    ("g_dev_strategy raced with g_dev_close and lost"));
833 
834 }
835 
836 /*
837  * g_dev_callback()
838  *
839  * Called by devfs when asynchronous device destruction is completed.
840  * - Mark that we have no attached device any more.
841  * - If there are no outstanding requests, schedule geom destruction.
842  *   Otherwise destruction will be scheduled later by g_dev_done().
843  */
844 
845 static void
846 g_dev_callback(void *arg)
847 {
848 	struct g_consumer *cp;
849 	struct g_dev_softc *sc;
850 	int active;
851 
852 	cp = arg;
853 	sc = cp->private;
854 	g_trace(G_T_TOPOLOGY, "g_dev_callback(%p(%s))", cp, cp->geom->name);
855 
856 	sc->sc_dev = NULL;
857 	sc->sc_alias = NULL;
858 	active = atomic_fetchadd_int(&sc->sc_active, SC_A_DESTROY);
859 	if ((active & SC_A_ACTIVE) == 0)
860 		g_post_event(g_dev_destroy, cp, M_WAITOK, NULL);
861 }
862 
863 /*
864  * g_dev_orphan()
865  *
866  * Called from below when the provider orphaned us.
867  * - Clear any dump settings.
868  * - Request asynchronous device destruction to prevent any more requests
869  *   from coming in.  The provider is already marked with an error, so
870  *   anything which comes in the interim will be returned immediately.
871  */
872 
873 static void
874 g_dev_orphan(struct g_consumer *cp)
875 {
876 	struct cdev *dev;
877 	struct g_dev_softc *sc;
878 
879 	g_topology_assert();
880 	sc = cp->private;
881 	dev = sc->sc_dev;
882 	g_trace(G_T_TOPOLOGY, "g_dev_orphan(%p(%s))", cp, cp->geom->name);
883 
884 	/* Reset any dump-area set on this device */
885 	if (dev->si_flags & SI_DUMPDEV) {
886 		struct diocskerneldump_arg kda;
887 
888 		bzero(&kda, sizeof(kda));
889 		kda.kda_index = KDA_REMOVE_DEV;
890 		(void)dumper_remove(devtoname(dev), &kda);
891 	}
892 
893 	/* Destroy the struct cdev *so we get no more requests */
894 	delist_dev(dev);
895 	destroy_dev_sched_cb(dev, g_dev_callback, cp);
896 }
897 
898 DECLARE_GEOM_CLASS(g_dev_class, g_dev);
899