xref: /freebsd/sys/vm/swap_pager.c (revision d11d407aee4835fd50811a5980125bb46748fa0b)
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 
68874651b1SDavid E. O'Brien #include <sys/cdefs.h>
69e9c0cc15SPoul-Henning Kamp #include "opt_vm.h"
70e9c0cc15SPoul-Henning Kamp 
71df8bae1dSRodney W. Grimes #include <sys/param.h>
729626b608SPoul-Henning Kamp #include <sys/bio.h>
73e2e050c8SConrad Meyer #include <sys/blist.h>
74df8bae1dSRodney W. Grimes #include <sys/buf.h>
75e2e050c8SConrad Meyer #include <sys/conf.h>
76e9c0cc15SPoul-Henning Kamp #include <sys/disk.h>
77504f5e29SDoug Moore #include <sys/disklabel.h>
78e2e050c8SConrad Meyer #include <sys/eventhandler.h>
79e9c0cc15SPoul-Henning Kamp #include <sys/fcntl.h>
80686aa928SMark Johnston #include <sys/limits.h>
81e2e050c8SConrad Meyer #include <sys/lock.h>
82e2e050c8SConrad Meyer #include <sys/kernel.h>
83e9c0cc15SPoul-Henning Kamp #include <sys/mount.h>
84e9c0cc15SPoul-Henning Kamp #include <sys/namei.h>
85df8bae1dSRodney W. Grimes #include <sys/malloc.h>
86f425ab8eSKonstantin Belousov #include <sys/pctrie.h>
87e2e050c8SConrad Meyer #include <sys/priv.h>
88e2e050c8SConrad Meyer #include <sys/proc.h>
891ba5ad42SEdward Tomasz Napierala #include <sys/racct.h>
903364c323SKonstantin Belousov #include <sys/resource.h>
913364c323SKonstantin Belousov #include <sys/resourcevar.h>
9289f6b863SAttilio Rao #include <sys/rwlock.h>
93d027ed2eSAlan Cox #include <sys/sbuf.h>
94327f4e83SMatthew Dillon #include <sys/sysctl.h>
95e9c0cc15SPoul-Henning Kamp #include <sys/sysproto.h>
96e2e050c8SConrad Meyer #include <sys/systm.h>
970cddd8f0SMatthew Dillon #include <sys/sx.h>
9853465702SKonstantin Belousov #include <sys/unistd.h>
9900a3fe96SKonstantin Belousov #include <sys/user.h>
100936524aaSMatthew Dillon #include <sys/vmmeter.h>
101e2e050c8SConrad Meyer #include <sys/vnode.h>
102df8bae1dSRodney W. Grimes 
103aed55708SRobert Watson #include <security/mac/mac_framework.h>
104aed55708SRobert Watson 
105df8bae1dSRodney W. Grimes #include <vm/vm.h>
10621cd6e62SSeigo Tanimura #include <vm/pmap.h>
10721cd6e62SSeigo Tanimura #include <vm/vm_map.h>
10821cd6e62SSeigo Tanimura #include <vm/vm_kern.h>
109efeaf95aSDavid Greenman #include <vm/vm_object.h>
110df8bae1dSRodney W. Grimes #include <vm/vm_page.h>
111efeaf95aSDavid Greenman #include <vm/vm_pager.h>
112df8bae1dSRodney W. Grimes #include <vm/vm_pageout.h>
113e9c0cc15SPoul-Henning Kamp #include <vm/vm_param.h>
114db08b0b0SDoug Moore #include <vm/vm_radix.h>
115df8bae1dSRodney W. Grimes #include <vm/swap_pager.h>
116efeaf95aSDavid Greenman #include <vm/vm_extern.h>
117670d17b5SJeff Roberson #include <vm/uma.h>
118df8bae1dSRodney W. Grimes 
119dee34ca4SPoul-Henning Kamp #include <geom/geom.h>
120dee34ca4SPoul-Henning Kamp 
121ec38b344SPoul-Henning Kamp /*
122064650c1SAlan Cox  * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64.
123064650c1SAlan Cox  * The 64-page limit is due to the radix code (kern/subr_blist.c).
124ec38b344SPoul-Henning Kamp  */
125ec38b344SPoul-Henning Kamp #ifndef MAX_PAGEOUT_CLUSTER
126e2241590SAlan Cox #define	MAX_PAGEOUT_CLUSTER	32
127ec38b344SPoul-Henning Kamp #endif
128ec38b344SPoul-Henning Kamp 
129ec38b344SPoul-Henning Kamp #if !defined(SWB_NPAGES)
130ec38b344SPoul-Henning Kamp #define SWB_NPAGES	MAX_PAGEOUT_CLUSTER
131ec38b344SPoul-Henning Kamp #endif
132ec38b344SPoul-Henning Kamp 
133f425ab8eSKonstantin Belousov #define	SWAP_META_PAGES		PCTRIE_COUNT
134ec38b344SPoul-Henning Kamp 
135f425ab8eSKonstantin Belousov /*
136f425ab8eSKonstantin Belousov  * A swblk structure maps each page index within a
137f425ab8eSKonstantin Belousov  * SWAP_META_PAGES-aligned and sized range to the address of an
138f425ab8eSKonstantin Belousov  * on-disk swap block (or SWAPBLK_NONE). The collection of these
139f425ab8eSKonstantin Belousov  * mappings for an entire vm object is implemented as a pc-trie.
140f425ab8eSKonstantin Belousov  */
141f425ab8eSKonstantin Belousov struct swblk {
142f425ab8eSKonstantin Belousov 	vm_pindex_t	p;
143f425ab8eSKonstantin Belousov 	daddr_t		d[SWAP_META_PAGES];
144e9c0cc15SPoul-Henning Kamp };
145e9c0cc15SPoul-Henning Kamp 
146a880104aSDoug Moore /*
147a880104aSDoug Moore  * A page_range structure records the start address and length of a sequence of
148a880104aSDoug Moore  * mapped page addresses.
149a880104aSDoug Moore  */
150a880104aSDoug Moore struct page_range {
151a880104aSDoug Moore 	daddr_t start;
152a880104aSDoug Moore 	daddr_t num;
153a880104aSDoug Moore };
154a880104aSDoug Moore 
1552c4992dbSAlan Cox static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data");
15620da9c2eSPoul-Henning Kamp static struct mtx sw_dev_mtx;
1578f60c087SPoul-Henning Kamp static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
1588f60c087SPoul-Henning Kamp static struct swdevt *swdevhd;	/* Allocate from here next */
1598f60c087SPoul-Henning Kamp static int nswapdev;		/* Number of swap devices */
1608f60c087SPoul-Henning Kamp int swap_pager_avail;
16104533e1eSKonstantin Belousov static struct sx swdev_syscall_lock;	/* serialize swap(on|off) */
162e9c0cc15SPoul-Henning Kamp 
163126a2470SMateusz Guzik static __exclusive_cache_line u_long swap_reserved;
164e8bb589dSMatt Macy static u_long swap_total;
165e8bb589dSMatt Macy static int sysctl_page_shift(SYSCTL_HANDLER_ARGS);
166a8081778SJeff Roberson 
1677029da5cSPawel Biernacki static SYSCTL_NODE(_vm_stats, OID_AUTO, swap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
1687029da5cSPawel Biernacki     "VM swap stats");
169a8081778SJeff Roberson 
170e8bb589dSMatt Macy SYSCTL_PROC(_vm, OID_AUTO, swap_reserved, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
171567378ccSEnji Cooper     &swap_reserved, 0, sysctl_page_shift, "QU",
1728a9c731fSIvan Voras     "Amount of swap storage needed to back all allocated anonymous memory.");
173e8bb589dSMatt Macy SYSCTL_PROC(_vm, OID_AUTO, swap_total, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
174567378ccSEnji Cooper     &swap_total, 0, sysctl_page_shift, "QU",
175e8bb589dSMatt Macy     "Total amount of available swap storage.");
176e8bb589dSMatt Macy 
177ccdaa1abSKonstantin Belousov int vm_overcommit __read_mostly = 0;
178a6cc4c6eSKonstantin Belousov SYSCTL_INT(_vm, VM_OVERCOMMIT, overcommit, CTLFLAG_RW, &vm_overcommit, 0,
1798a9c731fSIvan Voras     "Configure virtual memory overcommit behavior. See tuning(7) "
1808a9c731fSIvan Voras     "for details.");
18161203277SDag-Erling Smørgrav static unsigned long swzone;
18261203277SDag-Erling Smørgrav SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
18361203277SDag-Erling Smørgrav     "Actual size of swap metadata zone");
18461203277SDag-Erling Smørgrav static unsigned long swap_maxpages;
18561203277SDag-Erling Smørgrav SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
18661203277SDag-Erling Smørgrav     "Maximum amount of swap supported");
1873364c323SKonstantin Belousov 
188d869a17eSMark Johnston static COUNTER_U64_DEFINE_EARLY(swap_free_deferred);
189a8081778SJeff Roberson SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_deferred,
190a8081778SJeff Roberson     CTLFLAG_RD, &swap_free_deferred,
191a8081778SJeff Roberson     "Number of pages that deferred freeing swap space");
192a8081778SJeff Roberson 
193d869a17eSMark Johnston static COUNTER_U64_DEFINE_EARLY(swap_free_completed);
194a8081778SJeff Roberson SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_completed,
195a8081778SJeff Roberson     CTLFLAG_RD, &swap_free_completed,
196a8081778SJeff Roberson     "Number of deferred frees completed");
197a8081778SJeff Roberson 
198e8bb589dSMatt Macy static int
199e8bb589dSMatt Macy sysctl_page_shift(SYSCTL_HANDLER_ARGS)
200e8bb589dSMatt Macy {
201e8bb589dSMatt Macy 	uint64_t newval;
202e8bb589dSMatt Macy 	u_long value = *(u_long *)arg1;
203e8bb589dSMatt Macy 
204e8bb589dSMatt Macy 	newval = ((uint64_t)value) << PAGE_SHIFT;
205e8bb589dSMatt Macy 	return (sysctl_handle_64(oidp, &newval, 0, req));
206e8bb589dSMatt Macy }
207e8bb589dSMatt Macy 
208ee744122SMateusz Guzik static bool
209ee744122SMateusz Guzik swap_reserve_by_cred_rlimit(u_long pincr, struct ucred *cred, int oc)
210ee744122SMateusz Guzik {
211ee744122SMateusz Guzik 	struct uidinfo *uip;
212ee744122SMateusz Guzik 	u_long prev;
213ee744122SMateusz Guzik 
214ee744122SMateusz Guzik 	uip = cred->cr_ruidinfo;
215ee744122SMateusz Guzik 
216ee744122SMateusz Guzik 	prev = atomic_fetchadd_long(&uip->ui_vmsize, pincr);
217ee744122SMateusz Guzik 	if ((oc & SWAP_RESERVE_RLIMIT_ON) != 0 &&
218ee744122SMateusz Guzik 	    prev + pincr > lim_cur(curthread, RLIMIT_SWAP) &&
219ee744122SMateusz Guzik 	    priv_check(curthread, PRIV_VM_SWAP_NORLIMIT) != 0) {
220ee744122SMateusz Guzik 		prev = atomic_fetchadd_long(&uip->ui_vmsize, -pincr);
22126eed2aaSKonstantin Belousov 		KASSERT(prev >= pincr,
22226eed2aaSKonstantin Belousov 		    ("negative vmsize for uid %d\n", uip->ui_uid));
223ee744122SMateusz Guzik 		return (false);
224ee744122SMateusz Guzik 	}
225ee744122SMateusz Guzik 	return (true);
226ee744122SMateusz Guzik }
227ee744122SMateusz Guzik 
228ee744122SMateusz Guzik static void
229ee744122SMateusz Guzik swap_release_by_cred_rlimit(u_long pdecr, struct ucred *cred)
230ee744122SMateusz Guzik {
231ee744122SMateusz Guzik 	struct uidinfo *uip;
232ee744122SMateusz Guzik #ifdef INVARIANTS
233ee744122SMateusz Guzik 	u_long prev;
234ee744122SMateusz Guzik #endif
235ee744122SMateusz Guzik 
236ee744122SMateusz Guzik 	uip = cred->cr_ruidinfo;
237ee744122SMateusz Guzik 
238ee744122SMateusz Guzik #ifdef INVARIANTS
239ee744122SMateusz Guzik 	prev = atomic_fetchadd_long(&uip->ui_vmsize, -pdecr);
24026eed2aaSKonstantin Belousov 	KASSERT(prev >= pdecr,
24126eed2aaSKonstantin Belousov 	    ("negative vmsize for uid %d\n", uip->ui_uid));
242ee744122SMateusz Guzik #else
243ee744122SMateusz Guzik 	atomic_subtract_long(&uip->ui_vmsize, pdecr);
244ee744122SMateusz Guzik #endif
245ee744122SMateusz Guzik }
246ee744122SMateusz Guzik 
247ee744122SMateusz Guzik static void
248ee744122SMateusz Guzik swap_reserve_force_rlimit(u_long pincr, struct ucred *cred)
249ee744122SMateusz Guzik {
250ee744122SMateusz Guzik 	struct uidinfo *uip;
251ee744122SMateusz Guzik 
252ee744122SMateusz Guzik 	uip = cred->cr_ruidinfo;
253ee744122SMateusz Guzik 	atomic_add_long(&uip->ui_vmsize, pincr);
254ee744122SMateusz Guzik }
255ee744122SMateusz Guzik 
256ee744122SMateusz Guzik bool
2573364c323SKonstantin Belousov swap_reserve(vm_ooffset_t incr)
2583364c323SKonstantin Belousov {
2593364c323SKonstantin Belousov 
260ef694c1aSEdward Tomasz Napierala 	return (swap_reserve_by_cred(incr, curthread->td_ucred));
2613364c323SKonstantin Belousov }
2623364c323SKonstantin Belousov 
263ee744122SMateusz Guzik bool
264ef694c1aSEdward Tomasz Napierala swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
2653364c323SKonstantin Belousov {
266e8bb589dSMatt Macy 	u_long r, s, prev, pincr;
267ee744122SMateusz Guzik #ifdef RACCT
268ee744122SMateusz Guzik 	int error;
269ee744122SMateusz Guzik #endif
270ee744122SMateusz Guzik 	int oc;
2713364c323SKonstantin Belousov 	static int curfail;
2723364c323SKonstantin Belousov 	static struct timeval lastfail;
2733364c323SKonstantin Belousov 
27426eed2aaSKonstantin Belousov 	KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK",
27526eed2aaSKonstantin Belousov 	    __func__, (uintmax_t)incr));
2763364c323SKonstantin Belousov 
277afcc55f3SEdward Tomasz Napierala #ifdef RACCT
278ee744122SMateusz Guzik 	if (RACCT_ENABLED()) {
2791ba5ad42SEdward Tomasz Napierala 		PROC_LOCK(curproc);
2801ba5ad42SEdward Tomasz Napierala 		error = racct_add(curproc, RACCT_SWAP, incr);
2811ba5ad42SEdward Tomasz Napierala 		PROC_UNLOCK(curproc);
2821ba5ad42SEdward Tomasz Napierala 		if (error != 0)
283ee744122SMateusz Guzik 			return (false);
2844b5c9cf6SEdward Tomasz Napierala 	}
285afcc55f3SEdward Tomasz Napierala #endif
2861ba5ad42SEdward Tomasz Napierala 
287e8bb589dSMatt Macy 	pincr = atop(incr);
288e8bb589dSMatt Macy 	prev = atomic_fetchadd_long(&swap_reserved, pincr);
289e8bb589dSMatt Macy 	r = prev + pincr;
290ee744122SMateusz Guzik 	s = swap_total;
291a6cc4c6eSKonstantin Belousov 	oc = atomic_load_int(&vm_overcommit);
292ee744122SMateusz Guzik 	if (r > s && (oc & SWAP_RESERVE_ALLOW_NONWIRED) != 0) {
293ee744122SMateusz Guzik 		s += vm_cnt.v_page_count - vm_cnt.v_free_reserved -
294e958ad4cSJeff Roberson 		    vm_wire_count();
295ee744122SMateusz Guzik 	}
296ee744122SMateusz Guzik 	if ((oc & SWAP_RESERVE_FORCE_ON) != 0 && r > s &&
297ee744122SMateusz Guzik 	    priv_check(curthread, PRIV_VM_SWAP_NOQUOTA) != 0) {
298e8bb589dSMatt Macy 		prev = atomic_fetchadd_long(&swap_reserved, -pincr);
29926eed2aaSKonstantin Belousov 		KASSERT(prev >= pincr,
30026eed2aaSKonstantin Belousov 		    ("swap_reserved < incr on overcommit fail"));
301ee744122SMateusz Guzik 		goto out_error;
3023364c323SKonstantin Belousov 	}
3033364c323SKonstantin Belousov 
304ee744122SMateusz Guzik 	if (!swap_reserve_by_cred_rlimit(pincr, cred, oc)) {
305ee744122SMateusz Guzik 		prev = atomic_fetchadd_long(&swap_reserved, -pincr);
30626eed2aaSKonstantin Belousov 		KASSERT(prev >= pincr,
30726eed2aaSKonstantin Belousov 		    ("swap_reserved < incr on overcommit fail"));
308ee744122SMateusz Guzik 		goto out_error;
309ee744122SMateusz Guzik 	}
310ee744122SMateusz Guzik 
311ee744122SMateusz Guzik 	return (true);
312ee744122SMateusz Guzik 
313ee744122SMateusz Guzik out_error:
314ee744122SMateusz Guzik 	if (ppsratecheck(&lastfail, &curfail, 1)) {
31526eed2aaSKonstantin Belousov 		printf("uid %d, pid %d: swap reservation "
31626eed2aaSKonstantin Belousov 		    "for %jd bytes failed\n",
317ee744122SMateusz Guzik 		    cred->cr_ruidinfo->ui_uid, curproc->p_pid, incr);
318ee744122SMateusz Guzik 	}
319afcc55f3SEdward Tomasz Napierala #ifdef RACCT
320ee744122SMateusz Guzik 	if (RACCT_ENABLED()) {
3211ba5ad42SEdward Tomasz Napierala 		PROC_LOCK(curproc);
3221ba5ad42SEdward Tomasz Napierala 		racct_sub(curproc, RACCT_SWAP, incr);
3231ba5ad42SEdward Tomasz Napierala 		PROC_UNLOCK(curproc);
3241ba5ad42SEdward Tomasz Napierala 	}
325afcc55f3SEdward Tomasz Napierala #endif
3261ba5ad42SEdward Tomasz Napierala 
327ee744122SMateusz Guzik 	return (false);
3283364c323SKonstantin Belousov }
3293364c323SKonstantin Belousov 
3303364c323SKonstantin Belousov void
3313364c323SKonstantin Belousov swap_reserve_force(vm_ooffset_t incr)
3323364c323SKonstantin Belousov {
333e8bb589dSMatt Macy 	u_long pincr;
3343364c323SKonstantin Belousov 
33526eed2aaSKonstantin Belousov 	KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK",
33626eed2aaSKonstantin Belousov 	    __func__, (uintmax_t)incr));
3373364c323SKonstantin Belousov 
338afcc55f3SEdward Tomasz Napierala #ifdef RACCT
339ee744122SMateusz Guzik 	if (RACCT_ENABLED()) {
340ee744122SMateusz Guzik 		PROC_LOCK(curproc);
3411ba5ad42SEdward Tomasz Napierala 		racct_add_force(curproc, RACCT_SWAP, incr);
342ee744122SMateusz Guzik 		PROC_UNLOCK(curproc);
343ee744122SMateusz Guzik 	}
344afcc55f3SEdward Tomasz Napierala #endif
345e8bb589dSMatt Macy 	pincr = atop(incr);
346e8bb589dSMatt Macy 	atomic_add_long(&swap_reserved, pincr);
347ee744122SMateusz Guzik 	swap_reserve_force_rlimit(pincr, curthread->td_ucred);
3483364c323SKonstantin Belousov }
3493364c323SKonstantin Belousov 
3503364c323SKonstantin Belousov void
3513364c323SKonstantin Belousov swap_release(vm_ooffset_t decr)
3523364c323SKonstantin Belousov {
353ef694c1aSEdward Tomasz Napierala 	struct ucred *cred;
3543364c323SKonstantin Belousov 
3553364c323SKonstantin Belousov 	PROC_LOCK(curproc);
356e8bb589dSMatt Macy 	cred = curproc->p_ucred;
357ef694c1aSEdward Tomasz Napierala 	swap_release_by_cred(decr, cred);
3583364c323SKonstantin Belousov 	PROC_UNLOCK(curproc);
3593364c323SKonstantin Belousov }
3603364c323SKonstantin Belousov 
3613364c323SKonstantin Belousov void
362ef694c1aSEdward Tomasz Napierala swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
3633364c323SKonstantin Belousov {
364ee744122SMateusz Guzik 	u_long pdecr;
365ee744122SMateusz Guzik #ifdef INVARIANTS
366ee744122SMateusz Guzik 	u_long prev;
367ee744122SMateusz Guzik #endif
3683364c323SKonstantin Belousov 
36926eed2aaSKonstantin Belousov 	KASSERT((decr & PAGE_MASK) == 0, ("%s: decr: %ju & PAGE_MASK",
37026eed2aaSKonstantin Belousov 	    __func__, (uintmax_t)decr));
3713364c323SKonstantin Belousov 
372e8bb589dSMatt Macy 	pdecr = atop(decr);
373ee744122SMateusz Guzik #ifdef INVARIANTS
374e8bb589dSMatt Macy 	prev = atomic_fetchadd_long(&swap_reserved, -pdecr);
375ee744122SMateusz Guzik 	KASSERT(prev >= pdecr, ("swap_reserved < decr"));
376ee744122SMateusz Guzik #else
377ee744122SMateusz Guzik 	atomic_subtract_long(&swap_reserved, pdecr);
378ee744122SMateusz Guzik #endif
3793364c323SKonstantin Belousov 
380ee744122SMateusz Guzik 	swap_release_by_cred_rlimit(pdecr, cred);
381e8bb589dSMatt Macy #ifdef RACCT
382e8bb589dSMatt Macy 	if (racct_enable)
3831ba5ad42SEdward Tomasz Napierala 		racct_sub_cred(cred, RACCT_SWAP, decr);
384e8bb589dSMatt Macy #endif
3853364c323SKonstantin Belousov }
3863364c323SKonstantin Belousov 
387f08b3099SKonstantin Belousov static int swap_pager_full = 2;	/* swap space exhaustion (task killing) */
3887dea2c2eSAlan Cox static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
389756a5412SGleb Smirnoff static struct mtx swbuf_mtx;	/* to sync nsw_wcount_async */
390756a5412SGleb Smirnoff static int nsw_wcount_async;	/* limit async write buffers */
391327f4e83SMatthew Dillon static int nsw_wcount_async_max;/* assigned maximum			*/
392183f8e1eSGleb Smirnoff int nsw_cluster_max; 		/* maximum VOP I/O allowed		*/
3931c7c3c6aSMatthew Dillon 
39489c241d1SGleb Smirnoff static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
3954c36e917SKonstantin Belousov SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
3964c36e917SKonstantin Belousov     CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
3974c36e917SKonstantin Belousov     "Maximum running async swap ops");
398d027ed2eSAlan Cox static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS);
399d027ed2eSAlan Cox SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD |
400d027ed2eSAlan Cox     CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A",
401d027ed2eSAlan Cox     "Swap Fragmentation Info");
40289c241d1SGleb Smirnoff 
4030cddd8f0SMatthew Dillon static struct sx sw_alloc_sx;
404327f4e83SMatthew Dillon 
4051c7c3c6aSMatthew Dillon /*
4061c7c3c6aSMatthew Dillon  * "named" and "unnamed" anon region objects.  Try to reduce the overhead
4071c7c3c6aSMatthew Dillon  * of searching a named list by hashing it just a little.
4081c7c3c6aSMatthew Dillon  */
4091c7c3c6aSMatthew Dillon 
4101c7c3c6aSMatthew Dillon #define NOBJLISTS		8
4111c7c3c6aSMatthew Dillon 
4121c7c3c6aSMatthew Dillon #define NOBJLIST(handle)	\
413af647ddeSBruce Evans 	(&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
4141c7c3c6aSMatthew Dillon 
4151c7c3c6aSMatthew Dillon static struct pagerlst	swap_pager_object_list[NOBJLISTS];
416756a5412SGleb Smirnoff static uma_zone_t swwbuf_zone;
417756a5412SGleb Smirnoff static uma_zone_t swrbuf_zone;
418f425ab8eSKonstantin Belousov static uma_zone_t swblk_zone;
419f425ab8eSKonstantin Belousov static uma_zone_t swpctrie_zone;
4201c7c3c6aSMatthew Dillon 
4211c7c3c6aSMatthew Dillon /*
4221c7c3c6aSMatthew Dillon  * pagerops for OBJT_SWAP - "swap pager".  Some ops are also global procedure
4231c7c3c6aSMatthew Dillon  * calls hooked from other parts of the VM system and do not appear here.
4241c7c3c6aSMatthew Dillon  * (see vm/swap_pager.h).
4251c7c3c6aSMatthew Dillon  */
426ff98689dSBruce Evans static vm_object_t
42711caded3SAlfred Perlstein 		swap_pager_alloc(void *handle, vm_ooffset_t size,
4283364c323SKonstantin Belousov 		    vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
42911caded3SAlfred Perlstein static void	swap_pager_dealloc(vm_object_t object);
430b0cd2017SGleb Smirnoff static int	swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
431b0cd2017SGleb Smirnoff     int *);
432b0cd2017SGleb Smirnoff static int	swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
433b0cd2017SGleb Smirnoff     int *, pgo_getpages_iodone_t, void *);
434f74be55eSDimitry Andric static void	swap_pager_putpages(vm_object_t, vm_page_t *, int, int, int *);
4355ea4972cSAlan Cox static boolean_t
4365ea4972cSAlan Cox 		swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
43711caded3SAlfred Perlstein static void	swap_pager_init(void);
43811caded3SAlfred Perlstein static void	swap_pager_unswapped(vm_page_t);
439b3fed13eSDavid Schultz static void	swap_pager_swapoff(struct swdevt *sp);
440fe7bcbafSKyle Evans static void	swap_pager_update_writecount(vm_object_t object,
441fe7bcbafSKyle Evans     vm_offset_t start, vm_offset_t end);
442fe7bcbafSKyle Evans static void	swap_pager_release_writecount(vm_object_t object,
443fe7bcbafSKyle Evans     vm_offset_t start, vm_offset_t end);
444baa1ccceSKonstantin Belousov static void	swap_pager_freespace_pgo(vm_object_t object, vm_pindex_t start,
4451390a5cbSKonstantin Belousov     vm_size_t size);
446f708ef1bSPoul-Henning Kamp 
447d474440aSKonstantin Belousov const struct pagerops swappagerops = {
44800a3fe96SKonstantin Belousov 	.pgo_kvme_type = KVME_TYPE_SWAP,
449e04e4bacSPoul-Henning Kamp 	.pgo_init =	swap_pager_init,	/* early system initialization of pager	*/
450e04e4bacSPoul-Henning Kamp 	.pgo_alloc =	swap_pager_alloc,	/* allocate an OBJT_SWAP object */
451e04e4bacSPoul-Henning Kamp 	.pgo_dealloc =	swap_pager_dealloc,	/* deallocate an OBJT_SWAP object */
452e04e4bacSPoul-Henning Kamp 	.pgo_getpages =	swap_pager_getpages,	/* pagein */
45390effb23SGleb Smirnoff 	.pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
454e04e4bacSPoul-Henning Kamp 	.pgo_putpages =	swap_pager_putpages,	/* pageout */
455e04e4bacSPoul-Henning Kamp 	.pgo_haspage =	swap_pager_haspage,	/* get backing store status for page */
456e04e4bacSPoul-Henning Kamp 	.pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
457fe7bcbafSKyle Evans 	.pgo_update_writecount = swap_pager_update_writecount,
458fe7bcbafSKyle Evans 	.pgo_release_writecount = swap_pager_release_writecount,
459baa1ccceSKonstantin Belousov 	.pgo_freespace = swap_pager_freespace_pgo,
4604b8365d7SKonstantin Belousov };
4614b8365d7SKonstantin Belousov 
4621c7c3c6aSMatthew Dillon /*
4631c7c3c6aSMatthew Dillon  * swap_*() routines are externally accessible.  swp_*() routines are
4641c7c3c6aSMatthew Dillon  * internal.
4651c7c3c6aSMatthew Dillon  */
466e9c0cc15SPoul-Henning Kamp static int nswap_lowat = 128;	/* in pages, swap_pager_almost_full warn */
467e9c0cc15SPoul-Henning Kamp static int nswap_hiwat = 512;	/* in pages, swap_pager_almost_full warn */
46826f9a767SRodney W. Grimes 
46907c348eaSAlan Cox SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
47007c348eaSAlan Cox     "Maximum size of a swap block in pages");
471cee313c4SRobert Watson 
472a5edd34aSPoul-Henning Kamp static void	swp_sizecheck(void);
47311caded3SAlfred Perlstein static void	swp_pager_async_iodone(struct buf *bp);
474230869e0SAlan Cox static bool	swp_pager_swblk_empty(struct swblk *sb, int start, int limit);
475abdab7b6SDoug Moore static void	swp_pager_free_empty_swblk(vm_object_t, struct swblk *sb);
47688ad2d7bSKonstantin Belousov static int	swapongeom(struct vnode *);
47759efee01SPoul-Henning Kamp static int	swaponvp(struct thread *, struct vnode *, u_long);
4780190c38bSKonstantin Belousov static int	swapoff_one(struct swdevt *sp, struct ucred *cred,
479e8dc2ba2SKonstantin Belousov 		    u_int flags);
48024a1cce3SDavid Greenman 
4811c7c3c6aSMatthew Dillon /*
4821c7c3c6aSMatthew Dillon  * Swap bitmap functions
4831c7c3c6aSMatthew Dillon  */
484a880104aSDoug Moore static void	swp_pager_freeswapspace(const struct page_range *range);
48536b01270SDoug Moore static daddr_t	swp_pager_getswapspace(int *npages);
4861c7c3c6aSMatthew Dillon 
4871c7c3c6aSMatthew Dillon /*
4881c7c3c6aSMatthew Dillon  * Metadata functions
4891c7c3c6aSMatthew Dillon  */
490d0b225d1SDoug Moore static daddr_t swp_pager_meta_build(struct pctrie_iter *, vm_object_t object,
491d0b225d1SDoug Moore 	vm_pindex_t, daddr_t, bool);
492645510e6SKonstantin Belousov static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t,
493baa1ccceSKonstantin Belousov     vm_size_t *);
494467057fcSDoug Moore static void swp_pager_meta_transfer(vm_object_t src, vm_object_t dst,
49594264705SDoug Moore     vm_pindex_t pindex, vm_pindex_t count);
49611caded3SAlfred Perlstein static void swp_pager_meta_free_all(vm_object_t);
49739f6d1e7SDoug Moore static daddr_t swp_pager_meta_lookup(struct pctrie_iter *, vm_pindex_t);
4981c7c3c6aSMatthew Dillon 
49978f1deefSAlan Cox static void
500a880104aSDoug Moore swp_pager_init_freerange(struct page_range *range)
50178f1deefSAlan Cox {
502a880104aSDoug Moore 	range->start = SWAPBLK_NONE;
503a880104aSDoug Moore 	range->num = 0;
50478f1deefSAlan Cox }
50578f1deefSAlan Cox 
50678f1deefSAlan Cox static void
507a880104aSDoug Moore swp_pager_update_freerange(struct page_range *range, daddr_t addr)
50878f1deefSAlan Cox {
509a880104aSDoug Moore 	if (range->start + range->num == addr) {
510a880104aSDoug Moore 		range->num++;
51178f1deefSAlan Cox 	} else {
512a880104aSDoug Moore 		swp_pager_freeswapspace(range);
513a880104aSDoug Moore 		range->start = addr;
514a880104aSDoug Moore 		range->num = 1;
51578f1deefSAlan Cox 	}
51678f1deefSAlan Cox }
51778f1deefSAlan Cox 
518f425ab8eSKonstantin Belousov static void *
519f425ab8eSKonstantin Belousov swblk_trie_alloc(struct pctrie *ptree)
520f425ab8eSKonstantin Belousov {
521f425ab8eSKonstantin Belousov 
522f425ab8eSKonstantin Belousov 	return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
523f425ab8eSKonstantin Belousov 	    M_USE_RESERVE : 0)));
524f425ab8eSKonstantin Belousov }
525f425ab8eSKonstantin Belousov 
526f425ab8eSKonstantin Belousov static void
527f425ab8eSKonstantin Belousov swblk_trie_free(struct pctrie *ptree, void *node)
528f425ab8eSKonstantin Belousov {
529f425ab8eSKonstantin Belousov 
530f425ab8eSKonstantin Belousov 	uma_zfree(swpctrie_zone, node);
531f425ab8eSKonstantin Belousov }
532f425ab8eSKonstantin Belousov 
53352b35140SDoug Moore static int
53452b35140SDoug Moore swblk_start(struct swblk *sb, vm_pindex_t pindex)
53552b35140SDoug Moore {
53652b35140SDoug Moore 	return (sb == NULL || sb->p >= pindex ?
53752b35140SDoug Moore 	    0 : pindex % SWAP_META_PAGES);
53852b35140SDoug Moore }
53952b35140SDoug Moore 
540f425ab8eSKonstantin Belousov PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
541f425ab8eSKonstantin Belousov 
54294264705SDoug Moore static struct swblk *
54394264705SDoug Moore swblk_lookup(vm_object_t object, vm_pindex_t pindex)
54494264705SDoug Moore {
54594264705SDoug Moore 	return (SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
54694264705SDoug Moore 	    rounddown(pindex, SWAP_META_PAGES)));
54794264705SDoug Moore }
54894264705SDoug Moore 
54994264705SDoug Moore static void
55094264705SDoug Moore swblk_lookup_remove(vm_object_t object, struct swblk *sb)
55194264705SDoug Moore {
55294264705SDoug Moore 	SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
55394264705SDoug Moore }
55494264705SDoug Moore 
55594264705SDoug Moore static bool
55694264705SDoug Moore swblk_is_empty(vm_object_t object)
55794264705SDoug Moore {
55894264705SDoug Moore 	return (pctrie_is_empty(&object->un_pager.swp.swp_blks));
55994264705SDoug Moore }
56094264705SDoug Moore 
56134951b0bSDoug Moore static struct swblk *
56234951b0bSDoug Moore swblk_iter_lookup_ge(struct pctrie_iter *blks, vm_pindex_t pindex)
56334951b0bSDoug Moore {
56434951b0bSDoug Moore 	return (SWAP_PCTRIE_ITER_LOOKUP_GE(blks,
56534951b0bSDoug Moore 	    rounddown(pindex, SWAP_META_PAGES)));
56634951b0bSDoug Moore }
56734951b0bSDoug Moore 
568d0b225d1SDoug Moore static void
569d0b225d1SDoug Moore swblk_iter_init_only(struct pctrie_iter *blks, vm_object_t object)
57052b35140SDoug Moore {
57152b35140SDoug Moore 	VM_OBJECT_ASSERT_LOCKED(object);
57252b35140SDoug Moore 	MPASS((object->flags & OBJ_SWAP) != 0);
57352b35140SDoug Moore 	pctrie_iter_init(blks, &object->un_pager.swp.swp_blks);
574d0b225d1SDoug Moore }
575d0b225d1SDoug Moore 
576d0b225d1SDoug Moore 
577d0b225d1SDoug Moore static struct swblk *
578d0b225d1SDoug Moore swblk_iter_init(struct pctrie_iter *blks, vm_object_t object,
579d0b225d1SDoug Moore     vm_pindex_t pindex)
580d0b225d1SDoug Moore {
581d0b225d1SDoug Moore 	swblk_iter_init_only(blks, object);
58234951b0bSDoug Moore 	return (swblk_iter_lookup_ge(blks, pindex));
58352b35140SDoug Moore }
58452b35140SDoug Moore 
58552b35140SDoug Moore static struct swblk *
586d0b225d1SDoug Moore swblk_iter_reinit(struct pctrie_iter *blks, vm_object_t object,
587d0b225d1SDoug Moore     vm_pindex_t pindex)
588d0b225d1SDoug Moore {
589d0b225d1SDoug Moore 	swblk_iter_init_only(blks, object);
590d0b225d1SDoug Moore 	return (SWAP_PCTRIE_ITER_LOOKUP(blks,
591d0b225d1SDoug Moore 	    rounddown(pindex, SWAP_META_PAGES)));
592d0b225d1SDoug Moore }
593d0b225d1SDoug Moore 
594d0b225d1SDoug Moore static struct swblk *
5956af02087SDoug Moore swblk_iter_limit_init(struct pctrie_iter *blks, vm_object_t object,
59652b35140SDoug Moore     vm_pindex_t pindex, vm_pindex_t limit)
59752b35140SDoug Moore {
59852b35140SDoug Moore 	VM_OBJECT_ASSERT_LOCKED(object);
59952b35140SDoug Moore 	MPASS((object->flags & OBJ_SWAP) != 0);
60052b35140SDoug Moore 	pctrie_iter_limit_init(blks, &object->un_pager.swp.swp_blks, limit);
60134951b0bSDoug Moore 	return (swblk_iter_lookup_ge(blks, pindex));
60252b35140SDoug Moore }
60352b35140SDoug Moore 
60452b35140SDoug Moore static struct swblk *
60552b35140SDoug Moore swblk_iter_next(struct pctrie_iter *blks)
60652b35140SDoug Moore {
60752b35140SDoug Moore 	return (SWAP_PCTRIE_ITER_JUMP_GE(blks, SWAP_META_PAGES));
60852b35140SDoug Moore }
60952b35140SDoug Moore 
610d0b225d1SDoug Moore static struct swblk *
611d0b225d1SDoug Moore swblk_iter_lookup(struct pctrie_iter *blks, vm_pindex_t pindex)
612d0b225d1SDoug Moore {
613d0b225d1SDoug Moore 	return (SWAP_PCTRIE_ITER_LOOKUP(blks,
614d0b225d1SDoug Moore 	    rounddown(pindex, SWAP_META_PAGES)));
615d0b225d1SDoug Moore }
616d0b225d1SDoug Moore 
617d0b225d1SDoug Moore static int
618d0b225d1SDoug Moore swblk_iter_insert(struct pctrie_iter *blks, struct swblk *sb)
619d0b225d1SDoug Moore {
620d0b225d1SDoug Moore 	return (SWAP_PCTRIE_ITER_INSERT(blks, sb));
621d0b225d1SDoug Moore }
622d0b225d1SDoug Moore 
62352b35140SDoug Moore static void
62452b35140SDoug Moore swblk_iter_remove(struct pctrie_iter *blks)
62552b35140SDoug Moore {
62652b35140SDoug Moore 	SWAP_PCTRIE_ITER_REMOVE(blks);
62752b35140SDoug Moore }
62852b35140SDoug Moore 
6291c7c3c6aSMatthew Dillon /*
6301c7c3c6aSMatthew Dillon  * SWP_SIZECHECK() -	update swap_pager_full indication
6311c7c3c6aSMatthew Dillon  *
63220d3034fSMatthew Dillon  *	update the swap_pager_almost_full indication and warn when we are
63320d3034fSMatthew Dillon  *	about to run out of swap space, using lowat/hiwat hysteresis.
63420d3034fSMatthew Dillon  *
63520d3034fSMatthew Dillon  *	Clear swap_pager_full ( task killing ) indication when lowat is met.
6361c7c3c6aSMatthew Dillon  *
6371c7c3c6aSMatthew Dillon  *	No restrictions on call
6381c7c3c6aSMatthew Dillon  *	This routine may not block.
6391c7c3c6aSMatthew Dillon  */
640a5edd34aSPoul-Henning Kamp static void
6412f249180SPoul-Henning Kamp swp_sizecheck(void)
6420d94caffSDavid Greenman {
64323955314SAlfred Perlstein 
6448f60c087SPoul-Henning Kamp 	if (swap_pager_avail < nswap_lowat) {
64520d3034fSMatthew Dillon 		if (swap_pager_almost_full == 0) {
6461af87c92SDavid Greenman 			printf("swap_pager: out of swap space\n");
64720d3034fSMatthew Dillon 			swap_pager_almost_full = 1;
6482b0d37a4SMatthew Dillon 		}
64920d3034fSMatthew Dillon 	} else {
65026f9a767SRodney W. Grimes 		swap_pager_full = 0;
6518f60c087SPoul-Henning Kamp 		if (swap_pager_avail > nswap_hiwat)
65220d3034fSMatthew Dillon 			swap_pager_almost_full = 0;
65326f9a767SRodney W. Grimes 	}
6541c7c3c6aSMatthew Dillon }
6551c7c3c6aSMatthew Dillon 
6561c7c3c6aSMatthew Dillon /*
6571c7c3c6aSMatthew Dillon  * SWAP_PAGER_INIT() -	initialize the swap pager!
6581c7c3c6aSMatthew Dillon  *
6591c7c3c6aSMatthew Dillon  *	Expected to be started from system init.  NOTE:  This code is run
6601c7c3c6aSMatthew Dillon  *	before much else so be careful what you depend on.  Most of the VM
6611c7c3c6aSMatthew Dillon  *	system has yet to be initialized at this point.
6621c7c3c6aSMatthew Dillon  */
663f5a12711SPoul-Henning Kamp static void
6642f249180SPoul-Henning Kamp swap_pager_init(void)
665df8bae1dSRodney W. Grimes {
6661c7c3c6aSMatthew Dillon 	/*
6671c7c3c6aSMatthew Dillon 	 * Initialize object lists
6681c7c3c6aSMatthew Dillon 	 */
6691c7c3c6aSMatthew Dillon 	int i;
6701c7c3c6aSMatthew Dillon 
6711c7c3c6aSMatthew Dillon 	for (i = 0; i < NOBJLISTS; ++i)
6721c7c3c6aSMatthew Dillon 		TAILQ_INIT(&swap_pager_object_list[i]);
67320da9c2eSPoul-Henning Kamp 	mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
67415719273SKonstantin Belousov 	sx_init(&sw_alloc_sx, "swspsx");
67504533e1eSKonstantin Belousov 	sx_init(&swdev_syscall_lock, "swsysc");
676183f8e1eSGleb Smirnoff 
677183f8e1eSGleb Smirnoff 	/*
678183f8e1eSGleb Smirnoff 	 * The nsw_cluster_max is constrained by the bp->b_pages[]
679183f8e1eSGleb Smirnoff 	 * array, which has maxphys / PAGE_SIZE entries, and our locally
680183f8e1eSGleb Smirnoff 	 * defined MAX_PAGEOUT_CLUSTER.   Also be aware that swap ops are
681183f8e1eSGleb Smirnoff 	 * constrained by the swap device interleave stripe size.
682183f8e1eSGleb Smirnoff 	 *
683183f8e1eSGleb Smirnoff 	 * Initialized early so that GEOM_ELI can see it.
684183f8e1eSGleb Smirnoff 	 */
685183f8e1eSGleb Smirnoff 	nsw_cluster_max = min(maxphys / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
6861c7c3c6aSMatthew Dillon }
68726f9a767SRodney W. Grimes 
688df8bae1dSRodney W. Grimes /*
6891c7c3c6aSMatthew Dillon  * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
6901c7c3c6aSMatthew Dillon  *
6911c7c3c6aSMatthew Dillon  *	Expected to be started from pageout process once, prior to entering
6921c7c3c6aSMatthew Dillon  *	its main loop.
693df8bae1dSRodney W. Grimes  */
69424a1cce3SDavid Greenman void
6952f249180SPoul-Henning Kamp swap_pager_swap_init(void)
696df8bae1dSRodney W. Grimes {
69761203277SDag-Erling Smørgrav 	unsigned long n, n2;
6980d94caffSDavid Greenman 
69926f9a767SRodney W. Grimes 	/*
7001c7c3c6aSMatthew Dillon 	 * Number of in-transit swap bp operations.  Don't
7011c7c3c6aSMatthew Dillon 	 * exhaust the pbufs completely.  Make sure we
7021c7c3c6aSMatthew Dillon 	 * initialize workable values (0 will work for hysteresis
7031c7c3c6aSMatthew Dillon 	 * but it isn't very efficient).
7041c7c3c6aSMatthew Dillon 	 *
705327f4e83SMatthew Dillon 	 * Currently we hardwire nsw_wcount_async to 4.  This limit is
706327f4e83SMatthew Dillon 	 * designed to prevent other I/O from having high latencies due to
707327f4e83SMatthew Dillon 	 * our pageout I/O.  The value 4 works well for one or two active swap
708327f4e83SMatthew Dillon 	 * devices but is probably a little low if you have more.  Even so,
709327f4e83SMatthew Dillon 	 * a higher value would probably generate only a limited improvement
710327f4e83SMatthew Dillon 	 * with three or four active swap devices since the system does not
711327f4e83SMatthew Dillon 	 * typically have to pageout at extreme bandwidths.   We will want
712327f4e83SMatthew Dillon 	 * at least 2 per swap devices, and 4 is a pretty good value if you
713327f4e83SMatthew Dillon 	 * have one NFS swap device due to the command/ack latency over NFS.
714327f4e83SMatthew Dillon 	 * So it all works out pretty well.
715183f8e1eSGleb Smirnoff 	 *
716183f8e1eSGleb Smirnoff 	 * nsw_cluster_max is initialized in swap_pager_init().
71726f9a767SRodney W. Grimes 	 */
718327f4e83SMatthew Dillon 
719327f4e83SMatthew Dillon 	nsw_wcount_async = 4;
720327f4e83SMatthew Dillon 	nsw_wcount_async_max = nsw_wcount_async;
721756a5412SGleb Smirnoff 	mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
722756a5412SGleb Smirnoff 
723756a5412SGleb Smirnoff 	swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
724756a5412SGleb Smirnoff 	swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
72524a1cce3SDavid Greenman 
7261c7c3c6aSMatthew Dillon 	/*
727a8233027SKonstantin Belousov 	 * Initialize our zone, taking the user's requested size or
728a8233027SKonstantin Belousov 	 * estimating the number we need based on the number of pages
729a8233027SKonstantin Belousov 	 * in the system.
7301c7c3c6aSMatthew Dillon 	 */
731a8233027SKonstantin Belousov 	n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
732a8233027SKonstantin Belousov 	    vm_cnt.v_page_count / 2;
733f425ab8eSKonstantin Belousov 	swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
7346c5f36ffSJeff Roberson 	    pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0);
735f425ab8eSKonstantin Belousov 	swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
7366c5f36ffSJeff Roberson 	    NULL, NULL, _Alignof(struct swblk) - 1, 0);
73722a5e6b9SDag-Erling Smørgrav 	n2 = n;
7388355f576SJeff Roberson 	do {
739f425ab8eSKonstantin Belousov 		if (uma_zone_reserve_kva(swblk_zone, n))
74061ce6eeeSAlfred Perlstein 			break;
74161ce6eeeSAlfred Perlstein 		/*
74261ce6eeeSAlfred Perlstein 		 * if the allocation failed, try a zone two thirds the
74361ce6eeeSAlfred Perlstein 		 * size of the previous attempt.
74461ce6eeeSAlfred Perlstein 		 */
74561ce6eeeSAlfred Perlstein 		n -= ((n + 2) / 3);
74661ce6eeeSAlfred Perlstein 	} while (n > 0);
74753faf5a7SKonstantin Belousov 
74853faf5a7SKonstantin Belousov 	/*
74953faf5a7SKonstantin Belousov 	 * Often uma_zone_reserve_kva() cannot reserve exactly the
75053faf5a7SKonstantin Belousov 	 * requested size.  Account for the difference when
75153faf5a7SKonstantin Belousov 	 * calculating swap_maxpages.
75253faf5a7SKonstantin Belousov 	 */
75353faf5a7SKonstantin Belousov 	n = uma_zone_get_max(swblk_zone);
75453faf5a7SKonstantin Belousov 
7551fffcd75SKonstantin Belousov 	if (n < n2)
756a8233027SKonstantin Belousov 		printf("Swap blk zone entries changed from %lu to %lu.\n",
757f425ab8eSKonstantin Belousov 		    n2, n);
758303fa05aSKonstantin Belousov 	/* absolute maximum we can handle assuming 100% efficiency */
75961203277SDag-Erling Smørgrav 	swap_maxpages = n * SWAP_META_PAGES;
760f425ab8eSKonstantin Belousov 	swzone = n * sizeof(struct swblk);
761f425ab8eSKonstantin Belousov 	if (!uma_zone_reserve_kva(swpctrie_zone, n))
762f425ab8eSKonstantin Belousov 		printf("Cannot reserve swap pctrie zone, "
763f425ab8eSKonstantin Belousov 		    "reduce kern.maxswzone.\n");
76424a1cce3SDavid Greenman }
76524a1cce3SDavid Greenman 
76628bc23abSKonstantin Belousov bool
76728bc23abSKonstantin Belousov swap_pager_init_object(vm_object_t object, void *handle, struct ucred *cred,
76828bc23abSKonstantin Belousov     vm_ooffset_t size, vm_ooffset_t offset)
76928bc23abSKonstantin Belousov {
77028bc23abSKonstantin Belousov 	if (cred != NULL) {
77128bc23abSKonstantin Belousov 		if (!swap_reserve_by_cred(size, cred))
77228bc23abSKonstantin Belousov 			return (false);
77328bc23abSKonstantin Belousov 		crhold(cred);
77428bc23abSKonstantin Belousov 	}
77528bc23abSKonstantin Belousov 
77628bc23abSKonstantin Belousov 	object->un_pager.swp.writemappings = 0;
77728bc23abSKonstantin Belousov 	object->handle = handle;
77828bc23abSKonstantin Belousov 	if (cred != NULL) {
77928bc23abSKonstantin Belousov 		object->cred = cred;
78028bc23abSKonstantin Belousov 		object->charge = size;
78128bc23abSKonstantin Belousov 	}
78228bc23abSKonstantin Belousov 	return (true);
78328bc23abSKonstantin Belousov }
78428bc23abSKonstantin Belousov 
785eb4d6a1bSKonstantin Belousov static vm_object_t
7864b8365d7SKonstantin Belousov swap_pager_alloc_init(objtype_t otype, void *handle, struct ucred *cred,
7874b8365d7SKonstantin Belousov     vm_ooffset_t size, vm_ooffset_t offset)
788eb4d6a1bSKonstantin Belousov {
789eb4d6a1bSKonstantin Belousov 	vm_object_t object;
790eb4d6a1bSKonstantin Belousov 
791f425ab8eSKonstantin Belousov 	/*
792f425ab8eSKonstantin Belousov 	 * The un_pager.swp.swp_blks trie is initialized by
793f425ab8eSKonstantin Belousov 	 * vm_object_allocate() to ensure the correct order of
794f425ab8eSKonstantin Belousov 	 * visibility to other threads.
795f425ab8eSKonstantin Belousov 	 */
7964b8365d7SKonstantin Belousov 	object = vm_object_allocate(otype, OFF_TO_IDX(offset +
797eb4d6a1bSKonstantin Belousov 	    PAGE_MASK + size));
798f425ab8eSKonstantin Belousov 
79928bc23abSKonstantin Belousov 	if (!swap_pager_init_object(object, handle, cred, size, offset)) {
80028bc23abSKonstantin Belousov 		vm_object_deallocate(object);
80128bc23abSKonstantin Belousov 		return (NULL);
802eb4d6a1bSKonstantin Belousov 	}
803eb4d6a1bSKonstantin Belousov 	return (object);
804eb4d6a1bSKonstantin Belousov }
805eb4d6a1bSKonstantin Belousov 
80624a1cce3SDavid Greenman /*
8071c7c3c6aSMatthew Dillon  * SWAP_PAGER_ALLOC() -	allocate a new OBJT_SWAP VM object and instantiate
8081c7c3c6aSMatthew Dillon  *			its metadata structures.
8091c7c3c6aSMatthew Dillon  *
8101c7c3c6aSMatthew Dillon  *	This routine is called from the mmap and fork code to create a new
811eb4d6a1bSKonstantin Belousov  *	OBJT_SWAP object.
8121c7c3c6aSMatthew Dillon  *
813eb4d6a1bSKonstantin Belousov  *	This routine must ensure that no live duplicate is created for
814eb4d6a1bSKonstantin Belousov  *	the named object request, which is protected against by
815eb4d6a1bSKonstantin Belousov  *	holding the sw_alloc_sx lock in case handle != NULL.
81624a1cce3SDavid Greenman  */
817f5a12711SPoul-Henning Kamp static vm_object_t
8186cde7a16SDavid Greenman swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
8193364c323SKonstantin Belousov     vm_ooffset_t offset, struct ucred *cred)
82024a1cce3SDavid Greenman {
82124a1cce3SDavid Greenman 	vm_object_t object;
8222f7af3dbSAlan Cox 
823eb4d6a1bSKonstantin Belousov 	if (handle != NULL) {
8241c7c3c6aSMatthew Dillon 		/*
8251c7c3c6aSMatthew Dillon 		 * Reference existing named region or allocate new one.  There
8261c7c3c6aSMatthew Dillon 		 * should not be a race here against swp_pager_meta_build()
8271c7c3c6aSMatthew Dillon 		 * as called from vm_page_remove() in regards to the lookup
8281c7c3c6aSMatthew Dillon 		 * of the handle.
8291c7c3c6aSMatthew Dillon 		 */
8300cddd8f0SMatthew Dillon 		sx_xlock(&sw_alloc_sx);
8311c7c3c6aSMatthew Dillon 		object = vm_pager_object_lookup(NOBJLIST(handle), handle);
832b5e8f167SAlan Cox 		if (object == NULL) {
8334b8365d7SKonstantin Belousov 			object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
8344b8365d7SKonstantin Belousov 			    size, offset);
835eb4d6a1bSKonstantin Belousov 			if (object != NULL) {
836eb4d6a1bSKonstantin Belousov 				TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
837eb4d6a1bSKonstantin Belousov 				    object, pager_object_list);
8383364c323SKonstantin Belousov 			}
83924a1cce3SDavid Greenman 		}
8400cddd8f0SMatthew Dillon 		sx_xunlock(&sw_alloc_sx);
84124a1cce3SDavid Greenman 	} else {
8424b8365d7SKonstantin Belousov 		object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
8434b8365d7SKonstantin Belousov 		    size, offset);
84424a1cce3SDavid Greenman 	}
84524a1cce3SDavid Greenman 	return (object);
846df8bae1dSRodney W. Grimes }
847df8bae1dSRodney W. Grimes 
84826f9a767SRodney W. Grimes /*
8491c7c3c6aSMatthew Dillon  * SWAP_PAGER_DEALLOC() -	remove swap metadata from object
8501c7c3c6aSMatthew Dillon  *
8511c7c3c6aSMatthew Dillon  *	The swap backing for the object is destroyed.  The code is
8521c7c3c6aSMatthew Dillon  *	designed such that we can reinstantiate it later, but this
8531c7c3c6aSMatthew Dillon  *	routine is typically called only when the entire object is
8541c7c3c6aSMatthew Dillon  *	about to be destroyed.
8551c7c3c6aSMatthew Dillon  *
85615523cf7SKonstantin Belousov  *	The object must be locked.
85726f9a767SRodney W. Grimes  */
858df8bae1dSRodney W. Grimes static void
8592f249180SPoul-Henning Kamp swap_pager_dealloc(vm_object_t object)
86026f9a767SRodney W. Grimes {
8614dcc5c2dSMatthew Dillon 
862eb4d6a1bSKonstantin Belousov 	VM_OBJECT_ASSERT_WLOCKED(object);
863eb4d6a1bSKonstantin Belousov 	KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
864eb4d6a1bSKonstantin Belousov 
86526f9a767SRodney W. Grimes 	/*
8661c7c3c6aSMatthew Dillon 	 * Remove from list right away so lookups will fail if we block for
8671c7c3c6aSMatthew Dillon 	 * pageout completion.
86826f9a767SRodney W. Grimes 	 */
86967388836SKonstantin Belousov 	if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
870eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WUNLOCK(object);
871eb4d6a1bSKonstantin Belousov 		sx_xlock(&sw_alloc_sx);
872eb4d6a1bSKonstantin Belousov 		TAILQ_REMOVE(NOBJLIST(object->handle), object,
873eb4d6a1bSKonstantin Belousov 		    pager_object_list);
874eb4d6a1bSKonstantin Belousov 		sx_xunlock(&sw_alloc_sx);
875eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WLOCK(object);
876bd228075SAlan Cox 	}
8771c7c3c6aSMatthew Dillon 
8781c7c3c6aSMatthew Dillon 	vm_object_pip_wait(object, "swpdea");
8791c7c3c6aSMatthew Dillon 
8801c7c3c6aSMatthew Dillon 	/*
8811c7c3c6aSMatthew Dillon 	 * Free all remaining metadata.  We only bother to free it from
8821c7c3c6aSMatthew Dillon 	 * the swap meta data.  We do not attempt to free swapblk's still
8831c7c3c6aSMatthew Dillon 	 * associated with vm_page_t's for this object.  We do not care
8841c7c3c6aSMatthew Dillon 	 * if paging is still in progress on some objects.
8851c7c3c6aSMatthew Dillon 	 */
8861c7c3c6aSMatthew Dillon 	swp_pager_meta_free_all(object);
887e735691bSJohn Baldwin 	object->handle = NULL;
888e735691bSJohn Baldwin 	object->type = OBJT_DEAD;
889fffc1c59SMark Johnston 
890fffc1c59SMark Johnston 	/*
891fffc1c59SMark Johnston 	 * Release the allocation charge.
892fffc1c59SMark Johnston 	 */
893fffc1c59SMark Johnston 	if (object->cred != NULL) {
894fffc1c59SMark Johnston 		swap_release_by_cred(object->charge, object->cred);
895fffc1c59SMark Johnston 		object->charge = 0;
896fffc1c59SMark Johnston 		crfree(object->cred);
897fffc1c59SMark Johnston 		object->cred = NULL;
898fffc1c59SMark Johnston 	}
899fffc1c59SMark Johnston 
900fffc1c59SMark Johnston 	/*
901fffc1c59SMark Johnston 	 * Hide the object from swap_pager_swapoff().
902fffc1c59SMark Johnston 	 */
9034b8365d7SKonstantin Belousov 	vm_object_clear_flag(object, OBJ_SWAP);
9041c7c3c6aSMatthew Dillon }
9051c7c3c6aSMatthew Dillon 
9061c7c3c6aSMatthew Dillon /************************************************************************
9071c7c3c6aSMatthew Dillon  *			SWAP PAGER BITMAP ROUTINES			*
9081c7c3c6aSMatthew Dillon  ************************************************************************/
9091c7c3c6aSMatthew Dillon 
9101c7c3c6aSMatthew Dillon /*
9111c7c3c6aSMatthew Dillon  * SWP_PAGER_GETSWAPSPACE() -	allocate raw swap space
9121c7c3c6aSMatthew Dillon  *
91336b01270SDoug Moore  *	Allocate swap for up to the requested number of pages.  The
91436b01270SDoug Moore  *	starting swap block number (a page index) is returned or
91536b01270SDoug Moore  *	SWAPBLK_NONE if the allocation failed.
9161c7c3c6aSMatthew Dillon  *
9171c7c3c6aSMatthew Dillon  *	Also has the side effect of advising that somebody made a mistake
9181c7c3c6aSMatthew Dillon  *	when they configured swap and didn't configure enough.
9191c7c3c6aSMatthew Dillon  *
92015523cf7SKonstantin Belousov  *	This routine may not sleep.
9218f60c087SPoul-Henning Kamp  *
9228f60c087SPoul-Henning Kamp  *	We allocate in round-robin fashion from the configured devices.
9231c7c3c6aSMatthew Dillon  */
924a5edd34aSPoul-Henning Kamp static daddr_t
92536b01270SDoug Moore swp_pager_getswapspace(int *io_npages)
9261c7c3c6aSMatthew Dillon {
9271c7c3c6aSMatthew Dillon 	daddr_t blk;
9288f60c087SPoul-Henning Kamp 	struct swdevt *sp;
92987ae0686SDoug Moore 	int mpages, npages;
9301c7c3c6aSMatthew Dillon 
93136b01270SDoug Moore 	KASSERT(*io_npages >= 1,
93236b01270SDoug Moore 	    ("%s: npages not positive", __func__));
9338f60c087SPoul-Henning Kamp 	blk = SWAPBLK_NONE;
93431c82722SDoug Moore 	mpages = *io_npages;
93531c82722SDoug Moore 	npages = imin(BLIST_MAX_ALLOC, mpages);
93620da9c2eSPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
9378f60c087SPoul-Henning Kamp 	sp = swdevhd;
93848e98a2aSDoug Moore 	while (!TAILQ_EMPTY(&swtailq)) {
9398f60c087SPoul-Henning Kamp 		if (sp == NULL)
9408f60c087SPoul-Henning Kamp 			sp = TAILQ_FIRST(&swtailq);
94148e98a2aSDoug Moore 		if ((sp->sw_flags & SW_CLOSING) == 0)
94287ae0686SDoug Moore 			blk = blist_alloc(sp->sw_blist, &npages, mpages);
94348e98a2aSDoug Moore 		if (blk != SWAPBLK_NONE)
94448e98a2aSDoug Moore 			break;
94548e98a2aSDoug Moore 		sp = TAILQ_NEXT(sp, sw_list);
94648e98a2aSDoug Moore 		if (swdevhd == sp) {
94736b01270SDoug Moore 			if (npages == 1)
94848e98a2aSDoug Moore 				break;
94987ae0686SDoug Moore 			mpages = npages - 1;
95048e98a2aSDoug Moore 			npages >>= 1;
95148e98a2aSDoug Moore 		}
95248e98a2aSDoug Moore 	}
9538f60c087SPoul-Henning Kamp 	if (blk != SWAPBLK_NONE) {
95448e98a2aSDoug Moore 		*io_npages = npages;
9558f60c087SPoul-Henning Kamp 		blk += sp->sw_first;
9568f60c087SPoul-Henning Kamp 		sp->sw_used += npages;
957d05bc129SAlan Cox 		swap_pager_avail -= npages;
9588f60c087SPoul-Henning Kamp 		swp_sizecheck();
9598f60c087SPoul-Henning Kamp 		swdevhd = TAILQ_NEXT(sp, sw_list);
96048e98a2aSDoug Moore 	} else {
9612b0d37a4SMatthew Dillon 		if (swap_pager_full != 2) {
96248e98a2aSDoug Moore 			printf("swp_pager_getswapspace(%d): failed\n",
96348e98a2aSDoug Moore 			    *io_npages);
9642b0d37a4SMatthew Dillon 			swap_pager_full = 2;
96520d3034fSMatthew Dillon 			swap_pager_almost_full = 1;
9662b0d37a4SMatthew Dillon 		}
9678f60c087SPoul-Henning Kamp 		swdevhd = NULL;
96848e98a2aSDoug Moore 	}
969d05bc129SAlan Cox 	mtx_unlock(&sw_dev_mtx);
9701c7c3c6aSMatthew Dillon 	return (blk);
97126f9a767SRodney W. Grimes }
97226f9a767SRodney W. Grimes 
973541a1175SAlan Cox static bool
974b3fed13eSDavid Schultz swp_pager_isondev(daddr_t blk, struct swdevt *sp)
9758f60c087SPoul-Henning Kamp {
9768f60c087SPoul-Henning Kamp 
977b3fed13eSDavid Schultz 	return (blk >= sp->sw_first && blk < sp->sw_end);
9788f60c087SPoul-Henning Kamp }
9798f60c087SPoul-Henning Kamp 
9804b03903aSPoul-Henning Kamp static void
9814b03903aSPoul-Henning Kamp swp_pager_strategy(struct buf *bp)
9824b03903aSPoul-Henning Kamp {
9834b03903aSPoul-Henning Kamp 	struct swdevt *sp;
9844b03903aSPoul-Henning Kamp 
98520da9c2eSPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
9864b03903aSPoul-Henning Kamp 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
987541a1175SAlan Cox 		if (swp_pager_isondev(bp->b_blkno, sp)) {
98820da9c2eSPoul-Henning Kamp 			mtx_unlock(&sw_dev_mtx);
9892cc718a1SKonstantin Belousov 			if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
9902cc718a1SKonstantin Belousov 			    unmapped_buf_allowed) {
9912cc718a1SKonstantin Belousov 				bp->b_data = unmapped_buf;
9922cc718a1SKonstantin Belousov 				bp->b_offset = 0;
9932cc718a1SKonstantin Belousov 			} else {
9942cc718a1SKonstantin Belousov 				pmap_qenter((vm_offset_t)bp->b_data,
9952cc718a1SKonstantin Belousov 				    &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
9962cc718a1SKonstantin Belousov 			}
9974b03903aSPoul-Henning Kamp 			sp->sw_strategy(bp, sp);
9984b03903aSPoul-Henning Kamp 			return;
9994b03903aSPoul-Henning Kamp 		}
10004b03903aSPoul-Henning Kamp 	}
100120da9c2eSPoul-Henning Kamp 	panic("Swapdev not found");
10024b03903aSPoul-Henning Kamp }
10034b03903aSPoul-Henning Kamp 
100426f9a767SRodney W. Grimes /*
10051c7c3c6aSMatthew Dillon  * SWP_PAGER_FREESWAPSPACE() -	free raw swap space
10061c7c3c6aSMatthew Dillon  *
10071c7c3c6aSMatthew Dillon  *	This routine returns the specified swap blocks back to the bitmap.
10081c7c3c6aSMatthew Dillon  *
100915523cf7SKonstantin Belousov  *	This routine may not sleep.
101026f9a767SRodney W. Grimes  */
1011a5edd34aSPoul-Henning Kamp static void
1012a880104aSDoug Moore swp_pager_freeswapspace(const struct page_range *range)
10130d94caffSDavid Greenman {
1014a880104aSDoug Moore 	daddr_t blk, npages;
10158f60c087SPoul-Henning Kamp 	struct swdevt *sp;
101692da00bbSMatthew Dillon 
1017a880104aSDoug Moore 	blk = range->start;
1018a880104aSDoug Moore 	npages = range->num;
1019230869e0SAlan Cox 	if (npages == 0)
1020230869e0SAlan Cox 		return;
10217645e885SAlan Cox 	mtx_lock(&sw_dev_mtx);
10227645e885SAlan Cox 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
1023541a1175SAlan Cox 		if (swp_pager_isondev(blk, sp)) {
102492da00bbSMatthew Dillon 			sp->sw_used -= npages;
102592da00bbSMatthew Dillon 			/*
10267645e885SAlan Cox 			 * If we are attempting to stop swapping on
10277645e885SAlan Cox 			 * this device, we don't want to mark any
10287645e885SAlan Cox 			 * blocks free lest they be reused.
102992da00bbSMatthew Dillon 			 */
10307645e885SAlan Cox 			if ((sp->sw_flags & SW_CLOSING) == 0) {
10317645e885SAlan Cox 				blist_free(sp->sw_blist, blk - sp->sw_first,
10327645e885SAlan Cox 				    npages);
10338f60c087SPoul-Henning Kamp 				swap_pager_avail += npages;
10341c7c3c6aSMatthew Dillon 				swp_sizecheck();
103526f9a767SRodney W. Grimes 			}
10367645e885SAlan Cox 			mtx_unlock(&sw_dev_mtx);
10377645e885SAlan Cox 			return;
10387645e885SAlan Cox 		}
10397645e885SAlan Cox 	}
10407645e885SAlan Cox 	panic("Swapdev not found");
10417645e885SAlan Cox }
10421c7c3c6aSMatthew Dillon 
104326f9a767SRodney W. Grimes /*
1044d027ed2eSAlan Cox  * SYSCTL_SWAP_FRAGMENTATION() -	produce raw swap space stats
1045d027ed2eSAlan Cox  */
1046d027ed2eSAlan Cox static int
1047d027ed2eSAlan Cox sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
1048d027ed2eSAlan Cox {
1049d027ed2eSAlan Cox 	struct sbuf sbuf;
1050d027ed2eSAlan Cox 	struct swdevt *sp;
1051d027ed2eSAlan Cox 	const char *devname;
1052d027ed2eSAlan Cox 	int error;
1053d027ed2eSAlan Cox 
1054d027ed2eSAlan Cox 	error = sysctl_wire_old_buffer(req, 0);
1055d027ed2eSAlan Cox 	if (error != 0)
1056d027ed2eSAlan Cox 		return (error);
1057d027ed2eSAlan Cox 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1058d027ed2eSAlan Cox 	mtx_lock(&sw_dev_mtx);
1059d027ed2eSAlan Cox 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
10607ad2a82dSMateusz Guzik 		if (vn_isdisk(sp->sw_vp))
1061d027ed2eSAlan Cox 			devname = devtoname(sp->sw_vp->v_rdev);
1062d027ed2eSAlan Cox 		else
1063d027ed2eSAlan Cox 			devname = "[file]";
1064d027ed2eSAlan Cox 		sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
1065d027ed2eSAlan Cox 		blist_stats(sp->sw_blist, &sbuf);
1066d027ed2eSAlan Cox 	}
1067d027ed2eSAlan Cox 	mtx_unlock(&sw_dev_mtx);
1068d027ed2eSAlan Cox 	error = sbuf_finish(&sbuf);
1069d027ed2eSAlan Cox 	sbuf_delete(&sbuf);
1070d027ed2eSAlan Cox 	return (error);
1071d027ed2eSAlan Cox }
1072d027ed2eSAlan Cox 
1073d027ed2eSAlan Cox /*
10741c7c3c6aSMatthew Dillon  * SWAP_PAGER_FREESPACE() -	frees swap blocks associated with a page
10751c7c3c6aSMatthew Dillon  *				range within an object.
10761c7c3c6aSMatthew Dillon  *
10771c7c3c6aSMatthew Dillon  *	This routine removes swapblk assignments from swap metadata.
10781c7c3c6aSMatthew Dillon  *
10791c7c3c6aSMatthew Dillon  *	The external callers of this routine typically have already destroyed
10801c7c3c6aSMatthew Dillon  *	or renamed vm_page_t's associated with this range in the object so
10811c7c3c6aSMatthew Dillon  *	we should be ok.
1082c25673ffSAttilio Rao  *
1083c25673ffSAttilio Rao  *	The object must be locked.
108426f9a767SRodney W. Grimes  */
1085baa1ccceSKonstantin Belousov void
1086baa1ccceSKonstantin Belousov swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size,
1087baa1ccceSKonstantin Belousov     vm_size_t *freed)
108826f9a767SRodney W. Grimes {
1089baa1ccceSKonstantin Belousov 	MPASS((object->flags & OBJ_SWAP) != 0);
109023955314SAlfred Perlstein 
1091baa1ccceSKonstantin Belousov 	swp_pager_meta_free(object, start, size, freed);
1092baa1ccceSKonstantin Belousov }
1093baa1ccceSKonstantin Belousov 
1094baa1ccceSKonstantin Belousov static void
1095baa1ccceSKonstantin Belousov swap_pager_freespace_pgo(vm_object_t object, vm_pindex_t start, vm_size_t size)
1096baa1ccceSKonstantin Belousov {
1097baa1ccceSKonstantin Belousov 	MPASS((object->flags & OBJ_SWAP) != 0);
1098baa1ccceSKonstantin Belousov 
1099baa1ccceSKonstantin Belousov 	swp_pager_meta_free(object, start, size, NULL);
11004dcc5c2dSMatthew Dillon }
11014dcc5c2dSMatthew Dillon 
11024dcc5c2dSMatthew Dillon /*
11034dcc5c2dSMatthew Dillon  * SWAP_PAGER_RESERVE() - reserve swap blocks in object
11044dcc5c2dSMatthew Dillon  *
11054dcc5c2dSMatthew Dillon  *	Assigns swap blocks to the specified range within the object.  The
110656ce850bSKonstantin Belousov  *	swap blocks are not zeroed.  Any previous swap assignment is destroyed.
11074dcc5c2dSMatthew Dillon  *
11084dcc5c2dSMatthew Dillon  *	Returns 0 on success, -1 on failure.
11094dcc5c2dSMatthew Dillon  */
11104dcc5c2dSMatthew Dillon int
1111686aa928SMark Johnston swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_pindex_t size)
11124dcc5c2dSMatthew Dillon {
1113d0b225d1SDoug Moore 	struct pctrie_iter blks;
1114a880104aSDoug Moore 	struct page_range range;
1115a880104aSDoug Moore 	daddr_t addr, blk;
1116686aa928SMark Johnston 	vm_pindex_t i, j;
1117686aa928SMark Johnston 	int n;
11184dcc5c2dSMatthew Dillon 
1119a880104aSDoug Moore 	swp_pager_init_freerange(&range);
112089f6b863SAttilio Rao 	VM_OBJECT_WLOCK(object);
1121d0b225d1SDoug Moore 	swblk_iter_init_only(&blks, object);
112248e98a2aSDoug Moore 	for (i = 0; i < size; i += n) {
1123686aa928SMark Johnston 		n = MIN(size - i, INT_MAX);
112436b01270SDoug Moore 		blk = swp_pager_getswapspace(&n);
112548e98a2aSDoug Moore 		if (blk == SWAPBLK_NONE) {
1126baa1ccceSKonstantin Belousov 			swp_pager_meta_free(object, start, i, NULL);
112789f6b863SAttilio Rao 			VM_OBJECT_WUNLOCK(object);
11284dcc5c2dSMatthew Dillon 			return (-1);
11294dcc5c2dSMatthew Dillon 		}
113048e98a2aSDoug Moore 		for (j = 0; j < n; ++j) {
1131d0b225d1SDoug Moore 			addr = swp_pager_meta_build(&blks, object,
113275694e65SDoug Moore 			    start + i + j, blk + j, false);
113378f1deefSAlan Cox 			if (addr != SWAPBLK_NONE)
1134a880104aSDoug Moore 				swp_pager_update_freerange(&range, addr);
113548e98a2aSDoug Moore 		}
11364dcc5c2dSMatthew Dillon 	}
1137a880104aSDoug Moore 	swp_pager_freeswapspace(&range);
113889f6b863SAttilio Rao 	VM_OBJECT_WUNLOCK(object);
11394dcc5c2dSMatthew Dillon 	return (0);
114026f9a767SRodney W. Grimes }
114126f9a767SRodney W. Grimes 
11420a47b48bSJohn Dyson /*
11431c7c3c6aSMatthew Dillon  * SWAP_PAGER_COPY() -  copy blocks from source pager to destination pager
11441c7c3c6aSMatthew Dillon  *			and destroy the source.
11451c7c3c6aSMatthew Dillon  *
11461c7c3c6aSMatthew Dillon  *	Copy any valid swapblks from the source to the destination.  In
11471c7c3c6aSMatthew Dillon  *	cases where both the source and destination have a valid swapblk,
11481c7c3c6aSMatthew Dillon  *	we keep the destination's.
11491c7c3c6aSMatthew Dillon  *
115015523cf7SKonstantin Belousov  *	This routine is allowed to sleep.  It may sleep allocating metadata
115198087a06SJeff Roberson  *	indirectly through swp_pager_meta_build().
11521c7c3c6aSMatthew Dillon  *
11531c7c3c6aSMatthew Dillon  *	The source object contains no vm_page_t's (which is just as well)
11541c7c3c6aSMatthew Dillon  *
115515523cf7SKonstantin Belousov  *	The source and destination objects must be locked.
115615523cf7SKonstantin Belousov  *	Both object locks may temporarily be released.
115726f9a767SRodney W. Grimes  */
115826f9a767SRodney W. Grimes void
11592f249180SPoul-Henning Kamp swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
11602f249180SPoul-Henning Kamp     vm_pindex_t offset, int destroysource)
116126f9a767SRodney W. Grimes {
116289f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(srcobject);
116389f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(dstobject);
11640cddd8f0SMatthew Dillon 
116526f9a767SRodney W. Grimes 	/*
11661c7c3c6aSMatthew Dillon 	 * If destroysource is set, we remove the source object from the
11671c7c3c6aSMatthew Dillon 	 * swap_pager internal queue now.
116826f9a767SRodney W. Grimes 	 */
116967388836SKonstantin Belousov 	if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
117067388836SKonstantin Belousov 	    srcobject->handle != NULL) {
1171eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WUNLOCK(srcobject);
1172eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WUNLOCK(dstobject);
1173eb4d6a1bSKonstantin Belousov 		sx_xlock(&sw_alloc_sx);
1174eb4d6a1bSKonstantin Belousov 		TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1175eb4d6a1bSKonstantin Belousov 		    pager_object_list);
1176eb4d6a1bSKonstantin Belousov 		sx_xunlock(&sw_alloc_sx);
1177eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WLOCK(dstobject);
1178eb4d6a1bSKonstantin Belousov 		VM_OBJECT_WLOCK(srcobject);
1179bd228075SAlan Cox 	}
118026f9a767SRodney W. Grimes 
11811c7c3c6aSMatthew Dillon 	/*
11824abca9bbSAlan Cox 	 * Transfer source to destination.
11831c7c3c6aSMatthew Dillon 	 */
118494264705SDoug Moore 	swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size);
118526f9a767SRodney W. Grimes 
118626f9a767SRodney W. Grimes 	/*
11871c7c3c6aSMatthew Dillon 	 * Free left over swap blocks in source.
118826f9a767SRodney W. Grimes 	 */
1189cb6757c0SMark Johnston 	if (destroysource)
11901c7c3c6aSMatthew Dillon 		swp_pager_meta_free_all(srcobject);
119126f9a767SRodney W. Grimes }
119226f9a767SRodney W. Grimes 
1193df8bae1dSRodney W. Grimes /*
119439f6d1e7SDoug Moore  * SWP_PAGER_HASPAGE_ITER() -	determine if we have good backing store for
119539f6d1e7SDoug Moore  *				the requested page, accessed with the given
119639f6d1e7SDoug Moore  *				iterator.
11971c7c3c6aSMatthew Dillon  *
11981c7c3c6aSMatthew Dillon  *	We determine whether good backing store exists for the requested
11991c7c3c6aSMatthew Dillon  *	page and return TRUE if it does, FALSE if it doesn't.
12001c7c3c6aSMatthew Dillon  *
12011c7c3c6aSMatthew Dillon  *	If TRUE, we also try to determine how much valid, contiguous backing
1202915d1b71SMark Johnston  *	store exists before and after the requested page.
1203df8bae1dSRodney W. Grimes  */
12045ea4972cSAlan Cox static boolean_t
120539f6d1e7SDoug Moore swp_pager_haspage_iter(struct pctrie_iter *blks, vm_pindex_t pindex,
120639f6d1e7SDoug Moore     int *before, int *after)
120726f9a767SRodney W. Grimes {
1208915d1b71SMark Johnston 	daddr_t blk, blk0;
1209915d1b71SMark Johnston 	int i;
121026f9a767SRodney W. Grimes 
12111c7c3c6aSMatthew Dillon 	/*
12121c7c3c6aSMatthew Dillon 	 * do we have good backing store at the requested index ?
12131c7c3c6aSMatthew Dillon 	 */
121439f6d1e7SDoug Moore 	blk0 = swp_pager_meta_lookup(blks, pindex);
12154dcc5c2dSMatthew Dillon 	if (blk0 == SWAPBLK_NONE) {
12161c7c3c6aSMatthew Dillon 		if (before)
121724a1cce3SDavid Greenman 			*before = 0;
12181c7c3c6aSMatthew Dillon 		if (after)
121924a1cce3SDavid Greenman 			*after = 0;
122026f9a767SRodney W. Grimes 		return (FALSE);
122126f9a767SRodney W. Grimes 	}
122226f9a767SRodney W. Grimes 
122326f9a767SRodney W. Grimes 	/*
12241c7c3c6aSMatthew Dillon 	 * find backwards-looking contiguous good backing store
1225e47ed70bSJohn Dyson 	 */
12261c7c3c6aSMatthew Dillon 	if (before != NULL) {
1227915d1b71SMark Johnston 		for (i = 1; i < SWB_NPAGES; i++) {
12281c7c3c6aSMatthew Dillon 			if (i > pindex)
12291c7c3c6aSMatthew Dillon 				break;
123039f6d1e7SDoug Moore 			blk = swp_pager_meta_lookup(blks, pindex - i);
12311c7c3c6aSMatthew Dillon 			if (blk != blk0 - i)
12321c7c3c6aSMatthew Dillon 				break;
1233ffc82b0aSJohn Dyson 		}
1234915d1b71SMark Johnston 		*before = i - 1;
123526f9a767SRodney W. Grimes 	}
123626f9a767SRodney W. Grimes 
123726f9a767SRodney W. Grimes 	/*
12381c7c3c6aSMatthew Dillon 	 * find forward-looking contiguous good backing store
123926f9a767SRodney W. Grimes 	 */
12401c7c3c6aSMatthew Dillon 	if (after != NULL) {
1241915d1b71SMark Johnston 		for (i = 1; i < SWB_NPAGES; i++) {
124239f6d1e7SDoug Moore 			blk = swp_pager_meta_lookup(blks, pindex + i);
12431c7c3c6aSMatthew Dillon 			if (blk != blk0 + i)
12441c7c3c6aSMatthew Dillon 				break;
124526f9a767SRodney W. Grimes 		}
1246915d1b71SMark Johnston 		*after = i - 1;
12471c7c3c6aSMatthew Dillon 	}
12481c7c3c6aSMatthew Dillon 	return (TRUE);
12491c7c3c6aSMatthew Dillon }
12501c7c3c6aSMatthew Dillon 
125139f6d1e7SDoug Moore /*
125239f6d1e7SDoug Moore  * SWAP_PAGER_HASPAGE() -	determine if we have good backing store for
125339f6d1e7SDoug Moore  *				the requested page, in the given object.
125439f6d1e7SDoug Moore  *
125539f6d1e7SDoug Moore  *	We determine whether good backing store exists for the requested
125639f6d1e7SDoug Moore  *	page and return TRUE if it does, FALSE if it doesn't.
125739f6d1e7SDoug Moore  *
125839f6d1e7SDoug Moore  *	If TRUE, we also try to determine how much valid, contiguous backing
125939f6d1e7SDoug Moore  *	store exists before and after the requested page.
126039f6d1e7SDoug Moore  */
126139f6d1e7SDoug Moore static boolean_t
126239f6d1e7SDoug Moore swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
126339f6d1e7SDoug Moore     int *after)
126439f6d1e7SDoug Moore {
126539f6d1e7SDoug Moore 	struct pctrie_iter blks;
126639f6d1e7SDoug Moore 
126739f6d1e7SDoug Moore 	swblk_iter_init_only(&blks, object);
126839f6d1e7SDoug Moore 	return (swp_pager_haspage_iter(&blks, pindex, before, after));
126939f6d1e7SDoug Moore }
127039f6d1e7SDoug Moore 
1271995730a6SDoug Moore static void
1272995730a6SDoug Moore swap_pager_unswapped_acct(vm_page_t m)
1273995730a6SDoug Moore {
1274995730a6SDoug Moore 	KASSERT((m->object->flags & OBJ_SWAP) != 0,
1275995730a6SDoug Moore 	    ("Free object not swappable"));
1276995730a6SDoug Moore 	if ((m->a.flags & PGA_SWAP_FREE) != 0)
1277995730a6SDoug Moore 		counter_u64_add(swap_free_completed, 1);
1278995730a6SDoug Moore 	vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
1279995730a6SDoug Moore 
1280995730a6SDoug Moore 	/*
1281995730a6SDoug Moore 	 * The meta data only exists if the object is OBJT_SWAP
1282995730a6SDoug Moore 	 * and even then might not be allocated yet.
1283995730a6SDoug Moore 	 */
1284995730a6SDoug Moore }
1285995730a6SDoug Moore 
12861c7c3c6aSMatthew Dillon /*
12871c7c3c6aSMatthew Dillon  * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
12881c7c3c6aSMatthew Dillon  *
12891c7c3c6aSMatthew Dillon  *	This removes any associated swap backing store, whether valid or
12901c7c3c6aSMatthew Dillon  *	not, from the page.
12911c7c3c6aSMatthew Dillon  *
12921c7c3c6aSMatthew Dillon  *	This routine is typically called when a page is made dirty, at
12931c7c3c6aSMatthew Dillon  *	which point any associated swap can be freed.  MADV_FREE also
12941c7c3c6aSMatthew Dillon  *	calls us in a special-case situation
12951c7c3c6aSMatthew Dillon  *
12961c7c3c6aSMatthew Dillon  *	NOTE!!!  If the page is clean and the swap was valid, the caller
12971c7c3c6aSMatthew Dillon  *	should make the page dirty before calling this routine.  This routine
12981c7c3c6aSMatthew Dillon  *	does NOT change the m->dirty status of the page.  Also: MADV_FREE
12991c7c3c6aSMatthew Dillon  *	depends on it.
13001c7c3c6aSMatthew Dillon  *
130115523cf7SKonstantin Belousov  *	This routine may not sleep.
1302c25673ffSAttilio Rao  *
1303a8081778SJeff Roberson  *	The object containing the page may be locked.
13041c7c3c6aSMatthew Dillon  */
13051c7c3c6aSMatthew Dillon static void
13062f249180SPoul-Henning Kamp swap_pager_unswapped(vm_page_t m)
13071c7c3c6aSMatthew Dillon {
1308a880104aSDoug Moore 	struct page_range range;
13098ecbf14bSDoug Moore 	struct swblk *sb;
1310a8081778SJeff Roberson 	vm_object_t obj;
13112f249180SPoul-Henning Kamp 
1312a8081778SJeff Roberson 	/*
1313a8081778SJeff Roberson 	 * Handle enqueing deferred frees first.  If we do not have the
1314a8081778SJeff Roberson 	 * object lock we wait for the page daemon to clear the space.
1315a8081778SJeff Roberson 	 */
1316a8081778SJeff Roberson 	obj = m->object;
1317a8081778SJeff Roberson 	if (!VM_OBJECT_WOWNED(obj)) {
1318a8081778SJeff Roberson 		VM_PAGE_OBJECT_BUSY_ASSERT(m);
1319a8081778SJeff Roberson 		/*
1320a8081778SJeff Roberson 		 * The caller is responsible for synchronization but we
1321a8081778SJeff Roberson 		 * will harmlessly handle races.  This is typically provided
1322a8081778SJeff Roberson 		 * by only calling unswapped() when a page transitions from
1323a8081778SJeff Roberson 		 * clean to dirty.
1324a8081778SJeff Roberson 		 */
1325a8081778SJeff Roberson 		if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1326a8081778SJeff Roberson 		    PGA_SWAP_SPACE) {
1327a8081778SJeff Roberson 			vm_page_aflag_set(m, PGA_SWAP_FREE);
1328a8081778SJeff Roberson 			counter_u64_add(swap_free_deferred, 1);
1329a8081778SJeff Roberson 		}
1330a8081778SJeff Roberson 		return;
1331a8081778SJeff Roberson 	}
1332995730a6SDoug Moore 	swap_pager_unswapped_acct(m);
13338ecbf14bSDoug Moore 
133494264705SDoug Moore 	sb = swblk_lookup(m->object, m->pindex);
13358ecbf14bSDoug Moore 	if (sb == NULL)
13368ecbf14bSDoug Moore 		return;
1337a880104aSDoug Moore 	range.start = sb->d[m->pindex % SWAP_META_PAGES];
1338a880104aSDoug Moore 	if (range.start == SWAPBLK_NONE)
13398ecbf14bSDoug Moore 		return;
1340a880104aSDoug Moore 	range.num = 1;
1341a880104aSDoug Moore 	swp_pager_freeswapspace(&range);
13428ecbf14bSDoug Moore 	sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
13438ecbf14bSDoug Moore 	swp_pager_free_empty_swblk(m->object, sb);
13441c7c3c6aSMatthew Dillon }
13451c7c3c6aSMatthew Dillon 
13461c7c3c6aSMatthew Dillon /*
1347915d1b71SMark Johnston  * swap_pager_getpages() - bring pages in from swap
13481c7c3c6aSMatthew Dillon  *
13493f060b60SMark Johnston  *	Attempt to page in the pages in array "ma" of length "count".  The
13503f060b60SMark Johnston  *	caller may optionally specify that additional pages preceding and
13513f060b60SMark Johnston  *	succeeding the specified range be paged in.  The number of such pages
13523f060b60SMark Johnston  *	is returned in the "rbehind" and "rahead" parameters, and they will
13533f060b60SMark Johnston  *	be in the inactive queue upon return.
13541c7c3c6aSMatthew Dillon  *
13553f060b60SMark Johnston  *	The pages in "ma" must be busied and will remain busied upon return.
13561c7c3c6aSMatthew Dillon  */
1357f708ef1bSPoul-Henning Kamp static int
135839f6d1e7SDoug Moore swap_pager_getpages_locked(struct pctrie_iter *blks, vm_object_t object,
135939f6d1e7SDoug Moore     vm_page_t *ma, int count, int *rbehind, int *rahead)
1360df8bae1dSRodney W. Grimes {
13611c7c3c6aSMatthew Dillon 	struct buf *bp;
1362b7b8a096SKonstantin Belousov 	vm_page_t bm, mpred, msucc, p;
1363915d1b71SMark Johnston 	vm_pindex_t pindex;
13641c7c3c6aSMatthew Dillon 	daddr_t blk;
1365b7b8a096SKonstantin Belousov 	int i, maxahead, maxbehind, reqcount;
13660d94caffSDavid Greenman 
1367c90d075bSMark Johnston 	VM_OBJECT_ASSERT_WLOCKED(object);
1368915d1b71SMark Johnston 	reqcount = count;
13691c7c3c6aSMatthew Dillon 
13704b8365d7SKonstantin Belousov 	KASSERT((object->flags & OBJ_SWAP) != 0,
13718ecbf14bSDoug Moore 	    ("%s: object not swappable", __func__));
137239f6d1e7SDoug Moore 	if (!swp_pager_haspage_iter(blks, ma[0]->pindex, &maxbehind,
137339f6d1e7SDoug Moore 	    &maxahead)) {
1374d6e13f3bSJeff Roberson 		VM_OBJECT_WUNLOCK(object);
1375915d1b71SMark Johnston 		return (VM_PAGER_FAIL);
1376d6e13f3bSJeff Roberson 	}
1377915d1b71SMark Johnston 
137898087a06SJeff Roberson 	KASSERT(reqcount - 1 <= maxahead,
137998087a06SJeff Roberson 	    ("page count %d extends beyond swap block", reqcount));
138098087a06SJeff Roberson 
138198087a06SJeff Roberson 	/*
138298087a06SJeff Roberson 	 * Do not transfer any pages other than those that are xbusied
138398087a06SJeff Roberson 	 * when running during a split or collapse operation.  This
138498087a06SJeff Roberson 	 * prevents clustering from re-creating pages which are being
138598087a06SJeff Roberson 	 * moved into another object.
138698087a06SJeff Roberson 	 */
138798087a06SJeff Roberson 	if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
138898087a06SJeff Roberson 		maxahead = reqcount - 1;
138998087a06SJeff Roberson 		maxbehind = 0;
139098087a06SJeff Roberson 	}
139198087a06SJeff Roberson 
1392915d1b71SMark Johnston 	/*
1393915d1b71SMark Johnston 	 * Clip the readahead and readbehind ranges to exclude resident pages.
1394915d1b71SMark Johnston 	 */
1395915d1b71SMark Johnston 	if (rahead != NULL) {
1396dd9cb6daSMark Johnston 		*rahead = imin(*rahead, maxahead - (reqcount - 1));
13973f060b60SMark Johnston 		pindex = ma[reqcount - 1]->pindex;
13983f060b60SMark Johnston 		msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1399915d1b71SMark Johnston 		if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1400915d1b71SMark Johnston 			*rahead = msucc->pindex - pindex - 1;
1401915d1b71SMark Johnston 	}
1402915d1b71SMark Johnston 	if (rbehind != NULL) {
1403dd9cb6daSMark Johnston 		*rbehind = imin(*rbehind, maxbehind);
14043f060b60SMark Johnston 		pindex = ma[0]->pindex;
14053f060b60SMark Johnston 		mpred = TAILQ_PREV(ma[0], pglist, listq);
1406915d1b71SMark Johnston 		if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1407915d1b71SMark Johnston 			*rbehind = pindex - mpred->pindex - 1;
1408915d1b71SMark Johnston 	}
1409915d1b71SMark Johnston 
1410b7b8a096SKonstantin Belousov 	bm = ma[0];
1411b7b8a096SKonstantin Belousov 	for (i = 0; i < count; i++)
1412b7b8a096SKonstantin Belousov 		ma[i]->oflags |= VPO_SWAPINPROG;
1413b7b8a096SKonstantin Belousov 
1414915d1b71SMark Johnston 	/*
1415915d1b71SMark Johnston 	 * Allocate readahead and readbehind pages.
1416915d1b71SMark Johnston 	 */
1417b7b8a096SKonstantin Belousov 	if (rbehind != NULL) {
1418b7b8a096SKonstantin Belousov 		for (i = 1; i <= *rbehind; i++) {
14193f060b60SMark Johnston 			p = vm_page_alloc(object, ma[0]->pindex - i,
14207667839aSAlan Cox 			    VM_ALLOC_NORMAL);
1421b7b8a096SKonstantin Belousov 			if (p == NULL)
1422915d1b71SMark Johnston 				break;
1423b7b8a096SKonstantin Belousov 			p->oflags |= VPO_SWAPINPROG;
1424b7b8a096SKonstantin Belousov 			bm = p;
1425915d1b71SMark Johnston 		}
1426b7b8a096SKonstantin Belousov 		*rbehind = i - 1;
1427915d1b71SMark Johnston 	}
1428915d1b71SMark Johnston 	if (rahead != NULL) {
1429915d1b71SMark Johnston 		for (i = 0; i < *rahead; i++) {
1430915d1b71SMark Johnston 			p = vm_page_alloc(object,
14313f060b60SMark Johnston 			    ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1432915d1b71SMark Johnston 			if (p == NULL)
1433915d1b71SMark Johnston 				break;
1434b7b8a096SKonstantin Belousov 			p->oflags |= VPO_SWAPINPROG;
1435915d1b71SMark Johnston 		}
1436915d1b71SMark Johnston 		*rahead = i;
1437915d1b71SMark Johnston 	}
1438915d1b71SMark Johnston 	if (rbehind != NULL)
1439915d1b71SMark Johnston 		count += *rbehind;
1440915d1b71SMark Johnston 	if (rahead != NULL)
1441915d1b71SMark Johnston 		count += *rahead;
1442915d1b71SMark Johnston 
1443915d1b71SMark Johnston 	vm_object_pip_add(object, count);
1444915d1b71SMark Johnston 
1445b7b8a096SKonstantin Belousov 	pindex = bm->pindex;
144639f6d1e7SDoug Moore 	blk = swp_pager_meta_lookup(blks, pindex);
1447915d1b71SMark Johnston 	KASSERT(blk != SWAPBLK_NONE,
1448915d1b71SMark Johnston 	    ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1449915d1b71SMark Johnston 
1450915d1b71SMark Johnston 	VM_OBJECT_WUNLOCK(object);
1451756a5412SGleb Smirnoff 	bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1452cd853791SKonstantin Belousov 	MPASS((bp->b_flags & B_MAXPHYS) != 0);
1453b7b8a096SKonstantin Belousov 	/* Pages cannot leave the object while busy. */
1454b7b8a096SKonstantin Belousov 	for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1455b7b8a096SKonstantin Belousov 		MPASS(p->pindex == bm->pindex + i);
1456b7b8a096SKonstantin Belousov 		bp->b_pages[i] = p;
1457b7b8a096SKonstantin Belousov 	}
1458915d1b71SMark Johnston 
1459915d1b71SMark Johnston 	bp->b_flags |= B_PAGING;
146021144e3bSPoul-Henning Kamp 	bp->b_iocmd = BIO_READ;
14611c7c3c6aSMatthew Dillon 	bp->b_iodone = swp_pager_async_iodone;
1462fdcc1cc0SJohn Baldwin 	bp->b_rcred = crhold(thread0.td_ucred);
1463fdcc1cc0SJohn Baldwin 	bp->b_wcred = crhold(thread0.td_ucred);
1464b0cd2017SGleb Smirnoff 	bp->b_blkno = blk;
1465b0cd2017SGleb Smirnoff 	bp->b_bcount = PAGE_SIZE * count;
1466b0cd2017SGleb Smirnoff 	bp->b_bufsize = PAGE_SIZE * count;
1467b0cd2017SGleb Smirnoff 	bp->b_npages = count;
1468915d1b71SMark Johnston 	bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1469915d1b71SMark Johnston 	bp->b_pgafter = rahead != NULL ? *rahead : 0;
147026f9a767SRodney W. Grimes 
147183c9dea1SGleb Smirnoff 	VM_CNT_INC(v_swapin);
147283c9dea1SGleb Smirnoff 	VM_CNT_ADD(v_swappgsin, count);
14731c7c3c6aSMatthew Dillon 
14741c7c3c6aSMatthew Dillon 	/*
14751c7c3c6aSMatthew Dillon 	 * perform the I/O.  NOTE!!!  bp cannot be considered valid after
14761c7c3c6aSMatthew Dillon 	 * this point because we automatically release it on completion.
14771c7c3c6aSMatthew Dillon 	 * Instead, we look at the one page we are interested in which we
14781c7c3c6aSMatthew Dillon 	 * still hold a lock on even through the I/O completion.
14791c7c3c6aSMatthew Dillon 	 *
14803f060b60SMark Johnston 	 * The other pages in our ma[] array are also released on completion,
14811c7c3c6aSMatthew Dillon 	 * so we cannot assume they are valid anymore either.
14821c7c3c6aSMatthew Dillon 	 *
1483c37a77eeSPoul-Henning Kamp 	 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
14841c7c3c6aSMatthew Dillon 	 */
1485b890cb2cSPeter Wemm 	BUF_KERNPROC(bp);
14864b03903aSPoul-Henning Kamp 	swp_pager_strategy(bp);
148726f9a767SRodney W. Grimes 
148826f9a767SRodney W. Grimes 	/*
1489915d1b71SMark Johnston 	 * Wait for the pages we want to complete.  VPO_SWAPINPROG is always
14901c7c3c6aSMatthew Dillon 	 * cleared on completion.  If an I/O error occurs, SWAPBLK_NONE
1491915d1b71SMark Johnston 	 * is set in the metadata for each page in the request.
149226f9a767SRodney W. Grimes 	 */
149389f6b863SAttilio Rao 	VM_OBJECT_WLOCK(object);
1494d6e13f3bSJeff Roberson 	/* This could be implemented more efficiently with aflags */
14953f060b60SMark Johnston 	while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
14963f060b60SMark Johnston 		ma[0]->oflags |= VPO_SWAPSLEEP;
149783c9dea1SGleb Smirnoff 		VM_CNT_INC(v_intrans);
1498cf27e0d1SJeff Roberson 		if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1499c7aebda8SAttilio Rao 		    "swread", hz * 20)) {
15009bd86a98SBruce M Simpson 			printf(
1501c5690651SPoul-Henning Kamp "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1502c5690651SPoul-Henning Kamp 			    bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
15031c7c3c6aSMatthew Dillon 		}
15041b119d9dSDavid Greenman 	}
1505d6e13f3bSJeff Roberson 	VM_OBJECT_WUNLOCK(object);
150626f9a767SRodney W. Grimes 
150726f9a767SRodney W. Grimes 	/*
1508b0cd2017SGleb Smirnoff 	 * If we had an unrecoverable read error pages will not be valid.
150926f9a767SRodney W. Grimes 	 */
1510915d1b71SMark Johnston 	for (i = 0; i < reqcount; i++)
15113f060b60SMark Johnston 		if (ma[i]->valid != VM_PAGE_BITS_ALL)
15121c7c3c6aSMatthew Dillon 			return (VM_PAGER_ERROR);
1513b0cd2017SGleb Smirnoff 
15141c7c3c6aSMatthew Dillon 	return (VM_PAGER_OK);
15151c7c3c6aSMatthew Dillon 
15161c7c3c6aSMatthew Dillon 	/*
15171c7c3c6aSMatthew Dillon 	 * A final note: in a low swap situation, we cannot deallocate swap
15181c7c3c6aSMatthew Dillon 	 * and mark a page dirty here because the caller is likely to mark
15191c7c3c6aSMatthew Dillon 	 * the page clean when we return, causing the page to possibly revert
15201c7c3c6aSMatthew Dillon 	 * to all-zero's later.
15211c7c3c6aSMatthew Dillon 	 */
1522df8bae1dSRodney W. Grimes }
1523df8bae1dSRodney W. Grimes 
1524c90d075bSMark Johnston static int
1525c90d075bSMark Johnston swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count,
1526c90d075bSMark Johnston     int *rbehind, int *rahead)
1527c90d075bSMark Johnston {
152839f6d1e7SDoug Moore 	struct pctrie_iter blks;
1529c90d075bSMark Johnston 
1530c90d075bSMark Johnston 	VM_OBJECT_WLOCK(object);
153139f6d1e7SDoug Moore 	swblk_iter_init_only(&blks, object);
153239f6d1e7SDoug Moore 	return (swap_pager_getpages_locked(&blks, object, ma, count, rbehind,
153339f6d1e7SDoug Moore 	    rahead));
1534c90d075bSMark Johnston }
1535c90d075bSMark Johnston 
15361c7c3c6aSMatthew Dillon /*
153790effb23SGleb Smirnoff  * 	swap_pager_getpages_async():
153890effb23SGleb Smirnoff  *
153990effb23SGleb Smirnoff  *	Right now this is emulation of asynchronous operation on top of
154090effb23SGleb Smirnoff  *	swap_pager_getpages().
154190effb23SGleb Smirnoff  */
154290effb23SGleb Smirnoff static int
15433f060b60SMark Johnston swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1544b0cd2017SGleb Smirnoff     int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
154590effb23SGleb Smirnoff {
154690effb23SGleb Smirnoff 	int r, error;
154790effb23SGleb Smirnoff 
15483f060b60SMark Johnston 	r = swap_pager_getpages(object, ma, count, rbehind, rahead);
154990effb23SGleb Smirnoff 	switch (r) {
155090effb23SGleb Smirnoff 	case VM_PAGER_OK:
155190effb23SGleb Smirnoff 		error = 0;
155290effb23SGleb Smirnoff 		break;
155390effb23SGleb Smirnoff 	case VM_PAGER_ERROR:
155490effb23SGleb Smirnoff 		error = EIO;
155590effb23SGleb Smirnoff 		break;
155690effb23SGleb Smirnoff 	case VM_PAGER_FAIL:
155790effb23SGleb Smirnoff 		error = EINVAL;
155890effb23SGleb Smirnoff 		break;
155990effb23SGleb Smirnoff 	default:
1560d9328101SGleb Smirnoff 		panic("unhandled swap_pager_getpages() error %d", r);
156190effb23SGleb Smirnoff 	}
15623f060b60SMark Johnston 	(iodone)(arg, ma, count, error);
156390effb23SGleb Smirnoff 
156490effb23SGleb Smirnoff 	return (r);
156590effb23SGleb Smirnoff }
156690effb23SGleb Smirnoff 
156790effb23SGleb Smirnoff /*
15681c7c3c6aSMatthew Dillon  *	swap_pager_putpages:
15691c7c3c6aSMatthew Dillon  *
15701c7c3c6aSMatthew Dillon  *	Assign swap (if necessary) and initiate I/O on the specified pages.
15711c7c3c6aSMatthew Dillon  *
1572ea3aecf5SPeter Wemm  *	In a low memory situation we may block in VOP_STRATEGY(), but the new
15731c7c3c6aSMatthew Dillon  *	vm_page reservation system coupled with properly written VFS devices
15741c7c3c6aSMatthew Dillon  *	should ensure that no low-memory deadlock occurs.  This is an area
15751c7c3c6aSMatthew Dillon  *	which needs work.
15761c7c3c6aSMatthew Dillon  *
15771c7c3c6aSMatthew Dillon  *	The parent has N vm_object_pip_add() references prior to
15781c7c3c6aSMatthew Dillon  *	calling us and will remove references for rtvals[] that are
15791c7c3c6aSMatthew Dillon  *	not set to VM_PAGER_PEND.  We need to remove the rest on I/O
15801c7c3c6aSMatthew Dillon  *	completion.
15811c7c3c6aSMatthew Dillon  *
15821c7c3c6aSMatthew Dillon  *	The parent has soft-busy'd the pages it passes us and will unbusy
158323612f0dSDoug Moore  *	those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
15841c7c3c6aSMatthew Dillon  *	We need to unbusy the rest on I/O completion.
15851c7c3c6aSMatthew Dillon  */
1586d635a37fSWarner Losh static void
15873f060b60SMark Johnston swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1588e065e87cSKonstantin Belousov     int flags, int *rtvals)
1589df8bae1dSRodney W. Grimes {
1590d0b225d1SDoug Moore 	struct pctrie_iter blks;
1591a880104aSDoug Moore 	struct page_range range;
159223612f0dSDoug Moore 	struct buf *bp;
1593a880104aSDoug Moore 	daddr_t addr, blk;
159423612f0dSDoug Moore 	vm_page_t mreq;
159523612f0dSDoug Moore 	int i, j, n;
159623612f0dSDoug Moore 	bool async;
1597df8bae1dSRodney W. Grimes 
159823612f0dSDoug Moore 	KASSERT(count == 0 || ma[0]->object == object,
159923612f0dSDoug Moore 	    ("%s: object mismatch %p/%p",
160023612f0dSDoug Moore 	    __func__, object, ma[0]->object));
1601ee3dc7d7SAlan Cox 
160289f6b863SAttilio Rao 	VM_OBJECT_WUNLOCK(object);
160323612f0dSDoug Moore 	async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
1604a880104aSDoug Moore 	swp_pager_init_freerange(&range);
160526f9a767SRodney W. Grimes 
16061c7c3c6aSMatthew Dillon 	/*
16071c7c3c6aSMatthew Dillon 	 * Assign swap blocks and issue I/O.  We reallocate swap on the fly.
16081c7c3c6aSMatthew Dillon 	 * The page is left dirty until the pageout operation completes
16091c7c3c6aSMatthew Dillon 	 * successfully.
16101c7c3c6aSMatthew Dillon 	 */
16111c7c3c6aSMatthew Dillon 	for (i = 0; i < count; i += n) {
161231c82722SDoug Moore 		/* Maximum I/O size is limited by maximum swap block size. */
161331c82722SDoug Moore 		n = min(count - i, nsw_cluster_max);
16141c7c3c6aSMatthew Dillon 
161523612f0dSDoug Moore 		if (async) {
1616756a5412SGleb Smirnoff 			mtx_lock(&swbuf_mtx);
1617756a5412SGleb Smirnoff 			while (nsw_wcount_async == 0)
1618756a5412SGleb Smirnoff 				msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1619756a5412SGleb Smirnoff 				    "swbufa", 0);
1620756a5412SGleb Smirnoff 			nsw_wcount_async--;
1621756a5412SGleb Smirnoff 			mtx_unlock(&swbuf_mtx);
1622327f4e83SMatthew Dillon 		}
1623725b4ff0SMark Johnston 
1624725b4ff0SMark Johnston 		/* Get a block of swap of size up to size n. */
162536b01270SDoug Moore 		blk = swp_pager_getswapspace(&n);
1626725b4ff0SMark Johnston 		if (blk == SWAPBLK_NONE) {
1627725b4ff0SMark Johnston 			mtx_lock(&swbuf_mtx);
1628725b4ff0SMark Johnston 			if (++nsw_wcount_async == 1)
1629725b4ff0SMark Johnston 				wakeup(&nsw_wcount_async);
1630725b4ff0SMark Johnston 			mtx_unlock(&swbuf_mtx);
1631725b4ff0SMark Johnston 			for (j = 0; j < n; ++j)
1632725b4ff0SMark Johnston 				rtvals[i + j] = VM_PAGER_FAIL;
1633725b4ff0SMark Johnston 			continue;
1634725b4ff0SMark Johnston 		}
163554291f7dSAlan Cox 		VM_OBJECT_WLOCK(object);
1636d0b225d1SDoug Moore 		swblk_iter_init_only(&blks, object);
1637725b4ff0SMark Johnston 		for (j = 0; j < n; ++j) {
1638725b4ff0SMark Johnston 			mreq = ma[i + j];
1639725b4ff0SMark Johnston 			vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1640d0b225d1SDoug Moore 			KASSERT(mreq->object == object,
1641d0b225d1SDoug Moore 			    ("%s: object mismatch %p/%p",
1642d0b225d1SDoug Moore 			    __func__, mreq->object, object));
1643d0b225d1SDoug Moore 			addr = swp_pager_meta_build(&blks, object,
1644d0b225d1SDoug Moore 			    mreq->pindex, blk + j, false);
1645725b4ff0SMark Johnston 			if (addr != SWAPBLK_NONE)
1646a880104aSDoug Moore 				swp_pager_update_freerange(&range, addr);
1647725b4ff0SMark Johnston 			MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1648725b4ff0SMark Johnston 			mreq->oflags |= VPO_SWAPINPROG;
1649725b4ff0SMark Johnston 		}
1650725b4ff0SMark Johnston 		VM_OBJECT_WUNLOCK(object);
1651725b4ff0SMark Johnston 
1652756a5412SGleb Smirnoff 		bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1653cd853791SKonstantin Belousov 		MPASS((bp->b_flags & B_MAXPHYS) != 0);
165423612f0dSDoug Moore 		if (async)
1655cd853791SKonstantin Belousov 			bp->b_flags |= B_ASYNC;
16565e04322aSPoul-Henning Kamp 		bp->b_flags |= B_PAGING;
1657912e4ae9SPoul-Henning Kamp 		bp->b_iocmd = BIO_WRITE;
165826f9a767SRodney W. Grimes 
1659fdcc1cc0SJohn Baldwin 		bp->b_rcred = crhold(thread0.td_ucred);
1660fdcc1cc0SJohn Baldwin 		bp->b_wcred = crhold(thread0.td_ucred);
16611c7c3c6aSMatthew Dillon 		bp->b_bcount = PAGE_SIZE * n;
16621c7c3c6aSMatthew Dillon 		bp->b_bufsize = PAGE_SIZE * n;
16631c7c3c6aSMatthew Dillon 		bp->b_blkno = blk;
1664725b4ff0SMark Johnston 		for (j = 0; j < n; j++)
1665725b4ff0SMark Johnston 			bp->b_pages[j] = ma[i + j];
16661c7c3c6aSMatthew Dillon 		bp->b_npages = n;
1667725b4ff0SMark Johnston 
1668a5296b05SJulian Elischer 		/*
1669a5296b05SJulian Elischer 		 * Must set dirty range for NFS to work.
1670a5296b05SJulian Elischer 		 */
1671a5296b05SJulian Elischer 		bp->b_dirtyoff = 0;
1672a5296b05SJulian Elischer 		bp->b_dirtyend = bp->b_bcount;
16731c7c3c6aSMatthew Dillon 
167483c9dea1SGleb Smirnoff 		VM_CNT_INC(v_swapout);
167583c9dea1SGleb Smirnoff 		VM_CNT_ADD(v_swappgsout, bp->b_npages);
167626f9a767SRodney W. Grimes 
167726f9a767SRodney W. Grimes 		/*
167877923df2SAlan Cox 		 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
167977923df2SAlan Cox 		 * can call the async completion routine at the end of a
168077923df2SAlan Cox 		 * synchronous I/O operation.  Otherwise, our caller would
168177923df2SAlan Cox 		 * perform duplicate unbusy and wakeup operations on the page
168277923df2SAlan Cox 		 * and object, respectively.
168377923df2SAlan Cox 		 */
168477923df2SAlan Cox 		for (j = 0; j < n; j++)
168577923df2SAlan Cox 			rtvals[i + j] = VM_PAGER_PEND;
168677923df2SAlan Cox 
168777923df2SAlan Cox 		/*
16881c7c3c6aSMatthew Dillon 		 * asynchronous
16891c7c3c6aSMatthew Dillon 		 *
169023612f0dSDoug Moore 		 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
169126f9a767SRodney W. Grimes 		 */
169223612f0dSDoug Moore 		if (async) {
16931c7c3c6aSMatthew Dillon 			bp->b_iodone = swp_pager_async_iodone;
169467812eacSKirk McKusick 			BUF_KERNPROC(bp);
16954b03903aSPoul-Henning Kamp 			swp_pager_strategy(bp);
16961c7c3c6aSMatthew Dillon 			continue;
169726f9a767SRodney W. Grimes 		}
1698e47ed70bSJohn Dyson 
169926f9a767SRodney W. Grimes 		/*
17001c7c3c6aSMatthew Dillon 		 * synchronous
17011c7c3c6aSMatthew Dillon 		 *
170223612f0dSDoug Moore 		 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
17031c7c3c6aSMatthew Dillon 		 */
17042c840b1fSAlan Cox 		bp->b_iodone = bdone;
17054b03903aSPoul-Henning Kamp 		swp_pager_strategy(bp);
17061c7c3c6aSMatthew Dillon 
17071c7c3c6aSMatthew Dillon 		/*
170877923df2SAlan Cox 		 * Wait for the sync I/O to complete.
170926f9a767SRodney W. Grimes 		 */
17102c840b1fSAlan Cox 		bwait(bp, PVM, "swwrt");
171177923df2SAlan Cox 
17121c7c3c6aSMatthew Dillon 		/*
17131c7c3c6aSMatthew Dillon 		 * Now that we are through with the bp, we can call the
17141c7c3c6aSMatthew Dillon 		 * normal async completion, which frees everything up.
17151c7c3c6aSMatthew Dillon 		 */
17161c7c3c6aSMatthew Dillon 		swp_pager_async_iodone(bp);
17171c7c3c6aSMatthew Dillon 	}
1718a880104aSDoug Moore 	swp_pager_freeswapspace(&range);
171923612f0dSDoug Moore 	VM_OBJECT_WLOCK(object);
17201c7c3c6aSMatthew Dillon }
17211c7c3c6aSMatthew Dillon 
17221c7c3c6aSMatthew Dillon /*
17231c7c3c6aSMatthew Dillon  *	swp_pager_async_iodone:
17241c7c3c6aSMatthew Dillon  *
17251c7c3c6aSMatthew Dillon  *	Completion routine for asynchronous reads and writes from/to swap.
17261c7c3c6aSMatthew Dillon  *	Also called manually by synchronous code to finish up a bp.
17271c7c3c6aSMatthew Dillon  *
172815523cf7SKonstantin Belousov  *	This routine may not sleep.
17291c7c3c6aSMatthew Dillon  */
17301c7c3c6aSMatthew Dillon static void
17312f249180SPoul-Henning Kamp swp_pager_async_iodone(struct buf *bp)
17321c7c3c6aSMatthew Dillon {
17331c7c3c6aSMatthew Dillon 	int i;
17341c7c3c6aSMatthew Dillon 	vm_object_t object = NULL;
17351c7c3c6aSMatthew Dillon 
17361c7c3c6aSMatthew Dillon 	/*
17370b208315SEdward Tomasz Napierala 	 * Report error - unless we ran out of memory, in which case
17380b208315SEdward Tomasz Napierala 	 * we've already logged it in swapgeom_strategy().
17391c7c3c6aSMatthew Dillon 	 */
17400b208315SEdward Tomasz Napierala 	if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
17411c7c3c6aSMatthew Dillon 		printf(
17421c7c3c6aSMatthew Dillon 		    "swap_pager: I/O error - %s failed; blkno %ld,"
17431c7c3c6aSMatthew Dillon 			"size %ld, error %d\n",
174421144e3bSPoul-Henning Kamp 		    ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
17451c7c3c6aSMatthew Dillon 		    (long)bp->b_blkno,
17461c7c3c6aSMatthew Dillon 		    (long)bp->b_bcount,
17471c7c3c6aSMatthew Dillon 		    bp->b_error
17481c7c3c6aSMatthew Dillon 		);
17491c7c3c6aSMatthew Dillon 	}
17501c7c3c6aSMatthew Dillon 
17511c7c3c6aSMatthew Dillon 	/*
175226f9a767SRodney W. Grimes 	 * remove the mapping for kernel virtual
175326f9a767SRodney W. Grimes 	 */
1754fade8dd7SJeff Roberson 	if (buf_mapped(bp))
17551c7c3c6aSMatthew Dillon 		pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1756fade8dd7SJeff Roberson 	else
1757fade8dd7SJeff Roberson 		bp->b_data = bp->b_kvabase;
175826f9a767SRodney W. Grimes 
175933a609ecSAlan Cox 	if (bp->b_npages) {
176033a609ecSAlan Cox 		object = bp->b_pages[0]->object;
176189f6b863SAttilio Rao 		VM_OBJECT_WLOCK(object);
176233a609ecSAlan Cox 	}
17632965a453SKip Macy 
176426f9a767SRodney W. Grimes 	/*
17651c7c3c6aSMatthew Dillon 	 * cleanup pages.  If an error occurs writing to swap, we are in
17661c7c3c6aSMatthew Dillon 	 * very serious trouble.  If it happens to be a disk error, though,
17671c7c3c6aSMatthew Dillon 	 * we may be able to recover by reassigning the swap later on.  So
17681c7c3c6aSMatthew Dillon 	 * in this case we remove the m->swapblk assignment for the page
17691c7c3c6aSMatthew Dillon 	 * but do not free it in the rlist.  The errornous block(s) are thus
17701c7c3c6aSMatthew Dillon 	 * never reallocated as swap.  Redirty the page and continue.
177126f9a767SRodney W. Grimes 	 */
17721c7c3c6aSMatthew Dillon 	for (i = 0; i < bp->b_npages; ++i) {
17731c7c3c6aSMatthew Dillon 		vm_page_t m = bp->b_pages[i];
1774e47ed70bSJohn Dyson 
17755786be7cSAlan Cox 		m->oflags &= ~VPO_SWAPINPROG;
1776c7aebda8SAttilio Rao 		if (m->oflags & VPO_SWAPSLEEP) {
1777c7aebda8SAttilio Rao 			m->oflags &= ~VPO_SWAPSLEEP;
1778cf27e0d1SJeff Roberson 			wakeup(&object->handle);
1779c7aebda8SAttilio Rao 		}
1780e47ed70bSJohn Dyson 
1781a8081778SJeff Roberson 		/* We always have space after I/O, successful or not. */
1782a8081778SJeff Roberson 		vm_page_aflag_set(m, PGA_SWAP_SPACE);
1783a8081778SJeff Roberson 
1784c244d2deSPoul-Henning Kamp 		if (bp->b_ioflags & BIO_ERROR) {
1785ffc82b0aSJohn Dyson 			/*
17861c7c3c6aSMatthew Dillon 			 * If an error occurs I'd love to throw the swapblk
17871c7c3c6aSMatthew Dillon 			 * away without freeing it back to swapspace, so it
17881c7c3c6aSMatthew Dillon 			 * can never be used again.  But I can't from an
17891c7c3c6aSMatthew Dillon 			 * interrupt.
1790ffc82b0aSJohn Dyson 			 */
179121144e3bSPoul-Henning Kamp 			if (bp->b_iocmd == BIO_READ) {
17921c7c3c6aSMatthew Dillon 				/*
17931c7c3c6aSMatthew Dillon 				 * NOTE: for reads, m->dirty will probably
1794956f3135SPhilippe Charnier 				 * be overridden by the original caller of
17951c7c3c6aSMatthew Dillon 				 * getpages so don't play cute tricks here.
17961c7c3c6aSMatthew Dillon 				 */
17970012f373SJeff Roberson 				vm_page_invalid(m);
179846966507SMark Johnston 				if (i < bp->b_pgbefore ||
179946966507SMark Johnston 				    i >= bp->b_npages - bp->b_pgafter)
180046966507SMark Johnston 					vm_page_free_invalid(m);
18011c7c3c6aSMatthew Dillon 			} else {
18021c7c3c6aSMatthew Dillon 				/*
18031c7c3c6aSMatthew Dillon 				 * If a write error occurs, reactivate page
18041c7c3c6aSMatthew Dillon 				 * so it doesn't clog the inactive list,
18051c7c3c6aSMatthew Dillon 				 * then finish the I/O.
18061c7c3c6aSMatthew Dillon 				 */
180741e5a226SAlan Cox 				MPASS(m->dirty == VM_PAGE_BITS_ALL);
18089f5632e6SMark Johnston 
1809a8081778SJeff Roberson 				/* PQ_UNSWAPPABLE? */
18101c7c3c6aSMatthew Dillon 				vm_page_activate(m);
1811c7aebda8SAttilio Rao 				vm_page_sunbusy(m);
18121c7c3c6aSMatthew Dillon 			}
181321144e3bSPoul-Henning Kamp 		} else if (bp->b_iocmd == BIO_READ) {
18141c7c3c6aSMatthew Dillon 			/*
18151c7c3c6aSMatthew Dillon 			 * NOTE: for reads, m->dirty will probably be
1816956f3135SPhilippe Charnier 			 * overridden by the original caller of getpages so
18171c7c3c6aSMatthew Dillon 			 * we cannot set them in order to free the underlying
18181c7c3c6aSMatthew Dillon 			 * swap in a low-swap situation.  I don't think we'd
18191c7c3c6aSMatthew Dillon 			 * want to do that anyway, but it was an optimization
18201c7c3c6aSMatthew Dillon 			 * that existed in the old swapper for a time before
18211c7c3c6aSMatthew Dillon 			 * it got ripped out due to precisely this problem.
18221c7c3c6aSMatthew Dillon 			 */
1823016a3c93SAlan Cox 			KASSERT(!pmap_page_is_mapped(m),
1824016a3c93SAlan Cox 			    ("swp_pager_async_iodone: page %p is mapped", m));
1825016a3c93SAlan Cox 			KASSERT(m->dirty == 0,
1826016a3c93SAlan Cox 			    ("swp_pager_async_iodone: page %p is dirty", m));
1827915d1b71SMark Johnston 
18280012f373SJeff Roberson 			vm_page_valid(m);
1829915d1b71SMark Johnston 			if (i < bp->b_pgbefore ||
1830915d1b71SMark Johnston 			    i >= bp->b_npages - bp->b_pgafter)
1831915d1b71SMark Johnston 				vm_page_readahead_finish(m);
18321c7c3c6aSMatthew Dillon 		} else {
18331c7c3c6aSMatthew Dillon 			/*
1834016a3c93SAlan Cox 			 * For write success, clear the dirty
18351c7c3c6aSMatthew Dillon 			 * status, then finish the I/O ( which decrements the
18361c7c3c6aSMatthew Dillon 			 * busy count and possibly wakes waiter's up ).
1837ebcddc72SAlan Cox 			 * A page is only written to swap after a period of
1838ebcddc72SAlan Cox 			 * inactivity.  Therefore, we do not expect it to be
1839ebcddc72SAlan Cox 			 * reused.
18401c7c3c6aSMatthew Dillon 			 */
18416031c68dSAlan Cox 			KASSERT(!pmap_page_is_write_mapped(m),
1842016a3c93SAlan Cox 			    ("swp_pager_async_iodone: page %p is not write"
1843016a3c93SAlan Cox 			    " protected", m));
1844c52e7044SAlan Cox 			vm_page_undirty(m);
1845ebcddc72SAlan Cox 			vm_page_deactivate_noreuse(m);
1846ebcddc72SAlan Cox 			vm_page_sunbusy(m);
18473c4a2440SAlan Cox 		}
18483c4a2440SAlan Cox 	}
184926f9a767SRodney W. Grimes 
18501c7c3c6aSMatthew Dillon 	/*
18511c7c3c6aSMatthew Dillon 	 * adjust pip.  NOTE: the original parent may still have its own
18521c7c3c6aSMatthew Dillon 	 * pip refs on the object.
18531c7c3c6aSMatthew Dillon 	 */
18540d420ad3SAlan Cox 	if (object != NULL) {
18551c7c3c6aSMatthew Dillon 		vm_object_pip_wakeupn(object, bp->b_npages);
185689f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
18570d420ad3SAlan Cox 	}
185826f9a767SRodney W. Grimes 
18591c7c3c6aSMatthew Dillon 	/*
1860100650deSOlivier Houchard 	 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1861100650deSOlivier Houchard 	 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1862100650deSOlivier Houchard 	 * trigger a KASSERT in relpbuf().
1863100650deSOlivier Houchard 	 */
1864100650deSOlivier Houchard 	if (bp->b_vp) {
1865100650deSOlivier Houchard 		    bp->b_vp = NULL;
1866100650deSOlivier Houchard 		    bp->b_bufobj = NULL;
1867100650deSOlivier Houchard 	}
1868100650deSOlivier Houchard 	/*
18691c7c3c6aSMatthew Dillon 	 * release the physical I/O buffer
18701c7c3c6aSMatthew Dillon 	 */
1871756a5412SGleb Smirnoff 	if (bp->b_flags & B_ASYNC) {
1872756a5412SGleb Smirnoff 		mtx_lock(&swbuf_mtx);
1873756a5412SGleb Smirnoff 		if (++nsw_wcount_async == 1)
1874756a5412SGleb Smirnoff 			wakeup(&nsw_wcount_async);
1875756a5412SGleb Smirnoff 		mtx_unlock(&swbuf_mtx);
1876756a5412SGleb Smirnoff 	}
1877756a5412SGleb Smirnoff 	uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
187826f9a767SRodney W. Grimes }
18791c7c3c6aSMatthew Dillon 
1880b1fd102eSMark Johnston int
1881b1fd102eSMark Johnston swap_pager_nswapdev(void)
1882b1fd102eSMark Johnston {
1883b1fd102eSMark Johnston 
1884b1fd102eSMark Johnston 	return (nswapdev);
1885b1fd102eSMark Johnston }
1886b1fd102eSMark Johnston 
18877c022327SDoug Moore static void
1888995730a6SDoug Moore swp_pager_force_dirty(struct page_range *range, vm_page_t m, daddr_t *blk)
18897c022327SDoug Moore {
18907c022327SDoug Moore 	vm_page_dirty(m);
1891995730a6SDoug Moore 	swap_pager_unswapped_acct(m);
1892995730a6SDoug Moore 	swp_pager_update_freerange(range, *blk);
1893995730a6SDoug Moore 	*blk = SWAPBLK_NONE;
18947c022327SDoug Moore 	vm_page_launder(m);
189592da00bbSMatthew Dillon }
189692da00bbSMatthew Dillon 
1897ecfbddf0SKonstantin Belousov u_long
1898ecfbddf0SKonstantin Belousov swap_pager_swapped_pages(vm_object_t object)
1899ecfbddf0SKonstantin Belousov {
190052b35140SDoug Moore 	struct pctrie_iter blks;
1901ecfbddf0SKonstantin Belousov 	struct swblk *sb;
1902ecfbddf0SKonstantin Belousov 	u_long res;
1903ecfbddf0SKonstantin Belousov 	int i;
1904ecfbddf0SKonstantin Belousov 
1905ecfbddf0SKonstantin Belousov 	VM_OBJECT_ASSERT_LOCKED(object);
1906cb6757c0SMark Johnston 
190794264705SDoug Moore 	if (swblk_is_empty(object))
1908ecfbddf0SKonstantin Belousov 		return (0);
1909ecfbddf0SKonstantin Belousov 
191094264705SDoug Moore 	res = 0;
19116af02087SDoug Moore 	for (sb = swblk_iter_init(&blks, object, 0); sb != NULL;
191252b35140SDoug Moore 	    sb = swblk_iter_next(&blks)) {
1913ecfbddf0SKonstantin Belousov 		for (i = 0; i < SWAP_META_PAGES; i++) {
1914ecfbddf0SKonstantin Belousov 			if (sb->d[i] != SWAPBLK_NONE)
1915ecfbddf0SKonstantin Belousov 				res++;
1916ecfbddf0SKonstantin Belousov 		}
1917ecfbddf0SKonstantin Belousov 	}
1918ecfbddf0SKonstantin Belousov 	return (res);
1919ecfbddf0SKonstantin Belousov }
1920ecfbddf0SKonstantin Belousov 
192192da00bbSMatthew Dillon /*
19227c022327SDoug Moore  *	swap_pager_swapoff_object:
19237c022327SDoug Moore  *
19247c022327SDoug Moore  *	Page in all of the pages that have been paged out for an object
192556948d17SDoug Moore  *	to a swap device.
19267c022327SDoug Moore  */
19277c022327SDoug Moore static void
19287c022327SDoug Moore swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
19297c022327SDoug Moore {
193052b35140SDoug Moore 	struct pctrie_iter blks, pages;
1931995730a6SDoug Moore 	struct page_range range;
19327c022327SDoug Moore 	struct swblk *sb;
1933c90d075bSMark Johnston 	vm_page_t m;
1934995730a6SDoug Moore 	int i, rahead, rv;
1935995730a6SDoug Moore 	bool sb_empty;
19367c022327SDoug Moore 
1937995730a6SDoug Moore 	VM_OBJECT_ASSERT_WLOCKED(object);
19384b8365d7SKonstantin Belousov 	KASSERT((object->flags & OBJ_SWAP) != 0,
19398ecbf14bSDoug Moore 	    ("%s: Object not swappable", __func__));
194011078340SDoug Moore 	KASSERT((object->flags & OBJ_DEAD) == 0,
194111078340SDoug Moore 	    ("%s: Object already dead", __func__));
194252b35140SDoug Moore 	KASSERT((sp->sw_flags & SW_CLOSING) != 0,
194352b35140SDoug Moore 	    ("%s: Device not blocking further allocations", __func__));
1944c90d075bSMark Johnston 
194576c60597SDoug Moore 	vm_page_iter_init(&pages, object);
1946995730a6SDoug Moore 	swp_pager_init_freerange(&range);
19476af02087SDoug Moore 	sb = swblk_iter_init(&blks, object, 0);
194852b35140SDoug Moore 	while (sb != NULL) {
1949995730a6SDoug Moore 		sb_empty = true;
195052b35140SDoug Moore 		for (i = 0; i < SWAP_META_PAGES; i++) {
1951995730a6SDoug Moore 			/* Skip an invalid block. */
195252b35140SDoug Moore 			if (sb->d[i] == SWAPBLK_NONE)
195352b35140SDoug Moore 				continue;
195452b35140SDoug Moore 			/* Skip a block not of this device. */
195552b35140SDoug Moore 			if (!swp_pager_isondev(sb->d[i], sp)) {
1956995730a6SDoug Moore 				sb_empty = false;
19577c022327SDoug Moore 				continue;
1958995730a6SDoug Moore 			}
195956948d17SDoug Moore 
196056948d17SDoug Moore 			/*
196152b35140SDoug Moore 			 * Look for a page corresponding to this block. If the
196252b35140SDoug Moore 			 * found page has pending operations, sleep and restart
196352b35140SDoug Moore 			 * the scan.
196456948d17SDoug Moore 			 */
196552b35140SDoug Moore 			m = vm_page_iter_lookup(&pages, blks.index + i);
1966995730a6SDoug Moore 			if (m != NULL && (m->oflags & VPO_SWAPINPROG) != 0) {
1967995730a6SDoug Moore 				m->oflags |= VPO_SWAPSLEEP;
196852b35140SDoug Moore 				VM_OBJECT_SLEEP(object, &object->handle, PSWP,
196952b35140SDoug Moore 				    "swpoff", 0);
197052b35140SDoug Moore 				break;
1971995730a6SDoug Moore 			}
1972995730a6SDoug Moore 
1973995730a6SDoug Moore 			/*
197452b35140SDoug Moore 			 * If the found page is valid, mark it dirty and free
197552b35140SDoug Moore 			 * the swap block.
1976995730a6SDoug Moore 			 */
1977995730a6SDoug Moore 			if (m != NULL && vm_page_all_valid(m)) {
1978995730a6SDoug Moore 				swp_pager_force_dirty(&range, m, &sb->d[i]);
1979995730a6SDoug Moore 				continue;
1980995730a6SDoug Moore 			}
1981995730a6SDoug Moore 			/* Is there a page we can acquire or allocate? */
198252b35140SDoug Moore 			if (m != NULL) {
198352b35140SDoug Moore 				if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL))
198452b35140SDoug Moore 					break;
198552b35140SDoug Moore 			} else if ((m = vm_page_alloc(object, blks.index + i,
198652b35140SDoug Moore 			    VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL)) == NULL)
198752b35140SDoug Moore 				break;
198856948d17SDoug Moore 
198952b35140SDoug Moore 			/* Get the page from swap, and restart the scan. */
1990c90d075bSMark Johnston 			vm_object_pip_add(object, 1);
1991c90d075bSMark Johnston 			rahead = SWAP_META_PAGES;
199239f6d1e7SDoug Moore 			rv = swap_pager_getpages_locked(&blks, object, &m, 1,
199352b35140SDoug Moore 			    NULL, &rahead);
1994c90d075bSMark Johnston 			if (rv != VM_PAGER_OK)
199552b35140SDoug Moore 				panic("%s: read from swap failed: %d",
199652b35140SDoug Moore 				    __func__, rv);
1997c90d075bSMark Johnston 			VM_OBJECT_WLOCK(object);
1998e61568aeSMark Johnston 			vm_object_pip_wakeupn(object, 1);
1999995730a6SDoug Moore 			KASSERT(vm_page_all_valid(m),
2000995730a6SDoug Moore 			    ("%s: Page %p not all valid", __func__, m));
2001*d11d407aSMark Johnston 			vm_page_deactivate_noreuse(m);
2002c90d075bSMark Johnston 			vm_page_xunbusy(m);
200352b35140SDoug Moore 			break;
200452b35140SDoug Moore 		}
200552b35140SDoug Moore 		if (i < SWAP_META_PAGES) {
200652b35140SDoug Moore 			/*
200711078340SDoug Moore 			 * The object lock has been released and regained.
200811078340SDoug Moore 			 * Perhaps the object is now dead.
200911078340SDoug Moore 			 */
201011078340SDoug Moore 			if ((object->flags & OBJ_DEAD) != 0) {
201111078340SDoug Moore 				/*
201211078340SDoug Moore 				 * Make sure that pending writes finish before
201311078340SDoug Moore 				 * returning.
201411078340SDoug Moore 				 */
201511078340SDoug Moore 				vm_object_pip_wait(object, "swpoff");
201611078340SDoug Moore 				swp_pager_meta_free_all(object);
201711078340SDoug Moore 				break;
201811078340SDoug Moore 			}
201911078340SDoug Moore 
202011078340SDoug Moore 			/*
202111078340SDoug Moore 			 * The swapblk could have been freed, so reset the pages
202252b35140SDoug Moore 			 * iterator and search again for the first swblk at or
202352b35140SDoug Moore 			 * after blks.index.
202452b35140SDoug Moore 			 */
202552b35140SDoug Moore 			pctrie_iter_reset(&pages);
20266af02087SDoug Moore 			sb = swblk_iter_init(&blks, object, blks.index);
202752b35140SDoug Moore 			continue;
202852b35140SDoug Moore 		}
202952b35140SDoug Moore 		if (sb_empty) {
203052b35140SDoug Moore 			swblk_iter_remove(&blks);
203152b35140SDoug Moore 			uma_zfree(swblk_zone, sb);
203252b35140SDoug Moore 		}
203352b35140SDoug Moore 
203452b35140SDoug Moore 		/*
203552b35140SDoug Moore 		 * It is safe to advance to the next block.  No allocations
203652b35140SDoug Moore 		 * before blk.index have happened, even with the lock released,
203752b35140SDoug Moore 		 * because allocations on this device are blocked.
203852b35140SDoug Moore 		 */
203952b35140SDoug Moore 		sb = swblk_iter_next(&blks);
204056948d17SDoug Moore 	}
2041995730a6SDoug Moore 	swp_pager_freeswapspace(&range);
20427c022327SDoug Moore }
20437c022327SDoug Moore 
20447c022327SDoug Moore /*
204592da00bbSMatthew Dillon  *	swap_pager_swapoff:
204692da00bbSMatthew Dillon  *
204792da00bbSMatthew Dillon  *	Page in all of the pages that have been paged out to the
204892da00bbSMatthew Dillon  *	given device.  The corresponding blocks in the bitmap must be
204992da00bbSMatthew Dillon  *	marked as allocated and the device must be flagged SW_CLOSING.
205092da00bbSMatthew Dillon  *	There may be no processes swapped out to the device.
205192da00bbSMatthew Dillon  *
205292da00bbSMatthew Dillon  *	This routine may block.
205392da00bbSMatthew Dillon  */
2054e9c0cc15SPoul-Henning Kamp static void
2055b3fed13eSDavid Schultz swap_pager_swapoff(struct swdevt *sp)
205692da00bbSMatthew Dillon {
2057f425ab8eSKonstantin Belousov 	vm_object_t object;
20587c022327SDoug Moore 	int retries;
205992da00bbSMatthew Dillon 
206004533e1eSKonstantin Belousov 	sx_assert(&swdev_syscall_lock, SA_XLOCKED);
206192da00bbSMatthew Dillon 
20628bc61209SDavid Schultz 	retries = 0;
206392da00bbSMatthew Dillon full_rescan:
2064f425ab8eSKonstantin Belousov 	mtx_lock(&vm_object_list_mtx);
2065f425ab8eSKonstantin Belousov 	TAILQ_FOREACH(object, &vm_object_list, object_list) {
20664b8365d7SKonstantin Belousov 		if ((object->flags & OBJ_SWAP) == 0)
206798150664SKonstantin Belousov 			continue;
2068f425ab8eSKonstantin Belousov 		mtx_unlock(&vm_object_list_mtx);
206998150664SKonstantin Belousov 		/* Depends on type-stability. */
207098150664SKonstantin Belousov 		VM_OBJECT_WLOCK(object);
2071f425ab8eSKonstantin Belousov 
2072f425ab8eSKonstantin Belousov 		/*
2073f425ab8eSKonstantin Belousov 		 * Dead objects are eventually terminated on their own.
2074f425ab8eSKonstantin Belousov 		 */
2075f425ab8eSKonstantin Belousov 		if ((object->flags & OBJ_DEAD) != 0)
2076f425ab8eSKonstantin Belousov 			goto next_obj;
2077f425ab8eSKonstantin Belousov 
2078f425ab8eSKonstantin Belousov 		/*
2079f425ab8eSKonstantin Belousov 		 * Sync with fences placed after pctrie
2080f425ab8eSKonstantin Belousov 		 * initialization.  We must not access pctrie below
2081f425ab8eSKonstantin Belousov 		 * unless we checked that our object is swap and not
2082f425ab8eSKonstantin Belousov 		 * dead.
2083f425ab8eSKonstantin Belousov 		 */
2084f425ab8eSKonstantin Belousov 		atomic_thread_fence_acq();
20854b8365d7SKonstantin Belousov 		if ((object->flags & OBJ_SWAP) == 0)
2086f425ab8eSKonstantin Belousov 			goto next_obj;
2087f425ab8eSKonstantin Belousov 
20887c022327SDoug Moore 		swap_pager_swapoff_object(sp, object);
2089f425ab8eSKonstantin Belousov next_obj:
2090f425ab8eSKonstantin Belousov 		VM_OBJECT_WUNLOCK(object);
2091f425ab8eSKonstantin Belousov 		mtx_lock(&vm_object_list_mtx);
209292da00bbSMatthew Dillon 	}
2093f425ab8eSKonstantin Belousov 	mtx_unlock(&vm_object_list_mtx);
2094f425ab8eSKonstantin Belousov 
20958bc61209SDavid Schultz 	if (sp->sw_used) {
209692da00bbSMatthew Dillon 		/*
20978bc61209SDavid Schultz 		 * Objects may be locked or paging to the device being
20988bc61209SDavid Schultz 		 * removed, so we will miss their pages and need to
20998bc61209SDavid Schultz 		 * make another pass.  We have marked this device as
21008bc61209SDavid Schultz 		 * SW_CLOSING, so the activity should finish soon.
210192da00bbSMatthew Dillon 		 */
21028bc61209SDavid Schultz 		retries++;
21038bc61209SDavid Schultz 		if (retries > 100) {
21048bc61209SDavid Schultz 			panic("swapoff: failed to locate %d swap blocks",
21058bc61209SDavid Schultz 			    sp->sw_used);
21068bc61209SDavid Schultz 		}
21074d70511aSJohn Baldwin 		pause("swpoff", hz / 20);
210892da00bbSMatthew Dillon 		goto full_rescan;
210992da00bbSMatthew Dillon 	}
2110b1fd102eSMark Johnston 	EVENTHANDLER_INVOKE(swapoff, sp);
211192da00bbSMatthew Dillon }
211292da00bbSMatthew Dillon 
21131c7c3c6aSMatthew Dillon /************************************************************************
21141c7c3c6aSMatthew Dillon  *				SWAP META DATA 				*
21151c7c3c6aSMatthew Dillon  ************************************************************************
21161c7c3c6aSMatthew Dillon  *
21171c7c3c6aSMatthew Dillon  *	These routines manipulate the swap metadata stored in the
2118cec9f109SDavid E. O'Brien  *	OBJT_SWAP object.
21191c7c3c6aSMatthew Dillon  *
21204dcc5c2dSMatthew Dillon  *	Swap metadata is implemented with a global hash and not directly
21214dcc5c2dSMatthew Dillon  *	linked into the object.  Instead the object simply contains
21224dcc5c2dSMatthew Dillon  *	appropriate tracking counters.
21231c7c3c6aSMatthew Dillon  */
21241c7c3c6aSMatthew Dillon 
21251c7c3c6aSMatthew Dillon /*
2126230869e0SAlan Cox  * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
2127230869e0SAlan Cox  */
2128230869e0SAlan Cox static bool
2129230869e0SAlan Cox swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
2130230869e0SAlan Cox {
2131230869e0SAlan Cox 	int i;
2132230869e0SAlan Cox 
2133230869e0SAlan Cox 	MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
2134230869e0SAlan Cox 	for (i = start; i < limit; i++) {
2135230869e0SAlan Cox 		if (sb->d[i] != SWAPBLK_NONE)
2136230869e0SAlan Cox 			return (false);
2137230869e0SAlan Cox 	}
2138230869e0SAlan Cox 	return (true);
2139230869e0SAlan Cox }
2140230869e0SAlan Cox 
2141230869e0SAlan Cox /*
2142abdab7b6SDoug Moore  * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
2143abdab7b6SDoug Moore  *
2144abdab7b6SDoug Moore  *  Nothing is done if the block is still in use.
2145abdab7b6SDoug Moore  */
2146abdab7b6SDoug Moore static void
2147abdab7b6SDoug Moore swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
2148abdab7b6SDoug Moore {
2149abdab7b6SDoug Moore 
2150abdab7b6SDoug Moore 	if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
215194264705SDoug Moore 		swblk_lookup_remove(object, sb);
2152abdab7b6SDoug Moore 		uma_zfree(swblk_zone, sb);
2153abdab7b6SDoug Moore 	}
2154abdab7b6SDoug Moore }
2155abdab7b6SDoug Moore 
2156abdab7b6SDoug Moore /*
21571c7c3c6aSMatthew Dillon  * SWP_PAGER_META_BUILD() -	add swap block to swap meta data for object
21581c7c3c6aSMatthew Dillon  *
215975694e65SDoug Moore  *	Try to add the specified swapblk to the object's swap metadata.  If
216075694e65SDoug Moore  *	nowait_noreplace is set, add the specified swapblk only if there is no
216175694e65SDoug Moore  *	previously assigned swapblk at pindex.  If the swapblk is invalid, and
216275694e65SDoug Moore  *	replaces a valid swapblk, empty swap metadata is freed.  If memory
216375694e65SDoug Moore  *	allocation fails, and nowait_noreplace is set, return the specified
216475694e65SDoug Moore  *	swapblk immediately to indicate failure; otherwise, wait and retry until
216575694e65SDoug Moore  *	memory allocation succeeds.  Return the previously assigned swapblk, if
216675694e65SDoug Moore  *	any.
21671c7c3c6aSMatthew Dillon  */
216878f1deefSAlan Cox static daddr_t
2169d0b225d1SDoug Moore swp_pager_meta_build(struct pctrie_iter *blks, vm_object_t object,
2170d0b225d1SDoug Moore     vm_pindex_t pindex, daddr_t swapblk, bool nowait_noreplace)
21712f249180SPoul-Henning Kamp {
2172f425ab8eSKonstantin Belousov 	static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
2173eed99cb8SKonstantin Belousov 	struct swblk *sb, *sb1;
2174d0b225d1SDoug Moore 	vm_pindex_t modpi;
217578f1deefSAlan Cox 	daddr_t prev_swapblk;
2176f425ab8eSKonstantin Belousov 	int error, i;
21771c7c3c6aSMatthew Dillon 
217889f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
2179f425ab8eSKonstantin Belousov 
2180d0b225d1SDoug Moore 	sb = swblk_iter_lookup(blks, pindex);
2181f425ab8eSKonstantin Belousov 	if (sb == NULL) {
21821c7c3c6aSMatthew Dillon 		if (swapblk == SWAPBLK_NONE)
218378f1deefSAlan Cox 			return (SWAPBLK_NONE);
2184f425ab8eSKonstantin Belousov 		for (;;) {
2185f425ab8eSKonstantin Belousov 			sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
2186f425ab8eSKonstantin Belousov 			    pageproc ? M_USE_RESERVE : 0));
2187f425ab8eSKonstantin Belousov 			if (sb != NULL) {
2188d0b225d1SDoug Moore 				sb->p = rounddown(pindex, SWAP_META_PAGES);
2189f425ab8eSKonstantin Belousov 				for (i = 0; i < SWAP_META_PAGES; i++)
2190f425ab8eSKonstantin Belousov 					sb->d[i] = SWAPBLK_NONE;
2191f425ab8eSKonstantin Belousov 				if (atomic_cmpset_int(&swblk_zone_exhausted,
2192f425ab8eSKonstantin Belousov 				    1, 0))
2193f425ab8eSKonstantin Belousov 					printf("swblk zone ok\n");
2194f425ab8eSKonstantin Belousov 				break;
2195f425ab8eSKonstantin Belousov 			}
219675694e65SDoug Moore 			if (nowait_noreplace)
219775694e65SDoug Moore 				return (swapblk);
219889f6b863SAttilio Rao 			VM_OBJECT_WUNLOCK(object);
2199f425ab8eSKonstantin Belousov 			if (uma_zone_exhausted(swblk_zone)) {
2200f425ab8eSKonstantin Belousov 				if (atomic_cmpset_int(&swblk_zone_exhausted,
2201f425ab8eSKonstantin Belousov 				    0, 1))
2202f425ab8eSKonstantin Belousov 					printf("swap blk zone exhausted, "
22033ff863f1SDag-Erling Smørgrav 					    "increase kern.maxswzone\n");
22042025d69bSKonstantin Belousov 				vm_pageout_oom(VM_OOM_SWAPZ);
2205f425ab8eSKonstantin Belousov 				pause("swzonxb", 10);
22062025d69bSKonstantin Belousov 			} else
22078d6fbbb8SJeff Roberson 				uma_zwait(swblk_zone);
220889f6b863SAttilio Rao 			VM_OBJECT_WLOCK(object);
2209d0b225d1SDoug Moore 			sb = swblk_iter_reinit(blks, object, pindex);
2210eed99cb8SKonstantin Belousov 			if (sb != NULL)
2211eed99cb8SKonstantin Belousov 				/*
2212eed99cb8SKonstantin Belousov 				 * Somebody swapped out a nearby page,
2213d0b225d1SDoug Moore 				 * allocating swblk at the pindex index,
2214eed99cb8SKonstantin Belousov 				 * while we dropped the object lock.
2215eed99cb8SKonstantin Belousov 				 */
2216eed99cb8SKonstantin Belousov 				goto allocated;
22174dcc5c2dSMatthew Dillon 		}
2218f425ab8eSKonstantin Belousov 		for (;;) {
2219d0b225d1SDoug Moore 			error = swblk_iter_insert(blks, sb);
2220f425ab8eSKonstantin Belousov 			if (error == 0) {
2221f425ab8eSKonstantin Belousov 				if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2222f425ab8eSKonstantin Belousov 				    1, 0))
2223f425ab8eSKonstantin Belousov 					printf("swpctrie zone ok\n");
2224f425ab8eSKonstantin Belousov 				break;
22251c7c3c6aSMatthew Dillon 			}
222675694e65SDoug Moore 			if (nowait_noreplace) {
222775694e65SDoug Moore 				uma_zfree(swblk_zone, sb);
222875694e65SDoug Moore 				return (swapblk);
222975694e65SDoug Moore 			}
2230f425ab8eSKonstantin Belousov 			VM_OBJECT_WUNLOCK(object);
2231f425ab8eSKonstantin Belousov 			if (uma_zone_exhausted(swpctrie_zone)) {
2232f425ab8eSKonstantin Belousov 				if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2233f425ab8eSKonstantin Belousov 				    0, 1))
2234f425ab8eSKonstantin Belousov 					printf("swap pctrie zone exhausted, "
2235f425ab8eSKonstantin Belousov 					    "increase kern.maxswzone\n");
2236f425ab8eSKonstantin Belousov 				vm_pageout_oom(VM_OOM_SWAPZ);
2237f425ab8eSKonstantin Belousov 				pause("swzonxp", 10);
2238f425ab8eSKonstantin Belousov 			} else
22398d6fbbb8SJeff Roberson 				uma_zwait(swpctrie_zone);
2240f425ab8eSKonstantin Belousov 			VM_OBJECT_WLOCK(object);
2241d0b225d1SDoug Moore 			sb1 = swblk_iter_reinit(blks, object, pindex);
2242eed99cb8SKonstantin Belousov 			if (sb1 != NULL) {
2243eed99cb8SKonstantin Belousov 				uma_zfree(swblk_zone, sb);
2244eed99cb8SKonstantin Belousov 				sb = sb1;
2245eed99cb8SKonstantin Belousov 				goto allocated;
22461c7c3c6aSMatthew Dillon 			}
2247f425ab8eSKonstantin Belousov 		}
2248eed99cb8SKonstantin Belousov 	}
2249eed99cb8SKonstantin Belousov allocated:
2250d0b225d1SDoug Moore 	MPASS(sb->p == rounddown(pindex, SWAP_META_PAGES));
22511c7c3c6aSMatthew Dillon 
2252f425ab8eSKonstantin Belousov 	modpi = pindex % SWAP_META_PAGES;
225378f1deefSAlan Cox 	/* Return prior contents of metadata. */
225478f1deefSAlan Cox 	prev_swapblk = sb->d[modpi];
225575694e65SDoug Moore 	if (!nowait_noreplace || prev_swapblk == SWAPBLK_NONE) {
2256f425ab8eSKonstantin Belousov 		/* Enter block into metadata. */
2257f425ab8eSKonstantin Belousov 		sb->d[modpi] = swapblk;
225885d88d87SKonstantin Belousov 
225985d88d87SKonstantin Belousov 		/*
226085d88d87SKonstantin Belousov 		 * Free the swblk if we end up with the empty page run.
226185d88d87SKonstantin Belousov 		 */
2262d0b225d1SDoug Moore 		if (swapblk == SWAPBLK_NONE &&
2263d0b225d1SDoug Moore 		    swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
2264d0b225d1SDoug Moore 			swblk_iter_remove(blks);
2265d0b225d1SDoug Moore 			uma_zfree(swblk_zone, sb);
2266d0b225d1SDoug Moore 		}
226775694e65SDoug Moore 	}
226878f1deefSAlan Cox 	return (prev_swapblk);
226985d88d87SKonstantin Belousov }
22701c7c3c6aSMatthew Dillon 
22711c7c3c6aSMatthew Dillon /*
227294264705SDoug Moore  * SWP_PAGER_META_TRANSFER() - transfer a range of blocks in the srcobject's
227394264705SDoug Moore  * swap metadata into dstobject.
2274467057fcSDoug Moore  *
2275bae51702SDoug Moore  *	Blocks in src that correspond to holes in dst are transferred.  Blocks
2276bae51702SDoug Moore  *	in src that correspond to blocks in dst are freed.
2277467057fcSDoug Moore  */
2278467057fcSDoug Moore static void
2279467057fcSDoug Moore swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
228094264705SDoug Moore     vm_pindex_t pindex, vm_pindex_t count)
2281467057fcSDoug Moore {
2282d0b225d1SDoug Moore 	struct pctrie_iter dstblks, srcblks;
2283a880104aSDoug Moore 	struct page_range range;
2284467057fcSDoug Moore 	struct swblk *sb;
22854ccad545SDoug Moore 	daddr_t blk, d[SWAP_META_PAGES];
228652b35140SDoug Moore 	vm_pindex_t last;
22874ccad545SDoug Moore 	int d_mask, i, limit, start;
22884ccad545SDoug Moore 	_Static_assert(8 * sizeof(d_mask) >= SWAP_META_PAGES,
22894ccad545SDoug Moore 	    "d_mask not big enough");
2290467057fcSDoug Moore 
2291467057fcSDoug Moore 	VM_OBJECT_ASSERT_WLOCKED(srcobject);
229294264705SDoug Moore 	VM_OBJECT_ASSERT_WLOCKED(dstobject);
2293baa1ccceSKonstantin Belousov 
229494264705SDoug Moore 	if (count == 0 || swblk_is_empty(srcobject))
229594264705SDoug Moore 		return;
2296467057fcSDoug Moore 
2297a880104aSDoug Moore 	swp_pager_init_freerange(&range);
22984ccad545SDoug Moore 	d_mask = 0;
2299467057fcSDoug Moore 	last = pindex + count;
2300d0b225d1SDoug Moore 	swblk_iter_init_only(&dstblks, dstobject);
2301d0b225d1SDoug Moore 	for (sb = swblk_iter_limit_init(&srcblks, srcobject, pindex, last),
230252b35140SDoug Moore 	    start = swblk_start(sb, pindex);
2303d0b225d1SDoug Moore 	    sb != NULL; sb = swblk_iter_next(&srcblks), start = 0) {
2304d0b225d1SDoug Moore 		limit = MIN(last - srcblks.index, SWAP_META_PAGES);
2305467057fcSDoug Moore 		for (i = start; i < limit; i++) {
230694264705SDoug Moore 			if (sb->d[i] == SWAPBLK_NONE)
2307467057fcSDoug Moore 				continue;
2308d0b225d1SDoug Moore 			blk = swp_pager_meta_build(&dstblks, dstobject,
2309d0b225d1SDoug Moore 			    srcblks.index + i - pindex, sb->d[i], true);
231094264705SDoug Moore 			if (blk == sb->d[i]) {
231175694e65SDoug Moore 				/*
23124ccad545SDoug Moore 				 * Failed memory allocation stopped transfer;
23134ccad545SDoug Moore 				 * save this block for transfer with lock
23144ccad545SDoug Moore 				 * released.
231575694e65SDoug Moore 				 */
23164ccad545SDoug Moore 				d[i] = blk;
23174ccad545SDoug Moore 				d_mask |= 1 << i;
2318bae51702SDoug Moore 			} else if (blk != SWAPBLK_NONE) {
2319bae51702SDoug Moore 				/* Dst has a block at pindex, so free block. */
232094264705SDoug Moore 				swp_pager_update_freerange(&range, sb->d[i]);
2321bae51702SDoug Moore 			}
2322467057fcSDoug Moore 			sb->d[i] = SWAPBLK_NONE;
2323467057fcSDoug Moore 		}
2324467057fcSDoug Moore 		if (swp_pager_swblk_empty(sb, 0, start) &&
2325467057fcSDoug Moore 		    swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2326d0b225d1SDoug Moore 			swblk_iter_remove(&srcblks);
2327467057fcSDoug Moore 			uma_zfree(swblk_zone, sb);
2328467057fcSDoug Moore 		}
23294ccad545SDoug Moore 		if (d_mask != 0) {
23304ccad545SDoug Moore 			/* Finish block transfer, with the lock released. */
23314ccad545SDoug Moore 			VM_OBJECT_WUNLOCK(srcobject);
23324ccad545SDoug Moore 			do {
23334ccad545SDoug Moore 				i = ffs(d_mask) - 1;
2334d0b225d1SDoug Moore 				swp_pager_meta_build(&dstblks, dstobject,
2335d0b225d1SDoug Moore 				    srcblks.index + i - pindex, d[i], false);
23364ccad545SDoug Moore 				d_mask &= ~(1 << i);
23374ccad545SDoug Moore 			} while (d_mask != 0);
23384ccad545SDoug Moore 			VM_OBJECT_WLOCK(srcobject);
233952b35140SDoug Moore 
234052b35140SDoug Moore 			/*
234152b35140SDoug Moore 			 * While the lock was not held, the iterator path could
234252b35140SDoug Moore 			 * have become stale, so discard it.
234352b35140SDoug Moore 			 */
2344d0b225d1SDoug Moore 			pctrie_iter_reset(&srcblks);
23454ccad545SDoug Moore 		}
2346467057fcSDoug Moore 	}
2347a880104aSDoug Moore 	swp_pager_freeswapspace(&range);
2348467057fcSDoug Moore }
2349467057fcSDoug Moore 
2350467057fcSDoug Moore /*
23511c7c3c6aSMatthew Dillon  * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
23521c7c3c6aSMatthew Dillon  *
2353f1aaef47SDoug Moore  *	Return freed swap blocks to the swap bitmap, and free emptied swblk
2354f1aaef47SDoug Moore  *	metadata.  With 'freed' set, provide a count of freed blocks that were
2355f1aaef47SDoug Moore  *	not associated with valid resident pages.
23561c7c3c6aSMatthew Dillon  */
23571c7c3c6aSMatthew Dillon static void
2358baa1ccceSKonstantin Belousov swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count,
2359baa1ccceSKonstantin Belousov     vm_size_t *freed)
23601c7c3c6aSMatthew Dillon {
236152b35140SDoug Moore 	struct pctrie_iter blks, pages;
236294264705SDoug Moore 	struct page_range range;
236394264705SDoug Moore 	struct swblk *sb;
236494264705SDoug Moore 	vm_page_t m;
236594264705SDoug Moore 	vm_pindex_t last;
236694264705SDoug Moore 	vm_size_t fc;
236794264705SDoug Moore 	int i, limit, start;
236894264705SDoug Moore 
236994264705SDoug Moore 	VM_OBJECT_ASSERT_WLOCKED(object);
237094264705SDoug Moore 
237194264705SDoug Moore 	fc = 0;
237294264705SDoug Moore 	if (count == 0 || swblk_is_empty(object))
237394264705SDoug Moore 		goto out;
237494264705SDoug Moore 
237594264705SDoug Moore 	swp_pager_init_freerange(&range);
237676c60597SDoug Moore 	vm_page_iter_init(&pages, object);
237794264705SDoug Moore 	last = pindex + count;
23786af02087SDoug Moore 	for (sb = swblk_iter_limit_init(&blks, object, pindex, last),
237952b35140SDoug Moore 	    start = swblk_start(sb, pindex);
238052b35140SDoug Moore 	    sb != NULL; sb = swblk_iter_next(&blks), start = 0) {
238152b35140SDoug Moore 		limit = MIN(last - blks.index, SWAP_META_PAGES);
238294264705SDoug Moore 		for (i = start; i < limit; i++) {
238394264705SDoug Moore 			if (sb->d[i] == SWAPBLK_NONE)
238494264705SDoug Moore 				continue;
238594264705SDoug Moore 			swp_pager_update_freerange(&range, sb->d[i]);
238694264705SDoug Moore 			if (freed != NULL) {
238752b35140SDoug Moore 				m = vm_page_iter_lookup(&pages, blks.index + i);
238894264705SDoug Moore 				if (m == NULL || vm_page_none_valid(m))
238994264705SDoug Moore 					fc++;
239094264705SDoug Moore 			}
239194264705SDoug Moore 			sb->d[i] = SWAPBLK_NONE;
239294264705SDoug Moore 		}
239394264705SDoug Moore 		if (swp_pager_swblk_empty(sb, 0, start) &&
239494264705SDoug Moore 		    swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
239552b35140SDoug Moore 			swblk_iter_remove(&blks);
239694264705SDoug Moore 			uma_zfree(swblk_zone, sb);
239794264705SDoug Moore 		}
239894264705SDoug Moore 	}
239994264705SDoug Moore 	swp_pager_freeswapspace(&range);
240094264705SDoug Moore out:
240194264705SDoug Moore 	if (freed != NULL)
240294264705SDoug Moore 		*freed = fc;
24031c7c3c6aSMatthew Dillon }
24041c7c3c6aSMatthew Dillon 
2405a880104aSDoug Moore static void
24062a21cfe6SDoug Moore swp_pager_meta_free_block(struct swblk *sb, void *rangev)
2407a880104aSDoug Moore {
2408d2acf0a4SDoug Moore 	struct page_range *range = rangev;
2409d2acf0a4SDoug Moore 
2410a880104aSDoug Moore 	for (int i = 0; i < SWAP_META_PAGES; i++) {
2411a880104aSDoug Moore 		if (sb->d[i] != SWAPBLK_NONE)
2412a880104aSDoug Moore 			swp_pager_update_freerange(range, sb->d[i]);
2413a880104aSDoug Moore 	}
2414a880104aSDoug Moore 	uma_zfree(swblk_zone, sb);
2415a880104aSDoug Moore }
2416a880104aSDoug Moore 
24171c7c3c6aSMatthew Dillon /*
24181c7c3c6aSMatthew Dillon  * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
24191c7c3c6aSMatthew Dillon  *
24201c7c3c6aSMatthew Dillon  *	This routine locates and destroys all swap metadata associated with
24211c7c3c6aSMatthew Dillon  *	an object.
24221c7c3c6aSMatthew Dillon  */
24231c7c3c6aSMatthew Dillon static void
24241c7c3c6aSMatthew Dillon swp_pager_meta_free_all(vm_object_t object)
24251c7c3c6aSMatthew Dillon {
2426a880104aSDoug Moore 	struct page_range range;
24271c7c3c6aSMatthew Dillon 
242889f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
2429cb6757c0SMark Johnston 
2430a880104aSDoug Moore 	swp_pager_init_freerange(&range);
2431d2acf0a4SDoug Moore 	SWAP_PCTRIE_RECLAIM_CALLBACK(&object->un_pager.swp.swp_blks,
2432d2acf0a4SDoug Moore 	    swp_pager_meta_free_block, &range);
2433a880104aSDoug Moore 	swp_pager_freeswapspace(&range);
24341c7c3c6aSMatthew Dillon }
24351c7c3c6aSMatthew Dillon 
24361c7c3c6aSMatthew Dillon /*
24374abca9bbSAlan Cox  * SWP_PAGER_METACTL() -  misc control of swap meta data.
24381c7c3c6aSMatthew Dillon  *
24394abca9bbSAlan Cox  *	This routine is capable of looking up, or removing swapblk
24404abca9bbSAlan Cox  *	assignments in the swap meta data.  It returns the swapblk being
24414abca9bbSAlan Cox  *	looked-up, popped, or SWAPBLK_NONE if the block was invalid.
24421c7c3c6aSMatthew Dillon  *
24431c7c3c6aSMatthew Dillon  *	When acting on a busy resident page and paging is in progress, we
24441c7c3c6aSMatthew Dillon  *	have to wait until paging is complete but otherwise can act on the
24451c7c3c6aSMatthew Dillon  *	busy page.
24461c7c3c6aSMatthew Dillon  */
24471c7c3c6aSMatthew Dillon static daddr_t
244839f6d1e7SDoug Moore swp_pager_meta_lookup(struct pctrie_iter *blks, vm_pindex_t pindex)
24492f249180SPoul-Henning Kamp {
2450f425ab8eSKonstantin Belousov 	struct swblk *sb;
24514dcc5c2dSMatthew Dillon 
245239f6d1e7SDoug Moore 	sb = swblk_iter_lookup(blks, pindex);
2453f425ab8eSKonstantin Belousov 	if (sb == NULL)
2454f425ab8eSKonstantin Belousov 		return (SWAPBLK_NONE);
24558ecbf14bSDoug Moore 	return (sb->d[pindex % SWAP_META_PAGES]);
24561c7c3c6aSMatthew Dillon }
24571c7c3c6aSMatthew Dillon 
2458e9c0cc15SPoul-Henning Kamp /*
245994264705SDoug Moore  * Returns the least page index which is greater than or equal to the parameter
246094264705SDoug Moore  * pindex and for which there is a swap block allocated.  Returns OBJ_MAX_SIZE
246194264705SDoug Moore  * if are no allocated swap blocks for the object after the requested pindex.
246277d6fd97SKonstantin Belousov  */
246334951b0bSDoug Moore static vm_pindex_t
246434951b0bSDoug Moore swap_pager_iter_find_least(struct pctrie_iter *blks, vm_pindex_t pindex)
246577d6fd97SKonstantin Belousov {
2466f425ab8eSKonstantin Belousov 	struct swblk *sb;
2467f425ab8eSKonstantin Belousov 	int i;
246877d6fd97SKonstantin Belousov 
246934951b0bSDoug Moore 	if ((sb = swblk_iter_lookup_ge(blks, pindex)) == NULL)
247094264705SDoug Moore 		return (OBJ_MAX_SIZE);
247134951b0bSDoug Moore 	if (blks->index < pindex) {
247228af3eb6SDoug Moore 		for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2473f425ab8eSKonstantin Belousov 			if (sb->d[i] != SWAPBLK_NONE)
247434951b0bSDoug Moore 				return (blks->index + i);
247577d6fd97SKonstantin Belousov 		}
247634951b0bSDoug Moore 		if ((sb = swblk_iter_next(blks)) == NULL)
247794264705SDoug Moore 			return (OBJ_MAX_SIZE);
247828af3eb6SDoug Moore 	}
2479f425ab8eSKonstantin Belousov 	for (i = 0; i < SWAP_META_PAGES; i++) {
2480f425ab8eSKonstantin Belousov 		if (sb->d[i] != SWAPBLK_NONE)
248134951b0bSDoug Moore 			return (blks->index + i);
248277d6fd97SKonstantin Belousov 	}
2483f425ab8eSKonstantin Belousov 
2484f425ab8eSKonstantin Belousov 	/*
2485f425ab8eSKonstantin Belousov 	 * We get here if a swblk is present in the trie but it
2486f425ab8eSKonstantin Belousov 	 * doesn't map any blocks.
2487f425ab8eSKonstantin Belousov 	 */
248828af3eb6SDoug Moore 	MPASS(0);
248994264705SDoug Moore 	return (OBJ_MAX_SIZE);
249077d6fd97SKonstantin Belousov }
249177d6fd97SKonstantin Belousov 
249277d6fd97SKonstantin Belousov /*
2493db08b0b0SDoug Moore  * Find the first index >= pindex that has either a valid page or a swap
2494db08b0b0SDoug Moore  * block.
249534951b0bSDoug Moore  */
249634951b0bSDoug Moore vm_pindex_t
2497db08b0b0SDoug Moore swap_pager_seek_data(vm_object_t object, vm_pindex_t pindex)
249834951b0bSDoug Moore {
2499db08b0b0SDoug Moore 	struct pctrie_iter blks, pages;
2500db08b0b0SDoug Moore 	vm_page_t m;
2501db08b0b0SDoug Moore 	vm_pindex_t swap_index;
250234951b0bSDoug Moore 
250302e85d1cSDoug Moore 	VM_OBJECT_ASSERT_RLOCKED(object);
2504db08b0b0SDoug Moore 	vm_page_iter_init(&pages, object);
2505db08b0b0SDoug Moore 	m = vm_page_iter_lookup_ge(&pages, pindex);
2506db08b0b0SDoug Moore 	if (m != NULL) {
2507db08b0b0SDoug Moore 		if (!vm_page_any_valid(m))
2508db08b0b0SDoug Moore 			m = NULL;
2509db08b0b0SDoug Moore 		else if (pages.index == pindex)
2510db08b0b0SDoug Moore 			return (pages.index);
2511db08b0b0SDoug Moore 	}
251234951b0bSDoug Moore 	swblk_iter_init_only(&blks, object);
2513db08b0b0SDoug Moore 	swap_index = swap_pager_iter_find_least(&blks, pindex);
2514db08b0b0SDoug Moore 	if (swap_index == pindex)
2515db08b0b0SDoug Moore 		return (swap_index);
2516db08b0b0SDoug Moore 	if (swap_index == OBJ_MAX_SIZE)
2517db08b0b0SDoug Moore 		swap_index = object->size;
2518db08b0b0SDoug Moore 	if (m == NULL)
2519db08b0b0SDoug Moore 		return (swap_index);
2520db08b0b0SDoug Moore 
2521db08b0b0SDoug Moore 	while ((m = vm_radix_iter_step(&pages)) != NULL &&
2522db08b0b0SDoug Moore 	    pages.index < swap_index) {
2523db08b0b0SDoug Moore 		if (vm_page_any_valid(m))
2524db08b0b0SDoug Moore 			return (pages.index);
2525db08b0b0SDoug Moore 	}
2526db08b0b0SDoug Moore 	return (swap_index);
2527db08b0b0SDoug Moore }
2528db08b0b0SDoug Moore 
2529db08b0b0SDoug Moore /*
2530db08b0b0SDoug Moore  * Find the first index >= pindex that has neither a valid page nor a swap
2531db08b0b0SDoug Moore  * block.
2532db08b0b0SDoug Moore  */
2533db08b0b0SDoug Moore vm_pindex_t
2534db08b0b0SDoug Moore swap_pager_seek_hole(vm_object_t object, vm_pindex_t pindex)
2535db08b0b0SDoug Moore {
2536db08b0b0SDoug Moore 	struct pctrie_iter blks, pages;
2537db08b0b0SDoug Moore 	struct swblk *sb;
2538db08b0b0SDoug Moore 	vm_page_t m;
2539db08b0b0SDoug Moore 
2540faa9356fSDoug Moore 	VM_OBJECT_ASSERT_RLOCKED(object);
2541db08b0b0SDoug Moore 	vm_page_iter_init(&pages, object);
2542db08b0b0SDoug Moore 	swblk_iter_init_only(&blks, object);
2543db08b0b0SDoug Moore 	while (((m = vm_page_iter_lookup(&pages, pindex)) != NULL &&
2544db08b0b0SDoug Moore 	    vm_page_any_valid(m)) ||
2545db08b0b0SDoug Moore 	    ((sb = swblk_iter_lookup(&blks, pindex)) != NULL &&
2546db08b0b0SDoug Moore 	    sb->d[pindex % SWAP_META_PAGES] != SWAPBLK_NONE))
2547db08b0b0SDoug Moore 		pindex++;
2548db08b0b0SDoug Moore 	return (pindex);
254934951b0bSDoug Moore }
255034951b0bSDoug Moore 
255134951b0bSDoug Moore /*
255234951b0bSDoug Moore  * Is every page in the backing object or swap shadowed in the parent, and
255334951b0bSDoug Moore  * unbusy and valid in swap?
255434951b0bSDoug Moore  */
255534951b0bSDoug Moore bool
255634951b0bSDoug Moore swap_pager_scan_all_shadowed(vm_object_t object)
255734951b0bSDoug Moore {
255839f6d1e7SDoug Moore 	struct pctrie_iter backing_blks, backing_pages, blks, pages;
255934951b0bSDoug Moore 	vm_object_t backing_object;
256034951b0bSDoug Moore 	vm_page_t p, pp;
256134951b0bSDoug Moore 	vm_pindex_t backing_offset_index, new_pindex, pi, pi_ubound, ps, pv;
256234951b0bSDoug Moore 
256334951b0bSDoug Moore 	VM_OBJECT_ASSERT_WLOCKED(object);
256434951b0bSDoug Moore 	VM_OBJECT_ASSERT_WLOCKED(object->backing_object);
256534951b0bSDoug Moore 
256634951b0bSDoug Moore 	backing_object = object->backing_object;
256734951b0bSDoug Moore 
256834951b0bSDoug Moore 	if ((backing_object->flags & OBJ_ANON) == 0)
256934951b0bSDoug Moore 		return (false);
257034951b0bSDoug Moore 
257134951b0bSDoug Moore 	KASSERT((object->flags & OBJ_ANON) != 0,
257234951b0bSDoug Moore 	    ("Shadow object is not anonymous"));
257334951b0bSDoug Moore 	backing_offset_index = OFF_TO_IDX(object->backing_object_offset);
257434951b0bSDoug Moore 	pi_ubound = MIN(backing_object->size,
257534951b0bSDoug Moore 	    backing_offset_index + object->size);
257634951b0bSDoug Moore 	vm_page_iter_init(&pages, object);
257734951b0bSDoug Moore 	vm_page_iter_init(&backing_pages, backing_object);
257839f6d1e7SDoug Moore 	swblk_iter_init_only(&blks, object);
257934951b0bSDoug Moore 	swblk_iter_init_only(&backing_blks, backing_object);
258034951b0bSDoug Moore 
258134951b0bSDoug Moore 	/*
258234951b0bSDoug Moore 	 * Only check pages inside the parent object's range and inside the
258334951b0bSDoug Moore 	 * parent object's mapping of the backing object.
258434951b0bSDoug Moore 	 */
258534951b0bSDoug Moore 	pv = ps = pi = backing_offset_index - 1;
258634951b0bSDoug Moore 	for (;;) {
258734951b0bSDoug Moore 		if (pi == pv) {
258834951b0bSDoug Moore 			p = vm_page_iter_lookup_ge(&backing_pages, pv + 1);
258934951b0bSDoug Moore 			pv = p != NULL ? p->pindex : backing_object->size;
259034951b0bSDoug Moore 		}
259134951b0bSDoug Moore 		if (pi == ps)
259234951b0bSDoug Moore 			ps = swap_pager_iter_find_least(&backing_blks, ps + 1);
259334951b0bSDoug Moore 		pi = MIN(pv, ps);
259434951b0bSDoug Moore 		if (pi >= pi_ubound)
259534951b0bSDoug Moore 			break;
259634951b0bSDoug Moore 
259734951b0bSDoug Moore 		if (pi == pv) {
259834951b0bSDoug Moore 			/*
259934951b0bSDoug Moore 			 * If the backing object page is busy a grandparent or
260034951b0bSDoug Moore 			 * older page may still be undergoing CoW.  It is not
260134951b0bSDoug Moore 			 * safe to collapse the backing object until it is
260234951b0bSDoug Moore 			 * quiesced.
260334951b0bSDoug Moore 			 */
260434951b0bSDoug Moore 			if (vm_page_tryxbusy(p) == 0)
260534951b0bSDoug Moore 				return (false);
260634951b0bSDoug Moore 
260734951b0bSDoug Moore 			/*
260834951b0bSDoug Moore 			 * We raced with the fault handler that left newly
260934951b0bSDoug Moore 			 * allocated invalid page on the object queue and
261034951b0bSDoug Moore 			 * retried.
261134951b0bSDoug Moore 			 */
261234951b0bSDoug Moore 			if (!vm_page_all_valid(p))
261334951b0bSDoug Moore 				break;
261434951b0bSDoug Moore 
261534951b0bSDoug Moore 			/*
261634951b0bSDoug Moore 			 * Busy of p disallows fault handler to validate parent
261734951b0bSDoug Moore 			 * page (pp, below).
261834951b0bSDoug Moore 			 */
261934951b0bSDoug Moore 		}
262034951b0bSDoug Moore 
262134951b0bSDoug Moore 		/*
262234951b0bSDoug Moore 		 * See if the parent has the page or if the parent's object
262334951b0bSDoug Moore 		 * pager has the page.  If the parent has the page but the page
262434951b0bSDoug Moore 		 * is not valid, the parent's object pager must have the page.
262534951b0bSDoug Moore 		 *
262634951b0bSDoug Moore 		 * If this fails, the parent does not completely shadow the
262734951b0bSDoug Moore 		 * object and we might as well give up now.
262834951b0bSDoug Moore 		 */
262934951b0bSDoug Moore 		new_pindex = pi - backing_offset_index;
263034951b0bSDoug Moore 		pp = vm_page_iter_lookup(&pages, new_pindex);
263134951b0bSDoug Moore 
263234951b0bSDoug Moore 		/*
263334951b0bSDoug Moore 		 * The valid check here is stable due to object lock being
263434951b0bSDoug Moore 		 * required to clear valid and initiate paging.
263534951b0bSDoug Moore 		 */
263634951b0bSDoug Moore 		if ((pp == NULL || vm_page_none_valid(pp)) &&
263739f6d1e7SDoug Moore 		    !swp_pager_haspage_iter(&blks, new_pindex, NULL,
263839f6d1e7SDoug Moore 		    NULL))
263934951b0bSDoug Moore 			break;
264034951b0bSDoug Moore 		if (pi == pv)
264134951b0bSDoug Moore 			vm_page_xunbusy(p);
264234951b0bSDoug Moore 	}
264334951b0bSDoug Moore 	if (pi < pi_ubound) {
264434951b0bSDoug Moore 		if (pi == pv)
264534951b0bSDoug Moore 			vm_page_xunbusy(p);
264634951b0bSDoug Moore 		return (false);
264734951b0bSDoug Moore 	}
264834951b0bSDoug Moore 	return (true);
264934951b0bSDoug Moore }
265034951b0bSDoug Moore 
265134951b0bSDoug Moore /*
2652e9c0cc15SPoul-Henning Kamp  * System call swapon(name) enables swapping on device name,
2653e9c0cc15SPoul-Henning Kamp  * which must be in the swdevsw.  Return EBUSY
2654e9c0cc15SPoul-Henning Kamp  * if already swapping on this device.
2655e9c0cc15SPoul-Henning Kamp  */
2656e9c0cc15SPoul-Henning Kamp #ifndef _SYS_SYSPROTO_H_
2657e9c0cc15SPoul-Henning Kamp struct swapon_args {
2658e9c0cc15SPoul-Henning Kamp 	char *name;
2659e9c0cc15SPoul-Henning Kamp };
2660e9c0cc15SPoul-Henning Kamp #endif
2661e9c0cc15SPoul-Henning Kamp 
2662e9c0cc15SPoul-Henning Kamp int
26638451d0ddSKip Macy sys_swapon(struct thread *td, struct swapon_args *uap)
2664e9c0cc15SPoul-Henning Kamp {
2665e9c0cc15SPoul-Henning Kamp 	struct vattr attr;
2666e9c0cc15SPoul-Henning Kamp 	struct vnode *vp;
2667e9c0cc15SPoul-Henning Kamp 	struct nameidata nd;
2668e9c0cc15SPoul-Henning Kamp 	int error;
2669e9c0cc15SPoul-Henning Kamp 
2670acd3428bSRobert Watson 	error = priv_check(td, PRIV_SWAPON);
2671e9c0cc15SPoul-Henning Kamp 	if (error)
2672acd3428bSRobert Watson 		return (error);
2673e9c0cc15SPoul-Henning Kamp 
267404533e1eSKonstantin Belousov 	sx_xlock(&swdev_syscall_lock);
2675e9c0cc15SPoul-Henning Kamp 
2676e9c0cc15SPoul-Henning Kamp 	/*
2677e9c0cc15SPoul-Henning Kamp 	 * Swap metadata may not fit in the KVM if we have physical
2678e9c0cc15SPoul-Henning Kamp 	 * memory of >1GB.
2679e9c0cc15SPoul-Henning Kamp 	 */
2680f425ab8eSKonstantin Belousov 	if (swblk_zone == NULL) {
2681e9c0cc15SPoul-Henning Kamp 		error = ENOMEM;
2682e9c0cc15SPoul-Henning Kamp 		goto done;
2683e9c0cc15SPoul-Henning Kamp 	}
2684e9c0cc15SPoul-Henning Kamp 
26856ddf41faSKonstantin Belousov 	NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | LOCKLEAF | AUDITVNODE1,
26867e1d3eefSMateusz Guzik 	    UIO_USERSPACE, uap->name);
2687e9c0cc15SPoul-Henning Kamp 	error = namei(&nd);
2688e9c0cc15SPoul-Henning Kamp 	if (error)
2689e9c0cc15SPoul-Henning Kamp 		goto done;
2690e9c0cc15SPoul-Henning Kamp 
2691bb92cd7bSMateusz Guzik 	NDFREE_PNBUF(&nd);
2692e9c0cc15SPoul-Henning Kamp 	vp = nd.ni_vp;
2693e9c0cc15SPoul-Henning Kamp 
26947ad2a82dSMateusz Guzik 	if (vn_isdisk_error(vp, &error)) {
269588ad2d7bSKonstantin Belousov 		error = swapongeom(vp);
269620da9c2eSPoul-Henning Kamp 	} else if (vp->v_type == VREG &&
2697e9c0cc15SPoul-Henning Kamp 	    (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
26980359a12eSAttilio Rao 	    (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2699e9c0cc15SPoul-Henning Kamp 		/*
2700e9c0cc15SPoul-Henning Kamp 		 * Allow direct swapping to NFS regular files in the same
2701e9c0cc15SPoul-Henning Kamp 		 * way that nfs_mountroot() sets up diskless swapping.
2702e9c0cc15SPoul-Henning Kamp 		 */
270359efee01SPoul-Henning Kamp 		error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2704e9c0cc15SPoul-Henning Kamp 	}
2705e9c0cc15SPoul-Henning Kamp 
27066ddf41faSKonstantin Belousov 	if (error != 0)
27076ddf41faSKonstantin Belousov 		vput(vp);
27086ddf41faSKonstantin Belousov 	else
27096ddf41faSKonstantin Belousov 		VOP_UNLOCK(vp);
2710e9c0cc15SPoul-Henning Kamp done:
271104533e1eSKonstantin Belousov 	sx_xunlock(&swdev_syscall_lock);
2712e9c0cc15SPoul-Henning Kamp 	return (error);
2713e9c0cc15SPoul-Henning Kamp }
2714e9c0cc15SPoul-Henning Kamp 
27153ff863f1SDag-Erling Smørgrav /*
27163ff863f1SDag-Erling Smørgrav  * Check that the total amount of swap currently configured does not
27173ff863f1SDag-Erling Smørgrav  * exceed half the theoretical maximum.  If it does, print a warning
271835872e79SKonstantin Belousov  * message.
27193ff863f1SDag-Erling Smørgrav  */
272035872e79SKonstantin Belousov static void
272135872e79SKonstantin Belousov swapon_check_swzone(void)
27223ff863f1SDag-Erling Smørgrav {
27233ff863f1SDag-Erling Smørgrav 
27243ff863f1SDag-Erling Smørgrav 	/* recommend using no more than half that amount */
2725303fa05aSKonstantin Belousov 	if (swap_total > swap_maxpages / 2) {
27263ff863f1SDag-Erling Smørgrav 		printf("warning: total configured swap (%lu pages) "
27273ff863f1SDag-Erling Smørgrav 		    "exceeds maximum recommended amount (%lu pages).\n",
2728303fa05aSKonstantin Belousov 		    swap_total, swap_maxpages / 2);
27293ff863f1SDag-Erling Smørgrav 		printf("warning: increase kern.maxswzone "
27303ff863f1SDag-Erling Smørgrav 		    "or reduce amount of swap.\n");
27313ff863f1SDag-Erling Smørgrav 	}
27323ff863f1SDag-Erling Smørgrav }
27333ff863f1SDag-Erling Smørgrav 
273459efee01SPoul-Henning Kamp static void
27352cc718a1SKonstantin Belousov swaponsomething(struct vnode *vp, void *id, u_long nblks,
27362cc718a1SKonstantin Belousov     sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2737e9c0cc15SPoul-Henning Kamp {
27382d9974c1SAlan Cox 	struct swdevt *sp, *tsp;
273934e2051fSMark Johnston 	daddr_t dvbase;
2740e9c0cc15SPoul-Henning Kamp 
2741e9c0cc15SPoul-Henning Kamp 	/*
2742e9c0cc15SPoul-Henning Kamp 	 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2743e9c0cc15SPoul-Henning Kamp 	 * First chop nblks off to page-align it, then convert.
2744e9c0cc15SPoul-Henning Kamp 	 *
2745e9c0cc15SPoul-Henning Kamp 	 * sw->sw_nblks is in page-sized chunks now too.
2746e9c0cc15SPoul-Henning Kamp 	 */
2747e9c0cc15SPoul-Henning Kamp 	nblks &= ~(ctodb(1) - 1);
2748e9c0cc15SPoul-Henning Kamp 	nblks = dbtoc(nblks);
2749e9c0cc15SPoul-Henning Kamp 
27508f60c087SPoul-Henning Kamp 	sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
275100fd73d2SDoug Moore 	sp->sw_blist = blist_create(nblks, M_WAITOK);
2752dee34ca4SPoul-Henning Kamp 	sp->sw_vp = vp;
2753dee34ca4SPoul-Henning Kamp 	sp->sw_id = id;
2754f3732fd1SPoul-Henning Kamp 	sp->sw_dev = dev;
2755e9c0cc15SPoul-Henning Kamp 	sp->sw_nblks = nblks;
2756e9c0cc15SPoul-Henning Kamp 	sp->sw_used = 0;
275759efee01SPoul-Henning Kamp 	sp->sw_strategy = strategy;
2758dee34ca4SPoul-Henning Kamp 	sp->sw_close = close;
27592cc718a1SKonstantin Belousov 	sp->sw_flags = flags;
2760e9c0cc15SPoul-Henning Kamp 
2761e9c0cc15SPoul-Henning Kamp 	/*
2762504f5e29SDoug Moore 	 * Do not free the first blocks in order to avoid overwriting
27638f60c087SPoul-Henning Kamp 	 * any bsd label at the front of the partition
2764e9c0cc15SPoul-Henning Kamp 	 */
2765504f5e29SDoug Moore 	blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2766504f5e29SDoug Moore 	    nblks - howmany(BBSIZE, PAGE_SIZE));
2767e9c0cc15SPoul-Henning Kamp 
27682d9974c1SAlan Cox 	dvbase = 0;
276920da9c2eSPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
27702d9974c1SAlan Cox 	TAILQ_FOREACH(tsp, &swtailq, sw_list) {
27712d9974c1SAlan Cox 		if (tsp->sw_end >= dvbase) {
27722d9974c1SAlan Cox 			/*
27732d9974c1SAlan Cox 			 * We put one uncovered page between the devices
27742d9974c1SAlan Cox 			 * in order to definitively prevent any cross-device
27752d9974c1SAlan Cox 			 * I/O requests
27762d9974c1SAlan Cox 			 */
27772d9974c1SAlan Cox 			dvbase = tsp->sw_end + 1;
27782d9974c1SAlan Cox 		}
27792d9974c1SAlan Cox 	}
27802d9974c1SAlan Cox 	sp->sw_first = dvbase;
27812d9974c1SAlan Cox 	sp->sw_end = dvbase + nblks;
27828f60c087SPoul-Henning Kamp 	TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
27838f60c087SPoul-Henning Kamp 	nswapdev++;
2784504f5e29SDoug Moore 	swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2785e8bb589dSMatt Macy 	swap_total += nblks;
278635872e79SKonstantin Belousov 	swapon_check_swzone();
2787d05bc129SAlan Cox 	swp_sizecheck();
2788d05bc129SAlan Cox 	mtx_unlock(&sw_dev_mtx);
2789b1fd102eSMark Johnston 	EVENTHANDLER_INVOKE(swapon, sp);
279059efee01SPoul-Henning Kamp }
2791e9c0cc15SPoul-Henning Kamp 
2792e9c0cc15SPoul-Henning Kamp /*
2793e9c0cc15SPoul-Henning Kamp  * SYSCALL: swapoff(devname)
2794e9c0cc15SPoul-Henning Kamp  *
2795e9c0cc15SPoul-Henning Kamp  * Disable swapping on the given device.
2796dee34ca4SPoul-Henning Kamp  *
2797dee34ca4SPoul-Henning Kamp  * XXX: Badly designed system call: it should use a device index
2798dee34ca4SPoul-Henning Kamp  * rather than filename as specification.  We keep sw_vp around
2799dee34ca4SPoul-Henning Kamp  * only to make this work.
2800e9c0cc15SPoul-Henning Kamp  */
280153465702SKonstantin Belousov static int
280253465702SKonstantin Belousov kern_swapoff(struct thread *td, const char *name, enum uio_seg name_seg,
280353465702SKonstantin Belousov     u_int flags)
2804e9c0cc15SPoul-Henning Kamp {
2805e9c0cc15SPoul-Henning Kamp 	struct vnode *vp;
2806e9c0cc15SPoul-Henning Kamp 	struct nameidata nd;
2807e9c0cc15SPoul-Henning Kamp 	struct swdevt *sp;
280853465702SKonstantin Belousov 	int error;
2809e9c0cc15SPoul-Henning Kamp 
2810acd3428bSRobert Watson 	error = priv_check(td, PRIV_SWAPOFF);
2811a4e4132fSKonstantin Belousov 	if (error != 0)
2812a4e4132fSKonstantin Belousov 		return (error);
281353465702SKonstantin Belousov 	if ((flags & ~(SWAPOFF_FORCE)) != 0)
2814a4e4132fSKonstantin Belousov 		return (EINVAL);
2815a4e4132fSKonstantin Belousov 
281604533e1eSKonstantin Belousov 	sx_xlock(&swdev_syscall_lock);
2817e9c0cc15SPoul-Henning Kamp 
281853465702SKonstantin Belousov 	NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, name_seg, name);
2819e9c0cc15SPoul-Henning Kamp 	error = namei(&nd);
2820e9c0cc15SPoul-Henning Kamp 	if (error)
2821e9c0cc15SPoul-Henning Kamp 		goto done;
2822bb92cd7bSMateusz Guzik 	NDFREE_PNBUF(&nd);
2823e9c0cc15SPoul-Henning Kamp 	vp = nd.ni_vp;
2824e9c0cc15SPoul-Henning Kamp 
282520da9c2eSPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
28268f60c087SPoul-Henning Kamp 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2827dee34ca4SPoul-Henning Kamp 		if (sp->sw_vp == vp)
28280909f38aSPawel Jakub Dawidek 			break;
2829e9c0cc15SPoul-Henning Kamp 	}
283020da9c2eSPoul-Henning Kamp 	mtx_unlock(&sw_dev_mtx);
28310909f38aSPawel Jakub Dawidek 	if (sp == NULL) {
2832e9c0cc15SPoul-Henning Kamp 		error = EINVAL;
2833e9c0cc15SPoul-Henning Kamp 		goto done;
28340909f38aSPawel Jakub Dawidek 	}
283553465702SKonstantin Belousov 	error = swapoff_one(sp, td->td_ucred, flags);
28360909f38aSPawel Jakub Dawidek done:
283704533e1eSKonstantin Belousov 	sx_xunlock(&swdev_syscall_lock);
28380909f38aSPawel Jakub Dawidek 	return (error);
28390909f38aSPawel Jakub Dawidek }
28400909f38aSPawel Jakub Dawidek 
284153465702SKonstantin Belousov 
284253465702SKonstantin Belousov #ifdef COMPAT_FREEBSD13
284353465702SKonstantin Belousov int
284453465702SKonstantin Belousov freebsd13_swapoff(struct thread *td, struct freebsd13_swapoff_args *uap)
284553465702SKonstantin Belousov {
284653465702SKonstantin Belousov 	return (kern_swapoff(td, uap->name, UIO_USERSPACE, 0));
284753465702SKonstantin Belousov }
284853465702SKonstantin Belousov #endif
284953465702SKonstantin Belousov 
285053465702SKonstantin Belousov int
285153465702SKonstantin Belousov sys_swapoff(struct thread *td, struct swapoff_args *uap)
285253465702SKonstantin Belousov {
285353465702SKonstantin Belousov 	return (kern_swapoff(td, uap->name, UIO_USERSPACE, uap->flags));
285453465702SKonstantin Belousov }
285553465702SKonstantin Belousov 
28560909f38aSPawel Jakub Dawidek static int
2857e8dc2ba2SKonstantin Belousov swapoff_one(struct swdevt *sp, struct ucred *cred, u_int flags)
28580909f38aSPawel Jakub Dawidek {
285903bdd65fSAlan Cox 	u_long nblks;
2860e9c0cc15SPoul-Henning Kamp #ifdef MAC
28610909f38aSPawel Jakub Dawidek 	int error;
2862e9c0cc15SPoul-Henning Kamp #endif
2863e9c0cc15SPoul-Henning Kamp 
286404533e1eSKonstantin Belousov 	sx_assert(&swdev_syscall_lock, SA_XLOCKED);
28650909f38aSPawel Jakub Dawidek #ifdef MAC
2866cb05b60aSAttilio Rao 	(void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
286735918c55SChristian S.J. Peron 	error = mac_system_check_swapoff(cred, sp->sw_vp);
2868b249ce48SMateusz Guzik 	(void) VOP_UNLOCK(sp->sw_vp);
28690909f38aSPawel Jakub Dawidek 	if (error != 0)
28700909f38aSPawel Jakub Dawidek 		return (error);
28710909f38aSPawel Jakub Dawidek #endif
2872e9c0cc15SPoul-Henning Kamp 	nblks = sp->sw_nblks;
2873e9c0cc15SPoul-Henning Kamp 
2874e9c0cc15SPoul-Henning Kamp 	/*
2875e9c0cc15SPoul-Henning Kamp 	 * We can turn off this swap device safely only if the
2876e9c0cc15SPoul-Henning Kamp 	 * available virtual memory in the system will fit the amount
2877e9c0cc15SPoul-Henning Kamp 	 * of data we will have to page back in, plus an epsilon so
2878e9c0cc15SPoul-Henning Kamp 	 * the system doesn't become critically low on swap space.
28790190c38bSKonstantin Belousov 	 * The vm_free_count() part does not account e.g. for clean
28800190c38bSKonstantin Belousov 	 * pages that can be immediately reclaimed without paging, so
28810190c38bSKonstantin Belousov 	 * this is a very rough estimation.
28820190c38bSKonstantin Belousov 	 *
28830190c38bSKonstantin Belousov 	 * On the other hand, not turning swap off on swapoff_all()
28840190c38bSKonstantin Belousov 	 * means that we can lose swap data when filesystems go away,
28850190c38bSKonstantin Belousov 	 * which is arguably worse.
2886e9c0cc15SPoul-Henning Kamp 	 */
2887e8dc2ba2SKonstantin Belousov 	if ((flags & SWAPOFF_FORCE) == 0 &&
28880190c38bSKonstantin Belousov 	    vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
28890909f38aSPawel Jakub Dawidek 		return (ENOMEM);
2890e9c0cc15SPoul-Henning Kamp 
2891e9c0cc15SPoul-Henning Kamp 	/*
2892e9c0cc15SPoul-Henning Kamp 	 * Prevent further allocations on this device.
2893e9c0cc15SPoul-Henning Kamp 	 */
28942928cef7SAlan Cox 	mtx_lock(&sw_dev_mtx);
2895e9c0cc15SPoul-Henning Kamp 	sp->sw_flags |= SW_CLOSING;
289603bdd65fSAlan Cox 	swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2897e8bb589dSMatt Macy 	swap_total -= nblks;
28982928cef7SAlan Cox 	mtx_unlock(&sw_dev_mtx);
2899e9c0cc15SPoul-Henning Kamp 
2900e9c0cc15SPoul-Henning Kamp 	/*
2901e9c0cc15SPoul-Henning Kamp 	 * Page in the contents of the device and close it.
2902e9c0cc15SPoul-Henning Kamp 	 */
2903b3fed13eSDavid Schultz 	swap_pager_swapoff(sp);
2904e9c0cc15SPoul-Henning Kamp 
290535918c55SChristian S.J. Peron 	sp->sw_close(curthread, sp);
290620da9c2eSPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
29079e3e3fe5SWarner Losh 	sp->sw_id = NULL;
29088f60c087SPoul-Henning Kamp 	TAILQ_REMOVE(&swtailq, sp, sw_list);
29090676a140SAlan Cox 	nswapdev--;
29107dea2c2eSAlan Cox 	if (nswapdev == 0) {
29117dea2c2eSAlan Cox 		swap_pager_full = 2;
29127dea2c2eSAlan Cox 		swap_pager_almost_full = 1;
29137dea2c2eSAlan Cox 	}
29148f60c087SPoul-Henning Kamp 	if (swdevhd == sp)
29158f60c087SPoul-Henning Kamp 		swdevhd = NULL;
2916d05bc129SAlan Cox 	mtx_unlock(&sw_dev_mtx);
29178f60c087SPoul-Henning Kamp 	blist_destroy(sp->sw_blist);
29188f60c087SPoul-Henning Kamp 	free(sp, M_VMPGDATA);
29190909f38aSPawel Jakub Dawidek 	return (0);
29200909f38aSPawel Jakub Dawidek }
2921e9c0cc15SPoul-Henning Kamp 
29220909f38aSPawel Jakub Dawidek void
29230909f38aSPawel Jakub Dawidek swapoff_all(void)
29240909f38aSPawel Jakub Dawidek {
29250909f38aSPawel Jakub Dawidek 	struct swdevt *sp, *spt;
29260909f38aSPawel Jakub Dawidek 	const char *devname;
29270909f38aSPawel Jakub Dawidek 	int error;
29280909f38aSPawel Jakub Dawidek 
292904533e1eSKonstantin Belousov 	sx_xlock(&swdev_syscall_lock);
29300909f38aSPawel Jakub Dawidek 
29310909f38aSPawel Jakub Dawidek 	mtx_lock(&sw_dev_mtx);
29320909f38aSPawel Jakub Dawidek 	TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
29330909f38aSPawel Jakub Dawidek 		mtx_unlock(&sw_dev_mtx);
29347ad2a82dSMateusz Guzik 		if (vn_isdisk(sp->sw_vp))
29357870adb6SEd Schouten 			devname = devtoname(sp->sw_vp->v_rdev);
29360909f38aSPawel Jakub Dawidek 		else
29370909f38aSPawel Jakub Dawidek 			devname = "[file]";
2938e8dc2ba2SKonstantin Belousov 		error = swapoff_one(sp, thread0.td_ucred, SWAPOFF_FORCE);
29390909f38aSPawel Jakub Dawidek 		if (error != 0) {
29400909f38aSPawel Jakub Dawidek 			printf("Cannot remove swap device %s (error=%d), "
29410909f38aSPawel Jakub Dawidek 			    "skipping.\n", devname, error);
29420909f38aSPawel Jakub Dawidek 		} else if (bootverbose) {
29430909f38aSPawel Jakub Dawidek 			printf("Swap device %s removed.\n", devname);
29440909f38aSPawel Jakub Dawidek 		}
29450909f38aSPawel Jakub Dawidek 		mtx_lock(&sw_dev_mtx);
29460909f38aSPawel Jakub Dawidek 	}
29470909f38aSPawel Jakub Dawidek 	mtx_unlock(&sw_dev_mtx);
29480909f38aSPawel Jakub Dawidek 
294904533e1eSKonstantin Belousov 	sx_xunlock(&swdev_syscall_lock);
2950e9c0cc15SPoul-Henning Kamp }
2951e9c0cc15SPoul-Henning Kamp 
2952567104a1SPoul-Henning Kamp void
2953567104a1SPoul-Henning Kamp swap_pager_status(int *total, int *used)
2954567104a1SPoul-Henning Kamp {
2955567104a1SPoul-Henning Kamp 
29567ce3a312SMateusz Guzik 	*total = swap_total;
29577ce3a312SMateusz Guzik 	*used = swap_total - swap_pager_avail -
29587ce3a312SMateusz Guzik 	    nswapdev * howmany(BBSIZE, PAGE_SIZE);
2959567104a1SPoul-Henning Kamp }
2960567104a1SPoul-Henning Kamp 
2961dda4f960SKonstantin Belousov int
2962dda4f960SKonstantin Belousov swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2963dda4f960SKonstantin Belousov {
2964dda4f960SKonstantin Belousov 	struct swdevt *sp;
29657870adb6SEd Schouten 	const char *tmp_devname;
2966dda4f960SKonstantin Belousov 	int error, n;
2967dda4f960SKonstantin Belousov 
2968dda4f960SKonstantin Belousov 	n = 0;
2969dda4f960SKonstantin Belousov 	error = ENOENT;
2970dda4f960SKonstantin Belousov 	mtx_lock(&sw_dev_mtx);
2971dda4f960SKonstantin Belousov 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2972dda4f960SKonstantin Belousov 		if (n != name) {
2973dda4f960SKonstantin Belousov 			n++;
2974dda4f960SKonstantin Belousov 			continue;
2975dda4f960SKonstantin Belousov 		}
2976dda4f960SKonstantin Belousov 		xs->xsw_version = XSWDEV_VERSION;
2977dda4f960SKonstantin Belousov 		xs->xsw_dev = sp->sw_dev;
2978dda4f960SKonstantin Belousov 		xs->xsw_flags = sp->sw_flags;
2979dda4f960SKonstantin Belousov 		xs->xsw_nblks = sp->sw_nblks;
2980dda4f960SKonstantin Belousov 		xs->xsw_used = sp->sw_used;
2981dda4f960SKonstantin Belousov 		if (devname != NULL) {
29827ad2a82dSMateusz Guzik 			if (vn_isdisk(sp->sw_vp))
29837870adb6SEd Schouten 				tmp_devname = devtoname(sp->sw_vp->v_rdev);
2984dda4f960SKonstantin Belousov 			else
2985dda4f960SKonstantin Belousov 				tmp_devname = "[file]";
2986dda4f960SKonstantin Belousov 			strncpy(devname, tmp_devname, len);
2987dda4f960SKonstantin Belousov 		}
2988dda4f960SKonstantin Belousov 		error = 0;
2989dda4f960SKonstantin Belousov 		break;
2990dda4f960SKonstantin Belousov 	}
2991dda4f960SKonstantin Belousov 	mtx_unlock(&sw_dev_mtx);
2992dda4f960SKonstantin Belousov 	return (error);
2993dda4f960SKonstantin Belousov }
2994dda4f960SKonstantin Belousov 
299569921123SKonstantin Belousov #if defined(COMPAT_FREEBSD11)
299669921123SKonstantin Belousov #define XSWDEV_VERSION_11	1
299769921123SKonstantin Belousov struct xswdev11 {
299869921123SKonstantin Belousov 	u_int	xsw_version;
299969921123SKonstantin Belousov 	uint32_t xsw_dev;
300069921123SKonstantin Belousov 	int	xsw_flags;
300169921123SKonstantin Belousov 	int	xsw_nblks;
300269921123SKonstantin Belousov 	int     xsw_used;
300369921123SKonstantin Belousov };
300469921123SKonstantin Belousov #endif
300569921123SKonstantin Belousov 
3006f6d281e8SKonstantin Belousov #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
3007f6d281e8SKonstantin Belousov struct xswdev32 {
3008f6d281e8SKonstantin Belousov 	u_int	xsw_version;
3009f6d281e8SKonstantin Belousov 	u_int	xsw_dev1, xsw_dev2;
3010f6d281e8SKonstantin Belousov 	int	xsw_flags;
3011f6d281e8SKonstantin Belousov 	int	xsw_nblks;
3012f6d281e8SKonstantin Belousov 	int     xsw_used;
3013f6d281e8SKonstantin Belousov };
3014f6d281e8SKonstantin Belousov #endif
3015f6d281e8SKonstantin Belousov 
3016e9c0cc15SPoul-Henning Kamp static int
3017e9c0cc15SPoul-Henning Kamp sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
3018e9c0cc15SPoul-Henning Kamp {
3019e9c0cc15SPoul-Henning Kamp 	struct xswdev xs;
3020f6d281e8SKonstantin Belousov #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
3021f6d281e8SKonstantin Belousov 	struct xswdev32 xs32;
3022f6d281e8SKonstantin Belousov #endif
302369921123SKonstantin Belousov #if defined(COMPAT_FREEBSD11)
302469921123SKonstantin Belousov 	struct xswdev11 xs11;
302569921123SKonstantin Belousov #endif
3026dda4f960SKonstantin Belousov 	int error;
3027e9c0cc15SPoul-Henning Kamp 
3028e9c0cc15SPoul-Henning Kamp 	if (arg2 != 1)			/* name length */
3029e9c0cc15SPoul-Henning Kamp 		return (EINVAL);
303006d1fd9fSMark Johnston 
303106d1fd9fSMark Johnston 	memset(&xs, 0, sizeof(xs));
3032dda4f960SKonstantin Belousov 	error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
3033dda4f960SKonstantin Belousov 	if (error != 0)
3034dda4f960SKonstantin Belousov 		return (error);
3035f6d281e8SKonstantin Belousov #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
3036f6d281e8SKonstantin Belousov 	if (req->oldlen == sizeof(xs32)) {
303706d1fd9fSMark Johnston 		memset(&xs32, 0, sizeof(xs32));
3038f6d281e8SKonstantin Belousov 		xs32.xsw_version = XSWDEV_VERSION;
3039f6d281e8SKonstantin Belousov 		xs32.xsw_dev1 = xs.xsw_dev;
3040f6d281e8SKonstantin Belousov 		xs32.xsw_dev2 = xs.xsw_dev >> 32;
3041f6d281e8SKonstantin Belousov 		xs32.xsw_flags = xs.xsw_flags;
3042f6d281e8SKonstantin Belousov 		xs32.xsw_nblks = xs.xsw_nblks;
3043f6d281e8SKonstantin Belousov 		xs32.xsw_used = xs.xsw_used;
3044f6d281e8SKonstantin Belousov 		error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
3045f6d281e8SKonstantin Belousov 		return (error);
3046f6d281e8SKonstantin Belousov 	}
3047f6d281e8SKonstantin Belousov #endif
304869921123SKonstantin Belousov #if defined(COMPAT_FREEBSD11)
304969921123SKonstantin Belousov 	if (req->oldlen == sizeof(xs11)) {
305006d1fd9fSMark Johnston 		memset(&xs11, 0, sizeof(xs11));
305169921123SKonstantin Belousov 		xs11.xsw_version = XSWDEV_VERSION_11;
305269921123SKonstantin Belousov 		xs11.xsw_dev = xs.xsw_dev; /* truncation */
305369921123SKonstantin Belousov 		xs11.xsw_flags = xs.xsw_flags;
305469921123SKonstantin Belousov 		xs11.xsw_nblks = xs.xsw_nblks;
305569921123SKonstantin Belousov 		xs11.xsw_used = xs.xsw_used;
305669921123SKonstantin Belousov 		error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
3057f6d281e8SKonstantin Belousov 		return (error);
3058f6d281e8SKonstantin Belousov 	}
305969921123SKonstantin Belousov #endif
3060e9c0cc15SPoul-Henning Kamp 	error = SYSCTL_OUT(req, &xs, sizeof(xs));
3061e9c0cc15SPoul-Henning Kamp 	return (error);
3062e9c0cc15SPoul-Henning Kamp }
3063e9c0cc15SPoul-Henning Kamp 
30648f60c087SPoul-Henning Kamp SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
3065e9c0cc15SPoul-Henning Kamp     "Number of swap devices");
30664c36e917SKonstantin Belousov SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
30674c36e917SKonstantin Belousov     sysctl_vm_swap_info,
3068e9c0cc15SPoul-Henning Kamp     "Swap statistics by device");
3069ec38b344SPoul-Henning Kamp 
3070ec38b344SPoul-Henning Kamp /*
3071f425ab8eSKonstantin Belousov  * Count the approximate swap usage in pages for a vmspace.  The
3072f425ab8eSKonstantin Belousov  * shadowed or not yet copied on write swap blocks are not accounted.
3073ec38b344SPoul-Henning Kamp  * The map must be locked.
3074ec38b344SPoul-Henning Kamp  */
30752860553aSRebecca Cran long
3076ec38b344SPoul-Henning Kamp vmspace_swap_count(struct vmspace *vmspace)
3077ec38b344SPoul-Henning Kamp {
307852b35140SDoug Moore 	struct pctrie_iter blks;
307965d8409cSRebecca Cran 	vm_map_t map;
3080ec38b344SPoul-Henning Kamp 	vm_map_entry_t cur;
308165d8409cSRebecca Cran 	vm_object_t object;
3082f425ab8eSKonstantin Belousov 	struct swblk *sb;
3083f425ab8eSKonstantin Belousov 	vm_pindex_t e, pi;
3084f425ab8eSKonstantin Belousov 	long count;
308552b35140SDoug Moore 	int i, limit, start;
308665d8409cSRebecca Cran 
308765d8409cSRebecca Cran 	map = &vmspace->vm_map;
308865d8409cSRebecca Cran 	count = 0;
3089ec38b344SPoul-Henning Kamp 
30902288078cSDoug Moore 	VM_MAP_ENTRY_FOREACH(cur, map) {
3091f425ab8eSKonstantin Belousov 		if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
3092f425ab8eSKonstantin Belousov 			continue;
3093f425ab8eSKonstantin Belousov 		object = cur->object.vm_object;
30944b8365d7SKonstantin Belousov 		if (object == NULL || (object->flags & OBJ_SWAP) == 0)
3095f425ab8eSKonstantin Belousov 			continue;
3096f425ab8eSKonstantin Belousov 		VM_OBJECT_RLOCK(object);
30974b8365d7SKonstantin Belousov 		if ((object->flags & OBJ_SWAP) == 0)
3098f425ab8eSKonstantin Belousov 			goto unlock;
3099f425ab8eSKonstantin Belousov 		pi = OFF_TO_IDX(cur->offset);
3100f425ab8eSKonstantin Belousov 		e = pi + OFF_TO_IDX(cur->end - cur->start);
31016af02087SDoug Moore 		for (sb = swblk_iter_limit_init(&blks, object, pi, e),
310252b35140SDoug Moore 		    start = swblk_start(sb, pi);
310352b35140SDoug Moore 		    sb != NULL; sb = swblk_iter_next(&blks), start = 0) {
310452b35140SDoug Moore 			limit = MIN(e - blks.index, SWAP_META_PAGES);
310552b35140SDoug Moore 			for (i = start; i < limit; i++) {
310652b35140SDoug Moore 				if (sb->d[i] != SWAPBLK_NONE)
3107f425ab8eSKonstantin Belousov 					count++;
3108ec38b344SPoul-Henning Kamp 			}
3109ec38b344SPoul-Henning Kamp 		}
3110f425ab8eSKonstantin Belousov unlock:
3111f425ab8eSKonstantin Belousov 		VM_OBJECT_RUNLOCK(object);
3112ec38b344SPoul-Henning Kamp 	}
3113ec38b344SPoul-Henning Kamp 	return (count);
3114ec38b344SPoul-Henning Kamp }
3115dee34ca4SPoul-Henning Kamp 
3116dee34ca4SPoul-Henning Kamp /*
3117dee34ca4SPoul-Henning Kamp  * GEOM backend
3118dee34ca4SPoul-Henning Kamp  *
3119dee34ca4SPoul-Henning Kamp  * Swapping onto disk devices.
3120dee34ca4SPoul-Henning Kamp  *
3121dee34ca4SPoul-Henning Kamp  */
3122dee34ca4SPoul-Henning Kamp 
31235721c9c7SPoul-Henning Kamp static g_orphan_t swapgeom_orphan;
31245721c9c7SPoul-Henning Kamp 
3125dee34ca4SPoul-Henning Kamp static struct g_class g_swap_class = {
3126dee34ca4SPoul-Henning Kamp 	.name = "SWAP",
31275721c9c7SPoul-Henning Kamp 	.version = G_VERSION,
31285721c9c7SPoul-Henning Kamp 	.orphan = swapgeom_orphan,
3129dee34ca4SPoul-Henning Kamp };
3130dee34ca4SPoul-Henning Kamp 
3131dee34ca4SPoul-Henning Kamp DECLARE_GEOM_CLASS(g_swap_class, g_class);
3132dee34ca4SPoul-Henning Kamp 
3133dee34ca4SPoul-Henning Kamp static void
31343398491bSAlexander Motin swapgeom_close_ev(void *arg, int flags)
31353398491bSAlexander Motin {
31363398491bSAlexander Motin 	struct g_consumer *cp;
31373398491bSAlexander Motin 
31383398491bSAlexander Motin 	cp = arg;
31393398491bSAlexander Motin 	g_access(cp, -1, -1, 0);
31403398491bSAlexander Motin 	g_detach(cp);
31413398491bSAlexander Motin 	g_destroy_consumer(cp);
31423398491bSAlexander Motin }
31433398491bSAlexander Motin 
31449e3e3fe5SWarner Losh /*
31459e3e3fe5SWarner Losh  * Add a reference to the g_consumer for an inflight transaction.
31469e3e3fe5SWarner Losh  */
31479e3e3fe5SWarner Losh static void
31489e3e3fe5SWarner Losh swapgeom_acquire(struct g_consumer *cp)
31499e3e3fe5SWarner Losh {
31509e3e3fe5SWarner Losh 
31519e3e3fe5SWarner Losh 	mtx_assert(&sw_dev_mtx, MA_OWNED);
31529e3e3fe5SWarner Losh 	cp->index++;
31539e3e3fe5SWarner Losh }
31549e3e3fe5SWarner Losh 
31559e3e3fe5SWarner Losh /*
31560c657d22SKonstantin Belousov  * Remove a reference from the g_consumer.  Post a close event if all
31570c657d22SKonstantin Belousov  * references go away, since the function might be called from the
31580c657d22SKonstantin Belousov  * biodone context.
31599e3e3fe5SWarner Losh  */
31609e3e3fe5SWarner Losh static void
31619e3e3fe5SWarner Losh swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
31629e3e3fe5SWarner Losh {
31639e3e3fe5SWarner Losh 
31649e3e3fe5SWarner Losh 	mtx_assert(&sw_dev_mtx, MA_OWNED);
31659e3e3fe5SWarner Losh 	cp->index--;
31669e3e3fe5SWarner Losh 	if (cp->index == 0) {
31679e3e3fe5SWarner Losh 		if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
31689e3e3fe5SWarner Losh 			sp->sw_id = NULL;
31699e3e3fe5SWarner Losh 	}
31709e3e3fe5SWarner Losh }
31719e3e3fe5SWarner Losh 
31723398491bSAlexander Motin static void
3173dee34ca4SPoul-Henning Kamp swapgeom_done(struct bio *bp2)
3174dee34ca4SPoul-Henning Kamp {
31753398491bSAlexander Motin 	struct swdevt *sp;
3176dee34ca4SPoul-Henning Kamp 	struct buf *bp;
31773398491bSAlexander Motin 	struct g_consumer *cp;
3178dee34ca4SPoul-Henning Kamp 
3179dee34ca4SPoul-Henning Kamp 	bp = bp2->bio_caller2;
31803398491bSAlexander Motin 	cp = bp2->bio_from;
3181c5d3d25eSPoul-Henning Kamp 	bp->b_ioflags = bp2->bio_flags;
3182dee34ca4SPoul-Henning Kamp 	if (bp2->bio_error)
3183dee34ca4SPoul-Henning Kamp 		bp->b_ioflags |= BIO_ERROR;
3184c5d3d25eSPoul-Henning Kamp 	bp->b_resid = bp->b_bcount - bp2->bio_completed;
3185c5d3d25eSPoul-Henning Kamp 	bp->b_error = bp2->bio_error;
3186756a5412SGleb Smirnoff 	bp->b_caller1 = NULL;
3187dee34ca4SPoul-Henning Kamp 	bufdone(bp);
31883398491bSAlexander Motin 	sp = bp2->bio_caller1;
31899e3e3fe5SWarner Losh 	mtx_lock(&sw_dev_mtx);
31909e3e3fe5SWarner Losh 	swapgeom_release(cp, sp);
31913398491bSAlexander Motin 	mtx_unlock(&sw_dev_mtx);
3192dee34ca4SPoul-Henning Kamp 	g_destroy_bio(bp2);
3193dee34ca4SPoul-Henning Kamp }
3194dee34ca4SPoul-Henning Kamp 
3195dee34ca4SPoul-Henning Kamp static void
3196dee34ca4SPoul-Henning Kamp swapgeom_strategy(struct buf *bp, struct swdevt *sp)
3197dee34ca4SPoul-Henning Kamp {
3198dee34ca4SPoul-Henning Kamp 	struct bio *bio;
3199dee34ca4SPoul-Henning Kamp 	struct g_consumer *cp;
3200dee34ca4SPoul-Henning Kamp 
32013398491bSAlexander Motin 	mtx_lock(&sw_dev_mtx);
3202dee34ca4SPoul-Henning Kamp 	cp = sp->sw_id;
3203dee34ca4SPoul-Henning Kamp 	if (cp == NULL) {
32043398491bSAlexander Motin 		mtx_unlock(&sw_dev_mtx);
3205dee34ca4SPoul-Henning Kamp 		bp->b_error = ENXIO;
3206dee34ca4SPoul-Henning Kamp 		bp->b_ioflags |= BIO_ERROR;
3207dee34ca4SPoul-Henning Kamp 		bufdone(bp);
3208dee34ca4SPoul-Henning Kamp 		return;
3209dee34ca4SPoul-Henning Kamp 	}
32109e3e3fe5SWarner Losh 	swapgeom_acquire(cp);
32113398491bSAlexander Motin 	mtx_unlock(&sw_dev_mtx);
321211041003SKonstantin Belousov 	if (bp->b_iocmd == BIO_WRITE)
321311041003SKonstantin Belousov 		bio = g_new_bio();
321411041003SKonstantin Belousov 	else
32154f8205e5SPoul-Henning Kamp 		bio = g_alloc_bio();
32164f8205e5SPoul-Henning Kamp 	if (bio == NULL) {
32179e3e3fe5SWarner Losh 		mtx_lock(&sw_dev_mtx);
32189e3e3fe5SWarner Losh 		swapgeom_release(cp, sp);
32199e3e3fe5SWarner Losh 		mtx_unlock(&sw_dev_mtx);
32203e5b6861SPoul-Henning Kamp 		bp->b_error = ENOMEM;
32213e5b6861SPoul-Henning Kamp 		bp->b_ioflags |= BIO_ERROR;
32220b208315SEdward Tomasz Napierala 		printf("swap_pager: cannot allocate bio\n");
32233e5b6861SPoul-Henning Kamp 		bufdone(bp);
32243e5b6861SPoul-Henning Kamp 		return;
32253e5b6861SPoul-Henning Kamp 	}
322611041003SKonstantin Belousov 
3227756a5412SGleb Smirnoff 	bp->b_caller1 = bio;
32283398491bSAlexander Motin 	bio->bio_caller1 = sp;
3229dee34ca4SPoul-Henning Kamp 	bio->bio_caller2 = bp;
3230c5d3d25eSPoul-Henning Kamp 	bio->bio_cmd = bp->b_iocmd;
3231dee34ca4SPoul-Henning Kamp 	bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
3232dee34ca4SPoul-Henning Kamp 	bio->bio_length = bp->b_bcount;
3233dee34ca4SPoul-Henning Kamp 	bio->bio_done = swapgeom_done;
3234c6213befSGleb Smirnoff 	bio->bio_flags |= BIO_SWAP;
3235fade8dd7SJeff Roberson 	if (!buf_mapped(bp)) {
32362cc718a1SKonstantin Belousov 		bio->bio_ma = bp->b_pages;
32372cc718a1SKonstantin Belousov 		bio->bio_data = unmapped_buf;
32382cc718a1SKonstantin Belousov 		bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
32392cc718a1SKonstantin Belousov 		bio->bio_ma_n = bp->b_npages;
32402cc718a1SKonstantin Belousov 		bio->bio_flags |= BIO_UNMAPPED;
32412cc718a1SKonstantin Belousov 	} else {
32422cc718a1SKonstantin Belousov 		bio->bio_data = bp->b_data;
32432cc718a1SKonstantin Belousov 		bio->bio_ma = NULL;
32442cc718a1SKonstantin Belousov 	}
3245dee34ca4SPoul-Henning Kamp 	g_io_request(bio, cp);
3246dee34ca4SPoul-Henning Kamp 	return;
3247dee34ca4SPoul-Henning Kamp }
3248dee34ca4SPoul-Henning Kamp 
3249dee34ca4SPoul-Henning Kamp static void
3250dee34ca4SPoul-Henning Kamp swapgeom_orphan(struct g_consumer *cp)
3251dee34ca4SPoul-Henning Kamp {
3252dee34ca4SPoul-Henning Kamp 	struct swdevt *sp;
32533398491bSAlexander Motin 	int destroy;
3254dee34ca4SPoul-Henning Kamp 
3255dee34ca4SPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
32563398491bSAlexander Motin 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
32573398491bSAlexander Motin 		if (sp->sw_id == cp) {
32588f12d83aSAlexander Motin 			sp->sw_flags |= SW_CLOSING;
32593398491bSAlexander Motin 			break;
3260dee34ca4SPoul-Henning Kamp 		}
32613398491bSAlexander Motin 	}
32629e3e3fe5SWarner Losh 	/*
32639e3e3fe5SWarner Losh 	 * Drop reference we were created with. Do directly since we're in a
32649e3e3fe5SWarner Losh 	 * special context where we don't have to queue the call to
32659e3e3fe5SWarner Losh 	 * swapgeom_close_ev().
32669e3e3fe5SWarner Losh 	 */
32679e3e3fe5SWarner Losh 	cp->index--;
32683398491bSAlexander Motin 	destroy = ((sp != NULL) && (cp->index == 0));
32693398491bSAlexander Motin 	if (destroy)
32703398491bSAlexander Motin 		sp->sw_id = NULL;
32713398491bSAlexander Motin 	mtx_unlock(&sw_dev_mtx);
32723398491bSAlexander Motin 	if (destroy)
32733398491bSAlexander Motin 		swapgeom_close_ev(cp, 0);
3274dee34ca4SPoul-Henning Kamp }
3275dee34ca4SPoul-Henning Kamp 
3276dee34ca4SPoul-Henning Kamp static void
3277dee34ca4SPoul-Henning Kamp swapgeom_close(struct thread *td, struct swdevt *sw)
3278dee34ca4SPoul-Henning Kamp {
32793398491bSAlexander Motin 	struct g_consumer *cp;
3280dee34ca4SPoul-Henning Kamp 
32813398491bSAlexander Motin 	mtx_lock(&sw_dev_mtx);
32823398491bSAlexander Motin 	cp = sw->sw_id;
32833398491bSAlexander Motin 	sw->sw_id = NULL;
32843398491bSAlexander Motin 	mtx_unlock(&sw_dev_mtx);
32850c657d22SKonstantin Belousov 
32860c657d22SKonstantin Belousov 	/*
32870c657d22SKonstantin Belousov 	 * swapgeom_close() may be called from the biodone context,
32880c657d22SKonstantin Belousov 	 * where we cannot perform topology changes.  Delegate the
32890c657d22SKonstantin Belousov 	 * work to the events thread.
32900c657d22SKonstantin Belousov 	 */
32913398491bSAlexander Motin 	if (cp != NULL)
32923398491bSAlexander Motin 		g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
3293dee34ca4SPoul-Henning Kamp }
3294dee34ca4SPoul-Henning Kamp 
329588ad2d7bSKonstantin Belousov static int
329688ad2d7bSKonstantin Belousov swapongeom_locked(struct cdev *dev, struct vnode *vp)
3297dee34ca4SPoul-Henning Kamp {
3298dee34ca4SPoul-Henning Kamp 	struct g_provider *pp;
3299dee34ca4SPoul-Henning Kamp 	struct g_consumer *cp;
3300dee34ca4SPoul-Henning Kamp 	static struct g_geom *gp;
3301dee34ca4SPoul-Henning Kamp 	struct swdevt *sp;
3302dee34ca4SPoul-Henning Kamp 	u_long nblks;
3303dee34ca4SPoul-Henning Kamp 	int error;
3304dee34ca4SPoul-Henning Kamp 
330588ad2d7bSKonstantin Belousov 	pp = g_dev_getprovider(dev);
330688ad2d7bSKonstantin Belousov 	if (pp == NULL)
330788ad2d7bSKonstantin Belousov 		return (ENODEV);
3308dee34ca4SPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
3309dee34ca4SPoul-Henning Kamp 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
3310dee34ca4SPoul-Henning Kamp 		cp = sp->sw_id;
3311dee34ca4SPoul-Henning Kamp 		if (cp != NULL && cp->provider == pp) {
3312dee34ca4SPoul-Henning Kamp 			mtx_unlock(&sw_dev_mtx);
331388ad2d7bSKonstantin Belousov 			return (EBUSY);
3314dee34ca4SPoul-Henning Kamp 		}
3315dee34ca4SPoul-Henning Kamp 	}
3316dee34ca4SPoul-Henning Kamp 	mtx_unlock(&sw_dev_mtx);
33175721c9c7SPoul-Henning Kamp 	if (gp == NULL)
331802c62349SJaakko Heinonen 		gp = g_new_geomf(&g_swap_class, "swap");
3319dee34ca4SPoul-Henning Kamp 	cp = g_new_consumer(gp);
33209e3e3fe5SWarner Losh 	cp->index = 1;	/* Number of active I/Os, plus one for being active. */
33219e3e3fe5SWarner Losh 	cp->flags |=  G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
3322dee34ca4SPoul-Henning Kamp 	g_attach(cp, pp);
3323afeb65e6SPoul-Henning Kamp 	/*
3324afeb65e6SPoul-Henning Kamp 	 * XXX: Every time you think you can improve the margin for
3325afeb65e6SPoul-Henning Kamp 	 * footshooting, somebody depends on the ability to do so:
3326afeb65e6SPoul-Henning Kamp 	 * savecore(8) wants to write to our swapdev so we cannot
3327afeb65e6SPoul-Henning Kamp 	 * set an exclusive count :-(
3328afeb65e6SPoul-Henning Kamp 	 */
3329d2bae332SPoul-Henning Kamp 	error = g_access(cp, 1, 1, 0);
333088ad2d7bSKonstantin Belousov 	if (error != 0) {
3331dee34ca4SPoul-Henning Kamp 		g_detach(cp);
3332dee34ca4SPoul-Henning Kamp 		g_destroy_consumer(cp);
333388ad2d7bSKonstantin Belousov 		return (error);
3334dee34ca4SPoul-Henning Kamp 	}
3335dee34ca4SPoul-Henning Kamp 	nblks = pp->mediasize / DEV_BSIZE;
333688ad2d7bSKonstantin Belousov 	swaponsomething(vp, cp, nblks, swapgeom_strategy,
333788ad2d7bSKonstantin Belousov 	    swapgeom_close, dev2udev(dev),
33382cc718a1SKonstantin Belousov 	    (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
333988ad2d7bSKonstantin Belousov 	return (0);
3340dee34ca4SPoul-Henning Kamp }
3341dee34ca4SPoul-Henning Kamp 
3342dee34ca4SPoul-Henning Kamp static int
334388ad2d7bSKonstantin Belousov swapongeom(struct vnode *vp)
3344dee34ca4SPoul-Henning Kamp {
3345dee34ca4SPoul-Henning Kamp 	int error;
3346dee34ca4SPoul-Henning Kamp 
33476ddf41faSKonstantin Belousov 	ASSERT_VOP_ELOCKED(vp, "swapongeom");
3348abd80ddbSMateusz Guzik 	if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) {
334988ad2d7bSKonstantin Belousov 		error = ENOENT;
335088ad2d7bSKonstantin Belousov 	} else {
335188ad2d7bSKonstantin Belousov 		g_topology_lock();
335288ad2d7bSKonstantin Belousov 		error = swapongeom_locked(vp->v_rdev, vp);
335388ad2d7bSKonstantin Belousov 		g_topology_unlock();
335488ad2d7bSKonstantin Belousov 	}
3355dee34ca4SPoul-Henning Kamp 	return (error);
3356dee34ca4SPoul-Henning Kamp }
3357dee34ca4SPoul-Henning Kamp 
3358dee34ca4SPoul-Henning Kamp /*
3359dee34ca4SPoul-Henning Kamp  * VNODE backend
3360dee34ca4SPoul-Henning Kamp  *
3361dee34ca4SPoul-Henning Kamp  * This is used mainly for network filesystem (read: probably only tested
3362dee34ca4SPoul-Henning Kamp  * with NFS) swapfiles.
3363dee34ca4SPoul-Henning Kamp  *
3364dee34ca4SPoul-Henning Kamp  */
3365dee34ca4SPoul-Henning Kamp 
3366dee34ca4SPoul-Henning Kamp static void
3367dee34ca4SPoul-Henning Kamp swapdev_strategy(struct buf *bp, struct swdevt *sp)
3368dee34ca4SPoul-Henning Kamp {
3369494eb176SPoul-Henning Kamp 	struct vnode *vp2;
3370dee34ca4SPoul-Henning Kamp 
3371dee34ca4SPoul-Henning Kamp 	bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
3372dee34ca4SPoul-Henning Kamp 
3373dee34ca4SPoul-Henning Kamp 	vp2 = sp->sw_id;
3374dee34ca4SPoul-Henning Kamp 	vhold(vp2);
3375dee34ca4SPoul-Henning Kamp 	if (bp->b_iocmd == BIO_WRITE) {
3376b19740f4SKonstantin Belousov 		vn_lock(vp2, LK_EXCLUSIVE | LK_RETRY);
33773cfc7651SOlivier Houchard 		if (bp->b_bufobj)
3378494eb176SPoul-Henning Kamp 			bufobj_wdrop(bp->b_bufobj);
3379a76d8f4eSPoul-Henning Kamp 		bufobj_wref(&vp2->v_bufobj);
3380b19740f4SKonstantin Belousov 	} else {
3381b19740f4SKonstantin Belousov 		vn_lock(vp2, LK_SHARED | LK_RETRY);
3382dee34ca4SPoul-Henning Kamp 	}
33833cfc7651SOlivier Houchard 	if (bp->b_bufobj != &vp2->v_bufobj)
33843cfc7651SOlivier Houchard 		bp->b_bufobj = &vp2->v_bufobj;
3385dee34ca4SPoul-Henning Kamp 	bp->b_vp = vp2;
33862c18019fSPoul-Henning Kamp 	bp->b_iooffset = dbtob(bp->b_blkno);
3387b792bebeSPoul-Henning Kamp 	bstrategy(bp);
3388b19740f4SKonstantin Belousov 	VOP_UNLOCK(vp2);
3389dee34ca4SPoul-Henning Kamp }
3390dee34ca4SPoul-Henning Kamp 
3391dee34ca4SPoul-Henning Kamp static void
3392dee34ca4SPoul-Henning Kamp swapdev_close(struct thread *td, struct swdevt *sp)
3393dee34ca4SPoul-Henning Kamp {
3394a6d04f34SKonstantin Belousov 	struct vnode *vp;
3395dee34ca4SPoul-Henning Kamp 
3396a6d04f34SKonstantin Belousov 	vp = sp->sw_vp;
3397a6d04f34SKonstantin Belousov 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3398a6d04f34SKonstantin Belousov 	VOP_CLOSE(vp, FREAD | FWRITE, td->td_ucred, td);
3399a6d04f34SKonstantin Belousov 	vput(vp);
3400dee34ca4SPoul-Henning Kamp }
3401dee34ca4SPoul-Henning Kamp 
3402dee34ca4SPoul-Henning Kamp static int
3403dee34ca4SPoul-Henning Kamp swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
3404dee34ca4SPoul-Henning Kamp {
3405dee34ca4SPoul-Henning Kamp 	struct swdevt *sp;
3406dee34ca4SPoul-Henning Kamp 	int error;
3407dee34ca4SPoul-Henning Kamp 
34086ddf41faSKonstantin Belousov 	ASSERT_VOP_ELOCKED(vp, "swaponvp");
3409dee34ca4SPoul-Henning Kamp 	if (nblks == 0)
3410dee34ca4SPoul-Henning Kamp 		return (ENXIO);
3411dee34ca4SPoul-Henning Kamp 	mtx_lock(&sw_dev_mtx);
3412dee34ca4SPoul-Henning Kamp 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
3413dee34ca4SPoul-Henning Kamp 		if (sp->sw_id == vp) {
3414dee34ca4SPoul-Henning Kamp 			mtx_unlock(&sw_dev_mtx);
3415dee34ca4SPoul-Henning Kamp 			return (EBUSY);
3416dee34ca4SPoul-Henning Kamp 		}
3417dee34ca4SPoul-Henning Kamp 	}
3418dee34ca4SPoul-Henning Kamp 	mtx_unlock(&sw_dev_mtx);
3419dee34ca4SPoul-Henning Kamp 
3420dee34ca4SPoul-Henning Kamp #ifdef MAC
342130d239bcSRobert Watson 	error = mac_system_check_swapon(td->td_ucred, vp);
3422dee34ca4SPoul-Henning Kamp 	if (error == 0)
3423dee34ca4SPoul-Henning Kamp #endif
34249e223287SKonstantin Belousov 		error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
34256ddf41faSKonstantin Belousov 	if (error != 0)
3426dee34ca4SPoul-Henning Kamp 		return (error);
3427dee34ca4SPoul-Henning Kamp 
3428dee34ca4SPoul-Henning Kamp 	swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
34292cc718a1SKonstantin Belousov 	    NODEV, 0);
3430dee34ca4SPoul-Henning Kamp 	return (0);
3431dee34ca4SPoul-Henning Kamp }
343289c241d1SGleb Smirnoff 
343389c241d1SGleb Smirnoff static int
343489c241d1SGleb Smirnoff sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
343589c241d1SGleb Smirnoff {
343689c241d1SGleb Smirnoff 	int error, new, n;
343789c241d1SGleb Smirnoff 
343889c241d1SGleb Smirnoff 	new = nsw_wcount_async_max;
343989c241d1SGleb Smirnoff 	error = sysctl_handle_int(oidp, &new, 0, req);
344089c241d1SGleb Smirnoff 	if (error != 0 || req->newptr == NULL)
344189c241d1SGleb Smirnoff 		return (error);
344289c241d1SGleb Smirnoff 
344389c241d1SGleb Smirnoff 	if (new > nswbuf / 2 || new < 1)
344489c241d1SGleb Smirnoff 		return (EINVAL);
344589c241d1SGleb Smirnoff 
3446756a5412SGleb Smirnoff 	mtx_lock(&swbuf_mtx);
344789c241d1SGleb Smirnoff 	while (nsw_wcount_async_max != new) {
344889c241d1SGleb Smirnoff 		/*
344989c241d1SGleb Smirnoff 		 * Adjust difference.  If the current async count is too low,
345089c241d1SGleb Smirnoff 		 * we will need to sqeeze our update slowly in.  Sleep with a
345189c241d1SGleb Smirnoff 		 * higher priority than getpbuf() to finish faster.
345289c241d1SGleb Smirnoff 		 */
345389c241d1SGleb Smirnoff 		n = new - nsw_wcount_async_max;
345489c241d1SGleb Smirnoff 		if (nsw_wcount_async + n >= 0) {
345589c241d1SGleb Smirnoff 			nsw_wcount_async += n;
345689c241d1SGleb Smirnoff 			nsw_wcount_async_max += n;
345789c241d1SGleb Smirnoff 			wakeup(&nsw_wcount_async);
345889c241d1SGleb Smirnoff 		} else {
345989c241d1SGleb Smirnoff 			nsw_wcount_async_max -= nsw_wcount_async;
346089c241d1SGleb Smirnoff 			nsw_wcount_async = 0;
3461756a5412SGleb Smirnoff 			msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
346289c241d1SGleb Smirnoff 			    "swpsysctl", 0);
346389c241d1SGleb Smirnoff 		}
346489c241d1SGleb Smirnoff 	}
3465756a5412SGleb Smirnoff 	mtx_unlock(&swbuf_mtx);
346689c241d1SGleb Smirnoff 
346789c241d1SGleb Smirnoff 	return (0);
346889c241d1SGleb Smirnoff }
3469fe7bcbafSKyle Evans 
3470fe7bcbafSKyle Evans static void
3471fe7bcbafSKyle Evans swap_pager_update_writecount(vm_object_t object, vm_offset_t start,
3472fe7bcbafSKyle Evans     vm_offset_t end)
3473fe7bcbafSKyle Evans {
3474fe7bcbafSKyle Evans 
3475fe7bcbafSKyle Evans 	VM_OBJECT_WLOCK(object);
347663967687SJeff Roberson 	KASSERT((object->flags & OBJ_ANON) == 0,
3477fe7bcbafSKyle Evans 	    ("Splittable object with writecount"));
3478fe7bcbafSKyle Evans 	object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
3479fe7bcbafSKyle Evans 	VM_OBJECT_WUNLOCK(object);
3480fe7bcbafSKyle Evans }
3481fe7bcbafSKyle Evans 
3482fe7bcbafSKyle Evans static void
3483fe7bcbafSKyle Evans swap_pager_release_writecount(vm_object_t object, vm_offset_t start,
3484fe7bcbafSKyle Evans     vm_offset_t end)
3485fe7bcbafSKyle Evans {
3486fe7bcbafSKyle Evans 
3487fe7bcbafSKyle Evans 	VM_OBJECT_WLOCK(object);
348863967687SJeff Roberson 	KASSERT((object->flags & OBJ_ANON) == 0,
3489fe7bcbafSKyle Evans 	    ("Splittable object with writecount"));
34906ada4e8aSKonstantin Belousov 	KASSERT(object->un_pager.swp.writemappings >= (vm_ooffset_t)end - start,
34916ada4e8aSKonstantin Belousov 	    ("swap obj %p writecount %jx dec %jx", object,
34926ada4e8aSKonstantin Belousov 	    (uintmax_t)object->un_pager.swp.writemappings,
34936ada4e8aSKonstantin Belousov 	    (uintmax_t)((vm_ooffset_t)end - start)));
3494fe7bcbafSKyle Evans 	object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
3495fe7bcbafSKyle Evans 	VM_OBJECT_WUNLOCK(object);
3496fe7bcbafSKyle Evans }
3497