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