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