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