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