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