xref: /freebsd-12.1/sys/vm/swap_pager.c (revision 403ed644)
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1998 Matthew Dillon,
5  * Copyright (c) 1994 John S. Dyson
6  * Copyright (c) 1990 University of Utah.
7  * Copyright (c) 1982, 1986, 1989, 1993
8  *	The Regents of the University of California.  All rights reserved.
9  *
10  * This code is derived from software contributed to Berkeley by
11  * the Systems Programming Group of the University of Utah Computer
12  * Science Department.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. All advertising materials mentioning features or use of this software
23  *    must display the following acknowledgement:
24  *	This product includes software developed by the University of
25  *	California, Berkeley and its contributors.
26  * 4. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  *
42  *				New Swap System
43  *				Matthew Dillon
44  *
45  * Radix Bitmap 'blists'.
46  *
47  *	- The new swapper uses the new radix bitmap code.  This should scale
48  *	  to arbitrarily small or arbitrarily large swap spaces and an almost
49  *	  arbitrary degree of fragmentation.
50  *
51  * Features:
52  *
53  *	- on the fly reallocation of swap during putpages.  The new system
54  *	  does not try to keep previously allocated swap blocks for dirty
55  *	  pages.
56  *
57  *	- on the fly deallocation of swap
58  *
59  *	- No more garbage collection required.  Unnecessarily allocated swap
60  *	  blocks only exist for dirty vm_page_t's now and these are already
61  *	  cycled (in a high-load system) by the pager.  We also do on-the-fly
62  *	  removal of invalidated swap blocks when a page is destroyed
63  *	  or renamed.
64  *
65  * from: Utah $Hdr: swap_pager.c 1.4 91/04/30$
66  *
67  *	@(#)swap_pager.c	8.9 (Berkeley) 3/21/94
68  *	@(#)vm_swap.c	8.5 (Berkeley) 2/17/94
69  */
70 
71 #include <sys/cdefs.h>
72 __FBSDID("$FreeBSD$");
73 
74 #include "opt_swap.h"
75 #include "opt_vm.h"
76 
77 #include <sys/param.h>
78 #include <sys/systm.h>
79 #include <sys/conf.h>
80 #include <sys/kernel.h>
81 #include <sys/priv.h>
82 #include <sys/proc.h>
83 #include <sys/bio.h>
84 #include <sys/buf.h>
85 #include <sys/disk.h>
86 #include <sys/disklabel.h>
87 #include <sys/fcntl.h>
88 #include <sys/mount.h>
89 #include <sys/namei.h>
90 #include <sys/vnode.h>
91 #include <sys/malloc.h>
92 #include <sys/pctrie.h>
93 #include <sys/racct.h>
94 #include <sys/resource.h>
95 #include <sys/resourcevar.h>
96 #include <sys/rwlock.h>
97 #include <sys/sbuf.h>
98 #include <sys/sysctl.h>
99 #include <sys/sysproto.h>
100 #include <sys/blist.h>
101 #include <sys/lock.h>
102 #include <sys/sx.h>
103 #include <sys/vmmeter.h>
104 
105 #include <security/mac/mac_framework.h>
106 
107 #include <vm/vm.h>
108 #include <vm/pmap.h>
109 #include <vm/vm_map.h>
110 #include <vm/vm_kern.h>
111 #include <vm/vm_object.h>
112 #include <vm/vm_page.h>
113 #include <vm/vm_pager.h>
114 #include <vm/vm_pageout.h>
115 #include <vm/vm_param.h>
116 #include <vm/swap_pager.h>
117 #include <vm/vm_extern.h>
118 #include <vm/uma.h>
119 
120 #include <geom/geom.h>
121 
122 /*
123  * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64.
124  * The 64-page limit is due to the radix code (kern/subr_blist.c).
125  */
126 #ifndef MAX_PAGEOUT_CLUSTER
127 #define	MAX_PAGEOUT_CLUSTER	32
128 #endif
129 
130 #if !defined(SWB_NPAGES)
131 #define SWB_NPAGES	MAX_PAGEOUT_CLUSTER
132 #endif
133 
134 #define	SWAP_META_PAGES		PCTRIE_COUNT
135 
136 /*
137  * A swblk structure maps each page index within a
138  * SWAP_META_PAGES-aligned and sized range to the address of an
139  * on-disk swap block (or SWAPBLK_NONE). The collection of these
140  * mappings for an entire vm object is implemented as a pc-trie.
141  */
142 struct swblk {
143 	vm_pindex_t	p;
144 	daddr_t		d[SWAP_META_PAGES];
145 };
146 
147 static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data");
148 static struct mtx sw_dev_mtx;
149 static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
150 static struct swdevt *swdevhd;	/* Allocate from here next */
151 static int nswapdev;		/* Number of swap devices */
152 int swap_pager_avail;
153 static struct sx swdev_syscall_lock;	/* serialize swap(on|off) */
154 
155 static u_long swap_reserved;
156 static u_long swap_total;
157 static int sysctl_page_shift(SYSCTL_HANDLER_ARGS);
158 SYSCTL_PROC(_vm, OID_AUTO, swap_reserved, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
159     &swap_reserved, 0, sysctl_page_shift, "A",
160     "Amount of swap storage needed to back all allocated anonymous memory.");
161 SYSCTL_PROC(_vm, OID_AUTO, swap_total, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
162     &swap_total, 0, sysctl_page_shift, "A",
163     "Total amount of available swap storage.");
164 
165 static int overcommit = 0;
166 SYSCTL_INT(_vm, VM_OVERCOMMIT, overcommit, CTLFLAG_RW, &overcommit, 0,
167     "Configure virtual memory overcommit behavior. See tuning(7) "
168     "for details.");
169 static unsigned long swzone;
170 SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
171     "Actual size of swap metadata zone");
172 static unsigned long swap_maxpages;
173 SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
174     "Maximum amount of swap supported");
175 
176 /* bits from overcommit */
177 #define	SWAP_RESERVE_FORCE_ON		(1 << 0)
178 #define	SWAP_RESERVE_RLIMIT_ON		(1 << 1)
179 #define	SWAP_RESERVE_ALLOW_NONWIRED	(1 << 2)
180 
181 static int
sysctl_page_shift(SYSCTL_HANDLER_ARGS)182 sysctl_page_shift(SYSCTL_HANDLER_ARGS)
183 {
184 	uint64_t newval;
185 	u_long value = *(u_long *)arg1;
186 
187 	newval = ((uint64_t)value) << PAGE_SHIFT;
188 	return (sysctl_handle_64(oidp, &newval, 0, req));
189 }
190 
191 int
swap_reserve(vm_ooffset_t incr)192 swap_reserve(vm_ooffset_t incr)
193 {
194 
195 	return (swap_reserve_by_cred(incr, curthread->td_ucred));
196 }
197 
198 int
swap_reserve_by_cred(vm_ooffset_t incr,struct ucred * cred)199 swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
200 {
201 	u_long r, s, prev, pincr;
202 	int res, error;
203 	static int curfail;
204 	static struct timeval lastfail;
205 	struct uidinfo *uip;
206 
207 	uip = cred->cr_ruidinfo;
208 
209 	KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
210 	    (uintmax_t)incr));
211 
212 #ifdef RACCT
213 	if (racct_enable) {
214 		PROC_LOCK(curproc);
215 		error = racct_add(curproc, RACCT_SWAP, incr);
216 		PROC_UNLOCK(curproc);
217 		if (error != 0)
218 			return (0);
219 	}
220 #endif
221 
222 	pincr = atop(incr);
223 	res = 0;
224 	prev = atomic_fetchadd_long(&swap_reserved, pincr);
225 	r = prev + pincr;
226 	if (overcommit & SWAP_RESERVE_ALLOW_NONWIRED) {
227 		s = vm_cnt.v_page_count - vm_cnt.v_free_reserved -
228 		    vm_wire_count();
229 	} else
230 		s = 0;
231 	s += swap_total;
232 	if ((overcommit & SWAP_RESERVE_FORCE_ON) == 0 || r <= s ||
233 	    (error = priv_check(curthread, PRIV_VM_SWAP_NOQUOTA)) == 0) {
234 		res = 1;
235 	} else {
236 		prev = atomic_fetchadd_long(&swap_reserved, -pincr);
237 		if (prev < pincr)
238 			panic("swap_reserved < incr on overcommit fail");
239 	}
240 	if (res) {
241 		prev = atomic_fetchadd_long(&uip->ui_vmsize, pincr);
242 		if ((overcommit & SWAP_RESERVE_RLIMIT_ON) != 0 &&
243 		    prev + pincr > lim_cur(curthread, RLIMIT_SWAP) &&
244 		    priv_check(curthread, PRIV_VM_SWAP_NORLIMIT)) {
245 			res = 0;
246 			prev = atomic_fetchadd_long(&uip->ui_vmsize, -pincr);
247 			if (prev < pincr)
248 				panic("uip->ui_vmsize < incr on overcommit fail");
249 		}
250 	}
251 	if (!res && ppsratecheck(&lastfail, &curfail, 1)) {
252 		printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
253 		    uip->ui_uid, curproc->p_pid, incr);
254 	}
255 
256 #ifdef RACCT
257 	if (racct_enable && !res) {
258 		PROC_LOCK(curproc);
259 		racct_sub(curproc, RACCT_SWAP, incr);
260 		PROC_UNLOCK(curproc);
261 	}
262 #endif
263 
264 	return (res);
265 }
266 
267 void
swap_reserve_force(vm_ooffset_t incr)268 swap_reserve_force(vm_ooffset_t incr)
269 {
270 	struct uidinfo *uip;
271 	u_long pincr;
272 
273 	KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
274 	    (uintmax_t)incr));
275 
276 	PROC_LOCK(curproc);
277 #ifdef RACCT
278 	if (racct_enable)
279 		racct_add_force(curproc, RACCT_SWAP, incr);
280 #endif
281 	pincr = atop(incr);
282 	atomic_add_long(&swap_reserved, pincr);
283 	uip = curproc->p_ucred->cr_ruidinfo;
284 	atomic_add_long(&uip->ui_vmsize, pincr);
285 	PROC_UNLOCK(curproc);
286 }
287 
288 void
swap_release(vm_ooffset_t decr)289 swap_release(vm_ooffset_t decr)
290 {
291 	struct ucred *cred;
292 
293 	PROC_LOCK(curproc);
294 	cred = curproc->p_ucred;
295 	swap_release_by_cred(decr, cred);
296 	PROC_UNLOCK(curproc);
297 }
298 
299 void
swap_release_by_cred(vm_ooffset_t decr,struct ucred * cred)300 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
301 {
302 	u_long prev, pdecr;
303  	struct uidinfo *uip;
304 
305 	uip = cred->cr_ruidinfo;
306 
307 	KASSERT((decr & PAGE_MASK) == 0, ("%s: decr: %ju & PAGE_MASK", __func__,
308 	    (uintmax_t)decr));
309 
310 	pdecr = atop(decr);
311 	prev = atomic_fetchadd_long(&swap_reserved, -pdecr);
312 	if (prev < pdecr)
313 		panic("swap_reserved < decr");
314 
315 	prev = atomic_fetchadd_long(&uip->ui_vmsize, -pdecr);
316 	if (prev < pdecr)
317 		printf("negative vmsize for uid = %d\n", uip->ui_uid);
318 #ifdef RACCT
319 	if (racct_enable)
320 		racct_sub_cred(cred, RACCT_SWAP, decr);
321 #endif
322 }
323 
324 #define SWM_POP		0x01	/* pop out			*/
325 
326 static int swap_pager_full = 2;	/* swap space exhaustion (task killing) */
327 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
328 static int nsw_rcount;		/* free read buffers			*/
329 static int nsw_wcount_sync;	/* limit write buffers / synchronous	*/
330 static int nsw_wcount_async;	/* limit write buffers / asynchronous	*/
331 static int nsw_wcount_async_max;/* assigned maximum			*/
332 static int nsw_cluster_max;	/* maximum VOP I/O allowed		*/
333 
334 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
335 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
336     CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
337     "Maximum running async swap ops");
338 static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS);
339 SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD |
340     CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A",
341     "Swap Fragmentation Info");
342 
343 static struct sx sw_alloc_sx;
344 
345 /*
346  * "named" and "unnamed" anon region objects.  Try to reduce the overhead
347  * of searching a named list by hashing it just a little.
348  */
349 
350 #define NOBJLISTS		8
351 
352 #define NOBJLIST(handle)	\
353 	(&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
354 
355 static struct pagerlst	swap_pager_object_list[NOBJLISTS];
356 static uma_zone_t swblk_zone;
357 static uma_zone_t swpctrie_zone;
358 
359 /*
360  * pagerops for OBJT_SWAP - "swap pager".  Some ops are also global procedure
361  * calls hooked from other parts of the VM system and do not appear here.
362  * (see vm/swap_pager.h).
363  */
364 static vm_object_t
365 		swap_pager_alloc(void *handle, vm_ooffset_t size,
366 		    vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
367 static void	swap_pager_dealloc(vm_object_t object);
368 static int	swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
369     int *);
370 static int	swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
371     int *, pgo_getpages_iodone_t, void *);
372 static void	swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
373 static boolean_t
374 		swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
375 static void	swap_pager_init(void);
376 static void	swap_pager_unswapped(vm_page_t);
377 static void	swap_pager_swapoff(struct swdevt *sp);
378 
379 struct pagerops swappagerops = {
380 	.pgo_init =	swap_pager_init,	/* early system initialization of pager	*/
381 	.pgo_alloc =	swap_pager_alloc,	/* allocate an OBJT_SWAP object		*/
382 	.pgo_dealloc =	swap_pager_dealloc,	/* deallocate an OBJT_SWAP object	*/
383 	.pgo_getpages =	swap_pager_getpages,	/* pagein				*/
384 	.pgo_getpages_async = swap_pager_getpages_async, /* pagein (async)		*/
385 	.pgo_putpages =	swap_pager_putpages,	/* pageout				*/
386 	.pgo_haspage =	swap_pager_haspage,	/* get backing store status for page	*/
387 	.pgo_pageunswapped = swap_pager_unswapped,	/* remove swap related to page		*/
388 };
389 
390 /*
391  * swap_*() routines are externally accessible.  swp_*() routines are
392  * internal.
393  */
394 static int nswap_lowat = 128;	/* in pages, swap_pager_almost_full warn */
395 static int nswap_hiwat = 512;	/* in pages, swap_pager_almost_full warn */
396 
397 SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
398     "Maximum size of a swap block in pages");
399 
400 static void	swp_sizecheck(void);
401 static void	swp_pager_async_iodone(struct buf *bp);
402 static bool	swp_pager_swblk_empty(struct swblk *sb, int start, int limit);
403 static int	swapongeom(struct vnode *);
404 static int	swaponvp(struct thread *, struct vnode *, u_long);
405 static int	swapoff_one(struct swdevt *sp, struct ucred *cred);
406 
407 /*
408  * Swap bitmap functions
409  */
410 static void	swp_pager_freeswapspace(daddr_t blk, daddr_t npages);
411 static daddr_t	swp_pager_getswapspace(int npages);
412 
413 /*
414  * Metadata functions
415  */
416 static daddr_t swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
417 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t);
418 static void swp_pager_meta_free_all(vm_object_t);
419 static daddr_t swp_pager_meta_ctl(vm_object_t, vm_pindex_t, int);
420 
421 static void
swp_pager_init_freerange(daddr_t * start,daddr_t * num)422 swp_pager_init_freerange(daddr_t *start, daddr_t *num)
423 {
424 
425 	*start = SWAPBLK_NONE;
426 	*num = 0;
427 }
428 
429 static void
swp_pager_update_freerange(daddr_t * start,daddr_t * num,daddr_t addr)430 swp_pager_update_freerange(daddr_t *start, daddr_t *num, daddr_t addr)
431 {
432 
433 	if (*start + *num == addr) {
434 		(*num)++;
435 	} else {
436 		swp_pager_freeswapspace(*start, *num);
437 		*start = addr;
438 		*num = 1;
439 	}
440 }
441 
442 static void *
swblk_trie_alloc(struct pctrie * ptree)443 swblk_trie_alloc(struct pctrie *ptree)
444 {
445 
446 	return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
447 	    M_USE_RESERVE : 0)));
448 }
449 
450 static void
swblk_trie_free(struct pctrie * ptree,void * node)451 swblk_trie_free(struct pctrie *ptree, void *node)
452 {
453 
454 	uma_zfree(swpctrie_zone, node);
455 }
456 
457 PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
458 
459 /*
460  * SWP_SIZECHECK() -	update swap_pager_full indication
461  *
462  *	update the swap_pager_almost_full indication and warn when we are
463  *	about to run out of swap space, using lowat/hiwat hysteresis.
464  *
465  *	Clear swap_pager_full ( task killing ) indication when lowat is met.
466  *
467  *	No restrictions on call
468  *	This routine may not block.
469  */
470 static void
swp_sizecheck(void)471 swp_sizecheck(void)
472 {
473 
474 	if (swap_pager_avail < nswap_lowat) {
475 		if (swap_pager_almost_full == 0) {
476 			printf("swap_pager: out of swap space\n");
477 			swap_pager_almost_full = 1;
478 		}
479 	} else {
480 		swap_pager_full = 0;
481 		if (swap_pager_avail > nswap_hiwat)
482 			swap_pager_almost_full = 0;
483 	}
484 }
485 
486 /*
487  * SWAP_PAGER_INIT() -	initialize the swap pager!
488  *
489  *	Expected to be started from system init.  NOTE:  This code is run
490  *	before much else so be careful what you depend on.  Most of the VM
491  *	system has yet to be initialized at this point.
492  */
493 static void
swap_pager_init(void)494 swap_pager_init(void)
495 {
496 	/*
497 	 * Initialize object lists
498 	 */
499 	int i;
500 
501 	for (i = 0; i < NOBJLISTS; ++i)
502 		TAILQ_INIT(&swap_pager_object_list[i]);
503 	mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
504 	sx_init(&sw_alloc_sx, "swspsx");
505 	sx_init(&swdev_syscall_lock, "swsysc");
506 }
507 
508 /*
509  * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
510  *
511  *	Expected to be started from pageout process once, prior to entering
512  *	its main loop.
513  */
514 void
swap_pager_swap_init(void)515 swap_pager_swap_init(void)
516 {
517 	unsigned long n, n2;
518 
519 	/*
520 	 * Number of in-transit swap bp operations.  Don't
521 	 * exhaust the pbufs completely.  Make sure we
522 	 * initialize workable values (0 will work for hysteresis
523 	 * but it isn't very efficient).
524 	 *
525 	 * The nsw_cluster_max is constrained by the bp->b_pages[]
526 	 * array (MAXPHYS/PAGE_SIZE) and our locally defined
527 	 * MAX_PAGEOUT_CLUSTER.   Also be aware that swap ops are
528 	 * constrained by the swap device interleave stripe size.
529 	 *
530 	 * Currently we hardwire nsw_wcount_async to 4.  This limit is
531 	 * designed to prevent other I/O from having high latencies due to
532 	 * our pageout I/O.  The value 4 works well for one or two active swap
533 	 * devices but is probably a little low if you have more.  Even so,
534 	 * a higher value would probably generate only a limited improvement
535 	 * with three or four active swap devices since the system does not
536 	 * typically have to pageout at extreme bandwidths.   We will want
537 	 * at least 2 per swap devices, and 4 is a pretty good value if you
538 	 * have one NFS swap device due to the command/ack latency over NFS.
539 	 * So it all works out pretty well.
540 	 */
541 	nsw_cluster_max = min((MAXPHYS/PAGE_SIZE), MAX_PAGEOUT_CLUSTER);
542 
543 	mtx_lock(&pbuf_mtx);
544 	nsw_rcount = (nswbuf + 1) / 2;
545 	nsw_wcount_sync = (nswbuf + 3) / 4;
546 	nsw_wcount_async = 4;
547 	nsw_wcount_async_max = nsw_wcount_async;
548 	mtx_unlock(&pbuf_mtx);
549 
550 	/*
551 	 * Initialize our zone, taking the user's requested size or
552 	 * estimating the number we need based on the number of pages
553 	 * in the system.
554 	 */
555 	n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
556 	    vm_cnt.v_page_count / 2;
557 	swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
558 	    pctrie_zone_init, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM);
559 	if (swpctrie_zone == NULL)
560 		panic("failed to create swap pctrie zone.");
561 	swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
562 	    NULL, NULL, _Alignof(struct swblk) - 1, UMA_ZONE_VM);
563 	if (swblk_zone == NULL)
564 		panic("failed to create swap blk zone.");
565 	n2 = n;
566 	do {
567 		if (uma_zone_reserve_kva(swblk_zone, n))
568 			break;
569 		/*
570 		 * if the allocation failed, try a zone two thirds the
571 		 * size of the previous attempt.
572 		 */
573 		n -= ((n + 2) / 3);
574 	} while (n > 0);
575 
576 	/*
577 	 * Often uma_zone_reserve_kva() cannot reserve exactly the
578 	 * requested size.  Account for the difference when
579 	 * calculating swap_maxpages.
580 	 */
581 	n = uma_zone_get_max(swblk_zone);
582 
583 	if (n < n2)
584 		printf("Swap blk zone entries changed from %lu to %lu.\n",
585 		    n2, n);
586 	swap_maxpages = n * SWAP_META_PAGES;
587 	swzone = n * sizeof(struct swblk);
588 	if (!uma_zone_reserve_kva(swpctrie_zone, n))
589 		printf("Cannot reserve swap pctrie zone, "
590 		    "reduce kern.maxswzone.\n");
591 }
592 
593 static vm_object_t
swap_pager_alloc_init(void * handle,struct ucred * cred,vm_ooffset_t size,vm_ooffset_t offset)594 swap_pager_alloc_init(void *handle, struct ucred *cred, vm_ooffset_t size,
595     vm_ooffset_t offset)
596 {
597 	vm_object_t object;
598 
599 	if (cred != NULL) {
600 		if (!swap_reserve_by_cred(size, cred))
601 			return (NULL);
602 		crhold(cred);
603 	}
604 
605 	/*
606 	 * The un_pager.swp.swp_blks trie is initialized by
607 	 * vm_object_allocate() to ensure the correct order of
608 	 * visibility to other threads.
609 	 */
610 	object = vm_object_allocate(OBJT_SWAP, OFF_TO_IDX(offset +
611 	    PAGE_MASK + size));
612 
613 	object->handle = handle;
614 	if (cred != NULL) {
615 		object->cred = cred;
616 		object->charge = size;
617 	}
618 	return (object);
619 }
620 
621 /*
622  * SWAP_PAGER_ALLOC() -	allocate a new OBJT_SWAP VM object and instantiate
623  *			its metadata structures.
624  *
625  *	This routine is called from the mmap and fork code to create a new
626  *	OBJT_SWAP object.
627  *
628  *	This routine must ensure that no live duplicate is created for
629  *	the named object request, which is protected against by
630  *	holding the sw_alloc_sx lock in case handle != NULL.
631  */
632 static vm_object_t
swap_pager_alloc(void * handle,vm_ooffset_t size,vm_prot_t prot,vm_ooffset_t offset,struct ucred * cred)633 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
634     vm_ooffset_t offset, struct ucred *cred)
635 {
636 	vm_object_t object;
637 
638 	if (handle != NULL) {
639 		/*
640 		 * Reference existing named region or allocate new one.  There
641 		 * should not be a race here against swp_pager_meta_build()
642 		 * as called from vm_page_remove() in regards to the lookup
643 		 * of the handle.
644 		 */
645 		sx_xlock(&sw_alloc_sx);
646 		object = vm_pager_object_lookup(NOBJLIST(handle), handle);
647 		if (object == NULL) {
648 			object = swap_pager_alloc_init(handle, cred, size,
649 			    offset);
650 			if (object != NULL) {
651 				TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
652 				    object, pager_object_list);
653 			}
654 		}
655 		sx_xunlock(&sw_alloc_sx);
656 	} else {
657 		object = swap_pager_alloc_init(handle, cred, size, offset);
658 	}
659 	return (object);
660 }
661 
662 /*
663  * SWAP_PAGER_DEALLOC() -	remove swap metadata from object
664  *
665  *	The swap backing for the object is destroyed.  The code is
666  *	designed such that we can reinstantiate it later, but this
667  *	routine is typically called only when the entire object is
668  *	about to be destroyed.
669  *
670  *	The object must be locked.
671  */
672 static void
swap_pager_dealloc(vm_object_t object)673 swap_pager_dealloc(vm_object_t object)
674 {
675 
676 	VM_OBJECT_ASSERT_WLOCKED(object);
677 	KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
678 
679 	/*
680 	 * Remove from list right away so lookups will fail if we block for
681 	 * pageout completion.
682 	 */
683 	if (object->handle != NULL) {
684 		VM_OBJECT_WUNLOCK(object);
685 		sx_xlock(&sw_alloc_sx);
686 		TAILQ_REMOVE(NOBJLIST(object->handle), object,
687 		    pager_object_list);
688 		sx_xunlock(&sw_alloc_sx);
689 		VM_OBJECT_WLOCK(object);
690 	}
691 
692 	vm_object_pip_wait(object, "swpdea");
693 
694 	/*
695 	 * Free all remaining metadata.  We only bother to free it from
696 	 * the swap meta data.  We do not attempt to free swapblk's still
697 	 * associated with vm_page_t's for this object.  We do not care
698 	 * if paging is still in progress on some objects.
699 	 */
700 	swp_pager_meta_free_all(object);
701 	object->handle = NULL;
702 	object->type = OBJT_DEAD;
703 }
704 
705 /************************************************************************
706  *			SWAP PAGER BITMAP ROUTINES			*
707  ************************************************************************/
708 
709 /*
710  * SWP_PAGER_GETSWAPSPACE() -	allocate raw swap space
711  *
712  *	Allocate swap for the requested number of pages.  The starting
713  *	swap block number (a page index) is returned or SWAPBLK_NONE
714  *	if the allocation failed.
715  *
716  *	Also has the side effect of advising that somebody made a mistake
717  *	when they configured swap and didn't configure enough.
718  *
719  *	This routine may not sleep.
720  *
721  *	We allocate in round-robin fashion from the configured devices.
722  */
723 static daddr_t
swp_pager_getswapspace(int npages)724 swp_pager_getswapspace(int npages)
725 {
726 	daddr_t blk;
727 	struct swdevt *sp;
728 	int i;
729 
730 	blk = SWAPBLK_NONE;
731 	mtx_lock(&sw_dev_mtx);
732 	sp = swdevhd;
733 	for (i = 0; i < nswapdev; i++) {
734 		if (sp == NULL)
735 			sp = TAILQ_FIRST(&swtailq);
736 		if (!(sp->sw_flags & SW_CLOSING)) {
737 			blk = blist_alloc(sp->sw_blist, npages);
738 			if (blk != SWAPBLK_NONE) {
739 				blk += sp->sw_first;
740 				sp->sw_used += npages;
741 				swap_pager_avail -= npages;
742 				swp_sizecheck();
743 				swdevhd = TAILQ_NEXT(sp, sw_list);
744 				goto done;
745 			}
746 		}
747 		sp = TAILQ_NEXT(sp, sw_list);
748 	}
749 	if (swap_pager_full != 2) {
750 		printf("swap_pager_getswapspace(%d): failed\n", npages);
751 		swap_pager_full = 2;
752 		swap_pager_almost_full = 1;
753 	}
754 	swdevhd = NULL;
755 done:
756 	mtx_unlock(&sw_dev_mtx);
757 	return (blk);
758 }
759 
760 static int
swp_pager_isondev(daddr_t blk,struct swdevt * sp)761 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
762 {
763 
764 	return (blk >= sp->sw_first && blk < sp->sw_end);
765 }
766 
767 static void
swp_pager_strategy(struct buf * bp)768 swp_pager_strategy(struct buf *bp)
769 {
770 	struct swdevt *sp;
771 
772 	mtx_lock(&sw_dev_mtx);
773 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
774 		if (bp->b_blkno >= sp->sw_first && bp->b_blkno < sp->sw_end) {
775 			mtx_unlock(&sw_dev_mtx);
776 			if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
777 			    unmapped_buf_allowed) {
778 				bp->b_data = unmapped_buf;
779 				bp->b_offset = 0;
780 			} else {
781 				pmap_qenter((vm_offset_t)bp->b_data,
782 				    &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
783 			}
784 			sp->sw_strategy(bp, sp);
785 			return;
786 		}
787 	}
788 	panic("Swapdev not found");
789 }
790 
791 
792 /*
793  * SWP_PAGER_FREESWAPSPACE() -	free raw swap space
794  *
795  *	This routine returns the specified swap blocks back to the bitmap.
796  *
797  *	This routine may not sleep.
798  */
799 static void
swp_pager_freeswapspace(daddr_t blk,daddr_t npages)800 swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
801 {
802 	struct swdevt *sp;
803 
804 	if (npages == 0)
805 		return;
806 	mtx_lock(&sw_dev_mtx);
807 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
808 		if (blk >= sp->sw_first && blk < sp->sw_end) {
809 			sp->sw_used -= npages;
810 			/*
811 			 * If we are attempting to stop swapping on
812 			 * this device, we don't want to mark any
813 			 * blocks free lest they be reused.
814 			 */
815 			if ((sp->sw_flags & SW_CLOSING) == 0) {
816 				blist_free(sp->sw_blist, blk - sp->sw_first,
817 				    npages);
818 				swap_pager_avail += npages;
819 				swp_sizecheck();
820 			}
821 			mtx_unlock(&sw_dev_mtx);
822 			return;
823 		}
824 	}
825 	panic("Swapdev not found");
826 }
827 
828 /*
829  * SYSCTL_SWAP_FRAGMENTATION() -	produce raw swap space stats
830  */
831 static int
sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)832 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
833 {
834 	struct sbuf sbuf;
835 	struct swdevt *sp;
836 	const char *devname;
837 	int error;
838 
839 	error = sysctl_wire_old_buffer(req, 0);
840 	if (error != 0)
841 		return (error);
842 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
843 	mtx_lock(&sw_dev_mtx);
844 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
845 		if (vn_isdisk(sp->sw_vp, NULL))
846 			devname = devtoname(sp->sw_vp->v_rdev);
847 		else
848 			devname = "[file]";
849 		sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
850 		blist_stats(sp->sw_blist, &sbuf);
851 	}
852 	mtx_unlock(&sw_dev_mtx);
853 	error = sbuf_finish(&sbuf);
854 	sbuf_delete(&sbuf);
855 	return (error);
856 }
857 
858 /*
859  * SWAP_PAGER_FREESPACE() -	frees swap blocks associated with a page
860  *				range within an object.
861  *
862  *	This is a globally accessible routine.
863  *
864  *	This routine removes swapblk assignments from swap metadata.
865  *
866  *	The external callers of this routine typically have already destroyed
867  *	or renamed vm_page_t's associated with this range in the object so
868  *	we should be ok.
869  *
870  *	The object must be locked.
871  */
872 void
swap_pager_freespace(vm_object_t object,vm_pindex_t start,vm_size_t size)873 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
874 {
875 
876 	swp_pager_meta_free(object, start, size);
877 }
878 
879 /*
880  * SWAP_PAGER_RESERVE() - reserve swap blocks in object
881  *
882  *	Assigns swap blocks to the specified range within the object.  The
883  *	swap blocks are not zeroed.  Any previous swap assignment is destroyed.
884  *
885  *	Returns 0 on success, -1 on failure.
886  */
887 int
swap_pager_reserve(vm_object_t object,vm_pindex_t start,vm_size_t size)888 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
889 {
890 	int n = 0;
891 	daddr_t blk = SWAPBLK_NONE;
892 	vm_pindex_t beg = start;	/* save start index */
893 	daddr_t addr, n_free, s_free;
894 
895 	swp_pager_init_freerange(&s_free, &n_free);
896 	VM_OBJECT_WLOCK(object);
897 	while (size) {
898 		if (n == 0) {
899 			n = BLIST_MAX_ALLOC;
900 			while ((blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE) {
901 				n >>= 1;
902 				if (n == 0) {
903 					swp_pager_meta_free(object, beg, start - beg);
904 					VM_OBJECT_WUNLOCK(object);
905 					return (-1);
906 				}
907 			}
908 		}
909 		addr = swp_pager_meta_build(object, start, blk);
910 		if (addr != SWAPBLK_NONE)
911 			swp_pager_update_freerange(&s_free, &n_free, addr);
912 		--size;
913 		++start;
914 		++blk;
915 		--n;
916 	}
917 	swp_pager_freeswapspace(s_free, n_free);
918 	swp_pager_meta_free(object, start, n);
919 	VM_OBJECT_WUNLOCK(object);
920 	return (0);
921 }
922 
923 /*
924  * SWAP_PAGER_COPY() -  copy blocks from source pager to destination pager
925  *			and destroy the source.
926  *
927  *	Copy any valid swapblks from the source to the destination.  In
928  *	cases where both the source and destination have a valid swapblk,
929  *	we keep the destination's.
930  *
931  *	This routine is allowed to sleep.  It may sleep allocating metadata
932  *	indirectly through swp_pager_meta_build() or if paging is still in
933  *	progress on the source.
934  *
935  *	The source object contains no vm_page_t's (which is just as well)
936  *
937  *	The source object is of type OBJT_SWAP.
938  *
939  *	The source and destination objects must be locked.
940  *	Both object locks may temporarily be released.
941  */
942 void
swap_pager_copy(vm_object_t srcobject,vm_object_t dstobject,vm_pindex_t offset,int destroysource)943 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
944     vm_pindex_t offset, int destroysource)
945 {
946 	vm_pindex_t i;
947 	daddr_t dstaddr, n_free, s_free, srcaddr;
948 
949 	VM_OBJECT_ASSERT_WLOCKED(srcobject);
950 	VM_OBJECT_ASSERT_WLOCKED(dstobject);
951 
952 	/*
953 	 * If destroysource is set, we remove the source object from the
954 	 * swap_pager internal queue now.
955 	 */
956 	if (destroysource && srcobject->handle != NULL) {
957 		vm_object_pip_add(srcobject, 1);
958 		VM_OBJECT_WUNLOCK(srcobject);
959 		vm_object_pip_add(dstobject, 1);
960 		VM_OBJECT_WUNLOCK(dstobject);
961 		sx_xlock(&sw_alloc_sx);
962 		TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
963 		    pager_object_list);
964 		sx_xunlock(&sw_alloc_sx);
965 		VM_OBJECT_WLOCK(dstobject);
966 		vm_object_pip_wakeup(dstobject);
967 		VM_OBJECT_WLOCK(srcobject);
968 		vm_object_pip_wakeup(srcobject);
969 	}
970 
971 	/*
972 	 * Transfer source to destination.
973 	 */
974 	swp_pager_init_freerange(&s_free, &n_free);
975 	for (i = 0; i < dstobject->size; ++i) {
976 		srcaddr = swp_pager_meta_ctl(srcobject, i + offset, SWM_POP);
977 		if (srcaddr == SWAPBLK_NONE)
978 			continue;
979 		dstaddr = swp_pager_meta_ctl(dstobject, i, 0);
980 		if (dstaddr != SWAPBLK_NONE) {
981 			/*
982 			 * Destination has valid swapblk or it is represented
983 			 * by a resident page.  We destroy the source block.
984 			 */
985 			swp_pager_update_freerange(&s_free, &n_free, srcaddr);
986 			continue;
987 		}
988 
989 		/*
990 		 * Destination has no swapblk and is not resident,
991 		 * copy source.
992 		 *
993 		 * swp_pager_meta_build() can sleep.
994 		 */
995 		vm_object_pip_add(srcobject, 1);
996 		VM_OBJECT_WUNLOCK(srcobject);
997 		vm_object_pip_add(dstobject, 1);
998 		dstaddr = swp_pager_meta_build(dstobject, i, srcaddr);
999 		KASSERT(dstaddr == SWAPBLK_NONE,
1000 		    ("Unexpected destination swapblk"));
1001 		vm_object_pip_wakeup(dstobject);
1002 		VM_OBJECT_WLOCK(srcobject);
1003 		vm_object_pip_wakeup(srcobject);
1004 	}
1005 	swp_pager_freeswapspace(s_free, n_free);
1006 
1007 	/*
1008 	 * Free left over swap blocks in source.
1009 	 *
1010 	 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
1011 	 * double-remove the object from the swap queues.
1012 	 */
1013 	if (destroysource) {
1014 		swp_pager_meta_free_all(srcobject);
1015 		/*
1016 		 * Reverting the type is not necessary, the caller is going
1017 		 * to destroy srcobject directly, but I'm doing it here
1018 		 * for consistency since we've removed the object from its
1019 		 * queues.
1020 		 */
1021 		srcobject->type = OBJT_DEFAULT;
1022 	}
1023 }
1024 
1025 /*
1026  * SWAP_PAGER_HASPAGE() -	determine if we have good backing store for
1027  *				the requested page.
1028  *
1029  *	We determine whether good backing store exists for the requested
1030  *	page and return TRUE if it does, FALSE if it doesn't.
1031  *
1032  *	If TRUE, we also try to determine how much valid, contiguous backing
1033  *	store exists before and after the requested page.
1034  */
1035 static boolean_t
swap_pager_haspage(vm_object_t object,vm_pindex_t pindex,int * before,int * after)1036 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1037     int *after)
1038 {
1039 	daddr_t blk, blk0;
1040 	int i;
1041 
1042 	VM_OBJECT_ASSERT_LOCKED(object);
1043 
1044 	/*
1045 	 * do we have good backing store at the requested index ?
1046 	 */
1047 	blk0 = swp_pager_meta_ctl(object, pindex, 0);
1048 	if (blk0 == SWAPBLK_NONE) {
1049 		if (before)
1050 			*before = 0;
1051 		if (after)
1052 			*after = 0;
1053 		return (FALSE);
1054 	}
1055 
1056 	/*
1057 	 * find backwards-looking contiguous good backing store
1058 	 */
1059 	if (before != NULL) {
1060 		for (i = 1; i < SWB_NPAGES; i++) {
1061 			if (i > pindex)
1062 				break;
1063 			blk = swp_pager_meta_ctl(object, pindex - i, 0);
1064 			if (blk != blk0 - i)
1065 				break;
1066 		}
1067 		*before = i - 1;
1068 	}
1069 
1070 	/*
1071 	 * find forward-looking contiguous good backing store
1072 	 */
1073 	if (after != NULL) {
1074 		for (i = 1; i < SWB_NPAGES; i++) {
1075 			blk = swp_pager_meta_ctl(object, pindex + i, 0);
1076 			if (blk != blk0 + i)
1077 				break;
1078 		}
1079 		*after = i - 1;
1080 	}
1081 	return (TRUE);
1082 }
1083 
1084 /*
1085  * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1086  *
1087  *	This removes any associated swap backing store, whether valid or
1088  *	not, from the page.
1089  *
1090  *	This routine is typically called when a page is made dirty, at
1091  *	which point any associated swap can be freed.  MADV_FREE also
1092  *	calls us in a special-case situation
1093  *
1094  *	NOTE!!!  If the page is clean and the swap was valid, the caller
1095  *	should make the page dirty before calling this routine.  This routine
1096  *	does NOT change the m->dirty status of the page.  Also: MADV_FREE
1097  *	depends on it.
1098  *
1099  *	This routine may not sleep.
1100  *
1101  *	The object containing the page must be locked.
1102  */
1103 static void
swap_pager_unswapped(vm_page_t m)1104 swap_pager_unswapped(vm_page_t m)
1105 {
1106 	daddr_t srcaddr;
1107 
1108 	srcaddr = swp_pager_meta_ctl(m->object, m->pindex, SWM_POP);
1109 	if (srcaddr != SWAPBLK_NONE)
1110 		swp_pager_freeswapspace(srcaddr, 1);
1111 }
1112 
1113 /*
1114  * swap_pager_getpages() - bring pages in from swap
1115  *
1116  *	Attempt to page in the pages in array "ma" of length "count".  The
1117  *	caller may optionally specify that additional pages preceding and
1118  *	succeeding the specified range be paged in.  The number of such pages
1119  *	is returned in the "rbehind" and "rahead" parameters, and they will
1120  *	be in the inactive queue upon return.
1121  *
1122  *	The pages in "ma" must be busied and will remain busied upon return.
1123  */
1124 static int
swap_pager_getpages(vm_object_t object,vm_page_t * ma,int count,int * rbehind,int * rahead)1125 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count, int *rbehind,
1126     int *rahead)
1127 {
1128 	struct buf *bp;
1129 	vm_page_t bm, mpred, msucc, p;
1130 	vm_pindex_t pindex;
1131 	daddr_t blk;
1132 	int i, maxahead, maxbehind, reqcount;
1133 
1134 	reqcount = count;
1135 
1136 	/*
1137 	 * Determine the final number of read-behind pages and
1138 	 * allocate them BEFORE releasing the object lock.  Otherwise,
1139 	 * there can be a problematic race with vm_object_split().
1140 	 * Specifically, vm_object_split() might first transfer pages
1141 	 * that precede ma[0] in the current object to a new object,
1142 	 * and then this function incorrectly recreates those pages as
1143 	 * read-behind pages in the current object.
1144 	 */
1145 	if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead))
1146 		return (VM_PAGER_FAIL);
1147 
1148 	/*
1149 	 * Clip the readahead and readbehind ranges to exclude resident pages.
1150 	 */
1151 	if (rahead != NULL) {
1152 		KASSERT(reqcount - 1 <= maxahead,
1153 		    ("page count %d extends beyond swap block", reqcount));
1154 		*rahead = imin(*rahead, maxahead - (reqcount - 1));
1155 		pindex = ma[reqcount - 1]->pindex;
1156 		msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1157 		if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1158 			*rahead = msucc->pindex - pindex - 1;
1159 	}
1160 	if (rbehind != NULL) {
1161 		*rbehind = imin(*rbehind, maxbehind);
1162 		pindex = ma[0]->pindex;
1163 		mpred = TAILQ_PREV(ma[0], pglist, listq);
1164 		if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1165 			*rbehind = pindex - mpred->pindex - 1;
1166 	}
1167 
1168 	bm = ma[0];
1169 	for (i = 0; i < count; i++)
1170 		ma[i]->oflags |= VPO_SWAPINPROG;
1171 
1172 	/*
1173 	 * Allocate readahead and readbehind pages.
1174 	 */
1175 	if (rbehind != NULL) {
1176 		for (i = 1; i <= *rbehind; i++) {
1177 			p = vm_page_alloc(object, ma[0]->pindex - i,
1178 			    VM_ALLOC_NORMAL);
1179 			if (p == NULL)
1180 				break;
1181 			p->oflags |= VPO_SWAPINPROG;
1182 			bm = p;
1183 		}
1184 		*rbehind = i - 1;
1185 	}
1186 	if (rahead != NULL) {
1187 		for (i = 0; i < *rahead; i++) {
1188 			p = vm_page_alloc(object,
1189 			    ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1190 			if (p == NULL)
1191 				break;
1192 			p->oflags |= VPO_SWAPINPROG;
1193 		}
1194 		*rahead = i;
1195 	}
1196 	if (rbehind != NULL)
1197 		count += *rbehind;
1198 	if (rahead != NULL)
1199 		count += *rahead;
1200 
1201 	vm_object_pip_add(object, count);
1202 
1203 	pindex = bm->pindex;
1204 	blk = swp_pager_meta_ctl(object, pindex, 0);
1205 	KASSERT(blk != SWAPBLK_NONE,
1206 	    ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1207 
1208 	VM_OBJECT_WUNLOCK(object);
1209 	bp = getpbuf(&nsw_rcount);
1210 	/* Pages cannot leave the object while busy. */
1211 	for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1212 		MPASS(p->pindex == bm->pindex + i);
1213 		bp->b_pages[i] = p;
1214 	}
1215 
1216 	bp->b_flags |= B_PAGING;
1217 	bp->b_iocmd = BIO_READ;
1218 	bp->b_iodone = swp_pager_async_iodone;
1219 	bp->b_rcred = crhold(thread0.td_ucred);
1220 	bp->b_wcred = crhold(thread0.td_ucred);
1221 	bp->b_blkno = blk;
1222 	bp->b_bcount = PAGE_SIZE * count;
1223 	bp->b_bufsize = PAGE_SIZE * count;
1224 	bp->b_npages = count;
1225 	bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1226 	bp->b_pgafter = rahead != NULL ? *rahead : 0;
1227 
1228 	VM_CNT_INC(v_swapin);
1229 	VM_CNT_ADD(v_swappgsin, count);
1230 
1231 	/*
1232 	 * perform the I/O.  NOTE!!!  bp cannot be considered valid after
1233 	 * this point because we automatically release it on completion.
1234 	 * Instead, we look at the one page we are interested in which we
1235 	 * still hold a lock on even through the I/O completion.
1236 	 *
1237 	 * The other pages in our ma[] array are also released on completion,
1238 	 * so we cannot assume they are valid anymore either.
1239 	 *
1240 	 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1241 	 */
1242 	BUF_KERNPROC(bp);
1243 	swp_pager_strategy(bp);
1244 
1245 	/*
1246 	 * Wait for the pages we want to complete.  VPO_SWAPINPROG is always
1247 	 * cleared on completion.  If an I/O error occurs, SWAPBLK_NONE
1248 	 * is set in the metadata for each page in the request.
1249 	 */
1250 	VM_OBJECT_WLOCK(object);
1251 	while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
1252 		ma[0]->oflags |= VPO_SWAPSLEEP;
1253 		VM_CNT_INC(v_intrans);
1254 		if (VM_OBJECT_SLEEP(object, &object->paging_in_progress, PSWP,
1255 		    "swread", hz * 20)) {
1256 			printf(
1257 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1258 			    bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1259 		}
1260 	}
1261 
1262 	/*
1263 	 * If we had an unrecoverable read error pages will not be valid.
1264 	 */
1265 	for (i = 0; i < reqcount; i++)
1266 		if (ma[i]->valid != VM_PAGE_BITS_ALL)
1267 			return (VM_PAGER_ERROR);
1268 
1269 	return (VM_PAGER_OK);
1270 
1271 	/*
1272 	 * A final note: in a low swap situation, we cannot deallocate swap
1273 	 * and mark a page dirty here because the caller is likely to mark
1274 	 * the page clean when we return, causing the page to possibly revert
1275 	 * to all-zero's later.
1276 	 */
1277 }
1278 
1279 /*
1280  * 	swap_pager_getpages_async():
1281  *
1282  *	Right now this is emulation of asynchronous operation on top of
1283  *	swap_pager_getpages().
1284  */
1285 static int
swap_pager_getpages_async(vm_object_t object,vm_page_t * ma,int count,int * rbehind,int * rahead,pgo_getpages_iodone_t iodone,void * arg)1286 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1287     int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1288 {
1289 	int r, error;
1290 
1291 	r = swap_pager_getpages(object, ma, count, rbehind, rahead);
1292 	VM_OBJECT_WUNLOCK(object);
1293 	switch (r) {
1294 	case VM_PAGER_OK:
1295 		error = 0;
1296 		break;
1297 	case VM_PAGER_ERROR:
1298 		error = EIO;
1299 		break;
1300 	case VM_PAGER_FAIL:
1301 		error = EINVAL;
1302 		break;
1303 	default:
1304 		panic("unhandled swap_pager_getpages() error %d", r);
1305 	}
1306 	(iodone)(arg, ma, count, error);
1307 	VM_OBJECT_WLOCK(object);
1308 
1309 	return (r);
1310 }
1311 
1312 /*
1313  *	swap_pager_putpages:
1314  *
1315  *	Assign swap (if necessary) and initiate I/O on the specified pages.
1316  *
1317  *	We support both OBJT_DEFAULT and OBJT_SWAP objects.  DEFAULT objects
1318  *	are automatically converted to SWAP objects.
1319  *
1320  *	In a low memory situation we may block in VOP_STRATEGY(), but the new
1321  *	vm_page reservation system coupled with properly written VFS devices
1322  *	should ensure that no low-memory deadlock occurs.  This is an area
1323  *	which needs work.
1324  *
1325  *	The parent has N vm_object_pip_add() references prior to
1326  *	calling us and will remove references for rtvals[] that are
1327  *	not set to VM_PAGER_PEND.  We need to remove the rest on I/O
1328  *	completion.
1329  *
1330  *	The parent has soft-busy'd the pages it passes us and will unbusy
1331  *	those whos rtvals[] entry is not set to VM_PAGER_PEND on return.
1332  *	We need to unbusy the rest on I/O completion.
1333  */
1334 static void
swap_pager_putpages(vm_object_t object,vm_page_t * ma,int count,int flags,int * rtvals)1335 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1336     int flags, int *rtvals)
1337 {
1338 	int i, n;
1339 	boolean_t sync;
1340 	daddr_t addr, n_free, s_free;
1341 
1342 	swp_pager_init_freerange(&s_free, &n_free);
1343 	if (count && ma[0]->object != object) {
1344 		panic("swap_pager_putpages: object mismatch %p/%p",
1345 		    object,
1346 		    ma[0]->object
1347 		);
1348 	}
1349 
1350 	/*
1351 	 * Step 1
1352 	 *
1353 	 * Turn object into OBJT_SWAP
1354 	 * check for bogus sysops
1355 	 * force sync if not pageout process
1356 	 */
1357 	if (object->type != OBJT_SWAP) {
1358 		addr = swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1359 		KASSERT(addr == SWAPBLK_NONE,
1360 		    ("unexpected object swap block"));
1361 	}
1362 	VM_OBJECT_WUNLOCK(object);
1363 
1364 	n = 0;
1365 	if (curproc != pageproc)
1366 		sync = TRUE;
1367 	else
1368 		sync = (flags & VM_PAGER_PUT_SYNC) != 0;
1369 
1370 	/*
1371 	 * Step 2
1372 	 *
1373 	 * Assign swap blocks and issue I/O.  We reallocate swap on the fly.
1374 	 * The page is left dirty until the pageout operation completes
1375 	 * successfully.
1376 	 */
1377 	for (i = 0; i < count; i += n) {
1378 		int j;
1379 		struct buf *bp;
1380 		daddr_t blk;
1381 
1382 		/*
1383 		 * Maximum I/O size is limited by a number of factors.
1384 		 */
1385 		n = min(BLIST_MAX_ALLOC, count - i);
1386 		n = min(n, nsw_cluster_max);
1387 
1388 		/*
1389 		 * Get biggest block of swap we can.  If we fail, fall
1390 		 * back and try to allocate a smaller block.  Don't go
1391 		 * overboard trying to allocate space if it would overly
1392 		 * fragment swap.
1393 		 */
1394 		while (
1395 		    (blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE &&
1396 		    n > 4
1397 		) {
1398 			n >>= 1;
1399 		}
1400 		if (blk == SWAPBLK_NONE) {
1401 			for (j = 0; j < n; ++j)
1402 				rtvals[i+j] = VM_PAGER_FAIL;
1403 			continue;
1404 		}
1405 
1406 		/*
1407 		 * All I/O parameters have been satisfied, build the I/O
1408 		 * request and assign the swap space.
1409 		 */
1410 		if (sync == TRUE) {
1411 			bp = getpbuf(&nsw_wcount_sync);
1412 		} else {
1413 			bp = getpbuf(&nsw_wcount_async);
1414 			bp->b_flags = B_ASYNC;
1415 		}
1416 		bp->b_flags |= B_PAGING;
1417 		bp->b_iocmd = BIO_WRITE;
1418 
1419 		bp->b_rcred = crhold(thread0.td_ucred);
1420 		bp->b_wcred = crhold(thread0.td_ucred);
1421 		bp->b_bcount = PAGE_SIZE * n;
1422 		bp->b_bufsize = PAGE_SIZE * n;
1423 		bp->b_blkno = blk;
1424 
1425 		VM_OBJECT_WLOCK(object);
1426 		for (j = 0; j < n; ++j) {
1427 			vm_page_t mreq = ma[i+j];
1428 
1429 			addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1430 			    blk + j);
1431 			if (addr != SWAPBLK_NONE)
1432 				swp_pager_update_freerange(&s_free, &n_free,
1433 				    addr);
1434 			MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1435 			mreq->oflags |= VPO_SWAPINPROG;
1436 			bp->b_pages[j] = mreq;
1437 		}
1438 		VM_OBJECT_WUNLOCK(object);
1439 		bp->b_npages = n;
1440 		/*
1441 		 * Must set dirty range for NFS to work.
1442 		 */
1443 		bp->b_dirtyoff = 0;
1444 		bp->b_dirtyend = bp->b_bcount;
1445 
1446 		VM_CNT_INC(v_swapout);
1447 		VM_CNT_ADD(v_swappgsout, bp->b_npages);
1448 
1449 		/*
1450 		 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1451 		 * can call the async completion routine at the end of a
1452 		 * synchronous I/O operation.  Otherwise, our caller would
1453 		 * perform duplicate unbusy and wakeup operations on the page
1454 		 * and object, respectively.
1455 		 */
1456 		for (j = 0; j < n; j++)
1457 			rtvals[i + j] = VM_PAGER_PEND;
1458 
1459 		/*
1460 		 * asynchronous
1461 		 *
1462 		 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1463 		 */
1464 		if (sync == FALSE) {
1465 			bp->b_iodone = swp_pager_async_iodone;
1466 			BUF_KERNPROC(bp);
1467 			swp_pager_strategy(bp);
1468 			continue;
1469 		}
1470 
1471 		/*
1472 		 * synchronous
1473 		 *
1474 		 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1475 		 */
1476 		bp->b_iodone = bdone;
1477 		swp_pager_strategy(bp);
1478 
1479 		/*
1480 		 * Wait for the sync I/O to complete.
1481 		 */
1482 		bwait(bp, PVM, "swwrt");
1483 
1484 		/*
1485 		 * Now that we are through with the bp, we can call the
1486 		 * normal async completion, which frees everything up.
1487 		 */
1488 		swp_pager_async_iodone(bp);
1489 	}
1490 	VM_OBJECT_WLOCK(object);
1491 	swp_pager_freeswapspace(s_free, n_free);
1492 }
1493 
1494 /*
1495  *	swp_pager_async_iodone:
1496  *
1497  *	Completion routine for asynchronous reads and writes from/to swap.
1498  *	Also called manually by synchronous code to finish up a bp.
1499  *
1500  *	This routine may not sleep.
1501  */
1502 static void
swp_pager_async_iodone(struct buf * bp)1503 swp_pager_async_iodone(struct buf *bp)
1504 {
1505 	int i;
1506 	vm_object_t object = NULL;
1507 
1508 	/*
1509 	 * report error
1510 	 */
1511 	if (bp->b_ioflags & BIO_ERROR) {
1512 		printf(
1513 		    "swap_pager: I/O error - %s failed; blkno %ld,"
1514 			"size %ld, error %d\n",
1515 		    ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1516 		    (long)bp->b_blkno,
1517 		    (long)bp->b_bcount,
1518 		    bp->b_error
1519 		);
1520 	}
1521 
1522 	/*
1523 	 * remove the mapping for kernel virtual
1524 	 */
1525 	if (buf_mapped(bp))
1526 		pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1527 	else
1528 		bp->b_data = bp->b_kvabase;
1529 
1530 	if (bp->b_npages) {
1531 		object = bp->b_pages[0]->object;
1532 		VM_OBJECT_WLOCK(object);
1533 	}
1534 
1535 	/*
1536 	 * cleanup pages.  If an error occurs writing to swap, we are in
1537 	 * very serious trouble.  If it happens to be a disk error, though,
1538 	 * we may be able to recover by reassigning the swap later on.  So
1539 	 * in this case we remove the m->swapblk assignment for the page
1540 	 * but do not free it in the rlist.  The errornous block(s) are thus
1541 	 * never reallocated as swap.  Redirty the page and continue.
1542 	 */
1543 	for (i = 0; i < bp->b_npages; ++i) {
1544 		vm_page_t m = bp->b_pages[i];
1545 
1546 		m->oflags &= ~VPO_SWAPINPROG;
1547 		if (m->oflags & VPO_SWAPSLEEP) {
1548 			m->oflags &= ~VPO_SWAPSLEEP;
1549 			wakeup(&object->paging_in_progress);
1550 		}
1551 
1552 		if (bp->b_ioflags & BIO_ERROR) {
1553 			/*
1554 			 * If an error occurs I'd love to throw the swapblk
1555 			 * away without freeing it back to swapspace, so it
1556 			 * can never be used again.  But I can't from an
1557 			 * interrupt.
1558 			 */
1559 			if (bp->b_iocmd == BIO_READ) {
1560 				/*
1561 				 * NOTE: for reads, m->dirty will probably
1562 				 * be overridden by the original caller of
1563 				 * getpages so don't play cute tricks here.
1564 				 */
1565 				m->valid = 0;
1566 			} else {
1567 				/*
1568 				 * If a write error occurs, reactivate page
1569 				 * so it doesn't clog the inactive list,
1570 				 * then finish the I/O.
1571 				 */
1572 				MPASS(m->dirty == VM_PAGE_BITS_ALL);
1573 				vm_page_lock(m);
1574 				vm_page_activate(m);
1575 				vm_page_unlock(m);
1576 				vm_page_sunbusy(m);
1577 			}
1578 		} else if (bp->b_iocmd == BIO_READ) {
1579 			/*
1580 			 * NOTE: for reads, m->dirty will probably be
1581 			 * overridden by the original caller of getpages so
1582 			 * we cannot set them in order to free the underlying
1583 			 * swap in a low-swap situation.  I don't think we'd
1584 			 * want to do that anyway, but it was an optimization
1585 			 * that existed in the old swapper for a time before
1586 			 * it got ripped out due to precisely this problem.
1587 			 */
1588 			KASSERT(!pmap_page_is_mapped(m),
1589 			    ("swp_pager_async_iodone: page %p is mapped", m));
1590 			KASSERT(m->dirty == 0,
1591 			    ("swp_pager_async_iodone: page %p is dirty", m));
1592 
1593 			m->valid = VM_PAGE_BITS_ALL;
1594 			if (i < bp->b_pgbefore ||
1595 			    i >= bp->b_npages - bp->b_pgafter)
1596 				vm_page_readahead_finish(m);
1597 		} else {
1598 			/*
1599 			 * For write success, clear the dirty
1600 			 * status, then finish the I/O ( which decrements the
1601 			 * busy count and possibly wakes waiter's up ).
1602 			 * A page is only written to swap after a period of
1603 			 * inactivity.  Therefore, we do not expect it to be
1604 			 * reused.
1605 			 */
1606 			KASSERT(!pmap_page_is_write_mapped(m),
1607 			    ("swp_pager_async_iodone: page %p is not write"
1608 			    " protected", m));
1609 			vm_page_undirty(m);
1610 			vm_page_lock(m);
1611 			vm_page_deactivate_noreuse(m);
1612 			vm_page_unlock(m);
1613 			vm_page_sunbusy(m);
1614 		}
1615 	}
1616 
1617 	/*
1618 	 * adjust pip.  NOTE: the original parent may still have its own
1619 	 * pip refs on the object.
1620 	 */
1621 	if (object != NULL) {
1622 		vm_object_pip_wakeupn(object, bp->b_npages);
1623 		VM_OBJECT_WUNLOCK(object);
1624 	}
1625 
1626 	/*
1627 	 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1628 	 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1629 	 * trigger a KASSERT in relpbuf().
1630 	 */
1631 	if (bp->b_vp) {
1632 		    bp->b_vp = NULL;
1633 		    bp->b_bufobj = NULL;
1634 	}
1635 	/*
1636 	 * release the physical I/O buffer
1637 	 */
1638 	relpbuf(
1639 	    bp,
1640 	    ((bp->b_iocmd == BIO_READ) ? &nsw_rcount :
1641 		((bp->b_flags & B_ASYNC) ?
1642 		    &nsw_wcount_async :
1643 		    &nsw_wcount_sync
1644 		)
1645 	    )
1646 	);
1647 }
1648 
1649 int
swap_pager_nswapdev(void)1650 swap_pager_nswapdev(void)
1651 {
1652 
1653 	return (nswapdev);
1654 }
1655 
1656 static void
swp_pager_force_dirty(vm_page_t m)1657 swp_pager_force_dirty(vm_page_t m)
1658 {
1659 
1660 	vm_page_dirty(m);
1661 #ifdef INVARIANTS
1662 	vm_page_lock(m);
1663 	if (!vm_page_wired(m) && m->queue == PQ_NONE)
1664 		panic("page %p is neither wired nor queued", m);
1665 	vm_page_unlock(m);
1666 #endif
1667 	vm_page_xunbusy(m);
1668 	swap_pager_unswapped(m);
1669 }
1670 
1671 static void
swp_pager_force_launder(vm_page_t m)1672 swp_pager_force_launder(vm_page_t m)
1673 {
1674 
1675 	vm_page_dirty(m);
1676 	vm_page_lock(m);
1677 	vm_page_launder(m);
1678 	vm_page_unlock(m);
1679 	vm_page_xunbusy(m);
1680 	swap_pager_unswapped(m);
1681 }
1682 
1683 /*
1684  * SWP_PAGER_FORCE_PAGEIN() - force swap blocks to be paged in
1685  *
1686  *	This routine dissociates pages starting at the given index within an
1687  *	object from their backing store, paging them in if they do not reside
1688  *	in memory.  Pages that are paged in are marked dirty and placed in the
1689  *	laundry queue.  Pages are marked dirty because they no longer have
1690  *	backing store.  They are placed in the laundry queue because they have
1691  *	not been accessed recently.  Otherwise, they would already reside in
1692  *	memory.
1693  */
1694 static void
swp_pager_force_pagein(vm_object_t object,vm_pindex_t pindex,int npages)1695 swp_pager_force_pagein(vm_object_t object, vm_pindex_t pindex, int npages)
1696 {
1697 	vm_page_t ma[npages];
1698 	int i, j;
1699 
1700 	KASSERT(npages > 0, ("%s: No pages", __func__));
1701 	KASSERT(npages <= MAXPHYS / PAGE_SIZE,
1702 	    ("%s: Too many pages: %d", __func__, npages));
1703 	vm_object_pip_add(object, npages);
1704 	vm_page_grab_pages(object, pindex, VM_ALLOC_NORMAL, ma, npages);
1705 	for (i = j = 0;; i++) {
1706 		/* Count nonresident pages, to page-in all at once. */
1707 		if (i < npages && ma[i]->valid != VM_PAGE_BITS_ALL)
1708 			continue;
1709 		if (j < i) {
1710 			/* Page-in nonresident pages. Mark for laundering. */
1711 			if (swap_pager_getpages(object, &ma[j], i - j, NULL,
1712 			    NULL) != VM_PAGER_OK)
1713 				panic("%s: read from swap failed", __func__);
1714 			do {
1715 				swp_pager_force_launder(ma[j]);
1716 			} while (++j < i);
1717 		}
1718 		if (i == npages)
1719 			break;
1720 		/* Mark dirty a resident page. */
1721 		swp_pager_force_dirty(ma[j++]);
1722 	}
1723 	vm_object_pip_wakeupn(object, npages);
1724 }
1725 
1726 /*
1727  *	swap_pager_swapoff_object:
1728  *
1729  *	Page in all of the pages that have been paged out for an object
1730  *	to a swap device.
1731  */
1732 static void
swap_pager_swapoff_object(struct swdevt * sp,vm_object_t object)1733 swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
1734 {
1735 	struct swblk *sb;
1736 	vm_pindex_t pi, s_pindex;
1737 	daddr_t blk, n_blks, s_blk;
1738 	int i;
1739 
1740 	n_blks = 0;
1741 	for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1742 	    &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1743 		for (i = 0; i < SWAP_META_PAGES; i++) {
1744 			blk = sb->d[i];
1745 			if (!swp_pager_isondev(blk, sp))
1746 				blk = SWAPBLK_NONE;
1747 
1748 			/*
1749 			 * If there are no blocks/pages accumulated, start a new
1750 			 * accumulation here.
1751 			 */
1752 			if (n_blks == 0) {
1753 				if (blk != SWAPBLK_NONE) {
1754 					s_blk = blk;
1755 					s_pindex = sb->p + i;
1756 					n_blks = 1;
1757 				}
1758 				continue;
1759 			}
1760 
1761 			/*
1762 			 * If the accumulation can be extended without breaking
1763 			 * the sequence of consecutive blocks and pages that
1764 			 * swp_pager_force_pagein() depends on, do so.
1765 			 */
1766 			if (n_blks < MAXPHYS / PAGE_SIZE &&
1767 			    s_blk + n_blks == blk &&
1768 			    s_pindex + n_blks == sb->p + i) {
1769 				++n_blks;
1770 				continue;
1771 			}
1772 
1773 			/*
1774 			 * The sequence of consecutive blocks and pages cannot
1775 			 * be extended, so page them all in here.  Then,
1776 			 * because doing so involves releasing and reacquiring
1777 			 * a lock that protects the swap block pctrie, do not
1778 			 * rely on the current swap block.  Break this loop and
1779 			 * re-fetch the same pindex from the pctrie again.
1780 			 */
1781 			swp_pager_force_pagein(object, s_pindex, n_blks);
1782 			n_blks = 0;
1783 			break;
1784 		}
1785 		if (i == SWAP_META_PAGES)
1786 			pi = sb->p + SWAP_META_PAGES;
1787 	}
1788 	if (n_blks > 0)
1789 		swp_pager_force_pagein(object, s_pindex, n_blks);
1790 }
1791 
1792 /*
1793  *	swap_pager_swapoff:
1794  *
1795  *	Page in all of the pages that have been paged out to the
1796  *	given device.  The corresponding blocks in the bitmap must be
1797  *	marked as allocated and the device must be flagged SW_CLOSING.
1798  *	There may be no processes swapped out to the device.
1799  *
1800  *	This routine may block.
1801  */
1802 static void
swap_pager_swapoff(struct swdevt * sp)1803 swap_pager_swapoff(struct swdevt *sp)
1804 {
1805 	vm_object_t object;
1806 	int retries;
1807 
1808 	sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1809 
1810 	retries = 0;
1811 full_rescan:
1812 	mtx_lock(&vm_object_list_mtx);
1813 	TAILQ_FOREACH(object, &vm_object_list, object_list) {
1814 		if (object->type != OBJT_SWAP)
1815 			continue;
1816 		mtx_unlock(&vm_object_list_mtx);
1817 		/* Depends on type-stability. */
1818 		VM_OBJECT_WLOCK(object);
1819 
1820 		/*
1821 		 * Dead objects are eventually terminated on their own.
1822 		 */
1823 		if ((object->flags & OBJ_DEAD) != 0)
1824 			goto next_obj;
1825 
1826 		/*
1827 		 * Sync with fences placed after pctrie
1828 		 * initialization.  We must not access pctrie below
1829 		 * unless we checked that our object is swap and not
1830 		 * dead.
1831 		 */
1832 		atomic_thread_fence_acq();
1833 		if (object->type != OBJT_SWAP)
1834 			goto next_obj;
1835 
1836 		swap_pager_swapoff_object(sp, object);
1837 next_obj:
1838 		VM_OBJECT_WUNLOCK(object);
1839 		mtx_lock(&vm_object_list_mtx);
1840 	}
1841 	mtx_unlock(&vm_object_list_mtx);
1842 
1843 	if (sp->sw_used) {
1844 		/*
1845 		 * Objects may be locked or paging to the device being
1846 		 * removed, so we will miss their pages and need to
1847 		 * make another pass.  We have marked this device as
1848 		 * SW_CLOSING, so the activity should finish soon.
1849 		 */
1850 		retries++;
1851 		if (retries > 100) {
1852 			panic("swapoff: failed to locate %d swap blocks",
1853 			    sp->sw_used);
1854 		}
1855 		pause("swpoff", hz / 20);
1856 		goto full_rescan;
1857 	}
1858 	EVENTHANDLER_INVOKE(swapoff, sp);
1859 }
1860 
1861 /************************************************************************
1862  *				SWAP META DATA 				*
1863  ************************************************************************
1864  *
1865  *	These routines manipulate the swap metadata stored in the
1866  *	OBJT_SWAP object.
1867  *
1868  *	Swap metadata is implemented with a global hash and not directly
1869  *	linked into the object.  Instead the object simply contains
1870  *	appropriate tracking counters.
1871  */
1872 
1873 /*
1874  * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
1875  */
1876 static bool
swp_pager_swblk_empty(struct swblk * sb,int start,int limit)1877 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
1878 {
1879 	int i;
1880 
1881 	MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
1882 	for (i = start; i < limit; i++) {
1883 		if (sb->d[i] != SWAPBLK_NONE)
1884 			return (false);
1885 	}
1886 	return (true);
1887 }
1888 
1889 /*
1890  * SWP_PAGER_META_BUILD() -	add swap block to swap meta data for object
1891  *
1892  *	We first convert the object to a swap object if it is a default
1893  *	object.
1894  *
1895  *	The specified swapblk is added to the object's swap metadata.  If
1896  *	the swapblk is not valid, it is freed instead.  Any previously
1897  *	assigned swapblk is returned.
1898  */
1899 static daddr_t
swp_pager_meta_build(vm_object_t object,vm_pindex_t pindex,daddr_t swapblk)1900 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
1901 {
1902 	static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
1903 	struct swblk *sb, *sb1;
1904 	vm_pindex_t modpi, rdpi;
1905 	daddr_t prev_swapblk;
1906 	int error, i;
1907 
1908 	VM_OBJECT_ASSERT_WLOCKED(object);
1909 
1910 	/*
1911 	 * Convert default object to swap object if necessary
1912 	 */
1913 	if (object->type != OBJT_SWAP) {
1914 		pctrie_init(&object->un_pager.swp.swp_blks);
1915 
1916 		/*
1917 		 * Ensure that swap_pager_swapoff()'s iteration over
1918 		 * object_list does not see a garbage pctrie.
1919 		 */
1920 		atomic_thread_fence_rel();
1921 
1922 		object->type = OBJT_SWAP;
1923 		KASSERT(object->handle == NULL, ("default pager with handle"));
1924 	}
1925 
1926 	rdpi = rounddown(pindex, SWAP_META_PAGES);
1927 	sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
1928 	if (sb == NULL) {
1929 		if (swapblk == SWAPBLK_NONE)
1930 			return (SWAPBLK_NONE);
1931 		for (;;) {
1932 			sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
1933 			    pageproc ? M_USE_RESERVE : 0));
1934 			if (sb != NULL) {
1935 				sb->p = rdpi;
1936 				for (i = 0; i < SWAP_META_PAGES; i++)
1937 					sb->d[i] = SWAPBLK_NONE;
1938 				if (atomic_cmpset_int(&swblk_zone_exhausted,
1939 				    1, 0))
1940 					printf("swblk zone ok\n");
1941 				break;
1942 			}
1943 			VM_OBJECT_WUNLOCK(object);
1944 			if (uma_zone_exhausted(swblk_zone)) {
1945 				if (atomic_cmpset_int(&swblk_zone_exhausted,
1946 				    0, 1))
1947 					printf("swap blk zone exhausted, "
1948 					    "increase kern.maxswzone\n");
1949 				vm_pageout_oom(VM_OOM_SWAPZ);
1950 				pause("swzonxb", 10);
1951 			} else
1952 				uma_zwait(swblk_zone);
1953 			VM_OBJECT_WLOCK(object);
1954 			sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
1955 			    rdpi);
1956 			if (sb != NULL)
1957 				/*
1958 				 * Somebody swapped out a nearby page,
1959 				 * allocating swblk at the rdpi index,
1960 				 * while we dropped the object lock.
1961 				 */
1962 				goto allocated;
1963 		}
1964 		for (;;) {
1965 			error = SWAP_PCTRIE_INSERT(
1966 			    &object->un_pager.swp.swp_blks, sb);
1967 			if (error == 0) {
1968 				if (atomic_cmpset_int(&swpctrie_zone_exhausted,
1969 				    1, 0))
1970 					printf("swpctrie zone ok\n");
1971 				break;
1972 			}
1973 			VM_OBJECT_WUNLOCK(object);
1974 			if (uma_zone_exhausted(swpctrie_zone)) {
1975 				if (atomic_cmpset_int(&swpctrie_zone_exhausted,
1976 				    0, 1))
1977 					printf("swap pctrie zone exhausted, "
1978 					    "increase kern.maxswzone\n");
1979 				vm_pageout_oom(VM_OOM_SWAPZ);
1980 				pause("swzonxp", 10);
1981 			} else
1982 				uma_zwait(swpctrie_zone);
1983 			VM_OBJECT_WLOCK(object);
1984 			sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
1985 			    rdpi);
1986 			if (sb1 != NULL) {
1987 				uma_zfree(swblk_zone, sb);
1988 				sb = sb1;
1989 				goto allocated;
1990 			}
1991 		}
1992 	}
1993 allocated:
1994 	MPASS(sb->p == rdpi);
1995 
1996 	modpi = pindex % SWAP_META_PAGES;
1997 	/* Return prior contents of metadata. */
1998 	prev_swapblk = sb->d[modpi];
1999 	/* Enter block into metadata. */
2000 	sb->d[modpi] = swapblk;
2001 
2002 	/*
2003 	 * Free the swblk if we end up with the empty page run.
2004 	 */
2005 	if (swapblk == SWAPBLK_NONE &&
2006 	    swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
2007 		SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, rdpi);
2008 		uma_zfree(swblk_zone, sb);
2009 	}
2010 	return (prev_swapblk);
2011 }
2012 
2013 /*
2014  * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
2015  *
2016  *	The requested range of blocks is freed, with any associated swap
2017  *	returned to the swap bitmap.
2018  *
2019  *	This routine will free swap metadata structures as they are cleaned
2020  *	out.  This routine does *NOT* operate on swap metadata associated
2021  *	with resident pages.
2022  */
2023 static void
swp_pager_meta_free(vm_object_t object,vm_pindex_t pindex,vm_pindex_t count)2024 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count)
2025 {
2026 	struct swblk *sb;
2027 	daddr_t n_free, s_free;
2028 	vm_pindex_t last;
2029 	int i, limit, start;
2030 
2031 	VM_OBJECT_ASSERT_WLOCKED(object);
2032 	if (object->type != OBJT_SWAP || count == 0)
2033 		return;
2034 
2035 	swp_pager_init_freerange(&s_free, &n_free);
2036 	last = pindex + count;
2037 	for (;;) {
2038 		sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2039 		    rounddown(pindex, SWAP_META_PAGES));
2040 		if (sb == NULL || sb->p >= last)
2041 			break;
2042 		start = pindex > sb->p ? pindex - sb->p : 0;
2043 		limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2044 		    SWAP_META_PAGES;
2045 		for (i = start; i < limit; i++) {
2046 			if (sb->d[i] == SWAPBLK_NONE)
2047 				continue;
2048 			swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
2049 			sb->d[i] = SWAPBLK_NONE;
2050 		}
2051 		pindex = sb->p + SWAP_META_PAGES;
2052 		if (swp_pager_swblk_empty(sb, 0, start) &&
2053 		    swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2054 			SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks,
2055 			    sb->p);
2056 			uma_zfree(swblk_zone, sb);
2057 		}
2058 	}
2059 	swp_pager_freeswapspace(s_free, n_free);
2060 }
2061 
2062 /*
2063  * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
2064  *
2065  *	This routine locates and destroys all swap metadata associated with
2066  *	an object.
2067  */
2068 static void
swp_pager_meta_free_all(vm_object_t object)2069 swp_pager_meta_free_all(vm_object_t object)
2070 {
2071 	struct swblk *sb;
2072 	daddr_t n_free, s_free;
2073 	vm_pindex_t pindex;
2074 	int i;
2075 
2076 	VM_OBJECT_ASSERT_WLOCKED(object);
2077 	if (object->type != OBJT_SWAP)
2078 		return;
2079 
2080 	swp_pager_init_freerange(&s_free, &n_free);
2081 	for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
2082 	    &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
2083 		pindex = sb->p + SWAP_META_PAGES;
2084 		for (i = 0; i < SWAP_META_PAGES; i++) {
2085 			if (sb->d[i] == SWAPBLK_NONE)
2086 				continue;
2087 			swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
2088 		}
2089 		SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2090 		uma_zfree(swblk_zone, sb);
2091 	}
2092 	swp_pager_freeswapspace(s_free, n_free);
2093 }
2094 
2095 /*
2096  * SWP_PAGER_METACTL() -  misc control of swap meta data.
2097  *
2098  *	This routine is capable of looking up, or removing swapblk
2099  *	assignments in the swap meta data.  It returns the swapblk being
2100  *	looked-up, popped, or SWAPBLK_NONE if the block was invalid.
2101  *
2102  *	When acting on a busy resident page and paging is in progress, we
2103  *	have to wait until paging is complete but otherwise can act on the
2104  *	busy page.
2105  *
2106  *	SWM_POP		remove from meta data but do not free it
2107  */
2108 static daddr_t
swp_pager_meta_ctl(vm_object_t object,vm_pindex_t pindex,int flags)2109 swp_pager_meta_ctl(vm_object_t object, vm_pindex_t pindex, int flags)
2110 {
2111 	struct swblk *sb;
2112 	daddr_t r1;
2113 
2114 	if ((flags & SWM_POP) != 0)
2115 		VM_OBJECT_ASSERT_WLOCKED(object);
2116 	else
2117 		VM_OBJECT_ASSERT_LOCKED(object);
2118 
2119 	/*
2120 	 * The meta data only exists if the object is OBJT_SWAP
2121 	 * and even then might not be allocated yet.
2122 	 */
2123 	if (object->type != OBJT_SWAP)
2124 		return (SWAPBLK_NONE);
2125 
2126 	sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2127 	    rounddown(pindex, SWAP_META_PAGES));
2128 	if (sb == NULL)
2129 		return (SWAPBLK_NONE);
2130 	r1 = sb->d[pindex % SWAP_META_PAGES];
2131 	if (r1 == SWAPBLK_NONE)
2132 		return (SWAPBLK_NONE);
2133 	if ((flags & SWM_POP) != 0) {
2134 		sb->d[pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
2135 		if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
2136 			SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks,
2137 			    rounddown(pindex, SWAP_META_PAGES));
2138 			uma_zfree(swblk_zone, sb);
2139 		}
2140 	}
2141 	return (r1);
2142 }
2143 
2144 /*
2145  * Returns the least page index which is greater than or equal to the
2146  * parameter pindex and for which there is a swap block allocated.
2147  * Returns object's size if the object's type is not swap or if there
2148  * are no allocated swap blocks for the object after the requested
2149  * pindex.
2150  */
2151 vm_pindex_t
swap_pager_find_least(vm_object_t object,vm_pindex_t pindex)2152 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2153 {
2154 	struct swblk *sb;
2155 	int i;
2156 
2157 	VM_OBJECT_ASSERT_LOCKED(object);
2158 	if (object->type != OBJT_SWAP)
2159 		return (object->size);
2160 
2161 	sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2162 	    rounddown(pindex, SWAP_META_PAGES));
2163 	if (sb == NULL)
2164 		return (object->size);
2165 	if (sb->p < pindex) {
2166 		for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2167 			if (sb->d[i] != SWAPBLK_NONE)
2168 				return (sb->p + i);
2169 		}
2170 		sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2171 		    roundup(pindex, SWAP_META_PAGES));
2172 		if (sb == NULL)
2173 			return (object->size);
2174 	}
2175 	for (i = 0; i < SWAP_META_PAGES; i++) {
2176 		if (sb->d[i] != SWAPBLK_NONE)
2177 			return (sb->p + i);
2178 	}
2179 
2180 	/*
2181 	 * We get here if a swblk is present in the trie but it
2182 	 * doesn't map any blocks.
2183 	 */
2184 	MPASS(0);
2185 	return (object->size);
2186 }
2187 
2188 /*
2189  * System call swapon(name) enables swapping on device name,
2190  * which must be in the swdevsw.  Return EBUSY
2191  * if already swapping on this device.
2192  */
2193 #ifndef _SYS_SYSPROTO_H_
2194 struct swapon_args {
2195 	char *name;
2196 };
2197 #endif
2198 
2199 /*
2200  * MPSAFE
2201  */
2202 /* ARGSUSED */
2203 int
sys_swapon(struct thread * td,struct swapon_args * uap)2204 sys_swapon(struct thread *td, struct swapon_args *uap)
2205 {
2206 	struct vattr attr;
2207 	struct vnode *vp;
2208 	struct nameidata nd;
2209 	int error;
2210 
2211 	error = priv_check(td, PRIV_SWAPON);
2212 	if (error)
2213 		return (error);
2214 
2215 	sx_xlock(&swdev_syscall_lock);
2216 
2217 	/*
2218 	 * Swap metadata may not fit in the KVM if we have physical
2219 	 * memory of >1GB.
2220 	 */
2221 	if (swblk_zone == NULL) {
2222 		error = ENOMEM;
2223 		goto done;
2224 	}
2225 
2226 	NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2227 	    uap->name, td);
2228 	error = namei(&nd);
2229 	if (error)
2230 		goto done;
2231 
2232 	NDFREE(&nd, NDF_ONLY_PNBUF);
2233 	vp = nd.ni_vp;
2234 
2235 	if (vn_isdisk(vp, &error)) {
2236 		error = swapongeom(vp);
2237 	} else if (vp->v_type == VREG &&
2238 	    (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2239 	    (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2240 		/*
2241 		 * Allow direct swapping to NFS regular files in the same
2242 		 * way that nfs_mountroot() sets up diskless swapping.
2243 		 */
2244 		error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2245 	}
2246 
2247 	if (error)
2248 		vrele(vp);
2249 done:
2250 	sx_xunlock(&swdev_syscall_lock);
2251 	return (error);
2252 }
2253 
2254 /*
2255  * Check that the total amount of swap currently configured does not
2256  * exceed half the theoretical maximum.  If it does, print a warning
2257  * message.
2258  */
2259 static void
swapon_check_swzone(void)2260 swapon_check_swzone(void)
2261 {
2262 	unsigned long maxpages, npages;
2263 
2264 	npages = swap_total;
2265 	/* absolute maximum we can handle assuming 100% efficiency */
2266 	maxpages = uma_zone_get_max(swblk_zone) * SWAP_META_PAGES;
2267 
2268 	/* recommend using no more than half that amount */
2269 	if (npages > maxpages / 2) {
2270 		printf("warning: total configured swap (%lu pages) "
2271 		    "exceeds maximum recommended amount (%lu pages).\n",
2272 		    npages, maxpages / 2);
2273 		printf("warning: increase kern.maxswzone "
2274 		    "or reduce amount of swap.\n");
2275 	}
2276 }
2277 
2278 static void
swaponsomething(struct vnode * vp,void * id,u_long nblks,sw_strategy_t * strategy,sw_close_t * close,dev_t dev,int flags)2279 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2280     sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2281 {
2282 	struct swdevt *sp, *tsp;
2283 	swblk_t dvbase;
2284 	u_long mblocks;
2285 
2286 	/*
2287 	 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2288 	 * First chop nblks off to page-align it, then convert.
2289 	 *
2290 	 * sw->sw_nblks is in page-sized chunks now too.
2291 	 */
2292 	nblks &= ~(ctodb(1) - 1);
2293 	nblks = dbtoc(nblks);
2294 
2295 	/*
2296 	 * If we go beyond this, we get overflows in the radix
2297 	 * tree bitmap code.
2298 	 */
2299 	mblocks = 0x40000000 / BLIST_META_RADIX;
2300 	if (nblks > mblocks) {
2301 		printf(
2302     "WARNING: reducing swap size to maximum of %luMB per unit\n",
2303 		    mblocks / 1024 / 1024 * PAGE_SIZE);
2304 		nblks = mblocks;
2305 	}
2306 
2307 	sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2308 	sp->sw_vp = vp;
2309 	sp->sw_id = id;
2310 	sp->sw_dev = dev;
2311 	sp->sw_nblks = nblks;
2312 	sp->sw_used = 0;
2313 	sp->sw_strategy = strategy;
2314 	sp->sw_close = close;
2315 	sp->sw_flags = flags;
2316 
2317 	sp->sw_blist = blist_create(nblks, M_WAITOK);
2318 	/*
2319 	 * Do not free the first blocks in order to avoid overwriting
2320 	 * any bsd label at the front of the partition
2321 	 */
2322 	blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2323 	    nblks - howmany(BBSIZE, PAGE_SIZE));
2324 
2325 	dvbase = 0;
2326 	mtx_lock(&sw_dev_mtx);
2327 	TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2328 		if (tsp->sw_end >= dvbase) {
2329 			/*
2330 			 * We put one uncovered page between the devices
2331 			 * in order to definitively prevent any cross-device
2332 			 * I/O requests
2333 			 */
2334 			dvbase = tsp->sw_end + 1;
2335 		}
2336 	}
2337 	sp->sw_first = dvbase;
2338 	sp->sw_end = dvbase + nblks;
2339 	TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2340 	nswapdev++;
2341 	swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2342 	swap_total += nblks;
2343 	swapon_check_swzone();
2344 	swp_sizecheck();
2345 	mtx_unlock(&sw_dev_mtx);
2346 	EVENTHANDLER_INVOKE(swapon, sp);
2347 }
2348 
2349 /*
2350  * SYSCALL: swapoff(devname)
2351  *
2352  * Disable swapping on the given device.
2353  *
2354  * XXX: Badly designed system call: it should use a device index
2355  * rather than filename as specification.  We keep sw_vp around
2356  * only to make this work.
2357  */
2358 #ifndef _SYS_SYSPROTO_H_
2359 struct swapoff_args {
2360 	char *name;
2361 };
2362 #endif
2363 
2364 /*
2365  * MPSAFE
2366  */
2367 /* ARGSUSED */
2368 int
sys_swapoff(struct thread * td,struct swapoff_args * uap)2369 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2370 {
2371 	struct vnode *vp;
2372 	struct nameidata nd;
2373 	struct swdevt *sp;
2374 	int error;
2375 
2376 	error = priv_check(td, PRIV_SWAPOFF);
2377 	if (error)
2378 		return (error);
2379 
2380 	sx_xlock(&swdev_syscall_lock);
2381 
2382 	NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2383 	    td);
2384 	error = namei(&nd);
2385 	if (error)
2386 		goto done;
2387 	NDFREE(&nd, NDF_ONLY_PNBUF);
2388 	vp = nd.ni_vp;
2389 
2390 	mtx_lock(&sw_dev_mtx);
2391 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2392 		if (sp->sw_vp == vp)
2393 			break;
2394 	}
2395 	mtx_unlock(&sw_dev_mtx);
2396 	if (sp == NULL) {
2397 		error = EINVAL;
2398 		goto done;
2399 	}
2400 	error = swapoff_one(sp, td->td_ucred);
2401 done:
2402 	sx_xunlock(&swdev_syscall_lock);
2403 	return (error);
2404 }
2405 
2406 static int
swapoff_one(struct swdevt * sp,struct ucred * cred)2407 swapoff_one(struct swdevt *sp, struct ucred *cred)
2408 {
2409 	u_long nblks;
2410 #ifdef MAC
2411 	int error;
2412 #endif
2413 
2414 	sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2415 #ifdef MAC
2416 	(void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2417 	error = mac_system_check_swapoff(cred, sp->sw_vp);
2418 	(void) VOP_UNLOCK(sp->sw_vp, 0);
2419 	if (error != 0)
2420 		return (error);
2421 #endif
2422 	nblks = sp->sw_nblks;
2423 
2424 	/*
2425 	 * We can turn off this swap device safely only if the
2426 	 * available virtual memory in the system will fit the amount
2427 	 * of data we will have to page back in, plus an epsilon so
2428 	 * the system doesn't become critically low on swap space.
2429 	 */
2430 	if (vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
2431 		return (ENOMEM);
2432 
2433 	/*
2434 	 * Prevent further allocations on this device.
2435 	 */
2436 	mtx_lock(&sw_dev_mtx);
2437 	sp->sw_flags |= SW_CLOSING;
2438 	swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2439 	swap_total -= nblks;
2440 	mtx_unlock(&sw_dev_mtx);
2441 
2442 	/*
2443 	 * Page in the contents of the device and close it.
2444 	 */
2445 	swap_pager_swapoff(sp);
2446 
2447 	sp->sw_close(curthread, sp);
2448 	mtx_lock(&sw_dev_mtx);
2449 	sp->sw_id = NULL;
2450 	TAILQ_REMOVE(&swtailq, sp, sw_list);
2451 	nswapdev--;
2452 	if (nswapdev == 0) {
2453 		swap_pager_full = 2;
2454 		swap_pager_almost_full = 1;
2455 	}
2456 	if (swdevhd == sp)
2457 		swdevhd = NULL;
2458 	mtx_unlock(&sw_dev_mtx);
2459 	blist_destroy(sp->sw_blist);
2460 	free(sp, M_VMPGDATA);
2461 	return (0);
2462 }
2463 
2464 void
swapoff_all(void)2465 swapoff_all(void)
2466 {
2467 	struct swdevt *sp, *spt;
2468 	const char *devname;
2469 	int error;
2470 
2471 	sx_xlock(&swdev_syscall_lock);
2472 
2473 	mtx_lock(&sw_dev_mtx);
2474 	TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2475 		mtx_unlock(&sw_dev_mtx);
2476 		if (vn_isdisk(sp->sw_vp, NULL))
2477 			devname = devtoname(sp->sw_vp->v_rdev);
2478 		else
2479 			devname = "[file]";
2480 		error = swapoff_one(sp, thread0.td_ucred);
2481 		if (error != 0) {
2482 			printf("Cannot remove swap device %s (error=%d), "
2483 			    "skipping.\n", devname, error);
2484 		} else if (bootverbose) {
2485 			printf("Swap device %s removed.\n", devname);
2486 		}
2487 		mtx_lock(&sw_dev_mtx);
2488 	}
2489 	mtx_unlock(&sw_dev_mtx);
2490 
2491 	sx_xunlock(&swdev_syscall_lock);
2492 }
2493 
2494 void
swap_pager_status(int * total,int * used)2495 swap_pager_status(int *total, int *used)
2496 {
2497 	struct swdevt *sp;
2498 
2499 	*total = 0;
2500 	*used = 0;
2501 	mtx_lock(&sw_dev_mtx);
2502 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2503 		*total += sp->sw_nblks;
2504 		*used += sp->sw_used;
2505 	}
2506 	mtx_unlock(&sw_dev_mtx);
2507 }
2508 
2509 int
swap_dev_info(int name,struct xswdev * xs,char * devname,size_t len)2510 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2511 {
2512 	struct swdevt *sp;
2513 	const char *tmp_devname;
2514 	int error, n;
2515 
2516 	n = 0;
2517 	error = ENOENT;
2518 	mtx_lock(&sw_dev_mtx);
2519 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2520 		if (n != name) {
2521 			n++;
2522 			continue;
2523 		}
2524 		xs->xsw_version = XSWDEV_VERSION;
2525 		xs->xsw_dev = sp->sw_dev;
2526 		xs->xsw_flags = sp->sw_flags;
2527 		xs->xsw_nblks = sp->sw_nblks;
2528 		xs->xsw_used = sp->sw_used;
2529 		if (devname != NULL) {
2530 			if (vn_isdisk(sp->sw_vp, NULL))
2531 				tmp_devname = devtoname(sp->sw_vp->v_rdev);
2532 			else
2533 				tmp_devname = "[file]";
2534 			strncpy(devname, tmp_devname, len);
2535 		}
2536 		error = 0;
2537 		break;
2538 	}
2539 	mtx_unlock(&sw_dev_mtx);
2540 	return (error);
2541 }
2542 
2543 #if defined(COMPAT_FREEBSD11)
2544 #define XSWDEV_VERSION_11	1
2545 struct xswdev11 {
2546 	u_int	xsw_version;
2547 	uint32_t xsw_dev;
2548 	int	xsw_flags;
2549 	int	xsw_nblks;
2550 	int     xsw_used;
2551 };
2552 #endif
2553 
2554 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2555 struct xswdev32 {
2556 	u_int	xsw_version;
2557 	u_int	xsw_dev1, xsw_dev2;
2558 	int	xsw_flags;
2559 	int	xsw_nblks;
2560 	int     xsw_used;
2561 };
2562 #endif
2563 
2564 static int
sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)2565 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2566 {
2567 	struct xswdev xs;
2568 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2569 	struct xswdev32 xs32;
2570 #endif
2571 #if defined(COMPAT_FREEBSD11)
2572 	struct xswdev11 xs11;
2573 #endif
2574 	int error;
2575 
2576 	if (arg2 != 1)			/* name length */
2577 		return (EINVAL);
2578 	error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2579 	if (error != 0)
2580 		return (error);
2581 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2582 	if (req->oldlen == sizeof(xs32)) {
2583 		xs32.xsw_version = XSWDEV_VERSION;
2584 		xs32.xsw_dev1 = xs.xsw_dev;
2585 		xs32.xsw_dev2 = xs.xsw_dev >> 32;
2586 		xs32.xsw_flags = xs.xsw_flags;
2587 		xs32.xsw_nblks = xs.xsw_nblks;
2588 		xs32.xsw_used = xs.xsw_used;
2589 		error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2590 		return (error);
2591 	}
2592 #endif
2593 #if defined(COMPAT_FREEBSD11)
2594 	if (req->oldlen == sizeof(xs11)) {
2595 		xs11.xsw_version = XSWDEV_VERSION_11;
2596 		xs11.xsw_dev = xs.xsw_dev; /* truncation */
2597 		xs11.xsw_flags = xs.xsw_flags;
2598 		xs11.xsw_nblks = xs.xsw_nblks;
2599 		xs11.xsw_used = xs.xsw_used;
2600 		error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2601 		return (error);
2602 	}
2603 #endif
2604 	error = SYSCTL_OUT(req, &xs, sizeof(xs));
2605 	return (error);
2606 }
2607 
2608 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2609     "Number of swap devices");
2610 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2611     sysctl_vm_swap_info,
2612     "Swap statistics by device");
2613 
2614 /*
2615  * Count the approximate swap usage in pages for a vmspace.  The
2616  * shadowed or not yet copied on write swap blocks are not accounted.
2617  * The map must be locked.
2618  */
2619 long
vmspace_swap_count(struct vmspace * vmspace)2620 vmspace_swap_count(struct vmspace *vmspace)
2621 {
2622 	vm_map_t map;
2623 	vm_map_entry_t cur;
2624 	vm_object_t object;
2625 	struct swblk *sb;
2626 	vm_pindex_t e, pi;
2627 	long count;
2628 	int i;
2629 
2630 	map = &vmspace->vm_map;
2631 	count = 0;
2632 
2633 	for (cur = map->header.next; cur != &map->header; cur = cur->next) {
2634 		if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2635 			continue;
2636 		object = cur->object.vm_object;
2637 		if (object == NULL || object->type != OBJT_SWAP)
2638 			continue;
2639 		VM_OBJECT_RLOCK(object);
2640 		if (object->type != OBJT_SWAP)
2641 			goto unlock;
2642 		pi = OFF_TO_IDX(cur->offset);
2643 		e = pi + OFF_TO_IDX(cur->end - cur->start);
2644 		for (;; pi = sb->p + SWAP_META_PAGES) {
2645 			sb = SWAP_PCTRIE_LOOKUP_GE(
2646 			    &object->un_pager.swp.swp_blks, pi);
2647 			if (sb == NULL || sb->p >= e)
2648 				break;
2649 			for (i = 0; i < SWAP_META_PAGES; i++) {
2650 				if (sb->p + i < e &&
2651 				    sb->d[i] != SWAPBLK_NONE)
2652 					count++;
2653 			}
2654 		}
2655 unlock:
2656 		VM_OBJECT_RUNLOCK(object);
2657 	}
2658 	return (count);
2659 }
2660 
2661 /*
2662  * GEOM backend
2663  *
2664  * Swapping onto disk devices.
2665  *
2666  */
2667 
2668 static g_orphan_t swapgeom_orphan;
2669 
2670 static struct g_class g_swap_class = {
2671 	.name = "SWAP",
2672 	.version = G_VERSION,
2673 	.orphan = swapgeom_orphan,
2674 };
2675 
2676 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2677 
2678 
2679 static void
swapgeom_close_ev(void * arg,int flags)2680 swapgeom_close_ev(void *arg, int flags)
2681 {
2682 	struct g_consumer *cp;
2683 
2684 	cp = arg;
2685 	g_access(cp, -1, -1, 0);
2686 	g_detach(cp);
2687 	g_destroy_consumer(cp);
2688 }
2689 
2690 /*
2691  * Add a reference to the g_consumer for an inflight transaction.
2692  */
2693 static void
swapgeom_acquire(struct g_consumer * cp)2694 swapgeom_acquire(struct g_consumer *cp)
2695 {
2696 
2697 	mtx_assert(&sw_dev_mtx, MA_OWNED);
2698 	cp->index++;
2699 }
2700 
2701 /*
2702  * Remove a reference from the g_consumer.  Post a close event if all
2703  * references go away, since the function might be called from the
2704  * biodone context.
2705  */
2706 static void
swapgeom_release(struct g_consumer * cp,struct swdevt * sp)2707 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2708 {
2709 
2710 	mtx_assert(&sw_dev_mtx, MA_OWNED);
2711 	cp->index--;
2712 	if (cp->index == 0) {
2713 		if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2714 			sp->sw_id = NULL;
2715 	}
2716 }
2717 
2718 static void
swapgeom_done(struct bio * bp2)2719 swapgeom_done(struct bio *bp2)
2720 {
2721 	struct swdevt *sp;
2722 	struct buf *bp;
2723 	struct g_consumer *cp;
2724 
2725 	bp = bp2->bio_caller2;
2726 	cp = bp2->bio_from;
2727 	bp->b_ioflags = bp2->bio_flags;
2728 	if (bp2->bio_error)
2729 		bp->b_ioflags |= BIO_ERROR;
2730 	bp->b_resid = bp->b_bcount - bp2->bio_completed;
2731 	bp->b_error = bp2->bio_error;
2732 	bufdone(bp);
2733 	sp = bp2->bio_caller1;
2734 	mtx_lock(&sw_dev_mtx);
2735 	swapgeom_release(cp, sp);
2736 	mtx_unlock(&sw_dev_mtx);
2737 	g_destroy_bio(bp2);
2738 }
2739 
2740 static void
swapgeom_strategy(struct buf * bp,struct swdevt * sp)2741 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2742 {
2743 	struct bio *bio;
2744 	struct g_consumer *cp;
2745 
2746 	mtx_lock(&sw_dev_mtx);
2747 	cp = sp->sw_id;
2748 	if (cp == NULL) {
2749 		mtx_unlock(&sw_dev_mtx);
2750 		bp->b_error = ENXIO;
2751 		bp->b_ioflags |= BIO_ERROR;
2752 		bufdone(bp);
2753 		return;
2754 	}
2755 	swapgeom_acquire(cp);
2756 	mtx_unlock(&sw_dev_mtx);
2757 	if (bp->b_iocmd == BIO_WRITE)
2758 		bio = g_new_bio();
2759 	else
2760 		bio = g_alloc_bio();
2761 	if (bio == NULL) {
2762 		mtx_lock(&sw_dev_mtx);
2763 		swapgeom_release(cp, sp);
2764 		mtx_unlock(&sw_dev_mtx);
2765 		bp->b_error = ENOMEM;
2766 		bp->b_ioflags |= BIO_ERROR;
2767 		bufdone(bp);
2768 		return;
2769 	}
2770 
2771 	bio->bio_caller1 = sp;
2772 	bio->bio_caller2 = bp;
2773 	bio->bio_cmd = bp->b_iocmd;
2774 	bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2775 	bio->bio_length = bp->b_bcount;
2776 	bio->bio_done = swapgeom_done;
2777 	if (!buf_mapped(bp)) {
2778 		bio->bio_ma = bp->b_pages;
2779 		bio->bio_data = unmapped_buf;
2780 		bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2781 		bio->bio_ma_n = bp->b_npages;
2782 		bio->bio_flags |= BIO_UNMAPPED;
2783 	} else {
2784 		bio->bio_data = bp->b_data;
2785 		bio->bio_ma = NULL;
2786 	}
2787 	g_io_request(bio, cp);
2788 	return;
2789 }
2790 
2791 static void
swapgeom_orphan(struct g_consumer * cp)2792 swapgeom_orphan(struct g_consumer *cp)
2793 {
2794 	struct swdevt *sp;
2795 	int destroy;
2796 
2797 	mtx_lock(&sw_dev_mtx);
2798 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2799 		if (sp->sw_id == cp) {
2800 			sp->sw_flags |= SW_CLOSING;
2801 			break;
2802 		}
2803 	}
2804 	/*
2805 	 * Drop reference we were created with. Do directly since we're in a
2806 	 * special context where we don't have to queue the call to
2807 	 * swapgeom_close_ev().
2808 	 */
2809 	cp->index--;
2810 	destroy = ((sp != NULL) && (cp->index == 0));
2811 	if (destroy)
2812 		sp->sw_id = NULL;
2813 	mtx_unlock(&sw_dev_mtx);
2814 	if (destroy)
2815 		swapgeom_close_ev(cp, 0);
2816 }
2817 
2818 static void
swapgeom_close(struct thread * td,struct swdevt * sw)2819 swapgeom_close(struct thread *td, struct swdevt *sw)
2820 {
2821 	struct g_consumer *cp;
2822 
2823 	mtx_lock(&sw_dev_mtx);
2824 	cp = sw->sw_id;
2825 	sw->sw_id = NULL;
2826 	mtx_unlock(&sw_dev_mtx);
2827 
2828 	/*
2829 	 * swapgeom_close() may be called from the biodone context,
2830 	 * where we cannot perform topology changes.  Delegate the
2831 	 * work to the events thread.
2832 	 */
2833 	if (cp != NULL)
2834 		g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2835 }
2836 
2837 static int
swapongeom_locked(struct cdev * dev,struct vnode * vp)2838 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2839 {
2840 	struct g_provider *pp;
2841 	struct g_consumer *cp;
2842 	static struct g_geom *gp;
2843 	struct swdevt *sp;
2844 	u_long nblks;
2845 	int error;
2846 
2847 	pp = g_dev_getprovider(dev);
2848 	if (pp == NULL)
2849 		return (ENODEV);
2850 	mtx_lock(&sw_dev_mtx);
2851 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2852 		cp = sp->sw_id;
2853 		if (cp != NULL && cp->provider == pp) {
2854 			mtx_unlock(&sw_dev_mtx);
2855 			return (EBUSY);
2856 		}
2857 	}
2858 	mtx_unlock(&sw_dev_mtx);
2859 	if (gp == NULL)
2860 		gp = g_new_geomf(&g_swap_class, "swap");
2861 	cp = g_new_consumer(gp);
2862 	cp->index = 1;	/* Number of active I/Os, plus one for being active. */
2863 	cp->flags |=  G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2864 	g_attach(cp, pp);
2865 	/*
2866 	 * XXX: Every time you think you can improve the margin for
2867 	 * footshooting, somebody depends on the ability to do so:
2868 	 * savecore(8) wants to write to our swapdev so we cannot
2869 	 * set an exclusive count :-(
2870 	 */
2871 	error = g_access(cp, 1, 1, 0);
2872 	if (error != 0) {
2873 		g_detach(cp);
2874 		g_destroy_consumer(cp);
2875 		return (error);
2876 	}
2877 	nblks = pp->mediasize / DEV_BSIZE;
2878 	swaponsomething(vp, cp, nblks, swapgeom_strategy,
2879 	    swapgeom_close, dev2udev(dev),
2880 	    (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
2881 	return (0);
2882 }
2883 
2884 static int
swapongeom(struct vnode * vp)2885 swapongeom(struct vnode *vp)
2886 {
2887 	int error;
2888 
2889 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2890 	if (vp->v_type != VCHR || (vp->v_iflag & VI_DOOMED) != 0) {
2891 		error = ENOENT;
2892 	} else {
2893 		g_topology_lock();
2894 		error = swapongeom_locked(vp->v_rdev, vp);
2895 		g_topology_unlock();
2896 	}
2897 	VOP_UNLOCK(vp, 0);
2898 	return (error);
2899 }
2900 
2901 /*
2902  * VNODE backend
2903  *
2904  * This is used mainly for network filesystem (read: probably only tested
2905  * with NFS) swapfiles.
2906  *
2907  */
2908 
2909 static void
swapdev_strategy(struct buf * bp,struct swdevt * sp)2910 swapdev_strategy(struct buf *bp, struct swdevt *sp)
2911 {
2912 	struct vnode *vp2;
2913 
2914 	bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
2915 
2916 	vp2 = sp->sw_id;
2917 	vhold(vp2);
2918 	if (bp->b_iocmd == BIO_WRITE) {
2919 		if (bp->b_bufobj)
2920 			bufobj_wdrop(bp->b_bufobj);
2921 		bufobj_wref(&vp2->v_bufobj);
2922 	}
2923 	if (bp->b_bufobj != &vp2->v_bufobj)
2924 		bp->b_bufobj = &vp2->v_bufobj;
2925 	bp->b_vp = vp2;
2926 	bp->b_iooffset = dbtob(bp->b_blkno);
2927 	bstrategy(bp);
2928 	return;
2929 }
2930 
2931 static void
swapdev_close(struct thread * td,struct swdevt * sp)2932 swapdev_close(struct thread *td, struct swdevt *sp)
2933 {
2934 
2935 	VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
2936 	vrele(sp->sw_vp);
2937 }
2938 
2939 
2940 static int
swaponvp(struct thread * td,struct vnode * vp,u_long nblks)2941 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
2942 {
2943 	struct swdevt *sp;
2944 	int error;
2945 
2946 	if (nblks == 0)
2947 		return (ENXIO);
2948 	mtx_lock(&sw_dev_mtx);
2949 	TAILQ_FOREACH(sp, &swtailq, sw_list) {
2950 		if (sp->sw_id == vp) {
2951 			mtx_unlock(&sw_dev_mtx);
2952 			return (EBUSY);
2953 		}
2954 	}
2955 	mtx_unlock(&sw_dev_mtx);
2956 
2957 	(void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2958 #ifdef MAC
2959 	error = mac_system_check_swapon(td->td_ucred, vp);
2960 	if (error == 0)
2961 #endif
2962 		error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
2963 	(void) VOP_UNLOCK(vp, 0);
2964 	if (error)
2965 		return (error);
2966 
2967 	swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
2968 	    NODEV, 0);
2969 	return (0);
2970 }
2971 
2972 static int
sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)2973 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
2974 {
2975 	int error, new, n;
2976 
2977 	new = nsw_wcount_async_max;
2978 	error = sysctl_handle_int(oidp, &new, 0, req);
2979 	if (error != 0 || req->newptr == NULL)
2980 		return (error);
2981 
2982 	if (new > nswbuf / 2 || new < 1)
2983 		return (EINVAL);
2984 
2985 	mtx_lock(&pbuf_mtx);
2986 	while (nsw_wcount_async_max != new) {
2987 		/*
2988 		 * Adjust difference.  If the current async count is too low,
2989 		 * we will need to sqeeze our update slowly in.  Sleep with a
2990 		 * higher priority than getpbuf() to finish faster.
2991 		 */
2992 		n = new - nsw_wcount_async_max;
2993 		if (nsw_wcount_async + n >= 0) {
2994 			nsw_wcount_async += n;
2995 			nsw_wcount_async_max += n;
2996 			wakeup(&nsw_wcount_async);
2997 		} else {
2998 			nsw_wcount_async_max -= nsw_wcount_async;
2999 			nsw_wcount_async = 0;
3000 			msleep(&nsw_wcount_async, &pbuf_mtx, PSWP,
3001 			    "swpsysctl", 0);
3002 		}
3003 	}
3004 	mtx_unlock(&pbuf_mtx);
3005 
3006 	return (0);
3007 }
3008