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