2 * SPDX-License-Identifier: BSD-4-Clause
4 * Copyright (c) 1998 Matthew Dillon,
5 * Copyright (c) 1994 John S. Dyson
6 * Copyright (c) 1990 University of Utah.
7 * Copyright (c) 1982, 1986, 1989, 1993
8 * The Regents of the University of California. All rights reserved.
10 * This code is derived from software contributed to Berkeley by
11 * the Systems Programming Group of the University of Utah Computer
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 * 3. All advertising materials mentioning features or use of this software
23 * must display the following acknowledgement:
24 * This product includes software developed by the University of
25 * California, Berkeley and its contributors.
26 * 4. Neither the name of the University nor the names of its contributors
27 * may be used to endorse or promote products derived from this software
28 * without specific prior written permission.
30 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45 * Radix Bitmap 'blists'.
47 * - The new swapper uses the new radix bitmap code. This should scale
48 * to arbitrarily small or arbitrarily large swap spaces and an almost
49 * arbitrary degree of fragmentation.
53 * - on the fly reallocation of swap during putpages. The new system
54 * does not try to keep previously allocated swap blocks for dirty
57 * - on the fly deallocation of swap
59 * - No more garbage collection required. Unnecessarily allocated swap
60 * blocks only exist for dirty vm_page_t's now and these are already
61 * cycled (in a high-load system) by the pager. We also do on-the-fly
62 * removal of invalidated swap blocks when a page is destroyed
65 * from: Utah $Hdr: swap_pager.c 1.4 91/04/30$
67 * @(#)swap_pager.c 8.9 (Berkeley) 3/21/94
68 * @(#)vm_swap.c 8.5 (Berkeley) 2/17/94
71 #include <sys/cdefs.h>
72 __FBSDID("$FreeBSD$");
76 #include <sys/param.h>
78 #include <sys/blist.h>
82 #include <sys/disklabel.h>
83 #include <sys/eventhandler.h>
84 #include <sys/fcntl.h>
86 #include <sys/kernel.h>
87 #include <sys/mount.h>
88 #include <sys/namei.h>
89 #include <sys/malloc.h>
90 #include <sys/pctrie.h>
93 #include <sys/racct.h>
94 #include <sys/resource.h>
95 #include <sys/resourcevar.h>
96 #include <sys/rwlock.h>
98 #include <sys/sysctl.h>
99 #include <sys/sysproto.h>
100 #include <sys/systm.h>
102 #include <sys/vmmeter.h>
103 #include <sys/vnode.h>
105 #include <security/mac/mac_framework.h>
109 #include <vm/vm_map.h>
110 #include <vm/vm_kern.h>
111 #include <vm/vm_object.h>
112 #include <vm/vm_page.h>
113 #include <vm/vm_pager.h>
114 #include <vm/vm_pageout.h>
115 #include <vm/vm_param.h>
116 #include <vm/swap_pager.h>
117 #include <vm/vm_extern.h>
120 #include <geom/geom.h>
123 * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64.
124 * The 64-page limit is due to the radix code (kern/subr_blist.c).
126 #ifndef MAX_PAGEOUT_CLUSTER
127 #define MAX_PAGEOUT_CLUSTER 32
130 #if !defined(SWB_NPAGES)
131 #define SWB_NPAGES MAX_PAGEOUT_CLUSTER
134 #define SWAP_META_PAGES PCTRIE_COUNT
137 * A swblk structure maps each page index within a
138 * SWAP_META_PAGES-aligned and sized range to the address of an
139 * on-disk swap block (or SWAPBLK_NONE). The collection of these
140 * mappings for an entire vm object is implemented as a pc-trie.
144 daddr_t d[SWAP_META_PAGES];
147 static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data");
148 static struct mtx sw_dev_mtx;
149 static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
150 static struct swdevt *swdevhd; /* Allocate from here next */
151 static int nswapdev; /* Number of swap devices */
152 int swap_pager_avail;
153 static struct sx swdev_syscall_lock; /* serialize swap(on|off) */
155 static __exclusive_cache_line u_long swap_reserved;
156 static u_long swap_total;
157 static int sysctl_page_shift(SYSCTL_HANDLER_ARGS);
159 static SYSCTL_NODE(_vm_stats, OID_AUTO, swap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
162 SYSCTL_PROC(_vm, OID_AUTO, swap_reserved, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
163 &swap_reserved, 0, sysctl_page_shift, "A",
164 "Amount of swap storage needed to back all allocated anonymous memory.");
165 SYSCTL_PROC(_vm, OID_AUTO, swap_total, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
166 &swap_total, 0, sysctl_page_shift, "A",
167 "Total amount of available swap storage.");
169 static int overcommit = 0;
170 SYSCTL_INT(_vm, VM_OVERCOMMIT, overcommit, CTLFLAG_RW, &overcommit, 0,
171 "Configure virtual memory overcommit behavior. See tuning(7) "
173 static unsigned long swzone;
174 SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
175 "Actual size of swap metadata zone");
176 static unsigned long swap_maxpages;
177 SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
178 "Maximum amount of swap supported");
180 static COUNTER_U64_DEFINE_EARLY(swap_free_deferred);
181 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_deferred,
182 CTLFLAG_RD, &swap_free_deferred,
183 "Number of pages that deferred freeing swap space");
185 static COUNTER_U64_DEFINE_EARLY(swap_free_completed);
186 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_completed,
187 CTLFLAG_RD, &swap_free_completed,
188 "Number of deferred frees completed");
190 /* bits from overcommit */
191 #define SWAP_RESERVE_FORCE_ON (1 << 0)
192 #define SWAP_RESERVE_RLIMIT_ON (1 << 1)
193 #define SWAP_RESERVE_ALLOW_NONWIRED (1 << 2)
196 sysctl_page_shift(SYSCTL_HANDLER_ARGS)
199 u_long value = *(u_long *)arg1;
201 newval = ((uint64_t)value) << PAGE_SHIFT;
202 return (sysctl_handle_64(oidp, &newval, 0, req));
206 swap_reserve_by_cred_rlimit(u_long pincr, struct ucred *cred, int oc)
211 uip = cred->cr_ruidinfo;
213 prev = atomic_fetchadd_long(&uip->ui_vmsize, pincr);
214 if ((oc & SWAP_RESERVE_RLIMIT_ON) != 0 &&
215 prev + pincr > lim_cur(curthread, RLIMIT_SWAP) &&
216 priv_check(curthread, PRIV_VM_SWAP_NORLIMIT) != 0) {
217 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pincr);
218 KASSERT(prev >= pincr, ("negative vmsize for uid = %d\n", uip->ui_uid));
225 swap_release_by_cred_rlimit(u_long pdecr, struct ucred *cred)
232 uip = cred->cr_ruidinfo;
235 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pdecr);
236 KASSERT(prev >= pdecr, ("negative vmsize for uid = %d\n", uip->ui_uid));
238 atomic_subtract_long(&uip->ui_vmsize, pdecr);
243 swap_reserve_force_rlimit(u_long pincr, struct ucred *cred)
247 uip = cred->cr_ruidinfo;
248 atomic_add_long(&uip->ui_vmsize, pincr);
252 swap_reserve(vm_ooffset_t incr)
255 return (swap_reserve_by_cred(incr, curthread->td_ucred));
259 swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
261 u_long r, s, prev, pincr;
267 static struct timeval lastfail;
269 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
273 if (RACCT_ENABLED()) {
275 error = racct_add(curproc, RACCT_SWAP, incr);
276 PROC_UNLOCK(curproc);
283 prev = atomic_fetchadd_long(&swap_reserved, pincr);
286 oc = atomic_load_int(&overcommit);
287 if (r > s && (oc & SWAP_RESERVE_ALLOW_NONWIRED) != 0) {
288 s += vm_cnt.v_page_count - vm_cnt.v_free_reserved -
291 if ((oc & SWAP_RESERVE_FORCE_ON) != 0 && r > s &&
292 priv_check(curthread, PRIV_VM_SWAP_NOQUOTA) != 0) {
293 prev = atomic_fetchadd_long(&swap_reserved, -pincr);
294 KASSERT(prev >= pincr, ("swap_reserved < incr on overcommit fail"));
298 if (!swap_reserve_by_cred_rlimit(pincr, cred, oc)) {
299 prev = atomic_fetchadd_long(&swap_reserved, -pincr);
300 KASSERT(prev >= pincr, ("swap_reserved < incr on overcommit fail"));
307 if (ppsratecheck(&lastfail, &curfail, 1)) {
308 printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
309 cred->cr_ruidinfo->ui_uid, curproc->p_pid, incr);
312 if (RACCT_ENABLED()) {
314 racct_sub(curproc, RACCT_SWAP, incr);
315 PROC_UNLOCK(curproc);
323 swap_reserve_force(vm_ooffset_t incr)
327 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
331 if (RACCT_ENABLED()) {
333 racct_add_force(curproc, RACCT_SWAP, incr);
334 PROC_UNLOCK(curproc);
338 atomic_add_long(&swap_reserved, pincr);
339 swap_reserve_force_rlimit(pincr, curthread->td_ucred);
343 swap_release(vm_ooffset_t decr)
348 cred = curproc->p_ucred;
349 swap_release_by_cred(decr, cred);
350 PROC_UNLOCK(curproc);
354 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
361 KASSERT((decr & PAGE_MASK) == 0, ("%s: decr: %ju & PAGE_MASK", __func__,
366 prev = atomic_fetchadd_long(&swap_reserved, -pdecr);
367 KASSERT(prev >= pdecr, ("swap_reserved < decr"));
369 atomic_subtract_long(&swap_reserved, pdecr);
372 swap_release_by_cred_rlimit(pdecr, cred);
375 racct_sub_cred(cred, RACCT_SWAP, decr);
379 static int swap_pager_full = 2; /* swap space exhaustion (task killing) */
380 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
381 static struct mtx swbuf_mtx; /* to sync nsw_wcount_async */
382 static int nsw_wcount_async; /* limit async write buffers */
383 static int nsw_wcount_async_max;/* assigned maximum */
384 static int nsw_cluster_max; /* maximum VOP I/O allowed */
386 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
387 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
388 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
389 "Maximum running async swap ops");
390 static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS);
391 SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD |
392 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A",
393 "Swap Fragmentation Info");
395 static struct sx sw_alloc_sx;
398 * "named" and "unnamed" anon region objects. Try to reduce the overhead
399 * of searching a named list by hashing it just a little.
404 #define NOBJLIST(handle) \
405 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
407 static struct pagerlst swap_pager_object_list[NOBJLISTS];
408 static uma_zone_t swwbuf_zone;
409 static uma_zone_t swrbuf_zone;
410 static uma_zone_t swblk_zone;
411 static uma_zone_t swpctrie_zone;
414 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
415 * calls hooked from other parts of the VM system and do not appear here.
416 * (see vm/swap_pager.h).
419 swap_pager_alloc(void *handle, vm_ooffset_t size,
420 vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
421 static void swap_pager_dealloc(vm_object_t object);
422 static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
424 static int swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
425 int *, pgo_getpages_iodone_t, void *);
426 static void swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
428 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
429 static void swap_pager_init(void);
430 static void swap_pager_unswapped(vm_page_t);
431 static void swap_pager_swapoff(struct swdevt *sp);
432 static void swap_pager_update_writecount(vm_object_t object,
433 vm_offset_t start, vm_offset_t end);
434 static void swap_pager_release_writecount(vm_object_t object,
435 vm_offset_t start, vm_offset_t end);
436 static void swap_pager_set_writeable_dirty(vm_object_t object);
437 static bool swap_pager_mightbedirty(vm_object_t object);
438 static void swap_pager_getvp(vm_object_t object, struct vnode **vpp,
441 struct pagerops swappagerops = {
442 .pgo_init = swap_pager_init, /* early system initialization of pager */
443 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */
444 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
445 .pgo_getpages = swap_pager_getpages, /* pagein */
446 .pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
447 .pgo_putpages = swap_pager_putpages, /* pageout */
448 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */
449 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
450 .pgo_update_writecount = swap_pager_update_writecount,
451 .pgo_release_writecount = swap_pager_release_writecount,
452 .pgo_set_writeable_dirty = swap_pager_set_writeable_dirty,
453 .pgo_mightbedirty = swap_pager_mightbedirty,
454 .pgo_getvp = swap_pager_getvp,
458 * swap_*() routines are externally accessible. swp_*() routines are
461 static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
462 static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
464 SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
465 "Maximum size of a swap block in pages");
467 static void swp_sizecheck(void);
468 static void swp_pager_async_iodone(struct buf *bp);
469 static bool swp_pager_swblk_empty(struct swblk *sb, int start, int limit);
470 static void swp_pager_free_empty_swblk(vm_object_t, struct swblk *sb);
471 static int swapongeom(struct vnode *);
472 static int swaponvp(struct thread *, struct vnode *, u_long);
473 static int swapoff_one(struct swdevt *sp, struct ucred *cred);
476 * Swap bitmap functions
478 static void swp_pager_freeswapspace(daddr_t blk, daddr_t npages);
479 static daddr_t swp_pager_getswapspace(int *npages);
484 static daddr_t swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
485 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t);
486 static void swp_pager_meta_transfer(vm_object_t src, vm_object_t dst,
487 vm_pindex_t pindex, vm_pindex_t count);
488 static void swp_pager_meta_free_all(vm_object_t);
489 static daddr_t swp_pager_meta_lookup(vm_object_t, vm_pindex_t);
492 swp_pager_init_freerange(daddr_t *start, daddr_t *num)
495 *start = SWAPBLK_NONE;
500 swp_pager_update_freerange(daddr_t *start, daddr_t *num, daddr_t addr)
503 if (*start + *num == addr) {
506 swp_pager_freeswapspace(*start, *num);
513 swblk_trie_alloc(struct pctrie *ptree)
516 return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
517 M_USE_RESERVE : 0)));
521 swblk_trie_free(struct pctrie *ptree, void *node)
524 uma_zfree(swpctrie_zone, node);
527 PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
530 * SWP_SIZECHECK() - update swap_pager_full indication
532 * update the swap_pager_almost_full indication and warn when we are
533 * about to run out of swap space, using lowat/hiwat hysteresis.
535 * Clear swap_pager_full ( task killing ) indication when lowat is met.
537 * No restrictions on call
538 * This routine may not block.
544 if (swap_pager_avail < nswap_lowat) {
545 if (swap_pager_almost_full == 0) {
546 printf("swap_pager: out of swap space\n");
547 swap_pager_almost_full = 1;
551 if (swap_pager_avail > nswap_hiwat)
552 swap_pager_almost_full = 0;
557 * SWAP_PAGER_INIT() - initialize the swap pager!
559 * Expected to be started from system init. NOTE: This code is run
560 * before much else so be careful what you depend on. Most of the VM
561 * system has yet to be initialized at this point.
564 swap_pager_init(void)
567 * Initialize object lists
571 for (i = 0; i < NOBJLISTS; ++i)
572 TAILQ_INIT(&swap_pager_object_list[i]);
573 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
574 sx_init(&sw_alloc_sx, "swspsx");
575 sx_init(&swdev_syscall_lock, "swsysc");
579 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
581 * Expected to be started from pageout process once, prior to entering
585 swap_pager_swap_init(void)
590 * Number of in-transit swap bp operations. Don't
591 * exhaust the pbufs completely. Make sure we
592 * initialize workable values (0 will work for hysteresis
593 * but it isn't very efficient).
595 * The nsw_cluster_max is constrained by the bp->b_pages[]
596 * array, which has maxphys / PAGE_SIZE entries, and our locally
597 * defined MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
598 * constrained by the swap device interleave stripe size.
600 * Currently we hardwire nsw_wcount_async to 4. This limit is
601 * designed to prevent other I/O from having high latencies due to
602 * our pageout I/O. The value 4 works well for one or two active swap
603 * devices but is probably a little low if you have more. Even so,
604 * a higher value would probably generate only a limited improvement
605 * with three or four active swap devices since the system does not
606 * typically have to pageout at extreme bandwidths. We will want
607 * at least 2 per swap devices, and 4 is a pretty good value if you
608 * have one NFS swap device due to the command/ack latency over NFS.
609 * So it all works out pretty well.
611 nsw_cluster_max = min(maxphys / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
613 nsw_wcount_async = 4;
614 nsw_wcount_async_max = nsw_wcount_async;
615 mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
617 swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
618 swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
621 * Initialize our zone, taking the user's requested size or
622 * estimating the number we need based on the number of pages
625 n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
626 vm_cnt.v_page_count / 2;
627 swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
628 pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0);
629 if (swpctrie_zone == NULL)
630 panic("failed to create swap pctrie zone.");
631 swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
632 NULL, NULL, _Alignof(struct swblk) - 1, 0);
633 if (swblk_zone == NULL)
634 panic("failed to create swap blk zone.");
637 if (uma_zone_reserve_kva(swblk_zone, n))
640 * if the allocation failed, try a zone two thirds the
641 * size of the previous attempt.
647 * Often uma_zone_reserve_kva() cannot reserve exactly the
648 * requested size. Account for the difference when
649 * calculating swap_maxpages.
651 n = uma_zone_get_max(swblk_zone);
654 printf("Swap blk zone entries changed from %lu to %lu.\n",
656 /* absolute maximum we can handle assuming 100% efficiency */
657 swap_maxpages = n * SWAP_META_PAGES;
658 swzone = n * sizeof(struct swblk);
659 if (!uma_zone_reserve_kva(swpctrie_zone, n))
660 printf("Cannot reserve swap pctrie zone, "
661 "reduce kern.maxswzone.\n");
665 swap_pager_alloc_init(void *handle, struct ucred *cred, vm_ooffset_t size,
671 if (!swap_reserve_by_cred(size, cred))
677 * The un_pager.swp.swp_blks trie is initialized by
678 * vm_object_allocate() to ensure the correct order of
679 * visibility to other threads.
681 object = vm_object_allocate(OBJT_SWAP, OFF_TO_IDX(offset +
684 object->un_pager.swp.writemappings = 0;
685 object->handle = handle;
688 object->charge = size;
694 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
695 * its metadata structures.
697 * This routine is called from the mmap and fork code to create a new
700 * This routine must ensure that no live duplicate is created for
701 * the named object request, which is protected against by
702 * holding the sw_alloc_sx lock in case handle != NULL.
705 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
706 vm_ooffset_t offset, struct ucred *cred)
710 if (handle != NULL) {
712 * Reference existing named region or allocate new one. There
713 * should not be a race here against swp_pager_meta_build()
714 * as called from vm_page_remove() in regards to the lookup
717 sx_xlock(&sw_alloc_sx);
718 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
719 if (object == NULL) {
720 object = swap_pager_alloc_init(handle, cred, size,
722 if (object != NULL) {
723 TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
724 object, pager_object_list);
727 sx_xunlock(&sw_alloc_sx);
729 object = swap_pager_alloc_init(handle, cred, size, offset);
735 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
737 * The swap backing for the object is destroyed. The code is
738 * designed such that we can reinstantiate it later, but this
739 * routine is typically called only when the entire object is
740 * about to be destroyed.
742 * The object must be locked.
745 swap_pager_dealloc(vm_object_t object)
748 VM_OBJECT_ASSERT_WLOCKED(object);
749 KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
752 * Remove from list right away so lookups will fail if we block for
753 * pageout completion.
755 if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
756 VM_OBJECT_WUNLOCK(object);
757 sx_xlock(&sw_alloc_sx);
758 TAILQ_REMOVE(NOBJLIST(object->handle), object,
760 sx_xunlock(&sw_alloc_sx);
761 VM_OBJECT_WLOCK(object);
764 vm_object_pip_wait(object, "swpdea");
767 * Free all remaining metadata. We only bother to free it from
768 * the swap meta data. We do not attempt to free swapblk's still
769 * associated with vm_page_t's for this object. We do not care
770 * if paging is still in progress on some objects.
772 swp_pager_meta_free_all(object);
773 object->handle = NULL;
774 object->type = OBJT_DEAD;
777 /************************************************************************
778 * SWAP PAGER BITMAP ROUTINES *
779 ************************************************************************/
782 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
784 * Allocate swap for up to the requested number of pages. The
785 * starting swap block number (a page index) is returned or
786 * SWAPBLK_NONE if the allocation failed.
788 * Also has the side effect of advising that somebody made a mistake
789 * when they configured swap and didn't configure enough.
791 * This routine may not sleep.
793 * We allocate in round-robin fashion from the configured devices.
796 swp_pager_getswapspace(int *io_npages)
802 KASSERT(*io_npages >= 1,
803 ("%s: npages not positive", __func__));
806 npages = imin(BLIST_MAX_ALLOC, mpages);
807 mtx_lock(&sw_dev_mtx);
809 while (!TAILQ_EMPTY(&swtailq)) {
811 sp = TAILQ_FIRST(&swtailq);
812 if ((sp->sw_flags & SW_CLOSING) == 0)
813 blk = blist_alloc(sp->sw_blist, &npages, mpages);
814 if (blk != SWAPBLK_NONE)
816 sp = TAILQ_NEXT(sp, sw_list);
824 if (blk != SWAPBLK_NONE) {
827 sp->sw_used += npages;
828 swap_pager_avail -= npages;
830 swdevhd = TAILQ_NEXT(sp, sw_list);
832 if (swap_pager_full != 2) {
833 printf("swp_pager_getswapspace(%d): failed\n",
836 swap_pager_almost_full = 1;
840 mtx_unlock(&sw_dev_mtx);
845 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
848 return (blk >= sp->sw_first && blk < sp->sw_end);
852 swp_pager_strategy(struct buf *bp)
856 mtx_lock(&sw_dev_mtx);
857 TAILQ_FOREACH(sp, &swtailq, sw_list) {
858 if (swp_pager_isondev(bp->b_blkno, sp)) {
859 mtx_unlock(&sw_dev_mtx);
860 if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
861 unmapped_buf_allowed) {
862 bp->b_data = unmapped_buf;
865 pmap_qenter((vm_offset_t)bp->b_data,
866 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
868 sp->sw_strategy(bp, sp);
872 panic("Swapdev not found");
876 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
878 * This routine returns the specified swap blocks back to the bitmap.
880 * This routine may not sleep.
883 swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
889 mtx_lock(&sw_dev_mtx);
890 TAILQ_FOREACH(sp, &swtailq, sw_list) {
891 if (swp_pager_isondev(blk, sp)) {
892 sp->sw_used -= npages;
894 * If we are attempting to stop swapping on
895 * this device, we don't want to mark any
896 * blocks free lest they be reused.
898 if ((sp->sw_flags & SW_CLOSING) == 0) {
899 blist_free(sp->sw_blist, blk - sp->sw_first,
901 swap_pager_avail += npages;
904 mtx_unlock(&sw_dev_mtx);
908 panic("Swapdev not found");
912 * SYSCTL_SWAP_FRAGMENTATION() - produce raw swap space stats
915 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
922 error = sysctl_wire_old_buffer(req, 0);
925 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
926 mtx_lock(&sw_dev_mtx);
927 TAILQ_FOREACH(sp, &swtailq, sw_list) {
928 if (vn_isdisk(sp->sw_vp))
929 devname = devtoname(sp->sw_vp->v_rdev);
932 sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
933 blist_stats(sp->sw_blist, &sbuf);
935 mtx_unlock(&sw_dev_mtx);
936 error = sbuf_finish(&sbuf);
942 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
943 * range within an object.
945 * This is a globally accessible routine.
947 * This routine removes swapblk assignments from swap metadata.
949 * The external callers of this routine typically have already destroyed
950 * or renamed vm_page_t's associated with this range in the object so
953 * The object must be locked.
956 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
959 swp_pager_meta_free(object, start, size);
963 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
965 * Assigns swap blocks to the specified range within the object. The
966 * swap blocks are not zeroed. Any previous swap assignment is destroyed.
968 * Returns 0 on success, -1 on failure.
971 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
973 daddr_t addr, blk, n_free, s_free;
976 swp_pager_init_freerange(&s_free, &n_free);
977 VM_OBJECT_WLOCK(object);
978 for (i = 0; i < size; i += n) {
980 blk = swp_pager_getswapspace(&n);
981 if (blk == SWAPBLK_NONE) {
982 swp_pager_meta_free(object, start, i);
983 VM_OBJECT_WUNLOCK(object);
986 for (j = 0; j < n; ++j) {
987 addr = swp_pager_meta_build(object,
988 start + i + j, blk + j);
989 if (addr != SWAPBLK_NONE)
990 swp_pager_update_freerange(&s_free, &n_free,
994 swp_pager_freeswapspace(s_free, n_free);
995 VM_OBJECT_WUNLOCK(object);
1000 swp_pager_xfer_source(vm_object_t srcobject, vm_object_t dstobject,
1001 vm_pindex_t pindex, daddr_t addr)
1005 KASSERT(srcobject->type == OBJT_SWAP,
1006 ("%s: Srcobject not swappable", __func__));
1007 if (dstobject->type == OBJT_SWAP &&
1008 swp_pager_meta_lookup(dstobject, pindex) != SWAPBLK_NONE) {
1009 /* Caller should destroy the source block. */
1014 * Destination has no swapblk and is not resident, transfer source.
1015 * swp_pager_meta_build() can sleep.
1017 VM_OBJECT_WUNLOCK(srcobject);
1018 dstaddr = swp_pager_meta_build(dstobject, pindex, addr);
1019 KASSERT(dstaddr == SWAPBLK_NONE,
1020 ("Unexpected destination swapblk"));
1021 VM_OBJECT_WLOCK(srcobject);
1027 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
1028 * and destroy the source.
1030 * Copy any valid swapblks from the source to the destination. In
1031 * cases where both the source and destination have a valid swapblk,
1032 * we keep the destination's.
1034 * This routine is allowed to sleep. It may sleep allocating metadata
1035 * indirectly through swp_pager_meta_build().
1037 * The source object contains no vm_page_t's (which is just as well)
1039 * The source object is of type OBJT_SWAP.
1041 * The source and destination objects must be locked.
1042 * Both object locks may temporarily be released.
1045 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
1046 vm_pindex_t offset, int destroysource)
1049 VM_OBJECT_ASSERT_WLOCKED(srcobject);
1050 VM_OBJECT_ASSERT_WLOCKED(dstobject);
1053 * If destroysource is set, we remove the source object from the
1054 * swap_pager internal queue now.
1056 if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
1057 srcobject->handle != NULL) {
1058 VM_OBJECT_WUNLOCK(srcobject);
1059 VM_OBJECT_WUNLOCK(dstobject);
1060 sx_xlock(&sw_alloc_sx);
1061 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1063 sx_xunlock(&sw_alloc_sx);
1064 VM_OBJECT_WLOCK(dstobject);
1065 VM_OBJECT_WLOCK(srcobject);
1069 * Transfer source to destination.
1071 swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size);
1074 * Free left over swap blocks in source.
1076 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
1077 * double-remove the object from the swap queues.
1079 if (destroysource) {
1080 swp_pager_meta_free_all(srcobject);
1082 * Reverting the type is not necessary, the caller is going
1083 * to destroy srcobject directly, but I'm doing it here
1084 * for consistency since we've removed the object from its
1087 srcobject->type = OBJT_DEFAULT;
1092 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
1093 * the requested page.
1095 * We determine whether good backing store exists for the requested
1096 * page and return TRUE if it does, FALSE if it doesn't.
1098 * If TRUE, we also try to determine how much valid, contiguous backing
1099 * store exists before and after the requested page.
1102 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1108 VM_OBJECT_ASSERT_LOCKED(object);
1109 KASSERT(object->type == OBJT_SWAP,
1110 ("%s: object not swappable", __func__));
1113 * do we have good backing store at the requested index ?
1115 blk0 = swp_pager_meta_lookup(object, pindex);
1116 if (blk0 == SWAPBLK_NONE) {
1125 * find backwards-looking contiguous good backing store
1127 if (before != NULL) {
1128 for (i = 1; i < SWB_NPAGES; i++) {
1131 blk = swp_pager_meta_lookup(object, pindex - i);
1132 if (blk != blk0 - i)
1139 * find forward-looking contiguous good backing store
1141 if (after != NULL) {
1142 for (i = 1; i < SWB_NPAGES; i++) {
1143 blk = swp_pager_meta_lookup(object, pindex + i);
1144 if (blk != blk0 + i)
1153 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1155 * This removes any associated swap backing store, whether valid or
1156 * not, from the page.
1158 * This routine is typically called when a page is made dirty, at
1159 * which point any associated swap can be freed. MADV_FREE also
1160 * calls us in a special-case situation
1162 * NOTE!!! If the page is clean and the swap was valid, the caller
1163 * should make the page dirty before calling this routine. This routine
1164 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1167 * This routine may not sleep.
1169 * The object containing the page may be locked.
1172 swap_pager_unswapped(vm_page_t m)
1178 * Handle enqueing deferred frees first. If we do not have the
1179 * object lock we wait for the page daemon to clear the space.
1182 if (!VM_OBJECT_WOWNED(obj)) {
1183 VM_PAGE_OBJECT_BUSY_ASSERT(m);
1185 * The caller is responsible for synchronization but we
1186 * will harmlessly handle races. This is typically provided
1187 * by only calling unswapped() when a page transitions from
1190 if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1192 vm_page_aflag_set(m, PGA_SWAP_FREE);
1193 counter_u64_add(swap_free_deferred, 1);
1197 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1198 counter_u64_add(swap_free_completed, 1);
1199 vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
1202 * The meta data only exists if the object is OBJT_SWAP
1203 * and even then might not be allocated yet.
1205 KASSERT(m->object->type == OBJT_SWAP,
1206 ("Free object not swappable"));
1208 sb = SWAP_PCTRIE_LOOKUP(&m->object->un_pager.swp.swp_blks,
1209 rounddown(m->pindex, SWAP_META_PAGES));
1212 if (sb->d[m->pindex % SWAP_META_PAGES] == SWAPBLK_NONE)
1214 swp_pager_freeswapspace(sb->d[m->pindex % SWAP_META_PAGES], 1);
1215 sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
1216 swp_pager_free_empty_swblk(m->object, sb);
1220 * swap_pager_getpages() - bring pages in from swap
1222 * Attempt to page in the pages in array "ma" of length "count". The
1223 * caller may optionally specify that additional pages preceding and
1224 * succeeding the specified range be paged in. The number of such pages
1225 * is returned in the "rbehind" and "rahead" parameters, and they will
1226 * be in the inactive queue upon return.
1228 * The pages in "ma" must be busied and will remain busied upon return.
1231 swap_pager_getpages_locked(vm_object_t object, vm_page_t *ma, int count,
1232 int *rbehind, int *rahead)
1235 vm_page_t bm, mpred, msucc, p;
1238 int i, maxahead, maxbehind, reqcount;
1240 VM_OBJECT_ASSERT_WLOCKED(object);
1243 KASSERT(object->type == OBJT_SWAP,
1244 ("%s: object not swappable", __func__));
1245 if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead)) {
1246 VM_OBJECT_WUNLOCK(object);
1247 return (VM_PAGER_FAIL);
1250 KASSERT(reqcount - 1 <= maxahead,
1251 ("page count %d extends beyond swap block", reqcount));
1254 * Do not transfer any pages other than those that are xbusied
1255 * when running during a split or collapse operation. This
1256 * prevents clustering from re-creating pages which are being
1257 * moved into another object.
1259 if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
1260 maxahead = reqcount - 1;
1265 * Clip the readahead and readbehind ranges to exclude resident pages.
1267 if (rahead != NULL) {
1268 *rahead = imin(*rahead, maxahead - (reqcount - 1));
1269 pindex = ma[reqcount - 1]->pindex;
1270 msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1271 if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1272 *rahead = msucc->pindex - pindex - 1;
1274 if (rbehind != NULL) {
1275 *rbehind = imin(*rbehind, maxbehind);
1276 pindex = ma[0]->pindex;
1277 mpred = TAILQ_PREV(ma[0], pglist, listq);
1278 if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1279 *rbehind = pindex - mpred->pindex - 1;
1283 for (i = 0; i < count; i++)
1284 ma[i]->oflags |= VPO_SWAPINPROG;
1287 * Allocate readahead and readbehind pages.
1289 if (rbehind != NULL) {
1290 for (i = 1; i <= *rbehind; i++) {
1291 p = vm_page_alloc(object, ma[0]->pindex - i,
1295 p->oflags |= VPO_SWAPINPROG;
1300 if (rahead != NULL) {
1301 for (i = 0; i < *rahead; i++) {
1302 p = vm_page_alloc(object,
1303 ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1306 p->oflags |= VPO_SWAPINPROG;
1310 if (rbehind != NULL)
1315 vm_object_pip_add(object, count);
1317 pindex = bm->pindex;
1318 blk = swp_pager_meta_lookup(object, pindex);
1319 KASSERT(blk != SWAPBLK_NONE,
1320 ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1322 VM_OBJECT_WUNLOCK(object);
1323 bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1324 MPASS((bp->b_flags & B_MAXPHYS) != 0);
1325 /* Pages cannot leave the object while busy. */
1326 for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1327 MPASS(p->pindex == bm->pindex + i);
1331 bp->b_flags |= B_PAGING;
1332 bp->b_iocmd = BIO_READ;
1333 bp->b_iodone = swp_pager_async_iodone;
1334 bp->b_rcred = crhold(thread0.td_ucred);
1335 bp->b_wcred = crhold(thread0.td_ucred);
1337 bp->b_bcount = PAGE_SIZE * count;
1338 bp->b_bufsize = PAGE_SIZE * count;
1339 bp->b_npages = count;
1340 bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1341 bp->b_pgafter = rahead != NULL ? *rahead : 0;
1343 VM_CNT_INC(v_swapin);
1344 VM_CNT_ADD(v_swappgsin, count);
1347 * perform the I/O. NOTE!!! bp cannot be considered valid after
1348 * this point because we automatically release it on completion.
1349 * Instead, we look at the one page we are interested in which we
1350 * still hold a lock on even through the I/O completion.
1352 * The other pages in our ma[] array are also released on completion,
1353 * so we cannot assume they are valid anymore either.
1355 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1358 swp_pager_strategy(bp);
1361 * Wait for the pages we want to complete. VPO_SWAPINPROG is always
1362 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1363 * is set in the metadata for each page in the request.
1365 VM_OBJECT_WLOCK(object);
1366 /* This could be implemented more efficiently with aflags */
1367 while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
1368 ma[0]->oflags |= VPO_SWAPSLEEP;
1369 VM_CNT_INC(v_intrans);
1370 if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1371 "swread", hz * 20)) {
1373 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1374 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1377 VM_OBJECT_WUNLOCK(object);
1380 * If we had an unrecoverable read error pages will not be valid.
1382 for (i = 0; i < reqcount; i++)
1383 if (ma[i]->valid != VM_PAGE_BITS_ALL)
1384 return (VM_PAGER_ERROR);
1386 return (VM_PAGER_OK);
1389 * A final note: in a low swap situation, we cannot deallocate swap
1390 * and mark a page dirty here because the caller is likely to mark
1391 * the page clean when we return, causing the page to possibly revert
1392 * to all-zero's later.
1397 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count,
1398 int *rbehind, int *rahead)
1401 VM_OBJECT_WLOCK(object);
1402 return (swap_pager_getpages_locked(object, ma, count, rbehind, rahead));
1406 * swap_pager_getpages_async():
1408 * Right now this is emulation of asynchronous operation on top of
1409 * swap_pager_getpages().
1412 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1413 int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1417 r = swap_pager_getpages(object, ma, count, rbehind, rahead);
1422 case VM_PAGER_ERROR:
1429 panic("unhandled swap_pager_getpages() error %d", r);
1431 (iodone)(arg, ma, count, error);
1437 * swap_pager_putpages:
1439 * Assign swap (if necessary) and initiate I/O on the specified pages.
1441 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1442 * are automatically converted to SWAP objects.
1444 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1445 * vm_page reservation system coupled with properly written VFS devices
1446 * should ensure that no low-memory deadlock occurs. This is an area
1449 * The parent has N vm_object_pip_add() references prior to
1450 * calling us and will remove references for rtvals[] that are
1451 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1454 * The parent has soft-busy'd the pages it passes us and will unbusy
1455 * those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
1456 * We need to unbusy the rest on I/O completion.
1459 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1460 int flags, int *rtvals)
1463 daddr_t addr, blk, n_free, s_free;
1468 KASSERT(count == 0 || ma[0]->object == object,
1469 ("%s: object mismatch %p/%p",
1470 __func__, object, ma[0]->object));
1475 * Turn object into OBJT_SWAP. Force sync if not a pageout process.
1477 if (object->type != OBJT_SWAP) {
1478 addr = swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1479 KASSERT(addr == SWAPBLK_NONE,
1480 ("unexpected object swap block"));
1482 VM_OBJECT_WUNLOCK(object);
1483 async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
1484 swp_pager_init_freerange(&s_free, &n_free);
1489 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1490 * The page is left dirty until the pageout operation completes
1493 for (i = 0; i < count; i += n) {
1494 /* Maximum I/O size is limited by maximum swap block size. */
1495 n = min(count - i, nsw_cluster_max);
1498 mtx_lock(&swbuf_mtx);
1499 while (nsw_wcount_async == 0)
1500 msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1503 mtx_unlock(&swbuf_mtx);
1506 /* Get a block of swap of size up to size n. */
1507 VM_OBJECT_WLOCK(object);
1508 blk = swp_pager_getswapspace(&n);
1509 if (blk == SWAPBLK_NONE) {
1510 VM_OBJECT_WUNLOCK(object);
1511 mtx_lock(&swbuf_mtx);
1512 if (++nsw_wcount_async == 1)
1513 wakeup(&nsw_wcount_async);
1514 mtx_unlock(&swbuf_mtx);
1515 for (j = 0; j < n; ++j)
1516 rtvals[i + j] = VM_PAGER_FAIL;
1519 for (j = 0; j < n; ++j) {
1521 vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1522 addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1524 if (addr != SWAPBLK_NONE)
1525 swp_pager_update_freerange(&s_free, &n_free,
1527 MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1528 mreq->oflags |= VPO_SWAPINPROG;
1530 VM_OBJECT_WUNLOCK(object);
1532 bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1533 MPASS((bp->b_flags & B_MAXPHYS) != 0);
1535 bp->b_flags |= B_ASYNC;
1536 bp->b_flags |= B_PAGING;
1537 bp->b_iocmd = BIO_WRITE;
1539 bp->b_rcred = crhold(thread0.td_ucred);
1540 bp->b_wcred = crhold(thread0.td_ucred);
1541 bp->b_bcount = PAGE_SIZE * n;
1542 bp->b_bufsize = PAGE_SIZE * n;
1544 for (j = 0; j < n; j++)
1545 bp->b_pages[j] = ma[i + j];
1549 * Must set dirty range for NFS to work.
1552 bp->b_dirtyend = bp->b_bcount;
1554 VM_CNT_INC(v_swapout);
1555 VM_CNT_ADD(v_swappgsout, bp->b_npages);
1558 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1559 * can call the async completion routine at the end of a
1560 * synchronous I/O operation. Otherwise, our caller would
1561 * perform duplicate unbusy and wakeup operations on the page
1562 * and object, respectively.
1564 for (j = 0; j < n; j++)
1565 rtvals[i + j] = VM_PAGER_PEND;
1570 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1573 bp->b_iodone = swp_pager_async_iodone;
1575 swp_pager_strategy(bp);
1582 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1584 bp->b_iodone = bdone;
1585 swp_pager_strategy(bp);
1588 * Wait for the sync I/O to complete.
1590 bwait(bp, PVM, "swwrt");
1593 * Now that we are through with the bp, we can call the
1594 * normal async completion, which frees everything up.
1596 swp_pager_async_iodone(bp);
1598 swp_pager_freeswapspace(s_free, n_free);
1599 VM_OBJECT_WLOCK(object);
1603 * swp_pager_async_iodone:
1605 * Completion routine for asynchronous reads and writes from/to swap.
1606 * Also called manually by synchronous code to finish up a bp.
1608 * This routine may not sleep.
1611 swp_pager_async_iodone(struct buf *bp)
1614 vm_object_t object = NULL;
1617 * Report error - unless we ran out of memory, in which case
1618 * we've already logged it in swapgeom_strategy().
1620 if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
1622 "swap_pager: I/O error - %s failed; blkno %ld,"
1623 "size %ld, error %d\n",
1624 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1632 * remove the mapping for kernel virtual
1635 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1637 bp->b_data = bp->b_kvabase;
1640 object = bp->b_pages[0]->object;
1641 VM_OBJECT_WLOCK(object);
1645 * cleanup pages. If an error occurs writing to swap, we are in
1646 * very serious trouble. If it happens to be a disk error, though,
1647 * we may be able to recover by reassigning the swap later on. So
1648 * in this case we remove the m->swapblk assignment for the page
1649 * but do not free it in the rlist. The errornous block(s) are thus
1650 * never reallocated as swap. Redirty the page and continue.
1652 for (i = 0; i < bp->b_npages; ++i) {
1653 vm_page_t m = bp->b_pages[i];
1655 m->oflags &= ~VPO_SWAPINPROG;
1656 if (m->oflags & VPO_SWAPSLEEP) {
1657 m->oflags &= ~VPO_SWAPSLEEP;
1658 wakeup(&object->handle);
1661 /* We always have space after I/O, successful or not. */
1662 vm_page_aflag_set(m, PGA_SWAP_SPACE);
1664 if (bp->b_ioflags & BIO_ERROR) {
1666 * If an error occurs I'd love to throw the swapblk
1667 * away without freeing it back to swapspace, so it
1668 * can never be used again. But I can't from an
1671 if (bp->b_iocmd == BIO_READ) {
1673 * NOTE: for reads, m->dirty will probably
1674 * be overridden by the original caller of
1675 * getpages so don't play cute tricks here.
1680 * If a write error occurs, reactivate page
1681 * so it doesn't clog the inactive list,
1682 * then finish the I/O.
1684 MPASS(m->dirty == VM_PAGE_BITS_ALL);
1686 /* PQ_UNSWAPPABLE? */
1687 vm_page_activate(m);
1690 } else if (bp->b_iocmd == BIO_READ) {
1692 * NOTE: for reads, m->dirty will probably be
1693 * overridden by the original caller of getpages so
1694 * we cannot set them in order to free the underlying
1695 * swap in a low-swap situation. I don't think we'd
1696 * want to do that anyway, but it was an optimization
1697 * that existed in the old swapper for a time before
1698 * it got ripped out due to precisely this problem.
1700 KASSERT(!pmap_page_is_mapped(m),
1701 ("swp_pager_async_iodone: page %p is mapped", m));
1702 KASSERT(m->dirty == 0,
1703 ("swp_pager_async_iodone: page %p is dirty", m));
1706 if (i < bp->b_pgbefore ||
1707 i >= bp->b_npages - bp->b_pgafter)
1708 vm_page_readahead_finish(m);
1711 * For write success, clear the dirty
1712 * status, then finish the I/O ( which decrements the
1713 * busy count and possibly wakes waiter's up ).
1714 * A page is only written to swap after a period of
1715 * inactivity. Therefore, we do not expect it to be
1718 KASSERT(!pmap_page_is_write_mapped(m),
1719 ("swp_pager_async_iodone: page %p is not write"
1722 vm_page_deactivate_noreuse(m);
1728 * adjust pip. NOTE: the original parent may still have its own
1729 * pip refs on the object.
1731 if (object != NULL) {
1732 vm_object_pip_wakeupn(object, bp->b_npages);
1733 VM_OBJECT_WUNLOCK(object);
1737 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1738 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1739 * trigger a KASSERT in relpbuf().
1743 bp->b_bufobj = NULL;
1746 * release the physical I/O buffer
1748 if (bp->b_flags & B_ASYNC) {
1749 mtx_lock(&swbuf_mtx);
1750 if (++nsw_wcount_async == 1)
1751 wakeup(&nsw_wcount_async);
1752 mtx_unlock(&swbuf_mtx);
1754 uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
1758 swap_pager_nswapdev(void)
1765 swp_pager_force_dirty(vm_page_t m)
1769 swap_pager_unswapped(m);
1774 swap_pager_swapped_pages(vm_object_t object)
1781 VM_OBJECT_ASSERT_LOCKED(object);
1782 if (object->type != OBJT_SWAP)
1785 for (res = 0, pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1786 &object->un_pager.swp.swp_blks, pi)) != NULL;
1787 pi = sb->p + SWAP_META_PAGES) {
1788 for (i = 0; i < SWAP_META_PAGES; i++) {
1789 if (sb->d[i] != SWAPBLK_NONE)
1797 * swap_pager_swapoff_object:
1799 * Page in all of the pages that have been paged out for an object
1803 swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
1809 int i, nv, rahead, rv;
1811 KASSERT(object->type == OBJT_SWAP,
1812 ("%s: Object not swappable", __func__));
1814 for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1815 &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1816 if ((object->flags & OBJ_DEAD) != 0) {
1818 * Make sure that pending writes finish before
1821 vm_object_pip_wait(object, "swpoff");
1822 swp_pager_meta_free_all(object);
1825 for (i = 0; i < SWAP_META_PAGES; i++) {
1827 * Count the number of contiguous valid blocks.
1829 for (nv = 0; nv < SWAP_META_PAGES - i; nv++) {
1830 blk = sb->d[i + nv];
1831 if (!swp_pager_isondev(blk, sp) ||
1832 blk == SWAPBLK_NONE)
1839 * Look for a page corresponding to the first
1840 * valid block and ensure that any pending paging
1841 * operations on it are complete. If the page is valid,
1842 * mark it dirty and free the swap block. Try to batch
1843 * this operation since it may cause sp to be freed,
1844 * meaning that we must restart the scan. Avoid busying
1845 * valid pages since we may block forever on kernel
1848 m = vm_page_lookup(object, sb->p + i);
1850 m = vm_page_alloc(object, sb->p + i,
1851 VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
1855 if ((m->oflags & VPO_SWAPINPROG) != 0) {
1856 m->oflags |= VPO_SWAPSLEEP;
1857 VM_OBJECT_SLEEP(object, &object->handle,
1861 if (vm_page_all_valid(m)) {
1863 swp_pager_force_dirty(m);
1864 } while (--nv > 0 &&
1865 (m = vm_page_next(m)) != NULL &&
1866 vm_page_all_valid(m) &&
1867 (m->oflags & VPO_SWAPINPROG) == 0);
1870 if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL))
1874 vm_object_pip_add(object, 1);
1875 rahead = SWAP_META_PAGES;
1876 rv = swap_pager_getpages_locked(object, &m, 1, NULL,
1878 if (rv != VM_PAGER_OK)
1879 panic("%s: read from swap failed: %d",
1881 vm_object_pip_wakeupn(object, 1);
1882 VM_OBJECT_WLOCK(object);
1886 * The object lock was dropped so we must restart the
1887 * scan of this swap block. Pages paged in during this
1888 * iteration will be marked dirty in a future iteration.
1892 if (i == SWAP_META_PAGES)
1893 pi = sb->p + SWAP_META_PAGES;
1898 * swap_pager_swapoff:
1900 * Page in all of the pages that have been paged out to the
1901 * given device. The corresponding blocks in the bitmap must be
1902 * marked as allocated and the device must be flagged SW_CLOSING.
1903 * There may be no processes swapped out to the device.
1905 * This routine may block.
1908 swap_pager_swapoff(struct swdevt *sp)
1913 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1917 mtx_lock(&vm_object_list_mtx);
1918 TAILQ_FOREACH(object, &vm_object_list, object_list) {
1919 if (object->type != OBJT_SWAP)
1921 mtx_unlock(&vm_object_list_mtx);
1922 /* Depends on type-stability. */
1923 VM_OBJECT_WLOCK(object);
1926 * Dead objects are eventually terminated on their own.
1928 if ((object->flags & OBJ_DEAD) != 0)
1932 * Sync with fences placed after pctrie
1933 * initialization. We must not access pctrie below
1934 * unless we checked that our object is swap and not
1937 atomic_thread_fence_acq();
1938 if (object->type != OBJT_SWAP)
1941 swap_pager_swapoff_object(sp, object);
1943 VM_OBJECT_WUNLOCK(object);
1944 mtx_lock(&vm_object_list_mtx);
1946 mtx_unlock(&vm_object_list_mtx);
1950 * Objects may be locked or paging to the device being
1951 * removed, so we will miss their pages and need to
1952 * make another pass. We have marked this device as
1953 * SW_CLOSING, so the activity should finish soon.
1956 if (retries > 100) {
1957 panic("swapoff: failed to locate %d swap blocks",
1960 pause("swpoff", hz / 20);
1963 EVENTHANDLER_INVOKE(swapoff, sp);
1966 /************************************************************************
1968 ************************************************************************
1970 * These routines manipulate the swap metadata stored in the
1973 * Swap metadata is implemented with a global hash and not directly
1974 * linked into the object. Instead the object simply contains
1975 * appropriate tracking counters.
1979 * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
1982 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
1986 MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
1987 for (i = start; i < limit; i++) {
1988 if (sb->d[i] != SWAPBLK_NONE)
1995 * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
1997 * Nothing is done if the block is still in use.
2000 swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
2003 if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
2004 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2005 uma_zfree(swblk_zone, sb);
2010 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
2012 * We first convert the object to a swap object if it is a default
2015 * The specified swapblk is added to the object's swap metadata. If
2016 * the swapblk is not valid, it is freed instead. Any previously
2017 * assigned swapblk is returned.
2020 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
2022 static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
2023 struct swblk *sb, *sb1;
2024 vm_pindex_t modpi, rdpi;
2025 daddr_t prev_swapblk;
2028 VM_OBJECT_ASSERT_WLOCKED(object);
2031 * Convert default object to swap object if necessary
2033 if (object->type != OBJT_SWAP) {
2034 pctrie_init(&object->un_pager.swp.swp_blks);
2037 * Ensure that swap_pager_swapoff()'s iteration over
2038 * object_list does not see a garbage pctrie.
2040 atomic_thread_fence_rel();
2042 object->type = OBJT_SWAP;
2043 object->un_pager.swp.writemappings = 0;
2044 KASSERT((object->flags & OBJ_ANON) != 0 ||
2045 object->handle == NULL,
2046 ("default pager %p with handle %p",
2047 object, object->handle));
2050 rdpi = rounddown(pindex, SWAP_META_PAGES);
2051 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
2053 if (swapblk == SWAPBLK_NONE)
2054 return (SWAPBLK_NONE);
2056 sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
2057 pageproc ? M_USE_RESERVE : 0));
2060 for (i = 0; i < SWAP_META_PAGES; i++)
2061 sb->d[i] = SWAPBLK_NONE;
2062 if (atomic_cmpset_int(&swblk_zone_exhausted,
2064 printf("swblk zone ok\n");
2067 VM_OBJECT_WUNLOCK(object);
2068 if (uma_zone_exhausted(swblk_zone)) {
2069 if (atomic_cmpset_int(&swblk_zone_exhausted,
2071 printf("swap blk zone exhausted, "
2072 "increase kern.maxswzone\n");
2073 vm_pageout_oom(VM_OOM_SWAPZ);
2074 pause("swzonxb", 10);
2076 uma_zwait(swblk_zone);
2077 VM_OBJECT_WLOCK(object);
2078 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2082 * Somebody swapped out a nearby page,
2083 * allocating swblk at the rdpi index,
2084 * while we dropped the object lock.
2089 error = SWAP_PCTRIE_INSERT(
2090 &object->un_pager.swp.swp_blks, sb);
2092 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2094 printf("swpctrie zone ok\n");
2097 VM_OBJECT_WUNLOCK(object);
2098 if (uma_zone_exhausted(swpctrie_zone)) {
2099 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2101 printf("swap pctrie zone exhausted, "
2102 "increase kern.maxswzone\n");
2103 vm_pageout_oom(VM_OOM_SWAPZ);
2104 pause("swzonxp", 10);
2106 uma_zwait(swpctrie_zone);
2107 VM_OBJECT_WLOCK(object);
2108 sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2111 uma_zfree(swblk_zone, sb);
2118 MPASS(sb->p == rdpi);
2120 modpi = pindex % SWAP_META_PAGES;
2121 /* Return prior contents of metadata. */
2122 prev_swapblk = sb->d[modpi];
2123 /* Enter block into metadata. */
2124 sb->d[modpi] = swapblk;
2127 * Free the swblk if we end up with the empty page run.
2129 if (swapblk == SWAPBLK_NONE)
2130 swp_pager_free_empty_swblk(object, sb);
2131 return (prev_swapblk);
2135 * SWP_PAGER_META_TRANSFER() - free a range of blocks in the srcobject's swap
2136 * metadata, or transfer it into dstobject.
2138 * This routine will free swap metadata structures as they are cleaned
2142 swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
2143 vm_pindex_t pindex, vm_pindex_t count)
2146 daddr_t n_free, s_free;
2147 vm_pindex_t offset, last;
2148 int i, limit, start;
2150 VM_OBJECT_ASSERT_WLOCKED(srcobject);
2151 if (srcobject->type != OBJT_SWAP || count == 0)
2154 swp_pager_init_freerange(&s_free, &n_free);
2156 last = pindex + count;
2158 sb = SWAP_PCTRIE_LOOKUP_GE(&srcobject->un_pager.swp.swp_blks,
2159 rounddown(pindex, SWAP_META_PAGES));
2160 if (sb == NULL || sb->p >= last)
2162 start = pindex > sb->p ? pindex - sb->p : 0;
2163 limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2165 for (i = start; i < limit; i++) {
2166 if (sb->d[i] == SWAPBLK_NONE)
2168 if (dstobject == NULL ||
2169 !swp_pager_xfer_source(srcobject, dstobject,
2170 sb->p + i - offset, sb->d[i])) {
2171 swp_pager_update_freerange(&s_free, &n_free,
2174 sb->d[i] = SWAPBLK_NONE;
2176 pindex = sb->p + SWAP_META_PAGES;
2177 if (swp_pager_swblk_empty(sb, 0, start) &&
2178 swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2179 SWAP_PCTRIE_REMOVE(&srcobject->un_pager.swp.swp_blks,
2181 uma_zfree(swblk_zone, sb);
2184 swp_pager_freeswapspace(s_free, n_free);
2188 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
2190 * The requested range of blocks is freed, with any associated swap
2191 * returned to the swap bitmap.
2193 * This routine will free swap metadata structures as they are cleaned
2194 * out. This routine does *NOT* operate on swap metadata associated
2195 * with resident pages.
2198 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count)
2200 swp_pager_meta_transfer(object, NULL, pindex, count);
2204 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
2206 * This routine locates and destroys all swap metadata associated with
2210 swp_pager_meta_free_all(vm_object_t object)
2213 daddr_t n_free, s_free;
2217 VM_OBJECT_ASSERT_WLOCKED(object);
2218 if (object->type != OBJT_SWAP)
2221 swp_pager_init_freerange(&s_free, &n_free);
2222 for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
2223 &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
2224 pindex = sb->p + SWAP_META_PAGES;
2225 for (i = 0; i < SWAP_META_PAGES; i++) {
2226 if (sb->d[i] == SWAPBLK_NONE)
2228 swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
2230 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2231 uma_zfree(swblk_zone, sb);
2233 swp_pager_freeswapspace(s_free, n_free);
2237 * SWP_PAGER_METACTL() - misc control of swap meta data.
2239 * This routine is capable of looking up, or removing swapblk
2240 * assignments in the swap meta data. It returns the swapblk being
2241 * looked-up, popped, or SWAPBLK_NONE if the block was invalid.
2243 * When acting on a busy resident page and paging is in progress, we
2244 * have to wait until paging is complete but otherwise can act on the
2248 swp_pager_meta_lookup(vm_object_t object, vm_pindex_t pindex)
2252 VM_OBJECT_ASSERT_LOCKED(object);
2255 * The meta data only exists if the object is OBJT_SWAP
2256 * and even then might not be allocated yet.
2258 KASSERT(object->type == OBJT_SWAP,
2259 ("Lookup object not swappable"));
2261 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2262 rounddown(pindex, SWAP_META_PAGES));
2264 return (SWAPBLK_NONE);
2265 return (sb->d[pindex % SWAP_META_PAGES]);
2269 * Returns the least page index which is greater than or equal to the
2270 * parameter pindex and for which there is a swap block allocated.
2271 * Returns object's size if the object's type is not swap or if there
2272 * are no allocated swap blocks for the object after the requested
2276 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2281 VM_OBJECT_ASSERT_LOCKED(object);
2282 if (object->type != OBJT_SWAP)
2283 return (object->size);
2285 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2286 rounddown(pindex, SWAP_META_PAGES));
2288 return (object->size);
2289 if (sb->p < pindex) {
2290 for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2291 if (sb->d[i] != SWAPBLK_NONE)
2294 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2295 roundup(pindex, SWAP_META_PAGES));
2297 return (object->size);
2299 for (i = 0; i < SWAP_META_PAGES; i++) {
2300 if (sb->d[i] != SWAPBLK_NONE)
2305 * We get here if a swblk is present in the trie but it
2306 * doesn't map any blocks.
2309 return (object->size);
2313 * System call swapon(name) enables swapping on device name,
2314 * which must be in the swdevsw. Return EBUSY
2315 * if already swapping on this device.
2317 #ifndef _SYS_SYSPROTO_H_
2318 struct swapon_args {
2328 sys_swapon(struct thread *td, struct swapon_args *uap)
2332 struct nameidata nd;
2335 error = priv_check(td, PRIV_SWAPON);
2339 sx_xlock(&swdev_syscall_lock);
2342 * Swap metadata may not fit in the KVM if we have physical
2345 if (swblk_zone == NULL) {
2350 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2356 NDFREE(&nd, NDF_ONLY_PNBUF);
2359 if (vn_isdisk_error(vp, &error)) {
2360 error = swapongeom(vp);
2361 } else if (vp->v_type == VREG &&
2362 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2363 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2365 * Allow direct swapping to NFS regular files in the same
2366 * way that nfs_mountroot() sets up diskless swapping.
2368 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2374 sx_xunlock(&swdev_syscall_lock);
2379 * Check that the total amount of swap currently configured does not
2380 * exceed half the theoretical maximum. If it does, print a warning
2384 swapon_check_swzone(void)
2387 /* recommend using no more than half that amount */
2388 if (swap_total > swap_maxpages / 2) {
2389 printf("warning: total configured swap (%lu pages) "
2390 "exceeds maximum recommended amount (%lu pages).\n",
2391 swap_total, swap_maxpages / 2);
2392 printf("warning: increase kern.maxswzone "
2393 "or reduce amount of swap.\n");
2398 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2399 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2401 struct swdevt *sp, *tsp;
2405 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2406 * First chop nblks off to page-align it, then convert.
2408 * sw->sw_nblks is in page-sized chunks now too.
2410 nblks &= ~(ctodb(1) - 1);
2411 nblks = dbtoc(nblks);
2413 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2414 sp->sw_blist = blist_create(nblks, M_WAITOK);
2418 sp->sw_nblks = nblks;
2420 sp->sw_strategy = strategy;
2421 sp->sw_close = close;
2422 sp->sw_flags = flags;
2425 * Do not free the first blocks in order to avoid overwriting
2426 * any bsd label at the front of the partition
2428 blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2429 nblks - howmany(BBSIZE, PAGE_SIZE));
2432 mtx_lock(&sw_dev_mtx);
2433 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2434 if (tsp->sw_end >= dvbase) {
2436 * We put one uncovered page between the devices
2437 * in order to definitively prevent any cross-device
2440 dvbase = tsp->sw_end + 1;
2443 sp->sw_first = dvbase;
2444 sp->sw_end = dvbase + nblks;
2445 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2447 swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2448 swap_total += nblks;
2449 swapon_check_swzone();
2451 mtx_unlock(&sw_dev_mtx);
2452 EVENTHANDLER_INVOKE(swapon, sp);
2456 * SYSCALL: swapoff(devname)
2458 * Disable swapping on the given device.
2460 * XXX: Badly designed system call: it should use a device index
2461 * rather than filename as specification. We keep sw_vp around
2462 * only to make this work.
2464 #ifndef _SYS_SYSPROTO_H_
2465 struct swapoff_args {
2475 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2478 struct nameidata nd;
2482 error = priv_check(td, PRIV_SWAPOFF);
2486 sx_xlock(&swdev_syscall_lock);
2488 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2493 NDFREE(&nd, NDF_ONLY_PNBUF);
2496 mtx_lock(&sw_dev_mtx);
2497 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2498 if (sp->sw_vp == vp)
2501 mtx_unlock(&sw_dev_mtx);
2506 error = swapoff_one(sp, td->td_ucred);
2508 sx_xunlock(&swdev_syscall_lock);
2513 swapoff_one(struct swdevt *sp, struct ucred *cred)
2520 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2522 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2523 error = mac_system_check_swapoff(cred, sp->sw_vp);
2524 (void) VOP_UNLOCK(sp->sw_vp);
2528 nblks = sp->sw_nblks;
2531 * We can turn off this swap device safely only if the
2532 * available virtual memory in the system will fit the amount
2533 * of data we will have to page back in, plus an epsilon so
2534 * the system doesn't become critically low on swap space.
2536 if (vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
2540 * Prevent further allocations on this device.
2542 mtx_lock(&sw_dev_mtx);
2543 sp->sw_flags |= SW_CLOSING;
2544 swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2545 swap_total -= nblks;
2546 mtx_unlock(&sw_dev_mtx);
2549 * Page in the contents of the device and close it.
2551 swap_pager_swapoff(sp);
2553 sp->sw_close(curthread, sp);
2554 mtx_lock(&sw_dev_mtx);
2556 TAILQ_REMOVE(&swtailq, sp, sw_list);
2558 if (nswapdev == 0) {
2559 swap_pager_full = 2;
2560 swap_pager_almost_full = 1;
2564 mtx_unlock(&sw_dev_mtx);
2565 blist_destroy(sp->sw_blist);
2566 free(sp, M_VMPGDATA);
2573 struct swdevt *sp, *spt;
2574 const char *devname;
2577 sx_xlock(&swdev_syscall_lock);
2579 mtx_lock(&sw_dev_mtx);
2580 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2581 mtx_unlock(&sw_dev_mtx);
2582 if (vn_isdisk(sp->sw_vp))
2583 devname = devtoname(sp->sw_vp->v_rdev);
2586 error = swapoff_one(sp, thread0.td_ucred);
2588 printf("Cannot remove swap device %s (error=%d), "
2589 "skipping.\n", devname, error);
2590 } else if (bootverbose) {
2591 printf("Swap device %s removed.\n", devname);
2593 mtx_lock(&sw_dev_mtx);
2595 mtx_unlock(&sw_dev_mtx);
2597 sx_xunlock(&swdev_syscall_lock);
2601 swap_pager_status(int *total, int *used)
2604 *total = swap_total;
2605 *used = swap_total - swap_pager_avail -
2606 nswapdev * howmany(BBSIZE, PAGE_SIZE);
2610 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2613 const char *tmp_devname;
2618 mtx_lock(&sw_dev_mtx);
2619 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2624 xs->xsw_version = XSWDEV_VERSION;
2625 xs->xsw_dev = sp->sw_dev;
2626 xs->xsw_flags = sp->sw_flags;
2627 xs->xsw_nblks = sp->sw_nblks;
2628 xs->xsw_used = sp->sw_used;
2629 if (devname != NULL) {
2630 if (vn_isdisk(sp->sw_vp))
2631 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2633 tmp_devname = "[file]";
2634 strncpy(devname, tmp_devname, len);
2639 mtx_unlock(&sw_dev_mtx);
2643 #if defined(COMPAT_FREEBSD11)
2644 #define XSWDEV_VERSION_11 1
2654 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2657 u_int xsw_dev1, xsw_dev2;
2665 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2668 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2669 struct xswdev32 xs32;
2671 #if defined(COMPAT_FREEBSD11)
2672 struct xswdev11 xs11;
2676 if (arg2 != 1) /* name length */
2679 memset(&xs, 0, sizeof(xs));
2680 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2683 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2684 if (req->oldlen == sizeof(xs32)) {
2685 memset(&xs32, 0, sizeof(xs32));
2686 xs32.xsw_version = XSWDEV_VERSION;
2687 xs32.xsw_dev1 = xs.xsw_dev;
2688 xs32.xsw_dev2 = xs.xsw_dev >> 32;
2689 xs32.xsw_flags = xs.xsw_flags;
2690 xs32.xsw_nblks = xs.xsw_nblks;
2691 xs32.xsw_used = xs.xsw_used;
2692 error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2696 #if defined(COMPAT_FREEBSD11)
2697 if (req->oldlen == sizeof(xs11)) {
2698 memset(&xs11, 0, sizeof(xs11));
2699 xs11.xsw_version = XSWDEV_VERSION_11;
2700 xs11.xsw_dev = xs.xsw_dev; /* truncation */
2701 xs11.xsw_flags = xs.xsw_flags;
2702 xs11.xsw_nblks = xs.xsw_nblks;
2703 xs11.xsw_used = xs.xsw_used;
2704 error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2708 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2712 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2713 "Number of swap devices");
2714 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2715 sysctl_vm_swap_info,
2716 "Swap statistics by device");
2719 * Count the approximate swap usage in pages for a vmspace. The
2720 * shadowed or not yet copied on write swap blocks are not accounted.
2721 * The map must be locked.
2724 vmspace_swap_count(struct vmspace *vmspace)
2734 map = &vmspace->vm_map;
2737 VM_MAP_ENTRY_FOREACH(cur, map) {
2738 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2740 object = cur->object.vm_object;
2741 if (object == NULL || object->type != OBJT_SWAP)
2743 VM_OBJECT_RLOCK(object);
2744 if (object->type != OBJT_SWAP)
2746 pi = OFF_TO_IDX(cur->offset);
2747 e = pi + OFF_TO_IDX(cur->end - cur->start);
2748 for (;; pi = sb->p + SWAP_META_PAGES) {
2749 sb = SWAP_PCTRIE_LOOKUP_GE(
2750 &object->un_pager.swp.swp_blks, pi);
2751 if (sb == NULL || sb->p >= e)
2753 for (i = 0; i < SWAP_META_PAGES; i++) {
2754 if (sb->p + i < e &&
2755 sb->d[i] != SWAPBLK_NONE)
2760 VM_OBJECT_RUNLOCK(object);
2768 * Swapping onto disk devices.
2772 static g_orphan_t swapgeom_orphan;
2774 static struct g_class g_swap_class = {
2776 .version = G_VERSION,
2777 .orphan = swapgeom_orphan,
2780 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2783 swapgeom_close_ev(void *arg, int flags)
2785 struct g_consumer *cp;
2788 g_access(cp, -1, -1, 0);
2790 g_destroy_consumer(cp);
2794 * Add a reference to the g_consumer for an inflight transaction.
2797 swapgeom_acquire(struct g_consumer *cp)
2800 mtx_assert(&sw_dev_mtx, MA_OWNED);
2805 * Remove a reference from the g_consumer. Post a close event if all
2806 * references go away, since the function might be called from the
2810 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2813 mtx_assert(&sw_dev_mtx, MA_OWNED);
2815 if (cp->index == 0) {
2816 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2822 swapgeom_done(struct bio *bp2)
2826 struct g_consumer *cp;
2828 bp = bp2->bio_caller2;
2830 bp->b_ioflags = bp2->bio_flags;
2832 bp->b_ioflags |= BIO_ERROR;
2833 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2834 bp->b_error = bp2->bio_error;
2835 bp->b_caller1 = NULL;
2837 sp = bp2->bio_caller1;
2838 mtx_lock(&sw_dev_mtx);
2839 swapgeom_release(cp, sp);
2840 mtx_unlock(&sw_dev_mtx);
2845 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2848 struct g_consumer *cp;
2850 mtx_lock(&sw_dev_mtx);
2853 mtx_unlock(&sw_dev_mtx);
2854 bp->b_error = ENXIO;
2855 bp->b_ioflags |= BIO_ERROR;
2859 swapgeom_acquire(cp);
2860 mtx_unlock(&sw_dev_mtx);
2861 if (bp->b_iocmd == BIO_WRITE)
2864 bio = g_alloc_bio();
2866 mtx_lock(&sw_dev_mtx);
2867 swapgeom_release(cp, sp);
2868 mtx_unlock(&sw_dev_mtx);
2869 bp->b_error = ENOMEM;
2870 bp->b_ioflags |= BIO_ERROR;
2871 printf("swap_pager: cannot allocate bio\n");
2876 bp->b_caller1 = bio;
2877 bio->bio_caller1 = sp;
2878 bio->bio_caller2 = bp;
2879 bio->bio_cmd = bp->b_iocmd;
2880 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2881 bio->bio_length = bp->b_bcount;
2882 bio->bio_done = swapgeom_done;
2883 if (!buf_mapped(bp)) {
2884 bio->bio_ma = bp->b_pages;
2885 bio->bio_data = unmapped_buf;
2886 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2887 bio->bio_ma_n = bp->b_npages;
2888 bio->bio_flags |= BIO_UNMAPPED;
2890 bio->bio_data = bp->b_data;
2893 g_io_request(bio, cp);
2898 swapgeom_orphan(struct g_consumer *cp)
2903 mtx_lock(&sw_dev_mtx);
2904 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2905 if (sp->sw_id == cp) {
2906 sp->sw_flags |= SW_CLOSING;
2911 * Drop reference we were created with. Do directly since we're in a
2912 * special context where we don't have to queue the call to
2913 * swapgeom_close_ev().
2916 destroy = ((sp != NULL) && (cp->index == 0));
2919 mtx_unlock(&sw_dev_mtx);
2921 swapgeom_close_ev(cp, 0);
2925 swapgeom_close(struct thread *td, struct swdevt *sw)
2927 struct g_consumer *cp;
2929 mtx_lock(&sw_dev_mtx);
2932 mtx_unlock(&sw_dev_mtx);
2935 * swapgeom_close() may be called from the biodone context,
2936 * where we cannot perform topology changes. Delegate the
2937 * work to the events thread.
2940 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2944 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2946 struct g_provider *pp;
2947 struct g_consumer *cp;
2948 static struct g_geom *gp;
2953 pp = g_dev_getprovider(dev);
2956 mtx_lock(&sw_dev_mtx);
2957 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2959 if (cp != NULL && cp->provider == pp) {
2960 mtx_unlock(&sw_dev_mtx);
2964 mtx_unlock(&sw_dev_mtx);
2966 gp = g_new_geomf(&g_swap_class, "swap");
2967 cp = g_new_consumer(gp);
2968 cp->index = 1; /* Number of active I/Os, plus one for being active. */
2969 cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2972 * XXX: Every time you think you can improve the margin for
2973 * footshooting, somebody depends on the ability to do so:
2974 * savecore(8) wants to write to our swapdev so we cannot
2975 * set an exclusive count :-(
2977 error = g_access(cp, 1, 1, 0);
2980 g_destroy_consumer(cp);
2983 nblks = pp->mediasize / DEV_BSIZE;
2984 swaponsomething(vp, cp, nblks, swapgeom_strategy,
2985 swapgeom_close, dev2udev(dev),
2986 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
2991 swapongeom(struct vnode *vp)
2995 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2996 if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) {
3000 error = swapongeom_locked(vp->v_rdev, vp);
3001 g_topology_unlock();
3010 * This is used mainly for network filesystem (read: probably only tested
3011 * with NFS) swapfiles.
3016 swapdev_strategy(struct buf *bp, struct swdevt *sp)
3020 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
3024 if (bp->b_iocmd == BIO_WRITE) {
3026 bufobj_wdrop(bp->b_bufobj);
3027 bufobj_wref(&vp2->v_bufobj);
3029 if (bp->b_bufobj != &vp2->v_bufobj)
3030 bp->b_bufobj = &vp2->v_bufobj;
3032 bp->b_iooffset = dbtob(bp->b_blkno);
3038 swapdev_close(struct thread *td, struct swdevt *sp)
3041 VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
3046 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
3053 mtx_lock(&sw_dev_mtx);
3054 TAILQ_FOREACH(sp, &swtailq, sw_list) {
3055 if (sp->sw_id == vp) {
3056 mtx_unlock(&sw_dev_mtx);
3060 mtx_unlock(&sw_dev_mtx);
3062 (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3064 error = mac_system_check_swapon(td->td_ucred, vp);
3067 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
3068 (void) VOP_UNLOCK(vp);
3072 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
3078 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
3082 new = nsw_wcount_async_max;
3083 error = sysctl_handle_int(oidp, &new, 0, req);
3084 if (error != 0 || req->newptr == NULL)
3087 if (new > nswbuf / 2 || new < 1)
3090 mtx_lock(&swbuf_mtx);
3091 while (nsw_wcount_async_max != new) {
3093 * Adjust difference. If the current async count is too low,
3094 * we will need to sqeeze our update slowly in. Sleep with a
3095 * higher priority than getpbuf() to finish faster.
3097 n = new - nsw_wcount_async_max;
3098 if (nsw_wcount_async + n >= 0) {
3099 nsw_wcount_async += n;
3100 nsw_wcount_async_max += n;
3101 wakeup(&nsw_wcount_async);
3103 nsw_wcount_async_max -= nsw_wcount_async;
3104 nsw_wcount_async = 0;
3105 msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
3109 mtx_unlock(&swbuf_mtx);
3115 swap_pager_update_writecount(vm_object_t object, vm_offset_t start,
3119 VM_OBJECT_WLOCK(object);
3120 KASSERT((object->flags & OBJ_ANON) == 0,
3121 ("Splittable object with writecount"));
3122 object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
3123 VM_OBJECT_WUNLOCK(object);
3127 swap_pager_release_writecount(vm_object_t object, vm_offset_t start,
3131 VM_OBJECT_WLOCK(object);
3132 KASSERT((object->flags & OBJ_ANON) == 0,
3133 ("Splittable object with writecount"));
3134 object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
3135 VM_OBJECT_WUNLOCK(object);
3139 swap_pager_set_writeable_dirty(vm_object_t object)
3141 if ((object->flags & OBJ_TMPFS_NODE) != 0)
3142 vm_object_set_writeable_dirty_(object);
3146 swap_pager_mightbedirty(vm_object_t object)
3148 if ((object->flags & OBJ_TMPFS_NODE) != 0)
3149 return (vm_object_mightbedirty_(object));
3154 swap_pager_getvp(vm_object_t object, struct vnode **vpp, bool *vp_heldp)
3158 KASSERT((object->flags & OBJ_TMPFS_NODE) != 0,
3159 ("swap_pager_getvp: swap and !TMPFS obj %p", object));
3162 * Tmpfs VREG node, which was reclaimed, has
3163 * OBJ_TMPFS_NODE flag set, but not OBJ_TMPFS. In
3164 * this case there is no v_writecount to adjust.
3166 VM_OBJECT_RLOCK(object);
3167 if ((object->flags & OBJ_TMPFS) != 0) {
3168 vp = object->un_pager.swp.swp_tmpfs;
3175 VM_OBJECT_RUNLOCK(object);