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