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