xref: /freebsd/sys/vm/swap_pager.c (revision cfe55a8af81df098995143cf3a17f67f591f5dae)
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 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t,
491     vm_size_t *);
492 static void swp_pager_meta_transfer(vm_object_t src, vm_object_t dst,
493     vm_pindex_t pindex, vm_pindex_t count, vm_size_t *freed);
494 static void swp_pager_meta_free_all(vm_object_t);
495 static daddr_t swp_pager_meta_lookup(vm_object_t, vm_pindex_t);
496 
497 static void
498 swp_pager_init_freerange(struct page_range *range)
499 {
500 	range->start = SWAPBLK_NONE;
501 	range->num = 0;
502 }
503 
504 static void
505 swp_pager_update_freerange(struct page_range *range, daddr_t addr)
506 {
507 	if (range->start + range->num == addr) {
508 		range->num++;
509 	} else {
510 		swp_pager_freeswapspace(range);
511 		range->start = addr;
512 		range->num = 1;
513 	}
514 }
515 
516 static void *
517 swblk_trie_alloc(struct pctrie *ptree)
518 {
519 
520 	return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
521 	    M_USE_RESERVE : 0)));
522 }
523 
524 static void
525 swblk_trie_free(struct pctrie *ptree, void *node)
526 {
527 
528 	uma_zfree(swpctrie_zone, node);
529 }
530 
531 PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
532 
533 /*
534  * SWP_SIZECHECK() -	update swap_pager_full indication
535  *
536  *	update the swap_pager_almost_full indication and warn when we are
537  *	about to run out of swap space, using lowat/hiwat hysteresis.
538  *
539  *	Clear swap_pager_full ( task killing ) indication when lowat is met.
540  *
541  *	No restrictions on call
542  *	This routine may not block.
543  */
544 static void
545 swp_sizecheck(void)
546 {
547 
548 	if (swap_pager_avail < nswap_lowat) {
549 		if (swap_pager_almost_full == 0) {
550 			printf("swap_pager: out of swap space\n");
551 			swap_pager_almost_full = 1;
552 		}
553 	} else {
554 		swap_pager_full = 0;
555 		if (swap_pager_avail > nswap_hiwat)
556 			swap_pager_almost_full = 0;
557 	}
558 }
559 
560 /*
561  * SWAP_PAGER_INIT() -	initialize the swap pager!
562  *
563  *	Expected to be started from system init.  NOTE:  This code is run
564  *	before much else so be careful what you depend on.  Most of the VM
565  *	system has yet to be initialized at this point.
566  */
567 static void
568 swap_pager_init(void)
569 {
570 	/*
571 	 * Initialize object lists
572 	 */
573 	int i;
574 
575 	for (i = 0; i < NOBJLISTS; ++i)
576 		TAILQ_INIT(&swap_pager_object_list[i]);
577 	mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
578 	sx_init(&sw_alloc_sx, "swspsx");
579 	sx_init(&swdev_syscall_lock, "swsysc");
580 
581 	/*
582 	 * The nsw_cluster_max is constrained by the bp->b_pages[]
583 	 * array, which has maxphys / PAGE_SIZE entries, and our locally
584 	 * defined MAX_PAGEOUT_CLUSTER.   Also be aware that swap ops are
585 	 * constrained by the swap device interleave stripe size.
586 	 *
587 	 * Initialized early so that GEOM_ELI can see it.
588 	 */
589 	nsw_cluster_max = min(maxphys / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
590 }
591 
592 /*
593  * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
594  *
595  *	Expected to be started from pageout process once, prior to entering
596  *	its main loop.
597  */
598 void
599 swap_pager_swap_init(void)
600 {
601 	unsigned long n, n2;
602 
603 	/*
604 	 * Number of in-transit swap bp operations.  Don't
605 	 * exhaust the pbufs completely.  Make sure we
606 	 * initialize workable values (0 will work for hysteresis
607 	 * but it isn't very efficient).
608 	 *
609 	 * Currently we hardwire nsw_wcount_async to 4.  This limit is
610 	 * designed to prevent other I/O from having high latencies due to
611 	 * our pageout I/O.  The value 4 works well for one or two active swap
612 	 * devices but is probably a little low if you have more.  Even so,
613 	 * a higher value would probably generate only a limited improvement
614 	 * with three or four active swap devices since the system does not
615 	 * typically have to pageout at extreme bandwidths.   We will want
616 	 * at least 2 per swap devices, and 4 is a pretty good value if you
617 	 * have one NFS swap device due to the command/ack latency over NFS.
618 	 * So it all works out pretty well.
619 	 *
620 	 * nsw_cluster_max is initialized in swap_pager_init().
621 	 */
622 
623 	nsw_wcount_async = 4;
624 	nsw_wcount_async_max = nsw_wcount_async;
625 	mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
626 
627 	swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
628 	swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
629 
630 	/*
631 	 * Initialize our zone, taking the user's requested size or
632 	 * estimating the number we need based on the number of pages
633 	 * in the system.
634 	 */
635 	n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
636 	    vm_cnt.v_page_count / 2;
637 	swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
638 	    pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0);
639 	swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
640 	    NULL, NULL, _Alignof(struct swblk) - 1, 0);
641 	n2 = n;
642 	do {
643 		if (uma_zone_reserve_kva(swblk_zone, n))
644 			break;
645 		/*
646 		 * if the allocation failed, try a zone two thirds the
647 		 * size of the previous attempt.
648 		 */
649 		n -= ((n + 2) / 3);
650 	} while (n > 0);
651 
652 	/*
653 	 * Often uma_zone_reserve_kva() cannot reserve exactly the
654 	 * requested size.  Account for the difference when
655 	 * calculating swap_maxpages.
656 	 */
657 	n = uma_zone_get_max(swblk_zone);
658 
659 	if (n < n2)
660 		printf("Swap blk zone entries changed from %lu to %lu.\n",
661 		    n2, n);
662 	/* absolute maximum we can handle assuming 100% efficiency */
663 	swap_maxpages = n * SWAP_META_PAGES;
664 	swzone = n * sizeof(struct swblk);
665 	if (!uma_zone_reserve_kva(swpctrie_zone, n))
666 		printf("Cannot reserve swap pctrie zone, "
667 		    "reduce kern.maxswzone.\n");
668 }
669 
670 bool
671 swap_pager_init_object(vm_object_t object, void *handle, struct ucred *cred,
672     vm_ooffset_t size, vm_ooffset_t offset)
673 {
674 	if (cred != NULL) {
675 		if (!swap_reserve_by_cred(size, cred))
676 			return (false);
677 		crhold(cred);
678 	}
679 
680 	object->un_pager.swp.writemappings = 0;
681 	object->handle = handle;
682 	if (cred != NULL) {
683 		object->cred = cred;
684 		object->charge = size;
685 	}
686 	return (true);
687 }
688 
689 static vm_object_t
690 swap_pager_alloc_init(objtype_t otype, void *handle, struct ucred *cred,
691     vm_ooffset_t size, vm_ooffset_t offset)
692 {
693 	vm_object_t object;
694 
695 	/*
696 	 * The un_pager.swp.swp_blks trie is initialized by
697 	 * vm_object_allocate() to ensure the correct order of
698 	 * visibility to other threads.
699 	 */
700 	object = vm_object_allocate(otype, OFF_TO_IDX(offset +
701 	    PAGE_MASK + size));
702 
703 	if (!swap_pager_init_object(object, handle, cred, size, offset)) {
704 		vm_object_deallocate(object);
705 		return (NULL);
706 	}
707 	return (object);
708 }
709 
710 /*
711  * SWAP_PAGER_ALLOC() -	allocate a new OBJT_SWAP VM object and instantiate
712  *			its metadata structures.
713  *
714  *	This routine is called from the mmap and fork code to create a new
715  *	OBJT_SWAP object.
716  *
717  *	This routine must ensure that no live duplicate is created for
718  *	the named object request, which is protected against by
719  *	holding the sw_alloc_sx lock in case handle != NULL.
720  */
721 static vm_object_t
722 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
723     vm_ooffset_t offset, struct ucred *cred)
724 {
725 	vm_object_t object;
726 
727 	if (handle != NULL) {
728 		/*
729 		 * Reference existing named region or allocate new one.  There
730 		 * should not be a race here against swp_pager_meta_build()
731 		 * as called from vm_page_remove() in regards to the lookup
732 		 * of the handle.
733 		 */
734 		sx_xlock(&sw_alloc_sx);
735 		object = vm_pager_object_lookup(NOBJLIST(handle), handle);
736 		if (object == NULL) {
737 			object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
738 			    size, offset);
739 			if (object != NULL) {
740 				TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
741 				    object, pager_object_list);
742 			}
743 		}
744 		sx_xunlock(&sw_alloc_sx);
745 	} else {
746 		object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
747 		    size, offset);
748 	}
749 	return (object);
750 }
751 
752 /*
753  * SWAP_PAGER_DEALLOC() -	remove swap metadata from object
754  *
755  *	The swap backing for the object is destroyed.  The code is
756  *	designed such that we can reinstantiate it later, but this
757  *	routine is typically called only when the entire object is
758  *	about to be destroyed.
759  *
760  *	The object must be locked.
761  */
762 static void
763 swap_pager_dealloc(vm_object_t object)
764 {
765 
766 	VM_OBJECT_ASSERT_WLOCKED(object);
767 	KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
768 
769 	/*
770 	 * Remove from list right away so lookups will fail if we block for
771 	 * pageout completion.
772 	 */
773 	if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
774 		VM_OBJECT_WUNLOCK(object);
775 		sx_xlock(&sw_alloc_sx);
776 		TAILQ_REMOVE(NOBJLIST(object->handle), object,
777 		    pager_object_list);
778 		sx_xunlock(&sw_alloc_sx);
779 		VM_OBJECT_WLOCK(object);
780 	}
781 
782 	vm_object_pip_wait(object, "swpdea");
783 
784 	/*
785 	 * Free all remaining metadata.  We only bother to free it from
786 	 * the swap meta data.  We do not attempt to free swapblk's still
787 	 * associated with vm_page_t's for this object.  We do not care
788 	 * if paging is still in progress on some objects.
789 	 */
790 	swp_pager_meta_free_all(object);
791 	object->handle = NULL;
792 	object->type = OBJT_DEAD;
793 
794 	/*
795 	 * Release the allocation charge.
796 	 */
797 	if (object->cred != NULL) {
798 		swap_release_by_cred(object->charge, object->cred);
799 		object->charge = 0;
800 		crfree(object->cred);
801 		object->cred = NULL;
802 	}
803 
804 	/*
805 	 * Hide the object from swap_pager_swapoff().
806 	 */
807 	vm_object_clear_flag(object, OBJ_SWAP);
808 }
809 
810 /************************************************************************
811  *			SWAP PAGER BITMAP ROUTINES			*
812  ************************************************************************/
813 
814 /*
815  * SWP_PAGER_GETSWAPSPACE() -	allocate raw swap space
816  *
817  *	Allocate swap for up to the requested number of pages.  The
818  *	starting swap block number (a page index) is returned or
819  *	SWAPBLK_NONE if the allocation failed.
820  *
821  *	Also has the side effect of advising that somebody made a mistake
822  *	when they configured swap and didn't configure enough.
823  *
824  *	This routine may not sleep.
825  *
826  *	We allocate in round-robin fashion from the configured devices.
827  */
828 static daddr_t
829 swp_pager_getswapspace(int *io_npages)
830 {
831 	daddr_t blk;
832 	struct swdevt *sp;
833 	int mpages, npages;
834 
835 	KASSERT(*io_npages >= 1,
836 	    ("%s: npages not positive", __func__));
837 	blk = SWAPBLK_NONE;
838 	mpages = *io_npages;
839 	npages = imin(BLIST_MAX_ALLOC, mpages);
840 	mtx_lock(&sw_dev_mtx);
841 	sp = swdevhd;
842 	while (!TAILQ_EMPTY(&swtailq)) {
843 		if (sp == NULL)
844 			sp = TAILQ_FIRST(&swtailq);
845 		if ((sp->sw_flags & SW_CLOSING) == 0)
846 			blk = blist_alloc(sp->sw_blist, &npages, mpages);
847 		if (blk != SWAPBLK_NONE)
848 			break;
849 		sp = TAILQ_NEXT(sp, sw_list);
850 		if (swdevhd == sp) {
851 			if (npages == 1)
852 				break;
853 			mpages = npages - 1;
854 			npages >>= 1;
855 		}
856 	}
857 	if (blk != SWAPBLK_NONE) {
858 		*io_npages = npages;
859 		blk += sp->sw_first;
860 		sp->sw_used += npages;
861 		swap_pager_avail -= npages;
862 		swp_sizecheck();
863 		swdevhd = TAILQ_NEXT(sp, sw_list);
864 	} else {
865 		if (swap_pager_full != 2) {
866 			printf("swp_pager_getswapspace(%d): failed\n",
867 			    *io_npages);
868 			swap_pager_full = 2;
869 			swap_pager_almost_full = 1;
870 		}
871 		swdevhd = NULL;
872 	}
873 	mtx_unlock(&sw_dev_mtx);
874 	return (blk);
875 }
876 
877 static bool
878 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
879 {
880 
881 	return (blk >= sp->sw_first && blk < sp->sw_end);
882 }
883 
884 static void
885 swp_pager_strategy(struct buf *bp)
886 {
887 	struct swdevt *sp;
888 
889 	mtx_lock(&sw_dev_mtx);
890 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
891 		if (swp_pager_isondev(bp->b_blkno, sp)) {
892 			mtx_unlock(&sw_dev_mtx);
893 			if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
894 			    unmapped_buf_allowed) {
895 				bp->b_data = unmapped_buf;
896 				bp->b_offset = 0;
897 			} else {
898 				pmap_qenter((vm_offset_t)bp->b_data,
899 				    &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
900 			}
901 			sp->sw_strategy(bp, sp);
902 			return;
903 		}
904 	}
905 	panic("Swapdev not found");
906 }
907 
908 /*
909  * SWP_PAGER_FREESWAPSPACE() -	free raw swap space
910  *
911  *	This routine returns the specified swap blocks back to the bitmap.
912  *
913  *	This routine may not sleep.
914  */
915 static void
916 swp_pager_freeswapspace(const struct page_range *range)
917 {
918 	daddr_t blk, npages;
919 	struct swdevt *sp;
920 
921 	blk = range->start;
922 	npages = range->num;
923 	if (npages == 0)
924 		return;
925 	mtx_lock(&sw_dev_mtx);
926 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
927 		if (swp_pager_isondev(blk, sp)) {
928 			sp->sw_used -= npages;
929 			/*
930 			 * If we are attempting to stop swapping on
931 			 * this device, we don't want to mark any
932 			 * blocks free lest they be reused.
933 			 */
934 			if ((sp->sw_flags & SW_CLOSING) == 0) {
935 				blist_free(sp->sw_blist, blk - sp->sw_first,
936 				    npages);
937 				swap_pager_avail += npages;
938 				swp_sizecheck();
939 			}
940 			mtx_unlock(&sw_dev_mtx);
941 			return;
942 		}
943 	}
944 	panic("Swapdev not found");
945 }
946 
947 /*
948  * SYSCTL_SWAP_FRAGMENTATION() -	produce raw swap space stats
949  */
950 static int
951 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
952 {
953 	struct sbuf sbuf;
954 	struct swdevt *sp;
955 	const char *devname;
956 	int error;
957 
958 	error = sysctl_wire_old_buffer(req, 0);
959 	if (error != 0)
960 		return (error);
961 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
962 	mtx_lock(&sw_dev_mtx);
963 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
964 		if (vn_isdisk(sp->sw_vp))
965 			devname = devtoname(sp->sw_vp->v_rdev);
966 		else
967 			devname = "[file]";
968 		sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
969 		blist_stats(sp->sw_blist, &sbuf);
970 	}
971 	mtx_unlock(&sw_dev_mtx);
972 	error = sbuf_finish(&sbuf);
973 	sbuf_delete(&sbuf);
974 	return (error);
975 }
976 
977 /*
978  * SWAP_PAGER_FREESPACE() -	frees swap blocks associated with a page
979  *				range within an object.
980  *
981  *	This routine removes swapblk assignments from swap metadata.
982  *
983  *	The external callers of this routine typically have already destroyed
984  *	or renamed vm_page_t's associated with this range in the object so
985  *	we should be ok.
986  *
987  *	The object must be locked.
988  */
989 void
990 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size,
991     vm_size_t *freed)
992 {
993 	MPASS((object->flags & OBJ_SWAP) != 0);
994 
995 	swp_pager_meta_free(object, start, size, freed);
996 }
997 
998 static void
999 swap_pager_freespace_pgo(vm_object_t object, vm_pindex_t start, vm_size_t size)
1000 {
1001 	MPASS((object->flags & OBJ_SWAP) != 0);
1002 
1003 	swp_pager_meta_free(object, start, size, NULL);
1004 }
1005 
1006 /*
1007  * SWAP_PAGER_RESERVE() - reserve swap blocks in object
1008  *
1009  *	Assigns swap blocks to the specified range within the object.  The
1010  *	swap blocks are not zeroed.  Any previous swap assignment is destroyed.
1011  *
1012  *	Returns 0 on success, -1 on failure.
1013  */
1014 int
1015 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_pindex_t size)
1016 {
1017 	struct page_range range;
1018 	daddr_t addr, blk;
1019 	vm_pindex_t i, j;
1020 	int n;
1021 
1022 	swp_pager_init_freerange(&range);
1023 	VM_OBJECT_WLOCK(object);
1024 	for (i = 0; i < size; i += n) {
1025 		n = MIN(size - i, INT_MAX);
1026 		blk = swp_pager_getswapspace(&n);
1027 		if (blk == SWAPBLK_NONE) {
1028 			swp_pager_meta_free(object, start, i, NULL);
1029 			VM_OBJECT_WUNLOCK(object);
1030 			return (-1);
1031 		}
1032 		for (j = 0; j < n; ++j) {
1033 			addr = swp_pager_meta_build(object,
1034 			    start + i + j, blk + j);
1035 			if (addr != SWAPBLK_NONE)
1036 				swp_pager_update_freerange(&range, addr);
1037 		}
1038 	}
1039 	swp_pager_freeswapspace(&range);
1040 	VM_OBJECT_WUNLOCK(object);
1041 	return (0);
1042 }
1043 
1044 static bool
1045 swp_pager_xfer_source(vm_object_t srcobject, vm_object_t dstobject,
1046     vm_pindex_t pindex, daddr_t addr)
1047 {
1048 	daddr_t dstaddr __diagused;
1049 
1050 	KASSERT((srcobject->flags & OBJ_SWAP) != 0,
1051 	    ("%s: srcobject not swappable", __func__));
1052 	KASSERT((dstobject->flags & OBJ_SWAP) != 0,
1053 	    ("%s: dstobject not swappable", __func__));
1054 
1055 	if (swp_pager_meta_lookup(dstobject, pindex) != SWAPBLK_NONE) {
1056 		/* Caller should destroy the source block. */
1057 		return (false);
1058 	}
1059 
1060 	/*
1061 	 * Destination has no swapblk and is not resident, transfer source.
1062 	 * swp_pager_meta_build() can sleep.
1063 	 */
1064 	VM_OBJECT_WUNLOCK(srcobject);
1065 	dstaddr = swp_pager_meta_build(dstobject, pindex, addr);
1066 	KASSERT(dstaddr == SWAPBLK_NONE,
1067 	    ("Unexpected destination swapblk"));
1068 	VM_OBJECT_WLOCK(srcobject);
1069 
1070 	return (true);
1071 }
1072 
1073 /*
1074  * SWAP_PAGER_COPY() -  copy blocks from source pager to destination pager
1075  *			and destroy the source.
1076  *
1077  *	Copy any valid swapblks from the source to the destination.  In
1078  *	cases where both the source and destination have a valid swapblk,
1079  *	we keep the destination's.
1080  *
1081  *	This routine is allowed to sleep.  It may sleep allocating metadata
1082  *	indirectly through swp_pager_meta_build().
1083  *
1084  *	The source object contains no vm_page_t's (which is just as well)
1085  *
1086  *	The source and destination objects must be locked.
1087  *	Both object locks may temporarily be released.
1088  */
1089 void
1090 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
1091     vm_pindex_t offset, int destroysource)
1092 {
1093 	VM_OBJECT_ASSERT_WLOCKED(srcobject);
1094 	VM_OBJECT_ASSERT_WLOCKED(dstobject);
1095 
1096 	/*
1097 	 * If destroysource is set, we remove the source object from the
1098 	 * swap_pager internal queue now.
1099 	 */
1100 	if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
1101 	    srcobject->handle != NULL) {
1102 		VM_OBJECT_WUNLOCK(srcobject);
1103 		VM_OBJECT_WUNLOCK(dstobject);
1104 		sx_xlock(&sw_alloc_sx);
1105 		TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1106 		    pager_object_list);
1107 		sx_xunlock(&sw_alloc_sx);
1108 		VM_OBJECT_WLOCK(dstobject);
1109 		VM_OBJECT_WLOCK(srcobject);
1110 	}
1111 
1112 	/*
1113 	 * Transfer source to destination.
1114 	 */
1115 	swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size,
1116 	    NULL);
1117 
1118 	/*
1119 	 * Free left over swap blocks in source.
1120 	 */
1121 	if (destroysource)
1122 		swp_pager_meta_free_all(srcobject);
1123 }
1124 
1125 /*
1126  * SWAP_PAGER_HASPAGE() -	determine if we have good backing store for
1127  *				the requested page.
1128  *
1129  *	We determine whether good backing store exists for the requested
1130  *	page and return TRUE if it does, FALSE if it doesn't.
1131  *
1132  *	If TRUE, we also try to determine how much valid, contiguous backing
1133  *	store exists before and after the requested page.
1134  */
1135 static boolean_t
1136 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1137     int *after)
1138 {
1139 	daddr_t blk, blk0;
1140 	int i;
1141 
1142 	VM_OBJECT_ASSERT_LOCKED(object);
1143 	KASSERT((object->flags & OBJ_SWAP) != 0,
1144 	    ("%s: object not swappable", __func__));
1145 
1146 	/*
1147 	 * do we have good backing store at the requested index ?
1148 	 */
1149 	blk0 = swp_pager_meta_lookup(object, pindex);
1150 	if (blk0 == SWAPBLK_NONE) {
1151 		if (before)
1152 			*before = 0;
1153 		if (after)
1154 			*after = 0;
1155 		return (FALSE);
1156 	}
1157 
1158 	/*
1159 	 * find backwards-looking contiguous good backing store
1160 	 */
1161 	if (before != NULL) {
1162 		for (i = 1; i < SWB_NPAGES; i++) {
1163 			if (i > pindex)
1164 				break;
1165 			blk = swp_pager_meta_lookup(object, pindex - i);
1166 			if (blk != blk0 - i)
1167 				break;
1168 		}
1169 		*before = i - 1;
1170 	}
1171 
1172 	/*
1173 	 * find forward-looking contiguous good backing store
1174 	 */
1175 	if (after != NULL) {
1176 		for (i = 1; i < SWB_NPAGES; i++) {
1177 			blk = swp_pager_meta_lookup(object, pindex + i);
1178 			if (blk != blk0 + i)
1179 				break;
1180 		}
1181 		*after = i - 1;
1182 	}
1183 	return (TRUE);
1184 }
1185 
1186 static void
1187 swap_pager_unswapped_acct(vm_page_t m)
1188 {
1189 	KASSERT((m->object->flags & OBJ_SWAP) != 0,
1190 	    ("Free object not swappable"));
1191 	if ((m->a.flags & PGA_SWAP_FREE) != 0)
1192 		counter_u64_add(swap_free_completed, 1);
1193 	vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
1194 
1195 	/*
1196 	 * The meta data only exists if the object is OBJT_SWAP
1197 	 * and even then might not be allocated yet.
1198 	 */
1199 }
1200 
1201 /*
1202  * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1203  *
1204  *	This removes any associated swap backing store, whether valid or
1205  *	not, from the page.
1206  *
1207  *	This routine is typically called when a page is made dirty, at
1208  *	which point any associated swap can be freed.  MADV_FREE also
1209  *	calls us in a special-case situation
1210  *
1211  *	NOTE!!!  If the page is clean and the swap was valid, the caller
1212  *	should make the page dirty before calling this routine.  This routine
1213  *	does NOT change the m->dirty status of the page.  Also: MADV_FREE
1214  *	depends on it.
1215  *
1216  *	This routine may not sleep.
1217  *
1218  *	The object containing the page may be locked.
1219  */
1220 static void
1221 swap_pager_unswapped(vm_page_t m)
1222 {
1223 	struct page_range range;
1224 	struct swblk *sb;
1225 	vm_object_t obj;
1226 
1227 	/*
1228 	 * Handle enqueing deferred frees first.  If we do not have the
1229 	 * object lock we wait for the page daemon to clear the space.
1230 	 */
1231 	obj = m->object;
1232 	if (!VM_OBJECT_WOWNED(obj)) {
1233 		VM_PAGE_OBJECT_BUSY_ASSERT(m);
1234 		/*
1235 		 * The caller is responsible for synchronization but we
1236 		 * will harmlessly handle races.  This is typically provided
1237 		 * by only calling unswapped() when a page transitions from
1238 		 * clean to dirty.
1239 		 */
1240 		if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1241 		    PGA_SWAP_SPACE) {
1242 			vm_page_aflag_set(m, PGA_SWAP_FREE);
1243 			counter_u64_add(swap_free_deferred, 1);
1244 		}
1245 		return;
1246 	}
1247 	swap_pager_unswapped_acct(m);
1248 
1249 	sb = SWAP_PCTRIE_LOOKUP(&m->object->un_pager.swp.swp_blks,
1250 	    rounddown(m->pindex, SWAP_META_PAGES));
1251 	if (sb == NULL)
1252 		return;
1253 	range.start = sb->d[m->pindex % SWAP_META_PAGES];
1254 	if (range.start == SWAPBLK_NONE)
1255 		return;
1256 	range.num = 1;
1257 	swp_pager_freeswapspace(&range);
1258 	sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
1259 	swp_pager_free_empty_swblk(m->object, sb);
1260 }
1261 
1262 /*
1263  * swap_pager_getpages() - bring pages in from swap
1264  *
1265  *	Attempt to page in the pages in array "ma" of length "count".  The
1266  *	caller may optionally specify that additional pages preceding and
1267  *	succeeding the specified range be paged in.  The number of such pages
1268  *	is returned in the "rbehind" and "rahead" parameters, and they will
1269  *	be in the inactive queue upon return.
1270  *
1271  *	The pages in "ma" must be busied and will remain busied upon return.
1272  */
1273 static int
1274 swap_pager_getpages_locked(vm_object_t object, vm_page_t *ma, int count,
1275     int *rbehind, int *rahead)
1276 {
1277 	struct buf *bp;
1278 	vm_page_t bm, mpred, msucc, p;
1279 	vm_pindex_t pindex;
1280 	daddr_t blk;
1281 	int i, maxahead, maxbehind, reqcount;
1282 
1283 	VM_OBJECT_ASSERT_WLOCKED(object);
1284 	reqcount = count;
1285 
1286 	KASSERT((object->flags & OBJ_SWAP) != 0,
1287 	    ("%s: object not swappable", __func__));
1288 	if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead)) {
1289 		VM_OBJECT_WUNLOCK(object);
1290 		return (VM_PAGER_FAIL);
1291 	}
1292 
1293 	KASSERT(reqcount - 1 <= maxahead,
1294 	    ("page count %d extends beyond swap block", reqcount));
1295 
1296 	/*
1297 	 * Do not transfer any pages other than those that are xbusied
1298 	 * when running during a split or collapse operation.  This
1299 	 * prevents clustering from re-creating pages which are being
1300 	 * moved into another object.
1301 	 */
1302 	if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
1303 		maxahead = reqcount - 1;
1304 		maxbehind = 0;
1305 	}
1306 
1307 	/*
1308 	 * Clip the readahead and readbehind ranges to exclude resident pages.
1309 	 */
1310 	if (rahead != NULL) {
1311 		*rahead = imin(*rahead, maxahead - (reqcount - 1));
1312 		pindex = ma[reqcount - 1]->pindex;
1313 		msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1314 		if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1315 			*rahead = msucc->pindex - pindex - 1;
1316 	}
1317 	if (rbehind != NULL) {
1318 		*rbehind = imin(*rbehind, maxbehind);
1319 		pindex = ma[0]->pindex;
1320 		mpred = TAILQ_PREV(ma[0], pglist, listq);
1321 		if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1322 			*rbehind = pindex - mpred->pindex - 1;
1323 	}
1324 
1325 	bm = ma[0];
1326 	for (i = 0; i < count; i++)
1327 		ma[i]->oflags |= VPO_SWAPINPROG;
1328 
1329 	/*
1330 	 * Allocate readahead and readbehind pages.
1331 	 */
1332 	if (rbehind != NULL) {
1333 		for (i = 1; i <= *rbehind; i++) {
1334 			p = vm_page_alloc(object, ma[0]->pindex - i,
1335 			    VM_ALLOC_NORMAL);
1336 			if (p == NULL)
1337 				break;
1338 			p->oflags |= VPO_SWAPINPROG;
1339 			bm = p;
1340 		}
1341 		*rbehind = i - 1;
1342 	}
1343 	if (rahead != NULL) {
1344 		for (i = 0; i < *rahead; i++) {
1345 			p = vm_page_alloc(object,
1346 			    ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1347 			if (p == NULL)
1348 				break;
1349 			p->oflags |= VPO_SWAPINPROG;
1350 		}
1351 		*rahead = i;
1352 	}
1353 	if (rbehind != NULL)
1354 		count += *rbehind;
1355 	if (rahead != NULL)
1356 		count += *rahead;
1357 
1358 	vm_object_pip_add(object, count);
1359 
1360 	pindex = bm->pindex;
1361 	blk = swp_pager_meta_lookup(object, pindex);
1362 	KASSERT(blk != SWAPBLK_NONE,
1363 	    ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1364 
1365 	VM_OBJECT_WUNLOCK(object);
1366 	bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1367 	MPASS((bp->b_flags & B_MAXPHYS) != 0);
1368 	/* Pages cannot leave the object while busy. */
1369 	for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1370 		MPASS(p->pindex == bm->pindex + i);
1371 		bp->b_pages[i] = p;
1372 	}
1373 
1374 	bp->b_flags |= B_PAGING;
1375 	bp->b_iocmd = BIO_READ;
1376 	bp->b_iodone = swp_pager_async_iodone;
1377 	bp->b_rcred = crhold(thread0.td_ucred);
1378 	bp->b_wcred = crhold(thread0.td_ucred);
1379 	bp->b_blkno = blk;
1380 	bp->b_bcount = PAGE_SIZE * count;
1381 	bp->b_bufsize = PAGE_SIZE * count;
1382 	bp->b_npages = count;
1383 	bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1384 	bp->b_pgafter = rahead != NULL ? *rahead : 0;
1385 
1386 	VM_CNT_INC(v_swapin);
1387 	VM_CNT_ADD(v_swappgsin, count);
1388 
1389 	/*
1390 	 * perform the I/O.  NOTE!!!  bp cannot be considered valid after
1391 	 * this point because we automatically release it on completion.
1392 	 * Instead, we look at the one page we are interested in which we
1393 	 * still hold a lock on even through the I/O completion.
1394 	 *
1395 	 * The other pages in our ma[] array are also released on completion,
1396 	 * so we cannot assume they are valid anymore either.
1397 	 *
1398 	 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1399 	 */
1400 	BUF_KERNPROC(bp);
1401 	swp_pager_strategy(bp);
1402 
1403 	/*
1404 	 * Wait for the pages we want to complete.  VPO_SWAPINPROG is always
1405 	 * cleared on completion.  If an I/O error occurs, SWAPBLK_NONE
1406 	 * is set in the metadata for each page in the request.
1407 	 */
1408 	VM_OBJECT_WLOCK(object);
1409 	/* This could be implemented more efficiently with aflags */
1410 	while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
1411 		ma[0]->oflags |= VPO_SWAPSLEEP;
1412 		VM_CNT_INC(v_intrans);
1413 		if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1414 		    "swread", hz * 20)) {
1415 			printf(
1416 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1417 			    bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1418 		}
1419 	}
1420 	VM_OBJECT_WUNLOCK(object);
1421 
1422 	/*
1423 	 * If we had an unrecoverable read error pages will not be valid.
1424 	 */
1425 	for (i = 0; i < reqcount; i++)
1426 		if (ma[i]->valid != VM_PAGE_BITS_ALL)
1427 			return (VM_PAGER_ERROR);
1428 
1429 	return (VM_PAGER_OK);
1430 
1431 	/*
1432 	 * A final note: in a low swap situation, we cannot deallocate swap
1433 	 * and mark a page dirty here because the caller is likely to mark
1434 	 * the page clean when we return, causing the page to possibly revert
1435 	 * to all-zero's later.
1436 	 */
1437 }
1438 
1439 static int
1440 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count,
1441     int *rbehind, int *rahead)
1442 {
1443 
1444 	VM_OBJECT_WLOCK(object);
1445 	return (swap_pager_getpages_locked(object, ma, count, rbehind, rahead));
1446 }
1447 
1448 /*
1449  * 	swap_pager_getpages_async():
1450  *
1451  *	Right now this is emulation of asynchronous operation on top of
1452  *	swap_pager_getpages().
1453  */
1454 static int
1455 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1456     int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1457 {
1458 	int r, error;
1459 
1460 	r = swap_pager_getpages(object, ma, count, rbehind, rahead);
1461 	switch (r) {
1462 	case VM_PAGER_OK:
1463 		error = 0;
1464 		break;
1465 	case VM_PAGER_ERROR:
1466 		error = EIO;
1467 		break;
1468 	case VM_PAGER_FAIL:
1469 		error = EINVAL;
1470 		break;
1471 	default:
1472 		panic("unhandled swap_pager_getpages() error %d", r);
1473 	}
1474 	(iodone)(arg, ma, count, error);
1475 
1476 	return (r);
1477 }
1478 
1479 /*
1480  *	swap_pager_putpages:
1481  *
1482  *	Assign swap (if necessary) and initiate I/O on the specified pages.
1483  *
1484  *	In a low memory situation we may block in VOP_STRATEGY(), but the new
1485  *	vm_page reservation system coupled with properly written VFS devices
1486  *	should ensure that no low-memory deadlock occurs.  This is an area
1487  *	which needs work.
1488  *
1489  *	The parent has N vm_object_pip_add() references prior to
1490  *	calling us and will remove references for rtvals[] that are
1491  *	not set to VM_PAGER_PEND.  We need to remove the rest on I/O
1492  *	completion.
1493  *
1494  *	The parent has soft-busy'd the pages it passes us and will unbusy
1495  *	those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
1496  *	We need to unbusy the rest on I/O completion.
1497  */
1498 static void
1499 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1500     int flags, int *rtvals)
1501 {
1502 	struct page_range range;
1503 	struct buf *bp;
1504 	daddr_t addr, blk;
1505 	vm_page_t mreq;
1506 	int i, j, n;
1507 	bool async;
1508 
1509 	KASSERT(count == 0 || ma[0]->object == object,
1510 	    ("%s: object mismatch %p/%p",
1511 	    __func__, object, ma[0]->object));
1512 
1513 	VM_OBJECT_WUNLOCK(object);
1514 	async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
1515 	swp_pager_init_freerange(&range);
1516 
1517 	/*
1518 	 * Assign swap blocks and issue I/O.  We reallocate swap on the fly.
1519 	 * The page is left dirty until the pageout operation completes
1520 	 * successfully.
1521 	 */
1522 	for (i = 0; i < count; i += n) {
1523 		/* Maximum I/O size is limited by maximum swap block size. */
1524 		n = min(count - i, nsw_cluster_max);
1525 
1526 		if (async) {
1527 			mtx_lock(&swbuf_mtx);
1528 			while (nsw_wcount_async == 0)
1529 				msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1530 				    "swbufa", 0);
1531 			nsw_wcount_async--;
1532 			mtx_unlock(&swbuf_mtx);
1533 		}
1534 
1535 		/* Get a block of swap of size up to size n. */
1536 		blk = swp_pager_getswapspace(&n);
1537 		if (blk == SWAPBLK_NONE) {
1538 			mtx_lock(&swbuf_mtx);
1539 			if (++nsw_wcount_async == 1)
1540 				wakeup(&nsw_wcount_async);
1541 			mtx_unlock(&swbuf_mtx);
1542 			for (j = 0; j < n; ++j)
1543 				rtvals[i + j] = VM_PAGER_FAIL;
1544 			continue;
1545 		}
1546 		VM_OBJECT_WLOCK(object);
1547 		for (j = 0; j < n; ++j) {
1548 			mreq = ma[i + j];
1549 			vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1550 			addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1551 			    blk + j);
1552 			if (addr != SWAPBLK_NONE)
1553 				swp_pager_update_freerange(&range, addr);
1554 			MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1555 			mreq->oflags |= VPO_SWAPINPROG;
1556 		}
1557 		VM_OBJECT_WUNLOCK(object);
1558 
1559 		bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1560 		MPASS((bp->b_flags & B_MAXPHYS) != 0);
1561 		if (async)
1562 			bp->b_flags |= B_ASYNC;
1563 		bp->b_flags |= B_PAGING;
1564 		bp->b_iocmd = BIO_WRITE;
1565 
1566 		bp->b_rcred = crhold(thread0.td_ucred);
1567 		bp->b_wcred = crhold(thread0.td_ucred);
1568 		bp->b_bcount = PAGE_SIZE * n;
1569 		bp->b_bufsize = PAGE_SIZE * n;
1570 		bp->b_blkno = blk;
1571 		for (j = 0; j < n; j++)
1572 			bp->b_pages[j] = ma[i + j];
1573 		bp->b_npages = n;
1574 
1575 		/*
1576 		 * Must set dirty range for NFS to work.
1577 		 */
1578 		bp->b_dirtyoff = 0;
1579 		bp->b_dirtyend = bp->b_bcount;
1580 
1581 		VM_CNT_INC(v_swapout);
1582 		VM_CNT_ADD(v_swappgsout, bp->b_npages);
1583 
1584 		/*
1585 		 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1586 		 * can call the async completion routine at the end of a
1587 		 * synchronous I/O operation.  Otherwise, our caller would
1588 		 * perform duplicate unbusy and wakeup operations on the page
1589 		 * and object, respectively.
1590 		 */
1591 		for (j = 0; j < n; j++)
1592 			rtvals[i + j] = VM_PAGER_PEND;
1593 
1594 		/*
1595 		 * asynchronous
1596 		 *
1597 		 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1598 		 */
1599 		if (async) {
1600 			bp->b_iodone = swp_pager_async_iodone;
1601 			BUF_KERNPROC(bp);
1602 			swp_pager_strategy(bp);
1603 			continue;
1604 		}
1605 
1606 		/*
1607 		 * synchronous
1608 		 *
1609 		 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1610 		 */
1611 		bp->b_iodone = bdone;
1612 		swp_pager_strategy(bp);
1613 
1614 		/*
1615 		 * Wait for the sync I/O to complete.
1616 		 */
1617 		bwait(bp, PVM, "swwrt");
1618 
1619 		/*
1620 		 * Now that we are through with the bp, we can call the
1621 		 * normal async completion, which frees everything up.
1622 		 */
1623 		swp_pager_async_iodone(bp);
1624 	}
1625 	swp_pager_freeswapspace(&range);
1626 	VM_OBJECT_WLOCK(object);
1627 }
1628 
1629 /*
1630  *	swp_pager_async_iodone:
1631  *
1632  *	Completion routine for asynchronous reads and writes from/to swap.
1633  *	Also called manually by synchronous code to finish up a bp.
1634  *
1635  *	This routine may not sleep.
1636  */
1637 static void
1638 swp_pager_async_iodone(struct buf *bp)
1639 {
1640 	int i;
1641 	vm_object_t object = NULL;
1642 
1643 	/*
1644 	 * Report error - unless we ran out of memory, in which case
1645 	 * we've already logged it in swapgeom_strategy().
1646 	 */
1647 	if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
1648 		printf(
1649 		    "swap_pager: I/O error - %s failed; blkno %ld,"
1650 			"size %ld, error %d\n",
1651 		    ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1652 		    (long)bp->b_blkno,
1653 		    (long)bp->b_bcount,
1654 		    bp->b_error
1655 		);
1656 	}
1657 
1658 	/*
1659 	 * remove the mapping for kernel virtual
1660 	 */
1661 	if (buf_mapped(bp))
1662 		pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1663 	else
1664 		bp->b_data = bp->b_kvabase;
1665 
1666 	if (bp->b_npages) {
1667 		object = bp->b_pages[0]->object;
1668 		VM_OBJECT_WLOCK(object);
1669 	}
1670 
1671 	/*
1672 	 * cleanup pages.  If an error occurs writing to swap, we are in
1673 	 * very serious trouble.  If it happens to be a disk error, though,
1674 	 * we may be able to recover by reassigning the swap later on.  So
1675 	 * in this case we remove the m->swapblk assignment for the page
1676 	 * but do not free it in the rlist.  The errornous block(s) are thus
1677 	 * never reallocated as swap.  Redirty the page and continue.
1678 	 */
1679 	for (i = 0; i < bp->b_npages; ++i) {
1680 		vm_page_t m = bp->b_pages[i];
1681 
1682 		m->oflags &= ~VPO_SWAPINPROG;
1683 		if (m->oflags & VPO_SWAPSLEEP) {
1684 			m->oflags &= ~VPO_SWAPSLEEP;
1685 			wakeup(&object->handle);
1686 		}
1687 
1688 		/* We always have space after I/O, successful or not. */
1689 		vm_page_aflag_set(m, PGA_SWAP_SPACE);
1690 
1691 		if (bp->b_ioflags & BIO_ERROR) {
1692 			/*
1693 			 * If an error occurs I'd love to throw the swapblk
1694 			 * away without freeing it back to swapspace, so it
1695 			 * can never be used again.  But I can't from an
1696 			 * interrupt.
1697 			 */
1698 			if (bp->b_iocmd == BIO_READ) {
1699 				/*
1700 				 * NOTE: for reads, m->dirty will probably
1701 				 * be overridden by the original caller of
1702 				 * getpages so don't play cute tricks here.
1703 				 */
1704 				vm_page_invalid(m);
1705 				if (i < bp->b_pgbefore ||
1706 				    i >= bp->b_npages - bp->b_pgafter)
1707 					vm_page_free_invalid(m);
1708 			} else {
1709 				/*
1710 				 * If a write error occurs, reactivate page
1711 				 * so it doesn't clog the inactive list,
1712 				 * then finish the I/O.
1713 				 */
1714 				MPASS(m->dirty == VM_PAGE_BITS_ALL);
1715 
1716 				/* PQ_UNSWAPPABLE? */
1717 				vm_page_activate(m);
1718 				vm_page_sunbusy(m);
1719 			}
1720 		} else if (bp->b_iocmd == BIO_READ) {
1721 			/*
1722 			 * NOTE: for reads, m->dirty will probably be
1723 			 * overridden by the original caller of getpages so
1724 			 * we cannot set them in order to free the underlying
1725 			 * swap in a low-swap situation.  I don't think we'd
1726 			 * want to do that anyway, but it was an optimization
1727 			 * that existed in the old swapper for a time before
1728 			 * it got ripped out due to precisely this problem.
1729 			 */
1730 			KASSERT(!pmap_page_is_mapped(m),
1731 			    ("swp_pager_async_iodone: page %p is mapped", m));
1732 			KASSERT(m->dirty == 0,
1733 			    ("swp_pager_async_iodone: page %p is dirty", m));
1734 
1735 			vm_page_valid(m);
1736 			if (i < bp->b_pgbefore ||
1737 			    i >= bp->b_npages - bp->b_pgafter)
1738 				vm_page_readahead_finish(m);
1739 		} else {
1740 			/*
1741 			 * For write success, clear the dirty
1742 			 * status, then finish the I/O ( which decrements the
1743 			 * busy count and possibly wakes waiter's up ).
1744 			 * A page is only written to swap after a period of
1745 			 * inactivity.  Therefore, we do not expect it to be
1746 			 * reused.
1747 			 */
1748 			KASSERT(!pmap_page_is_write_mapped(m),
1749 			    ("swp_pager_async_iodone: page %p is not write"
1750 			    " protected", m));
1751 			vm_page_undirty(m);
1752 			vm_page_deactivate_noreuse(m);
1753 			vm_page_sunbusy(m);
1754 		}
1755 	}
1756 
1757 	/*
1758 	 * adjust pip.  NOTE: the original parent may still have its own
1759 	 * pip refs on the object.
1760 	 */
1761 	if (object != NULL) {
1762 		vm_object_pip_wakeupn(object, bp->b_npages);
1763 		VM_OBJECT_WUNLOCK(object);
1764 	}
1765 
1766 	/*
1767 	 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1768 	 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1769 	 * trigger a KASSERT in relpbuf().
1770 	 */
1771 	if (bp->b_vp) {
1772 		    bp->b_vp = NULL;
1773 		    bp->b_bufobj = NULL;
1774 	}
1775 	/*
1776 	 * release the physical I/O buffer
1777 	 */
1778 	if (bp->b_flags & B_ASYNC) {
1779 		mtx_lock(&swbuf_mtx);
1780 		if (++nsw_wcount_async == 1)
1781 			wakeup(&nsw_wcount_async);
1782 		mtx_unlock(&swbuf_mtx);
1783 	}
1784 	uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
1785 }
1786 
1787 int
1788 swap_pager_nswapdev(void)
1789 {
1790 
1791 	return (nswapdev);
1792 }
1793 
1794 static void
1795 swp_pager_force_dirty(struct page_range *range, vm_page_t m, daddr_t *blk)
1796 {
1797 	vm_page_dirty(m);
1798 	swap_pager_unswapped_acct(m);
1799 	swp_pager_update_freerange(range, *blk);
1800 	*blk = SWAPBLK_NONE;
1801 	vm_page_launder(m);
1802 }
1803 
1804 u_long
1805 swap_pager_swapped_pages(vm_object_t object)
1806 {
1807 	struct swblk *sb;
1808 	vm_pindex_t pi;
1809 	u_long res;
1810 	int i;
1811 
1812 	VM_OBJECT_ASSERT_LOCKED(object);
1813 
1814 	if (pctrie_is_empty(&object->un_pager.swp.swp_blks))
1815 		return (0);
1816 
1817 	for (res = 0, pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1818 	    &object->un_pager.swp.swp_blks, pi)) != NULL;
1819 	    pi = sb->p + SWAP_META_PAGES) {
1820 		for (i = 0; i < SWAP_META_PAGES; i++) {
1821 			if (sb->d[i] != SWAPBLK_NONE)
1822 				res++;
1823 		}
1824 	}
1825 	return (res);
1826 }
1827 
1828 /*
1829  *	swap_pager_swapoff_object:
1830  *
1831  *	Page in all of the pages that have been paged out for an object
1832  *	to a swap device.
1833  */
1834 static void
1835 swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
1836 {
1837 	struct page_range range;
1838 	struct swblk *sb;
1839 	vm_page_t m;
1840 	vm_pindex_t pi;
1841 	daddr_t blk;
1842 	int i, rahead, rv;
1843 	bool sb_empty;
1844 
1845 	VM_OBJECT_ASSERT_WLOCKED(object);
1846 	KASSERT((object->flags & OBJ_SWAP) != 0,
1847 	    ("%s: Object not swappable", __func__));
1848 
1849 	pi = 0;
1850 	i = 0;
1851 	swp_pager_init_freerange(&range);
1852 	for (;;) {
1853 		if (i == 0 && (object->flags & OBJ_DEAD) != 0) {
1854 			/*
1855 			 * Make sure that pending writes finish before
1856 			 * returning.
1857 			 */
1858 			vm_object_pip_wait(object, "swpoff");
1859 			swp_pager_meta_free_all(object);
1860 			break;
1861 		}
1862 
1863 		if (i == SWAP_META_PAGES) {
1864 			pi = sb->p + SWAP_META_PAGES;
1865 			if (sb_empty) {
1866 				SWAP_PCTRIE_REMOVE(
1867 				    &object->un_pager.swp.swp_blks, sb->p);
1868 				uma_zfree(swblk_zone, sb);
1869 			}
1870 			i = 0;
1871 		}
1872 
1873 		if (i == 0) {
1874 			sb = SWAP_PCTRIE_LOOKUP_GE(
1875 			    &object->un_pager.swp.swp_blks, pi);
1876 			if (sb == NULL)
1877 				break;
1878 			sb_empty = true;
1879 			m = NULL;
1880 		}
1881 
1882 		/* Skip an invalid block. */
1883 		blk = sb->d[i];
1884 		if (blk == SWAPBLK_NONE || !swp_pager_isondev(blk, sp)) {
1885 			if (blk != SWAPBLK_NONE)
1886 				sb_empty = false;
1887 			m = NULL;
1888 			i++;
1889 			continue;
1890 		}
1891 
1892 		/*
1893 		 * Look for a page corresponding to this block, If the found
1894 		 * page has pending operations, sleep and restart the scan.
1895 		 */
1896 		m = m != NULL ? vm_page_next(m) :
1897 		    vm_page_lookup(object, sb->p + i);
1898 		if (m != NULL && (m->oflags & VPO_SWAPINPROG) != 0) {
1899 			m->oflags |= VPO_SWAPSLEEP;
1900 			VM_OBJECT_SLEEP(object, &object->handle, PSWP, "swpoff",
1901 			    0);
1902 			i = 0;	/* Restart scan after object lock dropped. */
1903 			continue;
1904 		}
1905 
1906 		/*
1907 		 * If the found page is valid, mark it dirty and free the swap
1908 		 * block.
1909 		 */
1910 		if (m != NULL && vm_page_all_valid(m)) {
1911 			swp_pager_force_dirty(&range, m, &sb->d[i]);
1912 			i++;
1913 			continue;
1914 		}
1915 
1916 		/* Is there a page we can acquire or allocate? */
1917 		if (m == NULL) {
1918 			m = vm_page_alloc(object, sb->p + i,
1919 			    VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
1920 		} else if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL))
1921 			m = NULL;
1922 
1923 		/* If no page available, repeat this iteration. */
1924 		if (m == NULL)
1925 			continue;
1926 
1927 		/* Get the page from swap, mark it dirty, restart the scan. */
1928 		vm_object_pip_add(object, 1);
1929 		rahead = SWAP_META_PAGES;
1930 		rv = swap_pager_getpages_locked(object, &m, 1, NULL, &rahead);
1931 		if (rv != VM_PAGER_OK)
1932 			panic("%s: read from swap failed: %d", __func__, rv);
1933 		VM_OBJECT_WLOCK(object);
1934 		vm_object_pip_wakeupn(object, 1);
1935 		KASSERT(vm_page_all_valid(m),
1936 		    ("%s: Page %p not all valid", __func__, m));
1937 		swp_pager_force_dirty(&range, m, &sb->d[i]);
1938 		vm_page_xunbusy(m);
1939 		i = 0;	/* Restart scan after object lock dropped. */
1940 	}
1941 	swp_pager_freeswapspace(&range);
1942 }
1943 
1944 /*
1945  *	swap_pager_swapoff:
1946  *
1947  *	Page in all of the pages that have been paged out to the
1948  *	given device.  The corresponding blocks in the bitmap must be
1949  *	marked as allocated and the device must be flagged SW_CLOSING.
1950  *	There may be no processes swapped out to the device.
1951  *
1952  *	This routine may block.
1953  */
1954 static void
1955 swap_pager_swapoff(struct swdevt *sp)
1956 {
1957 	vm_object_t object;
1958 	int retries;
1959 
1960 	sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1961 
1962 	retries = 0;
1963 full_rescan:
1964 	mtx_lock(&vm_object_list_mtx);
1965 	TAILQ_FOREACH(object, &vm_object_list, object_list) {
1966 		if ((object->flags & OBJ_SWAP) == 0)
1967 			continue;
1968 		mtx_unlock(&vm_object_list_mtx);
1969 		/* Depends on type-stability. */
1970 		VM_OBJECT_WLOCK(object);
1971 
1972 		/*
1973 		 * Dead objects are eventually terminated on their own.
1974 		 */
1975 		if ((object->flags & OBJ_DEAD) != 0)
1976 			goto next_obj;
1977 
1978 		/*
1979 		 * Sync with fences placed after pctrie
1980 		 * initialization.  We must not access pctrie below
1981 		 * unless we checked that our object is swap and not
1982 		 * dead.
1983 		 */
1984 		atomic_thread_fence_acq();
1985 		if ((object->flags & OBJ_SWAP) == 0)
1986 			goto next_obj;
1987 
1988 		swap_pager_swapoff_object(sp, object);
1989 next_obj:
1990 		VM_OBJECT_WUNLOCK(object);
1991 		mtx_lock(&vm_object_list_mtx);
1992 	}
1993 	mtx_unlock(&vm_object_list_mtx);
1994 
1995 	if (sp->sw_used) {
1996 		/*
1997 		 * Objects may be locked or paging to the device being
1998 		 * removed, so we will miss their pages and need to
1999 		 * make another pass.  We have marked this device as
2000 		 * SW_CLOSING, so the activity should finish soon.
2001 		 */
2002 		retries++;
2003 		if (retries > 100) {
2004 			panic("swapoff: failed to locate %d swap blocks",
2005 			    sp->sw_used);
2006 		}
2007 		pause("swpoff", hz / 20);
2008 		goto full_rescan;
2009 	}
2010 	EVENTHANDLER_INVOKE(swapoff, sp);
2011 }
2012 
2013 /************************************************************************
2014  *				SWAP META DATA 				*
2015  ************************************************************************
2016  *
2017  *	These routines manipulate the swap metadata stored in the
2018  *	OBJT_SWAP object.
2019  *
2020  *	Swap metadata is implemented with a global hash and not directly
2021  *	linked into the object.  Instead the object simply contains
2022  *	appropriate tracking counters.
2023  */
2024 
2025 /*
2026  * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
2027  */
2028 static bool
2029 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
2030 {
2031 	int i;
2032 
2033 	MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
2034 	for (i = start; i < limit; i++) {
2035 		if (sb->d[i] != SWAPBLK_NONE)
2036 			return (false);
2037 	}
2038 	return (true);
2039 }
2040 
2041 /*
2042  * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
2043  *
2044  *  Nothing is done if the block is still in use.
2045  */
2046 static void
2047 swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
2048 {
2049 
2050 	if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
2051 		SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2052 		uma_zfree(swblk_zone, sb);
2053 	}
2054 }
2055 
2056 /*
2057  * SWP_PAGER_META_BUILD() -	add swap block to swap meta data for object
2058  *
2059  *	The specified swapblk is added to the object's swap metadata.  If
2060  *	the swapblk is not valid, it is freed instead.  Any previously
2061  *	assigned swapblk is returned.
2062  */
2063 static daddr_t
2064 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
2065 {
2066 	static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
2067 	struct swblk *sb, *sb1;
2068 	vm_pindex_t modpi, rdpi;
2069 	daddr_t prev_swapblk;
2070 	int error, i;
2071 
2072 	VM_OBJECT_ASSERT_WLOCKED(object);
2073 
2074 	rdpi = rounddown(pindex, SWAP_META_PAGES);
2075 	sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
2076 	if (sb == NULL) {
2077 		if (swapblk == SWAPBLK_NONE)
2078 			return (SWAPBLK_NONE);
2079 		for (;;) {
2080 			sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
2081 			    pageproc ? M_USE_RESERVE : 0));
2082 			if (sb != NULL) {
2083 				sb->p = rdpi;
2084 				for (i = 0; i < SWAP_META_PAGES; i++)
2085 					sb->d[i] = SWAPBLK_NONE;
2086 				if (atomic_cmpset_int(&swblk_zone_exhausted,
2087 				    1, 0))
2088 					printf("swblk zone ok\n");
2089 				break;
2090 			}
2091 			VM_OBJECT_WUNLOCK(object);
2092 			if (uma_zone_exhausted(swblk_zone)) {
2093 				if (atomic_cmpset_int(&swblk_zone_exhausted,
2094 				    0, 1))
2095 					printf("swap blk zone exhausted, "
2096 					    "increase kern.maxswzone\n");
2097 				vm_pageout_oom(VM_OOM_SWAPZ);
2098 				pause("swzonxb", 10);
2099 			} else
2100 				uma_zwait(swblk_zone);
2101 			VM_OBJECT_WLOCK(object);
2102 			sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2103 			    rdpi);
2104 			if (sb != NULL)
2105 				/*
2106 				 * Somebody swapped out a nearby page,
2107 				 * allocating swblk at the rdpi index,
2108 				 * while we dropped the object lock.
2109 				 */
2110 				goto allocated;
2111 		}
2112 		for (;;) {
2113 			error = SWAP_PCTRIE_INSERT(
2114 			    &object->un_pager.swp.swp_blks, sb);
2115 			if (error == 0) {
2116 				if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2117 				    1, 0))
2118 					printf("swpctrie zone ok\n");
2119 				break;
2120 			}
2121 			VM_OBJECT_WUNLOCK(object);
2122 			if (uma_zone_exhausted(swpctrie_zone)) {
2123 				if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2124 				    0, 1))
2125 					printf("swap pctrie zone exhausted, "
2126 					    "increase kern.maxswzone\n");
2127 				vm_pageout_oom(VM_OOM_SWAPZ);
2128 				pause("swzonxp", 10);
2129 			} else
2130 				uma_zwait(swpctrie_zone);
2131 			VM_OBJECT_WLOCK(object);
2132 			sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2133 			    rdpi);
2134 			if (sb1 != NULL) {
2135 				uma_zfree(swblk_zone, sb);
2136 				sb = sb1;
2137 				goto allocated;
2138 			}
2139 		}
2140 	}
2141 allocated:
2142 	MPASS(sb->p == rdpi);
2143 
2144 	modpi = pindex % SWAP_META_PAGES;
2145 	/* Return prior contents of metadata. */
2146 	prev_swapblk = sb->d[modpi];
2147 	/* Enter block into metadata. */
2148 	sb->d[modpi] = swapblk;
2149 
2150 	/*
2151 	 * Free the swblk if we end up with the empty page run.
2152 	 */
2153 	if (swapblk == SWAPBLK_NONE)
2154 		swp_pager_free_empty_swblk(object, sb);
2155 	return (prev_swapblk);
2156 }
2157 
2158 /*
2159  * SWP_PAGER_META_TRANSFER() - free a range of blocks in the srcobject's swap
2160  * metadata, or transfer it into dstobject.
2161  *
2162  *	This routine will free swap metadata structures as they are cleaned
2163  *	out.
2164  */
2165 static void
2166 swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
2167     vm_pindex_t pindex, vm_pindex_t count, vm_size_t *moved)
2168 {
2169 	struct page_range range;
2170 	struct swblk *sb;
2171 	vm_page_t m;
2172 	vm_pindex_t offset, last;
2173 	vm_size_t mc;
2174 	int i, limit, start;
2175 
2176 	VM_OBJECT_ASSERT_WLOCKED(srcobject);
2177 	MPASS(moved == NULL || dstobject == NULL);
2178 
2179 	mc = 0;
2180 	m = NULL;
2181 	if (count == 0 || pctrie_is_empty(&srcobject->un_pager.swp.swp_blks))
2182 		goto out;
2183 
2184 	swp_pager_init_freerange(&range);
2185 	offset = pindex;
2186 	last = pindex + count;
2187 	for (;;) {
2188 		sb = SWAP_PCTRIE_LOOKUP_GE(&srcobject->un_pager.swp.swp_blks,
2189 		    rounddown(pindex, SWAP_META_PAGES));
2190 		if (sb == NULL || sb->p >= last)
2191 			break;
2192 		start = pindex > sb->p ? pindex - sb->p : 0;
2193 		limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2194 		    SWAP_META_PAGES;
2195 		for (i = start; i < limit; i++) {
2196 			if (sb->d[i] == SWAPBLK_NONE)
2197 				continue;
2198 			if (dstobject == NULL ||
2199 			    !swp_pager_xfer_source(srcobject, dstobject,
2200 			    sb->p + i - offset, sb->d[i])) {
2201 				swp_pager_update_freerange(&range, sb->d[i]);
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