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