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