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