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