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