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