Home | History | Annotate | Line # | Download | only in uvm
uvm_swap.c revision 1.110
      1 /*	$NetBSD: uvm_swap.c,v 1.110 2006/10/22 09:44:21 yamt Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1995, 1996, 1997 Matthew R. Green
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. The name of the author may not be used to endorse or promote products
     16  *    derived from this software without specific prior written permission.
     17  *
     18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
     23  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
     25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     26  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     28  * SUCH DAMAGE.
     29  *
     30  * from: NetBSD: vm_swap.c,v 1.52 1997/12/02 13:47:37 pk Exp
     31  * from: Id: uvm_swap.c,v 1.1.2.42 1998/02/02 20:38:06 chuck Exp
     32  */
     33 
     34 #include <sys/cdefs.h>
     35 __KERNEL_RCSID(0, "$NetBSD: uvm_swap.c,v 1.110 2006/10/22 09:44:21 yamt Exp $");
     36 
     37 #include "fs_nfs.h"
     38 #include "opt_uvmhist.h"
     39 #include "opt_compat_netbsd.h"
     40 #include "opt_ddb.h"
     41 
     42 #include <sys/param.h>
     43 #include <sys/systm.h>
     44 #include <sys/buf.h>
     45 #include <sys/bufq.h>
     46 #include <sys/conf.h>
     47 #include <sys/proc.h>
     48 #include <sys/namei.h>
     49 #include <sys/disklabel.h>
     50 #include <sys/errno.h>
     51 #include <sys/kernel.h>
     52 #include <sys/vnode.h>
     53 #include <sys/file.h>
     54 #include <sys/vmem.h>
     55 #include <sys/kmem.h>
     56 #include <sys/blist.h>
     57 #include <sys/mount.h>
     58 #include <sys/pool.h>
     59 #include <sys/sa.h>
     60 #include <sys/syscallargs.h>
     61 #include <sys/swap.h>
     62 #include <sys/kauth.h>
     63 
     64 #include <uvm/uvm.h>
     65 
     66 #include <miscfs/specfs/specdev.h>
     67 
     68 /*
     69  * uvm_swap.c: manage configuration and i/o to swap space.
     70  */
     71 
     72 /*
     73  * swap space is managed in the following way:
     74  *
     75  * each swap partition or file is described by a "swapdev" structure.
     76  * each "swapdev" structure contains a "swapent" structure which contains
     77  * information that is passed up to the user (via system calls).
     78  *
     79  * each swap partition is assigned a "priority" (int) which controls
     80  * swap parition usage.
     81  *
     82  * the system maintains a global data structure describing all swap
     83  * partitions/files.   there is a sorted LIST of "swappri" structures
     84  * which describe "swapdev"'s at that priority.   this LIST is headed
     85  * by the "swap_priority" global var.    each "swappri" contains a
     86  * CIRCLEQ of "swapdev" structures at that priority.
     87  *
     88  * locking:
     89  *  - swap_syscall_lock (sleep lock): this lock serializes the swapctl
     90  *    system call and prevents the swap priority list from changing
     91  *    while we are in the middle of a system call (e.g. SWAP_STATS).
     92  *  - uvm.swap_data_lock (simple_lock): this lock protects all swap data
     93  *    structures including the priority list, the swapdev structures,
     94  *    and the swapmap arena.
     95  *
     96  * each swap device has the following info:
     97  *  - swap device in use (could be disabled, preventing future use)
     98  *  - swap enabled (allows new allocations on swap)
     99  *  - map info in /dev/drum
    100  *  - vnode pointer
    101  * for swap files only:
    102  *  - block size
    103  *  - max byte count in buffer
    104  *  - buffer
    105  *
    106  * userland controls and configures swap with the swapctl(2) system call.
    107  * the sys_swapctl performs the following operations:
    108  *  [1] SWAP_NSWAP: returns the number of swap devices currently configured
    109  *  [2] SWAP_STATS: given a pointer to an array of swapent structures
    110  *	(passed in via "arg") of a size passed in via "misc" ... we load
    111  *	the current swap config into the array. The actual work is done
    112  *	in the uvm_swap_stats(9) function.
    113  *  [3] SWAP_ON: given a pathname in arg (could be device or file) and a
    114  *	priority in "misc", start swapping on it.
    115  *  [4] SWAP_OFF: as SWAP_ON, but stops swapping to a device
    116  *  [5] SWAP_CTL: changes the priority of a swap device (new priority in
    117  *	"misc")
    118  */
    119 
    120 /*
    121  * swapdev: describes a single swap partition/file
    122  *
    123  * note the following should be true:
    124  * swd_inuse <= swd_nblks  [number of blocks in use is <= total blocks]
    125  * swd_nblks <= swd_mapsize [because mapsize includes miniroot+disklabel]
    126  */
    127 struct swapdev {
    128 	struct oswapent swd_ose;
    129 #define	swd_dev		swd_ose.ose_dev		/* device id */
    130 #define	swd_flags	swd_ose.ose_flags	/* flags:inuse/enable/fake */
    131 #define	swd_priority	swd_ose.ose_priority	/* our priority */
    132 	/* also: swd_ose.ose_nblks, swd_ose.ose_inuse */
    133 	char			*swd_path;	/* saved pathname of device */
    134 	int			swd_pathlen;	/* length of pathname */
    135 	int			swd_npages;	/* #pages we can use */
    136 	int			swd_npginuse;	/* #pages in use */
    137 	int			swd_npgbad;	/* #pages bad */
    138 	int			swd_drumoffset;	/* page0 offset in drum */
    139 	int			swd_drumsize;	/* #pages in drum */
    140 	blist_t			swd_blist;	/* blist for this swapdev */
    141 	struct vnode		*swd_vp;	/* backing vnode */
    142 	CIRCLEQ_ENTRY(swapdev)	swd_next;	/* priority circleq */
    143 
    144 	int			swd_bsize;	/* blocksize (bytes) */
    145 	int			swd_maxactive;	/* max active i/o reqs */
    146 	struct bufq_state	*swd_tab;	/* buffer list */
    147 	int			swd_active;	/* number of active buffers */
    148 };
    149 
    150 /*
    151  * swap device priority entry; the list is kept sorted on `spi_priority'.
    152  */
    153 struct swappri {
    154 	int			spi_priority;     /* priority */
    155 	CIRCLEQ_HEAD(spi_swapdev, swapdev)	spi_swapdev;
    156 	/* circleq of swapdevs at this priority */
    157 	LIST_ENTRY(swappri)	spi_swappri;      /* global list of pri's */
    158 };
    159 
    160 /*
    161  * The following two structures are used to keep track of data transfers
    162  * on swap devices associated with regular files.
    163  * NOTE: this code is more or less a copy of vnd.c; we use the same
    164  * structure names here to ease porting..
    165  */
    166 struct vndxfer {
    167 	struct buf	*vx_bp;		/* Pointer to parent buffer */
    168 	struct swapdev	*vx_sdp;
    169 	int		vx_error;
    170 	int		vx_pending;	/* # of pending aux buffers */
    171 	int		vx_flags;
    172 #define VX_BUSY		1
    173 #define VX_DEAD		2
    174 };
    175 
    176 struct vndbuf {
    177 	struct buf	vb_buf;
    178 	struct vndxfer	*vb_xfer;
    179 };
    180 
    181 
    182 /*
    183  * We keep a of pool vndbuf's and vndxfer structures.
    184  */
    185 POOL_INIT(vndxfer_pool, sizeof(struct vndxfer), 0, 0, 0, "swp vnx", NULL);
    186 POOL_INIT(vndbuf_pool, sizeof(struct vndbuf), 0, 0, 0, "swp vnd", NULL);
    187 
    188 #define	getvndxfer(vnx)	do {						\
    189 	int sp = splbio();						\
    190 	vnx = pool_get(&vndxfer_pool, PR_WAITOK);			\
    191 	splx(sp);							\
    192 } while (/*CONSTCOND*/ 0)
    193 
    194 #define putvndxfer(vnx) {						\
    195 	pool_put(&vndxfer_pool, (void *)(vnx));				\
    196 }
    197 
    198 #define	getvndbuf(vbp)	do {						\
    199 	int sp = splbio();						\
    200 	vbp = pool_get(&vndbuf_pool, PR_WAITOK);			\
    201 	splx(sp);							\
    202 } while (/*CONSTCOND*/ 0)
    203 
    204 #define putvndbuf(vbp) {						\
    205 	pool_put(&vndbuf_pool, (void *)(vbp));				\
    206 }
    207 
    208 /*
    209  * local variables
    210  */
    211 static vmem_t *swapmap;	/* controls the mapping of /dev/drum */
    212 
    213 /* list of all active swap devices [by priority] */
    214 LIST_HEAD(swap_priority, swappri);
    215 static struct swap_priority swap_priority;
    216 
    217 /* locks */
    218 static struct lock swap_syscall_lock;
    219 
    220 /*
    221  * prototypes
    222  */
    223 static struct swapdev	*swapdrum_getsdp(int);
    224 
    225 static struct swapdev	*swaplist_find(struct vnode *, int);
    226 static void		 swaplist_insert(struct swapdev *,
    227 					 struct swappri *, int);
    228 static void		 swaplist_trim(void);
    229 
    230 static int swap_on(struct lwp *, struct swapdev *);
    231 static int swap_off(struct lwp *, struct swapdev *);
    232 
    233 static void uvm_swap_stats_locked(int, struct swapent *, int, register_t *);
    234 
    235 static void sw_reg_strategy(struct swapdev *, struct buf *, int);
    236 static void sw_reg_iodone(struct buf *);
    237 static void sw_reg_start(struct swapdev *);
    238 
    239 static int uvm_swap_io(struct vm_page **, int, int, int);
    240 
    241 /*
    242  * uvm_swap_init: init the swap system data structures and locks
    243  *
    244  * => called at boot time from init_main.c after the filesystems
    245  *	are brought up (which happens after uvm_init())
    246  */
    247 void
    248 uvm_swap_init(void)
    249 {
    250 	UVMHIST_FUNC("uvm_swap_init");
    251 
    252 	UVMHIST_CALLED(pdhist);
    253 	/*
    254 	 * first, init the swap list, its counter, and its lock.
    255 	 * then get a handle on the vnode for /dev/drum by using
    256 	 * the its dev_t number ("swapdev", from MD conf.c).
    257 	 */
    258 
    259 	LIST_INIT(&swap_priority);
    260 	uvmexp.nswapdev = 0;
    261 	lockinit(&swap_syscall_lock, PVM, "swapsys", 0, 0);
    262 	simple_lock_init(&uvm.swap_data_lock);
    263 
    264 	if (bdevvp(swapdev, &swapdev_vp))
    265 		panic("uvm_swap_init: can't get vnode for swap device");
    266 
    267 	/*
    268 	 * create swap block resource map to map /dev/drum.   the range
    269 	 * from 1 to INT_MAX allows 2 gigablocks of swap space.  note
    270 	 * that block 0 is reserved (used to indicate an allocation
    271 	 * failure, or no allocation).
    272 	 */
    273 	swapmap = vmem_create("swapmap", 1, INT_MAX - 1, 1, NULL, NULL, NULL, 0,
    274 	    VM_NOSLEEP);
    275 	if (swapmap == 0)
    276 		panic("uvm_swap_init: extent_create failed");
    277 
    278 	/*
    279 	 * done!
    280 	 */
    281 	UVMHIST_LOG(pdhist, "<- done", 0, 0, 0, 0);
    282 }
    283 
    284 /*
    285  * swaplist functions: functions that operate on the list of swap
    286  * devices on the system.
    287  */
    288 
    289 /*
    290  * swaplist_insert: insert swap device "sdp" into the global list
    291  *
    292  * => caller must hold both swap_syscall_lock and uvm.swap_data_lock
    293  * => caller must provide a newly malloc'd swappri structure (we will
    294  *	FREE it if we don't need it... this it to prevent malloc blocking
    295  *	here while adding swap)
    296  */
    297 static void
    298 swaplist_insert(struct swapdev *sdp, struct swappri *newspp, int priority)
    299 {
    300 	struct swappri *spp, *pspp;
    301 	UVMHIST_FUNC("swaplist_insert"); UVMHIST_CALLED(pdhist);
    302 
    303 	/*
    304 	 * find entry at or after which to insert the new device.
    305 	 */
    306 	pspp = NULL;
    307 	LIST_FOREACH(spp, &swap_priority, spi_swappri) {
    308 		if (priority <= spp->spi_priority)
    309 			break;
    310 		pspp = spp;
    311 	}
    312 
    313 	/*
    314 	 * new priority?
    315 	 */
    316 	if (spp == NULL || spp->spi_priority != priority) {
    317 		spp = newspp;  /* use newspp! */
    318 		UVMHIST_LOG(pdhist, "created new swappri = %d",
    319 			    priority, 0, 0, 0);
    320 
    321 		spp->spi_priority = priority;
    322 		CIRCLEQ_INIT(&spp->spi_swapdev);
    323 
    324 		if (pspp)
    325 			LIST_INSERT_AFTER(pspp, spp, spi_swappri);
    326 		else
    327 			LIST_INSERT_HEAD(&swap_priority, spp, spi_swappri);
    328 	} else {
    329 	  	/* we don't need a new priority structure, free it */
    330 		kmem_free(newspp, sizeof(*newspp));
    331 	}
    332 
    333 	/*
    334 	 * priority found (or created).   now insert on the priority's
    335 	 * circleq list and bump the total number of swapdevs.
    336 	 */
    337 	sdp->swd_priority = priority;
    338 	CIRCLEQ_INSERT_TAIL(&spp->spi_swapdev, sdp, swd_next);
    339 	uvmexp.nswapdev++;
    340 }
    341 
    342 /*
    343  * swaplist_find: find and optionally remove a swap device from the
    344  *	global list.
    345  *
    346  * => caller must hold both swap_syscall_lock and uvm.swap_data_lock
    347  * => we return the swapdev we found (and removed)
    348  */
    349 static struct swapdev *
    350 swaplist_find(struct vnode *vp, boolean_t remove)
    351 {
    352 	struct swapdev *sdp;
    353 	struct swappri *spp;
    354 
    355 	/*
    356 	 * search the lists for the requested vp
    357 	 */
    358 
    359 	LIST_FOREACH(spp, &swap_priority, spi_swappri) {
    360 		CIRCLEQ_FOREACH(sdp, &spp->spi_swapdev, swd_next) {
    361 			if (sdp->swd_vp == vp) {
    362 				if (remove) {
    363 					CIRCLEQ_REMOVE(&spp->spi_swapdev,
    364 					    sdp, swd_next);
    365 					uvmexp.nswapdev--;
    366 				}
    367 				return(sdp);
    368 			}
    369 		}
    370 	}
    371 	return (NULL);
    372 }
    373 
    374 
    375 /*
    376  * swaplist_trim: scan priority list for empty priority entries and kill
    377  *	them.
    378  *
    379  * => caller must hold both swap_syscall_lock and uvm.swap_data_lock
    380  */
    381 static void
    382 swaplist_trim(void)
    383 {
    384 	struct swappri *spp, *nextspp;
    385 
    386 	for (spp = LIST_FIRST(&swap_priority); spp != NULL; spp = nextspp) {
    387 		nextspp = LIST_NEXT(spp, spi_swappri);
    388 		if (CIRCLEQ_FIRST(&spp->spi_swapdev) !=
    389 		    (void *)&spp->spi_swapdev)
    390 			continue;
    391 		LIST_REMOVE(spp, spi_swappri);
    392 		kmem_free(spp, sizeof(*spp));
    393 	}
    394 }
    395 
    396 /*
    397  * swapdrum_getsdp: given a page offset in /dev/drum, convert it back
    398  *	to the "swapdev" that maps that section of the drum.
    399  *
    400  * => each swapdev takes one big contig chunk of the drum
    401  * => caller must hold uvm.swap_data_lock
    402  */
    403 static struct swapdev *
    404 swapdrum_getsdp(int pgno)
    405 {
    406 	struct swapdev *sdp;
    407 	struct swappri *spp;
    408 
    409 	LIST_FOREACH(spp, &swap_priority, spi_swappri) {
    410 		CIRCLEQ_FOREACH(sdp, &spp->spi_swapdev, swd_next) {
    411 			if (sdp->swd_flags & SWF_FAKE)
    412 				continue;
    413 			if (pgno >= sdp->swd_drumoffset &&
    414 			    pgno < (sdp->swd_drumoffset + sdp->swd_drumsize)) {
    415 				return sdp;
    416 			}
    417 		}
    418 	}
    419 	return NULL;
    420 }
    421 
    422 
    423 /*
    424  * sys_swapctl: main entry point for swapctl(2) system call
    425  * 	[with two helper functions: swap_on and swap_off]
    426  */
    427 int
    428 sys_swapctl(struct lwp *l, void *v, register_t *retval)
    429 {
    430 	struct sys_swapctl_args /* {
    431 		syscallarg(int) cmd;
    432 		syscallarg(void *) arg;
    433 		syscallarg(int) misc;
    434 	} */ *uap = (struct sys_swapctl_args *)v;
    435 	struct vnode *vp;
    436 	struct nameidata nd;
    437 	struct swappri *spp;
    438 	struct swapdev *sdp;
    439 	struct swapent *sep;
    440 #define SWAP_PATH_MAX (PATH_MAX + 1)
    441 	char	*userpath;
    442 	size_t	len;
    443 	int	error, misc;
    444 	int	priority;
    445 	UVMHIST_FUNC("sys_swapctl"); UVMHIST_CALLED(pdhist);
    446 
    447 	misc = SCARG(uap, misc);
    448 
    449 	/*
    450 	 * ensure serialized syscall access by grabbing the swap_syscall_lock
    451 	 */
    452 	lockmgr(&swap_syscall_lock, LK_EXCLUSIVE, NULL);
    453 
    454 	userpath = kmem_alloc(SWAP_PATH_MAX, KM_SLEEP);
    455 	/*
    456 	 * we handle the non-priv NSWAP and STATS request first.
    457 	 *
    458 	 * SWAP_NSWAP: return number of config'd swap devices
    459 	 * [can also be obtained with uvmexp sysctl]
    460 	 */
    461 	if (SCARG(uap, cmd) == SWAP_NSWAP) {
    462 		UVMHIST_LOG(pdhist, "<- done SWAP_NSWAP=%d", uvmexp.nswapdev,
    463 		    0, 0, 0);
    464 		*retval = uvmexp.nswapdev;
    465 		error = 0;
    466 		goto out;
    467 	}
    468 
    469 	/*
    470 	 * SWAP_STATS: get stats on current # of configured swap devs
    471 	 *
    472 	 * note that the swap_priority list can't change as long
    473 	 * as we are holding the swap_syscall_lock.  we don't want
    474 	 * to grab the uvm.swap_data_lock because we may fault&sleep during
    475 	 * copyout() and we don't want to be holding that lock then!
    476 	 */
    477 	if (SCARG(uap, cmd) == SWAP_STATS
    478 #if defined(COMPAT_13)
    479 	    || SCARG(uap, cmd) == SWAP_OSTATS
    480 #endif
    481 	    ) {
    482 		if ((size_t)misc > (size_t)uvmexp.nswapdev)
    483 			misc = uvmexp.nswapdev;
    484 #if defined(COMPAT_13)
    485 		if (SCARG(uap, cmd) == SWAP_OSTATS)
    486 			len = sizeof(struct oswapent) * misc;
    487 		else
    488 #endif
    489 			len = sizeof(struct swapent) * misc;
    490 		sep = kmem_alloc(len, KM_SLEEP);
    491 
    492 		uvm_swap_stats_locked(SCARG(uap, cmd), sep, misc, retval);
    493 		error = copyout(sep, SCARG(uap, arg), len);
    494 
    495 		kmem_free(sep, len);
    496 		UVMHIST_LOG(pdhist, "<- done SWAP_STATS", 0, 0, 0, 0);
    497 		goto out;
    498 	}
    499 	if (SCARG(uap, cmd) == SWAP_GETDUMPDEV) {
    500 		dev_t	*devp = (dev_t *)SCARG(uap, arg);
    501 
    502 		error = copyout(&dumpdev, devp, sizeof(dumpdev));
    503 		goto out;
    504 	}
    505 
    506 	/*
    507 	 * all other requests require superuser privs.   verify.
    508 	 */
    509 	if ((error = kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_SWAPCTL,
    510 	    0, NULL, NULL, NULL)))
    511 		goto out;
    512 
    513 	if (SCARG(uap, cmd) == SWAP_DUMPOFF) {
    514 		/* drop the current dump device */
    515 		dumpdev = NODEV;
    516 		cpu_dumpconf();
    517 		goto out;
    518 	}
    519 
    520 	/*
    521 	 * at this point we expect a path name in arg.   we will
    522 	 * use namei() to gain a vnode reference (vref), and lock
    523 	 * the vnode (VOP_LOCK).
    524 	 *
    525 	 * XXX: a NULL arg means use the root vnode pointer (e.g. for
    526 	 * miniroot)
    527 	 */
    528 	if (SCARG(uap, arg) == NULL) {
    529 		vp = rootvp;		/* miniroot */
    530 		if (vget(vp, LK_EXCLUSIVE)) {
    531 			error = EBUSY;
    532 			goto out;
    533 		}
    534 		if (SCARG(uap, cmd) == SWAP_ON &&
    535 		    copystr("miniroot", userpath, SWAP_PATH_MAX, &len))
    536 			panic("swapctl: miniroot copy failed");
    537 	} else {
    538 		int	space;
    539 		char	*where;
    540 
    541 		if (SCARG(uap, cmd) == SWAP_ON) {
    542 			if ((error = copyinstr(SCARG(uap, arg), userpath,
    543 			    SWAP_PATH_MAX, &len)))
    544 				goto out;
    545 			space = UIO_SYSSPACE;
    546 			where = userpath;
    547 		} else {
    548 			space = UIO_USERSPACE;
    549 			where = (char *)SCARG(uap, arg);
    550 		}
    551 		NDINIT(&nd, LOOKUP, FOLLOW|LOCKLEAF, space, where, l);
    552 		if ((error = namei(&nd)))
    553 			goto out;
    554 		vp = nd.ni_vp;
    555 	}
    556 	/* note: "vp" is referenced and locked */
    557 
    558 	error = 0;		/* assume no error */
    559 	switch(SCARG(uap, cmd)) {
    560 
    561 	case SWAP_DUMPDEV:
    562 		if (vp->v_type != VBLK) {
    563 			error = ENOTBLK;
    564 			break;
    565 		}
    566 		if (bdevsw_lookup(vp->v_rdev))
    567 			dumpdev = vp->v_rdev;
    568 		else
    569 			dumpdev = NODEV;
    570 		cpu_dumpconf();
    571 		break;
    572 
    573 	case SWAP_CTL:
    574 		/*
    575 		 * get new priority, remove old entry (if any) and then
    576 		 * reinsert it in the correct place.  finally, prune out
    577 		 * any empty priority structures.
    578 		 */
    579 		priority = SCARG(uap, misc);
    580 		spp = kmem_alloc(sizeof(*spp), KM_SLEEP);
    581 		simple_lock(&uvm.swap_data_lock);
    582 		if ((sdp = swaplist_find(vp, 1)) == NULL) {
    583 			error = ENOENT;
    584 		} else {
    585 			swaplist_insert(sdp, spp, priority);
    586 			swaplist_trim();
    587 		}
    588 		simple_unlock(&uvm.swap_data_lock);
    589 		if (error)
    590 			kmem_free(spp, sizeof(*spp));
    591 		break;
    592 
    593 	case SWAP_ON:
    594 
    595 		/*
    596 		 * check for duplicates.   if none found, then insert a
    597 		 * dummy entry on the list to prevent someone else from
    598 		 * trying to enable this device while we are working on
    599 		 * it.
    600 		 */
    601 
    602 		priority = SCARG(uap, misc);
    603 		sdp = kmem_zalloc(sizeof(*sdp), KM_SLEEP);
    604 		spp = kmem_alloc(sizeof(*spp), KM_SLEEP);
    605 		sdp->swd_flags = SWF_FAKE;
    606 		sdp->swd_vp = vp;
    607 		sdp->swd_dev = (vp->v_type == VBLK) ? vp->v_rdev : NODEV;
    608 		bufq_alloc(&sdp->swd_tab, "disksort", BUFQ_SORT_RAWBLOCK);
    609 		simple_lock(&uvm.swap_data_lock);
    610 		if (swaplist_find(vp, 0) != NULL) {
    611 			error = EBUSY;
    612 			simple_unlock(&uvm.swap_data_lock);
    613 			bufq_free(sdp->swd_tab);
    614 			kmem_free(sdp, sizeof(*sdp));
    615 			kmem_free(spp, sizeof(*spp));
    616 			break;
    617 		}
    618 		swaplist_insert(sdp, spp, priority);
    619 		simple_unlock(&uvm.swap_data_lock);
    620 
    621 		sdp->swd_pathlen = len;
    622 		sdp->swd_path = kmem_alloc(len, KM_SLEEP);
    623 		if (copystr(userpath, sdp->swd_path, sdp->swd_pathlen, 0) != 0)
    624 			panic("swapctl: copystr");
    625 
    626 		/*
    627 		 * we've now got a FAKE placeholder in the swap list.
    628 		 * now attempt to enable swap on it.  if we fail, undo
    629 		 * what we've done and kill the fake entry we just inserted.
    630 		 * if swap_on is a success, it will clear the SWF_FAKE flag
    631 		 */
    632 
    633 		if ((error = swap_on(l, sdp)) != 0) {
    634 			simple_lock(&uvm.swap_data_lock);
    635 			(void) swaplist_find(vp, 1);  /* kill fake entry */
    636 			swaplist_trim();
    637 			simple_unlock(&uvm.swap_data_lock);
    638 			bufq_free(sdp->swd_tab);
    639 			kmem_free(sdp->swd_path, sdp->swd_pathlen);
    640 			kmem_free(sdp, sizeof(*sdp));
    641 			break;
    642 		}
    643 		break;
    644 
    645 	case SWAP_OFF:
    646 		simple_lock(&uvm.swap_data_lock);
    647 		if ((sdp = swaplist_find(vp, 0)) == NULL) {
    648 			simple_unlock(&uvm.swap_data_lock);
    649 			error = ENXIO;
    650 			break;
    651 		}
    652 
    653 		/*
    654 		 * If a device isn't in use or enabled, we
    655 		 * can't stop swapping from it (again).
    656 		 */
    657 		if ((sdp->swd_flags & (SWF_INUSE|SWF_ENABLE)) == 0) {
    658 			simple_unlock(&uvm.swap_data_lock);
    659 			error = EBUSY;
    660 			break;
    661 		}
    662 
    663 		/*
    664 		 * do the real work.
    665 		 */
    666 		error = swap_off(l, sdp);
    667 		break;
    668 
    669 	default:
    670 		error = EINVAL;
    671 	}
    672 
    673 	/*
    674 	 * done!  release the ref gained by namei() and unlock.
    675 	 */
    676 	vput(vp);
    677 
    678 out:
    679 	kmem_free(userpath, SWAP_PATH_MAX);
    680 	lockmgr(&swap_syscall_lock, LK_RELEASE, NULL);
    681 
    682 	UVMHIST_LOG(pdhist, "<- done!  error=%d", error, 0, 0, 0);
    683 	return (error);
    684 }
    685 
    686 /*
    687  * swap_stats: implements swapctl(SWAP_STATS). The function is kept
    688  * away from sys_swapctl() in order to allow COMPAT_* swapctl()
    689  * emulation to use it directly without going through sys_swapctl().
    690  * The problem with using sys_swapctl() there is that it involves
    691  * copying the swapent array to the stackgap, and this array's size
    692  * is not known at build time. Hence it would not be possible to
    693  * ensure it would fit in the stackgap in any case.
    694  */
    695 void
    696 uvm_swap_stats(int cmd, struct swapent *sep, int sec, register_t *retval)
    697 {
    698 
    699 	lockmgr(&swap_syscall_lock, LK_EXCLUSIVE, NULL);
    700 	uvm_swap_stats_locked(cmd, sep, sec, retval);
    701 	lockmgr(&swap_syscall_lock, LK_RELEASE, NULL);
    702 }
    703 
    704 static void
    705 uvm_swap_stats_locked(int cmd, struct swapent *sep, int sec, register_t *retval)
    706 {
    707 	struct swappri *spp;
    708 	struct swapdev *sdp;
    709 	int count = 0;
    710 
    711 	LIST_FOREACH(spp, &swap_priority, spi_swappri) {
    712 		for (sdp = CIRCLEQ_FIRST(&spp->spi_swapdev);
    713 		     sdp != (void *)&spp->spi_swapdev && sec-- > 0;
    714 		     sdp = CIRCLEQ_NEXT(sdp, swd_next)) {
    715 		  	/*
    716 			 * backwards compatibility for system call.
    717 			 * note that we use 'struct oswapent' as an
    718 			 * overlay into both 'struct swapdev' and
    719 			 * the userland 'struct swapent', as we
    720 			 * want to retain backwards compatibility
    721 			 * with NetBSD 1.3.
    722 			 */
    723 			sdp->swd_ose.ose_inuse =
    724 			    btodb((uint64_t)sdp->swd_npginuse <<
    725 			    PAGE_SHIFT);
    726 			(void)memcpy(sep, &sdp->swd_ose,
    727 			    sizeof(struct oswapent));
    728 
    729 			/* now copy out the path if necessary */
    730 #if !defined(COMPAT_13)
    731 			(void) cmd;
    732 #endif
    733 #if defined(COMPAT_13)
    734 			if (cmd == SWAP_STATS)
    735 #endif
    736 				(void)memcpy(&sep->se_path, sdp->swd_path,
    737 				    sdp->swd_pathlen);
    738 
    739 			count++;
    740 #if defined(COMPAT_13)
    741 			if (cmd == SWAP_OSTATS)
    742 				sep = (struct swapent *)
    743 				    ((struct oswapent *)sep + 1);
    744 			else
    745 #endif
    746 				sep++;
    747 		}
    748 	}
    749 
    750 	*retval = count;
    751 	return;
    752 }
    753 
    754 /*
    755  * swap_on: attempt to enable a swapdev for swapping.   note that the
    756  *	swapdev is already on the global list, but disabled (marked
    757  *	SWF_FAKE).
    758  *
    759  * => we avoid the start of the disk (to protect disk labels)
    760  * => we also avoid the miniroot, if we are swapping to root.
    761  * => caller should leave uvm.swap_data_lock unlocked, we may lock it
    762  *	if needed.
    763  */
    764 static int
    765 swap_on(struct lwp *l, struct swapdev *sdp)
    766 {
    767 	struct vnode *vp;
    768 	int error, npages, nblocks, size;
    769 	long addr;
    770 	u_long result;
    771 	struct vattr va;
    772 #ifdef NFS
    773 	extern int (**nfsv2_vnodeop_p)(void *);
    774 #endif /* NFS */
    775 	const struct bdevsw *bdev;
    776 	dev_t dev;
    777 	UVMHIST_FUNC("swap_on"); UVMHIST_CALLED(pdhist);
    778 
    779 	/*
    780 	 * we want to enable swapping on sdp.   the swd_vp contains
    781 	 * the vnode we want (locked and ref'd), and the swd_dev
    782 	 * contains the dev_t of the file, if it a block device.
    783 	 */
    784 
    785 	vp = sdp->swd_vp;
    786 	dev = sdp->swd_dev;
    787 
    788 	/*
    789 	 * open the swap file (mostly useful for block device files to
    790 	 * let device driver know what is up).
    791 	 *
    792 	 * we skip the open/close for root on swap because the root
    793 	 * has already been opened when root was mounted (mountroot).
    794 	 */
    795 	if (vp != rootvp) {
    796 		if ((error = VOP_OPEN(vp, FREAD|FWRITE, l->l_cred, l)))
    797 			return (error);
    798 	}
    799 
    800 	/* XXX this only works for block devices */
    801 	UVMHIST_LOG(pdhist, "  dev=%d, major(dev)=%d", dev, major(dev), 0,0);
    802 
    803 	/*
    804 	 * we now need to determine the size of the swap area.   for
    805 	 * block specials we can call the d_psize function.
    806 	 * for normal files, we must stat [get attrs].
    807 	 *
    808 	 * we put the result in nblks.
    809 	 * for normal files, we also want the filesystem block size
    810 	 * (which we get with statfs).
    811 	 */
    812 	switch (vp->v_type) {
    813 	case VBLK:
    814 		bdev = bdevsw_lookup(dev);
    815 		if (bdev == NULL || bdev->d_psize == NULL ||
    816 		    (nblocks = (*bdev->d_psize)(dev)) == -1) {
    817 			error = ENXIO;
    818 			goto bad;
    819 		}
    820 		break;
    821 
    822 	case VREG:
    823 		if ((error = VOP_GETATTR(vp, &va, l->l_cred, l)))
    824 			goto bad;
    825 		nblocks = (int)btodb(va.va_size);
    826 		if ((error =
    827 		     VFS_STATVFS(vp->v_mount, &vp->v_mount->mnt_stat, l)) != 0)
    828 			goto bad;
    829 
    830 		sdp->swd_bsize = vp->v_mount->mnt_stat.f_iosize;
    831 		/*
    832 		 * limit the max # of outstanding I/O requests we issue
    833 		 * at any one time.   take it easy on NFS servers.
    834 		 */
    835 #ifdef NFS
    836 		if (vp->v_op == nfsv2_vnodeop_p)
    837 			sdp->swd_maxactive = 2; /* XXX */
    838 		else
    839 #endif /* NFS */
    840 			sdp->swd_maxactive = 8; /* XXX */
    841 		break;
    842 
    843 	default:
    844 		error = ENXIO;
    845 		goto bad;
    846 	}
    847 
    848 	/*
    849 	 * save nblocks in a safe place and convert to pages.
    850 	 */
    851 
    852 	sdp->swd_ose.ose_nblks = nblocks;
    853 	npages = dbtob((uint64_t)nblocks) >> PAGE_SHIFT;
    854 
    855 	/*
    856 	 * for block special files, we want to make sure that leave
    857 	 * the disklabel and bootblocks alone, so we arrange to skip
    858 	 * over them (arbitrarily choosing to skip PAGE_SIZE bytes).
    859 	 * note that because of this the "size" can be less than the
    860 	 * actual number of blocks on the device.
    861 	 */
    862 	if (vp->v_type == VBLK) {
    863 		/* we use pages 1 to (size - 1) [inclusive] */
    864 		size = npages - 1;
    865 		addr = 1;
    866 	} else {
    867 		/* we use pages 0 to (size - 1) [inclusive] */
    868 		size = npages;
    869 		addr = 0;
    870 	}
    871 
    872 	/*
    873 	 * make sure we have enough blocks for a reasonable sized swap
    874 	 * area.   we want at least one page.
    875 	 */
    876 
    877 	if (size < 1) {
    878 		UVMHIST_LOG(pdhist, "  size <= 1!!", 0, 0, 0, 0);
    879 		error = EINVAL;
    880 		goto bad;
    881 	}
    882 
    883 	UVMHIST_LOG(pdhist, "  dev=%x: size=%d addr=%ld\n", dev, size, addr, 0);
    884 
    885 	/*
    886 	 * now we need to allocate an extent to manage this swap device
    887 	 */
    888 
    889 	sdp->swd_blist = blist_create(npages);
    890 	/* mark all expect the `saved' region free. */
    891 	blist_free(sdp->swd_blist, addr, size);
    892 
    893 	/*
    894 	 * if the vnode we are swapping to is the root vnode
    895 	 * (i.e. we are swapping to the miniroot) then we want
    896 	 * to make sure we don't overwrite it.   do a statfs to
    897 	 * find its size and skip over it.
    898 	 */
    899 	if (vp == rootvp) {
    900 		struct mount *mp;
    901 		struct statvfs *sp;
    902 		int rootblocks, rootpages;
    903 
    904 		mp = rootvnode->v_mount;
    905 		sp = &mp->mnt_stat;
    906 		rootblocks = sp->f_blocks * btodb(sp->f_frsize);
    907 		/*
    908 		 * XXX: sp->f_blocks isn't the total number of
    909 		 * blocks in the filesystem, it's the number of
    910 		 * data blocks.  so, our rootblocks almost
    911 		 * definitely underestimates the total size
    912 		 * of the filesystem - how badly depends on the
    913 		 * details of the filesystem type.  there isn't
    914 		 * an obvious way to deal with this cleanly
    915 		 * and perfectly, so for now we just pad our
    916 		 * rootblocks estimate with an extra 5 percent.
    917 		 */
    918 		rootblocks += (rootblocks >> 5) +
    919 			(rootblocks >> 6) +
    920 			(rootblocks >> 7);
    921 		rootpages = round_page(dbtob(rootblocks)) >> PAGE_SHIFT;
    922 		if (rootpages > size)
    923 			panic("swap_on: miniroot larger than swap?");
    924 
    925 		if (rootpages != blist_fill(sdp->swd_blist, addr, rootpages)) {
    926 			panic("swap_on: unable to preserve miniroot");
    927 		}
    928 
    929 		size -= rootpages;
    930 		printf("Preserved %d pages of miniroot ", rootpages);
    931 		printf("leaving %d pages of swap\n", size);
    932 	}
    933 
    934 	/*
    935 	 * add a ref to vp to reflect usage as a swap device.
    936 	 */
    937 	vref(vp);
    938 
    939 	/*
    940 	 * now add the new swapdev to the drum and enable.
    941 	 */
    942 	result = vmem_alloc(swapmap, npages, VM_BESTFIT | VM_SLEEP);
    943 	if (result == 0)
    944 		panic("swapdrum_add");
    945 
    946 	sdp->swd_drumoffset = (int)result;
    947 	sdp->swd_drumsize = npages;
    948 	sdp->swd_npages = size;
    949 	simple_lock(&uvm.swap_data_lock);
    950 	sdp->swd_flags &= ~SWF_FAKE;	/* going live */
    951 	sdp->swd_flags |= (SWF_INUSE|SWF_ENABLE);
    952 	uvmexp.swpages += size;
    953 	uvmexp.swpgavail += size;
    954 	simple_unlock(&uvm.swap_data_lock);
    955 	return (0);
    956 
    957 	/*
    958 	 * failure: clean up and return error.
    959 	 */
    960 
    961 bad:
    962 	if (sdp->swd_blist) {
    963 		blist_destroy(sdp->swd_blist);
    964 	}
    965 	if (vp != rootvp) {
    966 		(void)VOP_CLOSE(vp, FREAD|FWRITE, l->l_cred, l);
    967 	}
    968 	return (error);
    969 }
    970 
    971 /*
    972  * swap_off: stop swapping on swapdev
    973  *
    974  * => swap data should be locked, we will unlock.
    975  */
    976 static int
    977 swap_off(struct lwp *l, struct swapdev *sdp)
    978 {
    979 	int npages = sdp->swd_npages;
    980 	int error = 0;
    981 
    982 	UVMHIST_FUNC("swap_off"); UVMHIST_CALLED(pdhist);
    983 	UVMHIST_LOG(pdhist, "  dev=%x, npages=%d", sdp->swd_dev,npages,0,0);
    984 
    985 	/* disable the swap area being removed */
    986 	sdp->swd_flags &= ~SWF_ENABLE;
    987 	uvmexp.swpgavail -= npages;
    988 	simple_unlock(&uvm.swap_data_lock);
    989 
    990 	/*
    991 	 * the idea is to find all the pages that are paged out to this
    992 	 * device, and page them all in.  in uvm, swap-backed pageable
    993 	 * memory can take two forms: aobjs and anons.  call the
    994 	 * swapoff hook for each subsystem to bring in pages.
    995 	 */
    996 
    997 	if (uao_swap_off(sdp->swd_drumoffset,
    998 			 sdp->swd_drumoffset + sdp->swd_drumsize) ||
    999 	    amap_swap_off(sdp->swd_drumoffset,
   1000 			  sdp->swd_drumoffset + sdp->swd_drumsize)) {
   1001 		error = ENOMEM;
   1002 	} else if (sdp->swd_npginuse > sdp->swd_npgbad) {
   1003 		error = EBUSY;
   1004 	}
   1005 
   1006 	if (error) {
   1007 		simple_lock(&uvm.swap_data_lock);
   1008 		sdp->swd_flags |= SWF_ENABLE;
   1009 		uvmexp.swpgavail += npages;
   1010 		simple_unlock(&uvm.swap_data_lock);
   1011 
   1012 		return error;
   1013 	}
   1014 
   1015 	/*
   1016 	 * done with the vnode.
   1017 	 * drop our ref on the vnode before calling VOP_CLOSE()
   1018 	 * so that spec_close() can tell if this is the last close.
   1019 	 */
   1020 	vrele(sdp->swd_vp);
   1021 	if (sdp->swd_vp != rootvp) {
   1022 		(void) VOP_CLOSE(sdp->swd_vp, FREAD|FWRITE, l->l_cred, l);
   1023 	}
   1024 
   1025 	simple_lock(&uvm.swap_data_lock);
   1026 	uvmexp.swpages -= npages;
   1027 	uvmexp.swpginuse -= sdp->swd_npgbad;
   1028 
   1029 	if (swaplist_find(sdp->swd_vp, 1) == NULL)
   1030 		panic("swap_off: swapdev not in list");
   1031 	swaplist_trim();
   1032 	simple_unlock(&uvm.swap_data_lock);
   1033 
   1034 	/*
   1035 	 * free all resources!
   1036 	 */
   1037 	vmem_free(swapmap, sdp->swd_drumoffset, sdp->swd_drumsize);
   1038 	blist_destroy(sdp->swd_blist);
   1039 	bufq_free(sdp->swd_tab);
   1040 	kmem_free(sdp, sizeof(*sdp));
   1041 	return (0);
   1042 }
   1043 
   1044 /*
   1045  * /dev/drum interface and i/o functions
   1046  */
   1047 
   1048 /*
   1049  * swstrategy: perform I/O on the drum
   1050  *
   1051  * => we must map the i/o request from the drum to the correct swapdev.
   1052  */
   1053 static void
   1054 swstrategy(struct buf *bp)
   1055 {
   1056 	struct swapdev *sdp;
   1057 	struct vnode *vp;
   1058 	int s, pageno, bn;
   1059 	UVMHIST_FUNC("swstrategy"); UVMHIST_CALLED(pdhist);
   1060 
   1061 	/*
   1062 	 * convert block number to swapdev.   note that swapdev can't
   1063 	 * be yanked out from under us because we are holding resources
   1064 	 * in it (i.e. the blocks we are doing I/O on).
   1065 	 */
   1066 	pageno = dbtob((int64_t)bp->b_blkno) >> PAGE_SHIFT;
   1067 	simple_lock(&uvm.swap_data_lock);
   1068 	sdp = swapdrum_getsdp(pageno);
   1069 	simple_unlock(&uvm.swap_data_lock);
   1070 	if (sdp == NULL) {
   1071 		bp->b_error = EINVAL;
   1072 		bp->b_flags |= B_ERROR;
   1073 		biodone(bp);
   1074 		UVMHIST_LOG(pdhist, "  failed to get swap device", 0, 0, 0, 0);
   1075 		return;
   1076 	}
   1077 
   1078 	/*
   1079 	 * convert drum page number to block number on this swapdev.
   1080 	 */
   1081 
   1082 	pageno -= sdp->swd_drumoffset;	/* page # on swapdev */
   1083 	bn = btodb((uint64_t)pageno << PAGE_SHIFT); /* convert to diskblock */
   1084 
   1085 	UVMHIST_LOG(pdhist, "  %s: mapoff=%x bn=%x bcount=%ld",
   1086 		((bp->b_flags & B_READ) == 0) ? "write" : "read",
   1087 		sdp->swd_drumoffset, bn, bp->b_bcount);
   1088 
   1089 	/*
   1090 	 * for block devices we finish up here.
   1091 	 * for regular files we have to do more work which we delegate
   1092 	 * to sw_reg_strategy().
   1093 	 */
   1094 
   1095 	switch (sdp->swd_vp->v_type) {
   1096 	default:
   1097 		panic("swstrategy: vnode type 0x%x", sdp->swd_vp->v_type);
   1098 
   1099 	case VBLK:
   1100 
   1101 		/*
   1102 		 * must convert "bp" from an I/O on /dev/drum to an I/O
   1103 		 * on the swapdev (sdp).
   1104 		 */
   1105 		s = splbio();
   1106 		bp->b_blkno = bn;		/* swapdev block number */
   1107 		vp = sdp->swd_vp;		/* swapdev vnode pointer */
   1108 		bp->b_dev = sdp->swd_dev;	/* swapdev dev_t */
   1109 
   1110 		/*
   1111 		 * if we are doing a write, we have to redirect the i/o on
   1112 		 * drum's v_numoutput counter to the swapdevs.
   1113 		 */
   1114 		if ((bp->b_flags & B_READ) == 0) {
   1115 			vwakeup(bp);	/* kills one 'v_numoutput' on drum */
   1116 			V_INCR_NUMOUTPUT(vp);	/* put it on swapdev */
   1117 		}
   1118 
   1119 		/*
   1120 		 * finally plug in swapdev vnode and start I/O
   1121 		 */
   1122 		bp->b_vp = vp;
   1123 		splx(s);
   1124 		VOP_STRATEGY(vp, bp);
   1125 		return;
   1126 
   1127 	case VREG:
   1128 		/*
   1129 		 * delegate to sw_reg_strategy function.
   1130 		 */
   1131 		sw_reg_strategy(sdp, bp, bn);
   1132 		return;
   1133 	}
   1134 	/* NOTREACHED */
   1135 }
   1136 
   1137 /*
   1138  * swread: the read function for the drum (just a call to physio)
   1139  */
   1140 /*ARGSUSED*/
   1141 static int
   1142 swread(dev_t dev, struct uio *uio, int ioflag __unused)
   1143 {
   1144 	UVMHIST_FUNC("swread"); UVMHIST_CALLED(pdhist);
   1145 
   1146 	UVMHIST_LOG(pdhist, "  dev=%x offset=%qx", dev, uio->uio_offset, 0, 0);
   1147 	return (physio(swstrategy, NULL, dev, B_READ, minphys, uio));
   1148 }
   1149 
   1150 /*
   1151  * swwrite: the write function for the drum (just a call to physio)
   1152  */
   1153 /*ARGSUSED*/
   1154 static int
   1155 swwrite(dev_t dev, struct uio *uio, int ioflag __unused)
   1156 {
   1157 	UVMHIST_FUNC("swwrite"); UVMHIST_CALLED(pdhist);
   1158 
   1159 	UVMHIST_LOG(pdhist, "  dev=%x offset=%qx", dev, uio->uio_offset, 0, 0);
   1160 	return (physio(swstrategy, NULL, dev, B_WRITE, minphys, uio));
   1161 }
   1162 
   1163 const struct bdevsw swap_bdevsw = {
   1164 	noopen, noclose, swstrategy, noioctl, nodump, nosize, D_OTHER,
   1165 };
   1166 
   1167 const struct cdevsw swap_cdevsw = {
   1168 	nullopen, nullclose, swread, swwrite, noioctl,
   1169 	nostop, notty, nopoll, nommap, nokqfilter, D_OTHER,
   1170 };
   1171 
   1172 /*
   1173  * sw_reg_strategy: handle swap i/o to regular files
   1174  */
   1175 static void
   1176 sw_reg_strategy(struct swapdev *sdp, struct buf *bp, int bn)
   1177 {
   1178 	struct vnode	*vp;
   1179 	struct vndxfer	*vnx;
   1180 	daddr_t		nbn;
   1181 	caddr_t		addr;
   1182 	off_t		byteoff;
   1183 	int		s, off, nra, error, sz, resid;
   1184 	UVMHIST_FUNC("sw_reg_strategy"); UVMHIST_CALLED(pdhist);
   1185 
   1186 	/*
   1187 	 * allocate a vndxfer head for this transfer and point it to
   1188 	 * our buffer.
   1189 	 */
   1190 	getvndxfer(vnx);
   1191 	vnx->vx_flags = VX_BUSY;
   1192 	vnx->vx_error = 0;
   1193 	vnx->vx_pending = 0;
   1194 	vnx->vx_bp = bp;
   1195 	vnx->vx_sdp = sdp;
   1196 
   1197 	/*
   1198 	 * setup for main loop where we read filesystem blocks into
   1199 	 * our buffer.
   1200 	 */
   1201 	error = 0;
   1202 	bp->b_resid = bp->b_bcount;	/* nothing transfered yet! */
   1203 	addr = bp->b_data;		/* current position in buffer */
   1204 	byteoff = dbtob((uint64_t)bn);
   1205 
   1206 	for (resid = bp->b_resid; resid; resid -= sz) {
   1207 		struct vndbuf	*nbp;
   1208 
   1209 		/*
   1210 		 * translate byteoffset into block number.  return values:
   1211 		 *   vp = vnode of underlying device
   1212 		 *  nbn = new block number (on underlying vnode dev)
   1213 		 *  nra = num blocks we can read-ahead (excludes requested
   1214 		 *	block)
   1215 		 */
   1216 		nra = 0;
   1217 		error = VOP_BMAP(sdp->swd_vp, byteoff / sdp->swd_bsize,
   1218 				 	&vp, &nbn, &nra);
   1219 
   1220 		if (error == 0 && nbn == (daddr_t)-1) {
   1221 			/*
   1222 			 * this used to just set error, but that doesn't
   1223 			 * do the right thing.  Instead, it causes random
   1224 			 * memory errors.  The panic() should remain until
   1225 			 * this condition doesn't destabilize the system.
   1226 			 */
   1227 #if 1
   1228 			panic("sw_reg_strategy: swap to sparse file");
   1229 #else
   1230 			error = EIO;	/* failure */
   1231 #endif
   1232 		}
   1233 
   1234 		/*
   1235 		 * punt if there was an error or a hole in the file.
   1236 		 * we must wait for any i/o ops we have already started
   1237 		 * to finish before returning.
   1238 		 *
   1239 		 * XXX we could deal with holes here but it would be
   1240 		 * a hassle (in the write case).
   1241 		 */
   1242 		if (error) {
   1243 			s = splbio();
   1244 			vnx->vx_error = error;	/* pass error up */
   1245 			goto out;
   1246 		}
   1247 
   1248 		/*
   1249 		 * compute the size ("sz") of this transfer (in bytes).
   1250 		 */
   1251 		off = byteoff % sdp->swd_bsize;
   1252 		sz = (1 + nra) * sdp->swd_bsize - off;
   1253 		if (sz > resid)
   1254 			sz = resid;
   1255 
   1256 		UVMHIST_LOG(pdhist, "sw_reg_strategy: "
   1257 			    "vp %p/%p offset 0x%x/0x%x",
   1258 			    sdp->swd_vp, vp, byteoff, nbn);
   1259 
   1260 		/*
   1261 		 * now get a buf structure.   note that the vb_buf is
   1262 		 * at the front of the nbp structure so that you can
   1263 		 * cast pointers between the two structure easily.
   1264 		 */
   1265 		getvndbuf(nbp);
   1266 		BUF_INIT(&nbp->vb_buf);
   1267 		nbp->vb_buf.b_flags    = bp->b_flags | B_CALL;
   1268 		nbp->vb_buf.b_bcount   = sz;
   1269 		nbp->vb_buf.b_bufsize  = sz;
   1270 		nbp->vb_buf.b_error    = 0;
   1271 		nbp->vb_buf.b_data     = addr;
   1272 		nbp->vb_buf.b_lblkno   = 0;
   1273 		nbp->vb_buf.b_blkno    = nbn + btodb(off);
   1274 		nbp->vb_buf.b_rawblkno = nbp->vb_buf.b_blkno;
   1275 		nbp->vb_buf.b_iodone   = sw_reg_iodone;
   1276 		nbp->vb_buf.b_vp       = vp;
   1277 		if (vp->v_type == VBLK) {
   1278 			nbp->vb_buf.b_dev = vp->v_rdev;
   1279 		}
   1280 
   1281 		nbp->vb_xfer = vnx;	/* patch it back in to vnx */
   1282 
   1283 		/*
   1284 		 * Just sort by block number
   1285 		 */
   1286 		s = splbio();
   1287 		if (vnx->vx_error != 0) {
   1288 			putvndbuf(nbp);
   1289 			goto out;
   1290 		}
   1291 		vnx->vx_pending++;
   1292 
   1293 		/* sort it in and start I/O if we are not over our limit */
   1294 		BUFQ_PUT(sdp->swd_tab, &nbp->vb_buf);
   1295 		sw_reg_start(sdp);
   1296 		splx(s);
   1297 
   1298 		/*
   1299 		 * advance to the next I/O
   1300 		 */
   1301 		byteoff += sz;
   1302 		addr += sz;
   1303 	}
   1304 
   1305 	s = splbio();
   1306 
   1307 out: /* Arrive here at splbio */
   1308 	vnx->vx_flags &= ~VX_BUSY;
   1309 	if (vnx->vx_pending == 0) {
   1310 		if (vnx->vx_error != 0) {
   1311 			bp->b_error = vnx->vx_error;
   1312 			bp->b_flags |= B_ERROR;
   1313 		}
   1314 		putvndxfer(vnx);
   1315 		biodone(bp);
   1316 	}
   1317 	splx(s);
   1318 }
   1319 
   1320 /*
   1321  * sw_reg_start: start an I/O request on the requested swapdev
   1322  *
   1323  * => reqs are sorted by b_rawblkno (above)
   1324  */
   1325 static void
   1326 sw_reg_start(struct swapdev *sdp)
   1327 {
   1328 	struct buf	*bp;
   1329 	UVMHIST_FUNC("sw_reg_start"); UVMHIST_CALLED(pdhist);
   1330 
   1331 	/* recursion control */
   1332 	if ((sdp->swd_flags & SWF_BUSY) != 0)
   1333 		return;
   1334 
   1335 	sdp->swd_flags |= SWF_BUSY;
   1336 
   1337 	while (sdp->swd_active < sdp->swd_maxactive) {
   1338 		bp = BUFQ_GET(sdp->swd_tab);
   1339 		if (bp == NULL)
   1340 			break;
   1341 		sdp->swd_active++;
   1342 
   1343 		UVMHIST_LOG(pdhist,
   1344 		    "sw_reg_start:  bp %p vp %p blkno %p cnt %lx",
   1345 		    bp, bp->b_vp, bp->b_blkno, bp->b_bcount);
   1346 		if ((bp->b_flags & B_READ) == 0)
   1347 			V_INCR_NUMOUTPUT(bp->b_vp);
   1348 
   1349 		VOP_STRATEGY(bp->b_vp, bp);
   1350 	}
   1351 	sdp->swd_flags &= ~SWF_BUSY;
   1352 }
   1353 
   1354 /*
   1355  * sw_reg_iodone: one of our i/o's has completed and needs post-i/o cleanup
   1356  *
   1357  * => note that we can recover the vndbuf struct by casting the buf ptr
   1358  */
   1359 static void
   1360 sw_reg_iodone(struct buf *bp)
   1361 {
   1362 	struct vndbuf *vbp = (struct vndbuf *) bp;
   1363 	struct vndxfer *vnx = vbp->vb_xfer;
   1364 	struct buf *pbp = vnx->vx_bp;		/* parent buffer */
   1365 	struct swapdev	*sdp = vnx->vx_sdp;
   1366 	int s, resid, error;
   1367 	UVMHIST_FUNC("sw_reg_iodone"); UVMHIST_CALLED(pdhist);
   1368 
   1369 	UVMHIST_LOG(pdhist, "  vbp=%p vp=%p blkno=%x addr=%p",
   1370 	    vbp, vbp->vb_buf.b_vp, vbp->vb_buf.b_blkno, vbp->vb_buf.b_data);
   1371 	UVMHIST_LOG(pdhist, "  cnt=%lx resid=%lx",
   1372 	    vbp->vb_buf.b_bcount, vbp->vb_buf.b_resid, 0, 0);
   1373 
   1374 	/*
   1375 	 * protect vbp at splbio and update.
   1376 	 */
   1377 
   1378 	s = splbio();
   1379 	resid = vbp->vb_buf.b_bcount - vbp->vb_buf.b_resid;
   1380 	pbp->b_resid -= resid;
   1381 	vnx->vx_pending--;
   1382 
   1383 	if (vbp->vb_buf.b_flags & B_ERROR) {
   1384 		/* pass error upward */
   1385 		error = vbp->vb_buf.b_error ? vbp->vb_buf.b_error : EIO;
   1386 		UVMHIST_LOG(pdhist, "  got error=%d !", error, 0, 0, 0);
   1387 		vnx->vx_error = error;
   1388 	}
   1389 
   1390 	/*
   1391 	 * kill vbp structure
   1392 	 */
   1393 	putvndbuf(vbp);
   1394 
   1395 	/*
   1396 	 * wrap up this transaction if it has run to completion or, in
   1397 	 * case of an error, when all auxiliary buffers have returned.
   1398 	 */
   1399 	if (vnx->vx_error != 0) {
   1400 		/* pass error upward */
   1401 		pbp->b_flags |= B_ERROR;
   1402 		pbp->b_error = vnx->vx_error;
   1403 		if ((vnx->vx_flags & VX_BUSY) == 0 && vnx->vx_pending == 0) {
   1404 			putvndxfer(vnx);
   1405 			biodone(pbp);
   1406 		}
   1407 	} else if (pbp->b_resid == 0) {
   1408 		KASSERT(vnx->vx_pending == 0);
   1409 		if ((vnx->vx_flags & VX_BUSY) == 0) {
   1410 			UVMHIST_LOG(pdhist, "  iodone error=%d !",
   1411 			    pbp, vnx->vx_error, 0, 0);
   1412 			putvndxfer(vnx);
   1413 			biodone(pbp);
   1414 		}
   1415 	}
   1416 
   1417 	/*
   1418 	 * done!   start next swapdev I/O if one is pending
   1419 	 */
   1420 	sdp->swd_active--;
   1421 	sw_reg_start(sdp);
   1422 	splx(s);
   1423 }
   1424 
   1425 
   1426 /*
   1427  * uvm_swap_alloc: allocate space on swap
   1428  *
   1429  * => allocation is done "round robin" down the priority list, as we
   1430  *	allocate in a priority we "rotate" the circle queue.
   1431  * => space can be freed with uvm_swap_free
   1432  * => we return the page slot number in /dev/drum (0 == invalid slot)
   1433  * => we lock uvm.swap_data_lock
   1434  * => XXXMRG: "LESSOK" INTERFACE NEEDED TO EXTENT SYSTEM
   1435  */
   1436 int
   1437 uvm_swap_alloc(int *nslots /* IN/OUT */, boolean_t lessok)
   1438 {
   1439 	struct swapdev *sdp;
   1440 	struct swappri *spp;
   1441 	UVMHIST_FUNC("uvm_swap_alloc"); UVMHIST_CALLED(pdhist);
   1442 
   1443 	/*
   1444 	 * no swap devices configured yet?   definite failure.
   1445 	 */
   1446 	if (uvmexp.nswapdev < 1)
   1447 		return 0;
   1448 
   1449 	/*
   1450 	 * lock data lock, convert slots into blocks, and enter loop
   1451 	 */
   1452 	simple_lock(&uvm.swap_data_lock);
   1453 
   1454 ReTry:	/* XXXMRG */
   1455 	LIST_FOREACH(spp, &swap_priority, spi_swappri) {
   1456 		CIRCLEQ_FOREACH(sdp, &spp->spi_swapdev, swd_next) {
   1457 			uint64_t result;
   1458 
   1459 			/* if it's not enabled, then we can't swap from it */
   1460 			if ((sdp->swd_flags & SWF_ENABLE) == 0)
   1461 				continue;
   1462 			if (sdp->swd_npginuse + *nslots > sdp->swd_npages)
   1463 				continue;
   1464 			result = blist_alloc(sdp->swd_blist, *nslots);
   1465 			if (result == BLIST_NONE) {
   1466 				continue;
   1467 			}
   1468 			KASSERT(result < sdp->swd_drumsize);
   1469 
   1470 			/*
   1471 			 * successful allocation!  now rotate the circleq.
   1472 			 */
   1473 			CIRCLEQ_REMOVE(&spp->spi_swapdev, sdp, swd_next);
   1474 			CIRCLEQ_INSERT_TAIL(&spp->spi_swapdev, sdp, swd_next);
   1475 			sdp->swd_npginuse += *nslots;
   1476 			uvmexp.swpginuse += *nslots;
   1477 			simple_unlock(&uvm.swap_data_lock);
   1478 			/* done!  return drum slot number */
   1479 			UVMHIST_LOG(pdhist,
   1480 			    "success!  returning %d slots starting at %d",
   1481 			    *nslots, result + sdp->swd_drumoffset, 0, 0);
   1482 			return (result + sdp->swd_drumoffset);
   1483 		}
   1484 	}
   1485 
   1486 	/* XXXMRG: BEGIN HACK */
   1487 	if (*nslots > 1 && lessok) {
   1488 		*nslots = 1;
   1489 		/* XXXMRG: ugh!  blist should support this for us */
   1490 		goto ReTry;
   1491 	}
   1492 	/* XXXMRG: END HACK */
   1493 
   1494 	simple_unlock(&uvm.swap_data_lock);
   1495 	return 0;
   1496 }
   1497 
   1498 boolean_t
   1499 uvm_swapisfull(void)
   1500 {
   1501 	boolean_t rv;
   1502 
   1503 	simple_lock(&uvm.swap_data_lock);
   1504 	KASSERT(uvmexp.swpgonly <= uvmexp.swpages);
   1505 	rv = (uvmexp.swpgonly >= uvmexp.swpgavail);
   1506 	simple_unlock(&uvm.swap_data_lock);
   1507 
   1508 	return (rv);
   1509 }
   1510 
   1511 /*
   1512  * uvm_swap_markbad: keep track of swap ranges where we've had i/o errors
   1513  *
   1514  * => we lock uvm.swap_data_lock
   1515  */
   1516 void
   1517 uvm_swap_markbad(int startslot, int nslots)
   1518 {
   1519 	struct swapdev *sdp;
   1520 	UVMHIST_FUNC("uvm_swap_markbad"); UVMHIST_CALLED(pdhist);
   1521 
   1522 	simple_lock(&uvm.swap_data_lock);
   1523 	sdp = swapdrum_getsdp(startslot);
   1524 	KASSERT(sdp != NULL);
   1525 
   1526 	/*
   1527 	 * we just keep track of how many pages have been marked bad
   1528 	 * in this device, to make everything add up in swap_off().
   1529 	 * we assume here that the range of slots will all be within
   1530 	 * one swap device.
   1531 	 */
   1532 
   1533 	KASSERT(uvmexp.swpgonly >= nslots);
   1534 	uvmexp.swpgonly -= nslots;
   1535 	sdp->swd_npgbad += nslots;
   1536 	UVMHIST_LOG(pdhist, "now %d bad", sdp->swd_npgbad, 0,0,0);
   1537 	simple_unlock(&uvm.swap_data_lock);
   1538 }
   1539 
   1540 /*
   1541  * uvm_swap_free: free swap slots
   1542  *
   1543  * => this can be all or part of an allocation made by uvm_swap_alloc
   1544  * => we lock uvm.swap_data_lock
   1545  */
   1546 void
   1547 uvm_swap_free(int startslot, int nslots)
   1548 {
   1549 	struct swapdev *sdp;
   1550 	UVMHIST_FUNC("uvm_swap_free"); UVMHIST_CALLED(pdhist);
   1551 
   1552 	UVMHIST_LOG(pdhist, "freeing %d slots starting at %d", nslots,
   1553 	    startslot, 0, 0);
   1554 
   1555 	/*
   1556 	 * ignore attempts to free the "bad" slot.
   1557 	 */
   1558 
   1559 	if (startslot == SWSLOT_BAD) {
   1560 		return;
   1561 	}
   1562 
   1563 	/*
   1564 	 * convert drum slot offset back to sdp, free the blocks
   1565 	 * in the extent, and return.   must hold pri lock to do
   1566 	 * lookup and access the extent.
   1567 	 */
   1568 
   1569 	simple_lock(&uvm.swap_data_lock);
   1570 	sdp = swapdrum_getsdp(startslot);
   1571 	KASSERT(uvmexp.nswapdev >= 1);
   1572 	KASSERT(sdp != NULL);
   1573 	KASSERT(sdp->swd_npginuse >= nslots);
   1574 	blist_free(sdp->swd_blist, startslot - sdp->swd_drumoffset, nslots);
   1575 	sdp->swd_npginuse -= nslots;
   1576 	uvmexp.swpginuse -= nslots;
   1577 	simple_unlock(&uvm.swap_data_lock);
   1578 }
   1579 
   1580 /*
   1581  * uvm_swap_put: put any number of pages into a contig place on swap
   1582  *
   1583  * => can be sync or async
   1584  */
   1585 
   1586 int
   1587 uvm_swap_put(int swslot, struct vm_page **ppsp, int npages, int flags)
   1588 {
   1589 	int error;
   1590 
   1591 	error = uvm_swap_io(ppsp, swslot, npages, B_WRITE |
   1592 	    ((flags & PGO_SYNCIO) ? 0 : B_ASYNC));
   1593 	return error;
   1594 }
   1595 
   1596 /*
   1597  * uvm_swap_get: get a single page from swap
   1598  *
   1599  * => usually a sync op (from fault)
   1600  */
   1601 
   1602 int
   1603 uvm_swap_get(struct vm_page *page, int swslot, int flags)
   1604 {
   1605 	int error;
   1606 
   1607 	uvmexp.nswget++;
   1608 	KASSERT(flags & PGO_SYNCIO);
   1609 	if (swslot == SWSLOT_BAD) {
   1610 		return EIO;
   1611 	}
   1612 
   1613 	error = uvm_swap_io(&page, swslot, 1, B_READ |
   1614 	    ((flags & PGO_SYNCIO) ? 0 : B_ASYNC));
   1615 	if (error == 0) {
   1616 
   1617 		/*
   1618 		 * this page is no longer only in swap.
   1619 		 */
   1620 
   1621 		simple_lock(&uvm.swap_data_lock);
   1622 		KASSERT(uvmexp.swpgonly > 0);
   1623 		uvmexp.swpgonly--;
   1624 		simple_unlock(&uvm.swap_data_lock);
   1625 	}
   1626 	return error;
   1627 }
   1628 
   1629 /*
   1630  * uvm_swap_io: do an i/o operation to swap
   1631  */
   1632 
   1633 static int
   1634 uvm_swap_io(struct vm_page **pps, int startslot, int npages, int flags)
   1635 {
   1636 	daddr_t startblk;
   1637 	struct	buf *bp;
   1638 	vaddr_t kva;
   1639 	int	error, s, mapinflags;
   1640 	boolean_t write, async;
   1641 	UVMHIST_FUNC("uvm_swap_io"); UVMHIST_CALLED(pdhist);
   1642 
   1643 	UVMHIST_LOG(pdhist, "<- called, startslot=%d, npages=%d, flags=%d",
   1644 	    startslot, npages, flags, 0);
   1645 
   1646 	write = (flags & B_READ) == 0;
   1647 	async = (flags & B_ASYNC) != 0;
   1648 
   1649 	/*
   1650 	 * convert starting drum slot to block number
   1651 	 */
   1652 
   1653 	startblk = btodb((uint64_t)startslot << PAGE_SHIFT);
   1654 
   1655 	/*
   1656 	 * first, map the pages into the kernel.
   1657 	 */
   1658 
   1659 	mapinflags = !write ?
   1660 		UVMPAGER_MAPIN_WAITOK|UVMPAGER_MAPIN_READ :
   1661 		UVMPAGER_MAPIN_WAITOK|UVMPAGER_MAPIN_WRITE;
   1662 	kva = uvm_pagermapin(pps, npages, mapinflags);
   1663 
   1664 	/*
   1665 	 * now allocate a buf for the i/o.
   1666 	 */
   1667 
   1668 	bp = getiobuf();
   1669 
   1670 	/*
   1671 	 * fill in the bp/sbp.   we currently route our i/o through
   1672 	 * /dev/drum's vnode [swapdev_vp].
   1673 	 */
   1674 
   1675 	bp->b_flags = B_BUSY | B_NOCACHE | (flags & (B_READ|B_ASYNC));
   1676 	bp->b_proc = &proc0;	/* XXX */
   1677 	bp->b_vnbufs.le_next = NOLIST;
   1678 	bp->b_data = (caddr_t)kva;
   1679 	bp->b_blkno = startblk;
   1680 	bp->b_vp = swapdev_vp;
   1681 	bp->b_bufsize = bp->b_bcount = npages << PAGE_SHIFT;
   1682 
   1683 	/*
   1684 	 * bump v_numoutput (counter of number of active outputs).
   1685 	 */
   1686 
   1687 	if (write) {
   1688 		s = splbio();
   1689 		V_INCR_NUMOUTPUT(swapdev_vp);
   1690 		splx(s);
   1691 	}
   1692 
   1693 	/*
   1694 	 * for async ops we must set up the iodone handler.
   1695 	 */
   1696 
   1697 	if (async) {
   1698 		bp->b_flags |= B_CALL;
   1699 		bp->b_iodone = uvm_aio_biodone;
   1700 		UVMHIST_LOG(pdhist, "doing async!", 0, 0, 0, 0);
   1701 		if (curproc == uvm.pagedaemon_proc)
   1702 			BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
   1703 		else
   1704 			BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
   1705 	} else {
   1706 		BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
   1707 	}
   1708 	UVMHIST_LOG(pdhist,
   1709 	    "about to start io: data = %p blkno = 0x%x, bcount = %ld",
   1710 	    bp->b_data, bp->b_blkno, bp->b_bcount, 0);
   1711 
   1712 	/*
   1713 	 * now we start the I/O, and if async, return.
   1714 	 */
   1715 
   1716 	VOP_STRATEGY(swapdev_vp, bp);
   1717 	if (async)
   1718 		return 0;
   1719 
   1720 	/*
   1721 	 * must be sync i/o.   wait for it to finish
   1722 	 */
   1723 
   1724 	error = biowait(bp);
   1725 
   1726 	/*
   1727 	 * kill the pager mapping
   1728 	 */
   1729 
   1730 	uvm_pagermapout(kva, npages);
   1731 
   1732 	/*
   1733 	 * now dispose of the buf and we're done.
   1734 	 */
   1735 
   1736 	s = splbio();
   1737 	if (write)
   1738 		vwakeup(bp);
   1739 	putiobuf(bp);
   1740 	splx(s);
   1741 	UVMHIST_LOG(pdhist, "<- done (sync)  error=%d", error, 0, 0, 0);
   1742 	return (error);
   1743 }
   1744