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