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