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