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