xref: /freebsd/sys/vm/swap_pager.c (revision ecfbddf0cde3d4151217e3eb2d7c5388a423d397)
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>
102936524aaSMatthew Dillon #include <sys/vmmeter.h>
103e2e050c8SConrad Meyer #include <sys/vnode.h>
104df8bae1dSRodney W. Grimes 
105aed55708SRobert Watson #include <security/mac/mac_framework.h>
106aed55708SRobert Watson 
107df8bae1dSRodney W. Grimes #include <vm/vm.h>
10821cd6e62SSeigo Tanimura #include <vm/pmap.h>
10921cd6e62SSeigo Tanimura #include <vm/vm_map.h>
11021cd6e62SSeigo Tanimura #include <vm/vm_kern.h>
111efeaf95aSDavid Greenman #include <vm/vm_object.h>
112df8bae1dSRodney W. Grimes #include <vm/vm_page.h>
113efeaf95aSDavid Greenman #include <vm/vm_pager.h>
114df8bae1dSRodney W. Grimes #include <vm/vm_pageout.h>
115e9c0cc15SPoul-Henning Kamp #include <vm/vm_param.h>
116df8bae1dSRodney W. Grimes #include <vm/swap_pager.h>
117efeaf95aSDavid Greenman #include <vm/vm_extern.h>
118670d17b5SJeff Roberson #include <vm/uma.h>
119df8bae1dSRodney W. Grimes 
120dee34ca4SPoul-Henning Kamp #include <geom/geom.h>
121dee34ca4SPoul-Henning Kamp 
122ec38b344SPoul-Henning Kamp /*
123064650c1SAlan Cox  * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64.
124064650c1SAlan Cox  * The 64-page limit is due to the radix code (kern/subr_blist.c).
125ec38b344SPoul-Henning Kamp  */
126ec38b344SPoul-Henning Kamp #ifndef MAX_PAGEOUT_CLUSTER
127e2241590SAlan Cox #define	MAX_PAGEOUT_CLUSTER	32
128ec38b344SPoul-Henning Kamp #endif
129ec38b344SPoul-Henning Kamp 
130ec38b344SPoul-Henning Kamp #if !defined(SWB_NPAGES)
131ec38b344SPoul-Henning Kamp #define SWB_NPAGES	MAX_PAGEOUT_CLUSTER
132ec38b344SPoul-Henning Kamp #endif
133ec38b344SPoul-Henning Kamp 
134f425ab8eSKonstantin Belousov #define	SWAP_META_PAGES		PCTRIE_COUNT
135ec38b344SPoul-Henning Kamp 
136f425ab8eSKonstantin Belousov /*
137f425ab8eSKonstantin Belousov  * A swblk structure maps each page index within a
138f425ab8eSKonstantin Belousov  * SWAP_META_PAGES-aligned and sized range to the address of an
139f425ab8eSKonstantin Belousov  * on-disk swap block (or SWAPBLK_NONE). The collection of these
140f425ab8eSKonstantin Belousov  * mappings for an entire vm object is implemented as a pc-trie.
141f425ab8eSKonstantin Belousov  */
142f425ab8eSKonstantin Belousov struct swblk {
143f425ab8eSKonstantin Belousov 	vm_pindex_t	p;
144f425ab8eSKonstantin Belousov 	daddr_t		d[SWAP_META_PAGES];
145e9c0cc15SPoul-Henning Kamp };
146e9c0cc15SPoul-Henning Kamp 
1472c4992dbSAlan Cox static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data");
14820da9c2eSPoul-Henning Kamp static struct mtx sw_dev_mtx;
1498f60c087SPoul-Henning Kamp static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
1508f60c087SPoul-Henning Kamp static struct swdevt *swdevhd;	/* Allocate from here next */
1518f60c087SPoul-Henning Kamp static int nswapdev;		/* Number of swap devices */
1528f60c087SPoul-Henning Kamp int swap_pager_avail;
15304533e1eSKonstantin Belousov static struct sx swdev_syscall_lock;	/* serialize swap(on|off) */
154e9c0cc15SPoul-Henning Kamp 
155126a2470SMateusz Guzik static __exclusive_cache_line u_long swap_reserved;
156e8bb589dSMatt Macy static u_long swap_total;
157e8bb589dSMatt Macy static int sysctl_page_shift(SYSCTL_HANDLER_ARGS);
158a8081778SJeff Roberson 
1597029da5cSPawel Biernacki static SYSCTL_NODE(_vm_stats, OID_AUTO, swap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
1607029da5cSPawel Biernacki     "VM swap stats");
161a8081778SJeff Roberson 
162e8bb589dSMatt Macy SYSCTL_PROC(_vm, OID_AUTO, swap_reserved, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
163e8bb589dSMatt Macy     &swap_reserved, 0, sysctl_page_shift, "A",
1648a9c731fSIvan Voras     "Amount of swap storage needed to back all allocated anonymous memory.");
165e8bb589dSMatt Macy SYSCTL_PROC(_vm, OID_AUTO, swap_total, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
166e8bb589dSMatt Macy     &swap_total, 0, sysctl_page_shift, "A",
167e8bb589dSMatt Macy     "Total amount of available swap storage.");
168e8bb589dSMatt Macy 
1693364c323SKonstantin Belousov static int overcommit = 0;
170be7d4ac5SEdward Tomasz Napierala SYSCTL_INT(_vm, VM_OVERCOMMIT, overcommit, CTLFLAG_RW, &overcommit, 0,
1718a9c731fSIvan Voras     "Configure virtual memory overcommit behavior. See tuning(7) "
1728a9c731fSIvan Voras     "for details.");
17361203277SDag-Erling Smørgrav static unsigned long swzone;
17461203277SDag-Erling Smørgrav SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
17561203277SDag-Erling Smørgrav     "Actual size of swap metadata zone");
17661203277SDag-Erling Smørgrav static unsigned long swap_maxpages;
17761203277SDag-Erling Smørgrav SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
17861203277SDag-Erling Smørgrav     "Maximum amount of swap supported");
1793364c323SKonstantin Belousov 
180d869a17eSMark Johnston static COUNTER_U64_DEFINE_EARLY(swap_free_deferred);
181a8081778SJeff Roberson SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_deferred,
182a8081778SJeff Roberson     CTLFLAG_RD, &swap_free_deferred,
183a8081778SJeff Roberson     "Number of pages that deferred freeing swap space");
184a8081778SJeff Roberson 
185d869a17eSMark Johnston static COUNTER_U64_DEFINE_EARLY(swap_free_completed);
186a8081778SJeff Roberson SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_completed,
187a8081778SJeff Roberson     CTLFLAG_RD, &swap_free_completed,
188a8081778SJeff Roberson     "Number of deferred frees completed");
189a8081778SJeff Roberson 
1903364c323SKonstantin Belousov /* bits from overcommit */
1913364c323SKonstantin Belousov #define	SWAP_RESERVE_FORCE_ON		(1 << 0)
1923364c323SKonstantin Belousov #define	SWAP_RESERVE_RLIMIT_ON		(1 << 1)
1933364c323SKonstantin Belousov #define	SWAP_RESERVE_ALLOW_NONWIRED	(1 << 2)
1943364c323SKonstantin Belousov 
195e8bb589dSMatt Macy static int
196e8bb589dSMatt Macy sysctl_page_shift(SYSCTL_HANDLER_ARGS)
197e8bb589dSMatt Macy {
198e8bb589dSMatt Macy 	uint64_t newval;
199e8bb589dSMatt Macy 	u_long value = *(u_long *)arg1;
200e8bb589dSMatt Macy 
201e8bb589dSMatt Macy 	newval = ((uint64_t)value) << PAGE_SHIFT;
202e8bb589dSMatt Macy 	return (sysctl_handle_64(oidp, &newval, 0, req));
203e8bb589dSMatt Macy }
204e8bb589dSMatt Macy 
205ee744122SMateusz Guzik static bool
206ee744122SMateusz Guzik swap_reserve_by_cred_rlimit(u_long pincr, struct ucred *cred, int oc)
207ee744122SMateusz Guzik {
208ee744122SMateusz Guzik 	struct uidinfo *uip;
209ee744122SMateusz Guzik 	u_long prev;
210ee744122SMateusz Guzik 
211ee744122SMateusz Guzik 	uip = cred->cr_ruidinfo;
212ee744122SMateusz Guzik 
213ee744122SMateusz Guzik 	prev = atomic_fetchadd_long(&uip->ui_vmsize, pincr);
214ee744122SMateusz Guzik 	if ((oc & SWAP_RESERVE_RLIMIT_ON) != 0 &&
215ee744122SMateusz Guzik 	    prev + pincr > lim_cur(curthread, RLIMIT_SWAP) &&
216ee744122SMateusz Guzik 	    priv_check(curthread, PRIV_VM_SWAP_NORLIMIT) != 0) {
217ee744122SMateusz Guzik 		prev = atomic_fetchadd_long(&uip->ui_vmsize, -pincr);
218ee744122SMateusz Guzik 		KASSERT(prev >= pincr, ("negative vmsize for uid = %d\n", uip->ui_uid));
219ee744122SMateusz Guzik 		return (false);
220ee744122SMateusz Guzik 	}
221ee744122SMateusz Guzik 	return (true);
222ee744122SMateusz Guzik }
223ee744122SMateusz Guzik 
224ee744122SMateusz Guzik static void
225ee744122SMateusz Guzik swap_release_by_cred_rlimit(u_long pdecr, struct ucred *cred)
226ee744122SMateusz Guzik {
227ee744122SMateusz Guzik 	struct uidinfo *uip;
228ee744122SMateusz Guzik #ifdef INVARIANTS
229ee744122SMateusz Guzik 	u_long prev;
230ee744122SMateusz Guzik #endif
231ee744122SMateusz Guzik 
232ee744122SMateusz Guzik 	uip = cred->cr_ruidinfo;
233ee744122SMateusz Guzik 
234ee744122SMateusz Guzik #ifdef INVARIANTS
235ee744122SMateusz Guzik 	prev = atomic_fetchadd_long(&uip->ui_vmsize, -pdecr);
236ee744122SMateusz Guzik 	KASSERT(prev >= pdecr, ("negative vmsize for uid = %d\n", uip->ui_uid));
237ee744122SMateusz Guzik #else
238ee744122SMateusz Guzik 	atomic_subtract_long(&uip->ui_vmsize, pdecr);
239ee744122SMateusz Guzik #endif
240ee744122SMateusz Guzik }
241ee744122SMateusz Guzik 
242ee744122SMateusz Guzik static void
243ee744122SMateusz Guzik swap_reserve_force_rlimit(u_long pincr, struct ucred *cred)
244ee744122SMateusz Guzik {
245ee744122SMateusz Guzik 	struct uidinfo *uip;
246ee744122SMateusz Guzik 
247ee744122SMateusz Guzik 	uip = cred->cr_ruidinfo;
248ee744122SMateusz Guzik 	atomic_add_long(&uip->ui_vmsize, pincr);
249ee744122SMateusz Guzik }
250ee744122SMateusz Guzik 
251ee744122SMateusz Guzik bool
2523364c323SKonstantin Belousov swap_reserve(vm_ooffset_t incr)
2533364c323SKonstantin Belousov {
2543364c323SKonstantin Belousov 
255ef694c1aSEdward Tomasz Napierala 	return (swap_reserve_by_cred(incr, curthread->td_ucred));
2563364c323SKonstantin Belousov }
2573364c323SKonstantin Belousov 
258ee744122SMateusz Guzik bool
259ef694c1aSEdward Tomasz Napierala swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
2603364c323SKonstantin Belousov {
261e8bb589dSMatt Macy 	u_long r, s, prev, pincr;
262ee744122SMateusz Guzik #ifdef RACCT
263ee744122SMateusz Guzik 	int error;
264ee744122SMateusz Guzik #endif
265ee744122SMateusz Guzik 	int oc;
2663364c323SKonstantin Belousov 	static int curfail;
2673364c323SKonstantin Belousov 	static struct timeval lastfail;
2683364c323SKonstantin Belousov 
269e8bb589dSMatt Macy 	KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
270e8bb589dSMatt Macy 	    (uintmax_t)incr));
2713364c323SKonstantin Belousov 
272afcc55f3SEdward Tomasz Napierala #ifdef RACCT
273ee744122SMateusz Guzik 	if (RACCT_ENABLED()) {
2741ba5ad42SEdward Tomasz Napierala 		PROC_LOCK(curproc);
2751ba5ad42SEdward Tomasz Napierala 		error = racct_add(curproc, RACCT_SWAP, incr);
2761ba5ad42SEdward Tomasz Napierala 		PROC_UNLOCK(curproc);
2771ba5ad42SEdward Tomasz Napierala 		if (error != 0)
278ee744122SMateusz Guzik 			return (false);
2794b5c9cf6SEdward Tomasz Napierala 	}
280afcc55f3SEdward Tomasz Napierala #endif
2811ba5ad42SEdward Tomasz Napierala 
282e8bb589dSMatt Macy 	pincr = atop(incr);
283e8bb589dSMatt Macy 	prev = atomic_fetchadd_long(&swap_reserved, pincr);
284e8bb589dSMatt Macy 	r = prev + pincr;
285ee744122SMateusz Guzik 	s = swap_total;
286ee744122SMateusz Guzik 	oc = atomic_load_int(&overcommit);
287ee744122SMateusz Guzik 	if (r > s && (oc & SWAP_RESERVE_ALLOW_NONWIRED) != 0) {
288ee744122SMateusz Guzik 		s += vm_cnt.v_page_count - vm_cnt.v_free_reserved -
289e958ad4cSJeff Roberson 		    vm_wire_count();
290ee744122SMateusz Guzik 	}
291ee744122SMateusz Guzik 	if ((oc & SWAP_RESERVE_FORCE_ON) != 0 && r > s &&
292ee744122SMateusz Guzik 	    priv_check(curthread, PRIV_VM_SWAP_NOQUOTA) != 0) {
293e8bb589dSMatt Macy 		prev = atomic_fetchadd_long(&swap_reserved, -pincr);
294ee744122SMateusz Guzik 		KASSERT(prev >= pincr, ("swap_reserved < incr on overcommit fail"));
295ee744122SMateusz Guzik 		goto out_error;
2963364c323SKonstantin Belousov 	}
2973364c323SKonstantin Belousov 
298ee744122SMateusz Guzik 	if (!swap_reserve_by_cred_rlimit(pincr, cred, oc)) {
299ee744122SMateusz Guzik 		prev = atomic_fetchadd_long(&swap_reserved, -pincr);
300ee744122SMateusz Guzik 		KASSERT(prev >= pincr, ("swap_reserved < incr on overcommit fail"));
301ee744122SMateusz Guzik 		goto out_error;
302ee744122SMateusz Guzik 	}
303ee744122SMateusz Guzik 
304ee744122SMateusz Guzik 	return (true);
305ee744122SMateusz Guzik 
306ee744122SMateusz Guzik out_error:
307ee744122SMateusz Guzik 	if (ppsratecheck(&lastfail, &curfail, 1)) {
308ee744122SMateusz Guzik 		printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
309ee744122SMateusz Guzik 		    cred->cr_ruidinfo->ui_uid, curproc->p_pid, incr);
310ee744122SMateusz Guzik 	}
311afcc55f3SEdward Tomasz Napierala #ifdef RACCT
312ee744122SMateusz Guzik 	if (RACCT_ENABLED()) {
3131ba5ad42SEdward Tomasz Napierala 		PROC_LOCK(curproc);
3141ba5ad42SEdward Tomasz Napierala 		racct_sub(curproc, RACCT_SWAP, incr);
3151ba5ad42SEdward Tomasz Napierala 		PROC_UNLOCK(curproc);
3161ba5ad42SEdward Tomasz Napierala 	}
317afcc55f3SEdward Tomasz Napierala #endif
3181ba5ad42SEdward Tomasz Napierala 
319ee744122SMateusz Guzik 	return (false);
3203364c323SKonstantin Belousov }
3213364c323SKonstantin Belousov 
3223364c323SKonstantin Belousov void
3233364c323SKonstantin Belousov swap_reserve_force(vm_ooffset_t incr)
3243364c323SKonstantin Belousov {
325e8bb589dSMatt Macy 	u_long pincr;
3263364c323SKonstantin Belousov 
327e8bb589dSMatt Macy 	KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
328e8bb589dSMatt Macy 	    (uintmax_t)incr));
3293364c323SKonstantin Belousov 
330afcc55f3SEdward Tomasz Napierala #ifdef RACCT
331ee744122SMateusz Guzik 	if (RACCT_ENABLED()) {
332ee744122SMateusz Guzik 		PROC_LOCK(curproc);
3331ba5ad42SEdward Tomasz Napierala 		racct_add_force(curproc, RACCT_SWAP, incr);
334ee744122SMateusz Guzik 		PROC_UNLOCK(curproc);
335ee744122SMateusz Guzik 	}
336afcc55f3SEdward Tomasz Napierala #endif
337e8bb589dSMatt Macy 	pincr = atop(incr);
338e8bb589dSMatt Macy 	atomic_add_long(&swap_reserved, pincr);
339ee744122SMateusz Guzik 	swap_reserve_force_rlimit(pincr, curthread->td_ucred);
3403364c323SKonstantin Belousov }
3413364c323SKonstantin Belousov 
3423364c323SKonstantin Belousov void
3433364c323SKonstantin Belousov swap_release(vm_ooffset_t decr)
3443364c323SKonstantin Belousov {
345ef694c1aSEdward Tomasz Napierala 	struct ucred *cred;
3463364c323SKonstantin Belousov 
3473364c323SKonstantin Belousov 	PROC_LOCK(curproc);
348e8bb589dSMatt Macy 	cred = curproc->p_ucred;
349ef694c1aSEdward Tomasz Napierala 	swap_release_by_cred(decr, cred);
3503364c323SKonstantin Belousov 	PROC_UNLOCK(curproc);
3513364c323SKonstantin Belousov }
3523364c323SKonstantin Belousov 
3533364c323SKonstantin Belousov void
354ef694c1aSEdward Tomasz Napierala swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
3553364c323SKonstantin Belousov {
356ee744122SMateusz Guzik 	u_long pdecr;
357ee744122SMateusz Guzik #ifdef INVARIANTS
358ee744122SMateusz Guzik 	u_long prev;
359ee744122SMateusz Guzik #endif
3603364c323SKonstantin Belousov 
361e8bb589dSMatt Macy 	KASSERT((decr & PAGE_MASK) == 0, ("%s: decr: %ju & PAGE_MASK", __func__,
362e8bb589dSMatt Macy 	    (uintmax_t)decr));
3633364c323SKonstantin Belousov 
364e8bb589dSMatt Macy 	pdecr = atop(decr);
365ee744122SMateusz Guzik #ifdef INVARIANTS
366e8bb589dSMatt Macy 	prev = atomic_fetchadd_long(&swap_reserved, -pdecr);
367ee744122SMateusz Guzik 	KASSERT(prev >= pdecr, ("swap_reserved < decr"));
368ee744122SMateusz Guzik #else
369ee744122SMateusz Guzik 	atomic_subtract_long(&swap_reserved, pdecr);
370ee744122SMateusz Guzik #endif
3713364c323SKonstantin Belousov 
372ee744122SMateusz Guzik 	swap_release_by_cred_rlimit(pdecr, cred);
373e8bb589dSMatt Macy #ifdef RACCT
374e8bb589dSMatt Macy 	if (racct_enable)
3751ba5ad42SEdward Tomasz Napierala 		racct_sub_cred(cred, RACCT_SWAP, decr);
376e8bb589dSMatt Macy #endif
3773364c323SKonstantin Belousov }
3783364c323SKonstantin Belousov 
379f08b3099SKonstantin Belousov static int swap_pager_full = 2;	/* swap space exhaustion (task killing) */
3807dea2c2eSAlan Cox static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
381756a5412SGleb Smirnoff static struct mtx swbuf_mtx;	/* to sync nsw_wcount_async */
382756a5412SGleb Smirnoff static int nsw_wcount_async;	/* limit async write buffers */
383327f4e83SMatthew Dillon static int nsw_wcount_async_max;/* assigned maximum			*/
384327f4e83SMatthew Dillon static int nsw_cluster_max;	/* maximum VOP I/O allowed		*/
3851c7c3c6aSMatthew Dillon 
38689c241d1SGleb Smirnoff static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
3874c36e917SKonstantin Belousov SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
3884c36e917SKonstantin Belousov     CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
3894c36e917SKonstantin Belousov     "Maximum running async swap ops");
390d027ed2eSAlan Cox static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS);
391d027ed2eSAlan Cox SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD |
392d027ed2eSAlan Cox     CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A",
393d027ed2eSAlan Cox     "Swap Fragmentation Info");
39489c241d1SGleb Smirnoff 
3950cddd8f0SMatthew Dillon static struct sx sw_alloc_sx;
396327f4e83SMatthew Dillon 
3971c7c3c6aSMatthew Dillon /*
3981c7c3c6aSMatthew Dillon  * "named" and "unnamed" anon region objects.  Try to reduce the overhead
3991c7c3c6aSMatthew Dillon  * of searching a named list by hashing it just a little.
4001c7c3c6aSMatthew Dillon  */
4011c7c3c6aSMatthew Dillon 
4021c7c3c6aSMatthew Dillon #define NOBJLISTS		8
4031c7c3c6aSMatthew Dillon 
4041c7c3c6aSMatthew Dillon #define NOBJLIST(handle)	\
405af647ddeSBruce Evans 	(&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
4061c7c3c6aSMatthew Dillon 
4071c7c3c6aSMatthew Dillon static struct pagerlst	swap_pager_object_list[NOBJLISTS];
408756a5412SGleb Smirnoff static uma_zone_t swwbuf_zone;
409756a5412SGleb Smirnoff static uma_zone_t swrbuf_zone;
410f425ab8eSKonstantin Belousov static uma_zone_t swblk_zone;
411f425ab8eSKonstantin Belousov static uma_zone_t swpctrie_zone;
4121c7c3c6aSMatthew Dillon 
4131c7c3c6aSMatthew Dillon /*
4141c7c3c6aSMatthew Dillon  * pagerops for OBJT_SWAP - "swap pager".  Some ops are also global procedure
4151c7c3c6aSMatthew Dillon  * calls hooked from other parts of the VM system and do not appear here.
4161c7c3c6aSMatthew Dillon  * (see vm/swap_pager.h).
4171c7c3c6aSMatthew Dillon  */
418ff98689dSBruce Evans static vm_object_t
41911caded3SAlfred Perlstein 		swap_pager_alloc(void *handle, vm_ooffset_t size,
4203364c323SKonstantin Belousov 		    vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
42111caded3SAlfred Perlstein static void	swap_pager_dealloc(vm_object_t object);
422b0cd2017SGleb Smirnoff static int	swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
423b0cd2017SGleb Smirnoff     int *);
424b0cd2017SGleb Smirnoff static int	swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
425b0cd2017SGleb Smirnoff     int *, pgo_getpages_iodone_t, void *);
426751221fdSPoul-Henning Kamp static void	swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
4275ea4972cSAlan Cox static boolean_t
4285ea4972cSAlan Cox 		swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
42911caded3SAlfred Perlstein static void	swap_pager_init(void);
43011caded3SAlfred Perlstein static void	swap_pager_unswapped(vm_page_t);
431b3fed13eSDavid Schultz static void	swap_pager_swapoff(struct swdevt *sp);
432fe7bcbafSKyle Evans static void	swap_pager_update_writecount(vm_object_t object,
433fe7bcbafSKyle Evans     vm_offset_t start, vm_offset_t end);
434fe7bcbafSKyle Evans static void	swap_pager_release_writecount(vm_object_t object,
435fe7bcbafSKyle Evans     vm_offset_t start, vm_offset_t end);
436f708ef1bSPoul-Henning Kamp 
437df8bae1dSRodney W. Grimes struct pagerops swappagerops = {
438e04e4bacSPoul-Henning Kamp 	.pgo_init =	swap_pager_init,	/* early system initialization of pager	*/
439e04e4bacSPoul-Henning Kamp 	.pgo_alloc =	swap_pager_alloc,	/* allocate an OBJT_SWAP object		*/
440e04e4bacSPoul-Henning Kamp 	.pgo_dealloc =	swap_pager_dealloc,	/* deallocate an OBJT_SWAP object	*/
441e04e4bacSPoul-Henning Kamp 	.pgo_getpages =	swap_pager_getpages,	/* pagein				*/
44290effb23SGleb Smirnoff 	.pgo_getpages_async = swap_pager_getpages_async, /* pagein (async)		*/
443e04e4bacSPoul-Henning Kamp 	.pgo_putpages =	swap_pager_putpages,	/* pageout				*/
444e04e4bacSPoul-Henning Kamp 	.pgo_haspage =	swap_pager_haspage,	/* get backing store status for page	*/
445e04e4bacSPoul-Henning Kamp 	.pgo_pageunswapped = swap_pager_unswapped,	/* remove swap related to page		*/
446fe7bcbafSKyle Evans 	.pgo_update_writecount = swap_pager_update_writecount,
447fe7bcbafSKyle Evans 	.pgo_release_writecount = swap_pager_release_writecount,
448df8bae1dSRodney W. Grimes };
449df8bae1dSRodney W. Grimes 
4501c7c3c6aSMatthew Dillon /*
4511c7c3c6aSMatthew Dillon  * swap_*() routines are externally accessible.  swp_*() routines are
4521c7c3c6aSMatthew Dillon  * internal.
4531c7c3c6aSMatthew Dillon  */
454e9c0cc15SPoul-Henning Kamp static int nswap_lowat = 128;	/* in pages, swap_pager_almost_full warn */
455e9c0cc15SPoul-Henning Kamp static int nswap_hiwat = 512;	/* in pages, swap_pager_almost_full warn */
45626f9a767SRodney W. Grimes 
45707c348eaSAlan Cox SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
45807c348eaSAlan Cox     "Maximum size of a swap block in pages");
459cee313c4SRobert Watson 
460a5edd34aSPoul-Henning Kamp static void	swp_sizecheck(void);
46111caded3SAlfred Perlstein static void	swp_pager_async_iodone(struct buf *bp);
462230869e0SAlan Cox static bool	swp_pager_swblk_empty(struct swblk *sb, int start, int limit);
463abdab7b6SDoug Moore static void	swp_pager_free_empty_swblk(vm_object_t, struct swblk *sb);
46488ad2d7bSKonstantin Belousov static int	swapongeom(struct vnode *);
46559efee01SPoul-Henning Kamp static int	swaponvp(struct thread *, struct vnode *, u_long);
46635918c55SChristian S.J. Peron static int	swapoff_one(struct swdevt *sp, struct ucred *cred);
46724a1cce3SDavid Greenman 
4681c7c3c6aSMatthew Dillon /*
4691c7c3c6aSMatthew Dillon  * Swap bitmap functions
4701c7c3c6aSMatthew Dillon  */
471230869e0SAlan Cox static void	swp_pager_freeswapspace(daddr_t blk, daddr_t npages);
47236b01270SDoug Moore static daddr_t	swp_pager_getswapspace(int *npages);
4731c7c3c6aSMatthew Dillon 
4741c7c3c6aSMatthew Dillon /*
4751c7c3c6aSMatthew Dillon  * Metadata functions
4761c7c3c6aSMatthew Dillon  */
47778f1deefSAlan Cox static daddr_t swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
4782e56b64fSKonstantin Belousov static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t);
479467057fcSDoug Moore static void swp_pager_meta_transfer(vm_object_t src, vm_object_t dst,
480467057fcSDoug Moore     vm_pindex_t pindex, vm_pindex_t count);
48111caded3SAlfred Perlstein static void swp_pager_meta_free_all(vm_object_t);
4828ecbf14bSDoug Moore static daddr_t swp_pager_meta_lookup(vm_object_t, vm_pindex_t);
4831c7c3c6aSMatthew Dillon 
48478f1deefSAlan Cox static void
48578f1deefSAlan Cox swp_pager_init_freerange(daddr_t *start, daddr_t *num)
48678f1deefSAlan Cox {
48778f1deefSAlan Cox 
48878f1deefSAlan Cox 	*start = SWAPBLK_NONE;
48978f1deefSAlan Cox 	*num = 0;
49078f1deefSAlan Cox }
49178f1deefSAlan Cox 
49278f1deefSAlan Cox static void
49378f1deefSAlan Cox swp_pager_update_freerange(daddr_t *start, daddr_t *num, daddr_t addr)
49478f1deefSAlan Cox {
49578f1deefSAlan Cox 
49678f1deefSAlan Cox 	if (*start + *num == addr) {
49778f1deefSAlan Cox 		(*num)++;
49878f1deefSAlan Cox 	} else {
49978f1deefSAlan Cox 		swp_pager_freeswapspace(*start, *num);
50078f1deefSAlan Cox 		*start = addr;
50178f1deefSAlan Cox 		*num = 1;
50278f1deefSAlan Cox 	}
50378f1deefSAlan Cox }
50478f1deefSAlan Cox 
505f425ab8eSKonstantin Belousov static void *
506f425ab8eSKonstantin Belousov swblk_trie_alloc(struct pctrie *ptree)
507f425ab8eSKonstantin Belousov {
508f425ab8eSKonstantin Belousov 
509f425ab8eSKonstantin Belousov 	return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
510f425ab8eSKonstantin Belousov 	    M_USE_RESERVE : 0)));
511f425ab8eSKonstantin Belousov }
512f425ab8eSKonstantin Belousov 
513f425ab8eSKonstantin Belousov static void
514f425ab8eSKonstantin Belousov swblk_trie_free(struct pctrie *ptree, void *node)
515f425ab8eSKonstantin Belousov {
516f425ab8eSKonstantin Belousov 
517f425ab8eSKonstantin Belousov 	uma_zfree(swpctrie_zone, node);
518f425ab8eSKonstantin Belousov }
519f425ab8eSKonstantin Belousov 
520f425ab8eSKonstantin Belousov PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
521f425ab8eSKonstantin Belousov 
5221c7c3c6aSMatthew Dillon /*
5231c7c3c6aSMatthew Dillon  * SWP_SIZECHECK() -	update swap_pager_full indication
5241c7c3c6aSMatthew Dillon  *
52520d3034fSMatthew Dillon  *	update the swap_pager_almost_full indication and warn when we are
52620d3034fSMatthew Dillon  *	about to run out of swap space, using lowat/hiwat hysteresis.
52720d3034fSMatthew Dillon  *
52820d3034fSMatthew Dillon  *	Clear swap_pager_full ( task killing ) indication when lowat is met.
5291c7c3c6aSMatthew Dillon  *
5301c7c3c6aSMatthew Dillon  *	No restrictions on call
5311c7c3c6aSMatthew Dillon  *	This routine may not block.
5321c7c3c6aSMatthew Dillon  */
533a5edd34aSPoul-Henning Kamp static void
5342f249180SPoul-Henning Kamp swp_sizecheck(void)
5350d94caffSDavid Greenman {
53623955314SAlfred Perlstein 
5378f60c087SPoul-Henning Kamp 	if (swap_pager_avail < nswap_lowat) {
53820d3034fSMatthew Dillon 		if (swap_pager_almost_full == 0) {
5391af87c92SDavid Greenman 			printf("swap_pager: out of swap space\n");
54020d3034fSMatthew Dillon 			swap_pager_almost_full = 1;
5412b0d37a4SMatthew Dillon 		}
54220d3034fSMatthew Dillon 	} else {
54326f9a767SRodney W. Grimes 		swap_pager_full = 0;
5448f60c087SPoul-Henning Kamp 		if (swap_pager_avail > nswap_hiwat)
54520d3034fSMatthew Dillon 			swap_pager_almost_full = 0;
54626f9a767SRodney W. Grimes 	}
5471c7c3c6aSMatthew Dillon }
5481c7c3c6aSMatthew Dillon 
5491c7c3c6aSMatthew Dillon /*
5501c7c3c6aSMatthew Dillon  * SWAP_PAGER_INIT() -	initialize the swap pager!
5511c7c3c6aSMatthew Dillon  *
5521c7c3c6aSMatthew Dillon  *	Expected to be started from system init.  NOTE:  This code is run
5531c7c3c6aSMatthew Dillon  *	before much else so be careful what you depend on.  Most of the VM
5541c7c3c6aSMatthew Dillon  *	system has yet to be initialized at this point.
5551c7c3c6aSMatthew Dillon  */
556f5a12711SPoul-Henning Kamp static void
5572f249180SPoul-Henning Kamp swap_pager_init(void)
558df8bae1dSRodney W. Grimes {
5591c7c3c6aSMatthew Dillon 	/*
5601c7c3c6aSMatthew Dillon 	 * Initialize object lists
5611c7c3c6aSMatthew Dillon 	 */
5621c7c3c6aSMatthew Dillon 	int i;
5631c7c3c6aSMatthew Dillon 
5641c7c3c6aSMatthew Dillon 	for (i = 0; i < NOBJLISTS; ++i)
5651c7c3c6aSMatthew Dillon 		TAILQ_INIT(&swap_pager_object_list[i]);
56620da9c2eSPoul-Henning Kamp 	mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
56715719273SKonstantin Belousov 	sx_init(&sw_alloc_sx, "swspsx");
56804533e1eSKonstantin Belousov 	sx_init(&swdev_syscall_lock, "swsysc");
5691c7c3c6aSMatthew Dillon }
57026f9a767SRodney W. Grimes 
571df8bae1dSRodney W. Grimes /*
5721c7c3c6aSMatthew Dillon  * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
5731c7c3c6aSMatthew Dillon  *
5741c7c3c6aSMatthew Dillon  *	Expected to be started from pageout process once, prior to entering
5751c7c3c6aSMatthew Dillon  *	its main loop.
576df8bae1dSRodney W. Grimes  */
57724a1cce3SDavid Greenman void
5782f249180SPoul-Henning Kamp swap_pager_swap_init(void)
579df8bae1dSRodney W. Grimes {
58061203277SDag-Erling Smørgrav 	unsigned long n, n2;
5810d94caffSDavid Greenman 
58226f9a767SRodney W. Grimes 	/*
5831c7c3c6aSMatthew Dillon 	 * Number of in-transit swap bp operations.  Don't
5841c7c3c6aSMatthew Dillon 	 * exhaust the pbufs completely.  Make sure we
5851c7c3c6aSMatthew Dillon 	 * initialize workable values (0 will work for hysteresis
5861c7c3c6aSMatthew Dillon 	 * but it isn't very efficient).
5871c7c3c6aSMatthew Dillon 	 *
588327f4e83SMatthew Dillon 	 * The nsw_cluster_max is constrained by the bp->b_pages[]
589cd853791SKonstantin Belousov 	 * array, which has maxphys / PAGE_SIZE entries, and our locally
5907b9bcad9SDoug Moore 	 * defined MAX_PAGEOUT_CLUSTER.   Also be aware that swap ops are
5911c7c3c6aSMatthew Dillon 	 * constrained by the swap device interleave stripe size.
592327f4e83SMatthew Dillon 	 *
593327f4e83SMatthew Dillon 	 * Currently we hardwire nsw_wcount_async to 4.  This limit is
594327f4e83SMatthew Dillon 	 * designed to prevent other I/O from having high latencies due to
595327f4e83SMatthew Dillon 	 * our pageout I/O.  The value 4 works well for one or two active swap
596327f4e83SMatthew Dillon 	 * devices but is probably a little low if you have more.  Even so,
597327f4e83SMatthew Dillon 	 * a higher value would probably generate only a limited improvement
598327f4e83SMatthew Dillon 	 * with three or four active swap devices since the system does not
599327f4e83SMatthew Dillon 	 * typically have to pageout at extreme bandwidths.   We will want
600327f4e83SMatthew Dillon 	 * at least 2 per swap devices, and 4 is a pretty good value if you
601327f4e83SMatthew Dillon 	 * have one NFS swap device due to the command/ack latency over NFS.
602327f4e83SMatthew Dillon 	 * So it all works out pretty well.
60326f9a767SRodney W. Grimes 	 */
604cd853791SKonstantin Belousov 	nsw_cluster_max = min(maxphys / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
605327f4e83SMatthew Dillon 
606327f4e83SMatthew Dillon 	nsw_wcount_async = 4;
607327f4e83SMatthew Dillon 	nsw_wcount_async_max = nsw_wcount_async;
608756a5412SGleb Smirnoff 	mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
609756a5412SGleb Smirnoff 
610756a5412SGleb Smirnoff 	swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
611756a5412SGleb Smirnoff 	swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
61224a1cce3SDavid Greenman 
6131c7c3c6aSMatthew Dillon 	/*
614a8233027SKonstantin Belousov 	 * Initialize our zone, taking the user's requested size or
615a8233027SKonstantin Belousov 	 * estimating the number we need based on the number of pages
616a8233027SKonstantin Belousov 	 * in the system.
6171c7c3c6aSMatthew Dillon 	 */
618a8233027SKonstantin Belousov 	n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
619a8233027SKonstantin Belousov 	    vm_cnt.v_page_count / 2;
620f425ab8eSKonstantin Belousov 	swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
6216c5f36ffSJeff Roberson 	    pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0);
622f425ab8eSKonstantin Belousov 	if (swpctrie_zone == NULL)
623f425ab8eSKonstantin Belousov 		panic("failed to create swap pctrie zone.");
624f425ab8eSKonstantin Belousov 	swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
6256c5f36ffSJeff Roberson 	    NULL, NULL, _Alignof(struct swblk) - 1, 0);
626f425ab8eSKonstantin Belousov 	if (swblk_zone == NULL)
627f425ab8eSKonstantin Belousov 		panic("failed to create swap blk zone.");
62822a5e6b9SDag-Erling Smørgrav 	n2 = n;
6298355f576SJeff Roberson 	do {
630f425ab8eSKonstantin Belousov 		if (uma_zone_reserve_kva(swblk_zone, n))
63161ce6eeeSAlfred Perlstein 			break;
63261ce6eeeSAlfred Perlstein 		/*
63361ce6eeeSAlfred Perlstein 		 * if the allocation failed, try a zone two thirds the
63461ce6eeeSAlfred Perlstein 		 * size of the previous attempt.
63561ce6eeeSAlfred Perlstein 		 */
63661ce6eeeSAlfred Perlstein 		n -= ((n + 2) / 3);
63761ce6eeeSAlfred Perlstein 	} while (n > 0);
63853faf5a7SKonstantin Belousov 
63953faf5a7SKonstantin Belousov 	/*
64053faf5a7SKonstantin Belousov 	 * Often uma_zone_reserve_kva() cannot reserve exactly the
64153faf5a7SKonstantin Belousov 	 * requested size.  Account for the difference when
64253faf5a7SKonstantin Belousov 	 * calculating swap_maxpages.
64353faf5a7SKonstantin Belousov 	 */
64453faf5a7SKonstantin Belousov 	n = uma_zone_get_max(swblk_zone);
64553faf5a7SKonstantin Belousov 
6461fffcd75SKonstantin Belousov 	if (n < n2)
647a8233027SKonstantin Belousov 		printf("Swap blk zone entries changed from %lu to %lu.\n",
648f425ab8eSKonstantin Belousov 		    n2, n);
649303fa05aSKonstantin Belousov 	/* absolute maximum we can handle assuming 100% efficiency */
65061203277SDag-Erling Smørgrav 	swap_maxpages = n * SWAP_META_PAGES;
651f425ab8eSKonstantin Belousov 	swzone = n * sizeof(struct swblk);
652f425ab8eSKonstantin Belousov 	if (!uma_zone_reserve_kva(swpctrie_zone, n))
653f425ab8eSKonstantin Belousov 		printf("Cannot reserve swap pctrie zone, "
654f425ab8eSKonstantin Belousov 		    "reduce kern.maxswzone.\n");
65524a1cce3SDavid Greenman }
65624a1cce3SDavid Greenman 
657eb4d6a1bSKonstantin Belousov static vm_object_t
658eb4d6a1bSKonstantin Belousov swap_pager_alloc_init(void *handle, struct ucred *cred, vm_ooffset_t size,
659eb4d6a1bSKonstantin Belousov     vm_ooffset_t offset)
660eb4d6a1bSKonstantin Belousov {
661eb4d6a1bSKonstantin Belousov 	vm_object_t object;
662eb4d6a1bSKonstantin Belousov 
663eb4d6a1bSKonstantin Belousov 	if (cred != NULL) {
664eb4d6a1bSKonstantin Belousov 		if (!swap_reserve_by_cred(size, cred))
665eb4d6a1bSKonstantin Belousov 			return (NULL);
666eb4d6a1bSKonstantin Belousov 		crhold(cred);
667eb4d6a1bSKonstantin Belousov 	}
668f425ab8eSKonstantin Belousov 
669f425ab8eSKonstantin Belousov 	/*
670f425ab8eSKonstantin Belousov 	 * The un_pager.swp.swp_blks trie is initialized by
671f425ab8eSKonstantin Belousov 	 * vm_object_allocate() to ensure the correct order of
672f425ab8eSKonstantin Belousov 	 * visibility to other threads.
673f425ab8eSKonstantin Belousov 	 */
674eb4d6a1bSKonstantin Belousov 	object = vm_object_allocate(OBJT_SWAP, OFF_TO_IDX(offset +
675eb4d6a1bSKonstantin Belousov 	    PAGE_MASK + size));
676f425ab8eSKonstantin Belousov 
677fe7bcbafSKyle Evans 	object->un_pager.swp.writemappings = 0;
678eb4d6a1bSKonstantin Belousov 	object->handle = handle;
679eb4d6a1bSKonstantin Belousov 	if (cred != NULL) {
680eb4d6a1bSKonstantin Belousov 		object->cred = cred;
681eb4d6a1bSKonstantin Belousov 		object->charge = size;
682eb4d6a1bSKonstantin Belousov 	}
683eb4d6a1bSKonstantin Belousov 	return (object);
684eb4d6a1bSKonstantin Belousov }
685eb4d6a1bSKonstantin Belousov 
68624a1cce3SDavid Greenman /*
6871c7c3c6aSMatthew Dillon  * SWAP_PAGER_ALLOC() -	allocate a new OBJT_SWAP VM object and instantiate
6881c7c3c6aSMatthew Dillon  *			its metadata structures.
6891c7c3c6aSMatthew Dillon  *
6901c7c3c6aSMatthew Dillon  *	This routine is called from the mmap and fork code to create a new
691eb4d6a1bSKonstantin Belousov  *	OBJT_SWAP object.
6921c7c3c6aSMatthew Dillon  *
693eb4d6a1bSKonstantin Belousov  *	This routine must ensure that no live duplicate is created for
694eb4d6a1bSKonstantin Belousov  *	the named object request, which is protected against by
695eb4d6a1bSKonstantin Belousov  *	holding the sw_alloc_sx lock in case handle != NULL.
69624a1cce3SDavid Greenman  */
697f5a12711SPoul-Henning Kamp static vm_object_t
6986cde7a16SDavid Greenman swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
6993364c323SKonstantin Belousov     vm_ooffset_t offset, struct ucred *cred)
70024a1cce3SDavid Greenman {
70124a1cce3SDavid Greenman 	vm_object_t object;
7022f7af3dbSAlan Cox 
703eb4d6a1bSKonstantin Belousov 	if (handle != NULL) {
7041c7c3c6aSMatthew Dillon 		/*
7051c7c3c6aSMatthew Dillon 		 * Reference existing named region or allocate new one.  There
7061c7c3c6aSMatthew Dillon 		 * should not be a race here against swp_pager_meta_build()
7071c7c3c6aSMatthew Dillon 		 * as called from vm_page_remove() in regards to the lookup
7081c7c3c6aSMatthew Dillon 		 * of the handle.
7091c7c3c6aSMatthew Dillon 		 */
7100cddd8f0SMatthew Dillon 		sx_xlock(&sw_alloc_sx);
7111c7c3c6aSMatthew Dillon 		object = vm_pager_object_lookup(NOBJLIST(handle), handle);
712b5e8f167SAlan Cox 		if (object == NULL) {
713eb4d6a1bSKonstantin Belousov 			object = swap_pager_alloc_init(handle, cred, size,
714eb4d6a1bSKonstantin Belousov 			    offset);
715eb4d6a1bSKonstantin Belousov 			if (object != NULL) {
716eb4d6a1bSKonstantin Belousov 				TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
717eb4d6a1bSKonstantin Belousov 				    object, pager_object_list);
7183364c323SKonstantin Belousov 			}
71924a1cce3SDavid Greenman 		}
7200cddd8f0SMatthew Dillon 		sx_xunlock(&sw_alloc_sx);
72124a1cce3SDavid Greenman 	} else {
722eb4d6a1bSKonstantin Belousov 		object = swap_pager_alloc_init(handle, cred, size, offset);
72324a1cce3SDavid Greenman 	}
72424a1cce3SDavid Greenman 	return (object);
725df8bae1dSRodney W. Grimes }
726df8bae1dSRodney W. Grimes 
72726f9a767SRodney W. Grimes /*
7281c7c3c6aSMatthew Dillon  * SWAP_PAGER_DEALLOC() -	remove swap metadata from object
7291c7c3c6aSMatthew Dillon  *
7301c7c3c6aSMatthew Dillon  *	The swap backing for the object is destroyed.  The code is
7311c7c3c6aSMatthew Dillon  *	designed such that we can reinstantiate it later, but this
7321c7c3c6aSMatthew Dillon  *	routine is typically called only when the entire object is
7331c7c3c6aSMatthew Dillon  *	about to be destroyed.
7341c7c3c6aSMatthew Dillon  *
73515523cf7SKonstantin Belousov  *	The object must be locked.
73626f9a767SRodney W. Grimes  */
737df8bae1dSRodney W. Grimes static void
7382f249180SPoul-Henning Kamp swap_pager_dealloc(vm_object_t object)
73926f9a767SRodney W. Grimes {
7404dcc5c2dSMatthew Dillon 
741eb4d6a1bSKonstantin Belousov 	VM_OBJECT_ASSERT_WLOCKED(object);
742eb4d6a1bSKonstantin Belousov 	KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
743eb4d6a1bSKonstantin Belousov 
74426f9a767SRodney W. Grimes 	/*
7451c7c3c6aSMatthew Dillon 	 * Remove from list right away so lookups will fail if we block for
7461c7c3c6aSMatthew Dillon 	 * pageout completion.
74726f9a767SRodney W. Grimes 	 */
74867388836SKonstantin Belousov 	if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
749eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WUNLOCK(object);
750eb4d6a1bSKonstantin Belousov 		sx_xlock(&sw_alloc_sx);
751eb4d6a1bSKonstantin Belousov 		TAILQ_REMOVE(NOBJLIST(object->handle), object,
752eb4d6a1bSKonstantin Belousov 		    pager_object_list);
753eb4d6a1bSKonstantin Belousov 		sx_xunlock(&sw_alloc_sx);
754eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WLOCK(object);
755bd228075SAlan Cox 	}
7561c7c3c6aSMatthew Dillon 
7571c7c3c6aSMatthew Dillon 	vm_object_pip_wait(object, "swpdea");
7581c7c3c6aSMatthew Dillon 
7591c7c3c6aSMatthew Dillon 	/*
7601c7c3c6aSMatthew Dillon 	 * Free all remaining metadata.  We only bother to free it from
7611c7c3c6aSMatthew Dillon 	 * the swap meta data.  We do not attempt to free swapblk's still
7621c7c3c6aSMatthew Dillon 	 * associated with vm_page_t's for this object.  We do not care
7631c7c3c6aSMatthew Dillon 	 * if paging is still in progress on some objects.
7641c7c3c6aSMatthew Dillon 	 */
7651c7c3c6aSMatthew Dillon 	swp_pager_meta_free_all(object);
766e735691bSJohn Baldwin 	object->handle = NULL;
767e735691bSJohn Baldwin 	object->type = OBJT_DEAD;
7681c7c3c6aSMatthew Dillon }
7691c7c3c6aSMatthew Dillon 
7701c7c3c6aSMatthew Dillon /************************************************************************
7711c7c3c6aSMatthew Dillon  *			SWAP PAGER BITMAP ROUTINES			*
7721c7c3c6aSMatthew Dillon  ************************************************************************/
7731c7c3c6aSMatthew Dillon 
7741c7c3c6aSMatthew Dillon /*
7751c7c3c6aSMatthew Dillon  * SWP_PAGER_GETSWAPSPACE() -	allocate raw swap space
7761c7c3c6aSMatthew Dillon  *
77736b01270SDoug Moore  *	Allocate swap for up to the requested number of pages.  The
77836b01270SDoug Moore  *	starting swap block number (a page index) is returned or
77936b01270SDoug Moore  *	SWAPBLK_NONE if the allocation failed.
7801c7c3c6aSMatthew Dillon  *
7811c7c3c6aSMatthew Dillon  *	Also has the side effect of advising that somebody made a mistake
7821c7c3c6aSMatthew Dillon  *	when they configured swap and didn't configure enough.
7831c7c3c6aSMatthew Dillon  *
78415523cf7SKonstantin Belousov  *	This routine may not sleep.
7858f60c087SPoul-Henning Kamp  *
7868f60c087SPoul-Henning Kamp  *	We allocate in round-robin fashion from the configured devices.
7871c7c3c6aSMatthew Dillon  */
788a5edd34aSPoul-Henning Kamp static daddr_t
78936b01270SDoug Moore swp_pager_getswapspace(int *io_npages)
7901c7c3c6aSMatthew Dillon {
7911c7c3c6aSMatthew Dillon 	daddr_t blk;
7928f60c087SPoul-Henning Kamp 	struct swdevt *sp;
79387ae0686SDoug Moore 	int mpages, npages;
7941c7c3c6aSMatthew Dillon 
79536b01270SDoug Moore 	KASSERT(*io_npages >= 1,
79636b01270SDoug Moore 	    ("%s: npages not positive", __func__));
7978f60c087SPoul-Henning Kamp 	blk = SWAPBLK_NONE;
79831c82722SDoug Moore 	mpages = *io_npages;
79931c82722SDoug Moore 	npages = imin(BLIST_MAX_ALLOC, mpages);
80020da9c2eSPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
8018f60c087SPoul-Henning Kamp 	sp = swdevhd;
80248e98a2aSDoug Moore 	while (!TAILQ_EMPTY(&swtailq)) {
8038f60c087SPoul-Henning Kamp 		if (sp == NULL)
8048f60c087SPoul-Henning Kamp 			sp = TAILQ_FIRST(&swtailq);
80548e98a2aSDoug Moore 		if ((sp->sw_flags & SW_CLOSING) == 0)
80687ae0686SDoug Moore 			blk = blist_alloc(sp->sw_blist, &npages, mpages);
80748e98a2aSDoug Moore 		if (blk != SWAPBLK_NONE)
80848e98a2aSDoug Moore 			break;
80948e98a2aSDoug Moore 		sp = TAILQ_NEXT(sp, sw_list);
81048e98a2aSDoug Moore 		if (swdevhd == sp) {
81136b01270SDoug Moore 			if (npages == 1)
81248e98a2aSDoug Moore 				break;
81387ae0686SDoug Moore 			mpages = npages - 1;
81448e98a2aSDoug Moore 			npages >>= 1;
81548e98a2aSDoug Moore 		}
81648e98a2aSDoug Moore 	}
8178f60c087SPoul-Henning Kamp 	if (blk != SWAPBLK_NONE) {
81848e98a2aSDoug Moore 		*io_npages = npages;
8198f60c087SPoul-Henning Kamp 		blk += sp->sw_first;
8208f60c087SPoul-Henning Kamp 		sp->sw_used += npages;
821d05bc129SAlan Cox 		swap_pager_avail -= npages;
8228f60c087SPoul-Henning Kamp 		swp_sizecheck();
8238f60c087SPoul-Henning Kamp 		swdevhd = TAILQ_NEXT(sp, sw_list);
82448e98a2aSDoug Moore 	} else {
8252b0d37a4SMatthew Dillon 		if (swap_pager_full != 2) {
82648e98a2aSDoug Moore 			printf("swp_pager_getswapspace(%d): failed\n",
82748e98a2aSDoug Moore 			    *io_npages);
8282b0d37a4SMatthew Dillon 			swap_pager_full = 2;
82920d3034fSMatthew Dillon 			swap_pager_almost_full = 1;
8302b0d37a4SMatthew Dillon 		}
8318f60c087SPoul-Henning Kamp 		swdevhd = NULL;
83248e98a2aSDoug Moore 	}
833d05bc129SAlan Cox 	mtx_unlock(&sw_dev_mtx);
8341c7c3c6aSMatthew Dillon 	return (blk);
83526f9a767SRodney W. Grimes }
83626f9a767SRodney W. Grimes 
837541a1175SAlan Cox static bool
838b3fed13eSDavid Schultz swp_pager_isondev(daddr_t blk, struct swdevt *sp)
8398f60c087SPoul-Henning Kamp {
8408f60c087SPoul-Henning Kamp 
841b3fed13eSDavid Schultz 	return (blk >= sp->sw_first && blk < sp->sw_end);
8428f60c087SPoul-Henning Kamp }
8438f60c087SPoul-Henning Kamp 
8444b03903aSPoul-Henning Kamp static void
8454b03903aSPoul-Henning Kamp swp_pager_strategy(struct buf *bp)
8464b03903aSPoul-Henning Kamp {
8474b03903aSPoul-Henning Kamp 	struct swdevt *sp;
8484b03903aSPoul-Henning Kamp 
84920da9c2eSPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
8504b03903aSPoul-Henning Kamp 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
851541a1175SAlan Cox 		if (swp_pager_isondev(bp->b_blkno, sp)) {
85220da9c2eSPoul-Henning Kamp 			mtx_unlock(&sw_dev_mtx);
8532cc718a1SKonstantin Belousov 			if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
8542cc718a1SKonstantin Belousov 			    unmapped_buf_allowed) {
8552cc718a1SKonstantin Belousov 				bp->b_data = unmapped_buf;
8562cc718a1SKonstantin Belousov 				bp->b_offset = 0;
8572cc718a1SKonstantin Belousov 			} else {
8582cc718a1SKonstantin Belousov 				pmap_qenter((vm_offset_t)bp->b_data,
8592cc718a1SKonstantin Belousov 				    &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
8602cc718a1SKonstantin Belousov 			}
8614b03903aSPoul-Henning Kamp 			sp->sw_strategy(bp, sp);
8624b03903aSPoul-Henning Kamp 			return;
8634b03903aSPoul-Henning Kamp 		}
8644b03903aSPoul-Henning Kamp 	}
86520da9c2eSPoul-Henning Kamp 	panic("Swapdev not found");
8664b03903aSPoul-Henning Kamp }
8674b03903aSPoul-Henning Kamp 
86826f9a767SRodney W. Grimes /*
8691c7c3c6aSMatthew Dillon  * SWP_PAGER_FREESWAPSPACE() -	free raw swap space
8701c7c3c6aSMatthew Dillon  *
8711c7c3c6aSMatthew Dillon  *	This routine returns the specified swap blocks back to the bitmap.
8721c7c3c6aSMatthew Dillon  *
87315523cf7SKonstantin Belousov  *	This routine may not sleep.
87426f9a767SRodney W. Grimes  */
875a5edd34aSPoul-Henning Kamp static void
876230869e0SAlan Cox swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
8770d94caffSDavid Greenman {
8788f60c087SPoul-Henning Kamp 	struct swdevt *sp;
87992da00bbSMatthew Dillon 
880230869e0SAlan Cox 	if (npages == 0)
881230869e0SAlan Cox 		return;
8827645e885SAlan Cox 	mtx_lock(&sw_dev_mtx);
8837645e885SAlan Cox 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
884541a1175SAlan Cox 		if (swp_pager_isondev(blk, sp)) {
88592da00bbSMatthew Dillon 			sp->sw_used -= npages;
88692da00bbSMatthew Dillon 			/*
8877645e885SAlan Cox 			 * If we are attempting to stop swapping on
8887645e885SAlan Cox 			 * this device, we don't want to mark any
8897645e885SAlan Cox 			 * blocks free lest they be reused.
89092da00bbSMatthew Dillon 			 */
8917645e885SAlan Cox 			if ((sp->sw_flags & SW_CLOSING) == 0) {
8927645e885SAlan Cox 				blist_free(sp->sw_blist, blk - sp->sw_first,
8937645e885SAlan Cox 				    npages);
8948f60c087SPoul-Henning Kamp 				swap_pager_avail += npages;
8951c7c3c6aSMatthew Dillon 				swp_sizecheck();
89626f9a767SRodney W. Grimes 			}
8977645e885SAlan Cox 			mtx_unlock(&sw_dev_mtx);
8987645e885SAlan Cox 			return;
8997645e885SAlan Cox 		}
9007645e885SAlan Cox 	}
9017645e885SAlan Cox 	panic("Swapdev not found");
9027645e885SAlan Cox }
9031c7c3c6aSMatthew Dillon 
90426f9a767SRodney W. Grimes /*
905d027ed2eSAlan Cox  * SYSCTL_SWAP_FRAGMENTATION() -	produce raw swap space stats
906d027ed2eSAlan Cox  */
907d027ed2eSAlan Cox static int
908d027ed2eSAlan Cox sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
909d027ed2eSAlan Cox {
910d027ed2eSAlan Cox 	struct sbuf sbuf;
911d027ed2eSAlan Cox 	struct swdevt *sp;
912d027ed2eSAlan Cox 	const char *devname;
913d027ed2eSAlan Cox 	int error;
914d027ed2eSAlan Cox 
915d027ed2eSAlan Cox 	error = sysctl_wire_old_buffer(req, 0);
916d027ed2eSAlan Cox 	if (error != 0)
917d027ed2eSAlan Cox 		return (error);
918d027ed2eSAlan Cox 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
919d027ed2eSAlan Cox 	mtx_lock(&sw_dev_mtx);
920d027ed2eSAlan Cox 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
9217ad2a82dSMateusz Guzik 		if (vn_isdisk(sp->sw_vp))
922d027ed2eSAlan Cox 			devname = devtoname(sp->sw_vp->v_rdev);
923d027ed2eSAlan Cox 		else
924d027ed2eSAlan Cox 			devname = "[file]";
925d027ed2eSAlan Cox 		sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
926d027ed2eSAlan Cox 		blist_stats(sp->sw_blist, &sbuf);
927d027ed2eSAlan Cox 	}
928d027ed2eSAlan Cox 	mtx_unlock(&sw_dev_mtx);
929d027ed2eSAlan Cox 	error = sbuf_finish(&sbuf);
930d027ed2eSAlan Cox 	sbuf_delete(&sbuf);
931d027ed2eSAlan Cox 	return (error);
932d027ed2eSAlan Cox }
933d027ed2eSAlan Cox 
934d027ed2eSAlan Cox /*
9351c7c3c6aSMatthew Dillon  * SWAP_PAGER_FREESPACE() -	frees swap blocks associated with a page
9361c7c3c6aSMatthew Dillon  *				range within an object.
9371c7c3c6aSMatthew Dillon  *
9381c7c3c6aSMatthew Dillon  *	This is a globally accessible routine.
9391c7c3c6aSMatthew Dillon  *
9401c7c3c6aSMatthew Dillon  *	This routine removes swapblk assignments from swap metadata.
9411c7c3c6aSMatthew Dillon  *
9421c7c3c6aSMatthew Dillon  *	The external callers of this routine typically have already destroyed
9431c7c3c6aSMatthew Dillon  *	or renamed vm_page_t's associated with this range in the object so
9441c7c3c6aSMatthew Dillon  *	we should be ok.
945c25673ffSAttilio Rao  *
946c25673ffSAttilio Rao  *	The object must be locked.
94726f9a767SRodney W. Grimes  */
94826f9a767SRodney W. Grimes void
9492f249180SPoul-Henning Kamp swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
95026f9a767SRodney W. Grimes {
95123955314SAlfred Perlstein 
9521c7c3c6aSMatthew Dillon 	swp_pager_meta_free(object, start, size);
9534dcc5c2dSMatthew Dillon }
9544dcc5c2dSMatthew Dillon 
9554dcc5c2dSMatthew Dillon /*
9564dcc5c2dSMatthew Dillon  * SWAP_PAGER_RESERVE() - reserve swap blocks in object
9574dcc5c2dSMatthew Dillon  *
9584dcc5c2dSMatthew Dillon  *	Assigns swap blocks to the specified range within the object.  The
95956ce850bSKonstantin Belousov  *	swap blocks are not zeroed.  Any previous swap assignment is destroyed.
9604dcc5c2dSMatthew Dillon  *
9614dcc5c2dSMatthew Dillon  *	Returns 0 on success, -1 on failure.
9624dcc5c2dSMatthew Dillon  */
9634dcc5c2dSMatthew Dillon int
9644dcc5c2dSMatthew Dillon swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
9654dcc5c2dSMatthew Dillon {
96648e98a2aSDoug Moore 	daddr_t addr, blk, n_free, s_free;
96748e98a2aSDoug Moore 	int i, j, n;
9684dcc5c2dSMatthew Dillon 
96978f1deefSAlan Cox 	swp_pager_init_freerange(&s_free, &n_free);
97089f6b863SAttilio Rao 	VM_OBJECT_WLOCK(object);
97148e98a2aSDoug Moore 	for (i = 0; i < size; i += n) {
97231c82722SDoug Moore 		n = size - i;
97336b01270SDoug Moore 		blk = swp_pager_getswapspace(&n);
97448e98a2aSDoug Moore 		if (blk == SWAPBLK_NONE) {
97548e98a2aSDoug Moore 			swp_pager_meta_free(object, start, i);
97689f6b863SAttilio Rao 			VM_OBJECT_WUNLOCK(object);
9774dcc5c2dSMatthew Dillon 			return (-1);
9784dcc5c2dSMatthew Dillon 		}
97948e98a2aSDoug Moore 		for (j = 0; j < n; ++j) {
98048e98a2aSDoug Moore 			addr = swp_pager_meta_build(object,
98148e98a2aSDoug Moore 			    start + i + j, blk + j);
98278f1deefSAlan Cox 			if (addr != SWAPBLK_NONE)
98348e98a2aSDoug Moore 				swp_pager_update_freerange(&s_free, &n_free,
98448e98a2aSDoug Moore 				    addr);
98548e98a2aSDoug Moore 		}
9864dcc5c2dSMatthew Dillon 	}
98778f1deefSAlan Cox 	swp_pager_freeswapspace(s_free, n_free);
98889f6b863SAttilio Rao 	VM_OBJECT_WUNLOCK(object);
9894dcc5c2dSMatthew Dillon 	return (0);
99026f9a767SRodney W. Grimes }
99126f9a767SRodney W. Grimes 
992467057fcSDoug Moore static bool
993467057fcSDoug Moore swp_pager_xfer_source(vm_object_t srcobject, vm_object_t dstobject,
994467057fcSDoug Moore     vm_pindex_t pindex, daddr_t addr)
995467057fcSDoug Moore {
996467057fcSDoug Moore 	daddr_t dstaddr;
997467057fcSDoug Moore 
9988ecbf14bSDoug Moore 	KASSERT(srcobject->type == OBJT_SWAP,
9998ecbf14bSDoug Moore 	    ("%s: Srcobject not swappable", __func__));
10008ecbf14bSDoug Moore 	if (dstobject->type == OBJT_SWAP &&
10018ecbf14bSDoug Moore 	    swp_pager_meta_lookup(dstobject, pindex) != SWAPBLK_NONE) {
1002467057fcSDoug Moore 		/* Caller should destroy the source block. */
1003467057fcSDoug Moore 		return (false);
1004467057fcSDoug Moore 	}
1005467057fcSDoug Moore 
1006467057fcSDoug Moore 	/*
1007467057fcSDoug Moore 	 * Destination has no swapblk and is not resident, transfer source.
1008467057fcSDoug Moore 	 * swp_pager_meta_build() can sleep.
1009467057fcSDoug Moore 	 */
1010467057fcSDoug Moore 	VM_OBJECT_WUNLOCK(srcobject);
1011467057fcSDoug Moore 	dstaddr = swp_pager_meta_build(dstobject, pindex, addr);
1012467057fcSDoug Moore 	KASSERT(dstaddr == SWAPBLK_NONE,
1013467057fcSDoug Moore 	    ("Unexpected destination swapblk"));
1014467057fcSDoug Moore 	VM_OBJECT_WLOCK(srcobject);
101598087a06SJeff Roberson 
1016467057fcSDoug Moore 	return (true);
1017467057fcSDoug Moore }
1018467057fcSDoug Moore 
10190a47b48bSJohn Dyson /*
10201c7c3c6aSMatthew Dillon  * SWAP_PAGER_COPY() -  copy blocks from source pager to destination pager
10211c7c3c6aSMatthew Dillon  *			and destroy the source.
10221c7c3c6aSMatthew Dillon  *
10231c7c3c6aSMatthew Dillon  *	Copy any valid swapblks from the source to the destination.  In
10241c7c3c6aSMatthew Dillon  *	cases where both the source and destination have a valid swapblk,
10251c7c3c6aSMatthew Dillon  *	we keep the destination's.
10261c7c3c6aSMatthew Dillon  *
102715523cf7SKonstantin Belousov  *	This routine is allowed to sleep.  It may sleep allocating metadata
102898087a06SJeff Roberson  *	indirectly through swp_pager_meta_build().
10291c7c3c6aSMatthew Dillon  *
10301c7c3c6aSMatthew Dillon  *	The source object contains no vm_page_t's (which is just as well)
10311c7c3c6aSMatthew Dillon  *
10321c7c3c6aSMatthew Dillon  *	The source object is of type OBJT_SWAP.
10331c7c3c6aSMatthew Dillon  *
103415523cf7SKonstantin Belousov  *	The source and destination objects must be locked.
103515523cf7SKonstantin Belousov  *	Both object locks may temporarily be released.
103626f9a767SRodney W. Grimes  */
103726f9a767SRodney W. Grimes void
10382f249180SPoul-Henning Kamp swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
10392f249180SPoul-Henning Kamp     vm_pindex_t offset, int destroysource)
104026f9a767SRodney W. Grimes {
10414dcc5c2dSMatthew Dillon 
104289f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(srcobject);
104389f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(dstobject);
10440cddd8f0SMatthew Dillon 
104526f9a767SRodney W. Grimes 	/*
10461c7c3c6aSMatthew Dillon 	 * If destroysource is set, we remove the source object from the
10471c7c3c6aSMatthew Dillon 	 * swap_pager internal queue now.
104826f9a767SRodney W. Grimes 	 */
104967388836SKonstantin Belousov 	if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
105067388836SKonstantin Belousov 	    srcobject->handle != NULL) {
1051eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WUNLOCK(srcobject);
1052eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WUNLOCK(dstobject);
1053eb4d6a1bSKonstantin Belousov 		sx_xlock(&sw_alloc_sx);
1054eb4d6a1bSKonstantin Belousov 		TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1055eb4d6a1bSKonstantin Belousov 		    pager_object_list);
1056eb4d6a1bSKonstantin Belousov 		sx_xunlock(&sw_alloc_sx);
1057eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WLOCK(dstobject);
1058eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WLOCK(srcobject);
1059bd228075SAlan Cox 	}
106026f9a767SRodney W. Grimes 
10611c7c3c6aSMatthew Dillon 	/*
10624abca9bbSAlan Cox 	 * Transfer source to destination.
10631c7c3c6aSMatthew Dillon 	 */
1064467057fcSDoug Moore 	swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size);
106526f9a767SRodney W. Grimes 
106626f9a767SRodney W. Grimes 	/*
10671c7c3c6aSMatthew Dillon 	 * Free left over swap blocks in source.
10681c7c3c6aSMatthew Dillon 	 *
1069763df3ecSPedro F. Giffuni 	 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
10701c7c3c6aSMatthew Dillon 	 * double-remove the object from the swap queues.
107126f9a767SRodney W. Grimes 	 */
1072c0877f10SJohn Dyson 	if (destroysource) {
10731c7c3c6aSMatthew Dillon 		swp_pager_meta_free_all(srcobject);
10741c7c3c6aSMatthew Dillon 		/*
10751c7c3c6aSMatthew Dillon 		 * Reverting the type is not necessary, the caller is going
10761c7c3c6aSMatthew Dillon 		 * to destroy srcobject directly, but I'm doing it here
1077956f3135SPhilippe Charnier 		 * for consistency since we've removed the object from its
10781c7c3c6aSMatthew Dillon 		 * queues.
10791c7c3c6aSMatthew Dillon 		 */
10801c7c3c6aSMatthew Dillon 		srcobject->type = OBJT_DEFAULT;
1081c0877f10SJohn Dyson 	}
108226f9a767SRodney W. Grimes }
108326f9a767SRodney W. Grimes 
1084df8bae1dSRodney W. Grimes /*
10851c7c3c6aSMatthew Dillon  * SWAP_PAGER_HASPAGE() -	determine if we have good backing store for
10861c7c3c6aSMatthew Dillon  *				the requested page.
10871c7c3c6aSMatthew Dillon  *
10881c7c3c6aSMatthew Dillon  *	We determine whether good backing store exists for the requested
10891c7c3c6aSMatthew Dillon  *	page and return TRUE if it does, FALSE if it doesn't.
10901c7c3c6aSMatthew Dillon  *
10911c7c3c6aSMatthew Dillon  *	If TRUE, we also try to determine how much valid, contiguous backing
1092915d1b71SMark Johnston  *	store exists before and after the requested page.
1093df8bae1dSRodney W. Grimes  */
10945ea4972cSAlan Cox static boolean_t
1095915d1b71SMark Johnston swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1096915d1b71SMark Johnston     int *after)
109726f9a767SRodney W. Grimes {
1098915d1b71SMark Johnston 	daddr_t blk, blk0;
1099915d1b71SMark Johnston 	int i;
110026f9a767SRodney W. Grimes 
1101c25673ffSAttilio Rao 	VM_OBJECT_ASSERT_LOCKED(object);
11028ecbf14bSDoug Moore 	KASSERT(object->type == OBJT_SWAP,
11038ecbf14bSDoug Moore 	    ("%s: object not swappable", __func__));
1104915d1b71SMark Johnston 
11051c7c3c6aSMatthew Dillon 	/*
11061c7c3c6aSMatthew Dillon 	 * do we have good backing store at the requested index ?
11071c7c3c6aSMatthew Dillon 	 */
11088ecbf14bSDoug Moore 	blk0 = swp_pager_meta_lookup(object, pindex);
11094dcc5c2dSMatthew Dillon 	if (blk0 == SWAPBLK_NONE) {
11101c7c3c6aSMatthew Dillon 		if (before)
111124a1cce3SDavid Greenman 			*before = 0;
11121c7c3c6aSMatthew Dillon 		if (after)
111324a1cce3SDavid Greenman 			*after = 0;
111426f9a767SRodney W. Grimes 		return (FALSE);
111526f9a767SRodney W. Grimes 	}
111626f9a767SRodney W. Grimes 
111726f9a767SRodney W. Grimes 	/*
11181c7c3c6aSMatthew Dillon 	 * find backwards-looking contiguous good backing store
1119e47ed70bSJohn Dyson 	 */
11201c7c3c6aSMatthew Dillon 	if (before != NULL) {
1121915d1b71SMark Johnston 		for (i = 1; i < SWB_NPAGES; i++) {
11221c7c3c6aSMatthew Dillon 			if (i > pindex)
11231c7c3c6aSMatthew Dillon 				break;
11248ecbf14bSDoug Moore 			blk = swp_pager_meta_lookup(object, pindex - i);
11251c7c3c6aSMatthew Dillon 			if (blk != blk0 - i)
11261c7c3c6aSMatthew Dillon 				break;
1127ffc82b0aSJohn Dyson 		}
1128915d1b71SMark Johnston 		*before = i - 1;
112926f9a767SRodney W. Grimes 	}
113026f9a767SRodney W. Grimes 
113126f9a767SRodney W. Grimes 	/*
11321c7c3c6aSMatthew Dillon 	 * find forward-looking contiguous good backing store
113326f9a767SRodney W. Grimes 	 */
11341c7c3c6aSMatthew Dillon 	if (after != NULL) {
1135915d1b71SMark Johnston 		for (i = 1; i < SWB_NPAGES; i++) {
11368ecbf14bSDoug Moore 			blk = swp_pager_meta_lookup(object, pindex + i);
11371c7c3c6aSMatthew Dillon 			if (blk != blk0 + i)
11381c7c3c6aSMatthew Dillon 				break;
113926f9a767SRodney W. Grimes 		}
1140915d1b71SMark Johnston 		*after = i - 1;
11411c7c3c6aSMatthew Dillon 	}
11421c7c3c6aSMatthew Dillon 	return (TRUE);
11431c7c3c6aSMatthew Dillon }
11441c7c3c6aSMatthew Dillon 
11451c7c3c6aSMatthew Dillon /*
11461c7c3c6aSMatthew Dillon  * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
11471c7c3c6aSMatthew Dillon  *
11481c7c3c6aSMatthew Dillon  *	This removes any associated swap backing store, whether valid or
11491c7c3c6aSMatthew Dillon  *	not, from the page.
11501c7c3c6aSMatthew Dillon  *
11511c7c3c6aSMatthew Dillon  *	This routine is typically called when a page is made dirty, at
11521c7c3c6aSMatthew Dillon  *	which point any associated swap can be freed.  MADV_FREE also
11531c7c3c6aSMatthew Dillon  *	calls us in a special-case situation
11541c7c3c6aSMatthew Dillon  *
11551c7c3c6aSMatthew Dillon  *	NOTE!!!  If the page is clean and the swap was valid, the caller
11561c7c3c6aSMatthew Dillon  *	should make the page dirty before calling this routine.  This routine
11571c7c3c6aSMatthew Dillon  *	does NOT change the m->dirty status of the page.  Also: MADV_FREE
11581c7c3c6aSMatthew Dillon  *	depends on it.
11591c7c3c6aSMatthew Dillon  *
116015523cf7SKonstantin Belousov  *	This routine may not sleep.
1161c25673ffSAttilio Rao  *
1162a8081778SJeff Roberson  *	The object containing the page may be locked.
11631c7c3c6aSMatthew Dillon  */
11641c7c3c6aSMatthew Dillon static void
11652f249180SPoul-Henning Kamp swap_pager_unswapped(vm_page_t m)
11661c7c3c6aSMatthew Dillon {
11678ecbf14bSDoug Moore 	struct swblk *sb;
1168a8081778SJeff Roberson 	vm_object_t obj;
11692f249180SPoul-Henning Kamp 
1170a8081778SJeff Roberson 	/*
1171a8081778SJeff Roberson 	 * Handle enqueing deferred frees first.  If we do not have the
1172a8081778SJeff Roberson 	 * object lock we wait for the page daemon to clear the space.
1173a8081778SJeff Roberson 	 */
1174a8081778SJeff Roberson 	obj = m->object;
1175a8081778SJeff Roberson 	if (!VM_OBJECT_WOWNED(obj)) {
1176a8081778SJeff Roberson 		VM_PAGE_OBJECT_BUSY_ASSERT(m);
1177a8081778SJeff Roberson 		/*
1178a8081778SJeff Roberson 		 * The caller is responsible for synchronization but we
1179a8081778SJeff Roberson 		 * will harmlessly handle races.  This is typically provided
1180a8081778SJeff Roberson 		 * by only calling unswapped() when a page transitions from
1181a8081778SJeff Roberson 		 * clean to dirty.
1182a8081778SJeff Roberson 		 */
1183a8081778SJeff Roberson 		if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1184a8081778SJeff Roberson 		    PGA_SWAP_SPACE) {
1185a8081778SJeff Roberson 			vm_page_aflag_set(m, PGA_SWAP_FREE);
1186a8081778SJeff Roberson 			counter_u64_add(swap_free_deferred, 1);
1187a8081778SJeff Roberson 		}
1188a8081778SJeff Roberson 		return;
1189a8081778SJeff Roberson 	}
1190a8081778SJeff Roberson 	if ((m->a.flags & PGA_SWAP_FREE) != 0)
1191a8081778SJeff Roberson 		counter_u64_add(swap_free_completed, 1);
1192a8081778SJeff Roberson 	vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
11938ecbf14bSDoug Moore 
11948ecbf14bSDoug Moore 	/*
11958ecbf14bSDoug Moore 	 * The meta data only exists if the object is OBJT_SWAP
11968ecbf14bSDoug Moore 	 * and even then might not be allocated yet.
11978ecbf14bSDoug Moore 	 */
11988ecbf14bSDoug Moore 	KASSERT(m->object->type == OBJT_SWAP,
11998ecbf14bSDoug Moore 	    ("Free object not swappable"));
12008ecbf14bSDoug Moore 
12018ecbf14bSDoug Moore 	sb = SWAP_PCTRIE_LOOKUP(&m->object->un_pager.swp.swp_blks,
12028ecbf14bSDoug Moore 	    rounddown(m->pindex, SWAP_META_PAGES));
12038ecbf14bSDoug Moore 	if (sb == NULL)
12048ecbf14bSDoug Moore 		return;
12058ecbf14bSDoug Moore 	if (sb->d[m->pindex % SWAP_META_PAGES] == SWAPBLK_NONE)
12068ecbf14bSDoug Moore 		return;
12078ecbf14bSDoug Moore 	swp_pager_freeswapspace(sb->d[m->pindex % SWAP_META_PAGES], 1);
12088ecbf14bSDoug Moore 	sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
12098ecbf14bSDoug Moore 	swp_pager_free_empty_swblk(m->object, sb);
12101c7c3c6aSMatthew Dillon }
12111c7c3c6aSMatthew Dillon 
12121c7c3c6aSMatthew Dillon /*
1213915d1b71SMark Johnston  * swap_pager_getpages() - bring pages in from swap
12141c7c3c6aSMatthew Dillon  *
12153f060b60SMark Johnston  *	Attempt to page in the pages in array "ma" of length "count".  The
12163f060b60SMark Johnston  *	caller may optionally specify that additional pages preceding and
12173f060b60SMark Johnston  *	succeeding the specified range be paged in.  The number of such pages
12183f060b60SMark Johnston  *	is returned in the "rbehind" and "rahead" parameters, and they will
12193f060b60SMark Johnston  *	be in the inactive queue upon return.
12201c7c3c6aSMatthew Dillon  *
12213f060b60SMark Johnston  *	The pages in "ma" must be busied and will remain busied upon return.
12221c7c3c6aSMatthew Dillon  */
1223f708ef1bSPoul-Henning Kamp static int
1224c90d075bSMark Johnston swap_pager_getpages_locked(vm_object_t object, vm_page_t *ma, int count,
1225c90d075bSMark Johnston     int *rbehind, int *rahead)
1226df8bae1dSRodney W. Grimes {
12271c7c3c6aSMatthew Dillon 	struct buf *bp;
1228b7b8a096SKonstantin Belousov 	vm_page_t bm, mpred, msucc, p;
1229915d1b71SMark Johnston 	vm_pindex_t pindex;
12301c7c3c6aSMatthew Dillon 	daddr_t blk;
1231b7b8a096SKonstantin Belousov 	int i, maxahead, maxbehind, reqcount;
12320d94caffSDavid Greenman 
1233c90d075bSMark Johnston 	VM_OBJECT_ASSERT_WLOCKED(object);
1234915d1b71SMark Johnston 	reqcount = count;
12351c7c3c6aSMatthew Dillon 
12368ecbf14bSDoug Moore 	KASSERT(object->type == OBJT_SWAP,
12378ecbf14bSDoug Moore 	    ("%s: object not swappable", __func__));
1238d6e13f3bSJeff Roberson 	if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead)) {
1239d6e13f3bSJeff Roberson 		VM_OBJECT_WUNLOCK(object);
1240915d1b71SMark Johnston 		return (VM_PAGER_FAIL);
1241d6e13f3bSJeff Roberson 	}
1242915d1b71SMark Johnston 
124398087a06SJeff Roberson 	KASSERT(reqcount - 1 <= maxahead,
124498087a06SJeff Roberson 	    ("page count %d extends beyond swap block", reqcount));
124598087a06SJeff Roberson 
124698087a06SJeff Roberson 	/*
124798087a06SJeff Roberson 	 * Do not transfer any pages other than those that are xbusied
124898087a06SJeff Roberson 	 * when running during a split or collapse operation.  This
124998087a06SJeff Roberson 	 * prevents clustering from re-creating pages which are being
125098087a06SJeff Roberson 	 * moved into another object.
125198087a06SJeff Roberson 	 */
125298087a06SJeff Roberson 	if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
125398087a06SJeff Roberson 		maxahead = reqcount - 1;
125498087a06SJeff Roberson 		maxbehind = 0;
125598087a06SJeff Roberson 	}
125698087a06SJeff Roberson 
1257915d1b71SMark Johnston 	/*
1258915d1b71SMark Johnston 	 * Clip the readahead and readbehind ranges to exclude resident pages.
1259915d1b71SMark Johnston 	 */
1260915d1b71SMark Johnston 	if (rahead != NULL) {
1261dd9cb6daSMark Johnston 		*rahead = imin(*rahead, maxahead - (reqcount - 1));
12623f060b60SMark Johnston 		pindex = ma[reqcount - 1]->pindex;
12633f060b60SMark Johnston 		msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1264915d1b71SMark Johnston 		if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1265915d1b71SMark Johnston 			*rahead = msucc->pindex - pindex - 1;
1266915d1b71SMark Johnston 	}
1267915d1b71SMark Johnston 	if (rbehind != NULL) {
1268dd9cb6daSMark Johnston 		*rbehind = imin(*rbehind, maxbehind);
12693f060b60SMark Johnston 		pindex = ma[0]->pindex;
12703f060b60SMark Johnston 		mpred = TAILQ_PREV(ma[0], pglist, listq);
1271915d1b71SMark Johnston 		if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1272915d1b71SMark Johnston 			*rbehind = pindex - mpred->pindex - 1;
1273915d1b71SMark Johnston 	}
1274915d1b71SMark Johnston 
1275b7b8a096SKonstantin Belousov 	bm = ma[0];
1276b7b8a096SKonstantin Belousov 	for (i = 0; i < count; i++)
1277b7b8a096SKonstantin Belousov 		ma[i]->oflags |= VPO_SWAPINPROG;
1278b7b8a096SKonstantin Belousov 
1279915d1b71SMark Johnston 	/*
1280915d1b71SMark Johnston 	 * Allocate readahead and readbehind pages.
1281915d1b71SMark Johnston 	 */
1282b7b8a096SKonstantin Belousov 	if (rbehind != NULL) {
1283b7b8a096SKonstantin Belousov 		for (i = 1; i <= *rbehind; i++) {
12843f060b60SMark Johnston 			p = vm_page_alloc(object, ma[0]->pindex - i,
12857667839aSAlan Cox 			    VM_ALLOC_NORMAL);
1286b7b8a096SKonstantin Belousov 			if (p == NULL)
1287915d1b71SMark Johnston 				break;
1288b7b8a096SKonstantin Belousov 			p->oflags |= VPO_SWAPINPROG;
1289b7b8a096SKonstantin Belousov 			bm = p;
1290915d1b71SMark Johnston 		}
1291b7b8a096SKonstantin Belousov 		*rbehind = i - 1;
1292915d1b71SMark Johnston 	}
1293915d1b71SMark Johnston 	if (rahead != NULL) {
1294915d1b71SMark Johnston 		for (i = 0; i < *rahead; i++) {
1295915d1b71SMark Johnston 			p = vm_page_alloc(object,
12963f060b60SMark Johnston 			    ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1297915d1b71SMark Johnston 			if (p == NULL)
1298915d1b71SMark Johnston 				break;
1299b7b8a096SKonstantin Belousov 			p->oflags |= VPO_SWAPINPROG;
1300915d1b71SMark Johnston 		}
1301915d1b71SMark Johnston 		*rahead = i;
1302915d1b71SMark Johnston 	}
1303915d1b71SMark Johnston 	if (rbehind != NULL)
1304915d1b71SMark Johnston 		count += *rbehind;
1305915d1b71SMark Johnston 	if (rahead != NULL)
1306915d1b71SMark Johnston 		count += *rahead;
1307915d1b71SMark Johnston 
1308915d1b71SMark Johnston 	vm_object_pip_add(object, count);
1309915d1b71SMark Johnston 
1310b7b8a096SKonstantin Belousov 	pindex = bm->pindex;
13118ecbf14bSDoug Moore 	blk = swp_pager_meta_lookup(object, pindex);
1312915d1b71SMark Johnston 	KASSERT(blk != SWAPBLK_NONE,
1313915d1b71SMark Johnston 	    ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1314915d1b71SMark Johnston 
1315915d1b71SMark Johnston 	VM_OBJECT_WUNLOCK(object);
1316756a5412SGleb Smirnoff 	bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1317cd853791SKonstantin Belousov 	MPASS((bp->b_flags & B_MAXPHYS) != 0);
1318b7b8a096SKonstantin Belousov 	/* Pages cannot leave the object while busy. */
1319b7b8a096SKonstantin Belousov 	for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1320b7b8a096SKonstantin Belousov 		MPASS(p->pindex == bm->pindex + i);
1321b7b8a096SKonstantin Belousov 		bp->b_pages[i] = p;
1322b7b8a096SKonstantin Belousov 	}
1323915d1b71SMark Johnston 
1324915d1b71SMark Johnston 	bp->b_flags |= B_PAGING;
132521144e3bSPoul-Henning Kamp 	bp->b_iocmd = BIO_READ;
13261c7c3c6aSMatthew Dillon 	bp->b_iodone = swp_pager_async_iodone;
1327fdcc1cc0SJohn Baldwin 	bp->b_rcred = crhold(thread0.td_ucred);
1328fdcc1cc0SJohn Baldwin 	bp->b_wcred = crhold(thread0.td_ucred);
1329b0cd2017SGleb Smirnoff 	bp->b_blkno = blk;
1330b0cd2017SGleb Smirnoff 	bp->b_bcount = PAGE_SIZE * count;
1331b0cd2017SGleb Smirnoff 	bp->b_bufsize = PAGE_SIZE * count;
1332b0cd2017SGleb Smirnoff 	bp->b_npages = count;
1333915d1b71SMark Johnston 	bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1334915d1b71SMark Johnston 	bp->b_pgafter = rahead != NULL ? *rahead : 0;
133526f9a767SRodney W. Grimes 
133683c9dea1SGleb Smirnoff 	VM_CNT_INC(v_swapin);
133783c9dea1SGleb Smirnoff 	VM_CNT_ADD(v_swappgsin, count);
13381c7c3c6aSMatthew Dillon 
13391c7c3c6aSMatthew Dillon 	/*
13401c7c3c6aSMatthew Dillon 	 * perform the I/O.  NOTE!!!  bp cannot be considered valid after
13411c7c3c6aSMatthew Dillon 	 * this point because we automatically release it on completion.
13421c7c3c6aSMatthew Dillon 	 * Instead, we look at the one page we are interested in which we
13431c7c3c6aSMatthew Dillon 	 * still hold a lock on even through the I/O completion.
13441c7c3c6aSMatthew Dillon 	 *
13453f060b60SMark Johnston 	 * The other pages in our ma[] array are also released on completion,
13461c7c3c6aSMatthew Dillon 	 * so we cannot assume they are valid anymore either.
13471c7c3c6aSMatthew Dillon 	 *
1348c37a77eeSPoul-Henning Kamp 	 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
13491c7c3c6aSMatthew Dillon 	 */
1350b890cb2cSPeter Wemm 	BUF_KERNPROC(bp);
13514b03903aSPoul-Henning Kamp 	swp_pager_strategy(bp);
135226f9a767SRodney W. Grimes 
135326f9a767SRodney W. Grimes 	/*
1354915d1b71SMark Johnston 	 * Wait for the pages we want to complete.  VPO_SWAPINPROG is always
13551c7c3c6aSMatthew Dillon 	 * cleared on completion.  If an I/O error occurs, SWAPBLK_NONE
1356915d1b71SMark Johnston 	 * is set in the metadata for each page in the request.
135726f9a767SRodney W. Grimes 	 */
135889f6b863SAttilio Rao 	VM_OBJECT_WLOCK(object);
1359d6e13f3bSJeff Roberson 	/* This could be implemented more efficiently with aflags */
13603f060b60SMark Johnston 	while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
13613f060b60SMark Johnston 		ma[0]->oflags |= VPO_SWAPSLEEP;
136283c9dea1SGleb Smirnoff 		VM_CNT_INC(v_intrans);
1363cf27e0d1SJeff Roberson 		if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1364c7aebda8SAttilio Rao 		    "swread", hz * 20)) {
13659bd86a98SBruce M Simpson 			printf(
1366c5690651SPoul-Henning Kamp "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1367c5690651SPoul-Henning Kamp 			    bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
13681c7c3c6aSMatthew Dillon 		}
13691b119d9dSDavid Greenman 	}
1370d6e13f3bSJeff Roberson 	VM_OBJECT_WUNLOCK(object);
137126f9a767SRodney W. Grimes 
137226f9a767SRodney W. Grimes 	/*
1373b0cd2017SGleb Smirnoff 	 * If we had an unrecoverable read error pages will not be valid.
137426f9a767SRodney W. Grimes 	 */
1375915d1b71SMark Johnston 	for (i = 0; i < reqcount; i++)
13763f060b60SMark Johnston 		if (ma[i]->valid != VM_PAGE_BITS_ALL)
13771c7c3c6aSMatthew Dillon 			return (VM_PAGER_ERROR);
1378b0cd2017SGleb Smirnoff 
13791c7c3c6aSMatthew Dillon 	return (VM_PAGER_OK);
13801c7c3c6aSMatthew Dillon 
13811c7c3c6aSMatthew Dillon 	/*
13821c7c3c6aSMatthew Dillon 	 * A final note: in a low swap situation, we cannot deallocate swap
13831c7c3c6aSMatthew Dillon 	 * and mark a page dirty here because the caller is likely to mark
13841c7c3c6aSMatthew Dillon 	 * the page clean when we return, causing the page to possibly revert
13851c7c3c6aSMatthew Dillon 	 * to all-zero's later.
13861c7c3c6aSMatthew Dillon 	 */
1387df8bae1dSRodney W. Grimes }
1388df8bae1dSRodney W. Grimes 
1389c90d075bSMark Johnston static int
1390c90d075bSMark Johnston swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count,
1391c90d075bSMark Johnston     int *rbehind, int *rahead)
1392c90d075bSMark Johnston {
1393c90d075bSMark Johnston 
1394c90d075bSMark Johnston 	VM_OBJECT_WLOCK(object);
1395c90d075bSMark Johnston 	return (swap_pager_getpages_locked(object, ma, count, rbehind, rahead));
1396c90d075bSMark Johnston }
1397c90d075bSMark Johnston 
13981c7c3c6aSMatthew Dillon /*
139990effb23SGleb Smirnoff  * 	swap_pager_getpages_async():
140090effb23SGleb Smirnoff  *
140190effb23SGleb Smirnoff  *	Right now this is emulation of asynchronous operation on top of
140290effb23SGleb Smirnoff  *	swap_pager_getpages().
140390effb23SGleb Smirnoff  */
140490effb23SGleb Smirnoff static int
14053f060b60SMark Johnston swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1406b0cd2017SGleb Smirnoff     int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
140790effb23SGleb Smirnoff {
140890effb23SGleb Smirnoff 	int r, error;
140990effb23SGleb Smirnoff 
14103f060b60SMark Johnston 	r = swap_pager_getpages(object, ma, count, rbehind, rahead);
141190effb23SGleb Smirnoff 	switch (r) {
141290effb23SGleb Smirnoff 	case VM_PAGER_OK:
141390effb23SGleb Smirnoff 		error = 0;
141490effb23SGleb Smirnoff 		break;
141590effb23SGleb Smirnoff 	case VM_PAGER_ERROR:
141690effb23SGleb Smirnoff 		error = EIO;
141790effb23SGleb Smirnoff 		break;
141890effb23SGleb Smirnoff 	case VM_PAGER_FAIL:
141990effb23SGleb Smirnoff 		error = EINVAL;
142090effb23SGleb Smirnoff 		break;
142190effb23SGleb Smirnoff 	default:
1422d9328101SGleb Smirnoff 		panic("unhandled swap_pager_getpages() error %d", r);
142390effb23SGleb Smirnoff 	}
14243f060b60SMark Johnston 	(iodone)(arg, ma, count, error);
142590effb23SGleb Smirnoff 
142690effb23SGleb Smirnoff 	return (r);
142790effb23SGleb Smirnoff }
142890effb23SGleb Smirnoff 
142990effb23SGleb Smirnoff /*
14301c7c3c6aSMatthew Dillon  *	swap_pager_putpages:
14311c7c3c6aSMatthew Dillon  *
14321c7c3c6aSMatthew Dillon  *	Assign swap (if necessary) and initiate I/O on the specified pages.
14331c7c3c6aSMatthew Dillon  *
14341c7c3c6aSMatthew Dillon  *	We support both OBJT_DEFAULT and OBJT_SWAP objects.  DEFAULT objects
14351c7c3c6aSMatthew Dillon  *	are automatically converted to SWAP objects.
14361c7c3c6aSMatthew Dillon  *
1437ea3aecf5SPeter Wemm  *	In a low memory situation we may block in VOP_STRATEGY(), but the new
14381c7c3c6aSMatthew Dillon  *	vm_page reservation system coupled with properly written VFS devices
14391c7c3c6aSMatthew Dillon  *	should ensure that no low-memory deadlock occurs.  This is an area
14401c7c3c6aSMatthew Dillon  *	which needs work.
14411c7c3c6aSMatthew Dillon  *
14421c7c3c6aSMatthew Dillon  *	The parent has N vm_object_pip_add() references prior to
14431c7c3c6aSMatthew Dillon  *	calling us and will remove references for rtvals[] that are
14441c7c3c6aSMatthew Dillon  *	not set to VM_PAGER_PEND.  We need to remove the rest on I/O
14451c7c3c6aSMatthew Dillon  *	completion.
14461c7c3c6aSMatthew Dillon  *
14471c7c3c6aSMatthew Dillon  *	The parent has soft-busy'd the pages it passes us and will unbusy
144823612f0dSDoug Moore  *	those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
14491c7c3c6aSMatthew Dillon  *	We need to unbusy the rest on I/O completion.
14501c7c3c6aSMatthew Dillon  */
1451d635a37fSWarner Losh static void
14523f060b60SMark Johnston swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1453e065e87cSKonstantin Belousov     int flags, int *rtvals)
1454df8bae1dSRodney W. Grimes {
145523612f0dSDoug Moore 	struct buf *bp;
145623612f0dSDoug Moore 	daddr_t addr, blk, n_free, s_free;
145723612f0dSDoug Moore 	vm_page_t mreq;
145823612f0dSDoug Moore 	int i, j, n;
145923612f0dSDoug Moore 	bool async;
1460df8bae1dSRodney W. Grimes 
146123612f0dSDoug Moore 	KASSERT(count == 0 || ma[0]->object == object,
146223612f0dSDoug Moore 	    ("%s: object mismatch %p/%p",
146323612f0dSDoug Moore 	    __func__, object, ma[0]->object));
1464ee3dc7d7SAlan Cox 
14651c7c3c6aSMatthew Dillon 	/*
14661c7c3c6aSMatthew Dillon 	 * Step 1
14671c7c3c6aSMatthew Dillon 	 *
146823612f0dSDoug Moore 	 * Turn object into OBJT_SWAP.  Force sync if not a pageout process.
14691c7c3c6aSMatthew Dillon 	 */
147078f1deefSAlan Cox 	if (object->type != OBJT_SWAP) {
147178f1deefSAlan Cox 		addr = swp_pager_meta_build(object, 0, SWAPBLK_NONE);
147278f1deefSAlan Cox 		KASSERT(addr == SWAPBLK_NONE,
147378f1deefSAlan Cox 		    ("unexpected object swap block"));
147478f1deefSAlan Cox 	}
147589f6b863SAttilio Rao 	VM_OBJECT_WUNLOCK(object);
147623612f0dSDoug Moore 	async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
147723612f0dSDoug Moore 	swp_pager_init_freerange(&s_free, &n_free);
147826f9a767SRodney W. Grimes 
14791c7c3c6aSMatthew Dillon 	/*
14801c7c3c6aSMatthew Dillon 	 * Step 2
14811c7c3c6aSMatthew Dillon 	 *
14821c7c3c6aSMatthew Dillon 	 * Assign swap blocks and issue I/O.  We reallocate swap on the fly.
14831c7c3c6aSMatthew Dillon 	 * The page is left dirty until the pageout operation completes
14841c7c3c6aSMatthew Dillon 	 * successfully.
14851c7c3c6aSMatthew Dillon 	 */
14861c7c3c6aSMatthew Dillon 	for (i = 0; i < count; i += n) {
148731c82722SDoug Moore 		/* Maximum I/O size is limited by maximum swap block size. */
148831c82722SDoug Moore 		n = min(count - i, nsw_cluster_max);
14891c7c3c6aSMatthew Dillon 
149023612f0dSDoug Moore 		if (async) {
1491756a5412SGleb Smirnoff 			mtx_lock(&swbuf_mtx);
1492756a5412SGleb Smirnoff 			while (nsw_wcount_async == 0)
1493756a5412SGleb Smirnoff 				msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1494756a5412SGleb Smirnoff 				    "swbufa", 0);
1495756a5412SGleb Smirnoff 			nsw_wcount_async--;
1496756a5412SGleb Smirnoff 			mtx_unlock(&swbuf_mtx);
1497327f4e83SMatthew Dillon 		}
1498725b4ff0SMark Johnston 
1499725b4ff0SMark Johnston 		/* Get a block of swap of size up to size n. */
1500725b4ff0SMark Johnston 		VM_OBJECT_WLOCK(object);
150136b01270SDoug Moore 		blk = swp_pager_getswapspace(&n);
1502725b4ff0SMark Johnston 		if (blk == SWAPBLK_NONE) {
1503725b4ff0SMark Johnston 			VM_OBJECT_WUNLOCK(object);
1504725b4ff0SMark Johnston 			mtx_lock(&swbuf_mtx);
1505725b4ff0SMark Johnston 			if (++nsw_wcount_async == 1)
1506725b4ff0SMark Johnston 				wakeup(&nsw_wcount_async);
1507725b4ff0SMark Johnston 			mtx_unlock(&swbuf_mtx);
1508725b4ff0SMark Johnston 			for (j = 0; j < n; ++j)
1509725b4ff0SMark Johnston 				rtvals[i + j] = VM_PAGER_FAIL;
1510725b4ff0SMark Johnston 			continue;
1511725b4ff0SMark Johnston 		}
1512725b4ff0SMark Johnston 		for (j = 0; j < n; ++j) {
1513725b4ff0SMark Johnston 			mreq = ma[i + j];
1514725b4ff0SMark Johnston 			vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1515725b4ff0SMark Johnston 			addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1516725b4ff0SMark Johnston 			    blk + j);
1517725b4ff0SMark Johnston 			if (addr != SWAPBLK_NONE)
1518725b4ff0SMark Johnston 				swp_pager_update_freerange(&s_free, &n_free,
1519725b4ff0SMark Johnston 				    addr);
1520725b4ff0SMark Johnston 			MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1521725b4ff0SMark Johnston 			mreq->oflags |= VPO_SWAPINPROG;
1522725b4ff0SMark Johnston 		}
1523725b4ff0SMark Johnston 		VM_OBJECT_WUNLOCK(object);
1524725b4ff0SMark Johnston 
1525756a5412SGleb Smirnoff 		bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1526cd853791SKonstantin Belousov 		MPASS((bp->b_flags & B_MAXPHYS) != 0);
152723612f0dSDoug Moore 		if (async)
1528cd853791SKonstantin Belousov 			bp->b_flags |= B_ASYNC;
15295e04322aSPoul-Henning Kamp 		bp->b_flags |= B_PAGING;
1530912e4ae9SPoul-Henning Kamp 		bp->b_iocmd = BIO_WRITE;
153126f9a767SRodney W. Grimes 
1532fdcc1cc0SJohn Baldwin 		bp->b_rcred = crhold(thread0.td_ucred);
1533fdcc1cc0SJohn Baldwin 		bp->b_wcred = crhold(thread0.td_ucred);
15341c7c3c6aSMatthew Dillon 		bp->b_bcount = PAGE_SIZE * n;
15351c7c3c6aSMatthew Dillon 		bp->b_bufsize = PAGE_SIZE * n;
15361c7c3c6aSMatthew Dillon 		bp->b_blkno = blk;
1537725b4ff0SMark Johnston 		for (j = 0; j < n; j++)
1538725b4ff0SMark Johnston 			bp->b_pages[j] = ma[i + j];
15391c7c3c6aSMatthew Dillon 		bp->b_npages = n;
1540725b4ff0SMark Johnston 
1541a5296b05SJulian Elischer 		/*
1542a5296b05SJulian Elischer 		 * Must set dirty range for NFS to work.
1543a5296b05SJulian Elischer 		 */
1544a5296b05SJulian Elischer 		bp->b_dirtyoff = 0;
1545a5296b05SJulian Elischer 		bp->b_dirtyend = bp->b_bcount;
15461c7c3c6aSMatthew Dillon 
154783c9dea1SGleb Smirnoff 		VM_CNT_INC(v_swapout);
154883c9dea1SGleb Smirnoff 		VM_CNT_ADD(v_swappgsout, bp->b_npages);
154926f9a767SRodney W. Grimes 
155026f9a767SRodney W. Grimes 		/*
155177923df2SAlan Cox 		 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
155277923df2SAlan Cox 		 * can call the async completion routine at the end of a
155377923df2SAlan Cox 		 * synchronous I/O operation.  Otherwise, our caller would
155477923df2SAlan Cox 		 * perform duplicate unbusy and wakeup operations on the page
155577923df2SAlan Cox 		 * and object, respectively.
155677923df2SAlan Cox 		 */
155777923df2SAlan Cox 		for (j = 0; j < n; j++)
155877923df2SAlan Cox 			rtvals[i + j] = VM_PAGER_PEND;
155977923df2SAlan Cox 
156077923df2SAlan Cox 		/*
15611c7c3c6aSMatthew Dillon 		 * asynchronous
15621c7c3c6aSMatthew Dillon 		 *
156323612f0dSDoug Moore 		 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
156426f9a767SRodney W. Grimes 		 */
156523612f0dSDoug Moore 		if (async) {
15661c7c3c6aSMatthew Dillon 			bp->b_iodone = swp_pager_async_iodone;
156767812eacSKirk McKusick 			BUF_KERNPROC(bp);
15684b03903aSPoul-Henning Kamp 			swp_pager_strategy(bp);
15691c7c3c6aSMatthew Dillon 			continue;
157026f9a767SRodney W. Grimes 		}
1571e47ed70bSJohn Dyson 
157226f9a767SRodney W. Grimes 		/*
15731c7c3c6aSMatthew Dillon 		 * synchronous
15741c7c3c6aSMatthew Dillon 		 *
157523612f0dSDoug Moore 		 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
15761c7c3c6aSMatthew Dillon 		 */
15772c840b1fSAlan Cox 		bp->b_iodone = bdone;
15784b03903aSPoul-Henning Kamp 		swp_pager_strategy(bp);
15791c7c3c6aSMatthew Dillon 
15801c7c3c6aSMatthew Dillon 		/*
158177923df2SAlan Cox 		 * Wait for the sync I/O to complete.
158226f9a767SRodney W. Grimes 		 */
15832c840b1fSAlan Cox 		bwait(bp, PVM, "swwrt");
158477923df2SAlan Cox 
15851c7c3c6aSMatthew Dillon 		/*
15861c7c3c6aSMatthew Dillon 		 * Now that we are through with the bp, we can call the
15871c7c3c6aSMatthew Dillon 		 * normal async completion, which frees everything up.
15881c7c3c6aSMatthew Dillon 		 */
15891c7c3c6aSMatthew Dillon 		swp_pager_async_iodone(bp);
15901c7c3c6aSMatthew Dillon 	}
159178f1deefSAlan Cox 	swp_pager_freeswapspace(s_free, n_free);
159223612f0dSDoug Moore 	VM_OBJECT_WLOCK(object);
15931c7c3c6aSMatthew Dillon }
15941c7c3c6aSMatthew Dillon 
15951c7c3c6aSMatthew Dillon /*
15961c7c3c6aSMatthew Dillon  *	swp_pager_async_iodone:
15971c7c3c6aSMatthew Dillon  *
15981c7c3c6aSMatthew Dillon  *	Completion routine for asynchronous reads and writes from/to swap.
15991c7c3c6aSMatthew Dillon  *	Also called manually by synchronous code to finish up a bp.
16001c7c3c6aSMatthew Dillon  *
160115523cf7SKonstantin Belousov  *	This routine may not sleep.
16021c7c3c6aSMatthew Dillon  */
16031c7c3c6aSMatthew Dillon static void
16042f249180SPoul-Henning Kamp swp_pager_async_iodone(struct buf *bp)
16051c7c3c6aSMatthew Dillon {
16061c7c3c6aSMatthew Dillon 	int i;
16071c7c3c6aSMatthew Dillon 	vm_object_t object = NULL;
16081c7c3c6aSMatthew Dillon 
16091c7c3c6aSMatthew Dillon 	/*
16100b208315SEdward Tomasz Napierala 	 * Report error - unless we ran out of memory, in which case
16110b208315SEdward Tomasz Napierala 	 * we've already logged it in swapgeom_strategy().
16121c7c3c6aSMatthew Dillon 	 */
16130b208315SEdward Tomasz Napierala 	if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
16141c7c3c6aSMatthew Dillon 		printf(
16151c7c3c6aSMatthew Dillon 		    "swap_pager: I/O error - %s failed; blkno %ld,"
16161c7c3c6aSMatthew Dillon 			"size %ld, error %d\n",
161721144e3bSPoul-Henning Kamp 		    ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
16181c7c3c6aSMatthew Dillon 		    (long)bp->b_blkno,
16191c7c3c6aSMatthew Dillon 		    (long)bp->b_bcount,
16201c7c3c6aSMatthew Dillon 		    bp->b_error
16211c7c3c6aSMatthew Dillon 		);
16221c7c3c6aSMatthew Dillon 	}
16231c7c3c6aSMatthew Dillon 
16241c7c3c6aSMatthew Dillon 	/*
162526f9a767SRodney W. Grimes 	 * remove the mapping for kernel virtual
162626f9a767SRodney W. Grimes 	 */
1627fade8dd7SJeff Roberson 	if (buf_mapped(bp))
16281c7c3c6aSMatthew Dillon 		pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1629fade8dd7SJeff Roberson 	else
1630fade8dd7SJeff Roberson 		bp->b_data = bp->b_kvabase;
163126f9a767SRodney W. Grimes 
163233a609ecSAlan Cox 	if (bp->b_npages) {
163333a609ecSAlan Cox 		object = bp->b_pages[0]->object;
163489f6b863SAttilio Rao 		VM_OBJECT_WLOCK(object);
163533a609ecSAlan Cox 	}
16362965a453SKip Macy 
163726f9a767SRodney W. Grimes 	/*
16381c7c3c6aSMatthew Dillon 	 * cleanup pages.  If an error occurs writing to swap, we are in
16391c7c3c6aSMatthew Dillon 	 * very serious trouble.  If it happens to be a disk error, though,
16401c7c3c6aSMatthew Dillon 	 * we may be able to recover by reassigning the swap later on.  So
16411c7c3c6aSMatthew Dillon 	 * in this case we remove the m->swapblk assignment for the page
16421c7c3c6aSMatthew Dillon 	 * but do not free it in the rlist.  The errornous block(s) are thus
16431c7c3c6aSMatthew Dillon 	 * never reallocated as swap.  Redirty the page and continue.
164426f9a767SRodney W. Grimes 	 */
16451c7c3c6aSMatthew Dillon 	for (i = 0; i < bp->b_npages; ++i) {
16461c7c3c6aSMatthew Dillon 		vm_page_t m = bp->b_pages[i];
1647e47ed70bSJohn Dyson 
16485786be7cSAlan Cox 		m->oflags &= ~VPO_SWAPINPROG;
1649c7aebda8SAttilio Rao 		if (m->oflags & VPO_SWAPSLEEP) {
1650c7aebda8SAttilio Rao 			m->oflags &= ~VPO_SWAPSLEEP;
1651cf27e0d1SJeff Roberson 			wakeup(&object->handle);
1652c7aebda8SAttilio Rao 		}
1653e47ed70bSJohn Dyson 
1654a8081778SJeff Roberson 		/* We always have space after I/O, successful or not. */
1655a8081778SJeff Roberson 		vm_page_aflag_set(m, PGA_SWAP_SPACE);
1656a8081778SJeff Roberson 
1657c244d2deSPoul-Henning Kamp 		if (bp->b_ioflags & BIO_ERROR) {
1658ffc82b0aSJohn Dyson 			/*
16591c7c3c6aSMatthew Dillon 			 * If an error occurs I'd love to throw the swapblk
16601c7c3c6aSMatthew Dillon 			 * away without freeing it back to swapspace, so it
16611c7c3c6aSMatthew Dillon 			 * can never be used again.  But I can't from an
16621c7c3c6aSMatthew Dillon 			 * interrupt.
1663ffc82b0aSJohn Dyson 			 */
166421144e3bSPoul-Henning Kamp 			if (bp->b_iocmd == BIO_READ) {
16651c7c3c6aSMatthew Dillon 				/*
16661c7c3c6aSMatthew Dillon 				 * NOTE: for reads, m->dirty will probably
1667956f3135SPhilippe Charnier 				 * be overridden by the original caller of
16681c7c3c6aSMatthew Dillon 				 * getpages so don't play cute tricks here.
16691c7c3c6aSMatthew Dillon 				 */
16700012f373SJeff Roberson 				vm_page_invalid(m);
16711c7c3c6aSMatthew Dillon 			} else {
16721c7c3c6aSMatthew Dillon 				/*
16731c7c3c6aSMatthew Dillon 				 * If a write error occurs, reactivate page
16741c7c3c6aSMatthew Dillon 				 * so it doesn't clog the inactive list,
16751c7c3c6aSMatthew Dillon 				 * then finish the I/O.
16761c7c3c6aSMatthew Dillon 				 */
167741e5a226SAlan Cox 				MPASS(m->dirty == VM_PAGE_BITS_ALL);
16789f5632e6SMark Johnston 
1679a8081778SJeff Roberson 				/* PQ_UNSWAPPABLE? */
16801c7c3c6aSMatthew Dillon 				vm_page_activate(m);
1681c7aebda8SAttilio Rao 				vm_page_sunbusy(m);
16821c7c3c6aSMatthew Dillon 			}
168321144e3bSPoul-Henning Kamp 		} else if (bp->b_iocmd == BIO_READ) {
16841c7c3c6aSMatthew Dillon 			/*
16851c7c3c6aSMatthew Dillon 			 * NOTE: for reads, m->dirty will probably be
1686956f3135SPhilippe Charnier 			 * overridden by the original caller of getpages so
16871c7c3c6aSMatthew Dillon 			 * we cannot set them in order to free the underlying
16881c7c3c6aSMatthew Dillon 			 * swap in a low-swap situation.  I don't think we'd
16891c7c3c6aSMatthew Dillon 			 * want to do that anyway, but it was an optimization
16901c7c3c6aSMatthew Dillon 			 * that existed in the old swapper for a time before
16911c7c3c6aSMatthew Dillon 			 * it got ripped out due to precisely this problem.
16921c7c3c6aSMatthew Dillon 			 */
1693016a3c93SAlan Cox 			KASSERT(!pmap_page_is_mapped(m),
1694016a3c93SAlan Cox 			    ("swp_pager_async_iodone: page %p is mapped", m));
1695016a3c93SAlan Cox 			KASSERT(m->dirty == 0,
1696016a3c93SAlan Cox 			    ("swp_pager_async_iodone: page %p is dirty", m));
1697915d1b71SMark Johnston 
16980012f373SJeff Roberson 			vm_page_valid(m);
1699915d1b71SMark Johnston 			if (i < bp->b_pgbefore ||
1700915d1b71SMark Johnston 			    i >= bp->b_npages - bp->b_pgafter)
1701915d1b71SMark Johnston 				vm_page_readahead_finish(m);
17021c7c3c6aSMatthew Dillon 		} else {
17031c7c3c6aSMatthew Dillon 			/*
1704016a3c93SAlan Cox 			 * For write success, clear the dirty
17051c7c3c6aSMatthew Dillon 			 * status, then finish the I/O ( which decrements the
17061c7c3c6aSMatthew Dillon 			 * busy count and possibly wakes waiter's up ).
1707ebcddc72SAlan Cox 			 * A page is only written to swap after a period of
1708ebcddc72SAlan Cox 			 * inactivity.  Therefore, we do not expect it to be
1709ebcddc72SAlan Cox 			 * reused.
17101c7c3c6aSMatthew Dillon 			 */
17116031c68dSAlan Cox 			KASSERT(!pmap_page_is_write_mapped(m),
1712016a3c93SAlan Cox 			    ("swp_pager_async_iodone: page %p is not write"
1713016a3c93SAlan Cox 			    " protected", m));
1714c52e7044SAlan Cox 			vm_page_undirty(m);
1715ebcddc72SAlan Cox 			vm_page_deactivate_noreuse(m);
1716ebcddc72SAlan Cox 			vm_page_sunbusy(m);
17173c4a2440SAlan Cox 		}
17183c4a2440SAlan Cox 	}
171926f9a767SRodney W. Grimes 
17201c7c3c6aSMatthew Dillon 	/*
17211c7c3c6aSMatthew Dillon 	 * adjust pip.  NOTE: the original parent may still have its own
17221c7c3c6aSMatthew Dillon 	 * pip refs on the object.
17231c7c3c6aSMatthew Dillon 	 */
17240d420ad3SAlan Cox 	if (object != NULL) {
17251c7c3c6aSMatthew Dillon 		vm_object_pip_wakeupn(object, bp->b_npages);
172689f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
17270d420ad3SAlan Cox 	}
172826f9a767SRodney W. Grimes 
17291c7c3c6aSMatthew Dillon 	/*
1730100650deSOlivier Houchard 	 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1731100650deSOlivier Houchard 	 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1732100650deSOlivier Houchard 	 * trigger a KASSERT in relpbuf().
1733100650deSOlivier Houchard 	 */
1734100650deSOlivier Houchard 	if (bp->b_vp) {
1735100650deSOlivier Houchard 		    bp->b_vp = NULL;
1736100650deSOlivier Houchard 		    bp->b_bufobj = NULL;
1737100650deSOlivier Houchard 	}
1738100650deSOlivier Houchard 	/*
17391c7c3c6aSMatthew Dillon 	 * release the physical I/O buffer
17401c7c3c6aSMatthew Dillon 	 */
1741756a5412SGleb Smirnoff 	if (bp->b_flags & B_ASYNC) {
1742756a5412SGleb Smirnoff 		mtx_lock(&swbuf_mtx);
1743756a5412SGleb Smirnoff 		if (++nsw_wcount_async == 1)
1744756a5412SGleb Smirnoff 			wakeup(&nsw_wcount_async);
1745756a5412SGleb Smirnoff 		mtx_unlock(&swbuf_mtx);
1746756a5412SGleb Smirnoff 	}
1747756a5412SGleb Smirnoff 	uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
174826f9a767SRodney W. Grimes }
17491c7c3c6aSMatthew Dillon 
1750b1fd102eSMark Johnston int
1751b1fd102eSMark Johnston swap_pager_nswapdev(void)
1752b1fd102eSMark Johnston {
1753b1fd102eSMark Johnston 
1754b1fd102eSMark Johnston 	return (nswapdev);
1755b1fd102eSMark Johnston }
1756b1fd102eSMark Johnston 
17577c022327SDoug Moore static void
17587c022327SDoug Moore swp_pager_force_dirty(vm_page_t m)
17597c022327SDoug Moore {
17607c022327SDoug Moore 
17617c022327SDoug Moore 	vm_page_dirty(m);
176256948d17SDoug Moore 	swap_pager_unswapped(m);
17637c022327SDoug Moore 	vm_page_launder(m);
176492da00bbSMatthew Dillon }
176592da00bbSMatthew Dillon 
1766*ecfbddf0SKonstantin Belousov u_long
1767*ecfbddf0SKonstantin Belousov swap_pager_swapped_pages(vm_object_t object)
1768*ecfbddf0SKonstantin Belousov {
1769*ecfbddf0SKonstantin Belousov 	struct swblk *sb;
1770*ecfbddf0SKonstantin Belousov 	vm_pindex_t pi;
1771*ecfbddf0SKonstantin Belousov 	u_long res;
1772*ecfbddf0SKonstantin Belousov 	int i;
1773*ecfbddf0SKonstantin Belousov 
1774*ecfbddf0SKonstantin Belousov 	VM_OBJECT_ASSERT_LOCKED(object);
1775*ecfbddf0SKonstantin Belousov 	if (object->type != OBJT_SWAP)
1776*ecfbddf0SKonstantin Belousov 		return (0);
1777*ecfbddf0SKonstantin Belousov 
1778*ecfbddf0SKonstantin Belousov 	for (res = 0, pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1779*ecfbddf0SKonstantin Belousov 	    &object->un_pager.swp.swp_blks, pi)) != NULL;
1780*ecfbddf0SKonstantin Belousov 	    pi = sb->p + SWAP_META_PAGES) {
1781*ecfbddf0SKonstantin Belousov 		for (i = 0; i < SWAP_META_PAGES; i++) {
1782*ecfbddf0SKonstantin Belousov 			if (sb->d[i] != SWAPBLK_NONE)
1783*ecfbddf0SKonstantin Belousov 				res++;
1784*ecfbddf0SKonstantin Belousov 		}
1785*ecfbddf0SKonstantin Belousov 	}
1786*ecfbddf0SKonstantin Belousov 	return (res);
1787*ecfbddf0SKonstantin Belousov }
1788*ecfbddf0SKonstantin Belousov 
178992da00bbSMatthew Dillon /*
17907c022327SDoug Moore  *	swap_pager_swapoff_object:
17917c022327SDoug Moore  *
17927c022327SDoug Moore  *	Page in all of the pages that have been paged out for an object
179356948d17SDoug Moore  *	to a swap device.
17947c022327SDoug Moore  */
17957c022327SDoug Moore static void
17967c022327SDoug Moore swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
17977c022327SDoug Moore {
17987c022327SDoug Moore 	struct swblk *sb;
1799c90d075bSMark Johnston 	vm_page_t m;
1800c90d075bSMark Johnston 	vm_pindex_t pi;
1801c90d075bSMark Johnston 	daddr_t blk;
1802c90d075bSMark Johnston 	int i, nv, rahead, rv;
18037c022327SDoug Moore 
18048ecbf14bSDoug Moore 	KASSERT(object->type == OBJT_SWAP,
18058ecbf14bSDoug Moore 	    ("%s: Object not swappable", __func__));
1806c90d075bSMark Johnston 
18077c022327SDoug Moore 	for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
18087c022327SDoug Moore 	    &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1809c90d075bSMark Johnston 		if ((object->flags & OBJ_DEAD) != 0) {
1810c90d075bSMark Johnston 			/*
1811c90d075bSMark Johnston 			 * Make sure that pending writes finish before
1812c90d075bSMark Johnston 			 * returning.
1813c90d075bSMark Johnston 			 */
1814c90d075bSMark Johnston 			vm_object_pip_wait(object, "swpoff");
1815c90d075bSMark Johnston 			swp_pager_meta_free_all(object);
1816c90d075bSMark Johnston 			break;
1817c90d075bSMark Johnston 		}
18187c022327SDoug Moore 		for (i = 0; i < SWAP_META_PAGES; i++) {
181956948d17SDoug Moore 			/*
1820c90d075bSMark Johnston 			 * Count the number of contiguous valid blocks.
182156948d17SDoug Moore 			 */
1822c90d075bSMark Johnston 			for (nv = 0; nv < SWAP_META_PAGES - i; nv++) {
1823c90d075bSMark Johnston 				blk = sb->d[i + nv];
1824c90d075bSMark Johnston 				if (!swp_pager_isondev(blk, sp) ||
1825c90d075bSMark Johnston 				    blk == SWAPBLK_NONE)
1826c90d075bSMark Johnston 					break;
182756948d17SDoug Moore 			}
1828c90d075bSMark Johnston 			if (nv == 0)
18297c022327SDoug Moore 				continue;
183056948d17SDoug Moore 
183156948d17SDoug Moore 			/*
1832c90d075bSMark Johnston 			 * Look for a page corresponding to the first
1833c90d075bSMark Johnston 			 * valid block and ensure that any pending paging
1834c90d075bSMark Johnston 			 * operations on it are complete.  If the page is valid,
1835c90d075bSMark Johnston 			 * mark it dirty and free the swap block.  Try to batch
1836c90d075bSMark Johnston 			 * this operation since it may cause sp to be freed,
1837c90d075bSMark Johnston 			 * meaning that we must restart the scan.  Avoid busying
1838c90d075bSMark Johnston 			 * valid pages since we may block forever on kernel
1839c90d075bSMark Johnston 			 * stack pages.
184056948d17SDoug Moore 			 */
1841c90d075bSMark Johnston 			m = vm_page_lookup(object, sb->p + i);
1842c90d075bSMark Johnston 			if (m == NULL) {
1843c90d075bSMark Johnston 				m = vm_page_alloc(object, sb->p + i,
1844c90d075bSMark Johnston 				    VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
1845c90d075bSMark Johnston 				if (m == NULL)
1846c90d075bSMark Johnston 					break;
1847c90d075bSMark Johnston 			} else {
1848c90d075bSMark Johnston 				if ((m->oflags & VPO_SWAPINPROG) != 0) {
1849c90d075bSMark Johnston 					m->oflags |= VPO_SWAPSLEEP;
1850c90d075bSMark Johnston 					VM_OBJECT_SLEEP(object, &object->handle,
1851c90d075bSMark Johnston 					    PSWP, "swpoff", 0);
1852c90d075bSMark Johnston 					break;
1853c90d075bSMark Johnston 				}
1854c90d075bSMark Johnston 				if (vm_page_all_valid(m)) {
1855c90d075bSMark Johnston 					do {
1856c90d075bSMark Johnston 						swp_pager_force_dirty(m);
1857c90d075bSMark Johnston 					} while (--nv > 0 &&
1858c90d075bSMark Johnston 					    (m = vm_page_next(m)) != NULL &&
1859c90d075bSMark Johnston 					    vm_page_all_valid(m) &&
1860c90d075bSMark Johnston 					    (m->oflags & VPO_SWAPINPROG) == 0);
1861c90d075bSMark Johnston 					break;
1862c90d075bSMark Johnston 				}
1863c90d075bSMark Johnston 				if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL))
1864c90d075bSMark Johnston 					break;
18657c022327SDoug Moore 			}
186656948d17SDoug Moore 
1867c90d075bSMark Johnston 			vm_object_pip_add(object, 1);
1868c90d075bSMark Johnston 			rahead = SWAP_META_PAGES;
1869c90d075bSMark Johnston 			rv = swap_pager_getpages_locked(object, &m, 1, NULL,
1870c90d075bSMark Johnston 			    &rahead);
1871c90d075bSMark Johnston 			if (rv != VM_PAGER_OK)
1872c90d075bSMark Johnston 				panic("%s: read from swap failed: %d",
1873c90d075bSMark Johnston 				    __func__, rv);
1874c90d075bSMark Johnston 			vm_object_pip_wakeupn(object, 1);
1875c90d075bSMark Johnston 			VM_OBJECT_WLOCK(object);
1876c90d075bSMark Johnston 			vm_page_xunbusy(m);
1877c90d075bSMark Johnston 
187856948d17SDoug Moore 			/*
1879c90d075bSMark Johnston 			 * The object lock was dropped so we must restart the
1880c90d075bSMark Johnston 			 * scan of this swap block.  Pages paged in during this
1881c90d075bSMark Johnston 			 * iteration will be marked dirty in a future iteration.
188256948d17SDoug Moore 			 */
188356948d17SDoug Moore 			break;
188456948d17SDoug Moore 		}
188556948d17SDoug Moore 		if (i == SWAP_META_PAGES)
188656948d17SDoug Moore 			pi = sb->p + SWAP_META_PAGES;
188756948d17SDoug Moore 	}
18887c022327SDoug Moore }
18897c022327SDoug Moore 
18907c022327SDoug Moore /*
189192da00bbSMatthew Dillon  *	swap_pager_swapoff:
189292da00bbSMatthew Dillon  *
189392da00bbSMatthew Dillon  *	Page in all of the pages that have been paged out to the
189492da00bbSMatthew Dillon  *	given device.  The corresponding blocks in the bitmap must be
189592da00bbSMatthew Dillon  *	marked as allocated and the device must be flagged SW_CLOSING.
189692da00bbSMatthew Dillon  *	There may be no processes swapped out to the device.
189792da00bbSMatthew Dillon  *
189892da00bbSMatthew Dillon  *	This routine may block.
189992da00bbSMatthew Dillon  */
1900e9c0cc15SPoul-Henning Kamp static void
1901b3fed13eSDavid Schultz swap_pager_swapoff(struct swdevt *sp)
190292da00bbSMatthew Dillon {
1903f425ab8eSKonstantin Belousov 	vm_object_t object;
19047c022327SDoug Moore 	int retries;
190592da00bbSMatthew Dillon 
190604533e1eSKonstantin Belousov 	sx_assert(&swdev_syscall_lock, SA_XLOCKED);
190792da00bbSMatthew Dillon 
19088bc61209SDavid Schultz 	retries = 0;
190992da00bbSMatthew Dillon full_rescan:
1910f425ab8eSKonstantin Belousov 	mtx_lock(&vm_object_list_mtx);
1911f425ab8eSKonstantin Belousov 	TAILQ_FOREACH(object, &vm_object_list, object_list) {
1912f425ab8eSKonstantin Belousov 		if (object->type != OBJT_SWAP)
191398150664SKonstantin Belousov 			continue;
1914f425ab8eSKonstantin Belousov 		mtx_unlock(&vm_object_list_mtx);
191598150664SKonstantin Belousov 		/* Depends on type-stability. */
191698150664SKonstantin Belousov 		VM_OBJECT_WLOCK(object);
1917f425ab8eSKonstantin Belousov 
1918f425ab8eSKonstantin Belousov 		/*
1919f425ab8eSKonstantin Belousov 		 * Dead objects are eventually terminated on their own.
1920f425ab8eSKonstantin Belousov 		 */
1921f425ab8eSKonstantin Belousov 		if ((object->flags & OBJ_DEAD) != 0)
1922f425ab8eSKonstantin Belousov 			goto next_obj;
1923f425ab8eSKonstantin Belousov 
1924f425ab8eSKonstantin Belousov 		/*
1925f425ab8eSKonstantin Belousov 		 * Sync with fences placed after pctrie
1926f425ab8eSKonstantin Belousov 		 * initialization.  We must not access pctrie below
1927f425ab8eSKonstantin Belousov 		 * unless we checked that our object is swap and not
1928f425ab8eSKonstantin Belousov 		 * dead.
1929f425ab8eSKonstantin Belousov 		 */
1930f425ab8eSKonstantin Belousov 		atomic_thread_fence_acq();
1931f425ab8eSKonstantin Belousov 		if (object->type != OBJT_SWAP)
1932f425ab8eSKonstantin Belousov 			goto next_obj;
1933f425ab8eSKonstantin Belousov 
19347c022327SDoug Moore 		swap_pager_swapoff_object(sp, object);
1935f425ab8eSKonstantin Belousov next_obj:
1936f425ab8eSKonstantin Belousov 		VM_OBJECT_WUNLOCK(object);
1937f425ab8eSKonstantin Belousov 		mtx_lock(&vm_object_list_mtx);
193892da00bbSMatthew Dillon 	}
1939f425ab8eSKonstantin Belousov 	mtx_unlock(&vm_object_list_mtx);
1940f425ab8eSKonstantin Belousov 
19418bc61209SDavid Schultz 	if (sp->sw_used) {
194292da00bbSMatthew Dillon 		/*
19438bc61209SDavid Schultz 		 * Objects may be locked or paging to the device being
19448bc61209SDavid Schultz 		 * removed, so we will miss their pages and need to
19458bc61209SDavid Schultz 		 * make another pass.  We have marked this device as
19468bc61209SDavid Schultz 		 * SW_CLOSING, so the activity should finish soon.
194792da00bbSMatthew Dillon 		 */
19488bc61209SDavid Schultz 		retries++;
19498bc61209SDavid Schultz 		if (retries > 100) {
19508bc61209SDavid Schultz 			panic("swapoff: failed to locate %d swap blocks",
19518bc61209SDavid Schultz 			    sp->sw_used);
19528bc61209SDavid Schultz 		}
19534d70511aSJohn Baldwin 		pause("swpoff", hz / 20);
195492da00bbSMatthew Dillon 		goto full_rescan;
195592da00bbSMatthew Dillon 	}
1956b1fd102eSMark Johnston 	EVENTHANDLER_INVOKE(swapoff, sp);
195792da00bbSMatthew Dillon }
195892da00bbSMatthew Dillon 
19591c7c3c6aSMatthew Dillon /************************************************************************
19601c7c3c6aSMatthew Dillon  *				SWAP META DATA 				*
19611c7c3c6aSMatthew Dillon  ************************************************************************
19621c7c3c6aSMatthew Dillon  *
19631c7c3c6aSMatthew Dillon  *	These routines manipulate the swap metadata stored in the
1964cec9f109SDavid E. O'Brien  *	OBJT_SWAP object.
19651c7c3c6aSMatthew Dillon  *
19664dcc5c2dSMatthew Dillon  *	Swap metadata is implemented with a global hash and not directly
19674dcc5c2dSMatthew Dillon  *	linked into the object.  Instead the object simply contains
19684dcc5c2dSMatthew Dillon  *	appropriate tracking counters.
19691c7c3c6aSMatthew Dillon  */
19701c7c3c6aSMatthew Dillon 
19711c7c3c6aSMatthew Dillon /*
1972230869e0SAlan Cox  * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
1973230869e0SAlan Cox  */
1974230869e0SAlan Cox static bool
1975230869e0SAlan Cox swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
1976230869e0SAlan Cox {
1977230869e0SAlan Cox 	int i;
1978230869e0SAlan Cox 
1979230869e0SAlan Cox 	MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
1980230869e0SAlan Cox 	for (i = start; i < limit; i++) {
1981230869e0SAlan Cox 		if (sb->d[i] != SWAPBLK_NONE)
1982230869e0SAlan Cox 			return (false);
1983230869e0SAlan Cox 	}
1984230869e0SAlan Cox 	return (true);
1985230869e0SAlan Cox }
1986230869e0SAlan Cox 
1987230869e0SAlan Cox /*
1988abdab7b6SDoug Moore  * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
1989abdab7b6SDoug Moore  *
1990abdab7b6SDoug Moore  *  Nothing is done if the block is still in use.
1991abdab7b6SDoug Moore  */
1992abdab7b6SDoug Moore static void
1993abdab7b6SDoug Moore swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
1994abdab7b6SDoug Moore {
1995abdab7b6SDoug Moore 
1996abdab7b6SDoug Moore 	if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
1997abdab7b6SDoug Moore 		SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
1998abdab7b6SDoug Moore 		uma_zfree(swblk_zone, sb);
1999abdab7b6SDoug Moore 	}
2000abdab7b6SDoug Moore }
2001abdab7b6SDoug Moore 
2002abdab7b6SDoug Moore /*
20031c7c3c6aSMatthew Dillon  * SWP_PAGER_META_BUILD() -	add swap block to swap meta data for object
20041c7c3c6aSMatthew Dillon  *
20051c7c3c6aSMatthew Dillon  *	We first convert the object to a swap object if it is a default
20061c7c3c6aSMatthew Dillon  *	object.
20071c7c3c6aSMatthew Dillon  *
20081c7c3c6aSMatthew Dillon  *	The specified swapblk is added to the object's swap metadata.  If
20091c7c3c6aSMatthew Dillon  *	the swapblk is not valid, it is freed instead.  Any previously
201078f1deefSAlan Cox  *	assigned swapblk is returned.
20111c7c3c6aSMatthew Dillon  */
201278f1deefSAlan Cox static daddr_t
20132f249180SPoul-Henning Kamp swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
20142f249180SPoul-Henning Kamp {
2015f425ab8eSKonstantin Belousov 	static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
2016eed99cb8SKonstantin Belousov 	struct swblk *sb, *sb1;
2017f425ab8eSKonstantin Belousov 	vm_pindex_t modpi, rdpi;
201878f1deefSAlan Cox 	daddr_t prev_swapblk;
2019f425ab8eSKonstantin Belousov 	int error, i;
20201c7c3c6aSMatthew Dillon 
202189f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
2022f425ab8eSKonstantin Belousov 
20231c7c3c6aSMatthew Dillon 	/*
20241c7c3c6aSMatthew Dillon 	 * Convert default object to swap object if necessary
20251c7c3c6aSMatthew Dillon 	 */
20261c7c3c6aSMatthew Dillon 	if (object->type != OBJT_SWAP) {
2027f425ab8eSKonstantin Belousov 		pctrie_init(&object->un_pager.swp.swp_blks);
2028f425ab8eSKonstantin Belousov 
2029f425ab8eSKonstantin Belousov 		/*
2030f425ab8eSKonstantin Belousov 		 * Ensure that swap_pager_swapoff()'s iteration over
2031f425ab8eSKonstantin Belousov 		 * object_list does not see a garbage pctrie.
2032f425ab8eSKonstantin Belousov 		 */
2033f425ab8eSKonstantin Belousov 		atomic_thread_fence_rel();
2034f425ab8eSKonstantin Belousov 
20351c7c3c6aSMatthew Dillon 		object->type = OBJT_SWAP;
2036fe7bcbafSKyle Evans 		object->un_pager.swp.writemappings = 0;
203767388836SKonstantin Belousov 		KASSERT((object->flags & OBJ_ANON) != 0 ||
203867388836SKonstantin Belousov 		    object->handle == NULL,
203967388836SKonstantin Belousov 		    ("default pager %p with handle %p",
204067388836SKonstantin Belousov 		    object, object->handle));
2041bd228075SAlan Cox 	}
20421c7c3c6aSMatthew Dillon 
2043f425ab8eSKonstantin Belousov 	rdpi = rounddown(pindex, SWAP_META_PAGES);
2044f425ab8eSKonstantin Belousov 	sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
2045f425ab8eSKonstantin Belousov 	if (sb == NULL) {
20461c7c3c6aSMatthew Dillon 		if (swapblk == SWAPBLK_NONE)
204778f1deefSAlan Cox 			return (SWAPBLK_NONE);
2048f425ab8eSKonstantin Belousov 		for (;;) {
2049f425ab8eSKonstantin Belousov 			sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
2050f425ab8eSKonstantin Belousov 			    pageproc ? M_USE_RESERVE : 0));
2051f425ab8eSKonstantin Belousov 			if (sb != NULL) {
2052f425ab8eSKonstantin Belousov 				sb->p = rdpi;
2053f425ab8eSKonstantin Belousov 				for (i = 0; i < SWAP_META_PAGES; i++)
2054f425ab8eSKonstantin Belousov 					sb->d[i] = SWAPBLK_NONE;
2055f425ab8eSKonstantin Belousov 				if (atomic_cmpset_int(&swblk_zone_exhausted,
2056f425ab8eSKonstantin Belousov 				    1, 0))
2057f425ab8eSKonstantin Belousov 					printf("swblk zone ok\n");
2058f425ab8eSKonstantin Belousov 				break;
2059f425ab8eSKonstantin Belousov 			}
206089f6b863SAttilio Rao 			VM_OBJECT_WUNLOCK(object);
2061f425ab8eSKonstantin Belousov 			if (uma_zone_exhausted(swblk_zone)) {
2062f425ab8eSKonstantin Belousov 				if (atomic_cmpset_int(&swblk_zone_exhausted,
2063f425ab8eSKonstantin Belousov 				    0, 1))
2064f425ab8eSKonstantin Belousov 					printf("swap blk zone exhausted, "
20653ff863f1SDag-Erling Smørgrav 					    "increase kern.maxswzone\n");
20662025d69bSKonstantin Belousov 				vm_pageout_oom(VM_OOM_SWAPZ);
2067f425ab8eSKonstantin Belousov 				pause("swzonxb", 10);
20682025d69bSKonstantin Belousov 			} else
20698d6fbbb8SJeff Roberson 				uma_zwait(swblk_zone);
207089f6b863SAttilio Rao 			VM_OBJECT_WLOCK(object);
2071eed99cb8SKonstantin Belousov 			sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2072eed99cb8SKonstantin Belousov 			    rdpi);
2073eed99cb8SKonstantin Belousov 			if (sb != NULL)
2074eed99cb8SKonstantin Belousov 				/*
2075eed99cb8SKonstantin Belousov 				 * Somebody swapped out a nearby page,
2076eed99cb8SKonstantin Belousov 				 * allocating swblk at the rdpi index,
2077eed99cb8SKonstantin Belousov 				 * while we dropped the object lock.
2078eed99cb8SKonstantin Belousov 				 */
2079eed99cb8SKonstantin Belousov 				goto allocated;
20804dcc5c2dSMatthew Dillon 		}
2081f425ab8eSKonstantin Belousov 		for (;;) {
2082f425ab8eSKonstantin Belousov 			error = SWAP_PCTRIE_INSERT(
2083f425ab8eSKonstantin Belousov 			    &object->un_pager.swp.swp_blks, sb);
2084f425ab8eSKonstantin Belousov 			if (error == 0) {
2085f425ab8eSKonstantin Belousov 				if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2086f425ab8eSKonstantin Belousov 				    1, 0))
2087f425ab8eSKonstantin Belousov 					printf("swpctrie zone ok\n");
2088f425ab8eSKonstantin Belousov 				break;
20891c7c3c6aSMatthew Dillon 			}
2090f425ab8eSKonstantin Belousov 			VM_OBJECT_WUNLOCK(object);
2091f425ab8eSKonstantin Belousov 			if (uma_zone_exhausted(swpctrie_zone)) {
2092f425ab8eSKonstantin Belousov 				if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2093f425ab8eSKonstantin Belousov 				    0, 1))
2094f425ab8eSKonstantin Belousov 					printf("swap pctrie zone exhausted, "
2095f425ab8eSKonstantin Belousov 					    "increase kern.maxswzone\n");
2096f425ab8eSKonstantin Belousov 				vm_pageout_oom(VM_OOM_SWAPZ);
2097f425ab8eSKonstantin Belousov 				pause("swzonxp", 10);
2098f425ab8eSKonstantin Belousov 			} else
20998d6fbbb8SJeff Roberson 				uma_zwait(swpctrie_zone);
2100f425ab8eSKonstantin Belousov 			VM_OBJECT_WLOCK(object);
2101eed99cb8SKonstantin Belousov 			sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2102eed99cb8SKonstantin Belousov 			    rdpi);
2103eed99cb8SKonstantin Belousov 			if (sb1 != NULL) {
2104eed99cb8SKonstantin Belousov 				uma_zfree(swblk_zone, sb);
2105eed99cb8SKonstantin Belousov 				sb = sb1;
2106eed99cb8SKonstantin Belousov 				goto allocated;
21071c7c3c6aSMatthew Dillon 			}
2108f425ab8eSKonstantin Belousov 		}
2109eed99cb8SKonstantin Belousov 	}
2110eed99cb8SKonstantin Belousov allocated:
2111f425ab8eSKonstantin Belousov 	MPASS(sb->p == rdpi);
21121c7c3c6aSMatthew Dillon 
2113f425ab8eSKonstantin Belousov 	modpi = pindex % SWAP_META_PAGES;
211478f1deefSAlan Cox 	/* Return prior contents of metadata. */
211578f1deefSAlan Cox 	prev_swapblk = sb->d[modpi];
2116f425ab8eSKonstantin Belousov 	/* Enter block into metadata. */
2117f425ab8eSKonstantin Belousov 	sb->d[modpi] = swapblk;
211885d88d87SKonstantin Belousov 
211985d88d87SKonstantin Belousov 	/*
212085d88d87SKonstantin Belousov 	 * Free the swblk if we end up with the empty page run.
212185d88d87SKonstantin Belousov 	 */
2122abdab7b6SDoug Moore 	if (swapblk == SWAPBLK_NONE)
2123abdab7b6SDoug Moore 		swp_pager_free_empty_swblk(object, sb);
212478f1deefSAlan Cox 	return (prev_swapblk);
212585d88d87SKonstantin Belousov }
21261c7c3c6aSMatthew Dillon 
21271c7c3c6aSMatthew Dillon /*
2128467057fcSDoug Moore  * SWP_PAGER_META_TRANSFER() - free a range of blocks in the srcobject's swap
2129467057fcSDoug Moore  * metadata, or transfer it into dstobject.
2130467057fcSDoug Moore  *
2131467057fcSDoug Moore  *	This routine will free swap metadata structures as they are cleaned
2132467057fcSDoug Moore  *	out.
2133467057fcSDoug Moore  */
2134467057fcSDoug Moore static void
2135467057fcSDoug Moore swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
2136467057fcSDoug Moore     vm_pindex_t pindex, vm_pindex_t count)
2137467057fcSDoug Moore {
2138467057fcSDoug Moore 	struct swblk *sb;
2139467057fcSDoug Moore 	daddr_t n_free, s_free;
2140467057fcSDoug Moore 	vm_pindex_t offset, last;
2141467057fcSDoug Moore 	int i, limit, start;
2142467057fcSDoug Moore 
2143467057fcSDoug Moore 	VM_OBJECT_ASSERT_WLOCKED(srcobject);
2144467057fcSDoug Moore 	if (srcobject->type != OBJT_SWAP || count == 0)
2145467057fcSDoug Moore 		return;
2146467057fcSDoug Moore 
2147467057fcSDoug Moore 	swp_pager_init_freerange(&s_free, &n_free);
2148467057fcSDoug Moore 	offset = pindex;
2149467057fcSDoug Moore 	last = pindex + count;
2150467057fcSDoug Moore 	for (;;) {
2151467057fcSDoug Moore 		sb = SWAP_PCTRIE_LOOKUP_GE(&srcobject->un_pager.swp.swp_blks,
2152467057fcSDoug Moore 		    rounddown(pindex, SWAP_META_PAGES));
2153467057fcSDoug Moore 		if (sb == NULL || sb->p >= last)
2154467057fcSDoug Moore 			break;
2155467057fcSDoug Moore 		start = pindex > sb->p ? pindex - sb->p : 0;
2156467057fcSDoug Moore 		limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2157467057fcSDoug Moore 		    SWAP_META_PAGES;
2158467057fcSDoug Moore 		for (i = start; i < limit; i++) {
2159467057fcSDoug Moore 			if (sb->d[i] == SWAPBLK_NONE)
2160467057fcSDoug Moore 				continue;
2161467057fcSDoug Moore 			if (dstobject == NULL ||
2162467057fcSDoug Moore 			    !swp_pager_xfer_source(srcobject, dstobject,
2163467057fcSDoug Moore 			    sb->p + i - offset, sb->d[i])) {
2164467057fcSDoug Moore 				swp_pager_update_freerange(&s_free, &n_free,
2165467057fcSDoug Moore 				    sb->d[i]);
2166467057fcSDoug Moore 			}
2167467057fcSDoug Moore 			sb->d[i] = SWAPBLK_NONE;
2168467057fcSDoug Moore 		}
2169467057fcSDoug Moore 		pindex = sb->p + SWAP_META_PAGES;
2170467057fcSDoug Moore 		if (swp_pager_swblk_empty(sb, 0, start) &&
2171467057fcSDoug Moore 		    swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2172467057fcSDoug Moore 			SWAP_PCTRIE_REMOVE(&srcobject->un_pager.swp.swp_blks,
2173467057fcSDoug Moore 			    sb->p);
2174467057fcSDoug Moore 			uma_zfree(swblk_zone, sb);
2175467057fcSDoug Moore 		}
2176467057fcSDoug Moore 	}
2177467057fcSDoug Moore 	swp_pager_freeswapspace(s_free, n_free);
2178467057fcSDoug Moore }
2179467057fcSDoug Moore 
2180467057fcSDoug Moore /*
21811c7c3c6aSMatthew Dillon  * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
21821c7c3c6aSMatthew Dillon  *
21831c7c3c6aSMatthew Dillon  *	The requested range of blocks is freed, with any associated swap
21841c7c3c6aSMatthew Dillon  *	returned to the swap bitmap.
21851c7c3c6aSMatthew Dillon  *
21861c7c3c6aSMatthew Dillon  *	This routine will free swap metadata structures as they are cleaned
21871c7c3c6aSMatthew Dillon  *	out.  This routine does *NOT* operate on swap metadata associated
21881c7c3c6aSMatthew Dillon  *	with resident pages.
21891c7c3c6aSMatthew Dillon  */
21901c7c3c6aSMatthew Dillon static void
2191f425ab8eSKonstantin Belousov swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count)
21921c7c3c6aSMatthew Dillon {
2193467057fcSDoug Moore 	swp_pager_meta_transfer(object, NULL, pindex, count);
21941c7c3c6aSMatthew Dillon }
21951c7c3c6aSMatthew Dillon 
21961c7c3c6aSMatthew Dillon /*
21971c7c3c6aSMatthew Dillon  * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
21981c7c3c6aSMatthew Dillon  *
21991c7c3c6aSMatthew Dillon  *	This routine locates and destroys all swap metadata associated with
22001c7c3c6aSMatthew Dillon  *	an object.
22011c7c3c6aSMatthew Dillon  */
22021c7c3c6aSMatthew Dillon static void
22031c7c3c6aSMatthew Dillon swp_pager_meta_free_all(vm_object_t object)
22041c7c3c6aSMatthew Dillon {
2205f425ab8eSKonstantin Belousov 	struct swblk *sb;
220678f1deefSAlan Cox 	daddr_t n_free, s_free;
2207f425ab8eSKonstantin Belousov 	vm_pindex_t pindex;
220871057cd2SKonstantin Belousov 	int i;
22091c7c3c6aSMatthew Dillon 
221089f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
22111c7c3c6aSMatthew Dillon 	if (object->type != OBJT_SWAP)
22121c7c3c6aSMatthew Dillon 		return;
22131c7c3c6aSMatthew Dillon 
221478f1deefSAlan Cox 	swp_pager_init_freerange(&s_free, &n_free);
2215f425ab8eSKonstantin Belousov 	for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
2216f425ab8eSKonstantin Belousov 	    &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
2217f425ab8eSKonstantin Belousov 		pindex = sb->p + SWAP_META_PAGES;
2218f425ab8eSKonstantin Belousov 		for (i = 0; i < SWAP_META_PAGES; i++) {
2219230869e0SAlan Cox 			if (sb->d[i] == SWAPBLK_NONE)
2220230869e0SAlan Cox 				continue;
222178f1deefSAlan Cox 			swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
22221c7c3c6aSMatthew Dillon 		}
2223f425ab8eSKonstantin Belousov 		SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2224f425ab8eSKonstantin Belousov 		uma_zfree(swblk_zone, sb);
22251c7c3c6aSMatthew Dillon 	}
222678f1deefSAlan Cox 	swp_pager_freeswapspace(s_free, n_free);
22271c7c3c6aSMatthew Dillon }
22281c7c3c6aSMatthew Dillon 
22291c7c3c6aSMatthew Dillon /*
22304abca9bbSAlan Cox  * SWP_PAGER_METACTL() -  misc control of swap meta data.
22311c7c3c6aSMatthew Dillon  *
22324abca9bbSAlan Cox  *	This routine is capable of looking up, or removing swapblk
22334abca9bbSAlan Cox  *	assignments in the swap meta data.  It returns the swapblk being
22344abca9bbSAlan Cox  *	looked-up, popped, or SWAPBLK_NONE if the block was invalid.
22351c7c3c6aSMatthew Dillon  *
22361c7c3c6aSMatthew Dillon  *	When acting on a busy resident page and paging is in progress, we
22371c7c3c6aSMatthew Dillon  *	have to wait until paging is complete but otherwise can act on the
22381c7c3c6aSMatthew Dillon  *	busy page.
22391c7c3c6aSMatthew Dillon  */
22401c7c3c6aSMatthew Dillon static daddr_t
22418ecbf14bSDoug Moore swp_pager_meta_lookup(vm_object_t object, vm_pindex_t pindex)
22422f249180SPoul-Henning Kamp {
2243f425ab8eSKonstantin Belousov 	struct swblk *sb;
22444dcc5c2dSMatthew Dillon 
2245c25673ffSAttilio Rao 	VM_OBJECT_ASSERT_LOCKED(object);
2246ee620ea4SAlan Cox 
22471c7c3c6aSMatthew Dillon 	/*
2248ee620ea4SAlan Cox 	 * The meta data only exists if the object is OBJT_SWAP
22491c7c3c6aSMatthew Dillon 	 * and even then might not be allocated yet.
22501c7c3c6aSMatthew Dillon 	 */
22518ecbf14bSDoug Moore 	KASSERT(object->type == OBJT_SWAP,
22528ecbf14bSDoug Moore 	    ("Lookup object not swappable"));
22531c7c3c6aSMatthew Dillon 
2254f425ab8eSKonstantin Belousov 	sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2255f425ab8eSKonstantin Belousov 	    rounddown(pindex, SWAP_META_PAGES));
2256f425ab8eSKonstantin Belousov 	if (sb == NULL)
2257f425ab8eSKonstantin Belousov 		return (SWAPBLK_NONE);
22588ecbf14bSDoug Moore 	return (sb->d[pindex % SWAP_META_PAGES]);
22591c7c3c6aSMatthew Dillon }
22601c7c3c6aSMatthew Dillon 
2261e9c0cc15SPoul-Henning Kamp /*
226277d6fd97SKonstantin Belousov  * Returns the least page index which is greater than or equal to the
226377d6fd97SKonstantin Belousov  * parameter pindex and for which there is a swap block allocated.
226477d6fd97SKonstantin Belousov  * Returns object's size if the object's type is not swap or if there
226577d6fd97SKonstantin Belousov  * are no allocated swap blocks for the object after the requested
226677d6fd97SKonstantin Belousov  * pindex.
226777d6fd97SKonstantin Belousov  */
226877d6fd97SKonstantin Belousov vm_pindex_t
226977d6fd97SKonstantin Belousov swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
227077d6fd97SKonstantin Belousov {
2271f425ab8eSKonstantin Belousov 	struct swblk *sb;
2272f425ab8eSKonstantin Belousov 	int i;
227377d6fd97SKonstantin Belousov 
227477d6fd97SKonstantin Belousov 	VM_OBJECT_ASSERT_LOCKED(object);
2275f425ab8eSKonstantin Belousov 	if (object->type != OBJT_SWAP)
227677d6fd97SKonstantin Belousov 		return (object->size);
227777d6fd97SKonstantin Belousov 
2278f425ab8eSKonstantin Belousov 	sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2279f425ab8eSKonstantin Belousov 	    rounddown(pindex, SWAP_META_PAGES));
2280f425ab8eSKonstantin Belousov 	if (sb == NULL)
2281f425ab8eSKonstantin Belousov 		return (object->size);
2282f425ab8eSKonstantin Belousov 	if (sb->p < pindex) {
2283f425ab8eSKonstantin Belousov 		for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2284f425ab8eSKonstantin Belousov 			if (sb->d[i] != SWAPBLK_NONE)
2285f425ab8eSKonstantin Belousov 				return (sb->p + i);
228677d6fd97SKonstantin Belousov 		}
2287f425ab8eSKonstantin Belousov 		sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2288f425ab8eSKonstantin Belousov 		    roundup(pindex, SWAP_META_PAGES));
2289f425ab8eSKonstantin Belousov 		if (sb == NULL)
2290f425ab8eSKonstantin Belousov 			return (object->size);
229177d6fd97SKonstantin Belousov 	}
2292f425ab8eSKonstantin Belousov 	for (i = 0; i < SWAP_META_PAGES; i++) {
2293f425ab8eSKonstantin Belousov 		if (sb->d[i] != SWAPBLK_NONE)
2294f425ab8eSKonstantin Belousov 			return (sb->p + i);
229577d6fd97SKonstantin Belousov 	}
2296f425ab8eSKonstantin Belousov 
2297f425ab8eSKonstantin Belousov 	/*
2298f425ab8eSKonstantin Belousov 	 * We get here if a swblk is present in the trie but it
2299f425ab8eSKonstantin Belousov 	 * doesn't map any blocks.
2300f425ab8eSKonstantin Belousov 	 */
2301f425ab8eSKonstantin Belousov 	MPASS(0);
2302f425ab8eSKonstantin Belousov 	return (object->size);
230377d6fd97SKonstantin Belousov }
230477d6fd97SKonstantin Belousov 
230577d6fd97SKonstantin Belousov /*
2306e9c0cc15SPoul-Henning Kamp  * System call swapon(name) enables swapping on device name,
2307e9c0cc15SPoul-Henning Kamp  * which must be in the swdevsw.  Return EBUSY
2308e9c0cc15SPoul-Henning Kamp  * if already swapping on this device.
2309e9c0cc15SPoul-Henning Kamp  */
2310e9c0cc15SPoul-Henning Kamp #ifndef _SYS_SYSPROTO_H_
2311e9c0cc15SPoul-Henning Kamp struct swapon_args {
2312e9c0cc15SPoul-Henning Kamp 	char *name;
2313e9c0cc15SPoul-Henning Kamp };
2314e9c0cc15SPoul-Henning Kamp #endif
2315e9c0cc15SPoul-Henning Kamp 
2316e9c0cc15SPoul-Henning Kamp /*
2317e9c0cc15SPoul-Henning Kamp  * MPSAFE
2318e9c0cc15SPoul-Henning Kamp  */
2319e9c0cc15SPoul-Henning Kamp /* ARGSUSED */
2320e9c0cc15SPoul-Henning Kamp int
23218451d0ddSKip Macy sys_swapon(struct thread *td, struct swapon_args *uap)
2322e9c0cc15SPoul-Henning Kamp {
2323e9c0cc15SPoul-Henning Kamp 	struct vattr attr;
2324e9c0cc15SPoul-Henning Kamp 	struct vnode *vp;
2325e9c0cc15SPoul-Henning Kamp 	struct nameidata nd;
2326e9c0cc15SPoul-Henning Kamp 	int error;
2327e9c0cc15SPoul-Henning Kamp 
2328acd3428bSRobert Watson 	error = priv_check(td, PRIV_SWAPON);
2329e9c0cc15SPoul-Henning Kamp 	if (error)
2330acd3428bSRobert Watson 		return (error);
2331e9c0cc15SPoul-Henning Kamp 
233204533e1eSKonstantin Belousov 	sx_xlock(&swdev_syscall_lock);
2333e9c0cc15SPoul-Henning Kamp 
2334e9c0cc15SPoul-Henning Kamp 	/*
2335e9c0cc15SPoul-Henning Kamp 	 * Swap metadata may not fit in the KVM if we have physical
2336e9c0cc15SPoul-Henning Kamp 	 * memory of >1GB.
2337e9c0cc15SPoul-Henning Kamp 	 */
2338f425ab8eSKonstantin Belousov 	if (swblk_zone == NULL) {
2339e9c0cc15SPoul-Henning Kamp 		error = ENOMEM;
2340e9c0cc15SPoul-Henning Kamp 		goto done;
2341e9c0cc15SPoul-Henning Kamp 	}
2342e9c0cc15SPoul-Henning Kamp 
2343d9135e72SRobert Watson 	NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2344d9135e72SRobert Watson 	    uap->name, td);
2345e9c0cc15SPoul-Henning Kamp 	error = namei(&nd);
2346e9c0cc15SPoul-Henning Kamp 	if (error)
2347e9c0cc15SPoul-Henning Kamp 		goto done;
2348e9c0cc15SPoul-Henning Kamp 
2349e9c0cc15SPoul-Henning Kamp 	NDFREE(&nd, NDF_ONLY_PNBUF);
2350e9c0cc15SPoul-Henning Kamp 	vp = nd.ni_vp;
2351e9c0cc15SPoul-Henning Kamp 
23527ad2a82dSMateusz Guzik 	if (vn_isdisk_error(vp, &error)) {
235388ad2d7bSKonstantin Belousov 		error = swapongeom(vp);
235420da9c2eSPoul-Henning Kamp 	} else if (vp->v_type == VREG &&
2355e9c0cc15SPoul-Henning Kamp 	    (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
23560359a12eSAttilio Rao 	    (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2357e9c0cc15SPoul-Henning Kamp 		/*
2358e9c0cc15SPoul-Henning Kamp 		 * Allow direct swapping to NFS regular files in the same
2359e9c0cc15SPoul-Henning Kamp 		 * way that nfs_mountroot() sets up diskless swapping.
2360e9c0cc15SPoul-Henning Kamp 		 */
236159efee01SPoul-Henning Kamp 		error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2362e9c0cc15SPoul-Henning Kamp 	}
2363e9c0cc15SPoul-Henning Kamp 
2364e9c0cc15SPoul-Henning Kamp 	if (error)
2365e9c0cc15SPoul-Henning Kamp 		vrele(vp);
2366e9c0cc15SPoul-Henning Kamp done:
236704533e1eSKonstantin Belousov 	sx_xunlock(&swdev_syscall_lock);
2368e9c0cc15SPoul-Henning Kamp 	return (error);
2369e9c0cc15SPoul-Henning Kamp }
2370e9c0cc15SPoul-Henning Kamp 
23713ff863f1SDag-Erling Smørgrav /*
23723ff863f1SDag-Erling Smørgrav  * Check that the total amount of swap currently configured does not
23733ff863f1SDag-Erling Smørgrav  * exceed half the theoretical maximum.  If it does, print a warning
237435872e79SKonstantin Belousov  * message.
23753ff863f1SDag-Erling Smørgrav  */
237635872e79SKonstantin Belousov static void
237735872e79SKonstantin Belousov swapon_check_swzone(void)
23783ff863f1SDag-Erling Smørgrav {
23793ff863f1SDag-Erling Smørgrav 
23803ff863f1SDag-Erling Smørgrav 	/* recommend using no more than half that amount */
2381303fa05aSKonstantin Belousov 	if (swap_total > swap_maxpages / 2) {
23823ff863f1SDag-Erling Smørgrav 		printf("warning: total configured swap (%lu pages) "
23833ff863f1SDag-Erling Smørgrav 		    "exceeds maximum recommended amount (%lu pages).\n",
2384303fa05aSKonstantin Belousov 		    swap_total, swap_maxpages / 2);
23853ff863f1SDag-Erling Smørgrav 		printf("warning: increase kern.maxswzone "
23863ff863f1SDag-Erling Smørgrav 		    "or reduce amount of swap.\n");
23873ff863f1SDag-Erling Smørgrav 	}
23883ff863f1SDag-Erling Smørgrav }
23893ff863f1SDag-Erling Smørgrav 
239059efee01SPoul-Henning Kamp static void
23912cc718a1SKonstantin Belousov swaponsomething(struct vnode *vp, void *id, u_long nblks,
23922cc718a1SKonstantin Belousov     sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2393e9c0cc15SPoul-Henning Kamp {
23942d9974c1SAlan Cox 	struct swdevt *sp, *tsp;
239534e2051fSMark Johnston 	daddr_t dvbase;
2396e9c0cc15SPoul-Henning Kamp 
2397e9c0cc15SPoul-Henning Kamp 	/*
2398e9c0cc15SPoul-Henning Kamp 	 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2399e9c0cc15SPoul-Henning Kamp 	 * First chop nblks off to page-align it, then convert.
2400e9c0cc15SPoul-Henning Kamp 	 *
2401e9c0cc15SPoul-Henning Kamp 	 * sw->sw_nblks is in page-sized chunks now too.
2402e9c0cc15SPoul-Henning Kamp 	 */
2403e9c0cc15SPoul-Henning Kamp 	nblks &= ~(ctodb(1) - 1);
2404e9c0cc15SPoul-Henning Kamp 	nblks = dbtoc(nblks);
2405e9c0cc15SPoul-Henning Kamp 
24068f60c087SPoul-Henning Kamp 	sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
240700fd73d2SDoug Moore 	sp->sw_blist = blist_create(nblks, M_WAITOK);
2408dee34ca4SPoul-Henning Kamp 	sp->sw_vp = vp;
2409dee34ca4SPoul-Henning Kamp 	sp->sw_id = id;
2410f3732fd1SPoul-Henning Kamp 	sp->sw_dev = dev;
2411e9c0cc15SPoul-Henning Kamp 	sp->sw_nblks = nblks;
2412e9c0cc15SPoul-Henning Kamp 	sp->sw_used = 0;
241359efee01SPoul-Henning Kamp 	sp->sw_strategy = strategy;
2414dee34ca4SPoul-Henning Kamp 	sp->sw_close = close;
24152cc718a1SKonstantin Belousov 	sp->sw_flags = flags;
2416e9c0cc15SPoul-Henning Kamp 
2417e9c0cc15SPoul-Henning Kamp 	/*
2418504f5e29SDoug Moore 	 * Do not free the first blocks in order to avoid overwriting
24198f60c087SPoul-Henning Kamp 	 * any bsd label at the front of the partition
2420e9c0cc15SPoul-Henning Kamp 	 */
2421504f5e29SDoug Moore 	blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2422504f5e29SDoug Moore 	    nblks - howmany(BBSIZE, PAGE_SIZE));
2423e9c0cc15SPoul-Henning Kamp 
24242d9974c1SAlan Cox 	dvbase = 0;
242520da9c2eSPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
24262d9974c1SAlan Cox 	TAILQ_FOREACH(tsp, &swtailq, sw_list) {
24272d9974c1SAlan Cox 		if (tsp->sw_end >= dvbase) {
24282d9974c1SAlan Cox 			/*
24292d9974c1SAlan Cox 			 * We put one uncovered page between the devices
24302d9974c1SAlan Cox 			 * in order to definitively prevent any cross-device
24312d9974c1SAlan Cox 			 * I/O requests
24322d9974c1SAlan Cox 			 */
24332d9974c1SAlan Cox 			dvbase = tsp->sw_end + 1;
24342d9974c1SAlan Cox 		}
24352d9974c1SAlan Cox 	}
24362d9974c1SAlan Cox 	sp->sw_first = dvbase;
24372d9974c1SAlan Cox 	sp->sw_end = dvbase + nblks;
24388f60c087SPoul-Henning Kamp 	TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
24398f60c087SPoul-Henning Kamp 	nswapdev++;
2440504f5e29SDoug Moore 	swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2441e8bb589dSMatt Macy 	swap_total += nblks;
244235872e79SKonstantin Belousov 	swapon_check_swzone();
2443d05bc129SAlan Cox 	swp_sizecheck();
2444d05bc129SAlan Cox 	mtx_unlock(&sw_dev_mtx);
2445b1fd102eSMark Johnston 	EVENTHANDLER_INVOKE(swapon, sp);
244659efee01SPoul-Henning Kamp }
2447e9c0cc15SPoul-Henning Kamp 
2448e9c0cc15SPoul-Henning Kamp /*
2449e9c0cc15SPoul-Henning Kamp  * SYSCALL: swapoff(devname)
2450e9c0cc15SPoul-Henning Kamp  *
2451e9c0cc15SPoul-Henning Kamp  * Disable swapping on the given device.
2452dee34ca4SPoul-Henning Kamp  *
2453dee34ca4SPoul-Henning Kamp  * XXX: Badly designed system call: it should use a device index
2454dee34ca4SPoul-Henning Kamp  * rather than filename as specification.  We keep sw_vp around
2455dee34ca4SPoul-Henning Kamp  * only to make this work.
2456e9c0cc15SPoul-Henning Kamp  */
2457e9c0cc15SPoul-Henning Kamp #ifndef _SYS_SYSPROTO_H_
2458e9c0cc15SPoul-Henning Kamp struct swapoff_args {
2459e9c0cc15SPoul-Henning Kamp 	char *name;
2460e9c0cc15SPoul-Henning Kamp };
2461e9c0cc15SPoul-Henning Kamp #endif
2462e9c0cc15SPoul-Henning Kamp 
2463e9c0cc15SPoul-Henning Kamp /*
2464e9c0cc15SPoul-Henning Kamp  * MPSAFE
2465e9c0cc15SPoul-Henning Kamp  */
2466e9c0cc15SPoul-Henning Kamp /* ARGSUSED */
2467e9c0cc15SPoul-Henning Kamp int
24688451d0ddSKip Macy sys_swapoff(struct thread *td, struct swapoff_args *uap)
2469e9c0cc15SPoul-Henning Kamp {
2470e9c0cc15SPoul-Henning Kamp 	struct vnode *vp;
2471e9c0cc15SPoul-Henning Kamp 	struct nameidata nd;
2472e9c0cc15SPoul-Henning Kamp 	struct swdevt *sp;
24738f60c087SPoul-Henning Kamp 	int error;
2474e9c0cc15SPoul-Henning Kamp 
2475acd3428bSRobert Watson 	error = priv_check(td, PRIV_SWAPOFF);
2476e9c0cc15SPoul-Henning Kamp 	if (error)
24770909f38aSPawel Jakub Dawidek 		return (error);
2478e9c0cc15SPoul-Henning Kamp 
247904533e1eSKonstantin Belousov 	sx_xlock(&swdev_syscall_lock);
2480e9c0cc15SPoul-Henning Kamp 
2481d9135e72SRobert Watson 	NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2482d9135e72SRobert Watson 	    td);
2483e9c0cc15SPoul-Henning Kamp 	error = namei(&nd);
2484e9c0cc15SPoul-Henning Kamp 	if (error)
2485e9c0cc15SPoul-Henning Kamp 		goto done;
2486e9c0cc15SPoul-Henning Kamp 	NDFREE(&nd, NDF_ONLY_PNBUF);
2487e9c0cc15SPoul-Henning Kamp 	vp = nd.ni_vp;
2488e9c0cc15SPoul-Henning Kamp 
248920da9c2eSPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
24908f60c087SPoul-Henning Kamp 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2491dee34ca4SPoul-Henning Kamp 		if (sp->sw_vp == vp)
24920909f38aSPawel Jakub Dawidek 			break;
2493e9c0cc15SPoul-Henning Kamp 	}
249420da9c2eSPoul-Henning Kamp 	mtx_unlock(&sw_dev_mtx);
24950909f38aSPawel Jakub Dawidek 	if (sp == NULL) {
2496e9c0cc15SPoul-Henning Kamp 		error = EINVAL;
2497e9c0cc15SPoul-Henning Kamp 		goto done;
24980909f38aSPawel Jakub Dawidek 	}
249935918c55SChristian S.J. Peron 	error = swapoff_one(sp, td->td_ucred);
25000909f38aSPawel Jakub Dawidek done:
250104533e1eSKonstantin Belousov 	sx_xunlock(&swdev_syscall_lock);
25020909f38aSPawel Jakub Dawidek 	return (error);
25030909f38aSPawel Jakub Dawidek }
25040909f38aSPawel Jakub Dawidek 
25050909f38aSPawel Jakub Dawidek static int
250635918c55SChristian S.J. Peron swapoff_one(struct swdevt *sp, struct ucred *cred)
25070909f38aSPawel Jakub Dawidek {
250803bdd65fSAlan Cox 	u_long nblks;
2509e9c0cc15SPoul-Henning Kamp #ifdef MAC
25100909f38aSPawel Jakub Dawidek 	int error;
2511e9c0cc15SPoul-Henning Kamp #endif
2512e9c0cc15SPoul-Henning Kamp 
251304533e1eSKonstantin Belousov 	sx_assert(&swdev_syscall_lock, SA_XLOCKED);
25140909f38aSPawel Jakub Dawidek #ifdef MAC
2515cb05b60aSAttilio Rao 	(void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
251635918c55SChristian S.J. Peron 	error = mac_system_check_swapoff(cred, sp->sw_vp);
2517b249ce48SMateusz Guzik 	(void) VOP_UNLOCK(sp->sw_vp);
25180909f38aSPawel Jakub Dawidek 	if (error != 0)
25190909f38aSPawel Jakub Dawidek 		return (error);
25200909f38aSPawel Jakub Dawidek #endif
2521e9c0cc15SPoul-Henning Kamp 	nblks = sp->sw_nblks;
2522e9c0cc15SPoul-Henning Kamp 
2523e9c0cc15SPoul-Henning Kamp 	/*
2524e9c0cc15SPoul-Henning Kamp 	 * We can turn off this swap device safely only if the
2525e9c0cc15SPoul-Henning Kamp 	 * available virtual memory in the system will fit the amount
2526e9c0cc15SPoul-Henning Kamp 	 * of data we will have to page back in, plus an epsilon so
2527e9c0cc15SPoul-Henning Kamp 	 * the system doesn't become critically low on swap space.
2528e9c0cc15SPoul-Henning Kamp 	 */
2529e2068d0bSJeff Roberson 	if (vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
25300909f38aSPawel Jakub Dawidek 		return (ENOMEM);
2531e9c0cc15SPoul-Henning Kamp 
2532e9c0cc15SPoul-Henning Kamp 	/*
2533e9c0cc15SPoul-Henning Kamp 	 * Prevent further allocations on this device.
2534e9c0cc15SPoul-Henning Kamp 	 */
25352928cef7SAlan Cox 	mtx_lock(&sw_dev_mtx);
2536e9c0cc15SPoul-Henning Kamp 	sp->sw_flags |= SW_CLOSING;
253703bdd65fSAlan Cox 	swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2538e8bb589dSMatt Macy 	swap_total -= nblks;
25392928cef7SAlan Cox 	mtx_unlock(&sw_dev_mtx);
2540e9c0cc15SPoul-Henning Kamp 
2541e9c0cc15SPoul-Henning Kamp 	/*
2542e9c0cc15SPoul-Henning Kamp 	 * Page in the contents of the device and close it.
2543e9c0cc15SPoul-Henning Kamp 	 */
2544b3fed13eSDavid Schultz 	swap_pager_swapoff(sp);
2545e9c0cc15SPoul-Henning Kamp 
254635918c55SChristian S.J. Peron 	sp->sw_close(curthread, sp);
254720da9c2eSPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
25489e3e3fe5SWarner Losh 	sp->sw_id = NULL;
25498f60c087SPoul-Henning Kamp 	TAILQ_REMOVE(&swtailq, sp, sw_list);
25500676a140SAlan Cox 	nswapdev--;
25517dea2c2eSAlan Cox 	if (nswapdev == 0) {
25527dea2c2eSAlan Cox 		swap_pager_full = 2;
25537dea2c2eSAlan Cox 		swap_pager_almost_full = 1;
25547dea2c2eSAlan Cox 	}
25558f60c087SPoul-Henning Kamp 	if (swdevhd == sp)
25568f60c087SPoul-Henning Kamp 		swdevhd = NULL;
2557d05bc129SAlan Cox 	mtx_unlock(&sw_dev_mtx);
25588f60c087SPoul-Henning Kamp 	blist_destroy(sp->sw_blist);
25598f60c087SPoul-Henning Kamp 	free(sp, M_VMPGDATA);
25600909f38aSPawel Jakub Dawidek 	return (0);
25610909f38aSPawel Jakub Dawidek }
2562e9c0cc15SPoul-Henning Kamp 
25630909f38aSPawel Jakub Dawidek void
25640909f38aSPawel Jakub Dawidek swapoff_all(void)
25650909f38aSPawel Jakub Dawidek {
25660909f38aSPawel Jakub Dawidek 	struct swdevt *sp, *spt;
25670909f38aSPawel Jakub Dawidek 	const char *devname;
25680909f38aSPawel Jakub Dawidek 	int error;
25690909f38aSPawel Jakub Dawidek 
257004533e1eSKonstantin Belousov 	sx_xlock(&swdev_syscall_lock);
25710909f38aSPawel Jakub Dawidek 
25720909f38aSPawel Jakub Dawidek 	mtx_lock(&sw_dev_mtx);
25730909f38aSPawel Jakub Dawidek 	TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
25740909f38aSPawel Jakub Dawidek 		mtx_unlock(&sw_dev_mtx);
25757ad2a82dSMateusz Guzik 		if (vn_isdisk(sp->sw_vp))
25767870adb6SEd Schouten 			devname = devtoname(sp->sw_vp->v_rdev);
25770909f38aSPawel Jakub Dawidek 		else
25780909f38aSPawel Jakub Dawidek 			devname = "[file]";
257935918c55SChristian S.J. Peron 		error = swapoff_one(sp, thread0.td_ucred);
25800909f38aSPawel Jakub Dawidek 		if (error != 0) {
25810909f38aSPawel Jakub Dawidek 			printf("Cannot remove swap device %s (error=%d), "
25820909f38aSPawel Jakub Dawidek 			    "skipping.\n", devname, error);
25830909f38aSPawel Jakub Dawidek 		} else if (bootverbose) {
25840909f38aSPawel Jakub Dawidek 			printf("Swap device %s removed.\n", devname);
25850909f38aSPawel Jakub Dawidek 		}
25860909f38aSPawel Jakub Dawidek 		mtx_lock(&sw_dev_mtx);
25870909f38aSPawel Jakub Dawidek 	}
25880909f38aSPawel Jakub Dawidek 	mtx_unlock(&sw_dev_mtx);
25890909f38aSPawel Jakub Dawidek 
259004533e1eSKonstantin Belousov 	sx_xunlock(&swdev_syscall_lock);
2591e9c0cc15SPoul-Henning Kamp }
2592e9c0cc15SPoul-Henning Kamp 
2593567104a1SPoul-Henning Kamp void
2594567104a1SPoul-Henning Kamp swap_pager_status(int *total, int *used)
2595567104a1SPoul-Henning Kamp {
2596567104a1SPoul-Henning Kamp 
25977ce3a312SMateusz Guzik 	*total = swap_total;
25987ce3a312SMateusz Guzik 	*used = swap_total - swap_pager_avail -
25997ce3a312SMateusz Guzik 	    nswapdev * howmany(BBSIZE, PAGE_SIZE);
2600567104a1SPoul-Henning Kamp }
2601567104a1SPoul-Henning Kamp 
2602dda4f960SKonstantin Belousov int
2603dda4f960SKonstantin Belousov swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2604dda4f960SKonstantin Belousov {
2605dda4f960SKonstantin Belousov 	struct swdevt *sp;
26067870adb6SEd Schouten 	const char *tmp_devname;
2607dda4f960SKonstantin Belousov 	int error, n;
2608dda4f960SKonstantin Belousov 
2609dda4f960SKonstantin Belousov 	n = 0;
2610dda4f960SKonstantin Belousov 	error = ENOENT;
2611dda4f960SKonstantin Belousov 	mtx_lock(&sw_dev_mtx);
2612dda4f960SKonstantin Belousov 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2613dda4f960SKonstantin Belousov 		if (n != name) {
2614dda4f960SKonstantin Belousov 			n++;
2615dda4f960SKonstantin Belousov 			continue;
2616dda4f960SKonstantin Belousov 		}
2617dda4f960SKonstantin Belousov 		xs->xsw_version = XSWDEV_VERSION;
2618dda4f960SKonstantin Belousov 		xs->xsw_dev = sp->sw_dev;
2619dda4f960SKonstantin Belousov 		xs->xsw_flags = sp->sw_flags;
2620dda4f960SKonstantin Belousov 		xs->xsw_nblks = sp->sw_nblks;
2621dda4f960SKonstantin Belousov 		xs->xsw_used = sp->sw_used;
2622dda4f960SKonstantin Belousov 		if (devname != NULL) {
26237ad2a82dSMateusz Guzik 			if (vn_isdisk(sp->sw_vp))
26247870adb6SEd Schouten 				tmp_devname = devtoname(sp->sw_vp->v_rdev);
2625dda4f960SKonstantin Belousov 			else
2626dda4f960SKonstantin Belousov 				tmp_devname = "[file]";
2627dda4f960SKonstantin Belousov 			strncpy(devname, tmp_devname, len);
2628dda4f960SKonstantin Belousov 		}
2629dda4f960SKonstantin Belousov 		error = 0;
2630dda4f960SKonstantin Belousov 		break;
2631dda4f960SKonstantin Belousov 	}
2632dda4f960SKonstantin Belousov 	mtx_unlock(&sw_dev_mtx);
2633dda4f960SKonstantin Belousov 	return (error);
2634dda4f960SKonstantin Belousov }
2635dda4f960SKonstantin Belousov 
263669921123SKonstantin Belousov #if defined(COMPAT_FREEBSD11)
263769921123SKonstantin Belousov #define XSWDEV_VERSION_11	1
263869921123SKonstantin Belousov struct xswdev11 {
263969921123SKonstantin Belousov 	u_int	xsw_version;
264069921123SKonstantin Belousov 	uint32_t xsw_dev;
264169921123SKonstantin Belousov 	int	xsw_flags;
264269921123SKonstantin Belousov 	int	xsw_nblks;
264369921123SKonstantin Belousov 	int     xsw_used;
264469921123SKonstantin Belousov };
264569921123SKonstantin Belousov #endif
264669921123SKonstantin Belousov 
2647f6d281e8SKonstantin Belousov #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2648f6d281e8SKonstantin Belousov struct xswdev32 {
2649f6d281e8SKonstantin Belousov 	u_int	xsw_version;
2650f6d281e8SKonstantin Belousov 	u_int	xsw_dev1, xsw_dev2;
2651f6d281e8SKonstantin Belousov 	int	xsw_flags;
2652f6d281e8SKonstantin Belousov 	int	xsw_nblks;
2653f6d281e8SKonstantin Belousov 	int     xsw_used;
2654f6d281e8SKonstantin Belousov };
2655f6d281e8SKonstantin Belousov #endif
2656f6d281e8SKonstantin Belousov 
2657e9c0cc15SPoul-Henning Kamp static int
2658e9c0cc15SPoul-Henning Kamp sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2659e9c0cc15SPoul-Henning Kamp {
2660e9c0cc15SPoul-Henning Kamp 	struct xswdev xs;
2661f6d281e8SKonstantin Belousov #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2662f6d281e8SKonstantin Belousov 	struct xswdev32 xs32;
2663f6d281e8SKonstantin Belousov #endif
266469921123SKonstantin Belousov #if defined(COMPAT_FREEBSD11)
266569921123SKonstantin Belousov 	struct xswdev11 xs11;
266669921123SKonstantin Belousov #endif
2667dda4f960SKonstantin Belousov 	int error;
2668e9c0cc15SPoul-Henning Kamp 
2669e9c0cc15SPoul-Henning Kamp 	if (arg2 != 1)			/* name length */
2670e9c0cc15SPoul-Henning Kamp 		return (EINVAL);
2671dda4f960SKonstantin Belousov 	error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2672dda4f960SKonstantin Belousov 	if (error != 0)
2673dda4f960SKonstantin Belousov 		return (error);
2674f6d281e8SKonstantin Belousov #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2675f6d281e8SKonstantin Belousov 	if (req->oldlen == sizeof(xs32)) {
2676f6d281e8SKonstantin Belousov 		xs32.xsw_version = XSWDEV_VERSION;
2677f6d281e8SKonstantin Belousov 		xs32.xsw_dev1 = xs.xsw_dev;
2678f6d281e8SKonstantin Belousov 		xs32.xsw_dev2 = xs.xsw_dev >> 32;
2679f6d281e8SKonstantin Belousov 		xs32.xsw_flags = xs.xsw_flags;
2680f6d281e8SKonstantin Belousov 		xs32.xsw_nblks = xs.xsw_nblks;
2681f6d281e8SKonstantin Belousov 		xs32.xsw_used = xs.xsw_used;
2682f6d281e8SKonstantin Belousov 		error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2683f6d281e8SKonstantin Belousov 		return (error);
2684f6d281e8SKonstantin Belousov 	}
2685f6d281e8SKonstantin Belousov #endif
268669921123SKonstantin Belousov #if defined(COMPAT_FREEBSD11)
268769921123SKonstantin Belousov 	if (req->oldlen == sizeof(xs11)) {
268869921123SKonstantin Belousov 		xs11.xsw_version = XSWDEV_VERSION_11;
268969921123SKonstantin Belousov 		xs11.xsw_dev = xs.xsw_dev; /* truncation */
269069921123SKonstantin Belousov 		xs11.xsw_flags = xs.xsw_flags;
269169921123SKonstantin Belousov 		xs11.xsw_nblks = xs.xsw_nblks;
269269921123SKonstantin Belousov 		xs11.xsw_used = xs.xsw_used;
269369921123SKonstantin Belousov 		error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2694f6d281e8SKonstantin Belousov 		return (error);
2695f6d281e8SKonstantin Belousov 	}
269669921123SKonstantin Belousov #endif
2697e9c0cc15SPoul-Henning Kamp 	error = SYSCTL_OUT(req, &xs, sizeof(xs));
2698e9c0cc15SPoul-Henning Kamp 	return (error);
2699e9c0cc15SPoul-Henning Kamp }
2700e9c0cc15SPoul-Henning Kamp 
27018f60c087SPoul-Henning Kamp SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2702e9c0cc15SPoul-Henning Kamp     "Number of swap devices");
27034c36e917SKonstantin Belousov SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
27044c36e917SKonstantin Belousov     sysctl_vm_swap_info,
2705e9c0cc15SPoul-Henning Kamp     "Swap statistics by device");
2706ec38b344SPoul-Henning Kamp 
2707ec38b344SPoul-Henning Kamp /*
2708f425ab8eSKonstantin Belousov  * Count the approximate swap usage in pages for a vmspace.  The
2709f425ab8eSKonstantin Belousov  * shadowed or not yet copied on write swap blocks are not accounted.
2710ec38b344SPoul-Henning Kamp  * The map must be locked.
2711ec38b344SPoul-Henning Kamp  */
27122860553aSRebecca Cran long
2713ec38b344SPoul-Henning Kamp vmspace_swap_count(struct vmspace *vmspace)
2714ec38b344SPoul-Henning Kamp {
271565d8409cSRebecca Cran 	vm_map_t map;
2716ec38b344SPoul-Henning Kamp 	vm_map_entry_t cur;
271765d8409cSRebecca Cran 	vm_object_t object;
2718f425ab8eSKonstantin Belousov 	struct swblk *sb;
2719f425ab8eSKonstantin Belousov 	vm_pindex_t e, pi;
2720f425ab8eSKonstantin Belousov 	long count;
2721f425ab8eSKonstantin Belousov 	int i;
272265d8409cSRebecca Cran 
272365d8409cSRebecca Cran 	map = &vmspace->vm_map;
272465d8409cSRebecca Cran 	count = 0;
2725ec38b344SPoul-Henning Kamp 
27262288078cSDoug Moore 	VM_MAP_ENTRY_FOREACH(cur, map) {
2727f425ab8eSKonstantin Belousov 		if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2728f425ab8eSKonstantin Belousov 			continue;
2729f425ab8eSKonstantin Belousov 		object = cur->object.vm_object;
2730f425ab8eSKonstantin Belousov 		if (object == NULL || object->type != OBJT_SWAP)
2731f425ab8eSKonstantin Belousov 			continue;
2732f425ab8eSKonstantin Belousov 		VM_OBJECT_RLOCK(object);
2733f425ab8eSKonstantin Belousov 		if (object->type != OBJT_SWAP)
2734f425ab8eSKonstantin Belousov 			goto unlock;
2735f425ab8eSKonstantin Belousov 		pi = OFF_TO_IDX(cur->offset);
2736f425ab8eSKonstantin Belousov 		e = pi + OFF_TO_IDX(cur->end - cur->start);
2737f425ab8eSKonstantin Belousov 		for (;; pi = sb->p + SWAP_META_PAGES) {
2738f425ab8eSKonstantin Belousov 			sb = SWAP_PCTRIE_LOOKUP_GE(
2739f425ab8eSKonstantin Belousov 			    &object->un_pager.swp.swp_blks, pi);
2740f425ab8eSKonstantin Belousov 			if (sb == NULL || sb->p >= e)
2741f425ab8eSKonstantin Belousov 				break;
2742f425ab8eSKonstantin Belousov 			for (i = 0; i < SWAP_META_PAGES; i++) {
2743f425ab8eSKonstantin Belousov 				if (sb->p + i < e &&
2744f425ab8eSKonstantin Belousov 				    sb->d[i] != SWAPBLK_NONE)
2745f425ab8eSKonstantin Belousov 					count++;
2746ec38b344SPoul-Henning Kamp 			}
2747ec38b344SPoul-Henning Kamp 		}
2748f425ab8eSKonstantin Belousov unlock:
2749f425ab8eSKonstantin Belousov 		VM_OBJECT_RUNLOCK(object);
2750ec38b344SPoul-Henning Kamp 	}
2751ec38b344SPoul-Henning Kamp 	return (count);
2752ec38b344SPoul-Henning Kamp }
2753dee34ca4SPoul-Henning Kamp 
2754dee34ca4SPoul-Henning Kamp /*
2755dee34ca4SPoul-Henning Kamp  * GEOM backend
2756dee34ca4SPoul-Henning Kamp  *
2757dee34ca4SPoul-Henning Kamp  * Swapping onto disk devices.
2758dee34ca4SPoul-Henning Kamp  *
2759dee34ca4SPoul-Henning Kamp  */
2760dee34ca4SPoul-Henning Kamp 
27615721c9c7SPoul-Henning Kamp static g_orphan_t swapgeom_orphan;
27625721c9c7SPoul-Henning Kamp 
2763dee34ca4SPoul-Henning Kamp static struct g_class g_swap_class = {
2764dee34ca4SPoul-Henning Kamp 	.name = "SWAP",
27655721c9c7SPoul-Henning Kamp 	.version = G_VERSION,
27665721c9c7SPoul-Henning Kamp 	.orphan = swapgeom_orphan,
2767dee34ca4SPoul-Henning Kamp };
2768dee34ca4SPoul-Henning Kamp 
2769dee34ca4SPoul-Henning Kamp DECLARE_GEOM_CLASS(g_swap_class, g_class);
2770dee34ca4SPoul-Henning Kamp 
2771dee34ca4SPoul-Henning Kamp static void
27723398491bSAlexander Motin swapgeom_close_ev(void *arg, int flags)
27733398491bSAlexander Motin {
27743398491bSAlexander Motin 	struct g_consumer *cp;
27753398491bSAlexander Motin 
27763398491bSAlexander Motin 	cp = arg;
27773398491bSAlexander Motin 	g_access(cp, -1, -1, 0);
27783398491bSAlexander Motin 	g_detach(cp);
27793398491bSAlexander Motin 	g_destroy_consumer(cp);
27803398491bSAlexander Motin }
27813398491bSAlexander Motin 
27829e3e3fe5SWarner Losh /*
27839e3e3fe5SWarner Losh  * Add a reference to the g_consumer for an inflight transaction.
27849e3e3fe5SWarner Losh  */
27859e3e3fe5SWarner Losh static void
27869e3e3fe5SWarner Losh swapgeom_acquire(struct g_consumer *cp)
27879e3e3fe5SWarner Losh {
27889e3e3fe5SWarner Losh 
27899e3e3fe5SWarner Losh 	mtx_assert(&sw_dev_mtx, MA_OWNED);
27909e3e3fe5SWarner Losh 	cp->index++;
27919e3e3fe5SWarner Losh }
27929e3e3fe5SWarner Losh 
27939e3e3fe5SWarner Losh /*
27940c657d22SKonstantin Belousov  * Remove a reference from the g_consumer.  Post a close event if all
27950c657d22SKonstantin Belousov  * references go away, since the function might be called from the
27960c657d22SKonstantin Belousov  * biodone context.
27979e3e3fe5SWarner Losh  */
27989e3e3fe5SWarner Losh static void
27999e3e3fe5SWarner Losh swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
28009e3e3fe5SWarner Losh {
28019e3e3fe5SWarner Losh 
28029e3e3fe5SWarner Losh 	mtx_assert(&sw_dev_mtx, MA_OWNED);
28039e3e3fe5SWarner Losh 	cp->index--;
28049e3e3fe5SWarner Losh 	if (cp->index == 0) {
28059e3e3fe5SWarner Losh 		if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
28069e3e3fe5SWarner Losh 			sp->sw_id = NULL;
28079e3e3fe5SWarner Losh 	}
28089e3e3fe5SWarner Losh }
28099e3e3fe5SWarner Losh 
28103398491bSAlexander Motin static void
2811dee34ca4SPoul-Henning Kamp swapgeom_done(struct bio *bp2)
2812dee34ca4SPoul-Henning Kamp {
28133398491bSAlexander Motin 	struct swdevt *sp;
2814dee34ca4SPoul-Henning Kamp 	struct buf *bp;
28153398491bSAlexander Motin 	struct g_consumer *cp;
2816dee34ca4SPoul-Henning Kamp 
2817dee34ca4SPoul-Henning Kamp 	bp = bp2->bio_caller2;
28183398491bSAlexander Motin 	cp = bp2->bio_from;
2819c5d3d25eSPoul-Henning Kamp 	bp->b_ioflags = bp2->bio_flags;
2820dee34ca4SPoul-Henning Kamp 	if (bp2->bio_error)
2821dee34ca4SPoul-Henning Kamp 		bp->b_ioflags |= BIO_ERROR;
2822c5d3d25eSPoul-Henning Kamp 	bp->b_resid = bp->b_bcount - bp2->bio_completed;
2823c5d3d25eSPoul-Henning Kamp 	bp->b_error = bp2->bio_error;
2824756a5412SGleb Smirnoff 	bp->b_caller1 = NULL;
2825dee34ca4SPoul-Henning Kamp 	bufdone(bp);
28263398491bSAlexander Motin 	sp = bp2->bio_caller1;
28279e3e3fe5SWarner Losh 	mtx_lock(&sw_dev_mtx);
28289e3e3fe5SWarner Losh 	swapgeom_release(cp, sp);
28293398491bSAlexander Motin 	mtx_unlock(&sw_dev_mtx);
2830dee34ca4SPoul-Henning Kamp 	g_destroy_bio(bp2);
2831dee34ca4SPoul-Henning Kamp }
2832dee34ca4SPoul-Henning Kamp 
2833dee34ca4SPoul-Henning Kamp static void
2834dee34ca4SPoul-Henning Kamp swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2835dee34ca4SPoul-Henning Kamp {
2836dee34ca4SPoul-Henning Kamp 	struct bio *bio;
2837dee34ca4SPoul-Henning Kamp 	struct g_consumer *cp;
2838dee34ca4SPoul-Henning Kamp 
28393398491bSAlexander Motin 	mtx_lock(&sw_dev_mtx);
2840dee34ca4SPoul-Henning Kamp 	cp = sp->sw_id;
2841dee34ca4SPoul-Henning Kamp 	if (cp == NULL) {
28423398491bSAlexander Motin 		mtx_unlock(&sw_dev_mtx);
2843dee34ca4SPoul-Henning Kamp 		bp->b_error = ENXIO;
2844dee34ca4SPoul-Henning Kamp 		bp->b_ioflags |= BIO_ERROR;
2845dee34ca4SPoul-Henning Kamp 		bufdone(bp);
2846dee34ca4SPoul-Henning Kamp 		return;
2847dee34ca4SPoul-Henning Kamp 	}
28489e3e3fe5SWarner Losh 	swapgeom_acquire(cp);
28493398491bSAlexander Motin 	mtx_unlock(&sw_dev_mtx);
285011041003SKonstantin Belousov 	if (bp->b_iocmd == BIO_WRITE)
285111041003SKonstantin Belousov 		bio = g_new_bio();
285211041003SKonstantin Belousov 	else
28534f8205e5SPoul-Henning Kamp 		bio = g_alloc_bio();
28544f8205e5SPoul-Henning Kamp 	if (bio == NULL) {
28559e3e3fe5SWarner Losh 		mtx_lock(&sw_dev_mtx);
28569e3e3fe5SWarner Losh 		swapgeom_release(cp, sp);
28579e3e3fe5SWarner Losh 		mtx_unlock(&sw_dev_mtx);
28583e5b6861SPoul-Henning Kamp 		bp->b_error = ENOMEM;
28593e5b6861SPoul-Henning Kamp 		bp->b_ioflags |= BIO_ERROR;
28600b208315SEdward Tomasz Napierala 		printf("swap_pager: cannot allocate bio\n");
28613e5b6861SPoul-Henning Kamp 		bufdone(bp);
28623e5b6861SPoul-Henning Kamp 		return;
28633e5b6861SPoul-Henning Kamp 	}
286411041003SKonstantin Belousov 
2865756a5412SGleb Smirnoff 	bp->b_caller1 = bio;
28663398491bSAlexander Motin 	bio->bio_caller1 = sp;
2867dee34ca4SPoul-Henning Kamp 	bio->bio_caller2 = bp;
2868c5d3d25eSPoul-Henning Kamp 	bio->bio_cmd = bp->b_iocmd;
2869dee34ca4SPoul-Henning Kamp 	bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2870dee34ca4SPoul-Henning Kamp 	bio->bio_length = bp->b_bcount;
2871dee34ca4SPoul-Henning Kamp 	bio->bio_done = swapgeom_done;
2872fade8dd7SJeff Roberson 	if (!buf_mapped(bp)) {
28732cc718a1SKonstantin Belousov 		bio->bio_ma = bp->b_pages;
28742cc718a1SKonstantin Belousov 		bio->bio_data = unmapped_buf;
28752cc718a1SKonstantin Belousov 		bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
28762cc718a1SKonstantin Belousov 		bio->bio_ma_n = bp->b_npages;
28772cc718a1SKonstantin Belousov 		bio->bio_flags |= BIO_UNMAPPED;
28782cc718a1SKonstantin Belousov 	} else {
28792cc718a1SKonstantin Belousov 		bio->bio_data = bp->b_data;
28802cc718a1SKonstantin Belousov 		bio->bio_ma = NULL;
28812cc718a1SKonstantin Belousov 	}
2882dee34ca4SPoul-Henning Kamp 	g_io_request(bio, cp);
2883dee34ca4SPoul-Henning Kamp 	return;
2884dee34ca4SPoul-Henning Kamp }
2885dee34ca4SPoul-Henning Kamp 
2886dee34ca4SPoul-Henning Kamp static void
2887dee34ca4SPoul-Henning Kamp swapgeom_orphan(struct g_consumer *cp)
2888dee34ca4SPoul-Henning Kamp {
2889dee34ca4SPoul-Henning Kamp 	struct swdevt *sp;
28903398491bSAlexander Motin 	int destroy;
2891dee34ca4SPoul-Henning Kamp 
2892dee34ca4SPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
28933398491bSAlexander Motin 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
28943398491bSAlexander Motin 		if (sp->sw_id == cp) {
28958f12d83aSAlexander Motin 			sp->sw_flags |= SW_CLOSING;
28963398491bSAlexander Motin 			break;
2897dee34ca4SPoul-Henning Kamp 		}
28983398491bSAlexander Motin 	}
28999e3e3fe5SWarner Losh 	/*
29009e3e3fe5SWarner Losh 	 * Drop reference we were created with. Do directly since we're in a
29019e3e3fe5SWarner Losh 	 * special context where we don't have to queue the call to
29029e3e3fe5SWarner Losh 	 * swapgeom_close_ev().
29039e3e3fe5SWarner Losh 	 */
29049e3e3fe5SWarner Losh 	cp->index--;
29053398491bSAlexander Motin 	destroy = ((sp != NULL) && (cp->index == 0));
29063398491bSAlexander Motin 	if (destroy)
29073398491bSAlexander Motin 		sp->sw_id = NULL;
29083398491bSAlexander Motin 	mtx_unlock(&sw_dev_mtx);
29093398491bSAlexander Motin 	if (destroy)
29103398491bSAlexander Motin 		swapgeom_close_ev(cp, 0);
2911dee34ca4SPoul-Henning Kamp }
2912dee34ca4SPoul-Henning Kamp 
2913dee34ca4SPoul-Henning Kamp static void
2914dee34ca4SPoul-Henning Kamp swapgeom_close(struct thread *td, struct swdevt *sw)
2915dee34ca4SPoul-Henning Kamp {
29163398491bSAlexander Motin 	struct g_consumer *cp;
2917dee34ca4SPoul-Henning Kamp 
29183398491bSAlexander Motin 	mtx_lock(&sw_dev_mtx);
29193398491bSAlexander Motin 	cp = sw->sw_id;
29203398491bSAlexander Motin 	sw->sw_id = NULL;
29213398491bSAlexander Motin 	mtx_unlock(&sw_dev_mtx);
29220c657d22SKonstantin Belousov 
29230c657d22SKonstantin Belousov 	/*
29240c657d22SKonstantin Belousov 	 * swapgeom_close() may be called from the biodone context,
29250c657d22SKonstantin Belousov 	 * where we cannot perform topology changes.  Delegate the
29260c657d22SKonstantin Belousov 	 * work to the events thread.
29270c657d22SKonstantin Belousov 	 */
29283398491bSAlexander Motin 	if (cp != NULL)
29293398491bSAlexander Motin 		g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2930dee34ca4SPoul-Henning Kamp }
2931dee34ca4SPoul-Henning Kamp 
293288ad2d7bSKonstantin Belousov static int
293388ad2d7bSKonstantin Belousov swapongeom_locked(struct cdev *dev, struct vnode *vp)
2934dee34ca4SPoul-Henning Kamp {
2935dee34ca4SPoul-Henning Kamp 	struct g_provider *pp;
2936dee34ca4SPoul-Henning Kamp 	struct g_consumer *cp;
2937dee34ca4SPoul-Henning Kamp 	static struct g_geom *gp;
2938dee34ca4SPoul-Henning Kamp 	struct swdevt *sp;
2939dee34ca4SPoul-Henning Kamp 	u_long nblks;
2940dee34ca4SPoul-Henning Kamp 	int error;
2941dee34ca4SPoul-Henning Kamp 
294288ad2d7bSKonstantin Belousov 	pp = g_dev_getprovider(dev);
294388ad2d7bSKonstantin Belousov 	if (pp == NULL)
294488ad2d7bSKonstantin Belousov 		return (ENODEV);
2945dee34ca4SPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
2946dee34ca4SPoul-Henning Kamp 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2947dee34ca4SPoul-Henning Kamp 		cp = sp->sw_id;
2948dee34ca4SPoul-Henning Kamp 		if (cp != NULL && cp->provider == pp) {
2949dee34ca4SPoul-Henning Kamp 			mtx_unlock(&sw_dev_mtx);
295088ad2d7bSKonstantin Belousov 			return (EBUSY);
2951dee34ca4SPoul-Henning Kamp 		}
2952dee34ca4SPoul-Henning Kamp 	}
2953dee34ca4SPoul-Henning Kamp 	mtx_unlock(&sw_dev_mtx);
29545721c9c7SPoul-Henning Kamp 	if (gp == NULL)
295502c62349SJaakko Heinonen 		gp = g_new_geomf(&g_swap_class, "swap");
2956dee34ca4SPoul-Henning Kamp 	cp = g_new_consumer(gp);
29579e3e3fe5SWarner Losh 	cp->index = 1;	/* Number of active I/Os, plus one for being active. */
29589e3e3fe5SWarner Losh 	cp->flags |=  G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2959dee34ca4SPoul-Henning Kamp 	g_attach(cp, pp);
2960afeb65e6SPoul-Henning Kamp 	/*
2961afeb65e6SPoul-Henning Kamp 	 * XXX: Every time you think you can improve the margin for
2962afeb65e6SPoul-Henning Kamp 	 * footshooting, somebody depends on the ability to do so:
2963afeb65e6SPoul-Henning Kamp 	 * savecore(8) wants to write to our swapdev so we cannot
2964afeb65e6SPoul-Henning Kamp 	 * set an exclusive count :-(
2965afeb65e6SPoul-Henning Kamp 	 */
2966d2bae332SPoul-Henning Kamp 	error = g_access(cp, 1, 1, 0);
296788ad2d7bSKonstantin Belousov 	if (error != 0) {
2968dee34ca4SPoul-Henning Kamp 		g_detach(cp);
2969dee34ca4SPoul-Henning Kamp 		g_destroy_consumer(cp);
297088ad2d7bSKonstantin Belousov 		return (error);
2971dee34ca4SPoul-Henning Kamp 	}
2972dee34ca4SPoul-Henning Kamp 	nblks = pp->mediasize / DEV_BSIZE;
297388ad2d7bSKonstantin Belousov 	swaponsomething(vp, cp, nblks, swapgeom_strategy,
297488ad2d7bSKonstantin Belousov 	    swapgeom_close, dev2udev(dev),
29752cc718a1SKonstantin Belousov 	    (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
297688ad2d7bSKonstantin Belousov 	return (0);
2977dee34ca4SPoul-Henning Kamp }
2978dee34ca4SPoul-Henning Kamp 
2979dee34ca4SPoul-Henning Kamp static int
298088ad2d7bSKonstantin Belousov swapongeom(struct vnode *vp)
2981dee34ca4SPoul-Henning Kamp {
2982dee34ca4SPoul-Henning Kamp 	int error;
2983dee34ca4SPoul-Henning Kamp 
2984cb05b60aSAttilio Rao 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2985abd80ddbSMateusz Guzik 	if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) {
298688ad2d7bSKonstantin Belousov 		error = ENOENT;
298788ad2d7bSKonstantin Belousov 	} else {
298888ad2d7bSKonstantin Belousov 		g_topology_lock();
298988ad2d7bSKonstantin Belousov 		error = swapongeom_locked(vp->v_rdev, vp);
299088ad2d7bSKonstantin Belousov 		g_topology_unlock();
299188ad2d7bSKonstantin Belousov 	}
2992b249ce48SMateusz Guzik 	VOP_UNLOCK(vp);
2993dee34ca4SPoul-Henning Kamp 	return (error);
2994dee34ca4SPoul-Henning Kamp }
2995dee34ca4SPoul-Henning Kamp 
2996dee34ca4SPoul-Henning Kamp /*
2997dee34ca4SPoul-Henning Kamp  * VNODE backend
2998dee34ca4SPoul-Henning Kamp  *
2999dee34ca4SPoul-Henning Kamp  * This is used mainly for network filesystem (read: probably only tested
3000dee34ca4SPoul-Henning Kamp  * with NFS) swapfiles.
3001dee34ca4SPoul-Henning Kamp  *
3002dee34ca4SPoul-Henning Kamp  */
3003dee34ca4SPoul-Henning Kamp 
3004dee34ca4SPoul-Henning Kamp static void
3005dee34ca4SPoul-Henning Kamp swapdev_strategy(struct buf *bp, struct swdevt *sp)
3006dee34ca4SPoul-Henning Kamp {
3007494eb176SPoul-Henning Kamp 	struct vnode *vp2;
3008dee34ca4SPoul-Henning Kamp 
3009dee34ca4SPoul-Henning Kamp 	bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
3010dee34ca4SPoul-Henning Kamp 
3011dee34ca4SPoul-Henning Kamp 	vp2 = sp->sw_id;
3012dee34ca4SPoul-Henning Kamp 	vhold(vp2);
3013dee34ca4SPoul-Henning Kamp 	if (bp->b_iocmd == BIO_WRITE) {
30143cfc7651SOlivier Houchard 		if (bp->b_bufobj)
3015494eb176SPoul-Henning Kamp 			bufobj_wdrop(bp->b_bufobj);
3016a76d8f4eSPoul-Henning Kamp 		bufobj_wref(&vp2->v_bufobj);
3017dee34ca4SPoul-Henning Kamp 	}
30183cfc7651SOlivier Houchard 	if (bp->b_bufobj != &vp2->v_bufobj)
30193cfc7651SOlivier Houchard 		bp->b_bufobj = &vp2->v_bufobj;
3020dee34ca4SPoul-Henning Kamp 	bp->b_vp = vp2;
30212c18019fSPoul-Henning Kamp 	bp->b_iooffset = dbtob(bp->b_blkno);
3022b792bebeSPoul-Henning Kamp 	bstrategy(bp);
3023dee34ca4SPoul-Henning Kamp 	return;
3024dee34ca4SPoul-Henning Kamp }
3025dee34ca4SPoul-Henning Kamp 
3026dee34ca4SPoul-Henning Kamp static void
3027dee34ca4SPoul-Henning Kamp swapdev_close(struct thread *td, struct swdevt *sp)
3028dee34ca4SPoul-Henning Kamp {
3029dee34ca4SPoul-Henning Kamp 
3030dee34ca4SPoul-Henning Kamp 	VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
3031dee34ca4SPoul-Henning Kamp 	vrele(sp->sw_vp);
3032dee34ca4SPoul-Henning Kamp }
3033dee34ca4SPoul-Henning Kamp 
3034dee34ca4SPoul-Henning Kamp static int
3035dee34ca4SPoul-Henning Kamp swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
3036dee34ca4SPoul-Henning Kamp {
3037dee34ca4SPoul-Henning Kamp 	struct swdevt *sp;
3038dee34ca4SPoul-Henning Kamp 	int error;
3039dee34ca4SPoul-Henning Kamp 
3040dee34ca4SPoul-Henning Kamp 	if (nblks == 0)
3041dee34ca4SPoul-Henning Kamp 		return (ENXIO);
3042dee34ca4SPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
3043dee34ca4SPoul-Henning Kamp 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
3044dee34ca4SPoul-Henning Kamp 		if (sp->sw_id == vp) {
3045dee34ca4SPoul-Henning Kamp 			mtx_unlock(&sw_dev_mtx);
3046dee34ca4SPoul-Henning Kamp 			return (EBUSY);
3047dee34ca4SPoul-Henning Kamp 		}
3048dee34ca4SPoul-Henning Kamp 	}
3049dee34ca4SPoul-Henning Kamp 	mtx_unlock(&sw_dev_mtx);
3050dee34ca4SPoul-Henning Kamp 
3051cb05b60aSAttilio Rao 	(void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3052dee34ca4SPoul-Henning Kamp #ifdef MAC
305330d239bcSRobert Watson 	error = mac_system_check_swapon(td->td_ucred, vp);
3054dee34ca4SPoul-Henning Kamp 	if (error == 0)
3055dee34ca4SPoul-Henning Kamp #endif
30569e223287SKonstantin Belousov 		error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
3057b249ce48SMateusz Guzik 	(void) VOP_UNLOCK(vp);
3058dee34ca4SPoul-Henning Kamp 	if (error)
3059dee34ca4SPoul-Henning Kamp 		return (error);
3060dee34ca4SPoul-Henning Kamp 
3061dee34ca4SPoul-Henning Kamp 	swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
30622cc718a1SKonstantin Belousov 	    NODEV, 0);
3063dee34ca4SPoul-Henning Kamp 	return (0);
3064dee34ca4SPoul-Henning Kamp }
306589c241d1SGleb Smirnoff 
306689c241d1SGleb Smirnoff static int
306789c241d1SGleb Smirnoff sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
306889c241d1SGleb Smirnoff {
306989c241d1SGleb Smirnoff 	int error, new, n;
307089c241d1SGleb Smirnoff 
307189c241d1SGleb Smirnoff 	new = nsw_wcount_async_max;
307289c241d1SGleb Smirnoff 	error = sysctl_handle_int(oidp, &new, 0, req);
307389c241d1SGleb Smirnoff 	if (error != 0 || req->newptr == NULL)
307489c241d1SGleb Smirnoff 		return (error);
307589c241d1SGleb Smirnoff 
307689c241d1SGleb Smirnoff 	if (new > nswbuf / 2 || new < 1)
307789c241d1SGleb Smirnoff 		return (EINVAL);
307889c241d1SGleb Smirnoff 
3079756a5412SGleb Smirnoff 	mtx_lock(&swbuf_mtx);
308089c241d1SGleb Smirnoff 	while (nsw_wcount_async_max != new) {
308189c241d1SGleb Smirnoff 		/*
308289c241d1SGleb Smirnoff 		 * Adjust difference.  If the current async count is too low,
308389c241d1SGleb Smirnoff 		 * we will need to sqeeze our update slowly in.  Sleep with a
308489c241d1SGleb Smirnoff 		 * higher priority than getpbuf() to finish faster.
308589c241d1SGleb Smirnoff 		 */
308689c241d1SGleb Smirnoff 		n = new - nsw_wcount_async_max;
308789c241d1SGleb Smirnoff 		if (nsw_wcount_async + n >= 0) {
308889c241d1SGleb Smirnoff 			nsw_wcount_async += n;
308989c241d1SGleb Smirnoff 			nsw_wcount_async_max += n;
309089c241d1SGleb Smirnoff 			wakeup(&nsw_wcount_async);
309189c241d1SGleb Smirnoff 		} else {
309289c241d1SGleb Smirnoff 			nsw_wcount_async_max -= nsw_wcount_async;
309389c241d1SGleb Smirnoff 			nsw_wcount_async = 0;
3094756a5412SGleb Smirnoff 			msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
309589c241d1SGleb Smirnoff 			    "swpsysctl", 0);
309689c241d1SGleb Smirnoff 		}
309789c241d1SGleb Smirnoff 	}
3098756a5412SGleb Smirnoff 	mtx_unlock(&swbuf_mtx);
309989c241d1SGleb Smirnoff 
310089c241d1SGleb Smirnoff 	return (0);
310189c241d1SGleb Smirnoff }
3102fe7bcbafSKyle Evans 
3103fe7bcbafSKyle Evans static void
3104fe7bcbafSKyle Evans swap_pager_update_writecount(vm_object_t object, vm_offset_t start,
3105fe7bcbafSKyle Evans     vm_offset_t end)
3106fe7bcbafSKyle Evans {
3107fe7bcbafSKyle Evans 
3108fe7bcbafSKyle Evans 	VM_OBJECT_WLOCK(object);
310963967687SJeff Roberson 	KASSERT((object->flags & OBJ_ANON) == 0,
3110fe7bcbafSKyle Evans 	    ("Splittable object with writecount"));
3111fe7bcbafSKyle Evans 	object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
3112fe7bcbafSKyle Evans 	VM_OBJECT_WUNLOCK(object);
3113fe7bcbafSKyle Evans }
3114fe7bcbafSKyle Evans 
3115fe7bcbafSKyle Evans static void
3116fe7bcbafSKyle Evans swap_pager_release_writecount(vm_object_t object, vm_offset_t start,
3117fe7bcbafSKyle Evans     vm_offset_t end)
3118fe7bcbafSKyle Evans {
3119fe7bcbafSKyle Evans 
3120fe7bcbafSKyle Evans 	VM_OBJECT_WLOCK(object);
312163967687SJeff Roberson 	KASSERT((object->flags & OBJ_ANON) == 0,
3122fe7bcbafSKyle Evans 	    ("Splittable object with writecount"));
3123fe7bcbafSKyle Evans 	object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
3124fe7bcbafSKyle Evans 	VM_OBJECT_WUNLOCK(object);
3125fe7bcbafSKyle Evans }
3126