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 static 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");
578 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
580 * Expected to be started from pageout process once, prior to entering
584 swap_pager_swap_init(void)
589 * Number of in-transit swap bp operations. Don't
590 * exhaust the pbufs completely. Make sure we
591 * initialize workable values (0 will work for hysteresis
592 * but it isn't very efficient).
594 * The nsw_cluster_max is constrained by the bp->b_pages[]
595 * array, which has maxphys / PAGE_SIZE entries, and our locally
596 * defined MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
597 * constrained by the swap device interleave stripe size.
599 * Currently we hardwire nsw_wcount_async to 4. This limit is
600 * designed to prevent other I/O from having high latencies due to
601 * our pageout I/O. The value 4 works well for one or two active swap
602 * devices but is probably a little low if you have more. Even so,
603 * a higher value would probably generate only a limited improvement
604 * with three or four active swap devices since the system does not
605 * typically have to pageout at extreme bandwidths. We will want
606 * at least 2 per swap devices, and 4 is a pretty good value if you
607 * have one NFS swap device due to the command/ack latency over NFS.
608 * So it all works out pretty well.
610 nsw_cluster_max = min(maxphys / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
612 nsw_wcount_async = 4;
613 nsw_wcount_async_max = nsw_wcount_async;
614 mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
616 swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
617 swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
620 * Initialize our zone, taking the user's requested size or
621 * estimating the number we need based on the number of pages
624 n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
625 vm_cnt.v_page_count / 2;
626 swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
627 pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0);
628 if (swpctrie_zone == NULL)
629 panic("failed to create swap pctrie zone.");
630 swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
631 NULL, NULL, _Alignof(struct swblk) - 1, 0);
632 if (swblk_zone == NULL)
633 panic("failed to create swap blk zone.");
636 if (uma_zone_reserve_kva(swblk_zone, n))
639 * if the allocation failed, try a zone two thirds the
640 * size of the previous attempt.
646 * Often uma_zone_reserve_kva() cannot reserve exactly the
647 * requested size. Account for the difference when
648 * calculating swap_maxpages.
650 n = uma_zone_get_max(swblk_zone);
653 printf("Swap blk zone entries changed from %lu to %lu.\n",
655 /* absolute maximum we can handle assuming 100% efficiency */
656 swap_maxpages = n * SWAP_META_PAGES;
657 swzone = n * sizeof(struct swblk);
658 if (!uma_zone_reserve_kva(swpctrie_zone, n))
659 printf("Cannot reserve swap pctrie zone, "
660 "reduce kern.maxswzone.\n");
664 swap_pager_init_object(vm_object_t object, void *handle, struct ucred *cred,
665 vm_ooffset_t size, vm_ooffset_t offset)
668 if (!swap_reserve_by_cred(size, cred))
673 object->un_pager.swp.writemappings = 0;
674 object->handle = handle;
677 object->charge = size;
683 swap_pager_alloc_init(objtype_t otype, void *handle, struct ucred *cred,
684 vm_ooffset_t size, vm_ooffset_t offset)
689 * The un_pager.swp.swp_blks trie is initialized by
690 * vm_object_allocate() to ensure the correct order of
691 * visibility to other threads.
693 object = vm_object_allocate(otype, OFF_TO_IDX(offset +
696 if (!swap_pager_init_object(object, handle, cred, size, offset)) {
697 vm_object_deallocate(object);
704 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
705 * its metadata structures.
707 * This routine is called from the mmap and fork code to create a new
710 * This routine must ensure that no live duplicate is created for
711 * the named object request, which is protected against by
712 * holding the sw_alloc_sx lock in case handle != NULL.
715 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
716 vm_ooffset_t offset, struct ucred *cred)
720 if (handle != NULL) {
722 * Reference existing named region or allocate new one. There
723 * should not be a race here against swp_pager_meta_build()
724 * as called from vm_page_remove() in regards to the lookup
727 sx_xlock(&sw_alloc_sx);
728 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
729 if (object == NULL) {
730 object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
732 if (object != NULL) {
733 TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
734 object, pager_object_list);
737 sx_xunlock(&sw_alloc_sx);
739 object = swap_pager_alloc_init(OBJT_SWAP, handle, cred,
746 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
748 * The swap backing for the object is destroyed. The code is
749 * designed such that we can reinstantiate it later, but this
750 * routine is typically called only when the entire object is
751 * about to be destroyed.
753 * The object must be locked.
756 swap_pager_dealloc(vm_object_t object)
759 VM_OBJECT_ASSERT_WLOCKED(object);
760 KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
763 * Remove from list right away so lookups will fail if we block for
764 * pageout completion.
766 if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
767 VM_OBJECT_WUNLOCK(object);
768 sx_xlock(&sw_alloc_sx);
769 TAILQ_REMOVE(NOBJLIST(object->handle), object,
771 sx_xunlock(&sw_alloc_sx);
772 VM_OBJECT_WLOCK(object);
775 vm_object_pip_wait(object, "swpdea");
778 * Free all remaining metadata. We only bother to free it from
779 * the swap meta data. We do not attempt to free swapblk's still
780 * associated with vm_page_t's for this object. We do not care
781 * if paging is still in progress on some objects.
783 swp_pager_meta_free_all(object);
784 object->handle = NULL;
785 object->type = OBJT_DEAD;
786 vm_object_clear_flag(object, OBJ_SWAP);
789 /************************************************************************
790 * SWAP PAGER BITMAP ROUTINES *
791 ************************************************************************/
794 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
796 * Allocate swap for up to the requested number of pages. The
797 * starting swap block number (a page index) is returned or
798 * SWAPBLK_NONE if the allocation failed.
800 * Also has the side effect of advising that somebody made a mistake
801 * when they configured swap and didn't configure enough.
803 * This routine may not sleep.
805 * We allocate in round-robin fashion from the configured devices.
808 swp_pager_getswapspace(int *io_npages)
814 KASSERT(*io_npages >= 1,
815 ("%s: npages not positive", __func__));
818 npages = imin(BLIST_MAX_ALLOC, mpages);
819 mtx_lock(&sw_dev_mtx);
821 while (!TAILQ_EMPTY(&swtailq)) {
823 sp = TAILQ_FIRST(&swtailq);
824 if ((sp->sw_flags & SW_CLOSING) == 0)
825 blk = blist_alloc(sp->sw_blist, &npages, mpages);
826 if (blk != SWAPBLK_NONE)
828 sp = TAILQ_NEXT(sp, sw_list);
836 if (blk != SWAPBLK_NONE) {
839 sp->sw_used += npages;
840 swap_pager_avail -= npages;
842 swdevhd = TAILQ_NEXT(sp, sw_list);
844 if (swap_pager_full != 2) {
845 printf("swp_pager_getswapspace(%d): failed\n",
848 swap_pager_almost_full = 1;
852 mtx_unlock(&sw_dev_mtx);
857 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
860 return (blk >= sp->sw_first && blk < sp->sw_end);
864 swp_pager_strategy(struct buf *bp)
868 mtx_lock(&sw_dev_mtx);
869 TAILQ_FOREACH(sp, &swtailq, sw_list) {
870 if (swp_pager_isondev(bp->b_blkno, sp)) {
871 mtx_unlock(&sw_dev_mtx);
872 if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
873 unmapped_buf_allowed) {
874 bp->b_data = unmapped_buf;
877 pmap_qenter((vm_offset_t)bp->b_data,
878 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
880 sp->sw_strategy(bp, sp);
884 panic("Swapdev not found");
888 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
890 * This routine returns the specified swap blocks back to the bitmap.
892 * This routine may not sleep.
895 swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
901 mtx_lock(&sw_dev_mtx);
902 TAILQ_FOREACH(sp, &swtailq, sw_list) {
903 if (swp_pager_isondev(blk, sp)) {
904 sp->sw_used -= npages;
906 * If we are attempting to stop swapping on
907 * this device, we don't want to mark any
908 * blocks free lest they be reused.
910 if ((sp->sw_flags & SW_CLOSING) == 0) {
911 blist_free(sp->sw_blist, blk - sp->sw_first,
913 swap_pager_avail += npages;
916 mtx_unlock(&sw_dev_mtx);
920 panic("Swapdev not found");
924 * SYSCTL_SWAP_FRAGMENTATION() - produce raw swap space stats
927 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
934 error = sysctl_wire_old_buffer(req, 0);
937 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
938 mtx_lock(&sw_dev_mtx);
939 TAILQ_FOREACH(sp, &swtailq, sw_list) {
940 if (vn_isdisk(sp->sw_vp))
941 devname = devtoname(sp->sw_vp->v_rdev);
944 sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
945 blist_stats(sp->sw_blist, &sbuf);
947 mtx_unlock(&sw_dev_mtx);
948 error = sbuf_finish(&sbuf);
954 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
955 * range within an object.
957 * This routine removes swapblk assignments from swap metadata.
959 * The external callers of this routine typically have already destroyed
960 * or renamed vm_page_t's associated with this range in the object so
963 * The object must be locked.
966 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
969 swp_pager_meta_free(object, start, size);
973 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
975 * Assigns swap blocks to the specified range within the object. The
976 * swap blocks are not zeroed. Any previous swap assignment is destroyed.
978 * Returns 0 on success, -1 on failure.
981 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_pindex_t size)
983 daddr_t addr, blk, n_free, s_free;
987 swp_pager_init_freerange(&s_free, &n_free);
988 VM_OBJECT_WLOCK(object);
989 for (i = 0; i < size; i += n) {
990 n = MIN(size - i, INT_MAX);
991 blk = swp_pager_getswapspace(&n);
992 if (blk == SWAPBLK_NONE) {
993 swp_pager_meta_free(object, start, i);
994 VM_OBJECT_WUNLOCK(object);
997 for (j = 0; j < n; ++j) {
998 addr = swp_pager_meta_build(object,
999 start + i + j, blk + j);
1000 if (addr != SWAPBLK_NONE)
1001 swp_pager_update_freerange(&s_free, &n_free,
1005 swp_pager_freeswapspace(s_free, n_free);
1006 VM_OBJECT_WUNLOCK(object);
1011 swp_pager_xfer_source(vm_object_t srcobject, vm_object_t dstobject,
1012 vm_pindex_t pindex, daddr_t addr)
1016 KASSERT((srcobject->flags & OBJ_SWAP) != 0,
1017 ("%s: Srcobject not swappable", __func__));
1018 if ((dstobject->flags & OBJ_SWAP) != 0 &&
1019 swp_pager_meta_lookup(dstobject, pindex) != SWAPBLK_NONE) {
1020 /* Caller should destroy the source block. */
1025 * Destination has no swapblk and is not resident, transfer source.
1026 * swp_pager_meta_build() can sleep.
1028 VM_OBJECT_WUNLOCK(srcobject);
1029 dstaddr = swp_pager_meta_build(dstobject, pindex, addr);
1030 KASSERT(dstaddr == SWAPBLK_NONE,
1031 ("Unexpected destination swapblk"));
1032 VM_OBJECT_WLOCK(srcobject);
1038 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
1039 * and destroy the source.
1041 * Copy any valid swapblks from the source to the destination. In
1042 * cases where both the source and destination have a valid swapblk,
1043 * we keep the destination's.
1045 * This routine is allowed to sleep. It may sleep allocating metadata
1046 * indirectly through swp_pager_meta_build().
1048 * The source object contains no vm_page_t's (which is just as well)
1050 * The source object is of type OBJT_SWAP.
1052 * The source and destination objects must be locked.
1053 * Both object locks may temporarily be released.
1056 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
1057 vm_pindex_t offset, int destroysource)
1060 VM_OBJECT_ASSERT_WLOCKED(srcobject);
1061 VM_OBJECT_ASSERT_WLOCKED(dstobject);
1064 * If destroysource is set, we remove the source object from the
1065 * swap_pager internal queue now.
1067 if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
1068 srcobject->handle != NULL) {
1069 VM_OBJECT_WUNLOCK(srcobject);
1070 VM_OBJECT_WUNLOCK(dstobject);
1071 sx_xlock(&sw_alloc_sx);
1072 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1074 sx_xunlock(&sw_alloc_sx);
1075 VM_OBJECT_WLOCK(dstobject);
1076 VM_OBJECT_WLOCK(srcobject);
1080 * Transfer source to destination.
1082 swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size);
1085 * Free left over swap blocks in source.
1087 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
1088 * double-remove the object from the swap queues.
1090 if (destroysource) {
1091 swp_pager_meta_free_all(srcobject);
1093 * Reverting the type is not necessary, the caller is going
1094 * to destroy srcobject directly, but I'm doing it here
1095 * for consistency since we've removed the object from its
1098 srcobject->type = OBJT_DEFAULT;
1099 vm_object_clear_flag(srcobject, OBJ_SWAP);
1104 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
1105 * the requested page.
1107 * We determine whether good backing store exists for the requested
1108 * page and return TRUE if it does, FALSE if it doesn't.
1110 * If TRUE, we also try to determine how much valid, contiguous backing
1111 * store exists before and after the requested page.
1114 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1120 VM_OBJECT_ASSERT_LOCKED(object);
1121 KASSERT((object->flags & OBJ_SWAP) != 0,
1122 ("%s: object not swappable", __func__));
1125 * do we have good backing store at the requested index ?
1127 blk0 = swp_pager_meta_lookup(object, pindex);
1128 if (blk0 == SWAPBLK_NONE) {
1137 * find backwards-looking contiguous good backing store
1139 if (before != NULL) {
1140 for (i = 1; i < SWB_NPAGES; i++) {
1143 blk = swp_pager_meta_lookup(object, pindex - i);
1144 if (blk != blk0 - i)
1151 * find forward-looking contiguous good backing store
1153 if (after != NULL) {
1154 for (i = 1; i < SWB_NPAGES; i++) {
1155 blk = swp_pager_meta_lookup(object, pindex + i);
1156 if (blk != blk0 + i)
1165 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1167 * This removes any associated swap backing store, whether valid or
1168 * not, from the page.
1170 * This routine is typically called when a page is made dirty, at
1171 * which point any associated swap can be freed. MADV_FREE also
1172 * calls us in a special-case situation
1174 * NOTE!!! If the page is clean and the swap was valid, the caller
1175 * should make the page dirty before calling this routine. This routine
1176 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1179 * This routine may not sleep.
1181 * The object containing the page may be locked.
1184 swap_pager_unswapped(vm_page_t m)
1190 * Handle enqueing deferred frees first. If we do not have the
1191 * object lock we wait for the page daemon to clear the space.
1194 if (!VM_OBJECT_WOWNED(obj)) {
1195 VM_PAGE_OBJECT_BUSY_ASSERT(m);
1197 * The caller is responsible for synchronization but we
1198 * will harmlessly handle races. This is typically provided
1199 * by only calling unswapped() when a page transitions from
1202 if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1204 vm_page_aflag_set(m, PGA_SWAP_FREE);
1205 counter_u64_add(swap_free_deferred, 1);
1209 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1210 counter_u64_add(swap_free_completed, 1);
1211 vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
1214 * The meta data only exists if the object is OBJT_SWAP
1215 * and even then might not be allocated yet.
1217 KASSERT((m->object->flags & OBJ_SWAP) != 0,
1218 ("Free object not swappable"));
1220 sb = SWAP_PCTRIE_LOOKUP(&m->object->un_pager.swp.swp_blks,
1221 rounddown(m->pindex, SWAP_META_PAGES));
1224 if (sb->d[m->pindex % SWAP_META_PAGES] == SWAPBLK_NONE)
1226 swp_pager_freeswapspace(sb->d[m->pindex % SWAP_META_PAGES], 1);
1227 sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
1228 swp_pager_free_empty_swblk(m->object, sb);
1232 * swap_pager_getpages() - bring pages in from swap
1234 * Attempt to page in the pages in array "ma" of length "count". The
1235 * caller may optionally specify that additional pages preceding and
1236 * succeeding the specified range be paged in. The number of such pages
1237 * is returned in the "rbehind" and "rahead" parameters, and they will
1238 * be in the inactive queue upon return.
1240 * The pages in "ma" must be busied and will remain busied upon return.
1243 swap_pager_getpages_locked(vm_object_t object, vm_page_t *ma, int count,
1244 int *rbehind, int *rahead)
1247 vm_page_t bm, mpred, msucc, p;
1250 int i, maxahead, maxbehind, reqcount;
1252 VM_OBJECT_ASSERT_WLOCKED(object);
1255 KASSERT((object->flags & OBJ_SWAP) != 0,
1256 ("%s: object not swappable", __func__));
1257 if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead)) {
1258 VM_OBJECT_WUNLOCK(object);
1259 return (VM_PAGER_FAIL);
1262 KASSERT(reqcount - 1 <= maxahead,
1263 ("page count %d extends beyond swap block", reqcount));
1266 * Do not transfer any pages other than those that are xbusied
1267 * when running during a split or collapse operation. This
1268 * prevents clustering from re-creating pages which are being
1269 * moved into another object.
1271 if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
1272 maxahead = reqcount - 1;
1277 * Clip the readahead and readbehind ranges to exclude resident pages.
1279 if (rahead != NULL) {
1280 *rahead = imin(*rahead, maxahead - (reqcount - 1));
1281 pindex = ma[reqcount - 1]->pindex;
1282 msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1283 if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1284 *rahead = msucc->pindex - pindex - 1;
1286 if (rbehind != NULL) {
1287 *rbehind = imin(*rbehind, maxbehind);
1288 pindex = ma[0]->pindex;
1289 mpred = TAILQ_PREV(ma[0], pglist, listq);
1290 if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1291 *rbehind = pindex - mpred->pindex - 1;
1295 for (i = 0; i < count; i++)
1296 ma[i]->oflags |= VPO_SWAPINPROG;
1299 * Allocate readahead and readbehind pages.
1301 if (rbehind != NULL) {
1302 for (i = 1; i <= *rbehind; i++) {
1303 p = vm_page_alloc(object, ma[0]->pindex - i,
1307 p->oflags |= VPO_SWAPINPROG;
1312 if (rahead != NULL) {
1313 for (i = 0; i < *rahead; i++) {
1314 p = vm_page_alloc(object,
1315 ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1318 p->oflags |= VPO_SWAPINPROG;
1322 if (rbehind != NULL)
1327 vm_object_pip_add(object, count);
1329 pindex = bm->pindex;
1330 blk = swp_pager_meta_lookup(object, pindex);
1331 KASSERT(blk != SWAPBLK_NONE,
1332 ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1334 VM_OBJECT_WUNLOCK(object);
1335 bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1336 MPASS((bp->b_flags & B_MAXPHYS) != 0);
1337 /* Pages cannot leave the object while busy. */
1338 for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1339 MPASS(p->pindex == bm->pindex + i);
1343 bp->b_flags |= B_PAGING;
1344 bp->b_iocmd = BIO_READ;
1345 bp->b_iodone = swp_pager_async_iodone;
1346 bp->b_rcred = crhold(thread0.td_ucred);
1347 bp->b_wcred = crhold(thread0.td_ucred);
1349 bp->b_bcount = PAGE_SIZE * count;
1350 bp->b_bufsize = PAGE_SIZE * count;
1351 bp->b_npages = count;
1352 bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1353 bp->b_pgafter = rahead != NULL ? *rahead : 0;
1355 VM_CNT_INC(v_swapin);
1356 VM_CNT_ADD(v_swappgsin, count);
1359 * perform the I/O. NOTE!!! bp cannot be considered valid after
1360 * this point because we automatically release it on completion.
1361 * Instead, we look at the one page we are interested in which we
1362 * still hold a lock on even through the I/O completion.
1364 * The other pages in our ma[] array are also released on completion,
1365 * so we cannot assume they are valid anymore either.
1367 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1370 swp_pager_strategy(bp);
1373 * Wait for the pages we want to complete. VPO_SWAPINPROG is always
1374 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1375 * is set in the metadata for each page in the request.
1377 VM_OBJECT_WLOCK(object);
1378 /* This could be implemented more efficiently with aflags */
1379 while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
1380 ma[0]->oflags |= VPO_SWAPSLEEP;
1381 VM_CNT_INC(v_intrans);
1382 if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1383 "swread", hz * 20)) {
1385 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1386 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1389 VM_OBJECT_WUNLOCK(object);
1392 * If we had an unrecoverable read error pages will not be valid.
1394 for (i = 0; i < reqcount; i++)
1395 if (ma[i]->valid != VM_PAGE_BITS_ALL)
1396 return (VM_PAGER_ERROR);
1398 return (VM_PAGER_OK);
1401 * A final note: in a low swap situation, we cannot deallocate swap
1402 * and mark a page dirty here because the caller is likely to mark
1403 * the page clean when we return, causing the page to possibly revert
1404 * to all-zero's later.
1409 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count,
1410 int *rbehind, int *rahead)
1413 VM_OBJECT_WLOCK(object);
1414 return (swap_pager_getpages_locked(object, ma, count, rbehind, rahead));
1418 * swap_pager_getpages_async():
1420 * Right now this is emulation of asynchronous operation on top of
1421 * swap_pager_getpages().
1424 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1425 int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1429 r = swap_pager_getpages(object, ma, count, rbehind, rahead);
1434 case VM_PAGER_ERROR:
1441 panic("unhandled swap_pager_getpages() error %d", r);
1443 (iodone)(arg, ma, count, error);
1449 * swap_pager_putpages:
1451 * Assign swap (if necessary) and initiate I/O on the specified pages.
1453 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1454 * are automatically converted to SWAP objects.
1456 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1457 * vm_page reservation system coupled with properly written VFS devices
1458 * should ensure that no low-memory deadlock occurs. This is an area
1461 * The parent has N vm_object_pip_add() references prior to
1462 * calling us and will remove references for rtvals[] that are
1463 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1466 * The parent has soft-busy'd the pages it passes us and will unbusy
1467 * those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
1468 * We need to unbusy the rest on I/O completion.
1471 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1472 int flags, int *rtvals)
1475 daddr_t addr, blk, n_free, s_free;
1480 KASSERT(count == 0 || ma[0]->object == object,
1481 ("%s: object mismatch %p/%p",
1482 __func__, object, ma[0]->object));
1487 * Turn object into OBJT_SWAP. Force sync if not a pageout process.
1489 if ((object->flags & OBJ_SWAP) == 0) {
1490 addr = swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1491 KASSERT(addr == SWAPBLK_NONE,
1492 ("unexpected object swap block"));
1494 VM_OBJECT_WUNLOCK(object);
1495 async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
1496 swp_pager_init_freerange(&s_free, &n_free);
1501 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1502 * The page is left dirty until the pageout operation completes
1505 for (i = 0; i < count; i += n) {
1506 /* Maximum I/O size is limited by maximum swap block size. */
1507 n = min(count - i, nsw_cluster_max);
1510 mtx_lock(&swbuf_mtx);
1511 while (nsw_wcount_async == 0)
1512 msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1515 mtx_unlock(&swbuf_mtx);
1518 /* Get a block of swap of size up to size n. */
1519 VM_OBJECT_WLOCK(object);
1520 blk = swp_pager_getswapspace(&n);
1521 if (blk == SWAPBLK_NONE) {
1522 VM_OBJECT_WUNLOCK(object);
1523 mtx_lock(&swbuf_mtx);
1524 if (++nsw_wcount_async == 1)
1525 wakeup(&nsw_wcount_async);
1526 mtx_unlock(&swbuf_mtx);
1527 for (j = 0; j < n; ++j)
1528 rtvals[i + j] = VM_PAGER_FAIL;
1531 for (j = 0; j < n; ++j) {
1533 vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1534 addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1536 if (addr != SWAPBLK_NONE)
1537 swp_pager_update_freerange(&s_free, &n_free,
1539 MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1540 mreq->oflags |= VPO_SWAPINPROG;
1542 VM_OBJECT_WUNLOCK(object);
1544 bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1545 MPASS((bp->b_flags & B_MAXPHYS) != 0);
1547 bp->b_flags |= B_ASYNC;
1548 bp->b_flags |= B_PAGING;
1549 bp->b_iocmd = BIO_WRITE;
1551 bp->b_rcred = crhold(thread0.td_ucred);
1552 bp->b_wcred = crhold(thread0.td_ucred);
1553 bp->b_bcount = PAGE_SIZE * n;
1554 bp->b_bufsize = PAGE_SIZE * n;
1556 for (j = 0; j < n; j++)
1557 bp->b_pages[j] = ma[i + j];
1561 * Must set dirty range for NFS to work.
1564 bp->b_dirtyend = bp->b_bcount;
1566 VM_CNT_INC(v_swapout);
1567 VM_CNT_ADD(v_swappgsout, bp->b_npages);
1570 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1571 * can call the async completion routine at the end of a
1572 * synchronous I/O operation. Otherwise, our caller would
1573 * perform duplicate unbusy and wakeup operations on the page
1574 * and object, respectively.
1576 for (j = 0; j < n; j++)
1577 rtvals[i + j] = VM_PAGER_PEND;
1582 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1585 bp->b_iodone = swp_pager_async_iodone;
1587 swp_pager_strategy(bp);
1594 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1596 bp->b_iodone = bdone;
1597 swp_pager_strategy(bp);
1600 * Wait for the sync I/O to complete.
1602 bwait(bp, PVM, "swwrt");
1605 * Now that we are through with the bp, we can call the
1606 * normal async completion, which frees everything up.
1608 swp_pager_async_iodone(bp);
1610 swp_pager_freeswapspace(s_free, n_free);
1611 VM_OBJECT_WLOCK(object);
1615 * swp_pager_async_iodone:
1617 * Completion routine for asynchronous reads and writes from/to swap.
1618 * Also called manually by synchronous code to finish up a bp.
1620 * This routine may not sleep.
1623 swp_pager_async_iodone(struct buf *bp)
1626 vm_object_t object = NULL;
1629 * Report error - unless we ran out of memory, in which case
1630 * we've already logged it in swapgeom_strategy().
1632 if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
1634 "swap_pager: I/O error - %s failed; blkno %ld,"
1635 "size %ld, error %d\n",
1636 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1644 * remove the mapping for kernel virtual
1647 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1649 bp->b_data = bp->b_kvabase;
1652 object = bp->b_pages[0]->object;
1653 VM_OBJECT_WLOCK(object);
1657 * cleanup pages. If an error occurs writing to swap, we are in
1658 * very serious trouble. If it happens to be a disk error, though,
1659 * we may be able to recover by reassigning the swap later on. So
1660 * in this case we remove the m->swapblk assignment for the page
1661 * but do not free it in the rlist. The errornous block(s) are thus
1662 * never reallocated as swap. Redirty the page and continue.
1664 for (i = 0; i < bp->b_npages; ++i) {
1665 vm_page_t m = bp->b_pages[i];
1667 m->oflags &= ~VPO_SWAPINPROG;
1668 if (m->oflags & VPO_SWAPSLEEP) {
1669 m->oflags &= ~VPO_SWAPSLEEP;
1670 wakeup(&object->handle);
1673 /* We always have space after I/O, successful or not. */
1674 vm_page_aflag_set(m, PGA_SWAP_SPACE);
1676 if (bp->b_ioflags & BIO_ERROR) {
1678 * If an error occurs I'd love to throw the swapblk
1679 * away without freeing it back to swapspace, so it
1680 * can never be used again. But I can't from an
1683 if (bp->b_iocmd == BIO_READ) {
1685 * NOTE: for reads, m->dirty will probably
1686 * be overridden by the original caller of
1687 * getpages so don't play cute tricks here.
1692 * If a write error occurs, reactivate page
1693 * so it doesn't clog the inactive list,
1694 * then finish the I/O.
1696 MPASS(m->dirty == VM_PAGE_BITS_ALL);
1698 /* PQ_UNSWAPPABLE? */
1699 vm_page_activate(m);
1702 } else if (bp->b_iocmd == BIO_READ) {
1704 * NOTE: for reads, m->dirty will probably be
1705 * overridden by the original caller of getpages so
1706 * we cannot set them in order to free the underlying
1707 * swap in a low-swap situation. I don't think we'd
1708 * want to do that anyway, but it was an optimization
1709 * that existed in the old swapper for a time before
1710 * it got ripped out due to precisely this problem.
1712 KASSERT(!pmap_page_is_mapped(m),
1713 ("swp_pager_async_iodone: page %p is mapped", m));
1714 KASSERT(m->dirty == 0,
1715 ("swp_pager_async_iodone: page %p is dirty", m));
1718 if (i < bp->b_pgbefore ||
1719 i >= bp->b_npages - bp->b_pgafter)
1720 vm_page_readahead_finish(m);
1723 * For write success, clear the dirty
1724 * status, then finish the I/O ( which decrements the
1725 * busy count and possibly wakes waiter's up ).
1726 * A page is only written to swap after a period of
1727 * inactivity. Therefore, we do not expect it to be
1730 KASSERT(!pmap_page_is_write_mapped(m),
1731 ("swp_pager_async_iodone: page %p is not write"
1734 vm_page_deactivate_noreuse(m);
1740 * adjust pip. NOTE: the original parent may still have its own
1741 * pip refs on the object.
1743 if (object != NULL) {
1744 vm_object_pip_wakeupn(object, bp->b_npages);
1745 VM_OBJECT_WUNLOCK(object);
1749 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1750 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1751 * trigger a KASSERT in relpbuf().
1755 bp->b_bufobj = NULL;
1758 * release the physical I/O buffer
1760 if (bp->b_flags & B_ASYNC) {
1761 mtx_lock(&swbuf_mtx);
1762 if (++nsw_wcount_async == 1)
1763 wakeup(&nsw_wcount_async);
1764 mtx_unlock(&swbuf_mtx);
1766 uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
1770 swap_pager_nswapdev(void)
1777 swp_pager_force_dirty(vm_page_t m)
1781 swap_pager_unswapped(m);
1786 swap_pager_swapped_pages(vm_object_t object)
1793 VM_OBJECT_ASSERT_LOCKED(object);
1794 if ((object->flags & OBJ_SWAP) == 0)
1797 for (res = 0, pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1798 &object->un_pager.swp.swp_blks, pi)) != NULL;
1799 pi = sb->p + SWAP_META_PAGES) {
1800 for (i = 0; i < SWAP_META_PAGES; i++) {
1801 if (sb->d[i] != SWAPBLK_NONE)
1809 * swap_pager_swapoff_object:
1811 * Page in all of the pages that have been paged out for an object
1815 swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
1821 int i, nv, rahead, rv;
1823 KASSERT((object->flags & OBJ_SWAP) != 0,
1824 ("%s: Object not swappable", __func__));
1826 for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1827 &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1828 if ((object->flags & OBJ_DEAD) != 0) {
1830 * Make sure that pending writes finish before
1833 vm_object_pip_wait(object, "swpoff");
1834 swp_pager_meta_free_all(object);
1837 for (i = 0; i < SWAP_META_PAGES; i++) {
1839 * Count the number of contiguous valid blocks.
1841 for (nv = 0; nv < SWAP_META_PAGES - i; nv++) {
1842 blk = sb->d[i + nv];
1843 if (!swp_pager_isondev(blk, sp) ||
1844 blk == SWAPBLK_NONE)
1851 * Look for a page corresponding to the first
1852 * valid block and ensure that any pending paging
1853 * operations on it are complete. If the page is valid,
1854 * mark it dirty and free the swap block. Try to batch
1855 * this operation since it may cause sp to be freed,
1856 * meaning that we must restart the scan. Avoid busying
1857 * valid pages since we may block forever on kernel
1860 m = vm_page_lookup(object, sb->p + i);
1862 m = vm_page_alloc(object, sb->p + i,
1863 VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
1867 if ((m->oflags & VPO_SWAPINPROG) != 0) {
1868 m->oflags |= VPO_SWAPSLEEP;
1869 VM_OBJECT_SLEEP(object, &object->handle,
1873 if (vm_page_all_valid(m)) {
1875 swp_pager_force_dirty(m);
1876 } while (--nv > 0 &&
1877 (m = vm_page_next(m)) != NULL &&
1878 vm_page_all_valid(m) &&
1879 (m->oflags & VPO_SWAPINPROG) == 0);
1882 if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL))
1886 vm_object_pip_add(object, 1);
1887 rahead = SWAP_META_PAGES;
1888 rv = swap_pager_getpages_locked(object, &m, 1, NULL,
1890 if (rv != VM_PAGER_OK)
1891 panic("%s: read from swap failed: %d",
1893 vm_object_pip_wakeupn(object, 1);
1894 VM_OBJECT_WLOCK(object);
1898 * The object lock was dropped so we must restart the
1899 * scan of this swap block. Pages paged in during this
1900 * iteration will be marked dirty in a future iteration.
1904 if (i == SWAP_META_PAGES)
1905 pi = sb->p + SWAP_META_PAGES;
1910 * swap_pager_swapoff:
1912 * Page in all of the pages that have been paged out to the
1913 * given device. The corresponding blocks in the bitmap must be
1914 * marked as allocated and the device must be flagged SW_CLOSING.
1915 * There may be no processes swapped out to the device.
1917 * This routine may block.
1920 swap_pager_swapoff(struct swdevt *sp)
1925 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1929 mtx_lock(&vm_object_list_mtx);
1930 TAILQ_FOREACH(object, &vm_object_list, object_list) {
1931 if ((object->flags & OBJ_SWAP) == 0)
1933 mtx_unlock(&vm_object_list_mtx);
1934 /* Depends on type-stability. */
1935 VM_OBJECT_WLOCK(object);
1938 * Dead objects are eventually terminated on their own.
1940 if ((object->flags & OBJ_DEAD) != 0)
1944 * Sync with fences placed after pctrie
1945 * initialization. We must not access pctrie below
1946 * unless we checked that our object is swap and not
1949 atomic_thread_fence_acq();
1950 if ((object->flags & OBJ_SWAP) == 0)
1953 swap_pager_swapoff_object(sp, object);
1955 VM_OBJECT_WUNLOCK(object);
1956 mtx_lock(&vm_object_list_mtx);
1958 mtx_unlock(&vm_object_list_mtx);
1962 * Objects may be locked or paging to the device being
1963 * removed, so we will miss their pages and need to
1964 * make another pass. We have marked this device as
1965 * SW_CLOSING, so the activity should finish soon.
1968 if (retries > 100) {
1969 panic("swapoff: failed to locate %d swap blocks",
1972 pause("swpoff", hz / 20);
1975 EVENTHANDLER_INVOKE(swapoff, sp);
1978 /************************************************************************
1980 ************************************************************************
1982 * These routines manipulate the swap metadata stored in the
1985 * Swap metadata is implemented with a global hash and not directly
1986 * linked into the object. Instead the object simply contains
1987 * appropriate tracking counters.
1991 * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
1994 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
1998 MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
1999 for (i = start; i < limit; i++) {
2000 if (sb->d[i] != SWAPBLK_NONE)
2007 * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
2009 * Nothing is done if the block is still in use.
2012 swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
2015 if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
2016 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2017 uma_zfree(swblk_zone, sb);
2022 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
2024 * We first convert the object to a swap object if it is a default
2027 * The specified swapblk is added to the object's swap metadata. If
2028 * the swapblk is not valid, it is freed instead. Any previously
2029 * assigned swapblk is returned.
2032 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
2034 static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
2035 struct swblk *sb, *sb1;
2036 vm_pindex_t modpi, rdpi;
2037 daddr_t prev_swapblk;
2040 VM_OBJECT_ASSERT_WLOCKED(object);
2043 * Convert default object to swap object if necessary
2045 if ((object->flags & OBJ_SWAP) == 0) {
2046 pctrie_init(&object->un_pager.swp.swp_blks);
2049 * Ensure that swap_pager_swapoff()'s iteration over
2050 * object_list does not see a garbage pctrie.
2052 atomic_thread_fence_rel();
2054 object->type = OBJT_SWAP;
2055 vm_object_set_flag(object, OBJ_SWAP);
2056 object->un_pager.swp.writemappings = 0;
2057 KASSERT((object->flags & OBJ_ANON) != 0 ||
2058 object->handle == NULL,
2059 ("default pager %p with handle %p",
2060 object, object->handle));
2063 rdpi = rounddown(pindex, SWAP_META_PAGES);
2064 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
2066 if (swapblk == SWAPBLK_NONE)
2067 return (SWAPBLK_NONE);
2069 sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
2070 pageproc ? M_USE_RESERVE : 0));
2073 for (i = 0; i < SWAP_META_PAGES; i++)
2074 sb->d[i] = SWAPBLK_NONE;
2075 if (atomic_cmpset_int(&swblk_zone_exhausted,
2077 printf("swblk zone ok\n");
2080 VM_OBJECT_WUNLOCK(object);
2081 if (uma_zone_exhausted(swblk_zone)) {
2082 if (atomic_cmpset_int(&swblk_zone_exhausted,
2084 printf("swap blk zone exhausted, "
2085 "increase kern.maxswzone\n");
2086 vm_pageout_oom(VM_OOM_SWAPZ);
2087 pause("swzonxb", 10);
2089 uma_zwait(swblk_zone);
2090 VM_OBJECT_WLOCK(object);
2091 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2095 * Somebody swapped out a nearby page,
2096 * allocating swblk at the rdpi index,
2097 * while we dropped the object lock.
2102 error = SWAP_PCTRIE_INSERT(
2103 &object->un_pager.swp.swp_blks, sb);
2105 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2107 printf("swpctrie zone ok\n");
2110 VM_OBJECT_WUNLOCK(object);
2111 if (uma_zone_exhausted(swpctrie_zone)) {
2112 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2114 printf("swap pctrie zone exhausted, "
2115 "increase kern.maxswzone\n");
2116 vm_pageout_oom(VM_OOM_SWAPZ);
2117 pause("swzonxp", 10);
2119 uma_zwait(swpctrie_zone);
2120 VM_OBJECT_WLOCK(object);
2121 sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2124 uma_zfree(swblk_zone, sb);
2131 MPASS(sb->p == rdpi);
2133 modpi = pindex % SWAP_META_PAGES;
2134 /* Return prior contents of metadata. */
2135 prev_swapblk = sb->d[modpi];
2136 /* Enter block into metadata. */
2137 sb->d[modpi] = swapblk;
2140 * Free the swblk if we end up with the empty page run.
2142 if (swapblk == SWAPBLK_NONE)
2143 swp_pager_free_empty_swblk(object, sb);
2144 return (prev_swapblk);
2148 * SWP_PAGER_META_TRANSFER() - free a range of blocks in the srcobject's swap
2149 * metadata, or transfer it into dstobject.
2151 * This routine will free swap metadata structures as they are cleaned
2155 swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
2156 vm_pindex_t pindex, vm_pindex_t count)
2159 daddr_t n_free, s_free;
2160 vm_pindex_t offset, last;
2161 int i, limit, start;
2163 VM_OBJECT_ASSERT_WLOCKED(srcobject);
2164 if ((srcobject->flags & OBJ_SWAP) == 0 || count == 0)
2167 swp_pager_init_freerange(&s_free, &n_free);
2169 last = pindex + count;
2171 sb = SWAP_PCTRIE_LOOKUP_GE(&srcobject->un_pager.swp.swp_blks,
2172 rounddown(pindex, SWAP_META_PAGES));
2173 if (sb == NULL || sb->p >= last)
2175 start = pindex > sb->p ? pindex - sb->p : 0;
2176 limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2178 for (i = start; i < limit; i++) {
2179 if (sb->d[i] == SWAPBLK_NONE)
2181 if (dstobject == NULL ||
2182 !swp_pager_xfer_source(srcobject, dstobject,
2183 sb->p + i - offset, sb->d[i])) {
2184 swp_pager_update_freerange(&s_free, &n_free,
2187 sb->d[i] = SWAPBLK_NONE;
2189 pindex = sb->p + SWAP_META_PAGES;
2190 if (swp_pager_swblk_empty(sb, 0, start) &&
2191 swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2192 SWAP_PCTRIE_REMOVE(&srcobject->un_pager.swp.swp_blks,
2194 uma_zfree(swblk_zone, sb);
2197 swp_pager_freeswapspace(s_free, n_free);
2201 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
2203 * The requested range of blocks is freed, with any associated swap
2204 * returned to the swap bitmap.
2206 * This routine will free swap metadata structures as they are cleaned
2207 * out. This routine does *NOT* operate on swap metadata associated
2208 * with resident pages.
2211 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count)
2213 swp_pager_meta_transfer(object, NULL, pindex, count);
2217 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
2219 * This routine locates and destroys all swap metadata associated with
2223 swp_pager_meta_free_all(vm_object_t object)
2226 daddr_t n_free, s_free;
2230 VM_OBJECT_ASSERT_WLOCKED(object);
2231 if ((object->flags & OBJ_SWAP) == 0)
2234 swp_pager_init_freerange(&s_free, &n_free);
2235 for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
2236 &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
2237 pindex = sb->p + SWAP_META_PAGES;
2238 for (i = 0; i < SWAP_META_PAGES; i++) {
2239 if (sb->d[i] == SWAPBLK_NONE)
2241 swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
2243 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2244 uma_zfree(swblk_zone, sb);
2246 swp_pager_freeswapspace(s_free, n_free);
2250 * SWP_PAGER_METACTL() - misc control of swap meta data.
2252 * This routine is capable of looking up, or removing swapblk
2253 * assignments in the swap meta data. It returns the swapblk being
2254 * looked-up, popped, or SWAPBLK_NONE if the block was invalid.
2256 * When acting on a busy resident page and paging is in progress, we
2257 * have to wait until paging is complete but otherwise can act on the
2261 swp_pager_meta_lookup(vm_object_t object, vm_pindex_t pindex)
2265 VM_OBJECT_ASSERT_LOCKED(object);
2268 * The meta data only exists if the object is OBJT_SWAP
2269 * and even then might not be allocated yet.
2271 KASSERT((object->flags & OBJ_SWAP) != 0,
2272 ("Lookup object not swappable"));
2274 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2275 rounddown(pindex, SWAP_META_PAGES));
2277 return (SWAPBLK_NONE);
2278 return (sb->d[pindex % SWAP_META_PAGES]);
2282 * Returns the least page index which is greater than or equal to the
2283 * parameter pindex and for which there is a swap block allocated.
2284 * Returns object's size if the object's type is not swap or if there
2285 * are no allocated swap blocks for the object after the requested
2289 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2294 VM_OBJECT_ASSERT_LOCKED(object);
2295 if ((object->flags & OBJ_SWAP) == 0)
2296 return (object->size);
2298 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2299 rounddown(pindex, SWAP_META_PAGES));
2301 return (object->size);
2302 if (sb->p < pindex) {
2303 for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2304 if (sb->d[i] != SWAPBLK_NONE)
2307 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2308 roundup(pindex, SWAP_META_PAGES));
2310 return (object->size);
2312 for (i = 0; i < SWAP_META_PAGES; i++) {
2313 if (sb->d[i] != SWAPBLK_NONE)
2318 * We get here if a swblk is present in the trie but it
2319 * doesn't map any blocks.
2322 return (object->size);
2326 * System call swapon(name) enables swapping on device name,
2327 * which must be in the swdevsw. Return EBUSY
2328 * if already swapping on this device.
2330 #ifndef _SYS_SYSPROTO_H_
2331 struct swapon_args {
2341 sys_swapon(struct thread *td, struct swapon_args *uap)
2345 struct nameidata nd;
2348 error = priv_check(td, PRIV_SWAPON);
2352 sx_xlock(&swdev_syscall_lock);
2355 * Swap metadata may not fit in the KVM if we have physical
2358 if (swblk_zone == NULL) {
2363 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2369 NDFREE(&nd, NDF_ONLY_PNBUF);
2372 if (vn_isdisk_error(vp, &error)) {
2373 error = swapongeom(vp);
2374 } else if (vp->v_type == VREG &&
2375 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2376 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2378 * Allow direct swapping to NFS regular files in the same
2379 * way that nfs_mountroot() sets up diskless swapping.
2381 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2387 sx_xunlock(&swdev_syscall_lock);
2392 * Check that the total amount of swap currently configured does not
2393 * exceed half the theoretical maximum. If it does, print a warning
2397 swapon_check_swzone(void)
2400 /* recommend using no more than half that amount */
2401 if (swap_total > swap_maxpages / 2) {
2402 printf("warning: total configured swap (%lu pages) "
2403 "exceeds maximum recommended amount (%lu pages).\n",
2404 swap_total, swap_maxpages / 2);
2405 printf("warning: increase kern.maxswzone "
2406 "or reduce amount of swap.\n");
2411 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2412 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2414 struct swdevt *sp, *tsp;
2418 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2419 * First chop nblks off to page-align it, then convert.
2421 * sw->sw_nblks is in page-sized chunks now too.
2423 nblks &= ~(ctodb(1) - 1);
2424 nblks = dbtoc(nblks);
2426 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2427 sp->sw_blist = blist_create(nblks, M_WAITOK);
2431 sp->sw_nblks = nblks;
2433 sp->sw_strategy = strategy;
2434 sp->sw_close = close;
2435 sp->sw_flags = flags;
2438 * Do not free the first blocks in order to avoid overwriting
2439 * any bsd label at the front of the partition
2441 blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2442 nblks - howmany(BBSIZE, PAGE_SIZE));
2445 mtx_lock(&sw_dev_mtx);
2446 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2447 if (tsp->sw_end >= dvbase) {
2449 * We put one uncovered page between the devices
2450 * in order to definitively prevent any cross-device
2453 dvbase = tsp->sw_end + 1;
2456 sp->sw_first = dvbase;
2457 sp->sw_end = dvbase + nblks;
2458 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2460 swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2461 swap_total += nblks;
2462 swapon_check_swzone();
2464 mtx_unlock(&sw_dev_mtx);
2465 EVENTHANDLER_INVOKE(swapon, sp);
2469 * SYSCALL: swapoff(devname)
2471 * Disable swapping on the given device.
2473 * XXX: Badly designed system call: it should use a device index
2474 * rather than filename as specification. We keep sw_vp around
2475 * only to make this work.
2477 #ifndef _SYS_SYSPROTO_H_
2478 struct swapoff_args {
2488 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2491 struct nameidata nd;
2495 error = priv_check(td, PRIV_SWAPOFF);
2499 sx_xlock(&swdev_syscall_lock);
2501 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2506 NDFREE(&nd, NDF_ONLY_PNBUF);
2509 mtx_lock(&sw_dev_mtx);
2510 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2511 if (sp->sw_vp == vp)
2514 mtx_unlock(&sw_dev_mtx);
2519 error = swapoff_one(sp, td->td_ucred);
2521 sx_xunlock(&swdev_syscall_lock);
2526 swapoff_one(struct swdevt *sp, struct ucred *cred)
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.
2549 if (vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
2553 * Prevent further allocations on this device.
2555 mtx_lock(&sw_dev_mtx);
2556 sp->sw_flags |= SW_CLOSING;
2557 swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2558 swap_total -= nblks;
2559 mtx_unlock(&sw_dev_mtx);
2562 * Page in the contents of the device and close it.
2564 swap_pager_swapoff(sp);
2566 sp->sw_close(curthread, sp);
2567 mtx_lock(&sw_dev_mtx);
2569 TAILQ_REMOVE(&swtailq, sp, sw_list);
2571 if (nswapdev == 0) {
2572 swap_pager_full = 2;
2573 swap_pager_almost_full = 1;
2577 mtx_unlock(&sw_dev_mtx);
2578 blist_destroy(sp->sw_blist);
2579 free(sp, M_VMPGDATA);
2586 struct swdevt *sp, *spt;
2587 const char *devname;
2590 sx_xlock(&swdev_syscall_lock);
2592 mtx_lock(&sw_dev_mtx);
2593 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2594 mtx_unlock(&sw_dev_mtx);
2595 if (vn_isdisk(sp->sw_vp))
2596 devname = devtoname(sp->sw_vp->v_rdev);
2599 error = swapoff_one(sp, thread0.td_ucred);
2601 printf("Cannot remove swap device %s (error=%d), "
2602 "skipping.\n", devname, error);
2603 } else if (bootverbose) {
2604 printf("Swap device %s removed.\n", devname);
2606 mtx_lock(&sw_dev_mtx);
2608 mtx_unlock(&sw_dev_mtx);
2610 sx_xunlock(&swdev_syscall_lock);
2614 swap_pager_status(int *total, int *used)
2617 *total = swap_total;
2618 *used = swap_total - swap_pager_avail -
2619 nswapdev * howmany(BBSIZE, PAGE_SIZE);
2623 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2626 const char *tmp_devname;
2631 mtx_lock(&sw_dev_mtx);
2632 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2637 xs->xsw_version = XSWDEV_VERSION;
2638 xs->xsw_dev = sp->sw_dev;
2639 xs->xsw_flags = sp->sw_flags;
2640 xs->xsw_nblks = sp->sw_nblks;
2641 xs->xsw_used = sp->sw_used;
2642 if (devname != NULL) {
2643 if (vn_isdisk(sp->sw_vp))
2644 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2646 tmp_devname = "[file]";
2647 strncpy(devname, tmp_devname, len);
2652 mtx_unlock(&sw_dev_mtx);
2656 #if defined(COMPAT_FREEBSD11)
2657 #define XSWDEV_VERSION_11 1
2667 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2670 u_int xsw_dev1, xsw_dev2;
2678 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2681 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2682 struct xswdev32 xs32;
2684 #if defined(COMPAT_FREEBSD11)
2685 struct xswdev11 xs11;
2689 if (arg2 != 1) /* name length */
2692 memset(&xs, 0, sizeof(xs));
2693 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2696 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2697 if (req->oldlen == sizeof(xs32)) {
2698 memset(&xs32, 0, sizeof(xs32));
2699 xs32.xsw_version = XSWDEV_VERSION;
2700 xs32.xsw_dev1 = xs.xsw_dev;
2701 xs32.xsw_dev2 = xs.xsw_dev >> 32;
2702 xs32.xsw_flags = xs.xsw_flags;
2703 xs32.xsw_nblks = xs.xsw_nblks;
2704 xs32.xsw_used = xs.xsw_used;
2705 error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2709 #if defined(COMPAT_FREEBSD11)
2710 if (req->oldlen == sizeof(xs11)) {
2711 memset(&xs11, 0, sizeof(xs11));
2712 xs11.xsw_version = XSWDEV_VERSION_11;
2713 xs11.xsw_dev = xs.xsw_dev; /* truncation */
2714 xs11.xsw_flags = xs.xsw_flags;
2715 xs11.xsw_nblks = xs.xsw_nblks;
2716 xs11.xsw_used = xs.xsw_used;
2717 error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2721 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2725 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2726 "Number of swap devices");
2727 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2728 sysctl_vm_swap_info,
2729 "Swap statistics by device");
2732 * Count the approximate swap usage in pages for a vmspace. The
2733 * shadowed or not yet copied on write swap blocks are not accounted.
2734 * The map must be locked.
2737 vmspace_swap_count(struct vmspace *vmspace)
2747 map = &vmspace->vm_map;
2750 VM_MAP_ENTRY_FOREACH(cur, map) {
2751 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2753 object = cur->object.vm_object;
2754 if (object == NULL || (object->flags & OBJ_SWAP) == 0)
2756 VM_OBJECT_RLOCK(object);
2757 if ((object->flags & OBJ_SWAP) == 0)
2759 pi = OFF_TO_IDX(cur->offset);
2760 e = pi + OFF_TO_IDX(cur->end - cur->start);
2761 for (;; pi = sb->p + SWAP_META_PAGES) {
2762 sb = SWAP_PCTRIE_LOOKUP_GE(
2763 &object->un_pager.swp.swp_blks, pi);
2764 if (sb == NULL || sb->p >= e)
2766 for (i = 0; i < SWAP_META_PAGES; i++) {
2767 if (sb->p + i < e &&
2768 sb->d[i] != SWAPBLK_NONE)
2773 VM_OBJECT_RUNLOCK(object);
2781 * Swapping onto disk devices.
2785 static g_orphan_t swapgeom_orphan;
2787 static struct g_class g_swap_class = {
2789 .version = G_VERSION,
2790 .orphan = swapgeom_orphan,
2793 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2796 swapgeom_close_ev(void *arg, int flags)
2798 struct g_consumer *cp;
2801 g_access(cp, -1, -1, 0);
2803 g_destroy_consumer(cp);
2807 * Add a reference to the g_consumer for an inflight transaction.
2810 swapgeom_acquire(struct g_consumer *cp)
2813 mtx_assert(&sw_dev_mtx, MA_OWNED);
2818 * Remove a reference from the g_consumer. Post a close event if all
2819 * references go away, since the function might be called from the
2823 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2826 mtx_assert(&sw_dev_mtx, MA_OWNED);
2828 if (cp->index == 0) {
2829 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2835 swapgeom_done(struct bio *bp2)
2839 struct g_consumer *cp;
2841 bp = bp2->bio_caller2;
2843 bp->b_ioflags = bp2->bio_flags;
2845 bp->b_ioflags |= BIO_ERROR;
2846 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2847 bp->b_error = bp2->bio_error;
2848 bp->b_caller1 = NULL;
2850 sp = bp2->bio_caller1;
2851 mtx_lock(&sw_dev_mtx);
2852 swapgeom_release(cp, sp);
2853 mtx_unlock(&sw_dev_mtx);
2858 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2861 struct g_consumer *cp;
2863 mtx_lock(&sw_dev_mtx);
2866 mtx_unlock(&sw_dev_mtx);
2867 bp->b_error = ENXIO;
2868 bp->b_ioflags |= BIO_ERROR;
2872 swapgeom_acquire(cp);
2873 mtx_unlock(&sw_dev_mtx);
2874 if (bp->b_iocmd == BIO_WRITE)
2877 bio = g_alloc_bio();
2879 mtx_lock(&sw_dev_mtx);
2880 swapgeom_release(cp, sp);
2881 mtx_unlock(&sw_dev_mtx);
2882 bp->b_error = ENOMEM;
2883 bp->b_ioflags |= BIO_ERROR;
2884 printf("swap_pager: cannot allocate bio\n");
2889 bp->b_caller1 = bio;
2890 bio->bio_caller1 = sp;
2891 bio->bio_caller2 = bp;
2892 bio->bio_cmd = bp->b_iocmd;
2893 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2894 bio->bio_length = bp->b_bcount;
2895 bio->bio_done = swapgeom_done;
2896 if (!buf_mapped(bp)) {
2897 bio->bio_ma = bp->b_pages;
2898 bio->bio_data = unmapped_buf;
2899 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2900 bio->bio_ma_n = bp->b_npages;
2901 bio->bio_flags |= BIO_UNMAPPED;
2903 bio->bio_data = bp->b_data;
2906 g_io_request(bio, cp);
2911 swapgeom_orphan(struct g_consumer *cp)
2916 mtx_lock(&sw_dev_mtx);
2917 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2918 if (sp->sw_id == cp) {
2919 sp->sw_flags |= SW_CLOSING;
2924 * Drop reference we were created with. Do directly since we're in a
2925 * special context where we don't have to queue the call to
2926 * swapgeom_close_ev().
2929 destroy = ((sp != NULL) && (cp->index == 0));
2932 mtx_unlock(&sw_dev_mtx);
2934 swapgeom_close_ev(cp, 0);
2938 swapgeom_close(struct thread *td, struct swdevt *sw)
2940 struct g_consumer *cp;
2942 mtx_lock(&sw_dev_mtx);
2945 mtx_unlock(&sw_dev_mtx);
2948 * swapgeom_close() may be called from the biodone context,
2949 * where we cannot perform topology changes. Delegate the
2950 * work to the events thread.
2953 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2957 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2959 struct g_provider *pp;
2960 struct g_consumer *cp;
2961 static struct g_geom *gp;
2966 pp = g_dev_getprovider(dev);
2969 mtx_lock(&sw_dev_mtx);
2970 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2972 if (cp != NULL && cp->provider == pp) {
2973 mtx_unlock(&sw_dev_mtx);
2977 mtx_unlock(&sw_dev_mtx);
2979 gp = g_new_geomf(&g_swap_class, "swap");
2980 cp = g_new_consumer(gp);
2981 cp->index = 1; /* Number of active I/Os, plus one for being active. */
2982 cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2985 * XXX: Every time you think you can improve the margin for
2986 * footshooting, somebody depends on the ability to do so:
2987 * savecore(8) wants to write to our swapdev so we cannot
2988 * set an exclusive count :-(
2990 error = g_access(cp, 1, 1, 0);
2993 g_destroy_consumer(cp);
2996 nblks = pp->mediasize / DEV_BSIZE;
2997 swaponsomething(vp, cp, nblks, swapgeom_strategy,
2998 swapgeom_close, dev2udev(dev),
2999 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
3004 swapongeom(struct vnode *vp)
3008 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3009 if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) {
3013 error = swapongeom_locked(vp->v_rdev, vp);
3014 g_topology_unlock();
3023 * This is used mainly for network filesystem (read: probably only tested
3024 * with NFS) swapfiles.
3029 swapdev_strategy(struct buf *bp, struct swdevt *sp)
3033 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
3037 if (bp->b_iocmd == BIO_WRITE) {
3039 bufobj_wdrop(bp->b_bufobj);
3040 bufobj_wref(&vp2->v_bufobj);
3042 if (bp->b_bufobj != &vp2->v_bufobj)
3043 bp->b_bufobj = &vp2->v_bufobj;
3045 bp->b_iooffset = dbtob(bp->b_blkno);
3051 swapdev_close(struct thread *td, struct swdevt *sp)
3056 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3057 VOP_CLOSE(vp, FREAD | FWRITE, td->td_ucred, td);
3062 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
3069 mtx_lock(&sw_dev_mtx);
3070 TAILQ_FOREACH(sp, &swtailq, sw_list) {
3071 if (sp->sw_id == vp) {
3072 mtx_unlock(&sw_dev_mtx);
3076 mtx_unlock(&sw_dev_mtx);
3078 (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3080 error = mac_system_check_swapon(td->td_ucred, vp);
3083 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
3084 (void) VOP_UNLOCK(vp);
3088 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
3094 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
3098 new = nsw_wcount_async_max;
3099 error = sysctl_handle_int(oidp, &new, 0, req);
3100 if (error != 0 || req->newptr == NULL)
3103 if (new > nswbuf / 2 || new < 1)
3106 mtx_lock(&swbuf_mtx);
3107 while (nsw_wcount_async_max != new) {
3109 * Adjust difference. If the current async count is too low,
3110 * we will need to sqeeze our update slowly in. Sleep with a
3111 * higher priority than getpbuf() to finish faster.
3113 n = new - nsw_wcount_async_max;
3114 if (nsw_wcount_async + n >= 0) {
3115 nsw_wcount_async += n;
3116 nsw_wcount_async_max += n;
3117 wakeup(&nsw_wcount_async);
3119 nsw_wcount_async_max -= nsw_wcount_async;
3120 nsw_wcount_async = 0;
3121 msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
3125 mtx_unlock(&swbuf_mtx);
3131 swap_pager_update_writecount(vm_object_t object, vm_offset_t start,
3135 VM_OBJECT_WLOCK(object);
3136 KASSERT((object->flags & OBJ_ANON) == 0,
3137 ("Splittable object with writecount"));
3138 object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
3139 VM_OBJECT_WUNLOCK(object);
3143 swap_pager_release_writecount(vm_object_t object, vm_offset_t start,
3147 VM_OBJECT_WLOCK(object);
3148 KASSERT((object->flags & OBJ_ANON) == 0,
3149 ("Splittable object with writecount"));
3150 object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
3151 VM_OBJECT_WUNLOCK(object);