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