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