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