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