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