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