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>
86 #include <sys/kernel.h>
87 #include <sys/mount.h>
88 #include <sys/namei.h>
89 #include <sys/malloc.h>
90 #include <sys/pctrie.h>
93 #include <sys/racct.h>
94 #include <sys/resource.h>
95 #include <sys/resourcevar.h>
96 #include <sys/rwlock.h>
98 #include <sys/sysctl.h>
99 #include <sys/sysproto.h>
100 #include <sys/systm.h>
102 #include <sys/vmmeter.h>
103 #include <sys/vnode.h>
105 #include <security/mac/mac_framework.h>
109 #include <vm/vm_map.h>
110 #include <vm/vm_kern.h>
111 #include <vm/vm_object.h>
112 #include <vm/vm_page.h>
113 #include <vm/vm_pager.h>
114 #include <vm/vm_pageout.h>
115 #include <vm/vm_param.h>
116 #include <vm/swap_pager.h>
117 #include <vm/vm_extern.h>
120 #include <geom/geom.h>
123 * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64.
124 * The 64-page limit is due to the radix code (kern/subr_blist.c).
126 #ifndef MAX_PAGEOUT_CLUSTER
127 #define MAX_PAGEOUT_CLUSTER 32
130 #if !defined(SWB_NPAGES)
131 #define SWB_NPAGES MAX_PAGEOUT_CLUSTER
134 #define SWAP_META_PAGES PCTRIE_COUNT
137 * A swblk structure maps each page index within a
138 * SWAP_META_PAGES-aligned and sized range to the address of an
139 * on-disk swap block (or SWAPBLK_NONE). The collection of these
140 * mappings for an entire vm object is implemented as a pc-trie.
144 daddr_t d[SWAP_META_PAGES];
147 static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data");
148 static struct mtx sw_dev_mtx;
149 static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
150 static struct swdevt *swdevhd; /* Allocate from here next */
151 static int nswapdev; /* Number of swap devices */
152 int swap_pager_avail;
153 static struct sx swdev_syscall_lock; /* serialize swap(on|off) */
155 static __exclusive_cache_line u_long swap_reserved;
156 static u_long swap_total;
157 static int sysctl_page_shift(SYSCTL_HANDLER_ARGS);
159 static SYSCTL_NODE(_vm_stats, OID_AUTO, swap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
162 SYSCTL_PROC(_vm, OID_AUTO, swap_reserved, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
163 &swap_reserved, 0, sysctl_page_shift, "A",
164 "Amount of swap storage needed to back all allocated anonymous memory.");
165 SYSCTL_PROC(_vm, OID_AUTO, swap_total, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
166 &swap_total, 0, sysctl_page_shift, "A",
167 "Total amount of available swap storage.");
169 static int overcommit = 0;
170 SYSCTL_INT(_vm, VM_OVERCOMMIT, overcommit, CTLFLAG_RW, &overcommit, 0,
171 "Configure virtual memory overcommit behavior. See tuning(7) "
173 static unsigned long swzone;
174 SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
175 "Actual size of swap metadata zone");
176 static unsigned long swap_maxpages;
177 SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
178 "Maximum amount of swap supported");
180 static COUNTER_U64_DEFINE_EARLY(swap_free_deferred);
181 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_deferred,
182 CTLFLAG_RD, &swap_free_deferred,
183 "Number of pages that deferred freeing swap space");
185 static COUNTER_U64_DEFINE_EARLY(swap_free_completed);
186 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_completed,
187 CTLFLAG_RD, &swap_free_completed,
188 "Number of deferred frees completed");
190 /* bits from overcommit */
191 #define SWAP_RESERVE_FORCE_ON (1 << 0)
192 #define SWAP_RESERVE_RLIMIT_ON (1 << 1)
193 #define SWAP_RESERVE_ALLOW_NONWIRED (1 << 2)
196 sysctl_page_shift(SYSCTL_HANDLER_ARGS)
199 u_long value = *(u_long *)arg1;
201 newval = ((uint64_t)value) << PAGE_SHIFT;
202 return (sysctl_handle_64(oidp, &newval, 0, req));
206 swap_reserve_by_cred_rlimit(u_long pincr, struct ucred *cred, int oc)
211 uip = cred->cr_ruidinfo;
213 prev = atomic_fetchadd_long(&uip->ui_vmsize, pincr);
214 if ((oc & SWAP_RESERVE_RLIMIT_ON) != 0 &&
215 prev + pincr > lim_cur(curthread, RLIMIT_SWAP) &&
216 priv_check(curthread, PRIV_VM_SWAP_NORLIMIT) != 0) {
217 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pincr);
218 KASSERT(prev >= pincr, ("negative vmsize for uid = %d\n", uip->ui_uid));
225 swap_release_by_cred_rlimit(u_long pdecr, struct ucred *cred)
232 uip = cred->cr_ruidinfo;
235 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pdecr);
236 KASSERT(prev >= pdecr, ("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", __func__,
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(&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, ("swap_reserved < incr on overcommit fail"));
298 if (!swap_reserve_by_cred_rlimit(pincr, cred, oc)) {
299 prev = atomic_fetchadd_long(&swap_reserved, -pincr);
300 KASSERT(prev >= pincr, ("swap_reserved < incr on overcommit fail"));
307 if (ppsratecheck(&lastfail, &curfail, 1)) {
308 printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
309 cred->cr_ruidinfo->ui_uid, curproc->p_pid, incr);
312 if (RACCT_ENABLED()) {
314 racct_sub(curproc, RACCT_SWAP, incr);
315 PROC_UNLOCK(curproc);
323 swap_reserve_force(vm_ooffset_t incr)
327 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
331 if (RACCT_ENABLED()) {
333 racct_add_force(curproc, RACCT_SWAP, incr);
334 PROC_UNLOCK(curproc);
338 atomic_add_long(&swap_reserved, pincr);
339 swap_reserve_force_rlimit(pincr, curthread->td_ucred);
343 swap_release(vm_ooffset_t decr)
348 cred = curproc->p_ucred;
349 swap_release_by_cred(decr, cred);
350 PROC_UNLOCK(curproc);
354 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
361 KASSERT((decr & PAGE_MASK) == 0, ("%s: decr: %ju & PAGE_MASK", __func__,
366 prev = atomic_fetchadd_long(&swap_reserved, -pdecr);
367 KASSERT(prev >= pdecr, ("swap_reserved < decr"));
369 atomic_subtract_long(&swap_reserved, pdecr);
372 swap_release_by_cred_rlimit(pdecr, cred);
375 racct_sub_cred(cred, RACCT_SWAP, decr);
379 static int swap_pager_full = 2; /* swap space exhaustion (task killing) */
380 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
381 static struct mtx swbuf_mtx; /* to sync nsw_wcount_async */
382 static int nsw_wcount_async; /* limit async write buffers */
383 static int nsw_wcount_async_max;/* assigned maximum */
384 static int nsw_cluster_max; /* maximum VOP I/O allowed */
386 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
387 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
388 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
389 "Maximum running async swap ops");
390 static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS);
391 SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD |
392 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A",
393 "Swap Fragmentation Info");
395 static struct sx sw_alloc_sx;
398 * "named" and "unnamed" anon region objects. Try to reduce the overhead
399 * of searching a named list by hashing it just a little.
404 #define NOBJLIST(handle) \
405 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
407 static struct pagerlst swap_pager_object_list[NOBJLISTS];
408 static uma_zone_t swwbuf_zone;
409 static uma_zone_t swrbuf_zone;
410 static uma_zone_t swblk_zone;
411 static uma_zone_t swpctrie_zone;
414 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
415 * calls hooked from other parts of the VM system and do not appear here.
416 * (see vm/swap_pager.h).
419 swap_pager_alloc(void *handle, vm_ooffset_t size,
420 vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
421 static void swap_pager_dealloc(vm_object_t object);
422 static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
424 static int swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
425 int *, pgo_getpages_iodone_t, void *);
426 static void swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
428 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
429 static void swap_pager_init(void);
430 static void swap_pager_unswapped(vm_page_t);
431 static void swap_pager_swapoff(struct swdevt *sp);
432 static void swap_pager_update_writecount(vm_object_t object,
433 vm_offset_t start, vm_offset_t end);
434 static void swap_pager_release_writecount(vm_object_t object,
435 vm_offset_t start, vm_offset_t end);
437 struct pagerops swappagerops = {
438 .pgo_init = swap_pager_init, /* early system initialization of pager */
439 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */
440 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
441 .pgo_getpages = swap_pager_getpages, /* pagein */
442 .pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
443 .pgo_putpages = swap_pager_putpages, /* pageout */
444 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */
445 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
446 .pgo_update_writecount = swap_pager_update_writecount,
447 .pgo_release_writecount = swap_pager_release_writecount,
451 * swap_*() routines are externally accessible. swp_*() routines are
454 static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
455 static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
457 SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
458 "Maximum size of a swap block in pages");
460 static void swp_sizecheck(void);
461 static void swp_pager_async_iodone(struct buf *bp);
462 static bool swp_pager_swblk_empty(struct swblk *sb, int start, int limit);
463 static void swp_pager_free_empty_swblk(vm_object_t, struct swblk *sb);
464 static int swapongeom(struct vnode *);
465 static int swaponvp(struct thread *, struct vnode *, u_long);
466 static int swapoff_one(struct swdevt *sp, struct ucred *cred);
469 * Swap bitmap functions
471 static void swp_pager_freeswapspace(daddr_t blk, daddr_t npages);
472 static daddr_t swp_pager_getswapspace(int *npages);
477 static daddr_t swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
478 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t);
479 static void swp_pager_meta_transfer(vm_object_t src, vm_object_t dst,
480 vm_pindex_t pindex, vm_pindex_t count);
481 static void swp_pager_meta_free_all(vm_object_t);
482 static daddr_t swp_pager_meta_lookup(vm_object_t, vm_pindex_t);
485 swp_pager_init_freerange(daddr_t *start, daddr_t *num)
488 *start = SWAPBLK_NONE;
493 swp_pager_update_freerange(daddr_t *start, daddr_t *num, daddr_t addr)
496 if (*start + *num == addr) {
499 swp_pager_freeswapspace(*start, *num);
506 swblk_trie_alloc(struct pctrie *ptree)
509 return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
510 M_USE_RESERVE : 0)));
514 swblk_trie_free(struct pctrie *ptree, void *node)
517 uma_zfree(swpctrie_zone, node);
520 PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
523 * SWP_SIZECHECK() - update swap_pager_full indication
525 * update the swap_pager_almost_full indication and warn when we are
526 * about to run out of swap space, using lowat/hiwat hysteresis.
528 * Clear swap_pager_full ( task killing ) indication when lowat is met.
530 * No restrictions on call
531 * This routine may not block.
537 if (swap_pager_avail < nswap_lowat) {
538 if (swap_pager_almost_full == 0) {
539 printf("swap_pager: out of swap space\n");
540 swap_pager_almost_full = 1;
544 if (swap_pager_avail > nswap_hiwat)
545 swap_pager_almost_full = 0;
550 * SWAP_PAGER_INIT() - initialize the swap pager!
552 * Expected to be started from system init. NOTE: This code is run
553 * before much else so be careful what you depend on. Most of the VM
554 * system has yet to be initialized at this point.
557 swap_pager_init(void)
560 * Initialize object lists
564 for (i = 0; i < NOBJLISTS; ++i)
565 TAILQ_INIT(&swap_pager_object_list[i]);
566 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
567 sx_init(&sw_alloc_sx, "swspsx");
568 sx_init(&swdev_syscall_lock, "swsysc");
572 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
574 * Expected to be started from pageout process once, prior to entering
578 swap_pager_swap_init(void)
583 * Number of in-transit swap bp operations. Don't
584 * exhaust the pbufs completely. Make sure we
585 * initialize workable values (0 will work for hysteresis
586 * but it isn't very efficient).
588 * The nsw_cluster_max is constrained by the bp->b_pages[]
589 * array, which has MAXPHYS / PAGE_SIZE entries, and our locally
590 * defined MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
591 * constrained by the swap device interleave stripe size.
593 * Currently we hardwire nsw_wcount_async to 4. This limit is
594 * designed to prevent other I/O from having high latencies due to
595 * our pageout I/O. The value 4 works well for one or two active swap
596 * devices but is probably a little low if you have more. Even so,
597 * a higher value would probably generate only a limited improvement
598 * with three or four active swap devices since the system does not
599 * typically have to pageout at extreme bandwidths. We will want
600 * at least 2 per swap devices, and 4 is a pretty good value if you
601 * have one NFS swap device due to the command/ack latency over NFS.
602 * So it all works out pretty well.
604 nsw_cluster_max = min(MAXPHYS / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
606 nsw_wcount_async = 4;
607 nsw_wcount_async_max = nsw_wcount_async;
608 mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
610 swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
611 swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
614 * Initialize our zone, taking the user's requested size or
615 * estimating the number we need based on the number of pages
618 n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
619 vm_cnt.v_page_count / 2;
620 swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
621 pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0);
622 if (swpctrie_zone == NULL)
623 panic("failed to create swap pctrie zone.");
624 swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
625 NULL, NULL, _Alignof(struct swblk) - 1, 0);
626 if (swblk_zone == NULL)
627 panic("failed to create swap blk zone.");
630 if (uma_zone_reserve_kva(swblk_zone, n))
633 * if the allocation failed, try a zone two thirds the
634 * size of the previous attempt.
640 * Often uma_zone_reserve_kva() cannot reserve exactly the
641 * requested size. Account for the difference when
642 * calculating swap_maxpages.
644 n = uma_zone_get_max(swblk_zone);
647 printf("Swap blk zone entries changed from %lu to %lu.\n",
649 /* absolute maximum we can handle assuming 100% efficiency */
650 swap_maxpages = n * SWAP_META_PAGES;
651 swzone = n * sizeof(struct swblk);
652 if (!uma_zone_reserve_kva(swpctrie_zone, n))
653 printf("Cannot reserve swap pctrie zone, "
654 "reduce kern.maxswzone.\n");
658 swap_pager_alloc_init(void *handle, struct ucred *cred, vm_ooffset_t size,
664 if (!swap_reserve_by_cred(size, cred))
670 * The un_pager.swp.swp_blks trie is initialized by
671 * vm_object_allocate() to ensure the correct order of
672 * visibility to other threads.
674 object = vm_object_allocate(OBJT_SWAP, OFF_TO_IDX(offset +
677 object->un_pager.swp.writemappings = 0;
678 object->handle = handle;
681 object->charge = size;
687 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
688 * its metadata structures.
690 * This routine is called from the mmap and fork code to create a new
693 * This routine must ensure that no live duplicate is created for
694 * the named object request, which is protected against by
695 * holding the sw_alloc_sx lock in case handle != NULL.
698 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
699 vm_ooffset_t offset, struct ucred *cred)
703 if (handle != NULL) {
705 * Reference existing named region or allocate new one. There
706 * should not be a race here against swp_pager_meta_build()
707 * as called from vm_page_remove() in regards to the lookup
710 sx_xlock(&sw_alloc_sx);
711 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
712 if (object == NULL) {
713 object = swap_pager_alloc_init(handle, cred, size,
715 if (object != NULL) {
716 TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
717 object, pager_object_list);
720 sx_xunlock(&sw_alloc_sx);
722 object = swap_pager_alloc_init(handle, cred, size, offset);
728 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
730 * The swap backing for the object is destroyed. The code is
731 * designed such that we can reinstantiate it later, but this
732 * routine is typically called only when the entire object is
733 * about to be destroyed.
735 * The object must be locked.
738 swap_pager_dealloc(vm_object_t object)
741 VM_OBJECT_ASSERT_WLOCKED(object);
742 KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
745 * Remove from list right away so lookups will fail if we block for
746 * pageout completion.
748 if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
749 VM_OBJECT_WUNLOCK(object);
750 sx_xlock(&sw_alloc_sx);
751 TAILQ_REMOVE(NOBJLIST(object->handle), object,
753 sx_xunlock(&sw_alloc_sx);
754 VM_OBJECT_WLOCK(object);
757 vm_object_pip_wait(object, "swpdea");
760 * Free all remaining metadata. We only bother to free it from
761 * the swap meta data. We do not attempt to free swapblk's still
762 * associated with vm_page_t's for this object. We do not care
763 * if paging is still in progress on some objects.
765 swp_pager_meta_free_all(object);
766 object->handle = NULL;
767 object->type = OBJT_DEAD;
770 /************************************************************************
771 * SWAP PAGER BITMAP ROUTINES *
772 ************************************************************************/
775 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
777 * Allocate swap for up to the requested number of pages. The
778 * starting swap block number (a page index) is returned or
779 * SWAPBLK_NONE if the allocation failed.
781 * Also has the side effect of advising that somebody made a mistake
782 * when they configured swap and didn't configure enough.
784 * This routine may not sleep.
786 * We allocate in round-robin fashion from the configured devices.
789 swp_pager_getswapspace(int *io_npages)
795 KASSERT(*io_npages >= 1,
796 ("%s: npages not positive", __func__));
799 npages = imin(BLIST_MAX_ALLOC, mpages);
800 mtx_lock(&sw_dev_mtx);
802 while (!TAILQ_EMPTY(&swtailq)) {
804 sp = TAILQ_FIRST(&swtailq);
805 if ((sp->sw_flags & SW_CLOSING) == 0)
806 blk = blist_alloc(sp->sw_blist, &npages, mpages);
807 if (blk != SWAPBLK_NONE)
809 sp = TAILQ_NEXT(sp, sw_list);
817 if (blk != SWAPBLK_NONE) {
820 sp->sw_used += npages;
821 swap_pager_avail -= npages;
823 swdevhd = TAILQ_NEXT(sp, sw_list);
825 if (swap_pager_full != 2) {
826 printf("swp_pager_getswapspace(%d): failed\n",
829 swap_pager_almost_full = 1;
833 mtx_unlock(&sw_dev_mtx);
838 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
841 return (blk >= sp->sw_first && blk < sp->sw_end);
845 swp_pager_strategy(struct buf *bp)
849 mtx_lock(&sw_dev_mtx);
850 TAILQ_FOREACH(sp, &swtailq, sw_list) {
851 if (swp_pager_isondev(bp->b_blkno, sp)) {
852 mtx_unlock(&sw_dev_mtx);
853 if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
854 unmapped_buf_allowed) {
855 bp->b_data = unmapped_buf;
858 pmap_qenter((vm_offset_t)bp->b_data,
859 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
861 sp->sw_strategy(bp, sp);
865 panic("Swapdev not found");
869 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
871 * This routine returns the specified swap blocks back to the bitmap.
873 * This routine may not sleep.
876 swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
882 mtx_lock(&sw_dev_mtx);
883 TAILQ_FOREACH(sp, &swtailq, sw_list) {
884 if (swp_pager_isondev(blk, sp)) {
885 sp->sw_used -= npages;
887 * If we are attempting to stop swapping on
888 * this device, we don't want to mark any
889 * blocks free lest they be reused.
891 if ((sp->sw_flags & SW_CLOSING) == 0) {
892 blist_free(sp->sw_blist, blk - sp->sw_first,
894 swap_pager_avail += npages;
897 mtx_unlock(&sw_dev_mtx);
901 panic("Swapdev not found");
905 * SYSCTL_SWAP_FRAGMENTATION() - produce raw swap space stats
908 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
915 error = sysctl_wire_old_buffer(req, 0);
918 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
919 mtx_lock(&sw_dev_mtx);
920 TAILQ_FOREACH(sp, &swtailq, sw_list) {
921 if (vn_isdisk(sp->sw_vp))
922 devname = devtoname(sp->sw_vp->v_rdev);
925 sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
926 blist_stats(sp->sw_blist, &sbuf);
928 mtx_unlock(&sw_dev_mtx);
929 error = sbuf_finish(&sbuf);
935 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
936 * range within an object.
938 * This is a globally accessible routine.
940 * This routine removes swapblk assignments from swap metadata.
942 * The external callers of this routine typically have already destroyed
943 * or renamed vm_page_t's associated with this range in the object so
946 * The object must be locked.
949 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
952 swp_pager_meta_free(object, start, size);
956 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
958 * Assigns swap blocks to the specified range within the object. The
959 * swap blocks are not zeroed. Any previous swap assignment is destroyed.
961 * Returns 0 on success, -1 on failure.
964 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
966 daddr_t addr, blk, n_free, s_free;
969 swp_pager_init_freerange(&s_free, &n_free);
970 VM_OBJECT_WLOCK(object);
971 for (i = 0; i < size; i += n) {
973 blk = swp_pager_getswapspace(&n);
974 if (blk == SWAPBLK_NONE) {
975 swp_pager_meta_free(object, start, i);
976 VM_OBJECT_WUNLOCK(object);
979 for (j = 0; j < n; ++j) {
980 addr = swp_pager_meta_build(object,
981 start + i + j, blk + j);
982 if (addr != SWAPBLK_NONE)
983 swp_pager_update_freerange(&s_free, &n_free,
987 swp_pager_freeswapspace(s_free, n_free);
988 VM_OBJECT_WUNLOCK(object);
993 swp_pager_xfer_source(vm_object_t srcobject, vm_object_t dstobject,
994 vm_pindex_t pindex, daddr_t addr)
998 KASSERT(srcobject->type == OBJT_SWAP,
999 ("%s: Srcobject not swappable", __func__));
1000 if (dstobject->type == OBJT_SWAP &&
1001 swp_pager_meta_lookup(dstobject, pindex) != SWAPBLK_NONE) {
1002 /* Caller should destroy the source block. */
1007 * Destination has no swapblk and is not resident, transfer source.
1008 * swp_pager_meta_build() can sleep.
1010 VM_OBJECT_WUNLOCK(srcobject);
1011 dstaddr = swp_pager_meta_build(dstobject, pindex, addr);
1012 KASSERT(dstaddr == SWAPBLK_NONE,
1013 ("Unexpected destination swapblk"));
1014 VM_OBJECT_WLOCK(srcobject);
1020 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
1021 * and destroy the source.
1023 * Copy any valid swapblks from the source to the destination. In
1024 * cases where both the source and destination have a valid swapblk,
1025 * we keep the destination's.
1027 * This routine is allowed to sleep. It may sleep allocating metadata
1028 * indirectly through swp_pager_meta_build().
1030 * The source object contains no vm_page_t's (which is just as well)
1032 * The source object is of type OBJT_SWAP.
1034 * The source and destination objects must be locked.
1035 * Both object locks may temporarily be released.
1038 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
1039 vm_pindex_t offset, int destroysource)
1042 VM_OBJECT_ASSERT_WLOCKED(srcobject);
1043 VM_OBJECT_ASSERT_WLOCKED(dstobject);
1046 * If destroysource is set, we remove the source object from the
1047 * swap_pager internal queue now.
1049 if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
1050 srcobject->handle != NULL) {
1051 VM_OBJECT_WUNLOCK(srcobject);
1052 VM_OBJECT_WUNLOCK(dstobject);
1053 sx_xlock(&sw_alloc_sx);
1054 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1056 sx_xunlock(&sw_alloc_sx);
1057 VM_OBJECT_WLOCK(dstobject);
1058 VM_OBJECT_WLOCK(srcobject);
1062 * Transfer source to destination.
1064 swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size);
1067 * Free left over swap blocks in source.
1069 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
1070 * double-remove the object from the swap queues.
1072 if (destroysource) {
1073 swp_pager_meta_free_all(srcobject);
1075 * Reverting the type is not necessary, the caller is going
1076 * to destroy srcobject directly, but I'm doing it here
1077 * for consistency since we've removed the object from its
1080 srcobject->type = OBJT_DEFAULT;
1085 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
1086 * the requested page.
1088 * We determine whether good backing store exists for the requested
1089 * page and return TRUE if it does, FALSE if it doesn't.
1091 * If TRUE, we also try to determine how much valid, contiguous backing
1092 * store exists before and after the requested page.
1095 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1101 VM_OBJECT_ASSERT_LOCKED(object);
1102 KASSERT(object->type == OBJT_SWAP,
1103 ("%s: object not swappable", __func__));
1106 * do we have good backing store at the requested index ?
1108 blk0 = swp_pager_meta_lookup(object, pindex);
1109 if (blk0 == SWAPBLK_NONE) {
1118 * find backwards-looking contiguous good backing store
1120 if (before != NULL) {
1121 for (i = 1; i < SWB_NPAGES; i++) {
1124 blk = swp_pager_meta_lookup(object, pindex - i);
1125 if (blk != blk0 - i)
1132 * find forward-looking contiguous good backing store
1134 if (after != NULL) {
1135 for (i = 1; i < SWB_NPAGES; i++) {
1136 blk = swp_pager_meta_lookup(object, pindex + i);
1137 if (blk != blk0 + i)
1146 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1148 * This removes any associated swap backing store, whether valid or
1149 * not, from the page.
1151 * This routine is typically called when a page is made dirty, at
1152 * which point any associated swap can be freed. MADV_FREE also
1153 * calls us in a special-case situation
1155 * NOTE!!! If the page is clean and the swap was valid, the caller
1156 * should make the page dirty before calling this routine. This routine
1157 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1160 * This routine may not sleep.
1162 * The object containing the page may be locked.
1165 swap_pager_unswapped(vm_page_t m)
1171 * Handle enqueing deferred frees first. If we do not have the
1172 * object lock we wait for the page daemon to clear the space.
1175 if (!VM_OBJECT_WOWNED(obj)) {
1176 VM_PAGE_OBJECT_BUSY_ASSERT(m);
1178 * The caller is responsible for synchronization but we
1179 * will harmlessly handle races. This is typically provided
1180 * by only calling unswapped() when a page transitions from
1183 if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1185 vm_page_aflag_set(m, PGA_SWAP_FREE);
1186 counter_u64_add(swap_free_deferred, 1);
1190 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1191 counter_u64_add(swap_free_completed, 1);
1192 vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
1195 * The meta data only exists if the object is OBJT_SWAP
1196 * and even then might not be allocated yet.
1198 KASSERT(m->object->type == OBJT_SWAP,
1199 ("Free object not swappable"));
1201 sb = SWAP_PCTRIE_LOOKUP(&m->object->un_pager.swp.swp_blks,
1202 rounddown(m->pindex, SWAP_META_PAGES));
1205 if (sb->d[m->pindex % SWAP_META_PAGES] == SWAPBLK_NONE)
1207 swp_pager_freeswapspace(sb->d[m->pindex % SWAP_META_PAGES], 1);
1208 sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
1209 swp_pager_free_empty_swblk(m->object, sb);
1213 * swap_pager_getpages() - bring pages in from swap
1215 * Attempt to page in the pages in array "ma" of length "count". The
1216 * caller may optionally specify that additional pages preceding and
1217 * succeeding the specified range be paged in. The number of such pages
1218 * is returned in the "rbehind" and "rahead" parameters, and they will
1219 * be in the inactive queue upon return.
1221 * The pages in "ma" must be busied and will remain busied upon return.
1224 swap_pager_getpages_locked(vm_object_t object, vm_page_t *ma, int count,
1225 int *rbehind, int *rahead)
1228 vm_page_t bm, mpred, msucc, p;
1231 int i, maxahead, maxbehind, reqcount;
1233 VM_OBJECT_ASSERT_WLOCKED(object);
1236 KASSERT(object->type == OBJT_SWAP,
1237 ("%s: object not swappable", __func__));
1238 if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead)) {
1239 VM_OBJECT_WUNLOCK(object);
1240 return (VM_PAGER_FAIL);
1243 KASSERT(reqcount - 1 <= maxahead,
1244 ("page count %d extends beyond swap block", reqcount));
1247 * Do not transfer any pages other than those that are xbusied
1248 * when running during a split or collapse operation. This
1249 * prevents clustering from re-creating pages which are being
1250 * moved into another object.
1252 if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
1253 maxahead = reqcount - 1;
1258 * Clip the readahead and readbehind ranges to exclude resident pages.
1260 if (rahead != NULL) {
1261 *rahead = imin(*rahead, maxahead - (reqcount - 1));
1262 pindex = ma[reqcount - 1]->pindex;
1263 msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1264 if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1265 *rahead = msucc->pindex - pindex - 1;
1267 if (rbehind != NULL) {
1268 *rbehind = imin(*rbehind, maxbehind);
1269 pindex = ma[0]->pindex;
1270 mpred = TAILQ_PREV(ma[0], pglist, listq);
1271 if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1272 *rbehind = pindex - mpred->pindex - 1;
1276 for (i = 0; i < count; i++)
1277 ma[i]->oflags |= VPO_SWAPINPROG;
1280 * Allocate readahead and readbehind pages.
1282 if (rbehind != NULL) {
1283 for (i = 1; i <= *rbehind; i++) {
1284 p = vm_page_alloc(object, ma[0]->pindex - i,
1288 p->oflags |= VPO_SWAPINPROG;
1293 if (rahead != NULL) {
1294 for (i = 0; i < *rahead; i++) {
1295 p = vm_page_alloc(object,
1296 ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1299 p->oflags |= VPO_SWAPINPROG;
1303 if (rbehind != NULL)
1308 vm_object_pip_add(object, count);
1310 pindex = bm->pindex;
1311 blk = swp_pager_meta_lookup(object, pindex);
1312 KASSERT(blk != SWAPBLK_NONE,
1313 ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1315 VM_OBJECT_WUNLOCK(object);
1316 bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1317 /* Pages cannot leave the object while busy. */
1318 for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1319 MPASS(p->pindex == bm->pindex + i);
1323 bp->b_flags |= B_PAGING;
1324 bp->b_iocmd = BIO_READ;
1325 bp->b_iodone = swp_pager_async_iodone;
1326 bp->b_rcred = crhold(thread0.td_ucred);
1327 bp->b_wcred = crhold(thread0.td_ucred);
1329 bp->b_bcount = PAGE_SIZE * count;
1330 bp->b_bufsize = PAGE_SIZE * count;
1331 bp->b_npages = count;
1332 bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1333 bp->b_pgafter = rahead != NULL ? *rahead : 0;
1335 VM_CNT_INC(v_swapin);
1336 VM_CNT_ADD(v_swappgsin, count);
1339 * perform the I/O. NOTE!!! bp cannot be considered valid after
1340 * this point because we automatically release it on completion.
1341 * Instead, we look at the one page we are interested in which we
1342 * still hold a lock on even through the I/O completion.
1344 * The other pages in our ma[] array are also released on completion,
1345 * so we cannot assume they are valid anymore either.
1347 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1350 swp_pager_strategy(bp);
1353 * Wait for the pages we want to complete. VPO_SWAPINPROG is always
1354 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1355 * is set in the metadata for each page in the request.
1357 VM_OBJECT_WLOCK(object);
1358 /* This could be implemented more efficiently with aflags */
1359 while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
1360 ma[0]->oflags |= VPO_SWAPSLEEP;
1361 VM_CNT_INC(v_intrans);
1362 if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1363 "swread", hz * 20)) {
1365 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1366 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1369 VM_OBJECT_WUNLOCK(object);
1372 * If we had an unrecoverable read error pages will not be valid.
1374 for (i = 0; i < reqcount; i++)
1375 if (ma[i]->valid != VM_PAGE_BITS_ALL)
1376 return (VM_PAGER_ERROR);
1378 return (VM_PAGER_OK);
1381 * A final note: in a low swap situation, we cannot deallocate swap
1382 * and mark a page dirty here because the caller is likely to mark
1383 * the page clean when we return, causing the page to possibly revert
1384 * to all-zero's later.
1389 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count,
1390 int *rbehind, int *rahead)
1393 VM_OBJECT_WLOCK(object);
1394 return (swap_pager_getpages_locked(object, ma, count, rbehind, rahead));
1398 * swap_pager_getpages_async():
1400 * Right now this is emulation of asynchronous operation on top of
1401 * swap_pager_getpages().
1404 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1405 int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1409 r = swap_pager_getpages(object, ma, count, rbehind, rahead);
1414 case VM_PAGER_ERROR:
1421 panic("unhandled swap_pager_getpages() error %d", r);
1423 (iodone)(arg, ma, count, error);
1429 * swap_pager_putpages:
1431 * Assign swap (if necessary) and initiate I/O on the specified pages.
1433 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1434 * are automatically converted to SWAP objects.
1436 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1437 * vm_page reservation system coupled with properly written VFS devices
1438 * should ensure that no low-memory deadlock occurs. This is an area
1441 * The parent has N vm_object_pip_add() references prior to
1442 * calling us and will remove references for rtvals[] that are
1443 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1446 * The parent has soft-busy'd the pages it passes us and will unbusy
1447 * those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
1448 * We need to unbusy the rest on I/O completion.
1451 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1452 int flags, int *rtvals)
1455 daddr_t addr, blk, n_free, s_free;
1460 KASSERT(count == 0 || ma[0]->object == object,
1461 ("%s: object mismatch %p/%p",
1462 __func__, object, ma[0]->object));
1467 * Turn object into OBJT_SWAP. Force sync if not a pageout process.
1469 if (object->type != OBJT_SWAP) {
1470 addr = swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1471 KASSERT(addr == SWAPBLK_NONE,
1472 ("unexpected object swap block"));
1474 VM_OBJECT_WUNLOCK(object);
1475 async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
1476 swp_pager_init_freerange(&s_free, &n_free);
1481 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1482 * The page is left dirty until the pageout operation completes
1485 for (i = 0; i < count; i += n) {
1486 /* Maximum I/O size is limited by maximum swap block size. */
1487 n = min(count - i, nsw_cluster_max);
1490 mtx_lock(&swbuf_mtx);
1491 while (nsw_wcount_async == 0)
1492 msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1495 mtx_unlock(&swbuf_mtx);
1498 /* Get a block of swap of size up to size n. */
1499 VM_OBJECT_WLOCK(object);
1500 blk = swp_pager_getswapspace(&n);
1501 if (blk == SWAPBLK_NONE) {
1502 VM_OBJECT_WUNLOCK(object);
1503 mtx_lock(&swbuf_mtx);
1504 if (++nsw_wcount_async == 1)
1505 wakeup(&nsw_wcount_async);
1506 mtx_unlock(&swbuf_mtx);
1507 for (j = 0; j < n; ++j)
1508 rtvals[i + j] = VM_PAGER_FAIL;
1511 for (j = 0; j < n; ++j) {
1513 vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1514 addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1516 if (addr != SWAPBLK_NONE)
1517 swp_pager_update_freerange(&s_free, &n_free,
1519 MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1520 mreq->oflags |= VPO_SWAPINPROG;
1522 VM_OBJECT_WUNLOCK(object);
1524 bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1526 bp->b_flags = B_ASYNC;
1527 bp->b_flags |= B_PAGING;
1528 bp->b_iocmd = BIO_WRITE;
1530 bp->b_rcred = crhold(thread0.td_ucred);
1531 bp->b_wcred = crhold(thread0.td_ucred);
1532 bp->b_bcount = PAGE_SIZE * n;
1533 bp->b_bufsize = PAGE_SIZE * n;
1535 for (j = 0; j < n; j++)
1536 bp->b_pages[j] = ma[i + j];
1540 * Must set dirty range for NFS to work.
1543 bp->b_dirtyend = bp->b_bcount;
1545 VM_CNT_INC(v_swapout);
1546 VM_CNT_ADD(v_swappgsout, bp->b_npages);
1549 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1550 * can call the async completion routine at the end of a
1551 * synchronous I/O operation. Otherwise, our caller would
1552 * perform duplicate unbusy and wakeup operations on the page
1553 * and object, respectively.
1555 for (j = 0; j < n; j++)
1556 rtvals[i + j] = VM_PAGER_PEND;
1561 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1564 bp->b_iodone = swp_pager_async_iodone;
1566 swp_pager_strategy(bp);
1573 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1575 bp->b_iodone = bdone;
1576 swp_pager_strategy(bp);
1579 * Wait for the sync I/O to complete.
1581 bwait(bp, PVM, "swwrt");
1584 * Now that we are through with the bp, we can call the
1585 * normal async completion, which frees everything up.
1587 swp_pager_async_iodone(bp);
1589 swp_pager_freeswapspace(s_free, n_free);
1590 VM_OBJECT_WLOCK(object);
1594 * swp_pager_async_iodone:
1596 * Completion routine for asynchronous reads and writes from/to swap.
1597 * Also called manually by synchronous code to finish up a bp.
1599 * This routine may not sleep.
1602 swp_pager_async_iodone(struct buf *bp)
1605 vm_object_t object = NULL;
1608 * Report error - unless we ran out of memory, in which case
1609 * we've already logged it in swapgeom_strategy().
1611 if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
1613 "swap_pager: I/O error - %s failed; blkno %ld,"
1614 "size %ld, error %d\n",
1615 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1623 * remove the mapping for kernel virtual
1626 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1628 bp->b_data = bp->b_kvabase;
1631 object = bp->b_pages[0]->object;
1632 VM_OBJECT_WLOCK(object);
1636 * cleanup pages. If an error occurs writing to swap, we are in
1637 * very serious trouble. If it happens to be a disk error, though,
1638 * we may be able to recover by reassigning the swap later on. So
1639 * in this case we remove the m->swapblk assignment for the page
1640 * but do not free it in the rlist. The errornous block(s) are thus
1641 * never reallocated as swap. Redirty the page and continue.
1643 for (i = 0; i < bp->b_npages; ++i) {
1644 vm_page_t m = bp->b_pages[i];
1646 m->oflags &= ~VPO_SWAPINPROG;
1647 if (m->oflags & VPO_SWAPSLEEP) {
1648 m->oflags &= ~VPO_SWAPSLEEP;
1649 wakeup(&object->handle);
1652 /* We always have space after I/O, successful or not. */
1653 vm_page_aflag_set(m, PGA_SWAP_SPACE);
1655 if (bp->b_ioflags & BIO_ERROR) {
1657 * If an error occurs I'd love to throw the swapblk
1658 * away without freeing it back to swapspace, so it
1659 * can never be used again. But I can't from an
1662 if (bp->b_iocmd == BIO_READ) {
1664 * NOTE: for reads, m->dirty will probably
1665 * be overridden by the original caller of
1666 * getpages so don't play cute tricks here.
1671 * If a write error occurs, reactivate page
1672 * so it doesn't clog the inactive list,
1673 * then finish the I/O.
1675 MPASS(m->dirty == VM_PAGE_BITS_ALL);
1677 /* PQ_UNSWAPPABLE? */
1678 vm_page_activate(m);
1681 } else if (bp->b_iocmd == BIO_READ) {
1683 * NOTE: for reads, m->dirty will probably be
1684 * overridden by the original caller of getpages so
1685 * we cannot set them in order to free the underlying
1686 * swap in a low-swap situation. I don't think we'd
1687 * want to do that anyway, but it was an optimization
1688 * that existed in the old swapper for a time before
1689 * it got ripped out due to precisely this problem.
1691 KASSERT(!pmap_page_is_mapped(m),
1692 ("swp_pager_async_iodone: page %p is mapped", m));
1693 KASSERT(m->dirty == 0,
1694 ("swp_pager_async_iodone: page %p is dirty", m));
1697 if (i < bp->b_pgbefore ||
1698 i >= bp->b_npages - bp->b_pgafter)
1699 vm_page_readahead_finish(m);
1702 * For write success, clear the dirty
1703 * status, then finish the I/O ( which decrements the
1704 * busy count and possibly wakes waiter's up ).
1705 * A page is only written to swap after a period of
1706 * inactivity. Therefore, we do not expect it to be
1709 KASSERT(!pmap_page_is_write_mapped(m),
1710 ("swp_pager_async_iodone: page %p is not write"
1713 vm_page_deactivate_noreuse(m);
1719 * adjust pip. NOTE: the original parent may still have its own
1720 * pip refs on the object.
1722 if (object != NULL) {
1723 vm_object_pip_wakeupn(object, bp->b_npages);
1724 VM_OBJECT_WUNLOCK(object);
1728 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1729 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1730 * trigger a KASSERT in relpbuf().
1734 bp->b_bufobj = NULL;
1737 * release the physical I/O buffer
1739 if (bp->b_flags & B_ASYNC) {
1740 mtx_lock(&swbuf_mtx);
1741 if (++nsw_wcount_async == 1)
1742 wakeup(&nsw_wcount_async);
1743 mtx_unlock(&swbuf_mtx);
1745 uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
1749 swap_pager_nswapdev(void)
1756 swp_pager_force_dirty(vm_page_t m)
1760 swap_pager_unswapped(m);
1765 * swap_pager_swapoff_object:
1767 * Page in all of the pages that have been paged out for an object
1771 swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
1777 int i, nv, rahead, rv;
1779 KASSERT(object->type == OBJT_SWAP,
1780 ("%s: Object not swappable", __func__));
1782 for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1783 &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1784 if ((object->flags & OBJ_DEAD) != 0) {
1786 * Make sure that pending writes finish before
1789 vm_object_pip_wait(object, "swpoff");
1790 swp_pager_meta_free_all(object);
1793 for (i = 0; i < SWAP_META_PAGES; i++) {
1795 * Count the number of contiguous valid blocks.
1797 for (nv = 0; nv < SWAP_META_PAGES - i; nv++) {
1798 blk = sb->d[i + nv];
1799 if (!swp_pager_isondev(blk, sp) ||
1800 blk == SWAPBLK_NONE)
1807 * Look for a page corresponding to the first
1808 * valid block and ensure that any pending paging
1809 * operations on it are complete. If the page is valid,
1810 * mark it dirty and free the swap block. Try to batch
1811 * this operation since it may cause sp to be freed,
1812 * meaning that we must restart the scan. Avoid busying
1813 * valid pages since we may block forever on kernel
1816 m = vm_page_lookup(object, sb->p + i);
1818 m = vm_page_alloc(object, sb->p + i,
1819 VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
1823 if ((m->oflags & VPO_SWAPINPROG) != 0) {
1824 m->oflags |= VPO_SWAPSLEEP;
1825 VM_OBJECT_SLEEP(object, &object->handle,
1829 if (vm_page_all_valid(m)) {
1831 swp_pager_force_dirty(m);
1832 } while (--nv > 0 &&
1833 (m = vm_page_next(m)) != NULL &&
1834 vm_page_all_valid(m) &&
1835 (m->oflags & VPO_SWAPINPROG) == 0);
1838 if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL))
1842 vm_object_pip_add(object, 1);
1843 rahead = SWAP_META_PAGES;
1844 rv = swap_pager_getpages_locked(object, &m, 1, NULL,
1846 if (rv != VM_PAGER_OK)
1847 panic("%s: read from swap failed: %d",
1849 vm_object_pip_wakeupn(object, 1);
1850 VM_OBJECT_WLOCK(object);
1854 * The object lock was dropped so we must restart the
1855 * scan of this swap block. Pages paged in during this
1856 * iteration will be marked dirty in a future iteration.
1860 if (i == SWAP_META_PAGES)
1861 pi = sb->p + SWAP_META_PAGES;
1866 * swap_pager_swapoff:
1868 * Page in all of the pages that have been paged out to the
1869 * given device. The corresponding blocks in the bitmap must be
1870 * marked as allocated and the device must be flagged SW_CLOSING.
1871 * There may be no processes swapped out to the device.
1873 * This routine may block.
1876 swap_pager_swapoff(struct swdevt *sp)
1881 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1885 mtx_lock(&vm_object_list_mtx);
1886 TAILQ_FOREACH(object, &vm_object_list, object_list) {
1887 if (object->type != OBJT_SWAP)
1889 mtx_unlock(&vm_object_list_mtx);
1890 /* Depends on type-stability. */
1891 VM_OBJECT_WLOCK(object);
1894 * Dead objects are eventually terminated on their own.
1896 if ((object->flags & OBJ_DEAD) != 0)
1900 * Sync with fences placed after pctrie
1901 * initialization. We must not access pctrie below
1902 * unless we checked that our object is swap and not
1905 atomic_thread_fence_acq();
1906 if (object->type != OBJT_SWAP)
1909 swap_pager_swapoff_object(sp, object);
1911 VM_OBJECT_WUNLOCK(object);
1912 mtx_lock(&vm_object_list_mtx);
1914 mtx_unlock(&vm_object_list_mtx);
1918 * Objects may be locked or paging to the device being
1919 * removed, so we will miss their pages and need to
1920 * make another pass. We have marked this device as
1921 * SW_CLOSING, so the activity should finish soon.
1924 if (retries > 100) {
1925 panic("swapoff: failed to locate %d swap blocks",
1928 pause("swpoff", hz / 20);
1931 EVENTHANDLER_INVOKE(swapoff, sp);
1934 /************************************************************************
1936 ************************************************************************
1938 * These routines manipulate the swap metadata stored in the
1941 * Swap metadata is implemented with a global hash and not directly
1942 * linked into the object. Instead the object simply contains
1943 * appropriate tracking counters.
1947 * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
1950 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
1954 MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
1955 for (i = start; i < limit; i++) {
1956 if (sb->d[i] != SWAPBLK_NONE)
1963 * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
1965 * Nothing is done if the block is still in use.
1968 swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
1971 if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
1972 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
1973 uma_zfree(swblk_zone, sb);
1978 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
1980 * We first convert the object to a swap object if it is a default
1983 * The specified swapblk is added to the object's swap metadata. If
1984 * the swapblk is not valid, it is freed instead. Any previously
1985 * assigned swapblk is returned.
1988 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
1990 static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
1991 struct swblk *sb, *sb1;
1992 vm_pindex_t modpi, rdpi;
1993 daddr_t prev_swapblk;
1996 VM_OBJECT_ASSERT_WLOCKED(object);
1999 * Convert default object to swap object if necessary
2001 if (object->type != OBJT_SWAP) {
2002 pctrie_init(&object->un_pager.swp.swp_blks);
2005 * Ensure that swap_pager_swapoff()'s iteration over
2006 * object_list does not see a garbage pctrie.
2008 atomic_thread_fence_rel();
2010 object->type = OBJT_SWAP;
2011 object->un_pager.swp.writemappings = 0;
2012 KASSERT((object->flags & OBJ_ANON) != 0 ||
2013 object->handle == NULL,
2014 ("default pager %p with handle %p",
2015 object, object->handle));
2018 rdpi = rounddown(pindex, SWAP_META_PAGES);
2019 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
2021 if (swapblk == SWAPBLK_NONE)
2022 return (SWAPBLK_NONE);
2024 sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
2025 pageproc ? M_USE_RESERVE : 0));
2028 for (i = 0; i < SWAP_META_PAGES; i++)
2029 sb->d[i] = SWAPBLK_NONE;
2030 if (atomic_cmpset_int(&swblk_zone_exhausted,
2032 printf("swblk zone ok\n");
2035 VM_OBJECT_WUNLOCK(object);
2036 if (uma_zone_exhausted(swblk_zone)) {
2037 if (atomic_cmpset_int(&swblk_zone_exhausted,
2039 printf("swap blk zone exhausted, "
2040 "increase kern.maxswzone\n");
2041 vm_pageout_oom(VM_OOM_SWAPZ);
2042 pause("swzonxb", 10);
2044 uma_zwait(swblk_zone);
2045 VM_OBJECT_WLOCK(object);
2046 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2050 * Somebody swapped out a nearby page,
2051 * allocating swblk at the rdpi index,
2052 * while we dropped the object lock.
2057 error = SWAP_PCTRIE_INSERT(
2058 &object->un_pager.swp.swp_blks, sb);
2060 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2062 printf("swpctrie zone ok\n");
2065 VM_OBJECT_WUNLOCK(object);
2066 if (uma_zone_exhausted(swpctrie_zone)) {
2067 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2069 printf("swap pctrie zone exhausted, "
2070 "increase kern.maxswzone\n");
2071 vm_pageout_oom(VM_OOM_SWAPZ);
2072 pause("swzonxp", 10);
2074 uma_zwait(swpctrie_zone);
2075 VM_OBJECT_WLOCK(object);
2076 sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2079 uma_zfree(swblk_zone, sb);
2086 MPASS(sb->p == rdpi);
2088 modpi = pindex % SWAP_META_PAGES;
2089 /* Return prior contents of metadata. */
2090 prev_swapblk = sb->d[modpi];
2091 /* Enter block into metadata. */
2092 sb->d[modpi] = swapblk;
2095 * Free the swblk if we end up with the empty page run.
2097 if (swapblk == SWAPBLK_NONE)
2098 swp_pager_free_empty_swblk(object, sb);
2099 return (prev_swapblk);
2103 * SWP_PAGER_META_TRANSFER() - free a range of blocks in the srcobject's swap
2104 * metadata, or transfer it into dstobject.
2106 * This routine will free swap metadata structures as they are cleaned
2110 swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
2111 vm_pindex_t pindex, vm_pindex_t count)
2114 daddr_t n_free, s_free;
2115 vm_pindex_t offset, last;
2116 int i, limit, start;
2118 VM_OBJECT_ASSERT_WLOCKED(srcobject);
2119 if (srcobject->type != OBJT_SWAP || count == 0)
2122 swp_pager_init_freerange(&s_free, &n_free);
2124 last = pindex + count;
2126 sb = SWAP_PCTRIE_LOOKUP_GE(&srcobject->un_pager.swp.swp_blks,
2127 rounddown(pindex, SWAP_META_PAGES));
2128 if (sb == NULL || sb->p >= last)
2130 start = pindex > sb->p ? pindex - sb->p : 0;
2131 limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2133 for (i = start; i < limit; i++) {
2134 if (sb->d[i] == SWAPBLK_NONE)
2136 if (dstobject == NULL ||
2137 !swp_pager_xfer_source(srcobject, dstobject,
2138 sb->p + i - offset, sb->d[i])) {
2139 swp_pager_update_freerange(&s_free, &n_free,
2142 sb->d[i] = SWAPBLK_NONE;
2144 pindex = sb->p + SWAP_META_PAGES;
2145 if (swp_pager_swblk_empty(sb, 0, start) &&
2146 swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2147 SWAP_PCTRIE_REMOVE(&srcobject->un_pager.swp.swp_blks,
2149 uma_zfree(swblk_zone, sb);
2152 swp_pager_freeswapspace(s_free, n_free);
2156 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
2158 * The requested range of blocks is freed, with any associated swap
2159 * returned to the swap bitmap.
2161 * This routine will free swap metadata structures as they are cleaned
2162 * out. This routine does *NOT* operate on swap metadata associated
2163 * with resident pages.
2166 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count)
2168 swp_pager_meta_transfer(object, NULL, pindex, count);
2172 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
2174 * This routine locates and destroys all swap metadata associated with
2178 swp_pager_meta_free_all(vm_object_t object)
2181 daddr_t n_free, s_free;
2185 VM_OBJECT_ASSERT_WLOCKED(object);
2186 if (object->type != OBJT_SWAP)
2189 swp_pager_init_freerange(&s_free, &n_free);
2190 for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
2191 &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
2192 pindex = sb->p + SWAP_META_PAGES;
2193 for (i = 0; i < SWAP_META_PAGES; i++) {
2194 if (sb->d[i] == SWAPBLK_NONE)
2196 swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
2198 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2199 uma_zfree(swblk_zone, sb);
2201 swp_pager_freeswapspace(s_free, n_free);
2205 * SWP_PAGER_METACTL() - misc control of swap meta data.
2207 * This routine is capable of looking up, or removing swapblk
2208 * assignments in the swap meta data. It returns the swapblk being
2209 * looked-up, popped, or SWAPBLK_NONE if the block was invalid.
2211 * When acting on a busy resident page and paging is in progress, we
2212 * have to wait until paging is complete but otherwise can act on the
2216 swp_pager_meta_lookup(vm_object_t object, vm_pindex_t pindex)
2220 VM_OBJECT_ASSERT_LOCKED(object);
2223 * The meta data only exists if the object is OBJT_SWAP
2224 * and even then might not be allocated yet.
2226 KASSERT(object->type == OBJT_SWAP,
2227 ("Lookup object not swappable"));
2229 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2230 rounddown(pindex, SWAP_META_PAGES));
2232 return (SWAPBLK_NONE);
2233 return (sb->d[pindex % SWAP_META_PAGES]);
2237 * Returns the least page index which is greater than or equal to the
2238 * parameter pindex and for which there is a swap block allocated.
2239 * Returns object's size if the object's type is not swap or if there
2240 * are no allocated swap blocks for the object after the requested
2244 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2249 VM_OBJECT_ASSERT_LOCKED(object);
2250 if (object->type != OBJT_SWAP)
2251 return (object->size);
2253 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2254 rounddown(pindex, SWAP_META_PAGES));
2256 return (object->size);
2257 if (sb->p < pindex) {
2258 for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2259 if (sb->d[i] != SWAPBLK_NONE)
2262 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2263 roundup(pindex, SWAP_META_PAGES));
2265 return (object->size);
2267 for (i = 0; i < SWAP_META_PAGES; i++) {
2268 if (sb->d[i] != SWAPBLK_NONE)
2273 * We get here if a swblk is present in the trie but it
2274 * doesn't map any blocks.
2277 return (object->size);
2281 * System call swapon(name) enables swapping on device name,
2282 * which must be in the swdevsw. Return EBUSY
2283 * if already swapping on this device.
2285 #ifndef _SYS_SYSPROTO_H_
2286 struct swapon_args {
2296 sys_swapon(struct thread *td, struct swapon_args *uap)
2300 struct nameidata nd;
2303 error = priv_check(td, PRIV_SWAPON);
2307 sx_xlock(&swdev_syscall_lock);
2310 * Swap metadata may not fit in the KVM if we have physical
2313 if (swblk_zone == NULL) {
2318 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2324 NDFREE(&nd, NDF_ONLY_PNBUF);
2327 if (vn_isdisk_error(vp, &error)) {
2328 error = swapongeom(vp);
2329 } else if (vp->v_type == VREG &&
2330 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2331 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2333 * Allow direct swapping to NFS regular files in the same
2334 * way that nfs_mountroot() sets up diskless swapping.
2336 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2342 sx_xunlock(&swdev_syscall_lock);
2347 * Check that the total amount of swap currently configured does not
2348 * exceed half the theoretical maximum. If it does, print a warning
2352 swapon_check_swzone(void)
2355 /* recommend using no more than half that amount */
2356 if (swap_total > swap_maxpages / 2) {
2357 printf("warning: total configured swap (%lu pages) "
2358 "exceeds maximum recommended amount (%lu pages).\n",
2359 swap_total, swap_maxpages / 2);
2360 printf("warning: increase kern.maxswzone "
2361 "or reduce amount of swap.\n");
2366 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2367 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2369 struct swdevt *sp, *tsp;
2373 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2374 * First chop nblks off to page-align it, then convert.
2376 * sw->sw_nblks is in page-sized chunks now too.
2378 nblks &= ~(ctodb(1) - 1);
2379 nblks = dbtoc(nblks);
2381 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2382 sp->sw_blist = blist_create(nblks, M_WAITOK);
2386 sp->sw_nblks = nblks;
2388 sp->sw_strategy = strategy;
2389 sp->sw_close = close;
2390 sp->sw_flags = flags;
2393 * Do not free the first blocks in order to avoid overwriting
2394 * any bsd label at the front of the partition
2396 blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2397 nblks - howmany(BBSIZE, PAGE_SIZE));
2400 mtx_lock(&sw_dev_mtx);
2401 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2402 if (tsp->sw_end >= dvbase) {
2404 * We put one uncovered page between the devices
2405 * in order to definitively prevent any cross-device
2408 dvbase = tsp->sw_end + 1;
2411 sp->sw_first = dvbase;
2412 sp->sw_end = dvbase + nblks;
2413 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2415 swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2416 swap_total += nblks;
2417 swapon_check_swzone();
2419 mtx_unlock(&sw_dev_mtx);
2420 EVENTHANDLER_INVOKE(swapon, sp);
2424 * SYSCALL: swapoff(devname)
2426 * Disable swapping on the given device.
2428 * XXX: Badly designed system call: it should use a device index
2429 * rather than filename as specification. We keep sw_vp around
2430 * only to make this work.
2432 #ifndef _SYS_SYSPROTO_H_
2433 struct swapoff_args {
2443 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2446 struct nameidata nd;
2450 error = priv_check(td, PRIV_SWAPOFF);
2454 sx_xlock(&swdev_syscall_lock);
2456 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2461 NDFREE(&nd, NDF_ONLY_PNBUF);
2464 mtx_lock(&sw_dev_mtx);
2465 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2466 if (sp->sw_vp == vp)
2469 mtx_unlock(&sw_dev_mtx);
2474 error = swapoff_one(sp, td->td_ucred);
2476 sx_xunlock(&swdev_syscall_lock);
2481 swapoff_one(struct swdevt *sp, struct ucred *cred)
2488 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2490 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2491 error = mac_system_check_swapoff(cred, sp->sw_vp);
2492 (void) VOP_UNLOCK(sp->sw_vp);
2496 nblks = sp->sw_nblks;
2499 * We can turn off this swap device safely only if the
2500 * available virtual memory in the system will fit the amount
2501 * of data we will have to page back in, plus an epsilon so
2502 * the system doesn't become critically low on swap space.
2504 if (vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
2508 * Prevent further allocations on this device.
2510 mtx_lock(&sw_dev_mtx);
2511 sp->sw_flags |= SW_CLOSING;
2512 swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2513 swap_total -= nblks;
2514 mtx_unlock(&sw_dev_mtx);
2517 * Page in the contents of the device and close it.
2519 swap_pager_swapoff(sp);
2521 sp->sw_close(curthread, sp);
2522 mtx_lock(&sw_dev_mtx);
2524 TAILQ_REMOVE(&swtailq, sp, sw_list);
2526 if (nswapdev == 0) {
2527 swap_pager_full = 2;
2528 swap_pager_almost_full = 1;
2532 mtx_unlock(&sw_dev_mtx);
2533 blist_destroy(sp->sw_blist);
2534 free(sp, M_VMPGDATA);
2541 struct swdevt *sp, *spt;
2542 const char *devname;
2545 sx_xlock(&swdev_syscall_lock);
2547 mtx_lock(&sw_dev_mtx);
2548 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2549 mtx_unlock(&sw_dev_mtx);
2550 if (vn_isdisk(sp->sw_vp))
2551 devname = devtoname(sp->sw_vp->v_rdev);
2554 error = swapoff_one(sp, thread0.td_ucred);
2556 printf("Cannot remove swap device %s (error=%d), "
2557 "skipping.\n", devname, error);
2558 } else if (bootverbose) {
2559 printf("Swap device %s removed.\n", devname);
2561 mtx_lock(&sw_dev_mtx);
2563 mtx_unlock(&sw_dev_mtx);
2565 sx_xunlock(&swdev_syscall_lock);
2569 swap_pager_status(int *total, int *used)
2572 *total = swap_total;
2573 *used = swap_total - swap_pager_avail -
2574 nswapdev * howmany(BBSIZE, PAGE_SIZE);
2578 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2581 const char *tmp_devname;
2586 mtx_lock(&sw_dev_mtx);
2587 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2592 xs->xsw_version = XSWDEV_VERSION;
2593 xs->xsw_dev = sp->sw_dev;
2594 xs->xsw_flags = sp->sw_flags;
2595 xs->xsw_nblks = sp->sw_nblks;
2596 xs->xsw_used = sp->sw_used;
2597 if (devname != NULL) {
2598 if (vn_isdisk(sp->sw_vp))
2599 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2601 tmp_devname = "[file]";
2602 strncpy(devname, tmp_devname, len);
2607 mtx_unlock(&sw_dev_mtx);
2611 #if defined(COMPAT_FREEBSD11)
2612 #define XSWDEV_VERSION_11 1
2622 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2625 u_int xsw_dev1, xsw_dev2;
2633 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2636 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2637 struct xswdev32 xs32;
2639 #if defined(COMPAT_FREEBSD11)
2640 struct xswdev11 xs11;
2644 if (arg2 != 1) /* name length */
2646 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2649 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2650 if (req->oldlen == sizeof(xs32)) {
2651 xs32.xsw_version = XSWDEV_VERSION;
2652 xs32.xsw_dev1 = xs.xsw_dev;
2653 xs32.xsw_dev2 = xs.xsw_dev >> 32;
2654 xs32.xsw_flags = xs.xsw_flags;
2655 xs32.xsw_nblks = xs.xsw_nblks;
2656 xs32.xsw_used = xs.xsw_used;
2657 error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2661 #if defined(COMPAT_FREEBSD11)
2662 if (req->oldlen == sizeof(xs11)) {
2663 xs11.xsw_version = XSWDEV_VERSION_11;
2664 xs11.xsw_dev = xs.xsw_dev; /* truncation */
2665 xs11.xsw_flags = xs.xsw_flags;
2666 xs11.xsw_nblks = xs.xsw_nblks;
2667 xs11.xsw_used = xs.xsw_used;
2668 error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2672 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2676 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2677 "Number of swap devices");
2678 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2679 sysctl_vm_swap_info,
2680 "Swap statistics by device");
2683 * Count the approximate swap usage in pages for a vmspace. The
2684 * shadowed or not yet copied on write swap blocks are not accounted.
2685 * The map must be locked.
2688 vmspace_swap_count(struct vmspace *vmspace)
2698 map = &vmspace->vm_map;
2701 VM_MAP_ENTRY_FOREACH(cur, map) {
2702 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2704 object = cur->object.vm_object;
2705 if (object == NULL || object->type != OBJT_SWAP)
2707 VM_OBJECT_RLOCK(object);
2708 if (object->type != OBJT_SWAP)
2710 pi = OFF_TO_IDX(cur->offset);
2711 e = pi + OFF_TO_IDX(cur->end - cur->start);
2712 for (;; pi = sb->p + SWAP_META_PAGES) {
2713 sb = SWAP_PCTRIE_LOOKUP_GE(
2714 &object->un_pager.swp.swp_blks, pi);
2715 if (sb == NULL || sb->p >= e)
2717 for (i = 0; i < SWAP_META_PAGES; i++) {
2718 if (sb->p + i < e &&
2719 sb->d[i] != SWAPBLK_NONE)
2724 VM_OBJECT_RUNLOCK(object);
2732 * Swapping onto disk devices.
2736 static g_orphan_t swapgeom_orphan;
2738 static struct g_class g_swap_class = {
2740 .version = G_VERSION,
2741 .orphan = swapgeom_orphan,
2744 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2747 swapgeom_close_ev(void *arg, int flags)
2749 struct g_consumer *cp;
2752 g_access(cp, -1, -1, 0);
2754 g_destroy_consumer(cp);
2758 * Add a reference to the g_consumer for an inflight transaction.
2761 swapgeom_acquire(struct g_consumer *cp)
2764 mtx_assert(&sw_dev_mtx, MA_OWNED);
2769 * Remove a reference from the g_consumer. Post a close event if all
2770 * references go away, since the function might be called from the
2774 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2777 mtx_assert(&sw_dev_mtx, MA_OWNED);
2779 if (cp->index == 0) {
2780 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2786 swapgeom_done(struct bio *bp2)
2790 struct g_consumer *cp;
2792 bp = bp2->bio_caller2;
2794 bp->b_ioflags = bp2->bio_flags;
2796 bp->b_ioflags |= BIO_ERROR;
2797 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2798 bp->b_error = bp2->bio_error;
2799 bp->b_caller1 = NULL;
2801 sp = bp2->bio_caller1;
2802 mtx_lock(&sw_dev_mtx);
2803 swapgeom_release(cp, sp);
2804 mtx_unlock(&sw_dev_mtx);
2809 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2812 struct g_consumer *cp;
2814 mtx_lock(&sw_dev_mtx);
2817 mtx_unlock(&sw_dev_mtx);
2818 bp->b_error = ENXIO;
2819 bp->b_ioflags |= BIO_ERROR;
2823 swapgeom_acquire(cp);
2824 mtx_unlock(&sw_dev_mtx);
2825 if (bp->b_iocmd == BIO_WRITE)
2828 bio = g_alloc_bio();
2830 mtx_lock(&sw_dev_mtx);
2831 swapgeom_release(cp, sp);
2832 mtx_unlock(&sw_dev_mtx);
2833 bp->b_error = ENOMEM;
2834 bp->b_ioflags |= BIO_ERROR;
2835 printf("swap_pager: cannot allocate bio\n");
2840 bp->b_caller1 = bio;
2841 bio->bio_caller1 = sp;
2842 bio->bio_caller2 = bp;
2843 bio->bio_cmd = bp->b_iocmd;
2844 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2845 bio->bio_length = bp->b_bcount;
2846 bio->bio_done = swapgeom_done;
2847 if (!buf_mapped(bp)) {
2848 bio->bio_ma = bp->b_pages;
2849 bio->bio_data = unmapped_buf;
2850 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2851 bio->bio_ma_n = bp->b_npages;
2852 bio->bio_flags |= BIO_UNMAPPED;
2854 bio->bio_data = bp->b_data;
2857 g_io_request(bio, cp);
2862 swapgeom_orphan(struct g_consumer *cp)
2867 mtx_lock(&sw_dev_mtx);
2868 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2869 if (sp->sw_id == cp) {
2870 sp->sw_flags |= SW_CLOSING;
2875 * Drop reference we were created with. Do directly since we're in a
2876 * special context where we don't have to queue the call to
2877 * swapgeom_close_ev().
2880 destroy = ((sp != NULL) && (cp->index == 0));
2883 mtx_unlock(&sw_dev_mtx);
2885 swapgeom_close_ev(cp, 0);
2889 swapgeom_close(struct thread *td, struct swdevt *sw)
2891 struct g_consumer *cp;
2893 mtx_lock(&sw_dev_mtx);
2896 mtx_unlock(&sw_dev_mtx);
2899 * swapgeom_close() may be called from the biodone context,
2900 * where we cannot perform topology changes. Delegate the
2901 * work to the events thread.
2904 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2908 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2910 struct g_provider *pp;
2911 struct g_consumer *cp;
2912 static struct g_geom *gp;
2917 pp = g_dev_getprovider(dev);
2920 mtx_lock(&sw_dev_mtx);
2921 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2923 if (cp != NULL && cp->provider == pp) {
2924 mtx_unlock(&sw_dev_mtx);
2928 mtx_unlock(&sw_dev_mtx);
2930 gp = g_new_geomf(&g_swap_class, "swap");
2931 cp = g_new_consumer(gp);
2932 cp->index = 1; /* Number of active I/Os, plus one for being active. */
2933 cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2936 * XXX: Every time you think you can improve the margin for
2937 * footshooting, somebody depends on the ability to do so:
2938 * savecore(8) wants to write to our swapdev so we cannot
2939 * set an exclusive count :-(
2941 error = g_access(cp, 1, 1, 0);
2944 g_destroy_consumer(cp);
2947 nblks = pp->mediasize / DEV_BSIZE;
2948 swaponsomething(vp, cp, nblks, swapgeom_strategy,
2949 swapgeom_close, dev2udev(dev),
2950 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
2955 swapongeom(struct vnode *vp)
2959 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2960 if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) {
2964 error = swapongeom_locked(vp->v_rdev, vp);
2965 g_topology_unlock();
2974 * This is used mainly for network filesystem (read: probably only tested
2975 * with NFS) swapfiles.
2980 swapdev_strategy(struct buf *bp, struct swdevt *sp)
2984 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
2988 if (bp->b_iocmd == BIO_WRITE) {
2990 bufobj_wdrop(bp->b_bufobj);
2991 bufobj_wref(&vp2->v_bufobj);
2993 if (bp->b_bufobj != &vp2->v_bufobj)
2994 bp->b_bufobj = &vp2->v_bufobj;
2996 bp->b_iooffset = dbtob(bp->b_blkno);
3002 swapdev_close(struct thread *td, struct swdevt *sp)
3005 VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
3010 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
3017 mtx_lock(&sw_dev_mtx);
3018 TAILQ_FOREACH(sp, &swtailq, sw_list) {
3019 if (sp->sw_id == vp) {
3020 mtx_unlock(&sw_dev_mtx);
3024 mtx_unlock(&sw_dev_mtx);
3026 (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3028 error = mac_system_check_swapon(td->td_ucred, vp);
3031 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
3032 (void) VOP_UNLOCK(vp);
3036 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
3042 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
3046 new = nsw_wcount_async_max;
3047 error = sysctl_handle_int(oidp, &new, 0, req);
3048 if (error != 0 || req->newptr == NULL)
3051 if (new > nswbuf / 2 || new < 1)
3054 mtx_lock(&swbuf_mtx);
3055 while (nsw_wcount_async_max != new) {
3057 * Adjust difference. If the current async count is too low,
3058 * we will need to sqeeze our update slowly in. Sleep with a
3059 * higher priority than getpbuf() to finish faster.
3061 n = new - nsw_wcount_async_max;
3062 if (nsw_wcount_async + n >= 0) {
3063 nsw_wcount_async += n;
3064 nsw_wcount_async_max += n;
3065 wakeup(&nsw_wcount_async);
3067 nsw_wcount_async_max -= nsw_wcount_async;
3068 nsw_wcount_async = 0;
3069 msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
3073 mtx_unlock(&swbuf_mtx);
3079 swap_pager_update_writecount(vm_object_t object, vm_offset_t start,
3083 VM_OBJECT_WLOCK(object);
3084 KASSERT((object->flags & OBJ_ANON) == 0,
3085 ("Splittable object with writecount"));
3086 object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
3087 VM_OBJECT_WUNLOCK(object);
3091 swap_pager_release_writecount(vm_object_t object, vm_offset_t start,
3095 VM_OBJECT_WLOCK(object);
3096 KASSERT((object->flags & OBJ_ANON) == 0,
3097 ("Splittable object with writecount"));
3098 object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
3099 VM_OBJECT_WUNLOCK(object);