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