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