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