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