xref: /freebsd/sys/vm/swap_pager.c (revision d26c565597b88eb5c6000dbba9e348debe7095e3)
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1998 Matthew Dillon,
5  * Copyright (c) 1994 John S. Dyson
6  * Copyright (c) 1990 University of Utah.
7  * Copyright (c) 1982, 1986, 1989, 1993
8  *	The Regents of the University of California.  All rights reserved.
9  *
10  * This code is derived from software contributed to Berkeley by
11  * the Systems Programming Group of the University of Utah Computer
12  * Science Department.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. All advertising materials mentioning features or use of this software
23  *    must display the following acknowledgement:
24  *	This product includes software developed by the University of
25  *	California, Berkeley and its contributors.
26  * 4. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  *
42  *				New Swap System
43  *				Matthew Dillon
44  *
45  * Radix Bitmap 'blists'.
46  *
47  *	- The new swapper uses the new radix bitmap code.  This should scale
48  *	  to arbitrarily small or arbitrarily large swap spaces and an almost
49  *	  arbitrary degree of fragmentation.
50  *
51  * Features:
52  *
53  *	- on the fly reallocation of swap during putpages.  The new system
54  *	  does not try to keep previously allocated swap blocks for dirty
55  *	  pages.
56  *
57  *	- on the fly deallocation of swap
58  *
59  *	- No more garbage collection required.  Unnecessarily allocated swap
60  *	  blocks only exist for dirty vm_page_t's now and these are already
61  *	  cycled (in a high-load system) by the pager.  We also do on-the-fly
62  *	  removal of invalidated swap blocks when a page is destroyed
63  *	  or renamed.
64  *
65  * from: Utah $Hdr: swap_pager.c 1.4 91/04/30$
66  */
67 
68 #include <sys/cdefs.h>
69 #include "opt_vm.h"
70 
71 #include <sys/param.h>
72 #include <sys/bio.h>
73 #include <sys/blist.h>
74 #include <sys/buf.h>
75 #include <sys/conf.h>
76 #include <sys/disk.h>
77 #include <sys/disklabel.h>
78 #include <sys/eventhandler.h>
79 #include <sys/fcntl.h>
80 #include <sys/limits.h>
81 #include <sys/lock.h>
82 #include <sys/kernel.h>
83 #include <sys/mount.h>
84 #include <sys/namei.h>
85 #include <sys/malloc.h>
86 #include <sys/pctrie.h>
87 #include <sys/priv.h>
88 #include <sys/proc.h>
89 #include <sys/racct.h>
90 #include <sys/resource.h>
91 #include <sys/resourcevar.h>
92 #include <sys/rwlock.h>
93 #include <sys/sbuf.h>
94 #include <sys/sysctl.h>
95 #include <sys/sysproto.h>
96 #include <sys/systm.h>
97 #include <sys/sx.h>
98 #include <sys/unistd.h>
99 #include <sys/user.h>
100 #include <sys/vmmeter.h>
101 #include <sys/vnode.h>
102 
103 #include <security/mac/mac_framework.h>
104 
105 #include <vm/vm.h>
106 #include <vm/pmap.h>
107 #include <vm/vm_map.h>
108 #include <vm/vm_kern.h>
109 #include <vm/vm_object.h>
110 #include <vm/vm_page.h>
111 #include <vm/vm_pager.h>
112 #include <vm/vm_pageout.h>
113 #include <vm/vm_param.h>
114 #include <vm/swap_pager.h>
115 #include <vm/vm_extern.h>
116 #include <vm/uma.h>
117 
118 #include <geom/geom.h>
119 
120 /*
121  * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64.
122  * The 64-page limit is due to the radix code (kern/subr_blist.c).
123  */
124 #ifndef MAX_PAGEOUT_CLUSTER
125 #define	MAX_PAGEOUT_CLUSTER	32
126 #endif
127 
128 #if !defined(SWB_NPAGES)
129 #define SWB_NPAGES	MAX_PAGEOUT_CLUSTER
130 #endif
131 
132 #define	SWAP_META_PAGES		PCTRIE_COUNT
133 
134 /*
135  * A swblk structure maps each page index within a
136  * SWAP_META_PAGES-aligned and sized range to the address of an
137  * on-disk swap block (or SWAPBLK_NONE). The collection of these
138  * mappings for an entire vm object is implemented as a pc-trie.
139  */
140 struct swblk {
141 	vm_pindex_t	p;
142 	daddr_t		d[SWAP_META_PAGES];
143 };
144 
145 /*
146  * A page_range structure records the start address and length of a sequence of
147  * mapped page addresses.
148  */
149 struct page_range {
150 	daddr_t start;
151 	daddr_t num;
152 };
153 
154 static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data");
155 static struct mtx sw_dev_mtx;
156 static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
157 static struct swdevt *swdevhd;	/* Allocate from here next */
158 static int nswapdev;		/* Number of swap devices */
159 int swap_pager_avail;
160 static struct sx swdev_syscall_lock;	/* serialize swap(on|off) */
161 
162 static __exclusive_cache_line u_long swap_reserved;
163 static u_long swap_total;
164 static int sysctl_page_shift(SYSCTL_HANDLER_ARGS);
165 
166 static SYSCTL_NODE(_vm_stats, OID_AUTO, swap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
167     "VM swap stats");
168 
169 SYSCTL_PROC(_vm, OID_AUTO, swap_reserved, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
170     &swap_reserved, 0, sysctl_page_shift, "QU",
171     "Amount of swap storage needed to back all allocated anonymous memory.");
172 SYSCTL_PROC(_vm, OID_AUTO, swap_total, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
173     &swap_total, 0, sysctl_page_shift, "QU",
174     "Total amount of available swap storage.");
175 
176 int vm_overcommit __read_mostly = 0;
177 SYSCTL_INT(_vm, VM_OVERCOMMIT, overcommit, CTLFLAG_RW, &vm_overcommit, 0,
178     "Configure virtual memory overcommit behavior. See tuning(7) "
179     "for details.");
180 static unsigned long swzone;
181 SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
182     "Actual size of swap metadata zone");
183 static unsigned long swap_maxpages;
184 SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
185     "Maximum amount of swap supported");
186 
187 static COUNTER_U64_DEFINE_EARLY(swap_free_deferred);
188 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_deferred,
189     CTLFLAG_RD, &swap_free_deferred,
190     "Number of pages that deferred freeing swap space");
191 
192 static COUNTER_U64_DEFINE_EARLY(swap_free_completed);
193 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_completed,
194     CTLFLAG_RD, &swap_free_completed,
195     "Number of deferred frees completed");
196 
197 static int
198 sysctl_page_shift(SYSCTL_HANDLER_ARGS)
199 {
200 	uint64_t newval;
201 	u_long value = *(u_long *)arg1;
202 
203 	newval = ((uint64_t)value) << PAGE_SHIFT;
204 	return (sysctl_handle_64(oidp, &newval, 0, req));
205 }
206 
207 static bool
208 swap_reserve_by_cred_rlimit(u_long pincr, struct ucred *cred, int oc)
209 {
210 	struct uidinfo *uip;
211 	u_long prev;
212 
213 	uip = cred->cr_ruidinfo;
214 
215 	prev = atomic_fetchadd_long(&uip->ui_vmsize, pincr);
216 	if ((oc & SWAP_RESERVE_RLIMIT_ON) != 0 &&
217 	    prev + pincr > lim_cur(curthread, RLIMIT_SWAP) &&
218 	    priv_check(curthread, PRIV_VM_SWAP_NORLIMIT) != 0) {
219 		prev = atomic_fetchadd_long(&uip->ui_vmsize, -pincr);
220 		KASSERT(prev >= pincr,
221 		    ("negative vmsize for uid %d\n", uip->ui_uid));
222 		return (false);
223 	}
224 	return (true);
225 }
226 
227 static void
228 swap_release_by_cred_rlimit(u_long pdecr, struct ucred *cred)
229 {
230 	struct uidinfo *uip;
231 #ifdef INVARIANTS
232 	u_long prev;
233 #endif
234 
235 	uip = cred->cr_ruidinfo;
236 
237 #ifdef INVARIANTS
238 	prev = atomic_fetchadd_long(&uip->ui_vmsize, -pdecr);
239 	KASSERT(prev >= pdecr,
240 	    ("negative vmsize for uid %d\n", uip->ui_uid));
241 #else
242 	atomic_subtract_long(&uip->ui_vmsize, pdecr);
243 #endif
244 }
245 
246 static void
247 swap_reserve_force_rlimit(u_long pincr, struct ucred *cred)
248 {
249 	struct uidinfo *uip;
250 
251 	uip = cred->cr_ruidinfo;
252 	atomic_add_long(&uip->ui_vmsize, pincr);
253 }
254 
255 bool
256 swap_reserve(vm_ooffset_t incr)
257 {
258 
259 	return (swap_reserve_by_cred(incr, curthread->td_ucred));
260 }
261 
262 bool
263 swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
264 {
265 	u_long r, s, prev, pincr;
266 #ifdef RACCT
267 	int error;
268 #endif
269 	int oc;
270 	static int curfail;
271 	static struct timeval lastfail;
272 
273 	KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK",
274 	    __func__, (uintmax_t)incr));
275 
276 #ifdef RACCT
277 	if (RACCT_ENABLED()) {
278 		PROC_LOCK(curproc);
279 		error = racct_add(curproc, RACCT_SWAP, incr);
280 		PROC_UNLOCK(curproc);
281 		if (error != 0)
282 			return (false);
283 	}
284 #endif
285 
286 	pincr = atop(incr);
287 	prev = atomic_fetchadd_long(&swap_reserved, pincr);
288 	r = prev + pincr;
289 	s = swap_total;
290 	oc = atomic_load_int(&vm_overcommit);
291 	if (r > s && (oc & SWAP_RESERVE_ALLOW_NONWIRED) != 0) {
292 		s += vm_cnt.v_page_count - vm_cnt.v_free_reserved -
293 		    vm_wire_count();
294 	}
295 	if ((oc & SWAP_RESERVE_FORCE_ON) != 0 && r > s &&
296 	    priv_check(curthread, PRIV_VM_SWAP_NOQUOTA) != 0) {
297 		prev = atomic_fetchadd_long(&swap_reserved, -pincr);
298 		KASSERT(prev >= pincr,
299 		    ("swap_reserved < incr on overcommit fail"));
300 		goto out_error;
301 	}
302 
303 	if (!swap_reserve_by_cred_rlimit(pincr, cred, oc)) {
304 		prev = atomic_fetchadd_long(&swap_reserved, -pincr);
305 		KASSERT(prev >= pincr,
306 		    ("swap_reserved < incr on overcommit fail"));
307 		goto out_error;
308 	}
309 
310 	return (true);
311 
312 out_error:
313 	if (ppsratecheck(&lastfail, &curfail, 1)) {
314 		printf("uid %d, pid %d: swap reservation "
315 		    "for %jd bytes failed\n",
316 		    cred->cr_ruidinfo->ui_uid, curproc->p_pid, incr);
317 	}
318 #ifdef RACCT
319 	if (RACCT_ENABLED()) {
320 		PROC_LOCK(curproc);
321 		racct_sub(curproc, RACCT_SWAP, incr);
322 		PROC_UNLOCK(curproc);
323 	}
324 #endif
325 
326 	return (false);
327 }
328 
329 void
330 swap_reserve_force(vm_ooffset_t incr)
331 {
332 	u_long pincr;
333 
334 	KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK",
335 	    __func__, (uintmax_t)incr));
336 
337 #ifdef RACCT
338 	if (RACCT_ENABLED()) {
339 		PROC_LOCK(curproc);
340 		racct_add_force(curproc, RACCT_SWAP, incr);
341 		PROC_UNLOCK(curproc);
342 	}
343 #endif
344 	pincr = atop(incr);
345 	atomic_add_long(&swap_reserved, pincr);
346 	swap_reserve_force_rlimit(pincr, curthread->td_ucred);
347 }
348 
349 void
350 swap_release(vm_ooffset_t decr)
351 {
352 	struct ucred *cred;
353 
354 	PROC_LOCK(curproc);
355 	cred = curproc->p_ucred;
356 	swap_release_by_cred(decr, cred);
357 	PROC_UNLOCK(curproc);
358 }
359 
360 void
361 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
362 {
363 	u_long pdecr;
364 #ifdef INVARIANTS
365 	u_long prev;
366 #endif
367 
368 	KASSERT((decr & PAGE_MASK) == 0, ("%s: decr: %ju & PAGE_MASK",
369 	    __func__, (uintmax_t)decr));
370 
371 	pdecr = atop(decr);
372 #ifdef INVARIANTS
373 	prev = atomic_fetchadd_long(&swap_reserved, -pdecr);
374 	KASSERT(prev >= pdecr, ("swap_reserved < decr"));
375 #else
376 	atomic_subtract_long(&swap_reserved, pdecr);
377 #endif
378 
379 	swap_release_by_cred_rlimit(pdecr, cred);
380 #ifdef RACCT
381 	if (racct_enable)
382 		racct_sub_cred(cred, RACCT_SWAP, decr);
383 #endif
384 }
385 
386 static int swap_pager_full = 2;	/* swap space exhaustion (task killing) */
387 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
388 static struct mtx swbuf_mtx;	/* to sync nsw_wcount_async */
389 static int nsw_wcount_async;	/* limit async write buffers */
390 static int nsw_wcount_async_max;/* assigned maximum			*/
391 int nsw_cluster_max; 		/* maximum VOP I/O allowed		*/
392 
393 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
394 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
395     CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
396     "Maximum running async swap ops");
397 static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS);
398 SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD |
399     CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A",
400     "Swap Fragmentation Info");
401 
402 static struct sx sw_alloc_sx;
403 
404 /*
405  * "named" and "unnamed" anon region objects.  Try to reduce the overhead
406  * of searching a named list by hashing it just a little.
407  */
408 
409 #define NOBJLISTS		8
410 
411 #define NOBJLIST(handle)	\
412 	(&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
413 
414 static struct pagerlst	swap_pager_object_list[NOBJLISTS];
415 static uma_zone_t swwbuf_zone;
416 static uma_zone_t swrbuf_zone;
417 static uma_zone_t swblk_zone;
418 static uma_zone_t swpctrie_zone;
419 
420 /*
421  * pagerops for OBJT_SWAP - "swap pager".  Some ops are also global procedure
422  * calls hooked from other parts of the VM system and do not appear here.
423  * (see vm/swap_pager.h).
424  */
425 static vm_object_t
426 		swap_pager_alloc(void *handle, vm_ooffset_t size,
427 		    vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
428 static void	swap_pager_dealloc(vm_object_t object);
429 static int	swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
430     int *);
431 static int	swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
432     int *, pgo_getpages_iodone_t, void *);
433 static void	swap_pager_putpages(vm_object_t, vm_page_t *, int, int, int *);
434 static boolean_t
435 		swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
436 static void	swap_pager_init(void);
437 static void	swap_pager_unswapped(vm_page_t);
438 static void	swap_pager_swapoff(struct swdevt *sp);
439 static void	swap_pager_update_writecount(vm_object_t object,
440     vm_offset_t start, vm_offset_t end);
441 static void	swap_pager_release_writecount(vm_object_t object,
442     vm_offset_t start, vm_offset_t end);
443 static void	swap_pager_freespace_pgo(vm_object_t object, vm_pindex_t start,
444     vm_size_t size);
445 
446 const struct pagerops swappagerops = {
447 	.pgo_kvme_type = KVME_TYPE_SWAP,
448 	.pgo_init =	swap_pager_init,	/* early system initialization of pager	*/
449 	.pgo_alloc =	swap_pager_alloc,	/* allocate an OBJT_SWAP object */
450 	.pgo_dealloc =	swap_pager_dealloc,	/* deallocate an OBJT_SWAP object */
451 	.pgo_getpages =	swap_pager_getpages,	/* pagein */
452 	.pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
453 	.pgo_putpages =	swap_pager_putpages,	/* pageout */
454 	.pgo_haspage =	swap_pager_haspage,	/* get backing store status for page */
455 	.pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
456 	.pgo_update_writecount = swap_pager_update_writecount,
457 	.pgo_release_writecount = swap_pager_release_writecount,
458 	.pgo_freespace = swap_pager_freespace_pgo,
459 };
460 
461 /*
462  * swap_*() routines are externally accessible.  swp_*() routines are
463  * internal.
464  */
465 static int nswap_lowat = 128;	/* in pages, swap_pager_almost_full warn */
466 static int nswap_hiwat = 512;	/* in pages, swap_pager_almost_full warn */
467 
468 SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
469     "Maximum size of a swap block in pages");
470 
471 static void	swp_sizecheck(void);
472 static void	swp_pager_async_iodone(struct buf *bp);
473 static bool	swp_pager_swblk_empty(struct swblk *sb, int start, int limit);
474 static void	swp_pager_free_empty_swblk(vm_object_t, struct swblk *sb);
475 static int	swapongeom(struct vnode *);
476 static int	swaponvp(struct thread *, struct vnode *, u_long);
477 static int	swapoff_one(struct swdevt *sp, struct ucred *cred,
478 		    u_int flags);
479 
480 /*
481  * Swap bitmap functions
482  */
483 static void	swp_pager_freeswapspace(const struct page_range *range);
484 static daddr_t	swp_pager_getswapspace(int *npages);
485 
486 /*
487  * Metadata functions
488  */
489 static daddr_t swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
490 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t,
491     vm_size_t *);
492 static void swp_pager_meta_transfer(vm_object_t src, vm_object_t dst,
493     vm_pindex_t pindex, vm_pindex_t count, vm_size_t *freed);
494 static void swp_pager_meta_free_all(vm_object_t);
495 static daddr_t swp_pager_meta_lookup(vm_object_t, vm_pindex_t);
496 
497 static void
498 swp_pager_init_freerange(struct page_range *range)
499 {
500 	range->start = SWAPBLK_NONE;
501 	range->num = 0;
502 }
503 
504 static void
505 swp_pager_update_freerange(struct page_range *range, daddr_t addr)
506 {
507 	if (range->start + range->num == addr) {
508 		range->num++;
509 	} else {
510 		swp_pager_freeswapspace(range);
511 		range->start = addr;
512 		range->num = 1;
513 	}
514 }
515 
516 static void *
517 swblk_trie_alloc(struct pctrie *ptree)
518 {
519 
520 	return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
521 	    M_USE_RESERVE : 0)));
522 }
523 
524 static void
525 swblk_trie_free(struct pctrie *ptree, void *node)
526 {
527 
528 	uma_zfree(swpctrie_zone, node);
529 }
530 
531 PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
532 
533 /*
534  * SWP_SIZECHECK() -	update swap_pager_full indication
535  *
536  *	update the swap_pager_almost_full indication and warn when we are
537  *	about to run out of swap space, using lowat/hiwat hysteresis.
538  *
539  *	Clear swap_pager_full ( task killing ) indication when lowat is met.
540  *
541  *	No restrictions on call
542  *	This routine may not block.
543  */
544 static void
545 swp_sizecheck(void)
546 {
547 
548 	if (swap_pager_avail < nswap_lowat) {
549 		if (swap_pager_almost_full == 0) {
550 			printf("swap_pager: out of swap space\n");
551 			swap_pager_almost_full = 1;
552 		}
553 	} else {
554 		swap_pager_full = 0;
555 		if (swap_pager_avail > nswap_hiwat)
556 			swap_pager_almost_full = 0;
557 	}
558 }
559 
560 /*
561  * SWAP_PAGER_INIT() -	initialize the swap pager!
562  *
563  *	Expected to be started from system init.  NOTE:  This code is run
564  *	before much else so be careful what you depend on.  Most of the VM
565  *	system has yet to be initialized at this point.
566  */
567 static void
568 swap_pager_init(void)
569 {
570 	/*
571 	 * Initialize object lists
572 	 */
573 	int i;
574 
575 	for (i = 0; i < NOBJLISTS; ++i)
576 		TAILQ_INIT(&swap_pager_object_list[i]);
577 	mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
578 	sx_init(&sw_alloc_sx, "swspsx");
579 	sx_init(&swdev_syscall_lock, "swsysc");
580 
581 	/*
582 	 * The nsw_cluster_max is constrained by the bp->b_pages[]
583 	 * array, which has maxphys / PAGE_SIZE entries, and our locally
584 	 * defined MAX_PAGEOUT_CLUSTER.   Also be aware that swap ops are
585 	 * constrained by the swap device interleave stripe size.
586 	 *
587 	 * Initialized early so that GEOM_ELI can see it.
588 	 */
589 	nsw_cluster_max = min(maxphys / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
590 }
591 
592 /*
593  * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
594  *
595  *	Expected to be started from pageout process once, prior to entering
596  *	its main loop.
597  */
598 void
599 swap_pager_swap_init(void)
600 {
601 	unsigned long n, n2;
602 
603 	/*
604 	 * Number of in-transit swap bp operations.  Don't
605 	 * exhaust the pbufs completely.  Make sure we
606 	 * initialize workable values (0 will work for hysteresis
607 	 * but it isn't very efficient).
608 	 *
609 	 * Currently we hardwire nsw_wcount_async to 4.  This limit is
610 	 * designed to prevent other I/O from having high latencies due to
611 	 * our pageout I/O.  The value 4 works well for one or two active swap
612 	 * devices but is probably a little low if you have more.  Even so,
613 	 * a higher value would probably generate only a limited improvement
614 	 * with three or four active swap devices since the system does not
615 	 * typically have to pageout at extreme bandwidths.   We will want
616 	 * at least 2 per swap devices, and 4 is a pretty good value if you
617 	 * have one NFS swap device due to the command/ack latency over NFS.
618 	 * So it all works out pretty well.
619 	 *
620 	 * nsw_cluster_max is initialized in swap_pager_init().
621 	 */
622 
623 	nsw_wcount_async = 4;
624 	nsw_wcount_async_max = nsw_wcount_async;
625 	mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
626 
627 	swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
628 	swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
629 
630 	/*
631 	 * Initialize our zone, taking the user's requested size or
632 	 * estimating the number we need based on the number of pages
633 	 * in the system.
634 	 */
635 	n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
636 	    vm_cnt.v_page_count / 2;
637 	swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
638 	    pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0);
639 	swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
640 	    NULL, NULL, _Alignof(struct swblk) - 1, 0);
641 	n2 = n;
642 	do {
643 		if (uma_zone_reserve_kva(swblk_zone, n))
644 			break;
645 		/*
646 		 * if the allocation failed, try a zone two thirds the
647 		 * size of the previous attempt.
648 		 */
649 		n -= ((n + 2) / 3);
650 	} while (n > 0);
651 
652 	/*
653 	 * Often uma_zone_reserve_kva() cannot reserve exactly the
654 	 * requested size.  Account for the difference when
655 	 * calculating swap_maxpages.
656 	 */
657 	n = uma_zone_get_max(swblk_zone);
658 
659 	if (n < n2)
660 		printf("Swap blk zone entries changed from %lu to %lu.\n",
661 		    n2, n);
662 	/* absolute maximum we can handle assuming 100% efficiency */
663 	swap_maxpages = n * SWAP_META_PAGES;
664 	swzone = n * sizeof(struct swblk);
665 	if (!uma_zone_reserve_kva(swpctrie_zone, n))
666 		printf("Cannot reserve swap pctrie zone, "
667 		    "reduce kern.maxswzone.\n");
668 }
669 
670 bool
671 swap_pager_init_object(vm_object_t object, void *handle, struct ucred *cred,
672     vm_ooffset_t size, vm_ooffset_t offset)
673 {
674 	if (cred != NULL) {
675 		if (!swap_reserve_by_cred(size, cred))
676 			return (false);
677 		crhold(cred);
678 	}
679 
680 	object->un_pager.swp.writemappings = 0;
681 	object->handle = handle;
682 	if (cred != NULL) {
683 		object->cred = cred;
684 		object->charge = size;
685 	}
686 	return (true);
687 }
688 
689 static vm_object_t
690 swap_pager_alloc_init(objtype_t otype, void *handle, struct ucred *cred,
691     vm_ooffset_t size, vm_ooffset_t offset)
692 {
693 	vm_object_t object;
694 
695 	/*
696 	 * The un_pager.swp.swp_blks trie is initialized by
697 	 * vm_object_allocate() to ensure the correct order of
698 	 * visibility to other threads.
699 	 */
700 	object = vm_object_allocate(otype, OFF_TO_IDX(offset +
701 	    PAGE_MASK + size));
702 
703 	if (!swap_pager_init_object(object, handle, cred, size, offset)) {
704 		vm_object_deallocate(object);
705 		return (NULL);
706 	}
707 	return (object);
708 }
709 
710 /*
711  * SWAP_PAGER_ALLOC() -	allocate a new OBJT_SWAP VM object and instantiate
712  *			its metadata structures.
713  *
714  *	This routine is called from the mmap and fork code to create a new
715  *	OBJT_SWAP object.
716  *
717  *	This routine must ensure that no live duplicate is created for
718  *	the named object request, which is protected against by
719  *	holding the sw_alloc_sx lock in case handle != NULL.
720  */
721 static vm_object_t
722 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
723     vm_ooffset_t offset, struct ucred *cred)
724 {
725 	vm_object_t object;
726 
727 	if (handle != NULL) {
728 		/*
729 		 * Reference existing named region or allocate new one.  There
730 		 * should not be a race here against swp_pager_meta_build()
731 		 * as called from vm_page_remove() in regards to the lookup
732 		 * of the handle.
733 		 */
734 		sx_xlock(&sw_alloc_sx);
735 		object = vm_pager_object_lookup(NOBJLIST(handle), handle);
736 		if (object == NULL) {
737 			object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
738 			    size, offset);
739 			if (object != NULL) {
740 				TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
741 				    object, pager_object_list);
742 			}
743 		}
744 		sx_xunlock(&sw_alloc_sx);
745 	} else {
746 		object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
747 		    size, offset);
748 	}
749 	return (object);
750 }
751 
752 /*
753  * SWAP_PAGER_DEALLOC() -	remove swap metadata from object
754  *
755  *	The swap backing for the object is destroyed.  The code is
756  *	designed such that we can reinstantiate it later, but this
757  *	routine is typically called only when the entire object is
758  *	about to be destroyed.
759  *
760  *	The object must be locked.
761  */
762 static void
763 swap_pager_dealloc(vm_object_t object)
764 {
765 
766 	VM_OBJECT_ASSERT_WLOCKED(object);
767 	KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
768 
769 	/*
770 	 * Remove from list right away so lookups will fail if we block for
771 	 * pageout completion.
772 	 */
773 	if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
774 		VM_OBJECT_WUNLOCK(object);
775 		sx_xlock(&sw_alloc_sx);
776 		TAILQ_REMOVE(NOBJLIST(object->handle), object,
777 		    pager_object_list);
778 		sx_xunlock(&sw_alloc_sx);
779 		VM_OBJECT_WLOCK(object);
780 	}
781 
782 	vm_object_pip_wait(object, "swpdea");
783 
784 	/*
785 	 * Free all remaining metadata.  We only bother to free it from
786 	 * the swap meta data.  We do not attempt to free swapblk's still
787 	 * associated with vm_page_t's for this object.  We do not care
788 	 * if paging is still in progress on some objects.
789 	 */
790 	swp_pager_meta_free_all(object);
791 	object->handle = NULL;
792 	object->type = OBJT_DEAD;
793 
794 	/*
795 	 * Release the allocation charge.
796 	 */
797 	if (object->cred != NULL) {
798 		swap_release_by_cred(object->charge, object->cred);
799 		object->charge = 0;
800 		crfree(object->cred);
801 		object->cred = NULL;
802 	}
803 
804 	/*
805 	 * Hide the object from swap_pager_swapoff().
806 	 */
807 	vm_object_clear_flag(object, OBJ_SWAP);
808 }
809 
810 /************************************************************************
811  *			SWAP PAGER BITMAP ROUTINES			*
812  ************************************************************************/
813 
814 /*
815  * SWP_PAGER_GETSWAPSPACE() -	allocate raw swap space
816  *
817  *	Allocate swap for up to the requested number of pages.  The
818  *	starting swap block number (a page index) is returned or
819  *	SWAPBLK_NONE if the allocation failed.
820  *
821  *	Also has the side effect of advising that somebody made a mistake
822  *	when they configured swap and didn't configure enough.
823  *
824  *	This routine may not sleep.
825  *
826  *	We allocate in round-robin fashion from the configured devices.
827  */
828 static daddr_t
829 swp_pager_getswapspace(int *io_npages)
830 {
831 	daddr_t blk;
832 	struct swdevt *sp;
833 	int mpages, npages;
834 
835 	KASSERT(*io_npages >= 1,
836 	    ("%s: npages not positive", __func__));
837 	blk = SWAPBLK_NONE;
838 	mpages = *io_npages;
839 	npages = imin(BLIST_MAX_ALLOC, mpages);
840 	mtx_lock(&sw_dev_mtx);
841 	sp = swdevhd;
842 	while (!TAILQ_EMPTY(&swtailq)) {
843 		if (sp == NULL)
844 			sp = TAILQ_FIRST(&swtailq);
845 		if ((sp->sw_flags & SW_CLOSING) == 0)
846 			blk = blist_alloc(sp->sw_blist, &npages, mpages);
847 		if (blk != SWAPBLK_NONE)
848 			break;
849 		sp = TAILQ_NEXT(sp, sw_list);
850 		if (swdevhd == sp) {
851 			if (npages == 1)
852 				break;
853 			mpages = npages - 1;
854 			npages >>= 1;
855 		}
856 	}
857 	if (blk != SWAPBLK_NONE) {
858 		*io_npages = npages;
859 		blk += sp->sw_first;
860 		sp->sw_used += npages;
861 		swap_pager_avail -= npages;
862 		swp_sizecheck();
863 		swdevhd = TAILQ_NEXT(sp, sw_list);
864 	} else {
865 		if (swap_pager_full != 2) {
866 			printf("swp_pager_getswapspace(%d): failed\n",
867 			    *io_npages);
868 			swap_pager_full = 2;
869 			swap_pager_almost_full = 1;
870 		}
871 		swdevhd = NULL;
872 	}
873 	mtx_unlock(&sw_dev_mtx);
874 	return (blk);
875 }
876 
877 static bool
878 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
879 {
880 
881 	return (blk >= sp->sw_first && blk < sp->sw_end);
882 }
883 
884 static void
885 swp_pager_strategy(struct buf *bp)
886 {
887 	struct swdevt *sp;
888 
889 	mtx_lock(&sw_dev_mtx);
890 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
891 		if (swp_pager_isondev(bp->b_blkno, sp)) {
892 			mtx_unlock(&sw_dev_mtx);
893 			if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
894 			    unmapped_buf_allowed) {
895 				bp->b_data = unmapped_buf;
896 				bp->b_offset = 0;
897 			} else {
898 				pmap_qenter((vm_offset_t)bp->b_data,
899 				    &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
900 			}
901 			sp->sw_strategy(bp, sp);
902 			return;
903 		}
904 	}
905 	panic("Swapdev not found");
906 }
907 
908 /*
909  * SWP_PAGER_FREESWAPSPACE() -	free raw swap space
910  *
911  *	This routine returns the specified swap blocks back to the bitmap.
912  *
913  *	This routine may not sleep.
914  */
915 static void
916 swp_pager_freeswapspace(const struct page_range *range)
917 {
918 	daddr_t blk, npages;
919 	struct swdevt *sp;
920 
921 	blk = range->start;
922 	npages = range->num;
923 	if (npages == 0)
924 		return;
925 	mtx_lock(&sw_dev_mtx);
926 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
927 		if (swp_pager_isondev(blk, sp)) {
928 			sp->sw_used -= npages;
929 			/*
930 			 * If we are attempting to stop swapping on
931 			 * this device, we don't want to mark any
932 			 * blocks free lest they be reused.
933 			 */
934 			if ((sp->sw_flags & SW_CLOSING) == 0) {
935 				blist_free(sp->sw_blist, blk - sp->sw_first,
936 				    npages);
937 				swap_pager_avail += npages;
938 				swp_sizecheck();
939 			}
940 			mtx_unlock(&sw_dev_mtx);
941 			return;
942 		}
943 	}
944 	panic("Swapdev not found");
945 }
946 
947 /*
948  * SYSCTL_SWAP_FRAGMENTATION() -	produce raw swap space stats
949  */
950 static int
951 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
952 {
953 	struct sbuf sbuf;
954 	struct swdevt *sp;
955 	const char *devname;
956 	int error;
957 
958 	error = sysctl_wire_old_buffer(req, 0);
959 	if (error != 0)
960 		return (error);
961 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
962 	mtx_lock(&sw_dev_mtx);
963 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
964 		if (vn_isdisk(sp->sw_vp))
965 			devname = devtoname(sp->sw_vp->v_rdev);
966 		else
967 			devname = "[file]";
968 		sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
969 		blist_stats(sp->sw_blist, &sbuf);
970 	}
971 	mtx_unlock(&sw_dev_mtx);
972 	error = sbuf_finish(&sbuf);
973 	sbuf_delete(&sbuf);
974 	return (error);
975 }
976 
977 /*
978  * SWAP_PAGER_FREESPACE() -	frees swap blocks associated with a page
979  *				range within an object.
980  *
981  *	This routine removes swapblk assignments from swap metadata.
982  *
983  *	The external callers of this routine typically have already destroyed
984  *	or renamed vm_page_t's associated with this range in the object so
985  *	we should be ok.
986  *
987  *	The object must be locked.
988  */
989 void
990 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size,
991     vm_size_t *freed)
992 {
993 	MPASS((object->flags & OBJ_SWAP) != 0);
994 
995 	swp_pager_meta_free(object, start, size, freed);
996 }
997 
998 static void
999 swap_pager_freespace_pgo(vm_object_t object, vm_pindex_t start, vm_size_t size)
1000 {
1001 	MPASS((object->flags & OBJ_SWAP) != 0);
1002 
1003 	swp_pager_meta_free(object, start, size, NULL);
1004 }
1005 
1006 /*
1007  * SWAP_PAGER_RESERVE() - reserve swap blocks in object
1008  *
1009  *	Assigns swap blocks to the specified range within the object.  The
1010  *	swap blocks are not zeroed.  Any previous swap assignment is destroyed.
1011  *
1012  *	Returns 0 on success, -1 on failure.
1013  */
1014 int
1015 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_pindex_t size)
1016 {
1017 	struct page_range range;
1018 	daddr_t addr, blk;
1019 	vm_pindex_t i, j;
1020 	int n;
1021 
1022 	swp_pager_init_freerange(&range);
1023 	VM_OBJECT_WLOCK(object);
1024 	for (i = 0; i < size; i += n) {
1025 		n = MIN(size - i, INT_MAX);
1026 		blk = swp_pager_getswapspace(&n);
1027 		if (blk == SWAPBLK_NONE) {
1028 			swp_pager_meta_free(object, start, i, NULL);
1029 			VM_OBJECT_WUNLOCK(object);
1030 			return (-1);
1031 		}
1032 		for (j = 0; j < n; ++j) {
1033 			addr = swp_pager_meta_build(object,
1034 			    start + i + j, blk + j);
1035 			if (addr != SWAPBLK_NONE)
1036 				swp_pager_update_freerange(&range, addr);
1037 		}
1038 	}
1039 	swp_pager_freeswapspace(&range);
1040 	VM_OBJECT_WUNLOCK(object);
1041 	return (0);
1042 }
1043 
1044 static bool
1045 swp_pager_xfer_source(vm_object_t srcobject, vm_object_t dstobject,
1046     vm_pindex_t pindex, daddr_t addr)
1047 {
1048 	daddr_t dstaddr __diagused;
1049 
1050 	KASSERT((srcobject->flags & OBJ_SWAP) != 0,
1051 	    ("%s: srcobject not swappable", __func__));
1052 	KASSERT((dstobject->flags & OBJ_SWAP) != 0,
1053 	    ("%s: dstobject not swappable", __func__));
1054 
1055 	if (swp_pager_meta_lookup(dstobject, pindex) != SWAPBLK_NONE) {
1056 		/* Caller should destroy the source block. */
1057 		return (false);
1058 	}
1059 
1060 	/*
1061 	 * Destination has no swapblk and is not resident, transfer source.
1062 	 * swp_pager_meta_build() can sleep.
1063 	 */
1064 	VM_OBJECT_WUNLOCK(srcobject);
1065 	dstaddr = swp_pager_meta_build(dstobject, pindex, addr);
1066 	KASSERT(dstaddr == SWAPBLK_NONE,
1067 	    ("Unexpected destination swapblk"));
1068 	VM_OBJECT_WLOCK(srcobject);
1069 
1070 	return (true);
1071 }
1072 
1073 /*
1074  * SWAP_PAGER_COPY() -  copy blocks from source pager to destination pager
1075  *			and destroy the source.
1076  *
1077  *	Copy any valid swapblks from the source to the destination.  In
1078  *	cases where both the source and destination have a valid swapblk,
1079  *	we keep the destination's.
1080  *
1081  *	This routine is allowed to sleep.  It may sleep allocating metadata
1082  *	indirectly through swp_pager_meta_build().
1083  *
1084  *	The source object contains no vm_page_t's (which is just as well)
1085  *
1086  *	The source and destination objects must be locked.
1087  *	Both object locks may temporarily be released.
1088  */
1089 void
1090 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
1091     vm_pindex_t offset, int destroysource)
1092 {
1093 	VM_OBJECT_ASSERT_WLOCKED(srcobject);
1094 	VM_OBJECT_ASSERT_WLOCKED(dstobject);
1095 
1096 	/*
1097 	 * If destroysource is set, we remove the source object from the
1098 	 * swap_pager internal queue now.
1099 	 */
1100 	if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
1101 	    srcobject->handle != NULL) {
1102 		VM_OBJECT_WUNLOCK(srcobject);
1103 		VM_OBJECT_WUNLOCK(dstobject);
1104 		sx_xlock(&sw_alloc_sx);
1105 		TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1106 		    pager_object_list);
1107 		sx_xunlock(&sw_alloc_sx);
1108 		VM_OBJECT_WLOCK(dstobject);
1109 		VM_OBJECT_WLOCK(srcobject);
1110 	}
1111 
1112 	/*
1113 	 * Transfer source to destination.
1114 	 */
1115 	swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size,
1116 	    NULL);
1117 
1118 	/*
1119 	 * Free left over swap blocks in source.
1120 	 */
1121 	if (destroysource)
1122 		swp_pager_meta_free_all(srcobject);
1123 }
1124 
1125 /*
1126  * SWAP_PAGER_HASPAGE() -	determine if we have good backing store for
1127  *				the requested page.
1128  *
1129  *	We determine whether good backing store exists for the requested
1130  *	page and return TRUE if it does, FALSE if it doesn't.
1131  *
1132  *	If TRUE, we also try to determine how much valid, contiguous backing
1133  *	store exists before and after the requested page.
1134  */
1135 static boolean_t
1136 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1137     int *after)
1138 {
1139 	daddr_t blk, blk0;
1140 	int i;
1141 
1142 	VM_OBJECT_ASSERT_LOCKED(object);
1143 	KASSERT((object->flags & OBJ_SWAP) != 0,
1144 	    ("%s: object not swappable", __func__));
1145 
1146 	/*
1147 	 * do we have good backing store at the requested index ?
1148 	 */
1149 	blk0 = swp_pager_meta_lookup(object, pindex);
1150 	if (blk0 == SWAPBLK_NONE) {
1151 		if (before)
1152 			*before = 0;
1153 		if (after)
1154 			*after = 0;
1155 		return (FALSE);
1156 	}
1157 
1158 	/*
1159 	 * find backwards-looking contiguous good backing store
1160 	 */
1161 	if (before != NULL) {
1162 		for (i = 1; i < SWB_NPAGES; i++) {
1163 			if (i > pindex)
1164 				break;
1165 			blk = swp_pager_meta_lookup(object, pindex - i);
1166 			if (blk != blk0 - i)
1167 				break;
1168 		}
1169 		*before = i - 1;
1170 	}
1171 
1172 	/*
1173 	 * find forward-looking contiguous good backing store
1174 	 */
1175 	if (after != NULL) {
1176 		for (i = 1; i < SWB_NPAGES; i++) {
1177 			blk = swp_pager_meta_lookup(object, pindex + i);
1178 			if (blk != blk0 + i)
1179 				break;
1180 		}
1181 		*after = i - 1;
1182 	}
1183 	return (TRUE);
1184 }
1185 
1186 /*
1187  * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1188  *
1189  *	This removes any associated swap backing store, whether valid or
1190  *	not, from the page.
1191  *
1192  *	This routine is typically called when a page is made dirty, at
1193  *	which point any associated swap can be freed.  MADV_FREE also
1194  *	calls us in a special-case situation
1195  *
1196  *	NOTE!!!  If the page is clean and the swap was valid, the caller
1197  *	should make the page dirty before calling this routine.  This routine
1198  *	does NOT change the m->dirty status of the page.  Also: MADV_FREE
1199  *	depends on it.
1200  *
1201  *	This routine may not sleep.
1202  *
1203  *	The object containing the page may be locked.
1204  */
1205 static void
1206 swap_pager_unswapped(vm_page_t m)
1207 {
1208 	struct page_range range;
1209 	struct swblk *sb;
1210 	vm_object_t obj;
1211 
1212 	/*
1213 	 * Handle enqueing deferred frees first.  If we do not have the
1214 	 * object lock we wait for the page daemon to clear the space.
1215 	 */
1216 	obj = m->object;
1217 	if (!VM_OBJECT_WOWNED(obj)) {
1218 		VM_PAGE_OBJECT_BUSY_ASSERT(m);
1219 		/*
1220 		 * The caller is responsible for synchronization but we
1221 		 * will harmlessly handle races.  This is typically provided
1222 		 * by only calling unswapped() when a page transitions from
1223 		 * clean to dirty.
1224 		 */
1225 		if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1226 		    PGA_SWAP_SPACE) {
1227 			vm_page_aflag_set(m, PGA_SWAP_FREE);
1228 			counter_u64_add(swap_free_deferred, 1);
1229 		}
1230 		return;
1231 	}
1232 	if ((m->a.flags & PGA_SWAP_FREE) != 0)
1233 		counter_u64_add(swap_free_completed, 1);
1234 	vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
1235 
1236 	/*
1237 	 * The meta data only exists if the object is OBJT_SWAP
1238 	 * and even then might not be allocated yet.
1239 	 */
1240 	KASSERT((m->object->flags & OBJ_SWAP) != 0,
1241 	    ("Free object not swappable"));
1242 
1243 	sb = SWAP_PCTRIE_LOOKUP(&m->object->un_pager.swp.swp_blks,
1244 	    rounddown(m->pindex, SWAP_META_PAGES));
1245 	if (sb == NULL)
1246 		return;
1247 	range.start = sb->d[m->pindex % SWAP_META_PAGES];
1248 	if (range.start == SWAPBLK_NONE)
1249 		return;
1250 	range.num = 1;
1251 	swp_pager_freeswapspace(&range);
1252 	sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
1253 	swp_pager_free_empty_swblk(m->object, sb);
1254 }
1255 
1256 /*
1257  * swap_pager_getpages() - bring pages in from swap
1258  *
1259  *	Attempt to page in the pages in array "ma" of length "count".  The
1260  *	caller may optionally specify that additional pages preceding and
1261  *	succeeding the specified range be paged in.  The number of such pages
1262  *	is returned in the "rbehind" and "rahead" parameters, and they will
1263  *	be in the inactive queue upon return.
1264  *
1265  *	The pages in "ma" must be busied and will remain busied upon return.
1266  */
1267 static int
1268 swap_pager_getpages_locked(vm_object_t object, vm_page_t *ma, int count,
1269     int *rbehind, int *rahead)
1270 {
1271 	struct buf *bp;
1272 	vm_page_t bm, mpred, msucc, p;
1273 	vm_pindex_t pindex;
1274 	daddr_t blk;
1275 	int i, maxahead, maxbehind, reqcount;
1276 
1277 	VM_OBJECT_ASSERT_WLOCKED(object);
1278 	reqcount = count;
1279 
1280 	KASSERT((object->flags & OBJ_SWAP) != 0,
1281 	    ("%s: object not swappable", __func__));
1282 	if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead)) {
1283 		VM_OBJECT_WUNLOCK(object);
1284 		return (VM_PAGER_FAIL);
1285 	}
1286 
1287 	KASSERT(reqcount - 1 <= maxahead,
1288 	    ("page count %d extends beyond swap block", reqcount));
1289 
1290 	/*
1291 	 * Do not transfer any pages other than those that are xbusied
1292 	 * when running during a split or collapse operation.  This
1293 	 * prevents clustering from re-creating pages which are being
1294 	 * moved into another object.
1295 	 */
1296 	if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
1297 		maxahead = reqcount - 1;
1298 		maxbehind = 0;
1299 	}
1300 
1301 	/*
1302 	 * Clip the readahead and readbehind ranges to exclude resident pages.
1303 	 */
1304 	if (rahead != NULL) {
1305 		*rahead = imin(*rahead, maxahead - (reqcount - 1));
1306 		pindex = ma[reqcount - 1]->pindex;
1307 		msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1308 		if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1309 			*rahead = msucc->pindex - pindex - 1;
1310 	}
1311 	if (rbehind != NULL) {
1312 		*rbehind = imin(*rbehind, maxbehind);
1313 		pindex = ma[0]->pindex;
1314 		mpred = TAILQ_PREV(ma[0], pglist, listq);
1315 		if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1316 			*rbehind = pindex - mpred->pindex - 1;
1317 	}
1318 
1319 	bm = ma[0];
1320 	for (i = 0; i < count; i++)
1321 		ma[i]->oflags |= VPO_SWAPINPROG;
1322 
1323 	/*
1324 	 * Allocate readahead and readbehind pages.
1325 	 */
1326 	if (rbehind != NULL) {
1327 		for (i = 1; i <= *rbehind; i++) {
1328 			p = vm_page_alloc(object, ma[0]->pindex - i,
1329 			    VM_ALLOC_NORMAL);
1330 			if (p == NULL)
1331 				break;
1332 			p->oflags |= VPO_SWAPINPROG;
1333 			bm = p;
1334 		}
1335 		*rbehind = i - 1;
1336 	}
1337 	if (rahead != NULL) {
1338 		for (i = 0; i < *rahead; i++) {
1339 			p = vm_page_alloc(object,
1340 			    ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1341 			if (p == NULL)
1342 				break;
1343 			p->oflags |= VPO_SWAPINPROG;
1344 		}
1345 		*rahead = i;
1346 	}
1347 	if (rbehind != NULL)
1348 		count += *rbehind;
1349 	if (rahead != NULL)
1350 		count += *rahead;
1351 
1352 	vm_object_pip_add(object, count);
1353 
1354 	pindex = bm->pindex;
1355 	blk = swp_pager_meta_lookup(object, pindex);
1356 	KASSERT(blk != SWAPBLK_NONE,
1357 	    ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1358 
1359 	VM_OBJECT_WUNLOCK(object);
1360 	bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1361 	MPASS((bp->b_flags & B_MAXPHYS) != 0);
1362 	/* Pages cannot leave the object while busy. */
1363 	for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1364 		MPASS(p->pindex == bm->pindex + i);
1365 		bp->b_pages[i] = p;
1366 	}
1367 
1368 	bp->b_flags |= B_PAGING;
1369 	bp->b_iocmd = BIO_READ;
1370 	bp->b_iodone = swp_pager_async_iodone;
1371 	bp->b_rcred = crhold(thread0.td_ucred);
1372 	bp->b_wcred = crhold(thread0.td_ucred);
1373 	bp->b_blkno = blk;
1374 	bp->b_bcount = PAGE_SIZE * count;
1375 	bp->b_bufsize = PAGE_SIZE * count;
1376 	bp->b_npages = count;
1377 	bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1378 	bp->b_pgafter = rahead != NULL ? *rahead : 0;
1379 
1380 	VM_CNT_INC(v_swapin);
1381 	VM_CNT_ADD(v_swappgsin, count);
1382 
1383 	/*
1384 	 * perform the I/O.  NOTE!!!  bp cannot be considered valid after
1385 	 * this point because we automatically release it on completion.
1386 	 * Instead, we look at the one page we are interested in which we
1387 	 * still hold a lock on even through the I/O completion.
1388 	 *
1389 	 * The other pages in our ma[] array are also released on completion,
1390 	 * so we cannot assume they are valid anymore either.
1391 	 *
1392 	 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1393 	 */
1394 	BUF_KERNPROC(bp);
1395 	swp_pager_strategy(bp);
1396 
1397 	/*
1398 	 * Wait for the pages we want to complete.  VPO_SWAPINPROG is always
1399 	 * cleared on completion.  If an I/O error occurs, SWAPBLK_NONE
1400 	 * is set in the metadata for each page in the request.
1401 	 */
1402 	VM_OBJECT_WLOCK(object);
1403 	/* This could be implemented more efficiently with aflags */
1404 	while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
1405 		ma[0]->oflags |= VPO_SWAPSLEEP;
1406 		VM_CNT_INC(v_intrans);
1407 		if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1408 		    "swread", hz * 20)) {
1409 			printf(
1410 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1411 			    bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1412 		}
1413 	}
1414 	VM_OBJECT_WUNLOCK(object);
1415 
1416 	/*
1417 	 * If we had an unrecoverable read error pages will not be valid.
1418 	 */
1419 	for (i = 0; i < reqcount; i++)
1420 		if (ma[i]->valid != VM_PAGE_BITS_ALL)
1421 			return (VM_PAGER_ERROR);
1422 
1423 	return (VM_PAGER_OK);
1424 
1425 	/*
1426 	 * A final note: in a low swap situation, we cannot deallocate swap
1427 	 * and mark a page dirty here because the caller is likely to mark
1428 	 * the page clean when we return, causing the page to possibly revert
1429 	 * to all-zero's later.
1430 	 */
1431 }
1432 
1433 static int
1434 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count,
1435     int *rbehind, int *rahead)
1436 {
1437 
1438 	VM_OBJECT_WLOCK(object);
1439 	return (swap_pager_getpages_locked(object, ma, count, rbehind, rahead));
1440 }
1441 
1442 /*
1443  * 	swap_pager_getpages_async():
1444  *
1445  *	Right now this is emulation of asynchronous operation on top of
1446  *	swap_pager_getpages().
1447  */
1448 static int
1449 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1450     int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1451 {
1452 	int r, error;
1453 
1454 	r = swap_pager_getpages(object, ma, count, rbehind, rahead);
1455 	switch (r) {
1456 	case VM_PAGER_OK:
1457 		error = 0;
1458 		break;
1459 	case VM_PAGER_ERROR:
1460 		error = EIO;
1461 		break;
1462 	case VM_PAGER_FAIL:
1463 		error = EINVAL;
1464 		break;
1465 	default:
1466 		panic("unhandled swap_pager_getpages() error %d", r);
1467 	}
1468 	(iodone)(arg, ma, count, error);
1469 
1470 	return (r);
1471 }
1472 
1473 /*
1474  *	swap_pager_putpages:
1475  *
1476  *	Assign swap (if necessary) and initiate I/O on the specified pages.
1477  *
1478  *	In a low memory situation we may block in VOP_STRATEGY(), but the new
1479  *	vm_page reservation system coupled with properly written VFS devices
1480  *	should ensure that no low-memory deadlock occurs.  This is an area
1481  *	which needs work.
1482  *
1483  *	The parent has N vm_object_pip_add() references prior to
1484  *	calling us and will remove references for rtvals[] that are
1485  *	not set to VM_PAGER_PEND.  We need to remove the rest on I/O
1486  *	completion.
1487  *
1488  *	The parent has soft-busy'd the pages it passes us and will unbusy
1489  *	those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
1490  *	We need to unbusy the rest on I/O completion.
1491  */
1492 static void
1493 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1494     int flags, int *rtvals)
1495 {
1496 	struct page_range range;
1497 	struct buf *bp;
1498 	daddr_t addr, blk;
1499 	vm_page_t mreq;
1500 	int i, j, n;
1501 	bool async;
1502 
1503 	KASSERT(count == 0 || ma[0]->object == object,
1504 	    ("%s: object mismatch %p/%p",
1505 	    __func__, object, ma[0]->object));
1506 
1507 	VM_OBJECT_WUNLOCK(object);
1508 	async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
1509 	swp_pager_init_freerange(&range);
1510 
1511 	/*
1512 	 * Assign swap blocks and issue I/O.  We reallocate swap on the fly.
1513 	 * The page is left dirty until the pageout operation completes
1514 	 * successfully.
1515 	 */
1516 	for (i = 0; i < count; i += n) {
1517 		/* Maximum I/O size is limited by maximum swap block size. */
1518 		n = min(count - i, nsw_cluster_max);
1519 
1520 		if (async) {
1521 			mtx_lock(&swbuf_mtx);
1522 			while (nsw_wcount_async == 0)
1523 				msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1524 				    "swbufa", 0);
1525 			nsw_wcount_async--;
1526 			mtx_unlock(&swbuf_mtx);
1527 		}
1528 
1529 		/* Get a block of swap of size up to size n. */
1530 		blk = swp_pager_getswapspace(&n);
1531 		if (blk == SWAPBLK_NONE) {
1532 			mtx_lock(&swbuf_mtx);
1533 			if (++nsw_wcount_async == 1)
1534 				wakeup(&nsw_wcount_async);
1535 			mtx_unlock(&swbuf_mtx);
1536 			for (j = 0; j < n; ++j)
1537 				rtvals[i + j] = VM_PAGER_FAIL;
1538 			continue;
1539 		}
1540 		VM_OBJECT_WLOCK(object);
1541 		for (j = 0; j < n; ++j) {
1542 			mreq = ma[i + j];
1543 			vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1544 			addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1545 			    blk + j);
1546 			if (addr != SWAPBLK_NONE)
1547 				swp_pager_update_freerange(&range, addr);
1548 			MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1549 			mreq->oflags |= VPO_SWAPINPROG;
1550 		}
1551 		VM_OBJECT_WUNLOCK(object);
1552 
1553 		bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1554 		MPASS((bp->b_flags & B_MAXPHYS) != 0);
1555 		if (async)
1556 			bp->b_flags |= B_ASYNC;
1557 		bp->b_flags |= B_PAGING;
1558 		bp->b_iocmd = BIO_WRITE;
1559 
1560 		bp->b_rcred = crhold(thread0.td_ucred);
1561 		bp->b_wcred = crhold(thread0.td_ucred);
1562 		bp->b_bcount = PAGE_SIZE * n;
1563 		bp->b_bufsize = PAGE_SIZE * n;
1564 		bp->b_blkno = blk;
1565 		for (j = 0; j < n; j++)
1566 			bp->b_pages[j] = ma[i + j];
1567 		bp->b_npages = n;
1568 
1569 		/*
1570 		 * Must set dirty range for NFS to work.
1571 		 */
1572 		bp->b_dirtyoff = 0;
1573 		bp->b_dirtyend = bp->b_bcount;
1574 
1575 		VM_CNT_INC(v_swapout);
1576 		VM_CNT_ADD(v_swappgsout, bp->b_npages);
1577 
1578 		/*
1579 		 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1580 		 * can call the async completion routine at the end of a
1581 		 * synchronous I/O operation.  Otherwise, our caller would
1582 		 * perform duplicate unbusy and wakeup operations on the page
1583 		 * and object, respectively.
1584 		 */
1585 		for (j = 0; j < n; j++)
1586 			rtvals[i + j] = VM_PAGER_PEND;
1587 
1588 		/*
1589 		 * asynchronous
1590 		 *
1591 		 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1592 		 */
1593 		if (async) {
1594 			bp->b_iodone = swp_pager_async_iodone;
1595 			BUF_KERNPROC(bp);
1596 			swp_pager_strategy(bp);
1597 			continue;
1598 		}
1599 
1600 		/*
1601 		 * synchronous
1602 		 *
1603 		 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1604 		 */
1605 		bp->b_iodone = bdone;
1606 		swp_pager_strategy(bp);
1607 
1608 		/*
1609 		 * Wait for the sync I/O to complete.
1610 		 */
1611 		bwait(bp, PVM, "swwrt");
1612 
1613 		/*
1614 		 * Now that we are through with the bp, we can call the
1615 		 * normal async completion, which frees everything up.
1616 		 */
1617 		swp_pager_async_iodone(bp);
1618 	}
1619 	swp_pager_freeswapspace(&range);
1620 	VM_OBJECT_WLOCK(object);
1621 }
1622 
1623 /*
1624  *	swp_pager_async_iodone:
1625  *
1626  *	Completion routine for asynchronous reads and writes from/to swap.
1627  *	Also called manually by synchronous code to finish up a bp.
1628  *
1629  *	This routine may not sleep.
1630  */
1631 static void
1632 swp_pager_async_iodone(struct buf *bp)
1633 {
1634 	int i;
1635 	vm_object_t object = NULL;
1636 
1637 	/*
1638 	 * Report error - unless we ran out of memory, in which case
1639 	 * we've already logged it in swapgeom_strategy().
1640 	 */
1641 	if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
1642 		printf(
1643 		    "swap_pager: I/O error - %s failed; blkno %ld,"
1644 			"size %ld, error %d\n",
1645 		    ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1646 		    (long)bp->b_blkno,
1647 		    (long)bp->b_bcount,
1648 		    bp->b_error
1649 		);
1650 	}
1651 
1652 	/*
1653 	 * remove the mapping for kernel virtual
1654 	 */
1655 	if (buf_mapped(bp))
1656 		pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1657 	else
1658 		bp->b_data = bp->b_kvabase;
1659 
1660 	if (bp->b_npages) {
1661 		object = bp->b_pages[0]->object;
1662 		VM_OBJECT_WLOCK(object);
1663 	}
1664 
1665 	/*
1666 	 * cleanup pages.  If an error occurs writing to swap, we are in
1667 	 * very serious trouble.  If it happens to be a disk error, though,
1668 	 * we may be able to recover by reassigning the swap later on.  So
1669 	 * in this case we remove the m->swapblk assignment for the page
1670 	 * but do not free it in the rlist.  The errornous block(s) are thus
1671 	 * never reallocated as swap.  Redirty the page and continue.
1672 	 */
1673 	for (i = 0; i < bp->b_npages; ++i) {
1674 		vm_page_t m = bp->b_pages[i];
1675 
1676 		m->oflags &= ~VPO_SWAPINPROG;
1677 		if (m->oflags & VPO_SWAPSLEEP) {
1678 			m->oflags &= ~VPO_SWAPSLEEP;
1679 			wakeup(&object->handle);
1680 		}
1681 
1682 		/* We always have space after I/O, successful or not. */
1683 		vm_page_aflag_set(m, PGA_SWAP_SPACE);
1684 
1685 		if (bp->b_ioflags & BIO_ERROR) {
1686 			/*
1687 			 * If an error occurs I'd love to throw the swapblk
1688 			 * away without freeing it back to swapspace, so it
1689 			 * can never be used again.  But I can't from an
1690 			 * interrupt.
1691 			 */
1692 			if (bp->b_iocmd == BIO_READ) {
1693 				/*
1694 				 * NOTE: for reads, m->dirty will probably
1695 				 * be overridden by the original caller of
1696 				 * getpages so don't play cute tricks here.
1697 				 */
1698 				vm_page_invalid(m);
1699 				if (i < bp->b_pgbefore ||
1700 				    i >= bp->b_npages - bp->b_pgafter)
1701 					vm_page_free_invalid(m);
1702 			} else {
1703 				/*
1704 				 * If a write error occurs, reactivate page
1705 				 * so it doesn't clog the inactive list,
1706 				 * then finish the I/O.
1707 				 */
1708 				MPASS(m->dirty == VM_PAGE_BITS_ALL);
1709 
1710 				/* PQ_UNSWAPPABLE? */
1711 				vm_page_activate(m);
1712 				vm_page_sunbusy(m);
1713 			}
1714 		} else if (bp->b_iocmd == BIO_READ) {
1715 			/*
1716 			 * NOTE: for reads, m->dirty will probably be
1717 			 * overridden by the original caller of getpages so
1718 			 * we cannot set them in order to free the underlying
1719 			 * swap in a low-swap situation.  I don't think we'd
1720 			 * want to do that anyway, but it was an optimization
1721 			 * that existed in the old swapper for a time before
1722 			 * it got ripped out due to precisely this problem.
1723 			 */
1724 			KASSERT(!pmap_page_is_mapped(m),
1725 			    ("swp_pager_async_iodone: page %p is mapped", m));
1726 			KASSERT(m->dirty == 0,
1727 			    ("swp_pager_async_iodone: page %p is dirty", m));
1728 
1729 			vm_page_valid(m);
1730 			if (i < bp->b_pgbefore ||
1731 			    i >= bp->b_npages - bp->b_pgafter)
1732 				vm_page_readahead_finish(m);
1733 		} else {
1734 			/*
1735 			 * For write success, clear the dirty
1736 			 * status, then finish the I/O ( which decrements the
1737 			 * busy count and possibly wakes waiter's up ).
1738 			 * A page is only written to swap after a period of
1739 			 * inactivity.  Therefore, we do not expect it to be
1740 			 * reused.
1741 			 */
1742 			KASSERT(!pmap_page_is_write_mapped(m),
1743 			    ("swp_pager_async_iodone: page %p is not write"
1744 			    " protected", m));
1745 			vm_page_undirty(m);
1746 			vm_page_deactivate_noreuse(m);
1747 			vm_page_sunbusy(m);
1748 		}
1749 	}
1750 
1751 	/*
1752 	 * adjust pip.  NOTE: the original parent may still have its own
1753 	 * pip refs on the object.
1754 	 */
1755 	if (object != NULL) {
1756 		vm_object_pip_wakeupn(object, bp->b_npages);
1757 		VM_OBJECT_WUNLOCK(object);
1758 	}
1759 
1760 	/*
1761 	 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1762 	 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1763 	 * trigger a KASSERT in relpbuf().
1764 	 */
1765 	if (bp->b_vp) {
1766 		    bp->b_vp = NULL;
1767 		    bp->b_bufobj = NULL;
1768 	}
1769 	/*
1770 	 * release the physical I/O buffer
1771 	 */
1772 	if (bp->b_flags & B_ASYNC) {
1773 		mtx_lock(&swbuf_mtx);
1774 		if (++nsw_wcount_async == 1)
1775 			wakeup(&nsw_wcount_async);
1776 		mtx_unlock(&swbuf_mtx);
1777 	}
1778 	uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
1779 }
1780 
1781 int
1782 swap_pager_nswapdev(void)
1783 {
1784 
1785 	return (nswapdev);
1786 }
1787 
1788 static void
1789 swp_pager_force_dirty(vm_page_t m)
1790 {
1791 
1792 	vm_page_dirty(m);
1793 	swap_pager_unswapped(m);
1794 	vm_page_launder(m);
1795 }
1796 
1797 u_long
1798 swap_pager_swapped_pages(vm_object_t object)
1799 {
1800 	struct swblk *sb;
1801 	vm_pindex_t pi;
1802 	u_long res;
1803 	int i;
1804 
1805 	VM_OBJECT_ASSERT_LOCKED(object);
1806 
1807 	if (pctrie_is_empty(&object->un_pager.swp.swp_blks))
1808 		return (0);
1809 
1810 	for (res = 0, pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1811 	    &object->un_pager.swp.swp_blks, pi)) != NULL;
1812 	    pi = sb->p + SWAP_META_PAGES) {
1813 		for (i = 0; i < SWAP_META_PAGES; i++) {
1814 			if (sb->d[i] != SWAPBLK_NONE)
1815 				res++;
1816 		}
1817 	}
1818 	return (res);
1819 }
1820 
1821 /*
1822  *	swap_pager_swapoff_object:
1823  *
1824  *	Page in all of the pages that have been paged out for an object
1825  *	to a swap device.
1826  */
1827 static void
1828 swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
1829 {
1830 	struct swblk *sb;
1831 	vm_page_t m;
1832 	vm_pindex_t pi;
1833 	daddr_t blk;
1834 	int i, nv, rahead, rv;
1835 
1836 	KASSERT((object->flags & OBJ_SWAP) != 0,
1837 	    ("%s: Object not swappable", __func__));
1838 
1839 	for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1840 	    &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1841 		if ((object->flags & OBJ_DEAD) != 0) {
1842 			/*
1843 			 * Make sure that pending writes finish before
1844 			 * returning.
1845 			 */
1846 			vm_object_pip_wait(object, "swpoff");
1847 			swp_pager_meta_free_all(object);
1848 			break;
1849 		}
1850 		for (i = 0; i < SWAP_META_PAGES; i++) {
1851 			/*
1852 			 * Count the number of contiguous valid blocks.
1853 			 */
1854 			for (nv = 0; nv < SWAP_META_PAGES - i; nv++) {
1855 				blk = sb->d[i + nv];
1856 				if (!swp_pager_isondev(blk, sp) ||
1857 				    blk == SWAPBLK_NONE)
1858 					break;
1859 			}
1860 			if (nv == 0)
1861 				continue;
1862 
1863 			/*
1864 			 * Look for a page corresponding to the first
1865 			 * valid block and ensure that any pending paging
1866 			 * operations on it are complete.  If the page is valid,
1867 			 * mark it dirty and free the swap block.  Try to batch
1868 			 * this operation since it may cause sp to be freed,
1869 			 * meaning that we must restart the scan.  Avoid busying
1870 			 * valid pages since we may block forever on kernel
1871 			 * stack pages.
1872 			 */
1873 			m = vm_page_lookup(object, sb->p + i);
1874 			if (m == NULL) {
1875 				m = vm_page_alloc(object, sb->p + i,
1876 				    VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
1877 				if (m == NULL)
1878 					break;
1879 			} else {
1880 				if ((m->oflags & VPO_SWAPINPROG) != 0) {
1881 					m->oflags |= VPO_SWAPSLEEP;
1882 					VM_OBJECT_SLEEP(object, &object->handle,
1883 					    PSWP, "swpoff", 0);
1884 					break;
1885 				}
1886 				if (vm_page_all_valid(m)) {
1887 					do {
1888 						swp_pager_force_dirty(m);
1889 					} while (--nv > 0 &&
1890 					    (m = vm_page_next(m)) != NULL &&
1891 					    vm_page_all_valid(m) &&
1892 					    (m->oflags & VPO_SWAPINPROG) == 0);
1893 					break;
1894 				}
1895 				if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL))
1896 					break;
1897 			}
1898 
1899 			vm_object_pip_add(object, 1);
1900 			rahead = SWAP_META_PAGES;
1901 			rv = swap_pager_getpages_locked(object, &m, 1, NULL,
1902 			    &rahead);
1903 			if (rv != VM_PAGER_OK)
1904 				panic("%s: read from swap failed: %d",
1905 				    __func__, rv);
1906 			VM_OBJECT_WLOCK(object);
1907 			vm_object_pip_wakeupn(object, 1);
1908 			vm_page_xunbusy(m);
1909 
1910 			/*
1911 			 * The object lock was dropped so we must restart the
1912 			 * scan of this swap block.  Pages paged in during this
1913 			 * iteration will be marked dirty in a future iteration.
1914 			 */
1915 			break;
1916 		}
1917 		if (i == SWAP_META_PAGES)
1918 			pi = sb->p + SWAP_META_PAGES;
1919 	}
1920 }
1921 
1922 /*
1923  *	swap_pager_swapoff:
1924  *
1925  *	Page in all of the pages that have been paged out to the
1926  *	given device.  The corresponding blocks in the bitmap must be
1927  *	marked as allocated and the device must be flagged SW_CLOSING.
1928  *	There may be no processes swapped out to the device.
1929  *
1930  *	This routine may block.
1931  */
1932 static void
1933 swap_pager_swapoff(struct swdevt *sp)
1934 {
1935 	vm_object_t object;
1936 	int retries;
1937 
1938 	sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1939 
1940 	retries = 0;
1941 full_rescan:
1942 	mtx_lock(&vm_object_list_mtx);
1943 	TAILQ_FOREACH(object, &vm_object_list, object_list) {
1944 		if ((object->flags & OBJ_SWAP) == 0)
1945 			continue;
1946 		mtx_unlock(&vm_object_list_mtx);
1947 		/* Depends on type-stability. */
1948 		VM_OBJECT_WLOCK(object);
1949 
1950 		/*
1951 		 * Dead objects are eventually terminated on their own.
1952 		 */
1953 		if ((object->flags & OBJ_DEAD) != 0)
1954 			goto next_obj;
1955 
1956 		/*
1957 		 * Sync with fences placed after pctrie
1958 		 * initialization.  We must not access pctrie below
1959 		 * unless we checked that our object is swap and not
1960 		 * dead.
1961 		 */
1962 		atomic_thread_fence_acq();
1963 		if ((object->flags & OBJ_SWAP) == 0)
1964 			goto next_obj;
1965 
1966 		swap_pager_swapoff_object(sp, object);
1967 next_obj:
1968 		VM_OBJECT_WUNLOCK(object);
1969 		mtx_lock(&vm_object_list_mtx);
1970 	}
1971 	mtx_unlock(&vm_object_list_mtx);
1972 
1973 	if (sp->sw_used) {
1974 		/*
1975 		 * Objects may be locked or paging to the device being
1976 		 * removed, so we will miss their pages and need to
1977 		 * make another pass.  We have marked this device as
1978 		 * SW_CLOSING, so the activity should finish soon.
1979 		 */
1980 		retries++;
1981 		if (retries > 100) {
1982 			panic("swapoff: failed to locate %d swap blocks",
1983 			    sp->sw_used);
1984 		}
1985 		pause("swpoff", hz / 20);
1986 		goto full_rescan;
1987 	}
1988 	EVENTHANDLER_INVOKE(swapoff, sp);
1989 }
1990 
1991 /************************************************************************
1992  *				SWAP META DATA 				*
1993  ************************************************************************
1994  *
1995  *	These routines manipulate the swap metadata stored in the
1996  *	OBJT_SWAP object.
1997  *
1998  *	Swap metadata is implemented with a global hash and not directly
1999  *	linked into the object.  Instead the object simply contains
2000  *	appropriate tracking counters.
2001  */
2002 
2003 /*
2004  * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
2005  */
2006 static bool
2007 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
2008 {
2009 	int i;
2010 
2011 	MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
2012 	for (i = start; i < limit; i++) {
2013 		if (sb->d[i] != SWAPBLK_NONE)
2014 			return (false);
2015 	}
2016 	return (true);
2017 }
2018 
2019 /*
2020  * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
2021  *
2022  *  Nothing is done if the block is still in use.
2023  */
2024 static void
2025 swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
2026 {
2027 
2028 	if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
2029 		SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2030 		uma_zfree(swblk_zone, sb);
2031 	}
2032 }
2033 
2034 /*
2035  * SWP_PAGER_META_BUILD() -	add swap block to swap meta data for object
2036  *
2037  *	The specified swapblk is added to the object's swap metadata.  If
2038  *	the swapblk is not valid, it is freed instead.  Any previously
2039  *	assigned swapblk is returned.
2040  */
2041 static daddr_t
2042 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
2043 {
2044 	static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
2045 	struct swblk *sb, *sb1;
2046 	vm_pindex_t modpi, rdpi;
2047 	daddr_t prev_swapblk;
2048 	int error, i;
2049 
2050 	VM_OBJECT_ASSERT_WLOCKED(object);
2051 
2052 	rdpi = rounddown(pindex, SWAP_META_PAGES);
2053 	sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
2054 	if (sb == NULL) {
2055 		if (swapblk == SWAPBLK_NONE)
2056 			return (SWAPBLK_NONE);
2057 		for (;;) {
2058 			sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
2059 			    pageproc ? M_USE_RESERVE : 0));
2060 			if (sb != NULL) {
2061 				sb->p = rdpi;
2062 				for (i = 0; i < SWAP_META_PAGES; i++)
2063 					sb->d[i] = SWAPBLK_NONE;
2064 				if (atomic_cmpset_int(&swblk_zone_exhausted,
2065 				    1, 0))
2066 					printf("swblk zone ok\n");
2067 				break;
2068 			}
2069 			VM_OBJECT_WUNLOCK(object);
2070 			if (uma_zone_exhausted(swblk_zone)) {
2071 				if (atomic_cmpset_int(&swblk_zone_exhausted,
2072 				    0, 1))
2073 					printf("swap blk zone exhausted, "
2074 					    "increase kern.maxswzone\n");
2075 				vm_pageout_oom(VM_OOM_SWAPZ);
2076 				pause("swzonxb", 10);
2077 			} else
2078 				uma_zwait(swblk_zone);
2079 			VM_OBJECT_WLOCK(object);
2080 			sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2081 			    rdpi);
2082 			if (sb != NULL)
2083 				/*
2084 				 * Somebody swapped out a nearby page,
2085 				 * allocating swblk at the rdpi index,
2086 				 * while we dropped the object lock.
2087 				 */
2088 				goto allocated;
2089 		}
2090 		for (;;) {
2091 			error = SWAP_PCTRIE_INSERT(
2092 			    &object->un_pager.swp.swp_blks, sb);
2093 			if (error == 0) {
2094 				if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2095 				    1, 0))
2096 					printf("swpctrie zone ok\n");
2097 				break;
2098 			}
2099 			VM_OBJECT_WUNLOCK(object);
2100 			if (uma_zone_exhausted(swpctrie_zone)) {
2101 				if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2102 				    0, 1))
2103 					printf("swap pctrie zone exhausted, "
2104 					    "increase kern.maxswzone\n");
2105 				vm_pageout_oom(VM_OOM_SWAPZ);
2106 				pause("swzonxp", 10);
2107 			} else
2108 				uma_zwait(swpctrie_zone);
2109 			VM_OBJECT_WLOCK(object);
2110 			sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2111 			    rdpi);
2112 			if (sb1 != NULL) {
2113 				uma_zfree(swblk_zone, sb);
2114 				sb = sb1;
2115 				goto allocated;
2116 			}
2117 		}
2118 	}
2119 allocated:
2120 	MPASS(sb->p == rdpi);
2121 
2122 	modpi = pindex % SWAP_META_PAGES;
2123 	/* Return prior contents of metadata. */
2124 	prev_swapblk = sb->d[modpi];
2125 	/* Enter block into metadata. */
2126 	sb->d[modpi] = swapblk;
2127 
2128 	/*
2129 	 * Free the swblk if we end up with the empty page run.
2130 	 */
2131 	if (swapblk == SWAPBLK_NONE)
2132 		swp_pager_free_empty_swblk(object, sb);
2133 	return (prev_swapblk);
2134 }
2135 
2136 /*
2137  * SWP_PAGER_META_TRANSFER() - free a range of blocks in the srcobject's swap
2138  * metadata, or transfer it into dstobject.
2139  *
2140  *	This routine will free swap metadata structures as they are cleaned
2141  *	out.
2142  */
2143 static void
2144 swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
2145     vm_pindex_t pindex, vm_pindex_t count, vm_size_t *moved)
2146 {
2147 	struct page_range range;
2148 	struct swblk *sb;
2149 	vm_page_t m;
2150 	vm_pindex_t offset, last;
2151 	vm_size_t mc;
2152 	int i, limit, start;
2153 
2154 	VM_OBJECT_ASSERT_WLOCKED(srcobject);
2155 	MPASS(moved == NULL || dstobject == NULL);
2156 
2157 	mc = 0;
2158 	m = NULL;
2159 	if (count == 0 || pctrie_is_empty(&srcobject->un_pager.swp.swp_blks))
2160 		goto out;
2161 
2162 	swp_pager_init_freerange(&range);
2163 	offset = pindex;
2164 	last = pindex + count;
2165 	for (;;) {
2166 		sb = SWAP_PCTRIE_LOOKUP_GE(&srcobject->un_pager.swp.swp_blks,
2167 		    rounddown(pindex, SWAP_META_PAGES));
2168 		if (sb == NULL || sb->p >= last)
2169 			break;
2170 		start = pindex > sb->p ? pindex - sb->p : 0;
2171 		limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2172 		    SWAP_META_PAGES;
2173 		for (i = start; i < limit; i++) {
2174 			if (sb->d[i] == SWAPBLK_NONE)
2175 				continue;
2176 			if (dstobject == NULL ||
2177 			    !swp_pager_xfer_source(srcobject, dstobject,
2178 			    sb->p + i - offset, sb->d[i])) {
2179 				swp_pager_update_freerange(&range, sb->d[i]);
2180 			}
2181 			if (moved != NULL) {
2182 				if (m != NULL && m->pindex != pindex + i - 1)
2183 					m = NULL;
2184 				m = m != NULL ? vm_page_next(m) :
2185 				    vm_page_lookup(srcobject, pindex + i);
2186 				if (m == NULL || vm_page_none_valid(m))
2187 					mc++;
2188 			}
2189 			sb->d[i] = SWAPBLK_NONE;
2190 		}
2191 		pindex = sb->p + SWAP_META_PAGES;
2192 		if (swp_pager_swblk_empty(sb, 0, start) &&
2193 		    swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2194 			SWAP_PCTRIE_REMOVE(&srcobject->un_pager.swp.swp_blks,
2195 			    sb->p);
2196 			uma_zfree(swblk_zone, sb);
2197 		}
2198 	}
2199 	swp_pager_freeswapspace(&range);
2200 out:
2201 	if (moved != NULL)
2202 		*moved = mc;
2203 }
2204 
2205 /*
2206  * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
2207  *
2208  *	The requested range of blocks is freed, with any associated swap
2209  *	returned to the swap bitmap.
2210  *
2211  *	This routine will free swap metadata structures as they are cleaned
2212  *	out.  This routine does *NOT* operate on swap metadata associated
2213  *	with resident pages.
2214  */
2215 static void
2216 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count,
2217     vm_size_t *freed)
2218 {
2219 	swp_pager_meta_transfer(object, NULL, pindex, count, freed);
2220 }
2221 
2222 static void
2223 swp_pager_meta_free_block(struct swblk *sb, void *rangev)
2224 {
2225 	struct page_range *range = rangev;
2226 
2227 	for (int i = 0; i < SWAP_META_PAGES; i++) {
2228 		if (sb->d[i] != SWAPBLK_NONE)
2229 			swp_pager_update_freerange(range, sb->d[i]);
2230 	}
2231 	uma_zfree(swblk_zone, sb);
2232 }
2233 
2234 /*
2235  * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
2236  *
2237  *	This routine locates and destroys all swap metadata associated with
2238  *	an object.
2239  */
2240 static void
2241 swp_pager_meta_free_all(vm_object_t object)
2242 {
2243 	struct page_range range;
2244 
2245 	VM_OBJECT_ASSERT_WLOCKED(object);
2246 
2247 	swp_pager_init_freerange(&range);
2248 	SWAP_PCTRIE_RECLAIM_CALLBACK(&object->un_pager.swp.swp_blks,
2249 	    swp_pager_meta_free_block, &range);
2250 	swp_pager_freeswapspace(&range);
2251 }
2252 
2253 /*
2254  * SWP_PAGER_METACTL() -  misc control of swap meta data.
2255  *
2256  *	This routine is capable of looking up, or removing swapblk
2257  *	assignments in the swap meta data.  It returns the swapblk being
2258  *	looked-up, popped, or SWAPBLK_NONE if the block was invalid.
2259  *
2260  *	When acting on a busy resident page and paging is in progress, we
2261  *	have to wait until paging is complete but otherwise can act on the
2262  *	busy page.
2263  */
2264 static daddr_t
2265 swp_pager_meta_lookup(vm_object_t object, vm_pindex_t pindex)
2266 {
2267 	struct swblk *sb;
2268 
2269 	VM_OBJECT_ASSERT_LOCKED(object);
2270 
2271 	/*
2272 	 * The meta data only exists if the object is OBJT_SWAP
2273 	 * and even then might not be allocated yet.
2274 	 */
2275 	KASSERT((object->flags & OBJ_SWAP) != 0,
2276 	    ("Lookup object not swappable"));
2277 
2278 	sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2279 	    rounddown(pindex, SWAP_META_PAGES));
2280 	if (sb == NULL)
2281 		return (SWAPBLK_NONE);
2282 	return (sb->d[pindex % SWAP_META_PAGES]);
2283 }
2284 
2285 /*
2286  * Returns the least page index which is greater than or equal to the
2287  * parameter pindex and for which there is a swap block allocated.
2288  * Returns object's size if the object's type is not swap or if there
2289  * are no allocated swap blocks for the object after the requested
2290  * pindex.
2291  */
2292 vm_pindex_t
2293 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2294 {
2295 	struct swblk *sb;
2296 	int i;
2297 
2298 	VM_OBJECT_ASSERT_LOCKED(object);
2299 	MPASS((object->flags & OBJ_SWAP) != 0);
2300 
2301 	sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2302 	    rounddown(pindex, SWAP_META_PAGES));
2303 	if (sb == NULL)
2304 		return (object->size);
2305 	for (i = pindex - sb->p; i < SWAP_META_PAGES; i++) {
2306 		if (sb->d[i] != SWAPBLK_NONE)
2307 			return (sb->p + i);
2308 	}
2309 	sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks, pindex);
2310 	if (sb == NULL)
2311 		return (object->size);
2312 	for (i = 0; i < SWAP_META_PAGES; i++) {
2313 		if (sb->d[i] != SWAPBLK_NONE)
2314 			return (sb->p + i);
2315 	}
2316 
2317 	/*
2318 	 * We get here if a swblk is present in the trie but it
2319 	 * doesn't map any blocks.
2320 	 */
2321 	__unreachable();
2322 	return (object->size);
2323 }
2324 
2325 /*
2326  * System call swapon(name) enables swapping on device name,
2327  * which must be in the swdevsw.  Return EBUSY
2328  * if already swapping on this device.
2329  */
2330 #ifndef _SYS_SYSPROTO_H_
2331 struct swapon_args {
2332 	char *name;
2333 };
2334 #endif
2335 
2336 int
2337 sys_swapon(struct thread *td, struct swapon_args *uap)
2338 {
2339 	struct vattr attr;
2340 	struct vnode *vp;
2341 	struct nameidata nd;
2342 	int error;
2343 
2344 	error = priv_check(td, PRIV_SWAPON);
2345 	if (error)
2346 		return (error);
2347 
2348 	sx_xlock(&swdev_syscall_lock);
2349 
2350 	/*
2351 	 * Swap metadata may not fit in the KVM if we have physical
2352 	 * memory of >1GB.
2353 	 */
2354 	if (swblk_zone == NULL) {
2355 		error = ENOMEM;
2356 		goto done;
2357 	}
2358 
2359 	NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | LOCKLEAF | AUDITVNODE1,
2360 	    UIO_USERSPACE, uap->name);
2361 	error = namei(&nd);
2362 	if (error)
2363 		goto done;
2364 
2365 	NDFREE_PNBUF(&nd);
2366 	vp = nd.ni_vp;
2367 
2368 	if (vn_isdisk_error(vp, &error)) {
2369 		error = swapongeom(vp);
2370 	} else if (vp->v_type == VREG &&
2371 	    (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2372 	    (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2373 		/*
2374 		 * Allow direct swapping to NFS regular files in the same
2375 		 * way that nfs_mountroot() sets up diskless swapping.
2376 		 */
2377 		error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2378 	}
2379 
2380 	if (error != 0)
2381 		vput(vp);
2382 	else
2383 		VOP_UNLOCK(vp);
2384 done:
2385 	sx_xunlock(&swdev_syscall_lock);
2386 	return (error);
2387 }
2388 
2389 /*
2390  * Check that the total amount of swap currently configured does not
2391  * exceed half the theoretical maximum.  If it does, print a warning
2392  * message.
2393  */
2394 static void
2395 swapon_check_swzone(void)
2396 {
2397 
2398 	/* recommend using no more than half that amount */
2399 	if (swap_total > swap_maxpages / 2) {
2400 		printf("warning: total configured swap (%lu pages) "
2401 		    "exceeds maximum recommended amount (%lu pages).\n",
2402 		    swap_total, swap_maxpages / 2);
2403 		printf("warning: increase kern.maxswzone "
2404 		    "or reduce amount of swap.\n");
2405 	}
2406 }
2407 
2408 static void
2409 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2410     sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2411 {
2412 	struct swdevt *sp, *tsp;
2413 	daddr_t dvbase;
2414 
2415 	/*
2416 	 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2417 	 * First chop nblks off to page-align it, then convert.
2418 	 *
2419 	 * sw->sw_nblks is in page-sized chunks now too.
2420 	 */
2421 	nblks &= ~(ctodb(1) - 1);
2422 	nblks = dbtoc(nblks);
2423 
2424 	sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2425 	sp->sw_blist = blist_create(nblks, M_WAITOK);
2426 	sp->sw_vp = vp;
2427 	sp->sw_id = id;
2428 	sp->sw_dev = dev;
2429 	sp->sw_nblks = nblks;
2430 	sp->sw_used = 0;
2431 	sp->sw_strategy = strategy;
2432 	sp->sw_close = close;
2433 	sp->sw_flags = flags;
2434 
2435 	/*
2436 	 * Do not free the first blocks in order to avoid overwriting
2437 	 * any bsd label at the front of the partition
2438 	 */
2439 	blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2440 	    nblks - howmany(BBSIZE, PAGE_SIZE));
2441 
2442 	dvbase = 0;
2443 	mtx_lock(&sw_dev_mtx);
2444 	TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2445 		if (tsp->sw_end >= dvbase) {
2446 			/*
2447 			 * We put one uncovered page between the devices
2448 			 * in order to definitively prevent any cross-device
2449 			 * I/O requests
2450 			 */
2451 			dvbase = tsp->sw_end + 1;
2452 		}
2453 	}
2454 	sp->sw_first = dvbase;
2455 	sp->sw_end = dvbase + nblks;
2456 	TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2457 	nswapdev++;
2458 	swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2459 	swap_total += nblks;
2460 	swapon_check_swzone();
2461 	swp_sizecheck();
2462 	mtx_unlock(&sw_dev_mtx);
2463 	EVENTHANDLER_INVOKE(swapon, sp);
2464 }
2465 
2466 /*
2467  * SYSCALL: swapoff(devname)
2468  *
2469  * Disable swapping on the given device.
2470  *
2471  * XXX: Badly designed system call: it should use a device index
2472  * rather than filename as specification.  We keep sw_vp around
2473  * only to make this work.
2474  */
2475 static int
2476 kern_swapoff(struct thread *td, const char *name, enum uio_seg name_seg,
2477     u_int flags)
2478 {
2479 	struct vnode *vp;
2480 	struct nameidata nd;
2481 	struct swdevt *sp;
2482 	int error;
2483 
2484 	error = priv_check(td, PRIV_SWAPOFF);
2485 	if (error != 0)
2486 		return (error);
2487 	if ((flags & ~(SWAPOFF_FORCE)) != 0)
2488 		return (EINVAL);
2489 
2490 	sx_xlock(&swdev_syscall_lock);
2491 
2492 	NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, name_seg, name);
2493 	error = namei(&nd);
2494 	if (error)
2495 		goto done;
2496 	NDFREE_PNBUF(&nd);
2497 	vp = nd.ni_vp;
2498 
2499 	mtx_lock(&sw_dev_mtx);
2500 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2501 		if (sp->sw_vp == vp)
2502 			break;
2503 	}
2504 	mtx_unlock(&sw_dev_mtx);
2505 	if (sp == NULL) {
2506 		error = EINVAL;
2507 		goto done;
2508 	}
2509 	error = swapoff_one(sp, td->td_ucred, flags);
2510 done:
2511 	sx_xunlock(&swdev_syscall_lock);
2512 	return (error);
2513 }
2514 
2515 
2516 #ifdef COMPAT_FREEBSD13
2517 int
2518 freebsd13_swapoff(struct thread *td, struct freebsd13_swapoff_args *uap)
2519 {
2520 	return (kern_swapoff(td, uap->name, UIO_USERSPACE, 0));
2521 }
2522 #endif
2523 
2524 int
2525 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2526 {
2527 	return (kern_swapoff(td, uap->name, UIO_USERSPACE, uap->flags));
2528 }
2529 
2530 static int
2531 swapoff_one(struct swdevt *sp, struct ucred *cred, u_int flags)
2532 {
2533 	u_long nblks;
2534 #ifdef MAC
2535 	int error;
2536 #endif
2537 
2538 	sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2539 #ifdef MAC
2540 	(void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2541 	error = mac_system_check_swapoff(cred, sp->sw_vp);
2542 	(void) VOP_UNLOCK(sp->sw_vp);
2543 	if (error != 0)
2544 		return (error);
2545 #endif
2546 	nblks = sp->sw_nblks;
2547 
2548 	/*
2549 	 * We can turn off this swap device safely only if the
2550 	 * available virtual memory in the system will fit the amount
2551 	 * of data we will have to page back in, plus an epsilon so
2552 	 * the system doesn't become critically low on swap space.
2553 	 * The vm_free_count() part does not account e.g. for clean
2554 	 * pages that can be immediately reclaimed without paging, so
2555 	 * this is a very rough estimation.
2556 	 *
2557 	 * On the other hand, not turning swap off on swapoff_all()
2558 	 * means that we can lose swap data when filesystems go away,
2559 	 * which is arguably worse.
2560 	 */
2561 	if ((flags & SWAPOFF_FORCE) == 0 &&
2562 	    vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
2563 		return (ENOMEM);
2564 
2565 	/*
2566 	 * Prevent further allocations on this device.
2567 	 */
2568 	mtx_lock(&sw_dev_mtx);
2569 	sp->sw_flags |= SW_CLOSING;
2570 	swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2571 	swap_total -= nblks;
2572 	mtx_unlock(&sw_dev_mtx);
2573 
2574 	/*
2575 	 * Page in the contents of the device and close it.
2576 	 */
2577 	swap_pager_swapoff(sp);
2578 
2579 	sp->sw_close(curthread, sp);
2580 	mtx_lock(&sw_dev_mtx);
2581 	sp->sw_id = NULL;
2582 	TAILQ_REMOVE(&swtailq, sp, sw_list);
2583 	nswapdev--;
2584 	if (nswapdev == 0) {
2585 		swap_pager_full = 2;
2586 		swap_pager_almost_full = 1;
2587 	}
2588 	if (swdevhd == sp)
2589 		swdevhd = NULL;
2590 	mtx_unlock(&sw_dev_mtx);
2591 	blist_destroy(sp->sw_blist);
2592 	free(sp, M_VMPGDATA);
2593 	return (0);
2594 }
2595 
2596 void
2597 swapoff_all(void)
2598 {
2599 	struct swdevt *sp, *spt;
2600 	const char *devname;
2601 	int error;
2602 
2603 	sx_xlock(&swdev_syscall_lock);
2604 
2605 	mtx_lock(&sw_dev_mtx);
2606 	TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2607 		mtx_unlock(&sw_dev_mtx);
2608 		if (vn_isdisk(sp->sw_vp))
2609 			devname = devtoname(sp->sw_vp->v_rdev);
2610 		else
2611 			devname = "[file]";
2612 		error = swapoff_one(sp, thread0.td_ucred, SWAPOFF_FORCE);
2613 		if (error != 0) {
2614 			printf("Cannot remove swap device %s (error=%d), "
2615 			    "skipping.\n", devname, error);
2616 		} else if (bootverbose) {
2617 			printf("Swap device %s removed.\n", devname);
2618 		}
2619 		mtx_lock(&sw_dev_mtx);
2620 	}
2621 	mtx_unlock(&sw_dev_mtx);
2622 
2623 	sx_xunlock(&swdev_syscall_lock);
2624 }
2625 
2626 void
2627 swap_pager_status(int *total, int *used)
2628 {
2629 
2630 	*total = swap_total;
2631 	*used = swap_total - swap_pager_avail -
2632 	    nswapdev * howmany(BBSIZE, PAGE_SIZE);
2633 }
2634 
2635 int
2636 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2637 {
2638 	struct swdevt *sp;
2639 	const char *tmp_devname;
2640 	int error, n;
2641 
2642 	n = 0;
2643 	error = ENOENT;
2644 	mtx_lock(&sw_dev_mtx);
2645 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2646 		if (n != name) {
2647 			n++;
2648 			continue;
2649 		}
2650 		xs->xsw_version = XSWDEV_VERSION;
2651 		xs->xsw_dev = sp->sw_dev;
2652 		xs->xsw_flags = sp->sw_flags;
2653 		xs->xsw_nblks = sp->sw_nblks;
2654 		xs->xsw_used = sp->sw_used;
2655 		if (devname != NULL) {
2656 			if (vn_isdisk(sp->sw_vp))
2657 				tmp_devname = devtoname(sp->sw_vp->v_rdev);
2658 			else
2659 				tmp_devname = "[file]";
2660 			strncpy(devname, tmp_devname, len);
2661 		}
2662 		error = 0;
2663 		break;
2664 	}
2665 	mtx_unlock(&sw_dev_mtx);
2666 	return (error);
2667 }
2668 
2669 #if defined(COMPAT_FREEBSD11)
2670 #define XSWDEV_VERSION_11	1
2671 struct xswdev11 {
2672 	u_int	xsw_version;
2673 	uint32_t xsw_dev;
2674 	int	xsw_flags;
2675 	int	xsw_nblks;
2676 	int     xsw_used;
2677 };
2678 #endif
2679 
2680 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2681 struct xswdev32 {
2682 	u_int	xsw_version;
2683 	u_int	xsw_dev1, xsw_dev2;
2684 	int	xsw_flags;
2685 	int	xsw_nblks;
2686 	int     xsw_used;
2687 };
2688 #endif
2689 
2690 static int
2691 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2692 {
2693 	struct xswdev xs;
2694 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2695 	struct xswdev32 xs32;
2696 #endif
2697 #if defined(COMPAT_FREEBSD11)
2698 	struct xswdev11 xs11;
2699 #endif
2700 	int error;
2701 
2702 	if (arg2 != 1)			/* name length */
2703 		return (EINVAL);
2704 
2705 	memset(&xs, 0, sizeof(xs));
2706 	error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2707 	if (error != 0)
2708 		return (error);
2709 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2710 	if (req->oldlen == sizeof(xs32)) {
2711 		memset(&xs32, 0, sizeof(xs32));
2712 		xs32.xsw_version = XSWDEV_VERSION;
2713 		xs32.xsw_dev1 = xs.xsw_dev;
2714 		xs32.xsw_dev2 = xs.xsw_dev >> 32;
2715 		xs32.xsw_flags = xs.xsw_flags;
2716 		xs32.xsw_nblks = xs.xsw_nblks;
2717 		xs32.xsw_used = xs.xsw_used;
2718 		error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2719 		return (error);
2720 	}
2721 #endif
2722 #if defined(COMPAT_FREEBSD11)
2723 	if (req->oldlen == sizeof(xs11)) {
2724 		memset(&xs11, 0, sizeof(xs11));
2725 		xs11.xsw_version = XSWDEV_VERSION_11;
2726 		xs11.xsw_dev = xs.xsw_dev; /* truncation */
2727 		xs11.xsw_flags = xs.xsw_flags;
2728 		xs11.xsw_nblks = xs.xsw_nblks;
2729 		xs11.xsw_used = xs.xsw_used;
2730 		error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2731 		return (error);
2732 	}
2733 #endif
2734 	error = SYSCTL_OUT(req, &xs, sizeof(xs));
2735 	return (error);
2736 }
2737 
2738 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2739     "Number of swap devices");
2740 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2741     sysctl_vm_swap_info,
2742     "Swap statistics by device");
2743 
2744 /*
2745  * Count the approximate swap usage in pages for a vmspace.  The
2746  * shadowed or not yet copied on write swap blocks are not accounted.
2747  * The map must be locked.
2748  */
2749 long
2750 vmspace_swap_count(struct vmspace *vmspace)
2751 {
2752 	vm_map_t map;
2753 	vm_map_entry_t cur;
2754 	vm_object_t object;
2755 	struct swblk *sb;
2756 	vm_pindex_t e, pi;
2757 	long count;
2758 	int i;
2759 
2760 	map = &vmspace->vm_map;
2761 	count = 0;
2762 
2763 	VM_MAP_ENTRY_FOREACH(cur, map) {
2764 		if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2765 			continue;
2766 		object = cur->object.vm_object;
2767 		if (object == NULL || (object->flags & OBJ_SWAP) == 0)
2768 			continue;
2769 		VM_OBJECT_RLOCK(object);
2770 		if ((object->flags & OBJ_SWAP) == 0)
2771 			goto unlock;
2772 		pi = OFF_TO_IDX(cur->offset);
2773 		e = pi + OFF_TO_IDX(cur->end - cur->start);
2774 		for (;; pi = sb->p + SWAP_META_PAGES) {
2775 			sb = SWAP_PCTRIE_LOOKUP_GE(
2776 			    &object->un_pager.swp.swp_blks, pi);
2777 			if (sb == NULL || sb->p >= e)
2778 				break;
2779 			for (i = 0; i < SWAP_META_PAGES; i++) {
2780 				if (sb->p + i < e &&
2781 				    sb->d[i] != SWAPBLK_NONE)
2782 					count++;
2783 			}
2784 		}
2785 unlock:
2786 		VM_OBJECT_RUNLOCK(object);
2787 	}
2788 	return (count);
2789 }
2790 
2791 /*
2792  * GEOM backend
2793  *
2794  * Swapping onto disk devices.
2795  *
2796  */
2797 
2798 static g_orphan_t swapgeom_orphan;
2799 
2800 static struct g_class g_swap_class = {
2801 	.name = "SWAP",
2802 	.version = G_VERSION,
2803 	.orphan = swapgeom_orphan,
2804 };
2805 
2806 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2807 
2808 static void
2809 swapgeom_close_ev(void *arg, int flags)
2810 {
2811 	struct g_consumer *cp;
2812 
2813 	cp = arg;
2814 	g_access(cp, -1, -1, 0);
2815 	g_detach(cp);
2816 	g_destroy_consumer(cp);
2817 }
2818 
2819 /*
2820  * Add a reference to the g_consumer for an inflight transaction.
2821  */
2822 static void
2823 swapgeom_acquire(struct g_consumer *cp)
2824 {
2825 
2826 	mtx_assert(&sw_dev_mtx, MA_OWNED);
2827 	cp->index++;
2828 }
2829 
2830 /*
2831  * Remove a reference from the g_consumer.  Post a close event if all
2832  * references go away, since the function might be called from the
2833  * biodone context.
2834  */
2835 static void
2836 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2837 {
2838 
2839 	mtx_assert(&sw_dev_mtx, MA_OWNED);
2840 	cp->index--;
2841 	if (cp->index == 0) {
2842 		if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2843 			sp->sw_id = NULL;
2844 	}
2845 }
2846 
2847 static void
2848 swapgeom_done(struct bio *bp2)
2849 {
2850 	struct swdevt *sp;
2851 	struct buf *bp;
2852 	struct g_consumer *cp;
2853 
2854 	bp = bp2->bio_caller2;
2855 	cp = bp2->bio_from;
2856 	bp->b_ioflags = bp2->bio_flags;
2857 	if (bp2->bio_error)
2858 		bp->b_ioflags |= BIO_ERROR;
2859 	bp->b_resid = bp->b_bcount - bp2->bio_completed;
2860 	bp->b_error = bp2->bio_error;
2861 	bp->b_caller1 = NULL;
2862 	bufdone(bp);
2863 	sp = bp2->bio_caller1;
2864 	mtx_lock(&sw_dev_mtx);
2865 	swapgeom_release(cp, sp);
2866 	mtx_unlock(&sw_dev_mtx);
2867 	g_destroy_bio(bp2);
2868 }
2869 
2870 static void
2871 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2872 {
2873 	struct bio *bio;
2874 	struct g_consumer *cp;
2875 
2876 	mtx_lock(&sw_dev_mtx);
2877 	cp = sp->sw_id;
2878 	if (cp == NULL) {
2879 		mtx_unlock(&sw_dev_mtx);
2880 		bp->b_error = ENXIO;
2881 		bp->b_ioflags |= BIO_ERROR;
2882 		bufdone(bp);
2883 		return;
2884 	}
2885 	swapgeom_acquire(cp);
2886 	mtx_unlock(&sw_dev_mtx);
2887 	if (bp->b_iocmd == BIO_WRITE)
2888 		bio = g_new_bio();
2889 	else
2890 		bio = g_alloc_bio();
2891 	if (bio == NULL) {
2892 		mtx_lock(&sw_dev_mtx);
2893 		swapgeom_release(cp, sp);
2894 		mtx_unlock(&sw_dev_mtx);
2895 		bp->b_error = ENOMEM;
2896 		bp->b_ioflags |= BIO_ERROR;
2897 		printf("swap_pager: cannot allocate bio\n");
2898 		bufdone(bp);
2899 		return;
2900 	}
2901 
2902 	bp->b_caller1 = bio;
2903 	bio->bio_caller1 = sp;
2904 	bio->bio_caller2 = bp;
2905 	bio->bio_cmd = bp->b_iocmd;
2906 	bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2907 	bio->bio_length = bp->b_bcount;
2908 	bio->bio_done = swapgeom_done;
2909 	bio->bio_flags |= BIO_SWAP;
2910 	if (!buf_mapped(bp)) {
2911 		bio->bio_ma = bp->b_pages;
2912 		bio->bio_data = unmapped_buf;
2913 		bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2914 		bio->bio_ma_n = bp->b_npages;
2915 		bio->bio_flags |= BIO_UNMAPPED;
2916 	} else {
2917 		bio->bio_data = bp->b_data;
2918 		bio->bio_ma = NULL;
2919 	}
2920 	g_io_request(bio, cp);
2921 	return;
2922 }
2923 
2924 static void
2925 swapgeom_orphan(struct g_consumer *cp)
2926 {
2927 	struct swdevt *sp;
2928 	int destroy;
2929 
2930 	mtx_lock(&sw_dev_mtx);
2931 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2932 		if (sp->sw_id == cp) {
2933 			sp->sw_flags |= SW_CLOSING;
2934 			break;
2935 		}
2936 	}
2937 	/*
2938 	 * Drop reference we were created with. Do directly since we're in a
2939 	 * special context where we don't have to queue the call to
2940 	 * swapgeom_close_ev().
2941 	 */
2942 	cp->index--;
2943 	destroy = ((sp != NULL) && (cp->index == 0));
2944 	if (destroy)
2945 		sp->sw_id = NULL;
2946 	mtx_unlock(&sw_dev_mtx);
2947 	if (destroy)
2948 		swapgeom_close_ev(cp, 0);
2949 }
2950 
2951 static void
2952 swapgeom_close(struct thread *td, struct swdevt *sw)
2953 {
2954 	struct g_consumer *cp;
2955 
2956 	mtx_lock(&sw_dev_mtx);
2957 	cp = sw->sw_id;
2958 	sw->sw_id = NULL;
2959 	mtx_unlock(&sw_dev_mtx);
2960 
2961 	/*
2962 	 * swapgeom_close() may be called from the biodone context,
2963 	 * where we cannot perform topology changes.  Delegate the
2964 	 * work to the events thread.
2965 	 */
2966 	if (cp != NULL)
2967 		g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2968 }
2969 
2970 static int
2971 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2972 {
2973 	struct g_provider *pp;
2974 	struct g_consumer *cp;
2975 	static struct g_geom *gp;
2976 	struct swdevt *sp;
2977 	u_long nblks;
2978 	int error;
2979 
2980 	pp = g_dev_getprovider(dev);
2981 	if (pp == NULL)
2982 		return (ENODEV);
2983 	mtx_lock(&sw_dev_mtx);
2984 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2985 		cp = sp->sw_id;
2986 		if (cp != NULL && cp->provider == pp) {
2987 			mtx_unlock(&sw_dev_mtx);
2988 			return (EBUSY);
2989 		}
2990 	}
2991 	mtx_unlock(&sw_dev_mtx);
2992 	if (gp == NULL)
2993 		gp = g_new_geomf(&g_swap_class, "swap");
2994 	cp = g_new_consumer(gp);
2995 	cp->index = 1;	/* Number of active I/Os, plus one for being active. */
2996 	cp->flags |=  G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2997 	g_attach(cp, pp);
2998 	/*
2999 	 * XXX: Every time you think you can improve the margin for
3000 	 * footshooting, somebody depends on the ability to do so:
3001 	 * savecore(8) wants to write to our swapdev so we cannot
3002 	 * set an exclusive count :-(
3003 	 */
3004 	error = g_access(cp, 1, 1, 0);
3005 	if (error != 0) {
3006 		g_detach(cp);
3007 		g_destroy_consumer(cp);
3008 		return (error);
3009 	}
3010 	nblks = pp->mediasize / DEV_BSIZE;
3011 	swaponsomething(vp, cp, nblks, swapgeom_strategy,
3012 	    swapgeom_close, dev2udev(dev),
3013 	    (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
3014 	return (0);
3015 }
3016 
3017 static int
3018 swapongeom(struct vnode *vp)
3019 {
3020 	int error;
3021 
3022 	ASSERT_VOP_ELOCKED(vp, "swapongeom");
3023 	if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) {
3024 		error = ENOENT;
3025 	} else {
3026 		g_topology_lock();
3027 		error = swapongeom_locked(vp->v_rdev, vp);
3028 		g_topology_unlock();
3029 	}
3030 	return (error);
3031 }
3032 
3033 /*
3034  * VNODE backend
3035  *
3036  * This is used mainly for network filesystem (read: probably only tested
3037  * with NFS) swapfiles.
3038  *
3039  */
3040 
3041 static void
3042 swapdev_strategy(struct buf *bp, struct swdevt *sp)
3043 {
3044 	struct vnode *vp2;
3045 
3046 	bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
3047 
3048 	vp2 = sp->sw_id;
3049 	vhold(vp2);
3050 	if (bp->b_iocmd == BIO_WRITE) {
3051 		vn_lock(vp2, LK_EXCLUSIVE | LK_RETRY);
3052 		if (bp->b_bufobj)
3053 			bufobj_wdrop(bp->b_bufobj);
3054 		bufobj_wref(&vp2->v_bufobj);
3055 	} else {
3056 		vn_lock(vp2, LK_SHARED | LK_RETRY);
3057 	}
3058 	if (bp->b_bufobj != &vp2->v_bufobj)
3059 		bp->b_bufobj = &vp2->v_bufobj;
3060 	bp->b_vp = vp2;
3061 	bp->b_iooffset = dbtob(bp->b_blkno);
3062 	bstrategy(bp);
3063 	VOP_UNLOCK(vp2);
3064 }
3065 
3066 static void
3067 swapdev_close(struct thread *td, struct swdevt *sp)
3068 {
3069 	struct vnode *vp;
3070 
3071 	vp = sp->sw_vp;
3072 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3073 	VOP_CLOSE(vp, FREAD | FWRITE, td->td_ucred, td);
3074 	vput(vp);
3075 }
3076 
3077 static int
3078 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
3079 {
3080 	struct swdevt *sp;
3081 	int error;
3082 
3083 	ASSERT_VOP_ELOCKED(vp, "swaponvp");
3084 	if (nblks == 0)
3085 		return (ENXIO);
3086 	mtx_lock(&sw_dev_mtx);
3087 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
3088 		if (sp->sw_id == vp) {
3089 			mtx_unlock(&sw_dev_mtx);
3090 			return (EBUSY);
3091 		}
3092 	}
3093 	mtx_unlock(&sw_dev_mtx);
3094 
3095 #ifdef MAC
3096 	error = mac_system_check_swapon(td->td_ucred, vp);
3097 	if (error == 0)
3098 #endif
3099 		error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
3100 	if (error != 0)
3101 		return (error);
3102 
3103 	swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
3104 	    NODEV, 0);
3105 	return (0);
3106 }
3107 
3108 static int
3109 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
3110 {
3111 	int error, new, n;
3112 
3113 	new = nsw_wcount_async_max;
3114 	error = sysctl_handle_int(oidp, &new, 0, req);
3115 	if (error != 0 || req->newptr == NULL)
3116 		return (error);
3117 
3118 	if (new > nswbuf / 2 || new < 1)
3119 		return (EINVAL);
3120 
3121 	mtx_lock(&swbuf_mtx);
3122 	while (nsw_wcount_async_max != new) {
3123 		/*
3124 		 * Adjust difference.  If the current async count is too low,
3125 		 * we will need to sqeeze our update slowly in.  Sleep with a
3126 		 * higher priority than getpbuf() to finish faster.
3127 		 */
3128 		n = new - nsw_wcount_async_max;
3129 		if (nsw_wcount_async + n >= 0) {
3130 			nsw_wcount_async += n;
3131 			nsw_wcount_async_max += n;
3132 			wakeup(&nsw_wcount_async);
3133 		} else {
3134 			nsw_wcount_async_max -= nsw_wcount_async;
3135 			nsw_wcount_async = 0;
3136 			msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
3137 			    "swpsysctl", 0);
3138 		}
3139 	}
3140 	mtx_unlock(&swbuf_mtx);
3141 
3142 	return (0);
3143 }
3144 
3145 static void
3146 swap_pager_update_writecount(vm_object_t object, vm_offset_t start,
3147     vm_offset_t end)
3148 {
3149 
3150 	VM_OBJECT_WLOCK(object);
3151 	KASSERT((object->flags & OBJ_ANON) == 0,
3152 	    ("Splittable object with writecount"));
3153 	object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
3154 	VM_OBJECT_WUNLOCK(object);
3155 }
3156 
3157 static void
3158 swap_pager_release_writecount(vm_object_t object, vm_offset_t start,
3159     vm_offset_t end)
3160 {
3161 
3162 	VM_OBJECT_WLOCK(object);
3163 	KASSERT((object->flags & OBJ_ANON) == 0,
3164 	    ("Splittable object with writecount"));
3165 	KASSERT(object->un_pager.swp.writemappings >= (vm_ooffset_t)end - start,
3166 	    ("swap obj %p writecount %jx dec %jx", object,
3167 	    (uintmax_t)object->un_pager.swp.writemappings,
3168 	    (uintmax_t)((vm_ooffset_t)end - start)));
3169 	object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
3170 	VM_OBJECT_WUNLOCK(object);
3171 }
3172