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