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_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(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_SWAP_INIT() - swap pager initialization from pageout process
533 * Expected to be started from pageout process once, prior to entering
537 swap_pager_swap_init(void)
542 * Number of in-transit swap bp operations. Don't
543 * exhaust the pbufs completely. Make sure we
544 * initialize workable values (0 will work for hysteresis
545 * but it isn't very efficient).
547 * The nsw_cluster_max is constrained by the bp->b_pages[]
548 * array, which has MAXPHYS / PAGE_SIZE entries, and our locally
549 * defined MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
550 * constrained by the swap device interleave stripe size.
552 * Currently we hardwire nsw_wcount_async to 4. This limit is
553 * designed to prevent other I/O from having high latencies due to
554 * our pageout I/O. The value 4 works well for one or two active swap
555 * devices but is probably a little low if you have more. Even so,
556 * a higher value would probably generate only a limited improvement
557 * with three or four active swap devices since the system does not
558 * typically have to pageout at extreme bandwidths. We will want
559 * at least 2 per swap devices, and 4 is a pretty good value if you
560 * have one NFS swap device due to the command/ack latency over NFS.
561 * So it all works out pretty well.
563 nsw_cluster_max = min(MAXPHYS / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
565 nsw_wcount_async = 4;
566 nsw_wcount_async_max = nsw_wcount_async;
567 mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
569 swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
570 swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
573 * Initialize our zone, taking the user's requested size or
574 * estimating the number we need based on the number of pages
577 n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
578 vm_cnt.v_page_count / 2;
579 swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
580 pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0);
581 if (swpctrie_zone == NULL)
582 panic("failed to create swap pctrie zone.");
583 swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
584 NULL, NULL, _Alignof(struct swblk) - 1, 0);
585 if (swblk_zone == NULL)
586 panic("failed to create swap blk zone.");
589 if (uma_zone_reserve_kva(swblk_zone, n))
592 * if the allocation failed, try a zone two thirds the
593 * size of the previous attempt.
599 * Often uma_zone_reserve_kva() cannot reserve exactly the
600 * requested size. Account for the difference when
601 * calculating swap_maxpages.
603 n = uma_zone_get_max(swblk_zone);
606 printf("Swap blk zone entries changed from %lu to %lu.\n",
608 /* absolute maximum we can handle assuming 100% efficiency */
609 swap_maxpages = n * SWAP_META_PAGES;
610 swzone = n * sizeof(struct swblk);
611 if (!uma_zone_reserve_kva(swpctrie_zone, n))
612 printf("Cannot reserve swap pctrie zone, "
613 "reduce kern.maxswzone.\n");
617 swap_pager_alloc_init(void *handle, struct ucred *cred, vm_ooffset_t size,
623 if (!swap_reserve_by_cred(size, cred))
629 * The un_pager.swp.swp_blks trie is initialized by
630 * vm_object_allocate() to ensure the correct order of
631 * visibility to other threads.
633 object = vm_object_allocate(OBJT_SWAP, OFF_TO_IDX(offset +
636 object->un_pager.swp.writemappings = 0;
637 object->handle = handle;
640 object->charge = size;
646 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
647 * its metadata structures.
649 * This routine is called from the mmap and fork code to create a new
652 * This routine must ensure that no live duplicate is created for
653 * the named object request, which is protected against by
654 * holding the sw_alloc_sx lock in case handle != NULL.
657 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
658 vm_ooffset_t offset, struct ucred *cred)
662 if (handle != NULL) {
664 * Reference existing named region or allocate new one. There
665 * should not be a race here against swp_pager_meta_build()
666 * as called from vm_page_remove() in regards to the lookup
669 sx_xlock(&sw_alloc_sx);
670 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
671 if (object == NULL) {
672 object = swap_pager_alloc_init(handle, cred, size,
674 if (object != NULL) {
675 TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
676 object, pager_object_list);
679 sx_xunlock(&sw_alloc_sx);
681 object = swap_pager_alloc_init(handle, cred, size, offset);
687 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
689 * The swap backing for the object is destroyed. The code is
690 * designed such that we can reinstantiate it later, but this
691 * routine is typically called only when the entire object is
692 * about to be destroyed.
694 * The object must be locked.
697 swap_pager_dealloc(vm_object_t object)
700 VM_OBJECT_ASSERT_WLOCKED(object);
701 KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
704 * Remove from list right away so lookups will fail if we block for
705 * pageout completion.
707 if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
708 VM_OBJECT_WUNLOCK(object);
709 sx_xlock(&sw_alloc_sx);
710 TAILQ_REMOVE(NOBJLIST(object->handle), object,
712 sx_xunlock(&sw_alloc_sx);
713 VM_OBJECT_WLOCK(object);
716 vm_object_pip_wait(object, "swpdea");
719 * Free all remaining metadata. We only bother to free it from
720 * the swap meta data. We do not attempt to free swapblk's still
721 * associated with vm_page_t's for this object. We do not care
722 * if paging is still in progress on some objects.
724 swp_pager_meta_free_all(object);
725 object->handle = NULL;
726 object->type = OBJT_DEAD;
729 /************************************************************************
730 * SWAP PAGER BITMAP ROUTINES *
731 ************************************************************************/
734 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
736 * Allocate swap for up to the requested number of pages. The
737 * starting swap block number (a page index) is returned or
738 * SWAPBLK_NONE if the allocation failed.
740 * Also has the side effect of advising that somebody made a mistake
741 * when they configured swap and didn't configure enough.
743 * This routine may not sleep.
745 * We allocate in round-robin fashion from the configured devices.
748 swp_pager_getswapspace(int *io_npages)
754 KASSERT(*io_npages >= 1,
755 ("%s: npages not positive", __func__));
758 npages = imin(BLIST_MAX_ALLOC, mpages);
759 mtx_lock(&sw_dev_mtx);
761 while (!TAILQ_EMPTY(&swtailq)) {
763 sp = TAILQ_FIRST(&swtailq);
764 if ((sp->sw_flags & SW_CLOSING) == 0)
765 blk = blist_alloc(sp->sw_blist, &npages, mpages);
766 if (blk != SWAPBLK_NONE)
768 sp = TAILQ_NEXT(sp, sw_list);
776 if (blk != SWAPBLK_NONE) {
779 sp->sw_used += npages;
780 swap_pager_avail -= npages;
782 swdevhd = TAILQ_NEXT(sp, sw_list);
784 if (swap_pager_full != 2) {
785 printf("swp_pager_getswapspace(%d): failed\n",
788 swap_pager_almost_full = 1;
792 mtx_unlock(&sw_dev_mtx);
797 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
800 return (blk >= sp->sw_first && blk < sp->sw_end);
804 swp_pager_strategy(struct buf *bp)
808 mtx_lock(&sw_dev_mtx);
809 TAILQ_FOREACH(sp, &swtailq, sw_list) {
810 if (swp_pager_isondev(bp->b_blkno, sp)) {
811 mtx_unlock(&sw_dev_mtx);
812 if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
813 unmapped_buf_allowed) {
814 bp->b_data = unmapped_buf;
817 pmap_qenter((vm_offset_t)bp->b_data,
818 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
820 sp->sw_strategy(bp, sp);
824 panic("Swapdev not found");
829 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
831 * This routine returns the specified swap blocks back to the bitmap.
833 * This routine may not sleep.
836 swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
842 mtx_lock(&sw_dev_mtx);
843 TAILQ_FOREACH(sp, &swtailq, sw_list) {
844 if (swp_pager_isondev(blk, sp)) {
845 sp->sw_used -= npages;
847 * If we are attempting to stop swapping on
848 * this device, we don't want to mark any
849 * blocks free lest they be reused.
851 if ((sp->sw_flags & SW_CLOSING) == 0) {
852 blist_free(sp->sw_blist, blk - sp->sw_first,
854 swap_pager_avail += npages;
857 mtx_unlock(&sw_dev_mtx);
861 panic("Swapdev not found");
865 * SYSCTL_SWAP_FRAGMENTATION() - produce raw swap space stats
868 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
875 error = sysctl_wire_old_buffer(req, 0);
878 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
879 mtx_lock(&sw_dev_mtx);
880 TAILQ_FOREACH(sp, &swtailq, sw_list) {
881 if (vn_isdisk(sp->sw_vp, NULL))
882 devname = devtoname(sp->sw_vp->v_rdev);
885 sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
886 blist_stats(sp->sw_blist, &sbuf);
888 mtx_unlock(&sw_dev_mtx);
889 error = sbuf_finish(&sbuf);
895 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
896 * range within an object.
898 * This is a globally accessible routine.
900 * This routine removes swapblk assignments from swap metadata.
902 * The external callers of this routine typically have already destroyed
903 * or renamed vm_page_t's associated with this range in the object so
906 * The object must be locked.
909 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
912 swp_pager_meta_free(object, start, size);
916 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
918 * Assigns swap blocks to the specified range within the object. The
919 * swap blocks are not zeroed. Any previous swap assignment is destroyed.
921 * Returns 0 on success, -1 on failure.
924 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
926 daddr_t addr, blk, n_free, s_free;
929 swp_pager_init_freerange(&s_free, &n_free);
930 VM_OBJECT_WLOCK(object);
931 for (i = 0; i < size; i += n) {
933 blk = swp_pager_getswapspace(&n);
934 if (blk == SWAPBLK_NONE) {
935 swp_pager_meta_free(object, start, i);
936 VM_OBJECT_WUNLOCK(object);
939 for (j = 0; j < n; ++j) {
940 addr = swp_pager_meta_build(object,
941 start + i + j, blk + j);
942 if (addr != SWAPBLK_NONE)
943 swp_pager_update_freerange(&s_free, &n_free,
947 swp_pager_freeswapspace(s_free, n_free);
948 VM_OBJECT_WUNLOCK(object);
953 swp_pager_xfer_source(vm_object_t srcobject, vm_object_t dstobject,
954 vm_pindex_t pindex, daddr_t addr)
958 KASSERT(srcobject->type == OBJT_SWAP,
959 ("%s: Srcobject not swappable", __func__));
960 if (dstobject->type == OBJT_SWAP &&
961 swp_pager_meta_lookup(dstobject, pindex) != SWAPBLK_NONE) {
962 /* Caller should destroy the source block. */
967 * Destination has no swapblk and is not resident, transfer source.
968 * swp_pager_meta_build() can sleep.
970 VM_OBJECT_WUNLOCK(srcobject);
971 dstaddr = swp_pager_meta_build(dstobject, pindex, addr);
972 KASSERT(dstaddr == SWAPBLK_NONE,
973 ("Unexpected destination swapblk"));
974 VM_OBJECT_WLOCK(srcobject);
980 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
981 * and destroy the source.
983 * Copy any valid swapblks from the source to the destination. In
984 * cases where both the source and destination have a valid swapblk,
985 * we keep the destination's.
987 * This routine is allowed to sleep. It may sleep allocating metadata
988 * indirectly through swp_pager_meta_build().
990 * The source object contains no vm_page_t's (which is just as well)
992 * The source object is of type OBJT_SWAP.
994 * The source and destination objects must be locked.
995 * Both object locks may temporarily be released.
998 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
999 vm_pindex_t offset, int destroysource)
1002 VM_OBJECT_ASSERT_WLOCKED(srcobject);
1003 VM_OBJECT_ASSERT_WLOCKED(dstobject);
1006 * If destroysource is set, we remove the source object from the
1007 * swap_pager internal queue now.
1009 if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
1010 srcobject->handle != NULL) {
1011 VM_OBJECT_WUNLOCK(srcobject);
1012 VM_OBJECT_WUNLOCK(dstobject);
1013 sx_xlock(&sw_alloc_sx);
1014 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1016 sx_xunlock(&sw_alloc_sx);
1017 VM_OBJECT_WLOCK(dstobject);
1018 VM_OBJECT_WLOCK(srcobject);
1022 * Transfer source to destination.
1024 swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size);
1027 * Free left over swap blocks in source.
1029 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
1030 * double-remove the object from the swap queues.
1032 if (destroysource) {
1033 swp_pager_meta_free_all(srcobject);
1035 * Reverting the type is not necessary, the caller is going
1036 * to destroy srcobject directly, but I'm doing it here
1037 * for consistency since we've removed the object from its
1040 srcobject->type = OBJT_DEFAULT;
1045 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
1046 * the requested page.
1048 * We determine whether good backing store exists for the requested
1049 * page and return TRUE if it does, FALSE if it doesn't.
1051 * If TRUE, we also try to determine how much valid, contiguous backing
1052 * store exists before and after the requested page.
1055 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1061 VM_OBJECT_ASSERT_LOCKED(object);
1062 KASSERT(object->type == OBJT_SWAP,
1063 ("%s: object not swappable", __func__));
1066 * do we have good backing store at the requested index ?
1068 blk0 = swp_pager_meta_lookup(object, pindex);
1069 if (blk0 == SWAPBLK_NONE) {
1078 * find backwards-looking contiguous good backing store
1080 if (before != NULL) {
1081 for (i = 1; i < SWB_NPAGES; i++) {
1084 blk = swp_pager_meta_lookup(object, pindex - i);
1085 if (blk != blk0 - i)
1092 * find forward-looking contiguous good backing store
1094 if (after != NULL) {
1095 for (i = 1; i < SWB_NPAGES; i++) {
1096 blk = swp_pager_meta_lookup(object, pindex + i);
1097 if (blk != blk0 + i)
1106 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1108 * This removes any associated swap backing store, whether valid or
1109 * not, from the page.
1111 * This routine is typically called when a page is made dirty, at
1112 * which point any associated swap can be freed. MADV_FREE also
1113 * calls us in a special-case situation
1115 * NOTE!!! If the page is clean and the swap was valid, the caller
1116 * should make the page dirty before calling this routine. This routine
1117 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1120 * This routine may not sleep.
1122 * The object containing the page may be locked.
1125 swap_pager_unswapped(vm_page_t m)
1131 * Handle enqueing deferred frees first. If we do not have the
1132 * object lock we wait for the page daemon to clear the space.
1135 if (!VM_OBJECT_WOWNED(obj)) {
1136 VM_PAGE_OBJECT_BUSY_ASSERT(m);
1138 * The caller is responsible for synchronization but we
1139 * will harmlessly handle races. This is typically provided
1140 * by only calling unswapped() when a page transitions from
1143 if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1145 vm_page_aflag_set(m, PGA_SWAP_FREE);
1146 counter_u64_add(swap_free_deferred, 1);
1150 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1151 counter_u64_add(swap_free_completed, 1);
1152 vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
1155 * The meta data only exists if the object is OBJT_SWAP
1156 * and even then might not be allocated yet.
1158 KASSERT(m->object->type == OBJT_SWAP,
1159 ("Free object not swappable"));
1161 sb = SWAP_PCTRIE_LOOKUP(&m->object->un_pager.swp.swp_blks,
1162 rounddown(m->pindex, SWAP_META_PAGES));
1165 if (sb->d[m->pindex % SWAP_META_PAGES] == SWAPBLK_NONE)
1167 swp_pager_freeswapspace(sb->d[m->pindex % SWAP_META_PAGES], 1);
1168 sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
1169 swp_pager_free_empty_swblk(m->object, sb);
1173 * swap_pager_getpages() - bring pages in from swap
1175 * Attempt to page in the pages in array "ma" of length "count". The
1176 * caller may optionally specify that additional pages preceding and
1177 * succeeding the specified range be paged in. The number of such pages
1178 * is returned in the "rbehind" and "rahead" parameters, and they will
1179 * be in the inactive queue upon return.
1181 * The pages in "ma" must be busied and will remain busied upon return.
1184 swap_pager_getpages_locked(vm_object_t object, vm_page_t *ma, int count,
1185 int *rbehind, int *rahead)
1188 vm_page_t bm, mpred, msucc, p;
1191 int i, maxahead, maxbehind, reqcount;
1193 VM_OBJECT_ASSERT_WLOCKED(object);
1196 KASSERT(object->type == OBJT_SWAP,
1197 ("%s: object not swappable", __func__));
1198 if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead)) {
1199 VM_OBJECT_WUNLOCK(object);
1200 return (VM_PAGER_FAIL);
1203 KASSERT(reqcount - 1 <= maxahead,
1204 ("page count %d extends beyond swap block", reqcount));
1207 * Do not transfer any pages other than those that are xbusied
1208 * when running during a split or collapse operation. This
1209 * prevents clustering from re-creating pages which are being
1210 * moved into another object.
1212 if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
1213 maxahead = reqcount - 1;
1218 * Clip the readahead and readbehind ranges to exclude resident pages.
1220 if (rahead != NULL) {
1221 *rahead = imin(*rahead, maxahead - (reqcount - 1));
1222 pindex = ma[reqcount - 1]->pindex;
1223 msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1224 if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1225 *rahead = msucc->pindex - pindex - 1;
1227 if (rbehind != NULL) {
1228 *rbehind = imin(*rbehind, maxbehind);
1229 pindex = ma[0]->pindex;
1230 mpred = TAILQ_PREV(ma[0], pglist, listq);
1231 if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1232 *rbehind = pindex - mpred->pindex - 1;
1236 for (i = 0; i < count; i++)
1237 ma[i]->oflags |= VPO_SWAPINPROG;
1240 * Allocate readahead and readbehind pages.
1242 if (rbehind != NULL) {
1243 for (i = 1; i <= *rbehind; i++) {
1244 p = vm_page_alloc(object, ma[0]->pindex - i,
1248 p->oflags |= VPO_SWAPINPROG;
1253 if (rahead != NULL) {
1254 for (i = 0; i < *rahead; i++) {
1255 p = vm_page_alloc(object,
1256 ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1259 p->oflags |= VPO_SWAPINPROG;
1263 if (rbehind != NULL)
1268 vm_object_pip_add(object, count);
1270 pindex = bm->pindex;
1271 blk = swp_pager_meta_lookup(object, pindex);
1272 KASSERT(blk != SWAPBLK_NONE,
1273 ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1275 VM_OBJECT_WUNLOCK(object);
1276 bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1277 /* Pages cannot leave the object while busy. */
1278 for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1279 MPASS(p->pindex == bm->pindex + i);
1283 bp->b_flags |= B_PAGING;
1284 bp->b_iocmd = BIO_READ;
1285 bp->b_iodone = swp_pager_async_iodone;
1286 bp->b_rcred = crhold(thread0.td_ucred);
1287 bp->b_wcred = crhold(thread0.td_ucred);
1289 bp->b_bcount = PAGE_SIZE * count;
1290 bp->b_bufsize = PAGE_SIZE * count;
1291 bp->b_npages = count;
1292 bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1293 bp->b_pgafter = rahead != NULL ? *rahead : 0;
1295 VM_CNT_INC(v_swapin);
1296 VM_CNT_ADD(v_swappgsin, count);
1299 * perform the I/O. NOTE!!! bp cannot be considered valid after
1300 * this point because we automatically release it on completion.
1301 * Instead, we look at the one page we are interested in which we
1302 * still hold a lock on even through the I/O completion.
1304 * The other pages in our ma[] array are also released on completion,
1305 * so we cannot assume they are valid anymore either.
1307 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1310 swp_pager_strategy(bp);
1313 * Wait for the pages we want to complete. VPO_SWAPINPROG is always
1314 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1315 * is set in the metadata for each page in the request.
1317 VM_OBJECT_WLOCK(object);
1318 /* This could be implemented more efficiently with aflags */
1319 while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
1320 ma[0]->oflags |= VPO_SWAPSLEEP;
1321 VM_CNT_INC(v_intrans);
1322 if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1323 "swread", hz * 20)) {
1325 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1326 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1329 VM_OBJECT_WUNLOCK(object);
1332 * If we had an unrecoverable read error pages will not be valid.
1334 for (i = 0; i < reqcount; i++)
1335 if (ma[i]->valid != VM_PAGE_BITS_ALL)
1336 return (VM_PAGER_ERROR);
1338 return (VM_PAGER_OK);
1341 * A final note: in a low swap situation, we cannot deallocate swap
1342 * and mark a page dirty here because the caller is likely to mark
1343 * the page clean when we return, causing the page to possibly revert
1344 * to all-zero's later.
1349 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count,
1350 int *rbehind, int *rahead)
1353 VM_OBJECT_WLOCK(object);
1354 return (swap_pager_getpages_locked(object, ma, count, rbehind, rahead));
1358 * swap_pager_getpages_async():
1360 * Right now this is emulation of asynchronous operation on top of
1361 * swap_pager_getpages().
1364 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1365 int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1369 r = swap_pager_getpages(object, ma, count, rbehind, rahead);
1374 case VM_PAGER_ERROR:
1381 panic("unhandled swap_pager_getpages() error %d", r);
1383 (iodone)(arg, ma, count, error);
1389 * swap_pager_putpages:
1391 * Assign swap (if necessary) and initiate I/O on the specified pages.
1393 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1394 * are automatically converted to SWAP objects.
1396 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1397 * vm_page reservation system coupled with properly written VFS devices
1398 * should ensure that no low-memory deadlock occurs. This is an area
1401 * The parent has N vm_object_pip_add() references prior to
1402 * calling us and will remove references for rtvals[] that are
1403 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1406 * The parent has soft-busy'd the pages it passes us and will unbusy
1407 * those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
1408 * We need to unbusy the rest on I/O completion.
1411 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1412 int flags, int *rtvals)
1415 daddr_t addr, blk, n_free, s_free;
1420 KASSERT(count == 0 || ma[0]->object == object,
1421 ("%s: object mismatch %p/%p",
1422 __func__, object, ma[0]->object));
1427 * Turn object into OBJT_SWAP. Force sync if not a pageout process.
1429 if (object->type != OBJT_SWAP) {
1430 addr = swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1431 KASSERT(addr == SWAPBLK_NONE,
1432 ("unexpected object swap block"));
1434 VM_OBJECT_WUNLOCK(object);
1435 async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
1436 swp_pager_init_freerange(&s_free, &n_free);
1441 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1442 * The page is left dirty until the pageout operation completes
1445 for (i = 0; i < count; i += n) {
1446 /* Maximum I/O size is limited by maximum swap block size. */
1447 n = min(count - i, nsw_cluster_max);
1450 mtx_lock(&swbuf_mtx);
1451 while (nsw_wcount_async == 0)
1452 msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1455 mtx_unlock(&swbuf_mtx);
1458 /* Get a block of swap of size up to size n. */
1459 VM_OBJECT_WLOCK(object);
1460 blk = swp_pager_getswapspace(&n);
1461 if (blk == SWAPBLK_NONE) {
1462 VM_OBJECT_WUNLOCK(object);
1463 mtx_lock(&swbuf_mtx);
1464 if (++nsw_wcount_async == 1)
1465 wakeup(&nsw_wcount_async);
1466 mtx_unlock(&swbuf_mtx);
1467 for (j = 0; j < n; ++j)
1468 rtvals[i + j] = VM_PAGER_FAIL;
1471 for (j = 0; j < n; ++j) {
1473 vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1474 addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1476 if (addr != SWAPBLK_NONE)
1477 swp_pager_update_freerange(&s_free, &n_free,
1479 MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1480 mreq->oflags |= VPO_SWAPINPROG;
1482 VM_OBJECT_WUNLOCK(object);
1484 bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1486 bp->b_flags = B_ASYNC;
1487 bp->b_flags |= B_PAGING;
1488 bp->b_iocmd = BIO_WRITE;
1490 bp->b_rcred = crhold(thread0.td_ucred);
1491 bp->b_wcred = crhold(thread0.td_ucred);
1492 bp->b_bcount = PAGE_SIZE * n;
1493 bp->b_bufsize = PAGE_SIZE * n;
1495 for (j = 0; j < n; j++)
1496 bp->b_pages[j] = ma[i + j];
1500 * Must set dirty range for NFS to work.
1503 bp->b_dirtyend = bp->b_bcount;
1505 VM_CNT_INC(v_swapout);
1506 VM_CNT_ADD(v_swappgsout, bp->b_npages);
1509 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1510 * can call the async completion routine at the end of a
1511 * synchronous I/O operation. Otherwise, our caller would
1512 * perform duplicate unbusy and wakeup operations on the page
1513 * and object, respectively.
1515 for (j = 0; j < n; j++)
1516 rtvals[i + j] = VM_PAGER_PEND;
1521 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1524 bp->b_iodone = swp_pager_async_iodone;
1526 swp_pager_strategy(bp);
1533 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1535 bp->b_iodone = bdone;
1536 swp_pager_strategy(bp);
1539 * Wait for the sync I/O to complete.
1541 bwait(bp, PVM, "swwrt");
1544 * Now that we are through with the bp, we can call the
1545 * normal async completion, which frees everything up.
1547 swp_pager_async_iodone(bp);
1549 swp_pager_freeswapspace(s_free, n_free);
1550 VM_OBJECT_WLOCK(object);
1554 * swp_pager_async_iodone:
1556 * Completion routine for asynchronous reads and writes from/to swap.
1557 * Also called manually by synchronous code to finish up a bp.
1559 * This routine may not sleep.
1562 swp_pager_async_iodone(struct buf *bp)
1565 vm_object_t object = NULL;
1568 * Report error - unless we ran out of memory, in which case
1569 * we've already logged it in swapgeom_strategy().
1571 if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
1573 "swap_pager: I/O error - %s failed; blkno %ld,"
1574 "size %ld, error %d\n",
1575 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1583 * remove the mapping for kernel virtual
1586 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1588 bp->b_data = bp->b_kvabase;
1591 object = bp->b_pages[0]->object;
1592 VM_OBJECT_WLOCK(object);
1596 * cleanup pages. If an error occurs writing to swap, we are in
1597 * very serious trouble. If it happens to be a disk error, though,
1598 * we may be able to recover by reassigning the swap later on. So
1599 * in this case we remove the m->swapblk assignment for the page
1600 * but do not free it in the rlist. The errornous block(s) are thus
1601 * never reallocated as swap. Redirty the page and continue.
1603 for (i = 0; i < bp->b_npages; ++i) {
1604 vm_page_t m = bp->b_pages[i];
1606 m->oflags &= ~VPO_SWAPINPROG;
1607 if (m->oflags & VPO_SWAPSLEEP) {
1608 m->oflags &= ~VPO_SWAPSLEEP;
1609 wakeup(&object->handle);
1612 /* We always have space after I/O, successful or not. */
1613 vm_page_aflag_set(m, PGA_SWAP_SPACE);
1615 if (bp->b_ioflags & BIO_ERROR) {
1617 * If an error occurs I'd love to throw the swapblk
1618 * away without freeing it back to swapspace, so it
1619 * can never be used again. But I can't from an
1622 if (bp->b_iocmd == BIO_READ) {
1624 * NOTE: for reads, m->dirty will probably
1625 * be overridden by the original caller of
1626 * getpages so don't play cute tricks here.
1631 * If a write error occurs, reactivate page
1632 * so it doesn't clog the inactive list,
1633 * then finish the I/O.
1635 MPASS(m->dirty == VM_PAGE_BITS_ALL);
1637 /* PQ_UNSWAPPABLE? */
1638 vm_page_activate(m);
1641 } else if (bp->b_iocmd == BIO_READ) {
1643 * NOTE: for reads, m->dirty will probably be
1644 * overridden by the original caller of getpages so
1645 * we cannot set them in order to free the underlying
1646 * swap in a low-swap situation. I don't think we'd
1647 * want to do that anyway, but it was an optimization
1648 * that existed in the old swapper for a time before
1649 * it got ripped out due to precisely this problem.
1651 KASSERT(!pmap_page_is_mapped(m),
1652 ("swp_pager_async_iodone: page %p is mapped", m));
1653 KASSERT(m->dirty == 0,
1654 ("swp_pager_async_iodone: page %p is dirty", m));
1657 if (i < bp->b_pgbefore ||
1658 i >= bp->b_npages - bp->b_pgafter)
1659 vm_page_readahead_finish(m);
1662 * For write success, clear the dirty
1663 * status, then finish the I/O ( which decrements the
1664 * busy count and possibly wakes waiter's up ).
1665 * A page is only written to swap after a period of
1666 * inactivity. Therefore, we do not expect it to be
1669 KASSERT(!pmap_page_is_write_mapped(m),
1670 ("swp_pager_async_iodone: page %p is not write"
1673 vm_page_deactivate_noreuse(m);
1679 * adjust pip. NOTE: the original parent may still have its own
1680 * pip refs on the object.
1682 if (object != NULL) {
1683 vm_object_pip_wakeupn(object, bp->b_npages);
1684 VM_OBJECT_WUNLOCK(object);
1688 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1689 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1690 * trigger a KASSERT in relpbuf().
1694 bp->b_bufobj = NULL;
1697 * release the physical I/O buffer
1699 if (bp->b_flags & B_ASYNC) {
1700 mtx_lock(&swbuf_mtx);
1701 if (++nsw_wcount_async == 1)
1702 wakeup(&nsw_wcount_async);
1703 mtx_unlock(&swbuf_mtx);
1705 uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
1709 swap_pager_nswapdev(void)
1716 swp_pager_force_dirty(vm_page_t m)
1720 swap_pager_unswapped(m);
1725 * swap_pager_swapoff_object:
1727 * Page in all of the pages that have been paged out for an object
1731 swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
1737 int i, nv, rahead, rv;
1739 KASSERT(object->type == OBJT_SWAP,
1740 ("%s: Object not swappable", __func__));
1742 for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1743 &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1744 if ((object->flags & OBJ_DEAD) != 0) {
1746 * Make sure that pending writes finish before
1749 vm_object_pip_wait(object, "swpoff");
1750 swp_pager_meta_free_all(object);
1753 for (i = 0; i < SWAP_META_PAGES; i++) {
1755 * Count the number of contiguous valid blocks.
1757 for (nv = 0; nv < SWAP_META_PAGES - i; nv++) {
1758 blk = sb->d[i + nv];
1759 if (!swp_pager_isondev(blk, sp) ||
1760 blk == SWAPBLK_NONE)
1767 * Look for a page corresponding to the first
1768 * valid block and ensure that any pending paging
1769 * operations on it are complete. If the page is valid,
1770 * mark it dirty and free the swap block. Try to batch
1771 * this operation since it may cause sp to be freed,
1772 * meaning that we must restart the scan. Avoid busying
1773 * valid pages since we may block forever on kernel
1776 m = vm_page_lookup(object, sb->p + i);
1778 m = vm_page_alloc(object, sb->p + i,
1779 VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
1783 if ((m->oflags & VPO_SWAPINPROG) != 0) {
1784 m->oflags |= VPO_SWAPSLEEP;
1785 VM_OBJECT_SLEEP(object, &object->handle,
1789 if (vm_page_all_valid(m)) {
1791 swp_pager_force_dirty(m);
1792 } while (--nv > 0 &&
1793 (m = vm_page_next(m)) != NULL &&
1794 vm_page_all_valid(m) &&
1795 (m->oflags & VPO_SWAPINPROG) == 0);
1798 if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL))
1802 vm_object_pip_add(object, 1);
1803 rahead = SWAP_META_PAGES;
1804 rv = swap_pager_getpages_locked(object, &m, 1, NULL,
1806 if (rv != VM_PAGER_OK)
1807 panic("%s: read from swap failed: %d",
1809 vm_object_pip_wakeupn(object, 1);
1810 VM_OBJECT_WLOCK(object);
1814 * The object lock was dropped so we must restart the
1815 * scan of this swap block. Pages paged in during this
1816 * iteration will be marked dirty in a future iteration.
1820 if (i == SWAP_META_PAGES)
1821 pi = sb->p + SWAP_META_PAGES;
1826 * swap_pager_swapoff:
1828 * Page in all of the pages that have been paged out to the
1829 * given device. The corresponding blocks in the bitmap must be
1830 * marked as allocated and the device must be flagged SW_CLOSING.
1831 * There may be no processes swapped out to the device.
1833 * This routine may block.
1836 swap_pager_swapoff(struct swdevt *sp)
1841 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1845 mtx_lock(&vm_object_list_mtx);
1846 TAILQ_FOREACH(object, &vm_object_list, object_list) {
1847 if (object->type != OBJT_SWAP)
1849 mtx_unlock(&vm_object_list_mtx);
1850 /* Depends on type-stability. */
1851 VM_OBJECT_WLOCK(object);
1854 * Dead objects are eventually terminated on their own.
1856 if ((object->flags & OBJ_DEAD) != 0)
1860 * Sync with fences placed after pctrie
1861 * initialization. We must not access pctrie below
1862 * unless we checked that our object is swap and not
1865 atomic_thread_fence_acq();
1866 if (object->type != OBJT_SWAP)
1869 swap_pager_swapoff_object(sp, object);
1871 VM_OBJECT_WUNLOCK(object);
1872 mtx_lock(&vm_object_list_mtx);
1874 mtx_unlock(&vm_object_list_mtx);
1878 * Objects may be locked or paging to the device being
1879 * removed, so we will miss their pages and need to
1880 * make another pass. We have marked this device as
1881 * SW_CLOSING, so the activity should finish soon.
1884 if (retries > 100) {
1885 panic("swapoff: failed to locate %d swap blocks",
1888 pause("swpoff", hz / 20);
1891 EVENTHANDLER_INVOKE(swapoff, sp);
1894 /************************************************************************
1896 ************************************************************************
1898 * These routines manipulate the swap metadata stored in the
1901 * Swap metadata is implemented with a global hash and not directly
1902 * linked into the object. Instead the object simply contains
1903 * appropriate tracking counters.
1907 * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
1910 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
1914 MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
1915 for (i = start; i < limit; i++) {
1916 if (sb->d[i] != SWAPBLK_NONE)
1923 * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
1925 * Nothing is done if the block is still in use.
1928 swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
1931 if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
1932 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
1933 uma_zfree(swblk_zone, sb);
1938 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
1940 * We first convert the object to a swap object if it is a default
1943 * The specified swapblk is added to the object's swap metadata. If
1944 * the swapblk is not valid, it is freed instead. Any previously
1945 * assigned swapblk is returned.
1948 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
1950 static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
1951 struct swblk *sb, *sb1;
1952 vm_pindex_t modpi, rdpi;
1953 daddr_t prev_swapblk;
1956 VM_OBJECT_ASSERT_WLOCKED(object);
1959 * Convert default object to swap object if necessary
1961 if (object->type != OBJT_SWAP) {
1962 pctrie_init(&object->un_pager.swp.swp_blks);
1965 * Ensure that swap_pager_swapoff()'s iteration over
1966 * object_list does not see a garbage pctrie.
1968 atomic_thread_fence_rel();
1970 object->type = OBJT_SWAP;
1971 object->un_pager.swp.writemappings = 0;
1972 KASSERT((object->flags & OBJ_ANON) != 0 ||
1973 object->handle == NULL,
1974 ("default pager %p with handle %p",
1975 object, object->handle));
1978 rdpi = rounddown(pindex, SWAP_META_PAGES);
1979 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
1981 if (swapblk == SWAPBLK_NONE)
1982 return (SWAPBLK_NONE);
1984 sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
1985 pageproc ? M_USE_RESERVE : 0));
1988 for (i = 0; i < SWAP_META_PAGES; i++)
1989 sb->d[i] = SWAPBLK_NONE;
1990 if (atomic_cmpset_int(&swblk_zone_exhausted,
1992 printf("swblk zone ok\n");
1995 VM_OBJECT_WUNLOCK(object);
1996 if (uma_zone_exhausted(swblk_zone)) {
1997 if (atomic_cmpset_int(&swblk_zone_exhausted,
1999 printf("swap blk zone exhausted, "
2000 "increase kern.maxswzone\n");
2001 vm_pageout_oom(VM_OOM_SWAPZ);
2002 pause("swzonxb", 10);
2004 uma_zwait(swblk_zone);
2005 VM_OBJECT_WLOCK(object);
2006 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2010 * Somebody swapped out a nearby page,
2011 * allocating swblk at the rdpi index,
2012 * while we dropped the object lock.
2017 error = SWAP_PCTRIE_INSERT(
2018 &object->un_pager.swp.swp_blks, sb);
2020 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2022 printf("swpctrie zone ok\n");
2025 VM_OBJECT_WUNLOCK(object);
2026 if (uma_zone_exhausted(swpctrie_zone)) {
2027 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2029 printf("swap pctrie zone exhausted, "
2030 "increase kern.maxswzone\n");
2031 vm_pageout_oom(VM_OOM_SWAPZ);
2032 pause("swzonxp", 10);
2034 uma_zwait(swpctrie_zone);
2035 VM_OBJECT_WLOCK(object);
2036 sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2039 uma_zfree(swblk_zone, sb);
2046 MPASS(sb->p == rdpi);
2048 modpi = pindex % SWAP_META_PAGES;
2049 /* Return prior contents of metadata. */
2050 prev_swapblk = sb->d[modpi];
2051 /* Enter block into metadata. */
2052 sb->d[modpi] = swapblk;
2055 * Free the swblk if we end up with the empty page run.
2057 if (swapblk == SWAPBLK_NONE)
2058 swp_pager_free_empty_swblk(object, sb);
2059 return (prev_swapblk);
2063 * SWP_PAGER_META_TRANSFER() - free a range of blocks in the srcobject's swap
2064 * metadata, or transfer it into dstobject.
2066 * This routine will free swap metadata structures as they are cleaned
2070 swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
2071 vm_pindex_t pindex, vm_pindex_t count)
2074 daddr_t n_free, s_free;
2075 vm_pindex_t offset, last;
2076 int i, limit, start;
2078 VM_OBJECT_ASSERT_WLOCKED(srcobject);
2079 if (srcobject->type != OBJT_SWAP || count == 0)
2082 swp_pager_init_freerange(&s_free, &n_free);
2084 last = pindex + count;
2086 sb = SWAP_PCTRIE_LOOKUP_GE(&srcobject->un_pager.swp.swp_blks,
2087 rounddown(pindex, SWAP_META_PAGES));
2088 if (sb == NULL || sb->p >= last)
2090 start = pindex > sb->p ? pindex - sb->p : 0;
2091 limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2093 for (i = start; i < limit; i++) {
2094 if (sb->d[i] == SWAPBLK_NONE)
2096 if (dstobject == NULL ||
2097 !swp_pager_xfer_source(srcobject, dstobject,
2098 sb->p + i - offset, sb->d[i])) {
2099 swp_pager_update_freerange(&s_free, &n_free,
2102 sb->d[i] = SWAPBLK_NONE;
2104 pindex = sb->p + SWAP_META_PAGES;
2105 if (swp_pager_swblk_empty(sb, 0, start) &&
2106 swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2107 SWAP_PCTRIE_REMOVE(&srcobject->un_pager.swp.swp_blks,
2109 uma_zfree(swblk_zone, sb);
2112 swp_pager_freeswapspace(s_free, n_free);
2116 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
2118 * The requested range of blocks is freed, with any associated swap
2119 * returned to the swap bitmap.
2121 * This routine will free swap metadata structures as they are cleaned
2122 * out. This routine does *NOT* operate on swap metadata associated
2123 * with resident pages.
2126 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count)
2128 swp_pager_meta_transfer(object, NULL, pindex, count);
2132 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
2134 * This routine locates and destroys all swap metadata associated with
2138 swp_pager_meta_free_all(vm_object_t object)
2141 daddr_t n_free, s_free;
2145 VM_OBJECT_ASSERT_WLOCKED(object);
2146 if (object->type != OBJT_SWAP)
2149 swp_pager_init_freerange(&s_free, &n_free);
2150 for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
2151 &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
2152 pindex = sb->p + SWAP_META_PAGES;
2153 for (i = 0; i < SWAP_META_PAGES; i++) {
2154 if (sb->d[i] == SWAPBLK_NONE)
2156 swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
2158 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2159 uma_zfree(swblk_zone, sb);
2161 swp_pager_freeswapspace(s_free, n_free);
2165 * SWP_PAGER_METACTL() - misc control of swap meta data.
2167 * This routine is capable of looking up, or removing swapblk
2168 * assignments in the swap meta data. It returns the swapblk being
2169 * looked-up, popped, or SWAPBLK_NONE if the block was invalid.
2171 * When acting on a busy resident page and paging is in progress, we
2172 * have to wait until paging is complete but otherwise can act on the
2176 swp_pager_meta_lookup(vm_object_t object, vm_pindex_t pindex)
2180 VM_OBJECT_ASSERT_LOCKED(object);
2183 * The meta data only exists if the object is OBJT_SWAP
2184 * and even then might not be allocated yet.
2186 KASSERT(object->type == OBJT_SWAP,
2187 ("Lookup object not swappable"));
2189 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2190 rounddown(pindex, SWAP_META_PAGES));
2192 return (SWAPBLK_NONE);
2193 return (sb->d[pindex % SWAP_META_PAGES]);
2197 * Returns the least page index which is greater than or equal to the
2198 * parameter pindex and for which there is a swap block allocated.
2199 * Returns object's size if the object's type is not swap or if there
2200 * are no allocated swap blocks for the object after the requested
2204 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2209 VM_OBJECT_ASSERT_LOCKED(object);
2210 if (object->type != OBJT_SWAP)
2211 return (object->size);
2213 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2214 rounddown(pindex, SWAP_META_PAGES));
2216 return (object->size);
2217 if (sb->p < pindex) {
2218 for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2219 if (sb->d[i] != SWAPBLK_NONE)
2222 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2223 roundup(pindex, SWAP_META_PAGES));
2225 return (object->size);
2227 for (i = 0; i < SWAP_META_PAGES; i++) {
2228 if (sb->d[i] != SWAPBLK_NONE)
2233 * We get here if a swblk is present in the trie but it
2234 * doesn't map any blocks.
2237 return (object->size);
2241 * System call swapon(name) enables swapping on device name,
2242 * which must be in the swdevsw. Return EBUSY
2243 * if already swapping on this device.
2245 #ifndef _SYS_SYSPROTO_H_
2246 struct swapon_args {
2256 sys_swapon(struct thread *td, struct swapon_args *uap)
2260 struct nameidata nd;
2263 error = priv_check(td, PRIV_SWAPON);
2267 sx_xlock(&swdev_syscall_lock);
2270 * Swap metadata may not fit in the KVM if we have physical
2273 if (swblk_zone == NULL) {
2278 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2284 NDFREE(&nd, NDF_ONLY_PNBUF);
2287 if (vn_isdisk(vp, &error)) {
2288 error = swapongeom(vp);
2289 } else if (vp->v_type == VREG &&
2290 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2291 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2293 * Allow direct swapping to NFS regular files in the same
2294 * way that nfs_mountroot() sets up diskless swapping.
2296 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2302 sx_xunlock(&swdev_syscall_lock);
2307 * Check that the total amount of swap currently configured does not
2308 * exceed half the theoretical maximum. If it does, print a warning
2312 swapon_check_swzone(void)
2315 /* recommend using no more than half that amount */
2316 if (swap_total > swap_maxpages / 2) {
2317 printf("warning: total configured swap (%lu pages) "
2318 "exceeds maximum recommended amount (%lu pages).\n",
2319 swap_total, swap_maxpages / 2);
2320 printf("warning: increase kern.maxswzone "
2321 "or reduce amount of swap.\n");
2326 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2327 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2329 struct swdevt *sp, *tsp;
2334 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2335 * First chop nblks off to page-align it, then convert.
2337 * sw->sw_nblks is in page-sized chunks now too.
2339 nblks &= ~(ctodb(1) - 1);
2340 nblks = dbtoc(nblks);
2343 * If we go beyond this, we get overflows in the radix
2346 mblocks = 0x40000000 / BLIST_META_RADIX;
2347 if (nblks > mblocks) {
2349 "WARNING: reducing swap size to maximum of %luMB per unit\n",
2350 mblocks / 1024 / 1024 * PAGE_SIZE);
2354 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2358 sp->sw_nblks = nblks;
2360 sp->sw_strategy = strategy;
2361 sp->sw_close = close;
2362 sp->sw_flags = flags;
2364 sp->sw_blist = blist_create(nblks, M_WAITOK);
2366 * Do not free the first blocks in order to avoid overwriting
2367 * any bsd label at the front of the partition
2369 blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2370 nblks - howmany(BBSIZE, PAGE_SIZE));
2373 mtx_lock(&sw_dev_mtx);
2374 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2375 if (tsp->sw_end >= dvbase) {
2377 * We put one uncovered page between the devices
2378 * in order to definitively prevent any cross-device
2381 dvbase = tsp->sw_end + 1;
2384 sp->sw_first = dvbase;
2385 sp->sw_end = dvbase + nblks;
2386 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2388 swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2389 swap_total += nblks;
2390 swapon_check_swzone();
2392 mtx_unlock(&sw_dev_mtx);
2393 EVENTHANDLER_INVOKE(swapon, sp);
2397 * SYSCALL: swapoff(devname)
2399 * Disable swapping on the given device.
2401 * XXX: Badly designed system call: it should use a device index
2402 * rather than filename as specification. We keep sw_vp around
2403 * only to make this work.
2405 #ifndef _SYS_SYSPROTO_H_
2406 struct swapoff_args {
2416 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2419 struct nameidata nd;
2423 error = priv_check(td, PRIV_SWAPOFF);
2427 sx_xlock(&swdev_syscall_lock);
2429 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2434 NDFREE(&nd, NDF_ONLY_PNBUF);
2437 mtx_lock(&sw_dev_mtx);
2438 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2439 if (sp->sw_vp == vp)
2442 mtx_unlock(&sw_dev_mtx);
2447 error = swapoff_one(sp, td->td_ucred);
2449 sx_xunlock(&swdev_syscall_lock);
2454 swapoff_one(struct swdevt *sp, struct ucred *cred)
2461 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2463 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2464 error = mac_system_check_swapoff(cred, sp->sw_vp);
2465 (void) VOP_UNLOCK(sp->sw_vp);
2469 nblks = sp->sw_nblks;
2472 * We can turn off this swap device safely only if the
2473 * available virtual memory in the system will fit the amount
2474 * of data we will have to page back in, plus an epsilon so
2475 * the system doesn't become critically low on swap space.
2477 if (vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
2481 * Prevent further allocations on this device.
2483 mtx_lock(&sw_dev_mtx);
2484 sp->sw_flags |= SW_CLOSING;
2485 swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2486 swap_total -= nblks;
2487 mtx_unlock(&sw_dev_mtx);
2490 * Page in the contents of the device and close it.
2492 swap_pager_swapoff(sp);
2494 sp->sw_close(curthread, sp);
2495 mtx_lock(&sw_dev_mtx);
2497 TAILQ_REMOVE(&swtailq, sp, sw_list);
2499 if (nswapdev == 0) {
2500 swap_pager_full = 2;
2501 swap_pager_almost_full = 1;
2505 mtx_unlock(&sw_dev_mtx);
2506 blist_destroy(sp->sw_blist);
2507 free(sp, M_VMPGDATA);
2514 struct swdevt *sp, *spt;
2515 const char *devname;
2518 sx_xlock(&swdev_syscall_lock);
2520 mtx_lock(&sw_dev_mtx);
2521 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2522 mtx_unlock(&sw_dev_mtx);
2523 if (vn_isdisk(sp->sw_vp, NULL))
2524 devname = devtoname(sp->sw_vp->v_rdev);
2527 error = swapoff_one(sp, thread0.td_ucred);
2529 printf("Cannot remove swap device %s (error=%d), "
2530 "skipping.\n", devname, error);
2531 } else if (bootverbose) {
2532 printf("Swap device %s removed.\n", devname);
2534 mtx_lock(&sw_dev_mtx);
2536 mtx_unlock(&sw_dev_mtx);
2538 sx_xunlock(&swdev_syscall_lock);
2542 swap_pager_status(int *total, int *used)
2548 mtx_lock(&sw_dev_mtx);
2549 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2550 *total += sp->sw_nblks;
2551 *used += sp->sw_used;
2553 mtx_unlock(&sw_dev_mtx);
2557 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2560 const char *tmp_devname;
2565 mtx_lock(&sw_dev_mtx);
2566 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2571 xs->xsw_version = XSWDEV_VERSION;
2572 xs->xsw_dev = sp->sw_dev;
2573 xs->xsw_flags = sp->sw_flags;
2574 xs->xsw_nblks = sp->sw_nblks;
2575 xs->xsw_used = sp->sw_used;
2576 if (devname != NULL) {
2577 if (vn_isdisk(sp->sw_vp, NULL))
2578 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2580 tmp_devname = "[file]";
2581 strncpy(devname, tmp_devname, len);
2586 mtx_unlock(&sw_dev_mtx);
2590 #if defined(COMPAT_FREEBSD11)
2591 #define XSWDEV_VERSION_11 1
2601 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2604 u_int xsw_dev1, xsw_dev2;
2612 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2615 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2616 struct xswdev32 xs32;
2618 #if defined(COMPAT_FREEBSD11)
2619 struct xswdev11 xs11;
2623 if (arg2 != 1) /* name length */
2625 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2628 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2629 if (req->oldlen == sizeof(xs32)) {
2630 xs32.xsw_version = XSWDEV_VERSION;
2631 xs32.xsw_dev1 = xs.xsw_dev;
2632 xs32.xsw_dev2 = xs.xsw_dev >> 32;
2633 xs32.xsw_flags = xs.xsw_flags;
2634 xs32.xsw_nblks = xs.xsw_nblks;
2635 xs32.xsw_used = xs.xsw_used;
2636 error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2640 #if defined(COMPAT_FREEBSD11)
2641 if (req->oldlen == sizeof(xs11)) {
2642 xs11.xsw_version = XSWDEV_VERSION_11;
2643 xs11.xsw_dev = xs.xsw_dev; /* truncation */
2644 xs11.xsw_flags = xs.xsw_flags;
2645 xs11.xsw_nblks = xs.xsw_nblks;
2646 xs11.xsw_used = xs.xsw_used;
2647 error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2651 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2655 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2656 "Number of swap devices");
2657 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2658 sysctl_vm_swap_info,
2659 "Swap statistics by device");
2662 * Count the approximate swap usage in pages for a vmspace. The
2663 * shadowed or not yet copied on write swap blocks are not accounted.
2664 * The map must be locked.
2667 vmspace_swap_count(struct vmspace *vmspace)
2677 map = &vmspace->vm_map;
2680 VM_MAP_ENTRY_FOREACH(cur, map) {
2681 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2683 object = cur->object.vm_object;
2684 if (object == NULL || object->type != OBJT_SWAP)
2686 VM_OBJECT_RLOCK(object);
2687 if (object->type != OBJT_SWAP)
2689 pi = OFF_TO_IDX(cur->offset);
2690 e = pi + OFF_TO_IDX(cur->end - cur->start);
2691 for (;; pi = sb->p + SWAP_META_PAGES) {
2692 sb = SWAP_PCTRIE_LOOKUP_GE(
2693 &object->un_pager.swp.swp_blks, pi);
2694 if (sb == NULL || sb->p >= e)
2696 for (i = 0; i < SWAP_META_PAGES; i++) {
2697 if (sb->p + i < e &&
2698 sb->d[i] != SWAPBLK_NONE)
2703 VM_OBJECT_RUNLOCK(object);
2711 * Swapping onto disk devices.
2715 static g_orphan_t swapgeom_orphan;
2717 static struct g_class g_swap_class = {
2719 .version = G_VERSION,
2720 .orphan = swapgeom_orphan,
2723 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2727 swapgeom_close_ev(void *arg, int flags)
2729 struct g_consumer *cp;
2732 g_access(cp, -1, -1, 0);
2734 g_destroy_consumer(cp);
2738 * Add a reference to the g_consumer for an inflight transaction.
2741 swapgeom_acquire(struct g_consumer *cp)
2744 mtx_assert(&sw_dev_mtx, MA_OWNED);
2749 * Remove a reference from the g_consumer. Post a close event if all
2750 * references go away, since the function might be called from the
2754 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2757 mtx_assert(&sw_dev_mtx, MA_OWNED);
2759 if (cp->index == 0) {
2760 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2766 swapgeom_done(struct bio *bp2)
2770 struct g_consumer *cp;
2772 bp = bp2->bio_caller2;
2774 bp->b_ioflags = bp2->bio_flags;
2776 bp->b_ioflags |= BIO_ERROR;
2777 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2778 bp->b_error = bp2->bio_error;
2779 bp->b_caller1 = NULL;
2781 sp = bp2->bio_caller1;
2782 mtx_lock(&sw_dev_mtx);
2783 swapgeom_release(cp, sp);
2784 mtx_unlock(&sw_dev_mtx);
2789 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2792 struct g_consumer *cp;
2794 mtx_lock(&sw_dev_mtx);
2797 mtx_unlock(&sw_dev_mtx);
2798 bp->b_error = ENXIO;
2799 bp->b_ioflags |= BIO_ERROR;
2803 swapgeom_acquire(cp);
2804 mtx_unlock(&sw_dev_mtx);
2805 if (bp->b_iocmd == BIO_WRITE)
2808 bio = g_alloc_bio();
2810 mtx_lock(&sw_dev_mtx);
2811 swapgeom_release(cp, sp);
2812 mtx_unlock(&sw_dev_mtx);
2813 bp->b_error = ENOMEM;
2814 bp->b_ioflags |= BIO_ERROR;
2815 printf("swap_pager: cannot allocate bio\n");
2820 bp->b_caller1 = bio;
2821 bio->bio_caller1 = sp;
2822 bio->bio_caller2 = bp;
2823 bio->bio_cmd = bp->b_iocmd;
2824 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2825 bio->bio_length = bp->b_bcount;
2826 bio->bio_done = swapgeom_done;
2827 if (!buf_mapped(bp)) {
2828 bio->bio_ma = bp->b_pages;
2829 bio->bio_data = unmapped_buf;
2830 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2831 bio->bio_ma_n = bp->b_npages;
2832 bio->bio_flags |= BIO_UNMAPPED;
2834 bio->bio_data = bp->b_data;
2837 g_io_request(bio, cp);
2842 swapgeom_orphan(struct g_consumer *cp)
2847 mtx_lock(&sw_dev_mtx);
2848 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2849 if (sp->sw_id == cp) {
2850 sp->sw_flags |= SW_CLOSING;
2855 * Drop reference we were created with. Do directly since we're in a
2856 * special context where we don't have to queue the call to
2857 * swapgeom_close_ev().
2860 destroy = ((sp != NULL) && (cp->index == 0));
2863 mtx_unlock(&sw_dev_mtx);
2865 swapgeom_close_ev(cp, 0);
2869 swapgeom_close(struct thread *td, struct swdevt *sw)
2871 struct g_consumer *cp;
2873 mtx_lock(&sw_dev_mtx);
2876 mtx_unlock(&sw_dev_mtx);
2879 * swapgeom_close() may be called from the biodone context,
2880 * where we cannot perform topology changes. Delegate the
2881 * work to the events thread.
2884 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2888 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2890 struct g_provider *pp;
2891 struct g_consumer *cp;
2892 static struct g_geom *gp;
2897 pp = g_dev_getprovider(dev);
2900 mtx_lock(&sw_dev_mtx);
2901 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2903 if (cp != NULL && cp->provider == pp) {
2904 mtx_unlock(&sw_dev_mtx);
2908 mtx_unlock(&sw_dev_mtx);
2910 gp = g_new_geomf(&g_swap_class, "swap");
2911 cp = g_new_consumer(gp);
2912 cp->index = 1; /* Number of active I/Os, plus one for being active. */
2913 cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2916 * XXX: Every time you think you can improve the margin for
2917 * footshooting, somebody depends on the ability to do so:
2918 * savecore(8) wants to write to our swapdev so we cannot
2919 * set an exclusive count :-(
2921 error = g_access(cp, 1, 1, 0);
2924 g_destroy_consumer(cp);
2927 nblks = pp->mediasize / DEV_BSIZE;
2928 swaponsomething(vp, cp, nblks, swapgeom_strategy,
2929 swapgeom_close, dev2udev(dev),
2930 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
2935 swapongeom(struct vnode *vp)
2939 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2940 if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) {
2944 error = swapongeom_locked(vp->v_rdev, vp);
2945 g_topology_unlock();
2954 * This is used mainly for network filesystem (read: probably only tested
2955 * with NFS) swapfiles.
2960 swapdev_strategy(struct buf *bp, struct swdevt *sp)
2964 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
2968 if (bp->b_iocmd == BIO_WRITE) {
2970 bufobj_wdrop(bp->b_bufobj);
2971 bufobj_wref(&vp2->v_bufobj);
2973 if (bp->b_bufobj != &vp2->v_bufobj)
2974 bp->b_bufobj = &vp2->v_bufobj;
2976 bp->b_iooffset = dbtob(bp->b_blkno);
2982 swapdev_close(struct thread *td, struct swdevt *sp)
2985 VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
2991 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
2998 mtx_lock(&sw_dev_mtx);
2999 TAILQ_FOREACH(sp, &swtailq, sw_list) {
3000 if (sp->sw_id == vp) {
3001 mtx_unlock(&sw_dev_mtx);
3005 mtx_unlock(&sw_dev_mtx);
3007 (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3009 error = mac_system_check_swapon(td->td_ucred, vp);
3012 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
3013 (void) VOP_UNLOCK(vp);
3017 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
3023 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
3027 new = nsw_wcount_async_max;
3028 error = sysctl_handle_int(oidp, &new, 0, req);
3029 if (error != 0 || req->newptr == NULL)
3032 if (new > nswbuf / 2 || new < 1)
3035 mtx_lock(&swbuf_mtx);
3036 while (nsw_wcount_async_max != new) {
3038 * Adjust difference. If the current async count is too low,
3039 * we will need to sqeeze our update slowly in. Sleep with a
3040 * higher priority than getpbuf() to finish faster.
3042 n = new - nsw_wcount_async_max;
3043 if (nsw_wcount_async + n >= 0) {
3044 nsw_wcount_async += n;
3045 nsw_wcount_async_max += n;
3046 wakeup(&nsw_wcount_async);
3048 nsw_wcount_async_max -= nsw_wcount_async;
3049 nsw_wcount_async = 0;
3050 msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
3054 mtx_unlock(&swbuf_mtx);
3060 swap_pager_update_writecount(vm_object_t object, vm_offset_t start,
3064 VM_OBJECT_WLOCK(object);
3065 KASSERT((object->flags & OBJ_ANON) == 0,
3066 ("Splittable object with writecount"));
3067 object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
3068 VM_OBJECT_WUNLOCK(object);
3072 swap_pager_release_writecount(vm_object_t object, vm_offset_t start,
3076 VM_OBJECT_WLOCK(object);
3077 KASSERT((object->flags & OBJ_ANON) == 0,
3078 ("Splittable object with writecount"));
3079 object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
3080 VM_OBJECT_WUNLOCK(object);