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