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 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_t 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_t 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(vm_ooffset_t incr)
209 return (swap_reserve_by_cred(incr, curthread->td_ucred));
213 swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
215 u_long r, s, prev, pincr;
218 static struct timeval lastfail;
221 uip = cred->cr_ruidinfo;
223 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
229 error = racct_add(curproc, RACCT_SWAP, incr);
230 PROC_UNLOCK(curproc);
238 prev = atomic_fetchadd_long(&swap_reserved, pincr);
240 if (overcommit & SWAP_RESERVE_ALLOW_NONWIRED) {
241 s = vm_cnt.v_page_count - vm_cnt.v_free_reserved -
246 if ((overcommit & SWAP_RESERVE_FORCE_ON) == 0 || r <= s ||
247 (error = priv_check(curthread, PRIV_VM_SWAP_NOQUOTA)) == 0) {
250 prev = atomic_fetchadd_long(&swap_reserved, -pincr);
252 panic("swap_reserved < incr on overcommit fail");
255 prev = atomic_fetchadd_long(&uip->ui_vmsize, pincr);
256 if ((overcommit & SWAP_RESERVE_RLIMIT_ON) != 0 &&
257 prev + pincr > lim_cur(curthread, RLIMIT_SWAP) &&
258 priv_check(curthread, PRIV_VM_SWAP_NORLIMIT)) {
260 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pincr);
262 panic("uip->ui_vmsize < incr on overcommit fail");
265 if (!res && ppsratecheck(&lastfail, &curfail, 1)) {
266 printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
267 uip->ui_uid, curproc->p_pid, incr);
271 if (racct_enable && !res) {
273 racct_sub(curproc, RACCT_SWAP, incr);
274 PROC_UNLOCK(curproc);
282 swap_reserve_force(vm_ooffset_t incr)
287 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
293 racct_add_force(curproc, RACCT_SWAP, incr);
296 atomic_add_long(&swap_reserved, pincr);
297 uip = curproc->p_ucred->cr_ruidinfo;
298 atomic_add_long(&uip->ui_vmsize, pincr);
299 PROC_UNLOCK(curproc);
303 swap_release(vm_ooffset_t decr)
308 cred = curproc->p_ucred;
309 swap_release_by_cred(decr, cred);
310 PROC_UNLOCK(curproc);
314 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
319 uip = cred->cr_ruidinfo;
321 KASSERT((decr & PAGE_MASK) == 0, ("%s: decr: %ju & PAGE_MASK", __func__,
325 prev = atomic_fetchadd_long(&swap_reserved, -pdecr);
327 panic("swap_reserved < decr");
329 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pdecr);
331 printf("negative vmsize for uid = %d\n", uip->ui_uid);
334 racct_sub_cred(cred, RACCT_SWAP, decr);
338 static int swap_pager_full = 2; /* swap space exhaustion (task killing) */
339 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
340 static struct mtx swbuf_mtx; /* to sync nsw_wcount_async */
341 static int nsw_wcount_async; /* limit async write buffers */
342 static int nsw_wcount_async_max;/* assigned maximum */
343 static int nsw_cluster_max; /* maximum VOP I/O allowed */
345 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
346 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
347 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
348 "Maximum running async swap ops");
349 static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS);
350 SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD |
351 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A",
352 "Swap Fragmentation Info");
354 static struct sx sw_alloc_sx;
357 * "named" and "unnamed" anon region objects. Try to reduce the overhead
358 * of searching a named list by hashing it just a little.
363 #define NOBJLIST(handle) \
364 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
366 static struct pagerlst swap_pager_object_list[NOBJLISTS];
367 static uma_zone_t swwbuf_zone;
368 static uma_zone_t swrbuf_zone;
369 static uma_zone_t swblk_zone;
370 static uma_zone_t swpctrie_zone;
373 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
374 * calls hooked from other parts of the VM system and do not appear here.
375 * (see vm/swap_pager.h).
378 swap_pager_alloc(void *handle, vm_ooffset_t size,
379 vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
380 static void swap_pager_dealloc(vm_object_t object);
381 static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
383 static int swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
384 int *, pgo_getpages_iodone_t, void *);
385 static void swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
387 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
388 static void swap_pager_init(void);
389 static void swap_pager_unswapped(vm_page_t);
390 static void swap_pager_swapoff(struct swdevt *sp);
391 static void swap_pager_update_writecount(vm_object_t object,
392 vm_offset_t start, vm_offset_t end);
393 static void swap_pager_release_writecount(vm_object_t object,
394 vm_offset_t start, vm_offset_t end);
396 struct pagerops swappagerops = {
397 .pgo_init = swap_pager_init, /* early system initialization of pager */
398 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */
399 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
400 .pgo_getpages = swap_pager_getpages, /* pagein */
401 .pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
402 .pgo_putpages = swap_pager_putpages, /* pageout */
403 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */
404 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
405 .pgo_update_writecount = swap_pager_update_writecount,
406 .pgo_release_writecount = swap_pager_release_writecount,
410 * swap_*() routines are externally accessible. swp_*() routines are
413 static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
414 static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
416 SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
417 "Maximum size of a swap block in pages");
419 static void swp_sizecheck(void);
420 static void swp_pager_async_iodone(struct buf *bp);
421 static bool swp_pager_swblk_empty(struct swblk *sb, int start, int limit);
422 static void swp_pager_free_empty_swblk(vm_object_t, struct swblk *sb);
423 static int swapongeom(struct vnode *);
424 static int swaponvp(struct thread *, struct vnode *, u_long);
425 static int swapoff_one(struct swdevt *sp, struct ucred *cred);
428 * Swap bitmap functions
430 static void swp_pager_freeswapspace(daddr_t blk, daddr_t npages);
431 static daddr_t swp_pager_getswapspace(int *npages);
436 static daddr_t swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
437 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t);
438 static void swp_pager_meta_transfer(vm_object_t src, vm_object_t dst,
439 vm_pindex_t pindex, vm_pindex_t count);
440 static void swp_pager_meta_free_all(vm_object_t);
441 static daddr_t swp_pager_meta_lookup(vm_object_t, vm_pindex_t);
444 swp_pager_init_freerange(daddr_t *start, daddr_t *num)
447 *start = SWAPBLK_NONE;
452 swp_pager_update_freerange(daddr_t *start, daddr_t *num, daddr_t addr)
455 if (*start + *num == addr) {
458 swp_pager_freeswapspace(*start, *num);
465 swblk_trie_alloc(struct pctrie *ptree)
468 return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
469 M_USE_RESERVE : 0)));
473 swblk_trie_free(struct pctrie *ptree, void *node)
476 uma_zfree(swpctrie_zone, node);
479 PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
482 * SWP_SIZECHECK() - update swap_pager_full indication
484 * update the swap_pager_almost_full indication and warn when we are
485 * about to run out of swap space, using lowat/hiwat hysteresis.
487 * Clear swap_pager_full ( task killing ) indication when lowat is met.
489 * No restrictions on call
490 * This routine may not block.
496 if (swap_pager_avail < nswap_lowat) {
497 if (swap_pager_almost_full == 0) {
498 printf("swap_pager: out of swap space\n");
499 swap_pager_almost_full = 1;
503 if (swap_pager_avail > nswap_hiwat)
504 swap_pager_almost_full = 0;
509 * SWAP_PAGER_INIT() - initialize the swap pager!
511 * Expected to be started from system init. NOTE: This code is run
512 * before much else so be careful what you depend on. Most of the VM
513 * system has yet to be initialized at this point.
516 swap_pager_init(void)
519 * Initialize object lists
523 for (i = 0; i < NOBJLISTS; ++i)
524 TAILQ_INIT(&swap_pager_object_list[i]);
525 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
526 sx_init(&sw_alloc_sx, "swspsx");
527 sx_init(&swdev_syscall_lock, "swsysc");
531 swap_pager_counters(void)
534 swap_free_deferred = counter_u64_alloc(M_WAITOK);
535 swap_free_completed = counter_u64_alloc(M_WAITOK);
537 SYSINIT(swap_counters, SI_SUB_CPU, SI_ORDER_ANY, swap_pager_counters, NULL);
540 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
542 * Expected to be started from pageout process once, prior to entering
546 swap_pager_swap_init(void)
551 * Number of in-transit swap bp operations. Don't
552 * exhaust the pbufs completely. Make sure we
553 * initialize workable values (0 will work for hysteresis
554 * but it isn't very efficient).
556 * The nsw_cluster_max is constrained by the bp->b_pages[]
557 * array, which has MAXPHYS / PAGE_SIZE entries, and our locally
558 * defined MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
559 * constrained by the swap device interleave stripe size.
561 * Currently we hardwire nsw_wcount_async to 4. This limit is
562 * designed to prevent other I/O from having high latencies due to
563 * our pageout I/O. The value 4 works well for one or two active swap
564 * devices but is probably a little low if you have more. Even so,
565 * a higher value would probably generate only a limited improvement
566 * with three or four active swap devices since the system does not
567 * typically have to pageout at extreme bandwidths. We will want
568 * at least 2 per swap devices, and 4 is a pretty good value if you
569 * have one NFS swap device due to the command/ack latency over NFS.
570 * So it all works out pretty well.
572 nsw_cluster_max = min(MAXPHYS / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
574 nsw_wcount_async = 4;
575 nsw_wcount_async_max = nsw_wcount_async;
576 mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
578 swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
579 swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
582 * Initialize our zone, taking the user's requested size or
583 * estimating the number we need based on the number of pages
586 n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
587 vm_cnt.v_page_count / 2;
588 swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
589 pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0);
590 if (swpctrie_zone == NULL)
591 panic("failed to create swap pctrie zone.");
592 swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
593 NULL, NULL, _Alignof(struct swblk) - 1, 0);
594 if (swblk_zone == NULL)
595 panic("failed to create swap blk zone.");
598 if (uma_zone_reserve_kva(swblk_zone, n))
601 * if the allocation failed, try a zone two thirds the
602 * size of the previous attempt.
608 * Often uma_zone_reserve_kva() cannot reserve exactly the
609 * requested size. Account for the difference when
610 * calculating swap_maxpages.
612 n = uma_zone_get_max(swblk_zone);
615 printf("Swap blk zone entries changed from %lu to %lu.\n",
617 /* absolute maximum we can handle assuming 100% efficiency */
618 swap_maxpages = n * SWAP_META_PAGES;
619 swzone = n * sizeof(struct swblk);
620 if (!uma_zone_reserve_kva(swpctrie_zone, n))
621 printf("Cannot reserve swap pctrie zone, "
622 "reduce kern.maxswzone.\n");
626 swap_pager_alloc_init(void *handle, struct ucred *cred, vm_ooffset_t size,
632 if (!swap_reserve_by_cred(size, cred))
638 * The un_pager.swp.swp_blks trie is initialized by
639 * vm_object_allocate() to ensure the correct order of
640 * visibility to other threads.
642 object = vm_object_allocate(OBJT_SWAP, OFF_TO_IDX(offset +
645 object->un_pager.swp.writemappings = 0;
646 object->handle = handle;
649 object->charge = size;
655 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
656 * its metadata structures.
658 * This routine is called from the mmap and fork code to create a new
661 * This routine must ensure that no live duplicate is created for
662 * the named object request, which is protected against by
663 * holding the sw_alloc_sx lock in case handle != NULL.
666 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
667 vm_ooffset_t offset, struct ucred *cred)
671 if (handle != NULL) {
673 * Reference existing named region or allocate new one. There
674 * should not be a race here against swp_pager_meta_build()
675 * as called from vm_page_remove() in regards to the lookup
678 sx_xlock(&sw_alloc_sx);
679 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
680 if (object == NULL) {
681 object = swap_pager_alloc_init(handle, cred, size,
683 if (object != NULL) {
684 TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
685 object, pager_object_list);
688 sx_xunlock(&sw_alloc_sx);
690 object = swap_pager_alloc_init(handle, cred, size, offset);
696 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
698 * The swap backing for the object is destroyed. The code is
699 * designed such that we can reinstantiate it later, but this
700 * routine is typically called only when the entire object is
701 * about to be destroyed.
703 * The object must be locked.
706 swap_pager_dealloc(vm_object_t object)
709 VM_OBJECT_ASSERT_WLOCKED(object);
710 KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
713 * Remove from list right away so lookups will fail if we block for
714 * pageout completion.
716 if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
717 VM_OBJECT_WUNLOCK(object);
718 sx_xlock(&sw_alloc_sx);
719 TAILQ_REMOVE(NOBJLIST(object->handle), object,
721 sx_xunlock(&sw_alloc_sx);
722 VM_OBJECT_WLOCK(object);
725 vm_object_pip_wait(object, "swpdea");
728 * Free all remaining metadata. We only bother to free it from
729 * the swap meta data. We do not attempt to free swapblk's still
730 * associated with vm_page_t's for this object. We do not care
731 * if paging is still in progress on some objects.
733 swp_pager_meta_free_all(object);
734 object->handle = NULL;
735 object->type = OBJT_DEAD;
738 /************************************************************************
739 * SWAP PAGER BITMAP ROUTINES *
740 ************************************************************************/
743 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
745 * Allocate swap for up to the requested number of pages. The
746 * starting swap block number (a page index) is returned or
747 * SWAPBLK_NONE if the allocation failed.
749 * Also has the side effect of advising that somebody made a mistake
750 * when they configured swap and didn't configure enough.
752 * This routine may not sleep.
754 * We allocate in round-robin fashion from the configured devices.
757 swp_pager_getswapspace(int *io_npages)
763 KASSERT(*io_npages >= 1,
764 ("%s: npages not positive", __func__));
767 npages = imin(BLIST_MAX_ALLOC, mpages);
768 mtx_lock(&sw_dev_mtx);
770 while (!TAILQ_EMPTY(&swtailq)) {
772 sp = TAILQ_FIRST(&swtailq);
773 if ((sp->sw_flags & SW_CLOSING) == 0)
774 blk = blist_alloc(sp->sw_blist, &npages, mpages);
775 if (blk != SWAPBLK_NONE)
777 sp = TAILQ_NEXT(sp, sw_list);
785 if (blk != SWAPBLK_NONE) {
788 sp->sw_used += npages;
789 swap_pager_avail -= npages;
791 swdevhd = TAILQ_NEXT(sp, sw_list);
793 if (swap_pager_full != 2) {
794 printf("swp_pager_getswapspace(%d): failed\n",
797 swap_pager_almost_full = 1;
801 mtx_unlock(&sw_dev_mtx);
806 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
809 return (blk >= sp->sw_first && blk < sp->sw_end);
813 swp_pager_strategy(struct buf *bp)
817 mtx_lock(&sw_dev_mtx);
818 TAILQ_FOREACH(sp, &swtailq, sw_list) {
819 if (swp_pager_isondev(bp->b_blkno, sp)) {
820 mtx_unlock(&sw_dev_mtx);
821 if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
822 unmapped_buf_allowed) {
823 bp->b_data = unmapped_buf;
826 pmap_qenter((vm_offset_t)bp->b_data,
827 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
829 sp->sw_strategy(bp, sp);
833 panic("Swapdev not found");
838 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
840 * This routine returns the specified swap blocks back to the bitmap.
842 * This routine may not sleep.
845 swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
851 mtx_lock(&sw_dev_mtx);
852 TAILQ_FOREACH(sp, &swtailq, sw_list) {
853 if (swp_pager_isondev(blk, sp)) {
854 sp->sw_used -= npages;
856 * If we are attempting to stop swapping on
857 * this device, we don't want to mark any
858 * blocks free lest they be reused.
860 if ((sp->sw_flags & SW_CLOSING) == 0) {
861 blist_free(sp->sw_blist, blk - sp->sw_first,
863 swap_pager_avail += npages;
866 mtx_unlock(&sw_dev_mtx);
870 panic("Swapdev not found");
874 * SYSCTL_SWAP_FRAGMENTATION() - produce raw swap space stats
877 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
884 error = sysctl_wire_old_buffer(req, 0);
887 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
888 mtx_lock(&sw_dev_mtx);
889 TAILQ_FOREACH(sp, &swtailq, sw_list) {
890 if (vn_isdisk(sp->sw_vp, NULL))
891 devname = devtoname(sp->sw_vp->v_rdev);
894 sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
895 blist_stats(sp->sw_blist, &sbuf);
897 mtx_unlock(&sw_dev_mtx);
898 error = sbuf_finish(&sbuf);
904 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
905 * range within an object.
907 * This is a globally accessible routine.
909 * This routine removes swapblk assignments from swap metadata.
911 * The external callers of this routine typically have already destroyed
912 * or renamed vm_page_t's associated with this range in the object so
915 * The object must be locked.
918 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
921 swp_pager_meta_free(object, start, size);
925 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
927 * Assigns swap blocks to the specified range within the object. The
928 * swap blocks are not zeroed. Any previous swap assignment is destroyed.
930 * Returns 0 on success, -1 on failure.
933 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
935 daddr_t addr, blk, n_free, s_free;
938 swp_pager_init_freerange(&s_free, &n_free);
939 VM_OBJECT_WLOCK(object);
940 for (i = 0; i < size; i += n) {
942 blk = swp_pager_getswapspace(&n);
943 if (blk == SWAPBLK_NONE) {
944 swp_pager_meta_free(object, start, i);
945 VM_OBJECT_WUNLOCK(object);
948 for (j = 0; j < n; ++j) {
949 addr = swp_pager_meta_build(object,
950 start + i + j, blk + j);
951 if (addr != SWAPBLK_NONE)
952 swp_pager_update_freerange(&s_free, &n_free,
956 swp_pager_freeswapspace(s_free, n_free);
957 VM_OBJECT_WUNLOCK(object);
962 swp_pager_xfer_source(vm_object_t srcobject, vm_object_t dstobject,
963 vm_pindex_t pindex, daddr_t addr)
967 KASSERT(srcobject->type == OBJT_SWAP,
968 ("%s: Srcobject not swappable", __func__));
969 if (dstobject->type == OBJT_SWAP &&
970 swp_pager_meta_lookup(dstobject, pindex) != SWAPBLK_NONE) {
971 /* Caller should destroy the source block. */
976 * Destination has no swapblk and is not resident, transfer source.
977 * swp_pager_meta_build() can sleep.
979 VM_OBJECT_WUNLOCK(srcobject);
980 dstaddr = swp_pager_meta_build(dstobject, pindex, addr);
981 KASSERT(dstaddr == SWAPBLK_NONE,
982 ("Unexpected destination swapblk"));
983 VM_OBJECT_WLOCK(srcobject);
989 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
990 * and destroy the source.
992 * Copy any valid swapblks from the source to the destination. In
993 * cases where both the source and destination have a valid swapblk,
994 * we keep the destination's.
996 * This routine is allowed to sleep. It may sleep allocating metadata
997 * indirectly through swp_pager_meta_build().
999 * The source object contains no vm_page_t's (which is just as well)
1001 * The source object is of type OBJT_SWAP.
1003 * The source and destination objects must be locked.
1004 * Both object locks may temporarily be released.
1007 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
1008 vm_pindex_t offset, int destroysource)
1011 VM_OBJECT_ASSERT_WLOCKED(srcobject);
1012 VM_OBJECT_ASSERT_WLOCKED(dstobject);
1015 * If destroysource is set, we remove the source object from the
1016 * swap_pager internal queue now.
1018 if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
1019 srcobject->handle != NULL) {
1020 VM_OBJECT_WUNLOCK(srcobject);
1021 VM_OBJECT_WUNLOCK(dstobject);
1022 sx_xlock(&sw_alloc_sx);
1023 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1025 sx_xunlock(&sw_alloc_sx);
1026 VM_OBJECT_WLOCK(dstobject);
1027 VM_OBJECT_WLOCK(srcobject);
1031 * Transfer source to destination.
1033 swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size);
1036 * Free left over swap blocks in source.
1038 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
1039 * double-remove the object from the swap queues.
1041 if (destroysource) {
1042 swp_pager_meta_free_all(srcobject);
1044 * Reverting the type is not necessary, the caller is going
1045 * to destroy srcobject directly, but I'm doing it here
1046 * for consistency since we've removed the object from its
1049 srcobject->type = OBJT_DEFAULT;
1054 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
1055 * the requested page.
1057 * We determine whether good backing store exists for the requested
1058 * page and return TRUE if it does, FALSE if it doesn't.
1060 * If TRUE, we also try to determine how much valid, contiguous backing
1061 * store exists before and after the requested page.
1064 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1070 VM_OBJECT_ASSERT_LOCKED(object);
1071 KASSERT(object->type == OBJT_SWAP,
1072 ("%s: object not swappable", __func__));
1075 * do we have good backing store at the requested index ?
1077 blk0 = swp_pager_meta_lookup(object, pindex);
1078 if (blk0 == SWAPBLK_NONE) {
1087 * find backwards-looking contiguous good backing store
1089 if (before != NULL) {
1090 for (i = 1; i < SWB_NPAGES; i++) {
1093 blk = swp_pager_meta_lookup(object, pindex - i);
1094 if (blk != blk0 - i)
1101 * find forward-looking contiguous good backing store
1103 if (after != NULL) {
1104 for (i = 1; i < SWB_NPAGES; i++) {
1105 blk = swp_pager_meta_lookup(object, pindex + i);
1106 if (blk != blk0 + i)
1115 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1117 * This removes any associated swap backing store, whether valid or
1118 * not, from the page.
1120 * This routine is typically called when a page is made dirty, at
1121 * which point any associated swap can be freed. MADV_FREE also
1122 * calls us in a special-case situation
1124 * NOTE!!! If the page is clean and the swap was valid, the caller
1125 * should make the page dirty before calling this routine. This routine
1126 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1129 * This routine may not sleep.
1131 * The object containing the page may be locked.
1134 swap_pager_unswapped(vm_page_t m)
1140 * Handle enqueing deferred frees first. If we do not have the
1141 * object lock we wait for the page daemon to clear the space.
1144 if (!VM_OBJECT_WOWNED(obj)) {
1145 VM_PAGE_OBJECT_BUSY_ASSERT(m);
1147 * The caller is responsible for synchronization but we
1148 * will harmlessly handle races. This is typically provided
1149 * by only calling unswapped() when a page transitions from
1152 if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1154 vm_page_aflag_set(m, PGA_SWAP_FREE);
1155 counter_u64_add(swap_free_deferred, 1);
1159 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1160 counter_u64_add(swap_free_completed, 1);
1161 vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
1164 * The meta data only exists if the object is OBJT_SWAP
1165 * and even then might not be allocated yet.
1167 KASSERT(m->object->type == OBJT_SWAP,
1168 ("Free object not swappable"));
1170 sb = SWAP_PCTRIE_LOOKUP(&m->object->un_pager.swp.swp_blks,
1171 rounddown(m->pindex, SWAP_META_PAGES));
1174 if (sb->d[m->pindex % SWAP_META_PAGES] == SWAPBLK_NONE)
1176 swp_pager_freeswapspace(sb->d[m->pindex % SWAP_META_PAGES], 1);
1177 sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
1178 swp_pager_free_empty_swblk(m->object, sb);
1182 * swap_pager_getpages() - bring pages in from swap
1184 * Attempt to page in the pages in array "ma" of length "count". The
1185 * caller may optionally specify that additional pages preceding and
1186 * succeeding the specified range be paged in. The number of such pages
1187 * is returned in the "rbehind" and "rahead" parameters, and they will
1188 * be in the inactive queue upon return.
1190 * The pages in "ma" must be busied and will remain busied upon return.
1193 swap_pager_getpages_locked(vm_object_t object, vm_page_t *ma, int count,
1194 int *rbehind, int *rahead)
1197 vm_page_t bm, mpred, msucc, p;
1200 int i, maxahead, maxbehind, reqcount;
1202 VM_OBJECT_ASSERT_WLOCKED(object);
1205 KASSERT(object->type == OBJT_SWAP,
1206 ("%s: object not swappable", __func__));
1207 if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead)) {
1208 VM_OBJECT_WUNLOCK(object);
1209 return (VM_PAGER_FAIL);
1212 KASSERT(reqcount - 1 <= maxahead,
1213 ("page count %d extends beyond swap block", reqcount));
1216 * Do not transfer any pages other than those that are xbusied
1217 * when running during a split or collapse operation. This
1218 * prevents clustering from re-creating pages which are being
1219 * moved into another object.
1221 if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
1222 maxahead = reqcount - 1;
1227 * Clip the readahead and readbehind ranges to exclude resident pages.
1229 if (rahead != NULL) {
1230 *rahead = imin(*rahead, maxahead - (reqcount - 1));
1231 pindex = ma[reqcount - 1]->pindex;
1232 msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1233 if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1234 *rahead = msucc->pindex - pindex - 1;
1236 if (rbehind != NULL) {
1237 *rbehind = imin(*rbehind, maxbehind);
1238 pindex = ma[0]->pindex;
1239 mpred = TAILQ_PREV(ma[0], pglist, listq);
1240 if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1241 *rbehind = pindex - mpred->pindex - 1;
1245 for (i = 0; i < count; i++)
1246 ma[i]->oflags |= VPO_SWAPINPROG;
1249 * Allocate readahead and readbehind pages.
1251 if (rbehind != NULL) {
1252 for (i = 1; i <= *rbehind; i++) {
1253 p = vm_page_alloc(object, ma[0]->pindex - i,
1257 p->oflags |= VPO_SWAPINPROG;
1262 if (rahead != NULL) {
1263 for (i = 0; i < *rahead; i++) {
1264 p = vm_page_alloc(object,
1265 ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1268 p->oflags |= VPO_SWAPINPROG;
1272 if (rbehind != NULL)
1277 vm_object_pip_add(object, count);
1279 pindex = bm->pindex;
1280 blk = swp_pager_meta_lookup(object, pindex);
1281 KASSERT(blk != SWAPBLK_NONE,
1282 ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1284 VM_OBJECT_WUNLOCK(object);
1285 bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1286 /* Pages cannot leave the object while busy. */
1287 for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1288 MPASS(p->pindex == bm->pindex + i);
1292 bp->b_flags |= B_PAGING;
1293 bp->b_iocmd = BIO_READ;
1294 bp->b_iodone = swp_pager_async_iodone;
1295 bp->b_rcred = crhold(thread0.td_ucred);
1296 bp->b_wcred = crhold(thread0.td_ucred);
1298 bp->b_bcount = PAGE_SIZE * count;
1299 bp->b_bufsize = PAGE_SIZE * count;
1300 bp->b_npages = count;
1301 bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1302 bp->b_pgafter = rahead != NULL ? *rahead : 0;
1304 VM_CNT_INC(v_swapin);
1305 VM_CNT_ADD(v_swappgsin, count);
1308 * perform the I/O. NOTE!!! bp cannot be considered valid after
1309 * this point because we automatically release it on completion.
1310 * Instead, we look at the one page we are interested in which we
1311 * still hold a lock on even through the I/O completion.
1313 * The other pages in our ma[] array are also released on completion,
1314 * so we cannot assume they are valid anymore either.
1316 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1319 swp_pager_strategy(bp);
1322 * Wait for the pages we want to complete. VPO_SWAPINPROG is always
1323 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1324 * is set in the metadata for each page in the request.
1326 VM_OBJECT_WLOCK(object);
1327 /* This could be implemented more efficiently with aflags */
1328 while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
1329 ma[0]->oflags |= VPO_SWAPSLEEP;
1330 VM_CNT_INC(v_intrans);
1331 if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1332 "swread", hz * 20)) {
1334 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1335 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1338 VM_OBJECT_WUNLOCK(object);
1341 * If we had an unrecoverable read error pages will not be valid.
1343 for (i = 0; i < reqcount; i++)
1344 if (ma[i]->valid != VM_PAGE_BITS_ALL)
1345 return (VM_PAGER_ERROR);
1347 return (VM_PAGER_OK);
1350 * A final note: in a low swap situation, we cannot deallocate swap
1351 * and mark a page dirty here because the caller is likely to mark
1352 * the page clean when we return, causing the page to possibly revert
1353 * to all-zero's later.
1358 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count,
1359 int *rbehind, int *rahead)
1362 VM_OBJECT_WLOCK(object);
1363 return (swap_pager_getpages_locked(object, ma, count, rbehind, rahead));
1367 * swap_pager_getpages_async():
1369 * Right now this is emulation of asynchronous operation on top of
1370 * swap_pager_getpages().
1373 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1374 int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1378 r = swap_pager_getpages(object, ma, count, rbehind, rahead);
1383 case VM_PAGER_ERROR:
1390 panic("unhandled swap_pager_getpages() error %d", r);
1392 (iodone)(arg, ma, count, error);
1398 * swap_pager_putpages:
1400 * Assign swap (if necessary) and initiate I/O on the specified pages.
1402 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1403 * are automatically converted to SWAP objects.
1405 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1406 * vm_page reservation system coupled with properly written VFS devices
1407 * should ensure that no low-memory deadlock occurs. This is an area
1410 * The parent has N vm_object_pip_add() references prior to
1411 * calling us and will remove references for rtvals[] that are
1412 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1415 * The parent has soft-busy'd the pages it passes us and will unbusy
1416 * those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
1417 * We need to unbusy the rest on I/O completion.
1420 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1421 int flags, int *rtvals)
1424 daddr_t addr, blk, n_free, s_free;
1429 KASSERT(count == 0 || ma[0]->object == object,
1430 ("%s: object mismatch %p/%p",
1431 __func__, object, ma[0]->object));
1436 * Turn object into OBJT_SWAP. Force sync if not a pageout process.
1438 if (object->type != OBJT_SWAP) {
1439 addr = swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1440 KASSERT(addr == SWAPBLK_NONE,
1441 ("unexpected object swap block"));
1443 VM_OBJECT_WUNLOCK(object);
1444 async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
1445 swp_pager_init_freerange(&s_free, &n_free);
1450 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1451 * The page is left dirty until the pageout operation completes
1454 for (i = 0; i < count; i += n) {
1455 /* Maximum I/O size is limited by maximum swap block size. */
1456 n = min(count - i, nsw_cluster_max);
1459 mtx_lock(&swbuf_mtx);
1460 while (nsw_wcount_async == 0)
1461 msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1464 mtx_unlock(&swbuf_mtx);
1467 /* Get a block of swap of size up to size n. */
1468 VM_OBJECT_WLOCK(object);
1469 blk = swp_pager_getswapspace(&n);
1470 if (blk == SWAPBLK_NONE) {
1471 VM_OBJECT_WUNLOCK(object);
1472 mtx_lock(&swbuf_mtx);
1473 if (++nsw_wcount_async == 1)
1474 wakeup(&nsw_wcount_async);
1475 mtx_unlock(&swbuf_mtx);
1476 for (j = 0; j < n; ++j)
1477 rtvals[i + j] = VM_PAGER_FAIL;
1480 for (j = 0; j < n; ++j) {
1482 vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1483 addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1485 if (addr != SWAPBLK_NONE)
1486 swp_pager_update_freerange(&s_free, &n_free,
1488 MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1489 mreq->oflags |= VPO_SWAPINPROG;
1491 VM_OBJECT_WUNLOCK(object);
1493 bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1495 bp->b_flags = B_ASYNC;
1496 bp->b_flags |= B_PAGING;
1497 bp->b_iocmd = BIO_WRITE;
1499 bp->b_rcred = crhold(thread0.td_ucred);
1500 bp->b_wcred = crhold(thread0.td_ucred);
1501 bp->b_bcount = PAGE_SIZE * n;
1502 bp->b_bufsize = PAGE_SIZE * n;
1504 for (j = 0; j < n; j++)
1505 bp->b_pages[j] = ma[i + j];
1509 * Must set dirty range for NFS to work.
1512 bp->b_dirtyend = bp->b_bcount;
1514 VM_CNT_INC(v_swapout);
1515 VM_CNT_ADD(v_swappgsout, bp->b_npages);
1518 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1519 * can call the async completion routine at the end of a
1520 * synchronous I/O operation. Otherwise, our caller would
1521 * perform duplicate unbusy and wakeup operations on the page
1522 * and object, respectively.
1524 for (j = 0; j < n; j++)
1525 rtvals[i + j] = VM_PAGER_PEND;
1530 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1533 bp->b_iodone = swp_pager_async_iodone;
1535 swp_pager_strategy(bp);
1542 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1544 bp->b_iodone = bdone;
1545 swp_pager_strategy(bp);
1548 * Wait for the sync I/O to complete.
1550 bwait(bp, PVM, "swwrt");
1553 * Now that we are through with the bp, we can call the
1554 * normal async completion, which frees everything up.
1556 swp_pager_async_iodone(bp);
1558 swp_pager_freeswapspace(s_free, n_free);
1559 VM_OBJECT_WLOCK(object);
1563 * swp_pager_async_iodone:
1565 * Completion routine for asynchronous reads and writes from/to swap.
1566 * Also called manually by synchronous code to finish up a bp.
1568 * This routine may not sleep.
1571 swp_pager_async_iodone(struct buf *bp)
1574 vm_object_t object = NULL;
1577 * Report error - unless we ran out of memory, in which case
1578 * we've already logged it in swapgeom_strategy().
1580 if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
1582 "swap_pager: I/O error - %s failed; blkno %ld,"
1583 "size %ld, error %d\n",
1584 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1592 * remove the mapping for kernel virtual
1595 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1597 bp->b_data = bp->b_kvabase;
1600 object = bp->b_pages[0]->object;
1601 VM_OBJECT_WLOCK(object);
1605 * cleanup pages. If an error occurs writing to swap, we are in
1606 * very serious trouble. If it happens to be a disk error, though,
1607 * we may be able to recover by reassigning the swap later on. So
1608 * in this case we remove the m->swapblk assignment for the page
1609 * but do not free it in the rlist. The errornous block(s) are thus
1610 * never reallocated as swap. Redirty the page and continue.
1612 for (i = 0; i < bp->b_npages; ++i) {
1613 vm_page_t m = bp->b_pages[i];
1615 m->oflags &= ~VPO_SWAPINPROG;
1616 if (m->oflags & VPO_SWAPSLEEP) {
1617 m->oflags &= ~VPO_SWAPSLEEP;
1618 wakeup(&object->handle);
1621 /* We always have space after I/O, successful or not. */
1622 vm_page_aflag_set(m, PGA_SWAP_SPACE);
1624 if (bp->b_ioflags & BIO_ERROR) {
1626 * If an error occurs I'd love to throw the swapblk
1627 * away without freeing it back to swapspace, so it
1628 * can never be used again. But I can't from an
1631 if (bp->b_iocmd == BIO_READ) {
1633 * NOTE: for reads, m->dirty will probably
1634 * be overridden by the original caller of
1635 * getpages so don't play cute tricks here.
1640 * If a write error occurs, reactivate page
1641 * so it doesn't clog the inactive list,
1642 * then finish the I/O.
1644 MPASS(m->dirty == VM_PAGE_BITS_ALL);
1646 /* PQ_UNSWAPPABLE? */
1647 vm_page_activate(m);
1650 } else if (bp->b_iocmd == BIO_READ) {
1652 * NOTE: for reads, m->dirty will probably be
1653 * overridden by the original caller of getpages so
1654 * we cannot set them in order to free the underlying
1655 * swap in a low-swap situation. I don't think we'd
1656 * want to do that anyway, but it was an optimization
1657 * that existed in the old swapper for a time before
1658 * it got ripped out due to precisely this problem.
1660 KASSERT(!pmap_page_is_mapped(m),
1661 ("swp_pager_async_iodone: page %p is mapped", m));
1662 KASSERT(m->dirty == 0,
1663 ("swp_pager_async_iodone: page %p is dirty", m));
1666 if (i < bp->b_pgbefore ||
1667 i >= bp->b_npages - bp->b_pgafter)
1668 vm_page_readahead_finish(m);
1671 * For write success, clear the dirty
1672 * status, then finish the I/O ( which decrements the
1673 * busy count and possibly wakes waiter's up ).
1674 * A page is only written to swap after a period of
1675 * inactivity. Therefore, we do not expect it to be
1678 KASSERT(!pmap_page_is_write_mapped(m),
1679 ("swp_pager_async_iodone: page %p is not write"
1682 vm_page_deactivate_noreuse(m);
1688 * adjust pip. NOTE: the original parent may still have its own
1689 * pip refs on the object.
1691 if (object != NULL) {
1692 vm_object_pip_wakeupn(object, bp->b_npages);
1693 VM_OBJECT_WUNLOCK(object);
1697 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1698 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1699 * trigger a KASSERT in relpbuf().
1703 bp->b_bufobj = NULL;
1706 * release the physical I/O buffer
1708 if (bp->b_flags & B_ASYNC) {
1709 mtx_lock(&swbuf_mtx);
1710 if (++nsw_wcount_async == 1)
1711 wakeup(&nsw_wcount_async);
1712 mtx_unlock(&swbuf_mtx);
1714 uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
1718 swap_pager_nswapdev(void)
1725 swp_pager_force_dirty(vm_page_t m)
1729 swap_pager_unswapped(m);
1734 * swap_pager_swapoff_object:
1736 * Page in all of the pages that have been paged out for an object
1740 swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
1746 int i, nv, rahead, rv;
1748 KASSERT(object->type == OBJT_SWAP,
1749 ("%s: Object not swappable", __func__));
1751 for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1752 &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1753 if ((object->flags & OBJ_DEAD) != 0) {
1755 * Make sure that pending writes finish before
1758 vm_object_pip_wait(object, "swpoff");
1759 swp_pager_meta_free_all(object);
1762 for (i = 0; i < SWAP_META_PAGES; i++) {
1764 * Count the number of contiguous valid blocks.
1766 for (nv = 0; nv < SWAP_META_PAGES - i; nv++) {
1767 blk = sb->d[i + nv];
1768 if (!swp_pager_isondev(blk, sp) ||
1769 blk == SWAPBLK_NONE)
1776 * Look for a page corresponding to the first
1777 * valid block and ensure that any pending paging
1778 * operations on it are complete. If the page is valid,
1779 * mark it dirty and free the swap block. Try to batch
1780 * this operation since it may cause sp to be freed,
1781 * meaning that we must restart the scan. Avoid busying
1782 * valid pages since we may block forever on kernel
1785 m = vm_page_lookup(object, sb->p + i);
1787 m = vm_page_alloc(object, sb->p + i,
1788 VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
1792 if ((m->oflags & VPO_SWAPINPROG) != 0) {
1793 m->oflags |= VPO_SWAPSLEEP;
1794 VM_OBJECT_SLEEP(object, &object->handle,
1798 if (vm_page_all_valid(m)) {
1800 swp_pager_force_dirty(m);
1801 } while (--nv > 0 &&
1802 (m = vm_page_next(m)) != NULL &&
1803 vm_page_all_valid(m) &&
1804 (m->oflags & VPO_SWAPINPROG) == 0);
1807 if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL))
1811 vm_object_pip_add(object, 1);
1812 rahead = SWAP_META_PAGES;
1813 rv = swap_pager_getpages_locked(object, &m, 1, NULL,
1815 if (rv != VM_PAGER_OK)
1816 panic("%s: read from swap failed: %d",
1818 vm_object_pip_wakeupn(object, 1);
1819 VM_OBJECT_WLOCK(object);
1823 * The object lock was dropped so we must restart the
1824 * scan of this swap block. Pages paged in during this
1825 * iteration will be marked dirty in a future iteration.
1829 if (i == SWAP_META_PAGES)
1830 pi = sb->p + SWAP_META_PAGES;
1835 * swap_pager_swapoff:
1837 * Page in all of the pages that have been paged out to the
1838 * given device. The corresponding blocks in the bitmap must be
1839 * marked as allocated and the device must be flagged SW_CLOSING.
1840 * There may be no processes swapped out to the device.
1842 * This routine may block.
1845 swap_pager_swapoff(struct swdevt *sp)
1850 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1854 mtx_lock(&vm_object_list_mtx);
1855 TAILQ_FOREACH(object, &vm_object_list, object_list) {
1856 if (object->type != OBJT_SWAP)
1858 mtx_unlock(&vm_object_list_mtx);
1859 /* Depends on type-stability. */
1860 VM_OBJECT_WLOCK(object);
1863 * Dead objects are eventually terminated on their own.
1865 if ((object->flags & OBJ_DEAD) != 0)
1869 * Sync with fences placed after pctrie
1870 * initialization. We must not access pctrie below
1871 * unless we checked that our object is swap and not
1874 atomic_thread_fence_acq();
1875 if (object->type != OBJT_SWAP)
1878 swap_pager_swapoff_object(sp, object);
1880 VM_OBJECT_WUNLOCK(object);
1881 mtx_lock(&vm_object_list_mtx);
1883 mtx_unlock(&vm_object_list_mtx);
1887 * Objects may be locked or paging to the device being
1888 * removed, so we will miss their pages and need to
1889 * make another pass. We have marked this device as
1890 * SW_CLOSING, so the activity should finish soon.
1893 if (retries > 100) {
1894 panic("swapoff: failed to locate %d swap blocks",
1897 pause("swpoff", hz / 20);
1900 EVENTHANDLER_INVOKE(swapoff, sp);
1903 /************************************************************************
1905 ************************************************************************
1907 * These routines manipulate the swap metadata stored in the
1910 * Swap metadata is implemented with a global hash and not directly
1911 * linked into the object. Instead the object simply contains
1912 * appropriate tracking counters.
1916 * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
1919 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
1923 MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
1924 for (i = start; i < limit; i++) {
1925 if (sb->d[i] != SWAPBLK_NONE)
1932 * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
1934 * Nothing is done if the block is still in use.
1937 swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
1940 if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
1941 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
1942 uma_zfree(swblk_zone, sb);
1947 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
1949 * We first convert the object to a swap object if it is a default
1952 * The specified swapblk is added to the object's swap metadata. If
1953 * the swapblk is not valid, it is freed instead. Any previously
1954 * assigned swapblk is returned.
1957 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
1959 static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
1960 struct swblk *sb, *sb1;
1961 vm_pindex_t modpi, rdpi;
1962 daddr_t prev_swapblk;
1965 VM_OBJECT_ASSERT_WLOCKED(object);
1968 * Convert default object to swap object if necessary
1970 if (object->type != OBJT_SWAP) {
1971 pctrie_init(&object->un_pager.swp.swp_blks);
1974 * Ensure that swap_pager_swapoff()'s iteration over
1975 * object_list does not see a garbage pctrie.
1977 atomic_thread_fence_rel();
1979 object->type = OBJT_SWAP;
1980 object->un_pager.swp.writemappings = 0;
1981 KASSERT((object->flags & OBJ_ANON) != 0 ||
1982 object->handle == NULL,
1983 ("default pager %p with handle %p",
1984 object, object->handle));
1987 rdpi = rounddown(pindex, SWAP_META_PAGES);
1988 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
1990 if (swapblk == SWAPBLK_NONE)
1991 return (SWAPBLK_NONE);
1993 sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
1994 pageproc ? M_USE_RESERVE : 0));
1997 for (i = 0; i < SWAP_META_PAGES; i++)
1998 sb->d[i] = SWAPBLK_NONE;
1999 if (atomic_cmpset_int(&swblk_zone_exhausted,
2001 printf("swblk zone ok\n");
2004 VM_OBJECT_WUNLOCK(object);
2005 if (uma_zone_exhausted(swblk_zone)) {
2006 if (atomic_cmpset_int(&swblk_zone_exhausted,
2008 printf("swap blk zone exhausted, "
2009 "increase kern.maxswzone\n");
2010 vm_pageout_oom(VM_OOM_SWAPZ);
2011 pause("swzonxb", 10);
2013 uma_zwait(swblk_zone);
2014 VM_OBJECT_WLOCK(object);
2015 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2019 * Somebody swapped out a nearby page,
2020 * allocating swblk at the rdpi index,
2021 * while we dropped the object lock.
2026 error = SWAP_PCTRIE_INSERT(
2027 &object->un_pager.swp.swp_blks, sb);
2029 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2031 printf("swpctrie zone ok\n");
2034 VM_OBJECT_WUNLOCK(object);
2035 if (uma_zone_exhausted(swpctrie_zone)) {
2036 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2038 printf("swap pctrie zone exhausted, "
2039 "increase kern.maxswzone\n");
2040 vm_pageout_oom(VM_OOM_SWAPZ);
2041 pause("swzonxp", 10);
2043 uma_zwait(swpctrie_zone);
2044 VM_OBJECT_WLOCK(object);
2045 sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2048 uma_zfree(swblk_zone, sb);
2055 MPASS(sb->p == rdpi);
2057 modpi = pindex % SWAP_META_PAGES;
2058 /* Return prior contents of metadata. */
2059 prev_swapblk = sb->d[modpi];
2060 /* Enter block into metadata. */
2061 sb->d[modpi] = swapblk;
2064 * Free the swblk if we end up with the empty page run.
2066 if (swapblk == SWAPBLK_NONE)
2067 swp_pager_free_empty_swblk(object, sb);
2068 return (prev_swapblk);
2072 * SWP_PAGER_META_TRANSFER() - free a range of blocks in the srcobject's swap
2073 * metadata, or transfer it into dstobject.
2075 * This routine will free swap metadata structures as they are cleaned
2079 swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
2080 vm_pindex_t pindex, vm_pindex_t count)
2083 daddr_t n_free, s_free;
2084 vm_pindex_t offset, last;
2085 int i, limit, start;
2087 VM_OBJECT_ASSERT_WLOCKED(srcobject);
2088 if (srcobject->type != OBJT_SWAP || count == 0)
2091 swp_pager_init_freerange(&s_free, &n_free);
2093 last = pindex + count;
2095 sb = SWAP_PCTRIE_LOOKUP_GE(&srcobject->un_pager.swp.swp_blks,
2096 rounddown(pindex, SWAP_META_PAGES));
2097 if (sb == NULL || sb->p >= last)
2099 start = pindex > sb->p ? pindex - sb->p : 0;
2100 limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2102 for (i = start; i < limit; i++) {
2103 if (sb->d[i] == SWAPBLK_NONE)
2105 if (dstobject == NULL ||
2106 !swp_pager_xfer_source(srcobject, dstobject,
2107 sb->p + i - offset, sb->d[i])) {
2108 swp_pager_update_freerange(&s_free, &n_free,
2111 sb->d[i] = SWAPBLK_NONE;
2113 pindex = sb->p + SWAP_META_PAGES;
2114 if (swp_pager_swblk_empty(sb, 0, start) &&
2115 swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2116 SWAP_PCTRIE_REMOVE(&srcobject->un_pager.swp.swp_blks,
2118 uma_zfree(swblk_zone, sb);
2121 swp_pager_freeswapspace(s_free, n_free);
2125 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
2127 * The requested range of blocks is freed, with any associated swap
2128 * returned to the swap bitmap.
2130 * This routine will free swap metadata structures as they are cleaned
2131 * out. This routine does *NOT* operate on swap metadata associated
2132 * with resident pages.
2135 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count)
2137 swp_pager_meta_transfer(object, NULL, pindex, count);
2141 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
2143 * This routine locates and destroys all swap metadata associated with
2147 swp_pager_meta_free_all(vm_object_t object)
2150 daddr_t n_free, s_free;
2154 VM_OBJECT_ASSERT_WLOCKED(object);
2155 if (object->type != OBJT_SWAP)
2158 swp_pager_init_freerange(&s_free, &n_free);
2159 for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
2160 &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
2161 pindex = sb->p + SWAP_META_PAGES;
2162 for (i = 0; i < SWAP_META_PAGES; i++) {
2163 if (sb->d[i] == SWAPBLK_NONE)
2165 swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
2167 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2168 uma_zfree(swblk_zone, sb);
2170 swp_pager_freeswapspace(s_free, n_free);
2174 * SWP_PAGER_METACTL() - misc control of swap meta data.
2176 * This routine is capable of looking up, or removing swapblk
2177 * assignments in the swap meta data. It returns the swapblk being
2178 * looked-up, popped, or SWAPBLK_NONE if the block was invalid.
2180 * When acting on a busy resident page and paging is in progress, we
2181 * have to wait until paging is complete but otherwise can act on the
2185 swp_pager_meta_lookup(vm_object_t object, vm_pindex_t pindex)
2189 VM_OBJECT_ASSERT_LOCKED(object);
2192 * The meta data only exists if the object is OBJT_SWAP
2193 * and even then might not be allocated yet.
2195 KASSERT(object->type == OBJT_SWAP,
2196 ("Lookup object not swappable"));
2198 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2199 rounddown(pindex, SWAP_META_PAGES));
2201 return (SWAPBLK_NONE);
2202 return (sb->d[pindex % SWAP_META_PAGES]);
2206 * Returns the least page index which is greater than or equal to the
2207 * parameter pindex and for which there is a swap block allocated.
2208 * Returns object's size if the object's type is not swap or if there
2209 * are no allocated swap blocks for the object after the requested
2213 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2218 VM_OBJECT_ASSERT_LOCKED(object);
2219 if (object->type != OBJT_SWAP)
2220 return (object->size);
2222 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2223 rounddown(pindex, SWAP_META_PAGES));
2225 return (object->size);
2226 if (sb->p < pindex) {
2227 for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2228 if (sb->d[i] != SWAPBLK_NONE)
2231 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2232 roundup(pindex, SWAP_META_PAGES));
2234 return (object->size);
2236 for (i = 0; i < SWAP_META_PAGES; i++) {
2237 if (sb->d[i] != SWAPBLK_NONE)
2242 * We get here if a swblk is present in the trie but it
2243 * doesn't map any blocks.
2246 return (object->size);
2250 * System call swapon(name) enables swapping on device name,
2251 * which must be in the swdevsw. Return EBUSY
2252 * if already swapping on this device.
2254 #ifndef _SYS_SYSPROTO_H_
2255 struct swapon_args {
2265 sys_swapon(struct thread *td, struct swapon_args *uap)
2269 struct nameidata nd;
2272 error = priv_check(td, PRIV_SWAPON);
2276 sx_xlock(&swdev_syscall_lock);
2279 * Swap metadata may not fit in the KVM if we have physical
2282 if (swblk_zone == NULL) {
2287 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2293 NDFREE(&nd, NDF_ONLY_PNBUF);
2296 if (vn_isdisk(vp, &error)) {
2297 error = swapongeom(vp);
2298 } else if (vp->v_type == VREG &&
2299 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2300 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2302 * Allow direct swapping to NFS regular files in the same
2303 * way that nfs_mountroot() sets up diskless swapping.
2305 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2311 sx_xunlock(&swdev_syscall_lock);
2316 * Check that the total amount of swap currently configured does not
2317 * exceed half the theoretical maximum. If it does, print a warning
2321 swapon_check_swzone(void)
2324 /* recommend using no more than half that amount */
2325 if (swap_total > swap_maxpages / 2) {
2326 printf("warning: total configured swap (%lu pages) "
2327 "exceeds maximum recommended amount (%lu pages).\n",
2328 swap_total, swap_maxpages / 2);
2329 printf("warning: increase kern.maxswzone "
2330 "or reduce amount of swap.\n");
2335 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2336 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2338 struct swdevt *sp, *tsp;
2343 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2344 * First chop nblks off to page-align it, then convert.
2346 * sw->sw_nblks is in page-sized chunks now too.
2348 nblks &= ~(ctodb(1) - 1);
2349 nblks = dbtoc(nblks);
2352 * If we go beyond this, we get overflows in the radix
2355 mblocks = 0x40000000 / BLIST_META_RADIX;
2356 if (nblks > mblocks) {
2358 "WARNING: reducing swap size to maximum of %luMB per unit\n",
2359 mblocks / 1024 / 1024 * PAGE_SIZE);
2363 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2367 sp->sw_nblks = nblks;
2369 sp->sw_strategy = strategy;
2370 sp->sw_close = close;
2371 sp->sw_flags = flags;
2373 sp->sw_blist = blist_create(nblks, M_WAITOK);
2375 * Do not free the first blocks in order to avoid overwriting
2376 * any bsd label at the front of the partition
2378 blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2379 nblks - howmany(BBSIZE, PAGE_SIZE));
2382 mtx_lock(&sw_dev_mtx);
2383 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2384 if (tsp->sw_end >= dvbase) {
2386 * We put one uncovered page between the devices
2387 * in order to definitively prevent any cross-device
2390 dvbase = tsp->sw_end + 1;
2393 sp->sw_first = dvbase;
2394 sp->sw_end = dvbase + nblks;
2395 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2397 swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2398 swap_total += nblks;
2399 swapon_check_swzone();
2401 mtx_unlock(&sw_dev_mtx);
2402 EVENTHANDLER_INVOKE(swapon, sp);
2406 * SYSCALL: swapoff(devname)
2408 * Disable swapping on the given device.
2410 * XXX: Badly designed system call: it should use a device index
2411 * rather than filename as specification. We keep sw_vp around
2412 * only to make this work.
2414 #ifndef _SYS_SYSPROTO_H_
2415 struct swapoff_args {
2425 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2428 struct nameidata nd;
2432 error = priv_check(td, PRIV_SWAPOFF);
2436 sx_xlock(&swdev_syscall_lock);
2438 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2443 NDFREE(&nd, NDF_ONLY_PNBUF);
2446 mtx_lock(&sw_dev_mtx);
2447 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2448 if (sp->sw_vp == vp)
2451 mtx_unlock(&sw_dev_mtx);
2456 error = swapoff_one(sp, td->td_ucred);
2458 sx_xunlock(&swdev_syscall_lock);
2463 swapoff_one(struct swdevt *sp, struct ucred *cred)
2470 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2472 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2473 error = mac_system_check_swapoff(cred, sp->sw_vp);
2474 (void) VOP_UNLOCK(sp->sw_vp);
2478 nblks = sp->sw_nblks;
2481 * We can turn off this swap device safely only if the
2482 * available virtual memory in the system will fit the amount
2483 * of data we will have to page back in, plus an epsilon so
2484 * the system doesn't become critically low on swap space.
2486 if (vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
2490 * Prevent further allocations on this device.
2492 mtx_lock(&sw_dev_mtx);
2493 sp->sw_flags |= SW_CLOSING;
2494 swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2495 swap_total -= nblks;
2496 mtx_unlock(&sw_dev_mtx);
2499 * Page in the contents of the device and close it.
2501 swap_pager_swapoff(sp);
2503 sp->sw_close(curthread, sp);
2504 mtx_lock(&sw_dev_mtx);
2506 TAILQ_REMOVE(&swtailq, sp, sw_list);
2508 if (nswapdev == 0) {
2509 swap_pager_full = 2;
2510 swap_pager_almost_full = 1;
2514 mtx_unlock(&sw_dev_mtx);
2515 blist_destroy(sp->sw_blist);
2516 free(sp, M_VMPGDATA);
2523 struct swdevt *sp, *spt;
2524 const char *devname;
2527 sx_xlock(&swdev_syscall_lock);
2529 mtx_lock(&sw_dev_mtx);
2530 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2531 mtx_unlock(&sw_dev_mtx);
2532 if (vn_isdisk(sp->sw_vp, NULL))
2533 devname = devtoname(sp->sw_vp->v_rdev);
2536 error = swapoff_one(sp, thread0.td_ucred);
2538 printf("Cannot remove swap device %s (error=%d), "
2539 "skipping.\n", devname, error);
2540 } else if (bootverbose) {
2541 printf("Swap device %s removed.\n", devname);
2543 mtx_lock(&sw_dev_mtx);
2545 mtx_unlock(&sw_dev_mtx);
2547 sx_xunlock(&swdev_syscall_lock);
2551 swap_pager_status(int *total, int *used)
2557 mtx_lock(&sw_dev_mtx);
2558 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2559 *total += sp->sw_nblks;
2560 *used += sp->sw_used;
2562 mtx_unlock(&sw_dev_mtx);
2566 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2569 const char *tmp_devname;
2574 mtx_lock(&sw_dev_mtx);
2575 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2580 xs->xsw_version = XSWDEV_VERSION;
2581 xs->xsw_dev = sp->sw_dev;
2582 xs->xsw_flags = sp->sw_flags;
2583 xs->xsw_nblks = sp->sw_nblks;
2584 xs->xsw_used = sp->sw_used;
2585 if (devname != NULL) {
2586 if (vn_isdisk(sp->sw_vp, NULL))
2587 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2589 tmp_devname = "[file]";
2590 strncpy(devname, tmp_devname, len);
2595 mtx_unlock(&sw_dev_mtx);
2599 #if defined(COMPAT_FREEBSD11)
2600 #define XSWDEV_VERSION_11 1
2610 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2613 u_int xsw_dev1, xsw_dev2;
2621 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2624 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2625 struct xswdev32 xs32;
2627 #if defined(COMPAT_FREEBSD11)
2628 struct xswdev11 xs11;
2632 if (arg2 != 1) /* name length */
2634 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2637 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2638 if (req->oldlen == sizeof(xs32)) {
2639 xs32.xsw_version = XSWDEV_VERSION;
2640 xs32.xsw_dev1 = xs.xsw_dev;
2641 xs32.xsw_dev2 = xs.xsw_dev >> 32;
2642 xs32.xsw_flags = xs.xsw_flags;
2643 xs32.xsw_nblks = xs.xsw_nblks;
2644 xs32.xsw_used = xs.xsw_used;
2645 error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2649 #if defined(COMPAT_FREEBSD11)
2650 if (req->oldlen == sizeof(xs11)) {
2651 xs11.xsw_version = XSWDEV_VERSION_11;
2652 xs11.xsw_dev = xs.xsw_dev; /* truncation */
2653 xs11.xsw_flags = xs.xsw_flags;
2654 xs11.xsw_nblks = xs.xsw_nblks;
2655 xs11.xsw_used = xs.xsw_used;
2656 error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2660 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2664 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2665 "Number of swap devices");
2666 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2667 sysctl_vm_swap_info,
2668 "Swap statistics by device");
2671 * Count the approximate swap usage in pages for a vmspace. The
2672 * shadowed or not yet copied on write swap blocks are not accounted.
2673 * The map must be locked.
2676 vmspace_swap_count(struct vmspace *vmspace)
2686 map = &vmspace->vm_map;
2689 VM_MAP_ENTRY_FOREACH(cur, map) {
2690 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2692 object = cur->object.vm_object;
2693 if (object == NULL || object->type != OBJT_SWAP)
2695 VM_OBJECT_RLOCK(object);
2696 if (object->type != OBJT_SWAP)
2698 pi = OFF_TO_IDX(cur->offset);
2699 e = pi + OFF_TO_IDX(cur->end - cur->start);
2700 for (;; pi = sb->p + SWAP_META_PAGES) {
2701 sb = SWAP_PCTRIE_LOOKUP_GE(
2702 &object->un_pager.swp.swp_blks, pi);
2703 if (sb == NULL || sb->p >= e)
2705 for (i = 0; i < SWAP_META_PAGES; i++) {
2706 if (sb->p + i < e &&
2707 sb->d[i] != SWAPBLK_NONE)
2712 VM_OBJECT_RUNLOCK(object);
2720 * Swapping onto disk devices.
2724 static g_orphan_t swapgeom_orphan;
2726 static struct g_class g_swap_class = {
2728 .version = G_VERSION,
2729 .orphan = swapgeom_orphan,
2732 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2736 swapgeom_close_ev(void *arg, int flags)
2738 struct g_consumer *cp;
2741 g_access(cp, -1, -1, 0);
2743 g_destroy_consumer(cp);
2747 * Add a reference to the g_consumer for an inflight transaction.
2750 swapgeom_acquire(struct g_consumer *cp)
2753 mtx_assert(&sw_dev_mtx, MA_OWNED);
2758 * Remove a reference from the g_consumer. Post a close event if all
2759 * references go away, since the function might be called from the
2763 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2766 mtx_assert(&sw_dev_mtx, MA_OWNED);
2768 if (cp->index == 0) {
2769 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2775 swapgeom_done(struct bio *bp2)
2779 struct g_consumer *cp;
2781 bp = bp2->bio_caller2;
2783 bp->b_ioflags = bp2->bio_flags;
2785 bp->b_ioflags |= BIO_ERROR;
2786 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2787 bp->b_error = bp2->bio_error;
2788 bp->b_caller1 = NULL;
2790 sp = bp2->bio_caller1;
2791 mtx_lock(&sw_dev_mtx);
2792 swapgeom_release(cp, sp);
2793 mtx_unlock(&sw_dev_mtx);
2798 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2801 struct g_consumer *cp;
2803 mtx_lock(&sw_dev_mtx);
2806 mtx_unlock(&sw_dev_mtx);
2807 bp->b_error = ENXIO;
2808 bp->b_ioflags |= BIO_ERROR;
2812 swapgeom_acquire(cp);
2813 mtx_unlock(&sw_dev_mtx);
2814 if (bp->b_iocmd == BIO_WRITE)
2817 bio = g_alloc_bio();
2819 mtx_lock(&sw_dev_mtx);
2820 swapgeom_release(cp, sp);
2821 mtx_unlock(&sw_dev_mtx);
2822 bp->b_error = ENOMEM;
2823 bp->b_ioflags |= BIO_ERROR;
2824 printf("swap_pager: cannot allocate bio\n");
2829 bp->b_caller1 = bio;
2830 bio->bio_caller1 = sp;
2831 bio->bio_caller2 = bp;
2832 bio->bio_cmd = bp->b_iocmd;
2833 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2834 bio->bio_length = bp->b_bcount;
2835 bio->bio_done = swapgeom_done;
2836 if (!buf_mapped(bp)) {
2837 bio->bio_ma = bp->b_pages;
2838 bio->bio_data = unmapped_buf;
2839 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2840 bio->bio_ma_n = bp->b_npages;
2841 bio->bio_flags |= BIO_UNMAPPED;
2843 bio->bio_data = bp->b_data;
2846 g_io_request(bio, cp);
2851 swapgeom_orphan(struct g_consumer *cp)
2856 mtx_lock(&sw_dev_mtx);
2857 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2858 if (sp->sw_id == cp) {
2859 sp->sw_flags |= SW_CLOSING;
2864 * Drop reference we were created with. Do directly since we're in a
2865 * special context where we don't have to queue the call to
2866 * swapgeom_close_ev().
2869 destroy = ((sp != NULL) && (cp->index == 0));
2872 mtx_unlock(&sw_dev_mtx);
2874 swapgeom_close_ev(cp, 0);
2878 swapgeom_close(struct thread *td, struct swdevt *sw)
2880 struct g_consumer *cp;
2882 mtx_lock(&sw_dev_mtx);
2885 mtx_unlock(&sw_dev_mtx);
2888 * swapgeom_close() may be called from the biodone context,
2889 * where we cannot perform topology changes. Delegate the
2890 * work to the events thread.
2893 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2897 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2899 struct g_provider *pp;
2900 struct g_consumer *cp;
2901 static struct g_geom *gp;
2906 pp = g_dev_getprovider(dev);
2909 mtx_lock(&sw_dev_mtx);
2910 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2912 if (cp != NULL && cp->provider == pp) {
2913 mtx_unlock(&sw_dev_mtx);
2917 mtx_unlock(&sw_dev_mtx);
2919 gp = g_new_geomf(&g_swap_class, "swap");
2920 cp = g_new_consumer(gp);
2921 cp->index = 1; /* Number of active I/Os, plus one for being active. */
2922 cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2925 * XXX: Every time you think you can improve the margin for
2926 * footshooting, somebody depends on the ability to do so:
2927 * savecore(8) wants to write to our swapdev so we cannot
2928 * set an exclusive count :-(
2930 error = g_access(cp, 1, 1, 0);
2933 g_destroy_consumer(cp);
2936 nblks = pp->mediasize / DEV_BSIZE;
2937 swaponsomething(vp, cp, nblks, swapgeom_strategy,
2938 swapgeom_close, dev2udev(dev),
2939 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
2944 swapongeom(struct vnode *vp)
2948 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2949 if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) {
2953 error = swapongeom_locked(vp->v_rdev, vp);
2954 g_topology_unlock();
2963 * This is used mainly for network filesystem (read: probably only tested
2964 * with NFS) swapfiles.
2969 swapdev_strategy(struct buf *bp, struct swdevt *sp)
2973 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
2977 if (bp->b_iocmd == BIO_WRITE) {
2979 bufobj_wdrop(bp->b_bufobj);
2980 bufobj_wref(&vp2->v_bufobj);
2982 if (bp->b_bufobj != &vp2->v_bufobj)
2983 bp->b_bufobj = &vp2->v_bufobj;
2985 bp->b_iooffset = dbtob(bp->b_blkno);
2991 swapdev_close(struct thread *td, struct swdevt *sp)
2994 VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
3000 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
3007 mtx_lock(&sw_dev_mtx);
3008 TAILQ_FOREACH(sp, &swtailq, sw_list) {
3009 if (sp->sw_id == vp) {
3010 mtx_unlock(&sw_dev_mtx);
3014 mtx_unlock(&sw_dev_mtx);
3016 (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3018 error = mac_system_check_swapon(td->td_ucred, vp);
3021 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
3022 (void) VOP_UNLOCK(vp);
3026 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
3032 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
3036 new = nsw_wcount_async_max;
3037 error = sysctl_handle_int(oidp, &new, 0, req);
3038 if (error != 0 || req->newptr == NULL)
3041 if (new > nswbuf / 2 || new < 1)
3044 mtx_lock(&swbuf_mtx);
3045 while (nsw_wcount_async_max != new) {
3047 * Adjust difference. If the current async count is too low,
3048 * we will need to sqeeze our update slowly in. Sleep with a
3049 * higher priority than getpbuf() to finish faster.
3051 n = new - nsw_wcount_async_max;
3052 if (nsw_wcount_async + n >= 0) {
3053 nsw_wcount_async += n;
3054 nsw_wcount_async_max += n;
3055 wakeup(&nsw_wcount_async);
3057 nsw_wcount_async_max -= nsw_wcount_async;
3058 nsw_wcount_async = 0;
3059 msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
3063 mtx_unlock(&swbuf_mtx);
3069 swap_pager_update_writecount(vm_object_t object, vm_offset_t start,
3073 VM_OBJECT_WLOCK(object);
3074 KASSERT((object->flags & OBJ_ANON) == 0,
3075 ("Splittable object with writecount"));
3076 object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
3077 VM_OBJECT_WUNLOCK(object);
3081 swap_pager_release_writecount(vm_object_t object, vm_offset_t start,
3085 VM_OBJECT_WLOCK(object);
3086 KASSERT((object->flags & OBJ_ANON) == 0,
3087 ("Splittable object with writecount"));
3088 object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
3089 VM_OBJECT_WUNLOCK(object);