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