Home | History | Annotate | Line # | Download | only in uvm
      1 /*	$NetBSD: uvm_swap.c,v 1.236 2026/08/15 14:15:52 riastradh Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1995, 1996, 1997, 2009 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  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
     21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     22  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
     23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  *
     28  * from: NetBSD: vm_swap.c,v 1.52 1997/12/02 13:47:37 pk Exp
     29  * from: Id: uvm_swap.c,v 1.1.2.42 1998/02/02 20:38:06 chuck Exp
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 __KERNEL_RCSID(0, "$NetBSD: uvm_swap.c,v 1.236 2026/08/15 14:15:52 riastradh Exp $");
     34 
     35 #include "opt_uvmhist.h"
     36 #include "opt_compat_netbsd.h"
     37 #include "opt_ddb.h"
     38 #include "opt_vmswap.h"
     39 
     40 #include <sys/param.h>
     41 #include <sys/systm.h>
     42 #include <sys/atomic.h>
     43 #include <sys/buf.h>
     44 #include <sys/bufq.h>
     45 #include <sys/conf.h>
     46 #include <sys/cprng.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/vnode.h>
     53 #include <sys/file.h>
     54 #include <sys/vmem.h>
     55 #include <sys/blist.h>
     56 #include <sys/mount.h>
     57 #include <sys/pool.h>
     58 #include <sys/kmem.h>
     59 #include <sys/syscallargs.h>
     60 #include <sys/swap.h>
     61 #include <sys/kauth.h>
     62 #include <sys/sysctl.h>
     63 #include <sys/workqueue.h>
     64 
     65 #include <uvm/uvm.h>
     66 
     67 #include <miscfs/specfs/specdev.h>
     68 
     69 #ifdef VMSWAP_ENCRYPTION
     70 #include <crypto/aes/aes.h>
     71 #include <crypto/aes/aes_cbc.h>
     72 #endif /* VMSWAP_ENCRYPTION */
     73 
     74 /*
     75  * uvm_swap.c: manage configuration and i/o to swap space.
     76  */
     77 
     78 /*
     79  * swap space is managed in the following way:
     80  *
     81  * each swap partition or file is described by a "swapdev" structure.
     82  * each "swapdev" structure contains a "swapent" structure which contains
     83  * information that is passed up to the user (via system calls).
     84  *
     85  * each swap partition is assigned a "priority" (int) which controls
     86  * swap partition usage.
     87  *
     88  * the system maintains a global data structure describing all swap
     89  * partitions/files.   there is a sorted LIST of "swappri" structures
     90  * which describe "swapdev"'s at that priority.   this LIST is headed
     91  * by the "swap_priority" global var.    each "swappri" contains a
     92  * TAILQ of "swapdev" structures at that priority.
     93  *
     94  * locking:
     95  *  - swap_syscall_lock (krwlock_t): this lock serializes the swapctl
     96  *    system call and prevents the swap priority list from changing
     97  *    while we are in the middle of a system call (e.g. SWAP_STATS).
     98  *  - uvm_swap_data_lock (kmutex_t): this lock protects all swap data
     99  *    structures including the priority list, the swapdev structures,
    100  *    and the swapmap arena.
    101  *
    102  * each swap device has the following info:
    103  *  - swap device in use (could be disabled, preventing future use)
    104  *  - swap enabled (allows new allocations on swap)
    105  *  - map info in /dev/drum
    106  *  - vnode pointer
    107  * for swap files only:
    108  *  - block size
    109  *  - max byte count in buffer
    110  *  - buffer
    111  *
    112  * userland controls and configures swap with the swapctl(2) system call.
    113  * the sys_swapctl performs the following operations:
    114  *  [1] SWAP_NSWAP: returns the number of swap devices currently configured
    115  *  [2] SWAP_STATS: given a pointer to an array of swapent structures
    116  *	(passed in via "arg") of a size passed in via "misc" ... we load
    117  *	the current swap config into the array. The actual work is done
    118  *	in the uvm_swap_stats() function.
    119  *  [3] SWAP_ON: given a pathname in arg (could be device or file) and a
    120  *	priority in "misc", start swapping on it.
    121  *  [4] SWAP_OFF: as SWAP_ON, but stops swapping to a device
    122  *  [5] SWAP_CTL: changes the priority of a swap device (new priority in
    123  *	"misc")
    124  */
    125 
    126 /*
    127  * swapdev: describes a single swap partition/file
    128  *
    129  * note the following should be true:
    130  * swd_inuse <= swd_nblks  [number of blocks in use is <= total blocks]
    131  * swd_nblks <= swd_mapsize [because mapsize includes miniroot+disklabel]
    132  */
    133 struct swapdev {
    134 	dev_t			swd_dev;	/* device id */
    135 	int			swd_flags;	/* flags:inuse/enable/fake */
    136 	int			swd_priority;	/* our priority */
    137 	int			swd_nblks;	/* blocks in this device */
    138 	char			*swd_path;	/* saved pathname of device */
    139 	int			swd_pathlen;	/* length of pathname */
    140 	int			swd_npages;	/* #pages we can use */
    141 	int			swd_npginuse;	/* #pages in use */
    142 	int			swd_npgbad;	/* #pages bad */
    143 	int			swd_drumoffset;	/* page0 offset in drum */
    144 	int			swd_drumsize;	/* #pages in drum */
    145 	blist_t			swd_blist;	/* blist for this swapdev */
    146 	struct vnode		*swd_vp;	/* backing vnode */
    147 	TAILQ_ENTRY(swapdev)	swd_next;	/* priority tailq */
    148 
    149 #ifdef VMSWAP_ENCRYPTION
    150 	struct aesenc		swd_enckey;	/* AES key expanded for enc */
    151 	struct aesdec		swd_deckey;	/* AES key expanded for dec */
    152 	bool			swd_encinit;	/* true if keys initialized */
    153 #endif /* VMSWAP_ENCRYPTION */
    154 
    155 	/*
    156 	 * the following members are only used for swap on VREG file.
    157 	 * swd_lock protects swd_active and swd_tab.
    158 	 */
    159 	kmutex_t		swd_lock;
    160 	int			swd_bsize;	/* blocksize (bytes) */
    161 	int			swd_maxactive;	/* max active i/o reqs */
    162 	struct bufq_state	*swd_tab;	/* buffer list */
    163 	int			swd_active;	/* number of active buffers */
    164 };
    165 
    166 /*
    167  * swap device priority entry; the list is kept sorted on `spi_priority'.
    168  */
    169 struct swappri {
    170 	int			spi_priority;     /* priority */
    171 	TAILQ_HEAD(spi_swapdev, swapdev)	spi_swapdev;
    172 	/* tailq of swapdevs at this priority */
    173 	LIST_ENTRY(swappri)	spi_swappri;      /* global list of pri's */
    174 };
    175 
    176 /*
    177  * local variables
    178  */
    179 static vmem_t *swapmap;	/* controls the mapping of /dev/drum */
    180 
    181 /* list of all active swap devices [by priority] */
    182 LIST_HEAD(swap_priority, swappri);
    183 static struct swap_priority swap_priority;
    184 
    185 /* locks */
    186 static kmutex_t uvm_swap_data_lock __cacheline_aligned;
    187 static krwlock_t swap_syscall_lock;
    188 bool uvm_swap_init_done = false;
    189 
    190 /* workqueue and use counter for swap to regular files */
    191 static int sw_reg_count = 0;
    192 static struct workqueue *sw_reg_workqueue;
    193 
    194 /* tuneables */
    195 u_int uvm_swapisfull_factor = 99;
    196 #if VMSWAP_DEFAULT_PLAINTEXT
    197 bool uvm_swap_encrypt = false;
    198 #else
    199 bool uvm_swap_encrypt = true;
    200 #endif
    201 
    202 /*
    203  * prototypes
    204  */
    205 static struct swapdev	*swapdrum_getsdp(int);
    206 
    207 static struct swapdev	*swaplist_find(struct vnode *, bool);
    208 static void		 swaplist_insert(struct swapdev *,
    209 					 struct swappri *, int);
    210 static void		 swaplist_trim(void);
    211 
    212 static int swap_on(struct lwp *, struct swapdev *);
    213 static int swap_off(struct lwp *, struct swapdev *);
    214 
    215 static void sw_reg_strategy(struct swapdev *, struct buf *, int);
    216 static void sw_reg_biodone(struct buf *);
    217 static void sw_reg_iodone(struct work *wk, void *dummy);
    218 static void sw_reg_start(struct swapdev *);
    219 
    220 static int uvm_swap_io(struct vm_page **, int, int, int);
    221 
    222 #ifdef VMSWAP_ENCRYPTION
    223 static void uvm_swap_genkey(struct swapdev *);
    224 static void uvm_swap_encryptpage(struct swapdev *, void *, int);
    225 static void uvm_swap_decryptpage(struct swapdev *, void *, int);
    226 #endif /* VMSWAP_ENCRYPTION */
    227 
    228 /*
    229  * uvm_swap_init: init the swap system data structures and locks
    230  *
    231  * => called at boot time from init_main.c after the filesystems
    232  *	are brought up (which happens after uvm_init())
    233  */
    234 void
    235 uvm_swap_init(void)
    236 {
    237 	UVMHIST_FUNC(__func__);
    238 	UVMHIST_CALLED(pdhist);
    239 
    240 	/*
    241 	 * first, init the swap list, its counter, and its lock.
    242 	 * then get a handle on the vnode for /dev/drum by using
    243 	 * the its dev_t number ("swapdev", from MD conf.c).
    244 	 */
    245 	LIST_INIT(&swap_priority);
    246 	uvmexp.nswapdev = 0;
    247 	rw_init(&swap_syscall_lock);
    248 	mutex_init(&uvm_swap_data_lock, MUTEX_DEFAULT, IPL_NONE);
    249 
    250 	if (bdevvp(swapdev, &swapdev_vp))
    251 		panic("%s: can't get vnode for swap device", __func__);
    252 	if (vn_lock(swapdev_vp, LK_EXCLUSIVE | LK_RETRY))
    253 		panic("%s: can't lock swap device", __func__);
    254 	if (VOP_OPEN(swapdev_vp, FREAD | FWRITE, NOCRED))
    255 		panic("%s: can't open swap device", __func__);
    256 	VOP_UNLOCK(swapdev_vp);
    257 
    258 	/*
    259 	 * create swap block resource map to map /dev/drum.   the range
    260 	 * from 1 to INT_MAX allows 2 gigablocks of swap space.  note
    261 	 * that block 0 is reserved (used to indicate an allocation
    262 	 * failure, or no allocation).
    263 	 */
    264 	swapmap = vmem_create("swapmap", /*base*/1, /*size*/INT_MAX - 1,
    265 	    /*quantum*/1, /*alloc*/NULL, /*free*/NULL, /*arg*/NULL,
    266 	    /*qcache_max*/0, VM_NOSLEEP, IPL_NONE);
    267 	if (swapmap == 0) {
    268 		panic("%s: vmem_create failed", __func__);
    269 	}
    270 
    271 	uvm_swap_init_done = true;
    272 
    273 	UVMHIST_LOG(pdhist, "<- done", 0, 0, 0, 0);
    274 }
    275 
    276 /*
    277  * swaplist functions: functions that operate on the list of swap
    278  * devices on the system.
    279  */
    280 
    281 /*
    282  * swaplist_insert: insert swap device "sdp" into the global list
    283  *
    284  * => caller must hold both swap_syscall_lock and uvm_swap_data_lock
    285  * => caller must provide a newly allocated swappri structure (we will
    286  *	FREE it if we don't need it... this it to prevent allocation
    287  *	blocking here while adding swap)
    288  */
    289 static void
    290 swaplist_insert(struct swapdev *sdp, struct swappri *newspp, int priority)
    291 {
    292 	struct swappri *spp, *pspp;
    293 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
    294 
    295 	KASSERT(rw_write_held(&swap_syscall_lock));
    296 	KASSERT(mutex_owned(&uvm_swap_data_lock));
    297 
    298 	if (LIST_EMPTY(&swap_priority)) {
    299 		KASSERT(uvmexp.swpginuse == 0);
    300 		KASSERT(uvmexp.swpgonly == 0);
    301 		KASSERT(uvmexp.swpages == 0);
    302 		KASSERT(uvmexp.swpgavail == 0);
    303 	}
    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 = %jd",
    321 		    priority, 0, 0, 0);
    322 
    323 		spp->spi_priority = priority;
    324 		TAILQ_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 		kmem_free(newspp, sizeof(*newspp));
    333 	}
    334 
    335 	/*
    336 	 * priority found (or created).   now insert on the priority's
    337 	 * tailq list and bump the total number of swapdevs.
    338 	 */
    339 	sdp->swd_priority = priority;
    340 	TAILQ_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, bool remove)
    353 {
    354 	struct swapdev *sdp;
    355 	struct swappri *spp;
    356 
    357 	KASSERT(rw_lock_held(&swap_syscall_lock));
    358 	KASSERT(remove ? rw_write_held(&swap_syscall_lock) : 1);
    359 	KASSERT(mutex_owned(&uvm_swap_data_lock));
    360 
    361 	/*
    362 	 * search the lists for the requested vp
    363 	 */
    364 	LIST_FOREACH(spp, &swap_priority, spi_swappri) {
    365 		TAILQ_FOREACH(sdp, &spp->spi_swapdev, swd_next) {
    366 			if (sdp->swd_vp == vp) {
    367 				if (remove) {
    368 					TAILQ_REMOVE(&spp->spi_swapdev,
    369 					    sdp, swd_next);
    370 					uvmexp.nswapdev--;
    371 				}
    372 				return(sdp);
    373 			}
    374 		}
    375 	}
    376 	return (NULL);
    377 }
    378 
    379 /*
    380  * swaplist_trim: scan priority list for empty priority entries and kill
    381  *	them.
    382  *
    383  * => caller must hold both swap_syscall_lock and uvm_swap_data_lock
    384  */
    385 static void
    386 swaplist_trim(void)
    387 {
    388 	struct swappri *spp, *nextspp;
    389 
    390 	KASSERT(rw_write_held(&swap_syscall_lock));
    391 	KASSERT(mutex_owned(&uvm_swap_data_lock));
    392 
    393 	LIST_FOREACH_SAFE(spp, &swap_priority, spi_swappri, nextspp) {
    394 		if (!TAILQ_EMPTY(&spp->spi_swapdev))
    395 			continue;
    396 		LIST_REMOVE(spp, spi_swappri);
    397 		kmem_free(spp, sizeof(*spp));
    398 	}
    399 
    400 	if (LIST_EMPTY(&swap_priority)) {
    401 		KASSERT(uvmexp.swpginuse == 0);
    402 		KASSERT(uvmexp.swpgonly == 0);
    403 		KASSERT(uvmexp.swpages == 0);
    404 		KASSERT(uvmexp.swpgavail == 0);
    405 	}
    406 }
    407 
    408 /*
    409  * swapdrum_getsdp: given a page offset in /dev/drum, convert it back
    410  *	to the "swapdev" that maps that section of the drum.
    411  *
    412  * => each swapdev takes one big contig chunk of the drum
    413  * => caller must hold uvm_swap_data_lock
    414  */
    415 static struct swapdev *
    416 swapdrum_getsdp(int pgno)
    417 {
    418 	struct swapdev *sdp;
    419 	struct swappri *spp;
    420 
    421 	KASSERT(mutex_owned(&uvm_swap_data_lock));
    422 
    423 	LIST_FOREACH(spp, &swap_priority, spi_swappri) {
    424 		TAILQ_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  * swapdrum_sdp_is: true iff the swap device for pgno is sdp
    438  *
    439  * => for use in positive assertions only; result is not stable
    440  */
    441 static bool __debugused
    442 swapdrum_sdp_is(int pgno, struct swapdev *sdp)
    443 {
    444 	bool result;
    445 
    446 	mutex_enter(&uvm_swap_data_lock);
    447 	result = swapdrum_getsdp(pgno) == sdp;
    448 	mutex_exit(&uvm_swap_data_lock);
    449 
    450 	return result;
    451 }
    452 
    453 void
    454 swapsys_lock(krw_t op)
    455 {
    456 	rw_enter(&swap_syscall_lock, op);
    457 }
    458 
    459 void
    460 swapsys_unlock(void)
    461 {
    462 	rw_exit(&swap_syscall_lock);
    463 }
    464 
    465 static void
    466 swapent_cvt(struct swapent *se, const struct swapdev *sdp, int inuse)
    467 {
    468 	se->se_dev = sdp->swd_dev;
    469 	se->se_flags = sdp->swd_flags;
    470 	se->se_nblks = sdp->swd_nblks;
    471 	se->se_npgbad = sdp->swd_npgbad;
    472 	se->se_inuse = inuse;
    473 	se->se_priority = sdp->swd_priority;
    474 	KASSERT(sdp->swd_pathlen < sizeof(se->se_path));
    475 	strcpy(se->se_path, sdp->swd_path);
    476 }
    477 
    478 int (*uvm_swap_stats13)(const struct sys_swapctl_args *, register_t *) =
    479     (void *)enosys;
    480 int (*uvm_swap_stats50)(const struct sys_swapctl_args *, register_t *) =
    481     (void *)enosys;
    482 int (*uvm_swap_stats110)(const struct sys_swapctl_args *, register_t *) =
    483     (void *)enosys;
    484 
    485 /*
    486  * sys_swapctl: main entry point for swapctl(2) system call
    487  * 	[with three helper functions: swap_on, swap_off and uvm_swap_stats]
    488  */
    489 int
    490 sys_swapctl(struct lwp *l, const struct sys_swapctl_args *uap,
    491     register_t *retval)
    492 {
    493 	/* {
    494 		syscallarg(int) cmd;
    495 		syscallarg(void *) arg;
    496 		syscallarg(int) misc;
    497 	} */
    498 	struct vnode *vp;
    499 	struct nameidata nd;
    500 	struct swappri *spp;
    501 	struct swapdev *sdp;
    502 #define SWAP_PATH_MAX (PATH_MAX + 1)
    503 	char	*userpath;
    504 	size_t	len = 0;
    505 	int	error;
    506 	int	priority;
    507 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
    508 
    509 	/*
    510 	 * we handle the non-priv NSWAP and STATS request first.
    511 	 *
    512 	 * SWAP_NSWAP: return number of config'd swap devices
    513 	 * [can also be obtained with uvmexp sysctl]
    514 	 */
    515 	if (SCARG(uap, cmd) == SWAP_NSWAP) {
    516 		const int nswapdev = uvmexp.nswapdev;
    517 		UVMHIST_LOG(pdhist, "<- done SWAP_NSWAP=%jd", nswapdev,
    518 		    0, 0, 0);
    519 		*retval = nswapdev;
    520 		return 0;
    521 	}
    522 
    523 	userpath = kmem_alloc(SWAP_PATH_MAX, KM_SLEEP);
    524 
    525 	/*
    526 	 * ensure serialized syscall access by grabbing the swap_syscall_lock
    527 	 */
    528 	rw_enter(&swap_syscall_lock, RW_WRITER);
    529 
    530 	/*
    531 	 * SWAP_STATS: get stats on current # of configured swap devs
    532 	 *
    533 	 * note that the swap_priority list can't change as long
    534 	 * as we are holding the swap_syscall_lock.  we don't want
    535 	 * to grab the uvm_swap_data_lock because we may fault&sleep during
    536 	 * copyout() and we don't want to be holding that lock then!
    537 	 */
    538 	switch (SCARG(uap, cmd)) {
    539 	case SWAP_STATS13:
    540 		error = (*uvm_swap_stats13)(uap, retval);
    541 		goto out;
    542 	case SWAP_STATS50:
    543 		error = (*uvm_swap_stats50)(uap, retval);
    544 		goto out;
    545 	case SWAP_STATS110:
    546 		error = (*uvm_swap_stats110)(uap, retval);
    547 		goto out;
    548 	case SWAP_STATS:
    549 		error = uvm_swap_stats(SCARG(uap, arg), SCARG(uap, misc),
    550 		    NULL, sizeof(struct swapent), retval);
    551 		UVMHIST_LOG(pdhist, "<- done SWAP_STATS", 0, 0, 0, 0);
    552 		goto out;
    553 
    554 	case SWAP_GETDUMPDEV:
    555 		error = copyout(&dumpdev, SCARG(uap, arg), sizeof(dumpdev));
    556 		goto out;
    557 	default:
    558 		break;
    559 	}
    560 
    561 	/*
    562 	 * all other requests require superuser privs.   verify.
    563 	 */
    564 	if ((error = kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_SWAPCTL,
    565 	    0, NULL, NULL, NULL)))
    566 		goto out;
    567 
    568 	if (SCARG(uap, cmd) == SWAP_DUMPOFF) {
    569 		/* drop the current dump device */
    570 		dumpdev = NODEV;
    571 		dumpcdev = NODEV;
    572 		cpu_dumpconf();
    573 		goto out;
    574 	}
    575 
    576 	/*
    577 	 * at this point we expect a path name in arg.   we will
    578 	 * use namei() to gain a vnode reference (vref), and lock
    579 	 * the vnode (VOP_LOCK).
    580 	 *
    581 	 * XXX: a NULL arg means use the root vnode pointer (e.g. for
    582 	 * miniroot)
    583 	 */
    584 	if (SCARG(uap, arg) == NULL) {
    585 		vp = rootvp;		/* miniroot */
    586 		vref(vp);
    587 		if (vn_lock(vp, LK_EXCLUSIVE)) {
    588 			vrele(vp);
    589 			error = EBUSY;
    590 			goto out;
    591 		}
    592 		if (SCARG(uap, cmd) == SWAP_ON &&
    593 		    copystr("miniroot", userpath, SWAP_PATH_MAX, &len))
    594 			panic("swapctl: miniroot copy failed");
    595 	} else {
    596 		struct pathbuf *pb;
    597 
    598 		/*
    599 		 * This used to allow copying in one extra byte
    600 		 * (SWAP_PATH_MAX instead of PATH_MAX) for SWAP_ON.
    601 		 * This was completely pointless because if anyone
    602 		 * used that extra byte namei would fail with
    603 		 * ENAMETOOLONG anyway, so I've removed the excess
    604 		 * logic. - dholland 20100215
    605 		 */
    606 
    607 		error = pathbuf_copyin(SCARG(uap, arg), &pb);
    608 		if (error) {
    609 			goto out;
    610 		}
    611 		if (SCARG(uap, cmd) == SWAP_ON) {
    612 			/* get a copy of the string */
    613 			pathbuf_copystring(pb, userpath, SWAP_PATH_MAX);
    614 			len = strlen(userpath) + 1;
    615 		}
    616 		NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | TRYEMULROOT, pb);
    617 		if ((error = namei(&nd))) {
    618 			pathbuf_destroy(pb);
    619 			goto out;
    620 		}
    621 		vp = nd.ni_vp;
    622 		pathbuf_destroy(pb);
    623 	}
    624 	/* note: "vp" is referenced and locked */
    625 
    626 	error = 0;		/* assume no error */
    627 	switch (SCARG(uap, cmd)) {
    628 
    629 	case SWAP_DUMPDEV:
    630 		if (vp->v_type != VBLK) {
    631 			error = ENOTBLK;
    632 			break;
    633 		}
    634 		if (bdevsw_lookup(vp->v_rdev)) {
    635 			dumpdev = vp->v_rdev;
    636 			dumpcdev = devsw_blk2chr(dumpdev);
    637 		} else
    638 			dumpdev = NODEV;
    639 		cpu_dumpconf();
    640 		break;
    641 
    642 	case SWAP_CTL:
    643 		/*
    644 		 * get new priority, remove old entry (if any) and then
    645 		 * reinsert it in the correct place.  finally, prune out
    646 		 * any empty priority structures.
    647 		 */
    648 		priority = SCARG(uap, misc);
    649 		spp = kmem_alloc(sizeof(*spp), KM_SLEEP);
    650 		mutex_enter(&uvm_swap_data_lock);
    651 		if ((sdp = swaplist_find(vp, true)) == NULL) {
    652 			error = ENOENT;
    653 		} else {
    654 			swaplist_insert(sdp, spp, priority);
    655 			swaplist_trim();
    656 		}
    657 		mutex_exit(&uvm_swap_data_lock);
    658 		if (error)
    659 			kmem_free(spp, sizeof(*spp));
    660 		break;
    661 
    662 	case SWAP_ON:
    663 		/*
    664 		 * check for duplicates.   if none found, then insert a
    665 		 * dummy entry on the list to prevent someone else from
    666 		 * trying to enable this device while we are working on
    667 		 * it.
    668 		 */
    669 		priority = SCARG(uap, misc);
    670 		sdp = kmem_zalloc(sizeof(*sdp), KM_SLEEP);
    671 		spp = kmem_alloc(sizeof(*spp), KM_SLEEP);
    672 		mutex_init(&sdp->swd_lock, MUTEX_DEFAULT, IPL_NONE);
    673 		sdp->swd_flags = SWF_FAKE;
    674 		sdp->swd_vp = vp;
    675 		sdp->swd_dev = (vp->v_type == VBLK) ? vp->v_rdev : NODEV;
    676 		bufq_alloc(&sdp->swd_tab, "disksort", BUFQ_SORT_RAWBLOCK);
    677 		mutex_enter(&uvm_swap_data_lock);
    678 		if (swaplist_find(vp, false) != NULL) {
    679 			error = EBUSY;
    680 			mutex_exit(&uvm_swap_data_lock);
    681 			bufq_free(sdp->swd_tab);
    682 			mutex_destroy(&sdp->swd_lock);
    683 			kmem_free(sdp, sizeof(*sdp));
    684 			kmem_free(spp, sizeof(*spp));
    685 			break;
    686 		}
    687 		swaplist_insert(sdp, spp, priority);
    688 		mutex_exit(&uvm_swap_data_lock);
    689 
    690 		KASSERT(len > 0);
    691 		sdp->swd_pathlen = len;
    692 		sdp->swd_path = kmem_alloc(len, KM_SLEEP);
    693 		if (copystr(userpath, sdp->swd_path, len, 0) != 0)
    694 			panic("swapctl: copystr");
    695 
    696 		/*
    697 		 * we've now got a FAKE placeholder in the swap list.
    698 		 * now attempt to enable swap on it.  if we fail, undo
    699 		 * what we've done and kill the fake entry we just inserted.
    700 		 * if swap_on is a success, it will clear the SWF_FAKE flag
    701 		 */
    702 		if ((error = swap_on(l, sdp)) != 0) {
    703 			mutex_enter(&uvm_swap_data_lock);
    704 			(void) swaplist_find(vp, true);  /* kill fake entry */
    705 			swaplist_trim();
    706 			mutex_exit(&uvm_swap_data_lock);
    707 			bufq_free(sdp->swd_tab);
    708 			kmem_free(sdp->swd_path, sdp->swd_pathlen);
    709 			mutex_destroy(&sdp->swd_lock);
    710 			kmem_free(sdp, sizeof(*sdp));
    711 			break;
    712 		}
    713 		break;
    714 
    715 	case SWAP_OFF:
    716 		mutex_enter(&uvm_swap_data_lock);
    717 		if ((sdp = swaplist_find(vp, false)) == NULL) {
    718 			mutex_exit(&uvm_swap_data_lock);
    719 			error = ENXIO;
    720 			break;
    721 		}
    722 
    723 		/*
    724 		 * If a device isn't in use or enabled, we
    725 		 * can't stop swapping from it (again).
    726 		 */
    727 		if ((sdp->swd_flags & (SWF_INUSE|SWF_ENABLE)) == 0) {
    728 			mutex_exit(&uvm_swap_data_lock);
    729 			error = EBUSY;
    730 			break;
    731 		}
    732 
    733 		/*
    734 		 * do the real work.
    735 		 */
    736 		error = swap_off(l, sdp);
    737 		break;
    738 
    739 	default:
    740 		error = EINVAL;
    741 	}
    742 
    743 	/*
    744 	 * done!  release the ref gained by namei() and unlock.
    745 	 */
    746 	vput(vp);
    747 out:
    748 	rw_exit(&swap_syscall_lock);
    749 	kmem_free(userpath, SWAP_PATH_MAX);
    750 
    751 	UVMHIST_LOG(pdhist, "<- done!  error=%jd", error, 0, 0, 0);
    752 	return (error);
    753 }
    754 
    755 /*
    756  * uvm_swap_stats: implements swapctl(SWAP_STATS). The function is kept
    757  * away from sys_swapctl() in order to allow COMPAT_* swapctl()
    758  * emulation to use it directly without going through sys_swapctl().
    759  * The problem with using sys_swapctl() there is that it involves
    760  * copying the swapent array to the stackgap, and this array's size
    761  * is not known at build time. Hence it would not be possible to
    762  * ensure it would fit in the stackgap in any case.
    763  */
    764 int
    765 uvm_swap_stats(char *ptr, int misc,
    766     void (*f)(void *, const struct swapent *), size_t len,
    767     register_t *retval)
    768 {
    769 	struct swappri *spp;
    770 	struct swapdev *sdp, **sdps, **sp;
    771 	struct swapent sep;
    772 	size_t sdpsize = 0;
    773 	struct swapdev *stackbuf[8];	/* magic 8, any number >1 will do */
    774 	int count, slots;
    775 	int error;
    776 
    777 	KASSERT(len <= sizeof(sep));
    778 	if (len == 0)
    779 		return ENOSYS;
    780 
    781 	if (misc < 0)
    782 		return EINVAL;
    783 
    784 	if (misc == 0 || uvmexp.nswapdev == 0)
    785 		return 0;
    786 
    787 	KASSERT(rw_lock_held(&swap_syscall_lock));
    788 
    789 	/*
    790 	 * Allocate space (slots) for pointers to all swapdevs
    791 	 *
    792 	 * This needs to be done here (not earlier) (and so needs
    793 	 * the unlock/lock dance) because of the way the various
    794 	 * compat functions work.
    795 	 */
    796 	sdps = NULL;
    797 	slots = uvmexp.nswapdev;
    798 
    799 	if (slots > misc)	/* we never need more than requested */
    800 		slots = misc;
    801 
    802 	/*
    803 	 * Nb: do not limit misc to <= uvmexp.nswapdev yet,
    804 	 * as the latter might get bigger (or smaller)
    805 	 */
    806 	if ((SIZE_MAX / sizeof sdp) <= misc)	/* unlikely */
    807 		return E2BIG;
    808 
    809 	/*
    810 	 * One slot for each currently existing swap device, but
    811 	 * limited (above) to no more than the request wants (misc).
    812 	 * Each slot needs space for a pointer to a swapdev.
    813 	 */
    814 	sdpsize = (size_t)slots * sizeof sdp;
    815 
    816 	/*
    817 	 * Borrow from kmem_tmpbuf_alloc(9) but don't use that
    818 	 * so we don't need to do the unlock dance unnecessarily
    819 	 */
    820 	if (sdpsize <= sizeof stackbuf) {
    821 		/* Should be the common case */
    822 		sdps = stackbuf;
    823 	} else {
    824 		rw_exit(&swap_syscall_lock);
    825 
    826 		sdps = kmem_alloc(sdpsize, KM_SLEEP);
    827 
    828 		rw_enter(&swap_syscall_lock, RW_READER);
    829 
    830 		/*
    831 		 * At this point, 3 possibilities.
    832 		 *
    833 		 * 1. uvmexp.nswapdev has increased.
    834 		 *
    835 		 * A new swap device got added.  That's OK, just ignore the
    836 		 * excess device(s), and return the first N (the number that
    837 		 * were there when we started).
    838 		 *
    839 		 * 2. uvmexp.nswapdev has decreased.
    840 		 *
    841 		 * A swap device was deleted.  In this case we will return
    842 		 * less devices than requested but that's OK.  We will have
    843 		 * more slot memory than is needed to save them all, but just
    844 		 * a little more, and it gets freed just below.
    845 		 *
    846 		 * 3. uvmexp.nswapdev hasn't changed.
    847 		 *
    848 		 * This will be the usual case; no swapctl operations occurred
    849 		 * while the lock was released, or possibly a device was
    850 		 * deleted and another added - that's irrelevant.  At this
    851 		 * point all that matters is the number of devices, we haven't
    852 		 * looked at the lists yet.
    853 		 *
    854 		 * So we never need to adjust this allocation.
    855 		 *
    856 		 * And we don't need to look at uvmexp.nswapdev again!
    857 		 */
    858 	}
    859 
    860 	KASSERT(rw_lock_held(&swap_syscall_lock));
    861 
    862 	/*
    863 	 * Collect all of the swap descriptors, while holding the data lock,
    864 	 * so the lists cannot change.   Then they can be used safely.
    865 	 *
    866 	 * Entries cannot be deleted, because swap_syscall_lock is held,
    867 	 * but the lists holding them can be reordered except in this small
    868 	 * loop where we lock out that kind of activity.   No processing
    869 	 * happens here, this is fast, with no func calls, or anything which
    870 	 * might perform operations which might need the lock.
    871 	 */
    872 	mutex_enter(&uvm_swap_data_lock);
    873 	sp = sdps;
    874 	count = 0;
    875 	LIST_FOREACH(spp, &swap_priority, spi_swappri) {
    876 		TAILQ_FOREACH(sdp, &spp->spi_swapdev, swd_next) {
    877 			if (++count <= slots)
    878 				*sp++ = sdp;
    879 			/*
    880 			 * don't bother with exiting the loops early,
    881 			 * the lists tend to be very short, and not
    882 			 * exhausting them is a very rare occurrence.
    883 			 * So just loop and do nothing (but count) in
    884 			 * the odd case we could have broken out early.
    885 			 */
    886 		}
    887 	}
    888 	mutex_exit(&uvm_swap_data_lock);
    889 
    890 	/*
    891 	 * Now we have a stable list of devices which cannot change,
    892 	 * even if the swapping lists are reordered.
    893 	 */
    894 
    895 	if (misc > slots)		/* the number of storage slots */
    896 		misc = slots;
    897 	if (misc > count)		/* the number of devices now */
    898 		misc = count;
    899 
    900 	/*
    901 	 * This is the actual work of uvm_swap_stats() - above was bookkeeping.
    902 	 */
    903 	error = 0;
    904 	count = 0;
    905 	sp = sdps;
    906 	while (misc --> 0) {
    907 		int inuse;
    908 
    909 		sdp = *sp++;	/* The next swapdev, from the next slot */
    910 
    911 		inuse = btodb((uint64_t)sdp->swd_npginuse <<
    912 		    PAGE_SHIFT);
    913 
    914 		memset(&sep, 0, sizeof(sep));
    915 		swapent_cvt(&sep, sdp, inuse);
    916 		if (f)
    917 			(*f)(&sep, &sep);
    918 		if ((error = copyout(&sep, ptr, len)) != 0)
    919 			goto out;
    920 		ptr += len;
    921 		count++;
    922 	}
    923 	*retval = count;
    924    out:;
    925 	if (sdps != stackbuf) {
    926 		/*
    927 		 * XXX should unlock & lock again here probably,
    928 		 *     but for now, no...
    929 		 */
    930 		kmem_free(sdps, sdpsize);
    931 	}
    932 	return error;
    933 }
    934 
    935 /*
    936  * swap_on: attempt to enable a swapdev for swapping.   note that the
    937  *	swapdev is already on the global list, but disabled (marked
    938  *	SWF_FAKE).
    939  *
    940  * => we avoid the start of the disk (to protect disk labels)
    941  * => we also avoid the miniroot, if we are swapping to root.
    942  * => caller should leave uvm_swap_data_lock unlocked, we may lock it
    943  *	if needed.
    944  */
    945 static int
    946 swap_on(struct lwp *l, struct swapdev *sdp)
    947 {
    948 	struct vnode *vp;
    949 	int error, npages, nblocks, size;
    950 	long addr;
    951 	vmem_addr_t result;
    952 	struct vattr va;
    953 	dev_t dev;
    954 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
    955 
    956 	/*
    957 	 * we want to enable swapping on sdp.   the swd_vp contains
    958 	 * the vnode we want (locked and ref'd), and the swd_dev
    959 	 * contains the dev_t of the file, if it a block device.
    960 	 */
    961 	vp = sdp->swd_vp;
    962 	dev = sdp->swd_dev;
    963 
    964 	/*
    965 	 * open the swap file (mostly useful for block device files to
    966 	 * let device driver know what is up).
    967 	 *
    968 	 * we skip the open/close for root on swap because the root
    969 	 * has already been opened when root was mounted (mountroot).
    970 	 */
    971 	if (vp != rootvp) {
    972 		if ((error = VOP_OPEN(vp, FREAD|FWRITE, l->l_cred)))
    973 			return (error);
    974 	}
    975 
    976 	/* XXX this only works for block devices */
    977 	UVMHIST_LOG(pdhist, "  dev=%jd, major(dev)=%jd",
    978 	    dev, major(dev), 0, 0);
    979 
    980 	/*
    981 	 * we now need to determine the size of the swap area.   for
    982 	 * block specials we can call the d_psize function.
    983 	 * for normal files, we must stat [get attrs].
    984 	 *
    985 	 * we put the result in nblks.
    986 	 * for normal files, we also want the filesystem block size
    987 	 * (which we get with statfs).
    988 	 */
    989 	switch (vp->v_type) {
    990 	case VBLK:
    991 		if ((nblocks = bdev_size(dev)) == -1) {
    992 			error = ENXIO;
    993 			goto bad;
    994 		}
    995 		break;
    996 
    997 	case VREG:
    998 		if ((error = VOP_GETATTR(vp, &va, l->l_cred)))
    999 			goto bad;
   1000 		nblocks = (int)btodb(va.va_size);
   1001 		sdp->swd_bsize = 1 << vp->v_mount->mnt_fs_bshift;
   1002 		/*
   1003 		 * limit the max # of outstanding I/O requests we issue
   1004 		 * at any one time.   take it easy on NFS servers.
   1005 		 */
   1006 		if (vp->v_tag == VT_NFS)
   1007 			sdp->swd_maxactive = 2; /* XXX */
   1008 		else
   1009 			sdp->swd_maxactive = 8; /* XXX */
   1010 		break;
   1011 
   1012 	default:
   1013 		error = ENXIO;
   1014 		goto bad;
   1015 	}
   1016 
   1017 	/*
   1018 	 * save nblocks in a safe place and convert to pages.
   1019 	 */
   1020 	sdp->swd_nblks = nblocks;
   1021 	npages = dbtob((uint64_t)nblocks) >> PAGE_SHIFT;
   1022 
   1023 	/*
   1024 	 * for block special files, we want to make sure that leave
   1025 	 * the disklabel and bootblocks alone, so we arrange to skip
   1026 	 * over them (arbitrarily choosing to skip PAGE_SIZE bytes).
   1027 	 * note that because of this the "size" can be less than the
   1028 	 * actual number of blocks on the device.
   1029 	 */
   1030 	if (vp->v_type == VBLK) {
   1031 		/* we use pages 1 to (size - 1) [inclusive] */
   1032 		size = npages - 1;
   1033 		addr = 1;
   1034 	} else {
   1035 		/* we use pages 0 to (size - 1) [inclusive] */
   1036 		size = npages;
   1037 		addr = 0;
   1038 	}
   1039 
   1040 	/*
   1041 	 * make sure we have enough blocks for a reasonable sized swap
   1042 	 * area.   we want at least one page.
   1043 	 */
   1044 	if (size < 1) {
   1045 		UVMHIST_LOG(pdhist, "  size <= 1!!", 0, 0, 0, 0);
   1046 		error = EINVAL;
   1047 		goto bad;
   1048 	}
   1049 
   1050 	UVMHIST_LOG(pdhist,"  dev=%#jx: size=%jd addr=%jd",
   1051 	    dev, size, addr, 0);
   1052 
   1053 	/*
   1054 	 * now we need to allocate an extent to manage this swap device
   1055 	 */
   1056 	sdp->swd_blist = blist_create(npages);
   1057 	/* mark all expect the `saved' region free. */
   1058 	blist_free(sdp->swd_blist, addr, size);
   1059 
   1060 #ifdef VMSWAP_ENCRYPTION
   1061 	/*
   1062 	 * mark the keys uninitialized so we generate them lazily.
   1063 	 *
   1064 	 * we defer the key generation to help to maximize the amount
   1065 	 * of data fed into the entropy pool before generating a key,
   1066 	 * for the benefit of machines without HWRNG.
   1067 	 */
   1068 	sdp->swd_encinit = false;
   1069 #endif /* VMSWAP_ENCRYPTION */
   1070 
   1071 	/*
   1072 	 * if the vnode we are swapping to is the root vnode
   1073 	 * (i.e. we are swapping to the miniroot) then we want
   1074 	 * to make sure we don't overwrite it.   do a statfs to
   1075 	 * find its size and skip over it.
   1076 	 */
   1077 	if (vp == rootvp) {
   1078 		struct mount *mp;
   1079 		struct statvfs *sp;
   1080 		int rootblocks, rootpages;
   1081 
   1082 		mp = rootvnode->v_mount;
   1083 		sp = &mp->mnt_stat;
   1084 		rootblocks = sp->f_blocks * btodb(sp->f_frsize);
   1085 		/*
   1086 		 * XXX: sp->f_blocks isn't the total number of
   1087 		 * blocks in the filesystem, it's the number of
   1088 		 * data blocks.  so, our rootblocks almost
   1089 		 * definitely underestimates the total size
   1090 		 * of the filesystem - how badly depends on the
   1091 		 * details of the filesystem type.  there isn't
   1092 		 * an obvious way to deal with this cleanly
   1093 		 * and perfectly, so for now we just pad our
   1094 		 * rootblocks estimate with an extra 5 percent.
   1095 		 */
   1096 		rootblocks += (rootblocks >> 5) +
   1097 		    (rootblocks >> 6) +
   1098 		    (rootblocks >> 7);
   1099 		rootpages = round_page(dbtob(rootblocks)) >> PAGE_SHIFT;
   1100 		if (rootpages > size)
   1101 			panic("swap_on: miniroot larger than swap?");
   1102 
   1103 		if (rootpages != blist_fill(sdp->swd_blist, addr, rootpages)) {
   1104 			panic("swap_on: unable to preserve miniroot");
   1105 		}
   1106 
   1107 		size -= rootpages;
   1108 		printf("Preserved %d pages of miniroot ", rootpages);
   1109 		printf("leaving %d pages of swap\n", size);
   1110 	}
   1111 
   1112 	/*
   1113 	 * add a ref to vp to reflect usage as a swap device.
   1114 	 */
   1115 	vref(vp);
   1116 
   1117 	/*
   1118 	 * now add the new swapdev to the drum and enable.
   1119 	 */
   1120 	error = vmem_alloc(swapmap, npages, VM_BESTFIT | VM_SLEEP, &result);
   1121 	if (error != 0)
   1122 		panic("swapdrum_add");
   1123 	/*
   1124 	 * If this is the first regular swap create the workqueue.
   1125 	 * => Protected by swap_syscall_lock.
   1126 	 */
   1127 	if (vp->v_type != VBLK) {
   1128 		if (sw_reg_count++ == 0) {
   1129 			KASSERT(sw_reg_workqueue == NULL);
   1130 			if (workqueue_create(&sw_reg_workqueue, "swapiod",
   1131 			    sw_reg_iodone, NULL, PRIBIO, IPL_SOFTBIO,
   1132 			    WQ_MPSAFE) != 0)
   1133 				panic("%s: workqueue_create failed", __func__);
   1134 		}
   1135 	}
   1136 
   1137 	sdp->swd_drumoffset = (int)result;
   1138 	sdp->swd_drumsize = npages;
   1139 	sdp->swd_npages = size;
   1140 	mutex_enter(&uvm_swap_data_lock);
   1141 	sdp->swd_flags &= ~SWF_FAKE;	/* going live */
   1142 	sdp->swd_flags |= (SWF_INUSE|SWF_ENABLE);
   1143 	uvmexp.swpages += size;
   1144 	uvmexp.swpgavail += size;
   1145 	mutex_exit(&uvm_swap_data_lock);
   1146 	return (0);
   1147 
   1148 	/*
   1149 	 * failure: clean up and return error.
   1150 	 */
   1151 bad:
   1152 	if (sdp->swd_blist) {
   1153 		blist_destroy(sdp->swd_blist);
   1154 	}
   1155 	if (vp != rootvp) {
   1156 		(void)VOP_CLOSE(vp, FREAD|FWRITE, l->l_cred);
   1157 	}
   1158 	return (error);
   1159 }
   1160 
   1161 /*
   1162  * swap_off: stop swapping on swapdev
   1163  *
   1164  * => swap data should be locked, we will unlock.
   1165  */
   1166 static int
   1167 swap_off(struct lwp *l, struct swapdev *sdp)
   1168 {
   1169 	int npages = sdp->swd_npages;
   1170 	int error = 0;
   1171 
   1172 	UVMHIST_FUNC(__func__);
   1173 	UVMHIST_CALLARGS(pdhist,
   1174 	    "  dev=%#jx, npages=%jd", sdp->swd_dev,npages, 0, 0);
   1175 
   1176 	KASSERT(rw_write_held(&swap_syscall_lock));
   1177 	KASSERT(mutex_owned(&uvm_swap_data_lock));
   1178 
   1179 	/* disable the swap area being removed */
   1180 	sdp->swd_flags &= ~SWF_ENABLE;
   1181 	uvmexp.swpgavail -= npages;
   1182 	mutex_exit(&uvm_swap_data_lock);
   1183 
   1184 	/*
   1185 	 * the idea is to find all the pages that are paged out to this
   1186 	 * device, and page them all in.  in uvm, swap-backed pageable
   1187 	 * memory can take two forms: aobjs and anons.  call the
   1188 	 * swapoff hook for each subsystem to bring in pages.
   1189 	 */
   1190 	if (uao_swap_off(sdp->swd_drumoffset,
   1191 		sdp->swd_drumoffset + sdp->swd_drumsize) ||
   1192 	    amap_swap_off(sdp->swd_drumoffset,
   1193 		sdp->swd_drumoffset + sdp->swd_drumsize)) {
   1194 		error = ENOMEM;
   1195 	} else if (sdp->swd_npginuse > sdp->swd_npgbad) {
   1196 		error = EBUSY;
   1197 	}
   1198 
   1199 	if (error) {
   1200 		mutex_enter(&uvm_swap_data_lock);
   1201 		sdp->swd_flags |= SWF_ENABLE;
   1202 		uvmexp.swpgavail += npages;
   1203 		mutex_exit(&uvm_swap_data_lock);
   1204 
   1205 		return error;
   1206 	}
   1207 
   1208 	/*
   1209 	 * If this is the last regular swap destroy the workqueue.
   1210 	 * => Protected by swap_syscall_lock.
   1211 	 */
   1212 	if (sdp->swd_vp->v_type != VBLK) {
   1213 		KASSERT(sw_reg_count > 0);
   1214 		KASSERT(sw_reg_workqueue != NULL);
   1215 		if (--sw_reg_count == 0) {
   1216 			workqueue_destroy(sw_reg_workqueue);
   1217 			sw_reg_workqueue = NULL;
   1218 		}
   1219 	}
   1220 
   1221 	/*
   1222 	 * done with the vnode.
   1223 	 * drop our ref on the vnode before calling VOP_CLOSE()
   1224 	 * so that spec_close() can tell if this is the last close.
   1225 	 */
   1226 	vrele(sdp->swd_vp);
   1227 	if (sdp->swd_vp != rootvp) {
   1228 		(void) VOP_CLOSE(sdp->swd_vp, FREAD|FWRITE, l->l_cred);
   1229 	}
   1230 
   1231 	mutex_enter(&uvm_swap_data_lock);
   1232 	uvmexp.swpages -= npages;
   1233 	KASSERTMSG(uvmexp.swpginuse >= sdp->swd_npgbad,
   1234 	    "swpginuse %d sdp->swd_npgbad %d",
   1235 	    uvmexp.swpginuse, sdp->swd_npgbad);
   1236 	uvmexp.swpginuse -= sdp->swd_npgbad;
   1237 
   1238 	if (swaplist_find(sdp->swd_vp, true) == NULL)
   1239 		panic("%s: swapdev not in list", __func__);
   1240 	swaplist_trim();
   1241 	mutex_exit(&uvm_swap_data_lock);
   1242 
   1243 	/*
   1244 	 * free all resources!
   1245 	 */
   1246 	vmem_free(swapmap, sdp->swd_drumoffset, sdp->swd_drumsize);
   1247 	blist_destroy(sdp->swd_blist);
   1248 	bufq_free(sdp->swd_tab);
   1249 #ifdef VMSWAP_ENCRYPTION
   1250 	explicit_memset(&sdp->swd_enckey, 0, sizeof sdp->swd_enckey);
   1251 	explicit_memset(&sdp->swd_deckey, 0, sizeof sdp->swd_deckey);
   1252 #endif /* VMSWAP_ENCRYPTION */
   1253 	mutex_destroy(&sdp->swd_lock);
   1254 	kmem_free(sdp, sizeof(*sdp));
   1255 	return (0);
   1256 }
   1257 
   1258 void
   1259 uvm_swap_shutdown(struct lwp *l)
   1260 {
   1261 	struct swapdev *sdp;
   1262 	struct swappri *spp;
   1263 	struct vnode *vp;
   1264 	int error;
   1265 
   1266 	if (!uvm_swap_init_done || uvmexp.nswapdev == 0)
   1267 		return;
   1268 	printf("turning off swap...");
   1269 	rw_enter(&swap_syscall_lock, RW_WRITER);
   1270 	mutex_enter(&uvm_swap_data_lock);
   1271 again:
   1272 	LIST_FOREACH(spp, &swap_priority, spi_swappri)
   1273 		TAILQ_FOREACH(sdp, &spp->spi_swapdev, swd_next) {
   1274 			if (sdp->swd_flags & SWF_FAKE)
   1275 				continue;
   1276 			if ((sdp->swd_flags & (SWF_INUSE|SWF_ENABLE)) == 0)
   1277 				continue;
   1278 #ifdef DEBUG
   1279 			printf("\nturning off swap on %s...", sdp->swd_path);
   1280 #endif
   1281 			/* Have to lock and reference vnode for swap_off(). */
   1282 			vn_lock(vp = sdp->swd_vp, LK_EXCLUSIVE|LK_RETRY);
   1283 			vref(vp);
   1284 			error = swap_off(l, sdp);
   1285 			vput(vp);
   1286 			mutex_enter(&uvm_swap_data_lock);
   1287 			if (error) {
   1288 				printf("stopping swap on %s failed "
   1289 				    "with error %d\n", sdp->swd_path, error);
   1290 				TAILQ_REMOVE(&spp->spi_swapdev, sdp, swd_next);
   1291 				uvmexp.nswapdev--;
   1292 				swaplist_trim();
   1293 			}
   1294 			goto again;
   1295 		}
   1296 	printf(" done\n");
   1297 	mutex_exit(&uvm_swap_data_lock);
   1298 	rw_exit(&swap_syscall_lock);
   1299 }
   1300 
   1301 
   1302 /*
   1303  * /dev/drum interface and i/o functions
   1304  */
   1305 
   1306 /*
   1307  * swopen: allow the initial open from uvm_swap_init() and reject all others.
   1308  */
   1309 static int
   1310 swopen(dev_t dev, int flag, int mode, struct lwp *l)
   1311 {
   1312 	static bool inited = false;
   1313 
   1314 	if (!inited) {
   1315 		inited = true;
   1316 		return 0;
   1317 	}
   1318 	return ENODEV;
   1319 }
   1320 
   1321 static void
   1322 iobuf_redirect(struct buf *bp, struct vnode *vp)
   1323 {
   1324 
   1325 	if ((bp->b_flags & B_READ) == 0) {
   1326 		mutex_enter(bp->b_objlock);
   1327 		vwakeup(bp);
   1328 		mutex_exit(bp->b_objlock);
   1329 		mutex_enter(vp->v_interlock);
   1330 		vp->v_numoutput++;
   1331 		mutex_exit(vp->v_interlock);
   1332 	}
   1333 
   1334 	/*
   1335 	 * finally plug in swapdev vnode and start I/O
   1336 	 */
   1337 	bp->b_vp = vp;
   1338 	bp->b_objlock = vp->v_interlock;
   1339 }
   1340 
   1341 #ifdef VMSWAP_ENCRYPTION
   1342 struct sw_physio_decrypt_context {
   1343 	void *orig_buf;
   1344 	void *orig_private;
   1345 	void (*orig_iodone)(struct buf *);
   1346 	int swslot;
   1347 };
   1348 
   1349 static void
   1350 sw_physio_decrypt_iodone(struct buf *bp)
   1351 {
   1352 	struct sw_physio_decrypt_context *ctx = bp->b_private;
   1353 	void (*cb)(struct buf *bp) = ctx->orig_iodone;
   1354 	size_t npages = bp->b_bcount >> PAGE_SHIFT;
   1355 
   1356 	KASSERT(ctx->swslot > 0);
   1357 	KASSERT(npages << PAGE_SHIFT == bp->b_bcount);
   1358 	if (bp->b_error == 0) {
   1359 		if (bp->b_resid == 0) {
   1360 			uvm_swap_decrypt_pages(ctx->swslot, bp->b_data,
   1361 			    npages);
   1362 			memcpy(ctx->orig_buf, (uint8_t *)bp->b_data,
   1363 			    bp->b_bcount);
   1364 		} else {
   1365 			bp->b_error = EIO;
   1366 		}
   1367 	}
   1368 	kmem_intr_free(bp->b_data, bp->b_bcount);
   1369 	bp->b_data = ctx->orig_buf;
   1370 	if (bp->b_error != 0) {
   1371 		bp->b_resid = bp->b_bcount;
   1372 	}
   1373 	bp->b_private = ctx->orig_private;
   1374 	kmem_intr_free(ctx, sizeof(*ctx));
   1375 	(cb)(bp);	/* call the original b_iodone callback */
   1376 }
   1377 #endif /* VMSWAP_ENCRYPTION */
   1378 
   1379 /*
   1380  * swstrategy: perform I/O on the drum
   1381  *
   1382  * => we must map the i/o request from the drum to the correct swapdev.
   1383  */
   1384 static void
   1385 swstrategy(struct buf *bp)
   1386 {
   1387 	struct swapdev *sdp;
   1388 	struct vnode *vp;
   1389 	int pageno, bn;
   1390 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
   1391 
   1392 	KASSERT((bp->b_flags & B_RAW) == 0 ||
   1393 	    rw_read_held(&swap_syscall_lock));
   1394 
   1395 	/*
   1396 	 * reject non page aligned i/o.
   1397 	 */
   1398 	if ((dbtob((int64_t)bp->b_blkno) & PAGE_MASK) != 0 ||
   1399 	    (bp->b_bcount & PAGE_MASK) != 0) {
   1400 		bp->b_error = ENOTSUP;
   1401 		bp->b_resid = bp->b_bcount;
   1402 		biodone(bp);
   1403 		return;
   1404 	}
   1405 
   1406 	/*
   1407 	 * convert block number to swapdev.   note that swapdev can't
   1408 	 * be yanked out from under us because we are holding resources
   1409 	 * in it (i.e. the blocks we are doing I/O on) or read lock on
   1410 	 * swap_syscall_lock.
   1411 	 */
   1412 	pageno = dbtob((int64_t)bp->b_blkno) >> PAGE_SHIFT;
   1413 	mutex_enter(&uvm_swap_data_lock);
   1414 	sdp = swapdrum_getsdp(pageno);
   1415 	KASSERT((bp->b_flags & B_RAW) != 0 ||
   1416 	    (sdp != NULL && sdp->swd_npginuse > 0));
   1417 	mutex_exit(&uvm_swap_data_lock);
   1418 	if (sdp == NULL) {
   1419 		bp->b_error = EINVAL;
   1420 		bp->b_resid = bp->b_bcount;
   1421 		biodone(bp);
   1422 		UVMHIST_LOG(pdhist, "  failed to get swap device", 0, 0, 0, 0);
   1423 		return;
   1424 	}
   1425 
   1426 #ifdef VMSWAP_ENCRYPTION
   1427 	/*
   1428 	 * B_RAW here implies user i/o on /dev/drum, for which we need
   1429 	 * to handle encryption/decryption here.
   1430 	 * for swap in/out, it's handled by the caller.
   1431 	 */
   1432 	if ((bp->b_flags & B_RAW) != 0 &&
   1433 	    atomic_load_relaxed(&uvm_swap_encrypt)) {
   1434 		struct sw_physio_decrypt_context *ctx;
   1435 
   1436 		/*
   1437 		 * we only implement B_READ for now.
   1438 		 *
   1439 		 * REVISIT: what kind of apps needs to write to /dev/drum?
   1440 		 */
   1441 		if ((bp->b_flags & B_READ) == 0) {
   1442 			bp->b_error = ENOTSUP;
   1443 			bp->b_resid = bp->b_bcount;
   1444 			biodone(bp);
   1445 			return;
   1446 		}
   1447 
   1448 		/*
   1449 		 * In-place decryption in the userland buffer might
   1450 		 * have non-trivial implications, since the original
   1451 		 * bp->b_data is backed by pages shared with userland.
   1452 		 * For simplicity, we use a bounce buffer.
   1453 		 */
   1454 		ctx = kmem_intr_alloc(sizeof(*ctx), KM_SLEEP);
   1455 		ctx->swslot = dbtob((int64_t)bp->b_blkno) >> PAGE_SHIFT;
   1456 		KASSERT(ctx->swslot > 0);
   1457 		ctx->orig_buf = bp->b_data;
   1458 		ctx->orig_private = bp->b_private;
   1459 		ctx->orig_iodone = bp->b_iodone;
   1460 		bp->b_data = kmem_intr_alloc(bp->b_bcount, KM_SLEEP);
   1461 		bp->b_private = ctx;
   1462 		bp->b_iodone = sw_physio_decrypt_iodone;
   1463 	}
   1464 #endif /* VMSWAP_ENCRYPTION */
   1465 
   1466 	/*
   1467 	 * convert drum page number to block number on this swapdev.
   1468 	 */
   1469 	pageno -= sdp->swd_drumoffset;	/* page # on swapdev */
   1470 	bn = btodb((uint64_t)pageno << PAGE_SHIFT); /* convert to diskblock */
   1471 
   1472 	UVMHIST_LOG(pdhist,
   1473 	    "  Rd/Wr (0/1) %jd: mapoff=%#jx bn=%#jx bcount=%jd",
   1474 	    ((bp->b_flags & B_READ) == 0) ? 1 : 0,
   1475 	    sdp->swd_drumoffset, bn, bp->b_bcount);
   1476 
   1477 	/*
   1478 	 * for block devices we finish up here.
   1479 	 * for regular files we have to do more work which we delegate
   1480 	 * to sw_reg_strategy().
   1481 	 */
   1482 	vp = sdp->swd_vp;		/* swapdev vnode pointer */
   1483 	switch (vp->v_type) {
   1484 	default:
   1485 		panic("%s: vnode type 0x%x", __func__, vp->v_type);
   1486 
   1487 	case VBLK:
   1488 		/*
   1489 		 * must convert "bp" from an I/O on /dev/drum to an I/O
   1490 		 * on the swapdev (sdp).
   1491 		 *
   1492 		 * if we are doing a write, we have to redirect the i/o on
   1493 		 * drum's v_numoutput counter to the swapdev's.
   1494 		 */
   1495 		iobuf_redirect(bp, vp);
   1496 		bp->b_blkno = bn;		/* swapdev block number */
   1497 		VOP_STRATEGY(vp, bp);
   1498 		return;
   1499 
   1500 	case VREG:
   1501 		/*
   1502 		 * delegate to sw_reg_strategy function.
   1503 		 */
   1504 		sw_reg_strategy(sdp, bp, bn);
   1505 		return;
   1506 	}
   1507 	/* NOTREACHED */
   1508 }
   1509 
   1510 /*
   1511  * swread: the read function for the drum (just a call to physio)
   1512  */
   1513 static int
   1514 swread(dev_t dev, struct uio *uio, int ioflag)
   1515 {
   1516 	int ret;
   1517 
   1518 	UVMHIST_FUNC(__func__);
   1519 	UVMHIST_CALLARGS(pdhist,
   1520 	    "  dev=%#jx offset=%#jx", dev, uio->uio_offset, 0, 0);
   1521 
   1522 	rw_enter(&swap_syscall_lock, RW_READER);
   1523 	ret = physio(swstrategy, NULL, dev, B_READ, minphys, uio);
   1524 	rw_exit(&swap_syscall_lock);
   1525 	return ret;
   1526 }
   1527 
   1528 /*
   1529  * swwrite: the write function for the drum (just a call to physio)
   1530  */
   1531 static int
   1532 swwrite(dev_t dev, struct uio *uio, int ioflag)
   1533 {
   1534 	int ret;
   1535 
   1536 	UVMHIST_FUNC(__func__);
   1537 	UVMHIST_CALLARGS(pdhist,
   1538 	    "  dev=%#jx offset=%#jx", dev, uio->uio_offset, 0, 0);
   1539 
   1540 	rw_enter(&swap_syscall_lock, RW_READER);
   1541 	ret = physio(swstrategy, NULL, dev, B_WRITE, minphys, uio);
   1542 	rw_exit(&swap_syscall_lock);
   1543 	return ret;
   1544 }
   1545 
   1546 const struct bdevsw swap_bdevsw = {
   1547 	.d_open = swopen,
   1548 	.d_close = noclose,
   1549 	.d_strategy = swstrategy,
   1550 	.d_ioctl = noioctl,
   1551 	.d_dump = nodump,
   1552 	.d_psize = nosize,
   1553 	.d_discard = nodiscard,
   1554 	.d_flag = D_OTHER | D_MPSAFE,
   1555 };
   1556 
   1557 const struct cdevsw swap_cdevsw = {
   1558 	.d_open = nullopen,
   1559 	.d_close = nullclose,
   1560 	.d_read = swread,
   1561 	.d_write = swwrite,
   1562 	.d_ioctl = noioctl,
   1563 	.d_stop = nostop,
   1564 	.d_tty = notty,
   1565 	.d_poll = nopoll,
   1566 	.d_mmap = nommap,
   1567 	.d_kqfilter = nokqfilter,
   1568 	.d_discard = nodiscard,
   1569 	.d_flag = D_OTHER | D_MPSAFE,
   1570 };
   1571 
   1572 /*
   1573  * sw_reg_strategy: handle swap i/o to regular files
   1574  */
   1575 static void
   1576 sw_reg_strategy(struct swapdev *sdp, struct buf *bp, int bn)
   1577 {
   1578 	struct vnode	*devvp;
   1579 	daddr_t		nbn;
   1580 	off_t		byteoff;
   1581 	int		offset;
   1582 	int		off, nra, error, sz, resid;
   1583 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
   1584 
   1585 	/*
   1586 	 * setup for main loop where we read filesystem blocks into
   1587 	 * our buffer.
   1588 	 */
   1589 	error = 0;
   1590 	bp->b_resid = bp->b_bcount;	/* nothing transferred yet! */
   1591 	byteoff = dbtob((uint64_t)bn);
   1592 
   1593 	offset = 0;
   1594 	for (resid = bp->b_resid; resid; resid -= sz) {
   1595 		struct buf *nbp;
   1596 
   1597 		/*
   1598 		 * translate byteoffset into block number.  return values:
   1599 		 *   devvp = vnode of underlying device
   1600 		 *     nbn = new block number (on underlying vnode dev)
   1601 		 *     nra = num blocks we can read-ahead (excludes requested
   1602 		 *           block)
   1603 		 */
   1604 		nra = 0;
   1605 		error = VOP_BMAP(sdp->swd_vp, byteoff / sdp->swd_bsize,
   1606 		    &devvp, &nbn, &nra);
   1607 
   1608 		if (error == 0 && nbn == (daddr_t)-1) {
   1609 			error = EIO;	/* failure */
   1610 		}
   1611 
   1612 		/*
   1613 		 * punt if there was an error or a hole in the file.
   1614 		 * we must wait for any i/o ops we have already started
   1615 		 * to finish before returning.
   1616 		 *
   1617 		 * XXX we could deal with holes here but it would be
   1618 		 * a hassle (in the write case).
   1619 		 */
   1620 		if (error) {
   1621 			break;
   1622 		}
   1623 
   1624 		/*
   1625 		 * compute the size ("sz") of this transfer (in bytes).
   1626 		 */
   1627 		off = byteoff % sdp->swd_bsize;
   1628 		sz = (1 + nra) * sdp->swd_bsize - off;
   1629 		if (sz > resid)
   1630 			sz = resid;
   1631 
   1632 		UVMHIST_LOG(pdhist, "sw_reg_strategy: "
   1633 		    "vp %#jx/%#jx offset %#jx/%#jx",
   1634 		    (uintptr_t)sdp->swd_vp, (uintptr_t)devvp, byteoff, nbn);
   1635 
   1636 		nbp = getiobuf(devvp, !uvm_lwp_is_pagedaemon(curlwp));
   1637 		if (nbp == NULL) {
   1638 			error = ENOMEM;
   1639 			break;
   1640 		}
   1641 		nestiobuf_setup(bp, nbp, offset, sz);
   1642 		iobuf_redirect(nbp, devvp);
   1643 		nbp->b_blkno = nbn + btodb(off);
   1644 		KASSERT(nbp->b_iodone == nestiobuf_iodone);
   1645 		nbp->b_private2 = sdp;
   1646 		nbp->b_iodone = sw_reg_biodone;
   1647 
   1648 		/* sort it in and start I/O if we are not over our limit */
   1649 		mutex_enter(&sdp->swd_lock);
   1650 		bufq_put(sdp->swd_tab, nbp);
   1651 		sw_reg_start(sdp);
   1652 		mutex_exit(&sdp->swd_lock);
   1653 
   1654 		/*
   1655 		 * at this point "nbp" might have been freed.
   1656 		 */
   1657 
   1658 		/*
   1659 		 * advance to the next I/O
   1660 		 */
   1661 		byteoff += sz;
   1662 		offset += sz;
   1663 	}
   1664 	if (resid > 0) {
   1665 		KASSERT(error != 0);
   1666 		nestiobuf_done(bp, resid, error);
   1667 	}
   1668 }
   1669 
   1670 /*
   1671  * sw_reg_start: start an I/O request on the requested swapdev
   1672  *
   1673  * => reqs are sorted by b_rawblkno (above)
   1674  */
   1675 static void
   1676 sw_reg_start(struct swapdev *sdp)
   1677 {
   1678 	struct buf	*bp;
   1679 	struct vnode	*vp;
   1680 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
   1681 
   1682 	KASSERT(mutex_owned(&sdp->swd_lock));
   1683 
   1684 	/* recursion control */
   1685 	if ((sdp->swd_flags & SWF_BUSY) != 0)
   1686 		return;
   1687 
   1688 	sdp->swd_flags |= SWF_BUSY;
   1689 
   1690 	while (sdp->swd_active < sdp->swd_maxactive) {
   1691 		bp = bufq_get(sdp->swd_tab);
   1692 		if (bp == NULL)
   1693 			break;
   1694 		sdp->swd_active++;
   1695 
   1696 		UVMHIST_LOG(pdhist,
   1697 		    "sw_reg_start:  bp %#jx vp %#jx blkno %#jx cnt %#jx",
   1698 		    (uintptr_t)bp, (uintptr_t)bp->b_vp, (uintptr_t)bp->b_blkno,
   1699 		    bp->b_bcount);
   1700 		vp = bp->b_vp;
   1701 		VOP_STRATEGY(vp, bp);
   1702 	}
   1703 	sdp->swd_flags &= ~SWF_BUSY;
   1704 }
   1705 
   1706 /*
   1707  * sw_reg_biodone: one of our i/o's has completed
   1708  */
   1709 static void
   1710 sw_reg_biodone(struct buf *bp)
   1711 {
   1712 	workqueue_enqueue(sw_reg_workqueue, &bp->b_work, NULL);
   1713 }
   1714 
   1715 /*
   1716  * sw_reg_iodone: one of our i/o's has completed and needs post-i/o cleanup
   1717  *
   1718  * => note that we can recover the vndbuf struct by casting the buf ptr
   1719  */
   1720 static void
   1721 sw_reg_iodone(struct work *wk, void *dummy)
   1722 {
   1723 	struct buf *nbp = (void *)wk;
   1724 	struct swapdev *sdp = nbp->b_private2;
   1725 
   1726 	KASSERT(&nbp->b_work == wk);
   1727 	UVMHIST_FUNC(__func__);
   1728 	UVMHIST_CALLARGS(pdhist, "  bp=%#jx vp=%#jx blkno=%#jx addr=%#jx",
   1729 	    (uintptr_t)nbp, (uintptr_t)nbp->b_vp, nbp->b_blkno,
   1730 	    (uintptr_t)nbp->b_data);
   1731 	UVMHIST_LOG(pdhist, "  cnt=%#jx resid=%#jx",
   1732 	    nbp->b_bcount, nbp->b_resid, 0, 0);
   1733 
   1734 	/*
   1735 	 * start next swapdev I/O if one is pending
   1736 	 */
   1737 	mutex_enter(&sdp->swd_lock);
   1738 	KASSERT(sdp->swd_active > 0);
   1739 	sdp->swd_active--;
   1740 	sw_reg_start(sdp);
   1741 	mutex_exit(&sdp->swd_lock);
   1742 
   1743 	nestiobuf_iodone(nbp);
   1744 }
   1745 
   1746 
   1747 /*
   1748  * uvm_swap_alloc: allocate space on swap
   1749  *
   1750  * => allocation is done "round robin" down the priority list, as we
   1751  *	allocate in a priority we "rotate" the circle queue.
   1752  * => space can be freed with uvm_swap_free
   1753  * => we return the page slot number in /dev/drum (0 == invalid slot)
   1754  * => we lock uvm_swap_data_lock
   1755  * => XXXMRG: "LESSOK" INTERFACE NEEDED TO EXTENT SYSTEM
   1756  */
   1757 int
   1758 uvm_swap_alloc(int *nslots /* IN/OUT */, bool lessok)
   1759 {
   1760 	struct swapdev *sdp;
   1761 	struct swappri *spp;
   1762 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
   1763 
   1764 	/*
   1765 	 * no swap devices configured yet?   definite failure.
   1766 	 */
   1767 	if (uvmexp.nswapdev < 1)
   1768 		return 0;
   1769 
   1770 	/*
   1771 	 * XXXJAK: BEGIN HACK
   1772 	 *
   1773 	 * blist_alloc() in subr_blist.c will panic if we try to allocate
   1774 	 * too many slots.
   1775 	 */
   1776 	if (*nslots > BLIST_MAX_ALLOC) {
   1777 		if (__predict_false(lessok == false))
   1778 			return 0;
   1779 		*nslots = BLIST_MAX_ALLOC;
   1780 	}
   1781 	/* XXXJAK: END HACK */
   1782 
   1783 	/*
   1784 	 * lock data lock, convert slots into blocks, and enter loop
   1785 	 */
   1786 	mutex_enter(&uvm_swap_data_lock);
   1787 
   1788 ReTry:	/* XXXMRG */
   1789 	LIST_FOREACH(spp, &swap_priority, spi_swappri) {
   1790 		TAILQ_FOREACH(sdp, &spp->spi_swapdev, swd_next) {
   1791 			uint64_t result;
   1792 
   1793 			/* if it's not enabled, then we can't swap from it */
   1794 			if ((sdp->swd_flags & SWF_ENABLE) == 0)
   1795 				continue;
   1796 			if (sdp->swd_npginuse + *nslots > sdp->swd_npages)
   1797 				continue;
   1798 			result = blist_alloc(sdp->swd_blist, *nslots);
   1799 			if (result == BLIST_NONE) {
   1800 				continue;
   1801 			}
   1802 			KASSERT(result < sdp->swd_drumsize);
   1803 
   1804 			/*
   1805 			 * successful allocation!  now rotate the tailq.
   1806 			 */
   1807 			TAILQ_REMOVE(&spp->spi_swapdev, sdp, swd_next);
   1808 			TAILQ_INSERT_TAIL(&spp->spi_swapdev, sdp, swd_next);
   1809 			sdp->swd_npginuse += *nslots;
   1810 			uvmexp.swpginuse += *nslots;
   1811 			mutex_exit(&uvm_swap_data_lock);
   1812 			/* done!  return drum slot number */
   1813 			UVMHIST_LOG(pdhist,
   1814 			    "success!  returning %jd slots starting at %jd",
   1815 			    *nslots, result + sdp->swd_drumoffset, 0, 0);
   1816 			return (result + sdp->swd_drumoffset);
   1817 		}
   1818 	}
   1819 
   1820 	/* XXXMRG: BEGIN HACK */
   1821 	if (*nslots > 1 && lessok) {
   1822 		*nslots = 1;
   1823 		/* XXXMRG: ugh!  blist should support this for us */
   1824 		goto ReTry;
   1825 	}
   1826 	/* XXXMRG: END HACK */
   1827 
   1828 	mutex_exit(&uvm_swap_data_lock);
   1829 	return 0;
   1830 }
   1831 
   1832 /*
   1833  * uvm_swapisfull: return true if most of available swap is allocated
   1834  * and in use.  we don't count some small portion as it may be inaccessible
   1835  * to us at any given moment, for example if there is lock contention or if
   1836  * pages are busy.
   1837  */
   1838 bool
   1839 uvm_swapisfull(void)
   1840 {
   1841 	int swpgonly;
   1842 	bool rv;
   1843 
   1844 	if (uvmexp.swpages == 0) {
   1845 		return true;
   1846 	}
   1847 
   1848 	mutex_enter(&uvm_swap_data_lock);
   1849 	KASSERT(uvmexp.swpgonly <= uvmexp.swpages);
   1850 	swpgonly = (int)((uint64_t)uvmexp.swpgonly * 100 /
   1851 	    uvm_swapisfull_factor);
   1852 	rv = (swpgonly >= uvmexp.swpgavail);
   1853 	mutex_exit(&uvm_swap_data_lock);
   1854 
   1855 	return (rv);
   1856 }
   1857 
   1858 /*
   1859  * uvm_swap_markbad: keep track of swap ranges where we've had i/o errors
   1860  *
   1861  * => we lock uvm_swap_data_lock
   1862  */
   1863 void
   1864 uvm_swap_markbad(int startslot, int nslots)
   1865 {
   1866 	struct swapdev *sdp;
   1867 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
   1868 
   1869 	mutex_enter(&uvm_swap_data_lock);
   1870 	sdp = swapdrum_getsdp(startslot);
   1871 	KASSERT(sdp != NULL);
   1872 
   1873 	/*
   1874 	 * we just keep track of how many pages have been marked bad
   1875 	 * in this device, to make everything add up in swap_off().
   1876 	 * we assume here that the range of slots will all be within
   1877 	 * one swap device.
   1878 	 */
   1879 	KASSERT(uvmexp.swpgonly >= nslots);
   1880 	atomic_add_int(&uvmexp.swpgonly, -nslots);
   1881 	sdp->swd_npgbad += nslots;
   1882 	UVMHIST_LOG(pdhist, "now %jd bad", sdp->swd_npgbad, 0,0,0);
   1883 	mutex_exit(&uvm_swap_data_lock);
   1884 }
   1885 
   1886 /*
   1887  * uvm_swap_free: free swap slots
   1888  *
   1889  * => this can be all or part of an allocation made by uvm_swap_alloc
   1890  * => we lock uvm_swap_data_lock
   1891  */
   1892 void
   1893 uvm_swap_free(int startslot, int nslots)
   1894 {
   1895 	struct swapdev *sdp;
   1896 	UVMHIST_FUNC(__func__);
   1897 	UVMHIST_CALLARGS(pdhist, "freeing %jd slots starting at %jd", nslots,
   1898 	    startslot, 0, 0);
   1899 
   1900 	/*
   1901 	 * ignore attempts to free the "bad" slot.
   1902 	 */
   1903 	if (startslot == SWSLOT_BAD) {
   1904 		return;
   1905 	}
   1906 
   1907 	/*
   1908 	 * convert drum slot offset back to sdp, free the blocks
   1909 	 * in the extent, and return.   must hold pri lock to do
   1910 	 * lookup and access the extent.
   1911 	 */
   1912 	mutex_enter(&uvm_swap_data_lock);
   1913 	sdp = swapdrum_getsdp(startslot);
   1914 	KASSERT(uvmexp.nswapdev >= 1);
   1915 	KASSERT(sdp != NULL);
   1916 	KASSERT(sdp->swd_npginuse >= nslots);
   1917 	blist_free(sdp->swd_blist, startslot - sdp->swd_drumoffset, nslots);
   1918 	sdp->swd_npginuse -= nslots;
   1919 	KASSERTMSG(uvmexp.swpginuse >= nslots, "swpginuse %d nslots %d",
   1920 	    uvmexp.swpginuse, nslots);
   1921 	uvmexp.swpginuse -= nslots;
   1922 	mutex_exit(&uvm_swap_data_lock);
   1923 }
   1924 
   1925 /*
   1926  * uvm_swap_put: put any number of pages into a contig place on swap
   1927  *
   1928  * => can be sync or async
   1929  */
   1930 int
   1931 uvm_swap_put(int swslot, struct vm_page **ppsp, int npages, int flags)
   1932 {
   1933 	int error;
   1934 
   1935 	error = uvm_swap_io(ppsp, swslot, npages, B_WRITE |
   1936 	    ((flags & PGO_SYNCIO) ? 0 : B_ASYNC));
   1937 	return error;
   1938 }
   1939 
   1940 /*
   1941  * uvm_swap_get: get a single page from swap
   1942  *
   1943  * => usually a sync op (from fault)
   1944  */
   1945 int
   1946 uvm_swap_get(struct vm_page *page, int swslot, int flags)
   1947 {
   1948 	int error;
   1949 
   1950 	atomic_inc_uint(&uvmexp.nswget);
   1951 	KASSERT(flags & PGO_SYNCIO);
   1952 	if (swslot == SWSLOT_BAD) {
   1953 		return EIO;
   1954 	}
   1955 
   1956 	error = uvm_swap_io(&page, swslot, 1, B_READ |
   1957 	    ((flags & PGO_SYNCIO) ? 0 : B_ASYNC));
   1958 	if (error == 0) {
   1959 		/*
   1960 		 * this page is no longer only in swap.
   1961 		 */
   1962 		KASSERT(uvmexp.swpgonly > 0);
   1963 		atomic_dec_uint(&uvmexp.swpgonly);
   1964 	}
   1965 	return error;
   1966 }
   1967 
   1968 #ifdef VMSWAP_ENCRYPTION
   1969 static void
   1970 uvm_swap_encrypt_pages(int startslot, void *p, int npages)
   1971 {
   1972 	struct swapdev *sdp;
   1973 	int i;
   1974 
   1975 	if (!atomic_load_relaxed(&uvm_swap_encrypt)) {
   1976 		return;
   1977 	}
   1978 
   1979 	/*
   1980 	 * Make sure there is a swap encryption key generated.  We
   1981 	 * generate it at the latest possible time in order to take
   1982 	 * advantage of as much entropy sampling as possible.
   1983 	 *
   1984 	 * We use uvm_swap_data_lock to serialize the conditional and
   1985 	 * key generation, but once the key is generated, it is stable
   1986 	 * until the swap device is unconfigured -- which it can't be
   1987 	 * until after we return.  (XXX How is this enforced?  By the
   1988 	 * page daemon's holding the page PG_BUSY?)
   1989 	 */
   1990 	mutex_enter(&uvm_swap_data_lock);
   1991 	sdp = swapdrum_getsdp(startslot);
   1992 	if (!sdp->swd_encinit) {
   1993 		uvm_swap_genkey(sdp);
   1994 	}
   1995 	KASSERT(sdp->swd_encinit);
   1996 	mutex_exit(&uvm_swap_data_lock);
   1997 
   1998 	for (i = 0; i < npages; i++) {
   1999 		int s = startslot + i;
   2000 
   2001 		KDASSERT(swapdrum_sdp_is(s, sdp));
   2002 		KASSERT(s >= sdp->swd_drumoffset);
   2003 		s -= sdp->swd_drumoffset;
   2004 		KASSERT(s < sdp->swd_drumsize);
   2005 		uvm_swap_encryptpage(sdp,
   2006 		    (void *)((uint8_t *)p + (vsize_t)i*PAGE_SIZE), s);
   2007 	}
   2008 }
   2009 
   2010 void
   2011 uvm_swap_decrypt_pages(int startslot, void *p, int npages)
   2012 {
   2013 	struct swapdev *sdp;
   2014 	bool encinit;
   2015 	int i;
   2016 
   2017 	if (!atomic_load_relaxed(&uvm_swap_encrypt)) {
   2018 		return;
   2019 	}
   2020 
   2021 	/*
   2022 	 * Get the sdp.  Everything about it except the encinit bit,
   2023 	 * saying whether the encryption key is initialized or not, is
   2024 	 * stable until all swap pages have been released and the
   2025 	 * device is removed.
   2026 	 */
   2027 	mutex_enter(&uvm_swap_data_lock);
   2028 	sdp = swapdrum_getsdp(startslot);
   2029 	encinit = sdp->swd_encinit;
   2030 	mutex_exit(&uvm_swap_data_lock);
   2031 
   2032 	/*
   2033 	 * The condition  uvm_swap_encrypt && !encinit  means we are
   2034 	 * reading a swap device which has never been written by the
   2035 	 * swapout process.  This must be a user read on /dev/drum.
   2036 	 * Just return all-zero.
   2037 	 */
   2038 	if (!encinit) {
   2039 		memset(p, 0, npages * PAGE_SIZE);
   2040 		return;
   2041 	}
   2042 	for (i = 0; i < npages; i++) {
   2043 		int s = startslot + i;
   2044 
   2045 		KDASSERT(swapdrum_sdp_is(s, sdp));
   2046 		KASSERT(s >= sdp->swd_drumoffset);
   2047 		s -= sdp->swd_drumoffset;
   2048 		KASSERT(s < sdp->swd_drumsize);
   2049 		uvm_swap_decryptpage(sdp,
   2050 		    (void *)((uint8_t *)p + (vsize_t)i*PAGE_SIZE), s);
   2051 	}
   2052 }
   2053 #endif /* VMSWAP_ENCRYPTION */
   2054 
   2055 /*
   2056  * uvm_swap_io: do an i/o operation to swap
   2057  */
   2058 static int
   2059 uvm_swap_io(struct vm_page **pps, int startslot, int npages, int flags)
   2060 {
   2061 	daddr_t startblk;
   2062 	struct	buf *bp;
   2063 	vaddr_t kva;
   2064 	int	error, mapinflags;
   2065 	bool write, async;
   2066 	UVMHIST_FUNC(__func__);
   2067 	UVMHIST_CALLARGS(pdhist,
   2068 	    "<- called, startslot=%jd, npages=%jd, flags=%#jx",
   2069 	    startslot, npages, flags, 0);
   2070 
   2071 	write = (flags & B_READ) == 0;
   2072 	async = (flags & B_ASYNC) != 0;
   2073 #ifdef VMSWAP_ENCRYPTION
   2074 	bool swap_encrypt = atomic_load_relaxed(&uvm_swap_encrypt);
   2075 #endif
   2076 
   2077 	/*
   2078 	 * allocate a buf for the i/o.
   2079 	 */
   2080 	KASSERT(!uvm_lwp_is_pagedaemon(curlwp) || write);
   2081 	KASSERT(!uvm_lwp_is_pagedaemon(curlwp) || async);
   2082 	bp = getiobuf(swapdev_vp, !uvm_lwp_is_pagedaemon(curlwp));
   2083 	if (bp == NULL) {
   2084 		uvm_aio_aiodone_pages(pps, npages, true, ENOMEM);
   2085 		return ENOMEM;
   2086 	}
   2087 
   2088 	/*
   2089 	 * convert starting drum slot to block number
   2090 	 */
   2091 	startblk = btodb((uint64_t)startslot << PAGE_SHIFT);
   2092 
   2093 	/*
   2094 	 * first, map the pages into the kernel.
   2095 	 */
   2096 	mapinflags = !write ?
   2097 	    UVMPAGER_MAPIN_WAITOK|UVMPAGER_MAPIN_READ :
   2098 	    UVMPAGER_MAPIN_WAITOK|UVMPAGER_MAPIN_WRITE;
   2099 #ifdef VMSWAP_ENCRYPTION
   2100 	if (write && swap_encrypt)	/* need to encrypt in-place */
   2101 		mapinflags |= UVMPAGER_MAPIN_READ;
   2102 #endif /* VMSWAP_ENCRYPTION */
   2103 	kva = uvm_pagermapin(pps, npages, mapinflags);
   2104 
   2105 #ifdef VMSWAP_ENCRYPTION
   2106 	/*
   2107 	 * encrypt writes in place if requested
   2108 	 */
   2109 	if (write) {
   2110 		uvm_swap_encrypt_pages(startslot, (void *)kva, npages);
   2111 	}
   2112 #endif /* VMSWAP_ENCRYPTION */
   2113 
   2114 	/*
   2115 	 * fill in the bp/sbp.   we currently route our i/o through
   2116 	 * /dev/drum's vnode [swapdev_vp].
   2117 	 */
   2118 	bp->b_cflags = BC_BUSY | BC_NOCACHE;
   2119 	bp->b_flags = (flags & (B_READ|B_ASYNC));
   2120 	bp->b_proc = &proc0;	/* XXX */
   2121 	bp->b_vnbufs.le_next = NOLIST;
   2122 	bp->b_data = (void *)kva;
   2123 	bp->b_blkno = startblk;
   2124 	bp->b_bufsize = bp->b_bcount = npages << PAGE_SHIFT;
   2125 
   2126 	/*
   2127 	 * bump v_numoutput (counter of number of active outputs).
   2128 	 */
   2129 	if (write) {
   2130 		mutex_enter(swapdev_vp->v_interlock);
   2131 		swapdev_vp->v_numoutput++;
   2132 		mutex_exit(swapdev_vp->v_interlock);
   2133 	}
   2134 
   2135 	/*
   2136 	 * for async ops we must set up the iodone handler.
   2137 	 */
   2138 	if (async) {
   2139 		bp->b_iodone = uvm_aio_aiodone;
   2140 		UVMHIST_LOG(pdhist, "doing async!", 0, 0, 0, 0);
   2141 		if (uvm_lwp_is_pagedaemon(curlwp))
   2142 			BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
   2143 		else
   2144 			BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
   2145 	} else {
   2146 		bp->b_iodone = NULL;
   2147 		BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
   2148 	}
   2149 	UVMHIST_LOG(pdhist,
   2150 	    "about to start io: data = %#jx blkno = %#jx, bcount = %jd",
   2151 	    (uintptr_t)bp->b_data, bp->b_blkno, bp->b_bcount, 0);
   2152 
   2153 	/*
   2154 	 * now we start the I/O, and if async, return.
   2155 	 */
   2156 	VOP_STRATEGY(swapdev_vp, bp);
   2157 	if (async) {
   2158 		/*
   2159 		 * Reads are always synchronous; if this changes, we
   2160 		 * need to add an asynchronous path for decryption.
   2161 		 */
   2162 		KASSERT(write);
   2163 		return 0;
   2164 	}
   2165 
   2166 	/*
   2167 	 * must be sync i/o.   wait for it to finish
   2168 	 */
   2169 	error = biowait(bp);
   2170 	if (error)
   2171 		goto out;
   2172 
   2173 #ifdef VMSWAP_ENCRYPTION
   2174 	/*
   2175 	 * decrypt reads in place if needed
   2176 	 */
   2177 	if (!write) {
   2178 		uvm_swap_decrypt_pages(startslot, (void *)kva, npages);
   2179 	}
   2180 #endif /* VMSWAP_ENCRYPTION */
   2181 out:
   2182 	/*
   2183 	 * kill the pager mapping
   2184 	 */
   2185 	uvm_pagermapout(kva, npages);
   2186 
   2187 	/*
   2188 	 * now dispose of the buf and we're done.
   2189 	 */
   2190 	if (write) {
   2191 		mutex_enter(swapdev_vp->v_interlock);
   2192 		vwakeup(bp);
   2193 		mutex_exit(swapdev_vp->v_interlock);
   2194 	}
   2195 	putiobuf(bp);
   2196 	UVMHIST_LOG(pdhist, "<- done (sync)  error=%jd", error, 0, 0, 0);
   2197 
   2198 	return (error);
   2199 }
   2200 
   2201 #ifdef VMSWAP_ENCRYPTION
   2202 /*
   2203  * uvm_swap_genkey(sdp)
   2204  *
   2205  *	Generate a key for swap encryption.
   2206  */
   2207 static void
   2208 uvm_swap_genkey(struct swapdev *sdp)
   2209 {
   2210 	uint8_t key[32];
   2211 
   2212 	KASSERT(!sdp->swd_encinit);
   2213 
   2214 	cprng_strong(kern_cprng, key, sizeof key, 0);
   2215 	aes_setenckey256(&sdp->swd_enckey, key);
   2216 	aes_setdeckey256(&sdp->swd_deckey, key);
   2217 	explicit_memset(key, 0, sizeof key);
   2218 
   2219 	sdp->swd_encinit = true;
   2220 }
   2221 
   2222 /*
   2223  * uvm_swap_encryptpage(sdp, kva, slot)
   2224  *
   2225  *	Encrypt one page of data at kva for the specified slot number
   2226  *	in the swap device.
   2227  */
   2228 static void
   2229 uvm_swap_encryptpage(struct swapdev *sdp, void *kva, int slot)
   2230 {
   2231 	uint8_t preiv[16] __aligned(16) = {0}, iv[16] __aligned(16);
   2232 
   2233 	/* iv := AES_k(le32enc(slot) || 0^96) */
   2234 	le32enc(preiv, slot);
   2235 	aes_enc(&sdp->swd_enckey, (const void *)preiv, iv, AES_256_NROUNDS);
   2236 
   2237 	/* *kva := AES-CBC_k(iv, *kva) */
   2238 	aes_cbc_enc(&sdp->swd_enckey, kva, kva, PAGE_SIZE, iv,
   2239 	    AES_256_NROUNDS);
   2240 
   2241 	explicit_memset(&iv, 0, sizeof iv);
   2242 }
   2243 
   2244 /*
   2245  * uvm_swap_decryptpage(sdp, kva, slot)
   2246  *
   2247  *	Decrypt one page of data at kva for the specified slot number
   2248  *	in the swap device.
   2249  */
   2250 static void
   2251 uvm_swap_decryptpage(struct swapdev *sdp, void *kva, int slot)
   2252 {
   2253 	uint8_t preiv[16] __aligned(16) = {0}, iv[16] __aligned(16);
   2254 
   2255 	/* iv := AES_k(le32enc(slot) || 0^96) */
   2256 	le32enc(preiv, slot);
   2257 	aes_enc(&sdp->swd_enckey, (const void *)preiv, iv, AES_256_NROUNDS);
   2258 
   2259 	/* *kva := AES-CBC^{-1}_k(iv, *kva) */
   2260 	aes_cbc_dec(&sdp->swd_deckey, kva, kva, PAGE_SIZE, iv,
   2261 	    AES_256_NROUNDS);
   2262 
   2263 	explicit_memset(&iv, 0, sizeof iv);
   2264 }
   2265 
   2266 static int
   2267 sysctl_kern_uvm_swap_encrypt(SYSCTLFN_ARGS)
   2268 {
   2269 	struct sysctlnode node;
   2270 	int swap_encrypt = uvm_swap_encrypt;
   2271 	int error;
   2272 
   2273 	node = *rnode;
   2274 	node.sysctl_data = &swap_encrypt;
   2275 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2276 	if (error != 0 || newp == NULL) {
   2277 		return error;
   2278 	}
   2279 
   2280 	/*
   2281 	 * allow a change only when no swap is configured to ensure
   2282 	 * that uvm_swap_encrypt is a constant from the POV of
   2283 	 * any swap devices.
   2284 	 */
   2285 	error = 0;
   2286 	mutex_enter(&uvm_swap_data_lock);
   2287 	if (uvm_swap_encrypt != swap_encrypt) {
   2288 		if (LIST_EMPTY(&swap_priority)) {
   2289 			uvm_swap_encrypt = swap_encrypt;
   2290 		} else {
   2291 			error = EBUSY;
   2292 		}
   2293 	}
   2294 	mutex_exit(&uvm_swap_data_lock);
   2295 
   2296 	return error;
   2297 }
   2298 
   2299 SYSCTL_SETUP(sysctl_uvmswap_setup, "sysctl uvmswap setup")
   2300 {
   2301 
   2302 	sysctl_createv(clog, 0, NULL, NULL,
   2303 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_BOOL, "swap_encrypt",
   2304 	    SYSCTL_DESCR("Encrypt data when swapped out to disk"),
   2305 	    sysctl_kern_uvm_swap_encrypt, 0, NULL, 0,
   2306 	    CTL_VM, CTL_CREATE, CTL_EOL);
   2307 }
   2308 #endif /* VMSWAP_ENCRYPTION */
   2309