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