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