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