2 * SPDX-License-Identifier: BSD-4-Clause
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.
10 * This code is derived from software contributed to Berkeley by
11 * the Systems Programming Group of the University of Utah Computer
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
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.
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
45 * Radix Bitmap 'blists'.
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.
53 * - on the fly reallocation of swap during putpages. The new system
54 * does not try to keep previously allocated swap blocks for dirty
57 * - on the fly deallocation of swap
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
65 * from: Utah $Hdr: swap_pager.c 1.4 91/04/30$
67 * @(#)swap_pager.c 8.9 (Berkeley) 3/21/94
68 * @(#)vm_swap.c 8.5 (Berkeley) 2/17/94
71 #include <sys/cdefs.h>
72 __FBSDID("$FreeBSD$");
76 #include <sys/param.h>
78 #include <sys/blist.h>
82 #include <sys/disklabel.h>
83 #include <sys/eventhandler.h>
84 #include <sys/fcntl.h>
85 #include <sys/limits.h>
87 #include <sys/kernel.h>
88 #include <sys/mount.h>
89 #include <sys/namei.h>
90 #include <sys/malloc.h>
91 #include <sys/pctrie.h>
94 #include <sys/racct.h>
95 #include <sys/resource.h>
96 #include <sys/resourcevar.h>
97 #include <sys/rwlock.h>
99 #include <sys/sysctl.h>
100 #include <sys/sysproto.h>
101 #include <sys/systm.h>
103 #include <sys/unistd.h>
104 #include <sys/user.h>
105 #include <sys/vmmeter.h>
106 #include <sys/vnode.h>
108 #include <security/mac/mac_framework.h>
112 #include <vm/vm_map.h>
113 #include <vm/vm_kern.h>
114 #include <vm/vm_object.h>
115 #include <vm/vm_page.h>
116 #include <vm/vm_pager.h>
117 #include <vm/vm_pageout.h>
118 #include <vm/vm_param.h>
119 #include <vm/swap_pager.h>
120 #include <vm/vm_extern.h>
123 #include <geom/geom.h>
126 * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64.
127 * The 64-page limit is due to the radix code (kern/subr_blist.c).
129 #ifndef MAX_PAGEOUT_CLUSTER
130 #define MAX_PAGEOUT_CLUSTER 32
133 #if !defined(SWB_NPAGES)
134 #define SWB_NPAGES MAX_PAGEOUT_CLUSTER
137 #define SWAP_META_PAGES PCTRIE_COUNT
140 * A swblk structure maps each page index within a
141 * SWAP_META_PAGES-aligned and sized range to the address of an
142 * on-disk swap block (or SWAPBLK_NONE). The collection of these
143 * mappings for an entire vm object is implemented as a pc-trie.
147 daddr_t d[SWAP_META_PAGES];
150 static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data");
151 static struct mtx sw_dev_mtx;
152 static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
153 static struct swdevt *swdevhd; /* Allocate from here next */
154 static int nswapdev; /* Number of swap devices */
155 int swap_pager_avail;
156 static struct sx swdev_syscall_lock; /* serialize swap(on|off) */
158 static __exclusive_cache_line u_long swap_reserved;
159 static u_long swap_total;
160 static int sysctl_page_shift(SYSCTL_HANDLER_ARGS);
162 static SYSCTL_NODE(_vm_stats, OID_AUTO, swap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
165 SYSCTL_PROC(_vm, OID_AUTO, swap_reserved, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
166 &swap_reserved, 0, sysctl_page_shift, "A",
167 "Amount of swap storage needed to back all allocated anonymous memory.");
168 SYSCTL_PROC(_vm, OID_AUTO, swap_total, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
169 &swap_total, 0, sysctl_page_shift, "A",
170 "Total amount of available swap storage.");
172 int vm_overcommit __read_mostly = 0;
173 SYSCTL_INT(_vm, VM_OVERCOMMIT, overcommit, CTLFLAG_RW, &vm_overcommit, 0,
174 "Configure virtual memory overcommit behavior. See tuning(7) "
176 static unsigned long swzone;
177 SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
178 "Actual size of swap metadata zone");
179 static unsigned long swap_maxpages;
180 SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
181 "Maximum amount of swap supported");
183 static COUNTER_U64_DEFINE_EARLY(swap_free_deferred);
184 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_deferred,
185 CTLFLAG_RD, &swap_free_deferred,
186 "Number of pages that deferred freeing swap space");
188 static COUNTER_U64_DEFINE_EARLY(swap_free_completed);
189 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_completed,
190 CTLFLAG_RD, &swap_free_completed,
191 "Number of deferred frees completed");
194 sysctl_page_shift(SYSCTL_HANDLER_ARGS)
197 u_long value = *(u_long *)arg1;
199 newval = ((uint64_t)value) << PAGE_SHIFT;
200 return (sysctl_handle_64(oidp, &newval, 0, req));
204 swap_reserve_by_cred_rlimit(u_long pincr, struct ucred *cred, int oc)
209 uip = cred->cr_ruidinfo;
211 prev = atomic_fetchadd_long(&uip->ui_vmsize, pincr);
212 if ((oc & SWAP_RESERVE_RLIMIT_ON) != 0 &&
213 prev + pincr > lim_cur(curthread, RLIMIT_SWAP) &&
214 priv_check(curthread, PRIV_VM_SWAP_NORLIMIT) != 0) {
215 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pincr);
216 KASSERT(prev >= pincr,
217 ("negative vmsize for uid %d\n", uip->ui_uid));
224 swap_release_by_cred_rlimit(u_long pdecr, struct ucred *cred)
231 uip = cred->cr_ruidinfo;
234 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pdecr);
235 KASSERT(prev >= pdecr,
236 ("negative vmsize for uid %d\n", uip->ui_uid));
238 atomic_subtract_long(&uip->ui_vmsize, pdecr);
243 swap_reserve_force_rlimit(u_long pincr, struct ucred *cred)
247 uip = cred->cr_ruidinfo;
248 atomic_add_long(&uip->ui_vmsize, pincr);
252 swap_reserve(vm_ooffset_t incr)
255 return (swap_reserve_by_cred(incr, curthread->td_ucred));
259 swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
261 u_long r, s, prev, pincr;
267 static struct timeval lastfail;
269 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK",
270 __func__, (uintmax_t)incr));
273 if (RACCT_ENABLED()) {
275 error = racct_add(curproc, RACCT_SWAP, incr);
276 PROC_UNLOCK(curproc);
283 prev = atomic_fetchadd_long(&swap_reserved, pincr);
286 oc = atomic_load_int(&vm_overcommit);
287 if (r > s && (oc & SWAP_RESERVE_ALLOW_NONWIRED) != 0) {
288 s += vm_cnt.v_page_count - vm_cnt.v_free_reserved -
291 if ((oc & SWAP_RESERVE_FORCE_ON) != 0 && r > s &&
292 priv_check(curthread, PRIV_VM_SWAP_NOQUOTA) != 0) {
293 prev = atomic_fetchadd_long(&swap_reserved, -pincr);
294 KASSERT(prev >= pincr,
295 ("swap_reserved < incr on overcommit fail"));
299 if (!swap_reserve_by_cred_rlimit(pincr, cred, oc)) {
300 prev = atomic_fetchadd_long(&swap_reserved, -pincr);
301 KASSERT(prev >= pincr,
302 ("swap_reserved < incr on overcommit fail"));
309 if (ppsratecheck(&lastfail, &curfail, 1)) {
310 printf("uid %d, pid %d: swap reservation "
311 "for %jd bytes failed\n",
312 cred->cr_ruidinfo->ui_uid, curproc->p_pid, incr);
315 if (RACCT_ENABLED()) {
317 racct_sub(curproc, RACCT_SWAP, incr);
318 PROC_UNLOCK(curproc);
326 swap_reserve_force(vm_ooffset_t incr)
330 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK",
331 __func__, (uintmax_t)incr));
334 if (RACCT_ENABLED()) {
336 racct_add_force(curproc, RACCT_SWAP, incr);
337 PROC_UNLOCK(curproc);
341 atomic_add_long(&swap_reserved, pincr);
342 swap_reserve_force_rlimit(pincr, curthread->td_ucred);
346 swap_release(vm_ooffset_t decr)
351 cred = curproc->p_ucred;
352 swap_release_by_cred(decr, cred);
353 PROC_UNLOCK(curproc);
357 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
364 KASSERT((decr & PAGE_MASK) == 0, ("%s: decr: %ju & PAGE_MASK",
365 __func__, (uintmax_t)decr));
369 prev = atomic_fetchadd_long(&swap_reserved, -pdecr);
370 KASSERT(prev >= pdecr, ("swap_reserved < decr"));
372 atomic_subtract_long(&swap_reserved, pdecr);
375 swap_release_by_cred_rlimit(pdecr, cred);
378 racct_sub_cred(cred, RACCT_SWAP, decr);
382 static int swap_pager_full = 2; /* swap space exhaustion (task killing) */
383 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
384 static struct mtx swbuf_mtx; /* to sync nsw_wcount_async */
385 static int nsw_wcount_async; /* limit async write buffers */
386 static int nsw_wcount_async_max;/* assigned maximum */
387 static int nsw_cluster_max; /* maximum VOP I/O allowed */
389 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
390 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
391 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
392 "Maximum running async swap ops");
393 static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS);
394 SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD |
395 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A",
396 "Swap Fragmentation Info");
398 static struct sx sw_alloc_sx;
401 * "named" and "unnamed" anon region objects. Try to reduce the overhead
402 * of searching a named list by hashing it just a little.
407 #define NOBJLIST(handle) \
408 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
410 static struct pagerlst swap_pager_object_list[NOBJLISTS];
411 static uma_zone_t swwbuf_zone;
412 static uma_zone_t swrbuf_zone;
413 static uma_zone_t swblk_zone;
414 static uma_zone_t swpctrie_zone;
417 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
418 * calls hooked from other parts of the VM system and do not appear here.
419 * (see vm/swap_pager.h).
422 swap_pager_alloc(void *handle, vm_ooffset_t size,
423 vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
424 static void swap_pager_dealloc(vm_object_t object);
425 static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
427 static int swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
428 int *, pgo_getpages_iodone_t, void *);
429 static void swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
431 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
432 static void swap_pager_init(void);
433 static void swap_pager_unswapped(vm_page_t);
434 static void swap_pager_swapoff(struct swdevt *sp);
435 static void swap_pager_update_writecount(vm_object_t object,
436 vm_offset_t start, vm_offset_t end);
437 static void swap_pager_release_writecount(vm_object_t object,
438 vm_offset_t start, vm_offset_t end);
439 static void swap_pager_freespace_pgo(vm_object_t object, vm_pindex_t start,
442 const struct pagerops swappagerops = {
443 .pgo_kvme_type = KVME_TYPE_SWAP,
444 .pgo_init = swap_pager_init, /* early system initialization of pager */
445 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */
446 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
447 .pgo_getpages = swap_pager_getpages, /* pagein */
448 .pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
449 .pgo_putpages = swap_pager_putpages, /* pageout */
450 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */
451 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
452 .pgo_update_writecount = swap_pager_update_writecount,
453 .pgo_release_writecount = swap_pager_release_writecount,
454 .pgo_freespace = swap_pager_freespace_pgo,
458 * swap_*() routines are externally accessible. swp_*() routines are
461 static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
462 static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
464 SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
465 "Maximum size of a swap block in pages");
467 static void swp_sizecheck(void);
468 static void swp_pager_async_iodone(struct buf *bp);
469 static bool swp_pager_swblk_empty(struct swblk *sb, int start, int limit);
470 static void swp_pager_free_empty_swblk(vm_object_t, struct swblk *sb);
471 static int swapongeom(struct vnode *);
472 static int swaponvp(struct thread *, struct vnode *, u_long);
473 static int swapoff_one(struct swdevt *sp, struct ucred *cred,
477 * Swap bitmap functions
479 static void swp_pager_freeswapspace(daddr_t blk, daddr_t npages);
480 static daddr_t swp_pager_getswapspace(int *npages);
485 static daddr_t swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
486 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t,
488 static void swp_pager_meta_transfer(vm_object_t src, vm_object_t dst,
489 vm_pindex_t pindex, vm_pindex_t count, vm_size_t *freed);
490 static void swp_pager_meta_free_all(vm_object_t);
491 static daddr_t swp_pager_meta_lookup(vm_object_t, vm_pindex_t);
494 swp_pager_init_freerange(daddr_t *start, daddr_t *num)
497 *start = SWAPBLK_NONE;
502 swp_pager_update_freerange(daddr_t *start, daddr_t *num, daddr_t addr)
505 if (*start + *num == addr) {
508 swp_pager_freeswapspace(*start, *num);
515 swblk_trie_alloc(struct pctrie *ptree)
518 return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
519 M_USE_RESERVE : 0)));
523 swblk_trie_free(struct pctrie *ptree, void *node)
526 uma_zfree(swpctrie_zone, node);
529 PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
532 * SWP_SIZECHECK() - update swap_pager_full indication
534 * update the swap_pager_almost_full indication and warn when we are
535 * about to run out of swap space, using lowat/hiwat hysteresis.
537 * Clear swap_pager_full ( task killing ) indication when lowat is met.
539 * No restrictions on call
540 * This routine may not block.
546 if (swap_pager_avail < nswap_lowat) {
547 if (swap_pager_almost_full == 0) {
548 printf("swap_pager: out of swap space\n");
549 swap_pager_almost_full = 1;
553 if (swap_pager_avail > nswap_hiwat)
554 swap_pager_almost_full = 0;
559 * SWAP_PAGER_INIT() - initialize the swap pager!
561 * Expected to be started from system init. NOTE: This code is run
562 * before much else so be careful what you depend on. Most of the VM
563 * system has yet to be initialized at this point.
566 swap_pager_init(void)
569 * Initialize object lists
573 for (i = 0; i < NOBJLISTS; ++i)
574 TAILQ_INIT(&swap_pager_object_list[i]);
575 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
576 sx_init(&sw_alloc_sx, "swspsx");
577 sx_init(&swdev_syscall_lock, "swsysc");
581 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
583 * Expected to be started from pageout process once, prior to entering
587 swap_pager_swap_init(void)
592 * Number of in-transit swap bp operations. Don't
593 * exhaust the pbufs completely. Make sure we
594 * initialize workable values (0 will work for hysteresis
595 * but it isn't very efficient).
597 * The nsw_cluster_max is constrained by the bp->b_pages[]
598 * array, which has maxphys / PAGE_SIZE entries, and our locally
599 * defined MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
600 * constrained by the swap device interleave stripe size.
602 * Currently we hardwire nsw_wcount_async to 4. This limit is
603 * designed to prevent other I/O from having high latencies due to
604 * our pageout I/O. The value 4 works well for one or two active swap
605 * devices but is probably a little low if you have more. Even so,
606 * a higher value would probably generate only a limited improvement
607 * with three or four active swap devices since the system does not
608 * typically have to pageout at extreme bandwidths. We will want
609 * at least 2 per swap devices, and 4 is a pretty good value if you
610 * have one NFS swap device due to the command/ack latency over NFS.
611 * So it all works out pretty well.
613 nsw_cluster_max = min(maxphys / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
615 nsw_wcount_async = 4;
616 nsw_wcount_async_max = nsw_wcount_async;
617 mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
619 swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
620 swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
623 * Initialize our zone, taking the user's requested size or
624 * estimating the number we need based on the number of pages
627 n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
628 vm_cnt.v_page_count / 2;
629 swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
630 pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0);
631 swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
632 NULL, NULL, _Alignof(struct swblk) - 1, 0);
635 if (uma_zone_reserve_kva(swblk_zone, n))
638 * if the allocation failed, try a zone two thirds the
639 * size of the previous attempt.
645 * Often uma_zone_reserve_kva() cannot reserve exactly the
646 * requested size. Account for the difference when
647 * calculating swap_maxpages.
649 n = uma_zone_get_max(swblk_zone);
652 printf("Swap blk zone entries changed from %lu to %lu.\n",
654 /* absolute maximum we can handle assuming 100% efficiency */
655 swap_maxpages = n * SWAP_META_PAGES;
656 swzone = n * sizeof(struct swblk);
657 if (!uma_zone_reserve_kva(swpctrie_zone, n))
658 printf("Cannot reserve swap pctrie zone, "
659 "reduce kern.maxswzone.\n");
663 swap_pager_init_object(vm_object_t object, void *handle, struct ucred *cred,
664 vm_ooffset_t size, vm_ooffset_t offset)
667 if (!swap_reserve_by_cred(size, cred))
672 object->un_pager.swp.writemappings = 0;
673 object->handle = handle;
676 object->charge = size;
682 swap_pager_alloc_init(objtype_t otype, void *handle, struct ucred *cred,
683 vm_ooffset_t size, vm_ooffset_t offset)
688 * The un_pager.swp.swp_blks trie is initialized by
689 * vm_object_allocate() to ensure the correct order of
690 * visibility to other threads.
692 object = vm_object_allocate(otype, OFF_TO_IDX(offset +
695 if (!swap_pager_init_object(object, handle, cred, size, offset)) {
696 vm_object_deallocate(object);
703 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
704 * its metadata structures.
706 * This routine is called from the mmap and fork code to create a new
709 * This routine must ensure that no live duplicate is created for
710 * the named object request, which is protected against by
711 * holding the sw_alloc_sx lock in case handle != NULL.
714 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
715 vm_ooffset_t offset, struct ucred *cred)
719 if (handle != NULL) {
721 * Reference existing named region or allocate new one. There
722 * should not be a race here against swp_pager_meta_build()
723 * as called from vm_page_remove() in regards to the lookup
726 sx_xlock(&sw_alloc_sx);
727 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
728 if (object == NULL) {
729 object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
731 if (object != NULL) {
732 TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
733 object, pager_object_list);
736 sx_xunlock(&sw_alloc_sx);
738 object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
745 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
747 * The swap backing for the object is destroyed. The code is
748 * designed such that we can reinstantiate it later, but this
749 * routine is typically called only when the entire object is
750 * about to be destroyed.
752 * The object must be locked.
755 swap_pager_dealloc(vm_object_t object)
758 VM_OBJECT_ASSERT_WLOCKED(object);
759 KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
762 * Remove from list right away so lookups will fail if we block for
763 * pageout completion.
765 if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
766 VM_OBJECT_WUNLOCK(object);
767 sx_xlock(&sw_alloc_sx);
768 TAILQ_REMOVE(NOBJLIST(object->handle), object,
770 sx_xunlock(&sw_alloc_sx);
771 VM_OBJECT_WLOCK(object);
774 vm_object_pip_wait(object, "swpdea");
777 * Free all remaining metadata. We only bother to free it from
778 * the swap meta data. We do not attempt to free swapblk's still
779 * associated with vm_page_t's for this object. We do not care
780 * if paging is still in progress on some objects.
782 swp_pager_meta_free_all(object);
783 object->handle = NULL;
784 object->type = OBJT_DEAD;
785 vm_object_clear_flag(object, OBJ_SWAP);
788 /************************************************************************
789 * SWAP PAGER BITMAP ROUTINES *
790 ************************************************************************/
793 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
795 * Allocate swap for up to the requested number of pages. The
796 * starting swap block number (a page index) is returned or
797 * SWAPBLK_NONE if the allocation failed.
799 * Also has the side effect of advising that somebody made a mistake
800 * when they configured swap and didn't configure enough.
802 * This routine may not sleep.
804 * We allocate in round-robin fashion from the configured devices.
807 swp_pager_getswapspace(int *io_npages)
813 KASSERT(*io_npages >= 1,
814 ("%s: npages not positive", __func__));
817 npages = imin(BLIST_MAX_ALLOC, mpages);
818 mtx_lock(&sw_dev_mtx);
820 while (!TAILQ_EMPTY(&swtailq)) {
822 sp = TAILQ_FIRST(&swtailq);
823 if ((sp->sw_flags & SW_CLOSING) == 0)
824 blk = blist_alloc(sp->sw_blist, &npages, mpages);
825 if (blk != SWAPBLK_NONE)
827 sp = TAILQ_NEXT(sp, sw_list);
835 if (blk != SWAPBLK_NONE) {
838 sp->sw_used += npages;
839 swap_pager_avail -= npages;
841 swdevhd = TAILQ_NEXT(sp, sw_list);
843 if (swap_pager_full != 2) {
844 printf("swp_pager_getswapspace(%d): failed\n",
847 swap_pager_almost_full = 1;
851 mtx_unlock(&sw_dev_mtx);
856 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
859 return (blk >= sp->sw_first && blk < sp->sw_end);
863 swp_pager_strategy(struct buf *bp)
867 mtx_lock(&sw_dev_mtx);
868 TAILQ_FOREACH(sp, &swtailq, sw_list) {
869 if (swp_pager_isondev(bp->b_blkno, sp)) {
870 mtx_unlock(&sw_dev_mtx);
871 if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
872 unmapped_buf_allowed) {
873 bp->b_data = unmapped_buf;
876 pmap_qenter((vm_offset_t)bp->b_data,
877 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
879 sp->sw_strategy(bp, sp);
883 panic("Swapdev not found");
887 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
889 * This routine returns the specified swap blocks back to the bitmap.
891 * This routine may not sleep.
894 swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
900 mtx_lock(&sw_dev_mtx);
901 TAILQ_FOREACH(sp, &swtailq, sw_list) {
902 if (swp_pager_isondev(blk, sp)) {
903 sp->sw_used -= npages;
905 * If we are attempting to stop swapping on
906 * this device, we don't want to mark any
907 * blocks free lest they be reused.
909 if ((sp->sw_flags & SW_CLOSING) == 0) {
910 blist_free(sp->sw_blist, blk - sp->sw_first,
912 swap_pager_avail += npages;
915 mtx_unlock(&sw_dev_mtx);
919 panic("Swapdev not found");
923 * SYSCTL_SWAP_FRAGMENTATION() - produce raw swap space stats
926 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
933 error = sysctl_wire_old_buffer(req, 0);
936 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
937 mtx_lock(&sw_dev_mtx);
938 TAILQ_FOREACH(sp, &swtailq, sw_list) {
939 if (vn_isdisk(sp->sw_vp))
940 devname = devtoname(sp->sw_vp->v_rdev);
943 sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
944 blist_stats(sp->sw_blist, &sbuf);
946 mtx_unlock(&sw_dev_mtx);
947 error = sbuf_finish(&sbuf);
953 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
954 * range within an object.
956 * This routine removes swapblk assignments from swap metadata.
958 * The external callers of this routine typically have already destroyed
959 * or renamed vm_page_t's associated with this range in the object so
962 * The object must be locked.
965 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size,
968 MPASS((object->flags & OBJ_SWAP) != 0);
970 swp_pager_meta_free(object, start, size, freed);
974 swap_pager_freespace_pgo(vm_object_t object, vm_pindex_t start, vm_size_t size)
976 MPASS((object->flags & OBJ_SWAP) != 0);
978 swp_pager_meta_free(object, start, size, NULL);
982 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
984 * Assigns swap blocks to the specified range within the object. The
985 * swap blocks are not zeroed. Any previous swap assignment is destroyed.
987 * Returns 0 on success, -1 on failure.
990 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_pindex_t size)
992 daddr_t addr, blk, n_free, s_free;
996 swp_pager_init_freerange(&s_free, &n_free);
997 VM_OBJECT_WLOCK(object);
998 for (i = 0; i < size; i += n) {
999 n = MIN(size - i, INT_MAX);
1000 blk = swp_pager_getswapspace(&n);
1001 if (blk == SWAPBLK_NONE) {
1002 swp_pager_meta_free(object, start, i, NULL);
1003 VM_OBJECT_WUNLOCK(object);
1006 for (j = 0; j < n; ++j) {
1007 addr = swp_pager_meta_build(object,
1008 start + i + j, blk + j);
1009 if (addr != SWAPBLK_NONE)
1010 swp_pager_update_freerange(&s_free, &n_free,
1014 swp_pager_freeswapspace(s_free, n_free);
1015 VM_OBJECT_WUNLOCK(object);
1020 swp_pager_xfer_source(vm_object_t srcobject, vm_object_t dstobject,
1021 vm_pindex_t pindex, daddr_t addr)
1025 KASSERT((srcobject->flags & OBJ_SWAP) != 0,
1026 ("%s: Srcobject not swappable", __func__));
1027 if ((dstobject->flags & OBJ_SWAP) != 0 &&
1028 swp_pager_meta_lookup(dstobject, pindex) != SWAPBLK_NONE) {
1029 /* Caller should destroy the source block. */
1034 * Destination has no swapblk and is not resident, transfer source.
1035 * swp_pager_meta_build() can sleep.
1037 VM_OBJECT_WUNLOCK(srcobject);
1038 dstaddr = swp_pager_meta_build(dstobject, pindex, addr);
1039 KASSERT(dstaddr == SWAPBLK_NONE,
1040 ("Unexpected destination swapblk"));
1041 VM_OBJECT_WLOCK(srcobject);
1047 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
1048 * and destroy the source.
1050 * Copy any valid swapblks from the source to the destination. In
1051 * cases where both the source and destination have a valid swapblk,
1052 * we keep the destination's.
1054 * This routine is allowed to sleep. It may sleep allocating metadata
1055 * indirectly through swp_pager_meta_build().
1057 * The source object contains no vm_page_t's (which is just as well)
1059 * The source object is of type OBJT_SWAP.
1061 * The source and destination objects must be locked.
1062 * Both object locks may temporarily be released.
1065 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
1066 vm_pindex_t offset, int destroysource)
1069 VM_OBJECT_ASSERT_WLOCKED(srcobject);
1070 VM_OBJECT_ASSERT_WLOCKED(dstobject);
1073 * If destroysource is set, we remove the source object from the
1074 * swap_pager internal queue now.
1076 if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
1077 srcobject->handle != NULL) {
1078 VM_OBJECT_WUNLOCK(srcobject);
1079 VM_OBJECT_WUNLOCK(dstobject);
1080 sx_xlock(&sw_alloc_sx);
1081 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1083 sx_xunlock(&sw_alloc_sx);
1084 VM_OBJECT_WLOCK(dstobject);
1085 VM_OBJECT_WLOCK(srcobject);
1089 * Transfer source to destination.
1091 swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size,
1095 * Free left over swap blocks in source.
1097 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
1098 * double-remove the object from the swap queues.
1100 if (destroysource) {
1101 swp_pager_meta_free_all(srcobject);
1103 * Reverting the type is not necessary, the caller is going
1104 * to destroy srcobject directly, but I'm doing it here
1105 * for consistency since we've removed the object from its
1108 srcobject->type = OBJT_DEFAULT;
1109 vm_object_clear_flag(srcobject, OBJ_SWAP);
1114 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
1115 * the requested page.
1117 * We determine whether good backing store exists for the requested
1118 * page and return TRUE if it does, FALSE if it doesn't.
1120 * If TRUE, we also try to determine how much valid, contiguous backing
1121 * store exists before and after the requested page.
1124 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1130 VM_OBJECT_ASSERT_LOCKED(object);
1131 KASSERT((object->flags & OBJ_SWAP) != 0,
1132 ("%s: object not swappable", __func__));
1135 * do we have good backing store at the requested index ?
1137 blk0 = swp_pager_meta_lookup(object, pindex);
1138 if (blk0 == SWAPBLK_NONE) {
1147 * find backwards-looking contiguous good backing store
1149 if (before != NULL) {
1150 for (i = 1; i < SWB_NPAGES; i++) {
1153 blk = swp_pager_meta_lookup(object, pindex - i);
1154 if (blk != blk0 - i)
1161 * find forward-looking contiguous good backing store
1163 if (after != NULL) {
1164 for (i = 1; i < SWB_NPAGES; i++) {
1165 blk = swp_pager_meta_lookup(object, pindex + i);
1166 if (blk != blk0 + i)
1175 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1177 * This removes any associated swap backing store, whether valid or
1178 * not, from the page.
1180 * This routine is typically called when a page is made dirty, at
1181 * which point any associated swap can be freed. MADV_FREE also
1182 * calls us in a special-case situation
1184 * NOTE!!! If the page is clean and the swap was valid, the caller
1185 * should make the page dirty before calling this routine. This routine
1186 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1189 * This routine may not sleep.
1191 * The object containing the page may be locked.
1194 swap_pager_unswapped(vm_page_t m)
1200 * Handle enqueing deferred frees first. If we do not have the
1201 * object lock we wait for the page daemon to clear the space.
1204 if (!VM_OBJECT_WOWNED(obj)) {
1205 VM_PAGE_OBJECT_BUSY_ASSERT(m);
1207 * The caller is responsible for synchronization but we
1208 * will harmlessly handle races. This is typically provided
1209 * by only calling unswapped() when a page transitions from
1212 if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1214 vm_page_aflag_set(m, PGA_SWAP_FREE);
1215 counter_u64_add(swap_free_deferred, 1);
1219 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1220 counter_u64_add(swap_free_completed, 1);
1221 vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
1224 * The meta data only exists if the object is OBJT_SWAP
1225 * and even then might not be allocated yet.
1227 KASSERT((m->object->flags & OBJ_SWAP) != 0,
1228 ("Free object not swappable"));
1230 sb = SWAP_PCTRIE_LOOKUP(&m->object->un_pager.swp.swp_blks,
1231 rounddown(m->pindex, SWAP_META_PAGES));
1234 if (sb->d[m->pindex % SWAP_META_PAGES] == SWAPBLK_NONE)
1236 swp_pager_freeswapspace(sb->d[m->pindex % SWAP_META_PAGES], 1);
1237 sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
1238 swp_pager_free_empty_swblk(m->object, sb);
1242 * swap_pager_getpages() - bring pages in from swap
1244 * Attempt to page in the pages in array "ma" of length "count". The
1245 * caller may optionally specify that additional pages preceding and
1246 * succeeding the specified range be paged in. The number of such pages
1247 * is returned in the "rbehind" and "rahead" parameters, and they will
1248 * be in the inactive queue upon return.
1250 * The pages in "ma" must be busied and will remain busied upon return.
1253 swap_pager_getpages_locked(vm_object_t object, vm_page_t *ma, int count,
1254 int *rbehind, int *rahead)
1257 vm_page_t bm, mpred, msucc, p;
1260 int i, maxahead, maxbehind, reqcount;
1262 VM_OBJECT_ASSERT_WLOCKED(object);
1265 KASSERT((object->flags & OBJ_SWAP) != 0,
1266 ("%s: object not swappable", __func__));
1267 if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead)) {
1268 VM_OBJECT_WUNLOCK(object);
1269 return (VM_PAGER_FAIL);
1272 KASSERT(reqcount - 1 <= maxahead,
1273 ("page count %d extends beyond swap block", reqcount));
1276 * Do not transfer any pages other than those that are xbusied
1277 * when running during a split or collapse operation. This
1278 * prevents clustering from re-creating pages which are being
1279 * moved into another object.
1281 if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
1282 maxahead = reqcount - 1;
1287 * Clip the readahead and readbehind ranges to exclude resident pages.
1289 if (rahead != NULL) {
1290 *rahead = imin(*rahead, maxahead - (reqcount - 1));
1291 pindex = ma[reqcount - 1]->pindex;
1292 msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1293 if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1294 *rahead = msucc->pindex - pindex - 1;
1296 if (rbehind != NULL) {
1297 *rbehind = imin(*rbehind, maxbehind);
1298 pindex = ma[0]->pindex;
1299 mpred = TAILQ_PREV(ma[0], pglist, listq);
1300 if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1301 *rbehind = pindex - mpred->pindex - 1;
1305 for (i = 0; i < count; i++)
1306 ma[i]->oflags |= VPO_SWAPINPROG;
1309 * Allocate readahead and readbehind pages.
1311 if (rbehind != NULL) {
1312 for (i = 1; i <= *rbehind; i++) {
1313 p = vm_page_alloc(object, ma[0]->pindex - i,
1317 p->oflags |= VPO_SWAPINPROG;
1322 if (rahead != NULL) {
1323 for (i = 0; i < *rahead; i++) {
1324 p = vm_page_alloc(object,
1325 ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1328 p->oflags |= VPO_SWAPINPROG;
1332 if (rbehind != NULL)
1337 vm_object_pip_add(object, count);
1339 pindex = bm->pindex;
1340 blk = swp_pager_meta_lookup(object, pindex);
1341 KASSERT(blk != SWAPBLK_NONE,
1342 ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1344 VM_OBJECT_WUNLOCK(object);
1345 bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1346 MPASS((bp->b_flags & B_MAXPHYS) != 0);
1347 /* Pages cannot leave the object while busy. */
1348 for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1349 MPASS(p->pindex == bm->pindex + i);
1353 bp->b_flags |= B_PAGING;
1354 bp->b_iocmd = BIO_READ;
1355 bp->b_iodone = swp_pager_async_iodone;
1356 bp->b_rcred = crhold(thread0.td_ucred);
1357 bp->b_wcred = crhold(thread0.td_ucred);
1359 bp->b_bcount = PAGE_SIZE * count;
1360 bp->b_bufsize = PAGE_SIZE * count;
1361 bp->b_npages = count;
1362 bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1363 bp->b_pgafter = rahead != NULL ? *rahead : 0;
1365 VM_CNT_INC(v_swapin);
1366 VM_CNT_ADD(v_swappgsin, count);
1369 * perform the I/O. NOTE!!! bp cannot be considered valid after
1370 * this point because we automatically release it on completion.
1371 * Instead, we look at the one page we are interested in which we
1372 * still hold a lock on even through the I/O completion.
1374 * The other pages in our ma[] array are also released on completion,
1375 * so we cannot assume they are valid anymore either.
1377 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1380 swp_pager_strategy(bp);
1383 * Wait for the pages we want to complete. VPO_SWAPINPROG is always
1384 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1385 * is set in the metadata for each page in the request.
1387 VM_OBJECT_WLOCK(object);
1388 /* This could be implemented more efficiently with aflags */
1389 while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
1390 ma[0]->oflags |= VPO_SWAPSLEEP;
1391 VM_CNT_INC(v_intrans);
1392 if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1393 "swread", hz * 20)) {
1395 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1396 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1399 VM_OBJECT_WUNLOCK(object);
1402 * If we had an unrecoverable read error pages will not be valid.
1404 for (i = 0; i < reqcount; i++)
1405 if (ma[i]->valid != VM_PAGE_BITS_ALL)
1406 return (VM_PAGER_ERROR);
1408 return (VM_PAGER_OK);
1411 * A final note: in a low swap situation, we cannot deallocate swap
1412 * and mark a page dirty here because the caller is likely to mark
1413 * the page clean when we return, causing the page to possibly revert
1414 * to all-zero's later.
1419 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count,
1420 int *rbehind, int *rahead)
1423 VM_OBJECT_WLOCK(object);
1424 return (swap_pager_getpages_locked(object, ma, count, rbehind, rahead));
1428 * swap_pager_getpages_async():
1430 * Right now this is emulation of asynchronous operation on top of
1431 * swap_pager_getpages().
1434 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1435 int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1439 r = swap_pager_getpages(object, ma, count, rbehind, rahead);
1444 case VM_PAGER_ERROR:
1451 panic("unhandled swap_pager_getpages() error %d", r);
1453 (iodone)(arg, ma, count, error);
1459 * swap_pager_putpages:
1461 * Assign swap (if necessary) and initiate I/O on the specified pages.
1463 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1464 * are automatically converted to SWAP objects.
1466 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1467 * vm_page reservation system coupled with properly written VFS devices
1468 * should ensure that no low-memory deadlock occurs. This is an area
1471 * The parent has N vm_object_pip_add() references prior to
1472 * calling us and will remove references for rtvals[] that are
1473 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1476 * The parent has soft-busy'd the pages it passes us and will unbusy
1477 * those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
1478 * We need to unbusy the rest on I/O completion.
1481 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1482 int flags, int *rtvals)
1485 daddr_t addr, blk, n_free, s_free;
1490 KASSERT(count == 0 || ma[0]->object == object,
1491 ("%s: object mismatch %p/%p",
1492 __func__, object, ma[0]->object));
1497 * Turn object into OBJT_SWAP. Force sync if not a pageout process.
1499 if ((object->flags & OBJ_SWAP) == 0) {
1500 addr = swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1501 KASSERT(addr == SWAPBLK_NONE,
1502 ("unexpected object swap block"));
1504 VM_OBJECT_WUNLOCK(object);
1505 async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
1506 swp_pager_init_freerange(&s_free, &n_free);
1511 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1512 * The page is left dirty until the pageout operation completes
1515 for (i = 0; i < count; i += n) {
1516 /* Maximum I/O size is limited by maximum swap block size. */
1517 n = min(count - i, nsw_cluster_max);
1520 mtx_lock(&swbuf_mtx);
1521 while (nsw_wcount_async == 0)
1522 msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1525 mtx_unlock(&swbuf_mtx);
1528 /* Get a block of swap of size up to size n. */
1529 blk = swp_pager_getswapspace(&n);
1530 if (blk == SWAPBLK_NONE) {
1531 mtx_lock(&swbuf_mtx);
1532 if (++nsw_wcount_async == 1)
1533 wakeup(&nsw_wcount_async);
1534 mtx_unlock(&swbuf_mtx);
1535 for (j = 0; j < n; ++j)
1536 rtvals[i + j] = VM_PAGER_FAIL;
1539 VM_OBJECT_WLOCK(object);
1540 for (j = 0; j < n; ++j) {
1542 vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1543 addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1545 if (addr != SWAPBLK_NONE)
1546 swp_pager_update_freerange(&s_free, &n_free,
1548 MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1549 mreq->oflags |= VPO_SWAPINPROG;
1551 VM_OBJECT_WUNLOCK(object);
1553 bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1554 MPASS((bp->b_flags & B_MAXPHYS) != 0);
1556 bp->b_flags |= B_ASYNC;
1557 bp->b_flags |= B_PAGING;
1558 bp->b_iocmd = BIO_WRITE;
1560 bp->b_rcred = crhold(thread0.td_ucred);
1561 bp->b_wcred = crhold(thread0.td_ucred);
1562 bp->b_bcount = PAGE_SIZE * n;
1563 bp->b_bufsize = PAGE_SIZE * n;
1565 for (j = 0; j < n; j++)
1566 bp->b_pages[j] = ma[i + j];
1570 * Must set dirty range for NFS to work.
1573 bp->b_dirtyend = bp->b_bcount;
1575 VM_CNT_INC(v_swapout);
1576 VM_CNT_ADD(v_swappgsout, bp->b_npages);
1579 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1580 * can call the async completion routine at the end of a
1581 * synchronous I/O operation. Otherwise, our caller would
1582 * perform duplicate unbusy and wakeup operations on the page
1583 * and object, respectively.
1585 for (j = 0; j < n; j++)
1586 rtvals[i + j] = VM_PAGER_PEND;
1591 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1594 bp->b_iodone = swp_pager_async_iodone;
1596 swp_pager_strategy(bp);
1603 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1605 bp->b_iodone = bdone;
1606 swp_pager_strategy(bp);
1609 * Wait for the sync I/O to complete.
1611 bwait(bp, PVM, "swwrt");
1614 * Now that we are through with the bp, we can call the
1615 * normal async completion, which frees everything up.
1617 swp_pager_async_iodone(bp);
1619 swp_pager_freeswapspace(s_free, n_free);
1620 VM_OBJECT_WLOCK(object);
1624 * swp_pager_async_iodone:
1626 * Completion routine for asynchronous reads and writes from/to swap.
1627 * Also called manually by synchronous code to finish up a bp.
1629 * This routine may not sleep.
1632 swp_pager_async_iodone(struct buf *bp)
1635 vm_object_t object = NULL;
1638 * Report error - unless we ran out of memory, in which case
1639 * we've already logged it in swapgeom_strategy().
1641 if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
1643 "swap_pager: I/O error - %s failed; blkno %ld,"
1644 "size %ld, error %d\n",
1645 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1653 * remove the mapping for kernel virtual
1656 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1658 bp->b_data = bp->b_kvabase;
1661 object = bp->b_pages[0]->object;
1662 VM_OBJECT_WLOCK(object);
1666 * cleanup pages. If an error occurs writing to swap, we are in
1667 * very serious trouble. If it happens to be a disk error, though,
1668 * we may be able to recover by reassigning the swap later on. So
1669 * in this case we remove the m->swapblk assignment for the page
1670 * but do not free it in the rlist. The errornous block(s) are thus
1671 * never reallocated as swap. Redirty the page and continue.
1673 for (i = 0; i < bp->b_npages; ++i) {
1674 vm_page_t m = bp->b_pages[i];
1676 m->oflags &= ~VPO_SWAPINPROG;
1677 if (m->oflags & VPO_SWAPSLEEP) {
1678 m->oflags &= ~VPO_SWAPSLEEP;
1679 wakeup(&object->handle);
1682 /* We always have space after I/O, successful or not. */
1683 vm_page_aflag_set(m, PGA_SWAP_SPACE);
1685 if (bp->b_ioflags & BIO_ERROR) {
1687 * If an error occurs I'd love to throw the swapblk
1688 * away without freeing it back to swapspace, so it
1689 * can never be used again. But I can't from an
1692 if (bp->b_iocmd == BIO_READ) {
1694 * NOTE: for reads, m->dirty will probably
1695 * be overridden by the original caller of
1696 * getpages so don't play cute tricks here.
1701 * If a write error occurs, reactivate page
1702 * so it doesn't clog the inactive list,
1703 * then finish the I/O.
1705 MPASS(m->dirty == VM_PAGE_BITS_ALL);
1707 /* PQ_UNSWAPPABLE? */
1708 vm_page_activate(m);
1711 } else if (bp->b_iocmd == BIO_READ) {
1713 * NOTE: for reads, m->dirty will probably be
1714 * overridden by the original caller of getpages so
1715 * we cannot set them in order to free the underlying
1716 * swap in a low-swap situation. I don't think we'd
1717 * want to do that anyway, but it was an optimization
1718 * that existed in the old swapper for a time before
1719 * it got ripped out due to precisely this problem.
1721 KASSERT(!pmap_page_is_mapped(m),
1722 ("swp_pager_async_iodone: page %p is mapped", m));
1723 KASSERT(m->dirty == 0,
1724 ("swp_pager_async_iodone: page %p is dirty", m));
1727 if (i < bp->b_pgbefore ||
1728 i >= bp->b_npages - bp->b_pgafter)
1729 vm_page_readahead_finish(m);
1732 * For write success, clear the dirty
1733 * status, then finish the I/O ( which decrements the
1734 * busy count and possibly wakes waiter's up ).
1735 * A page is only written to swap after a period of
1736 * inactivity. Therefore, we do not expect it to be
1739 KASSERT(!pmap_page_is_write_mapped(m),
1740 ("swp_pager_async_iodone: page %p is not write"
1743 vm_page_deactivate_noreuse(m);
1749 * adjust pip. NOTE: the original parent may still have its own
1750 * pip refs on the object.
1752 if (object != NULL) {
1753 vm_object_pip_wakeupn(object, bp->b_npages);
1754 VM_OBJECT_WUNLOCK(object);
1758 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1759 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1760 * trigger a KASSERT in relpbuf().
1764 bp->b_bufobj = NULL;
1767 * release the physical I/O buffer
1769 if (bp->b_flags & B_ASYNC) {
1770 mtx_lock(&swbuf_mtx);
1771 if (++nsw_wcount_async == 1)
1772 wakeup(&nsw_wcount_async);
1773 mtx_unlock(&swbuf_mtx);
1775 uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
1779 swap_pager_nswapdev(void)
1786 swp_pager_force_dirty(vm_page_t m)
1790 swap_pager_unswapped(m);
1795 swap_pager_swapped_pages(vm_object_t object)
1802 VM_OBJECT_ASSERT_LOCKED(object);
1803 if ((object->flags & OBJ_SWAP) == 0)
1806 for (res = 0, pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1807 &object->un_pager.swp.swp_blks, pi)) != NULL;
1808 pi = sb->p + SWAP_META_PAGES) {
1809 for (i = 0; i < SWAP_META_PAGES; i++) {
1810 if (sb->d[i] != SWAPBLK_NONE)
1818 * swap_pager_swapoff_object:
1820 * Page in all of the pages that have been paged out for an object
1824 swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
1830 int i, nv, rahead, rv;
1832 KASSERT((object->flags & OBJ_SWAP) != 0,
1833 ("%s: Object not swappable", __func__));
1835 for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1836 &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1837 if ((object->flags & OBJ_DEAD) != 0) {
1839 * Make sure that pending writes finish before
1842 vm_object_pip_wait(object, "swpoff");
1843 swp_pager_meta_free_all(object);
1846 for (i = 0; i < SWAP_META_PAGES; i++) {
1848 * Count the number of contiguous valid blocks.
1850 for (nv = 0; nv < SWAP_META_PAGES - i; nv++) {
1851 blk = sb->d[i + nv];
1852 if (!swp_pager_isondev(blk, sp) ||
1853 blk == SWAPBLK_NONE)
1860 * Look for a page corresponding to the first
1861 * valid block and ensure that any pending paging
1862 * operations on it are complete. If the page is valid,
1863 * mark it dirty and free the swap block. Try to batch
1864 * this operation since it may cause sp to be freed,
1865 * meaning that we must restart the scan. Avoid busying
1866 * valid pages since we may block forever on kernel
1869 m = vm_page_lookup(object, sb->p + i);
1871 m = vm_page_alloc(object, sb->p + i,
1872 VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
1876 if ((m->oflags & VPO_SWAPINPROG) != 0) {
1877 m->oflags |= VPO_SWAPSLEEP;
1878 VM_OBJECT_SLEEP(object, &object->handle,
1882 if (vm_page_all_valid(m)) {
1884 swp_pager_force_dirty(m);
1885 } while (--nv > 0 &&
1886 (m = vm_page_next(m)) != NULL &&
1887 vm_page_all_valid(m) &&
1888 (m->oflags & VPO_SWAPINPROG) == 0);
1891 if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL))
1895 vm_object_pip_add(object, 1);
1896 rahead = SWAP_META_PAGES;
1897 rv = swap_pager_getpages_locked(object, &m, 1, NULL,
1899 if (rv != VM_PAGER_OK)
1900 panic("%s: read from swap failed: %d",
1902 vm_object_pip_wakeupn(object, 1);
1903 VM_OBJECT_WLOCK(object);
1907 * The object lock was dropped so we must restart the
1908 * scan of this swap block. Pages paged in during this
1909 * iteration will be marked dirty in a future iteration.
1913 if (i == SWAP_META_PAGES)
1914 pi = sb->p + SWAP_META_PAGES;
1919 * swap_pager_swapoff:
1921 * Page in all of the pages that have been paged out to the
1922 * given device. The corresponding blocks in the bitmap must be
1923 * marked as allocated and the device must be flagged SW_CLOSING.
1924 * There may be no processes swapped out to the device.
1926 * This routine may block.
1929 swap_pager_swapoff(struct swdevt *sp)
1934 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1938 mtx_lock(&vm_object_list_mtx);
1939 TAILQ_FOREACH(object, &vm_object_list, object_list) {
1940 if ((object->flags & OBJ_SWAP) == 0)
1942 mtx_unlock(&vm_object_list_mtx);
1943 /* Depends on type-stability. */
1944 VM_OBJECT_WLOCK(object);
1947 * Dead objects are eventually terminated on their own.
1949 if ((object->flags & OBJ_DEAD) != 0)
1953 * Sync with fences placed after pctrie
1954 * initialization. We must not access pctrie below
1955 * unless we checked that our object is swap and not
1958 atomic_thread_fence_acq();
1959 if ((object->flags & OBJ_SWAP) == 0)
1962 swap_pager_swapoff_object(sp, object);
1964 VM_OBJECT_WUNLOCK(object);
1965 mtx_lock(&vm_object_list_mtx);
1967 mtx_unlock(&vm_object_list_mtx);
1971 * Objects may be locked or paging to the device being
1972 * removed, so we will miss their pages and need to
1973 * make another pass. We have marked this device as
1974 * SW_CLOSING, so the activity should finish soon.
1977 if (retries > 100) {
1978 panic("swapoff: failed to locate %d swap blocks",
1981 pause("swpoff", hz / 20);
1984 EVENTHANDLER_INVOKE(swapoff, sp);
1987 /************************************************************************
1989 ************************************************************************
1991 * These routines manipulate the swap metadata stored in the
1994 * Swap metadata is implemented with a global hash and not directly
1995 * linked into the object. Instead the object simply contains
1996 * appropriate tracking counters.
2000 * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
2003 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
2007 MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
2008 for (i = start; i < limit; i++) {
2009 if (sb->d[i] != SWAPBLK_NONE)
2016 * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
2018 * Nothing is done if the block is still in use.
2021 swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
2024 if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
2025 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2026 uma_zfree(swblk_zone, sb);
2031 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
2033 * We first convert the object to a swap object if it is a default
2036 * The specified swapblk is added to the object's swap metadata. If
2037 * the swapblk is not valid, it is freed instead. Any previously
2038 * assigned swapblk is returned.
2041 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
2043 static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
2044 struct swblk *sb, *sb1;
2045 vm_pindex_t modpi, rdpi;
2046 daddr_t prev_swapblk;
2049 VM_OBJECT_ASSERT_WLOCKED(object);
2052 * Convert default object to swap object if necessary
2054 if ((object->flags & OBJ_SWAP) == 0) {
2055 pctrie_init(&object->un_pager.swp.swp_blks);
2058 * Ensure that swap_pager_swapoff()'s iteration over
2059 * object_list does not see a garbage pctrie.
2061 atomic_thread_fence_rel();
2063 object->type = OBJT_SWAP;
2064 vm_object_set_flag(object, OBJ_SWAP);
2065 object->un_pager.swp.writemappings = 0;
2066 KASSERT((object->flags & OBJ_ANON) != 0 ||
2067 object->handle == NULL,
2068 ("default pager %p with handle %p",
2069 object, object->handle));
2072 rdpi = rounddown(pindex, SWAP_META_PAGES);
2073 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
2075 if (swapblk == SWAPBLK_NONE)
2076 return (SWAPBLK_NONE);
2078 sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
2079 pageproc ? M_USE_RESERVE : 0));
2082 for (i = 0; i < SWAP_META_PAGES; i++)
2083 sb->d[i] = SWAPBLK_NONE;
2084 if (atomic_cmpset_int(&swblk_zone_exhausted,
2086 printf("swblk zone ok\n");
2089 VM_OBJECT_WUNLOCK(object);
2090 if (uma_zone_exhausted(swblk_zone)) {
2091 if (atomic_cmpset_int(&swblk_zone_exhausted,
2093 printf("swap blk zone exhausted, "
2094 "increase kern.maxswzone\n");
2095 vm_pageout_oom(VM_OOM_SWAPZ);
2096 pause("swzonxb", 10);
2098 uma_zwait(swblk_zone);
2099 VM_OBJECT_WLOCK(object);
2100 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2104 * Somebody swapped out a nearby page,
2105 * allocating swblk at the rdpi index,
2106 * while we dropped the object lock.
2111 error = SWAP_PCTRIE_INSERT(
2112 &object->un_pager.swp.swp_blks, sb);
2114 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2116 printf("swpctrie zone ok\n");
2119 VM_OBJECT_WUNLOCK(object);
2120 if (uma_zone_exhausted(swpctrie_zone)) {
2121 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2123 printf("swap pctrie zone exhausted, "
2124 "increase kern.maxswzone\n");
2125 vm_pageout_oom(VM_OOM_SWAPZ);
2126 pause("swzonxp", 10);
2128 uma_zwait(swpctrie_zone);
2129 VM_OBJECT_WLOCK(object);
2130 sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2133 uma_zfree(swblk_zone, sb);
2140 MPASS(sb->p == rdpi);
2142 modpi = pindex % SWAP_META_PAGES;
2143 /* Return prior contents of metadata. */
2144 prev_swapblk = sb->d[modpi];
2145 /* Enter block into metadata. */
2146 sb->d[modpi] = swapblk;
2149 * Free the swblk if we end up with the empty page run.
2151 if (swapblk == SWAPBLK_NONE)
2152 swp_pager_free_empty_swblk(object, sb);
2153 return (prev_swapblk);
2157 * SWP_PAGER_META_TRANSFER() - free a range of blocks in the srcobject's swap
2158 * metadata, or transfer it into dstobject.
2160 * This routine will free swap metadata structures as they are cleaned
2164 swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
2165 vm_pindex_t pindex, vm_pindex_t count, vm_size_t *moved)
2169 daddr_t n_free, s_free;
2170 vm_pindex_t offset, last;
2172 int i, limit, start;
2174 VM_OBJECT_ASSERT_WLOCKED(srcobject);
2175 MPASS(moved == NULL || dstobject == NULL);
2179 if ((srcobject->flags & OBJ_SWAP) == 0 || count == 0)
2182 swp_pager_init_freerange(&s_free, &n_free);
2184 last = pindex + count;
2186 sb = SWAP_PCTRIE_LOOKUP_GE(&srcobject->un_pager.swp.swp_blks,
2187 rounddown(pindex, SWAP_META_PAGES));
2188 if (sb == NULL || sb->p >= last)
2190 start = pindex > sb->p ? pindex - sb->p : 0;
2191 limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2193 for (i = start; i < limit; i++) {
2194 if (sb->d[i] == SWAPBLK_NONE)
2196 if (dstobject == NULL ||
2197 !swp_pager_xfer_source(srcobject, dstobject,
2198 sb->p + i - offset, sb->d[i])) {
2199 swp_pager_update_freerange(&s_free, &n_free,
2202 if (moved != NULL) {
2203 if (m != NULL && m->pindex != pindex + i - 1)
2205 m = m != NULL ? vm_page_next(m) :
2206 vm_page_lookup(srcobject, pindex + i);
2207 if (m == NULL || vm_page_none_valid(m))
2210 sb->d[i] = SWAPBLK_NONE;
2212 pindex = sb->p + SWAP_META_PAGES;
2213 if (swp_pager_swblk_empty(sb, 0, start) &&
2214 swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2215 SWAP_PCTRIE_REMOVE(&srcobject->un_pager.swp.swp_blks,
2217 uma_zfree(swblk_zone, sb);
2220 swp_pager_freeswapspace(s_free, n_free);
2227 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
2229 * The requested range of blocks is freed, with any associated swap
2230 * returned to the swap bitmap.
2232 * This routine will free swap metadata structures as they are cleaned
2233 * out. This routine does *NOT* operate on swap metadata associated
2234 * with resident pages.
2237 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count,
2240 swp_pager_meta_transfer(object, NULL, pindex, count, freed);
2244 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
2246 * This routine locates and destroys all swap metadata associated with
2250 swp_pager_meta_free_all(vm_object_t object)
2253 daddr_t n_free, s_free;
2257 VM_OBJECT_ASSERT_WLOCKED(object);
2258 if ((object->flags & OBJ_SWAP) == 0)
2261 swp_pager_init_freerange(&s_free, &n_free);
2262 for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
2263 &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
2264 pindex = sb->p + SWAP_META_PAGES;
2265 for (i = 0; i < SWAP_META_PAGES; i++) {
2266 if (sb->d[i] == SWAPBLK_NONE)
2268 swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
2270 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2271 uma_zfree(swblk_zone, sb);
2273 swp_pager_freeswapspace(s_free, n_free);
2277 * SWP_PAGER_METACTL() - misc control of swap meta data.
2279 * This routine is capable of looking up, or removing swapblk
2280 * assignments in the swap meta data. It returns the swapblk being
2281 * looked-up, popped, or SWAPBLK_NONE if the block was invalid.
2283 * When acting on a busy resident page and paging is in progress, we
2284 * have to wait until paging is complete but otherwise can act on the
2288 swp_pager_meta_lookup(vm_object_t object, vm_pindex_t pindex)
2292 VM_OBJECT_ASSERT_LOCKED(object);
2295 * The meta data only exists if the object is OBJT_SWAP
2296 * and even then might not be allocated yet.
2298 KASSERT((object->flags & OBJ_SWAP) != 0,
2299 ("Lookup object not swappable"));
2301 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2302 rounddown(pindex, SWAP_META_PAGES));
2304 return (SWAPBLK_NONE);
2305 return (sb->d[pindex % SWAP_META_PAGES]);
2309 * Returns the least page index which is greater than or equal to the
2310 * parameter pindex and for which there is a swap block allocated.
2311 * Returns object's size if the object's type is not swap or if there
2312 * are no allocated swap blocks for the object after the requested
2316 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2321 VM_OBJECT_ASSERT_LOCKED(object);
2322 if ((object->flags & OBJ_SWAP) == 0)
2323 return (object->size);
2325 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2326 rounddown(pindex, SWAP_META_PAGES));
2328 return (object->size);
2329 if (sb->p < pindex) {
2330 for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2331 if (sb->d[i] != SWAPBLK_NONE)
2334 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2335 roundup(pindex, SWAP_META_PAGES));
2337 return (object->size);
2339 for (i = 0; i < SWAP_META_PAGES; i++) {
2340 if (sb->d[i] != SWAPBLK_NONE)
2345 * We get here if a swblk is present in the trie but it
2346 * doesn't map any blocks.
2349 return (object->size);
2353 * System call swapon(name) enables swapping on device name,
2354 * which must be in the swdevsw. Return EBUSY
2355 * if already swapping on this device.
2357 #ifndef _SYS_SYSPROTO_H_
2358 struct swapon_args {
2364 sys_swapon(struct thread *td, struct swapon_args *uap)
2368 struct nameidata nd;
2371 error = priv_check(td, PRIV_SWAPON);
2375 sx_xlock(&swdev_syscall_lock);
2378 * Swap metadata may not fit in the KVM if we have physical
2381 if (swblk_zone == NULL) {
2386 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | LOCKLEAF | AUDITVNODE1,
2387 UIO_USERSPACE, uap->name, td);
2392 NDFREE(&nd, NDF_ONLY_PNBUF);
2395 if (vn_isdisk_error(vp, &error)) {
2396 error = swapongeom(vp);
2397 } else if (vp->v_type == VREG &&
2398 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2399 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2401 * Allow direct swapping to NFS regular files in the same
2402 * way that nfs_mountroot() sets up diskless swapping.
2404 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2412 sx_xunlock(&swdev_syscall_lock);
2417 * Check that the total amount of swap currently configured does not
2418 * exceed half the theoretical maximum. If it does, print a warning
2422 swapon_check_swzone(void)
2425 /* recommend using no more than half that amount */
2426 if (swap_total > swap_maxpages / 2) {
2427 printf("warning: total configured swap (%lu pages) "
2428 "exceeds maximum recommended amount (%lu pages).\n",
2429 swap_total, swap_maxpages / 2);
2430 printf("warning: increase kern.maxswzone "
2431 "or reduce amount of swap.\n");
2436 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2437 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2439 struct swdevt *sp, *tsp;
2443 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2444 * First chop nblks off to page-align it, then convert.
2446 * sw->sw_nblks is in page-sized chunks now too.
2448 nblks &= ~(ctodb(1) - 1);
2449 nblks = dbtoc(nblks);
2451 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2452 sp->sw_blist = blist_create(nblks, M_WAITOK);
2456 sp->sw_nblks = nblks;
2458 sp->sw_strategy = strategy;
2459 sp->sw_close = close;
2460 sp->sw_flags = flags;
2463 * Do not free the first blocks in order to avoid overwriting
2464 * any bsd label at the front of the partition
2466 blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2467 nblks - howmany(BBSIZE, PAGE_SIZE));
2470 mtx_lock(&sw_dev_mtx);
2471 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2472 if (tsp->sw_end >= dvbase) {
2474 * We put one uncovered page between the devices
2475 * in order to definitively prevent any cross-device
2478 dvbase = tsp->sw_end + 1;
2481 sp->sw_first = dvbase;
2482 sp->sw_end = dvbase + nblks;
2483 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2485 swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2486 swap_total += nblks;
2487 swapon_check_swzone();
2489 mtx_unlock(&sw_dev_mtx);
2490 EVENTHANDLER_INVOKE(swapon, sp);
2494 * SYSCALL: swapoff(devname)
2496 * Disable swapping on the given device.
2498 * XXX: Badly designed system call: it should use a device index
2499 * rather than filename as specification. We keep sw_vp around
2500 * only to make this work.
2503 kern_swapoff(struct thread *td, const char *name, enum uio_seg name_seg,
2507 struct nameidata nd;
2511 error = priv_check(td, PRIV_SWAPOFF);
2514 if ((flags & ~(SWAPOFF_FORCE)) != 0)
2517 sx_xlock(&swdev_syscall_lock);
2519 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, name_seg, name, td);
2523 NDFREE(&nd, NDF_ONLY_PNBUF);
2526 mtx_lock(&sw_dev_mtx);
2527 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2528 if (sp->sw_vp == vp)
2531 mtx_unlock(&sw_dev_mtx);
2536 error = swapoff_one(sp, td->td_ucred, flags);
2538 sx_xunlock(&swdev_syscall_lock);
2543 freebsd13_swapoff(struct thread *td, struct freebsd13_swapoff_args *uap)
2545 return (kern_swapoff(td, uap->name, UIO_USERSPACE, 0));
2549 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2551 return (kern_swapoff(td, uap->name, UIO_USERSPACE, uap->flags));
2555 swapoff_one(struct swdevt *sp, struct ucred *cred, u_int flags)
2562 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2564 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2565 error = mac_system_check_swapoff(cred, sp->sw_vp);
2566 (void) VOP_UNLOCK(sp->sw_vp);
2570 nblks = sp->sw_nblks;
2573 * We can turn off this swap device safely only if the
2574 * available virtual memory in the system will fit the amount
2575 * of data we will have to page back in, plus an epsilon so
2576 * the system doesn't become critically low on swap space.
2577 * The vm_free_count() part does not account e.g. for clean
2578 * pages that can be immediately reclaimed without paging, so
2579 * this is a very rough estimation.
2581 * On the other hand, not turning swap off on swapoff_all()
2582 * means that we can lose swap data when filesystems go away,
2583 * which is arguably worse.
2585 if ((flags & SWAPOFF_FORCE) == 0 &&
2586 vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
2590 * Prevent further allocations on this device.
2592 mtx_lock(&sw_dev_mtx);
2593 sp->sw_flags |= SW_CLOSING;
2594 swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2595 swap_total -= nblks;
2596 mtx_unlock(&sw_dev_mtx);
2599 * Page in the contents of the device and close it.
2601 swap_pager_swapoff(sp);
2603 sp->sw_close(curthread, sp);
2604 mtx_lock(&sw_dev_mtx);
2606 TAILQ_REMOVE(&swtailq, sp, sw_list);
2608 if (nswapdev == 0) {
2609 swap_pager_full = 2;
2610 swap_pager_almost_full = 1;
2614 mtx_unlock(&sw_dev_mtx);
2615 blist_destroy(sp->sw_blist);
2616 free(sp, M_VMPGDATA);
2623 struct swdevt *sp, *spt;
2624 const char *devname;
2627 sx_xlock(&swdev_syscall_lock);
2629 mtx_lock(&sw_dev_mtx);
2630 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2631 mtx_unlock(&sw_dev_mtx);
2632 if (vn_isdisk(sp->sw_vp))
2633 devname = devtoname(sp->sw_vp->v_rdev);
2636 error = swapoff_one(sp, thread0.td_ucred, SWAPOFF_FORCE);
2638 printf("Cannot remove swap device %s (error=%d), "
2639 "skipping.\n", devname, error);
2640 } else if (bootverbose) {
2641 printf("Swap device %s removed.\n", devname);
2643 mtx_lock(&sw_dev_mtx);
2645 mtx_unlock(&sw_dev_mtx);
2647 sx_xunlock(&swdev_syscall_lock);
2651 swap_pager_status(int *total, int *used)
2654 *total = swap_total;
2655 *used = swap_total - swap_pager_avail -
2656 nswapdev * howmany(BBSIZE, PAGE_SIZE);
2660 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2663 const char *tmp_devname;
2668 mtx_lock(&sw_dev_mtx);
2669 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2674 xs->xsw_version = XSWDEV_VERSION;
2675 xs->xsw_dev = sp->sw_dev;
2676 xs->xsw_flags = sp->sw_flags;
2677 xs->xsw_nblks = sp->sw_nblks;
2678 xs->xsw_used = sp->sw_used;
2679 if (devname != NULL) {
2680 if (vn_isdisk(sp->sw_vp))
2681 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2683 tmp_devname = "[file]";
2684 strncpy(devname, tmp_devname, len);
2689 mtx_unlock(&sw_dev_mtx);
2693 #if defined(COMPAT_FREEBSD11)
2694 #define XSWDEV_VERSION_11 1
2704 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2707 u_int xsw_dev1, xsw_dev2;
2715 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2718 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2719 struct xswdev32 xs32;
2721 #if defined(COMPAT_FREEBSD11)
2722 struct xswdev11 xs11;
2726 if (arg2 != 1) /* name length */
2729 memset(&xs, 0, sizeof(xs));
2730 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2733 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2734 if (req->oldlen == sizeof(xs32)) {
2735 memset(&xs32, 0, sizeof(xs32));
2736 xs32.xsw_version = XSWDEV_VERSION;
2737 xs32.xsw_dev1 = xs.xsw_dev;
2738 xs32.xsw_dev2 = xs.xsw_dev >> 32;
2739 xs32.xsw_flags = xs.xsw_flags;
2740 xs32.xsw_nblks = xs.xsw_nblks;
2741 xs32.xsw_used = xs.xsw_used;
2742 error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2746 #if defined(COMPAT_FREEBSD11)
2747 if (req->oldlen == sizeof(xs11)) {
2748 memset(&xs11, 0, sizeof(xs11));
2749 xs11.xsw_version = XSWDEV_VERSION_11;
2750 xs11.xsw_dev = xs.xsw_dev; /* truncation */
2751 xs11.xsw_flags = xs.xsw_flags;
2752 xs11.xsw_nblks = xs.xsw_nblks;
2753 xs11.xsw_used = xs.xsw_used;
2754 error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2758 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2762 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2763 "Number of swap devices");
2764 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2765 sysctl_vm_swap_info,
2766 "Swap statistics by device");
2769 * Count the approximate swap usage in pages for a vmspace. The
2770 * shadowed or not yet copied on write swap blocks are not accounted.
2771 * The map must be locked.
2774 vmspace_swap_count(struct vmspace *vmspace)
2784 map = &vmspace->vm_map;
2787 VM_MAP_ENTRY_FOREACH(cur, map) {
2788 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2790 object = cur->object.vm_object;
2791 if (object == NULL || (object->flags & OBJ_SWAP) == 0)
2793 VM_OBJECT_RLOCK(object);
2794 if ((object->flags & OBJ_SWAP) == 0)
2796 pi = OFF_TO_IDX(cur->offset);
2797 e = pi + OFF_TO_IDX(cur->end - cur->start);
2798 for (;; pi = sb->p + SWAP_META_PAGES) {
2799 sb = SWAP_PCTRIE_LOOKUP_GE(
2800 &object->un_pager.swp.swp_blks, pi);
2801 if (sb == NULL || sb->p >= e)
2803 for (i = 0; i < SWAP_META_PAGES; i++) {
2804 if (sb->p + i < e &&
2805 sb->d[i] != SWAPBLK_NONE)
2810 VM_OBJECT_RUNLOCK(object);
2818 * Swapping onto disk devices.
2822 static g_orphan_t swapgeom_orphan;
2824 static struct g_class g_swap_class = {
2826 .version = G_VERSION,
2827 .orphan = swapgeom_orphan,
2830 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2833 swapgeom_close_ev(void *arg, int flags)
2835 struct g_consumer *cp;
2838 g_access(cp, -1, -1, 0);
2840 g_destroy_consumer(cp);
2844 * Add a reference to the g_consumer for an inflight transaction.
2847 swapgeom_acquire(struct g_consumer *cp)
2850 mtx_assert(&sw_dev_mtx, MA_OWNED);
2855 * Remove a reference from the g_consumer. Post a close event if all
2856 * references go away, since the function might be called from the
2860 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2863 mtx_assert(&sw_dev_mtx, MA_OWNED);
2865 if (cp->index == 0) {
2866 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2872 swapgeom_done(struct bio *bp2)
2876 struct g_consumer *cp;
2878 bp = bp2->bio_caller2;
2880 bp->b_ioflags = bp2->bio_flags;
2882 bp->b_ioflags |= BIO_ERROR;
2883 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2884 bp->b_error = bp2->bio_error;
2885 bp->b_caller1 = NULL;
2887 sp = bp2->bio_caller1;
2888 mtx_lock(&sw_dev_mtx);
2889 swapgeom_release(cp, sp);
2890 mtx_unlock(&sw_dev_mtx);
2895 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2898 struct g_consumer *cp;
2900 mtx_lock(&sw_dev_mtx);
2903 mtx_unlock(&sw_dev_mtx);
2904 bp->b_error = ENXIO;
2905 bp->b_ioflags |= BIO_ERROR;
2909 swapgeom_acquire(cp);
2910 mtx_unlock(&sw_dev_mtx);
2911 if (bp->b_iocmd == BIO_WRITE)
2914 bio = g_alloc_bio();
2916 mtx_lock(&sw_dev_mtx);
2917 swapgeom_release(cp, sp);
2918 mtx_unlock(&sw_dev_mtx);
2919 bp->b_error = ENOMEM;
2920 bp->b_ioflags |= BIO_ERROR;
2921 printf("swap_pager: cannot allocate bio\n");
2926 bp->b_caller1 = bio;
2927 bio->bio_caller1 = sp;
2928 bio->bio_caller2 = bp;
2929 bio->bio_cmd = bp->b_iocmd;
2930 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2931 bio->bio_length = bp->b_bcount;
2932 bio->bio_done = swapgeom_done;
2933 if (!buf_mapped(bp)) {
2934 bio->bio_ma = bp->b_pages;
2935 bio->bio_data = unmapped_buf;
2936 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2937 bio->bio_ma_n = bp->b_npages;
2938 bio->bio_flags |= BIO_UNMAPPED;
2940 bio->bio_data = bp->b_data;
2943 g_io_request(bio, cp);
2948 swapgeom_orphan(struct g_consumer *cp)
2953 mtx_lock(&sw_dev_mtx);
2954 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2955 if (sp->sw_id == cp) {
2956 sp->sw_flags |= SW_CLOSING;
2961 * Drop reference we were created with. Do directly since we're in a
2962 * special context where we don't have to queue the call to
2963 * swapgeom_close_ev().
2966 destroy = ((sp != NULL) && (cp->index == 0));
2969 mtx_unlock(&sw_dev_mtx);
2971 swapgeom_close_ev(cp, 0);
2975 swapgeom_close(struct thread *td, struct swdevt *sw)
2977 struct g_consumer *cp;
2979 mtx_lock(&sw_dev_mtx);
2982 mtx_unlock(&sw_dev_mtx);
2985 * swapgeom_close() may be called from the biodone context,
2986 * where we cannot perform topology changes. Delegate the
2987 * work to the events thread.
2990 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2994 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2996 struct g_provider *pp;
2997 struct g_consumer *cp;
2998 static struct g_geom *gp;
3003 pp = g_dev_getprovider(dev);
3006 mtx_lock(&sw_dev_mtx);
3007 TAILQ_FOREACH(sp, &swtailq, sw_list) {
3009 if (cp != NULL && cp->provider == pp) {
3010 mtx_unlock(&sw_dev_mtx);
3014 mtx_unlock(&sw_dev_mtx);
3016 gp = g_new_geomf(&g_swap_class, "swap");
3017 cp = g_new_consumer(gp);
3018 cp->index = 1; /* Number of active I/Os, plus one for being active. */
3019 cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
3022 * XXX: Every time you think you can improve the margin for
3023 * footshooting, somebody depends on the ability to do so:
3024 * savecore(8) wants to write to our swapdev so we cannot
3025 * set an exclusive count :-(
3027 error = g_access(cp, 1, 1, 0);
3030 g_destroy_consumer(cp);
3033 nblks = pp->mediasize / DEV_BSIZE;
3034 swaponsomething(vp, cp, nblks, swapgeom_strategy,
3035 swapgeom_close, dev2udev(dev),
3036 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
3041 swapongeom(struct vnode *vp)
3045 ASSERT_VOP_ELOCKED(vp, "swapongeom");
3046 if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) {
3050 error = swapongeom_locked(vp->v_rdev, vp);
3051 g_topology_unlock();
3059 * This is used mainly for network filesystem (read: probably only tested
3060 * with NFS) swapfiles.
3065 swapdev_strategy(struct buf *bp, struct swdevt *sp)
3069 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
3073 if (bp->b_iocmd == BIO_WRITE) {
3074 vn_lock(vp2, LK_EXCLUSIVE | LK_RETRY);
3076 bufobj_wdrop(bp->b_bufobj);
3077 bufobj_wref(&vp2->v_bufobj);
3079 vn_lock(vp2, LK_SHARED | LK_RETRY);
3081 if (bp->b_bufobj != &vp2->v_bufobj)
3082 bp->b_bufobj = &vp2->v_bufobj;
3084 bp->b_iooffset = dbtob(bp->b_blkno);
3090 swapdev_close(struct thread *td, struct swdevt *sp)
3095 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3096 VOP_CLOSE(vp, FREAD | FWRITE, td->td_ucred, td);
3101 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
3106 ASSERT_VOP_ELOCKED(vp, "swaponvp");
3109 mtx_lock(&sw_dev_mtx);
3110 TAILQ_FOREACH(sp, &swtailq, sw_list) {
3111 if (sp->sw_id == vp) {
3112 mtx_unlock(&sw_dev_mtx);
3116 mtx_unlock(&sw_dev_mtx);
3119 error = mac_system_check_swapon(td->td_ucred, vp);
3122 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
3126 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
3132 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
3136 new = nsw_wcount_async_max;
3137 error = sysctl_handle_int(oidp, &new, 0, req);
3138 if (error != 0 || req->newptr == NULL)
3141 if (new > nswbuf / 2 || new < 1)
3144 mtx_lock(&swbuf_mtx);
3145 while (nsw_wcount_async_max != new) {
3147 * Adjust difference. If the current async count is too low,
3148 * we will need to sqeeze our update slowly in. Sleep with a
3149 * higher priority than getpbuf() to finish faster.
3151 n = new - nsw_wcount_async_max;
3152 if (nsw_wcount_async + n >= 0) {
3153 nsw_wcount_async += n;
3154 nsw_wcount_async_max += n;
3155 wakeup(&nsw_wcount_async);
3157 nsw_wcount_async_max -= nsw_wcount_async;
3158 nsw_wcount_async = 0;
3159 msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
3163 mtx_unlock(&swbuf_mtx);
3169 swap_pager_update_writecount(vm_object_t object, vm_offset_t start,
3173 VM_OBJECT_WLOCK(object);
3174 KASSERT((object->flags & OBJ_ANON) == 0,
3175 ("Splittable object with writecount"));
3176 object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
3177 VM_OBJECT_WUNLOCK(object);
3181 swap_pager_release_writecount(vm_object_t object, vm_offset_t start,
3185 VM_OBJECT_WLOCK(object);
3186 KASSERT((object->flags & OBJ_ANON) == 0,
3187 ("Splittable object with writecount"));
3188 object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
3189 VM_OBJECT_WUNLOCK(object);