xref: /freebsd/sys/vm/swap_pager.c (revision 00a3fe968b840ee197c32dfe4107dab730bd9915)
160727d8bSWarner Losh /*-
2df57947fSPedro F. Giffuni  * SPDX-License-Identifier: BSD-4-Clause
3df57947fSPedro F. Giffuni  *
41c7c3c6aSMatthew Dillon  * Copyright (c) 1998 Matthew Dillon,
526f9a767SRodney W. Grimes  * Copyright (c) 1994 John S. Dyson
6df8bae1dSRodney W. Grimes  * Copyright (c) 1990 University of Utah.
7e9c0cc15SPoul-Henning Kamp  * Copyright (c) 1982, 1986, 1989, 1993
8df8bae1dSRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
9df8bae1dSRodney W. Grimes  *
10df8bae1dSRodney W. Grimes  * This code is derived from software contributed to Berkeley by
11df8bae1dSRodney W. Grimes  * the Systems Programming Group of the University of Utah Computer
12df8bae1dSRodney W. Grimes  * Science Department.
13df8bae1dSRodney W. Grimes  *
14df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
15df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
16df8bae1dSRodney W. Grimes  * are met:
17df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
18df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
19df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
20df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
21df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
22df8bae1dSRodney W. Grimes  * 3. All advertising materials mentioning features or use of this software
235929bcfaSPhilippe Charnier  *    must display the following acknowledgement:
24df8bae1dSRodney W. Grimes  *	This product includes software developed by the University of
25df8bae1dSRodney W. Grimes  *	California, Berkeley and its contributors.
26df8bae1dSRodney W. Grimes  * 4. Neither the name of the University nor the names of its contributors
27df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
28df8bae1dSRodney W. Grimes  *    without specific prior written permission.
29df8bae1dSRodney W. Grimes  *
30df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
41df8bae1dSRodney W. Grimes  *
421c7c3c6aSMatthew Dillon  *				New Swap System
431c7c3c6aSMatthew Dillon  *				Matthew Dillon
441c7c3c6aSMatthew Dillon  *
451c7c3c6aSMatthew Dillon  * Radix Bitmap 'blists'.
461c7c3c6aSMatthew Dillon  *
471c7c3c6aSMatthew Dillon  *	- The new swapper uses the new radix bitmap code.  This should scale
481c7c3c6aSMatthew Dillon  *	  to arbitrarily small or arbitrarily large swap spaces and an almost
491c7c3c6aSMatthew Dillon  *	  arbitrary degree of fragmentation.
501c7c3c6aSMatthew Dillon  *
511c7c3c6aSMatthew Dillon  * Features:
521c7c3c6aSMatthew Dillon  *
531c7c3c6aSMatthew Dillon  *	- on the fly reallocation of swap during putpages.  The new system
541c7c3c6aSMatthew Dillon  *	  does not try to keep previously allocated swap blocks for dirty
551c7c3c6aSMatthew Dillon  *	  pages.
561c7c3c6aSMatthew Dillon  *
571c7c3c6aSMatthew Dillon  *	- on the fly deallocation of swap
581c7c3c6aSMatthew Dillon  *
591c7c3c6aSMatthew Dillon  *	- No more garbage collection required.  Unnecessarily allocated swap
601c7c3c6aSMatthew Dillon  *	  blocks only exist for dirty vm_page_t's now and these are already
611c7c3c6aSMatthew Dillon  *	  cycled (in a high-load system) by the pager.  We also do on-the-fly
621c7c3c6aSMatthew Dillon  *	  removal of invalidated swap blocks when a page is destroyed
631c7c3c6aSMatthew Dillon  *	  or renamed.
641c7c3c6aSMatthew Dillon  *
65df8bae1dSRodney W. Grimes  * from: Utah $Hdr: swap_pager.c 1.4 91/04/30$
66df8bae1dSRodney W. Grimes  *
67df8bae1dSRodney W. Grimes  *	@(#)swap_pager.c	8.9 (Berkeley) 3/21/94
68e9c0cc15SPoul-Henning Kamp  *	@(#)vm_swap.c	8.5 (Berkeley) 2/17/94
69df8bae1dSRodney W. Grimes  */
70df8bae1dSRodney W. Grimes 
71874651b1SDavid E. O'Brien #include <sys/cdefs.h>
72874651b1SDavid E. O'Brien __FBSDID("$FreeBSD$");
73874651b1SDavid E. O'Brien 
74e9c0cc15SPoul-Henning Kamp #include "opt_vm.h"
75e9c0cc15SPoul-Henning Kamp 
76df8bae1dSRodney W. Grimes #include <sys/param.h>
779626b608SPoul-Henning Kamp #include <sys/bio.h>
78e2e050c8SConrad Meyer #include <sys/blist.h>
79df8bae1dSRodney W. Grimes #include <sys/buf.h>
80e2e050c8SConrad Meyer #include <sys/conf.h>
81e9c0cc15SPoul-Henning Kamp #include <sys/disk.h>
82504f5e29SDoug Moore #include <sys/disklabel.h>
83e2e050c8SConrad Meyer #include <sys/eventhandler.h>
84e9c0cc15SPoul-Henning Kamp #include <sys/fcntl.h>
85e2e050c8SConrad Meyer #include <sys/lock.h>
86e2e050c8SConrad Meyer #include <sys/kernel.h>
87e9c0cc15SPoul-Henning Kamp #include <sys/mount.h>
88e9c0cc15SPoul-Henning Kamp #include <sys/namei.h>
89df8bae1dSRodney W. Grimes #include <sys/malloc.h>
90f425ab8eSKonstantin Belousov #include <sys/pctrie.h>
91e2e050c8SConrad Meyer #include <sys/priv.h>
92e2e050c8SConrad Meyer #include <sys/proc.h>
931ba5ad42SEdward Tomasz Napierala #include <sys/racct.h>
943364c323SKonstantin Belousov #include <sys/resource.h>
953364c323SKonstantin Belousov #include <sys/resourcevar.h>
9689f6b863SAttilio Rao #include <sys/rwlock.h>
97d027ed2eSAlan Cox #include <sys/sbuf.h>
98327f4e83SMatthew Dillon #include <sys/sysctl.h>
99e9c0cc15SPoul-Henning Kamp #include <sys/sysproto.h>
100e2e050c8SConrad Meyer #include <sys/systm.h>
1010cddd8f0SMatthew Dillon #include <sys/sx.h>
102*00a3fe96SKonstantin Belousov #include <sys/user.h>
103936524aaSMatthew Dillon #include <sys/vmmeter.h>
104e2e050c8SConrad Meyer #include <sys/vnode.h>
105df8bae1dSRodney W. Grimes 
106aed55708SRobert Watson #include <security/mac/mac_framework.h>
107aed55708SRobert Watson 
108df8bae1dSRodney W. Grimes #include <vm/vm.h>
10921cd6e62SSeigo Tanimura #include <vm/pmap.h>
11021cd6e62SSeigo Tanimura #include <vm/vm_map.h>
11121cd6e62SSeigo Tanimura #include <vm/vm_kern.h>
112efeaf95aSDavid Greenman #include <vm/vm_object.h>
113df8bae1dSRodney W. Grimes #include <vm/vm_page.h>
114efeaf95aSDavid Greenman #include <vm/vm_pager.h>
115df8bae1dSRodney W. Grimes #include <vm/vm_pageout.h>
116e9c0cc15SPoul-Henning Kamp #include <vm/vm_param.h>
117df8bae1dSRodney W. Grimes #include <vm/swap_pager.h>
118efeaf95aSDavid Greenman #include <vm/vm_extern.h>
119670d17b5SJeff Roberson #include <vm/uma.h>
120df8bae1dSRodney W. Grimes 
121dee34ca4SPoul-Henning Kamp #include <geom/geom.h>
122dee34ca4SPoul-Henning Kamp 
123ec38b344SPoul-Henning Kamp /*
124064650c1SAlan Cox  * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64.
125064650c1SAlan Cox  * The 64-page limit is due to the radix code (kern/subr_blist.c).
126ec38b344SPoul-Henning Kamp  */
127ec38b344SPoul-Henning Kamp #ifndef MAX_PAGEOUT_CLUSTER
128e2241590SAlan Cox #define	MAX_PAGEOUT_CLUSTER	32
129ec38b344SPoul-Henning Kamp #endif
130ec38b344SPoul-Henning Kamp 
131ec38b344SPoul-Henning Kamp #if !defined(SWB_NPAGES)
132ec38b344SPoul-Henning Kamp #define SWB_NPAGES	MAX_PAGEOUT_CLUSTER
133ec38b344SPoul-Henning Kamp #endif
134ec38b344SPoul-Henning Kamp 
135f425ab8eSKonstantin Belousov #define	SWAP_META_PAGES		PCTRIE_COUNT
136ec38b344SPoul-Henning Kamp 
137f425ab8eSKonstantin Belousov /*
138f425ab8eSKonstantin Belousov  * A swblk structure maps each page index within a
139f425ab8eSKonstantin Belousov  * SWAP_META_PAGES-aligned and sized range to the address of an
140f425ab8eSKonstantin Belousov  * on-disk swap block (or SWAPBLK_NONE). The collection of these
141f425ab8eSKonstantin Belousov  * mappings for an entire vm object is implemented as a pc-trie.
142f425ab8eSKonstantin Belousov  */
143f425ab8eSKonstantin Belousov struct swblk {
144f425ab8eSKonstantin Belousov 	vm_pindex_t	p;
145f425ab8eSKonstantin Belousov 	daddr_t		d[SWAP_META_PAGES];
146e9c0cc15SPoul-Henning Kamp };
147e9c0cc15SPoul-Henning Kamp 
1482c4992dbSAlan Cox static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data");
14920da9c2eSPoul-Henning Kamp static struct mtx sw_dev_mtx;
1508f60c087SPoul-Henning Kamp static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
1518f60c087SPoul-Henning Kamp static struct swdevt *swdevhd;	/* Allocate from here next */
1528f60c087SPoul-Henning Kamp static int nswapdev;		/* Number of swap devices */
1538f60c087SPoul-Henning Kamp int swap_pager_avail;
15404533e1eSKonstantin Belousov static struct sx swdev_syscall_lock;	/* serialize swap(on|off) */
155e9c0cc15SPoul-Henning Kamp 
156126a2470SMateusz Guzik static __exclusive_cache_line u_long swap_reserved;
157e8bb589dSMatt Macy static u_long swap_total;
158e8bb589dSMatt Macy static int sysctl_page_shift(SYSCTL_HANDLER_ARGS);
159a8081778SJeff Roberson 
1607029da5cSPawel Biernacki static SYSCTL_NODE(_vm_stats, OID_AUTO, swap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
1617029da5cSPawel Biernacki     "VM swap stats");
162a8081778SJeff Roberson 
163e8bb589dSMatt Macy SYSCTL_PROC(_vm, OID_AUTO, swap_reserved, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
164e8bb589dSMatt Macy     &swap_reserved, 0, sysctl_page_shift, "A",
1658a9c731fSIvan Voras     "Amount of swap storage needed to back all allocated anonymous memory.");
166e8bb589dSMatt Macy SYSCTL_PROC(_vm, OID_AUTO, swap_total, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
167e8bb589dSMatt Macy     &swap_total, 0, sysctl_page_shift, "A",
168e8bb589dSMatt Macy     "Total amount of available swap storage.");
169e8bb589dSMatt Macy 
1703364c323SKonstantin Belousov static int overcommit = 0;
171be7d4ac5SEdward Tomasz Napierala SYSCTL_INT(_vm, VM_OVERCOMMIT, overcommit, CTLFLAG_RW, &overcommit, 0,
1728a9c731fSIvan Voras     "Configure virtual memory overcommit behavior. See tuning(7) "
1738a9c731fSIvan Voras     "for details.");
17461203277SDag-Erling Smørgrav static unsigned long swzone;
17561203277SDag-Erling Smørgrav SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
17661203277SDag-Erling Smørgrav     "Actual size of swap metadata zone");
17761203277SDag-Erling Smørgrav static unsigned long swap_maxpages;
17861203277SDag-Erling Smørgrav SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
17961203277SDag-Erling Smørgrav     "Maximum amount of swap supported");
1803364c323SKonstantin Belousov 
181d869a17eSMark Johnston static COUNTER_U64_DEFINE_EARLY(swap_free_deferred);
182a8081778SJeff Roberson SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_deferred,
183a8081778SJeff Roberson     CTLFLAG_RD, &swap_free_deferred,
184a8081778SJeff Roberson     "Number of pages that deferred freeing swap space");
185a8081778SJeff Roberson 
186d869a17eSMark Johnston static COUNTER_U64_DEFINE_EARLY(swap_free_completed);
187a8081778SJeff Roberson SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_completed,
188a8081778SJeff Roberson     CTLFLAG_RD, &swap_free_completed,
189a8081778SJeff Roberson     "Number of deferred frees completed");
190a8081778SJeff Roberson 
1913364c323SKonstantin Belousov /* bits from overcommit */
1923364c323SKonstantin Belousov #define	SWAP_RESERVE_FORCE_ON		(1 << 0)
1933364c323SKonstantin Belousov #define	SWAP_RESERVE_RLIMIT_ON		(1 << 1)
1943364c323SKonstantin Belousov #define	SWAP_RESERVE_ALLOW_NONWIRED	(1 << 2)
1953364c323SKonstantin Belousov 
196e8bb589dSMatt Macy static int
197e8bb589dSMatt Macy sysctl_page_shift(SYSCTL_HANDLER_ARGS)
198e8bb589dSMatt Macy {
199e8bb589dSMatt Macy 	uint64_t newval;
200e8bb589dSMatt Macy 	u_long value = *(u_long *)arg1;
201e8bb589dSMatt Macy 
202e8bb589dSMatt Macy 	newval = ((uint64_t)value) << PAGE_SHIFT;
203e8bb589dSMatt Macy 	return (sysctl_handle_64(oidp, &newval, 0, req));
204e8bb589dSMatt Macy }
205e8bb589dSMatt Macy 
206ee744122SMateusz Guzik static bool
207ee744122SMateusz Guzik swap_reserve_by_cred_rlimit(u_long pincr, struct ucred *cred, int oc)
208ee744122SMateusz Guzik {
209ee744122SMateusz Guzik 	struct uidinfo *uip;
210ee744122SMateusz Guzik 	u_long prev;
211ee744122SMateusz Guzik 
212ee744122SMateusz Guzik 	uip = cred->cr_ruidinfo;
213ee744122SMateusz Guzik 
214ee744122SMateusz Guzik 	prev = atomic_fetchadd_long(&uip->ui_vmsize, pincr);
215ee744122SMateusz Guzik 	if ((oc & SWAP_RESERVE_RLIMIT_ON) != 0 &&
216ee744122SMateusz Guzik 	    prev + pincr > lim_cur(curthread, RLIMIT_SWAP) &&
217ee744122SMateusz Guzik 	    priv_check(curthread, PRIV_VM_SWAP_NORLIMIT) != 0) {
218ee744122SMateusz Guzik 		prev = atomic_fetchadd_long(&uip->ui_vmsize, -pincr);
219ee744122SMateusz Guzik 		KASSERT(prev >= pincr, ("negative vmsize for uid = %d\n", uip->ui_uid));
220ee744122SMateusz Guzik 		return (false);
221ee744122SMateusz Guzik 	}
222ee744122SMateusz Guzik 	return (true);
223ee744122SMateusz Guzik }
224ee744122SMateusz Guzik 
225ee744122SMateusz Guzik static void
226ee744122SMateusz Guzik swap_release_by_cred_rlimit(u_long pdecr, struct ucred *cred)
227ee744122SMateusz Guzik {
228ee744122SMateusz Guzik 	struct uidinfo *uip;
229ee744122SMateusz Guzik #ifdef INVARIANTS
230ee744122SMateusz Guzik 	u_long prev;
231ee744122SMateusz Guzik #endif
232ee744122SMateusz Guzik 
233ee744122SMateusz Guzik 	uip = cred->cr_ruidinfo;
234ee744122SMateusz Guzik 
235ee744122SMateusz Guzik #ifdef INVARIANTS
236ee744122SMateusz Guzik 	prev = atomic_fetchadd_long(&uip->ui_vmsize, -pdecr);
237ee744122SMateusz Guzik 	KASSERT(prev >= pdecr, ("negative vmsize for uid = %d\n", uip->ui_uid));
238ee744122SMateusz Guzik #else
239ee744122SMateusz Guzik 	atomic_subtract_long(&uip->ui_vmsize, pdecr);
240ee744122SMateusz Guzik #endif
241ee744122SMateusz Guzik }
242ee744122SMateusz Guzik 
243ee744122SMateusz Guzik static void
244ee744122SMateusz Guzik swap_reserve_force_rlimit(u_long pincr, struct ucred *cred)
245ee744122SMateusz Guzik {
246ee744122SMateusz Guzik 	struct uidinfo *uip;
247ee744122SMateusz Guzik 
248ee744122SMateusz Guzik 	uip = cred->cr_ruidinfo;
249ee744122SMateusz Guzik 	atomic_add_long(&uip->ui_vmsize, pincr);
250ee744122SMateusz Guzik }
251ee744122SMateusz Guzik 
252ee744122SMateusz Guzik bool
2533364c323SKonstantin Belousov swap_reserve(vm_ooffset_t incr)
2543364c323SKonstantin Belousov {
2553364c323SKonstantin Belousov 
256ef694c1aSEdward Tomasz Napierala 	return (swap_reserve_by_cred(incr, curthread->td_ucred));
2573364c323SKonstantin Belousov }
2583364c323SKonstantin Belousov 
259ee744122SMateusz Guzik bool
260ef694c1aSEdward Tomasz Napierala swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
2613364c323SKonstantin Belousov {
262e8bb589dSMatt Macy 	u_long r, s, prev, pincr;
263ee744122SMateusz Guzik #ifdef RACCT
264ee744122SMateusz Guzik 	int error;
265ee744122SMateusz Guzik #endif
266ee744122SMateusz Guzik 	int oc;
2673364c323SKonstantin Belousov 	static int curfail;
2683364c323SKonstantin Belousov 	static struct timeval lastfail;
2693364c323SKonstantin Belousov 
270e8bb589dSMatt Macy 	KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
271e8bb589dSMatt Macy 	    (uintmax_t)incr));
2723364c323SKonstantin Belousov 
273afcc55f3SEdward Tomasz Napierala #ifdef RACCT
274ee744122SMateusz Guzik 	if (RACCT_ENABLED()) {
2751ba5ad42SEdward Tomasz Napierala 		PROC_LOCK(curproc);
2761ba5ad42SEdward Tomasz Napierala 		error = racct_add(curproc, RACCT_SWAP, incr);
2771ba5ad42SEdward Tomasz Napierala 		PROC_UNLOCK(curproc);
2781ba5ad42SEdward Tomasz Napierala 		if (error != 0)
279ee744122SMateusz Guzik 			return (false);
2804b5c9cf6SEdward Tomasz Napierala 	}
281afcc55f3SEdward Tomasz Napierala #endif
2821ba5ad42SEdward Tomasz Napierala 
283e8bb589dSMatt Macy 	pincr = atop(incr);
284e8bb589dSMatt Macy 	prev = atomic_fetchadd_long(&swap_reserved, pincr);
285e8bb589dSMatt Macy 	r = prev + pincr;
286ee744122SMateusz Guzik 	s = swap_total;
287ee744122SMateusz Guzik 	oc = atomic_load_int(&overcommit);
288ee744122SMateusz Guzik 	if (r > s && (oc & SWAP_RESERVE_ALLOW_NONWIRED) != 0) {
289ee744122SMateusz Guzik 		s += vm_cnt.v_page_count - vm_cnt.v_free_reserved -
290e958ad4cSJeff Roberson 		    vm_wire_count();
291ee744122SMateusz Guzik 	}
292ee744122SMateusz Guzik 	if ((oc & SWAP_RESERVE_FORCE_ON) != 0 && r > s &&
293ee744122SMateusz Guzik 	    priv_check(curthread, PRIV_VM_SWAP_NOQUOTA) != 0) {
294e8bb589dSMatt Macy 		prev = atomic_fetchadd_long(&swap_reserved, -pincr);
295ee744122SMateusz Guzik 		KASSERT(prev >= pincr, ("swap_reserved < incr on overcommit fail"));
296ee744122SMateusz Guzik 		goto out_error;
2973364c323SKonstantin Belousov 	}
2983364c323SKonstantin Belousov 
299ee744122SMateusz Guzik 	if (!swap_reserve_by_cred_rlimit(pincr, cred, oc)) {
300ee744122SMateusz Guzik 		prev = atomic_fetchadd_long(&swap_reserved, -pincr);
301ee744122SMateusz Guzik 		KASSERT(prev >= pincr, ("swap_reserved < incr on overcommit fail"));
302ee744122SMateusz Guzik 		goto out_error;
303ee744122SMateusz Guzik 	}
304ee744122SMateusz Guzik 
305ee744122SMateusz Guzik 	return (true);
306ee744122SMateusz Guzik 
307ee744122SMateusz Guzik out_error:
308ee744122SMateusz Guzik 	if (ppsratecheck(&lastfail, &curfail, 1)) {
309ee744122SMateusz Guzik 		printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
310ee744122SMateusz Guzik 		    cred->cr_ruidinfo->ui_uid, curproc->p_pid, incr);
311ee744122SMateusz Guzik 	}
312afcc55f3SEdward Tomasz Napierala #ifdef RACCT
313ee744122SMateusz Guzik 	if (RACCT_ENABLED()) {
3141ba5ad42SEdward Tomasz Napierala 		PROC_LOCK(curproc);
3151ba5ad42SEdward Tomasz Napierala 		racct_sub(curproc, RACCT_SWAP, incr);
3161ba5ad42SEdward Tomasz Napierala 		PROC_UNLOCK(curproc);
3171ba5ad42SEdward Tomasz Napierala 	}
318afcc55f3SEdward Tomasz Napierala #endif
3191ba5ad42SEdward Tomasz Napierala 
320ee744122SMateusz Guzik 	return (false);
3213364c323SKonstantin Belousov }
3223364c323SKonstantin Belousov 
3233364c323SKonstantin Belousov void
3243364c323SKonstantin Belousov swap_reserve_force(vm_ooffset_t incr)
3253364c323SKonstantin Belousov {
326e8bb589dSMatt Macy 	u_long pincr;
3273364c323SKonstantin Belousov 
328e8bb589dSMatt Macy 	KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
329e8bb589dSMatt Macy 	    (uintmax_t)incr));
3303364c323SKonstantin Belousov 
331afcc55f3SEdward Tomasz Napierala #ifdef RACCT
332ee744122SMateusz Guzik 	if (RACCT_ENABLED()) {
333ee744122SMateusz Guzik 		PROC_LOCK(curproc);
3341ba5ad42SEdward Tomasz Napierala 		racct_add_force(curproc, RACCT_SWAP, incr);
335ee744122SMateusz Guzik 		PROC_UNLOCK(curproc);
336ee744122SMateusz Guzik 	}
337afcc55f3SEdward Tomasz Napierala #endif
338e8bb589dSMatt Macy 	pincr = atop(incr);
339e8bb589dSMatt Macy 	atomic_add_long(&swap_reserved, pincr);
340ee744122SMateusz Guzik 	swap_reserve_force_rlimit(pincr, curthread->td_ucred);
3413364c323SKonstantin Belousov }
3423364c323SKonstantin Belousov 
3433364c323SKonstantin Belousov void
3443364c323SKonstantin Belousov swap_release(vm_ooffset_t decr)
3453364c323SKonstantin Belousov {
346ef694c1aSEdward Tomasz Napierala 	struct ucred *cred;
3473364c323SKonstantin Belousov 
3483364c323SKonstantin Belousov 	PROC_LOCK(curproc);
349e8bb589dSMatt Macy 	cred = curproc->p_ucred;
350ef694c1aSEdward Tomasz Napierala 	swap_release_by_cred(decr, cred);
3513364c323SKonstantin Belousov 	PROC_UNLOCK(curproc);
3523364c323SKonstantin Belousov }
3533364c323SKonstantin Belousov 
3543364c323SKonstantin Belousov void
355ef694c1aSEdward Tomasz Napierala swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
3563364c323SKonstantin Belousov {
357ee744122SMateusz Guzik 	u_long pdecr;
358ee744122SMateusz Guzik #ifdef INVARIANTS
359ee744122SMateusz Guzik 	u_long prev;
360ee744122SMateusz Guzik #endif
3613364c323SKonstantin Belousov 
362e8bb589dSMatt Macy 	KASSERT((decr & PAGE_MASK) == 0, ("%s: decr: %ju & PAGE_MASK", __func__,
363e8bb589dSMatt Macy 	    (uintmax_t)decr));
3643364c323SKonstantin Belousov 
365e8bb589dSMatt Macy 	pdecr = atop(decr);
366ee744122SMateusz Guzik #ifdef INVARIANTS
367e8bb589dSMatt Macy 	prev = atomic_fetchadd_long(&swap_reserved, -pdecr);
368ee744122SMateusz Guzik 	KASSERT(prev >= pdecr, ("swap_reserved < decr"));
369ee744122SMateusz Guzik #else
370ee744122SMateusz Guzik 	atomic_subtract_long(&swap_reserved, pdecr);
371ee744122SMateusz Guzik #endif
3723364c323SKonstantin Belousov 
373ee744122SMateusz Guzik 	swap_release_by_cred_rlimit(pdecr, cred);
374e8bb589dSMatt Macy #ifdef RACCT
375e8bb589dSMatt Macy 	if (racct_enable)
3761ba5ad42SEdward Tomasz Napierala 		racct_sub_cred(cred, RACCT_SWAP, decr);
377e8bb589dSMatt Macy #endif
3783364c323SKonstantin Belousov }
3793364c323SKonstantin Belousov 
380f08b3099SKonstantin Belousov static int swap_pager_full = 2;	/* swap space exhaustion (task killing) */
3817dea2c2eSAlan Cox static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
382756a5412SGleb Smirnoff static struct mtx swbuf_mtx;	/* to sync nsw_wcount_async */
383756a5412SGleb Smirnoff static int nsw_wcount_async;	/* limit async write buffers */
384327f4e83SMatthew Dillon static int nsw_wcount_async_max;/* assigned maximum			*/
385327f4e83SMatthew Dillon static int nsw_cluster_max;	/* maximum VOP I/O allowed		*/
3861c7c3c6aSMatthew Dillon 
38789c241d1SGleb Smirnoff static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
3884c36e917SKonstantin Belousov SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
3894c36e917SKonstantin Belousov     CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
3904c36e917SKonstantin Belousov     "Maximum running async swap ops");
391d027ed2eSAlan Cox static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS);
392d027ed2eSAlan Cox SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD |
393d027ed2eSAlan Cox     CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A",
394d027ed2eSAlan Cox     "Swap Fragmentation Info");
39589c241d1SGleb Smirnoff 
3960cddd8f0SMatthew Dillon static struct sx sw_alloc_sx;
397327f4e83SMatthew Dillon 
3981c7c3c6aSMatthew Dillon /*
3991c7c3c6aSMatthew Dillon  * "named" and "unnamed" anon region objects.  Try to reduce the overhead
4001c7c3c6aSMatthew Dillon  * of searching a named list by hashing it just a little.
4011c7c3c6aSMatthew Dillon  */
4021c7c3c6aSMatthew Dillon 
4031c7c3c6aSMatthew Dillon #define NOBJLISTS		8
4041c7c3c6aSMatthew Dillon 
4051c7c3c6aSMatthew Dillon #define NOBJLIST(handle)	\
406af647ddeSBruce Evans 	(&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
4071c7c3c6aSMatthew Dillon 
4081c7c3c6aSMatthew Dillon static struct pagerlst	swap_pager_object_list[NOBJLISTS];
409756a5412SGleb Smirnoff static uma_zone_t swwbuf_zone;
410756a5412SGleb Smirnoff static uma_zone_t swrbuf_zone;
411f425ab8eSKonstantin Belousov static uma_zone_t swblk_zone;
412f425ab8eSKonstantin Belousov static uma_zone_t swpctrie_zone;
4131c7c3c6aSMatthew Dillon 
4141c7c3c6aSMatthew Dillon /*
4151c7c3c6aSMatthew Dillon  * pagerops for OBJT_SWAP - "swap pager".  Some ops are also global procedure
4161c7c3c6aSMatthew Dillon  * calls hooked from other parts of the VM system and do not appear here.
4171c7c3c6aSMatthew Dillon  * (see vm/swap_pager.h).
4181c7c3c6aSMatthew Dillon  */
419ff98689dSBruce Evans static vm_object_t
42011caded3SAlfred Perlstein 		swap_pager_alloc(void *handle, vm_ooffset_t size,
4213364c323SKonstantin Belousov 		    vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
4224b8365d7SKonstantin Belousov static vm_object_t
4234b8365d7SKonstantin Belousov 		swap_tmpfs_pager_alloc(void *handle, vm_ooffset_t size,
4244b8365d7SKonstantin Belousov 		    vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
42511caded3SAlfred Perlstein static void	swap_pager_dealloc(vm_object_t object);
426b0cd2017SGleb Smirnoff static int	swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
427b0cd2017SGleb Smirnoff     int *);
428b0cd2017SGleb Smirnoff static int	swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
429b0cd2017SGleb Smirnoff     int *, pgo_getpages_iodone_t, void *);
430751221fdSPoul-Henning Kamp static void	swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
4315ea4972cSAlan Cox static boolean_t
4325ea4972cSAlan Cox 		swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
43311caded3SAlfred Perlstein static void	swap_pager_init(void);
43411caded3SAlfred Perlstein static void	swap_pager_unswapped(vm_page_t);
435b3fed13eSDavid Schultz static void	swap_pager_swapoff(struct swdevt *sp);
436fe7bcbafSKyle Evans static void	swap_pager_update_writecount(vm_object_t object,
437fe7bcbafSKyle Evans     vm_offset_t start, vm_offset_t end);
438fe7bcbafSKyle Evans static void	swap_pager_release_writecount(vm_object_t object,
439fe7bcbafSKyle Evans     vm_offset_t start, vm_offset_t end);
4404b8365d7SKonstantin Belousov static void	swap_tmpfs_pager_getvp(vm_object_t object, struct vnode **vpp,
441192112b7SKonstantin Belousov     bool *vp_heldp);
4421390a5cbSKonstantin Belousov static void	swap_pager_freespace(vm_object_t object, vm_pindex_t start,
4431390a5cbSKonstantin Belousov     vm_size_t size);
444f708ef1bSPoul-Henning Kamp 
445d474440aSKonstantin Belousov const struct pagerops swappagerops = {
446*00a3fe96SKonstantin Belousov 	.pgo_kvme_type = KVME_TYPE_SWAP,
447e04e4bacSPoul-Henning Kamp 	.pgo_init =	swap_pager_init,	/* early system initialization of pager	*/
448e04e4bacSPoul-Henning Kamp 	.pgo_alloc =	swap_pager_alloc,	/* allocate an OBJT_SWAP object */
449e04e4bacSPoul-Henning Kamp 	.pgo_dealloc =	swap_pager_dealloc,	/* deallocate an OBJT_SWAP object */
450e04e4bacSPoul-Henning Kamp 	.pgo_getpages =	swap_pager_getpages,	/* pagein */
45190effb23SGleb Smirnoff 	.pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
452e04e4bacSPoul-Henning Kamp 	.pgo_putpages =	swap_pager_putpages,	/* pageout */
453e04e4bacSPoul-Henning Kamp 	.pgo_haspage =	swap_pager_haspage,	/* get backing store status for page */
454e04e4bacSPoul-Henning Kamp 	.pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
455fe7bcbafSKyle Evans 	.pgo_update_writecount = swap_pager_update_writecount,
456fe7bcbafSKyle Evans 	.pgo_release_writecount = swap_pager_release_writecount,
4574b8365d7SKonstantin Belousov 	.pgo_freespace = swap_pager_freespace,
4584b8365d7SKonstantin Belousov };
4594b8365d7SKonstantin Belousov 
460d474440aSKonstantin Belousov const struct pagerops swaptmpfspagerops = {
461*00a3fe96SKonstantin Belousov 	.pgo_kvme_type = KVME_TYPE_VNODE,
4624b8365d7SKonstantin Belousov 	.pgo_alloc =	swap_tmpfs_pager_alloc,
4634b8365d7SKonstantin Belousov 	.pgo_dealloc =	swap_pager_dealloc,
4644b8365d7SKonstantin Belousov 	.pgo_getpages =	swap_pager_getpages,
4654b8365d7SKonstantin Belousov 	.pgo_getpages_async = swap_pager_getpages_async,
4664b8365d7SKonstantin Belousov 	.pgo_putpages =	swap_pager_putpages,
4674b8365d7SKonstantin Belousov 	.pgo_haspage =	swap_pager_haspage,
4684b8365d7SKonstantin Belousov 	.pgo_pageunswapped = swap_pager_unswapped,
4694b8365d7SKonstantin Belousov 	.pgo_update_writecount = swap_pager_update_writecount,
4704b8365d7SKonstantin Belousov 	.pgo_release_writecount = swap_pager_release_writecount,
4714b8365d7SKonstantin Belousov 	.pgo_set_writeable_dirty = vm_object_set_writeable_dirty_,
4724b8365d7SKonstantin Belousov 	.pgo_mightbedirty = vm_object_mightbedirty_,
4734b8365d7SKonstantin Belousov 	.pgo_getvp = swap_tmpfs_pager_getvp,
4741390a5cbSKonstantin Belousov 	.pgo_freespace = swap_pager_freespace,
475df8bae1dSRodney W. Grimes };
476df8bae1dSRodney W. Grimes 
4771c7c3c6aSMatthew Dillon /*
4781c7c3c6aSMatthew Dillon  * swap_*() routines are externally accessible.  swp_*() routines are
4791c7c3c6aSMatthew Dillon  * internal.
4801c7c3c6aSMatthew Dillon  */
481e9c0cc15SPoul-Henning Kamp static int nswap_lowat = 128;	/* in pages, swap_pager_almost_full warn */
482e9c0cc15SPoul-Henning Kamp static int nswap_hiwat = 512;	/* in pages, swap_pager_almost_full warn */
48326f9a767SRodney W. Grimes 
48407c348eaSAlan Cox SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
48507c348eaSAlan Cox     "Maximum size of a swap block in pages");
486cee313c4SRobert Watson 
487a5edd34aSPoul-Henning Kamp static void	swp_sizecheck(void);
48811caded3SAlfred Perlstein static void	swp_pager_async_iodone(struct buf *bp);
489230869e0SAlan Cox static bool	swp_pager_swblk_empty(struct swblk *sb, int start, int limit);
490abdab7b6SDoug Moore static void	swp_pager_free_empty_swblk(vm_object_t, struct swblk *sb);
49188ad2d7bSKonstantin Belousov static int	swapongeom(struct vnode *);
49259efee01SPoul-Henning Kamp static int	swaponvp(struct thread *, struct vnode *, u_long);
49335918c55SChristian S.J. Peron static int	swapoff_one(struct swdevt *sp, struct ucred *cred);
49424a1cce3SDavid Greenman 
4951c7c3c6aSMatthew Dillon /*
4961c7c3c6aSMatthew Dillon  * Swap bitmap functions
4971c7c3c6aSMatthew Dillon  */
498230869e0SAlan Cox static void	swp_pager_freeswapspace(daddr_t blk, daddr_t npages);
49936b01270SDoug Moore static daddr_t	swp_pager_getswapspace(int *npages);
5001c7c3c6aSMatthew Dillon 
5011c7c3c6aSMatthew Dillon /*
5021c7c3c6aSMatthew Dillon  * Metadata functions
5031c7c3c6aSMatthew Dillon  */
50478f1deefSAlan Cox static daddr_t swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
5052e56b64fSKonstantin Belousov static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t);
506467057fcSDoug Moore static void swp_pager_meta_transfer(vm_object_t src, vm_object_t dst,
507467057fcSDoug Moore     vm_pindex_t pindex, vm_pindex_t count);
50811caded3SAlfred Perlstein static void swp_pager_meta_free_all(vm_object_t);
5098ecbf14bSDoug Moore static daddr_t swp_pager_meta_lookup(vm_object_t, vm_pindex_t);
5101c7c3c6aSMatthew Dillon 
51178f1deefSAlan Cox static void
51278f1deefSAlan Cox swp_pager_init_freerange(daddr_t *start, daddr_t *num)
51378f1deefSAlan Cox {
51478f1deefSAlan Cox 
51578f1deefSAlan Cox 	*start = SWAPBLK_NONE;
51678f1deefSAlan Cox 	*num = 0;
51778f1deefSAlan Cox }
51878f1deefSAlan Cox 
51978f1deefSAlan Cox static void
52078f1deefSAlan Cox swp_pager_update_freerange(daddr_t *start, daddr_t *num, daddr_t addr)
52178f1deefSAlan Cox {
52278f1deefSAlan Cox 
52378f1deefSAlan Cox 	if (*start + *num == addr) {
52478f1deefSAlan Cox 		(*num)++;
52578f1deefSAlan Cox 	} else {
52678f1deefSAlan Cox 		swp_pager_freeswapspace(*start, *num);
52778f1deefSAlan Cox 		*start = addr;
52878f1deefSAlan Cox 		*num = 1;
52978f1deefSAlan Cox 	}
53078f1deefSAlan Cox }
53178f1deefSAlan Cox 
532f425ab8eSKonstantin Belousov static void *
533f425ab8eSKonstantin Belousov swblk_trie_alloc(struct pctrie *ptree)
534f425ab8eSKonstantin Belousov {
535f425ab8eSKonstantin Belousov 
536f425ab8eSKonstantin Belousov 	return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
537f425ab8eSKonstantin Belousov 	    M_USE_RESERVE : 0)));
538f425ab8eSKonstantin Belousov }
539f425ab8eSKonstantin Belousov 
540f425ab8eSKonstantin Belousov static void
541f425ab8eSKonstantin Belousov swblk_trie_free(struct pctrie *ptree, void *node)
542f425ab8eSKonstantin Belousov {
543f425ab8eSKonstantin Belousov 
544f425ab8eSKonstantin Belousov 	uma_zfree(swpctrie_zone, node);
545f425ab8eSKonstantin Belousov }
546f425ab8eSKonstantin Belousov 
547f425ab8eSKonstantin Belousov PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
548f425ab8eSKonstantin Belousov 
5491c7c3c6aSMatthew Dillon /*
5501c7c3c6aSMatthew Dillon  * SWP_SIZECHECK() -	update swap_pager_full indication
5511c7c3c6aSMatthew Dillon  *
55220d3034fSMatthew Dillon  *	update the swap_pager_almost_full indication and warn when we are
55320d3034fSMatthew Dillon  *	about to run out of swap space, using lowat/hiwat hysteresis.
55420d3034fSMatthew Dillon  *
55520d3034fSMatthew Dillon  *	Clear swap_pager_full ( task killing ) indication when lowat is met.
5561c7c3c6aSMatthew Dillon  *
5571c7c3c6aSMatthew Dillon  *	No restrictions on call
5581c7c3c6aSMatthew Dillon  *	This routine may not block.
5591c7c3c6aSMatthew Dillon  */
560a5edd34aSPoul-Henning Kamp static void
5612f249180SPoul-Henning Kamp swp_sizecheck(void)
5620d94caffSDavid Greenman {
56323955314SAlfred Perlstein 
5648f60c087SPoul-Henning Kamp 	if (swap_pager_avail < nswap_lowat) {
56520d3034fSMatthew Dillon 		if (swap_pager_almost_full == 0) {
5661af87c92SDavid Greenman 			printf("swap_pager: out of swap space\n");
56720d3034fSMatthew Dillon 			swap_pager_almost_full = 1;
5682b0d37a4SMatthew Dillon 		}
56920d3034fSMatthew Dillon 	} else {
57026f9a767SRodney W. Grimes 		swap_pager_full = 0;
5718f60c087SPoul-Henning Kamp 		if (swap_pager_avail > nswap_hiwat)
57220d3034fSMatthew Dillon 			swap_pager_almost_full = 0;
57326f9a767SRodney W. Grimes 	}
5741c7c3c6aSMatthew Dillon }
5751c7c3c6aSMatthew Dillon 
5761c7c3c6aSMatthew Dillon /*
5771c7c3c6aSMatthew Dillon  * SWAP_PAGER_INIT() -	initialize the swap pager!
5781c7c3c6aSMatthew Dillon  *
5791c7c3c6aSMatthew Dillon  *	Expected to be started from system init.  NOTE:  This code is run
5801c7c3c6aSMatthew Dillon  *	before much else so be careful what you depend on.  Most of the VM
5811c7c3c6aSMatthew Dillon  *	system has yet to be initialized at this point.
5821c7c3c6aSMatthew Dillon  */
583f5a12711SPoul-Henning Kamp static void
5842f249180SPoul-Henning Kamp swap_pager_init(void)
585df8bae1dSRodney W. Grimes {
5861c7c3c6aSMatthew Dillon 	/*
5871c7c3c6aSMatthew Dillon 	 * Initialize object lists
5881c7c3c6aSMatthew Dillon 	 */
5891c7c3c6aSMatthew Dillon 	int i;
5901c7c3c6aSMatthew Dillon 
5911c7c3c6aSMatthew Dillon 	for (i = 0; i < NOBJLISTS; ++i)
5921c7c3c6aSMatthew Dillon 		TAILQ_INIT(&swap_pager_object_list[i]);
59320da9c2eSPoul-Henning Kamp 	mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
59415719273SKonstantin Belousov 	sx_init(&sw_alloc_sx, "swspsx");
59504533e1eSKonstantin Belousov 	sx_init(&swdev_syscall_lock, "swsysc");
5961c7c3c6aSMatthew Dillon }
59726f9a767SRodney W. Grimes 
598df8bae1dSRodney W. Grimes /*
5991c7c3c6aSMatthew Dillon  * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
6001c7c3c6aSMatthew Dillon  *
6011c7c3c6aSMatthew Dillon  *	Expected to be started from pageout process once, prior to entering
6021c7c3c6aSMatthew Dillon  *	its main loop.
603df8bae1dSRodney W. Grimes  */
60424a1cce3SDavid Greenman void
6052f249180SPoul-Henning Kamp swap_pager_swap_init(void)
606df8bae1dSRodney W. Grimes {
60761203277SDag-Erling Smørgrav 	unsigned long n, n2;
6080d94caffSDavid Greenman 
60926f9a767SRodney W. Grimes 	/*
6101c7c3c6aSMatthew Dillon 	 * Number of in-transit swap bp operations.  Don't
6111c7c3c6aSMatthew Dillon 	 * exhaust the pbufs completely.  Make sure we
6121c7c3c6aSMatthew Dillon 	 * initialize workable values (0 will work for hysteresis
6131c7c3c6aSMatthew Dillon 	 * but it isn't very efficient).
6141c7c3c6aSMatthew Dillon 	 *
615327f4e83SMatthew Dillon 	 * The nsw_cluster_max is constrained by the bp->b_pages[]
616cd853791SKonstantin Belousov 	 * array, which has maxphys / PAGE_SIZE entries, and our locally
6177b9bcad9SDoug Moore 	 * defined MAX_PAGEOUT_CLUSTER.   Also be aware that swap ops are
6181c7c3c6aSMatthew Dillon 	 * constrained by the swap device interleave stripe size.
619327f4e83SMatthew Dillon 	 *
620327f4e83SMatthew Dillon 	 * Currently we hardwire nsw_wcount_async to 4.  This limit is
621327f4e83SMatthew Dillon 	 * designed to prevent other I/O from having high latencies due to
622327f4e83SMatthew Dillon 	 * our pageout I/O.  The value 4 works well for one or two active swap
623327f4e83SMatthew Dillon 	 * devices but is probably a little low if you have more.  Even so,
624327f4e83SMatthew Dillon 	 * a higher value would probably generate only a limited improvement
625327f4e83SMatthew Dillon 	 * with three or four active swap devices since the system does not
626327f4e83SMatthew Dillon 	 * typically have to pageout at extreme bandwidths.   We will want
627327f4e83SMatthew Dillon 	 * at least 2 per swap devices, and 4 is a pretty good value if you
628327f4e83SMatthew Dillon 	 * have one NFS swap device due to the command/ack latency over NFS.
629327f4e83SMatthew Dillon 	 * So it all works out pretty well.
63026f9a767SRodney W. Grimes 	 */
631cd853791SKonstantin Belousov 	nsw_cluster_max = min(maxphys / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
632327f4e83SMatthew Dillon 
633327f4e83SMatthew Dillon 	nsw_wcount_async = 4;
634327f4e83SMatthew Dillon 	nsw_wcount_async_max = nsw_wcount_async;
635756a5412SGleb Smirnoff 	mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
636756a5412SGleb Smirnoff 
637756a5412SGleb Smirnoff 	swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
638756a5412SGleb Smirnoff 	swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
63924a1cce3SDavid Greenman 
6401c7c3c6aSMatthew Dillon 	/*
641a8233027SKonstantin Belousov 	 * Initialize our zone, taking the user's requested size or
642a8233027SKonstantin Belousov 	 * estimating the number we need based on the number of pages
643a8233027SKonstantin Belousov 	 * in the system.
6441c7c3c6aSMatthew Dillon 	 */
645a8233027SKonstantin Belousov 	n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
646a8233027SKonstantin Belousov 	    vm_cnt.v_page_count / 2;
647f425ab8eSKonstantin Belousov 	swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
6486c5f36ffSJeff Roberson 	    pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0);
649f425ab8eSKonstantin Belousov 	if (swpctrie_zone == NULL)
650f425ab8eSKonstantin Belousov 		panic("failed to create swap pctrie zone.");
651f425ab8eSKonstantin Belousov 	swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
6526c5f36ffSJeff Roberson 	    NULL, NULL, _Alignof(struct swblk) - 1, 0);
653f425ab8eSKonstantin Belousov 	if (swblk_zone == NULL)
654f425ab8eSKonstantin Belousov 		panic("failed to create swap blk zone.");
65522a5e6b9SDag-Erling Smørgrav 	n2 = n;
6568355f576SJeff Roberson 	do {
657f425ab8eSKonstantin Belousov 		if (uma_zone_reserve_kva(swblk_zone, n))
65861ce6eeeSAlfred Perlstein 			break;
65961ce6eeeSAlfred Perlstein 		/*
66061ce6eeeSAlfred Perlstein 		 * if the allocation failed, try a zone two thirds the
66161ce6eeeSAlfred Perlstein 		 * size of the previous attempt.
66261ce6eeeSAlfred Perlstein 		 */
66361ce6eeeSAlfred Perlstein 		n -= ((n + 2) / 3);
66461ce6eeeSAlfred Perlstein 	} while (n > 0);
66553faf5a7SKonstantin Belousov 
66653faf5a7SKonstantin Belousov 	/*
66753faf5a7SKonstantin Belousov 	 * Often uma_zone_reserve_kva() cannot reserve exactly the
66853faf5a7SKonstantin Belousov 	 * requested size.  Account for the difference when
66953faf5a7SKonstantin Belousov 	 * calculating swap_maxpages.
67053faf5a7SKonstantin Belousov 	 */
67153faf5a7SKonstantin Belousov 	n = uma_zone_get_max(swblk_zone);
67253faf5a7SKonstantin Belousov 
6731fffcd75SKonstantin Belousov 	if (n < n2)
674a8233027SKonstantin Belousov 		printf("Swap blk zone entries changed from %lu to %lu.\n",
675f425ab8eSKonstantin Belousov 		    n2, n);
676303fa05aSKonstantin Belousov 	/* absolute maximum we can handle assuming 100% efficiency */
67761203277SDag-Erling Smørgrav 	swap_maxpages = n * SWAP_META_PAGES;
678f425ab8eSKonstantin Belousov 	swzone = n * sizeof(struct swblk);
679f425ab8eSKonstantin Belousov 	if (!uma_zone_reserve_kva(swpctrie_zone, n))
680f425ab8eSKonstantin Belousov 		printf("Cannot reserve swap pctrie zone, "
681f425ab8eSKonstantin Belousov 		    "reduce kern.maxswzone.\n");
68224a1cce3SDavid Greenman }
68324a1cce3SDavid Greenman 
684eb4d6a1bSKonstantin Belousov static vm_object_t
6854b8365d7SKonstantin Belousov swap_pager_alloc_init(objtype_t otype, void *handle, struct ucred *cred,
6864b8365d7SKonstantin Belousov     vm_ooffset_t size, vm_ooffset_t offset)
687eb4d6a1bSKonstantin Belousov {
688eb4d6a1bSKonstantin Belousov 	vm_object_t object;
689eb4d6a1bSKonstantin Belousov 
690eb4d6a1bSKonstantin Belousov 	if (cred != NULL) {
691eb4d6a1bSKonstantin Belousov 		if (!swap_reserve_by_cred(size, cred))
692eb4d6a1bSKonstantin Belousov 			return (NULL);
693eb4d6a1bSKonstantin Belousov 		crhold(cred);
694eb4d6a1bSKonstantin Belousov 	}
695f425ab8eSKonstantin Belousov 
696f425ab8eSKonstantin Belousov 	/*
697f425ab8eSKonstantin Belousov 	 * The un_pager.swp.swp_blks trie is initialized by
698f425ab8eSKonstantin Belousov 	 * vm_object_allocate() to ensure the correct order of
699f425ab8eSKonstantin Belousov 	 * visibility to other threads.
700f425ab8eSKonstantin Belousov 	 */
7014b8365d7SKonstantin Belousov 	object = vm_object_allocate(otype, OFF_TO_IDX(offset +
702eb4d6a1bSKonstantin Belousov 	    PAGE_MASK + size));
703f425ab8eSKonstantin Belousov 
704fe7bcbafSKyle Evans 	object->un_pager.swp.writemappings = 0;
705eb4d6a1bSKonstantin Belousov 	object->handle = handle;
706eb4d6a1bSKonstantin Belousov 	if (cred != NULL) {
707eb4d6a1bSKonstantin Belousov 		object->cred = cred;
708eb4d6a1bSKonstantin Belousov 		object->charge = size;
709eb4d6a1bSKonstantin Belousov 	}
710eb4d6a1bSKonstantin Belousov 	return (object);
711eb4d6a1bSKonstantin Belousov }
712eb4d6a1bSKonstantin Belousov 
71324a1cce3SDavid Greenman /*
7141c7c3c6aSMatthew Dillon  * SWAP_PAGER_ALLOC() -	allocate a new OBJT_SWAP VM object and instantiate
7151c7c3c6aSMatthew Dillon  *			its metadata structures.
7161c7c3c6aSMatthew Dillon  *
7171c7c3c6aSMatthew Dillon  *	This routine is called from the mmap and fork code to create a new
718eb4d6a1bSKonstantin Belousov  *	OBJT_SWAP object.
7191c7c3c6aSMatthew Dillon  *
720eb4d6a1bSKonstantin Belousov  *	This routine must ensure that no live duplicate is created for
721eb4d6a1bSKonstantin Belousov  *	the named object request, which is protected against by
722eb4d6a1bSKonstantin Belousov  *	holding the sw_alloc_sx lock in case handle != NULL.
72324a1cce3SDavid Greenman  */
724f5a12711SPoul-Henning Kamp static vm_object_t
7256cde7a16SDavid Greenman swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
7263364c323SKonstantin Belousov     vm_ooffset_t offset, struct ucred *cred)
72724a1cce3SDavid Greenman {
72824a1cce3SDavid Greenman 	vm_object_t object;
7292f7af3dbSAlan Cox 
730eb4d6a1bSKonstantin Belousov 	if (handle != NULL) {
7311c7c3c6aSMatthew Dillon 		/*
7321c7c3c6aSMatthew Dillon 		 * Reference existing named region or allocate new one.  There
7331c7c3c6aSMatthew Dillon 		 * should not be a race here against swp_pager_meta_build()
7341c7c3c6aSMatthew Dillon 		 * as called from vm_page_remove() in regards to the lookup
7351c7c3c6aSMatthew Dillon 		 * of the handle.
7361c7c3c6aSMatthew Dillon 		 */
7370cddd8f0SMatthew Dillon 		sx_xlock(&sw_alloc_sx);
7381c7c3c6aSMatthew Dillon 		object = vm_pager_object_lookup(NOBJLIST(handle), handle);
739b5e8f167SAlan Cox 		if (object == NULL) {
7404b8365d7SKonstantin Belousov 			object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
7414b8365d7SKonstantin Belousov 			    size, offset);
742eb4d6a1bSKonstantin Belousov 			if (object != NULL) {
743eb4d6a1bSKonstantin Belousov 				TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
744eb4d6a1bSKonstantin Belousov 				    object, pager_object_list);
7453364c323SKonstantin Belousov 			}
74624a1cce3SDavid Greenman 		}
7470cddd8f0SMatthew Dillon 		sx_xunlock(&sw_alloc_sx);
74824a1cce3SDavid Greenman 	} else {
7494b8365d7SKonstantin Belousov 		object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
7504b8365d7SKonstantin Belousov 		    size, offset);
75124a1cce3SDavid Greenman 	}
75224a1cce3SDavid Greenman 	return (object);
753df8bae1dSRodney W. Grimes }
754df8bae1dSRodney W. Grimes 
7554b8365d7SKonstantin Belousov static vm_object_t
7564b8365d7SKonstantin Belousov swap_tmpfs_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
7574b8365d7SKonstantin Belousov     vm_ooffset_t offset, struct ucred *cred)
7584b8365d7SKonstantin Belousov {
7594b8365d7SKonstantin Belousov 	vm_object_t object;
7604b8365d7SKonstantin Belousov 
7614b8365d7SKonstantin Belousov 	MPASS(handle == NULL);
7624b8365d7SKonstantin Belousov 	object = swap_pager_alloc_init(OBJT_SWAP_TMPFS, handle, cred,
7634b8365d7SKonstantin Belousov 	    size, offset);
7644b8365d7SKonstantin Belousov 	return (object);
7654b8365d7SKonstantin Belousov }
7664b8365d7SKonstantin Belousov 
76726f9a767SRodney W. Grimes /*
7681c7c3c6aSMatthew Dillon  * SWAP_PAGER_DEALLOC() -	remove swap metadata from object
7691c7c3c6aSMatthew Dillon  *
7701c7c3c6aSMatthew Dillon  *	The swap backing for the object is destroyed.  The code is
7711c7c3c6aSMatthew Dillon  *	designed such that we can reinstantiate it later, but this
7721c7c3c6aSMatthew Dillon  *	routine is typically called only when the entire object is
7731c7c3c6aSMatthew Dillon  *	about to be destroyed.
7741c7c3c6aSMatthew Dillon  *
77515523cf7SKonstantin Belousov  *	The object must be locked.
77626f9a767SRodney W. Grimes  */
777df8bae1dSRodney W. Grimes static void
7782f249180SPoul-Henning Kamp swap_pager_dealloc(vm_object_t object)
77926f9a767SRodney W. Grimes {
7804dcc5c2dSMatthew Dillon 
781eb4d6a1bSKonstantin Belousov 	VM_OBJECT_ASSERT_WLOCKED(object);
782eb4d6a1bSKonstantin Belousov 	KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
783eb4d6a1bSKonstantin Belousov 
78426f9a767SRodney W. Grimes 	/*
7851c7c3c6aSMatthew Dillon 	 * Remove from list right away so lookups will fail if we block for
7861c7c3c6aSMatthew Dillon 	 * pageout completion.
78726f9a767SRodney W. Grimes 	 */
78867388836SKonstantin Belousov 	if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
789eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WUNLOCK(object);
790eb4d6a1bSKonstantin Belousov 		sx_xlock(&sw_alloc_sx);
791eb4d6a1bSKonstantin Belousov 		TAILQ_REMOVE(NOBJLIST(object->handle), object,
792eb4d6a1bSKonstantin Belousov 		    pager_object_list);
793eb4d6a1bSKonstantin Belousov 		sx_xunlock(&sw_alloc_sx);
794eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WLOCK(object);
795bd228075SAlan Cox 	}
7961c7c3c6aSMatthew Dillon 
7971c7c3c6aSMatthew Dillon 	vm_object_pip_wait(object, "swpdea");
7981c7c3c6aSMatthew Dillon 
7991c7c3c6aSMatthew Dillon 	/*
8001c7c3c6aSMatthew Dillon 	 * Free all remaining metadata.  We only bother to free it from
8011c7c3c6aSMatthew Dillon 	 * the swap meta data.  We do not attempt to free swapblk's still
8021c7c3c6aSMatthew Dillon 	 * associated with vm_page_t's for this object.  We do not care
8031c7c3c6aSMatthew Dillon 	 * if paging is still in progress on some objects.
8041c7c3c6aSMatthew Dillon 	 */
8051c7c3c6aSMatthew Dillon 	swp_pager_meta_free_all(object);
806e735691bSJohn Baldwin 	object->handle = NULL;
807e735691bSJohn Baldwin 	object->type = OBJT_DEAD;
8084b8365d7SKonstantin Belousov 	vm_object_clear_flag(object, OBJ_SWAP);
8091c7c3c6aSMatthew Dillon }
8101c7c3c6aSMatthew Dillon 
8111c7c3c6aSMatthew Dillon /************************************************************************
8121c7c3c6aSMatthew Dillon  *			SWAP PAGER BITMAP ROUTINES			*
8131c7c3c6aSMatthew Dillon  ************************************************************************/
8141c7c3c6aSMatthew Dillon 
8151c7c3c6aSMatthew Dillon /*
8161c7c3c6aSMatthew Dillon  * SWP_PAGER_GETSWAPSPACE() -	allocate raw swap space
8171c7c3c6aSMatthew Dillon  *
81836b01270SDoug Moore  *	Allocate swap for up to the requested number of pages.  The
81936b01270SDoug Moore  *	starting swap block number (a page index) is returned or
82036b01270SDoug Moore  *	SWAPBLK_NONE if the allocation failed.
8211c7c3c6aSMatthew Dillon  *
8221c7c3c6aSMatthew Dillon  *	Also has the side effect of advising that somebody made a mistake
8231c7c3c6aSMatthew Dillon  *	when they configured swap and didn't configure enough.
8241c7c3c6aSMatthew Dillon  *
82515523cf7SKonstantin Belousov  *	This routine may not sleep.
8268f60c087SPoul-Henning Kamp  *
8278f60c087SPoul-Henning Kamp  *	We allocate in round-robin fashion from the configured devices.
8281c7c3c6aSMatthew Dillon  */
829a5edd34aSPoul-Henning Kamp static daddr_t
83036b01270SDoug Moore swp_pager_getswapspace(int *io_npages)
8311c7c3c6aSMatthew Dillon {
8321c7c3c6aSMatthew Dillon 	daddr_t blk;
8338f60c087SPoul-Henning Kamp 	struct swdevt *sp;
83487ae0686SDoug Moore 	int mpages, npages;
8351c7c3c6aSMatthew Dillon 
83636b01270SDoug Moore 	KASSERT(*io_npages >= 1,
83736b01270SDoug Moore 	    ("%s: npages not positive", __func__));
8388f60c087SPoul-Henning Kamp 	blk = SWAPBLK_NONE;
83931c82722SDoug Moore 	mpages = *io_npages;
84031c82722SDoug Moore 	npages = imin(BLIST_MAX_ALLOC, mpages);
84120da9c2eSPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
8428f60c087SPoul-Henning Kamp 	sp = swdevhd;
84348e98a2aSDoug Moore 	while (!TAILQ_EMPTY(&swtailq)) {
8448f60c087SPoul-Henning Kamp 		if (sp == NULL)
8458f60c087SPoul-Henning Kamp 			sp = TAILQ_FIRST(&swtailq);
84648e98a2aSDoug Moore 		if ((sp->sw_flags & SW_CLOSING) == 0)
84787ae0686SDoug Moore 			blk = blist_alloc(sp->sw_blist, &npages, mpages);
84848e98a2aSDoug Moore 		if (blk != SWAPBLK_NONE)
84948e98a2aSDoug Moore 			break;
85048e98a2aSDoug Moore 		sp = TAILQ_NEXT(sp, sw_list);
85148e98a2aSDoug Moore 		if (swdevhd == sp) {
85236b01270SDoug Moore 			if (npages == 1)
85348e98a2aSDoug Moore 				break;
85487ae0686SDoug Moore 			mpages = npages - 1;
85548e98a2aSDoug Moore 			npages >>= 1;
85648e98a2aSDoug Moore 		}
85748e98a2aSDoug Moore 	}
8588f60c087SPoul-Henning Kamp 	if (blk != SWAPBLK_NONE) {
85948e98a2aSDoug Moore 		*io_npages = npages;
8608f60c087SPoul-Henning Kamp 		blk += sp->sw_first;
8618f60c087SPoul-Henning Kamp 		sp->sw_used += npages;
862d05bc129SAlan Cox 		swap_pager_avail -= npages;
8638f60c087SPoul-Henning Kamp 		swp_sizecheck();
8648f60c087SPoul-Henning Kamp 		swdevhd = TAILQ_NEXT(sp, sw_list);
86548e98a2aSDoug Moore 	} else {
8662b0d37a4SMatthew Dillon 		if (swap_pager_full != 2) {
86748e98a2aSDoug Moore 			printf("swp_pager_getswapspace(%d): failed\n",
86848e98a2aSDoug Moore 			    *io_npages);
8692b0d37a4SMatthew Dillon 			swap_pager_full = 2;
87020d3034fSMatthew Dillon 			swap_pager_almost_full = 1;
8712b0d37a4SMatthew Dillon 		}
8728f60c087SPoul-Henning Kamp 		swdevhd = NULL;
87348e98a2aSDoug Moore 	}
874d05bc129SAlan Cox 	mtx_unlock(&sw_dev_mtx);
8751c7c3c6aSMatthew Dillon 	return (blk);
87626f9a767SRodney W. Grimes }
87726f9a767SRodney W. Grimes 
878541a1175SAlan Cox static bool
879b3fed13eSDavid Schultz swp_pager_isondev(daddr_t blk, struct swdevt *sp)
8808f60c087SPoul-Henning Kamp {
8818f60c087SPoul-Henning Kamp 
882b3fed13eSDavid Schultz 	return (blk >= sp->sw_first && blk < sp->sw_end);
8838f60c087SPoul-Henning Kamp }
8848f60c087SPoul-Henning Kamp 
8854b03903aSPoul-Henning Kamp static void
8864b03903aSPoul-Henning Kamp swp_pager_strategy(struct buf *bp)
8874b03903aSPoul-Henning Kamp {
8884b03903aSPoul-Henning Kamp 	struct swdevt *sp;
8894b03903aSPoul-Henning Kamp 
89020da9c2eSPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
8914b03903aSPoul-Henning Kamp 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
892541a1175SAlan Cox 		if (swp_pager_isondev(bp->b_blkno, sp)) {
89320da9c2eSPoul-Henning Kamp 			mtx_unlock(&sw_dev_mtx);
8942cc718a1SKonstantin Belousov 			if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
8952cc718a1SKonstantin Belousov 			    unmapped_buf_allowed) {
8962cc718a1SKonstantin Belousov 				bp->b_data = unmapped_buf;
8972cc718a1SKonstantin Belousov 				bp->b_offset = 0;
8982cc718a1SKonstantin Belousov 			} else {
8992cc718a1SKonstantin Belousov 				pmap_qenter((vm_offset_t)bp->b_data,
9002cc718a1SKonstantin Belousov 				    &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
9012cc718a1SKonstantin Belousov 			}
9024b03903aSPoul-Henning Kamp 			sp->sw_strategy(bp, sp);
9034b03903aSPoul-Henning Kamp 			return;
9044b03903aSPoul-Henning Kamp 		}
9054b03903aSPoul-Henning Kamp 	}
90620da9c2eSPoul-Henning Kamp 	panic("Swapdev not found");
9074b03903aSPoul-Henning Kamp }
9084b03903aSPoul-Henning Kamp 
90926f9a767SRodney W. Grimes /*
9101c7c3c6aSMatthew Dillon  * SWP_PAGER_FREESWAPSPACE() -	free raw swap space
9111c7c3c6aSMatthew Dillon  *
9121c7c3c6aSMatthew Dillon  *	This routine returns the specified swap blocks back to the bitmap.
9131c7c3c6aSMatthew Dillon  *
91415523cf7SKonstantin Belousov  *	This routine may not sleep.
91526f9a767SRodney W. Grimes  */
916a5edd34aSPoul-Henning Kamp static void
917230869e0SAlan Cox swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
9180d94caffSDavid Greenman {
9198f60c087SPoul-Henning Kamp 	struct swdevt *sp;
92092da00bbSMatthew Dillon 
921230869e0SAlan Cox 	if (npages == 0)
922230869e0SAlan Cox 		return;
9237645e885SAlan Cox 	mtx_lock(&sw_dev_mtx);
9247645e885SAlan Cox 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
925541a1175SAlan Cox 		if (swp_pager_isondev(blk, sp)) {
92692da00bbSMatthew Dillon 			sp->sw_used -= npages;
92792da00bbSMatthew Dillon 			/*
9287645e885SAlan Cox 			 * If we are attempting to stop swapping on
9297645e885SAlan Cox 			 * this device, we don't want to mark any
9307645e885SAlan Cox 			 * blocks free lest they be reused.
93192da00bbSMatthew Dillon 			 */
9327645e885SAlan Cox 			if ((sp->sw_flags & SW_CLOSING) == 0) {
9337645e885SAlan Cox 				blist_free(sp->sw_blist, blk - sp->sw_first,
9347645e885SAlan Cox 				    npages);
9358f60c087SPoul-Henning Kamp 				swap_pager_avail += npages;
9361c7c3c6aSMatthew Dillon 				swp_sizecheck();
93726f9a767SRodney W. Grimes 			}
9387645e885SAlan Cox 			mtx_unlock(&sw_dev_mtx);
9397645e885SAlan Cox 			return;
9407645e885SAlan Cox 		}
9417645e885SAlan Cox 	}
9427645e885SAlan Cox 	panic("Swapdev not found");
9437645e885SAlan Cox }
9441c7c3c6aSMatthew Dillon 
94526f9a767SRodney W. Grimes /*
946d027ed2eSAlan Cox  * SYSCTL_SWAP_FRAGMENTATION() -	produce raw swap space stats
947d027ed2eSAlan Cox  */
948d027ed2eSAlan Cox static int
949d027ed2eSAlan Cox sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
950d027ed2eSAlan Cox {
951d027ed2eSAlan Cox 	struct sbuf sbuf;
952d027ed2eSAlan Cox 	struct swdevt *sp;
953d027ed2eSAlan Cox 	const char *devname;
954d027ed2eSAlan Cox 	int error;
955d027ed2eSAlan Cox 
956d027ed2eSAlan Cox 	error = sysctl_wire_old_buffer(req, 0);
957d027ed2eSAlan Cox 	if (error != 0)
958d027ed2eSAlan Cox 		return (error);
959d027ed2eSAlan Cox 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
960d027ed2eSAlan Cox 	mtx_lock(&sw_dev_mtx);
961d027ed2eSAlan Cox 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
9627ad2a82dSMateusz Guzik 		if (vn_isdisk(sp->sw_vp))
963d027ed2eSAlan Cox 			devname = devtoname(sp->sw_vp->v_rdev);
964d027ed2eSAlan Cox 		else
965d027ed2eSAlan Cox 			devname = "[file]";
966d027ed2eSAlan Cox 		sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
967d027ed2eSAlan Cox 		blist_stats(sp->sw_blist, &sbuf);
968d027ed2eSAlan Cox 	}
969d027ed2eSAlan Cox 	mtx_unlock(&sw_dev_mtx);
970d027ed2eSAlan Cox 	error = sbuf_finish(&sbuf);
971d027ed2eSAlan Cox 	sbuf_delete(&sbuf);
972d027ed2eSAlan Cox 	return (error);
973d027ed2eSAlan Cox }
974d027ed2eSAlan Cox 
975d027ed2eSAlan Cox /*
9761c7c3c6aSMatthew Dillon  * SWAP_PAGER_FREESPACE() -	frees swap blocks associated with a page
9771c7c3c6aSMatthew Dillon  *				range within an object.
9781c7c3c6aSMatthew Dillon  *
9791c7c3c6aSMatthew Dillon  *	This routine removes swapblk assignments from swap metadata.
9801c7c3c6aSMatthew Dillon  *
9811c7c3c6aSMatthew Dillon  *	The external callers of this routine typically have already destroyed
9821c7c3c6aSMatthew Dillon  *	or renamed vm_page_t's associated with this range in the object so
9831c7c3c6aSMatthew Dillon  *	we should be ok.
984c25673ffSAttilio Rao  *
985c25673ffSAttilio Rao  *	The object must be locked.
98626f9a767SRodney W. Grimes  */
9871390a5cbSKonstantin Belousov static void
9882f249180SPoul-Henning Kamp swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
98926f9a767SRodney W. Grimes {
99023955314SAlfred Perlstein 
9911c7c3c6aSMatthew Dillon 	swp_pager_meta_free(object, start, size);
9924dcc5c2dSMatthew Dillon }
9934dcc5c2dSMatthew Dillon 
9944dcc5c2dSMatthew Dillon /*
9954dcc5c2dSMatthew Dillon  * SWAP_PAGER_RESERVE() - reserve swap blocks in object
9964dcc5c2dSMatthew Dillon  *
9974dcc5c2dSMatthew Dillon  *	Assigns swap blocks to the specified range within the object.  The
99856ce850bSKonstantin Belousov  *	swap blocks are not zeroed.  Any previous swap assignment is destroyed.
9994dcc5c2dSMatthew Dillon  *
10004dcc5c2dSMatthew Dillon  *	Returns 0 on success, -1 on failure.
10014dcc5c2dSMatthew Dillon  */
10024dcc5c2dSMatthew Dillon int
10034dcc5c2dSMatthew Dillon swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
10044dcc5c2dSMatthew Dillon {
100548e98a2aSDoug Moore 	daddr_t addr, blk, n_free, s_free;
100648e98a2aSDoug Moore 	int i, j, n;
10074dcc5c2dSMatthew Dillon 
100878f1deefSAlan Cox 	swp_pager_init_freerange(&s_free, &n_free);
100989f6b863SAttilio Rao 	VM_OBJECT_WLOCK(object);
101048e98a2aSDoug Moore 	for (i = 0; i < size; i += n) {
101131c82722SDoug Moore 		n = size - i;
101236b01270SDoug Moore 		blk = swp_pager_getswapspace(&n);
101348e98a2aSDoug Moore 		if (blk == SWAPBLK_NONE) {
101448e98a2aSDoug Moore 			swp_pager_meta_free(object, start, i);
101589f6b863SAttilio Rao 			VM_OBJECT_WUNLOCK(object);
10164dcc5c2dSMatthew Dillon 			return (-1);
10174dcc5c2dSMatthew Dillon 		}
101848e98a2aSDoug Moore 		for (j = 0; j < n; ++j) {
101948e98a2aSDoug Moore 			addr = swp_pager_meta_build(object,
102048e98a2aSDoug Moore 			    start + i + j, blk + j);
102178f1deefSAlan Cox 			if (addr != SWAPBLK_NONE)
102248e98a2aSDoug Moore 				swp_pager_update_freerange(&s_free, &n_free,
102348e98a2aSDoug Moore 				    addr);
102448e98a2aSDoug Moore 		}
10254dcc5c2dSMatthew Dillon 	}
102678f1deefSAlan Cox 	swp_pager_freeswapspace(s_free, n_free);
102789f6b863SAttilio Rao 	VM_OBJECT_WUNLOCK(object);
10284dcc5c2dSMatthew Dillon 	return (0);
102926f9a767SRodney W. Grimes }
103026f9a767SRodney W. Grimes 
1031467057fcSDoug Moore static bool
1032467057fcSDoug Moore swp_pager_xfer_source(vm_object_t srcobject, vm_object_t dstobject,
1033467057fcSDoug Moore     vm_pindex_t pindex, daddr_t addr)
1034467057fcSDoug Moore {
1035467057fcSDoug Moore 	daddr_t dstaddr;
1036467057fcSDoug Moore 
10374b8365d7SKonstantin Belousov 	KASSERT((srcobject->flags & OBJ_SWAP) != 0,
10388ecbf14bSDoug Moore 	    ("%s: Srcobject not swappable", __func__));
10394b8365d7SKonstantin Belousov 	if ((dstobject->flags & OBJ_SWAP) != 0 &&
10408ecbf14bSDoug Moore 	    swp_pager_meta_lookup(dstobject, pindex) != SWAPBLK_NONE) {
1041467057fcSDoug Moore 		/* Caller should destroy the source block. */
1042467057fcSDoug Moore 		return (false);
1043467057fcSDoug Moore 	}
1044467057fcSDoug Moore 
1045467057fcSDoug Moore 	/*
1046467057fcSDoug Moore 	 * Destination has no swapblk and is not resident, transfer source.
1047467057fcSDoug Moore 	 * swp_pager_meta_build() can sleep.
1048467057fcSDoug Moore 	 */
1049467057fcSDoug Moore 	VM_OBJECT_WUNLOCK(srcobject);
1050467057fcSDoug Moore 	dstaddr = swp_pager_meta_build(dstobject, pindex, addr);
1051467057fcSDoug Moore 	KASSERT(dstaddr == SWAPBLK_NONE,
1052467057fcSDoug Moore 	    ("Unexpected destination swapblk"));
1053467057fcSDoug Moore 	VM_OBJECT_WLOCK(srcobject);
105498087a06SJeff Roberson 
1055467057fcSDoug Moore 	return (true);
1056467057fcSDoug Moore }
1057467057fcSDoug Moore 
10580a47b48bSJohn Dyson /*
10591c7c3c6aSMatthew Dillon  * SWAP_PAGER_COPY() -  copy blocks from source pager to destination pager
10601c7c3c6aSMatthew Dillon  *			and destroy the source.
10611c7c3c6aSMatthew Dillon  *
10621c7c3c6aSMatthew Dillon  *	Copy any valid swapblks from the source to the destination.  In
10631c7c3c6aSMatthew Dillon  *	cases where both the source and destination have a valid swapblk,
10641c7c3c6aSMatthew Dillon  *	we keep the destination's.
10651c7c3c6aSMatthew Dillon  *
106615523cf7SKonstantin Belousov  *	This routine is allowed to sleep.  It may sleep allocating metadata
106798087a06SJeff Roberson  *	indirectly through swp_pager_meta_build().
10681c7c3c6aSMatthew Dillon  *
10691c7c3c6aSMatthew Dillon  *	The source object contains no vm_page_t's (which is just as well)
10701c7c3c6aSMatthew Dillon  *
10711c7c3c6aSMatthew Dillon  *	The source object is of type OBJT_SWAP.
10721c7c3c6aSMatthew Dillon  *
107315523cf7SKonstantin Belousov  *	The source and destination objects must be locked.
107415523cf7SKonstantin Belousov  *	Both object locks may temporarily be released.
107526f9a767SRodney W. Grimes  */
107626f9a767SRodney W. Grimes void
10772f249180SPoul-Henning Kamp swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
10782f249180SPoul-Henning Kamp     vm_pindex_t offset, int destroysource)
107926f9a767SRodney W. Grimes {
10804dcc5c2dSMatthew Dillon 
108189f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(srcobject);
108289f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(dstobject);
10830cddd8f0SMatthew Dillon 
108426f9a767SRodney W. Grimes 	/*
10851c7c3c6aSMatthew Dillon 	 * If destroysource is set, we remove the source object from the
10861c7c3c6aSMatthew Dillon 	 * swap_pager internal queue now.
108726f9a767SRodney W. Grimes 	 */
108867388836SKonstantin Belousov 	if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
108967388836SKonstantin Belousov 	    srcobject->handle != NULL) {
1090eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WUNLOCK(srcobject);
1091eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WUNLOCK(dstobject);
1092eb4d6a1bSKonstantin Belousov 		sx_xlock(&sw_alloc_sx);
1093eb4d6a1bSKonstantin Belousov 		TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1094eb4d6a1bSKonstantin Belousov 		    pager_object_list);
1095eb4d6a1bSKonstantin Belousov 		sx_xunlock(&sw_alloc_sx);
1096eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WLOCK(dstobject);
1097eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WLOCK(srcobject);
1098bd228075SAlan Cox 	}
109926f9a767SRodney W. Grimes 
11001c7c3c6aSMatthew Dillon 	/*
11014abca9bbSAlan Cox 	 * Transfer source to destination.
11021c7c3c6aSMatthew Dillon 	 */
1103467057fcSDoug Moore 	swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size);
110426f9a767SRodney W. Grimes 
110526f9a767SRodney W. Grimes 	/*
11061c7c3c6aSMatthew Dillon 	 * Free left over swap blocks in source.
11071c7c3c6aSMatthew Dillon 	 *
1108763df3ecSPedro F. Giffuni 	 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
11091c7c3c6aSMatthew Dillon 	 * double-remove the object from the swap queues.
111026f9a767SRodney W. Grimes 	 */
1111c0877f10SJohn Dyson 	if (destroysource) {
11121c7c3c6aSMatthew Dillon 		swp_pager_meta_free_all(srcobject);
11131c7c3c6aSMatthew Dillon 		/*
11141c7c3c6aSMatthew Dillon 		 * Reverting the type is not necessary, the caller is going
11151c7c3c6aSMatthew Dillon 		 * to destroy srcobject directly, but I'm doing it here
1116956f3135SPhilippe Charnier 		 * for consistency since we've removed the object from its
11171c7c3c6aSMatthew Dillon 		 * queues.
11181c7c3c6aSMatthew Dillon 		 */
11191c7c3c6aSMatthew Dillon 		srcobject->type = OBJT_DEFAULT;
11204b8365d7SKonstantin Belousov 		vm_object_clear_flag(srcobject, OBJ_SWAP);
1121c0877f10SJohn Dyson 	}
112226f9a767SRodney W. Grimes }
112326f9a767SRodney W. Grimes 
1124df8bae1dSRodney W. Grimes /*
11251c7c3c6aSMatthew Dillon  * SWAP_PAGER_HASPAGE() -	determine if we have good backing store for
11261c7c3c6aSMatthew Dillon  *				the requested page.
11271c7c3c6aSMatthew Dillon  *
11281c7c3c6aSMatthew Dillon  *	We determine whether good backing store exists for the requested
11291c7c3c6aSMatthew Dillon  *	page and return TRUE if it does, FALSE if it doesn't.
11301c7c3c6aSMatthew Dillon  *
11311c7c3c6aSMatthew Dillon  *	If TRUE, we also try to determine how much valid, contiguous backing
1132915d1b71SMark Johnston  *	store exists before and after the requested page.
1133df8bae1dSRodney W. Grimes  */
11345ea4972cSAlan Cox static boolean_t
1135915d1b71SMark Johnston swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1136915d1b71SMark Johnston     int *after)
113726f9a767SRodney W. Grimes {
1138915d1b71SMark Johnston 	daddr_t blk, blk0;
1139915d1b71SMark Johnston 	int i;
114026f9a767SRodney W. Grimes 
1141c25673ffSAttilio Rao 	VM_OBJECT_ASSERT_LOCKED(object);
11424b8365d7SKonstantin Belousov 	KASSERT((object->flags & OBJ_SWAP) != 0,
11438ecbf14bSDoug Moore 	    ("%s: object not swappable", __func__));
1144915d1b71SMark Johnston 
11451c7c3c6aSMatthew Dillon 	/*
11461c7c3c6aSMatthew Dillon 	 * do we have good backing store at the requested index ?
11471c7c3c6aSMatthew Dillon 	 */
11488ecbf14bSDoug Moore 	blk0 = swp_pager_meta_lookup(object, pindex);
11494dcc5c2dSMatthew Dillon 	if (blk0 == SWAPBLK_NONE) {
11501c7c3c6aSMatthew Dillon 		if (before)
115124a1cce3SDavid Greenman 			*before = 0;
11521c7c3c6aSMatthew Dillon 		if (after)
115324a1cce3SDavid Greenman 			*after = 0;
115426f9a767SRodney W. Grimes 		return (FALSE);
115526f9a767SRodney W. Grimes 	}
115626f9a767SRodney W. Grimes 
115726f9a767SRodney W. Grimes 	/*
11581c7c3c6aSMatthew Dillon 	 * find backwards-looking contiguous good backing store
1159e47ed70bSJohn Dyson 	 */
11601c7c3c6aSMatthew Dillon 	if (before != NULL) {
1161915d1b71SMark Johnston 		for (i = 1; i < SWB_NPAGES; i++) {
11621c7c3c6aSMatthew Dillon 			if (i > pindex)
11631c7c3c6aSMatthew Dillon 				break;
11648ecbf14bSDoug Moore 			blk = swp_pager_meta_lookup(object, pindex - i);
11651c7c3c6aSMatthew Dillon 			if (blk != blk0 - i)
11661c7c3c6aSMatthew Dillon 				break;
1167ffc82b0aSJohn Dyson 		}
1168915d1b71SMark Johnston 		*before = i - 1;
116926f9a767SRodney W. Grimes 	}
117026f9a767SRodney W. Grimes 
117126f9a767SRodney W. Grimes 	/*
11721c7c3c6aSMatthew Dillon 	 * find forward-looking contiguous good backing store
117326f9a767SRodney W. Grimes 	 */
11741c7c3c6aSMatthew Dillon 	if (after != NULL) {
1175915d1b71SMark Johnston 		for (i = 1; i < SWB_NPAGES; i++) {
11768ecbf14bSDoug Moore 			blk = swp_pager_meta_lookup(object, pindex + i);
11771c7c3c6aSMatthew Dillon 			if (blk != blk0 + i)
11781c7c3c6aSMatthew Dillon 				break;
117926f9a767SRodney W. Grimes 		}
1180915d1b71SMark Johnston 		*after = i - 1;
11811c7c3c6aSMatthew Dillon 	}
11821c7c3c6aSMatthew Dillon 	return (TRUE);
11831c7c3c6aSMatthew Dillon }
11841c7c3c6aSMatthew Dillon 
11851c7c3c6aSMatthew Dillon /*
11861c7c3c6aSMatthew Dillon  * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
11871c7c3c6aSMatthew Dillon  *
11881c7c3c6aSMatthew Dillon  *	This removes any associated swap backing store, whether valid or
11891c7c3c6aSMatthew Dillon  *	not, from the page.
11901c7c3c6aSMatthew Dillon  *
11911c7c3c6aSMatthew Dillon  *	This routine is typically called when a page is made dirty, at
11921c7c3c6aSMatthew Dillon  *	which point any associated swap can be freed.  MADV_FREE also
11931c7c3c6aSMatthew Dillon  *	calls us in a special-case situation
11941c7c3c6aSMatthew Dillon  *
11951c7c3c6aSMatthew Dillon  *	NOTE!!!  If the page is clean and the swap was valid, the caller
11961c7c3c6aSMatthew Dillon  *	should make the page dirty before calling this routine.  This routine
11971c7c3c6aSMatthew Dillon  *	does NOT change the m->dirty status of the page.  Also: MADV_FREE
11981c7c3c6aSMatthew Dillon  *	depends on it.
11991c7c3c6aSMatthew Dillon  *
120015523cf7SKonstantin Belousov  *	This routine may not sleep.
1201c25673ffSAttilio Rao  *
1202a8081778SJeff Roberson  *	The object containing the page may be locked.
12031c7c3c6aSMatthew Dillon  */
12041c7c3c6aSMatthew Dillon static void
12052f249180SPoul-Henning Kamp swap_pager_unswapped(vm_page_t m)
12061c7c3c6aSMatthew Dillon {
12078ecbf14bSDoug Moore 	struct swblk *sb;
1208a8081778SJeff Roberson 	vm_object_t obj;
12092f249180SPoul-Henning Kamp 
1210a8081778SJeff Roberson 	/*
1211a8081778SJeff Roberson 	 * Handle enqueing deferred frees first.  If we do not have the
1212a8081778SJeff Roberson 	 * object lock we wait for the page daemon to clear the space.
1213a8081778SJeff Roberson 	 */
1214a8081778SJeff Roberson 	obj = m->object;
1215a8081778SJeff Roberson 	if (!VM_OBJECT_WOWNED(obj)) {
1216a8081778SJeff Roberson 		VM_PAGE_OBJECT_BUSY_ASSERT(m);
1217a8081778SJeff Roberson 		/*
1218a8081778SJeff Roberson 		 * The caller is responsible for synchronization but we
1219a8081778SJeff Roberson 		 * will harmlessly handle races.  This is typically provided
1220a8081778SJeff Roberson 		 * by only calling unswapped() when a page transitions from
1221a8081778SJeff Roberson 		 * clean to dirty.
1222a8081778SJeff Roberson 		 */
1223a8081778SJeff Roberson 		if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1224a8081778SJeff Roberson 		    PGA_SWAP_SPACE) {
1225a8081778SJeff Roberson 			vm_page_aflag_set(m, PGA_SWAP_FREE);
1226a8081778SJeff Roberson 			counter_u64_add(swap_free_deferred, 1);
1227a8081778SJeff Roberson 		}
1228a8081778SJeff Roberson 		return;
1229a8081778SJeff Roberson 	}
1230a8081778SJeff Roberson 	if ((m->a.flags & PGA_SWAP_FREE) != 0)
1231a8081778SJeff Roberson 		counter_u64_add(swap_free_completed, 1);
1232a8081778SJeff Roberson 	vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
12338ecbf14bSDoug Moore 
12348ecbf14bSDoug Moore 	/*
12358ecbf14bSDoug Moore 	 * The meta data only exists if the object is OBJT_SWAP
12368ecbf14bSDoug Moore 	 * and even then might not be allocated yet.
12378ecbf14bSDoug Moore 	 */
12384b8365d7SKonstantin Belousov 	KASSERT((m->object->flags & OBJ_SWAP) != 0,
12398ecbf14bSDoug Moore 	    ("Free object not swappable"));
12408ecbf14bSDoug Moore 
12418ecbf14bSDoug Moore 	sb = SWAP_PCTRIE_LOOKUP(&m->object->un_pager.swp.swp_blks,
12428ecbf14bSDoug Moore 	    rounddown(m->pindex, SWAP_META_PAGES));
12438ecbf14bSDoug Moore 	if (sb == NULL)
12448ecbf14bSDoug Moore 		return;
12458ecbf14bSDoug Moore 	if (sb->d[m->pindex % SWAP_META_PAGES] == SWAPBLK_NONE)
12468ecbf14bSDoug Moore 		return;
12478ecbf14bSDoug Moore 	swp_pager_freeswapspace(sb->d[m->pindex % SWAP_META_PAGES], 1);
12488ecbf14bSDoug Moore 	sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
12498ecbf14bSDoug Moore 	swp_pager_free_empty_swblk(m->object, sb);
12501c7c3c6aSMatthew Dillon }
12511c7c3c6aSMatthew Dillon 
12521c7c3c6aSMatthew Dillon /*
1253915d1b71SMark Johnston  * swap_pager_getpages() - bring pages in from swap
12541c7c3c6aSMatthew Dillon  *
12553f060b60SMark Johnston  *	Attempt to page in the pages in array "ma" of length "count".  The
12563f060b60SMark Johnston  *	caller may optionally specify that additional pages preceding and
12573f060b60SMark Johnston  *	succeeding the specified range be paged in.  The number of such pages
12583f060b60SMark Johnston  *	is returned in the "rbehind" and "rahead" parameters, and they will
12593f060b60SMark Johnston  *	be in the inactive queue upon return.
12601c7c3c6aSMatthew Dillon  *
12613f060b60SMark Johnston  *	The pages in "ma" must be busied and will remain busied upon return.
12621c7c3c6aSMatthew Dillon  */
1263f708ef1bSPoul-Henning Kamp static int
1264c90d075bSMark Johnston swap_pager_getpages_locked(vm_object_t object, vm_page_t *ma, int count,
1265c90d075bSMark Johnston     int *rbehind, int *rahead)
1266df8bae1dSRodney W. Grimes {
12671c7c3c6aSMatthew Dillon 	struct buf *bp;
1268b7b8a096SKonstantin Belousov 	vm_page_t bm, mpred, msucc, p;
1269915d1b71SMark Johnston 	vm_pindex_t pindex;
12701c7c3c6aSMatthew Dillon 	daddr_t blk;
1271b7b8a096SKonstantin Belousov 	int i, maxahead, maxbehind, reqcount;
12720d94caffSDavid Greenman 
1273c90d075bSMark Johnston 	VM_OBJECT_ASSERT_WLOCKED(object);
1274915d1b71SMark Johnston 	reqcount = count;
12751c7c3c6aSMatthew Dillon 
12764b8365d7SKonstantin Belousov 	KASSERT((object->flags & OBJ_SWAP) != 0,
12778ecbf14bSDoug Moore 	    ("%s: object not swappable", __func__));
1278d6e13f3bSJeff Roberson 	if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead)) {
1279d6e13f3bSJeff Roberson 		VM_OBJECT_WUNLOCK(object);
1280915d1b71SMark Johnston 		return (VM_PAGER_FAIL);
1281d6e13f3bSJeff Roberson 	}
1282915d1b71SMark Johnston 
128398087a06SJeff Roberson 	KASSERT(reqcount - 1 <= maxahead,
128498087a06SJeff Roberson 	    ("page count %d extends beyond swap block", reqcount));
128598087a06SJeff Roberson 
128698087a06SJeff Roberson 	/*
128798087a06SJeff Roberson 	 * Do not transfer any pages other than those that are xbusied
128898087a06SJeff Roberson 	 * when running during a split or collapse operation.  This
128998087a06SJeff Roberson 	 * prevents clustering from re-creating pages which are being
129098087a06SJeff Roberson 	 * moved into another object.
129198087a06SJeff Roberson 	 */
129298087a06SJeff Roberson 	if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
129398087a06SJeff Roberson 		maxahead = reqcount - 1;
129498087a06SJeff Roberson 		maxbehind = 0;
129598087a06SJeff Roberson 	}
129698087a06SJeff Roberson 
1297915d1b71SMark Johnston 	/*
1298915d1b71SMark Johnston 	 * Clip the readahead and readbehind ranges to exclude resident pages.
1299915d1b71SMark Johnston 	 */
1300915d1b71SMark Johnston 	if (rahead != NULL) {
1301dd9cb6daSMark Johnston 		*rahead = imin(*rahead, maxahead - (reqcount - 1));
13023f060b60SMark Johnston 		pindex = ma[reqcount - 1]->pindex;
13033f060b60SMark Johnston 		msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1304915d1b71SMark Johnston 		if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1305915d1b71SMark Johnston 			*rahead = msucc->pindex - pindex - 1;
1306915d1b71SMark Johnston 	}
1307915d1b71SMark Johnston 	if (rbehind != NULL) {
1308dd9cb6daSMark Johnston 		*rbehind = imin(*rbehind, maxbehind);
13093f060b60SMark Johnston 		pindex = ma[0]->pindex;
13103f060b60SMark Johnston 		mpred = TAILQ_PREV(ma[0], pglist, listq);
1311915d1b71SMark Johnston 		if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1312915d1b71SMark Johnston 			*rbehind = pindex - mpred->pindex - 1;
1313915d1b71SMark Johnston 	}
1314915d1b71SMark Johnston 
1315b7b8a096SKonstantin Belousov 	bm = ma[0];
1316b7b8a096SKonstantin Belousov 	for (i = 0; i < count; i++)
1317b7b8a096SKonstantin Belousov 		ma[i]->oflags |= VPO_SWAPINPROG;
1318b7b8a096SKonstantin Belousov 
1319915d1b71SMark Johnston 	/*
1320915d1b71SMark Johnston 	 * Allocate readahead and readbehind pages.
1321915d1b71SMark Johnston 	 */
1322b7b8a096SKonstantin Belousov 	if (rbehind != NULL) {
1323b7b8a096SKonstantin Belousov 		for (i = 1; i <= *rbehind; i++) {
13243f060b60SMark Johnston 			p = vm_page_alloc(object, ma[0]->pindex - i,
13257667839aSAlan Cox 			    VM_ALLOC_NORMAL);
1326b7b8a096SKonstantin Belousov 			if (p == NULL)
1327915d1b71SMark Johnston 				break;
1328b7b8a096SKonstantin Belousov 			p->oflags |= VPO_SWAPINPROG;
1329b7b8a096SKonstantin Belousov 			bm = p;
1330915d1b71SMark Johnston 		}
1331b7b8a096SKonstantin Belousov 		*rbehind = i - 1;
1332915d1b71SMark Johnston 	}
1333915d1b71SMark Johnston 	if (rahead != NULL) {
1334915d1b71SMark Johnston 		for (i = 0; i < *rahead; i++) {
1335915d1b71SMark Johnston 			p = vm_page_alloc(object,
13363f060b60SMark Johnston 			    ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1337915d1b71SMark Johnston 			if (p == NULL)
1338915d1b71SMark Johnston 				break;
1339b7b8a096SKonstantin Belousov 			p->oflags |= VPO_SWAPINPROG;
1340915d1b71SMark Johnston 		}
1341915d1b71SMark Johnston 		*rahead = i;
1342915d1b71SMark Johnston 	}
1343915d1b71SMark Johnston 	if (rbehind != NULL)
1344915d1b71SMark Johnston 		count += *rbehind;
1345915d1b71SMark Johnston 	if (rahead != NULL)
1346915d1b71SMark Johnston 		count += *rahead;
1347915d1b71SMark Johnston 
1348915d1b71SMark Johnston 	vm_object_pip_add(object, count);
1349915d1b71SMark Johnston 
1350b7b8a096SKonstantin Belousov 	pindex = bm->pindex;
13518ecbf14bSDoug Moore 	blk = swp_pager_meta_lookup(object, pindex);
1352915d1b71SMark Johnston 	KASSERT(blk != SWAPBLK_NONE,
1353915d1b71SMark Johnston 	    ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1354915d1b71SMark Johnston 
1355915d1b71SMark Johnston 	VM_OBJECT_WUNLOCK(object);
1356756a5412SGleb Smirnoff 	bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1357cd853791SKonstantin Belousov 	MPASS((bp->b_flags & B_MAXPHYS) != 0);
1358b7b8a096SKonstantin Belousov 	/* Pages cannot leave the object while busy. */
1359b7b8a096SKonstantin Belousov 	for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1360b7b8a096SKonstantin Belousov 		MPASS(p->pindex == bm->pindex + i);
1361b7b8a096SKonstantin Belousov 		bp->b_pages[i] = p;
1362b7b8a096SKonstantin Belousov 	}
1363915d1b71SMark Johnston 
1364915d1b71SMark Johnston 	bp->b_flags |= B_PAGING;
136521144e3bSPoul-Henning Kamp 	bp->b_iocmd = BIO_READ;
13661c7c3c6aSMatthew Dillon 	bp->b_iodone = swp_pager_async_iodone;
1367fdcc1cc0SJohn Baldwin 	bp->b_rcred = crhold(thread0.td_ucred);
1368fdcc1cc0SJohn Baldwin 	bp->b_wcred = crhold(thread0.td_ucred);
1369b0cd2017SGleb Smirnoff 	bp->b_blkno = blk;
1370b0cd2017SGleb Smirnoff 	bp->b_bcount = PAGE_SIZE * count;
1371b0cd2017SGleb Smirnoff 	bp->b_bufsize = PAGE_SIZE * count;
1372b0cd2017SGleb Smirnoff 	bp->b_npages = count;
1373915d1b71SMark Johnston 	bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1374915d1b71SMark Johnston 	bp->b_pgafter = rahead != NULL ? *rahead : 0;
137526f9a767SRodney W. Grimes 
137683c9dea1SGleb Smirnoff 	VM_CNT_INC(v_swapin);
137783c9dea1SGleb Smirnoff 	VM_CNT_ADD(v_swappgsin, count);
13781c7c3c6aSMatthew Dillon 
13791c7c3c6aSMatthew Dillon 	/*
13801c7c3c6aSMatthew Dillon 	 * perform the I/O.  NOTE!!!  bp cannot be considered valid after
13811c7c3c6aSMatthew Dillon 	 * this point because we automatically release it on completion.
13821c7c3c6aSMatthew Dillon 	 * Instead, we look at the one page we are interested in which we
13831c7c3c6aSMatthew Dillon 	 * still hold a lock on even through the I/O completion.
13841c7c3c6aSMatthew Dillon 	 *
13853f060b60SMark Johnston 	 * The other pages in our ma[] array are also released on completion,
13861c7c3c6aSMatthew Dillon 	 * so we cannot assume they are valid anymore either.
13871c7c3c6aSMatthew Dillon 	 *
1388c37a77eeSPoul-Henning Kamp 	 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
13891c7c3c6aSMatthew Dillon 	 */
1390b890cb2cSPeter Wemm 	BUF_KERNPROC(bp);
13914b03903aSPoul-Henning Kamp 	swp_pager_strategy(bp);
139226f9a767SRodney W. Grimes 
139326f9a767SRodney W. Grimes 	/*
1394915d1b71SMark Johnston 	 * Wait for the pages we want to complete.  VPO_SWAPINPROG is always
13951c7c3c6aSMatthew Dillon 	 * cleared on completion.  If an I/O error occurs, SWAPBLK_NONE
1396915d1b71SMark Johnston 	 * is set in the metadata for each page in the request.
139726f9a767SRodney W. Grimes 	 */
139889f6b863SAttilio Rao 	VM_OBJECT_WLOCK(object);
1399d6e13f3bSJeff Roberson 	/* This could be implemented more efficiently with aflags */
14003f060b60SMark Johnston 	while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
14013f060b60SMark Johnston 		ma[0]->oflags |= VPO_SWAPSLEEP;
140283c9dea1SGleb Smirnoff 		VM_CNT_INC(v_intrans);
1403cf27e0d1SJeff Roberson 		if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1404c7aebda8SAttilio Rao 		    "swread", hz * 20)) {
14059bd86a98SBruce M Simpson 			printf(
1406c5690651SPoul-Henning Kamp "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1407c5690651SPoul-Henning Kamp 			    bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
14081c7c3c6aSMatthew Dillon 		}
14091b119d9dSDavid Greenman 	}
1410d6e13f3bSJeff Roberson 	VM_OBJECT_WUNLOCK(object);
141126f9a767SRodney W. Grimes 
141226f9a767SRodney W. Grimes 	/*
1413b0cd2017SGleb Smirnoff 	 * If we had an unrecoverable read error pages will not be valid.
141426f9a767SRodney W. Grimes 	 */
1415915d1b71SMark Johnston 	for (i = 0; i < reqcount; i++)
14163f060b60SMark Johnston 		if (ma[i]->valid != VM_PAGE_BITS_ALL)
14171c7c3c6aSMatthew Dillon 			return (VM_PAGER_ERROR);
1418b0cd2017SGleb Smirnoff 
14191c7c3c6aSMatthew Dillon 	return (VM_PAGER_OK);
14201c7c3c6aSMatthew Dillon 
14211c7c3c6aSMatthew Dillon 	/*
14221c7c3c6aSMatthew Dillon 	 * A final note: in a low swap situation, we cannot deallocate swap
14231c7c3c6aSMatthew Dillon 	 * and mark a page dirty here because the caller is likely to mark
14241c7c3c6aSMatthew Dillon 	 * the page clean when we return, causing the page to possibly revert
14251c7c3c6aSMatthew Dillon 	 * to all-zero's later.
14261c7c3c6aSMatthew Dillon 	 */
1427df8bae1dSRodney W. Grimes }
1428df8bae1dSRodney W. Grimes 
1429c90d075bSMark Johnston static int
1430c90d075bSMark Johnston swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count,
1431c90d075bSMark Johnston     int *rbehind, int *rahead)
1432c90d075bSMark Johnston {
1433c90d075bSMark Johnston 
1434c90d075bSMark Johnston 	VM_OBJECT_WLOCK(object);
1435c90d075bSMark Johnston 	return (swap_pager_getpages_locked(object, ma, count, rbehind, rahead));
1436c90d075bSMark Johnston }
1437c90d075bSMark Johnston 
14381c7c3c6aSMatthew Dillon /*
143990effb23SGleb Smirnoff  * 	swap_pager_getpages_async():
144090effb23SGleb Smirnoff  *
144190effb23SGleb Smirnoff  *	Right now this is emulation of asynchronous operation on top of
144290effb23SGleb Smirnoff  *	swap_pager_getpages().
144390effb23SGleb Smirnoff  */
144490effb23SGleb Smirnoff static int
14453f060b60SMark Johnston swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1446b0cd2017SGleb Smirnoff     int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
144790effb23SGleb Smirnoff {
144890effb23SGleb Smirnoff 	int r, error;
144990effb23SGleb Smirnoff 
14503f060b60SMark Johnston 	r = swap_pager_getpages(object, ma, count, rbehind, rahead);
145190effb23SGleb Smirnoff 	switch (r) {
145290effb23SGleb Smirnoff 	case VM_PAGER_OK:
145390effb23SGleb Smirnoff 		error = 0;
145490effb23SGleb Smirnoff 		break;
145590effb23SGleb Smirnoff 	case VM_PAGER_ERROR:
145690effb23SGleb Smirnoff 		error = EIO;
145790effb23SGleb Smirnoff 		break;
145890effb23SGleb Smirnoff 	case VM_PAGER_FAIL:
145990effb23SGleb Smirnoff 		error = EINVAL;
146090effb23SGleb Smirnoff 		break;
146190effb23SGleb Smirnoff 	default:
1462d9328101SGleb Smirnoff 		panic("unhandled swap_pager_getpages() error %d", r);
146390effb23SGleb Smirnoff 	}
14643f060b60SMark Johnston 	(iodone)(arg, ma, count, error);
146590effb23SGleb Smirnoff 
146690effb23SGleb Smirnoff 	return (r);
146790effb23SGleb Smirnoff }
146890effb23SGleb Smirnoff 
146990effb23SGleb Smirnoff /*
14701c7c3c6aSMatthew Dillon  *	swap_pager_putpages:
14711c7c3c6aSMatthew Dillon  *
14721c7c3c6aSMatthew Dillon  *	Assign swap (if necessary) and initiate I/O on the specified pages.
14731c7c3c6aSMatthew Dillon  *
14741c7c3c6aSMatthew Dillon  *	We support both OBJT_DEFAULT and OBJT_SWAP objects.  DEFAULT objects
14751c7c3c6aSMatthew Dillon  *	are automatically converted to SWAP objects.
14761c7c3c6aSMatthew Dillon  *
1477ea3aecf5SPeter Wemm  *	In a low memory situation we may block in VOP_STRATEGY(), but the new
14781c7c3c6aSMatthew Dillon  *	vm_page reservation system coupled with properly written VFS devices
14791c7c3c6aSMatthew Dillon  *	should ensure that no low-memory deadlock occurs.  This is an area
14801c7c3c6aSMatthew Dillon  *	which needs work.
14811c7c3c6aSMatthew Dillon  *
14821c7c3c6aSMatthew Dillon  *	The parent has N vm_object_pip_add() references prior to
14831c7c3c6aSMatthew Dillon  *	calling us and will remove references for rtvals[] that are
14841c7c3c6aSMatthew Dillon  *	not set to VM_PAGER_PEND.  We need to remove the rest on I/O
14851c7c3c6aSMatthew Dillon  *	completion.
14861c7c3c6aSMatthew Dillon  *
14871c7c3c6aSMatthew Dillon  *	The parent has soft-busy'd the pages it passes us and will unbusy
148823612f0dSDoug Moore  *	those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
14891c7c3c6aSMatthew Dillon  *	We need to unbusy the rest on I/O completion.
14901c7c3c6aSMatthew Dillon  */
1491d635a37fSWarner Losh static void
14923f060b60SMark Johnston swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1493e065e87cSKonstantin Belousov     int flags, int *rtvals)
1494df8bae1dSRodney W. Grimes {
149523612f0dSDoug Moore 	struct buf *bp;
149623612f0dSDoug Moore 	daddr_t addr, blk, n_free, s_free;
149723612f0dSDoug Moore 	vm_page_t mreq;
149823612f0dSDoug Moore 	int i, j, n;
149923612f0dSDoug Moore 	bool async;
1500df8bae1dSRodney W. Grimes 
150123612f0dSDoug Moore 	KASSERT(count == 0 || ma[0]->object == object,
150223612f0dSDoug Moore 	    ("%s: object mismatch %p/%p",
150323612f0dSDoug Moore 	    __func__, object, ma[0]->object));
1504ee3dc7d7SAlan Cox 
15051c7c3c6aSMatthew Dillon 	/*
15061c7c3c6aSMatthew Dillon 	 * Step 1
15071c7c3c6aSMatthew Dillon 	 *
150823612f0dSDoug Moore 	 * Turn object into OBJT_SWAP.  Force sync if not a pageout process.
15091c7c3c6aSMatthew Dillon 	 */
15104b8365d7SKonstantin Belousov 	if ((object->flags & OBJ_SWAP) == 0) {
151178f1deefSAlan Cox 		addr = swp_pager_meta_build(object, 0, SWAPBLK_NONE);
151278f1deefSAlan Cox 		KASSERT(addr == SWAPBLK_NONE,
151378f1deefSAlan Cox 		    ("unexpected object swap block"));
151478f1deefSAlan Cox 	}
151589f6b863SAttilio Rao 	VM_OBJECT_WUNLOCK(object);
151623612f0dSDoug Moore 	async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
151723612f0dSDoug Moore 	swp_pager_init_freerange(&s_free, &n_free);
151826f9a767SRodney W. Grimes 
15191c7c3c6aSMatthew Dillon 	/*
15201c7c3c6aSMatthew Dillon 	 * Step 2
15211c7c3c6aSMatthew Dillon 	 *
15221c7c3c6aSMatthew Dillon 	 * Assign swap blocks and issue I/O.  We reallocate swap on the fly.
15231c7c3c6aSMatthew Dillon 	 * The page is left dirty until the pageout operation completes
15241c7c3c6aSMatthew Dillon 	 * successfully.
15251c7c3c6aSMatthew Dillon 	 */
15261c7c3c6aSMatthew Dillon 	for (i = 0; i < count; i += n) {
152731c82722SDoug Moore 		/* Maximum I/O size is limited by maximum swap block size. */
152831c82722SDoug Moore 		n = min(count - i, nsw_cluster_max);
15291c7c3c6aSMatthew Dillon 
153023612f0dSDoug Moore 		if (async) {
1531756a5412SGleb Smirnoff 			mtx_lock(&swbuf_mtx);
1532756a5412SGleb Smirnoff 			while (nsw_wcount_async == 0)
1533756a5412SGleb Smirnoff 				msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1534756a5412SGleb Smirnoff 				    "swbufa", 0);
1535756a5412SGleb Smirnoff 			nsw_wcount_async--;
1536756a5412SGleb Smirnoff 			mtx_unlock(&swbuf_mtx);
1537327f4e83SMatthew Dillon 		}
1538725b4ff0SMark Johnston 
1539725b4ff0SMark Johnston 		/* Get a block of swap of size up to size n. */
1540725b4ff0SMark Johnston 		VM_OBJECT_WLOCK(object);
154136b01270SDoug Moore 		blk = swp_pager_getswapspace(&n);
1542725b4ff0SMark Johnston 		if (blk == SWAPBLK_NONE) {
1543725b4ff0SMark Johnston 			VM_OBJECT_WUNLOCK(object);
1544725b4ff0SMark Johnston 			mtx_lock(&swbuf_mtx);
1545725b4ff0SMark Johnston 			if (++nsw_wcount_async == 1)
1546725b4ff0SMark Johnston 				wakeup(&nsw_wcount_async);
1547725b4ff0SMark Johnston 			mtx_unlock(&swbuf_mtx);
1548725b4ff0SMark Johnston 			for (j = 0; j < n; ++j)
1549725b4ff0SMark Johnston 				rtvals[i + j] = VM_PAGER_FAIL;
1550725b4ff0SMark Johnston 			continue;
1551725b4ff0SMark Johnston 		}
1552725b4ff0SMark Johnston 		for (j = 0; j < n; ++j) {
1553725b4ff0SMark Johnston 			mreq = ma[i + j];
1554725b4ff0SMark Johnston 			vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1555725b4ff0SMark Johnston 			addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1556725b4ff0SMark Johnston 			    blk + j);
1557725b4ff0SMark Johnston 			if (addr != SWAPBLK_NONE)
1558725b4ff0SMark Johnston 				swp_pager_update_freerange(&s_free, &n_free,
1559725b4ff0SMark Johnston 				    addr);
1560725b4ff0SMark Johnston 			MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1561725b4ff0SMark Johnston 			mreq->oflags |= VPO_SWAPINPROG;
1562725b4ff0SMark Johnston 		}
1563725b4ff0SMark Johnston 		VM_OBJECT_WUNLOCK(object);
1564725b4ff0SMark Johnston 
1565756a5412SGleb Smirnoff 		bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1566cd853791SKonstantin Belousov 		MPASS((bp->b_flags & B_MAXPHYS) != 0);
156723612f0dSDoug Moore 		if (async)
1568cd853791SKonstantin Belousov 			bp->b_flags |= B_ASYNC;
15695e04322aSPoul-Henning Kamp 		bp->b_flags |= B_PAGING;
1570912e4ae9SPoul-Henning Kamp 		bp->b_iocmd = BIO_WRITE;
157126f9a767SRodney W. Grimes 
1572fdcc1cc0SJohn Baldwin 		bp->b_rcred = crhold(thread0.td_ucred);
1573fdcc1cc0SJohn Baldwin 		bp->b_wcred = crhold(thread0.td_ucred);
15741c7c3c6aSMatthew Dillon 		bp->b_bcount = PAGE_SIZE * n;
15751c7c3c6aSMatthew Dillon 		bp->b_bufsize = PAGE_SIZE * n;
15761c7c3c6aSMatthew Dillon 		bp->b_blkno = blk;
1577725b4ff0SMark Johnston 		for (j = 0; j < n; j++)
1578725b4ff0SMark Johnston 			bp->b_pages[j] = ma[i + j];
15791c7c3c6aSMatthew Dillon 		bp->b_npages = n;
1580725b4ff0SMark Johnston 
1581a5296b05SJulian Elischer 		/*
1582a5296b05SJulian Elischer 		 * Must set dirty range for NFS to work.
1583a5296b05SJulian Elischer 		 */
1584a5296b05SJulian Elischer 		bp->b_dirtyoff = 0;
1585a5296b05SJulian Elischer 		bp->b_dirtyend = bp->b_bcount;
15861c7c3c6aSMatthew Dillon 
158783c9dea1SGleb Smirnoff 		VM_CNT_INC(v_swapout);
158883c9dea1SGleb Smirnoff 		VM_CNT_ADD(v_swappgsout, bp->b_npages);
158926f9a767SRodney W. Grimes 
159026f9a767SRodney W. Grimes 		/*
159177923df2SAlan Cox 		 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
159277923df2SAlan Cox 		 * can call the async completion routine at the end of a
159377923df2SAlan Cox 		 * synchronous I/O operation.  Otherwise, our caller would
159477923df2SAlan Cox 		 * perform duplicate unbusy and wakeup operations on the page
159577923df2SAlan Cox 		 * and object, respectively.
159677923df2SAlan Cox 		 */
159777923df2SAlan Cox 		for (j = 0; j < n; j++)
159877923df2SAlan Cox 			rtvals[i + j] = VM_PAGER_PEND;
159977923df2SAlan Cox 
160077923df2SAlan Cox 		/*
16011c7c3c6aSMatthew Dillon 		 * asynchronous
16021c7c3c6aSMatthew Dillon 		 *
160323612f0dSDoug Moore 		 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
160426f9a767SRodney W. Grimes 		 */
160523612f0dSDoug Moore 		if (async) {
16061c7c3c6aSMatthew Dillon 			bp->b_iodone = swp_pager_async_iodone;
160767812eacSKirk McKusick 			BUF_KERNPROC(bp);
16084b03903aSPoul-Henning Kamp 			swp_pager_strategy(bp);
16091c7c3c6aSMatthew Dillon 			continue;
161026f9a767SRodney W. Grimes 		}
1611e47ed70bSJohn Dyson 
161226f9a767SRodney W. Grimes 		/*
16131c7c3c6aSMatthew Dillon 		 * synchronous
16141c7c3c6aSMatthew Dillon 		 *
161523612f0dSDoug Moore 		 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
16161c7c3c6aSMatthew Dillon 		 */
16172c840b1fSAlan Cox 		bp->b_iodone = bdone;
16184b03903aSPoul-Henning Kamp 		swp_pager_strategy(bp);
16191c7c3c6aSMatthew Dillon 
16201c7c3c6aSMatthew Dillon 		/*
162177923df2SAlan Cox 		 * Wait for the sync I/O to complete.
162226f9a767SRodney W. Grimes 		 */
16232c840b1fSAlan Cox 		bwait(bp, PVM, "swwrt");
162477923df2SAlan Cox 
16251c7c3c6aSMatthew Dillon 		/*
16261c7c3c6aSMatthew Dillon 		 * Now that we are through with the bp, we can call the
16271c7c3c6aSMatthew Dillon 		 * normal async completion, which frees everything up.
16281c7c3c6aSMatthew Dillon 		 */
16291c7c3c6aSMatthew Dillon 		swp_pager_async_iodone(bp);
16301c7c3c6aSMatthew Dillon 	}
163178f1deefSAlan Cox 	swp_pager_freeswapspace(s_free, n_free);
163223612f0dSDoug Moore 	VM_OBJECT_WLOCK(object);
16331c7c3c6aSMatthew Dillon }
16341c7c3c6aSMatthew Dillon 
16351c7c3c6aSMatthew Dillon /*
16361c7c3c6aSMatthew Dillon  *	swp_pager_async_iodone:
16371c7c3c6aSMatthew Dillon  *
16381c7c3c6aSMatthew Dillon  *	Completion routine for asynchronous reads and writes from/to swap.
16391c7c3c6aSMatthew Dillon  *	Also called manually by synchronous code to finish up a bp.
16401c7c3c6aSMatthew Dillon  *
164115523cf7SKonstantin Belousov  *	This routine may not sleep.
16421c7c3c6aSMatthew Dillon  */
16431c7c3c6aSMatthew Dillon static void
16442f249180SPoul-Henning Kamp swp_pager_async_iodone(struct buf *bp)
16451c7c3c6aSMatthew Dillon {
16461c7c3c6aSMatthew Dillon 	int i;
16471c7c3c6aSMatthew Dillon 	vm_object_t object = NULL;
16481c7c3c6aSMatthew Dillon 
16491c7c3c6aSMatthew Dillon 	/*
16500b208315SEdward Tomasz Napierala 	 * Report error - unless we ran out of memory, in which case
16510b208315SEdward Tomasz Napierala 	 * we've already logged it in swapgeom_strategy().
16521c7c3c6aSMatthew Dillon 	 */
16530b208315SEdward Tomasz Napierala 	if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
16541c7c3c6aSMatthew Dillon 		printf(
16551c7c3c6aSMatthew Dillon 		    "swap_pager: I/O error - %s failed; blkno %ld,"
16561c7c3c6aSMatthew Dillon 			"size %ld, error %d\n",
165721144e3bSPoul-Henning Kamp 		    ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
16581c7c3c6aSMatthew Dillon 		    (long)bp->b_blkno,
16591c7c3c6aSMatthew Dillon 		    (long)bp->b_bcount,
16601c7c3c6aSMatthew Dillon 		    bp->b_error
16611c7c3c6aSMatthew Dillon 		);
16621c7c3c6aSMatthew Dillon 	}
16631c7c3c6aSMatthew Dillon 
16641c7c3c6aSMatthew Dillon 	/*
166526f9a767SRodney W. Grimes 	 * remove the mapping for kernel virtual
166626f9a767SRodney W. Grimes 	 */
1667fade8dd7SJeff Roberson 	if (buf_mapped(bp))
16681c7c3c6aSMatthew Dillon 		pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1669fade8dd7SJeff Roberson 	else
1670fade8dd7SJeff Roberson 		bp->b_data = bp->b_kvabase;
167126f9a767SRodney W. Grimes 
167233a609ecSAlan Cox 	if (bp->b_npages) {
167333a609ecSAlan Cox 		object = bp->b_pages[0]->object;
167489f6b863SAttilio Rao 		VM_OBJECT_WLOCK(object);
167533a609ecSAlan Cox 	}
16762965a453SKip Macy 
167726f9a767SRodney W. Grimes 	/*
16781c7c3c6aSMatthew Dillon 	 * cleanup pages.  If an error occurs writing to swap, we are in
16791c7c3c6aSMatthew Dillon 	 * very serious trouble.  If it happens to be a disk error, though,
16801c7c3c6aSMatthew Dillon 	 * we may be able to recover by reassigning the swap later on.  So
16811c7c3c6aSMatthew Dillon 	 * in this case we remove the m->swapblk assignment for the page
16821c7c3c6aSMatthew Dillon 	 * but do not free it in the rlist.  The errornous block(s) are thus
16831c7c3c6aSMatthew Dillon 	 * never reallocated as swap.  Redirty the page and continue.
168426f9a767SRodney W. Grimes 	 */
16851c7c3c6aSMatthew Dillon 	for (i = 0; i < bp->b_npages; ++i) {
16861c7c3c6aSMatthew Dillon 		vm_page_t m = bp->b_pages[i];
1687e47ed70bSJohn Dyson 
16885786be7cSAlan Cox 		m->oflags &= ~VPO_SWAPINPROG;
1689c7aebda8SAttilio Rao 		if (m->oflags & VPO_SWAPSLEEP) {
1690c7aebda8SAttilio Rao 			m->oflags &= ~VPO_SWAPSLEEP;
1691cf27e0d1SJeff Roberson 			wakeup(&object->handle);
1692c7aebda8SAttilio Rao 		}
1693e47ed70bSJohn Dyson 
1694a8081778SJeff Roberson 		/* We always have space after I/O, successful or not. */
1695a8081778SJeff Roberson 		vm_page_aflag_set(m, PGA_SWAP_SPACE);
1696a8081778SJeff Roberson 
1697c244d2deSPoul-Henning Kamp 		if (bp->b_ioflags & BIO_ERROR) {
1698ffc82b0aSJohn Dyson 			/*
16991c7c3c6aSMatthew Dillon 			 * If an error occurs I'd love to throw the swapblk
17001c7c3c6aSMatthew Dillon 			 * away without freeing it back to swapspace, so it
17011c7c3c6aSMatthew Dillon 			 * can never be used again.  But I can't from an
17021c7c3c6aSMatthew Dillon 			 * interrupt.
1703ffc82b0aSJohn Dyson 			 */
170421144e3bSPoul-Henning Kamp 			if (bp->b_iocmd == BIO_READ) {
17051c7c3c6aSMatthew Dillon 				/*
17061c7c3c6aSMatthew Dillon 				 * NOTE: for reads, m->dirty will probably
1707956f3135SPhilippe Charnier 				 * be overridden by the original caller of
17081c7c3c6aSMatthew Dillon 				 * getpages so don't play cute tricks here.
17091c7c3c6aSMatthew Dillon 				 */
17100012f373SJeff Roberson 				vm_page_invalid(m);
17111c7c3c6aSMatthew Dillon 			} else {
17121c7c3c6aSMatthew Dillon 				/*
17131c7c3c6aSMatthew Dillon 				 * If a write error occurs, reactivate page
17141c7c3c6aSMatthew Dillon 				 * so it doesn't clog the inactive list,
17151c7c3c6aSMatthew Dillon 				 * then finish the I/O.
17161c7c3c6aSMatthew Dillon 				 */
171741e5a226SAlan Cox 				MPASS(m->dirty == VM_PAGE_BITS_ALL);
17189f5632e6SMark Johnston 
1719a8081778SJeff Roberson 				/* PQ_UNSWAPPABLE? */
17201c7c3c6aSMatthew Dillon 				vm_page_activate(m);
1721c7aebda8SAttilio Rao 				vm_page_sunbusy(m);
17221c7c3c6aSMatthew Dillon 			}
172321144e3bSPoul-Henning Kamp 		} else if (bp->b_iocmd == BIO_READ) {
17241c7c3c6aSMatthew Dillon 			/*
17251c7c3c6aSMatthew Dillon 			 * NOTE: for reads, m->dirty will probably be
1726956f3135SPhilippe Charnier 			 * overridden by the original caller of getpages so
17271c7c3c6aSMatthew Dillon 			 * we cannot set them in order to free the underlying
17281c7c3c6aSMatthew Dillon 			 * swap in a low-swap situation.  I don't think we'd
17291c7c3c6aSMatthew Dillon 			 * want to do that anyway, but it was an optimization
17301c7c3c6aSMatthew Dillon 			 * that existed in the old swapper for a time before
17311c7c3c6aSMatthew Dillon 			 * it got ripped out due to precisely this problem.
17321c7c3c6aSMatthew Dillon 			 */
1733016a3c93SAlan Cox 			KASSERT(!pmap_page_is_mapped(m),
1734016a3c93SAlan Cox 			    ("swp_pager_async_iodone: page %p is mapped", m));
1735016a3c93SAlan Cox 			KASSERT(m->dirty == 0,
1736016a3c93SAlan Cox 			    ("swp_pager_async_iodone: page %p is dirty", m));
1737915d1b71SMark Johnston 
17380012f373SJeff Roberson 			vm_page_valid(m);
1739915d1b71SMark Johnston 			if (i < bp->b_pgbefore ||
1740915d1b71SMark Johnston 			    i >= bp->b_npages - bp->b_pgafter)
1741915d1b71SMark Johnston 				vm_page_readahead_finish(m);
17421c7c3c6aSMatthew Dillon 		} else {
17431c7c3c6aSMatthew Dillon 			/*
1744016a3c93SAlan Cox 			 * For write success, clear the dirty
17451c7c3c6aSMatthew Dillon 			 * status, then finish the I/O ( which decrements the
17461c7c3c6aSMatthew Dillon 			 * busy count and possibly wakes waiter's up ).
1747ebcddc72SAlan Cox 			 * A page is only written to swap after a period of
1748ebcddc72SAlan Cox 			 * inactivity.  Therefore, we do not expect it to be
1749ebcddc72SAlan Cox 			 * reused.
17501c7c3c6aSMatthew Dillon 			 */
17516031c68dSAlan Cox 			KASSERT(!pmap_page_is_write_mapped(m),
1752016a3c93SAlan Cox 			    ("swp_pager_async_iodone: page %p is not write"
1753016a3c93SAlan Cox 			    " protected", m));
1754c52e7044SAlan Cox 			vm_page_undirty(m);
1755ebcddc72SAlan Cox 			vm_page_deactivate_noreuse(m);
1756ebcddc72SAlan Cox 			vm_page_sunbusy(m);
17573c4a2440SAlan Cox 		}
17583c4a2440SAlan Cox 	}
175926f9a767SRodney W. Grimes 
17601c7c3c6aSMatthew Dillon 	/*
17611c7c3c6aSMatthew Dillon 	 * adjust pip.  NOTE: the original parent may still have its own
17621c7c3c6aSMatthew Dillon 	 * pip refs on the object.
17631c7c3c6aSMatthew Dillon 	 */
17640d420ad3SAlan Cox 	if (object != NULL) {
17651c7c3c6aSMatthew Dillon 		vm_object_pip_wakeupn(object, bp->b_npages);
176689f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
17670d420ad3SAlan Cox 	}
176826f9a767SRodney W. Grimes 
17691c7c3c6aSMatthew Dillon 	/*
1770100650deSOlivier Houchard 	 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1771100650deSOlivier Houchard 	 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1772100650deSOlivier Houchard 	 * trigger a KASSERT in relpbuf().
1773100650deSOlivier Houchard 	 */
1774100650deSOlivier Houchard 	if (bp->b_vp) {
1775100650deSOlivier Houchard 		    bp->b_vp = NULL;
1776100650deSOlivier Houchard 		    bp->b_bufobj = NULL;
1777100650deSOlivier Houchard 	}
1778100650deSOlivier Houchard 	/*
17791c7c3c6aSMatthew Dillon 	 * release the physical I/O buffer
17801c7c3c6aSMatthew Dillon 	 */
1781756a5412SGleb Smirnoff 	if (bp->b_flags & B_ASYNC) {
1782756a5412SGleb Smirnoff 		mtx_lock(&swbuf_mtx);
1783756a5412SGleb Smirnoff 		if (++nsw_wcount_async == 1)
1784756a5412SGleb Smirnoff 			wakeup(&nsw_wcount_async);
1785756a5412SGleb Smirnoff 		mtx_unlock(&swbuf_mtx);
1786756a5412SGleb Smirnoff 	}
1787756a5412SGleb Smirnoff 	uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
178826f9a767SRodney W. Grimes }
17891c7c3c6aSMatthew Dillon 
1790b1fd102eSMark Johnston int
1791b1fd102eSMark Johnston swap_pager_nswapdev(void)
1792b1fd102eSMark Johnston {
1793b1fd102eSMark Johnston 
1794b1fd102eSMark Johnston 	return (nswapdev);
1795b1fd102eSMark Johnston }
1796b1fd102eSMark Johnston 
17977c022327SDoug Moore static void
17987c022327SDoug Moore swp_pager_force_dirty(vm_page_t m)
17997c022327SDoug Moore {
18007c022327SDoug Moore 
18017c022327SDoug Moore 	vm_page_dirty(m);
180256948d17SDoug Moore 	swap_pager_unswapped(m);
18037c022327SDoug Moore 	vm_page_launder(m);
180492da00bbSMatthew Dillon }
180592da00bbSMatthew Dillon 
1806ecfbddf0SKonstantin Belousov u_long
1807ecfbddf0SKonstantin Belousov swap_pager_swapped_pages(vm_object_t object)
1808ecfbddf0SKonstantin Belousov {
1809ecfbddf0SKonstantin Belousov 	struct swblk *sb;
1810ecfbddf0SKonstantin Belousov 	vm_pindex_t pi;
1811ecfbddf0SKonstantin Belousov 	u_long res;
1812ecfbddf0SKonstantin Belousov 	int i;
1813ecfbddf0SKonstantin Belousov 
1814ecfbddf0SKonstantin Belousov 	VM_OBJECT_ASSERT_LOCKED(object);
18154b8365d7SKonstantin Belousov 	if ((object->flags & OBJ_SWAP) == 0)
1816ecfbddf0SKonstantin Belousov 		return (0);
1817ecfbddf0SKonstantin Belousov 
1818ecfbddf0SKonstantin Belousov 	for (res = 0, pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1819ecfbddf0SKonstantin Belousov 	    &object->un_pager.swp.swp_blks, pi)) != NULL;
1820ecfbddf0SKonstantin Belousov 	    pi = sb->p + SWAP_META_PAGES) {
1821ecfbddf0SKonstantin Belousov 		for (i = 0; i < SWAP_META_PAGES; i++) {
1822ecfbddf0SKonstantin Belousov 			if (sb->d[i] != SWAPBLK_NONE)
1823ecfbddf0SKonstantin Belousov 				res++;
1824ecfbddf0SKonstantin Belousov 		}
1825ecfbddf0SKonstantin Belousov 	}
1826ecfbddf0SKonstantin Belousov 	return (res);
1827ecfbddf0SKonstantin Belousov }
1828ecfbddf0SKonstantin Belousov 
182992da00bbSMatthew Dillon /*
18307c022327SDoug Moore  *	swap_pager_swapoff_object:
18317c022327SDoug Moore  *
18327c022327SDoug Moore  *	Page in all of the pages that have been paged out for an object
183356948d17SDoug Moore  *	to a swap device.
18347c022327SDoug Moore  */
18357c022327SDoug Moore static void
18367c022327SDoug Moore swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
18377c022327SDoug Moore {
18387c022327SDoug Moore 	struct swblk *sb;
1839c90d075bSMark Johnston 	vm_page_t m;
1840c90d075bSMark Johnston 	vm_pindex_t pi;
1841c90d075bSMark Johnston 	daddr_t blk;
1842c90d075bSMark Johnston 	int i, nv, rahead, rv;
18437c022327SDoug Moore 
18444b8365d7SKonstantin Belousov 	KASSERT((object->flags & OBJ_SWAP) != 0,
18458ecbf14bSDoug Moore 	    ("%s: Object not swappable", __func__));
1846c90d075bSMark Johnston 
18477c022327SDoug Moore 	for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
18487c022327SDoug Moore 	    &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1849c90d075bSMark Johnston 		if ((object->flags & OBJ_DEAD) != 0) {
1850c90d075bSMark Johnston 			/*
1851c90d075bSMark Johnston 			 * Make sure that pending writes finish before
1852c90d075bSMark Johnston 			 * returning.
1853c90d075bSMark Johnston 			 */
1854c90d075bSMark Johnston 			vm_object_pip_wait(object, "swpoff");
1855c90d075bSMark Johnston 			swp_pager_meta_free_all(object);
1856c90d075bSMark Johnston 			break;
1857c90d075bSMark Johnston 		}
18587c022327SDoug Moore 		for (i = 0; i < SWAP_META_PAGES; i++) {
185956948d17SDoug Moore 			/*
1860c90d075bSMark Johnston 			 * Count the number of contiguous valid blocks.
186156948d17SDoug Moore 			 */
1862c90d075bSMark Johnston 			for (nv = 0; nv < SWAP_META_PAGES - i; nv++) {
1863c90d075bSMark Johnston 				blk = sb->d[i + nv];
1864c90d075bSMark Johnston 				if (!swp_pager_isondev(blk, sp) ||
1865c90d075bSMark Johnston 				    blk == SWAPBLK_NONE)
1866c90d075bSMark Johnston 					break;
186756948d17SDoug Moore 			}
1868c90d075bSMark Johnston 			if (nv == 0)
18697c022327SDoug Moore 				continue;
187056948d17SDoug Moore 
187156948d17SDoug Moore 			/*
1872c90d075bSMark Johnston 			 * Look for a page corresponding to the first
1873c90d075bSMark Johnston 			 * valid block and ensure that any pending paging
1874c90d075bSMark Johnston 			 * operations on it are complete.  If the page is valid,
1875c90d075bSMark Johnston 			 * mark it dirty and free the swap block.  Try to batch
1876c90d075bSMark Johnston 			 * this operation since it may cause sp to be freed,
1877c90d075bSMark Johnston 			 * meaning that we must restart the scan.  Avoid busying
1878c90d075bSMark Johnston 			 * valid pages since we may block forever on kernel
1879c90d075bSMark Johnston 			 * stack pages.
188056948d17SDoug Moore 			 */
1881c90d075bSMark Johnston 			m = vm_page_lookup(object, sb->p + i);
1882c90d075bSMark Johnston 			if (m == NULL) {
1883c90d075bSMark Johnston 				m = vm_page_alloc(object, sb->p + i,
1884c90d075bSMark Johnston 				    VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
1885c90d075bSMark Johnston 				if (m == NULL)
1886c90d075bSMark Johnston 					break;
1887c90d075bSMark Johnston 			} else {
1888c90d075bSMark Johnston 				if ((m->oflags & VPO_SWAPINPROG) != 0) {
1889c90d075bSMark Johnston 					m->oflags |= VPO_SWAPSLEEP;
1890c90d075bSMark Johnston 					VM_OBJECT_SLEEP(object, &object->handle,
1891c90d075bSMark Johnston 					    PSWP, "swpoff", 0);
1892c90d075bSMark Johnston 					break;
1893c90d075bSMark Johnston 				}
1894c90d075bSMark Johnston 				if (vm_page_all_valid(m)) {
1895c90d075bSMark Johnston 					do {
1896c90d075bSMark Johnston 						swp_pager_force_dirty(m);
1897c90d075bSMark Johnston 					} while (--nv > 0 &&
1898c90d075bSMark Johnston 					    (m = vm_page_next(m)) != NULL &&
1899c90d075bSMark Johnston 					    vm_page_all_valid(m) &&
1900c90d075bSMark Johnston 					    (m->oflags & VPO_SWAPINPROG) == 0);
1901c90d075bSMark Johnston 					break;
1902c90d075bSMark Johnston 				}
1903c90d075bSMark Johnston 				if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL))
1904c90d075bSMark Johnston 					break;
19057c022327SDoug Moore 			}
190656948d17SDoug Moore 
1907c90d075bSMark Johnston 			vm_object_pip_add(object, 1);
1908c90d075bSMark Johnston 			rahead = SWAP_META_PAGES;
1909c90d075bSMark Johnston 			rv = swap_pager_getpages_locked(object, &m, 1, NULL,
1910c90d075bSMark Johnston 			    &rahead);
1911c90d075bSMark Johnston 			if (rv != VM_PAGER_OK)
1912c90d075bSMark Johnston 				panic("%s: read from swap failed: %d",
1913c90d075bSMark Johnston 				    __func__, rv);
1914c90d075bSMark Johnston 			vm_object_pip_wakeupn(object, 1);
1915c90d075bSMark Johnston 			VM_OBJECT_WLOCK(object);
1916c90d075bSMark Johnston 			vm_page_xunbusy(m);
1917c90d075bSMark Johnston 
191856948d17SDoug Moore 			/*
1919c90d075bSMark Johnston 			 * The object lock was dropped so we must restart the
1920c90d075bSMark Johnston 			 * scan of this swap block.  Pages paged in during this
1921c90d075bSMark Johnston 			 * iteration will be marked dirty in a future iteration.
192256948d17SDoug Moore 			 */
192356948d17SDoug Moore 			break;
192456948d17SDoug Moore 		}
192556948d17SDoug Moore 		if (i == SWAP_META_PAGES)
192656948d17SDoug Moore 			pi = sb->p + SWAP_META_PAGES;
192756948d17SDoug Moore 	}
19287c022327SDoug Moore }
19297c022327SDoug Moore 
19307c022327SDoug Moore /*
193192da00bbSMatthew Dillon  *	swap_pager_swapoff:
193292da00bbSMatthew Dillon  *
193392da00bbSMatthew Dillon  *	Page in all of the pages that have been paged out to the
193492da00bbSMatthew Dillon  *	given device.  The corresponding blocks in the bitmap must be
193592da00bbSMatthew Dillon  *	marked as allocated and the device must be flagged SW_CLOSING.
193692da00bbSMatthew Dillon  *	There may be no processes swapped out to the device.
193792da00bbSMatthew Dillon  *
193892da00bbSMatthew Dillon  *	This routine may block.
193992da00bbSMatthew Dillon  */
1940e9c0cc15SPoul-Henning Kamp static void
1941b3fed13eSDavid Schultz swap_pager_swapoff(struct swdevt *sp)
194292da00bbSMatthew Dillon {
1943f425ab8eSKonstantin Belousov 	vm_object_t object;
19447c022327SDoug Moore 	int retries;
194592da00bbSMatthew Dillon 
194604533e1eSKonstantin Belousov 	sx_assert(&swdev_syscall_lock, SA_XLOCKED);
194792da00bbSMatthew Dillon 
19488bc61209SDavid Schultz 	retries = 0;
194992da00bbSMatthew Dillon full_rescan:
1950f425ab8eSKonstantin Belousov 	mtx_lock(&vm_object_list_mtx);
1951f425ab8eSKonstantin Belousov 	TAILQ_FOREACH(object, &vm_object_list, object_list) {
19524b8365d7SKonstantin Belousov 		if ((object->flags & OBJ_SWAP) == 0)
195398150664SKonstantin Belousov 			continue;
1954f425ab8eSKonstantin Belousov 		mtx_unlock(&vm_object_list_mtx);
195598150664SKonstantin Belousov 		/* Depends on type-stability. */
195698150664SKonstantin Belousov 		VM_OBJECT_WLOCK(object);
1957f425ab8eSKonstantin Belousov 
1958f425ab8eSKonstantin Belousov 		/*
1959f425ab8eSKonstantin Belousov 		 * Dead objects are eventually terminated on their own.
1960f425ab8eSKonstantin Belousov 		 */
1961f425ab8eSKonstantin Belousov 		if ((object->flags & OBJ_DEAD) != 0)
1962f425ab8eSKonstantin Belousov 			goto next_obj;
1963f425ab8eSKonstantin Belousov 
1964f425ab8eSKonstantin Belousov 		/*
1965f425ab8eSKonstantin Belousov 		 * Sync with fences placed after pctrie
1966f425ab8eSKonstantin Belousov 		 * initialization.  We must not access pctrie below
1967f425ab8eSKonstantin Belousov 		 * unless we checked that our object is swap and not
1968f425ab8eSKonstantin Belousov 		 * dead.
1969f425ab8eSKonstantin Belousov 		 */
1970f425ab8eSKonstantin Belousov 		atomic_thread_fence_acq();
19714b8365d7SKonstantin Belousov 		if ((object->flags & OBJ_SWAP) == 0)
1972f425ab8eSKonstantin Belousov 			goto next_obj;
1973f425ab8eSKonstantin Belousov 
19747c022327SDoug Moore 		swap_pager_swapoff_object(sp, object);
1975f425ab8eSKonstantin Belousov next_obj:
1976f425ab8eSKonstantin Belousov 		VM_OBJECT_WUNLOCK(object);
1977f425ab8eSKonstantin Belousov 		mtx_lock(&vm_object_list_mtx);
197892da00bbSMatthew Dillon 	}
1979f425ab8eSKonstantin Belousov 	mtx_unlock(&vm_object_list_mtx);
1980f425ab8eSKonstantin Belousov 
19818bc61209SDavid Schultz 	if (sp->sw_used) {
198292da00bbSMatthew Dillon 		/*
19838bc61209SDavid Schultz 		 * Objects may be locked or paging to the device being
19848bc61209SDavid Schultz 		 * removed, so we will miss their pages and need to
19858bc61209SDavid Schultz 		 * make another pass.  We have marked this device as
19868bc61209SDavid Schultz 		 * SW_CLOSING, so the activity should finish soon.
198792da00bbSMatthew Dillon 		 */
19888bc61209SDavid Schultz 		retries++;
19898bc61209SDavid Schultz 		if (retries > 100) {
19908bc61209SDavid Schultz 			panic("swapoff: failed to locate %d swap blocks",
19918bc61209SDavid Schultz 			    sp->sw_used);
19928bc61209SDavid Schultz 		}
19934d70511aSJohn Baldwin 		pause("swpoff", hz / 20);
199492da00bbSMatthew Dillon 		goto full_rescan;
199592da00bbSMatthew Dillon 	}
1996b1fd102eSMark Johnston 	EVENTHANDLER_INVOKE(swapoff, sp);
199792da00bbSMatthew Dillon }
199892da00bbSMatthew Dillon 
19991c7c3c6aSMatthew Dillon /************************************************************************
20001c7c3c6aSMatthew Dillon  *				SWAP META DATA 				*
20011c7c3c6aSMatthew Dillon  ************************************************************************
20021c7c3c6aSMatthew Dillon  *
20031c7c3c6aSMatthew Dillon  *	These routines manipulate the swap metadata stored in the
2004cec9f109SDavid E. O'Brien  *	OBJT_SWAP object.
20051c7c3c6aSMatthew Dillon  *
20064dcc5c2dSMatthew Dillon  *	Swap metadata is implemented with a global hash and not directly
20074dcc5c2dSMatthew Dillon  *	linked into the object.  Instead the object simply contains
20084dcc5c2dSMatthew Dillon  *	appropriate tracking counters.
20091c7c3c6aSMatthew Dillon  */
20101c7c3c6aSMatthew Dillon 
20111c7c3c6aSMatthew Dillon /*
2012230869e0SAlan Cox  * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
2013230869e0SAlan Cox  */
2014230869e0SAlan Cox static bool
2015230869e0SAlan Cox swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
2016230869e0SAlan Cox {
2017230869e0SAlan Cox 	int i;
2018230869e0SAlan Cox 
2019230869e0SAlan Cox 	MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
2020230869e0SAlan Cox 	for (i = start; i < limit; i++) {
2021230869e0SAlan Cox 		if (sb->d[i] != SWAPBLK_NONE)
2022230869e0SAlan Cox 			return (false);
2023230869e0SAlan Cox 	}
2024230869e0SAlan Cox 	return (true);
2025230869e0SAlan Cox }
2026230869e0SAlan Cox 
2027230869e0SAlan Cox /*
2028abdab7b6SDoug Moore  * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
2029abdab7b6SDoug Moore  *
2030abdab7b6SDoug Moore  *  Nothing is done if the block is still in use.
2031abdab7b6SDoug Moore  */
2032abdab7b6SDoug Moore static void
2033abdab7b6SDoug Moore swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
2034abdab7b6SDoug Moore {
2035abdab7b6SDoug Moore 
2036abdab7b6SDoug Moore 	if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
2037abdab7b6SDoug Moore 		SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2038abdab7b6SDoug Moore 		uma_zfree(swblk_zone, sb);
2039abdab7b6SDoug Moore 	}
2040abdab7b6SDoug Moore }
2041abdab7b6SDoug Moore 
2042abdab7b6SDoug Moore /*
20431c7c3c6aSMatthew Dillon  * SWP_PAGER_META_BUILD() -	add swap block to swap meta data for object
20441c7c3c6aSMatthew Dillon  *
20451c7c3c6aSMatthew Dillon  *	We first convert the object to a swap object if it is a default
20461c7c3c6aSMatthew Dillon  *	object.
20471c7c3c6aSMatthew Dillon  *
20481c7c3c6aSMatthew Dillon  *	The specified swapblk is added to the object's swap metadata.  If
20491c7c3c6aSMatthew Dillon  *	the swapblk is not valid, it is freed instead.  Any previously
205078f1deefSAlan Cox  *	assigned swapblk is returned.
20511c7c3c6aSMatthew Dillon  */
205278f1deefSAlan Cox static daddr_t
20532f249180SPoul-Henning Kamp swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
20542f249180SPoul-Henning Kamp {
2055f425ab8eSKonstantin Belousov 	static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
2056eed99cb8SKonstantin Belousov 	struct swblk *sb, *sb1;
2057f425ab8eSKonstantin Belousov 	vm_pindex_t modpi, rdpi;
205878f1deefSAlan Cox 	daddr_t prev_swapblk;
2059f425ab8eSKonstantin Belousov 	int error, i;
20601c7c3c6aSMatthew Dillon 
206189f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
2062f425ab8eSKonstantin Belousov 
20631c7c3c6aSMatthew Dillon 	/*
20641c7c3c6aSMatthew Dillon 	 * Convert default object to swap object if necessary
20651c7c3c6aSMatthew Dillon 	 */
20664b8365d7SKonstantin Belousov 	if ((object->flags & OBJ_SWAP) == 0) {
2067f425ab8eSKonstantin Belousov 		pctrie_init(&object->un_pager.swp.swp_blks);
2068f425ab8eSKonstantin Belousov 
2069f425ab8eSKonstantin Belousov 		/*
2070f425ab8eSKonstantin Belousov 		 * Ensure that swap_pager_swapoff()'s iteration over
2071f425ab8eSKonstantin Belousov 		 * object_list does not see a garbage pctrie.
2072f425ab8eSKonstantin Belousov 		 */
2073f425ab8eSKonstantin Belousov 		atomic_thread_fence_rel();
2074f425ab8eSKonstantin Belousov 
20751c7c3c6aSMatthew Dillon 		object->type = OBJT_SWAP;
20764b8365d7SKonstantin Belousov 		vm_object_set_flag(object, OBJ_SWAP);
2077fe7bcbafSKyle Evans 		object->un_pager.swp.writemappings = 0;
207867388836SKonstantin Belousov 		KASSERT((object->flags & OBJ_ANON) != 0 ||
207967388836SKonstantin Belousov 		    object->handle == NULL,
208067388836SKonstantin Belousov 		    ("default pager %p with handle %p",
208167388836SKonstantin Belousov 		    object, object->handle));
2082bd228075SAlan Cox 	}
20831c7c3c6aSMatthew Dillon 
2084f425ab8eSKonstantin Belousov 	rdpi = rounddown(pindex, SWAP_META_PAGES);
2085f425ab8eSKonstantin Belousov 	sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
2086f425ab8eSKonstantin Belousov 	if (sb == NULL) {
20871c7c3c6aSMatthew Dillon 		if (swapblk == SWAPBLK_NONE)
208878f1deefSAlan Cox 			return (SWAPBLK_NONE);
2089f425ab8eSKonstantin Belousov 		for (;;) {
2090f425ab8eSKonstantin Belousov 			sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
2091f425ab8eSKonstantin Belousov 			    pageproc ? M_USE_RESERVE : 0));
2092f425ab8eSKonstantin Belousov 			if (sb != NULL) {
2093f425ab8eSKonstantin Belousov 				sb->p = rdpi;
2094f425ab8eSKonstantin Belousov 				for (i = 0; i < SWAP_META_PAGES; i++)
2095f425ab8eSKonstantin Belousov 					sb->d[i] = SWAPBLK_NONE;
2096f425ab8eSKonstantin Belousov 				if (atomic_cmpset_int(&swblk_zone_exhausted,
2097f425ab8eSKonstantin Belousov 				    1, 0))
2098f425ab8eSKonstantin Belousov 					printf("swblk zone ok\n");
2099f425ab8eSKonstantin Belousov 				break;
2100f425ab8eSKonstantin Belousov 			}
210189f6b863SAttilio Rao 			VM_OBJECT_WUNLOCK(object);
2102f425ab8eSKonstantin Belousov 			if (uma_zone_exhausted(swblk_zone)) {
2103f425ab8eSKonstantin Belousov 				if (atomic_cmpset_int(&swblk_zone_exhausted,
2104f425ab8eSKonstantin Belousov 				    0, 1))
2105f425ab8eSKonstantin Belousov 					printf("swap blk zone exhausted, "
21063ff863f1SDag-Erling Smørgrav 					    "increase kern.maxswzone\n");
21072025d69bSKonstantin Belousov 				vm_pageout_oom(VM_OOM_SWAPZ);
2108f425ab8eSKonstantin Belousov 				pause("swzonxb", 10);
21092025d69bSKonstantin Belousov 			} else
21108d6fbbb8SJeff Roberson 				uma_zwait(swblk_zone);
211189f6b863SAttilio Rao 			VM_OBJECT_WLOCK(object);
2112eed99cb8SKonstantin Belousov 			sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2113eed99cb8SKonstantin Belousov 			    rdpi);
2114eed99cb8SKonstantin Belousov 			if (sb != NULL)
2115eed99cb8SKonstantin Belousov 				/*
2116eed99cb8SKonstantin Belousov 				 * Somebody swapped out a nearby page,
2117eed99cb8SKonstantin Belousov 				 * allocating swblk at the rdpi index,
2118eed99cb8SKonstantin Belousov 				 * while we dropped the object lock.
2119eed99cb8SKonstantin Belousov 				 */
2120eed99cb8SKonstantin Belousov 				goto allocated;
21214dcc5c2dSMatthew Dillon 		}
2122f425ab8eSKonstantin Belousov 		for (;;) {
2123f425ab8eSKonstantin Belousov 			error = SWAP_PCTRIE_INSERT(
2124f425ab8eSKonstantin Belousov 			    &object->un_pager.swp.swp_blks, sb);
2125f425ab8eSKonstantin Belousov 			if (error == 0) {
2126f425ab8eSKonstantin Belousov 				if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2127f425ab8eSKonstantin Belousov 				    1, 0))
2128f425ab8eSKonstantin Belousov 					printf("swpctrie zone ok\n");
2129f425ab8eSKonstantin Belousov 				break;
21301c7c3c6aSMatthew Dillon 			}
2131f425ab8eSKonstantin Belousov 			VM_OBJECT_WUNLOCK(object);
2132f425ab8eSKonstantin Belousov 			if (uma_zone_exhausted(swpctrie_zone)) {
2133f425ab8eSKonstantin Belousov 				if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2134f425ab8eSKonstantin Belousov 				    0, 1))
2135f425ab8eSKonstantin Belousov 					printf("swap pctrie zone exhausted, "
2136f425ab8eSKonstantin Belousov 					    "increase kern.maxswzone\n");
2137f425ab8eSKonstantin Belousov 				vm_pageout_oom(VM_OOM_SWAPZ);
2138f425ab8eSKonstantin Belousov 				pause("swzonxp", 10);
2139f425ab8eSKonstantin Belousov 			} else
21408d6fbbb8SJeff Roberson 				uma_zwait(swpctrie_zone);
2141f425ab8eSKonstantin Belousov 			VM_OBJECT_WLOCK(object);
2142eed99cb8SKonstantin Belousov 			sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2143eed99cb8SKonstantin Belousov 			    rdpi);
2144eed99cb8SKonstantin Belousov 			if (sb1 != NULL) {
2145eed99cb8SKonstantin Belousov 				uma_zfree(swblk_zone, sb);
2146eed99cb8SKonstantin Belousov 				sb = sb1;
2147eed99cb8SKonstantin Belousov 				goto allocated;
21481c7c3c6aSMatthew Dillon 			}
2149f425ab8eSKonstantin Belousov 		}
2150eed99cb8SKonstantin Belousov 	}
2151eed99cb8SKonstantin Belousov allocated:
2152f425ab8eSKonstantin Belousov 	MPASS(sb->p == rdpi);
21531c7c3c6aSMatthew Dillon 
2154f425ab8eSKonstantin Belousov 	modpi = pindex % SWAP_META_PAGES;
215578f1deefSAlan Cox 	/* Return prior contents of metadata. */
215678f1deefSAlan Cox 	prev_swapblk = sb->d[modpi];
2157f425ab8eSKonstantin Belousov 	/* Enter block into metadata. */
2158f425ab8eSKonstantin Belousov 	sb->d[modpi] = swapblk;
215985d88d87SKonstantin Belousov 
216085d88d87SKonstantin Belousov 	/*
216185d88d87SKonstantin Belousov 	 * Free the swblk if we end up with the empty page run.
216285d88d87SKonstantin Belousov 	 */
2163abdab7b6SDoug Moore 	if (swapblk == SWAPBLK_NONE)
2164abdab7b6SDoug Moore 		swp_pager_free_empty_swblk(object, sb);
216578f1deefSAlan Cox 	return (prev_swapblk);
216685d88d87SKonstantin Belousov }
21671c7c3c6aSMatthew Dillon 
21681c7c3c6aSMatthew Dillon /*
2169467057fcSDoug Moore  * SWP_PAGER_META_TRANSFER() - free a range of blocks in the srcobject's swap
2170467057fcSDoug Moore  * metadata, or transfer it into dstobject.
2171467057fcSDoug Moore  *
2172467057fcSDoug Moore  *	This routine will free swap metadata structures as they are cleaned
2173467057fcSDoug Moore  *	out.
2174467057fcSDoug Moore  */
2175467057fcSDoug Moore static void
2176467057fcSDoug Moore swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
2177467057fcSDoug Moore     vm_pindex_t pindex, vm_pindex_t count)
2178467057fcSDoug Moore {
2179467057fcSDoug Moore 	struct swblk *sb;
2180467057fcSDoug Moore 	daddr_t n_free, s_free;
2181467057fcSDoug Moore 	vm_pindex_t offset, last;
2182467057fcSDoug Moore 	int i, limit, start;
2183467057fcSDoug Moore 
2184467057fcSDoug Moore 	VM_OBJECT_ASSERT_WLOCKED(srcobject);
21854b8365d7SKonstantin Belousov 	if ((srcobject->flags & OBJ_SWAP) == 0 || count == 0)
2186467057fcSDoug Moore 		return;
2187467057fcSDoug Moore 
2188467057fcSDoug Moore 	swp_pager_init_freerange(&s_free, &n_free);
2189467057fcSDoug Moore 	offset = pindex;
2190467057fcSDoug Moore 	last = pindex + count;
2191467057fcSDoug Moore 	for (;;) {
2192467057fcSDoug Moore 		sb = SWAP_PCTRIE_LOOKUP_GE(&srcobject->un_pager.swp.swp_blks,
2193467057fcSDoug Moore 		    rounddown(pindex, SWAP_META_PAGES));
2194467057fcSDoug Moore 		if (sb == NULL || sb->p >= last)
2195467057fcSDoug Moore 			break;
2196467057fcSDoug Moore 		start = pindex > sb->p ? pindex - sb->p : 0;
2197467057fcSDoug Moore 		limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2198467057fcSDoug Moore 		    SWAP_META_PAGES;
2199467057fcSDoug Moore 		for (i = start; i < limit; i++) {
2200467057fcSDoug Moore 			if (sb->d[i] == SWAPBLK_NONE)
2201467057fcSDoug Moore 				continue;
2202467057fcSDoug Moore 			if (dstobject == NULL ||
2203467057fcSDoug Moore 			    !swp_pager_xfer_source(srcobject, dstobject,
2204467057fcSDoug Moore 			    sb->p + i - offset, sb->d[i])) {
2205467057fcSDoug Moore 				swp_pager_update_freerange(&s_free, &n_free,
2206467057fcSDoug Moore 				    sb->d[i]);
2207467057fcSDoug Moore 			}
2208467057fcSDoug Moore 			sb->d[i] = SWAPBLK_NONE;
2209467057fcSDoug Moore 		}
2210467057fcSDoug Moore 		pindex = sb->p + SWAP_META_PAGES;
2211467057fcSDoug Moore 		if (swp_pager_swblk_empty(sb, 0, start) &&
2212467057fcSDoug Moore 		    swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2213467057fcSDoug Moore 			SWAP_PCTRIE_REMOVE(&srcobject->un_pager.swp.swp_blks,
2214467057fcSDoug Moore 			    sb->p);
2215467057fcSDoug Moore 			uma_zfree(swblk_zone, sb);
2216467057fcSDoug Moore 		}
2217467057fcSDoug Moore 	}
2218467057fcSDoug Moore 	swp_pager_freeswapspace(s_free, n_free);
2219467057fcSDoug Moore }
2220467057fcSDoug Moore 
2221467057fcSDoug Moore /*
22221c7c3c6aSMatthew Dillon  * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
22231c7c3c6aSMatthew Dillon  *
22241c7c3c6aSMatthew Dillon  *	The requested range of blocks is freed, with any associated swap
22251c7c3c6aSMatthew Dillon  *	returned to the swap bitmap.
22261c7c3c6aSMatthew Dillon  *
22271c7c3c6aSMatthew Dillon  *	This routine will free swap metadata structures as they are cleaned
22281c7c3c6aSMatthew Dillon  *	out.  This routine does *NOT* operate on swap metadata associated
22291c7c3c6aSMatthew Dillon  *	with resident pages.
22301c7c3c6aSMatthew Dillon  */
22311c7c3c6aSMatthew Dillon static void
2232f425ab8eSKonstantin Belousov swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count)
22331c7c3c6aSMatthew Dillon {
2234467057fcSDoug Moore 	swp_pager_meta_transfer(object, NULL, pindex, count);
22351c7c3c6aSMatthew Dillon }
22361c7c3c6aSMatthew Dillon 
22371c7c3c6aSMatthew Dillon /*
22381c7c3c6aSMatthew Dillon  * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
22391c7c3c6aSMatthew Dillon  *
22401c7c3c6aSMatthew Dillon  *	This routine locates and destroys all swap metadata associated with
22411c7c3c6aSMatthew Dillon  *	an object.
22421c7c3c6aSMatthew Dillon  */
22431c7c3c6aSMatthew Dillon static void
22441c7c3c6aSMatthew Dillon swp_pager_meta_free_all(vm_object_t object)
22451c7c3c6aSMatthew Dillon {
2246f425ab8eSKonstantin Belousov 	struct swblk *sb;
224778f1deefSAlan Cox 	daddr_t n_free, s_free;
2248f425ab8eSKonstantin Belousov 	vm_pindex_t pindex;
224971057cd2SKonstantin Belousov 	int i;
22501c7c3c6aSMatthew Dillon 
225189f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
22524b8365d7SKonstantin Belousov 	if ((object->flags & OBJ_SWAP) == 0)
22531c7c3c6aSMatthew Dillon 		return;
22541c7c3c6aSMatthew Dillon 
225578f1deefSAlan Cox 	swp_pager_init_freerange(&s_free, &n_free);
2256f425ab8eSKonstantin Belousov 	for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
2257f425ab8eSKonstantin Belousov 	    &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
2258f425ab8eSKonstantin Belousov 		pindex = sb->p + SWAP_META_PAGES;
2259f425ab8eSKonstantin Belousov 		for (i = 0; i < SWAP_META_PAGES; i++) {
2260230869e0SAlan Cox 			if (sb->d[i] == SWAPBLK_NONE)
2261230869e0SAlan Cox 				continue;
226278f1deefSAlan Cox 			swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
22631c7c3c6aSMatthew Dillon 		}
2264f425ab8eSKonstantin Belousov 		SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2265f425ab8eSKonstantin Belousov 		uma_zfree(swblk_zone, sb);
22661c7c3c6aSMatthew Dillon 	}
226778f1deefSAlan Cox 	swp_pager_freeswapspace(s_free, n_free);
22681c7c3c6aSMatthew Dillon }
22691c7c3c6aSMatthew Dillon 
22701c7c3c6aSMatthew Dillon /*
22714abca9bbSAlan Cox  * SWP_PAGER_METACTL() -  misc control of swap meta data.
22721c7c3c6aSMatthew Dillon  *
22734abca9bbSAlan Cox  *	This routine is capable of looking up, or removing swapblk
22744abca9bbSAlan Cox  *	assignments in the swap meta data.  It returns the swapblk being
22754abca9bbSAlan Cox  *	looked-up, popped, or SWAPBLK_NONE if the block was invalid.
22761c7c3c6aSMatthew Dillon  *
22771c7c3c6aSMatthew Dillon  *	When acting on a busy resident page and paging is in progress, we
22781c7c3c6aSMatthew Dillon  *	have to wait until paging is complete but otherwise can act on the
22791c7c3c6aSMatthew Dillon  *	busy page.
22801c7c3c6aSMatthew Dillon  */
22811c7c3c6aSMatthew Dillon static daddr_t
22828ecbf14bSDoug Moore swp_pager_meta_lookup(vm_object_t object, vm_pindex_t pindex)
22832f249180SPoul-Henning Kamp {
2284f425ab8eSKonstantin Belousov 	struct swblk *sb;
22854dcc5c2dSMatthew Dillon 
2286c25673ffSAttilio Rao 	VM_OBJECT_ASSERT_LOCKED(object);
2287ee620ea4SAlan Cox 
22881c7c3c6aSMatthew Dillon 	/*
2289ee620ea4SAlan Cox 	 * The meta data only exists if the object is OBJT_SWAP
22901c7c3c6aSMatthew Dillon 	 * and even then might not be allocated yet.
22911c7c3c6aSMatthew Dillon 	 */
22924b8365d7SKonstantin Belousov 	KASSERT((object->flags & OBJ_SWAP) != 0,
22938ecbf14bSDoug Moore 	    ("Lookup object not swappable"));
22941c7c3c6aSMatthew Dillon 
2295f425ab8eSKonstantin Belousov 	sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2296f425ab8eSKonstantin Belousov 	    rounddown(pindex, SWAP_META_PAGES));
2297f425ab8eSKonstantin Belousov 	if (sb == NULL)
2298f425ab8eSKonstantin Belousov 		return (SWAPBLK_NONE);
22998ecbf14bSDoug Moore 	return (sb->d[pindex % SWAP_META_PAGES]);
23001c7c3c6aSMatthew Dillon }
23011c7c3c6aSMatthew Dillon 
2302e9c0cc15SPoul-Henning Kamp /*
230377d6fd97SKonstantin Belousov  * Returns the least page index which is greater than or equal to the
230477d6fd97SKonstantin Belousov  * parameter pindex and for which there is a swap block allocated.
230577d6fd97SKonstantin Belousov  * Returns object's size if the object's type is not swap or if there
230677d6fd97SKonstantin Belousov  * are no allocated swap blocks for the object after the requested
230777d6fd97SKonstantin Belousov  * pindex.
230877d6fd97SKonstantin Belousov  */
230977d6fd97SKonstantin Belousov vm_pindex_t
231077d6fd97SKonstantin Belousov swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
231177d6fd97SKonstantin Belousov {
2312f425ab8eSKonstantin Belousov 	struct swblk *sb;
2313f425ab8eSKonstantin Belousov 	int i;
231477d6fd97SKonstantin Belousov 
231577d6fd97SKonstantin Belousov 	VM_OBJECT_ASSERT_LOCKED(object);
23164b8365d7SKonstantin Belousov 	if ((object->flags & OBJ_SWAP) == 0)
231777d6fd97SKonstantin Belousov 		return (object->size);
231877d6fd97SKonstantin Belousov 
2319f425ab8eSKonstantin Belousov 	sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2320f425ab8eSKonstantin Belousov 	    rounddown(pindex, SWAP_META_PAGES));
2321f425ab8eSKonstantin Belousov 	if (sb == NULL)
2322f425ab8eSKonstantin Belousov 		return (object->size);
2323f425ab8eSKonstantin Belousov 	if (sb->p < pindex) {
2324f425ab8eSKonstantin Belousov 		for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2325f425ab8eSKonstantin Belousov 			if (sb->d[i] != SWAPBLK_NONE)
2326f425ab8eSKonstantin Belousov 				return (sb->p + i);
232777d6fd97SKonstantin Belousov 		}
2328f425ab8eSKonstantin Belousov 		sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2329f425ab8eSKonstantin Belousov 		    roundup(pindex, SWAP_META_PAGES));
2330f425ab8eSKonstantin Belousov 		if (sb == NULL)
2331f425ab8eSKonstantin Belousov 			return (object->size);
233277d6fd97SKonstantin Belousov 	}
2333f425ab8eSKonstantin Belousov 	for (i = 0; i < SWAP_META_PAGES; i++) {
2334f425ab8eSKonstantin Belousov 		if (sb->d[i] != SWAPBLK_NONE)
2335f425ab8eSKonstantin Belousov 			return (sb->p + i);
233677d6fd97SKonstantin Belousov 	}
2337f425ab8eSKonstantin Belousov 
2338f425ab8eSKonstantin Belousov 	/*
2339f425ab8eSKonstantin Belousov 	 * We get here if a swblk is present in the trie but it
2340f425ab8eSKonstantin Belousov 	 * doesn't map any blocks.
2341f425ab8eSKonstantin Belousov 	 */
2342f425ab8eSKonstantin Belousov 	MPASS(0);
2343f425ab8eSKonstantin Belousov 	return (object->size);
234477d6fd97SKonstantin Belousov }
234577d6fd97SKonstantin Belousov 
234677d6fd97SKonstantin Belousov /*
2347e9c0cc15SPoul-Henning Kamp  * System call swapon(name) enables swapping on device name,
2348e9c0cc15SPoul-Henning Kamp  * which must be in the swdevsw.  Return EBUSY
2349e9c0cc15SPoul-Henning Kamp  * if already swapping on this device.
2350e9c0cc15SPoul-Henning Kamp  */
2351e9c0cc15SPoul-Henning Kamp #ifndef _SYS_SYSPROTO_H_
2352e9c0cc15SPoul-Henning Kamp struct swapon_args {
2353e9c0cc15SPoul-Henning Kamp 	char *name;
2354e9c0cc15SPoul-Henning Kamp };
2355e9c0cc15SPoul-Henning Kamp #endif
2356e9c0cc15SPoul-Henning Kamp 
2357e9c0cc15SPoul-Henning Kamp /*
2358e9c0cc15SPoul-Henning Kamp  * MPSAFE
2359e9c0cc15SPoul-Henning Kamp  */
2360e9c0cc15SPoul-Henning Kamp /* ARGSUSED */
2361e9c0cc15SPoul-Henning Kamp int
23628451d0ddSKip Macy sys_swapon(struct thread *td, struct swapon_args *uap)
2363e9c0cc15SPoul-Henning Kamp {
2364e9c0cc15SPoul-Henning Kamp 	struct vattr attr;
2365e9c0cc15SPoul-Henning Kamp 	struct vnode *vp;
2366e9c0cc15SPoul-Henning Kamp 	struct nameidata nd;
2367e9c0cc15SPoul-Henning Kamp 	int error;
2368e9c0cc15SPoul-Henning Kamp 
2369acd3428bSRobert Watson 	error = priv_check(td, PRIV_SWAPON);
2370e9c0cc15SPoul-Henning Kamp 	if (error)
2371acd3428bSRobert Watson 		return (error);
2372e9c0cc15SPoul-Henning Kamp 
237304533e1eSKonstantin Belousov 	sx_xlock(&swdev_syscall_lock);
2374e9c0cc15SPoul-Henning Kamp 
2375e9c0cc15SPoul-Henning Kamp 	/*
2376e9c0cc15SPoul-Henning Kamp 	 * Swap metadata may not fit in the KVM if we have physical
2377e9c0cc15SPoul-Henning Kamp 	 * memory of >1GB.
2378e9c0cc15SPoul-Henning Kamp 	 */
2379f425ab8eSKonstantin Belousov 	if (swblk_zone == NULL) {
2380e9c0cc15SPoul-Henning Kamp 		error = ENOMEM;
2381e9c0cc15SPoul-Henning Kamp 		goto done;
2382e9c0cc15SPoul-Henning Kamp 	}
2383e9c0cc15SPoul-Henning Kamp 
2384d9135e72SRobert Watson 	NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2385d9135e72SRobert Watson 	    uap->name, td);
2386e9c0cc15SPoul-Henning Kamp 	error = namei(&nd);
2387e9c0cc15SPoul-Henning Kamp 	if (error)
2388e9c0cc15SPoul-Henning Kamp 		goto done;
2389e9c0cc15SPoul-Henning Kamp 
2390e9c0cc15SPoul-Henning Kamp 	NDFREE(&nd, NDF_ONLY_PNBUF);
2391e9c0cc15SPoul-Henning Kamp 	vp = nd.ni_vp;
2392e9c0cc15SPoul-Henning Kamp 
23937ad2a82dSMateusz Guzik 	if (vn_isdisk_error(vp, &error)) {
239488ad2d7bSKonstantin Belousov 		error = swapongeom(vp);
239520da9c2eSPoul-Henning Kamp 	} else if (vp->v_type == VREG &&
2396e9c0cc15SPoul-Henning Kamp 	    (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
23970359a12eSAttilio Rao 	    (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2398e9c0cc15SPoul-Henning Kamp 		/*
2399e9c0cc15SPoul-Henning Kamp 		 * Allow direct swapping to NFS regular files in the same
2400e9c0cc15SPoul-Henning Kamp 		 * way that nfs_mountroot() sets up diskless swapping.
2401e9c0cc15SPoul-Henning Kamp 		 */
240259efee01SPoul-Henning Kamp 		error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2403e9c0cc15SPoul-Henning Kamp 	}
2404e9c0cc15SPoul-Henning Kamp 
2405e9c0cc15SPoul-Henning Kamp 	if (error)
2406e9c0cc15SPoul-Henning Kamp 		vrele(vp);
2407e9c0cc15SPoul-Henning Kamp done:
240804533e1eSKonstantin Belousov 	sx_xunlock(&swdev_syscall_lock);
2409e9c0cc15SPoul-Henning Kamp 	return (error);
2410e9c0cc15SPoul-Henning Kamp }
2411e9c0cc15SPoul-Henning Kamp 
24123ff863f1SDag-Erling Smørgrav /*
24133ff863f1SDag-Erling Smørgrav  * Check that the total amount of swap currently configured does not
24143ff863f1SDag-Erling Smørgrav  * exceed half the theoretical maximum.  If it does, print a warning
241535872e79SKonstantin Belousov  * message.
24163ff863f1SDag-Erling Smørgrav  */
241735872e79SKonstantin Belousov static void
241835872e79SKonstantin Belousov swapon_check_swzone(void)
24193ff863f1SDag-Erling Smørgrav {
24203ff863f1SDag-Erling Smørgrav 
24213ff863f1SDag-Erling Smørgrav 	/* recommend using no more than half that amount */
2422303fa05aSKonstantin Belousov 	if (swap_total > swap_maxpages / 2) {
24233ff863f1SDag-Erling Smørgrav 		printf("warning: total configured swap (%lu pages) "
24243ff863f1SDag-Erling Smørgrav 		    "exceeds maximum recommended amount (%lu pages).\n",
2425303fa05aSKonstantin Belousov 		    swap_total, swap_maxpages / 2);
24263ff863f1SDag-Erling Smørgrav 		printf("warning: increase kern.maxswzone "
24273ff863f1SDag-Erling Smørgrav 		    "or reduce amount of swap.\n");
24283ff863f1SDag-Erling Smørgrav 	}
24293ff863f1SDag-Erling Smørgrav }
24303ff863f1SDag-Erling Smørgrav 
243159efee01SPoul-Henning Kamp static void
24322cc718a1SKonstantin Belousov swaponsomething(struct vnode *vp, void *id, u_long nblks,
24332cc718a1SKonstantin Belousov     sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2434e9c0cc15SPoul-Henning Kamp {
24352d9974c1SAlan Cox 	struct swdevt *sp, *tsp;
243634e2051fSMark Johnston 	daddr_t dvbase;
2437e9c0cc15SPoul-Henning Kamp 
2438e9c0cc15SPoul-Henning Kamp 	/*
2439e9c0cc15SPoul-Henning Kamp 	 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2440e9c0cc15SPoul-Henning Kamp 	 * First chop nblks off to page-align it, then convert.
2441e9c0cc15SPoul-Henning Kamp 	 *
2442e9c0cc15SPoul-Henning Kamp 	 * sw->sw_nblks is in page-sized chunks now too.
2443e9c0cc15SPoul-Henning Kamp 	 */
2444e9c0cc15SPoul-Henning Kamp 	nblks &= ~(ctodb(1) - 1);
2445e9c0cc15SPoul-Henning Kamp 	nblks = dbtoc(nblks);
2446e9c0cc15SPoul-Henning Kamp 
24478f60c087SPoul-Henning Kamp 	sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
244800fd73d2SDoug Moore 	sp->sw_blist = blist_create(nblks, M_WAITOK);
2449dee34ca4SPoul-Henning Kamp 	sp->sw_vp = vp;
2450dee34ca4SPoul-Henning Kamp 	sp->sw_id = id;
2451f3732fd1SPoul-Henning Kamp 	sp->sw_dev = dev;
2452e9c0cc15SPoul-Henning Kamp 	sp->sw_nblks = nblks;
2453e9c0cc15SPoul-Henning Kamp 	sp->sw_used = 0;
245459efee01SPoul-Henning Kamp 	sp->sw_strategy = strategy;
2455dee34ca4SPoul-Henning Kamp 	sp->sw_close = close;
24562cc718a1SKonstantin Belousov 	sp->sw_flags = flags;
2457e9c0cc15SPoul-Henning Kamp 
2458e9c0cc15SPoul-Henning Kamp 	/*
2459504f5e29SDoug Moore 	 * Do not free the first blocks in order to avoid overwriting
24608f60c087SPoul-Henning Kamp 	 * any bsd label at the front of the partition
2461e9c0cc15SPoul-Henning Kamp 	 */
2462504f5e29SDoug Moore 	blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2463504f5e29SDoug Moore 	    nblks - howmany(BBSIZE, PAGE_SIZE));
2464e9c0cc15SPoul-Henning Kamp 
24652d9974c1SAlan Cox 	dvbase = 0;
246620da9c2eSPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
24672d9974c1SAlan Cox 	TAILQ_FOREACH(tsp, &swtailq, sw_list) {
24682d9974c1SAlan Cox 		if (tsp->sw_end >= dvbase) {
24692d9974c1SAlan Cox 			/*
24702d9974c1SAlan Cox 			 * We put one uncovered page between the devices
24712d9974c1SAlan Cox 			 * in order to definitively prevent any cross-device
24722d9974c1SAlan Cox 			 * I/O requests
24732d9974c1SAlan Cox 			 */
24742d9974c1SAlan Cox 			dvbase = tsp->sw_end + 1;
24752d9974c1SAlan Cox 		}
24762d9974c1SAlan Cox 	}
24772d9974c1SAlan Cox 	sp->sw_first = dvbase;
24782d9974c1SAlan Cox 	sp->sw_end = dvbase + nblks;
24798f60c087SPoul-Henning Kamp 	TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
24808f60c087SPoul-Henning Kamp 	nswapdev++;
2481504f5e29SDoug Moore 	swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2482e8bb589dSMatt Macy 	swap_total += nblks;
248335872e79SKonstantin Belousov 	swapon_check_swzone();
2484d05bc129SAlan Cox 	swp_sizecheck();
2485d05bc129SAlan Cox 	mtx_unlock(&sw_dev_mtx);
2486b1fd102eSMark Johnston 	EVENTHANDLER_INVOKE(swapon, sp);
248759efee01SPoul-Henning Kamp }
2488e9c0cc15SPoul-Henning Kamp 
2489e9c0cc15SPoul-Henning Kamp /*
2490e9c0cc15SPoul-Henning Kamp  * SYSCALL: swapoff(devname)
2491e9c0cc15SPoul-Henning Kamp  *
2492e9c0cc15SPoul-Henning Kamp  * Disable swapping on the given device.
2493dee34ca4SPoul-Henning Kamp  *
2494dee34ca4SPoul-Henning Kamp  * XXX: Badly designed system call: it should use a device index
2495dee34ca4SPoul-Henning Kamp  * rather than filename as specification.  We keep sw_vp around
2496dee34ca4SPoul-Henning Kamp  * only to make this work.
2497e9c0cc15SPoul-Henning Kamp  */
2498e9c0cc15SPoul-Henning Kamp #ifndef _SYS_SYSPROTO_H_
2499e9c0cc15SPoul-Henning Kamp struct swapoff_args {
2500e9c0cc15SPoul-Henning Kamp 	char *name;
2501e9c0cc15SPoul-Henning Kamp };
2502e9c0cc15SPoul-Henning Kamp #endif
2503e9c0cc15SPoul-Henning Kamp 
2504e9c0cc15SPoul-Henning Kamp /*
2505e9c0cc15SPoul-Henning Kamp  * MPSAFE
2506e9c0cc15SPoul-Henning Kamp  */
2507e9c0cc15SPoul-Henning Kamp /* ARGSUSED */
2508e9c0cc15SPoul-Henning Kamp int
25098451d0ddSKip Macy sys_swapoff(struct thread *td, struct swapoff_args *uap)
2510e9c0cc15SPoul-Henning Kamp {
2511e9c0cc15SPoul-Henning Kamp 	struct vnode *vp;
2512e9c0cc15SPoul-Henning Kamp 	struct nameidata nd;
2513e9c0cc15SPoul-Henning Kamp 	struct swdevt *sp;
25148f60c087SPoul-Henning Kamp 	int error;
2515e9c0cc15SPoul-Henning Kamp 
2516acd3428bSRobert Watson 	error = priv_check(td, PRIV_SWAPOFF);
2517e9c0cc15SPoul-Henning Kamp 	if (error)
25180909f38aSPawel Jakub Dawidek 		return (error);
2519e9c0cc15SPoul-Henning Kamp 
252004533e1eSKonstantin Belousov 	sx_xlock(&swdev_syscall_lock);
2521e9c0cc15SPoul-Henning Kamp 
2522d9135e72SRobert Watson 	NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2523d9135e72SRobert Watson 	    td);
2524e9c0cc15SPoul-Henning Kamp 	error = namei(&nd);
2525e9c0cc15SPoul-Henning Kamp 	if (error)
2526e9c0cc15SPoul-Henning Kamp 		goto done;
2527e9c0cc15SPoul-Henning Kamp 	NDFREE(&nd, NDF_ONLY_PNBUF);
2528e9c0cc15SPoul-Henning Kamp 	vp = nd.ni_vp;
2529e9c0cc15SPoul-Henning Kamp 
253020da9c2eSPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
25318f60c087SPoul-Henning Kamp 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2532dee34ca4SPoul-Henning Kamp 		if (sp->sw_vp == vp)
25330909f38aSPawel Jakub Dawidek 			break;
2534e9c0cc15SPoul-Henning Kamp 	}
253520da9c2eSPoul-Henning Kamp 	mtx_unlock(&sw_dev_mtx);
25360909f38aSPawel Jakub Dawidek 	if (sp == NULL) {
2537e9c0cc15SPoul-Henning Kamp 		error = EINVAL;
2538e9c0cc15SPoul-Henning Kamp 		goto done;
25390909f38aSPawel Jakub Dawidek 	}
254035918c55SChristian S.J. Peron 	error = swapoff_one(sp, td->td_ucred);
25410909f38aSPawel Jakub Dawidek done:
254204533e1eSKonstantin Belousov 	sx_xunlock(&swdev_syscall_lock);
25430909f38aSPawel Jakub Dawidek 	return (error);
25440909f38aSPawel Jakub Dawidek }
25450909f38aSPawel Jakub Dawidek 
25460909f38aSPawel Jakub Dawidek static int
254735918c55SChristian S.J. Peron swapoff_one(struct swdevt *sp, struct ucred *cred)
25480909f38aSPawel Jakub Dawidek {
254903bdd65fSAlan Cox 	u_long nblks;
2550e9c0cc15SPoul-Henning Kamp #ifdef MAC
25510909f38aSPawel Jakub Dawidek 	int error;
2552e9c0cc15SPoul-Henning Kamp #endif
2553e9c0cc15SPoul-Henning Kamp 
255404533e1eSKonstantin Belousov 	sx_assert(&swdev_syscall_lock, SA_XLOCKED);
25550909f38aSPawel Jakub Dawidek #ifdef MAC
2556cb05b60aSAttilio Rao 	(void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
255735918c55SChristian S.J. Peron 	error = mac_system_check_swapoff(cred, sp->sw_vp);
2558b249ce48SMateusz Guzik 	(void) VOP_UNLOCK(sp->sw_vp);
25590909f38aSPawel Jakub Dawidek 	if (error != 0)
25600909f38aSPawel Jakub Dawidek 		return (error);
25610909f38aSPawel Jakub Dawidek #endif
2562e9c0cc15SPoul-Henning Kamp 	nblks = sp->sw_nblks;
2563e9c0cc15SPoul-Henning Kamp 
2564e9c0cc15SPoul-Henning Kamp 	/*
2565e9c0cc15SPoul-Henning Kamp 	 * We can turn off this swap device safely only if the
2566e9c0cc15SPoul-Henning Kamp 	 * available virtual memory in the system will fit the amount
2567e9c0cc15SPoul-Henning Kamp 	 * of data we will have to page back in, plus an epsilon so
2568e9c0cc15SPoul-Henning Kamp 	 * the system doesn't become critically low on swap space.
2569e9c0cc15SPoul-Henning Kamp 	 */
2570e2068d0bSJeff Roberson 	if (vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
25710909f38aSPawel Jakub Dawidek 		return (ENOMEM);
2572e9c0cc15SPoul-Henning Kamp 
2573e9c0cc15SPoul-Henning Kamp 	/*
2574e9c0cc15SPoul-Henning Kamp 	 * Prevent further allocations on this device.
2575e9c0cc15SPoul-Henning Kamp 	 */
25762928cef7SAlan Cox 	mtx_lock(&sw_dev_mtx);
2577e9c0cc15SPoul-Henning Kamp 	sp->sw_flags |= SW_CLOSING;
257803bdd65fSAlan Cox 	swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2579e8bb589dSMatt Macy 	swap_total -= nblks;
25802928cef7SAlan Cox 	mtx_unlock(&sw_dev_mtx);
2581e9c0cc15SPoul-Henning Kamp 
2582e9c0cc15SPoul-Henning Kamp 	/*
2583e9c0cc15SPoul-Henning Kamp 	 * Page in the contents of the device and close it.
2584e9c0cc15SPoul-Henning Kamp 	 */
2585b3fed13eSDavid Schultz 	swap_pager_swapoff(sp);
2586e9c0cc15SPoul-Henning Kamp 
258735918c55SChristian S.J. Peron 	sp->sw_close(curthread, sp);
258820da9c2eSPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
25899e3e3fe5SWarner Losh 	sp->sw_id = NULL;
25908f60c087SPoul-Henning Kamp 	TAILQ_REMOVE(&swtailq, sp, sw_list);
25910676a140SAlan Cox 	nswapdev--;
25927dea2c2eSAlan Cox 	if (nswapdev == 0) {
25937dea2c2eSAlan Cox 		swap_pager_full = 2;
25947dea2c2eSAlan Cox 		swap_pager_almost_full = 1;
25957dea2c2eSAlan Cox 	}
25968f60c087SPoul-Henning Kamp 	if (swdevhd == sp)
25978f60c087SPoul-Henning Kamp 		swdevhd = NULL;
2598d05bc129SAlan Cox 	mtx_unlock(&sw_dev_mtx);
25998f60c087SPoul-Henning Kamp 	blist_destroy(sp->sw_blist);
26008f60c087SPoul-Henning Kamp 	free(sp, M_VMPGDATA);
26010909f38aSPawel Jakub Dawidek 	return (0);
26020909f38aSPawel Jakub Dawidek }
2603e9c0cc15SPoul-Henning Kamp 
26040909f38aSPawel Jakub Dawidek void
26050909f38aSPawel Jakub Dawidek swapoff_all(void)
26060909f38aSPawel Jakub Dawidek {
26070909f38aSPawel Jakub Dawidek 	struct swdevt *sp, *spt;
26080909f38aSPawel Jakub Dawidek 	const char *devname;
26090909f38aSPawel Jakub Dawidek 	int error;
26100909f38aSPawel Jakub Dawidek 
261104533e1eSKonstantin Belousov 	sx_xlock(&swdev_syscall_lock);
26120909f38aSPawel Jakub Dawidek 
26130909f38aSPawel Jakub Dawidek 	mtx_lock(&sw_dev_mtx);
26140909f38aSPawel Jakub Dawidek 	TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
26150909f38aSPawel Jakub Dawidek 		mtx_unlock(&sw_dev_mtx);
26167ad2a82dSMateusz Guzik 		if (vn_isdisk(sp->sw_vp))
26177870adb6SEd Schouten 			devname = devtoname(sp->sw_vp->v_rdev);
26180909f38aSPawel Jakub Dawidek 		else
26190909f38aSPawel Jakub Dawidek 			devname = "[file]";
262035918c55SChristian S.J. Peron 		error = swapoff_one(sp, thread0.td_ucred);
26210909f38aSPawel Jakub Dawidek 		if (error != 0) {
26220909f38aSPawel Jakub Dawidek 			printf("Cannot remove swap device %s (error=%d), "
26230909f38aSPawel Jakub Dawidek 			    "skipping.\n", devname, error);
26240909f38aSPawel Jakub Dawidek 		} else if (bootverbose) {
26250909f38aSPawel Jakub Dawidek 			printf("Swap device %s removed.\n", devname);
26260909f38aSPawel Jakub Dawidek 		}
26270909f38aSPawel Jakub Dawidek 		mtx_lock(&sw_dev_mtx);
26280909f38aSPawel Jakub Dawidek 	}
26290909f38aSPawel Jakub Dawidek 	mtx_unlock(&sw_dev_mtx);
26300909f38aSPawel Jakub Dawidek 
263104533e1eSKonstantin Belousov 	sx_xunlock(&swdev_syscall_lock);
2632e9c0cc15SPoul-Henning Kamp }
2633e9c0cc15SPoul-Henning Kamp 
2634567104a1SPoul-Henning Kamp void
2635567104a1SPoul-Henning Kamp swap_pager_status(int *total, int *used)
2636567104a1SPoul-Henning Kamp {
2637567104a1SPoul-Henning Kamp 
26387ce3a312SMateusz Guzik 	*total = swap_total;
26397ce3a312SMateusz Guzik 	*used = swap_total - swap_pager_avail -
26407ce3a312SMateusz Guzik 	    nswapdev * howmany(BBSIZE, PAGE_SIZE);
2641567104a1SPoul-Henning Kamp }
2642567104a1SPoul-Henning Kamp 
2643dda4f960SKonstantin Belousov int
2644dda4f960SKonstantin Belousov swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2645dda4f960SKonstantin Belousov {
2646dda4f960SKonstantin Belousov 	struct swdevt *sp;
26477870adb6SEd Schouten 	const char *tmp_devname;
2648dda4f960SKonstantin Belousov 	int error, n;
2649dda4f960SKonstantin Belousov 
2650dda4f960SKonstantin Belousov 	n = 0;
2651dda4f960SKonstantin Belousov 	error = ENOENT;
2652dda4f960SKonstantin Belousov 	mtx_lock(&sw_dev_mtx);
2653dda4f960SKonstantin Belousov 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2654dda4f960SKonstantin Belousov 		if (n != name) {
2655dda4f960SKonstantin Belousov 			n++;
2656dda4f960SKonstantin Belousov 			continue;
2657dda4f960SKonstantin Belousov 		}
2658dda4f960SKonstantin Belousov 		xs->xsw_version = XSWDEV_VERSION;
2659dda4f960SKonstantin Belousov 		xs->xsw_dev = sp->sw_dev;
2660dda4f960SKonstantin Belousov 		xs->xsw_flags = sp->sw_flags;
2661dda4f960SKonstantin Belousov 		xs->xsw_nblks = sp->sw_nblks;
2662dda4f960SKonstantin Belousov 		xs->xsw_used = sp->sw_used;
2663dda4f960SKonstantin Belousov 		if (devname != NULL) {
26647ad2a82dSMateusz Guzik 			if (vn_isdisk(sp->sw_vp))
26657870adb6SEd Schouten 				tmp_devname = devtoname(sp->sw_vp->v_rdev);
2666dda4f960SKonstantin Belousov 			else
2667dda4f960SKonstantin Belousov 				tmp_devname = "[file]";
2668dda4f960SKonstantin Belousov 			strncpy(devname, tmp_devname, len);
2669dda4f960SKonstantin Belousov 		}
2670dda4f960SKonstantin Belousov 		error = 0;
2671dda4f960SKonstantin Belousov 		break;
2672dda4f960SKonstantin Belousov 	}
2673dda4f960SKonstantin Belousov 	mtx_unlock(&sw_dev_mtx);
2674dda4f960SKonstantin Belousov 	return (error);
2675dda4f960SKonstantin Belousov }
2676dda4f960SKonstantin Belousov 
267769921123SKonstantin Belousov #if defined(COMPAT_FREEBSD11)
267869921123SKonstantin Belousov #define XSWDEV_VERSION_11	1
267969921123SKonstantin Belousov struct xswdev11 {
268069921123SKonstantin Belousov 	u_int	xsw_version;
268169921123SKonstantin Belousov 	uint32_t xsw_dev;
268269921123SKonstantin Belousov 	int	xsw_flags;
268369921123SKonstantin Belousov 	int	xsw_nblks;
268469921123SKonstantin Belousov 	int     xsw_used;
268569921123SKonstantin Belousov };
268669921123SKonstantin Belousov #endif
268769921123SKonstantin Belousov 
2688f6d281e8SKonstantin Belousov #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2689f6d281e8SKonstantin Belousov struct xswdev32 {
2690f6d281e8SKonstantin Belousov 	u_int	xsw_version;
2691f6d281e8SKonstantin Belousov 	u_int	xsw_dev1, xsw_dev2;
2692f6d281e8SKonstantin Belousov 	int	xsw_flags;
2693f6d281e8SKonstantin Belousov 	int	xsw_nblks;
2694f6d281e8SKonstantin Belousov 	int     xsw_used;
2695f6d281e8SKonstantin Belousov };
2696f6d281e8SKonstantin Belousov #endif
2697f6d281e8SKonstantin Belousov 
2698e9c0cc15SPoul-Henning Kamp static int
2699e9c0cc15SPoul-Henning Kamp sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2700e9c0cc15SPoul-Henning Kamp {
2701e9c0cc15SPoul-Henning Kamp 	struct xswdev xs;
2702f6d281e8SKonstantin Belousov #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2703f6d281e8SKonstantin Belousov 	struct xswdev32 xs32;
2704f6d281e8SKonstantin Belousov #endif
270569921123SKonstantin Belousov #if defined(COMPAT_FREEBSD11)
270669921123SKonstantin Belousov 	struct xswdev11 xs11;
270769921123SKonstantin Belousov #endif
2708dda4f960SKonstantin Belousov 	int error;
2709e9c0cc15SPoul-Henning Kamp 
2710e9c0cc15SPoul-Henning Kamp 	if (arg2 != 1)			/* name length */
2711e9c0cc15SPoul-Henning Kamp 		return (EINVAL);
271206d1fd9fSMark Johnston 
271306d1fd9fSMark Johnston 	memset(&xs, 0, sizeof(xs));
2714dda4f960SKonstantin Belousov 	error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2715dda4f960SKonstantin Belousov 	if (error != 0)
2716dda4f960SKonstantin Belousov 		return (error);
2717f6d281e8SKonstantin Belousov #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2718f6d281e8SKonstantin Belousov 	if (req->oldlen == sizeof(xs32)) {
271906d1fd9fSMark Johnston 		memset(&xs32, 0, sizeof(xs32));
2720f6d281e8SKonstantin Belousov 		xs32.xsw_version = XSWDEV_VERSION;
2721f6d281e8SKonstantin Belousov 		xs32.xsw_dev1 = xs.xsw_dev;
2722f6d281e8SKonstantin Belousov 		xs32.xsw_dev2 = xs.xsw_dev >> 32;
2723f6d281e8SKonstantin Belousov 		xs32.xsw_flags = xs.xsw_flags;
2724f6d281e8SKonstantin Belousov 		xs32.xsw_nblks = xs.xsw_nblks;
2725f6d281e8SKonstantin Belousov 		xs32.xsw_used = xs.xsw_used;
2726f6d281e8SKonstantin Belousov 		error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2727f6d281e8SKonstantin Belousov 		return (error);
2728f6d281e8SKonstantin Belousov 	}
2729f6d281e8SKonstantin Belousov #endif
273069921123SKonstantin Belousov #if defined(COMPAT_FREEBSD11)
273169921123SKonstantin Belousov 	if (req->oldlen == sizeof(xs11)) {
273206d1fd9fSMark Johnston 		memset(&xs11, 0, sizeof(xs11));
273369921123SKonstantin Belousov 		xs11.xsw_version = XSWDEV_VERSION_11;
273469921123SKonstantin Belousov 		xs11.xsw_dev = xs.xsw_dev; /* truncation */
273569921123SKonstantin Belousov 		xs11.xsw_flags = xs.xsw_flags;
273669921123SKonstantin Belousov 		xs11.xsw_nblks = xs.xsw_nblks;
273769921123SKonstantin Belousov 		xs11.xsw_used = xs.xsw_used;
273869921123SKonstantin Belousov 		error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2739f6d281e8SKonstantin Belousov 		return (error);
2740f6d281e8SKonstantin Belousov 	}
274169921123SKonstantin Belousov #endif
2742e9c0cc15SPoul-Henning Kamp 	error = SYSCTL_OUT(req, &xs, sizeof(xs));
2743e9c0cc15SPoul-Henning Kamp 	return (error);
2744e9c0cc15SPoul-Henning Kamp }
2745e9c0cc15SPoul-Henning Kamp 
27468f60c087SPoul-Henning Kamp SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2747e9c0cc15SPoul-Henning Kamp     "Number of swap devices");
27484c36e917SKonstantin Belousov SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
27494c36e917SKonstantin Belousov     sysctl_vm_swap_info,
2750e9c0cc15SPoul-Henning Kamp     "Swap statistics by device");
2751ec38b344SPoul-Henning Kamp 
2752ec38b344SPoul-Henning Kamp /*
2753f425ab8eSKonstantin Belousov  * Count the approximate swap usage in pages for a vmspace.  The
2754f425ab8eSKonstantin Belousov  * shadowed or not yet copied on write swap blocks are not accounted.
2755ec38b344SPoul-Henning Kamp  * The map must be locked.
2756ec38b344SPoul-Henning Kamp  */
27572860553aSRebecca Cran long
2758ec38b344SPoul-Henning Kamp vmspace_swap_count(struct vmspace *vmspace)
2759ec38b344SPoul-Henning Kamp {
276065d8409cSRebecca Cran 	vm_map_t map;
2761ec38b344SPoul-Henning Kamp 	vm_map_entry_t cur;
276265d8409cSRebecca Cran 	vm_object_t object;
2763f425ab8eSKonstantin Belousov 	struct swblk *sb;
2764f425ab8eSKonstantin Belousov 	vm_pindex_t e, pi;
2765f425ab8eSKonstantin Belousov 	long count;
2766f425ab8eSKonstantin Belousov 	int i;
276765d8409cSRebecca Cran 
276865d8409cSRebecca Cran 	map = &vmspace->vm_map;
276965d8409cSRebecca Cran 	count = 0;
2770ec38b344SPoul-Henning Kamp 
27712288078cSDoug Moore 	VM_MAP_ENTRY_FOREACH(cur, map) {
2772f425ab8eSKonstantin Belousov 		if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2773f425ab8eSKonstantin Belousov 			continue;
2774f425ab8eSKonstantin Belousov 		object = cur->object.vm_object;
27754b8365d7SKonstantin Belousov 		if (object == NULL || (object->flags & OBJ_SWAP) == 0)
2776f425ab8eSKonstantin Belousov 			continue;
2777f425ab8eSKonstantin Belousov 		VM_OBJECT_RLOCK(object);
27784b8365d7SKonstantin Belousov 		if ((object->flags & OBJ_SWAP) == 0)
2779f425ab8eSKonstantin Belousov 			goto unlock;
2780f425ab8eSKonstantin Belousov 		pi = OFF_TO_IDX(cur->offset);
2781f425ab8eSKonstantin Belousov 		e = pi + OFF_TO_IDX(cur->end - cur->start);
2782f425ab8eSKonstantin Belousov 		for (;; pi = sb->p + SWAP_META_PAGES) {
2783f425ab8eSKonstantin Belousov 			sb = SWAP_PCTRIE_LOOKUP_GE(
2784f425ab8eSKonstantin Belousov 			    &object->un_pager.swp.swp_blks, pi);
2785f425ab8eSKonstantin Belousov 			if (sb == NULL || sb->p >= e)
2786f425ab8eSKonstantin Belousov 				break;
2787f425ab8eSKonstantin Belousov 			for (i = 0; i < SWAP_META_PAGES; i++) {
2788f425ab8eSKonstantin Belousov 				if (sb->p + i < e &&
2789f425ab8eSKonstantin Belousov 				    sb->d[i] != SWAPBLK_NONE)
2790f425ab8eSKonstantin Belousov 					count++;
2791ec38b344SPoul-Henning Kamp 			}
2792ec38b344SPoul-Henning Kamp 		}
2793f425ab8eSKonstantin Belousov unlock:
2794f425ab8eSKonstantin Belousov 		VM_OBJECT_RUNLOCK(object);
2795ec38b344SPoul-Henning Kamp 	}
2796ec38b344SPoul-Henning Kamp 	return (count);
2797ec38b344SPoul-Henning Kamp }
2798dee34ca4SPoul-Henning Kamp 
2799dee34ca4SPoul-Henning Kamp /*
2800dee34ca4SPoul-Henning Kamp  * GEOM backend
2801dee34ca4SPoul-Henning Kamp  *
2802dee34ca4SPoul-Henning Kamp  * Swapping onto disk devices.
2803dee34ca4SPoul-Henning Kamp  *
2804dee34ca4SPoul-Henning Kamp  */
2805dee34ca4SPoul-Henning Kamp 
28065721c9c7SPoul-Henning Kamp static g_orphan_t swapgeom_orphan;
28075721c9c7SPoul-Henning Kamp 
2808dee34ca4SPoul-Henning Kamp static struct g_class g_swap_class = {
2809dee34ca4SPoul-Henning Kamp 	.name = "SWAP",
28105721c9c7SPoul-Henning Kamp 	.version = G_VERSION,
28115721c9c7SPoul-Henning Kamp 	.orphan = swapgeom_orphan,
2812dee34ca4SPoul-Henning Kamp };
2813dee34ca4SPoul-Henning Kamp 
2814dee34ca4SPoul-Henning Kamp DECLARE_GEOM_CLASS(g_swap_class, g_class);
2815dee34ca4SPoul-Henning Kamp 
2816dee34ca4SPoul-Henning Kamp static void
28173398491bSAlexander Motin swapgeom_close_ev(void *arg, int flags)
28183398491bSAlexander Motin {
28193398491bSAlexander Motin 	struct g_consumer *cp;
28203398491bSAlexander Motin 
28213398491bSAlexander Motin 	cp = arg;
28223398491bSAlexander Motin 	g_access(cp, -1, -1, 0);
28233398491bSAlexander Motin 	g_detach(cp);
28243398491bSAlexander Motin 	g_destroy_consumer(cp);
28253398491bSAlexander Motin }
28263398491bSAlexander Motin 
28279e3e3fe5SWarner Losh /*
28289e3e3fe5SWarner Losh  * Add a reference to the g_consumer for an inflight transaction.
28299e3e3fe5SWarner Losh  */
28309e3e3fe5SWarner Losh static void
28319e3e3fe5SWarner Losh swapgeom_acquire(struct g_consumer *cp)
28329e3e3fe5SWarner Losh {
28339e3e3fe5SWarner Losh 
28349e3e3fe5SWarner Losh 	mtx_assert(&sw_dev_mtx, MA_OWNED);
28359e3e3fe5SWarner Losh 	cp->index++;
28369e3e3fe5SWarner Losh }
28379e3e3fe5SWarner Losh 
28389e3e3fe5SWarner Losh /*
28390c657d22SKonstantin Belousov  * Remove a reference from the g_consumer.  Post a close event if all
28400c657d22SKonstantin Belousov  * references go away, since the function might be called from the
28410c657d22SKonstantin Belousov  * biodone context.
28429e3e3fe5SWarner Losh  */
28439e3e3fe5SWarner Losh static void
28449e3e3fe5SWarner Losh swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
28459e3e3fe5SWarner Losh {
28469e3e3fe5SWarner Losh 
28479e3e3fe5SWarner Losh 	mtx_assert(&sw_dev_mtx, MA_OWNED);
28489e3e3fe5SWarner Losh 	cp->index--;
28499e3e3fe5SWarner Losh 	if (cp->index == 0) {
28509e3e3fe5SWarner Losh 		if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
28519e3e3fe5SWarner Losh 			sp->sw_id = NULL;
28529e3e3fe5SWarner Losh 	}
28539e3e3fe5SWarner Losh }
28549e3e3fe5SWarner Losh 
28553398491bSAlexander Motin static void
2856dee34ca4SPoul-Henning Kamp swapgeom_done(struct bio *bp2)
2857dee34ca4SPoul-Henning Kamp {
28583398491bSAlexander Motin 	struct swdevt *sp;
2859dee34ca4SPoul-Henning Kamp 	struct buf *bp;
28603398491bSAlexander Motin 	struct g_consumer *cp;
2861dee34ca4SPoul-Henning Kamp 
2862dee34ca4SPoul-Henning Kamp 	bp = bp2->bio_caller2;
28633398491bSAlexander Motin 	cp = bp2->bio_from;
2864c5d3d25eSPoul-Henning Kamp 	bp->b_ioflags = bp2->bio_flags;
2865dee34ca4SPoul-Henning Kamp 	if (bp2->bio_error)
2866dee34ca4SPoul-Henning Kamp 		bp->b_ioflags |= BIO_ERROR;
2867c5d3d25eSPoul-Henning Kamp 	bp->b_resid = bp->b_bcount - bp2->bio_completed;
2868c5d3d25eSPoul-Henning Kamp 	bp->b_error = bp2->bio_error;
2869756a5412SGleb Smirnoff 	bp->b_caller1 = NULL;
2870dee34ca4SPoul-Henning Kamp 	bufdone(bp);
28713398491bSAlexander Motin 	sp = bp2->bio_caller1;
28729e3e3fe5SWarner Losh 	mtx_lock(&sw_dev_mtx);
28739e3e3fe5SWarner Losh 	swapgeom_release(cp, sp);
28743398491bSAlexander Motin 	mtx_unlock(&sw_dev_mtx);
2875dee34ca4SPoul-Henning Kamp 	g_destroy_bio(bp2);
2876dee34ca4SPoul-Henning Kamp }
2877dee34ca4SPoul-Henning Kamp 
2878dee34ca4SPoul-Henning Kamp static void
2879dee34ca4SPoul-Henning Kamp swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2880dee34ca4SPoul-Henning Kamp {
2881dee34ca4SPoul-Henning Kamp 	struct bio *bio;
2882dee34ca4SPoul-Henning Kamp 	struct g_consumer *cp;
2883dee34ca4SPoul-Henning Kamp 
28843398491bSAlexander Motin 	mtx_lock(&sw_dev_mtx);
2885dee34ca4SPoul-Henning Kamp 	cp = sp->sw_id;
2886dee34ca4SPoul-Henning Kamp 	if (cp == NULL) {
28873398491bSAlexander Motin 		mtx_unlock(&sw_dev_mtx);
2888dee34ca4SPoul-Henning Kamp 		bp->b_error = ENXIO;
2889dee34ca4SPoul-Henning Kamp 		bp->b_ioflags |= BIO_ERROR;
2890dee34ca4SPoul-Henning Kamp 		bufdone(bp);
2891dee34ca4SPoul-Henning Kamp 		return;
2892dee34ca4SPoul-Henning Kamp 	}
28939e3e3fe5SWarner Losh 	swapgeom_acquire(cp);
28943398491bSAlexander Motin 	mtx_unlock(&sw_dev_mtx);
289511041003SKonstantin Belousov 	if (bp->b_iocmd == BIO_WRITE)
289611041003SKonstantin Belousov 		bio = g_new_bio();
289711041003SKonstantin Belousov 	else
28984f8205e5SPoul-Henning Kamp 		bio = g_alloc_bio();
28994f8205e5SPoul-Henning Kamp 	if (bio == NULL) {
29009e3e3fe5SWarner Losh 		mtx_lock(&sw_dev_mtx);
29019e3e3fe5SWarner Losh 		swapgeom_release(cp, sp);
29029e3e3fe5SWarner Losh 		mtx_unlock(&sw_dev_mtx);
29033e5b6861SPoul-Henning Kamp 		bp->b_error = ENOMEM;
29043e5b6861SPoul-Henning Kamp 		bp->b_ioflags |= BIO_ERROR;
29050b208315SEdward Tomasz Napierala 		printf("swap_pager: cannot allocate bio\n");
29063e5b6861SPoul-Henning Kamp 		bufdone(bp);
29073e5b6861SPoul-Henning Kamp 		return;
29083e5b6861SPoul-Henning Kamp 	}
290911041003SKonstantin Belousov 
2910756a5412SGleb Smirnoff 	bp->b_caller1 = bio;
29113398491bSAlexander Motin 	bio->bio_caller1 = sp;
2912dee34ca4SPoul-Henning Kamp 	bio->bio_caller2 = bp;
2913c5d3d25eSPoul-Henning Kamp 	bio->bio_cmd = bp->b_iocmd;
2914dee34ca4SPoul-Henning Kamp 	bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2915dee34ca4SPoul-Henning Kamp 	bio->bio_length = bp->b_bcount;
2916dee34ca4SPoul-Henning Kamp 	bio->bio_done = swapgeom_done;
2917fade8dd7SJeff Roberson 	if (!buf_mapped(bp)) {
29182cc718a1SKonstantin Belousov 		bio->bio_ma = bp->b_pages;
29192cc718a1SKonstantin Belousov 		bio->bio_data = unmapped_buf;
29202cc718a1SKonstantin Belousov 		bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
29212cc718a1SKonstantin Belousov 		bio->bio_ma_n = bp->b_npages;
29222cc718a1SKonstantin Belousov 		bio->bio_flags |= BIO_UNMAPPED;
29232cc718a1SKonstantin Belousov 	} else {
29242cc718a1SKonstantin Belousov 		bio->bio_data = bp->b_data;
29252cc718a1SKonstantin Belousov 		bio->bio_ma = NULL;
29262cc718a1SKonstantin Belousov 	}
2927dee34ca4SPoul-Henning Kamp 	g_io_request(bio, cp);
2928dee34ca4SPoul-Henning Kamp 	return;
2929dee34ca4SPoul-Henning Kamp }
2930dee34ca4SPoul-Henning Kamp 
2931dee34ca4SPoul-Henning Kamp static void
2932dee34ca4SPoul-Henning Kamp swapgeom_orphan(struct g_consumer *cp)
2933dee34ca4SPoul-Henning Kamp {
2934dee34ca4SPoul-Henning Kamp 	struct swdevt *sp;
29353398491bSAlexander Motin 	int destroy;
2936dee34ca4SPoul-Henning Kamp 
2937dee34ca4SPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
29383398491bSAlexander Motin 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
29393398491bSAlexander Motin 		if (sp->sw_id == cp) {
29408f12d83aSAlexander Motin 			sp->sw_flags |= SW_CLOSING;
29413398491bSAlexander Motin 			break;
2942dee34ca4SPoul-Henning Kamp 		}
29433398491bSAlexander Motin 	}
29449e3e3fe5SWarner Losh 	/*
29459e3e3fe5SWarner Losh 	 * Drop reference we were created with. Do directly since we're in a
29469e3e3fe5SWarner Losh 	 * special context where we don't have to queue the call to
29479e3e3fe5SWarner Losh 	 * swapgeom_close_ev().
29489e3e3fe5SWarner Losh 	 */
29499e3e3fe5SWarner Losh 	cp->index--;
29503398491bSAlexander Motin 	destroy = ((sp != NULL) && (cp->index == 0));
29513398491bSAlexander Motin 	if (destroy)
29523398491bSAlexander Motin 		sp->sw_id = NULL;
29533398491bSAlexander Motin 	mtx_unlock(&sw_dev_mtx);
29543398491bSAlexander Motin 	if (destroy)
29553398491bSAlexander Motin 		swapgeom_close_ev(cp, 0);
2956dee34ca4SPoul-Henning Kamp }
2957dee34ca4SPoul-Henning Kamp 
2958dee34ca4SPoul-Henning Kamp static void
2959dee34ca4SPoul-Henning Kamp swapgeom_close(struct thread *td, struct swdevt *sw)
2960dee34ca4SPoul-Henning Kamp {
29613398491bSAlexander Motin 	struct g_consumer *cp;
2962dee34ca4SPoul-Henning Kamp 
29633398491bSAlexander Motin 	mtx_lock(&sw_dev_mtx);
29643398491bSAlexander Motin 	cp = sw->sw_id;
29653398491bSAlexander Motin 	sw->sw_id = NULL;
29663398491bSAlexander Motin 	mtx_unlock(&sw_dev_mtx);
29670c657d22SKonstantin Belousov 
29680c657d22SKonstantin Belousov 	/*
29690c657d22SKonstantin Belousov 	 * swapgeom_close() may be called from the biodone context,
29700c657d22SKonstantin Belousov 	 * where we cannot perform topology changes.  Delegate the
29710c657d22SKonstantin Belousov 	 * work to the events thread.
29720c657d22SKonstantin Belousov 	 */
29733398491bSAlexander Motin 	if (cp != NULL)
29743398491bSAlexander Motin 		g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2975dee34ca4SPoul-Henning Kamp }
2976dee34ca4SPoul-Henning Kamp 
297788ad2d7bSKonstantin Belousov static int
297888ad2d7bSKonstantin Belousov swapongeom_locked(struct cdev *dev, struct vnode *vp)
2979dee34ca4SPoul-Henning Kamp {
2980dee34ca4SPoul-Henning Kamp 	struct g_provider *pp;
2981dee34ca4SPoul-Henning Kamp 	struct g_consumer *cp;
2982dee34ca4SPoul-Henning Kamp 	static struct g_geom *gp;
2983dee34ca4SPoul-Henning Kamp 	struct swdevt *sp;
2984dee34ca4SPoul-Henning Kamp 	u_long nblks;
2985dee34ca4SPoul-Henning Kamp 	int error;
2986dee34ca4SPoul-Henning Kamp 
298788ad2d7bSKonstantin Belousov 	pp = g_dev_getprovider(dev);
298888ad2d7bSKonstantin Belousov 	if (pp == NULL)
298988ad2d7bSKonstantin Belousov 		return (ENODEV);
2990dee34ca4SPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
2991dee34ca4SPoul-Henning Kamp 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2992dee34ca4SPoul-Henning Kamp 		cp = sp->sw_id;
2993dee34ca4SPoul-Henning Kamp 		if (cp != NULL && cp->provider == pp) {
2994dee34ca4SPoul-Henning Kamp 			mtx_unlock(&sw_dev_mtx);
299588ad2d7bSKonstantin Belousov 			return (EBUSY);
2996dee34ca4SPoul-Henning Kamp 		}
2997dee34ca4SPoul-Henning Kamp 	}
2998dee34ca4SPoul-Henning Kamp 	mtx_unlock(&sw_dev_mtx);
29995721c9c7SPoul-Henning Kamp 	if (gp == NULL)
300002c62349SJaakko Heinonen 		gp = g_new_geomf(&g_swap_class, "swap");
3001dee34ca4SPoul-Henning Kamp 	cp = g_new_consumer(gp);
30029e3e3fe5SWarner Losh 	cp->index = 1;	/* Number of active I/Os, plus one for being active. */
30039e3e3fe5SWarner Losh 	cp->flags |=  G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
3004dee34ca4SPoul-Henning Kamp 	g_attach(cp, pp);
3005afeb65e6SPoul-Henning Kamp 	/*
3006afeb65e6SPoul-Henning Kamp 	 * XXX: Every time you think you can improve the margin for
3007afeb65e6SPoul-Henning Kamp 	 * footshooting, somebody depends on the ability to do so:
3008afeb65e6SPoul-Henning Kamp 	 * savecore(8) wants to write to our swapdev so we cannot
3009afeb65e6SPoul-Henning Kamp 	 * set an exclusive count :-(
3010afeb65e6SPoul-Henning Kamp 	 */
3011d2bae332SPoul-Henning Kamp 	error = g_access(cp, 1, 1, 0);
301288ad2d7bSKonstantin Belousov 	if (error != 0) {
3013dee34ca4SPoul-Henning Kamp 		g_detach(cp);
3014dee34ca4SPoul-Henning Kamp 		g_destroy_consumer(cp);
301588ad2d7bSKonstantin Belousov 		return (error);
3016dee34ca4SPoul-Henning Kamp 	}
3017dee34ca4SPoul-Henning Kamp 	nblks = pp->mediasize / DEV_BSIZE;
301888ad2d7bSKonstantin Belousov 	swaponsomething(vp, cp, nblks, swapgeom_strategy,
301988ad2d7bSKonstantin Belousov 	    swapgeom_close, dev2udev(dev),
30202cc718a1SKonstantin Belousov 	    (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
302188ad2d7bSKonstantin Belousov 	return (0);
3022dee34ca4SPoul-Henning Kamp }
3023dee34ca4SPoul-Henning Kamp 
3024dee34ca4SPoul-Henning Kamp static int
302588ad2d7bSKonstantin Belousov swapongeom(struct vnode *vp)
3026dee34ca4SPoul-Henning Kamp {
3027dee34ca4SPoul-Henning Kamp 	int error;
3028dee34ca4SPoul-Henning Kamp 
3029cb05b60aSAttilio Rao 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3030abd80ddbSMateusz Guzik 	if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) {
303188ad2d7bSKonstantin Belousov 		error = ENOENT;
303288ad2d7bSKonstantin Belousov 	} else {
303388ad2d7bSKonstantin Belousov 		g_topology_lock();
303488ad2d7bSKonstantin Belousov 		error = swapongeom_locked(vp->v_rdev, vp);
303588ad2d7bSKonstantin Belousov 		g_topology_unlock();
303688ad2d7bSKonstantin Belousov 	}
3037b249ce48SMateusz Guzik 	VOP_UNLOCK(vp);
3038dee34ca4SPoul-Henning Kamp 	return (error);
3039dee34ca4SPoul-Henning Kamp }
3040dee34ca4SPoul-Henning Kamp 
3041dee34ca4SPoul-Henning Kamp /*
3042dee34ca4SPoul-Henning Kamp  * VNODE backend
3043dee34ca4SPoul-Henning Kamp  *
3044dee34ca4SPoul-Henning Kamp  * This is used mainly for network filesystem (read: probably only tested
3045dee34ca4SPoul-Henning Kamp  * with NFS) swapfiles.
3046dee34ca4SPoul-Henning Kamp  *
3047dee34ca4SPoul-Henning Kamp  */
3048dee34ca4SPoul-Henning Kamp 
3049dee34ca4SPoul-Henning Kamp static void
3050dee34ca4SPoul-Henning Kamp swapdev_strategy(struct buf *bp, struct swdevt *sp)
3051dee34ca4SPoul-Henning Kamp {
3052494eb176SPoul-Henning Kamp 	struct vnode *vp2;
3053dee34ca4SPoul-Henning Kamp 
3054dee34ca4SPoul-Henning Kamp 	bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
3055dee34ca4SPoul-Henning Kamp 
3056dee34ca4SPoul-Henning Kamp 	vp2 = sp->sw_id;
3057dee34ca4SPoul-Henning Kamp 	vhold(vp2);
3058dee34ca4SPoul-Henning Kamp 	if (bp->b_iocmd == BIO_WRITE) {
30593cfc7651SOlivier Houchard 		if (bp->b_bufobj)
3060494eb176SPoul-Henning Kamp 			bufobj_wdrop(bp->b_bufobj);
3061a76d8f4eSPoul-Henning Kamp 		bufobj_wref(&vp2->v_bufobj);
3062dee34ca4SPoul-Henning Kamp 	}
30633cfc7651SOlivier Houchard 	if (bp->b_bufobj != &vp2->v_bufobj)
30643cfc7651SOlivier Houchard 		bp->b_bufobj = &vp2->v_bufobj;
3065dee34ca4SPoul-Henning Kamp 	bp->b_vp = vp2;
30662c18019fSPoul-Henning Kamp 	bp->b_iooffset = dbtob(bp->b_blkno);
3067b792bebeSPoul-Henning Kamp 	bstrategy(bp);
3068dee34ca4SPoul-Henning Kamp 	return;
3069dee34ca4SPoul-Henning Kamp }
3070dee34ca4SPoul-Henning Kamp 
3071dee34ca4SPoul-Henning Kamp static void
3072dee34ca4SPoul-Henning Kamp swapdev_close(struct thread *td, struct swdevt *sp)
3073dee34ca4SPoul-Henning Kamp {
3074dee34ca4SPoul-Henning Kamp 
3075dee34ca4SPoul-Henning Kamp 	VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
3076dee34ca4SPoul-Henning Kamp 	vrele(sp->sw_vp);
3077dee34ca4SPoul-Henning Kamp }
3078dee34ca4SPoul-Henning Kamp 
3079dee34ca4SPoul-Henning Kamp static int
3080dee34ca4SPoul-Henning Kamp swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
3081dee34ca4SPoul-Henning Kamp {
3082dee34ca4SPoul-Henning Kamp 	struct swdevt *sp;
3083dee34ca4SPoul-Henning Kamp 	int error;
3084dee34ca4SPoul-Henning Kamp 
3085dee34ca4SPoul-Henning Kamp 	if (nblks == 0)
3086dee34ca4SPoul-Henning Kamp 		return (ENXIO);
3087dee34ca4SPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
3088dee34ca4SPoul-Henning Kamp 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
3089dee34ca4SPoul-Henning Kamp 		if (sp->sw_id == vp) {
3090dee34ca4SPoul-Henning Kamp 			mtx_unlock(&sw_dev_mtx);
3091dee34ca4SPoul-Henning Kamp 			return (EBUSY);
3092dee34ca4SPoul-Henning Kamp 		}
3093dee34ca4SPoul-Henning Kamp 	}
3094dee34ca4SPoul-Henning Kamp 	mtx_unlock(&sw_dev_mtx);
3095dee34ca4SPoul-Henning Kamp 
3096cb05b60aSAttilio Rao 	(void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3097dee34ca4SPoul-Henning Kamp #ifdef MAC
309830d239bcSRobert Watson 	error = mac_system_check_swapon(td->td_ucred, vp);
3099dee34ca4SPoul-Henning Kamp 	if (error == 0)
3100dee34ca4SPoul-Henning Kamp #endif
31019e223287SKonstantin Belousov 		error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
3102b249ce48SMateusz Guzik 	(void) VOP_UNLOCK(vp);
3103dee34ca4SPoul-Henning Kamp 	if (error)
3104dee34ca4SPoul-Henning Kamp 		return (error);
3105dee34ca4SPoul-Henning Kamp 
3106dee34ca4SPoul-Henning Kamp 	swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
31072cc718a1SKonstantin Belousov 	    NODEV, 0);
3108dee34ca4SPoul-Henning Kamp 	return (0);
3109dee34ca4SPoul-Henning Kamp }
311089c241d1SGleb Smirnoff 
311189c241d1SGleb Smirnoff static int
311289c241d1SGleb Smirnoff sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
311389c241d1SGleb Smirnoff {
311489c241d1SGleb Smirnoff 	int error, new, n;
311589c241d1SGleb Smirnoff 
311689c241d1SGleb Smirnoff 	new = nsw_wcount_async_max;
311789c241d1SGleb Smirnoff 	error = sysctl_handle_int(oidp, &new, 0, req);
311889c241d1SGleb Smirnoff 	if (error != 0 || req->newptr == NULL)
311989c241d1SGleb Smirnoff 		return (error);
312089c241d1SGleb Smirnoff 
312189c241d1SGleb Smirnoff 	if (new > nswbuf / 2 || new < 1)
312289c241d1SGleb Smirnoff 		return (EINVAL);
312389c241d1SGleb Smirnoff 
3124756a5412SGleb Smirnoff 	mtx_lock(&swbuf_mtx);
312589c241d1SGleb Smirnoff 	while (nsw_wcount_async_max != new) {
312689c241d1SGleb Smirnoff 		/*
312789c241d1SGleb Smirnoff 		 * Adjust difference.  If the current async count is too low,
312889c241d1SGleb Smirnoff 		 * we will need to sqeeze our update slowly in.  Sleep with a
312989c241d1SGleb Smirnoff 		 * higher priority than getpbuf() to finish faster.
313089c241d1SGleb Smirnoff 		 */
313189c241d1SGleb Smirnoff 		n = new - nsw_wcount_async_max;
313289c241d1SGleb Smirnoff 		if (nsw_wcount_async + n >= 0) {
313389c241d1SGleb Smirnoff 			nsw_wcount_async += n;
313489c241d1SGleb Smirnoff 			nsw_wcount_async_max += n;
313589c241d1SGleb Smirnoff 			wakeup(&nsw_wcount_async);
313689c241d1SGleb Smirnoff 		} else {
313789c241d1SGleb Smirnoff 			nsw_wcount_async_max -= nsw_wcount_async;
313889c241d1SGleb Smirnoff 			nsw_wcount_async = 0;
3139756a5412SGleb Smirnoff 			msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
314089c241d1SGleb Smirnoff 			    "swpsysctl", 0);
314189c241d1SGleb Smirnoff 		}
314289c241d1SGleb Smirnoff 	}
3143756a5412SGleb Smirnoff 	mtx_unlock(&swbuf_mtx);
314489c241d1SGleb Smirnoff 
314589c241d1SGleb Smirnoff 	return (0);
314689c241d1SGleb Smirnoff }
3147fe7bcbafSKyle Evans 
3148fe7bcbafSKyle Evans static void
3149fe7bcbafSKyle Evans swap_pager_update_writecount(vm_object_t object, vm_offset_t start,
3150fe7bcbafSKyle Evans     vm_offset_t end)
3151fe7bcbafSKyle Evans {
3152fe7bcbafSKyle Evans 
3153fe7bcbafSKyle Evans 	VM_OBJECT_WLOCK(object);
315463967687SJeff Roberson 	KASSERT((object->flags & OBJ_ANON) == 0,
3155fe7bcbafSKyle Evans 	    ("Splittable object with writecount"));
3156fe7bcbafSKyle Evans 	object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
3157fe7bcbafSKyle Evans 	VM_OBJECT_WUNLOCK(object);
3158fe7bcbafSKyle Evans }
3159fe7bcbafSKyle Evans 
3160fe7bcbafSKyle Evans static void
3161fe7bcbafSKyle Evans swap_pager_release_writecount(vm_object_t object, vm_offset_t start,
3162fe7bcbafSKyle Evans     vm_offset_t end)
3163fe7bcbafSKyle Evans {
3164fe7bcbafSKyle Evans 
3165fe7bcbafSKyle Evans 	VM_OBJECT_WLOCK(object);
316663967687SJeff Roberson 	KASSERT((object->flags & OBJ_ANON) == 0,
3167fe7bcbafSKyle Evans 	    ("Splittable object with writecount"));
3168fe7bcbafSKyle Evans 	object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
3169fe7bcbafSKyle Evans 	VM_OBJECT_WUNLOCK(object);
3170fe7bcbafSKyle Evans }
3171180bcaa4SKonstantin Belousov 
3172180bcaa4SKonstantin Belousov static void
31734b8365d7SKonstantin Belousov swap_tmpfs_pager_getvp(vm_object_t object, struct vnode **vpp, bool *vp_heldp)
3174192112b7SKonstantin Belousov {
3175192112b7SKonstantin Belousov 	struct vnode *vp;
3176192112b7SKonstantin Belousov 
3177192112b7SKonstantin Belousov 	/*
31784b8365d7SKonstantin Belousov 	 * Tmpfs VREG node, which was reclaimed, has OBJT_SWAP_TMPFS
31794b8365d7SKonstantin Belousov 	 * type, but not OBJ_TMPFS flag.  In this case there is no
31804b8365d7SKonstantin Belousov 	 * v_writecount to adjust.
3181192112b7SKonstantin Belousov 	 */
3182a7c198a2SKonstantin Belousov 	if (vp_heldp != NULL)
3183192112b7SKonstantin Belousov 		VM_OBJECT_RLOCK(object);
3184a7c198a2SKonstantin Belousov 	else
3185a7c198a2SKonstantin Belousov 		VM_OBJECT_ASSERT_LOCKED(object);
3186192112b7SKonstantin Belousov 	if ((object->flags & OBJ_TMPFS) != 0) {
3187192112b7SKonstantin Belousov 		vp = object->un_pager.swp.swp_tmpfs;
3188192112b7SKonstantin Belousov 		if (vp != NULL) {
3189192112b7SKonstantin Belousov 			*vpp = vp;
3190a7c198a2SKonstantin Belousov 			if (vp_heldp != NULL) {
3191a7c198a2SKonstantin Belousov 				vhold(vp);
3192192112b7SKonstantin Belousov 				*vp_heldp = true;
3193192112b7SKonstantin Belousov 			}
3194192112b7SKonstantin Belousov 		}
3195a7c198a2SKonstantin Belousov 	}
3196a7c198a2SKonstantin Belousov 	if (vp_heldp != NULL)
3197192112b7SKonstantin Belousov 		VM_OBJECT_RUNLOCK(object);
3198192112b7SKonstantin Belousov }
3199