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