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/user.h>
104 #include <sys/vmmeter.h>
105 #include <sys/vnode.h>
107 #include <security/mac/mac_framework.h>
111 #include <vm/vm_map.h>
112 #include <vm/vm_kern.h>
113 #include <vm/vm_object.h>
114 #include <vm/vm_page.h>
115 #include <vm/vm_pager.h>
116 #include <vm/vm_pageout.h>
117 #include <vm/vm_param.h>
118 #include <vm/swap_pager.h>
119 #include <vm/vm_extern.h>
122 #include <geom/geom.h>
125 * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64.
126 * The 64-page limit is due to the radix code (kern/subr_blist.c).
128 #ifndef MAX_PAGEOUT_CLUSTER
129 #define MAX_PAGEOUT_CLUSTER 32
132 #if !defined(SWB_NPAGES)
133 #define SWB_NPAGES MAX_PAGEOUT_CLUSTER
136 #define SWAP_META_PAGES PCTRIE_COUNT
139 * A swblk structure maps each page index within a
140 * SWAP_META_PAGES-aligned and sized range to the address of an
141 * on-disk swap block (or SWAPBLK_NONE). The collection of these
142 * mappings for an entire vm object is implemented as a pc-trie.
146 daddr_t d[SWAP_META_PAGES];
149 static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data");
150 static struct mtx sw_dev_mtx;
151 static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
152 static struct swdevt *swdevhd; /* Allocate from here next */
153 static int nswapdev; /* Number of swap devices */
154 int swap_pager_avail;
155 static struct sx swdev_syscall_lock; /* serialize swap(on|off) */
157 static __exclusive_cache_line u_long swap_reserved;
158 static u_long swap_total;
159 static int sysctl_page_shift(SYSCTL_HANDLER_ARGS);
161 static SYSCTL_NODE(_vm_stats, OID_AUTO, swap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
164 SYSCTL_PROC(_vm, OID_AUTO, swap_reserved, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
165 &swap_reserved, 0, sysctl_page_shift, "A",
166 "Amount of swap storage needed to back all allocated anonymous memory.");
167 SYSCTL_PROC(_vm, OID_AUTO, swap_total, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
168 &swap_total, 0, sysctl_page_shift, "A",
169 "Total amount of available swap storage.");
171 static int overcommit = 0;
172 SYSCTL_INT(_vm, VM_OVERCOMMIT, overcommit, CTLFLAG_RW, &overcommit, 0,
173 "Configure virtual memory overcommit behavior. See tuning(7) "
175 static unsigned long swzone;
176 SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
177 "Actual size of swap metadata zone");
178 static unsigned long swap_maxpages;
179 SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
180 "Maximum amount of swap supported");
182 static COUNTER_U64_DEFINE_EARLY(swap_free_deferred);
183 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_deferred,
184 CTLFLAG_RD, &swap_free_deferred,
185 "Number of pages that deferred freeing swap space");
187 static COUNTER_U64_DEFINE_EARLY(swap_free_completed);
188 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_completed,
189 CTLFLAG_RD, &swap_free_completed,
190 "Number of deferred frees completed");
192 /* bits from overcommit */
193 #define SWAP_RESERVE_FORCE_ON (1 << 0)
194 #define SWAP_RESERVE_RLIMIT_ON (1 << 1)
195 #define SWAP_RESERVE_ALLOW_NONWIRED (1 << 2)
198 sysctl_page_shift(SYSCTL_HANDLER_ARGS)
201 u_long value = *(u_long *)arg1;
203 newval = ((uint64_t)value) << PAGE_SHIFT;
204 return (sysctl_handle_64(oidp, &newval, 0, req));
208 swap_reserve_by_cred_rlimit(u_long pincr, struct ucred *cred, int oc)
213 uip = cred->cr_ruidinfo;
215 prev = atomic_fetchadd_long(&uip->ui_vmsize, pincr);
216 if ((oc & SWAP_RESERVE_RLIMIT_ON) != 0 &&
217 prev + pincr > lim_cur(curthread, RLIMIT_SWAP) &&
218 priv_check(curthread, PRIV_VM_SWAP_NORLIMIT) != 0) {
219 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pincr);
220 KASSERT(prev >= pincr, ("negative vmsize for uid = %d\n", uip->ui_uid));
227 swap_release_by_cred_rlimit(u_long pdecr, struct ucred *cred)
234 uip = cred->cr_ruidinfo;
237 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pdecr);
238 KASSERT(prev >= pdecr, ("negative vmsize for uid = %d\n", uip->ui_uid));
240 atomic_subtract_long(&uip->ui_vmsize, pdecr);
245 swap_reserve_force_rlimit(u_long pincr, struct ucred *cred)
249 uip = cred->cr_ruidinfo;
250 atomic_add_long(&uip->ui_vmsize, pincr);
254 swap_reserve(vm_ooffset_t incr)
257 return (swap_reserve_by_cred(incr, curthread->td_ucred));
261 swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
263 u_long r, s, prev, pincr;
269 static struct timeval lastfail;
271 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
275 if (RACCT_ENABLED()) {
277 error = racct_add(curproc, RACCT_SWAP, incr);
278 PROC_UNLOCK(curproc);
285 prev = atomic_fetchadd_long(&swap_reserved, pincr);
288 oc = atomic_load_int(&overcommit);
289 if (r > s && (oc & SWAP_RESERVE_ALLOW_NONWIRED) != 0) {
290 s += vm_cnt.v_page_count - vm_cnt.v_free_reserved -
293 if ((oc & SWAP_RESERVE_FORCE_ON) != 0 && r > s &&
294 priv_check(curthread, PRIV_VM_SWAP_NOQUOTA) != 0) {
295 prev = atomic_fetchadd_long(&swap_reserved, -pincr);
296 KASSERT(prev >= pincr, ("swap_reserved < incr on overcommit fail"));
300 if (!swap_reserve_by_cred_rlimit(pincr, cred, oc)) {
301 prev = atomic_fetchadd_long(&swap_reserved, -pincr);
302 KASSERT(prev >= pincr, ("swap_reserved < incr on overcommit fail"));
309 if (ppsratecheck(&lastfail, &curfail, 1)) {
310 printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
311 cred->cr_ruidinfo->ui_uid, curproc->p_pid, incr);
314 if (RACCT_ENABLED()) {
316 racct_sub(curproc, RACCT_SWAP, incr);
317 PROC_UNLOCK(curproc);
325 swap_reserve_force(vm_ooffset_t incr)
329 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
333 if (RACCT_ENABLED()) {
335 racct_add_force(curproc, RACCT_SWAP, incr);
336 PROC_UNLOCK(curproc);
340 atomic_add_long(&swap_reserved, pincr);
341 swap_reserve_force_rlimit(pincr, curthread->td_ucred);
345 swap_release(vm_ooffset_t decr)
350 cred = curproc->p_ucred;
351 swap_release_by_cred(decr, cred);
352 PROC_UNLOCK(curproc);
356 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
363 KASSERT((decr & PAGE_MASK) == 0, ("%s: decr: %ju & PAGE_MASK", __func__,
368 prev = atomic_fetchadd_long(&swap_reserved, -pdecr);
369 KASSERT(prev >= pdecr, ("swap_reserved < decr"));
371 atomic_subtract_long(&swap_reserved, pdecr);
374 swap_release_by_cred_rlimit(pdecr, cred);
377 racct_sub_cred(cred, RACCT_SWAP, decr);
381 static int swap_pager_full = 2; /* swap space exhaustion (task killing) */
382 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
383 static struct mtx swbuf_mtx; /* to sync nsw_wcount_async */
384 static int nsw_wcount_async; /* limit async write buffers */
385 static int nsw_wcount_async_max;/* assigned maximum */
386 int nsw_cluster_max; /* maximum VOP I/O allowed */
388 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
389 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
390 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
391 "Maximum running async swap ops");
392 static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS);
393 SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD |
394 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A",
395 "Swap Fragmentation Info");
397 static struct sx sw_alloc_sx;
400 * "named" and "unnamed" anon region objects. Try to reduce the overhead
401 * of searching a named list by hashing it just a little.
406 #define NOBJLIST(handle) \
407 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
409 static struct pagerlst swap_pager_object_list[NOBJLISTS];
410 static uma_zone_t swwbuf_zone;
411 static uma_zone_t swrbuf_zone;
412 static uma_zone_t swblk_zone;
413 static uma_zone_t swpctrie_zone;
416 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
417 * calls hooked from other parts of the VM system and do not appear here.
418 * (see vm/swap_pager.h).
421 swap_pager_alloc(void *handle, vm_ooffset_t size,
422 vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
423 static void swap_pager_dealloc(vm_object_t object);
424 static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
426 static int swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
427 int *, pgo_getpages_iodone_t, void *);
428 static void swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
430 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
431 static void swap_pager_init(void);
432 static void swap_pager_unswapped(vm_page_t);
433 static void swap_pager_swapoff(struct swdevt *sp);
434 static void swap_pager_update_writecount(vm_object_t object,
435 vm_offset_t start, vm_offset_t end);
436 static void swap_pager_release_writecount(vm_object_t object,
437 vm_offset_t start, vm_offset_t end);
438 static void swap_pager_freespace(vm_object_t object, vm_pindex_t start,
441 const struct pagerops swappagerops = {
442 .pgo_kvme_type = KVME_TYPE_SWAP,
443 .pgo_init = swap_pager_init, /* early system initialization of pager */
444 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */
445 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
446 .pgo_getpages = swap_pager_getpages, /* pagein */
447 .pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
448 .pgo_putpages = swap_pager_putpages, /* pageout */
449 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */
450 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
451 .pgo_update_writecount = swap_pager_update_writecount,
452 .pgo_release_writecount = swap_pager_release_writecount,
453 .pgo_freespace = swap_pager_freespace,
457 * swap_*() routines are externally accessible. swp_*() routines are
460 static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
461 static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
463 SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
464 "Maximum size of a swap block in pages");
466 static void swp_sizecheck(void);
467 static void swp_pager_async_iodone(struct buf *bp);
468 static bool swp_pager_swblk_empty(struct swblk *sb, int start, int limit);
469 static void swp_pager_free_empty_swblk(vm_object_t, struct swblk *sb);
470 static int swapongeom(struct vnode *);
471 static int swaponvp(struct thread *, struct vnode *, u_long);
472 static int swapoff_one(struct swdevt *sp, struct ucred *cred);
475 * Swap bitmap functions
477 static void swp_pager_freeswapspace(daddr_t blk, daddr_t npages);
478 static daddr_t swp_pager_getswapspace(int *npages);
483 static daddr_t swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
484 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t);
485 static void swp_pager_meta_transfer(vm_object_t src, vm_object_t dst,
486 vm_pindex_t pindex, vm_pindex_t count);
487 static void swp_pager_meta_free_all(vm_object_t);
488 static daddr_t swp_pager_meta_lookup(vm_object_t, vm_pindex_t);
491 swp_pager_init_freerange(daddr_t *start, daddr_t *num)
494 *start = SWAPBLK_NONE;
499 swp_pager_update_freerange(daddr_t *start, daddr_t *num, daddr_t addr)
502 if (*start + *num == addr) {
505 swp_pager_freeswapspace(*start, *num);
512 swblk_trie_alloc(struct pctrie *ptree)
515 return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
516 M_USE_RESERVE : 0)));
520 swblk_trie_free(struct pctrie *ptree, void *node)
523 uma_zfree(swpctrie_zone, node);
526 PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
529 * SWP_SIZECHECK() - update swap_pager_full indication
531 * update the swap_pager_almost_full indication and warn when we are
532 * about to run out of swap space, using lowat/hiwat hysteresis.
534 * Clear swap_pager_full ( task killing ) indication when lowat is met.
536 * No restrictions on call
537 * This routine may not block.
543 if (swap_pager_avail < nswap_lowat) {
544 if (swap_pager_almost_full == 0) {
545 printf("swap_pager: out of swap space\n");
546 swap_pager_almost_full = 1;
550 if (swap_pager_avail > nswap_hiwat)
551 swap_pager_almost_full = 0;
556 * SWAP_PAGER_INIT() - initialize the swap pager!
558 * Expected to be started from system init. NOTE: This code is run
559 * before much else so be careful what you depend on. Most of the VM
560 * system has yet to be initialized at this point.
563 swap_pager_init(void)
566 * Initialize object lists
570 for (i = 0; i < NOBJLISTS; ++i)
571 TAILQ_INIT(&swap_pager_object_list[i]);
572 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
573 sx_init(&sw_alloc_sx, "swspsx");
574 sx_init(&swdev_syscall_lock, "swsysc");
577 * The nsw_cluster_max is constrained by the bp->b_pages[]
578 * array, which has maxphys / PAGE_SIZE entries, and our locally
579 * defined MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
580 * constrained by the swap device interleave stripe size.
582 * Initialized early so that GEOM_ELI can see it.
584 nsw_cluster_max = min(maxphys / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
588 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
590 * Expected to be started from pageout process once, prior to entering
594 swap_pager_swap_init(void)
599 * Number of in-transit swap bp operations. Don't
600 * exhaust the pbufs completely. Make sure we
601 * initialize workable values (0 will work for hysteresis
602 * but it isn't very efficient).
604 * Currently we hardwire nsw_wcount_async to 4. This limit is
605 * designed to prevent other I/O from having high latencies due to
606 * our pageout I/O. The value 4 works well for one or two active swap
607 * devices but is probably a little low if you have more. Even so,
608 * a higher value would probably generate only a limited improvement
609 * with three or four active swap devices since the system does not
610 * typically have to pageout at extreme bandwidths. We will want
611 * at least 2 per swap devices, and 4 is a pretty good value if you
612 * have one NFS swap device due to the command/ack latency over NFS.
613 * So it all works out pretty well.
615 * nsw_cluster_max is initialized in swap_pager_init().
618 nsw_wcount_async = 4;
619 nsw_wcount_async_max = nsw_wcount_async;
620 mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
622 swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
623 swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
626 * Initialize our zone, taking the user's requested size or
627 * estimating the number we need based on the number of pages
630 n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
631 vm_cnt.v_page_count / 2;
632 swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
633 pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0);
634 if (swpctrie_zone == NULL)
635 panic("failed to create swap pctrie zone.");
636 swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
637 NULL, NULL, _Alignof(struct swblk) - 1, 0);
638 if (swblk_zone == NULL)
639 panic("failed to create swap blk zone.");
642 if (uma_zone_reserve_kva(swblk_zone, n))
645 * if the allocation failed, try a zone two thirds the
646 * size of the previous attempt.
652 * Often uma_zone_reserve_kva() cannot reserve exactly the
653 * requested size. Account for the difference when
654 * calculating swap_maxpages.
656 n = uma_zone_get_max(swblk_zone);
659 printf("Swap blk zone entries changed from %lu to %lu.\n",
661 /* absolute maximum we can handle assuming 100% efficiency */
662 swap_maxpages = n * SWAP_META_PAGES;
663 swzone = n * sizeof(struct swblk);
664 if (!uma_zone_reserve_kva(swpctrie_zone, n))
665 printf("Cannot reserve swap pctrie zone, "
666 "reduce kern.maxswzone.\n");
670 swap_pager_init_object(vm_object_t object, void *handle, struct ucred *cred,
671 vm_ooffset_t size, vm_ooffset_t offset)
674 if (!swap_reserve_by_cred(size, cred))
679 object->un_pager.swp.writemappings = 0;
680 object->handle = handle;
683 object->charge = size;
689 swap_pager_alloc_init(objtype_t otype, void *handle, struct ucred *cred,
690 vm_ooffset_t size, vm_ooffset_t offset)
695 * The un_pager.swp.swp_blks trie is initialized by
696 * vm_object_allocate() to ensure the correct order of
697 * visibility to other threads.
699 object = vm_object_allocate(otype, OFF_TO_IDX(offset +
702 if (!swap_pager_init_object(object, handle, cred, size, offset)) {
703 vm_object_deallocate(object);
710 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
711 * its metadata structures.
713 * This routine is called from the mmap and fork code to create a new
716 * This routine must ensure that no live duplicate is created for
717 * the named object request, which is protected against by
718 * holding the sw_alloc_sx lock in case handle != NULL.
721 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
722 vm_ooffset_t offset, struct ucred *cred)
726 if (handle != NULL) {
728 * Reference existing named region or allocate new one. There
729 * should not be a race here against swp_pager_meta_build()
730 * as called from vm_page_remove() in regards to the lookup
733 sx_xlock(&sw_alloc_sx);
734 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
735 if (object == NULL) {
736 object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
738 if (object != NULL) {
739 TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
740 object, pager_object_list);
743 sx_xunlock(&sw_alloc_sx);
745 object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
752 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
754 * The swap backing for the object is destroyed. The code is
755 * designed such that we can reinstantiate it later, but this
756 * routine is typically called only when the entire object is
757 * about to be destroyed.
759 * The object must be locked.
762 swap_pager_dealloc(vm_object_t object)
765 VM_OBJECT_ASSERT_WLOCKED(object);
766 KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
769 * Remove from list right away so lookups will fail if we block for
770 * pageout completion.
772 if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
773 VM_OBJECT_WUNLOCK(object);
774 sx_xlock(&sw_alloc_sx);
775 TAILQ_REMOVE(NOBJLIST(object->handle), object,
777 sx_xunlock(&sw_alloc_sx);
778 VM_OBJECT_WLOCK(object);
781 vm_object_pip_wait(object, "swpdea");
784 * Free all remaining metadata. We only bother to free it from
785 * the swap meta data. We do not attempt to free swapblk's still
786 * associated with vm_page_t's for this object. We do not care
787 * if paging is still in progress on some objects.
789 swp_pager_meta_free_all(object);
790 object->handle = NULL;
791 object->type = OBJT_DEAD;
792 vm_object_clear_flag(object, OBJ_SWAP);
795 /************************************************************************
796 * SWAP PAGER BITMAP ROUTINES *
797 ************************************************************************/
800 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
802 * Allocate swap for up to the requested number of pages. The
803 * starting swap block number (a page index) is returned or
804 * SWAPBLK_NONE if the allocation failed.
806 * Also has the side effect of advising that somebody made a mistake
807 * when they configured swap and didn't configure enough.
809 * This routine may not sleep.
811 * We allocate in round-robin fashion from the configured devices.
814 swp_pager_getswapspace(int *io_npages)
820 KASSERT(*io_npages >= 1,
821 ("%s: npages not positive", __func__));
824 npages = imin(BLIST_MAX_ALLOC, mpages);
825 mtx_lock(&sw_dev_mtx);
827 while (!TAILQ_EMPTY(&swtailq)) {
829 sp = TAILQ_FIRST(&swtailq);
830 if ((sp->sw_flags & SW_CLOSING) == 0)
831 blk = blist_alloc(sp->sw_blist, &npages, mpages);
832 if (blk != SWAPBLK_NONE)
834 sp = TAILQ_NEXT(sp, sw_list);
842 if (blk != SWAPBLK_NONE) {
845 sp->sw_used += npages;
846 swap_pager_avail -= npages;
848 swdevhd = TAILQ_NEXT(sp, sw_list);
850 if (swap_pager_full != 2) {
851 printf("swp_pager_getswapspace(%d): failed\n",
854 swap_pager_almost_full = 1;
858 mtx_unlock(&sw_dev_mtx);
863 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
866 return (blk >= sp->sw_first && blk < sp->sw_end);
870 swp_pager_strategy(struct buf *bp)
874 mtx_lock(&sw_dev_mtx);
875 TAILQ_FOREACH(sp, &swtailq, sw_list) {
876 if (swp_pager_isondev(bp->b_blkno, sp)) {
877 mtx_unlock(&sw_dev_mtx);
878 if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
879 unmapped_buf_allowed) {
880 bp->b_data = unmapped_buf;
883 pmap_qenter((vm_offset_t)bp->b_data,
884 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
886 sp->sw_strategy(bp, sp);
890 panic("Swapdev not found");
894 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
896 * This routine returns the specified swap blocks back to the bitmap.
898 * This routine may not sleep.
901 swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
907 mtx_lock(&sw_dev_mtx);
908 TAILQ_FOREACH(sp, &swtailq, sw_list) {
909 if (swp_pager_isondev(blk, sp)) {
910 sp->sw_used -= npages;
912 * If we are attempting to stop swapping on
913 * this device, we don't want to mark any
914 * blocks free lest they be reused.
916 if ((sp->sw_flags & SW_CLOSING) == 0) {
917 blist_free(sp->sw_blist, blk - sp->sw_first,
919 swap_pager_avail += npages;
922 mtx_unlock(&sw_dev_mtx);
926 panic("Swapdev not found");
930 * SYSCTL_SWAP_FRAGMENTATION() - produce raw swap space stats
933 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
940 error = sysctl_wire_old_buffer(req, 0);
943 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
944 mtx_lock(&sw_dev_mtx);
945 TAILQ_FOREACH(sp, &swtailq, sw_list) {
946 if (vn_isdisk(sp->sw_vp))
947 devname = devtoname(sp->sw_vp->v_rdev);
950 sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
951 blist_stats(sp->sw_blist, &sbuf);
953 mtx_unlock(&sw_dev_mtx);
954 error = sbuf_finish(&sbuf);
960 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
961 * range within an object.
963 * This routine removes swapblk assignments from swap metadata.
965 * The external callers of this routine typically have already destroyed
966 * or renamed vm_page_t's associated with this range in the object so
969 * The object must be locked.
972 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
975 swp_pager_meta_free(object, start, size);
979 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
981 * Assigns swap blocks to the specified range within the object. The
982 * swap blocks are not zeroed. Any previous swap assignment is destroyed.
984 * Returns 0 on success, -1 on failure.
987 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_pindex_t size)
989 daddr_t addr, blk, n_free, s_free;
993 swp_pager_init_freerange(&s_free, &n_free);
994 VM_OBJECT_WLOCK(object);
995 for (i = 0; i < size; i += n) {
996 n = MIN(size - i, INT_MAX);
997 blk = swp_pager_getswapspace(&n);
998 if (blk == SWAPBLK_NONE) {
999 swp_pager_meta_free(object, start, i);
1000 VM_OBJECT_WUNLOCK(object);
1003 for (j = 0; j < n; ++j) {
1004 addr = swp_pager_meta_build(object,
1005 start + i + j, blk + j);
1006 if (addr != SWAPBLK_NONE)
1007 swp_pager_update_freerange(&s_free, &n_free,
1011 swp_pager_freeswapspace(s_free, n_free);
1012 VM_OBJECT_WUNLOCK(object);
1017 swp_pager_xfer_source(vm_object_t srcobject, vm_object_t dstobject,
1018 vm_pindex_t pindex, daddr_t addr)
1022 KASSERT((srcobject->flags & OBJ_SWAP) != 0,
1023 ("%s: Srcobject not swappable", __func__));
1024 if ((dstobject->flags & OBJ_SWAP) != 0 &&
1025 swp_pager_meta_lookup(dstobject, pindex) != SWAPBLK_NONE) {
1026 /* Caller should destroy the source block. */
1031 * Destination has no swapblk and is not resident, transfer source.
1032 * swp_pager_meta_build() can sleep.
1034 VM_OBJECT_WUNLOCK(srcobject);
1035 dstaddr = swp_pager_meta_build(dstobject, pindex, addr);
1036 KASSERT(dstaddr == SWAPBLK_NONE,
1037 ("Unexpected destination swapblk"));
1038 VM_OBJECT_WLOCK(srcobject);
1044 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
1045 * and destroy the source.
1047 * Copy any valid swapblks from the source to the destination. In
1048 * cases where both the source and destination have a valid swapblk,
1049 * we keep the destination's.
1051 * This routine is allowed to sleep. It may sleep allocating metadata
1052 * indirectly through swp_pager_meta_build().
1054 * The source object contains no vm_page_t's (which is just as well)
1056 * The source object is of type OBJT_SWAP.
1058 * The source and destination objects must be locked.
1059 * Both object locks may temporarily be released.
1062 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
1063 vm_pindex_t offset, int destroysource)
1066 VM_OBJECT_ASSERT_WLOCKED(srcobject);
1067 VM_OBJECT_ASSERT_WLOCKED(dstobject);
1070 * If destroysource is set, we remove the source object from the
1071 * swap_pager internal queue now.
1073 if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
1074 srcobject->handle != NULL) {
1075 VM_OBJECT_WUNLOCK(srcobject);
1076 VM_OBJECT_WUNLOCK(dstobject);
1077 sx_xlock(&sw_alloc_sx);
1078 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1080 sx_xunlock(&sw_alloc_sx);
1081 VM_OBJECT_WLOCK(dstobject);
1082 VM_OBJECT_WLOCK(srcobject);
1086 * Transfer source to destination.
1088 swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size);
1091 * Free left over swap blocks in source.
1093 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
1094 * double-remove the object from the swap queues.
1096 if (destroysource) {
1097 swp_pager_meta_free_all(srcobject);
1099 * Reverting the type is not necessary, the caller is going
1100 * to destroy srcobject directly, but I'm doing it here
1101 * for consistency since we've removed the object from its
1104 srcobject->type = OBJT_DEFAULT;
1105 vm_object_clear_flag(srcobject, OBJ_SWAP);
1110 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
1111 * the requested page.
1113 * We determine whether good backing store exists for the requested
1114 * page and return TRUE if it does, FALSE if it doesn't.
1116 * If TRUE, we also try to determine how much valid, contiguous backing
1117 * store exists before and after the requested page.
1120 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1126 VM_OBJECT_ASSERT_LOCKED(object);
1127 KASSERT((object->flags & OBJ_SWAP) != 0,
1128 ("%s: object not swappable", __func__));
1131 * do we have good backing store at the requested index ?
1133 blk0 = swp_pager_meta_lookup(object, pindex);
1134 if (blk0 == SWAPBLK_NONE) {
1143 * find backwards-looking contiguous good backing store
1145 if (before != NULL) {
1146 for (i = 1; i < SWB_NPAGES; i++) {
1149 blk = swp_pager_meta_lookup(object, pindex - i);
1150 if (blk != blk0 - i)
1157 * find forward-looking contiguous good backing store
1159 if (after != NULL) {
1160 for (i = 1; i < SWB_NPAGES; i++) {
1161 blk = swp_pager_meta_lookup(object, pindex + i);
1162 if (blk != blk0 + i)
1171 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1173 * This removes any associated swap backing store, whether valid or
1174 * not, from the page.
1176 * This routine is typically called when a page is made dirty, at
1177 * which point any associated swap can be freed. MADV_FREE also
1178 * calls us in a special-case situation
1180 * NOTE!!! If the page is clean and the swap was valid, the caller
1181 * should make the page dirty before calling this routine. This routine
1182 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1185 * This routine may not sleep.
1187 * The object containing the page may be locked.
1190 swap_pager_unswapped(vm_page_t m)
1196 * Handle enqueing deferred frees first. If we do not have the
1197 * object lock we wait for the page daemon to clear the space.
1200 if (!VM_OBJECT_WOWNED(obj)) {
1201 VM_PAGE_OBJECT_BUSY_ASSERT(m);
1203 * The caller is responsible for synchronization but we
1204 * will harmlessly handle races. This is typically provided
1205 * by only calling unswapped() when a page transitions from
1208 if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1210 vm_page_aflag_set(m, PGA_SWAP_FREE);
1211 counter_u64_add(swap_free_deferred, 1);
1215 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1216 counter_u64_add(swap_free_completed, 1);
1217 vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
1220 * The meta data only exists if the object is OBJT_SWAP
1221 * and even then might not be allocated yet.
1223 KASSERT((m->object->flags & OBJ_SWAP) != 0,
1224 ("Free object not swappable"));
1226 sb = SWAP_PCTRIE_LOOKUP(&m->object->un_pager.swp.swp_blks,
1227 rounddown(m->pindex, SWAP_META_PAGES));
1230 if (sb->d[m->pindex % SWAP_META_PAGES] == SWAPBLK_NONE)
1232 swp_pager_freeswapspace(sb->d[m->pindex % SWAP_META_PAGES], 1);
1233 sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
1234 swp_pager_free_empty_swblk(m->object, sb);
1238 * swap_pager_getpages() - bring pages in from swap
1240 * Attempt to page in the pages in array "ma" of length "count". The
1241 * caller may optionally specify that additional pages preceding and
1242 * succeeding the specified range be paged in. The number of such pages
1243 * is returned in the "rbehind" and "rahead" parameters, and they will
1244 * be in the inactive queue upon return.
1246 * The pages in "ma" must be busied and will remain busied upon return.
1249 swap_pager_getpages_locked(vm_object_t object, vm_page_t *ma, int count,
1250 int *rbehind, int *rahead)
1253 vm_page_t bm, mpred, msucc, p;
1256 int i, maxahead, maxbehind, reqcount;
1258 VM_OBJECT_ASSERT_WLOCKED(object);
1261 KASSERT((object->flags & OBJ_SWAP) != 0,
1262 ("%s: object not swappable", __func__));
1263 if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead)) {
1264 VM_OBJECT_WUNLOCK(object);
1265 return (VM_PAGER_FAIL);
1268 KASSERT(reqcount - 1 <= maxahead,
1269 ("page count %d extends beyond swap block", reqcount));
1272 * Do not transfer any pages other than those that are xbusied
1273 * when running during a split or collapse operation. This
1274 * prevents clustering from re-creating pages which are being
1275 * moved into another object.
1277 if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
1278 maxahead = reqcount - 1;
1283 * Clip the readahead and readbehind ranges to exclude resident pages.
1285 if (rahead != NULL) {
1286 *rahead = imin(*rahead, maxahead - (reqcount - 1));
1287 pindex = ma[reqcount - 1]->pindex;
1288 msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1289 if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1290 *rahead = msucc->pindex - pindex - 1;
1292 if (rbehind != NULL) {
1293 *rbehind = imin(*rbehind, maxbehind);
1294 pindex = ma[0]->pindex;
1295 mpred = TAILQ_PREV(ma[0], pglist, listq);
1296 if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1297 *rbehind = pindex - mpred->pindex - 1;
1301 for (i = 0; i < count; i++)
1302 ma[i]->oflags |= VPO_SWAPINPROG;
1305 * Allocate readahead and readbehind pages.
1307 if (rbehind != NULL) {
1308 for (i = 1; i <= *rbehind; i++) {
1309 p = vm_page_alloc(object, ma[0]->pindex - i,
1313 p->oflags |= VPO_SWAPINPROG;
1318 if (rahead != NULL) {
1319 for (i = 0; i < *rahead; i++) {
1320 p = vm_page_alloc(object,
1321 ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1324 p->oflags |= VPO_SWAPINPROG;
1328 if (rbehind != NULL)
1333 vm_object_pip_add(object, count);
1335 pindex = bm->pindex;
1336 blk = swp_pager_meta_lookup(object, pindex);
1337 KASSERT(blk != SWAPBLK_NONE,
1338 ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1340 VM_OBJECT_WUNLOCK(object);
1341 bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1342 MPASS((bp->b_flags & B_MAXPHYS) != 0);
1343 /* Pages cannot leave the object while busy. */
1344 for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1345 MPASS(p->pindex == bm->pindex + i);
1349 bp->b_flags |= B_PAGING;
1350 bp->b_iocmd = BIO_READ;
1351 bp->b_iodone = swp_pager_async_iodone;
1352 bp->b_rcred = crhold(thread0.td_ucred);
1353 bp->b_wcred = crhold(thread0.td_ucred);
1355 bp->b_bcount = PAGE_SIZE * count;
1356 bp->b_bufsize = PAGE_SIZE * count;
1357 bp->b_npages = count;
1358 bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1359 bp->b_pgafter = rahead != NULL ? *rahead : 0;
1361 VM_CNT_INC(v_swapin);
1362 VM_CNT_ADD(v_swappgsin, count);
1365 * perform the I/O. NOTE!!! bp cannot be considered valid after
1366 * this point because we automatically release it on completion.
1367 * Instead, we look at the one page we are interested in which we
1368 * still hold a lock on even through the I/O completion.
1370 * The other pages in our ma[] array are also released on completion,
1371 * so we cannot assume they are valid anymore either.
1373 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1376 swp_pager_strategy(bp);
1379 * Wait for the pages we want to complete. VPO_SWAPINPROG is always
1380 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1381 * is set in the metadata for each page in the request.
1383 VM_OBJECT_WLOCK(object);
1384 /* This could be implemented more efficiently with aflags */
1385 while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
1386 ma[0]->oflags |= VPO_SWAPSLEEP;
1387 VM_CNT_INC(v_intrans);
1388 if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1389 "swread", hz * 20)) {
1391 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1392 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1395 VM_OBJECT_WUNLOCK(object);
1398 * If we had an unrecoverable read error pages will not be valid.
1400 for (i = 0; i < reqcount; i++)
1401 if (ma[i]->valid != VM_PAGE_BITS_ALL)
1402 return (VM_PAGER_ERROR);
1404 return (VM_PAGER_OK);
1407 * A final note: in a low swap situation, we cannot deallocate swap
1408 * and mark a page dirty here because the caller is likely to mark
1409 * the page clean when we return, causing the page to possibly revert
1410 * to all-zero's later.
1415 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count,
1416 int *rbehind, int *rahead)
1419 VM_OBJECT_WLOCK(object);
1420 return (swap_pager_getpages_locked(object, ma, count, rbehind, rahead));
1424 * swap_pager_getpages_async():
1426 * Right now this is emulation of asynchronous operation on top of
1427 * swap_pager_getpages().
1430 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1431 int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1435 r = swap_pager_getpages(object, ma, count, rbehind, rahead);
1440 case VM_PAGER_ERROR:
1447 panic("unhandled swap_pager_getpages() error %d", r);
1449 (iodone)(arg, ma, count, error);
1455 * swap_pager_putpages:
1457 * Assign swap (if necessary) and initiate I/O on the specified pages.
1459 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1460 * are automatically converted to SWAP objects.
1462 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1463 * vm_page reservation system coupled with properly written VFS devices
1464 * should ensure that no low-memory deadlock occurs. This is an area
1467 * The parent has N vm_object_pip_add() references prior to
1468 * calling us and will remove references for rtvals[] that are
1469 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1472 * The parent has soft-busy'd the pages it passes us and will unbusy
1473 * those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
1474 * We need to unbusy the rest on I/O completion.
1477 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1478 int flags, int *rtvals)
1481 daddr_t addr, blk, n_free, s_free;
1486 KASSERT(count == 0 || ma[0]->object == object,
1487 ("%s: object mismatch %p/%p",
1488 __func__, object, ma[0]->object));
1493 * Turn object into OBJT_SWAP. Force sync if not a pageout process.
1495 if ((object->flags & OBJ_SWAP) == 0) {
1496 addr = swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1497 KASSERT(addr == SWAPBLK_NONE,
1498 ("unexpected object swap block"));
1500 VM_OBJECT_WUNLOCK(object);
1501 async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
1502 swp_pager_init_freerange(&s_free, &n_free);
1507 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1508 * The page is left dirty until the pageout operation completes
1511 for (i = 0; i < count; i += n) {
1512 /* Maximum I/O size is limited by maximum swap block size. */
1513 n = min(count - i, nsw_cluster_max);
1516 mtx_lock(&swbuf_mtx);
1517 while (nsw_wcount_async == 0)
1518 msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1521 mtx_unlock(&swbuf_mtx);
1524 /* Get a block of swap of size up to size n. */
1525 VM_OBJECT_WLOCK(object);
1526 blk = swp_pager_getswapspace(&n);
1527 if (blk == SWAPBLK_NONE) {
1528 VM_OBJECT_WUNLOCK(object);
1529 mtx_lock(&swbuf_mtx);
1530 if (++nsw_wcount_async == 1)
1531 wakeup(&nsw_wcount_async);
1532 mtx_unlock(&swbuf_mtx);
1533 for (j = 0; j < n; ++j)
1534 rtvals[i + j] = VM_PAGER_FAIL;
1537 for (j = 0; j < n; ++j) {
1539 vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1540 addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1542 if (addr != SWAPBLK_NONE)
1543 swp_pager_update_freerange(&s_free, &n_free,
1545 MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1546 mreq->oflags |= VPO_SWAPINPROG;
1548 VM_OBJECT_WUNLOCK(object);
1550 bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1551 MPASS((bp->b_flags & B_MAXPHYS) != 0);
1553 bp->b_flags |= B_ASYNC;
1554 bp->b_flags |= B_PAGING;
1555 bp->b_iocmd = BIO_WRITE;
1557 bp->b_rcred = crhold(thread0.td_ucred);
1558 bp->b_wcred = crhold(thread0.td_ucred);
1559 bp->b_bcount = PAGE_SIZE * n;
1560 bp->b_bufsize = PAGE_SIZE * n;
1562 for (j = 0; j < n; j++)
1563 bp->b_pages[j] = ma[i + j];
1567 * Must set dirty range for NFS to work.
1570 bp->b_dirtyend = bp->b_bcount;
1572 VM_CNT_INC(v_swapout);
1573 VM_CNT_ADD(v_swappgsout, bp->b_npages);
1576 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1577 * can call the async completion routine at the end of a
1578 * synchronous I/O operation. Otherwise, our caller would
1579 * perform duplicate unbusy and wakeup operations on the page
1580 * and object, respectively.
1582 for (j = 0; j < n; j++)
1583 rtvals[i + j] = VM_PAGER_PEND;
1588 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1591 bp->b_iodone = swp_pager_async_iodone;
1593 swp_pager_strategy(bp);
1600 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1602 bp->b_iodone = bdone;
1603 swp_pager_strategy(bp);
1606 * Wait for the sync I/O to complete.
1608 bwait(bp, PVM, "swwrt");
1611 * Now that we are through with the bp, we can call the
1612 * normal async completion, which frees everything up.
1614 swp_pager_async_iodone(bp);
1616 swp_pager_freeswapspace(s_free, n_free);
1617 VM_OBJECT_WLOCK(object);
1621 * swp_pager_async_iodone:
1623 * Completion routine for asynchronous reads and writes from/to swap.
1624 * Also called manually by synchronous code to finish up a bp.
1626 * This routine may not sleep.
1629 swp_pager_async_iodone(struct buf *bp)
1632 vm_object_t object = NULL;
1635 * Report error - unless we ran out of memory, in which case
1636 * we've already logged it in swapgeom_strategy().
1638 if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
1640 "swap_pager: I/O error - %s failed; blkno %ld,"
1641 "size %ld, error %d\n",
1642 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1650 * remove the mapping for kernel virtual
1653 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1655 bp->b_data = bp->b_kvabase;
1658 object = bp->b_pages[0]->object;
1659 VM_OBJECT_WLOCK(object);
1663 * cleanup pages. If an error occurs writing to swap, we are in
1664 * very serious trouble. If it happens to be a disk error, though,
1665 * we may be able to recover by reassigning the swap later on. So
1666 * in this case we remove the m->swapblk assignment for the page
1667 * but do not free it in the rlist. The errornous block(s) are thus
1668 * never reallocated as swap. Redirty the page and continue.
1670 for (i = 0; i < bp->b_npages; ++i) {
1671 vm_page_t m = bp->b_pages[i];
1673 m->oflags &= ~VPO_SWAPINPROG;
1674 if (m->oflags & VPO_SWAPSLEEP) {
1675 m->oflags &= ~VPO_SWAPSLEEP;
1676 wakeup(&object->handle);
1679 /* We always have space after I/O, successful or not. */
1680 vm_page_aflag_set(m, PGA_SWAP_SPACE);
1682 if (bp->b_ioflags & BIO_ERROR) {
1684 * If an error occurs I'd love to throw the swapblk
1685 * away without freeing it back to swapspace, so it
1686 * can never be used again. But I can't from an
1689 if (bp->b_iocmd == BIO_READ) {
1691 * NOTE: for reads, m->dirty will probably
1692 * be overridden by the original caller of
1693 * getpages so don't play cute tricks here.
1698 * If a write error occurs, reactivate page
1699 * so it doesn't clog the inactive list,
1700 * then finish the I/O.
1702 MPASS(m->dirty == VM_PAGE_BITS_ALL);
1704 /* PQ_UNSWAPPABLE? */
1705 vm_page_activate(m);
1708 } else if (bp->b_iocmd == BIO_READ) {
1710 * NOTE: for reads, m->dirty will probably be
1711 * overridden by the original caller of getpages so
1712 * we cannot set them in order to free the underlying
1713 * swap in a low-swap situation. I don't think we'd
1714 * want to do that anyway, but it was an optimization
1715 * that existed in the old swapper for a time before
1716 * it got ripped out due to precisely this problem.
1718 KASSERT(!pmap_page_is_mapped(m),
1719 ("swp_pager_async_iodone: page %p is mapped", m));
1720 KASSERT(m->dirty == 0,
1721 ("swp_pager_async_iodone: page %p is dirty", m));
1724 if (i < bp->b_pgbefore ||
1725 i >= bp->b_npages - bp->b_pgafter)
1726 vm_page_readahead_finish(m);
1729 * For write success, clear the dirty
1730 * status, then finish the I/O ( which decrements the
1731 * busy count and possibly wakes waiter's up ).
1732 * A page is only written to swap after a period of
1733 * inactivity. Therefore, we do not expect it to be
1736 KASSERT(!pmap_page_is_write_mapped(m),
1737 ("swp_pager_async_iodone: page %p is not write"
1740 vm_page_deactivate_noreuse(m);
1746 * adjust pip. NOTE: the original parent may still have its own
1747 * pip refs on the object.
1749 if (object != NULL) {
1750 vm_object_pip_wakeupn(object, bp->b_npages);
1751 VM_OBJECT_WUNLOCK(object);
1755 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1756 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1757 * trigger a KASSERT in relpbuf().
1761 bp->b_bufobj = NULL;
1764 * release the physical I/O buffer
1766 if (bp->b_flags & B_ASYNC) {
1767 mtx_lock(&swbuf_mtx);
1768 if (++nsw_wcount_async == 1)
1769 wakeup(&nsw_wcount_async);
1770 mtx_unlock(&swbuf_mtx);
1772 uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
1776 swap_pager_nswapdev(void)
1783 swp_pager_force_dirty(vm_page_t m)
1787 swap_pager_unswapped(m);
1792 swap_pager_swapped_pages(vm_object_t object)
1799 VM_OBJECT_ASSERT_LOCKED(object);
1800 if ((object->flags & OBJ_SWAP) == 0)
1803 for (res = 0, pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1804 &object->un_pager.swp.swp_blks, pi)) != NULL;
1805 pi = sb->p + SWAP_META_PAGES) {
1806 for (i = 0; i < SWAP_META_PAGES; i++) {
1807 if (sb->d[i] != SWAPBLK_NONE)
1815 * swap_pager_swapoff_object:
1817 * Page in all of the pages that have been paged out for an object
1821 swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
1827 int i, nv, rahead, rv;
1829 KASSERT((object->flags & OBJ_SWAP) != 0,
1830 ("%s: Object not swappable", __func__));
1832 for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1833 &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1834 if ((object->flags & OBJ_DEAD) != 0) {
1836 * Make sure that pending writes finish before
1839 vm_object_pip_wait(object, "swpoff");
1840 swp_pager_meta_free_all(object);
1843 for (i = 0; i < SWAP_META_PAGES; i++) {
1845 * Count the number of contiguous valid blocks.
1847 for (nv = 0; nv < SWAP_META_PAGES - i; nv++) {
1848 blk = sb->d[i + nv];
1849 if (!swp_pager_isondev(blk, sp) ||
1850 blk == SWAPBLK_NONE)
1857 * Look for a page corresponding to the first
1858 * valid block and ensure that any pending paging
1859 * operations on it are complete. If the page is valid,
1860 * mark it dirty and free the swap block. Try to batch
1861 * this operation since it may cause sp to be freed,
1862 * meaning that we must restart the scan. Avoid busying
1863 * valid pages since we may block forever on kernel
1866 m = vm_page_lookup(object, sb->p + i);
1868 m = vm_page_alloc(object, sb->p + i,
1869 VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
1873 if ((m->oflags & VPO_SWAPINPROG) != 0) {
1874 m->oflags |= VPO_SWAPSLEEP;
1875 VM_OBJECT_SLEEP(object, &object->handle,
1879 if (vm_page_all_valid(m)) {
1881 swp_pager_force_dirty(m);
1882 } while (--nv > 0 &&
1883 (m = vm_page_next(m)) != NULL &&
1884 vm_page_all_valid(m) &&
1885 (m->oflags & VPO_SWAPINPROG) == 0);
1888 if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL))
1892 vm_object_pip_add(object, 1);
1893 rahead = SWAP_META_PAGES;
1894 rv = swap_pager_getpages_locked(object, &m, 1, NULL,
1896 if (rv != VM_PAGER_OK)
1897 panic("%s: read from swap failed: %d",
1899 vm_object_pip_wakeupn(object, 1);
1900 VM_OBJECT_WLOCK(object);
1904 * The object lock was dropped so we must restart the
1905 * scan of this swap block. Pages paged in during this
1906 * iteration will be marked dirty in a future iteration.
1910 if (i == SWAP_META_PAGES)
1911 pi = sb->p + SWAP_META_PAGES;
1916 * swap_pager_swapoff:
1918 * Page in all of the pages that have been paged out to the
1919 * given device. The corresponding blocks in the bitmap must be
1920 * marked as allocated and the device must be flagged SW_CLOSING.
1921 * There may be no processes swapped out to the device.
1923 * This routine may block.
1926 swap_pager_swapoff(struct swdevt *sp)
1931 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1935 mtx_lock(&vm_object_list_mtx);
1936 TAILQ_FOREACH(object, &vm_object_list, object_list) {
1937 if ((object->flags & OBJ_SWAP) == 0)
1939 mtx_unlock(&vm_object_list_mtx);
1940 /* Depends on type-stability. */
1941 VM_OBJECT_WLOCK(object);
1944 * Dead objects are eventually terminated on their own.
1946 if ((object->flags & OBJ_DEAD) != 0)
1950 * Sync with fences placed after pctrie
1951 * initialization. We must not access pctrie below
1952 * unless we checked that our object is swap and not
1955 atomic_thread_fence_acq();
1956 if ((object->flags & OBJ_SWAP) == 0)
1959 swap_pager_swapoff_object(sp, object);
1961 VM_OBJECT_WUNLOCK(object);
1962 mtx_lock(&vm_object_list_mtx);
1964 mtx_unlock(&vm_object_list_mtx);
1968 * Objects may be locked or paging to the device being
1969 * removed, so we will miss their pages and need to
1970 * make another pass. We have marked this device as
1971 * SW_CLOSING, so the activity should finish soon.
1974 if (retries > 100) {
1975 panic("swapoff: failed to locate %d swap blocks",
1978 pause("swpoff", hz / 20);
1981 EVENTHANDLER_INVOKE(swapoff, sp);
1984 /************************************************************************
1986 ************************************************************************
1988 * These routines manipulate the swap metadata stored in the
1991 * Swap metadata is implemented with a global hash and not directly
1992 * linked into the object. Instead the object simply contains
1993 * appropriate tracking counters.
1997 * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
2000 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
2004 MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
2005 for (i = start; i < limit; i++) {
2006 if (sb->d[i] != SWAPBLK_NONE)
2013 * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
2015 * Nothing is done if the block is still in use.
2018 swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
2021 if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
2022 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2023 uma_zfree(swblk_zone, sb);
2028 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
2030 * We first convert the object to a swap object if it is a default
2033 * The specified swapblk is added to the object's swap metadata. If
2034 * the swapblk is not valid, it is freed instead. Any previously
2035 * assigned swapblk is returned.
2038 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
2040 static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
2041 struct swblk *sb, *sb1;
2042 vm_pindex_t modpi, rdpi;
2043 daddr_t prev_swapblk;
2046 VM_OBJECT_ASSERT_WLOCKED(object);
2049 * Convert default object to swap object if necessary
2051 if ((object->flags & OBJ_SWAP) == 0) {
2052 pctrie_init(&object->un_pager.swp.swp_blks);
2055 * Ensure that swap_pager_swapoff()'s iteration over
2056 * object_list does not see a garbage pctrie.
2058 atomic_thread_fence_rel();
2060 object->type = OBJT_SWAP;
2061 vm_object_set_flag(object, OBJ_SWAP);
2062 object->un_pager.swp.writemappings = 0;
2063 KASSERT((object->flags & OBJ_ANON) != 0 ||
2064 object->handle == NULL,
2065 ("default pager %p with handle %p",
2066 object, object->handle));
2069 rdpi = rounddown(pindex, SWAP_META_PAGES);
2070 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
2072 if (swapblk == SWAPBLK_NONE)
2073 return (SWAPBLK_NONE);
2075 sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
2076 pageproc ? M_USE_RESERVE : 0));
2079 for (i = 0; i < SWAP_META_PAGES; i++)
2080 sb->d[i] = SWAPBLK_NONE;
2081 if (atomic_cmpset_int(&swblk_zone_exhausted,
2083 printf("swblk zone ok\n");
2086 VM_OBJECT_WUNLOCK(object);
2087 if (uma_zone_exhausted(swblk_zone)) {
2088 if (atomic_cmpset_int(&swblk_zone_exhausted,
2090 printf("swap blk zone exhausted, "
2091 "increase kern.maxswzone\n");
2092 vm_pageout_oom(VM_OOM_SWAPZ);
2093 pause("swzonxb", 10);
2095 uma_zwait(swblk_zone);
2096 VM_OBJECT_WLOCK(object);
2097 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2101 * Somebody swapped out a nearby page,
2102 * allocating swblk at the rdpi index,
2103 * while we dropped the object lock.
2108 error = SWAP_PCTRIE_INSERT(
2109 &object->un_pager.swp.swp_blks, sb);
2111 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2113 printf("swpctrie zone ok\n");
2116 VM_OBJECT_WUNLOCK(object);
2117 if (uma_zone_exhausted(swpctrie_zone)) {
2118 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2120 printf("swap pctrie zone exhausted, "
2121 "increase kern.maxswzone\n");
2122 vm_pageout_oom(VM_OOM_SWAPZ);
2123 pause("swzonxp", 10);
2125 uma_zwait(swpctrie_zone);
2126 VM_OBJECT_WLOCK(object);
2127 sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2130 uma_zfree(swblk_zone, sb);
2137 MPASS(sb->p == rdpi);
2139 modpi = pindex % SWAP_META_PAGES;
2140 /* Return prior contents of metadata. */
2141 prev_swapblk = sb->d[modpi];
2142 /* Enter block into metadata. */
2143 sb->d[modpi] = swapblk;
2146 * Free the swblk if we end up with the empty page run.
2148 if (swapblk == SWAPBLK_NONE)
2149 swp_pager_free_empty_swblk(object, sb);
2150 return (prev_swapblk);
2154 * SWP_PAGER_META_TRANSFER() - free a range of blocks in the srcobject's swap
2155 * metadata, or transfer it into dstobject.
2157 * This routine will free swap metadata structures as they are cleaned
2161 swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
2162 vm_pindex_t pindex, vm_pindex_t count)
2165 daddr_t n_free, s_free;
2166 vm_pindex_t offset, last;
2167 int i, limit, start;
2169 VM_OBJECT_ASSERT_WLOCKED(srcobject);
2170 if ((srcobject->flags & OBJ_SWAP) == 0 || count == 0)
2173 swp_pager_init_freerange(&s_free, &n_free);
2175 last = pindex + count;
2177 sb = SWAP_PCTRIE_LOOKUP_GE(&srcobject->un_pager.swp.swp_blks,
2178 rounddown(pindex, SWAP_META_PAGES));
2179 if (sb == NULL || sb->p >= last)
2181 start = pindex > sb->p ? pindex - sb->p : 0;
2182 limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2184 for (i = start; i < limit; i++) {
2185 if (sb->d[i] == SWAPBLK_NONE)
2187 if (dstobject == NULL ||
2188 !swp_pager_xfer_source(srcobject, dstobject,
2189 sb->p + i - offset, sb->d[i])) {
2190 swp_pager_update_freerange(&s_free, &n_free,
2193 sb->d[i] = SWAPBLK_NONE;
2195 pindex = sb->p + SWAP_META_PAGES;
2196 if (swp_pager_swblk_empty(sb, 0, start) &&
2197 swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2198 SWAP_PCTRIE_REMOVE(&srcobject->un_pager.swp.swp_blks,
2200 uma_zfree(swblk_zone, sb);
2203 swp_pager_freeswapspace(s_free, n_free);
2207 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
2209 * The requested range of blocks is freed, with any associated swap
2210 * returned to the swap bitmap.
2212 * This routine will free swap metadata structures as they are cleaned
2213 * out. This routine does *NOT* operate on swap metadata associated
2214 * with resident pages.
2217 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count)
2219 swp_pager_meta_transfer(object, NULL, pindex, count);
2223 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
2225 * This routine locates and destroys all swap metadata associated with
2229 swp_pager_meta_free_all(vm_object_t object)
2232 daddr_t n_free, s_free;
2236 VM_OBJECT_ASSERT_WLOCKED(object);
2237 if ((object->flags & OBJ_SWAP) == 0)
2240 swp_pager_init_freerange(&s_free, &n_free);
2241 for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
2242 &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
2243 pindex = sb->p + SWAP_META_PAGES;
2244 for (i = 0; i < SWAP_META_PAGES; i++) {
2245 if (sb->d[i] == SWAPBLK_NONE)
2247 swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
2249 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2250 uma_zfree(swblk_zone, sb);
2252 swp_pager_freeswapspace(s_free, n_free);
2256 * SWP_PAGER_METACTL() - misc control of swap meta data.
2258 * This routine is capable of looking up, or removing swapblk
2259 * assignments in the swap meta data. It returns the swapblk being
2260 * looked-up, popped, or SWAPBLK_NONE if the block was invalid.
2262 * When acting on a busy resident page and paging is in progress, we
2263 * have to wait until paging is complete but otherwise can act on the
2267 swp_pager_meta_lookup(vm_object_t object, vm_pindex_t pindex)
2271 VM_OBJECT_ASSERT_LOCKED(object);
2274 * The meta data only exists if the object is OBJT_SWAP
2275 * and even then might not be allocated yet.
2277 KASSERT((object->flags & OBJ_SWAP) != 0,
2278 ("Lookup object not swappable"));
2280 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2281 rounddown(pindex, SWAP_META_PAGES));
2283 return (SWAPBLK_NONE);
2284 return (sb->d[pindex % SWAP_META_PAGES]);
2288 * Returns the least page index which is greater than or equal to the
2289 * parameter pindex and for which there is a swap block allocated.
2290 * Returns object's size if the object's type is not swap or if there
2291 * are no allocated swap blocks for the object after the requested
2295 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2300 VM_OBJECT_ASSERT_LOCKED(object);
2301 if ((object->flags & OBJ_SWAP) == 0)
2302 return (object->size);
2304 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2305 rounddown(pindex, SWAP_META_PAGES));
2307 return (object->size);
2308 if (sb->p < pindex) {
2309 for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2310 if (sb->d[i] != SWAPBLK_NONE)
2313 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2314 roundup(pindex, SWAP_META_PAGES));
2316 return (object->size);
2318 for (i = 0; i < SWAP_META_PAGES; i++) {
2319 if (sb->d[i] != SWAPBLK_NONE)
2324 * We get here if a swblk is present in the trie but it
2325 * doesn't map any blocks.
2328 return (object->size);
2332 * System call swapon(name) enables swapping on device name,
2333 * which must be in the swdevsw. Return EBUSY
2334 * if already swapping on this device.
2336 #ifndef _SYS_SYSPROTO_H_
2337 struct swapon_args {
2347 sys_swapon(struct thread *td, struct swapon_args *uap)
2351 struct nameidata nd;
2354 error = priv_check(td, PRIV_SWAPON);
2358 sx_xlock(&swdev_syscall_lock);
2361 * Swap metadata may not fit in the KVM if we have physical
2364 if (swblk_zone == NULL) {
2369 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2375 NDFREE(&nd, NDF_ONLY_PNBUF);
2378 if (vn_isdisk_error(vp, &error)) {
2379 error = swapongeom(vp);
2380 } else if (vp->v_type == VREG &&
2381 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2382 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2384 * Allow direct swapping to NFS regular files in the same
2385 * way that nfs_mountroot() sets up diskless swapping.
2387 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2393 sx_xunlock(&swdev_syscall_lock);
2398 * Check that the total amount of swap currently configured does not
2399 * exceed half the theoretical maximum. If it does, print a warning
2403 swapon_check_swzone(void)
2406 /* recommend using no more than half that amount */
2407 if (swap_total > swap_maxpages / 2) {
2408 printf("warning: total configured swap (%lu pages) "
2409 "exceeds maximum recommended amount (%lu pages).\n",
2410 swap_total, swap_maxpages / 2);
2411 printf("warning: increase kern.maxswzone "
2412 "or reduce amount of swap.\n");
2417 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2418 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2420 struct swdevt *sp, *tsp;
2424 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2425 * First chop nblks off to page-align it, then convert.
2427 * sw->sw_nblks is in page-sized chunks now too.
2429 nblks &= ~(ctodb(1) - 1);
2430 nblks = dbtoc(nblks);
2432 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2433 sp->sw_blist = blist_create(nblks, M_WAITOK);
2437 sp->sw_nblks = nblks;
2439 sp->sw_strategy = strategy;
2440 sp->sw_close = close;
2441 sp->sw_flags = flags;
2444 * Do not free the first blocks in order to avoid overwriting
2445 * any bsd label at the front of the partition
2447 blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2448 nblks - howmany(BBSIZE, PAGE_SIZE));
2451 mtx_lock(&sw_dev_mtx);
2452 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2453 if (tsp->sw_end >= dvbase) {
2455 * We put one uncovered page between the devices
2456 * in order to definitively prevent any cross-device
2459 dvbase = tsp->sw_end + 1;
2462 sp->sw_first = dvbase;
2463 sp->sw_end = dvbase + nblks;
2464 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2466 swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2467 swap_total += nblks;
2468 swapon_check_swzone();
2470 mtx_unlock(&sw_dev_mtx);
2471 EVENTHANDLER_INVOKE(swapon, sp);
2475 * SYSCALL: swapoff(devname)
2477 * Disable swapping on the given device.
2479 * XXX: Badly designed system call: it should use a device index
2480 * rather than filename as specification. We keep sw_vp around
2481 * only to make this work.
2483 #ifndef _SYS_SYSPROTO_H_
2484 struct swapoff_args {
2494 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2497 struct nameidata nd;
2501 error = priv_check(td, PRIV_SWAPOFF);
2505 sx_xlock(&swdev_syscall_lock);
2507 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2512 NDFREE(&nd, NDF_ONLY_PNBUF);
2515 mtx_lock(&sw_dev_mtx);
2516 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2517 if (sp->sw_vp == vp)
2520 mtx_unlock(&sw_dev_mtx);
2525 error = swapoff_one(sp, td->td_ucred);
2527 sx_xunlock(&swdev_syscall_lock);
2532 swapoff_one(struct swdevt *sp, struct ucred *cred)
2539 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2541 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2542 error = mac_system_check_swapoff(cred, sp->sw_vp);
2543 (void) VOP_UNLOCK(sp->sw_vp);
2547 nblks = sp->sw_nblks;
2550 * We can turn off this swap device safely only if the
2551 * available virtual memory in the system will fit the amount
2552 * of data we will have to page back in, plus an epsilon so
2553 * the system doesn't become critically low on swap space.
2555 if (vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
2559 * Prevent further allocations on this device.
2561 mtx_lock(&sw_dev_mtx);
2562 sp->sw_flags |= SW_CLOSING;
2563 swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2564 swap_total -= nblks;
2565 mtx_unlock(&sw_dev_mtx);
2568 * Page in the contents of the device and close it.
2570 swap_pager_swapoff(sp);
2572 sp->sw_close(curthread, sp);
2573 mtx_lock(&sw_dev_mtx);
2575 TAILQ_REMOVE(&swtailq, sp, sw_list);
2577 if (nswapdev == 0) {
2578 swap_pager_full = 2;
2579 swap_pager_almost_full = 1;
2583 mtx_unlock(&sw_dev_mtx);
2584 blist_destroy(sp->sw_blist);
2585 free(sp, M_VMPGDATA);
2592 struct swdevt *sp, *spt;
2593 const char *devname;
2596 sx_xlock(&swdev_syscall_lock);
2598 mtx_lock(&sw_dev_mtx);
2599 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2600 mtx_unlock(&sw_dev_mtx);
2601 if (vn_isdisk(sp->sw_vp))
2602 devname = devtoname(sp->sw_vp->v_rdev);
2605 error = swapoff_one(sp, thread0.td_ucred);
2607 printf("Cannot remove swap device %s (error=%d), "
2608 "skipping.\n", devname, error);
2609 } else if (bootverbose) {
2610 printf("Swap device %s removed.\n", devname);
2612 mtx_lock(&sw_dev_mtx);
2614 mtx_unlock(&sw_dev_mtx);
2616 sx_xunlock(&swdev_syscall_lock);
2620 swap_pager_status(int *total, int *used)
2623 *total = swap_total;
2624 *used = swap_total - swap_pager_avail -
2625 nswapdev * howmany(BBSIZE, PAGE_SIZE);
2629 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2632 const char *tmp_devname;
2637 mtx_lock(&sw_dev_mtx);
2638 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2643 xs->xsw_version = XSWDEV_VERSION;
2644 xs->xsw_dev = sp->sw_dev;
2645 xs->xsw_flags = sp->sw_flags;
2646 xs->xsw_nblks = sp->sw_nblks;
2647 xs->xsw_used = sp->sw_used;
2648 if (devname != NULL) {
2649 if (vn_isdisk(sp->sw_vp))
2650 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2652 tmp_devname = "[file]";
2653 strncpy(devname, tmp_devname, len);
2658 mtx_unlock(&sw_dev_mtx);
2662 #if defined(COMPAT_FREEBSD11)
2663 #define XSWDEV_VERSION_11 1
2673 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2676 u_int xsw_dev1, xsw_dev2;
2684 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2687 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2688 struct xswdev32 xs32;
2690 #if defined(COMPAT_FREEBSD11)
2691 struct xswdev11 xs11;
2695 if (arg2 != 1) /* name length */
2698 memset(&xs, 0, sizeof(xs));
2699 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2702 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2703 if (req->oldlen == sizeof(xs32)) {
2704 memset(&xs32, 0, sizeof(xs32));
2705 xs32.xsw_version = XSWDEV_VERSION;
2706 xs32.xsw_dev1 = xs.xsw_dev;
2707 xs32.xsw_dev2 = xs.xsw_dev >> 32;
2708 xs32.xsw_flags = xs.xsw_flags;
2709 xs32.xsw_nblks = xs.xsw_nblks;
2710 xs32.xsw_used = xs.xsw_used;
2711 error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2715 #if defined(COMPAT_FREEBSD11)
2716 if (req->oldlen == sizeof(xs11)) {
2717 memset(&xs11, 0, sizeof(xs11));
2718 xs11.xsw_version = XSWDEV_VERSION_11;
2719 xs11.xsw_dev = xs.xsw_dev; /* truncation */
2720 xs11.xsw_flags = xs.xsw_flags;
2721 xs11.xsw_nblks = xs.xsw_nblks;
2722 xs11.xsw_used = xs.xsw_used;
2723 error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2727 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2731 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2732 "Number of swap devices");
2733 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2734 sysctl_vm_swap_info,
2735 "Swap statistics by device");
2738 * Count the approximate swap usage in pages for a vmspace. The
2739 * shadowed or not yet copied on write swap blocks are not accounted.
2740 * The map must be locked.
2743 vmspace_swap_count(struct vmspace *vmspace)
2753 map = &vmspace->vm_map;
2756 VM_MAP_ENTRY_FOREACH(cur, map) {
2757 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2759 object = cur->object.vm_object;
2760 if (object == NULL || (object->flags & OBJ_SWAP) == 0)
2762 VM_OBJECT_RLOCK(object);
2763 if ((object->flags & OBJ_SWAP) == 0)
2765 pi = OFF_TO_IDX(cur->offset);
2766 e = pi + OFF_TO_IDX(cur->end - cur->start);
2767 for (;; pi = sb->p + SWAP_META_PAGES) {
2768 sb = SWAP_PCTRIE_LOOKUP_GE(
2769 &object->un_pager.swp.swp_blks, pi);
2770 if (sb == NULL || sb->p >= e)
2772 for (i = 0; i < SWAP_META_PAGES; i++) {
2773 if (sb->p + i < e &&
2774 sb->d[i] != SWAPBLK_NONE)
2779 VM_OBJECT_RUNLOCK(object);
2787 * Swapping onto disk devices.
2791 static g_orphan_t swapgeom_orphan;
2793 static struct g_class g_swap_class = {
2795 .version = G_VERSION,
2796 .orphan = swapgeom_orphan,
2799 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2802 swapgeom_close_ev(void *arg, int flags)
2804 struct g_consumer *cp;
2807 g_access(cp, -1, -1, 0);
2809 g_destroy_consumer(cp);
2813 * Add a reference to the g_consumer for an inflight transaction.
2816 swapgeom_acquire(struct g_consumer *cp)
2819 mtx_assert(&sw_dev_mtx, MA_OWNED);
2824 * Remove a reference from the g_consumer. Post a close event if all
2825 * references go away, since the function might be called from the
2829 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2832 mtx_assert(&sw_dev_mtx, MA_OWNED);
2834 if (cp->index == 0) {
2835 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2841 swapgeom_done(struct bio *bp2)
2845 struct g_consumer *cp;
2847 bp = bp2->bio_caller2;
2849 bp->b_ioflags = bp2->bio_flags;
2851 bp->b_ioflags |= BIO_ERROR;
2852 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2853 bp->b_error = bp2->bio_error;
2854 bp->b_caller1 = NULL;
2856 sp = bp2->bio_caller1;
2857 mtx_lock(&sw_dev_mtx);
2858 swapgeom_release(cp, sp);
2859 mtx_unlock(&sw_dev_mtx);
2864 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2867 struct g_consumer *cp;
2869 mtx_lock(&sw_dev_mtx);
2872 mtx_unlock(&sw_dev_mtx);
2873 bp->b_error = ENXIO;
2874 bp->b_ioflags |= BIO_ERROR;
2878 swapgeom_acquire(cp);
2879 mtx_unlock(&sw_dev_mtx);
2880 if (bp->b_iocmd == BIO_WRITE)
2883 bio = g_alloc_bio();
2885 mtx_lock(&sw_dev_mtx);
2886 swapgeom_release(cp, sp);
2887 mtx_unlock(&sw_dev_mtx);
2888 bp->b_error = ENOMEM;
2889 bp->b_ioflags |= BIO_ERROR;
2890 printf("swap_pager: cannot allocate bio\n");
2895 bp->b_caller1 = bio;
2896 bio->bio_caller1 = sp;
2897 bio->bio_caller2 = bp;
2898 bio->bio_cmd = bp->b_iocmd;
2899 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2900 bio->bio_length = bp->b_bcount;
2901 bio->bio_done = swapgeom_done;
2902 bio->bio_flags |= BIO_SWAP;
2903 if (!buf_mapped(bp)) {
2904 bio->bio_ma = bp->b_pages;
2905 bio->bio_data = unmapped_buf;
2906 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2907 bio->bio_ma_n = bp->b_npages;
2908 bio->bio_flags |= BIO_UNMAPPED;
2910 bio->bio_data = bp->b_data;
2913 g_io_request(bio, cp);
2918 swapgeom_orphan(struct g_consumer *cp)
2923 mtx_lock(&sw_dev_mtx);
2924 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2925 if (sp->sw_id == cp) {
2926 sp->sw_flags |= SW_CLOSING;
2931 * Drop reference we were created with. Do directly since we're in a
2932 * special context where we don't have to queue the call to
2933 * swapgeom_close_ev().
2936 destroy = ((sp != NULL) && (cp->index == 0));
2939 mtx_unlock(&sw_dev_mtx);
2941 swapgeom_close_ev(cp, 0);
2945 swapgeom_close(struct thread *td, struct swdevt *sw)
2947 struct g_consumer *cp;
2949 mtx_lock(&sw_dev_mtx);
2952 mtx_unlock(&sw_dev_mtx);
2955 * swapgeom_close() may be called from the biodone context,
2956 * where we cannot perform topology changes. Delegate the
2957 * work to the events thread.
2960 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2964 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2966 struct g_provider *pp;
2967 struct g_consumer *cp;
2968 static struct g_geom *gp;
2973 pp = g_dev_getprovider(dev);
2976 mtx_lock(&sw_dev_mtx);
2977 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2979 if (cp != NULL && cp->provider == pp) {
2980 mtx_unlock(&sw_dev_mtx);
2984 mtx_unlock(&sw_dev_mtx);
2986 gp = g_new_geomf(&g_swap_class, "swap");
2987 cp = g_new_consumer(gp);
2988 cp->index = 1; /* Number of active I/Os, plus one for being active. */
2989 cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2992 * XXX: Every time you think you can improve the margin for
2993 * footshooting, somebody depends on the ability to do so:
2994 * savecore(8) wants to write to our swapdev so we cannot
2995 * set an exclusive count :-(
2997 error = g_access(cp, 1, 1, 0);
3000 g_destroy_consumer(cp);
3003 nblks = pp->mediasize / DEV_BSIZE;
3004 swaponsomething(vp, cp, nblks, swapgeom_strategy,
3005 swapgeom_close, dev2udev(dev),
3006 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
3011 swapongeom(struct vnode *vp)
3015 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3016 if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) {
3020 error = swapongeom_locked(vp->v_rdev, vp);
3021 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) {
3046 bufobj_wdrop(bp->b_bufobj);
3047 bufobj_wref(&vp2->v_bufobj);
3049 if (bp->b_bufobj != &vp2->v_bufobj)
3050 bp->b_bufobj = &vp2->v_bufobj;
3052 bp->b_iooffset = dbtob(bp->b_blkno);
3058 swapdev_close(struct thread *td, struct swdevt *sp)
3061 VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
3066 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
3073 mtx_lock(&sw_dev_mtx);
3074 TAILQ_FOREACH(sp, &swtailq, sw_list) {
3075 if (sp->sw_id == vp) {
3076 mtx_unlock(&sw_dev_mtx);
3080 mtx_unlock(&sw_dev_mtx);
3082 (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3084 error = mac_system_check_swapon(td->td_ucred, vp);
3087 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
3088 (void) VOP_UNLOCK(vp);
3092 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
3098 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
3102 new = nsw_wcount_async_max;
3103 error = sysctl_handle_int(oidp, &new, 0, req);
3104 if (error != 0 || req->newptr == NULL)
3107 if (new > nswbuf / 2 || new < 1)
3110 mtx_lock(&swbuf_mtx);
3111 while (nsw_wcount_async_max != new) {
3113 * Adjust difference. If the current async count is too low,
3114 * we will need to sqeeze our update slowly in. Sleep with a
3115 * higher priority than getpbuf() to finish faster.
3117 n = new - nsw_wcount_async_max;
3118 if (nsw_wcount_async + n >= 0) {
3119 nsw_wcount_async += n;
3120 nsw_wcount_async_max += n;
3121 wakeup(&nsw_wcount_async);
3123 nsw_wcount_async_max -= nsw_wcount_async;
3124 nsw_wcount_async = 0;
3125 msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
3129 mtx_unlock(&swbuf_mtx);
3135 swap_pager_update_writecount(vm_object_t object, vm_offset_t start,
3139 VM_OBJECT_WLOCK(object);
3140 KASSERT((object->flags & OBJ_ANON) == 0,
3141 ("Splittable object with writecount"));
3142 object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
3143 VM_OBJECT_WUNLOCK(object);
3147 swap_pager_release_writecount(vm_object_t object, vm_offset_t start,
3151 VM_OBJECT_WLOCK(object);
3152 KASSERT((object->flags & OBJ_ANON) == 0,
3153 ("Splittable object with writecount"));
3154 object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
3155 VM_OBJECT_WUNLOCK(object);