Home | History | Annotate | Line # | Download | only in dev
vnd.c revision 1.284
      1 /*	$NetBSD: vnd.c,v 1.284 2022/03/28 11:16:59 mlelstv Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1996, 1997, 1998, 2008, 2020 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 1988 University of Utah.
     34  * Copyright (c) 1990, 1993
     35  *	The Regents of the University of California.  All rights reserved.
     36  *
     37  * This code is derived from software contributed to Berkeley by
     38  * the Systems Programming Group of the University of Utah Computer
     39  * Science Department.
     40  *
     41  * Redistribution and use in source and binary forms, with or without
     42  * modification, are permitted provided that the following conditions
     43  * are met:
     44  * 1. Redistributions of source code must retain the above copyright
     45  *    notice, this list of conditions and the following disclaimer.
     46  * 2. Redistributions in binary form must reproduce the above copyright
     47  *    notice, this list of conditions and the following disclaimer in the
     48  *    documentation and/or other materials provided with the distribution.
     49  * 3. Neither the name of the University nor the names of its contributors
     50  *    may be used to endorse or promote products derived from this software
     51  *    without specific prior written permission.
     52  *
     53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     63  * SUCH DAMAGE.
     64  *
     65  * from: Utah $Hdr: vn.c 1.13 94/04/02$
     66  *
     67  *	@(#)vn.c	8.9 (Berkeley) 5/14/95
     68  */
     69 
     70 /*
     71  * Vnode disk driver.
     72  *
     73  * Block/character interface to a vnode.  Allows one to treat a file
     74  * as a disk (e.g. build a filesystem in it, mount it, etc.).
     75  *
     76  * NOTE 1: If the vnode supports the VOP_BMAP and VOP_STRATEGY operations,
     77  * this uses them to avoid distorting the local buffer cache.  If those
     78  * block-level operations are not available, this falls back to the regular
     79  * read and write calls.  Using these may distort the cache in some cases
     80  * but better have the driver working than preventing it to work on file
     81  * systems where the block-level operations are not implemented for
     82  * whatever reason.
     83  *
     84  * NOTE 2: There is a security issue involved with this driver.
     85  * Once mounted all access to the contents of the "mapped" file via
     86  * the special file is controlled by the permissions on the special
     87  * file, the protection of the mapped file is ignored (effectively,
     88  * by using root credentials in all transactions).
     89  *
     90  * NOTE 3: Doesn't interact with leases, should it?
     91  */
     92 
     93 #include <sys/cdefs.h>
     94 __KERNEL_RCSID(0, "$NetBSD: vnd.c,v 1.284 2022/03/28 11:16:59 mlelstv Exp $");
     95 
     96 #if defined(_KERNEL_OPT)
     97 #include "opt_vnd.h"
     98 #include "opt_compat_netbsd.h"
     99 #endif
    100 
    101 #include <sys/param.h>
    102 #include <sys/systm.h>
    103 #include <sys/namei.h>
    104 #include <sys/proc.h>
    105 #include <sys/kthread.h>
    106 #include <sys/errno.h>
    107 #include <sys/buf.h>
    108 #include <sys/bufq.h>
    109 #include <sys/malloc.h>
    110 #include <sys/ioctl.h>
    111 #include <sys/disklabel.h>
    112 #include <sys/device.h>
    113 #include <sys/disk.h>
    114 #include <sys/stat.h>
    115 #include <sys/mount.h>
    116 #include <sys/vnode.h>
    117 #include <sys/fstrans.h>
    118 #include <sys/file.h>
    119 #include <sys/uio.h>
    120 #include <sys/conf.h>
    121 #include <sys/kauth.h>
    122 #include <sys/module.h>
    123 #include <sys/compat_stub.h>
    124 #include <sys/atomic.h>
    125 
    126 #include <net/zlib.h>
    127 
    128 #include <miscfs/genfs/genfs.h>
    129 #include <miscfs/specfs/specdev.h>
    130 
    131 #include <dev/dkvar.h>
    132 #include <dev/vndvar.h>
    133 
    134 #include "ioconf.h"
    135 
    136 #if defined(VNDDEBUG) && !defined(DEBUG)
    137 #define DEBUG
    138 #endif
    139 
    140 #ifdef DEBUG
    141 int dovndcluster = 1;
    142 #define VDB_FOLLOW	0x01
    143 #define VDB_INIT	0x02
    144 #define VDB_IO		0x04
    145 #define VDB_LABEL	0x08
    146 int vnddebug = 0;
    147 #endif
    148 
    149 #define vndunit(x)	DISKUNIT(x)
    150 
    151 struct vndxfer {
    152 	struct buf vx_buf;
    153 	struct vnd_softc *vx_vnd;
    154 };
    155 #define	VND_BUFTOXFER(bp)	((struct vndxfer *)(void *)bp)
    156 
    157 #define VND_GETXFER(vnd)	pool_get(&(vnd)->sc_vxpool, PR_WAITOK)
    158 #define VND_PUTXFER(vnd, vx)	pool_put(&(vnd)->sc_vxpool, (vx))
    159 
    160 #define VNDLABELDEV(dev) \
    161     (MAKEDISKDEV(major((dev)), vndunit((dev)), RAW_PART))
    162 
    163 #define	VND_MAXPENDING(vnd)	((vnd)->sc_maxactive * 4)
    164 #define	VND_MAXPAGES(vnd)	(1024 * 1024 / PAGE_SIZE)
    165 
    166 
    167 static void	vndclear(struct vnd_softc *, int);
    168 static int	vnddoclear(struct vnd_softc *, int, int, bool);
    169 static int	vndsetcred(struct vnd_softc *, kauth_cred_t);
    170 static void	vndthrottle(struct vnd_softc *, struct vnode *);
    171 static void	vndiodone(struct buf *);
    172 #if 0
    173 static void	vndshutdown(void);
    174 #endif
    175 
    176 static void	vndgetdefaultlabel(struct vnd_softc *, struct disklabel *);
    177 static void	vndgetdisklabel(dev_t, struct vnd_softc *);
    178 
    179 static int	vndlock(struct vnd_softc *);
    180 static void	vndunlock(struct vnd_softc *);
    181 #ifdef VND_COMPRESSION
    182 static void	compstrategy(struct buf *, off_t);
    183 static void	*vnd_alloc(void *, u_int, u_int);
    184 static void	vnd_free(void *, void *);
    185 #endif /* VND_COMPRESSION */
    186 
    187 static void	vndthread(void *);
    188 static bool	vnode_has_op(const struct vnode *, int);
    189 static void	handle_with_rdwr(struct vnd_softc *, const struct buf *,
    190 		    struct buf *);
    191 static void	handle_with_strategy(struct vnd_softc *, const struct buf *,
    192 		    struct buf *);
    193 static void	vnd_set_geometry(struct vnd_softc *);
    194 
    195 static dev_type_open(vndopen);
    196 static dev_type_close(vndclose);
    197 static dev_type_read(vndread);
    198 static dev_type_write(vndwrite);
    199 static dev_type_ioctl(vndioctl);
    200 static dev_type_strategy(vndstrategy);
    201 static dev_type_dump(vnddump);
    202 static dev_type_size(vndsize);
    203 
    204 const struct bdevsw vnd_bdevsw = {
    205 	.d_open = vndopen,
    206 	.d_close = vndclose,
    207 	.d_strategy = vndstrategy,
    208 	.d_ioctl = vndioctl,
    209 	.d_dump = vnddump,
    210 	.d_psize = vndsize,
    211 	.d_discard = nodiscard,
    212 	.d_flag = D_DISK
    213 };
    214 
    215 const struct cdevsw vnd_cdevsw = {
    216 	.d_open = vndopen,
    217 	.d_close = vndclose,
    218 	.d_read = vndread,
    219 	.d_write = vndwrite,
    220 	.d_ioctl = vndioctl,
    221 	.d_stop = nostop,
    222 	.d_tty = notty,
    223 	.d_poll = nopoll,
    224 	.d_mmap = nommap,
    225 	.d_kqfilter = nokqfilter,
    226 	.d_discard = nodiscard,
    227 	.d_flag = D_DISK
    228 };
    229 
    230 static int	vnd_match(device_t, cfdata_t, void *);
    231 static void	vnd_attach(device_t, device_t, void *);
    232 static int	vnd_detach(device_t, int);
    233 
    234 CFATTACH_DECL3_NEW(vnd, sizeof(struct vnd_softc),
    235     vnd_match, vnd_attach, vnd_detach, NULL, NULL, NULL, DVF_DETACH_SHUTDOWN);
    236 
    237 static struct vnd_softc	*vnd_spawn(int);
    238 static int	vnd_destroy(device_t);
    239 
    240 static const struct	dkdriver vnddkdriver = {
    241 	.d_strategy = vndstrategy,
    242 	.d_minphys = minphys
    243 };
    244 
    245 void
    246 vndattach(int num)
    247 {
    248 	int error;
    249 
    250 	error = config_cfattach_attach(vnd_cd.cd_name, &vnd_ca);
    251 	if (error)
    252 		aprint_error("%s: unable to register cfattach, error = %d\n",
    253 		    vnd_cd.cd_name, error);
    254 }
    255 
    256 static int
    257 vnd_match(device_t self, cfdata_t cfdata, void *aux)
    258 {
    259 
    260 	return 1;
    261 }
    262 
    263 static void
    264 vnd_attach(device_t parent, device_t self, void *aux)
    265 {
    266 	struct vnd_softc *sc = device_private(self);
    267 
    268 	sc->sc_dev = self;
    269 	sc->sc_comp_offsets = NULL;
    270 	sc->sc_comp_buff = NULL;
    271 	sc->sc_comp_decombuf = NULL;
    272 	bufq_alloc(&sc->sc_tab, "disksort", BUFQ_SORT_RAWBLOCK);
    273 	disk_init(&sc->sc_dkdev, device_xname(self), &vnddkdriver);
    274 	if (!pmf_device_register(self, NULL, NULL))
    275 		aprint_error_dev(self, "couldn't establish power handler\n");
    276 }
    277 
    278 static int
    279 vnd_detach(device_t self, int flags)
    280 {
    281 	int error;
    282 	struct vnd_softc *sc = device_private(self);
    283 
    284 	if (sc->sc_flags & VNF_INITED) {
    285 		error = vnddoclear(sc, 0, -1, (flags & DETACH_FORCE) != 0);
    286 		if (error != 0)
    287 			return error;
    288 	}
    289 
    290 	pmf_device_deregister(self);
    291 	bufq_free(sc->sc_tab);
    292 	disk_destroy(&sc->sc_dkdev);
    293 
    294 	return 0;
    295 }
    296 
    297 static struct vnd_softc *
    298 vnd_spawn(int unit)
    299 {
    300 	cfdata_t cf;
    301 
    302 	cf = malloc(sizeof(*cf), M_DEVBUF, M_WAITOK);
    303 	cf->cf_name = vnd_cd.cd_name;
    304 	cf->cf_atname = vnd_cd.cd_name;
    305 	cf->cf_unit = unit;
    306 	cf->cf_fstate = FSTATE_STAR;
    307 
    308 	return device_private(config_attach_pseudo(cf));
    309 }
    310 
    311 static int
    312 vnd_destroy(device_t dev)
    313 {
    314 	int error;
    315 	cfdata_t cf;
    316 
    317 	cf = device_cfdata(dev);
    318 	error = config_detach(dev, DETACH_QUIET);
    319 	if (error)
    320 		return error;
    321 	free(cf, M_DEVBUF);
    322 	return 0;
    323 }
    324 
    325 static int
    326 vndopen(dev_t dev, int flags, int mode, struct lwp *l)
    327 {
    328 	int unit = vndunit(dev);
    329 	struct vnd_softc *sc;
    330 	int error = 0, part, pmask;
    331 	struct disklabel *lp;
    332 
    333 #ifdef DEBUG
    334 	if (vnddebug & VDB_FOLLOW)
    335 		printf("vndopen(0x%"PRIx64", 0x%x, 0x%x, %p)\n", dev, flags, mode, l);
    336 #endif
    337 	sc = device_lookup_private(&vnd_cd, unit);
    338 	if (sc == NULL) {
    339 		sc = vnd_spawn(unit);
    340 		if (sc == NULL)
    341 			return ENOMEM;
    342 
    343 		/* compatibility, keep disklabel after close */
    344 		sc->sc_flags = VNF_KLABEL;
    345 	}
    346 
    347 	if ((error = vndlock(sc)) != 0)
    348 		return error;
    349 
    350 	mutex_enter(&sc->sc_dkdev.dk_openlock);
    351 
    352 	if ((sc->sc_flags & VNF_CLEARING) != 0) {
    353 		error = ENXIO;
    354 		goto done;
    355 	}
    356 
    357 	lp = sc->sc_dkdev.dk_label;
    358 
    359 	part = DISKPART(dev);
    360 	pmask = (1 << part);
    361 
    362 	if (sc->sc_dkdev.dk_nwedges != 0 && part != RAW_PART) {
    363 		error = EBUSY;
    364 		goto done;
    365 	}
    366 
    367 	if ((flags & FWRITE) && (sc->sc_flags & VNF_READONLY)) {
    368 		error = EROFS;
    369 		goto done;
    370 	}
    371 
    372 	if (sc->sc_flags & VNF_INITED) {
    373 		if ((sc->sc_dkdev.dk_openmask & ~(1<<RAW_PART)) != 0) {
    374 			/*
    375 			 * If any non-raw partition is open, but the disk
    376 			 * has been invalidated, disallow further opens.
    377 			 */
    378 			if ((sc->sc_flags & VNF_VLABEL) == 0) {
    379 				error = EIO;
    380 				goto done;
    381 			}
    382 		} else {
    383 			/*
    384 			 * Load the partition info if not already loaded.
    385 			 */
    386 			if ((sc->sc_flags & VNF_VLABEL) == 0) {
    387 				sc->sc_flags |= VNF_VLABEL;
    388 				vndgetdisklabel(dev, sc);
    389 			}
    390 		}
    391 	}
    392 
    393 	/* Check that the partitions exists. */
    394 	if (part != RAW_PART) {
    395 		if (((sc->sc_flags & VNF_INITED) == 0) ||
    396 		    ((part >= lp->d_npartitions) ||
    397 		     (lp->d_partitions[part].p_fstype == FS_UNUSED))) {
    398 			error = ENXIO;
    399 			goto done;
    400 		}
    401 	}
    402 
    403 	/* Prevent our unit from being unconfigured while open. */
    404 	switch (mode) {
    405 	case S_IFCHR:
    406 		sc->sc_dkdev.dk_copenmask |= pmask;
    407 		break;
    408 
    409 	case S_IFBLK:
    410 		sc->sc_dkdev.dk_bopenmask |= pmask;
    411 		break;
    412 	}
    413 	sc->sc_dkdev.dk_openmask =
    414 	    sc->sc_dkdev.dk_copenmask | sc->sc_dkdev.dk_bopenmask;
    415 
    416  done:
    417 	mutex_exit(&sc->sc_dkdev.dk_openlock);
    418 	vndunlock(sc);
    419 	return error;
    420 }
    421 
    422 static int
    423 vndclose(dev_t dev, int flags, int mode, struct lwp *l)
    424 {
    425 	int unit = vndunit(dev);
    426 	struct vnd_softc *sc;
    427 	int error = 0, part;
    428 
    429 #ifdef DEBUG
    430 	if (vnddebug & VDB_FOLLOW)
    431 		printf("vndclose(0x%"PRIx64", 0x%x, 0x%x, %p)\n", dev, flags, mode, l);
    432 #endif
    433 	sc = device_lookup_private(&vnd_cd, unit);
    434 	if (sc == NULL)
    435 		return ENXIO;
    436 
    437 	if ((error = vndlock(sc)) != 0)
    438 		return error;
    439 
    440 	mutex_enter(&sc->sc_dkdev.dk_openlock);
    441 
    442 	part = DISKPART(dev);
    443 
    444 	/* ...that much closer to allowing unconfiguration... */
    445 	switch (mode) {
    446 	case S_IFCHR:
    447 		sc->sc_dkdev.dk_copenmask &= ~(1 << part);
    448 		break;
    449 
    450 	case S_IFBLK:
    451 		sc->sc_dkdev.dk_bopenmask &= ~(1 << part);
    452 		break;
    453 	}
    454 	sc->sc_dkdev.dk_openmask =
    455 	    sc->sc_dkdev.dk_copenmask | sc->sc_dkdev.dk_bopenmask;
    456 
    457 	/* are we last opener ? */
    458 	if (sc->sc_dkdev.dk_openmask == 0) {
    459 		if ((sc->sc_flags & VNF_KLABEL) == 0)
    460 			sc->sc_flags &= ~VNF_VLABEL;
    461 	}
    462 
    463 	mutex_exit(&sc->sc_dkdev.dk_openlock);
    464 
    465 	vndunlock(sc);
    466 
    467 	if ((sc->sc_flags & VNF_INITED) == 0) {
    468 		if ((error = vnd_destroy(sc->sc_dev)) != 0) {
    469 			aprint_error_dev(sc->sc_dev,
    470 			    "unable to detach instance\n");
    471 			return error;
    472 		}
    473 	}
    474 
    475 	return 0;
    476 }
    477 
    478 /*
    479  * Queue the request, and wakeup the kernel thread to handle it.
    480  */
    481 static void
    482 vndstrategy(struct buf *bp)
    483 {
    484 	int unit = vndunit(bp->b_dev);
    485 	struct vnd_softc *vnd =
    486 	    device_lookup_private(&vnd_cd, unit);
    487 	struct disklabel *lp;
    488 	daddr_t blkno;
    489 	int s = splbio();
    490 
    491 	if (vnd == NULL) {
    492 		bp->b_error = ENXIO;
    493 		goto done;
    494 	}
    495 	lp = vnd->sc_dkdev.dk_label;
    496 
    497 	if ((vnd->sc_flags & VNF_INITED) == 0) {
    498 		bp->b_error = ENXIO;
    499 		goto done;
    500 	}
    501 
    502 	/*
    503 	 * The transfer must be a whole number of blocks.
    504 	 */
    505 	if ((bp->b_bcount % lp->d_secsize) != 0) {
    506 		bp->b_error = EINVAL;
    507 		goto done;
    508 	}
    509 
    510 	/*
    511 	 * check if we're read-only.
    512 	 */
    513 	if ((vnd->sc_flags & VNF_READONLY) && !(bp->b_flags & B_READ)) {
    514 		bp->b_error = EACCES;
    515 		goto done;
    516 	}
    517 
    518 	/* If it's a nil transfer, wake up the top half now. */
    519 	if (bp->b_bcount == 0) {
    520 		goto done;
    521 	}
    522 
    523 	/*
    524 	 * Do bounds checking and adjust transfer.  If there's an error,
    525 	 * the bounds check will flag that for us.
    526 	 */
    527 	if (DISKPART(bp->b_dev) == RAW_PART) {
    528 		if (bounds_check_with_mediasize(bp, DEV_BSIZE,
    529 		    vnd->sc_size) <= 0)
    530 			goto done;
    531 	} else {
    532 		if (bounds_check_with_label(&vnd->sc_dkdev,
    533 		    bp, vnd->sc_flags & (VNF_WLABEL|VNF_LABELLING)) <= 0)
    534 			goto done;
    535 	}
    536 
    537 	/*
    538 	 * Put the block number in terms of the logical blocksize
    539 	 * of the "device".
    540 	 */
    541 
    542 	blkno = bp->b_blkno / (lp->d_secsize / DEV_BSIZE);
    543 
    544 	/*
    545 	 * Translate the partition-relative block number to an absolute.
    546 	 */
    547 	if (DISKPART(bp->b_dev) != RAW_PART) {
    548 		struct partition *pp;
    549 
    550 		pp = &vnd->sc_dkdev.dk_label->d_partitions[
    551 		    DISKPART(bp->b_dev)];
    552 		blkno += pp->p_offset;
    553 	}
    554 	bp->b_rawblkno = blkno;
    555 
    556 #ifdef DEBUG
    557 	if (vnddebug & VDB_FOLLOW)
    558 		printf("vndstrategy(%p): unit %d\n", bp, unit);
    559 #endif
    560 	if ((vnd->sc_flags & VNF_USE_VN_RDWR)) {
    561 		KASSERT(vnd->sc_pending >= 0 &&
    562 		    vnd->sc_pending <= VND_MAXPENDING(vnd));
    563 		while (vnd->sc_pending == VND_MAXPENDING(vnd))
    564 			tsleep(&vnd->sc_pending, PRIBIO, "vndpc", 0);
    565 		vnd->sc_pending++;
    566 	}
    567 	bufq_put(vnd->sc_tab, bp);
    568 	wakeup(&vnd->sc_tab);
    569 	splx(s);
    570 	return;
    571 
    572 done:
    573 	bp->b_resid = bp->b_bcount;
    574 	biodone(bp);
    575 	splx(s);
    576 }
    577 
    578 static bool
    579 vnode_has_strategy(struct vnd_softc *vnd)
    580 {
    581 	return vnode_has_op(vnd->sc_vp, VOFFSET(vop_bmap)) &&
    582 	    vnode_has_op(vnd->sc_vp, VOFFSET(vop_strategy));
    583 }
    584 
    585 /* Verify that I/O requests cannot be smaller than the
    586  * smallest I/O size supported by the backend.
    587  */
    588 static bool
    589 vnode_has_large_blocks(struct vnd_softc *vnd)
    590 {
    591 	u_int32_t vnd_secsize, iosize;
    592 
    593 	iosize = vnd->sc_iosize;
    594 	vnd_secsize = vnd->sc_geom.vng_secsize;
    595 
    596 	return vnd_secsize % iosize != 0;
    597 }
    598 
    599 /* XXX this function needs a reliable check to detect
    600  * sparse files. Otherwise, bmap/strategy may be used
    601  * and fail on non-allocated blocks. VOP_READ/VOP_WRITE
    602  * works on sparse files.
    603  */
    604 #if notyet
    605 static bool
    606 vnode_strategy_probe(struct vnd_softc *vnd)
    607 {
    608 	int error;
    609 	daddr_t nbn;
    610 
    611 	if (!vnode_has_strategy(vnd))
    612 		return false;
    613 
    614 	if (vnode_has_large_blocks(vnd))
    615 		return false;
    616 
    617 	/* Convert the first logical block number to its
    618 	 * physical block number.
    619 	 */
    620 	error = 0;
    621 	vn_lock(vnd->sc_vp, LK_EXCLUSIVE | LK_RETRY);
    622 	error = VOP_BMAP(vnd->sc_vp, 0, NULL, &nbn, NULL);
    623 	VOP_UNLOCK(vnd->sc_vp);
    624 
    625 	/* Test if that worked. */
    626 	if (error == 0 && (long)nbn == -1)
    627 		return false;
    628 
    629 	return true;
    630 }
    631 #endif
    632 
    633 static void
    634 vndthread(void *arg)
    635 {
    636 	struct vnd_softc *vnd = arg;
    637 	int s;
    638 
    639 	/* Determine whether we can *use* VOP_BMAP and VOP_STRATEGY to
    640 	 * directly access the backing vnode.  If we can, use these two
    641 	 * operations to avoid messing with the local buffer cache.
    642 	 * Otherwise fall back to regular VOP_READ/VOP_WRITE operations
    643 	 * which are guaranteed to work with any file system. */
    644 	if ((vnd->sc_flags & VNF_USE_VN_RDWR) == 0 &&
    645 	    ! vnode_has_strategy(vnd))
    646 		vnd->sc_flags |= VNF_USE_VN_RDWR;
    647 
    648 	/* VOP_STRATEGY can only be used if the backing vnode allows
    649 	 * to access blocks as small as defined by the vnd geometry.
    650 	 */
    651 	if ((vnd->sc_flags & VNF_USE_VN_RDWR) == 0 &&
    652 	    vnode_has_large_blocks(vnd))
    653 		vnd->sc_flags |= VNF_USE_VN_RDWR;
    654 
    655 #ifdef DEBUG
    656 	if (vnddebug & VDB_INIT)
    657 		printf("vndthread: vp %p, %s\n", vnd->sc_vp,
    658 		    (vnd->sc_flags & VNF_USE_VN_RDWR) == 0 ?
    659 		    "using bmap/strategy operations" :
    660 		    "using read/write operations");
    661 #endif
    662 
    663 	s = splbio();
    664 	vnd->sc_flags |= VNF_KTHREAD;
    665 	wakeup(&vnd->sc_kthread);
    666 
    667 	/*
    668 	 * Dequeue requests and serve them depending on the available
    669 	 * vnode operations.
    670 	 */
    671 	while ((vnd->sc_flags & VNF_VUNCONF) == 0) {
    672 		struct vndxfer *vnx;
    673 		struct buf *obp;
    674 		struct buf *bp;
    675 
    676 		obp = bufq_get(vnd->sc_tab);
    677 		if (obp == NULL) {
    678 			tsleep(&vnd->sc_tab, PRIBIO, "vndbp", 0);
    679 			continue;
    680 		};
    681 		if ((vnd->sc_flags & VNF_USE_VN_RDWR)) {
    682 			KASSERT(vnd->sc_pending > 0 &&
    683 			    vnd->sc_pending <= VND_MAXPENDING(vnd));
    684 			if (vnd->sc_pending-- == VND_MAXPENDING(vnd))
    685 				wakeup(&vnd->sc_pending);
    686 		}
    687 		splx(s);
    688 #ifdef DEBUG
    689 		if (vnddebug & VDB_FOLLOW)
    690 			printf("vndthread(%p)\n", obp);
    691 #endif
    692 
    693 		if (vnd->sc_vp->v_mount == NULL) {
    694 			obp->b_error = ENXIO;
    695 			goto done;
    696 		}
    697 #ifdef VND_COMPRESSION
    698 		/* handle a compressed read */
    699 		if ((obp->b_flags & B_READ) != 0 && (vnd->sc_flags & VNF_COMP)) {
    700 			off_t bn;
    701 
    702 			/* Convert to a byte offset within the file. */
    703 			bn = obp->b_rawblkno *
    704 			    vnd->sc_dkdev.dk_label->d_secsize;
    705 
    706 			compstrategy(obp, bn);
    707 			goto done;
    708 		}
    709 #endif /* VND_COMPRESSION */
    710 
    711 		/*
    712 		 * Allocate a header for this transfer and link it to the
    713 		 * buffer
    714 		 */
    715 		s = splbio();
    716 		vnx = VND_GETXFER(vnd);
    717 		splx(s);
    718 		vnx->vx_vnd = vnd;
    719 
    720 		s = splbio();
    721 		while (vnd->sc_active >= vnd->sc_maxactive) {
    722 			tsleep(&vnd->sc_tab, PRIBIO, "vndac", 0);
    723 		}
    724 		vnd->sc_active++;
    725 		splx(s);
    726 
    727 		/* Instrumentation. */
    728 		disk_busy(&vnd->sc_dkdev);
    729 
    730 		bp = &vnx->vx_buf;
    731 		buf_init(bp);
    732 		bp->b_flags = (obp->b_flags & (B_READ | B_PHYS | B_RAW));
    733 		bp->b_oflags = obp->b_oflags;
    734 		bp->b_cflags = obp->b_cflags;
    735 		bp->b_iodone = vndiodone;
    736 		bp->b_private = obp;
    737 		bp->b_vp = vnd->sc_vp;
    738 		bp->b_objlock = bp->b_vp->v_interlock;
    739 		bp->b_data = obp->b_data;
    740 		bp->b_bcount = obp->b_bcount;
    741 		BIO_COPYPRIO(bp, obp);
    742 
    743 		/* Make sure the request succeeds while suspending this fs. */
    744 		fstrans_start_lazy(vnd->sc_vp->v_mount);
    745 
    746 		/* Handle the request using the appropriate operations. */
    747 		if ((vnd->sc_flags & VNF_USE_VN_RDWR) == 0)
    748 			handle_with_strategy(vnd, obp, bp);
    749 		else
    750 			handle_with_rdwr(vnd, obp, bp);
    751 
    752 		fstrans_done(vnd->sc_vp->v_mount);
    753 
    754 		s = splbio();
    755 		continue;
    756 
    757 done:
    758 		biodone(obp);
    759 		s = splbio();
    760 	}
    761 
    762 	vnd->sc_flags &= (~VNF_KTHREAD | VNF_VUNCONF);
    763 	wakeup(&vnd->sc_kthread);
    764 	splx(s);
    765 	kthread_exit(0);
    766 }
    767 
    768 /*
    769  * Checks if the given vnode supports the requested operation.
    770  * The operation is specified the offset returned by VOFFSET.
    771  *
    772  * XXX The test below used to determine this is quite fragile
    773  * because it relies on the file system to use genfs to specify
    774  * unimplemented operations.  There might be another way to do
    775  * it more cleanly.
    776  */
    777 static bool
    778 vnode_has_op(const struct vnode *vp, int opoffset)
    779 {
    780 	int (*defaultp)(void *);
    781 	int (*opp)(void *);
    782 
    783 	defaultp = vp->v_op[VOFFSET(vop_default)];
    784 	opp = vp->v_op[opoffset];
    785 
    786 	return opp != defaultp && opp != genfs_eopnotsupp &&
    787 	    opp != genfs_badop && opp != genfs_nullop;
    788 }
    789 
    790 /*
    791  * Handles the read/write request given in 'bp' using the vnode's VOP_READ
    792  * and VOP_WRITE operations.
    793  *
    794  * 'obp' is a pointer to the original request fed to the vnd device.
    795  */
    796 static void
    797 handle_with_rdwr(struct vnd_softc *vnd, const struct buf *obp, struct buf *bp)
    798 {
    799 	bool doread;
    800 	off_t offset;
    801 	size_t len, resid;
    802 	struct vnode *vp;
    803 	int npages;
    804 
    805 	doread = bp->b_flags & B_READ;
    806 	offset = obp->b_rawblkno * vnd->sc_dkdev.dk_label->d_secsize;
    807 	len = bp->b_bcount;
    808 	vp = vnd->sc_vp;
    809 
    810 #if defined(DEBUG)
    811 	if (vnddebug & VDB_IO)
    812 		printf("vnd (rdwr): vp %p, %s, rawblkno 0x%" PRIx64
    813 		    ", secsize %d, offset %" PRIu64
    814 		    ", bcount %d\n",
    815 		    vp, doread ? "read" : "write", obp->b_rawblkno,
    816 		    vnd->sc_dkdev.dk_label->d_secsize, offset,
    817 		    bp->b_bcount);
    818 #endif
    819 
    820 	/* Issue the read or write operation. */
    821 	bp->b_error =
    822 	    vn_rdwr(doread ? UIO_READ : UIO_WRITE,
    823 	    vp, bp->b_data, len, offset, UIO_SYSSPACE,
    824 	    IO_ADV_ENCODE(POSIX_FADV_NOREUSE) | IO_DIRECT,
    825 		vnd->sc_cred, &resid, NULL);
    826 	bp->b_resid = resid;
    827 
    828 	/*
    829 	 * Avoid caching too many pages, the vnd user
    830 	 * is usually a filesystem and caches itself.
    831 	 * We need some amount of caching to not hinder
    832 	 * read-ahead and write-behind operations.
    833 	 */
    834 	npages = atomic_load_relaxed(&vp->v_uobj.uo_npages);
    835 	if (npages > VND_MAXPAGES(vnd)) {
    836 		rw_enter(vp->v_uobj.vmobjlock, RW_WRITER);
    837 		(void) VOP_PUTPAGES(vp, 0, 0,
    838 		    PGO_ALLPAGES | PGO_CLEANIT | PGO_FREE);
    839 	}
    840 
    841 	/* We need to increase the number of outputs on the vnode if
    842 	 * there was any write to it. */
    843 	if (!doread) {
    844 		mutex_enter(vp->v_interlock);
    845 		vp->v_numoutput++;
    846 		mutex_exit(vp->v_interlock);
    847 	}
    848 
    849 	biodone(bp);
    850 }
    851 
    852 /*
    853  * Handes the read/write request given in 'bp' using the vnode's VOP_BMAP
    854  * and VOP_STRATEGY operations.
    855  *
    856  * 'obp' is a pointer to the original request fed to the vnd device.
    857  */
    858 static void
    859 handle_with_strategy(struct vnd_softc *vnd, const struct buf *obp,
    860     struct buf *bp)
    861 {
    862 	int bsize, error, flags, skipped;
    863 	size_t resid, sz;
    864 	off_t bn, offset;
    865 	struct vnode *vp;
    866 	struct buf *nbp = NULL;
    867 
    868 	flags = obp->b_flags;
    869 
    870 
    871 	/* convert to a byte offset within the file. */
    872 	bn = obp->b_rawblkno * vnd->sc_dkdev.dk_label->d_secsize;
    873 
    874 	bsize = vnd->sc_vp->v_mount->mnt_stat.f_iosize;
    875 	skipped = 0;
    876 
    877 	/*
    878 	 * Break the request into bsize pieces and feed them
    879 	 * sequentially using VOP_BMAP/VOP_STRATEGY.
    880 	 * We do it this way to keep from flooding NFS servers if we
    881 	 * are connected to an NFS file.  This places the burden on
    882 	 * the client rather than the server.
    883 	 */
    884 	error = 0;
    885 	bp->b_resid = bp->b_bcount;
    886 	for (offset = 0, resid = bp->b_resid; /* true */;
    887 	    resid -= sz, offset += sz) {
    888 		daddr_t nbn;
    889 		int off, nra;
    890 
    891 		nra = 0;
    892 		vn_lock(vnd->sc_vp, LK_EXCLUSIVE | LK_RETRY);
    893 		error = VOP_BMAP(vnd->sc_vp, bn / bsize, &vp, &nbn, &nra);
    894 		VOP_UNLOCK(vnd->sc_vp);
    895 
    896 		if (error == 0 && (long)nbn == -1)
    897 			error = EIO;
    898 
    899 		/*
    900 		 * If there was an error or a hole in the file...punt.
    901 		 * Note that we may have to wait for any operations
    902 		 * that we have already fired off before releasing
    903 		 * the buffer.
    904 		 *
    905 		 * XXX we could deal with holes here but it would be
    906 		 * a hassle (in the write case).
    907 		 */
    908 		if (error) {
    909 			skipped += resid;
    910 			break;
    911 		}
    912 
    913 #ifdef DEBUG
    914 		if (!dovndcluster)
    915 			nra = 0;
    916 #endif
    917 
    918 		off = bn % bsize;
    919 		sz = MIN(((off_t)1 + nra) * bsize - off, resid);
    920 #ifdef	DEBUG
    921 		if (vnddebug & VDB_IO)
    922 			printf("vndstrategy: vp %p/%p bn 0x%qx/0x%" PRIx64
    923 			    " sz 0x%zx\n", vnd->sc_vp, vp, (long long)bn,
    924 			    nbn, sz);
    925 #endif
    926 
    927 		nbp = getiobuf(vp, true);
    928 		nestiobuf_setup(bp, nbp, offset, sz);
    929 		nbp->b_blkno = nbn + btodb(off);
    930 
    931 #if 0 /* XXX #ifdef DEBUG */
    932 		if (vnddebug & VDB_IO)
    933 			printf("vndstart(%ld): bp %p vp %p blkno "
    934 			    "0x%" PRIx64 " flags %x addr %p cnt 0x%x\n",
    935 			    (long) (vnd-vnd_softc), &nbp->vb_buf,
    936 			    nbp->vb_buf.b_vp, nbp->vb_buf.b_blkno,
    937 			    nbp->vb_buf.b_flags, nbp->vb_buf.b_data,
    938 			    nbp->vb_buf.b_bcount);
    939 #endif
    940 		if (resid == sz) {
    941 			break;
    942 		}
    943 		VOP_STRATEGY(vp, nbp);
    944 		bn += sz;
    945 	}
    946 	if (!(flags & B_READ)) {
    947 		struct vnode *w_vp;
    948 		/*
    949 		 * this is the last nested buf, account for
    950 		 * the parent buf write too.
    951 		 * This has to be done last, so that
    952 		 * fsync won't wait for this write which
    953 		 * has no chance to complete before all nested bufs
    954 		 * have been queued. But it has to be done
    955 		 * before the last VOP_STRATEGY()
    956 		 * or the call to nestiobuf_done().
    957 		 */
    958 		w_vp = bp->b_vp;
    959 		mutex_enter(w_vp->v_interlock);
    960 		w_vp->v_numoutput++;
    961 		mutex_exit(w_vp->v_interlock);
    962 	}
    963 	KASSERT(skipped != 0 || nbp != NULL);
    964 	if (skipped)
    965 		nestiobuf_done(bp, skipped, error);
    966 	else
    967 		VOP_STRATEGY(vp, nbp);
    968 }
    969 
    970 static void
    971 vndiodone(struct buf *bp)
    972 {
    973 	struct vndxfer *vnx = VND_BUFTOXFER(bp);
    974 	struct vnd_softc *vnd = vnx->vx_vnd;
    975 	struct buf *obp = bp->b_private;
    976 	int s = splbio();
    977 
    978 	KERNEL_LOCK(1, NULL);		/* XXXSMP */
    979 	KASSERT(&vnx->vx_buf == bp);
    980 	KASSERT(vnd->sc_active > 0);
    981 #ifdef DEBUG
    982 	if (vnddebug & VDB_IO) {
    983 		printf("vndiodone1: bp %p iodone: error %d\n",
    984 		    bp, bp->b_error);
    985 	}
    986 #endif
    987 	disk_unbusy(&vnd->sc_dkdev, bp->b_bcount - bp->b_resid,
    988 	    (bp->b_flags & B_READ));
    989 	vnd->sc_active--;
    990 	if (vnd->sc_active == 0) {
    991 		wakeup(&vnd->sc_tab);
    992 	}
    993 	KERNEL_UNLOCK_ONE(NULL);	/* XXXSMP */
    994 	splx(s);
    995 	obp->b_error = bp->b_error;
    996 	obp->b_resid = bp->b_resid;
    997 	buf_destroy(bp);
    998 	VND_PUTXFER(vnd, vnx);
    999 	biodone(obp);
   1000 }
   1001 
   1002 /* ARGSUSED */
   1003 static int
   1004 vndread(dev_t dev, struct uio *uio, int flags)
   1005 {
   1006 	int unit = vndunit(dev);
   1007 	struct vnd_softc *sc;
   1008 
   1009 #ifdef DEBUG
   1010 	if (vnddebug & VDB_FOLLOW)
   1011 		printf("vndread(0x%"PRIx64", %p)\n", dev, uio);
   1012 #endif
   1013 
   1014 	sc = device_lookup_private(&vnd_cd, unit);
   1015 	if (sc == NULL)
   1016 		return ENXIO;
   1017 
   1018 	if ((sc->sc_flags & VNF_INITED) == 0)
   1019 		return ENXIO;
   1020 
   1021 	return physio(vndstrategy, NULL, dev, B_READ, minphys, uio);
   1022 }
   1023 
   1024 /* ARGSUSED */
   1025 static int
   1026 vndwrite(dev_t dev, struct uio *uio, int flags)
   1027 {
   1028 	int unit = vndunit(dev);
   1029 	struct vnd_softc *sc;
   1030 
   1031 #ifdef DEBUG
   1032 	if (vnddebug & VDB_FOLLOW)
   1033 		printf("vndwrite(0x%"PRIx64", %p)\n", dev, uio);
   1034 #endif
   1035 
   1036 	sc = device_lookup_private(&vnd_cd, unit);
   1037 	if (sc == NULL)
   1038 		return ENXIO;
   1039 
   1040 	if ((sc->sc_flags & VNF_INITED) == 0)
   1041 		return ENXIO;
   1042 
   1043 	return physio(vndstrategy, NULL, dev, B_WRITE, minphys, uio);
   1044 }
   1045 
   1046 static int
   1047 vnd_cget(struct lwp *l, int unit, int *un, struct vattr *va)
   1048 {
   1049 	int error;
   1050 	struct vnd_softc *vnd;
   1051 
   1052 	if (*un == -1)
   1053 		*un = unit;
   1054 	if (*un < 0)
   1055 		return EINVAL;
   1056 
   1057 	vnd = device_lookup_private(&vnd_cd, *un);
   1058 	if (vnd == NULL)
   1059 		return -1;
   1060 
   1061 	if ((vnd->sc_flags & VNF_INITED) == 0)
   1062 		return -1;
   1063 
   1064 	vn_lock(vnd->sc_vp, LK_SHARED | LK_RETRY);
   1065 	error = VOP_GETATTR(vnd->sc_vp, va, l->l_cred);
   1066 	VOP_UNLOCK(vnd->sc_vp);
   1067 	return error;
   1068 }
   1069 
   1070 static int
   1071 vnddoclear(struct vnd_softc *vnd, int pmask, int minor, bool force)
   1072 {
   1073 	int error;
   1074 
   1075 	if ((error = vndlock(vnd)) != 0)
   1076 		return error;
   1077 
   1078 	/*
   1079 	 * Don't unconfigure if any other partitions are open
   1080 	 * or if both the character and block flavors of this
   1081 	 * partition are open.
   1082 	 */
   1083 	if (DK_BUSY(vnd, pmask) && !force) {
   1084 		vndunlock(vnd);
   1085 		return EBUSY;
   1086 	}
   1087 
   1088 	/* Delete all of our wedges */
   1089 	dkwedge_delall(&vnd->sc_dkdev);
   1090 
   1091 	/*
   1092 	 * XXX vndclear() might call vndclose() implicitly;
   1093 	 * release lock to avoid recursion
   1094 	 *
   1095 	 * Set VNF_CLEARING to prevent vndopen() from
   1096 	 * sneaking in after we vndunlock().
   1097 	 */
   1098 	vnd->sc_flags |= VNF_CLEARING;
   1099 	vndunlock(vnd);
   1100 	vndclear(vnd, minor);
   1101 #ifdef DEBUG
   1102 	if (vnddebug & VDB_INIT)
   1103 		printf("%s: CLRed\n", __func__);
   1104 #endif
   1105 
   1106 	/* Destroy the xfer and buffer pools. */
   1107 	pool_destroy(&vnd->sc_vxpool);
   1108 
   1109 	/* Detach the disk. */
   1110 	disk_detach(&vnd->sc_dkdev);
   1111 
   1112 	return 0;
   1113 }
   1114 
   1115 static int
   1116 vndioctl_get(struct lwp *l, void *data, int unit, struct vattr *va)
   1117 {
   1118 	int error;
   1119 
   1120 	KASSERT(l);
   1121 
   1122 	/* the first member is always int vnd_unit in all the versions */
   1123 	if (*(int *)data >= vnd_cd.cd_ndevs)
   1124 		return ENXIO;
   1125 
   1126 	switch (error = vnd_cget(l, unit, (int *)data, va)) {
   1127 	case -1:
   1128 		/* unused is not an error */
   1129 		memset(va, 0, sizeof(*va));
   1130 		/*FALLTHROUGH*/
   1131 	case 0:
   1132 		return 0;
   1133 	default:
   1134 		return error;
   1135 	}
   1136 }
   1137 
   1138 /* ARGSUSED */
   1139 static int
   1140 vndioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
   1141 {
   1142 	bool force;
   1143 	int unit = vndunit(dev);
   1144 	struct vnd_softc *vnd;
   1145 	struct vnd_ioctl *vio;
   1146 	struct vattr vattr;
   1147 	struct pathbuf *pb;
   1148 	struct vnode *vp;
   1149 	int error, part, pmask;
   1150 	uint64_t geomsize;
   1151 	int fflags;
   1152 #ifdef __HAVE_OLD_DISKLABEL
   1153 	struct disklabel newlabel;
   1154 #endif
   1155 
   1156 #ifdef DEBUG
   1157 	if (vnddebug & VDB_FOLLOW)
   1158 		printf("vndioctl(0x%"PRIx64", 0x%lx, %p, 0x%x, %p): unit %d\n",
   1159 		    dev, cmd, data, flag, l->l_proc, unit);
   1160 #endif
   1161 	/* Do the get's first; they don't need initialization or verification */
   1162 	switch (cmd) {
   1163 	case VNDIOCGET:
   1164 		if ((error = vndioctl_get(l, data, unit, &vattr)) != 0)
   1165 			return error;
   1166 
   1167 		struct vnd_user *vnu = data;
   1168 		vnu->vnu_dev = vattr.va_fsid;
   1169 		vnu->vnu_ino = vattr.va_fileid;
   1170 		return 0;
   1171 
   1172 	default:
   1173 		/* First check for COMPAT_50 hook */
   1174 		MODULE_HOOK_CALL(compat_vndioctl_50_hook,
   1175 		    (cmd, l, data, unit, &vattr, vndioctl_get),
   1176 		    enosys(), error);
   1177 
   1178 		/*
   1179 		 * If not present, then COMPAT_30 hook also not
   1180 		 * present, so just continue with checks for the
   1181 		 * "write" commands
   1182 		 */
   1183 		if (error == ENOSYS) {
   1184 			error = 0;
   1185 			break;
   1186 		}
   1187 
   1188 		/* If not already handled, try the COMPAT_30 hook */
   1189 		if (error == EPASSTHROUGH)
   1190 			MODULE_HOOK_CALL(compat_vndioctl_30_hook,
   1191 			    (cmd, l, data, unit, &vattr, vndioctl_get),
   1192 			    enosys(), error);
   1193 
   1194 		/* If no COMPAT_30 module, or not handled, check writes */
   1195 		if (error == ENOSYS || error == EPASSTHROUGH) {
   1196 			error = 0;
   1197 			break;
   1198 		}
   1199 		return error;
   1200 	}
   1201 
   1202 	vnd = device_lookup_private(&vnd_cd, unit);
   1203 	if (vnd == NULL)
   1204 		return ENXIO;
   1205 	vio = (struct vnd_ioctl *)data;
   1206 
   1207 	/* Must be open for writes for these commands... */
   1208 	switch (cmd) {
   1209 	case VNDIOCSET50:
   1210 	case VNDIOCCLR50:
   1211 		if (!compat_vndioctl_50_hook.hooked)
   1212 			return EINVAL;
   1213 		/* FALLTHROUGH */
   1214 	case VNDIOCSET:
   1215 	case VNDIOCCLR:
   1216 	case DIOCSDINFO:
   1217 	case DIOCWDINFO:
   1218 #ifdef __HAVE_OLD_DISKLABEL
   1219 	case ODIOCSDINFO:
   1220 	case ODIOCWDINFO:
   1221 #endif
   1222 	case DIOCKLABEL:
   1223 	case DIOCWLABEL:
   1224 	case DIOCCACHESYNC:
   1225 		if ((flag & FWRITE) == 0)
   1226 			return EBADF;
   1227 	}
   1228 
   1229 	switch (cmd) {
   1230 	case VNDIOCSET50:
   1231 	case VNDIOCSET:
   1232 		/* Must not be initialized */
   1233 		if (vnd->sc_flags & VNF_INITED)
   1234 			return EBUSY;
   1235 		break;
   1236 	default:
   1237 		/* Must be initialized */
   1238 		if ((vnd->sc_flags & VNF_INITED) == 0)
   1239 			return ENXIO;
   1240 		break;
   1241 	}
   1242 
   1243 	error = disk_ioctl(&vnd->sc_dkdev, dev, cmd, data, flag, l);
   1244 	if (error != EPASSTHROUGH)
   1245 		return error;
   1246 
   1247 	switch (cmd) {
   1248 	case VNDIOCSET50:
   1249 	case VNDIOCSET:
   1250 		if ((error = vndlock(vnd)) != 0)
   1251 			return error;
   1252 
   1253 		fflags = FREAD;
   1254 		if ((vio->vnd_flags & VNDIOF_READONLY) == 0)
   1255 			fflags |= FWRITE;
   1256 		if ((vio->vnd_flags & VNDIOF_FILEIO) != 0)
   1257 			vnd->sc_flags |= VNF_USE_VN_RDWR;
   1258 		error = pathbuf_copyin(vio->vnd_file, &pb);
   1259 		if (error) {
   1260 			goto unlock_and_exit;
   1261 		}
   1262 		error = vn_open(NULL, pb, 0, fflags, 0, &vp, NULL, NULL);
   1263 		if (error != 0) {
   1264 			pathbuf_destroy(pb);
   1265 			goto unlock_and_exit;
   1266 		}
   1267 		KASSERT(l);
   1268 		error = VOP_GETATTR(vp, &vattr, l->l_cred);
   1269 		if (!error && vp->v_type != VREG)
   1270 			error = EOPNOTSUPP;
   1271 		if (!error && vattr.va_bytes < vattr.va_size)
   1272 			/* File is definitely sparse, use vn_rdwr() */
   1273 			vnd->sc_flags |= VNF_USE_VN_RDWR;
   1274 		if (error) {
   1275 			VOP_UNLOCK(vp);
   1276 			goto close_and_exit;
   1277 		}
   1278 
   1279 		/* If using a compressed file, initialize its info */
   1280 		/* (or abort with an error if kernel has no compression) */
   1281 		if (vio->vnd_flags & VNDIOF_COMP) {
   1282 #ifdef VND_COMPRESSION
   1283 			struct vnd_comp_header *ch;
   1284 			int i;
   1285 			uint32_t comp_size;
   1286 			uint32_t comp_maxsize;
   1287 
   1288 			/* allocate space for compressed file header */
   1289 			ch = malloc(sizeof(struct vnd_comp_header),
   1290 			    M_TEMP, M_WAITOK);
   1291 
   1292 			/* read compressed file header */
   1293 			error = vn_rdwr(UIO_READ, vp, (void *)ch,
   1294 			    sizeof(struct vnd_comp_header), 0, UIO_SYSSPACE,
   1295 			    IO_UNIT|IO_NODELOCKED, l->l_cred, NULL, NULL);
   1296 			if (error) {
   1297 				free(ch, M_TEMP);
   1298 				VOP_UNLOCK(vp);
   1299 				goto close_and_exit;
   1300 			}
   1301 
   1302 			if (be32toh(ch->block_size) == 0 ||
   1303 			    be32toh(ch->num_blocks) > UINT32_MAX - 1) {
   1304 				free(ch, M_TEMP);
   1305 				VOP_UNLOCK(vp);
   1306 				goto close_and_exit;
   1307 			}
   1308 
   1309 			/* save some header info */
   1310 			vnd->sc_comp_blksz = be32toh(ch->block_size);
   1311 			/* note last offset is the file byte size */
   1312 			vnd->sc_comp_numoffs = be32toh(ch->num_blocks) + 1;
   1313 			free(ch, M_TEMP);
   1314 			if (!DK_DEV_BSIZE_OK(vnd->sc_comp_blksz)) {
   1315 				VOP_UNLOCK(vp);
   1316 				error = EINVAL;
   1317 				goto close_and_exit;
   1318 			}
   1319 			KASSERT(0 < vnd->sc_comp_blksz);
   1320 			KASSERT(0 < vnd->sc_comp_numoffs);
   1321 			/*
   1322 			 * @#^@!$& gcc -Wtype-limits refuses to let me
   1323 			 * write SIZE_MAX/sizeof(uint64_t) < numoffs,
   1324 			 * because the range of the type on amd64 makes
   1325 			 * the comparisons always false.
   1326 			 */
   1327 #if SIZE_MAX <= UINT32_MAX*(64/CHAR_BIT)
   1328 			if (SIZE_MAX/sizeof(uint64_t) < vnd->sc_comp_numoffs) {
   1329 				VOP_UNLOCK(vp);
   1330 				error = EINVAL;
   1331 				goto close_and_exit;
   1332 			}
   1333 #endif
   1334 			if ((vattr.va_size < sizeof(struct vnd_comp_header)) ||
   1335 			    (vattr.va_size - sizeof(struct vnd_comp_header) <
   1336 				sizeof(uint64_t)*vnd->sc_comp_numoffs) ||
   1337 			    (UQUAD_MAX/vnd->sc_comp_blksz <
   1338 				vnd->sc_comp_numoffs - 1)) {
   1339 				VOP_UNLOCK(vp);
   1340 				error = EINVAL;
   1341 				goto close_and_exit;
   1342 			}
   1343 
   1344 			/* set decompressed file size */
   1345 			KASSERT(vnd->sc_comp_numoffs - 1 <=
   1346 			    UQUAD_MAX/vnd->sc_comp_blksz);
   1347 			vattr.va_size =
   1348 			    ((u_quad_t)vnd->sc_comp_numoffs - 1) *
   1349 			     (u_quad_t)vnd->sc_comp_blksz;
   1350 
   1351 			/* allocate space for all the compressed offsets */
   1352 			__CTASSERT(UINT32_MAX <= UQUAD_MAX/sizeof(uint64_t));
   1353 			vnd->sc_comp_offsets =
   1354 			    malloc(sizeof(uint64_t) * vnd->sc_comp_numoffs,
   1355 				M_DEVBUF, M_WAITOK);
   1356 
   1357 			/* read in the offsets */
   1358 			error = vn_rdwr(UIO_READ, vp,
   1359 			    (void *)vnd->sc_comp_offsets,
   1360 			    sizeof(uint64_t) * vnd->sc_comp_numoffs,
   1361 			    sizeof(struct vnd_comp_header), UIO_SYSSPACE,
   1362 			  IO_UNIT|IO_NODELOCKED, l->l_cred, NULL, NULL);
   1363 			if (error) {
   1364 				VOP_UNLOCK(vp);
   1365 				goto close_and_exit;
   1366 			}
   1367 			/*
   1368 			 * find largest block size (used for allocation limit).
   1369 			 * Also convert offset to native byte order.
   1370 			 */
   1371 			comp_maxsize = 0;
   1372 			for (i = 0; i < vnd->sc_comp_numoffs - 1; i++) {
   1373 				vnd->sc_comp_offsets[i] =
   1374 				    be64toh(vnd->sc_comp_offsets[i]);
   1375 				comp_size =
   1376 				    be64toh(vnd->sc_comp_offsets[i + 1])
   1377 				    - vnd->sc_comp_offsets[i];
   1378 				if (comp_size > comp_maxsize)
   1379 					comp_maxsize = comp_size;
   1380 			}
   1381 			vnd->sc_comp_offsets[vnd->sc_comp_numoffs - 1] =
   1382 			    be64toh(vnd->sc_comp_offsets[vnd->sc_comp_numoffs
   1383 				    - 1]);
   1384 
   1385 			/* create compressed data buffer */
   1386 			vnd->sc_comp_buff = malloc(comp_maxsize,
   1387 			    M_DEVBUF, M_WAITOK);
   1388 
   1389 			/* create decompressed buffer */
   1390 			vnd->sc_comp_decombuf = malloc(vnd->sc_comp_blksz,
   1391 			    M_DEVBUF, M_WAITOK);
   1392 			vnd->sc_comp_buffblk = -1;
   1393 
   1394 			/* Initialize decompress stream */
   1395 			memset(&vnd->sc_comp_stream, 0, sizeof(z_stream));
   1396 			vnd->sc_comp_stream.zalloc = vnd_alloc;
   1397 			vnd->sc_comp_stream.zfree = vnd_free;
   1398 			error = inflateInit2(&vnd->sc_comp_stream, MAX_WBITS);
   1399 			if (error) {
   1400 				if (vnd->sc_comp_stream.msg)
   1401 					printf("vnd%d: compressed file, %s\n",
   1402 					    unit, vnd->sc_comp_stream.msg);
   1403 				VOP_UNLOCK(vp);
   1404 				error = EINVAL;
   1405 				goto close_and_exit;
   1406 			}
   1407 
   1408 			vnd->sc_flags |= VNF_COMP | VNF_READONLY;
   1409 #else /* !VND_COMPRESSION */
   1410 			VOP_UNLOCK(vp);
   1411 			error = EOPNOTSUPP;
   1412 			goto close_and_exit;
   1413 #endif /* VND_COMPRESSION */
   1414 		}
   1415 
   1416 		VOP_UNLOCK(vp);
   1417 		vnd->sc_vp = vp;
   1418 		vnd->sc_size = btodb(vattr.va_size);	/* note truncation */
   1419 
   1420 		/* get smallest I/O size for underlying device, fall back to
   1421 		 * fundamental I/O size of underlying filesystem
   1422 		 */
   1423 		error = bdev_ioctl(vattr.va_fsid, DIOCGSECTORSIZE, &vnd->sc_iosize, FKIOCTL, l);
   1424 		if (error)
   1425 			vnd->sc_iosize = vnd->sc_vp->v_mount->mnt_stat.f_frsize;
   1426 
   1427 		/* Default I/O size to DEV_BSIZE */
   1428 		if (vnd->sc_iosize == 0)
   1429 			vnd->sc_iosize = DEV_BSIZE;
   1430 
   1431 		/*
   1432 		 * Use pseudo-geometry specified.  If none was provided,
   1433 		 * use "standard" Adaptec fictitious geometry.
   1434 		 */
   1435 		if (vio->vnd_flags & VNDIOF_HASGEOM) {
   1436 
   1437 			memcpy(&vnd->sc_geom, &vio->vnd_geom,
   1438 			    sizeof(vio->vnd_geom));
   1439 
   1440 			/*
   1441 			 * Sanity-check the sector size.
   1442 			 */
   1443 			if (!DK_DEV_BSIZE_OK(vnd->sc_geom.vng_secsize) ||
   1444 			    vnd->sc_geom.vng_ntracks == 0 ||
   1445 			    vnd->sc_geom.vng_nsectors == 0) {
   1446 				error = EINVAL;
   1447 				goto close_and_exit;
   1448 			}
   1449 
   1450 			/*
   1451 			 * Compute missing cylinder count from size
   1452 			 */
   1453 			if (vnd->sc_geom.vng_ncylinders == 0)
   1454 				vnd->sc_geom.vng_ncylinders = vnd->sc_size / (
   1455 					(vnd->sc_geom.vng_secsize / DEV_BSIZE) *
   1456 					vnd->sc_geom.vng_ntracks *
   1457 					vnd->sc_geom.vng_nsectors);
   1458 
   1459 			/*
   1460 			 * Compute the size (in DEV_BSIZE blocks) specified
   1461 			 * by the geometry.
   1462 			 */
   1463 			geomsize = (int64_t)vnd->sc_geom.vng_nsectors *
   1464 			    vnd->sc_geom.vng_ntracks *
   1465 			    vnd->sc_geom.vng_ncylinders *
   1466 			    (vnd->sc_geom.vng_secsize / DEV_BSIZE);
   1467 
   1468 			/*
   1469 			 * Sanity-check the size against the specified
   1470 			 * geometry.
   1471 			 */
   1472 			if (vnd->sc_size < geomsize) {
   1473 				error = EINVAL;
   1474 				goto close_and_exit;
   1475 			}
   1476 		} else if (vnd->sc_size >= (32 * 64)) {
   1477 			/*
   1478 			 * Size must be at least 2048 DEV_BSIZE blocks
   1479 			 * (1M) in order to use this geometry.
   1480 			 */
   1481 			vnd->sc_geom.vng_secsize = DEV_BSIZE;
   1482 			vnd->sc_geom.vng_nsectors = 32;
   1483 			vnd->sc_geom.vng_ntracks = 64;
   1484 			vnd->sc_geom.vng_ncylinders = vnd->sc_size / (64 * 32);
   1485 		} else {
   1486 			vnd->sc_geom.vng_secsize = DEV_BSIZE;
   1487 			vnd->sc_geom.vng_nsectors = 1;
   1488 			vnd->sc_geom.vng_ntracks = 1;
   1489 			vnd->sc_geom.vng_ncylinders = vnd->sc_size;
   1490 		}
   1491 
   1492 		vnd_set_geometry(vnd);
   1493 
   1494 		if (vio->vnd_flags & VNDIOF_READONLY) {
   1495 			vnd->sc_flags |= VNF_READONLY;
   1496 		}
   1497 
   1498 		if ((error = vndsetcred(vnd, l->l_cred)) != 0)
   1499 			goto close_and_exit;
   1500 
   1501 		vndthrottle(vnd, vnd->sc_vp);
   1502 		vio->vnd_osize = dbtob(vnd->sc_size);
   1503 		if (cmd != VNDIOCSET50)
   1504 			vio->vnd_size = dbtob(vnd->sc_size);
   1505 		vnd->sc_flags |= VNF_INITED;
   1506 
   1507 		/* create the kernel thread, wait for it to be up */
   1508 		error = kthread_create(PRI_NONE, 0, NULL, vndthread, vnd,
   1509 		    &vnd->sc_kthread, "%s", device_xname(vnd->sc_dev));
   1510 		if (error)
   1511 			goto close_and_exit;
   1512 		while ((vnd->sc_flags & VNF_KTHREAD) == 0) {
   1513 			tsleep(&vnd->sc_kthread, PRIBIO, "vndthr", 0);
   1514 		}
   1515 #ifdef DEBUG
   1516 		if (vnddebug & VDB_INIT)
   1517 			printf("vndioctl: SET vp %p size 0x%lx %d/%d/%d/%d\n",
   1518 			    vnd->sc_vp, (unsigned long) vnd->sc_size,
   1519 			    vnd->sc_geom.vng_secsize,
   1520 			    vnd->sc_geom.vng_nsectors,
   1521 			    vnd->sc_geom.vng_ntracks,
   1522 			    vnd->sc_geom.vng_ncylinders);
   1523 #endif
   1524 
   1525 		/* Attach the disk. */
   1526 		disk_attach(&vnd->sc_dkdev);
   1527 
   1528 		/* Initialize the xfer and buffer pools. */
   1529 		pool_init(&vnd->sc_vxpool, sizeof(struct vndxfer), 0,
   1530 		    0, 0, "vndxpl", NULL, IPL_BIO);
   1531 
   1532 		vndunlock(vnd);
   1533 
   1534 		pathbuf_destroy(pb);
   1535 
   1536 		/* Discover wedges on this disk */
   1537 		dkwedge_discover(&vnd->sc_dkdev);
   1538 
   1539 		break;
   1540 
   1541 close_and_exit:
   1542 		(void) vn_close(vp, fflags, l->l_cred);
   1543 		pathbuf_destroy(pb);
   1544 unlock_and_exit:
   1545 #ifdef VND_COMPRESSION
   1546 		/* free any allocated memory (for compressed file) */
   1547 		if (vnd->sc_comp_offsets) {
   1548 			free(vnd->sc_comp_offsets, M_DEVBUF);
   1549 			vnd->sc_comp_offsets = NULL;
   1550 		}
   1551 		if (vnd->sc_comp_buff) {
   1552 			free(vnd->sc_comp_buff, M_DEVBUF);
   1553 			vnd->sc_comp_buff = NULL;
   1554 		}
   1555 		if (vnd->sc_comp_decombuf) {
   1556 			free(vnd->sc_comp_decombuf, M_DEVBUF);
   1557 			vnd->sc_comp_decombuf = NULL;
   1558 		}
   1559 #endif /* VND_COMPRESSION */
   1560 		vndunlock(vnd);
   1561 		return error;
   1562 
   1563 	case VNDIOCCLR50:
   1564 	case VNDIOCCLR:
   1565 		part = DISKPART(dev);
   1566 		pmask = (1 << part);
   1567 		force = (vio->vnd_flags & VNDIOF_FORCE) != 0;
   1568 
   1569 		if ((error = vnddoclear(vnd, pmask, minor(dev), force)) != 0)
   1570 			return error;
   1571 
   1572 		break;
   1573 
   1574 
   1575 	case DIOCWDINFO:
   1576 	case DIOCSDINFO:
   1577 #ifdef __HAVE_OLD_DISKLABEL
   1578 	case ODIOCWDINFO:
   1579 	case ODIOCSDINFO:
   1580 #endif
   1581 	{
   1582 		struct disklabel *lp;
   1583 
   1584 		if ((error = vndlock(vnd)) != 0)
   1585 			return error;
   1586 
   1587 		vnd->sc_flags |= VNF_LABELLING;
   1588 
   1589 #ifdef __HAVE_OLD_DISKLABEL
   1590 		if (cmd == ODIOCSDINFO || cmd == ODIOCWDINFO) {
   1591 			memset(&newlabel, 0, sizeof newlabel);
   1592 			memcpy(&newlabel, data, sizeof (struct olddisklabel));
   1593 			lp = &newlabel;
   1594 		} else
   1595 #endif
   1596 		lp = (struct disklabel *)data;
   1597 
   1598 		error = setdisklabel(vnd->sc_dkdev.dk_label,
   1599 		    lp, 0, vnd->sc_dkdev.dk_cpulabel);
   1600 		if (error == 0) {
   1601 			if (cmd == DIOCWDINFO
   1602 #ifdef __HAVE_OLD_DISKLABEL
   1603 			    || cmd == ODIOCWDINFO
   1604 #endif
   1605 			   )
   1606 				error = writedisklabel(VNDLABELDEV(dev),
   1607 				    vndstrategy, vnd->sc_dkdev.dk_label,
   1608 				    vnd->sc_dkdev.dk_cpulabel);
   1609 		}
   1610 
   1611 		vnd->sc_flags &= ~VNF_LABELLING;
   1612 
   1613 		vndunlock(vnd);
   1614 
   1615 		if (error)
   1616 			return error;
   1617 		break;
   1618 	}
   1619 
   1620 	case DIOCKLABEL:
   1621 		if (*(int *)data != 0)
   1622 			vnd->sc_flags |= VNF_KLABEL;
   1623 		else
   1624 			vnd->sc_flags &= ~VNF_KLABEL;
   1625 		break;
   1626 
   1627 	case DIOCWLABEL:
   1628 		if (*(int *)data != 0)
   1629 			vnd->sc_flags |= VNF_WLABEL;
   1630 		else
   1631 			vnd->sc_flags &= ~VNF_WLABEL;
   1632 		break;
   1633 
   1634 	case DIOCGDEFLABEL:
   1635 		vndgetdefaultlabel(vnd, (struct disklabel *)data);
   1636 		break;
   1637 
   1638 #ifdef __HAVE_OLD_DISKLABEL
   1639 	case ODIOCGDEFLABEL:
   1640 		vndgetdefaultlabel(vnd, &newlabel);
   1641 		if (newlabel.d_npartitions > OLDMAXPARTITIONS)
   1642 			return ENOTTY;
   1643 		memcpy(data, &newlabel, sizeof (struct olddisklabel));
   1644 		break;
   1645 #endif
   1646 
   1647 	case DIOCGSTRATEGY:
   1648 	    {
   1649 		struct disk_strategy *dks = (void *)data;
   1650 
   1651 		/* No lock needed, never changed */
   1652 		strlcpy(dks->dks_name,
   1653 		    bufq_getstrategyname(vnd->sc_tab),
   1654 		    sizeof(dks->dks_name));
   1655 		dks->dks_paramlen = 0;
   1656 		break;
   1657 	    }
   1658 	case DIOCGCACHE:
   1659 	    {
   1660 		int *bits = (int *)data;
   1661 		*bits |= DKCACHE_READ | DKCACHE_WRITE;
   1662 		break;
   1663 	    }
   1664 	case DIOCCACHESYNC:
   1665 		vn_lock(vnd->sc_vp, LK_EXCLUSIVE | LK_RETRY);
   1666 		error = VOP_FSYNC(vnd->sc_vp, vnd->sc_cred,
   1667 		    FSYNC_WAIT | FSYNC_DATAONLY | FSYNC_CACHE, 0, 0);
   1668 		VOP_UNLOCK(vnd->sc_vp);
   1669 		return error;
   1670 
   1671 	default:
   1672 		return ENOTTY;
   1673 	}
   1674 
   1675 	return 0;
   1676 }
   1677 
   1678 /*
   1679  * Duplicate the current processes' credentials.  Since we are called only
   1680  * as the result of a SET ioctl and only root can do that, any future access
   1681  * to this "disk" is essentially as root.  Note that credentials may change
   1682  * if some other uid can write directly to the mapped file (NFS).
   1683  */
   1684 static int
   1685 vndsetcred(struct vnd_softc *vnd, kauth_cred_t cred)
   1686 {
   1687 	struct uio auio;
   1688 	struct iovec aiov;
   1689 	char *tmpbuf;
   1690 	int error;
   1691 
   1692 	vnd->sc_cred = kauth_cred_dup(cred);
   1693 	tmpbuf = malloc(DEV_BSIZE, M_TEMP, M_WAITOK);
   1694 
   1695 	/* XXX: Horrible kludge to establish credentials for NFS */
   1696 	aiov.iov_base = tmpbuf;
   1697 	aiov.iov_len = uimin(DEV_BSIZE, dbtob(vnd->sc_size));
   1698 	auio.uio_iov = &aiov;
   1699 	auio.uio_iovcnt = 1;
   1700 	auio.uio_offset = 0;
   1701 	auio.uio_rw = UIO_READ;
   1702 	auio.uio_resid = aiov.iov_len;
   1703 	UIO_SETUP_SYSSPACE(&auio);
   1704 	vn_lock(vnd->sc_vp, LK_EXCLUSIVE | LK_RETRY);
   1705 	error = VOP_READ(vnd->sc_vp, &auio, 0, vnd->sc_cred);
   1706 	if (error == 0) {
   1707 		/*
   1708 		 * Because vnd does all IO directly through the vnode
   1709 		 * we need to flush (at least) the buffer from the above
   1710 		 * VOP_READ from the buffer cache to prevent cache
   1711 		 * incoherencies.  Also, be careful to write dirty
   1712 		 * buffers back to stable storage.
   1713 		 */
   1714 		error = vinvalbuf(vnd->sc_vp, V_SAVE, vnd->sc_cred,
   1715 			    curlwp, 0, 0);
   1716 	}
   1717 	VOP_UNLOCK(vnd->sc_vp);
   1718 
   1719 	free(tmpbuf, M_TEMP);
   1720 	return error;
   1721 }
   1722 
   1723 /*
   1724  * Set maxactive based on FS type
   1725  */
   1726 static void
   1727 vndthrottle(struct vnd_softc *vnd, struct vnode *vp)
   1728 {
   1729 
   1730 	if (vp->v_tag == VT_NFS)
   1731 		vnd->sc_maxactive = 2;
   1732 	else
   1733 		vnd->sc_maxactive = 8;
   1734 
   1735 	if (vnd->sc_maxactive < 1)
   1736 		vnd->sc_maxactive = 1;
   1737 }
   1738 
   1739 #if 0
   1740 static void
   1741 vndshutdown(void)
   1742 {
   1743 	struct vnd_softc *vnd;
   1744 
   1745 	for (vnd = &vnd_softc[0]; vnd < &vnd_softc[numvnd]; vnd++)
   1746 		if (vnd->sc_flags & VNF_INITED)
   1747 			vndclear(vnd);
   1748 }
   1749 #endif
   1750 
   1751 static void
   1752 vndclear(struct vnd_softc *vnd, int myminor)
   1753 {
   1754 	struct vnode *vp = vnd->sc_vp;
   1755 	int fflags = FREAD;
   1756 	int bmaj, cmaj, i, mn;
   1757 	int s;
   1758 
   1759 #ifdef DEBUG
   1760 	if (vnddebug & VDB_FOLLOW)
   1761 		printf("vndclear(%p): vp %p\n", vnd, vp);
   1762 #endif
   1763 	/* locate the major number */
   1764 	bmaj = bdevsw_lookup_major(&vnd_bdevsw);
   1765 	cmaj = cdevsw_lookup_major(&vnd_cdevsw);
   1766 
   1767 	/* Nuke the vnodes for any open instances */
   1768 	for (i = 0; i < MAXPARTITIONS; i++) {
   1769 		mn = DISKMINOR(device_unit(vnd->sc_dev), i);
   1770 		vdevgone(bmaj, mn, mn, VBLK);
   1771 		if (mn != myminor) /* XXX avoid to kill own vnode */
   1772 			vdevgone(cmaj, mn, mn, VCHR);
   1773 	}
   1774 
   1775 	if ((vnd->sc_flags & VNF_READONLY) == 0)
   1776 		fflags |= FWRITE;
   1777 
   1778 	s = splbio();
   1779 	bufq_drain(vnd->sc_tab);
   1780 	splx(s);
   1781 
   1782 	vnd->sc_flags |= VNF_VUNCONF;
   1783 	wakeup(&vnd->sc_tab);
   1784 	while (vnd->sc_flags & VNF_KTHREAD)
   1785 		tsleep(&vnd->sc_kthread, PRIBIO, "vnthr", 0);
   1786 
   1787 #ifdef VND_COMPRESSION
   1788 	/* free the compressed file buffers */
   1789 	if (vnd->sc_flags & VNF_COMP) {
   1790 		if (vnd->sc_comp_offsets) {
   1791 			free(vnd->sc_comp_offsets, M_DEVBUF);
   1792 			vnd->sc_comp_offsets = NULL;
   1793 		}
   1794 		if (vnd->sc_comp_buff) {
   1795 			free(vnd->sc_comp_buff, M_DEVBUF);
   1796 			vnd->sc_comp_buff = NULL;
   1797 		}
   1798 		if (vnd->sc_comp_decombuf) {
   1799 			free(vnd->sc_comp_decombuf, M_DEVBUF);
   1800 			vnd->sc_comp_decombuf = NULL;
   1801 		}
   1802 	}
   1803 #endif /* VND_COMPRESSION */
   1804 	vnd->sc_flags &=
   1805 	    ~(VNF_INITED | VNF_READONLY | VNF_KLABEL | VNF_VLABEL
   1806 	      | VNF_VUNCONF | VNF_COMP | VNF_CLEARING);
   1807 	if (vp == NULL)
   1808 		panic("vndclear: null vp");
   1809 	(void) vn_close(vp, fflags, vnd->sc_cred);
   1810 	kauth_cred_free(vnd->sc_cred);
   1811 	vnd->sc_vp = NULL;
   1812 	vnd->sc_cred = NULL;
   1813 	vnd->sc_size = 0;
   1814 }
   1815 
   1816 static int
   1817 vndsize(dev_t dev)
   1818 {
   1819 	struct vnd_softc *sc;
   1820 	struct disklabel *lp;
   1821 	int part, unit, omask;
   1822 	int size;
   1823 
   1824 	unit = vndunit(dev);
   1825 	sc = device_lookup_private(&vnd_cd, unit);
   1826 	if (sc == NULL)
   1827 		return -1;
   1828 
   1829 	if ((sc->sc_flags & VNF_INITED) == 0)
   1830 		return -1;
   1831 
   1832 	part = DISKPART(dev);
   1833 	omask = sc->sc_dkdev.dk_openmask & (1 << part);
   1834 	lp = sc->sc_dkdev.dk_label;
   1835 
   1836 	if (omask == 0 && vndopen(dev, 0, S_IFBLK, curlwp))	/* XXX */
   1837 		return -1;
   1838 
   1839 	if (lp->d_partitions[part].p_fstype != FS_SWAP)
   1840 		size = -1;
   1841 	else
   1842 		size = lp->d_partitions[part].p_size *
   1843 		    (lp->d_secsize / DEV_BSIZE);
   1844 
   1845 	if (omask == 0 && vndclose(dev, 0, S_IFBLK, curlwp))	/* XXX */
   1846 		return -1;
   1847 
   1848 	return size;
   1849 }
   1850 
   1851 static int
   1852 vnddump(dev_t dev, daddr_t blkno, void *va,
   1853     size_t size)
   1854 {
   1855 
   1856 	/* Not implemented. */
   1857 	return ENXIO;
   1858 }
   1859 
   1860 static void
   1861 vndgetdefaultlabel(struct vnd_softc *sc, struct disklabel *lp)
   1862 {
   1863 	struct vndgeom *vng = &sc->sc_geom;
   1864 	struct partition *pp;
   1865 	unsigned spb;
   1866 
   1867 	memset(lp, 0, sizeof(*lp));
   1868 
   1869 	spb = vng->vng_secsize / DEV_BSIZE;
   1870 	if (sc->sc_size / spb > UINT32_MAX)
   1871 		lp->d_secperunit = UINT32_MAX;
   1872 	else
   1873 		lp->d_secperunit = sc->sc_size / spb;
   1874 	lp->d_secsize = vng->vng_secsize;
   1875 	lp->d_nsectors = vng->vng_nsectors;
   1876 	lp->d_ntracks = vng->vng_ntracks;
   1877 	lp->d_ncylinders = vng->vng_ncylinders;
   1878 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
   1879 
   1880 	strncpy(lp->d_typename, "vnd", sizeof(lp->d_typename));
   1881 	lp->d_type = DKTYPE_VND;
   1882 	strncpy(lp->d_packname, "fictitious", sizeof(lp->d_packname));
   1883 	lp->d_rpm = 3600;
   1884 	lp->d_interleave = 1;
   1885 	lp->d_flags = 0;
   1886 
   1887 	pp = &lp->d_partitions[RAW_PART];
   1888 	pp->p_offset = 0;
   1889 	pp->p_size = lp->d_secperunit;
   1890 	pp->p_fstype = FS_UNUSED;
   1891 	lp->d_npartitions = RAW_PART + 1;
   1892 
   1893 	lp->d_magic = DISKMAGIC;
   1894 	lp->d_magic2 = DISKMAGIC;
   1895 	lp->d_checksum = dkcksum(lp);
   1896 }
   1897 
   1898 /*
   1899  * Read the disklabel from a vnd.  If one is not present, create a fake one.
   1900  */
   1901 static void
   1902 vndgetdisklabel(dev_t dev, struct vnd_softc *sc)
   1903 {
   1904 	const char *errstring;
   1905 	struct disklabel *lp = sc->sc_dkdev.dk_label;
   1906 	struct cpu_disklabel *clp = sc->sc_dkdev.dk_cpulabel;
   1907 	int i;
   1908 
   1909 	memset(clp, 0, sizeof(*clp));
   1910 
   1911 	vndgetdefaultlabel(sc, lp);
   1912 
   1913 	/*
   1914 	 * Call the generic disklabel extraction routine.
   1915 	 */
   1916 	errstring = readdisklabel(VNDLABELDEV(dev), vndstrategy, lp, clp);
   1917 	if (errstring) {
   1918 		/*
   1919 		 * Lack of disklabel is common, but we print the warning
   1920 		 * anyway, since it might contain other useful information.
   1921 		 */
   1922 		aprint_normal_dev(sc->sc_dev, "%s\n", errstring);
   1923 
   1924 		/*
   1925 		 * For historical reasons, if there's no disklabel
   1926 		 * present, all partitions must be FS_BSDFFS and
   1927 		 * occupy the entire disk.
   1928 		 */
   1929 		for (i = 0; i < MAXPARTITIONS; i++) {
   1930 			/*
   1931 			 * Don't wipe out port specific hack (such as
   1932 			 * dos partition hack of i386 port).
   1933 			 */
   1934 			if (lp->d_partitions[i].p_size != 0)
   1935 				continue;
   1936 
   1937 			lp->d_partitions[i].p_size = lp->d_secperunit;
   1938 			lp->d_partitions[i].p_offset = 0;
   1939 			lp->d_partitions[i].p_fstype = FS_BSDFFS;
   1940 		}
   1941 
   1942 		strncpy(lp->d_packname, "default label",
   1943 		    sizeof(lp->d_packname));
   1944 
   1945 		lp->d_npartitions = MAXPARTITIONS;
   1946 		lp->d_checksum = dkcksum(lp);
   1947 	}
   1948 }
   1949 
   1950 /*
   1951  * Wait interruptibly for an exclusive lock.
   1952  *
   1953  * XXX
   1954  * Several drivers do this; it should be abstracted and made MP-safe.
   1955  */
   1956 static int
   1957 vndlock(struct vnd_softc *sc)
   1958 {
   1959 	int error;
   1960 
   1961 	while ((sc->sc_flags & VNF_LOCKED) != 0) {
   1962 		sc->sc_flags |= VNF_WANTED;
   1963 		if ((error = tsleep(sc, PRIBIO | PCATCH, "vndlck", 0)) != 0)
   1964 			return error;
   1965 	}
   1966 	sc->sc_flags |= VNF_LOCKED;
   1967 	return 0;
   1968 }
   1969 
   1970 /*
   1971  * Unlock and wake up any waiters.
   1972  */
   1973 static void
   1974 vndunlock(struct vnd_softc *sc)
   1975 {
   1976 
   1977 	sc->sc_flags &= ~VNF_LOCKED;
   1978 	if ((sc->sc_flags & VNF_WANTED) != 0) {
   1979 		sc->sc_flags &= ~VNF_WANTED;
   1980 		wakeup(sc);
   1981 	}
   1982 }
   1983 
   1984 #ifdef VND_COMPRESSION
   1985 /* compressed file read */
   1986 static void
   1987 compstrategy(struct buf *bp, off_t bn)
   1988 {
   1989 	int error;
   1990 	int unit = vndunit(bp->b_dev);
   1991 	struct vnd_softc *vnd =
   1992 	    device_lookup_private(&vnd_cd, unit);
   1993 	u_int32_t comp_block;
   1994 	struct uio auio;
   1995 	char *addr;
   1996 	int s;
   1997 
   1998 	/* set up constants for data move */
   1999 	auio.uio_rw = UIO_READ;
   2000 	UIO_SETUP_SYSSPACE(&auio);
   2001 
   2002 	/* read, and transfer the data */
   2003 	addr = bp->b_data;
   2004 	bp->b_resid = bp->b_bcount;
   2005 	s = splbio();
   2006 	while (bp->b_resid > 0) {
   2007 		unsigned length;
   2008 		size_t length_in_buffer;
   2009 		u_int32_t offset_in_buffer;
   2010 		struct iovec aiov;
   2011 
   2012 		/* calculate the compressed block number */
   2013 		comp_block = bn / (off_t)vnd->sc_comp_blksz;
   2014 
   2015 		/* check for good block number */
   2016 		if (comp_block >= vnd->sc_comp_numoffs) {
   2017 			bp->b_error = EINVAL;
   2018 			splx(s);
   2019 			return;
   2020 		}
   2021 
   2022 		/* read in the compressed block, if not in buffer */
   2023 		if (comp_block != vnd->sc_comp_buffblk) {
   2024 			length = vnd->sc_comp_offsets[comp_block + 1] -
   2025 			    vnd->sc_comp_offsets[comp_block];
   2026 			vn_lock(vnd->sc_vp, LK_EXCLUSIVE | LK_RETRY);
   2027 			error = vn_rdwr(UIO_READ, vnd->sc_vp, vnd->sc_comp_buff,
   2028 			    length, vnd->sc_comp_offsets[comp_block],
   2029 			    UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT, vnd->sc_cred,
   2030 			    NULL, NULL);
   2031 			if (error) {
   2032 				bp->b_error = error;
   2033 				VOP_UNLOCK(vnd->sc_vp);
   2034 				splx(s);
   2035 				return;
   2036 			}
   2037 			/* uncompress the buffer */
   2038 			vnd->sc_comp_stream.next_in = vnd->sc_comp_buff;
   2039 			vnd->sc_comp_stream.avail_in = length;
   2040 			vnd->sc_comp_stream.next_out = vnd->sc_comp_decombuf;
   2041 			vnd->sc_comp_stream.avail_out = vnd->sc_comp_blksz;
   2042 			inflateReset(&vnd->sc_comp_stream);
   2043 			error = inflate(&vnd->sc_comp_stream, Z_FINISH);
   2044 			if (error != Z_STREAM_END) {
   2045 				if (vnd->sc_comp_stream.msg)
   2046 					aprint_normal_dev(vnd->sc_dev,
   2047 					    "compressed file, %s\n",
   2048 					    vnd->sc_comp_stream.msg);
   2049 				bp->b_error = EBADMSG;
   2050 				VOP_UNLOCK(vnd->sc_vp);
   2051 				splx(s);
   2052 				return;
   2053 			}
   2054 			vnd->sc_comp_buffblk = comp_block;
   2055 			VOP_UNLOCK(vnd->sc_vp);
   2056 		}
   2057 
   2058 		/* transfer the usable uncompressed data */
   2059 		offset_in_buffer = bn % (off_t)vnd->sc_comp_blksz;
   2060 		length_in_buffer = vnd->sc_comp_blksz - offset_in_buffer;
   2061 		if (length_in_buffer > bp->b_resid)
   2062 			length_in_buffer = bp->b_resid;
   2063 		auio.uio_iov = &aiov;
   2064 		auio.uio_iovcnt = 1;
   2065 		aiov.iov_base = addr;
   2066 		aiov.iov_len = length_in_buffer;
   2067 		auio.uio_resid = aiov.iov_len;
   2068 		auio.uio_offset = 0;
   2069 		error = uiomove(vnd->sc_comp_decombuf + offset_in_buffer,
   2070 		    length_in_buffer, &auio);
   2071 		if (error) {
   2072 			bp->b_error = error;
   2073 			splx(s);
   2074 			return;
   2075 		}
   2076 
   2077 		bn += length_in_buffer;
   2078 		addr += length_in_buffer;
   2079 		bp->b_resid -= length_in_buffer;
   2080 	}
   2081 	splx(s);
   2082 }
   2083 
   2084 /* compression memory allocation routines */
   2085 static void *
   2086 vnd_alloc(void *aux, u_int items, u_int siz)
   2087 {
   2088 	return malloc(items * siz, M_TEMP, M_NOWAIT);
   2089 }
   2090 
   2091 static void
   2092 vnd_free(void *aux, void *ptr)
   2093 {
   2094 	free(ptr, M_TEMP);
   2095 }
   2096 #endif /* VND_COMPRESSION */
   2097 
   2098 static void
   2099 vnd_set_geometry(struct vnd_softc *vnd)
   2100 {
   2101 	struct disk_geom *dg = &vnd->sc_dkdev.dk_geom;
   2102 	unsigned spb;
   2103 
   2104 	memset(dg, 0, sizeof(*dg));
   2105 
   2106 	spb = vnd->sc_geom.vng_secsize / DEV_BSIZE;
   2107 	dg->dg_secperunit = vnd->sc_size / spb;
   2108 	dg->dg_secsize = vnd->sc_geom.vng_secsize;
   2109 	dg->dg_nsectors = vnd->sc_geom.vng_nsectors;
   2110 	dg->dg_ntracks = vnd->sc_geom.vng_ntracks;
   2111 	dg->dg_ncylinders = vnd->sc_geom.vng_ncylinders;
   2112 
   2113 #ifdef DEBUG
   2114 	if (vnddebug & VDB_LABEL) {
   2115 		printf("dg->dg_secperunit: %" PRId64 "\n", dg->dg_secperunit);
   2116 		printf("dg->dg_ncylinders: %u\n", dg->dg_ncylinders);
   2117 	}
   2118 #endif
   2119 	disk_set_info(vnd->sc_dev, &vnd->sc_dkdev, NULL);
   2120 }
   2121 
   2122 #ifdef VND_COMPRESSION
   2123 #define VND_DEPENDS "zlib"
   2124 #else
   2125 #define VND_DEPENDS NULL
   2126 #endif
   2127 
   2128 MODULE(MODULE_CLASS_DRIVER, vnd, VND_DEPENDS);
   2129 
   2130 #ifdef _MODULE
   2131 int vnd_bmajor = -1, vnd_cmajor = -1;
   2132 
   2133 CFDRIVER_DECL(vnd, DV_DISK, NULL);
   2134 #endif
   2135 
   2136 static int
   2137 vnd_modcmd(modcmd_t cmd, void *arg)
   2138 {
   2139 	int error = 0;
   2140 
   2141 	switch (cmd) {
   2142 	case MODULE_CMD_INIT:
   2143 #ifdef _MODULE
   2144 		error = config_cfdriver_attach(&vnd_cd);
   2145 		if (error)
   2146 			break;
   2147 
   2148 		error = config_cfattach_attach(vnd_cd.cd_name, &vnd_ca);
   2149 	        if (error) {
   2150 			config_cfdriver_detach(&vnd_cd);
   2151 #ifdef DIAGNOSTIC
   2152 			aprint_error("%s: unable to register cfattach for \n"
   2153 			    "%s, error %d", __func__, vnd_cd.cd_name, error);
   2154 #endif
   2155 			break;
   2156 		}
   2157 
   2158                 /*
   2159                  * Attach the {b,c}devsw's
   2160                  */
   2161 		error = devsw_attach("vnd", &vnd_bdevsw, &vnd_bmajor,
   2162 		    &vnd_cdevsw, &vnd_cmajor);
   2163                 /*
   2164                  * If devsw_attach fails, remove from autoconf database
   2165                  */
   2166 		if (error) {
   2167 			config_cfattach_detach(vnd_cd.cd_name, &vnd_ca);
   2168 			config_cfdriver_detach(&vnd_cd);
   2169 #ifdef DIAGNOSTIC
   2170                         aprint_error("%s: unable to attach %s devsw, "
   2171                             "error %d", __func__, vnd_cd.cd_name, error);
   2172 #endif
   2173 			break;
   2174 		}
   2175 #endif
   2176 		break;
   2177 
   2178 	case MODULE_CMD_FINI:
   2179 #ifdef _MODULE
   2180                 /*
   2181                  * Remove {b,c}devsw's
   2182                  */
   2183 		devsw_detach(&vnd_bdevsw, &vnd_cdevsw);
   2184 
   2185                 /*
   2186                  * Now remove device from autoconf database
   2187                  */
   2188 		error = config_cfattach_detach(vnd_cd.cd_name, &vnd_ca);
   2189                 if (error) {
   2190                         (void)devsw_attach("vnd", &vnd_bdevsw, &vnd_bmajor,
   2191                             &vnd_cdevsw, &vnd_cmajor);
   2192 #ifdef DIAGNOSTIC
   2193                         aprint_error("%s: failed to detach %s cfattach, "
   2194                             "error %d\n", __func__, vnd_cd.cd_name, error);
   2195 #endif
   2196                         break;
   2197                 }
   2198                 error = config_cfdriver_detach(&vnd_cd);
   2199                 if (error) {
   2200                         (void)config_cfattach_attach(vnd_cd.cd_name, &vnd_ca);
   2201                         (void)devsw_attach("vnd", &vnd_bdevsw, &vnd_bmajor,
   2202                             &vnd_cdevsw, &vnd_cmajor);
   2203 #ifdef DIAGNOSTIC
   2204                         aprint_error("%s: failed to detach %s cfdriver, "
   2205                             "error %d\n", __func__, vnd_cd.cd_name, error);
   2206                         break;
   2207 #endif
   2208                 }
   2209 #endif
   2210 		break;
   2211 
   2212 	case MODULE_CMD_STAT:
   2213 		return ENOTTY;
   2214 
   2215 	default:
   2216 		return ENOTTY;
   2217 	}
   2218 
   2219 	return error;
   2220 }
   2221