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