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