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