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