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