2 * SPDX-License-Identifier: BSD-4-Clause
4 * Copyright (c) 1998 Matthew Dillon,
5 * Copyright (c) 1994 John S. Dyson
6 * Copyright (c) 1990 University of Utah.
7 * Copyright (c) 1982, 1986, 1989, 1993
8 * The Regents of the University of California. All rights reserved.
10 * This code is derived from software contributed to Berkeley by
11 * the Systems Programming Group of the University of Utah Computer
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 * 3. All advertising materials mentioning features or use of this software
23 * must display the following acknowledgement:
24 * This product includes software developed by the University of
25 * California, Berkeley and its contributors.
26 * 4. Neither the name of the University nor the names of its contributors
27 * may be used to endorse or promote products derived from this software
28 * without specific prior written permission.
30 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45 * Radix Bitmap 'blists'.
47 * - The new swapper uses the new radix bitmap code. This should scale
48 * to arbitrarily small or arbitrarily large swap spaces and an almost
49 * arbitrary degree of fragmentation.
53 * - on the fly reallocation of swap during putpages. The new system
54 * does not try to keep previously allocated swap blocks for dirty
57 * - on the fly deallocation of swap
59 * - No more garbage collection required. Unnecessarily allocated swap
60 * blocks only exist for dirty vm_page_t's now and these are already
61 * cycled (in a high-load system) by the pager. We also do on-the-fly
62 * removal of invalidated swap blocks when a page is destroyed
65 * from: Utah $Hdr: swap_pager.c 1.4 91/04/30$
67 * @(#)swap_pager.c 8.9 (Berkeley) 3/21/94
68 * @(#)vm_swap.c 8.5 (Berkeley) 2/17/94
71 #include <sys/cdefs.h>
72 __FBSDID("$FreeBSD$");
76 #include <sys/param.h>
78 #include <sys/blist.h>
82 #include <sys/disklabel.h>
83 #include <sys/eventhandler.h>
84 #include <sys/fcntl.h>
85 #include <sys/limits.h>
87 #include <sys/kernel.h>
88 #include <sys/mount.h>
89 #include <sys/namei.h>
90 #include <sys/malloc.h>
91 #include <sys/pctrie.h>
94 #include <sys/racct.h>
95 #include <sys/resource.h>
96 #include <sys/resourcevar.h>
97 #include <sys/rwlock.h>
99 #include <sys/sysctl.h>
100 #include <sys/sysproto.h>
101 #include <sys/systm.h>
103 #include <sys/unistd.h>
104 #include <sys/user.h>
105 #include <sys/vmmeter.h>
106 #include <sys/vnode.h>
108 #include <security/mac/mac_framework.h>
112 #include <vm/vm_map.h>
113 #include <vm/vm_kern.h>
114 #include <vm/vm_object.h>
115 #include <vm/vm_page.h>
116 #include <vm/vm_pager.h>
117 #include <vm/vm_pageout.h>
118 #include <vm/vm_param.h>
119 #include <vm/swap_pager.h>
120 #include <vm/vm_extern.h>
123 #include <geom/geom.h>
126 * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64.
127 * The 64-page limit is due to the radix code (kern/subr_blist.c).
129 #ifndef MAX_PAGEOUT_CLUSTER
130 #define MAX_PAGEOUT_CLUSTER 32
133 #if !defined(SWB_NPAGES)
134 #define SWB_NPAGES MAX_PAGEOUT_CLUSTER
137 #define SWAP_META_PAGES PCTRIE_COUNT
140 * A swblk structure maps each page index within a
141 * SWAP_META_PAGES-aligned and sized range to the address of an
142 * on-disk swap block (or SWAPBLK_NONE). The collection of these
143 * mappings for an entire vm object is implemented as a pc-trie.
147 daddr_t d[SWAP_META_PAGES];
150 static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data");
151 static struct mtx sw_dev_mtx;
152 static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
153 static struct swdevt *swdevhd; /* Allocate from here next */
154 static int nswapdev; /* Number of swap devices */
155 int swap_pager_avail;
156 static struct sx swdev_syscall_lock; /* serialize swap(on|off) */
158 static __exclusive_cache_line u_long swap_reserved;
159 static u_long swap_total;
160 static int sysctl_page_shift(SYSCTL_HANDLER_ARGS);
162 static SYSCTL_NODE(_vm_stats, OID_AUTO, swap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
165 SYSCTL_PROC(_vm, OID_AUTO, swap_reserved, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
166 &swap_reserved, 0, sysctl_page_shift, "QU",
167 "Amount of swap storage needed to back all allocated anonymous memory.");
168 SYSCTL_PROC(_vm, OID_AUTO, swap_total, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
169 &swap_total, 0, sysctl_page_shift, "QU",
170 "Total amount of available swap storage.");
172 static int overcommit = 0;
173 SYSCTL_INT(_vm, VM_OVERCOMMIT, overcommit, CTLFLAG_RW, &overcommit, 0,
174 "Configure virtual memory overcommit behavior. See tuning(7) "
176 static unsigned long swzone;
177 SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
178 "Actual size of swap metadata zone");
179 static unsigned long swap_maxpages;
180 SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
181 "Maximum amount of swap supported");
183 static COUNTER_U64_DEFINE_EARLY(swap_free_deferred);
184 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_deferred,
185 CTLFLAG_RD, &swap_free_deferred,
186 "Number of pages that deferred freeing swap space");
188 static COUNTER_U64_DEFINE_EARLY(swap_free_completed);
189 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_completed,
190 CTLFLAG_RD, &swap_free_completed,
191 "Number of deferred frees completed");
193 /* bits from overcommit */
194 #define SWAP_RESERVE_FORCE_ON (1 << 0)
195 #define SWAP_RESERVE_RLIMIT_ON (1 << 1)
196 #define SWAP_RESERVE_ALLOW_NONWIRED (1 << 2)
199 sysctl_page_shift(SYSCTL_HANDLER_ARGS)
202 u_long value = *(u_long *)arg1;
204 newval = ((uint64_t)value) << PAGE_SHIFT;
205 return (sysctl_handle_64(oidp, &newval, 0, req));
209 swap_reserve_by_cred_rlimit(u_long pincr, struct ucred *cred, int oc)
214 uip = cred->cr_ruidinfo;
216 prev = atomic_fetchadd_long(&uip->ui_vmsize, pincr);
217 if ((oc & SWAP_RESERVE_RLIMIT_ON) != 0 &&
218 prev + pincr > lim_cur(curthread, RLIMIT_SWAP) &&
219 priv_check(curthread, PRIV_VM_SWAP_NORLIMIT) != 0) {
220 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pincr);
221 KASSERT(prev >= pincr, ("negative vmsize for uid = %d\n", uip->ui_uid));
228 swap_release_by_cred_rlimit(u_long pdecr, struct ucred *cred)
235 uip = cred->cr_ruidinfo;
238 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pdecr);
239 KASSERT(prev >= pdecr, ("negative vmsize for uid = %d\n", uip->ui_uid));
241 atomic_subtract_long(&uip->ui_vmsize, pdecr);
246 swap_reserve_force_rlimit(u_long pincr, struct ucred *cred)
250 uip = cred->cr_ruidinfo;
251 atomic_add_long(&uip->ui_vmsize, pincr);
255 swap_reserve(vm_ooffset_t incr)
258 return (swap_reserve_by_cred(incr, curthread->td_ucred));
262 swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
264 u_long r, s, prev, pincr;
270 static struct timeval lastfail;
272 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
276 if (RACCT_ENABLED()) {
278 error = racct_add(curproc, RACCT_SWAP, incr);
279 PROC_UNLOCK(curproc);
286 prev = atomic_fetchadd_long(&swap_reserved, pincr);
289 oc = atomic_load_int(&overcommit);
290 if (r > s && (oc & SWAP_RESERVE_ALLOW_NONWIRED) != 0) {
291 s += vm_cnt.v_page_count - vm_cnt.v_free_reserved -
294 if ((oc & SWAP_RESERVE_FORCE_ON) != 0 && r > s &&
295 priv_check(curthread, PRIV_VM_SWAP_NOQUOTA) != 0) {
296 prev = atomic_fetchadd_long(&swap_reserved, -pincr);
297 KASSERT(prev >= pincr, ("swap_reserved < incr on overcommit fail"));
301 if (!swap_reserve_by_cred_rlimit(pincr, cred, oc)) {
302 prev = atomic_fetchadd_long(&swap_reserved, -pincr);
303 KASSERT(prev >= pincr, ("swap_reserved < incr on overcommit fail"));
310 if (ppsratecheck(&lastfail, &curfail, 1)) {
311 printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
312 cred->cr_ruidinfo->ui_uid, curproc->p_pid, incr);
315 if (RACCT_ENABLED()) {
317 racct_sub(curproc, RACCT_SWAP, incr);
318 PROC_UNLOCK(curproc);
326 swap_reserve_force(vm_ooffset_t incr)
330 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
334 if (RACCT_ENABLED()) {
336 racct_add_force(curproc, RACCT_SWAP, incr);
337 PROC_UNLOCK(curproc);
341 atomic_add_long(&swap_reserved, pincr);
342 swap_reserve_force_rlimit(pincr, curthread->td_ucred);
346 swap_release(vm_ooffset_t decr)
351 cred = curproc->p_ucred;
352 swap_release_by_cred(decr, cred);
353 PROC_UNLOCK(curproc);
357 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
364 KASSERT((decr & PAGE_MASK) == 0, ("%s: decr: %ju & PAGE_MASK", __func__,
369 prev = atomic_fetchadd_long(&swap_reserved, -pdecr);
370 KASSERT(prev >= pdecr, ("swap_reserved < decr"));
372 atomic_subtract_long(&swap_reserved, pdecr);
375 swap_release_by_cred_rlimit(pdecr, cred);
378 racct_sub_cred(cred, RACCT_SWAP, decr);
382 static int swap_pager_full = 2; /* swap space exhaustion (task killing) */
383 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
384 static struct mtx swbuf_mtx; /* to sync nsw_wcount_async */
385 static int nsw_wcount_async; /* limit async write buffers */
386 static int nsw_wcount_async_max;/* assigned maximum */
387 int nsw_cluster_max; /* maximum VOP I/O allowed */
389 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
390 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
391 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
392 "Maximum running async swap ops");
393 static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS);
394 SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD |
395 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A",
396 "Swap Fragmentation Info");
398 static struct sx sw_alloc_sx;
401 * "named" and "unnamed" anon region objects. Try to reduce the overhead
402 * of searching a named list by hashing it just a little.
407 #define NOBJLIST(handle) \
408 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
410 static struct pagerlst swap_pager_object_list[NOBJLISTS];
411 static uma_zone_t swwbuf_zone;
412 static uma_zone_t swrbuf_zone;
413 static uma_zone_t swblk_zone;
414 static uma_zone_t swpctrie_zone;
417 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
418 * calls hooked from other parts of the VM system and do not appear here.
419 * (see vm/swap_pager.h).
422 swap_pager_alloc(void *handle, vm_ooffset_t size,
423 vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
424 static void swap_pager_dealloc(vm_object_t object);
425 static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
427 static int swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
428 int *, pgo_getpages_iodone_t, void *);
429 static void swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
431 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
432 static void swap_pager_init(void);
433 static void swap_pager_unswapped(vm_page_t);
434 static void swap_pager_swapoff(struct swdevt *sp);
435 static void swap_pager_update_writecount(vm_object_t object,
436 vm_offset_t start, vm_offset_t end);
437 static void swap_pager_release_writecount(vm_object_t object,
438 vm_offset_t start, vm_offset_t end);
439 static void swap_pager_freespace(vm_object_t object, vm_pindex_t start,
442 const struct pagerops swappagerops = {
443 .pgo_kvme_type = KVME_TYPE_SWAP,
444 .pgo_init = swap_pager_init, /* early system initialization of pager */
445 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */
446 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
447 .pgo_getpages = swap_pager_getpages, /* pagein */
448 .pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
449 .pgo_putpages = swap_pager_putpages, /* pageout */
450 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */
451 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
452 .pgo_update_writecount = swap_pager_update_writecount,
453 .pgo_release_writecount = swap_pager_release_writecount,
454 .pgo_freespace = swap_pager_freespace,
458 * swap_*() routines are externally accessible. swp_*() routines are
461 static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
462 static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
464 SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
465 "Maximum size of a swap block in pages");
467 static void swp_sizecheck(void);
468 static void swp_pager_async_iodone(struct buf *bp);
469 static bool swp_pager_swblk_empty(struct swblk *sb, int start, int limit);
470 static void swp_pager_free_empty_swblk(vm_object_t, struct swblk *sb);
471 static int swapongeom(struct vnode *);
472 static int swaponvp(struct thread *, struct vnode *, u_long);
473 static int swapoff_one(struct swdevt *sp, struct ucred *cred,
477 * Swap bitmap functions
479 static void swp_pager_freeswapspace(daddr_t blk, daddr_t npages);
480 static daddr_t swp_pager_getswapspace(int *npages);
485 static daddr_t swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
486 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t);
487 static void swp_pager_meta_transfer(vm_object_t src, vm_object_t dst,
488 vm_pindex_t pindex, vm_pindex_t count);
489 static void swp_pager_meta_free_all(vm_object_t);
490 static daddr_t swp_pager_meta_lookup(vm_object_t, vm_pindex_t);
493 swp_pager_init_freerange(daddr_t *start, daddr_t *num)
496 *start = SWAPBLK_NONE;
501 swp_pager_update_freerange(daddr_t *start, daddr_t *num, daddr_t addr)
504 if (*start + *num == addr) {
507 swp_pager_freeswapspace(*start, *num);
514 swblk_trie_alloc(struct pctrie *ptree)
517 return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
518 M_USE_RESERVE : 0)));
522 swblk_trie_free(struct pctrie *ptree, void *node)
525 uma_zfree(swpctrie_zone, node);
528 PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
531 * SWP_SIZECHECK() - update swap_pager_full indication
533 * update the swap_pager_almost_full indication and warn when we are
534 * about to run out of swap space, using lowat/hiwat hysteresis.
536 * Clear swap_pager_full ( task killing ) indication when lowat is met.
538 * No restrictions on call
539 * This routine may not block.
545 if (swap_pager_avail < nswap_lowat) {
546 if (swap_pager_almost_full == 0) {
547 printf("swap_pager: out of swap space\n");
548 swap_pager_almost_full = 1;
552 if (swap_pager_avail > nswap_hiwat)
553 swap_pager_almost_full = 0;
558 * SWAP_PAGER_INIT() - initialize the swap pager!
560 * Expected to be started from system init. NOTE: This code is run
561 * before much else so be careful what you depend on. Most of the VM
562 * system has yet to be initialized at this point.
565 swap_pager_init(void)
568 * Initialize object lists
572 for (i = 0; i < NOBJLISTS; ++i)
573 TAILQ_INIT(&swap_pager_object_list[i]);
574 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
575 sx_init(&sw_alloc_sx, "swspsx");
576 sx_init(&swdev_syscall_lock, "swsysc");
579 * The nsw_cluster_max is constrained by the bp->b_pages[]
580 * array, which has maxphys / PAGE_SIZE entries, and our locally
581 * defined MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
582 * constrained by the swap device interleave stripe size.
584 * Initialized early so that GEOM_ELI can see it.
586 nsw_cluster_max = min(maxphys / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
590 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
592 * Expected to be started from pageout process once, prior to entering
596 swap_pager_swap_init(void)
601 * Number of in-transit swap bp operations. Don't
602 * exhaust the pbufs completely. Make sure we
603 * initialize workable values (0 will work for hysteresis
604 * but it isn't very efficient).
606 * Currently we hardwire nsw_wcount_async to 4. This limit is
607 * designed to prevent other I/O from having high latencies due to
608 * our pageout I/O. The value 4 works well for one or two active swap
609 * devices but is probably a little low if you have more. Even so,
610 * a higher value would probably generate only a limited improvement
611 * with three or four active swap devices since the system does not
612 * typically have to pageout at extreme bandwidths. We will want
613 * at least 2 per swap devices, and 4 is a pretty good value if you
614 * have one NFS swap device due to the command/ack latency over NFS.
615 * So it all works out pretty well.
617 * nsw_cluster_max is initialized in swap_pager_init().
620 nsw_wcount_async = 4;
621 nsw_wcount_async_max = nsw_wcount_async;
622 mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
624 swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
625 swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
628 * Initialize our zone, taking the user's requested size or
629 * estimating the number we need based on the number of pages
632 n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
633 vm_cnt.v_page_count / 2;
634 swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
635 pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0);
636 swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
637 NULL, NULL, _Alignof(struct swblk) - 1, 0);
640 if (uma_zone_reserve_kva(swblk_zone, n))
643 * if the allocation failed, try a zone two thirds the
644 * size of the previous attempt.
650 * Often uma_zone_reserve_kva() cannot reserve exactly the
651 * requested size. Account for the difference when
652 * calculating swap_maxpages.
654 n = uma_zone_get_max(swblk_zone);
657 printf("Swap blk zone entries changed from %lu to %lu.\n",
659 /* absolute maximum we can handle assuming 100% efficiency */
660 swap_maxpages = n * SWAP_META_PAGES;
661 swzone = n * sizeof(struct swblk);
662 if (!uma_zone_reserve_kva(swpctrie_zone, n))
663 printf("Cannot reserve swap pctrie zone, "
664 "reduce kern.maxswzone.\n");
668 swap_pager_init_object(vm_object_t object, void *handle, struct ucred *cred,
669 vm_ooffset_t size, vm_ooffset_t offset)
672 if (!swap_reserve_by_cred(size, cred))
677 object->un_pager.swp.writemappings = 0;
678 object->handle = handle;
681 object->charge = size;
687 swap_pager_alloc_init(objtype_t otype, void *handle, struct ucred *cred,
688 vm_ooffset_t size, vm_ooffset_t offset)
693 * The un_pager.swp.swp_blks trie is initialized by
694 * vm_object_allocate() to ensure the correct order of
695 * visibility to other threads.
697 object = vm_object_allocate(otype, OFF_TO_IDX(offset +
700 if (!swap_pager_init_object(object, handle, cred, size, offset)) {
701 vm_object_deallocate(object);
708 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
709 * its metadata structures.
711 * This routine is called from the mmap and fork code to create a new
714 * This routine must ensure that no live duplicate is created for
715 * the named object request, which is protected against by
716 * holding the sw_alloc_sx lock in case handle != NULL.
719 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
720 vm_ooffset_t offset, struct ucred *cred)
724 if (handle != NULL) {
726 * Reference existing named region or allocate new one. There
727 * should not be a race here against swp_pager_meta_build()
728 * as called from vm_page_remove() in regards to the lookup
731 sx_xlock(&sw_alloc_sx);
732 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
733 if (object == NULL) {
734 object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
736 if (object != NULL) {
737 TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
738 object, pager_object_list);
741 sx_xunlock(&sw_alloc_sx);
743 object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
750 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
752 * The swap backing for the object is destroyed. The code is
753 * designed such that we can reinstantiate it later, but this
754 * routine is typically called only when the entire object is
755 * about to be destroyed.
757 * The object must be locked.
760 swap_pager_dealloc(vm_object_t object)
763 VM_OBJECT_ASSERT_WLOCKED(object);
764 KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
767 * Remove from list right away so lookups will fail if we block for
768 * pageout completion.
770 if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
771 VM_OBJECT_WUNLOCK(object);
772 sx_xlock(&sw_alloc_sx);
773 TAILQ_REMOVE(NOBJLIST(object->handle), object,
775 sx_xunlock(&sw_alloc_sx);
776 VM_OBJECT_WLOCK(object);
779 vm_object_pip_wait(object, "swpdea");
782 * Free all remaining metadata. We only bother to free it from
783 * the swap meta data. We do not attempt to free swapblk's still
784 * associated with vm_page_t's for this object. We do not care
785 * if paging is still in progress on some objects.
787 swp_pager_meta_free_all(object);
788 object->handle = NULL;
789 object->type = OBJT_DEAD;
790 vm_object_clear_flag(object, OBJ_SWAP);
793 /************************************************************************
794 * SWAP PAGER BITMAP ROUTINES *
795 ************************************************************************/
798 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
800 * Allocate swap for up to the requested number of pages. The
801 * starting swap block number (a page index) is returned or
802 * SWAPBLK_NONE if the allocation failed.
804 * Also has the side effect of advising that somebody made a mistake
805 * when they configured swap and didn't configure enough.
807 * This routine may not sleep.
809 * We allocate in round-robin fashion from the configured devices.
812 swp_pager_getswapspace(int *io_npages)
818 KASSERT(*io_npages >= 1,
819 ("%s: npages not positive", __func__));
822 npages = imin(BLIST_MAX_ALLOC, mpages);
823 mtx_lock(&sw_dev_mtx);
825 while (!TAILQ_EMPTY(&swtailq)) {
827 sp = TAILQ_FIRST(&swtailq);
828 if ((sp->sw_flags & SW_CLOSING) == 0)
829 blk = blist_alloc(sp->sw_blist, &npages, mpages);
830 if (blk != SWAPBLK_NONE)
832 sp = TAILQ_NEXT(sp, sw_list);
840 if (blk != SWAPBLK_NONE) {
843 sp->sw_used += npages;
844 swap_pager_avail -= npages;
846 swdevhd = TAILQ_NEXT(sp, sw_list);
848 if (swap_pager_full != 2) {
849 printf("swp_pager_getswapspace(%d): failed\n",
852 swap_pager_almost_full = 1;
856 mtx_unlock(&sw_dev_mtx);
861 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
864 return (blk >= sp->sw_first && blk < sp->sw_end);
868 swp_pager_strategy(struct buf *bp)
872 mtx_lock(&sw_dev_mtx);
873 TAILQ_FOREACH(sp, &swtailq, sw_list) {
874 if (swp_pager_isondev(bp->b_blkno, sp)) {
875 mtx_unlock(&sw_dev_mtx);
876 if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
877 unmapped_buf_allowed) {
878 bp->b_data = unmapped_buf;
881 pmap_qenter((vm_offset_t)bp->b_data,
882 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
884 sp->sw_strategy(bp, sp);
888 panic("Swapdev not found");
892 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
894 * This routine returns the specified swap blocks back to the bitmap.
896 * This routine may not sleep.
899 swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
905 mtx_lock(&sw_dev_mtx);
906 TAILQ_FOREACH(sp, &swtailq, sw_list) {
907 if (swp_pager_isondev(blk, sp)) {
908 sp->sw_used -= npages;
910 * If we are attempting to stop swapping on
911 * this device, we don't want to mark any
912 * blocks free lest they be reused.
914 if ((sp->sw_flags & SW_CLOSING) == 0) {
915 blist_free(sp->sw_blist, blk - sp->sw_first,
917 swap_pager_avail += npages;
920 mtx_unlock(&sw_dev_mtx);
924 panic("Swapdev not found");
928 * SYSCTL_SWAP_FRAGMENTATION() - produce raw swap space stats
931 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
938 error = sysctl_wire_old_buffer(req, 0);
941 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
942 mtx_lock(&sw_dev_mtx);
943 TAILQ_FOREACH(sp, &swtailq, sw_list) {
944 if (vn_isdisk(sp->sw_vp))
945 devname = devtoname(sp->sw_vp->v_rdev);
948 sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
949 blist_stats(sp->sw_blist, &sbuf);
951 mtx_unlock(&sw_dev_mtx);
952 error = sbuf_finish(&sbuf);
958 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
959 * range within an object.
961 * This routine removes swapblk assignments from swap metadata.
963 * The external callers of this routine typically have already destroyed
964 * or renamed vm_page_t's associated with this range in the object so
967 * The object must be locked.
970 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
973 swp_pager_meta_free(object, start, size);
977 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
979 * Assigns swap blocks to the specified range within the object. The
980 * swap blocks are not zeroed. Any previous swap assignment is destroyed.
982 * Returns 0 on success, -1 on failure.
985 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_pindex_t size)
987 daddr_t addr, blk, n_free, s_free;
991 swp_pager_init_freerange(&s_free, &n_free);
992 VM_OBJECT_WLOCK(object);
993 for (i = 0; i < size; i += n) {
994 n = MIN(size - i, INT_MAX);
995 blk = swp_pager_getswapspace(&n);
996 if (blk == SWAPBLK_NONE) {
997 swp_pager_meta_free(object, start, i);
998 VM_OBJECT_WUNLOCK(object);
1001 for (j = 0; j < n; ++j) {
1002 addr = swp_pager_meta_build(object,
1003 start + i + j, blk + j);
1004 if (addr != SWAPBLK_NONE)
1005 swp_pager_update_freerange(&s_free, &n_free,
1009 swp_pager_freeswapspace(s_free, n_free);
1010 VM_OBJECT_WUNLOCK(object);
1015 swp_pager_xfer_source(vm_object_t srcobject, vm_object_t dstobject,
1016 vm_pindex_t pindex, daddr_t addr)
1018 daddr_t dstaddr __diagused;
1020 KASSERT((srcobject->flags & OBJ_SWAP) != 0,
1021 ("%s: Srcobject not swappable", __func__));
1022 if ((dstobject->flags & OBJ_SWAP) != 0 &&
1023 swp_pager_meta_lookup(dstobject, pindex) != SWAPBLK_NONE) {
1024 /* Caller should destroy the source block. */
1029 * Destination has no swapblk and is not resident, transfer source.
1030 * swp_pager_meta_build() can sleep.
1032 VM_OBJECT_WUNLOCK(srcobject);
1033 dstaddr = swp_pager_meta_build(dstobject, pindex, addr);
1034 KASSERT(dstaddr == SWAPBLK_NONE,
1035 ("Unexpected destination swapblk"));
1036 VM_OBJECT_WLOCK(srcobject);
1042 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
1043 * and destroy the source.
1045 * Copy any valid swapblks from the source to the destination. In
1046 * cases where both the source and destination have a valid swapblk,
1047 * we keep the destination's.
1049 * This routine is allowed to sleep. It may sleep allocating metadata
1050 * indirectly through swp_pager_meta_build().
1052 * The source object contains no vm_page_t's (which is just as well)
1054 * The source object is of type OBJT_SWAP.
1056 * The source and destination objects must be locked.
1057 * Both object locks may temporarily be released.
1060 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
1061 vm_pindex_t offset, int destroysource)
1064 VM_OBJECT_ASSERT_WLOCKED(srcobject);
1065 VM_OBJECT_ASSERT_WLOCKED(dstobject);
1068 * If destroysource is set, we remove the source object from the
1069 * swap_pager internal queue now.
1071 if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
1072 srcobject->handle != NULL) {
1073 VM_OBJECT_WUNLOCK(srcobject);
1074 VM_OBJECT_WUNLOCK(dstobject);
1075 sx_xlock(&sw_alloc_sx);
1076 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1078 sx_xunlock(&sw_alloc_sx);
1079 VM_OBJECT_WLOCK(dstobject);
1080 VM_OBJECT_WLOCK(srcobject);
1084 * Transfer source to destination.
1086 swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size);
1089 * Free left over swap blocks in source.
1091 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
1092 * double-remove the object from the swap queues.
1094 if (destroysource) {
1095 swp_pager_meta_free_all(srcobject);
1097 * Reverting the type is not necessary, the caller is going
1098 * to destroy srcobject directly, but I'm doing it here
1099 * for consistency since we've removed the object from its
1102 srcobject->type = OBJT_DEFAULT;
1103 vm_object_clear_flag(srcobject, OBJ_SWAP);
1108 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
1109 * the requested page.
1111 * We determine whether good backing store exists for the requested
1112 * page and return TRUE if it does, FALSE if it doesn't.
1114 * If TRUE, we also try to determine how much valid, contiguous backing
1115 * store exists before and after the requested page.
1118 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1124 VM_OBJECT_ASSERT_LOCKED(object);
1125 KASSERT((object->flags & OBJ_SWAP) != 0,
1126 ("%s: object not swappable", __func__));
1129 * do we have good backing store at the requested index ?
1131 blk0 = swp_pager_meta_lookup(object, pindex);
1132 if (blk0 == SWAPBLK_NONE) {
1141 * find backwards-looking contiguous good backing store
1143 if (before != NULL) {
1144 for (i = 1; i < SWB_NPAGES; i++) {
1147 blk = swp_pager_meta_lookup(object, pindex - i);
1148 if (blk != blk0 - i)
1155 * find forward-looking contiguous good backing store
1157 if (after != NULL) {
1158 for (i = 1; i < SWB_NPAGES; i++) {
1159 blk = swp_pager_meta_lookup(object, pindex + i);
1160 if (blk != blk0 + i)
1169 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1171 * This removes any associated swap backing store, whether valid or
1172 * not, from the page.
1174 * This routine is typically called when a page is made dirty, at
1175 * which point any associated swap can be freed. MADV_FREE also
1176 * calls us in a special-case situation
1178 * NOTE!!! If the page is clean and the swap was valid, the caller
1179 * should make the page dirty before calling this routine. This routine
1180 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1183 * This routine may not sleep.
1185 * The object containing the page may be locked.
1188 swap_pager_unswapped(vm_page_t m)
1194 * Handle enqueing deferred frees first. If we do not have the
1195 * object lock we wait for the page daemon to clear the space.
1198 if (!VM_OBJECT_WOWNED(obj)) {
1199 VM_PAGE_OBJECT_BUSY_ASSERT(m);
1201 * The caller is responsible for synchronization but we
1202 * will harmlessly handle races. This is typically provided
1203 * by only calling unswapped() when a page transitions from
1206 if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1208 vm_page_aflag_set(m, PGA_SWAP_FREE);
1209 counter_u64_add(swap_free_deferred, 1);
1213 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1214 counter_u64_add(swap_free_completed, 1);
1215 vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
1218 * The meta data only exists if the object is OBJT_SWAP
1219 * and even then might not be allocated yet.
1221 KASSERT((m->object->flags & OBJ_SWAP) != 0,
1222 ("Free object not swappable"));
1224 sb = SWAP_PCTRIE_LOOKUP(&m->object->un_pager.swp.swp_blks,
1225 rounddown(m->pindex, SWAP_META_PAGES));
1228 if (sb->d[m->pindex % SWAP_META_PAGES] == SWAPBLK_NONE)
1230 swp_pager_freeswapspace(sb->d[m->pindex % SWAP_META_PAGES], 1);
1231 sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
1232 swp_pager_free_empty_swblk(m->object, sb);
1236 * swap_pager_getpages() - bring pages in from swap
1238 * Attempt to page in the pages in array "ma" of length "count". The
1239 * caller may optionally specify that additional pages preceding and
1240 * succeeding the specified range be paged in. The number of such pages
1241 * is returned in the "rbehind" and "rahead" parameters, and they will
1242 * be in the inactive queue upon return.
1244 * The pages in "ma" must be busied and will remain busied upon return.
1247 swap_pager_getpages_locked(vm_object_t object, vm_page_t *ma, int count,
1248 int *rbehind, int *rahead)
1251 vm_page_t bm, mpred, msucc, p;
1254 int i, maxahead, maxbehind, reqcount;
1256 VM_OBJECT_ASSERT_WLOCKED(object);
1259 KASSERT((object->flags & OBJ_SWAP) != 0,
1260 ("%s: object not swappable", __func__));
1261 if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead)) {
1262 VM_OBJECT_WUNLOCK(object);
1263 return (VM_PAGER_FAIL);
1266 KASSERT(reqcount - 1 <= maxahead,
1267 ("page count %d extends beyond swap block", reqcount));
1270 * Do not transfer any pages other than those that are xbusied
1271 * when running during a split or collapse operation. This
1272 * prevents clustering from re-creating pages which are being
1273 * moved into another object.
1275 if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
1276 maxahead = reqcount - 1;
1281 * Clip the readahead and readbehind ranges to exclude resident pages.
1283 if (rahead != NULL) {
1284 *rahead = imin(*rahead, maxahead - (reqcount - 1));
1285 pindex = ma[reqcount - 1]->pindex;
1286 msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1287 if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1288 *rahead = msucc->pindex - pindex - 1;
1290 if (rbehind != NULL) {
1291 *rbehind = imin(*rbehind, maxbehind);
1292 pindex = ma[0]->pindex;
1293 mpred = TAILQ_PREV(ma[0], pglist, listq);
1294 if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1295 *rbehind = pindex - mpred->pindex - 1;
1299 for (i = 0; i < count; i++)
1300 ma[i]->oflags |= VPO_SWAPINPROG;
1303 * Allocate readahead and readbehind pages.
1305 if (rbehind != NULL) {
1306 for (i = 1; i <= *rbehind; i++) {
1307 p = vm_page_alloc(object, ma[0]->pindex - i,
1311 p->oflags |= VPO_SWAPINPROG;
1316 if (rahead != NULL) {
1317 for (i = 0; i < *rahead; i++) {
1318 p = vm_page_alloc(object,
1319 ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1322 p->oflags |= VPO_SWAPINPROG;
1326 if (rbehind != NULL)
1331 vm_object_pip_add(object, count);
1333 pindex = bm->pindex;
1334 blk = swp_pager_meta_lookup(object, pindex);
1335 KASSERT(blk != SWAPBLK_NONE,
1336 ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1338 VM_OBJECT_WUNLOCK(object);
1339 bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1340 MPASS((bp->b_flags & B_MAXPHYS) != 0);
1341 /* Pages cannot leave the object while busy. */
1342 for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1343 MPASS(p->pindex == bm->pindex + i);
1347 bp->b_flags |= B_PAGING;
1348 bp->b_iocmd = BIO_READ;
1349 bp->b_iodone = swp_pager_async_iodone;
1350 bp->b_rcred = crhold(thread0.td_ucred);
1351 bp->b_wcred = crhold(thread0.td_ucred);
1353 bp->b_bcount = PAGE_SIZE * count;
1354 bp->b_bufsize = PAGE_SIZE * count;
1355 bp->b_npages = count;
1356 bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1357 bp->b_pgafter = rahead != NULL ? *rahead : 0;
1359 VM_CNT_INC(v_swapin);
1360 VM_CNT_ADD(v_swappgsin, count);
1363 * perform the I/O. NOTE!!! bp cannot be considered valid after
1364 * this point because we automatically release it on completion.
1365 * Instead, we look at the one page we are interested in which we
1366 * still hold a lock on even through the I/O completion.
1368 * The other pages in our ma[] array are also released on completion,
1369 * so we cannot assume they are valid anymore either.
1371 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1374 swp_pager_strategy(bp);
1377 * Wait for the pages we want to complete. VPO_SWAPINPROG is always
1378 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1379 * is set in the metadata for each page in the request.
1381 VM_OBJECT_WLOCK(object);
1382 /* This could be implemented more efficiently with aflags */
1383 while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
1384 ma[0]->oflags |= VPO_SWAPSLEEP;
1385 VM_CNT_INC(v_intrans);
1386 if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1387 "swread", hz * 20)) {
1389 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1390 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1393 VM_OBJECT_WUNLOCK(object);
1396 * If we had an unrecoverable read error pages will not be valid.
1398 for (i = 0; i < reqcount; i++)
1399 if (ma[i]->valid != VM_PAGE_BITS_ALL)
1400 return (VM_PAGER_ERROR);
1402 return (VM_PAGER_OK);
1405 * A final note: in a low swap situation, we cannot deallocate swap
1406 * and mark a page dirty here because the caller is likely to mark
1407 * the page clean when we return, causing the page to possibly revert
1408 * to all-zero's later.
1413 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count,
1414 int *rbehind, int *rahead)
1417 VM_OBJECT_WLOCK(object);
1418 return (swap_pager_getpages_locked(object, ma, count, rbehind, rahead));
1422 * swap_pager_getpages_async():
1424 * Right now this is emulation of asynchronous operation on top of
1425 * swap_pager_getpages().
1428 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1429 int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1433 r = swap_pager_getpages(object, ma, count, rbehind, rahead);
1438 case VM_PAGER_ERROR:
1445 panic("unhandled swap_pager_getpages() error %d", r);
1447 (iodone)(arg, ma, count, error);
1453 * swap_pager_putpages:
1455 * Assign swap (if necessary) and initiate I/O on the specified pages.
1457 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1458 * are automatically converted to SWAP objects.
1460 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1461 * vm_page reservation system coupled with properly written VFS devices
1462 * should ensure that no low-memory deadlock occurs. This is an area
1465 * The parent has N vm_object_pip_add() references prior to
1466 * calling us and will remove references for rtvals[] that are
1467 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1470 * The parent has soft-busy'd the pages it passes us and will unbusy
1471 * those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
1472 * We need to unbusy the rest on I/O completion.
1475 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1476 int flags, int *rtvals)
1479 daddr_t addr, blk, n_free, s_free;
1484 KASSERT(count == 0 || ma[0]->object == object,
1485 ("%s: object mismatch %p/%p",
1486 __func__, object, ma[0]->object));
1491 * Turn object into OBJT_SWAP. Force sync if not a pageout process.
1493 if ((object->flags & OBJ_SWAP) == 0) {
1494 addr = swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1495 KASSERT(addr == SWAPBLK_NONE,
1496 ("unexpected object swap block"));
1498 VM_OBJECT_WUNLOCK(object);
1499 async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
1500 swp_pager_init_freerange(&s_free, &n_free);
1505 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1506 * The page is left dirty until the pageout operation completes
1509 for (i = 0; i < count; i += n) {
1510 /* Maximum I/O size is limited by maximum swap block size. */
1511 n = min(count - i, nsw_cluster_max);
1514 mtx_lock(&swbuf_mtx);
1515 while (nsw_wcount_async == 0)
1516 msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1519 mtx_unlock(&swbuf_mtx);
1522 /* Get a block of swap of size up to size n. */
1523 VM_OBJECT_WLOCK(object);
1524 blk = swp_pager_getswapspace(&n);
1525 if (blk == SWAPBLK_NONE) {
1526 VM_OBJECT_WUNLOCK(object);
1527 mtx_lock(&swbuf_mtx);
1528 if (++nsw_wcount_async == 1)
1529 wakeup(&nsw_wcount_async);
1530 mtx_unlock(&swbuf_mtx);
1531 for (j = 0; j < n; ++j)
1532 rtvals[i + j] = VM_PAGER_FAIL;
1535 for (j = 0; j < n; ++j) {
1537 vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1538 addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1540 if (addr != SWAPBLK_NONE)
1541 swp_pager_update_freerange(&s_free, &n_free,
1543 MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1544 mreq->oflags |= VPO_SWAPINPROG;
1546 VM_OBJECT_WUNLOCK(object);
1548 bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1549 MPASS((bp->b_flags & B_MAXPHYS) != 0);
1551 bp->b_flags |= B_ASYNC;
1552 bp->b_flags |= B_PAGING;
1553 bp->b_iocmd = BIO_WRITE;
1555 bp->b_rcred = crhold(thread0.td_ucred);
1556 bp->b_wcred = crhold(thread0.td_ucred);
1557 bp->b_bcount = PAGE_SIZE * n;
1558 bp->b_bufsize = PAGE_SIZE * n;
1560 for (j = 0; j < n; j++)
1561 bp->b_pages[j] = ma[i + j];
1565 * Must set dirty range for NFS to work.
1568 bp->b_dirtyend = bp->b_bcount;
1570 VM_CNT_INC(v_swapout);
1571 VM_CNT_ADD(v_swappgsout, bp->b_npages);
1574 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1575 * can call the async completion routine at the end of a
1576 * synchronous I/O operation. Otherwise, our caller would
1577 * perform duplicate unbusy and wakeup operations on the page
1578 * and object, respectively.
1580 for (j = 0; j < n; j++)
1581 rtvals[i + j] = VM_PAGER_PEND;
1586 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1589 bp->b_iodone = swp_pager_async_iodone;
1591 swp_pager_strategy(bp);
1598 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1600 bp->b_iodone = bdone;
1601 swp_pager_strategy(bp);
1604 * Wait for the sync I/O to complete.
1606 bwait(bp, PVM, "swwrt");
1609 * Now that we are through with the bp, we can call the
1610 * normal async completion, which frees everything up.
1612 swp_pager_async_iodone(bp);
1614 swp_pager_freeswapspace(s_free, n_free);
1615 VM_OBJECT_WLOCK(object);
1619 * swp_pager_async_iodone:
1621 * Completion routine for asynchronous reads and writes from/to swap.
1622 * Also called manually by synchronous code to finish up a bp.
1624 * This routine may not sleep.
1627 swp_pager_async_iodone(struct buf *bp)
1630 vm_object_t object = NULL;
1633 * Report error - unless we ran out of memory, in which case
1634 * we've already logged it in swapgeom_strategy().
1636 if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
1638 "swap_pager: I/O error - %s failed; blkno %ld,"
1639 "size %ld, error %d\n",
1640 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1648 * remove the mapping for kernel virtual
1651 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1653 bp->b_data = bp->b_kvabase;
1656 object = bp->b_pages[0]->object;
1657 VM_OBJECT_WLOCK(object);
1661 * cleanup pages. If an error occurs writing to swap, we are in
1662 * very serious trouble. If it happens to be a disk error, though,
1663 * we may be able to recover by reassigning the swap later on. So
1664 * in this case we remove the m->swapblk assignment for the page
1665 * but do not free it in the rlist. The errornous block(s) are thus
1666 * never reallocated as swap. Redirty the page and continue.
1668 for (i = 0; i < bp->b_npages; ++i) {
1669 vm_page_t m = bp->b_pages[i];
1671 m->oflags &= ~VPO_SWAPINPROG;
1672 if (m->oflags & VPO_SWAPSLEEP) {
1673 m->oflags &= ~VPO_SWAPSLEEP;
1674 wakeup(&object->handle);
1677 /* We always have space after I/O, successful or not. */
1678 vm_page_aflag_set(m, PGA_SWAP_SPACE);
1680 if (bp->b_ioflags & BIO_ERROR) {
1682 * If an error occurs I'd love to throw the swapblk
1683 * away without freeing it back to swapspace, so it
1684 * can never be used again. But I can't from an
1687 if (bp->b_iocmd == BIO_READ) {
1689 * NOTE: for reads, m->dirty will probably
1690 * be overridden by the original caller of
1691 * getpages so don't play cute tricks here.
1696 * If a write error occurs, reactivate page
1697 * so it doesn't clog the inactive list,
1698 * then finish the I/O.
1700 MPASS(m->dirty == VM_PAGE_BITS_ALL);
1702 /* PQ_UNSWAPPABLE? */
1703 vm_page_activate(m);
1706 } else if (bp->b_iocmd == BIO_READ) {
1708 * NOTE: for reads, m->dirty will probably be
1709 * overridden by the original caller of getpages so
1710 * we cannot set them in order to free the underlying
1711 * swap in a low-swap situation. I don't think we'd
1712 * want to do that anyway, but it was an optimization
1713 * that existed in the old swapper for a time before
1714 * it got ripped out due to precisely this problem.
1716 KASSERT(!pmap_page_is_mapped(m),
1717 ("swp_pager_async_iodone: page %p is mapped", m));
1718 KASSERT(m->dirty == 0,
1719 ("swp_pager_async_iodone: page %p is dirty", m));
1722 if (i < bp->b_pgbefore ||
1723 i >= bp->b_npages - bp->b_pgafter)
1724 vm_page_readahead_finish(m);
1727 * For write success, clear the dirty
1728 * status, then finish the I/O ( which decrements the
1729 * busy count and possibly wakes waiter's up ).
1730 * A page is only written to swap after a period of
1731 * inactivity. Therefore, we do not expect it to be
1734 KASSERT(!pmap_page_is_write_mapped(m),
1735 ("swp_pager_async_iodone: page %p is not write"
1738 vm_page_deactivate_noreuse(m);
1744 * adjust pip. NOTE: the original parent may still have its own
1745 * pip refs on the object.
1747 if (object != NULL) {
1748 vm_object_pip_wakeupn(object, bp->b_npages);
1749 VM_OBJECT_WUNLOCK(object);
1753 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1754 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1755 * trigger a KASSERT in relpbuf().
1759 bp->b_bufobj = NULL;
1762 * release the physical I/O buffer
1764 if (bp->b_flags & B_ASYNC) {
1765 mtx_lock(&swbuf_mtx);
1766 if (++nsw_wcount_async == 1)
1767 wakeup(&nsw_wcount_async);
1768 mtx_unlock(&swbuf_mtx);
1770 uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
1774 swap_pager_nswapdev(void)
1781 swp_pager_force_dirty(vm_page_t m)
1785 swap_pager_unswapped(m);
1790 swap_pager_swapped_pages(vm_object_t object)
1797 VM_OBJECT_ASSERT_LOCKED(object);
1798 if ((object->flags & OBJ_SWAP) == 0)
1801 for (res = 0, pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1802 &object->un_pager.swp.swp_blks, pi)) != NULL;
1803 pi = sb->p + SWAP_META_PAGES) {
1804 for (i = 0; i < SWAP_META_PAGES; i++) {
1805 if (sb->d[i] != SWAPBLK_NONE)
1813 * swap_pager_swapoff_object:
1815 * Page in all of the pages that have been paged out for an object
1819 swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
1825 int i, nv, rahead, rv;
1827 KASSERT((object->flags & OBJ_SWAP) != 0,
1828 ("%s: Object not swappable", __func__));
1830 for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1831 &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1832 if ((object->flags & OBJ_DEAD) != 0) {
1834 * Make sure that pending writes finish before
1837 vm_object_pip_wait(object, "swpoff");
1838 swp_pager_meta_free_all(object);
1841 for (i = 0; i < SWAP_META_PAGES; i++) {
1843 * Count the number of contiguous valid blocks.
1845 for (nv = 0; nv < SWAP_META_PAGES - i; nv++) {
1846 blk = sb->d[i + nv];
1847 if (!swp_pager_isondev(blk, sp) ||
1848 blk == SWAPBLK_NONE)
1855 * Look for a page corresponding to the first
1856 * valid block and ensure that any pending paging
1857 * operations on it are complete. If the page is valid,
1858 * mark it dirty and free the swap block. Try to batch
1859 * this operation since it may cause sp to be freed,
1860 * meaning that we must restart the scan. Avoid busying
1861 * valid pages since we may block forever on kernel
1864 m = vm_page_lookup(object, sb->p + i);
1866 m = vm_page_alloc(object, sb->p + i,
1867 VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
1871 if ((m->oflags & VPO_SWAPINPROG) != 0) {
1872 m->oflags |= VPO_SWAPSLEEP;
1873 VM_OBJECT_SLEEP(object, &object->handle,
1877 if (vm_page_all_valid(m)) {
1879 swp_pager_force_dirty(m);
1880 } while (--nv > 0 &&
1881 (m = vm_page_next(m)) != NULL &&
1882 vm_page_all_valid(m) &&
1883 (m->oflags & VPO_SWAPINPROG) == 0);
1886 if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL))
1890 vm_object_pip_add(object, 1);
1891 rahead = SWAP_META_PAGES;
1892 rv = swap_pager_getpages_locked(object, &m, 1, NULL,
1894 if (rv != VM_PAGER_OK)
1895 panic("%s: read from swap failed: %d",
1897 vm_object_pip_wakeupn(object, 1);
1898 VM_OBJECT_WLOCK(object);
1902 * The object lock was dropped so we must restart the
1903 * scan of this swap block. Pages paged in during this
1904 * iteration will be marked dirty in a future iteration.
1908 if (i == SWAP_META_PAGES)
1909 pi = sb->p + SWAP_META_PAGES;
1914 * swap_pager_swapoff:
1916 * Page in all of the pages that have been paged out to the
1917 * given device. The corresponding blocks in the bitmap must be
1918 * marked as allocated and the device must be flagged SW_CLOSING.
1919 * There may be no processes swapped out to the device.
1921 * This routine may block.
1924 swap_pager_swapoff(struct swdevt *sp)
1929 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1933 mtx_lock(&vm_object_list_mtx);
1934 TAILQ_FOREACH(object, &vm_object_list, object_list) {
1935 if ((object->flags & OBJ_SWAP) == 0)
1937 mtx_unlock(&vm_object_list_mtx);
1938 /* Depends on type-stability. */
1939 VM_OBJECT_WLOCK(object);
1942 * Dead objects are eventually terminated on their own.
1944 if ((object->flags & OBJ_DEAD) != 0)
1948 * Sync with fences placed after pctrie
1949 * initialization. We must not access pctrie below
1950 * unless we checked that our object is swap and not
1953 atomic_thread_fence_acq();
1954 if ((object->flags & OBJ_SWAP) == 0)
1957 swap_pager_swapoff_object(sp, object);
1959 VM_OBJECT_WUNLOCK(object);
1960 mtx_lock(&vm_object_list_mtx);
1962 mtx_unlock(&vm_object_list_mtx);
1966 * Objects may be locked or paging to the device being
1967 * removed, so we will miss their pages and need to
1968 * make another pass. We have marked this device as
1969 * SW_CLOSING, so the activity should finish soon.
1972 if (retries > 100) {
1973 panic("swapoff: failed to locate %d swap blocks",
1976 pause("swpoff", hz / 20);
1979 EVENTHANDLER_INVOKE(swapoff, sp);
1982 /************************************************************************
1984 ************************************************************************
1986 * These routines manipulate the swap metadata stored in the
1989 * Swap metadata is implemented with a global hash and not directly
1990 * linked into the object. Instead the object simply contains
1991 * appropriate tracking counters.
1995 * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
1998 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
2002 MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
2003 for (i = start; i < limit; i++) {
2004 if (sb->d[i] != SWAPBLK_NONE)
2011 * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
2013 * Nothing is done if the block is still in use.
2016 swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
2019 if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
2020 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2021 uma_zfree(swblk_zone, sb);
2026 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
2028 * We first convert the object to a swap object if it is a default
2031 * The specified swapblk is added to the object's swap metadata. If
2032 * the swapblk is not valid, it is freed instead. Any previously
2033 * assigned swapblk is returned.
2036 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
2038 static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
2039 struct swblk *sb, *sb1;
2040 vm_pindex_t modpi, rdpi;
2041 daddr_t prev_swapblk;
2044 VM_OBJECT_ASSERT_WLOCKED(object);
2047 * Convert default object to swap object if necessary
2049 if ((object->flags & OBJ_SWAP) == 0) {
2050 pctrie_init(&object->un_pager.swp.swp_blks);
2053 * Ensure that swap_pager_swapoff()'s iteration over
2054 * object_list does not see a garbage pctrie.
2056 atomic_thread_fence_rel();
2058 object->type = OBJT_SWAP;
2059 vm_object_set_flag(object, OBJ_SWAP);
2060 object->un_pager.swp.writemappings = 0;
2061 KASSERT((object->flags & OBJ_ANON) != 0 ||
2062 object->handle == NULL,
2063 ("default pager %p with handle %p",
2064 object, object->handle));
2067 rdpi = rounddown(pindex, SWAP_META_PAGES);
2068 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
2070 if (swapblk == SWAPBLK_NONE)
2071 return (SWAPBLK_NONE);
2073 sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
2074 pageproc ? M_USE_RESERVE : 0));
2077 for (i = 0; i < SWAP_META_PAGES; i++)
2078 sb->d[i] = SWAPBLK_NONE;
2079 if (atomic_cmpset_int(&swblk_zone_exhausted,
2081 printf("swblk zone ok\n");
2084 VM_OBJECT_WUNLOCK(object);
2085 if (uma_zone_exhausted(swblk_zone)) {
2086 if (atomic_cmpset_int(&swblk_zone_exhausted,
2088 printf("swap blk zone exhausted, "
2089 "increase kern.maxswzone\n");
2090 vm_pageout_oom(VM_OOM_SWAPZ);
2091 pause("swzonxb", 10);
2093 uma_zwait(swblk_zone);
2094 VM_OBJECT_WLOCK(object);
2095 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2099 * Somebody swapped out a nearby page,
2100 * allocating swblk at the rdpi index,
2101 * while we dropped the object lock.
2106 error = SWAP_PCTRIE_INSERT(
2107 &object->un_pager.swp.swp_blks, sb);
2109 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2111 printf("swpctrie zone ok\n");
2114 VM_OBJECT_WUNLOCK(object);
2115 if (uma_zone_exhausted(swpctrie_zone)) {
2116 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2118 printf("swap pctrie zone exhausted, "
2119 "increase kern.maxswzone\n");
2120 vm_pageout_oom(VM_OOM_SWAPZ);
2121 pause("swzonxp", 10);
2123 uma_zwait(swpctrie_zone);
2124 VM_OBJECT_WLOCK(object);
2125 sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2128 uma_zfree(swblk_zone, sb);
2135 MPASS(sb->p == rdpi);
2137 modpi = pindex % SWAP_META_PAGES;
2138 /* Return prior contents of metadata. */
2139 prev_swapblk = sb->d[modpi];
2140 /* Enter block into metadata. */
2141 sb->d[modpi] = swapblk;
2144 * Free the swblk if we end up with the empty page run.
2146 if (swapblk == SWAPBLK_NONE)
2147 swp_pager_free_empty_swblk(object, sb);
2148 return (prev_swapblk);
2152 * SWP_PAGER_META_TRANSFER() - free a range of blocks in the srcobject's swap
2153 * metadata, or transfer it into dstobject.
2155 * This routine will free swap metadata structures as they are cleaned
2159 swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
2160 vm_pindex_t pindex, vm_pindex_t count)
2163 daddr_t n_free, s_free;
2164 vm_pindex_t offset, last;
2165 int i, limit, start;
2167 VM_OBJECT_ASSERT_WLOCKED(srcobject);
2168 if ((srcobject->flags & OBJ_SWAP) == 0 || count == 0)
2171 swp_pager_init_freerange(&s_free, &n_free);
2173 last = pindex + count;
2175 sb = SWAP_PCTRIE_LOOKUP_GE(&srcobject->un_pager.swp.swp_blks,
2176 rounddown(pindex, SWAP_META_PAGES));
2177 if (sb == NULL || sb->p >= last)
2179 start = pindex > sb->p ? pindex - sb->p : 0;
2180 limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2182 for (i = start; i < limit; i++) {
2183 if (sb->d[i] == SWAPBLK_NONE)
2185 if (dstobject == NULL ||
2186 !swp_pager_xfer_source(srcobject, dstobject,
2187 sb->p + i - offset, sb->d[i])) {
2188 swp_pager_update_freerange(&s_free, &n_free,
2191 sb->d[i] = SWAPBLK_NONE;
2193 pindex = sb->p + SWAP_META_PAGES;
2194 if (swp_pager_swblk_empty(sb, 0, start) &&
2195 swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2196 SWAP_PCTRIE_REMOVE(&srcobject->un_pager.swp.swp_blks,
2198 uma_zfree(swblk_zone, sb);
2201 swp_pager_freeswapspace(s_free, n_free);
2205 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
2207 * The requested range of blocks is freed, with any associated swap
2208 * returned to the swap bitmap.
2210 * This routine will free swap metadata structures as they are cleaned
2211 * out. This routine does *NOT* operate on swap metadata associated
2212 * with resident pages.
2215 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count)
2217 swp_pager_meta_transfer(object, NULL, pindex, count);
2221 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
2223 * This routine locates and destroys all swap metadata associated with
2227 swp_pager_meta_free_all(vm_object_t object)
2230 daddr_t n_free, s_free;
2234 VM_OBJECT_ASSERT_WLOCKED(object);
2235 if ((object->flags & OBJ_SWAP) == 0)
2238 swp_pager_init_freerange(&s_free, &n_free);
2239 for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
2240 &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
2241 pindex = sb->p + SWAP_META_PAGES;
2242 for (i = 0; i < SWAP_META_PAGES; i++) {
2243 if (sb->d[i] == SWAPBLK_NONE)
2245 swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
2247 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2248 uma_zfree(swblk_zone, sb);
2250 swp_pager_freeswapspace(s_free, n_free);
2254 * SWP_PAGER_METACTL() - misc control of swap meta data.
2256 * This routine is capable of looking up, or removing swapblk
2257 * assignments in the swap meta data. It returns the swapblk being
2258 * looked-up, popped, or SWAPBLK_NONE if the block was invalid.
2260 * When acting on a busy resident page and paging is in progress, we
2261 * have to wait until paging is complete but otherwise can act on the
2265 swp_pager_meta_lookup(vm_object_t object, vm_pindex_t pindex)
2269 VM_OBJECT_ASSERT_LOCKED(object);
2272 * The meta data only exists if the object is OBJT_SWAP
2273 * and even then might not be allocated yet.
2275 KASSERT((object->flags & OBJ_SWAP) != 0,
2276 ("Lookup object not swappable"));
2278 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2279 rounddown(pindex, SWAP_META_PAGES));
2281 return (SWAPBLK_NONE);
2282 return (sb->d[pindex % SWAP_META_PAGES]);
2286 * Returns the least page index which is greater than or equal to the
2287 * parameter pindex and for which there is a swap block allocated.
2288 * Returns object's size if the object's type is not swap or if there
2289 * are no allocated swap blocks for the object after the requested
2293 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2298 VM_OBJECT_ASSERT_LOCKED(object);
2299 if ((object->flags & OBJ_SWAP) == 0)
2300 return (object->size);
2302 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2303 rounddown(pindex, SWAP_META_PAGES));
2305 return (object->size);
2306 if (sb->p < pindex) {
2307 for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2308 if (sb->d[i] != SWAPBLK_NONE)
2311 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2312 roundup(pindex, SWAP_META_PAGES));
2314 return (object->size);
2316 for (i = 0; i < SWAP_META_PAGES; i++) {
2317 if (sb->d[i] != SWAPBLK_NONE)
2322 * We get here if a swblk is present in the trie but it
2323 * doesn't map any blocks.
2326 return (object->size);
2330 * System call swapon(name) enables swapping on device name,
2331 * which must be in the swdevsw. Return EBUSY
2332 * if already swapping on this device.
2334 #ifndef _SYS_SYSPROTO_H_
2335 struct swapon_args {
2341 sys_swapon(struct thread *td, struct swapon_args *uap)
2345 struct nameidata nd;
2348 error = priv_check(td, PRIV_SWAPON);
2352 sx_xlock(&swdev_syscall_lock);
2355 * Swap metadata may not fit in the KVM if we have physical
2358 if (swblk_zone == NULL) {
2363 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | LOCKLEAF | AUDITVNODE1,
2364 UIO_USERSPACE, uap->name);
2372 if (vn_isdisk_error(vp, &error)) {
2373 error = swapongeom(vp);
2374 } else if (vp->v_type == VREG &&
2375 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2376 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2378 * Allow direct swapping to NFS regular files in the same
2379 * way that nfs_mountroot() sets up diskless swapping.
2381 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2389 sx_xunlock(&swdev_syscall_lock);
2394 * Check that the total amount of swap currently configured does not
2395 * exceed half the theoretical maximum. If it does, print a warning
2399 swapon_check_swzone(void)
2402 /* recommend using no more than half that amount */
2403 if (swap_total > swap_maxpages / 2) {
2404 printf("warning: total configured swap (%lu pages) "
2405 "exceeds maximum recommended amount (%lu pages).\n",
2406 swap_total, swap_maxpages / 2);
2407 printf("warning: increase kern.maxswzone "
2408 "or reduce amount of swap.\n");
2413 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2414 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2416 struct swdevt *sp, *tsp;
2420 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2421 * First chop nblks off to page-align it, then convert.
2423 * sw->sw_nblks is in page-sized chunks now too.
2425 nblks &= ~(ctodb(1) - 1);
2426 nblks = dbtoc(nblks);
2428 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2429 sp->sw_blist = blist_create(nblks, M_WAITOK);
2433 sp->sw_nblks = nblks;
2435 sp->sw_strategy = strategy;
2436 sp->sw_close = close;
2437 sp->sw_flags = flags;
2440 * Do not free the first blocks in order to avoid overwriting
2441 * any bsd label at the front of the partition
2443 blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2444 nblks - howmany(BBSIZE, PAGE_SIZE));
2447 mtx_lock(&sw_dev_mtx);
2448 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2449 if (tsp->sw_end >= dvbase) {
2451 * We put one uncovered page between the devices
2452 * in order to definitively prevent any cross-device
2455 dvbase = tsp->sw_end + 1;
2458 sp->sw_first = dvbase;
2459 sp->sw_end = dvbase + nblks;
2460 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2462 swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2463 swap_total += nblks;
2464 swapon_check_swzone();
2466 mtx_unlock(&sw_dev_mtx);
2467 EVENTHANDLER_INVOKE(swapon, sp);
2471 * SYSCALL: swapoff(devname)
2473 * Disable swapping on the given device.
2475 * XXX: Badly designed system call: it should use a device index
2476 * rather than filename as specification. We keep sw_vp around
2477 * only to make this work.
2480 kern_swapoff(struct thread *td, const char *name, enum uio_seg name_seg,
2484 struct nameidata nd;
2488 error = priv_check(td, PRIV_SWAPOFF);
2491 if ((flags & ~(SWAPOFF_FORCE)) != 0)
2494 sx_xlock(&swdev_syscall_lock);
2496 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, name_seg, name);
2503 mtx_lock(&sw_dev_mtx);
2504 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2505 if (sp->sw_vp == vp)
2508 mtx_unlock(&sw_dev_mtx);
2513 error = swapoff_one(sp, td->td_ucred, flags);
2515 sx_xunlock(&swdev_syscall_lock);
2520 #ifdef COMPAT_FREEBSD13
2522 freebsd13_swapoff(struct thread *td, struct freebsd13_swapoff_args *uap)
2524 return (kern_swapoff(td, uap->name, UIO_USERSPACE, 0));
2529 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2531 return (kern_swapoff(td, uap->name, UIO_USERSPACE, uap->flags));
2535 swapoff_one(struct swdevt *sp, struct ucred *cred, u_int flags)
2542 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2544 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2545 error = mac_system_check_swapoff(cred, sp->sw_vp);
2546 (void) VOP_UNLOCK(sp->sw_vp);
2550 nblks = sp->sw_nblks;
2553 * We can turn off this swap device safely only if the
2554 * available virtual memory in the system will fit the amount
2555 * of data we will have to page back in, plus an epsilon so
2556 * the system doesn't become critically low on swap space.
2557 * The vm_free_count() part does not account e.g. for clean
2558 * pages that can be immediately reclaimed without paging, so
2559 * this is a very rough estimation.
2561 * On the other hand, not turning swap off on swapoff_all()
2562 * means that we can lose swap data when filesystems go away,
2563 * which is arguably worse.
2565 if ((flags & SWAPOFF_FORCE) == 0 &&
2566 vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
2570 * Prevent further allocations on this device.
2572 mtx_lock(&sw_dev_mtx);
2573 sp->sw_flags |= SW_CLOSING;
2574 swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2575 swap_total -= nblks;
2576 mtx_unlock(&sw_dev_mtx);
2579 * Page in the contents of the device and close it.
2581 swap_pager_swapoff(sp);
2583 sp->sw_close(curthread, sp);
2584 mtx_lock(&sw_dev_mtx);
2586 TAILQ_REMOVE(&swtailq, sp, sw_list);
2588 if (nswapdev == 0) {
2589 swap_pager_full = 2;
2590 swap_pager_almost_full = 1;
2594 mtx_unlock(&sw_dev_mtx);
2595 blist_destroy(sp->sw_blist);
2596 free(sp, M_VMPGDATA);
2603 struct swdevt *sp, *spt;
2604 const char *devname;
2607 sx_xlock(&swdev_syscall_lock);
2609 mtx_lock(&sw_dev_mtx);
2610 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2611 mtx_unlock(&sw_dev_mtx);
2612 if (vn_isdisk(sp->sw_vp))
2613 devname = devtoname(sp->sw_vp->v_rdev);
2616 error = swapoff_one(sp, thread0.td_ucred, SWAPOFF_FORCE);
2618 printf("Cannot remove swap device %s (error=%d), "
2619 "skipping.\n", devname, error);
2620 } else if (bootverbose) {
2621 printf("Swap device %s removed.\n", devname);
2623 mtx_lock(&sw_dev_mtx);
2625 mtx_unlock(&sw_dev_mtx);
2627 sx_xunlock(&swdev_syscall_lock);
2631 swap_pager_status(int *total, int *used)
2634 *total = swap_total;
2635 *used = swap_total - swap_pager_avail -
2636 nswapdev * howmany(BBSIZE, PAGE_SIZE);
2640 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2643 const char *tmp_devname;
2648 mtx_lock(&sw_dev_mtx);
2649 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2654 xs->xsw_version = XSWDEV_VERSION;
2655 xs->xsw_dev = sp->sw_dev;
2656 xs->xsw_flags = sp->sw_flags;
2657 xs->xsw_nblks = sp->sw_nblks;
2658 xs->xsw_used = sp->sw_used;
2659 if (devname != NULL) {
2660 if (vn_isdisk(sp->sw_vp))
2661 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2663 tmp_devname = "[file]";
2664 strncpy(devname, tmp_devname, len);
2669 mtx_unlock(&sw_dev_mtx);
2673 #if defined(COMPAT_FREEBSD11)
2674 #define XSWDEV_VERSION_11 1
2684 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2687 u_int xsw_dev1, xsw_dev2;
2695 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2698 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2699 struct xswdev32 xs32;
2701 #if defined(COMPAT_FREEBSD11)
2702 struct xswdev11 xs11;
2706 if (arg2 != 1) /* name length */
2709 memset(&xs, 0, sizeof(xs));
2710 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2713 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2714 if (req->oldlen == sizeof(xs32)) {
2715 memset(&xs32, 0, sizeof(xs32));
2716 xs32.xsw_version = XSWDEV_VERSION;
2717 xs32.xsw_dev1 = xs.xsw_dev;
2718 xs32.xsw_dev2 = xs.xsw_dev >> 32;
2719 xs32.xsw_flags = xs.xsw_flags;
2720 xs32.xsw_nblks = xs.xsw_nblks;
2721 xs32.xsw_used = xs.xsw_used;
2722 error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2726 #if defined(COMPAT_FREEBSD11)
2727 if (req->oldlen == sizeof(xs11)) {
2728 memset(&xs11, 0, sizeof(xs11));
2729 xs11.xsw_version = XSWDEV_VERSION_11;
2730 xs11.xsw_dev = xs.xsw_dev; /* truncation */
2731 xs11.xsw_flags = xs.xsw_flags;
2732 xs11.xsw_nblks = xs.xsw_nblks;
2733 xs11.xsw_used = xs.xsw_used;
2734 error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2738 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2742 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2743 "Number of swap devices");
2744 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2745 sysctl_vm_swap_info,
2746 "Swap statistics by device");
2749 * Count the approximate swap usage in pages for a vmspace. The
2750 * shadowed or not yet copied on write swap blocks are not accounted.
2751 * The map must be locked.
2754 vmspace_swap_count(struct vmspace *vmspace)
2764 map = &vmspace->vm_map;
2767 VM_MAP_ENTRY_FOREACH(cur, map) {
2768 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2770 object = cur->object.vm_object;
2771 if (object == NULL || (object->flags & OBJ_SWAP) == 0)
2773 VM_OBJECT_RLOCK(object);
2774 if ((object->flags & OBJ_SWAP) == 0)
2776 pi = OFF_TO_IDX(cur->offset);
2777 e = pi + OFF_TO_IDX(cur->end - cur->start);
2778 for (;; pi = sb->p + SWAP_META_PAGES) {
2779 sb = SWAP_PCTRIE_LOOKUP_GE(
2780 &object->un_pager.swp.swp_blks, pi);
2781 if (sb == NULL || sb->p >= e)
2783 for (i = 0; i < SWAP_META_PAGES; i++) {
2784 if (sb->p + i < e &&
2785 sb->d[i] != SWAPBLK_NONE)
2790 VM_OBJECT_RUNLOCK(object);
2798 * Swapping onto disk devices.
2802 static g_orphan_t swapgeom_orphan;
2804 static struct g_class g_swap_class = {
2806 .version = G_VERSION,
2807 .orphan = swapgeom_orphan,
2810 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2813 swapgeom_close_ev(void *arg, int flags)
2815 struct g_consumer *cp;
2818 g_access(cp, -1, -1, 0);
2820 g_destroy_consumer(cp);
2824 * Add a reference to the g_consumer for an inflight transaction.
2827 swapgeom_acquire(struct g_consumer *cp)
2830 mtx_assert(&sw_dev_mtx, MA_OWNED);
2835 * Remove a reference from the g_consumer. Post a close event if all
2836 * references go away, since the function might be called from the
2840 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2843 mtx_assert(&sw_dev_mtx, MA_OWNED);
2845 if (cp->index == 0) {
2846 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2852 swapgeom_done(struct bio *bp2)
2856 struct g_consumer *cp;
2858 bp = bp2->bio_caller2;
2860 bp->b_ioflags = bp2->bio_flags;
2862 bp->b_ioflags |= BIO_ERROR;
2863 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2864 bp->b_error = bp2->bio_error;
2865 bp->b_caller1 = NULL;
2867 sp = bp2->bio_caller1;
2868 mtx_lock(&sw_dev_mtx);
2869 swapgeom_release(cp, sp);
2870 mtx_unlock(&sw_dev_mtx);
2875 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2878 struct g_consumer *cp;
2880 mtx_lock(&sw_dev_mtx);
2883 mtx_unlock(&sw_dev_mtx);
2884 bp->b_error = ENXIO;
2885 bp->b_ioflags |= BIO_ERROR;
2889 swapgeom_acquire(cp);
2890 mtx_unlock(&sw_dev_mtx);
2891 if (bp->b_iocmd == BIO_WRITE)
2894 bio = g_alloc_bio();
2896 mtx_lock(&sw_dev_mtx);
2897 swapgeom_release(cp, sp);
2898 mtx_unlock(&sw_dev_mtx);
2899 bp->b_error = ENOMEM;
2900 bp->b_ioflags |= BIO_ERROR;
2901 printf("swap_pager: cannot allocate bio\n");
2906 bp->b_caller1 = bio;
2907 bio->bio_caller1 = sp;
2908 bio->bio_caller2 = bp;
2909 bio->bio_cmd = bp->b_iocmd;
2910 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2911 bio->bio_length = bp->b_bcount;
2912 bio->bio_done = swapgeom_done;
2913 bio->bio_flags |= BIO_SWAP;
2914 if (!buf_mapped(bp)) {
2915 bio->bio_ma = bp->b_pages;
2916 bio->bio_data = unmapped_buf;
2917 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2918 bio->bio_ma_n = bp->b_npages;
2919 bio->bio_flags |= BIO_UNMAPPED;
2921 bio->bio_data = bp->b_data;
2924 g_io_request(bio, cp);
2929 swapgeom_orphan(struct g_consumer *cp)
2934 mtx_lock(&sw_dev_mtx);
2935 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2936 if (sp->sw_id == cp) {
2937 sp->sw_flags |= SW_CLOSING;
2942 * Drop reference we were created with. Do directly since we're in a
2943 * special context where we don't have to queue the call to
2944 * swapgeom_close_ev().
2947 destroy = ((sp != NULL) && (cp->index == 0));
2950 mtx_unlock(&sw_dev_mtx);
2952 swapgeom_close_ev(cp, 0);
2956 swapgeom_close(struct thread *td, struct swdevt *sw)
2958 struct g_consumer *cp;
2960 mtx_lock(&sw_dev_mtx);
2963 mtx_unlock(&sw_dev_mtx);
2966 * swapgeom_close() may be called from the biodone context,
2967 * where we cannot perform topology changes. Delegate the
2968 * work to the events thread.
2971 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2975 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2977 struct g_provider *pp;
2978 struct g_consumer *cp;
2979 static struct g_geom *gp;
2984 pp = g_dev_getprovider(dev);
2987 mtx_lock(&sw_dev_mtx);
2988 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2990 if (cp != NULL && cp->provider == pp) {
2991 mtx_unlock(&sw_dev_mtx);
2995 mtx_unlock(&sw_dev_mtx);
2997 gp = g_new_geomf(&g_swap_class, "swap");
2998 cp = g_new_consumer(gp);
2999 cp->index = 1; /* Number of active I/Os, plus one for being active. */
3000 cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
3003 * XXX: Every time you think you can improve the margin for
3004 * footshooting, somebody depends on the ability to do so:
3005 * savecore(8) wants to write to our swapdev so we cannot
3006 * set an exclusive count :-(
3008 error = g_access(cp, 1, 1, 0);
3011 g_destroy_consumer(cp);
3014 nblks = pp->mediasize / DEV_BSIZE;
3015 swaponsomething(vp, cp, nblks, swapgeom_strategy,
3016 swapgeom_close, dev2udev(dev),
3017 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
3022 swapongeom(struct vnode *vp)
3026 ASSERT_VOP_ELOCKED(vp, "swapongeom");
3027 if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) {
3031 error = swapongeom_locked(vp->v_rdev, vp);
3032 g_topology_unlock();
3040 * This is used mainly for network filesystem (read: probably only tested
3041 * with NFS) swapfiles.
3046 swapdev_strategy(struct buf *bp, struct swdevt *sp)
3050 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
3054 if (bp->b_iocmd == BIO_WRITE) {
3055 vn_lock(vp2, LK_EXCLUSIVE | LK_RETRY);
3057 bufobj_wdrop(bp->b_bufobj);
3058 bufobj_wref(&vp2->v_bufobj);
3060 vn_lock(vp2, LK_SHARED | LK_RETRY);
3062 if (bp->b_bufobj != &vp2->v_bufobj)
3063 bp->b_bufobj = &vp2->v_bufobj;
3065 bp->b_iooffset = dbtob(bp->b_blkno);
3071 swapdev_close(struct thread *td, struct swdevt *sp)
3076 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3077 VOP_CLOSE(vp, FREAD | FWRITE, td->td_ucred, td);
3082 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
3087 ASSERT_VOP_ELOCKED(vp, "swaponvp");
3090 mtx_lock(&sw_dev_mtx);
3091 TAILQ_FOREACH(sp, &swtailq, sw_list) {
3092 if (sp->sw_id == vp) {
3093 mtx_unlock(&sw_dev_mtx);
3097 mtx_unlock(&sw_dev_mtx);
3100 error = mac_system_check_swapon(td->td_ucred, vp);
3103 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
3107 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
3113 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
3117 new = nsw_wcount_async_max;
3118 error = sysctl_handle_int(oidp, &new, 0, req);
3119 if (error != 0 || req->newptr == NULL)
3122 if (new > nswbuf / 2 || new < 1)
3125 mtx_lock(&swbuf_mtx);
3126 while (nsw_wcount_async_max != new) {
3128 * Adjust difference. If the current async count is too low,
3129 * we will need to sqeeze our update slowly in. Sleep with a
3130 * higher priority than getpbuf() to finish faster.
3132 n = new - nsw_wcount_async_max;
3133 if (nsw_wcount_async + n >= 0) {
3134 nsw_wcount_async += n;
3135 nsw_wcount_async_max += n;
3136 wakeup(&nsw_wcount_async);
3138 nsw_wcount_async_max -= nsw_wcount_async;
3139 nsw_wcount_async = 0;
3140 msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
3144 mtx_unlock(&swbuf_mtx);
3150 swap_pager_update_writecount(vm_object_t object, vm_offset_t start,
3154 VM_OBJECT_WLOCK(object);
3155 KASSERT((object->flags & OBJ_ANON) == 0,
3156 ("Splittable object with writecount"));
3157 object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
3158 VM_OBJECT_WUNLOCK(object);
3162 swap_pager_release_writecount(vm_object_t object, vm_offset_t start,
3166 VM_OBJECT_WLOCK(object);
3167 KASSERT((object->flags & OBJ_ANON) == 0,
3168 ("Splittable object with writecount"));
3169 object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
3170 VM_OBJECT_WUNLOCK(object);