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, "A",
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, "A",
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 static 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");
580 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
582 * Expected to be started from pageout process once, prior to entering
586 swap_pager_swap_init(void)
591 * Number of in-transit swap bp operations. Don't
592 * exhaust the pbufs completely. Make sure we
593 * initialize workable values (0 will work for hysteresis
594 * but it isn't very efficient).
596 * The nsw_cluster_max is constrained by the bp->b_pages[]
597 * array, which has maxphys / PAGE_SIZE entries, and our locally
598 * defined MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
599 * constrained by the swap device interleave stripe size.
601 * Currently we hardwire nsw_wcount_async to 4. This limit is
602 * designed to prevent other I/O from having high latencies due to
603 * our pageout I/O. The value 4 works well for one or two active swap
604 * devices but is probably a little low if you have more. Even so,
605 * a higher value would probably generate only a limited improvement
606 * with three or four active swap devices since the system does not
607 * typically have to pageout at extreme bandwidths. We will want
608 * at least 2 per swap devices, and 4 is a pretty good value if you
609 * have one NFS swap device due to the command/ack latency over NFS.
610 * So it all works out pretty well.
612 nsw_cluster_max = min(maxphys / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
614 nsw_wcount_async = 4;
615 nsw_wcount_async_max = nsw_wcount_async;
616 mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
618 swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
619 swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
622 * Initialize our zone, taking the user's requested size or
623 * estimating the number we need based on the number of pages
626 n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
627 vm_cnt.v_page_count / 2;
628 swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
629 pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0);
630 swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
631 NULL, NULL, _Alignof(struct swblk) - 1, 0);
634 if (uma_zone_reserve_kva(swblk_zone, n))
637 * if the allocation failed, try a zone two thirds the
638 * size of the previous attempt.
644 * Often uma_zone_reserve_kva() cannot reserve exactly the
645 * requested size. Account for the difference when
646 * calculating swap_maxpages.
648 n = uma_zone_get_max(swblk_zone);
651 printf("Swap blk zone entries changed from %lu to %lu.\n",
653 /* absolute maximum we can handle assuming 100% efficiency */
654 swap_maxpages = n * SWAP_META_PAGES;
655 swzone = n * sizeof(struct swblk);
656 if (!uma_zone_reserve_kva(swpctrie_zone, n))
657 printf("Cannot reserve swap pctrie zone, "
658 "reduce kern.maxswzone.\n");
662 swap_pager_init_object(vm_object_t object, void *handle, struct ucred *cred,
663 vm_ooffset_t size, vm_ooffset_t offset)
666 if (!swap_reserve_by_cred(size, cred))
671 object->un_pager.swp.writemappings = 0;
672 object->handle = handle;
675 object->charge = size;
681 swap_pager_alloc_init(objtype_t otype, void *handle, struct ucred *cred,
682 vm_ooffset_t size, vm_ooffset_t offset)
687 * The un_pager.swp.swp_blks trie is initialized by
688 * vm_object_allocate() to ensure the correct order of
689 * visibility to other threads.
691 object = vm_object_allocate(otype, OFF_TO_IDX(offset +
694 if (!swap_pager_init_object(object, handle, cred, size, offset)) {
695 vm_object_deallocate(object);
702 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
703 * its metadata structures.
705 * This routine is called from the mmap and fork code to create a new
708 * This routine must ensure that no live duplicate is created for
709 * the named object request, which is protected against by
710 * holding the sw_alloc_sx lock in case handle != NULL.
713 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
714 vm_ooffset_t offset, struct ucred *cred)
718 if (handle != NULL) {
720 * Reference existing named region or allocate new one. There
721 * should not be a race here against swp_pager_meta_build()
722 * as called from vm_page_remove() in regards to the lookup
725 sx_xlock(&sw_alloc_sx);
726 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
727 if (object == NULL) {
728 object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
730 if (object != NULL) {
731 TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
732 object, pager_object_list);
735 sx_xunlock(&sw_alloc_sx);
737 object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
744 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
746 * The swap backing for the object is destroyed. The code is
747 * designed such that we can reinstantiate it later, but this
748 * routine is typically called only when the entire object is
749 * about to be destroyed.
751 * The object must be locked.
754 swap_pager_dealloc(vm_object_t object)
757 VM_OBJECT_ASSERT_WLOCKED(object);
758 KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
761 * Remove from list right away so lookups will fail if we block for
762 * pageout completion.
764 if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
765 VM_OBJECT_WUNLOCK(object);
766 sx_xlock(&sw_alloc_sx);
767 TAILQ_REMOVE(NOBJLIST(object->handle), object,
769 sx_xunlock(&sw_alloc_sx);
770 VM_OBJECT_WLOCK(object);
773 vm_object_pip_wait(object, "swpdea");
776 * Free all remaining metadata. We only bother to free it from
777 * the swap meta data. We do not attempt to free swapblk's still
778 * associated with vm_page_t's for this object. We do not care
779 * if paging is still in progress on some objects.
781 swp_pager_meta_free_all(object);
782 object->handle = NULL;
783 object->type = OBJT_DEAD;
784 vm_object_clear_flag(object, OBJ_SWAP);
787 /************************************************************************
788 * SWAP PAGER BITMAP ROUTINES *
789 ************************************************************************/
792 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
794 * Allocate swap for up to the requested number of pages. The
795 * starting swap block number (a page index) is returned or
796 * SWAPBLK_NONE if the allocation failed.
798 * Also has the side effect of advising that somebody made a mistake
799 * when they configured swap and didn't configure enough.
801 * This routine may not sleep.
803 * We allocate in round-robin fashion from the configured devices.
806 swp_pager_getswapspace(int *io_npages)
812 KASSERT(*io_npages >= 1,
813 ("%s: npages not positive", __func__));
816 npages = imin(BLIST_MAX_ALLOC, mpages);
817 mtx_lock(&sw_dev_mtx);
819 while (!TAILQ_EMPTY(&swtailq)) {
821 sp = TAILQ_FIRST(&swtailq);
822 if ((sp->sw_flags & SW_CLOSING) == 0)
823 blk = blist_alloc(sp->sw_blist, &npages, mpages);
824 if (blk != SWAPBLK_NONE)
826 sp = TAILQ_NEXT(sp, sw_list);
834 if (blk != SWAPBLK_NONE) {
837 sp->sw_used += npages;
838 swap_pager_avail -= npages;
840 swdevhd = TAILQ_NEXT(sp, sw_list);
842 if (swap_pager_full != 2) {
843 printf("swp_pager_getswapspace(%d): failed\n",
846 swap_pager_almost_full = 1;
850 mtx_unlock(&sw_dev_mtx);
855 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
858 return (blk >= sp->sw_first && blk < sp->sw_end);
862 swp_pager_strategy(struct buf *bp)
866 mtx_lock(&sw_dev_mtx);
867 TAILQ_FOREACH(sp, &swtailq, sw_list) {
868 if (swp_pager_isondev(bp->b_blkno, sp)) {
869 mtx_unlock(&sw_dev_mtx);
870 if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
871 unmapped_buf_allowed) {
872 bp->b_data = unmapped_buf;
875 pmap_qenter((vm_offset_t)bp->b_data,
876 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
878 sp->sw_strategy(bp, sp);
882 panic("Swapdev not found");
886 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
888 * This routine returns the specified swap blocks back to the bitmap.
890 * This routine may not sleep.
893 swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
899 mtx_lock(&sw_dev_mtx);
900 TAILQ_FOREACH(sp, &swtailq, sw_list) {
901 if (swp_pager_isondev(blk, sp)) {
902 sp->sw_used -= npages;
904 * If we are attempting to stop swapping on
905 * this device, we don't want to mark any
906 * blocks free lest they be reused.
908 if ((sp->sw_flags & SW_CLOSING) == 0) {
909 blist_free(sp->sw_blist, blk - sp->sw_first,
911 swap_pager_avail += npages;
914 mtx_unlock(&sw_dev_mtx);
918 panic("Swapdev not found");
922 * SYSCTL_SWAP_FRAGMENTATION() - produce raw swap space stats
925 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
932 error = sysctl_wire_old_buffer(req, 0);
935 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
936 mtx_lock(&sw_dev_mtx);
937 TAILQ_FOREACH(sp, &swtailq, sw_list) {
938 if (vn_isdisk(sp->sw_vp))
939 devname = devtoname(sp->sw_vp->v_rdev);
942 sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
943 blist_stats(sp->sw_blist, &sbuf);
945 mtx_unlock(&sw_dev_mtx);
946 error = sbuf_finish(&sbuf);
952 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
953 * range within an object.
955 * This routine removes swapblk assignments from swap metadata.
957 * The external callers of this routine typically have already destroyed
958 * or renamed vm_page_t's associated with this range in the object so
961 * The object must be locked.
964 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
967 swp_pager_meta_free(object, start, size);
971 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
973 * Assigns swap blocks to the specified range within the object. The
974 * swap blocks are not zeroed. Any previous swap assignment is destroyed.
976 * Returns 0 on success, -1 on failure.
979 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_pindex_t size)
981 daddr_t addr, blk, n_free, s_free;
985 swp_pager_init_freerange(&s_free, &n_free);
986 VM_OBJECT_WLOCK(object);
987 for (i = 0; i < size; i += n) {
988 n = MIN(size - i, INT_MAX);
989 blk = swp_pager_getswapspace(&n);
990 if (blk == SWAPBLK_NONE) {
991 swp_pager_meta_free(object, start, i);
992 VM_OBJECT_WUNLOCK(object);
995 for (j = 0; j < n; ++j) {
996 addr = swp_pager_meta_build(object,
997 start + i + j, blk + j);
998 if (addr != SWAPBLK_NONE)
999 swp_pager_update_freerange(&s_free, &n_free,
1003 swp_pager_freeswapspace(s_free, n_free);
1004 VM_OBJECT_WUNLOCK(object);
1009 swp_pager_xfer_source(vm_object_t srcobject, vm_object_t dstobject,
1010 vm_pindex_t pindex, daddr_t addr)
1014 KASSERT((srcobject->flags & OBJ_SWAP) != 0,
1015 ("%s: Srcobject not swappable", __func__));
1016 if ((dstobject->flags & OBJ_SWAP) != 0 &&
1017 swp_pager_meta_lookup(dstobject, pindex) != SWAPBLK_NONE) {
1018 /* Caller should destroy the source block. */
1023 * Destination has no swapblk and is not resident, transfer source.
1024 * swp_pager_meta_build() can sleep.
1026 VM_OBJECT_WUNLOCK(srcobject);
1027 dstaddr = swp_pager_meta_build(dstobject, pindex, addr);
1028 KASSERT(dstaddr == SWAPBLK_NONE,
1029 ("Unexpected destination swapblk"));
1030 VM_OBJECT_WLOCK(srcobject);
1036 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
1037 * and destroy the source.
1039 * Copy any valid swapblks from the source to the destination. In
1040 * cases where both the source and destination have a valid swapblk,
1041 * we keep the destination's.
1043 * This routine is allowed to sleep. It may sleep allocating metadata
1044 * indirectly through swp_pager_meta_build().
1046 * The source object contains no vm_page_t's (which is just as well)
1048 * The source object is of type OBJT_SWAP.
1050 * The source and destination objects must be locked.
1051 * Both object locks may temporarily be released.
1054 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
1055 vm_pindex_t offset, int destroysource)
1058 VM_OBJECT_ASSERT_WLOCKED(srcobject);
1059 VM_OBJECT_ASSERT_WLOCKED(dstobject);
1062 * If destroysource is set, we remove the source object from the
1063 * swap_pager internal queue now.
1065 if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
1066 srcobject->handle != NULL) {
1067 VM_OBJECT_WUNLOCK(srcobject);
1068 VM_OBJECT_WUNLOCK(dstobject);
1069 sx_xlock(&sw_alloc_sx);
1070 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1072 sx_xunlock(&sw_alloc_sx);
1073 VM_OBJECT_WLOCK(dstobject);
1074 VM_OBJECT_WLOCK(srcobject);
1078 * Transfer source to destination.
1080 swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size);
1083 * Free left over swap blocks in source.
1085 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
1086 * double-remove the object from the swap queues.
1088 if (destroysource) {
1089 swp_pager_meta_free_all(srcobject);
1091 * Reverting the type is not necessary, the caller is going
1092 * to destroy srcobject directly, but I'm doing it here
1093 * for consistency since we've removed the object from its
1096 srcobject->type = OBJT_DEFAULT;
1097 vm_object_clear_flag(srcobject, OBJ_SWAP);
1102 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
1103 * the requested page.
1105 * We determine whether good backing store exists for the requested
1106 * page and return TRUE if it does, FALSE if it doesn't.
1108 * If TRUE, we also try to determine how much valid, contiguous backing
1109 * store exists before and after the requested page.
1112 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1118 VM_OBJECT_ASSERT_LOCKED(object);
1119 KASSERT((object->flags & OBJ_SWAP) != 0,
1120 ("%s: object not swappable", __func__));
1123 * do we have good backing store at the requested index ?
1125 blk0 = swp_pager_meta_lookup(object, pindex);
1126 if (blk0 == SWAPBLK_NONE) {
1135 * find backwards-looking contiguous good backing store
1137 if (before != NULL) {
1138 for (i = 1; i < SWB_NPAGES; i++) {
1141 blk = swp_pager_meta_lookup(object, pindex - i);
1142 if (blk != blk0 - i)
1149 * find forward-looking contiguous good backing store
1151 if (after != NULL) {
1152 for (i = 1; i < SWB_NPAGES; i++) {
1153 blk = swp_pager_meta_lookup(object, pindex + i);
1154 if (blk != blk0 + i)
1163 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1165 * This removes any associated swap backing store, whether valid or
1166 * not, from the page.
1168 * This routine is typically called when a page is made dirty, at
1169 * which point any associated swap can be freed. MADV_FREE also
1170 * calls us in a special-case situation
1172 * NOTE!!! If the page is clean and the swap was valid, the caller
1173 * should make the page dirty before calling this routine. This routine
1174 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1177 * This routine may not sleep.
1179 * The object containing the page may be locked.
1182 swap_pager_unswapped(vm_page_t m)
1188 * Handle enqueing deferred frees first. If we do not have the
1189 * object lock we wait for the page daemon to clear the space.
1192 if (!VM_OBJECT_WOWNED(obj)) {
1193 VM_PAGE_OBJECT_BUSY_ASSERT(m);
1195 * The caller is responsible for synchronization but we
1196 * will harmlessly handle races. This is typically provided
1197 * by only calling unswapped() when a page transitions from
1200 if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1202 vm_page_aflag_set(m, PGA_SWAP_FREE);
1203 counter_u64_add(swap_free_deferred, 1);
1207 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1208 counter_u64_add(swap_free_completed, 1);
1209 vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
1212 * The meta data only exists if the object is OBJT_SWAP
1213 * and even then might not be allocated yet.
1215 KASSERT((m->object->flags & OBJ_SWAP) != 0,
1216 ("Free object not swappable"));
1218 sb = SWAP_PCTRIE_LOOKUP(&m->object->un_pager.swp.swp_blks,
1219 rounddown(m->pindex, SWAP_META_PAGES));
1222 if (sb->d[m->pindex % SWAP_META_PAGES] == SWAPBLK_NONE)
1224 swp_pager_freeswapspace(sb->d[m->pindex % SWAP_META_PAGES], 1);
1225 sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
1226 swp_pager_free_empty_swblk(m->object, sb);
1230 * swap_pager_getpages() - bring pages in from swap
1232 * Attempt to page in the pages in array "ma" of length "count". The
1233 * caller may optionally specify that additional pages preceding and
1234 * succeeding the specified range be paged in. The number of such pages
1235 * is returned in the "rbehind" and "rahead" parameters, and they will
1236 * be in the inactive queue upon return.
1238 * The pages in "ma" must be busied and will remain busied upon return.
1241 swap_pager_getpages_locked(vm_object_t object, vm_page_t *ma, int count,
1242 int *rbehind, int *rahead)
1245 vm_page_t bm, mpred, msucc, p;
1248 int i, maxahead, maxbehind, reqcount;
1250 VM_OBJECT_ASSERT_WLOCKED(object);
1253 KASSERT((object->flags & OBJ_SWAP) != 0,
1254 ("%s: object not swappable", __func__));
1255 if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead)) {
1256 VM_OBJECT_WUNLOCK(object);
1257 return (VM_PAGER_FAIL);
1260 KASSERT(reqcount - 1 <= maxahead,
1261 ("page count %d extends beyond swap block", reqcount));
1264 * Do not transfer any pages other than those that are xbusied
1265 * when running during a split or collapse operation. This
1266 * prevents clustering from re-creating pages which are being
1267 * moved into another object.
1269 if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
1270 maxahead = reqcount - 1;
1275 * Clip the readahead and readbehind ranges to exclude resident pages.
1277 if (rahead != NULL) {
1278 *rahead = imin(*rahead, maxahead - (reqcount - 1));
1279 pindex = ma[reqcount - 1]->pindex;
1280 msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1281 if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1282 *rahead = msucc->pindex - pindex - 1;
1284 if (rbehind != NULL) {
1285 *rbehind = imin(*rbehind, maxbehind);
1286 pindex = ma[0]->pindex;
1287 mpred = TAILQ_PREV(ma[0], pglist, listq);
1288 if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1289 *rbehind = pindex - mpred->pindex - 1;
1293 for (i = 0; i < count; i++)
1294 ma[i]->oflags |= VPO_SWAPINPROG;
1297 * Allocate readahead and readbehind pages.
1299 if (rbehind != NULL) {
1300 for (i = 1; i <= *rbehind; i++) {
1301 p = vm_page_alloc(object, ma[0]->pindex - i,
1305 p->oflags |= VPO_SWAPINPROG;
1310 if (rahead != NULL) {
1311 for (i = 0; i < *rahead; i++) {
1312 p = vm_page_alloc(object,
1313 ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1316 p->oflags |= VPO_SWAPINPROG;
1320 if (rbehind != NULL)
1325 vm_object_pip_add(object, count);
1327 pindex = bm->pindex;
1328 blk = swp_pager_meta_lookup(object, pindex);
1329 KASSERT(blk != SWAPBLK_NONE,
1330 ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1332 VM_OBJECT_WUNLOCK(object);
1333 bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1334 MPASS((bp->b_flags & B_MAXPHYS) != 0);
1335 /* Pages cannot leave the object while busy. */
1336 for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1337 MPASS(p->pindex == bm->pindex + i);
1341 bp->b_flags |= B_PAGING;
1342 bp->b_iocmd = BIO_READ;
1343 bp->b_iodone = swp_pager_async_iodone;
1344 bp->b_rcred = crhold(thread0.td_ucred);
1345 bp->b_wcred = crhold(thread0.td_ucred);
1347 bp->b_bcount = PAGE_SIZE * count;
1348 bp->b_bufsize = PAGE_SIZE * count;
1349 bp->b_npages = count;
1350 bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1351 bp->b_pgafter = rahead != NULL ? *rahead : 0;
1353 VM_CNT_INC(v_swapin);
1354 VM_CNT_ADD(v_swappgsin, count);
1357 * perform the I/O. NOTE!!! bp cannot be considered valid after
1358 * this point because we automatically release it on completion.
1359 * Instead, we look at the one page we are interested in which we
1360 * still hold a lock on even through the I/O completion.
1362 * The other pages in our ma[] array are also released on completion,
1363 * so we cannot assume they are valid anymore either.
1365 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1368 swp_pager_strategy(bp);
1371 * Wait for the pages we want to complete. VPO_SWAPINPROG is always
1372 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1373 * is set in the metadata for each page in the request.
1375 VM_OBJECT_WLOCK(object);
1376 /* This could be implemented more efficiently with aflags */
1377 while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
1378 ma[0]->oflags |= VPO_SWAPSLEEP;
1379 VM_CNT_INC(v_intrans);
1380 if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1381 "swread", hz * 20)) {
1383 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1384 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1387 VM_OBJECT_WUNLOCK(object);
1390 * If we had an unrecoverable read error pages will not be valid.
1392 for (i = 0; i < reqcount; i++)
1393 if (ma[i]->valid != VM_PAGE_BITS_ALL)
1394 return (VM_PAGER_ERROR);
1396 return (VM_PAGER_OK);
1399 * A final note: in a low swap situation, we cannot deallocate swap
1400 * and mark a page dirty here because the caller is likely to mark
1401 * the page clean when we return, causing the page to possibly revert
1402 * to all-zero's later.
1407 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count,
1408 int *rbehind, int *rahead)
1411 VM_OBJECT_WLOCK(object);
1412 return (swap_pager_getpages_locked(object, ma, count, rbehind, rahead));
1416 * swap_pager_getpages_async():
1418 * Right now this is emulation of asynchronous operation on top of
1419 * swap_pager_getpages().
1422 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1423 int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1427 r = swap_pager_getpages(object, ma, count, rbehind, rahead);
1432 case VM_PAGER_ERROR:
1439 panic("unhandled swap_pager_getpages() error %d", r);
1441 (iodone)(arg, ma, count, error);
1447 * swap_pager_putpages:
1449 * Assign swap (if necessary) and initiate I/O on the specified pages.
1451 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1452 * are automatically converted to SWAP objects.
1454 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1455 * vm_page reservation system coupled with properly written VFS devices
1456 * should ensure that no low-memory deadlock occurs. This is an area
1459 * The parent has N vm_object_pip_add() references prior to
1460 * calling us and will remove references for rtvals[] that are
1461 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1464 * The parent has soft-busy'd the pages it passes us and will unbusy
1465 * those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
1466 * We need to unbusy the rest on I/O completion.
1469 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1470 int flags, int *rtvals)
1473 daddr_t addr, blk, n_free, s_free;
1478 KASSERT(count == 0 || ma[0]->object == object,
1479 ("%s: object mismatch %p/%p",
1480 __func__, object, ma[0]->object));
1485 * Turn object into OBJT_SWAP. Force sync if not a pageout process.
1487 if ((object->flags & OBJ_SWAP) == 0) {
1488 addr = swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1489 KASSERT(addr == SWAPBLK_NONE,
1490 ("unexpected object swap block"));
1492 VM_OBJECT_WUNLOCK(object);
1493 async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
1494 swp_pager_init_freerange(&s_free, &n_free);
1499 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1500 * The page is left dirty until the pageout operation completes
1503 for (i = 0; i < count; i += n) {
1504 /* Maximum I/O size is limited by maximum swap block size. */
1505 n = min(count - i, nsw_cluster_max);
1508 mtx_lock(&swbuf_mtx);
1509 while (nsw_wcount_async == 0)
1510 msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1513 mtx_unlock(&swbuf_mtx);
1516 /* Get a block of swap of size up to size n. */
1517 VM_OBJECT_WLOCK(object);
1518 blk = swp_pager_getswapspace(&n);
1519 if (blk == SWAPBLK_NONE) {
1520 VM_OBJECT_WUNLOCK(object);
1521 mtx_lock(&swbuf_mtx);
1522 if (++nsw_wcount_async == 1)
1523 wakeup(&nsw_wcount_async);
1524 mtx_unlock(&swbuf_mtx);
1525 for (j = 0; j < n; ++j)
1526 rtvals[i + j] = VM_PAGER_FAIL;
1529 for (j = 0; j < n; ++j) {
1531 vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1532 addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1534 if (addr != SWAPBLK_NONE)
1535 swp_pager_update_freerange(&s_free, &n_free,
1537 MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1538 mreq->oflags |= VPO_SWAPINPROG;
1540 VM_OBJECT_WUNLOCK(object);
1542 bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1543 MPASS((bp->b_flags & B_MAXPHYS) != 0);
1545 bp->b_flags |= B_ASYNC;
1546 bp->b_flags |= B_PAGING;
1547 bp->b_iocmd = BIO_WRITE;
1549 bp->b_rcred = crhold(thread0.td_ucred);
1550 bp->b_wcred = crhold(thread0.td_ucred);
1551 bp->b_bcount = PAGE_SIZE * n;
1552 bp->b_bufsize = PAGE_SIZE * n;
1554 for (j = 0; j < n; j++)
1555 bp->b_pages[j] = ma[i + j];
1559 * Must set dirty range for NFS to work.
1562 bp->b_dirtyend = bp->b_bcount;
1564 VM_CNT_INC(v_swapout);
1565 VM_CNT_ADD(v_swappgsout, bp->b_npages);
1568 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1569 * can call the async completion routine at the end of a
1570 * synchronous I/O operation. Otherwise, our caller would
1571 * perform duplicate unbusy and wakeup operations on the page
1572 * and object, respectively.
1574 for (j = 0; j < n; j++)
1575 rtvals[i + j] = VM_PAGER_PEND;
1580 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1583 bp->b_iodone = swp_pager_async_iodone;
1585 swp_pager_strategy(bp);
1592 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1594 bp->b_iodone = bdone;
1595 swp_pager_strategy(bp);
1598 * Wait for the sync I/O to complete.
1600 bwait(bp, PVM, "swwrt");
1603 * Now that we are through with the bp, we can call the
1604 * normal async completion, which frees everything up.
1606 swp_pager_async_iodone(bp);
1608 swp_pager_freeswapspace(s_free, n_free);
1609 VM_OBJECT_WLOCK(object);
1613 * swp_pager_async_iodone:
1615 * Completion routine for asynchronous reads and writes from/to swap.
1616 * Also called manually by synchronous code to finish up a bp.
1618 * This routine may not sleep.
1621 swp_pager_async_iodone(struct buf *bp)
1624 vm_object_t object = NULL;
1627 * Report error - unless we ran out of memory, in which case
1628 * we've already logged it in swapgeom_strategy().
1630 if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
1632 "swap_pager: I/O error - %s failed; blkno %ld,"
1633 "size %ld, error %d\n",
1634 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1642 * remove the mapping for kernel virtual
1645 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1647 bp->b_data = bp->b_kvabase;
1650 object = bp->b_pages[0]->object;
1651 VM_OBJECT_WLOCK(object);
1655 * cleanup pages. If an error occurs writing to swap, we are in
1656 * very serious trouble. If it happens to be a disk error, though,
1657 * we may be able to recover by reassigning the swap later on. So
1658 * in this case we remove the m->swapblk assignment for the page
1659 * but do not free it in the rlist. The errornous block(s) are thus
1660 * never reallocated as swap. Redirty the page and continue.
1662 for (i = 0; i < bp->b_npages; ++i) {
1663 vm_page_t m = bp->b_pages[i];
1665 m->oflags &= ~VPO_SWAPINPROG;
1666 if (m->oflags & VPO_SWAPSLEEP) {
1667 m->oflags &= ~VPO_SWAPSLEEP;
1668 wakeup(&object->handle);
1671 /* We always have space after I/O, successful or not. */
1672 vm_page_aflag_set(m, PGA_SWAP_SPACE);
1674 if (bp->b_ioflags & BIO_ERROR) {
1676 * If an error occurs I'd love to throw the swapblk
1677 * away without freeing it back to swapspace, so it
1678 * can never be used again. But I can't from an
1681 if (bp->b_iocmd == BIO_READ) {
1683 * NOTE: for reads, m->dirty will probably
1684 * be overridden by the original caller of
1685 * getpages so don't play cute tricks here.
1690 * If a write error occurs, reactivate page
1691 * so it doesn't clog the inactive list,
1692 * then finish the I/O.
1694 MPASS(m->dirty == VM_PAGE_BITS_ALL);
1696 /* PQ_UNSWAPPABLE? */
1697 vm_page_activate(m);
1700 } else if (bp->b_iocmd == BIO_READ) {
1702 * NOTE: for reads, m->dirty will probably be
1703 * overridden by the original caller of getpages so
1704 * we cannot set them in order to free the underlying
1705 * swap in a low-swap situation. I don't think we'd
1706 * want to do that anyway, but it was an optimization
1707 * that existed in the old swapper for a time before
1708 * it got ripped out due to precisely this problem.
1710 KASSERT(!pmap_page_is_mapped(m),
1711 ("swp_pager_async_iodone: page %p is mapped", m));
1712 KASSERT(m->dirty == 0,
1713 ("swp_pager_async_iodone: page %p is dirty", m));
1716 if (i < bp->b_pgbefore ||
1717 i >= bp->b_npages - bp->b_pgafter)
1718 vm_page_readahead_finish(m);
1721 * For write success, clear the dirty
1722 * status, then finish the I/O ( which decrements the
1723 * busy count and possibly wakes waiter's up ).
1724 * A page is only written to swap after a period of
1725 * inactivity. Therefore, we do not expect it to be
1728 KASSERT(!pmap_page_is_write_mapped(m),
1729 ("swp_pager_async_iodone: page %p is not write"
1732 vm_page_deactivate_noreuse(m);
1738 * adjust pip. NOTE: the original parent may still have its own
1739 * pip refs on the object.
1741 if (object != NULL) {
1742 vm_object_pip_wakeupn(object, bp->b_npages);
1743 VM_OBJECT_WUNLOCK(object);
1747 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1748 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1749 * trigger a KASSERT in relpbuf().
1753 bp->b_bufobj = NULL;
1756 * release the physical I/O buffer
1758 if (bp->b_flags & B_ASYNC) {
1759 mtx_lock(&swbuf_mtx);
1760 if (++nsw_wcount_async == 1)
1761 wakeup(&nsw_wcount_async);
1762 mtx_unlock(&swbuf_mtx);
1764 uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
1768 swap_pager_nswapdev(void)
1775 swp_pager_force_dirty(vm_page_t m)
1779 swap_pager_unswapped(m);
1784 swap_pager_swapped_pages(vm_object_t object)
1791 VM_OBJECT_ASSERT_LOCKED(object);
1792 if ((object->flags & OBJ_SWAP) == 0)
1795 for (res = 0, pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1796 &object->un_pager.swp.swp_blks, pi)) != NULL;
1797 pi = sb->p + SWAP_META_PAGES) {
1798 for (i = 0; i < SWAP_META_PAGES; i++) {
1799 if (sb->d[i] != SWAPBLK_NONE)
1807 * swap_pager_swapoff_object:
1809 * Page in all of the pages that have been paged out for an object
1813 swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
1819 int i, nv, rahead, rv;
1821 KASSERT((object->flags & OBJ_SWAP) != 0,
1822 ("%s: Object not swappable", __func__));
1824 for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1825 &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1826 if ((object->flags & OBJ_DEAD) != 0) {
1828 * Make sure that pending writes finish before
1831 vm_object_pip_wait(object, "swpoff");
1832 swp_pager_meta_free_all(object);
1835 for (i = 0; i < SWAP_META_PAGES; i++) {
1837 * Count the number of contiguous valid blocks.
1839 for (nv = 0; nv < SWAP_META_PAGES - i; nv++) {
1840 blk = sb->d[i + nv];
1841 if (!swp_pager_isondev(blk, sp) ||
1842 blk == SWAPBLK_NONE)
1849 * Look for a page corresponding to the first
1850 * valid block and ensure that any pending paging
1851 * operations on it are complete. If the page is valid,
1852 * mark it dirty and free the swap block. Try to batch
1853 * this operation since it may cause sp to be freed,
1854 * meaning that we must restart the scan. Avoid busying
1855 * valid pages since we may block forever on kernel
1858 m = vm_page_lookup(object, sb->p + i);
1860 m = vm_page_alloc(object, sb->p + i,
1861 VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
1865 if ((m->oflags & VPO_SWAPINPROG) != 0) {
1866 m->oflags |= VPO_SWAPSLEEP;
1867 VM_OBJECT_SLEEP(object, &object->handle,
1871 if (vm_page_all_valid(m)) {
1873 swp_pager_force_dirty(m);
1874 } while (--nv > 0 &&
1875 (m = vm_page_next(m)) != NULL &&
1876 vm_page_all_valid(m) &&
1877 (m->oflags & VPO_SWAPINPROG) == 0);
1880 if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL))
1884 vm_object_pip_add(object, 1);
1885 rahead = SWAP_META_PAGES;
1886 rv = swap_pager_getpages_locked(object, &m, 1, NULL,
1888 if (rv != VM_PAGER_OK)
1889 panic("%s: read from swap failed: %d",
1891 vm_object_pip_wakeupn(object, 1);
1892 VM_OBJECT_WLOCK(object);
1896 * The object lock was dropped so we must restart the
1897 * scan of this swap block. Pages paged in during this
1898 * iteration will be marked dirty in a future iteration.
1902 if (i == SWAP_META_PAGES)
1903 pi = sb->p + SWAP_META_PAGES;
1908 * swap_pager_swapoff:
1910 * Page in all of the pages that have been paged out to the
1911 * given device. The corresponding blocks in the bitmap must be
1912 * marked as allocated and the device must be flagged SW_CLOSING.
1913 * There may be no processes swapped out to the device.
1915 * This routine may block.
1918 swap_pager_swapoff(struct swdevt *sp)
1923 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1927 mtx_lock(&vm_object_list_mtx);
1928 TAILQ_FOREACH(object, &vm_object_list, object_list) {
1929 if ((object->flags & OBJ_SWAP) == 0)
1931 mtx_unlock(&vm_object_list_mtx);
1932 /* Depends on type-stability. */
1933 VM_OBJECT_WLOCK(object);
1936 * Dead objects are eventually terminated on their own.
1938 if ((object->flags & OBJ_DEAD) != 0)
1942 * Sync with fences placed after pctrie
1943 * initialization. We must not access pctrie below
1944 * unless we checked that our object is swap and not
1947 atomic_thread_fence_acq();
1948 if ((object->flags & OBJ_SWAP) == 0)
1951 swap_pager_swapoff_object(sp, object);
1953 VM_OBJECT_WUNLOCK(object);
1954 mtx_lock(&vm_object_list_mtx);
1956 mtx_unlock(&vm_object_list_mtx);
1960 * Objects may be locked or paging to the device being
1961 * removed, so we will miss their pages and need to
1962 * make another pass. We have marked this device as
1963 * SW_CLOSING, so the activity should finish soon.
1966 if (retries > 100) {
1967 panic("swapoff: failed to locate %d swap blocks",
1970 pause("swpoff", hz / 20);
1973 EVENTHANDLER_INVOKE(swapoff, sp);
1976 /************************************************************************
1978 ************************************************************************
1980 * These routines manipulate the swap metadata stored in the
1983 * Swap metadata is implemented with a global hash and not directly
1984 * linked into the object. Instead the object simply contains
1985 * appropriate tracking counters.
1989 * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
1992 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
1996 MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
1997 for (i = start; i < limit; i++) {
1998 if (sb->d[i] != SWAPBLK_NONE)
2005 * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
2007 * Nothing is done if the block is still in use.
2010 swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
2013 if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
2014 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2015 uma_zfree(swblk_zone, sb);
2020 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
2022 * We first convert the object to a swap object if it is a default
2025 * The specified swapblk is added to the object's swap metadata. If
2026 * the swapblk is not valid, it is freed instead. Any previously
2027 * assigned swapblk is returned.
2030 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
2032 static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
2033 struct swblk *sb, *sb1;
2034 vm_pindex_t modpi, rdpi;
2035 daddr_t prev_swapblk;
2038 VM_OBJECT_ASSERT_WLOCKED(object);
2041 * Convert default object to swap object if necessary
2043 if ((object->flags & OBJ_SWAP) == 0) {
2044 pctrie_init(&object->un_pager.swp.swp_blks);
2047 * Ensure that swap_pager_swapoff()'s iteration over
2048 * object_list does not see a garbage pctrie.
2050 atomic_thread_fence_rel();
2052 object->type = OBJT_SWAP;
2053 vm_object_set_flag(object, OBJ_SWAP);
2054 object->un_pager.swp.writemappings = 0;
2055 KASSERT((object->flags & OBJ_ANON) != 0 ||
2056 object->handle == NULL,
2057 ("default pager %p with handle %p",
2058 object, object->handle));
2061 rdpi = rounddown(pindex, SWAP_META_PAGES);
2062 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
2064 if (swapblk == SWAPBLK_NONE)
2065 return (SWAPBLK_NONE);
2067 sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
2068 pageproc ? M_USE_RESERVE : 0));
2071 for (i = 0; i < SWAP_META_PAGES; i++)
2072 sb->d[i] = SWAPBLK_NONE;
2073 if (atomic_cmpset_int(&swblk_zone_exhausted,
2075 printf("swblk zone ok\n");
2078 VM_OBJECT_WUNLOCK(object);
2079 if (uma_zone_exhausted(swblk_zone)) {
2080 if (atomic_cmpset_int(&swblk_zone_exhausted,
2082 printf("swap blk zone exhausted, "
2083 "increase kern.maxswzone\n");
2084 vm_pageout_oom(VM_OOM_SWAPZ);
2085 pause("swzonxb", 10);
2087 uma_zwait(swblk_zone);
2088 VM_OBJECT_WLOCK(object);
2089 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2093 * Somebody swapped out a nearby page,
2094 * allocating swblk at the rdpi index,
2095 * while we dropped the object lock.
2100 error = SWAP_PCTRIE_INSERT(
2101 &object->un_pager.swp.swp_blks, sb);
2103 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2105 printf("swpctrie zone ok\n");
2108 VM_OBJECT_WUNLOCK(object);
2109 if (uma_zone_exhausted(swpctrie_zone)) {
2110 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2112 printf("swap pctrie zone exhausted, "
2113 "increase kern.maxswzone\n");
2114 vm_pageout_oom(VM_OOM_SWAPZ);
2115 pause("swzonxp", 10);
2117 uma_zwait(swpctrie_zone);
2118 VM_OBJECT_WLOCK(object);
2119 sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2122 uma_zfree(swblk_zone, sb);
2129 MPASS(sb->p == rdpi);
2131 modpi = pindex % SWAP_META_PAGES;
2132 /* Return prior contents of metadata. */
2133 prev_swapblk = sb->d[modpi];
2134 /* Enter block into metadata. */
2135 sb->d[modpi] = swapblk;
2138 * Free the swblk if we end up with the empty page run.
2140 if (swapblk == SWAPBLK_NONE)
2141 swp_pager_free_empty_swblk(object, sb);
2142 return (prev_swapblk);
2146 * SWP_PAGER_META_TRANSFER() - free a range of blocks in the srcobject's swap
2147 * metadata, or transfer it into dstobject.
2149 * This routine will free swap metadata structures as they are cleaned
2153 swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
2154 vm_pindex_t pindex, vm_pindex_t count)
2157 daddr_t n_free, s_free;
2158 vm_pindex_t offset, last;
2159 int i, limit, start;
2161 VM_OBJECT_ASSERT_WLOCKED(srcobject);
2162 if ((srcobject->flags & OBJ_SWAP) == 0 || count == 0)
2165 swp_pager_init_freerange(&s_free, &n_free);
2167 last = pindex + count;
2169 sb = SWAP_PCTRIE_LOOKUP_GE(&srcobject->un_pager.swp.swp_blks,
2170 rounddown(pindex, SWAP_META_PAGES));
2171 if (sb == NULL || sb->p >= last)
2173 start = pindex > sb->p ? pindex - sb->p : 0;
2174 limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2176 for (i = start; i < limit; i++) {
2177 if (sb->d[i] == SWAPBLK_NONE)
2179 if (dstobject == NULL ||
2180 !swp_pager_xfer_source(srcobject, dstobject,
2181 sb->p + i - offset, sb->d[i])) {
2182 swp_pager_update_freerange(&s_free, &n_free,
2185 sb->d[i] = SWAPBLK_NONE;
2187 pindex = sb->p + SWAP_META_PAGES;
2188 if (swp_pager_swblk_empty(sb, 0, start) &&
2189 swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2190 SWAP_PCTRIE_REMOVE(&srcobject->un_pager.swp.swp_blks,
2192 uma_zfree(swblk_zone, sb);
2195 swp_pager_freeswapspace(s_free, n_free);
2199 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
2201 * The requested range of blocks is freed, with any associated swap
2202 * returned to the swap bitmap.
2204 * This routine will free swap metadata structures as they are cleaned
2205 * out. This routine does *NOT* operate on swap metadata associated
2206 * with resident pages.
2209 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count)
2211 swp_pager_meta_transfer(object, NULL, pindex, count);
2215 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
2217 * This routine locates and destroys all swap metadata associated with
2221 swp_pager_meta_free_all(vm_object_t object)
2224 daddr_t n_free, s_free;
2228 VM_OBJECT_ASSERT_WLOCKED(object);
2229 if ((object->flags & OBJ_SWAP) == 0)
2232 swp_pager_init_freerange(&s_free, &n_free);
2233 for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
2234 &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
2235 pindex = sb->p + SWAP_META_PAGES;
2236 for (i = 0; i < SWAP_META_PAGES; i++) {
2237 if (sb->d[i] == SWAPBLK_NONE)
2239 swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
2241 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2242 uma_zfree(swblk_zone, sb);
2244 swp_pager_freeswapspace(s_free, n_free);
2248 * SWP_PAGER_METACTL() - misc control of swap meta data.
2250 * This routine is capable of looking up, or removing swapblk
2251 * assignments in the swap meta data. It returns the swapblk being
2252 * looked-up, popped, or SWAPBLK_NONE if the block was invalid.
2254 * When acting on a busy resident page and paging is in progress, we
2255 * have to wait until paging is complete but otherwise can act on the
2259 swp_pager_meta_lookup(vm_object_t object, vm_pindex_t pindex)
2263 VM_OBJECT_ASSERT_LOCKED(object);
2266 * The meta data only exists if the object is OBJT_SWAP
2267 * and even then might not be allocated yet.
2269 KASSERT((object->flags & OBJ_SWAP) != 0,
2270 ("Lookup object not swappable"));
2272 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2273 rounddown(pindex, SWAP_META_PAGES));
2275 return (SWAPBLK_NONE);
2276 return (sb->d[pindex % SWAP_META_PAGES]);
2280 * Returns the least page index which is greater than or equal to the
2281 * parameter pindex and for which there is a swap block allocated.
2282 * Returns object's size if the object's type is not swap or if there
2283 * are no allocated swap blocks for the object after the requested
2287 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2292 VM_OBJECT_ASSERT_LOCKED(object);
2293 if ((object->flags & OBJ_SWAP) == 0)
2294 return (object->size);
2296 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2297 rounddown(pindex, SWAP_META_PAGES));
2299 return (object->size);
2300 if (sb->p < pindex) {
2301 for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2302 if (sb->d[i] != SWAPBLK_NONE)
2305 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2306 roundup(pindex, SWAP_META_PAGES));
2308 return (object->size);
2310 for (i = 0; i < SWAP_META_PAGES; i++) {
2311 if (sb->d[i] != SWAPBLK_NONE)
2316 * We get here if a swblk is present in the trie but it
2317 * doesn't map any blocks.
2320 return (object->size);
2324 * System call swapon(name) enables swapping on device name,
2325 * which must be in the swdevsw. Return EBUSY
2326 * if already swapping on this device.
2328 #ifndef _SYS_SYSPROTO_H_
2329 struct swapon_args {
2335 sys_swapon(struct thread *td, struct swapon_args *uap)
2339 struct nameidata nd;
2342 error = priv_check(td, PRIV_SWAPON);
2346 sx_xlock(&swdev_syscall_lock);
2349 * Swap metadata may not fit in the KVM if we have physical
2352 if (swblk_zone == NULL) {
2357 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | LOCKLEAF | AUDITVNODE1,
2358 UIO_USERSPACE, uap->name, td);
2363 NDFREE(&nd, NDF_ONLY_PNBUF);
2366 if (vn_isdisk_error(vp, &error)) {
2367 error = swapongeom(vp);
2368 } else if (vp->v_type == VREG &&
2369 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2370 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2372 * Allow direct swapping to NFS regular files in the same
2373 * way that nfs_mountroot() sets up diskless swapping.
2375 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2383 sx_xunlock(&swdev_syscall_lock);
2388 * Check that the total amount of swap currently configured does not
2389 * exceed half the theoretical maximum. If it does, print a warning
2393 swapon_check_swzone(void)
2396 /* recommend using no more than half that amount */
2397 if (swap_total > swap_maxpages / 2) {
2398 printf("warning: total configured swap (%lu pages) "
2399 "exceeds maximum recommended amount (%lu pages).\n",
2400 swap_total, swap_maxpages / 2);
2401 printf("warning: increase kern.maxswzone "
2402 "or reduce amount of swap.\n");
2407 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2408 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2410 struct swdevt *sp, *tsp;
2414 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2415 * First chop nblks off to page-align it, then convert.
2417 * sw->sw_nblks is in page-sized chunks now too.
2419 nblks &= ~(ctodb(1) - 1);
2420 nblks = dbtoc(nblks);
2422 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2423 sp->sw_blist = blist_create(nblks, M_WAITOK);
2427 sp->sw_nblks = nblks;
2429 sp->sw_strategy = strategy;
2430 sp->sw_close = close;
2431 sp->sw_flags = flags;
2434 * Do not free the first blocks in order to avoid overwriting
2435 * any bsd label at the front of the partition
2437 blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2438 nblks - howmany(BBSIZE, PAGE_SIZE));
2441 mtx_lock(&sw_dev_mtx);
2442 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2443 if (tsp->sw_end >= dvbase) {
2445 * We put one uncovered page between the devices
2446 * in order to definitively prevent any cross-device
2449 dvbase = tsp->sw_end + 1;
2452 sp->sw_first = dvbase;
2453 sp->sw_end = dvbase + nblks;
2454 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2456 swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2457 swap_total += nblks;
2458 swapon_check_swzone();
2460 mtx_unlock(&sw_dev_mtx);
2461 EVENTHANDLER_INVOKE(swapon, sp);
2465 * SYSCALL: swapoff(devname)
2467 * Disable swapping on the given device.
2469 * XXX: Badly designed system call: it should use a device index
2470 * rather than filename as specification. We keep sw_vp around
2471 * only to make this work.
2474 kern_swapoff(struct thread *td, const char *name, enum uio_seg name_seg,
2478 struct nameidata nd;
2482 error = priv_check(td, PRIV_SWAPOFF);
2485 if ((flags & ~(SWAPOFF_FORCE)) != 0)
2488 sx_xlock(&swdev_syscall_lock);
2490 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, name_seg, name, td);
2494 NDFREE(&nd, NDF_ONLY_PNBUF);
2497 mtx_lock(&sw_dev_mtx);
2498 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2499 if (sp->sw_vp == vp)
2502 mtx_unlock(&sw_dev_mtx);
2507 error = swapoff_one(sp, td->td_ucred, flags);
2509 sx_xunlock(&swdev_syscall_lock);
2514 freebsd13_swapoff(struct thread *td, struct freebsd13_swapoff_args *uap)
2516 return (kern_swapoff(td, uap->name, UIO_USERSPACE, 0));
2520 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2522 return (kern_swapoff(td, uap->name, UIO_USERSPACE, uap->flags));
2526 swapoff_one(struct swdevt *sp, struct ucred *cred, u_int flags)
2533 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2535 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2536 error = mac_system_check_swapoff(cred, sp->sw_vp);
2537 (void) VOP_UNLOCK(sp->sw_vp);
2541 nblks = sp->sw_nblks;
2544 * We can turn off this swap device safely only if the
2545 * available virtual memory in the system will fit the amount
2546 * of data we will have to page back in, plus an epsilon so
2547 * the system doesn't become critically low on swap space.
2548 * The vm_free_count() part does not account e.g. for clean
2549 * pages that can be immediately reclaimed without paging, so
2550 * this is a very rough estimation.
2552 * On the other hand, not turning swap off on swapoff_all()
2553 * means that we can lose swap data when filesystems go away,
2554 * which is arguably worse.
2556 if ((flags & SWAPOFF_FORCE) == 0 &&
2557 vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
2561 * Prevent further allocations on this device.
2563 mtx_lock(&sw_dev_mtx);
2564 sp->sw_flags |= SW_CLOSING;
2565 swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2566 swap_total -= nblks;
2567 mtx_unlock(&sw_dev_mtx);
2570 * Page in the contents of the device and close it.
2572 swap_pager_swapoff(sp);
2574 sp->sw_close(curthread, sp);
2575 mtx_lock(&sw_dev_mtx);
2577 TAILQ_REMOVE(&swtailq, sp, sw_list);
2579 if (nswapdev == 0) {
2580 swap_pager_full = 2;
2581 swap_pager_almost_full = 1;
2585 mtx_unlock(&sw_dev_mtx);
2586 blist_destroy(sp->sw_blist);
2587 free(sp, M_VMPGDATA);
2594 struct swdevt *sp, *spt;
2595 const char *devname;
2598 sx_xlock(&swdev_syscall_lock);
2600 mtx_lock(&sw_dev_mtx);
2601 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2602 mtx_unlock(&sw_dev_mtx);
2603 if (vn_isdisk(sp->sw_vp))
2604 devname = devtoname(sp->sw_vp->v_rdev);
2607 error = swapoff_one(sp, thread0.td_ucred, SWAPOFF_FORCE);
2609 printf("Cannot remove swap device %s (error=%d), "
2610 "skipping.\n", devname, error);
2611 } else if (bootverbose) {
2612 printf("Swap device %s removed.\n", devname);
2614 mtx_lock(&sw_dev_mtx);
2616 mtx_unlock(&sw_dev_mtx);
2618 sx_xunlock(&swdev_syscall_lock);
2622 swap_pager_status(int *total, int *used)
2625 *total = swap_total;
2626 *used = swap_total - swap_pager_avail -
2627 nswapdev * howmany(BBSIZE, PAGE_SIZE);
2631 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2634 const char *tmp_devname;
2639 mtx_lock(&sw_dev_mtx);
2640 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2645 xs->xsw_version = XSWDEV_VERSION;
2646 xs->xsw_dev = sp->sw_dev;
2647 xs->xsw_flags = sp->sw_flags;
2648 xs->xsw_nblks = sp->sw_nblks;
2649 xs->xsw_used = sp->sw_used;
2650 if (devname != NULL) {
2651 if (vn_isdisk(sp->sw_vp))
2652 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2654 tmp_devname = "[file]";
2655 strncpy(devname, tmp_devname, len);
2660 mtx_unlock(&sw_dev_mtx);
2664 #if defined(COMPAT_FREEBSD11)
2665 #define XSWDEV_VERSION_11 1
2675 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2678 u_int xsw_dev1, xsw_dev2;
2686 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2689 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2690 struct xswdev32 xs32;
2692 #if defined(COMPAT_FREEBSD11)
2693 struct xswdev11 xs11;
2697 if (arg2 != 1) /* name length */
2700 memset(&xs, 0, sizeof(xs));
2701 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2704 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2705 if (req->oldlen == sizeof(xs32)) {
2706 memset(&xs32, 0, sizeof(xs32));
2707 xs32.xsw_version = XSWDEV_VERSION;
2708 xs32.xsw_dev1 = xs.xsw_dev;
2709 xs32.xsw_dev2 = xs.xsw_dev >> 32;
2710 xs32.xsw_flags = xs.xsw_flags;
2711 xs32.xsw_nblks = xs.xsw_nblks;
2712 xs32.xsw_used = xs.xsw_used;
2713 error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2717 #if defined(COMPAT_FREEBSD11)
2718 if (req->oldlen == sizeof(xs11)) {
2719 memset(&xs11, 0, sizeof(xs11));
2720 xs11.xsw_version = XSWDEV_VERSION_11;
2721 xs11.xsw_dev = xs.xsw_dev; /* truncation */
2722 xs11.xsw_flags = xs.xsw_flags;
2723 xs11.xsw_nblks = xs.xsw_nblks;
2724 xs11.xsw_used = xs.xsw_used;
2725 error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2729 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2733 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2734 "Number of swap devices");
2735 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2736 sysctl_vm_swap_info,
2737 "Swap statistics by device");
2740 * Count the approximate swap usage in pages for a vmspace. The
2741 * shadowed or not yet copied on write swap blocks are not accounted.
2742 * The map must be locked.
2745 vmspace_swap_count(struct vmspace *vmspace)
2755 map = &vmspace->vm_map;
2758 VM_MAP_ENTRY_FOREACH(cur, map) {
2759 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2761 object = cur->object.vm_object;
2762 if (object == NULL || (object->flags & OBJ_SWAP) == 0)
2764 VM_OBJECT_RLOCK(object);
2765 if ((object->flags & OBJ_SWAP) == 0)
2767 pi = OFF_TO_IDX(cur->offset);
2768 e = pi + OFF_TO_IDX(cur->end - cur->start);
2769 for (;; pi = sb->p + SWAP_META_PAGES) {
2770 sb = SWAP_PCTRIE_LOOKUP_GE(
2771 &object->un_pager.swp.swp_blks, pi);
2772 if (sb == NULL || sb->p >= e)
2774 for (i = 0; i < SWAP_META_PAGES; i++) {
2775 if (sb->p + i < e &&
2776 sb->d[i] != SWAPBLK_NONE)
2781 VM_OBJECT_RUNLOCK(object);
2789 * Swapping onto disk devices.
2793 static g_orphan_t swapgeom_orphan;
2795 static struct g_class g_swap_class = {
2797 .version = G_VERSION,
2798 .orphan = swapgeom_orphan,
2801 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2804 swapgeom_close_ev(void *arg, int flags)
2806 struct g_consumer *cp;
2809 g_access(cp, -1, -1, 0);
2811 g_destroy_consumer(cp);
2815 * Add a reference to the g_consumer for an inflight transaction.
2818 swapgeom_acquire(struct g_consumer *cp)
2821 mtx_assert(&sw_dev_mtx, MA_OWNED);
2826 * Remove a reference from the g_consumer. Post a close event if all
2827 * references go away, since the function might be called from the
2831 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2834 mtx_assert(&sw_dev_mtx, MA_OWNED);
2836 if (cp->index == 0) {
2837 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2843 swapgeom_done(struct bio *bp2)
2847 struct g_consumer *cp;
2849 bp = bp2->bio_caller2;
2851 bp->b_ioflags = bp2->bio_flags;
2853 bp->b_ioflags |= BIO_ERROR;
2854 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2855 bp->b_error = bp2->bio_error;
2856 bp->b_caller1 = NULL;
2858 sp = bp2->bio_caller1;
2859 mtx_lock(&sw_dev_mtx);
2860 swapgeom_release(cp, sp);
2861 mtx_unlock(&sw_dev_mtx);
2866 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2869 struct g_consumer *cp;
2871 mtx_lock(&sw_dev_mtx);
2874 mtx_unlock(&sw_dev_mtx);
2875 bp->b_error = ENXIO;
2876 bp->b_ioflags |= BIO_ERROR;
2880 swapgeom_acquire(cp);
2881 mtx_unlock(&sw_dev_mtx);
2882 if (bp->b_iocmd == BIO_WRITE)
2885 bio = g_alloc_bio();
2887 mtx_lock(&sw_dev_mtx);
2888 swapgeom_release(cp, sp);
2889 mtx_unlock(&sw_dev_mtx);
2890 bp->b_error = ENOMEM;
2891 bp->b_ioflags |= BIO_ERROR;
2892 printf("swap_pager: cannot allocate bio\n");
2897 bp->b_caller1 = bio;
2898 bio->bio_caller1 = sp;
2899 bio->bio_caller2 = bp;
2900 bio->bio_cmd = bp->b_iocmd;
2901 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2902 bio->bio_length = bp->b_bcount;
2903 bio->bio_done = swapgeom_done;
2904 if (!buf_mapped(bp)) {
2905 bio->bio_ma = bp->b_pages;
2906 bio->bio_data = unmapped_buf;
2907 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2908 bio->bio_ma_n = bp->b_npages;
2909 bio->bio_flags |= BIO_UNMAPPED;
2911 bio->bio_data = bp->b_data;
2914 g_io_request(bio, cp);
2919 swapgeom_orphan(struct g_consumer *cp)
2924 mtx_lock(&sw_dev_mtx);
2925 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2926 if (sp->sw_id == cp) {
2927 sp->sw_flags |= SW_CLOSING;
2932 * Drop reference we were created with. Do directly since we're in a
2933 * special context where we don't have to queue the call to
2934 * swapgeom_close_ev().
2937 destroy = ((sp != NULL) && (cp->index == 0));
2940 mtx_unlock(&sw_dev_mtx);
2942 swapgeom_close_ev(cp, 0);
2946 swapgeom_close(struct thread *td, struct swdevt *sw)
2948 struct g_consumer *cp;
2950 mtx_lock(&sw_dev_mtx);
2953 mtx_unlock(&sw_dev_mtx);
2956 * swapgeom_close() may be called from the biodone context,
2957 * where we cannot perform topology changes. Delegate the
2958 * work to the events thread.
2961 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2965 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2967 struct g_provider *pp;
2968 struct g_consumer *cp;
2969 static struct g_geom *gp;
2974 pp = g_dev_getprovider(dev);
2977 mtx_lock(&sw_dev_mtx);
2978 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2980 if (cp != NULL && cp->provider == pp) {
2981 mtx_unlock(&sw_dev_mtx);
2985 mtx_unlock(&sw_dev_mtx);
2987 gp = g_new_geomf(&g_swap_class, "swap");
2988 cp = g_new_consumer(gp);
2989 cp->index = 1; /* Number of active I/Os, plus one for being active. */
2990 cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2993 * XXX: Every time you think you can improve the margin for
2994 * footshooting, somebody depends on the ability to do so:
2995 * savecore(8) wants to write to our swapdev so we cannot
2996 * set an exclusive count :-(
2998 error = g_access(cp, 1, 1, 0);
3001 g_destroy_consumer(cp);
3004 nblks = pp->mediasize / DEV_BSIZE;
3005 swaponsomething(vp, cp, nblks, swapgeom_strategy,
3006 swapgeom_close, dev2udev(dev),
3007 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
3012 swapongeom(struct vnode *vp)
3016 ASSERT_VOP_ELOCKED(vp, "swapongeom");
3017 if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) {
3021 error = swapongeom_locked(vp->v_rdev, vp);
3022 g_topology_unlock();
3030 * This is used mainly for network filesystem (read: probably only tested
3031 * with NFS) swapfiles.
3036 swapdev_strategy(struct buf *bp, struct swdevt *sp)
3040 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
3044 if (bp->b_iocmd == BIO_WRITE) {
3045 vn_lock(vp2, LK_EXCLUSIVE | LK_RETRY);
3047 bufobj_wdrop(bp->b_bufobj);
3048 bufobj_wref(&vp2->v_bufobj);
3050 vn_lock(vp2, LK_SHARED | LK_RETRY);
3052 if (bp->b_bufobj != &vp2->v_bufobj)
3053 bp->b_bufobj = &vp2->v_bufobj;
3055 bp->b_iooffset = dbtob(bp->b_blkno);
3061 swapdev_close(struct thread *td, struct swdevt *sp)
3066 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3067 VOP_CLOSE(vp, FREAD | FWRITE, td->td_ucred, td);
3072 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
3077 ASSERT_VOP_ELOCKED(vp, "swaponvp");
3080 mtx_lock(&sw_dev_mtx);
3081 TAILQ_FOREACH(sp, &swtailq, sw_list) {
3082 if (sp->sw_id == vp) {
3083 mtx_unlock(&sw_dev_mtx);
3087 mtx_unlock(&sw_dev_mtx);
3090 error = mac_system_check_swapon(td->td_ucred, vp);
3093 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
3097 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
3103 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
3107 new = nsw_wcount_async_max;
3108 error = sysctl_handle_int(oidp, &new, 0, req);
3109 if (error != 0 || req->newptr == NULL)
3112 if (new > nswbuf / 2 || new < 1)
3115 mtx_lock(&swbuf_mtx);
3116 while (nsw_wcount_async_max != new) {
3118 * Adjust difference. If the current async count is too low,
3119 * we will need to sqeeze our update slowly in. Sleep with a
3120 * higher priority than getpbuf() to finish faster.
3122 n = new - nsw_wcount_async_max;
3123 if (nsw_wcount_async + n >= 0) {
3124 nsw_wcount_async += n;
3125 nsw_wcount_async_max += n;
3126 wakeup(&nsw_wcount_async);
3128 nsw_wcount_async_max -= nsw_wcount_async;
3129 nsw_wcount_async = 0;
3130 msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
3134 mtx_unlock(&swbuf_mtx);
3140 swap_pager_update_writecount(vm_object_t object, vm_offset_t start,
3144 VM_OBJECT_WLOCK(object);
3145 KASSERT((object->flags & OBJ_ANON) == 0,
3146 ("Splittable object with writecount"));
3147 object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
3148 VM_OBJECT_WUNLOCK(object);
3152 swap_pager_release_writecount(vm_object_t object, vm_offset_t start,
3156 VM_OBJECT_WLOCK(object);
3157 KASSERT((object->flags & OBJ_ANON) == 0,
3158 ("Splittable object with writecount"));
3159 object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
3160 VM_OBJECT_WUNLOCK(object);