2 * SPDX-License-Identifier: BSD-4-Clause
4 * Copyright (c) 1998 Matthew Dillon,
5 * Copyright (c) 1994 John S. Dyson
6 * Copyright (c) 1990 University of Utah.
7 * Copyright (c) 1982, 1986, 1989, 1993
8 * The Regents of the University of California. All rights reserved.
10 * This code is derived from software contributed to Berkeley by
11 * the Systems Programming Group of the University of Utah Computer
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 * 3. All advertising materials mentioning features or use of this software
23 * must display the following acknowledgement:
24 * This product includes software developed by the University of
25 * California, Berkeley and its contributors.
26 * 4. Neither the name of the University nor the names of its contributors
27 * may be used to endorse or promote products derived from this software
28 * without specific prior written permission.
30 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45 * Radix Bitmap 'blists'.
47 * - The new swapper uses the new radix bitmap code. This should scale
48 * to arbitrarily small or arbitrarily large swap spaces and an almost
49 * arbitrary degree of fragmentation.
53 * - on the fly reallocation of swap during putpages. The new system
54 * does not try to keep previously allocated swap blocks for dirty
57 * - on the fly deallocation of swap
59 * - No more garbage collection required. Unnecessarily allocated swap
60 * blocks only exist for dirty vm_page_t's now and these are already
61 * cycled (in a high-load system) by the pager. We also do on-the-fly
62 * removal of invalidated swap blocks when a page is destroyed
65 * from: Utah $Hdr: swap_pager.c 1.4 91/04/30$
67 * @(#)swap_pager.c 8.9 (Berkeley) 3/21/94
68 * @(#)vm_swap.c 8.5 (Berkeley) 2/17/94
71 #include <sys/cdefs.h>
72 __FBSDID("$FreeBSD$");
76 #include <sys/param.h>
78 #include <sys/blist.h>
82 #include <sys/disklabel.h>
83 #include <sys/eventhandler.h>
84 #include <sys/fcntl.h>
86 #include <sys/kernel.h>
87 #include <sys/mount.h>
88 #include <sys/namei.h>
89 #include <sys/malloc.h>
90 #include <sys/pctrie.h>
93 #include <sys/racct.h>
94 #include <sys/resource.h>
95 #include <sys/resourcevar.h>
96 #include <sys/rwlock.h>
98 #include <sys/sysctl.h>
99 #include <sys/sysproto.h>
100 #include <sys/systm.h>
102 #include <sys/vmmeter.h>
103 #include <sys/vnode.h>
105 #include <security/mac/mac_framework.h>
109 #include <vm/vm_map.h>
110 #include <vm/vm_kern.h>
111 #include <vm/vm_object.h>
112 #include <vm/vm_page.h>
113 #include <vm/vm_pager.h>
114 #include <vm/vm_pageout.h>
115 #include <vm/vm_param.h>
116 #include <vm/swap_pager.h>
117 #include <vm/vm_extern.h>
120 #include <geom/geom.h>
123 * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64.
124 * The 64-page limit is due to the radix code (kern/subr_blist.c).
126 #ifndef MAX_PAGEOUT_CLUSTER
127 #define MAX_PAGEOUT_CLUSTER 32
130 #if !defined(SWB_NPAGES)
131 #define SWB_NPAGES MAX_PAGEOUT_CLUSTER
134 #define SWAP_META_PAGES PCTRIE_COUNT
137 * A swblk structure maps each page index within a
138 * SWAP_META_PAGES-aligned and sized range to the address of an
139 * on-disk swap block (or SWAPBLK_NONE). The collection of these
140 * mappings for an entire vm object is implemented as a pc-trie.
144 daddr_t d[SWAP_META_PAGES];
147 static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data");
148 static struct mtx sw_dev_mtx;
149 static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
150 static struct swdevt *swdevhd; /* Allocate from here next */
151 static int nswapdev; /* Number of swap devices */
152 int swap_pager_avail;
153 static struct sx swdev_syscall_lock; /* serialize swap(on|off) */
155 static u_long swap_reserved;
156 static u_long swap_total;
157 static int sysctl_page_shift(SYSCTL_HANDLER_ARGS);
159 static SYSCTL_NODE(_vm_stats, OID_AUTO, swap, CTLFLAG_RD, 0, "VM swap stats");
161 SYSCTL_PROC(_vm, OID_AUTO, swap_reserved, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
162 &swap_reserved, 0, sysctl_page_shift, "A",
163 "Amount of swap storage needed to back all allocated anonymous memory.");
164 SYSCTL_PROC(_vm, OID_AUTO, swap_total, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
165 &swap_total, 0, sysctl_page_shift, "A",
166 "Total amount of available swap storage.");
168 static int overcommit = 0;
169 SYSCTL_INT(_vm, VM_OVERCOMMIT, overcommit, CTLFLAG_RW, &overcommit, 0,
170 "Configure virtual memory overcommit behavior. See tuning(7) "
172 static unsigned long swzone;
173 SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
174 "Actual size of swap metadata zone");
175 static unsigned long swap_maxpages;
176 SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
177 "Maximum amount of swap supported");
179 static counter_u64_t swap_free_deferred;
180 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_deferred,
181 CTLFLAG_RD, &swap_free_deferred,
182 "Number of pages that deferred freeing swap space");
184 static counter_u64_t swap_free_completed;
185 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_completed,
186 CTLFLAG_RD, &swap_free_completed,
187 "Number of deferred frees completed");
189 /* bits from overcommit */
190 #define SWAP_RESERVE_FORCE_ON (1 << 0)
191 #define SWAP_RESERVE_RLIMIT_ON (1 << 1)
192 #define SWAP_RESERVE_ALLOW_NONWIRED (1 << 2)
195 sysctl_page_shift(SYSCTL_HANDLER_ARGS)
198 u_long value = *(u_long *)arg1;
200 newval = ((uint64_t)value) << PAGE_SHIFT;
201 return (sysctl_handle_64(oidp, &newval, 0, req));
205 swap_reserve(vm_ooffset_t incr)
208 return (swap_reserve_by_cred(incr, curthread->td_ucred));
212 swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
214 u_long r, s, prev, pincr;
217 static struct timeval lastfail;
220 uip = cred->cr_ruidinfo;
222 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
228 error = racct_add(curproc, RACCT_SWAP, incr);
229 PROC_UNLOCK(curproc);
237 prev = atomic_fetchadd_long(&swap_reserved, pincr);
239 if (overcommit & SWAP_RESERVE_ALLOW_NONWIRED) {
240 s = vm_cnt.v_page_count - vm_cnt.v_free_reserved -
245 if ((overcommit & SWAP_RESERVE_FORCE_ON) == 0 || r <= s ||
246 (error = priv_check(curthread, PRIV_VM_SWAP_NOQUOTA)) == 0) {
249 prev = atomic_fetchadd_long(&swap_reserved, -pincr);
251 panic("swap_reserved < incr on overcommit fail");
254 prev = atomic_fetchadd_long(&uip->ui_vmsize, pincr);
255 if ((overcommit & SWAP_RESERVE_RLIMIT_ON) != 0 &&
256 prev + pincr > lim_cur(curthread, RLIMIT_SWAP) &&
257 priv_check(curthread, PRIV_VM_SWAP_NORLIMIT)) {
259 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pincr);
261 panic("uip->ui_vmsize < incr on overcommit fail");
264 if (!res && ppsratecheck(&lastfail, &curfail, 1)) {
265 printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
266 uip->ui_uid, curproc->p_pid, incr);
270 if (racct_enable && !res) {
272 racct_sub(curproc, RACCT_SWAP, incr);
273 PROC_UNLOCK(curproc);
281 swap_reserve_force(vm_ooffset_t incr)
286 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
292 racct_add_force(curproc, RACCT_SWAP, incr);
295 atomic_add_long(&swap_reserved, pincr);
296 uip = curproc->p_ucred->cr_ruidinfo;
297 atomic_add_long(&uip->ui_vmsize, pincr);
298 PROC_UNLOCK(curproc);
302 swap_release(vm_ooffset_t decr)
307 cred = curproc->p_ucred;
308 swap_release_by_cred(decr, cred);
309 PROC_UNLOCK(curproc);
313 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
318 uip = cred->cr_ruidinfo;
320 KASSERT((decr & PAGE_MASK) == 0, ("%s: decr: %ju & PAGE_MASK", __func__,
324 prev = atomic_fetchadd_long(&swap_reserved, -pdecr);
326 panic("swap_reserved < decr");
328 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pdecr);
330 printf("negative vmsize for uid = %d\n", uip->ui_uid);
333 racct_sub_cred(cred, RACCT_SWAP, decr);
337 static int swap_pager_full = 2; /* swap space exhaustion (task killing) */
338 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
339 static struct mtx swbuf_mtx; /* to sync nsw_wcount_async */
340 static int nsw_wcount_async; /* limit async write buffers */
341 static int nsw_wcount_async_max;/* assigned maximum */
342 static int nsw_cluster_max; /* maximum VOP I/O allowed */
344 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
345 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
346 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
347 "Maximum running async swap ops");
348 static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS);
349 SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD |
350 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A",
351 "Swap Fragmentation Info");
353 static struct sx sw_alloc_sx;
356 * "named" and "unnamed" anon region objects. Try to reduce the overhead
357 * of searching a named list by hashing it just a little.
362 #define NOBJLIST(handle) \
363 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
365 static struct pagerlst swap_pager_object_list[NOBJLISTS];
366 static uma_zone_t swwbuf_zone;
367 static uma_zone_t swrbuf_zone;
368 static uma_zone_t swblk_zone;
369 static uma_zone_t swpctrie_zone;
372 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
373 * calls hooked from other parts of the VM system and do not appear here.
374 * (see vm/swap_pager.h).
377 swap_pager_alloc(void *handle, vm_ooffset_t size,
378 vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
379 static void swap_pager_dealloc(vm_object_t object);
380 static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
382 static int swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
383 int *, pgo_getpages_iodone_t, void *);
384 static void swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
386 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
387 static void swap_pager_init(void);
388 static void swap_pager_unswapped(vm_page_t);
389 static void swap_pager_swapoff(struct swdevt *sp);
390 static void swap_pager_update_writecount(vm_object_t object,
391 vm_offset_t start, vm_offset_t end);
392 static void swap_pager_release_writecount(vm_object_t object,
393 vm_offset_t start, vm_offset_t end);
395 struct pagerops swappagerops = {
396 .pgo_init = swap_pager_init, /* early system initialization of pager */
397 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */
398 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
399 .pgo_getpages = swap_pager_getpages, /* pagein */
400 .pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
401 .pgo_putpages = swap_pager_putpages, /* pageout */
402 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */
403 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
404 .pgo_update_writecount = swap_pager_update_writecount,
405 .pgo_release_writecount = swap_pager_release_writecount,
409 * swap_*() routines are externally accessible. swp_*() routines are
412 static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
413 static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
415 SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
416 "Maximum size of a swap block in pages");
418 static void swp_sizecheck(void);
419 static void swp_pager_async_iodone(struct buf *bp);
420 static bool swp_pager_swblk_empty(struct swblk *sb, int start, int limit);
421 static void swp_pager_free_empty_swblk(vm_object_t, struct swblk *sb);
422 static int swapongeom(struct vnode *);
423 static int swaponvp(struct thread *, struct vnode *, u_long);
424 static int swapoff_one(struct swdevt *sp, struct ucred *cred);
427 * Swap bitmap functions
429 static void swp_pager_freeswapspace(daddr_t blk, daddr_t npages);
430 static daddr_t swp_pager_getswapspace(int *npages, int limit);
435 static daddr_t swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
436 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t);
437 static void swp_pager_meta_transfer(vm_object_t src, vm_object_t dst,
438 vm_pindex_t pindex, vm_pindex_t count);
439 static void swp_pager_meta_free_all(vm_object_t);
440 static daddr_t swp_pager_meta_lookup(vm_object_t, vm_pindex_t);
443 swp_pager_init_freerange(daddr_t *start, daddr_t *num)
446 *start = SWAPBLK_NONE;
451 swp_pager_update_freerange(daddr_t *start, daddr_t *num, daddr_t addr)
454 if (*start + *num == addr) {
457 swp_pager_freeswapspace(*start, *num);
464 swblk_trie_alloc(struct pctrie *ptree)
467 return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
468 M_USE_RESERVE : 0)));
472 swblk_trie_free(struct pctrie *ptree, void *node)
475 uma_zfree(swpctrie_zone, node);
478 PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
481 * SWP_SIZECHECK() - update swap_pager_full indication
483 * update the swap_pager_almost_full indication and warn when we are
484 * about to run out of swap space, using lowat/hiwat hysteresis.
486 * Clear swap_pager_full ( task killing ) indication when lowat is met.
488 * No restrictions on call
489 * This routine may not block.
495 if (swap_pager_avail < nswap_lowat) {
496 if (swap_pager_almost_full == 0) {
497 printf("swap_pager: out of swap space\n");
498 swap_pager_almost_full = 1;
502 if (swap_pager_avail > nswap_hiwat)
503 swap_pager_almost_full = 0;
508 * SWAP_PAGER_INIT() - initialize the swap pager!
510 * Expected to be started from system init. NOTE: This code is run
511 * before much else so be careful what you depend on. Most of the VM
512 * system has yet to be initialized at this point.
515 swap_pager_init(void)
518 * Initialize object lists
522 for (i = 0; i < NOBJLISTS; ++i)
523 TAILQ_INIT(&swap_pager_object_list[i]);
524 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
525 sx_init(&sw_alloc_sx, "swspsx");
526 sx_init(&swdev_syscall_lock, "swsysc");
530 swap_pager_counters(void)
533 swap_free_deferred = counter_u64_alloc(M_WAITOK);
534 swap_free_completed = counter_u64_alloc(M_WAITOK);
536 SYSINIT(swap_counters, SI_SUB_CPU, SI_ORDER_ANY, swap_pager_counters, NULL);
539 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
541 * Expected to be started from pageout process once, prior to entering
545 swap_pager_swap_init(void)
550 * Number of in-transit swap bp operations. Don't
551 * exhaust the pbufs completely. Make sure we
552 * initialize workable values (0 will work for hysteresis
553 * but it isn't very efficient).
555 * The nsw_cluster_max is constrained by the bp->b_pages[]
556 * array, which has MAXPHYS / PAGE_SIZE entries, and our locally
557 * defined MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
558 * constrained by the swap device interleave stripe size.
560 * Currently we hardwire nsw_wcount_async to 4. This limit is
561 * designed to prevent other I/O from having high latencies due to
562 * our pageout I/O. The value 4 works well for one or two active swap
563 * devices but is probably a little low if you have more. Even so,
564 * a higher value would probably generate only a limited improvement
565 * with three or four active swap devices since the system does not
566 * typically have to pageout at extreme bandwidths. We will want
567 * at least 2 per swap devices, and 4 is a pretty good value if you
568 * have one NFS swap device due to the command/ack latency over NFS.
569 * So it all works out pretty well.
571 nsw_cluster_max = min(MAXPHYS / PAGE_SIZE, MAX_PAGEOUT_CLUSTER);
573 nsw_wcount_async = 4;
574 nsw_wcount_async_max = nsw_wcount_async;
575 mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
577 swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
578 swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
581 * Initialize our zone, taking the user's requested size or
582 * estimating the number we need based on the number of pages
585 n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
586 vm_cnt.v_page_count / 2;
587 swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
588 pctrie_zone_init, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM);
589 if (swpctrie_zone == NULL)
590 panic("failed to create swap pctrie zone.");
591 swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
592 NULL, NULL, _Alignof(struct swblk) - 1, UMA_ZONE_VM);
593 if (swblk_zone == NULL)
594 panic("failed to create swap blk zone.");
597 if (uma_zone_reserve_kva(swblk_zone, n))
600 * if the allocation failed, try a zone two thirds the
601 * size of the previous attempt.
607 * Often uma_zone_reserve_kva() cannot reserve exactly the
608 * requested size. Account for the difference when
609 * calculating swap_maxpages.
611 n = uma_zone_get_max(swblk_zone);
614 printf("Swap blk zone entries changed from %lu to %lu.\n",
616 /* absolute maximum we can handle assuming 100% efficiency */
617 swap_maxpages = n * SWAP_META_PAGES;
618 swzone = n * sizeof(struct swblk);
619 if (!uma_zone_reserve_kva(swpctrie_zone, n))
620 printf("Cannot reserve swap pctrie zone, "
621 "reduce kern.maxswzone.\n");
625 swap_pager_alloc_init(void *handle, struct ucred *cred, vm_ooffset_t size,
631 if (!swap_reserve_by_cred(size, cred))
637 * The un_pager.swp.swp_blks trie is initialized by
638 * vm_object_allocate() to ensure the correct order of
639 * visibility to other threads.
641 object = vm_object_allocate(OBJT_SWAP, OFF_TO_IDX(offset +
644 object->un_pager.swp.writemappings = 0;
645 object->handle = handle;
648 object->charge = size;
654 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
655 * its metadata structures.
657 * This routine is called from the mmap and fork code to create a new
660 * This routine must ensure that no live duplicate is created for
661 * the named object request, which is protected against by
662 * holding the sw_alloc_sx lock in case handle != NULL.
665 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
666 vm_ooffset_t offset, struct ucred *cred)
670 if (handle != NULL) {
672 * Reference existing named region or allocate new one. There
673 * should not be a race here against swp_pager_meta_build()
674 * as called from vm_page_remove() in regards to the lookup
677 sx_xlock(&sw_alloc_sx);
678 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
679 if (object == NULL) {
680 object = swap_pager_alloc_init(handle, cred, size,
682 if (object != NULL) {
683 TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
684 object, pager_object_list);
687 sx_xunlock(&sw_alloc_sx);
689 object = swap_pager_alloc_init(handle, cred, size, offset);
695 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
697 * The swap backing for the object is destroyed. The code is
698 * designed such that we can reinstantiate it later, but this
699 * routine is typically called only when the entire object is
700 * about to be destroyed.
702 * The object must be locked.
705 swap_pager_dealloc(vm_object_t object)
708 VM_OBJECT_ASSERT_WLOCKED(object);
709 KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
712 * Remove from list right away so lookups will fail if we block for
713 * pageout completion.
715 if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) {
716 VM_OBJECT_WUNLOCK(object);
717 sx_xlock(&sw_alloc_sx);
718 TAILQ_REMOVE(NOBJLIST(object->handle), object,
720 sx_xunlock(&sw_alloc_sx);
721 VM_OBJECT_WLOCK(object);
724 vm_object_pip_wait(object, "swpdea");
727 * Free all remaining metadata. We only bother to free it from
728 * the swap meta data. We do not attempt to free swapblk's still
729 * associated with vm_page_t's for this object. We do not care
730 * if paging is still in progress on some objects.
732 swp_pager_meta_free_all(object);
733 object->handle = NULL;
734 object->type = OBJT_DEAD;
737 /************************************************************************
738 * SWAP PAGER BITMAP ROUTINES *
739 ************************************************************************/
742 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
744 * Allocate swap for up to the requested number of pages, and at
745 * least a minimum number of pages. The starting swap block number
746 * (a page index) is returned or SWAPBLK_NONE if the allocation
749 * Also has the side effect of advising that somebody made a mistake
750 * when they configured swap and didn't configure enough.
752 * This routine may not sleep.
754 * We allocate in round-robin fashion from the configured devices.
757 swp_pager_getswapspace(int *io_npages, int limit)
765 npages = imin(BLIST_MAX_ALLOC, mpages);
766 mtx_lock(&sw_dev_mtx);
768 while (!TAILQ_EMPTY(&swtailq)) {
770 sp = TAILQ_FIRST(&swtailq);
771 if ((sp->sw_flags & SW_CLOSING) == 0)
772 blk = blist_alloc(sp->sw_blist, &npages, mpages);
773 if (blk != SWAPBLK_NONE)
775 sp = TAILQ_NEXT(sp, sw_list);
783 if (blk != SWAPBLK_NONE) {
786 sp->sw_used += npages;
787 swap_pager_avail -= npages;
789 swdevhd = TAILQ_NEXT(sp, sw_list);
791 if (swap_pager_full != 2) {
792 printf("swp_pager_getswapspace(%d): failed\n",
795 swap_pager_almost_full = 1;
799 mtx_unlock(&sw_dev_mtx);
804 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
807 return (blk >= sp->sw_first && blk < sp->sw_end);
811 swp_pager_strategy(struct buf *bp)
815 mtx_lock(&sw_dev_mtx);
816 TAILQ_FOREACH(sp, &swtailq, sw_list) {
817 if (swp_pager_isondev(bp->b_blkno, sp)) {
818 mtx_unlock(&sw_dev_mtx);
819 if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
820 unmapped_buf_allowed) {
821 bp->b_data = unmapped_buf;
824 pmap_qenter((vm_offset_t)bp->b_data,
825 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
827 sp->sw_strategy(bp, sp);
831 panic("Swapdev not found");
836 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
838 * This routine returns the specified swap blocks back to the bitmap.
840 * This routine may not sleep.
843 swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
849 mtx_lock(&sw_dev_mtx);
850 TAILQ_FOREACH(sp, &swtailq, sw_list) {
851 if (swp_pager_isondev(blk, sp)) {
852 sp->sw_used -= npages;
854 * If we are attempting to stop swapping on
855 * this device, we don't want to mark any
856 * blocks free lest they be reused.
858 if ((sp->sw_flags & SW_CLOSING) == 0) {
859 blist_free(sp->sw_blist, blk - sp->sw_first,
861 swap_pager_avail += npages;
864 mtx_unlock(&sw_dev_mtx);
868 panic("Swapdev not found");
872 * SYSCTL_SWAP_FRAGMENTATION() - produce raw swap space stats
875 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
882 error = sysctl_wire_old_buffer(req, 0);
885 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
886 mtx_lock(&sw_dev_mtx);
887 TAILQ_FOREACH(sp, &swtailq, sw_list) {
888 if (vn_isdisk(sp->sw_vp, NULL))
889 devname = devtoname(sp->sw_vp->v_rdev);
892 sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
893 blist_stats(sp->sw_blist, &sbuf);
895 mtx_unlock(&sw_dev_mtx);
896 error = sbuf_finish(&sbuf);
902 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
903 * range within an object.
905 * This is a globally accessible routine.
907 * This routine removes swapblk assignments from swap metadata.
909 * The external callers of this routine typically have already destroyed
910 * or renamed vm_page_t's associated with this range in the object so
913 * The object must be locked.
916 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
919 swp_pager_meta_free(object, start, size);
923 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
925 * Assigns swap blocks to the specified range within the object. The
926 * swap blocks are not zeroed. Any previous swap assignment is destroyed.
928 * Returns 0 on success, -1 on failure.
931 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
933 daddr_t addr, blk, n_free, s_free;
936 swp_pager_init_freerange(&s_free, &n_free);
937 VM_OBJECT_WLOCK(object);
938 for (i = 0; i < size; i += n) {
940 blk = swp_pager_getswapspace(&n, 1);
941 if (blk == SWAPBLK_NONE) {
942 swp_pager_meta_free(object, start, i);
943 VM_OBJECT_WUNLOCK(object);
946 for (j = 0; j < n; ++j) {
947 addr = swp_pager_meta_build(object,
948 start + i + j, blk + j);
949 if (addr != SWAPBLK_NONE)
950 swp_pager_update_freerange(&s_free, &n_free,
954 swp_pager_freeswapspace(s_free, n_free);
955 VM_OBJECT_WUNLOCK(object);
960 swp_pager_xfer_source(vm_object_t srcobject, vm_object_t dstobject,
961 vm_pindex_t pindex, daddr_t addr)
965 KASSERT(srcobject->type == OBJT_SWAP,
966 ("%s: Srcobject not swappable", __func__));
967 if (dstobject->type == OBJT_SWAP &&
968 swp_pager_meta_lookup(dstobject, pindex) != SWAPBLK_NONE) {
969 /* Caller should destroy the source block. */
974 * Destination has no swapblk and is not resident, transfer source.
975 * swp_pager_meta_build() can sleep.
977 VM_OBJECT_WUNLOCK(srcobject);
978 dstaddr = swp_pager_meta_build(dstobject, pindex, addr);
979 KASSERT(dstaddr == SWAPBLK_NONE,
980 ("Unexpected destination swapblk"));
981 VM_OBJECT_WLOCK(srcobject);
987 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
988 * and destroy the source.
990 * Copy any valid swapblks from the source to the destination. In
991 * cases where both the source and destination have a valid swapblk,
992 * we keep the destination's.
994 * This routine is allowed to sleep. It may sleep allocating metadata
995 * indirectly through swp_pager_meta_build().
997 * The source object contains no vm_page_t's (which is just as well)
999 * The source object is of type OBJT_SWAP.
1001 * The source and destination objects must be locked.
1002 * Both object locks may temporarily be released.
1005 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
1006 vm_pindex_t offset, int destroysource)
1009 VM_OBJECT_ASSERT_WLOCKED(srcobject);
1010 VM_OBJECT_ASSERT_WLOCKED(dstobject);
1013 * If destroysource is set, we remove the source object from the
1014 * swap_pager internal queue now.
1016 if (destroysource && (srcobject->flags & OBJ_ANON) == 0 &&
1017 srcobject->handle != NULL) {
1018 VM_OBJECT_WUNLOCK(srcobject);
1019 VM_OBJECT_WUNLOCK(dstobject);
1020 sx_xlock(&sw_alloc_sx);
1021 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
1023 sx_xunlock(&sw_alloc_sx);
1024 VM_OBJECT_WLOCK(dstobject);
1025 VM_OBJECT_WLOCK(srcobject);
1029 * Transfer source to destination.
1031 swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size);
1034 * Free left over swap blocks in source.
1036 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
1037 * double-remove the object from the swap queues.
1039 if (destroysource) {
1040 swp_pager_meta_free_all(srcobject);
1042 * Reverting the type is not necessary, the caller is going
1043 * to destroy srcobject directly, but I'm doing it here
1044 * for consistency since we've removed the object from its
1047 srcobject->type = OBJT_DEFAULT;
1052 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
1053 * the requested page.
1055 * We determine whether good backing store exists for the requested
1056 * page and return TRUE if it does, FALSE if it doesn't.
1058 * If TRUE, we also try to determine how much valid, contiguous backing
1059 * store exists before and after the requested page.
1062 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1068 VM_OBJECT_ASSERT_LOCKED(object);
1069 KASSERT(object->type == OBJT_SWAP,
1070 ("%s: object not swappable", __func__));
1073 * do we have good backing store at the requested index ?
1075 blk0 = swp_pager_meta_lookup(object, pindex);
1076 if (blk0 == SWAPBLK_NONE) {
1085 * find backwards-looking contiguous good backing store
1087 if (before != NULL) {
1088 for (i = 1; i < SWB_NPAGES; i++) {
1091 blk = swp_pager_meta_lookup(object, pindex - i);
1092 if (blk != blk0 - i)
1099 * find forward-looking contiguous good backing store
1101 if (after != NULL) {
1102 for (i = 1; i < SWB_NPAGES; i++) {
1103 blk = swp_pager_meta_lookup(object, pindex + i);
1104 if (blk != blk0 + i)
1113 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1115 * This removes any associated swap backing store, whether valid or
1116 * not, from the page.
1118 * This routine is typically called when a page is made dirty, at
1119 * which point any associated swap can be freed. MADV_FREE also
1120 * calls us in a special-case situation
1122 * NOTE!!! If the page is clean and the swap was valid, the caller
1123 * should make the page dirty before calling this routine. This routine
1124 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1127 * This routine may not sleep.
1129 * The object containing the page may be locked.
1132 swap_pager_unswapped(vm_page_t m)
1138 * Handle enqueing deferred frees first. If we do not have the
1139 * object lock we wait for the page daemon to clear the space.
1142 if (!VM_OBJECT_WOWNED(obj)) {
1143 VM_PAGE_OBJECT_BUSY_ASSERT(m);
1145 * The caller is responsible for synchronization but we
1146 * will harmlessly handle races. This is typically provided
1147 * by only calling unswapped() when a page transitions from
1150 if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) ==
1152 vm_page_aflag_set(m, PGA_SWAP_FREE);
1153 counter_u64_add(swap_free_deferred, 1);
1157 if ((m->a.flags & PGA_SWAP_FREE) != 0)
1158 counter_u64_add(swap_free_completed, 1);
1159 vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE);
1162 * The meta data only exists if the object is OBJT_SWAP
1163 * and even then might not be allocated yet.
1165 KASSERT(m->object->type == OBJT_SWAP,
1166 ("Free object not swappable"));
1168 sb = SWAP_PCTRIE_LOOKUP(&m->object->un_pager.swp.swp_blks,
1169 rounddown(m->pindex, SWAP_META_PAGES));
1172 if (sb->d[m->pindex % SWAP_META_PAGES] == SWAPBLK_NONE)
1174 swp_pager_freeswapspace(sb->d[m->pindex % SWAP_META_PAGES], 1);
1175 sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
1176 swp_pager_free_empty_swblk(m->object, sb);
1180 * swap_pager_getpages() - bring pages in from swap
1182 * Attempt to page in the pages in array "ma" of length "count". The
1183 * caller may optionally specify that additional pages preceding and
1184 * succeeding the specified range be paged in. The number of such pages
1185 * is returned in the "rbehind" and "rahead" parameters, and they will
1186 * be in the inactive queue upon return.
1188 * The pages in "ma" must be busied and will remain busied upon return.
1191 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count, int *rbehind,
1195 vm_page_t bm, mpred, msucc, p;
1198 int i, maxahead, maxbehind, reqcount;
1200 VM_OBJECT_WLOCK(object);
1203 KASSERT(object->type == OBJT_SWAP,
1204 ("%s: object not swappable", __func__));
1205 if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead)) {
1206 VM_OBJECT_WUNLOCK(object);
1207 return (VM_PAGER_FAIL);
1210 KASSERT(reqcount - 1 <= maxahead,
1211 ("page count %d extends beyond swap block", reqcount));
1214 * Do not transfer any pages other than those that are xbusied
1215 * when running during a split or collapse operation. This
1216 * prevents clustering from re-creating pages which are being
1217 * moved into another object.
1219 if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) {
1220 maxahead = reqcount - 1;
1225 * Clip the readahead and readbehind ranges to exclude resident pages.
1227 if (rahead != NULL) {
1228 *rahead = imin(*rahead, maxahead - (reqcount - 1));
1229 pindex = ma[reqcount - 1]->pindex;
1230 msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1231 if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1232 *rahead = msucc->pindex - pindex - 1;
1234 if (rbehind != NULL) {
1235 *rbehind = imin(*rbehind, maxbehind);
1236 pindex = ma[0]->pindex;
1237 mpred = TAILQ_PREV(ma[0], pglist, listq);
1238 if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1239 *rbehind = pindex - mpred->pindex - 1;
1243 for (i = 0; i < count; i++)
1244 ma[i]->oflags |= VPO_SWAPINPROG;
1247 * Allocate readahead and readbehind pages.
1249 if (rbehind != NULL) {
1250 for (i = 1; i <= *rbehind; i++) {
1251 p = vm_page_alloc(object, ma[0]->pindex - i,
1255 p->oflags |= VPO_SWAPINPROG;
1260 if (rahead != NULL) {
1261 for (i = 0; i < *rahead; i++) {
1262 p = vm_page_alloc(object,
1263 ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1266 p->oflags |= VPO_SWAPINPROG;
1270 if (rbehind != NULL)
1275 vm_object_pip_add(object, count);
1277 pindex = bm->pindex;
1278 blk = swp_pager_meta_lookup(object, pindex);
1279 KASSERT(blk != SWAPBLK_NONE,
1280 ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1282 VM_OBJECT_WUNLOCK(object);
1283 bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1284 /* Pages cannot leave the object while busy. */
1285 for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1286 MPASS(p->pindex == bm->pindex + i);
1290 bp->b_flags |= B_PAGING;
1291 bp->b_iocmd = BIO_READ;
1292 bp->b_iodone = swp_pager_async_iodone;
1293 bp->b_rcred = crhold(thread0.td_ucred);
1294 bp->b_wcred = crhold(thread0.td_ucred);
1296 bp->b_bcount = PAGE_SIZE * count;
1297 bp->b_bufsize = PAGE_SIZE * count;
1298 bp->b_npages = count;
1299 bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1300 bp->b_pgafter = rahead != NULL ? *rahead : 0;
1302 VM_CNT_INC(v_swapin);
1303 VM_CNT_ADD(v_swappgsin, count);
1306 * perform the I/O. NOTE!!! bp cannot be considered valid after
1307 * this point because we automatically release it on completion.
1308 * Instead, we look at the one page we are interested in which we
1309 * still hold a lock on even through the I/O completion.
1311 * The other pages in our ma[] array are also released on completion,
1312 * so we cannot assume they are valid anymore either.
1314 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1317 swp_pager_strategy(bp);
1320 * Wait for the pages we want to complete. VPO_SWAPINPROG is always
1321 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1322 * is set in the metadata for each page in the request.
1324 VM_OBJECT_WLOCK(object);
1325 /* This could be implemented more efficiently with aflags */
1326 while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
1327 ma[0]->oflags |= VPO_SWAPSLEEP;
1328 VM_CNT_INC(v_intrans);
1329 if (VM_OBJECT_SLEEP(object, &object->handle, PSWP,
1330 "swread", hz * 20)) {
1332 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1333 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1336 VM_OBJECT_WUNLOCK(object);
1339 * If we had an unrecoverable read error pages will not be valid.
1341 for (i = 0; i < reqcount; i++)
1342 if (ma[i]->valid != VM_PAGE_BITS_ALL)
1343 return (VM_PAGER_ERROR);
1345 return (VM_PAGER_OK);
1348 * A final note: in a low swap situation, we cannot deallocate swap
1349 * and mark a page dirty here because the caller is likely to mark
1350 * the page clean when we return, causing the page to possibly revert
1351 * to all-zero's later.
1356 * swap_pager_getpages_async():
1358 * Right now this is emulation of asynchronous operation on top of
1359 * swap_pager_getpages().
1362 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1363 int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1367 r = swap_pager_getpages(object, ma, count, rbehind, rahead);
1372 case VM_PAGER_ERROR:
1379 panic("unhandled swap_pager_getpages() error %d", r);
1381 (iodone)(arg, ma, count, error);
1387 * swap_pager_putpages:
1389 * Assign swap (if necessary) and initiate I/O on the specified pages.
1391 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1392 * are automatically converted to SWAP objects.
1394 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1395 * vm_page reservation system coupled with properly written VFS devices
1396 * should ensure that no low-memory deadlock occurs. This is an area
1399 * The parent has N vm_object_pip_add() references prior to
1400 * calling us and will remove references for rtvals[] that are
1401 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1404 * The parent has soft-busy'd the pages it passes us and will unbusy
1405 * those whose rtvals[] entry is not set to VM_PAGER_PEND on return.
1406 * We need to unbusy the rest on I/O completion.
1409 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1410 int flags, int *rtvals)
1413 daddr_t addr, blk, n_free, s_free;
1418 KASSERT(count == 0 || ma[0]->object == object,
1419 ("%s: object mismatch %p/%p",
1420 __func__, object, ma[0]->object));
1425 * Turn object into OBJT_SWAP. Force sync if not a pageout process.
1427 if (object->type != OBJT_SWAP) {
1428 addr = swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1429 KASSERT(addr == SWAPBLK_NONE,
1430 ("unexpected object swap block"));
1432 VM_OBJECT_WUNLOCK(object);
1433 async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0;
1434 swp_pager_init_freerange(&s_free, &n_free);
1439 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1440 * The page is left dirty until the pageout operation completes
1443 for (i = 0; i < count; i += n) {
1444 /* Maximum I/O size is limited by maximum swap block size. */
1445 n = min(count - i, nsw_cluster_max);
1447 /* Get a block of swap of size up to size n. */
1448 blk = swp_pager_getswapspace(&n, 4);
1449 if (blk == SWAPBLK_NONE) {
1450 for (j = 0; j < n; ++j)
1451 rtvals[i + j] = VM_PAGER_FAIL;
1456 * All I/O parameters have been satisfied. Build the I/O
1457 * request and assign the swap space.
1460 mtx_lock(&swbuf_mtx);
1461 while (nsw_wcount_async == 0)
1462 msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1465 mtx_unlock(&swbuf_mtx);
1467 bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1469 bp->b_flags = B_ASYNC;
1470 bp->b_flags |= B_PAGING;
1471 bp->b_iocmd = BIO_WRITE;
1473 bp->b_rcred = crhold(thread0.td_ucred);
1474 bp->b_wcred = crhold(thread0.td_ucred);
1475 bp->b_bcount = PAGE_SIZE * n;
1476 bp->b_bufsize = PAGE_SIZE * n;
1479 VM_OBJECT_WLOCK(object);
1480 for (j = 0; j < n; ++j) {
1482 vm_page_aflag_clear(mreq, PGA_SWAP_FREE);
1483 addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1485 if (addr != SWAPBLK_NONE)
1486 swp_pager_update_freerange(&s_free, &n_free,
1488 MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1489 mreq->oflags |= VPO_SWAPINPROG;
1490 bp->b_pages[j] = mreq;
1492 VM_OBJECT_WUNLOCK(object);
1495 * Must set dirty range for NFS to work.
1498 bp->b_dirtyend = bp->b_bcount;
1500 VM_CNT_INC(v_swapout);
1501 VM_CNT_ADD(v_swappgsout, bp->b_npages);
1504 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1505 * can call the async completion routine at the end of a
1506 * synchronous I/O operation. Otherwise, our caller would
1507 * perform duplicate unbusy and wakeup operations on the page
1508 * and object, respectively.
1510 for (j = 0; j < n; j++)
1511 rtvals[i + j] = VM_PAGER_PEND;
1516 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1519 bp->b_iodone = swp_pager_async_iodone;
1521 swp_pager_strategy(bp);
1528 * NOTE: b_blkno is destroyed by the call to swapdev_strategy.
1530 bp->b_iodone = bdone;
1531 swp_pager_strategy(bp);
1534 * Wait for the sync I/O to complete.
1536 bwait(bp, PVM, "swwrt");
1539 * Now that we are through with the bp, we can call the
1540 * normal async completion, which frees everything up.
1542 swp_pager_async_iodone(bp);
1544 swp_pager_freeswapspace(s_free, n_free);
1545 VM_OBJECT_WLOCK(object);
1549 * swp_pager_async_iodone:
1551 * Completion routine for asynchronous reads and writes from/to swap.
1552 * Also called manually by synchronous code to finish up a bp.
1554 * This routine may not sleep.
1557 swp_pager_async_iodone(struct buf *bp)
1560 vm_object_t object = NULL;
1563 * Report error - unless we ran out of memory, in which case
1564 * we've already logged it in swapgeom_strategy().
1566 if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) {
1568 "swap_pager: I/O error - %s failed; blkno %ld,"
1569 "size %ld, error %d\n",
1570 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1578 * remove the mapping for kernel virtual
1581 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1583 bp->b_data = bp->b_kvabase;
1586 object = bp->b_pages[0]->object;
1587 VM_OBJECT_WLOCK(object);
1591 * cleanup pages. If an error occurs writing to swap, we are in
1592 * very serious trouble. If it happens to be a disk error, though,
1593 * we may be able to recover by reassigning the swap later on. So
1594 * in this case we remove the m->swapblk assignment for the page
1595 * but do not free it in the rlist. The errornous block(s) are thus
1596 * never reallocated as swap. Redirty the page and continue.
1598 for (i = 0; i < bp->b_npages; ++i) {
1599 vm_page_t m = bp->b_pages[i];
1601 m->oflags &= ~VPO_SWAPINPROG;
1602 if (m->oflags & VPO_SWAPSLEEP) {
1603 m->oflags &= ~VPO_SWAPSLEEP;
1604 wakeup(&object->handle);
1607 /* We always have space after I/O, successful or not. */
1608 vm_page_aflag_set(m, PGA_SWAP_SPACE);
1610 if (bp->b_ioflags & BIO_ERROR) {
1612 * If an error occurs I'd love to throw the swapblk
1613 * away without freeing it back to swapspace, so it
1614 * can never be used again. But I can't from an
1617 if (bp->b_iocmd == BIO_READ) {
1619 * NOTE: for reads, m->dirty will probably
1620 * be overridden by the original caller of
1621 * getpages so don't play cute tricks here.
1626 * If a write error occurs, reactivate page
1627 * so it doesn't clog the inactive list,
1628 * then finish the I/O.
1630 MPASS(m->dirty == VM_PAGE_BITS_ALL);
1632 /* PQ_UNSWAPPABLE? */
1633 vm_page_activate(m);
1636 } else if (bp->b_iocmd == BIO_READ) {
1638 * NOTE: for reads, m->dirty will probably be
1639 * overridden by the original caller of getpages so
1640 * we cannot set them in order to free the underlying
1641 * swap in a low-swap situation. I don't think we'd
1642 * want to do that anyway, but it was an optimization
1643 * that existed in the old swapper for a time before
1644 * it got ripped out due to precisely this problem.
1646 KASSERT(!pmap_page_is_mapped(m),
1647 ("swp_pager_async_iodone: page %p is mapped", m));
1648 KASSERT(m->dirty == 0,
1649 ("swp_pager_async_iodone: page %p is dirty", m));
1652 if (i < bp->b_pgbefore ||
1653 i >= bp->b_npages - bp->b_pgafter)
1654 vm_page_readahead_finish(m);
1657 * For write success, clear the dirty
1658 * status, then finish the I/O ( which decrements the
1659 * busy count and possibly wakes waiter's up ).
1660 * A page is only written to swap after a period of
1661 * inactivity. Therefore, we do not expect it to be
1664 KASSERT(!pmap_page_is_write_mapped(m),
1665 ("swp_pager_async_iodone: page %p is not write"
1668 vm_page_deactivate_noreuse(m);
1674 * adjust pip. NOTE: the original parent may still have its own
1675 * pip refs on the object.
1677 if (object != NULL) {
1678 vm_object_pip_wakeupn(object, bp->b_npages);
1679 VM_OBJECT_WUNLOCK(object);
1683 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1684 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1685 * trigger a KASSERT in relpbuf().
1689 bp->b_bufobj = NULL;
1692 * release the physical I/O buffer
1694 if (bp->b_flags & B_ASYNC) {
1695 mtx_lock(&swbuf_mtx);
1696 if (++nsw_wcount_async == 1)
1697 wakeup(&nsw_wcount_async);
1698 mtx_unlock(&swbuf_mtx);
1700 uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
1704 swap_pager_nswapdev(void)
1711 swp_pager_force_dirty(vm_page_t m)
1716 if (!vm_page_wired(m) && m->a.queue == PQ_NONE)
1717 panic("page %p is neither wired nor queued", m);
1720 swap_pager_unswapped(m);
1724 swp_pager_force_launder(vm_page_t m)
1730 swap_pager_unswapped(m);
1734 * SWP_PAGER_FORCE_PAGEIN() - force swap blocks to be paged in
1736 * This routine dissociates pages starting at the given index within an
1737 * object from their backing store, paging them in if they do not reside
1738 * in memory. Pages that are paged in are marked dirty and placed in the
1739 * laundry queue. Pages are marked dirty because they no longer have
1740 * backing store. They are placed in the laundry queue because they have
1741 * not been accessed recently. Otherwise, they would already reside in
1745 swp_pager_force_pagein(vm_object_t object, vm_pindex_t pindex, int npages)
1747 vm_page_t ma[npages];
1750 KASSERT(npages > 0, ("%s: No pages", __func__));
1751 KASSERT(npages <= MAXPHYS / PAGE_SIZE,
1752 ("%s: Too many pages: %d", __func__, npages));
1753 KASSERT(object->type == OBJT_SWAP,
1754 ("%s: Object not swappable", __func__));
1755 vm_object_pip_add(object, npages);
1756 vm_page_grab_pages(object, pindex, VM_ALLOC_NORMAL, ma, npages);
1757 for (i = j = 0;; i++) {
1758 /* Count nonresident pages, to page-in all at once. */
1759 if (i < npages && ma[i]->valid != VM_PAGE_BITS_ALL)
1762 VM_OBJECT_WUNLOCK(object);
1763 /* Page-in nonresident pages. Mark for laundering. */
1764 if (swap_pager_getpages(object, &ma[j], i - j, NULL,
1765 NULL) != VM_PAGER_OK)
1766 panic("%s: read from swap failed", __func__);
1767 VM_OBJECT_WLOCK(object);
1769 swp_pager_force_launder(ma[j]);
1774 /* Mark dirty a resident page. */
1775 swp_pager_force_dirty(ma[j++]);
1777 vm_object_pip_wakeupn(object, npages);
1781 * swap_pager_swapoff_object:
1783 * Page in all of the pages that have been paged out for an object
1787 swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object)
1790 vm_pindex_t pi, s_pindex;
1791 daddr_t blk, n_blks, s_blk;
1794 KASSERT(object->type == OBJT_SWAP,
1795 ("%s: Object not swappable", __func__));
1797 for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1798 &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1799 for (i = 0; i < SWAP_META_PAGES; i++) {
1801 if (!swp_pager_isondev(blk, sp))
1805 * If there are no blocks/pages accumulated, start a new
1806 * accumulation here.
1809 if (blk != SWAPBLK_NONE) {
1811 s_pindex = sb->p + i;
1818 * If the accumulation can be extended without breaking
1819 * the sequence of consecutive blocks and pages that
1820 * swp_pager_force_pagein() depends on, do so.
1822 if (n_blks < MAXPHYS / PAGE_SIZE &&
1823 s_blk + n_blks == blk &&
1824 s_pindex + n_blks == sb->p + i) {
1830 * The sequence of consecutive blocks and pages cannot
1831 * be extended, so page them all in here. Then,
1832 * because doing so involves releasing and reacquiring
1833 * a lock that protects the swap block pctrie, do not
1834 * rely on the current swap block. Break this loop and
1835 * re-fetch the same pindex from the pctrie again.
1837 swp_pager_force_pagein(object, s_pindex, n_blks);
1841 if (i == SWAP_META_PAGES)
1842 pi = sb->p + SWAP_META_PAGES;
1845 swp_pager_force_pagein(object, s_pindex, n_blks);
1849 * swap_pager_swapoff:
1851 * Page in all of the pages that have been paged out to the
1852 * given device. The corresponding blocks in the bitmap must be
1853 * marked as allocated and the device must be flagged SW_CLOSING.
1854 * There may be no processes swapped out to the device.
1856 * This routine may block.
1859 swap_pager_swapoff(struct swdevt *sp)
1864 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1868 mtx_lock(&vm_object_list_mtx);
1869 TAILQ_FOREACH(object, &vm_object_list, object_list) {
1870 if (object->type != OBJT_SWAP)
1872 mtx_unlock(&vm_object_list_mtx);
1873 /* Depends on type-stability. */
1874 VM_OBJECT_WLOCK(object);
1877 * Dead objects are eventually terminated on their own.
1879 if ((object->flags & OBJ_DEAD) != 0)
1883 * Sync with fences placed after pctrie
1884 * initialization. We must not access pctrie below
1885 * unless we checked that our object is swap and not
1888 atomic_thread_fence_acq();
1889 if (object->type != OBJT_SWAP)
1892 swap_pager_swapoff_object(sp, object);
1894 VM_OBJECT_WUNLOCK(object);
1895 mtx_lock(&vm_object_list_mtx);
1897 mtx_unlock(&vm_object_list_mtx);
1901 * Objects may be locked or paging to the device being
1902 * removed, so we will miss their pages and need to
1903 * make another pass. We have marked this device as
1904 * SW_CLOSING, so the activity should finish soon.
1907 if (retries > 100) {
1908 panic("swapoff: failed to locate %d swap blocks",
1911 pause("swpoff", hz / 20);
1914 EVENTHANDLER_INVOKE(swapoff, sp);
1917 /************************************************************************
1919 ************************************************************************
1921 * These routines manipulate the swap metadata stored in the
1924 * Swap metadata is implemented with a global hash and not directly
1925 * linked into the object. Instead the object simply contains
1926 * appropriate tracking counters.
1930 * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
1933 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
1937 MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
1938 for (i = start; i < limit; i++) {
1939 if (sb->d[i] != SWAPBLK_NONE)
1946 * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free
1948 * Nothing is done if the block is still in use.
1951 swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb)
1954 if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
1955 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
1956 uma_zfree(swblk_zone, sb);
1961 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
1963 * We first convert the object to a swap object if it is a default
1966 * The specified swapblk is added to the object's swap metadata. If
1967 * the swapblk is not valid, it is freed instead. Any previously
1968 * assigned swapblk is returned.
1971 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
1973 static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
1974 struct swblk *sb, *sb1;
1975 vm_pindex_t modpi, rdpi;
1976 daddr_t prev_swapblk;
1979 VM_OBJECT_ASSERT_WLOCKED(object);
1982 * Convert default object to swap object if necessary
1984 if (object->type != OBJT_SWAP) {
1985 pctrie_init(&object->un_pager.swp.swp_blks);
1988 * Ensure that swap_pager_swapoff()'s iteration over
1989 * object_list does not see a garbage pctrie.
1991 atomic_thread_fence_rel();
1993 object->type = OBJT_SWAP;
1994 object->un_pager.swp.writemappings = 0;
1995 KASSERT((object->flags & OBJ_ANON) != 0 ||
1996 object->handle == NULL,
1997 ("default pager %p with handle %p",
1998 object, object->handle));
2001 rdpi = rounddown(pindex, SWAP_META_PAGES);
2002 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
2004 if (swapblk == SWAPBLK_NONE)
2005 return (SWAPBLK_NONE);
2007 sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
2008 pageproc ? M_USE_RESERVE : 0));
2011 for (i = 0; i < SWAP_META_PAGES; i++)
2012 sb->d[i] = SWAPBLK_NONE;
2013 if (atomic_cmpset_int(&swblk_zone_exhausted,
2015 printf("swblk zone ok\n");
2018 VM_OBJECT_WUNLOCK(object);
2019 if (uma_zone_exhausted(swblk_zone)) {
2020 if (atomic_cmpset_int(&swblk_zone_exhausted,
2022 printf("swap blk zone exhausted, "
2023 "increase kern.maxswzone\n");
2024 vm_pageout_oom(VM_OOM_SWAPZ);
2025 pause("swzonxb", 10);
2027 uma_zwait(swblk_zone);
2028 VM_OBJECT_WLOCK(object);
2029 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2033 * Somebody swapped out a nearby page,
2034 * allocating swblk at the rdpi index,
2035 * while we dropped the object lock.
2040 error = SWAP_PCTRIE_INSERT(
2041 &object->un_pager.swp.swp_blks, sb);
2043 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2045 printf("swpctrie zone ok\n");
2048 VM_OBJECT_WUNLOCK(object);
2049 if (uma_zone_exhausted(swpctrie_zone)) {
2050 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
2052 printf("swap pctrie zone exhausted, "
2053 "increase kern.maxswzone\n");
2054 vm_pageout_oom(VM_OOM_SWAPZ);
2055 pause("swzonxp", 10);
2057 uma_zwait(swpctrie_zone);
2058 VM_OBJECT_WLOCK(object);
2059 sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2062 uma_zfree(swblk_zone, sb);
2069 MPASS(sb->p == rdpi);
2071 modpi = pindex % SWAP_META_PAGES;
2072 /* Return prior contents of metadata. */
2073 prev_swapblk = sb->d[modpi];
2074 /* Enter block into metadata. */
2075 sb->d[modpi] = swapblk;
2078 * Free the swblk if we end up with the empty page run.
2080 if (swapblk == SWAPBLK_NONE)
2081 swp_pager_free_empty_swblk(object, sb);
2082 return (prev_swapblk);
2086 * SWP_PAGER_META_TRANSFER() - free a range of blocks in the srcobject's swap
2087 * metadata, or transfer it into dstobject.
2089 * This routine will free swap metadata structures as they are cleaned
2093 swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject,
2094 vm_pindex_t pindex, vm_pindex_t count)
2097 daddr_t n_free, s_free;
2098 vm_pindex_t offset, last;
2099 int i, limit, start;
2101 VM_OBJECT_ASSERT_WLOCKED(srcobject);
2102 if (srcobject->type != OBJT_SWAP || count == 0)
2105 swp_pager_init_freerange(&s_free, &n_free);
2107 last = pindex + count;
2109 sb = SWAP_PCTRIE_LOOKUP_GE(&srcobject->un_pager.swp.swp_blks,
2110 rounddown(pindex, SWAP_META_PAGES));
2111 if (sb == NULL || sb->p >= last)
2113 start = pindex > sb->p ? pindex - sb->p : 0;
2114 limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
2116 for (i = start; i < limit; i++) {
2117 if (sb->d[i] == SWAPBLK_NONE)
2119 if (dstobject == NULL ||
2120 !swp_pager_xfer_source(srcobject, dstobject,
2121 sb->p + i - offset, sb->d[i])) {
2122 swp_pager_update_freerange(&s_free, &n_free,
2125 sb->d[i] = SWAPBLK_NONE;
2127 pindex = sb->p + SWAP_META_PAGES;
2128 if (swp_pager_swblk_empty(sb, 0, start) &&
2129 swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
2130 SWAP_PCTRIE_REMOVE(&srcobject->un_pager.swp.swp_blks,
2132 uma_zfree(swblk_zone, sb);
2135 swp_pager_freeswapspace(s_free, n_free);
2139 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
2141 * The requested range of blocks is freed, with any associated swap
2142 * returned to the swap bitmap.
2144 * This routine will free swap metadata structures as they are cleaned
2145 * out. This routine does *NOT* operate on swap metadata associated
2146 * with resident pages.
2149 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count)
2151 swp_pager_meta_transfer(object, NULL, pindex, count);
2155 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
2157 * This routine locates and destroys all swap metadata associated with
2161 swp_pager_meta_free_all(vm_object_t object)
2164 daddr_t n_free, s_free;
2168 VM_OBJECT_ASSERT_WLOCKED(object);
2169 if (object->type != OBJT_SWAP)
2172 swp_pager_init_freerange(&s_free, &n_free);
2173 for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
2174 &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
2175 pindex = sb->p + SWAP_META_PAGES;
2176 for (i = 0; i < SWAP_META_PAGES; i++) {
2177 if (sb->d[i] == SWAPBLK_NONE)
2179 swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
2181 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2182 uma_zfree(swblk_zone, sb);
2184 swp_pager_freeswapspace(s_free, n_free);
2188 * SWP_PAGER_METACTL() - misc control of swap meta data.
2190 * This routine is capable of looking up, or removing swapblk
2191 * assignments in the swap meta data. It returns the swapblk being
2192 * looked-up, popped, or SWAPBLK_NONE if the block was invalid.
2194 * When acting on a busy resident page and paging is in progress, we
2195 * have to wait until paging is complete but otherwise can act on the
2199 swp_pager_meta_lookup(vm_object_t object, vm_pindex_t pindex)
2203 VM_OBJECT_ASSERT_LOCKED(object);
2206 * The meta data only exists if the object is OBJT_SWAP
2207 * and even then might not be allocated yet.
2209 KASSERT(object->type == OBJT_SWAP,
2210 ("Lookup object not swappable"));
2212 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2213 rounddown(pindex, SWAP_META_PAGES));
2215 return (SWAPBLK_NONE);
2216 return (sb->d[pindex % SWAP_META_PAGES]);
2220 * Returns the least page index which is greater than or equal to the
2221 * parameter pindex and for which there is a swap block allocated.
2222 * Returns object's size if the object's type is not swap or if there
2223 * are no allocated swap blocks for the object after the requested
2227 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2232 VM_OBJECT_ASSERT_LOCKED(object);
2233 if (object->type != OBJT_SWAP)
2234 return (object->size);
2236 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2237 rounddown(pindex, SWAP_META_PAGES));
2239 return (object->size);
2240 if (sb->p < pindex) {
2241 for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2242 if (sb->d[i] != SWAPBLK_NONE)
2245 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2246 roundup(pindex, SWAP_META_PAGES));
2248 return (object->size);
2250 for (i = 0; i < SWAP_META_PAGES; i++) {
2251 if (sb->d[i] != SWAPBLK_NONE)
2256 * We get here if a swblk is present in the trie but it
2257 * doesn't map any blocks.
2260 return (object->size);
2264 * System call swapon(name) enables swapping on device name,
2265 * which must be in the swdevsw. Return EBUSY
2266 * if already swapping on this device.
2268 #ifndef _SYS_SYSPROTO_H_
2269 struct swapon_args {
2279 sys_swapon(struct thread *td, struct swapon_args *uap)
2283 struct nameidata nd;
2286 error = priv_check(td, PRIV_SWAPON);
2290 sx_xlock(&swdev_syscall_lock);
2293 * Swap metadata may not fit in the KVM if we have physical
2296 if (swblk_zone == NULL) {
2301 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2307 NDFREE(&nd, NDF_ONLY_PNBUF);
2310 if (vn_isdisk(vp, &error)) {
2311 error = swapongeom(vp);
2312 } else if (vp->v_type == VREG &&
2313 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2314 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2316 * Allow direct swapping to NFS regular files in the same
2317 * way that nfs_mountroot() sets up diskless swapping.
2319 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2325 sx_xunlock(&swdev_syscall_lock);
2330 * Check that the total amount of swap currently configured does not
2331 * exceed half the theoretical maximum. If it does, print a warning
2335 swapon_check_swzone(void)
2338 /* recommend using no more than half that amount */
2339 if (swap_total > swap_maxpages / 2) {
2340 printf("warning: total configured swap (%lu pages) "
2341 "exceeds maximum recommended amount (%lu pages).\n",
2342 swap_total, swap_maxpages / 2);
2343 printf("warning: increase kern.maxswzone "
2344 "or reduce amount of swap.\n");
2349 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2350 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2352 struct swdevt *sp, *tsp;
2357 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2358 * First chop nblks off to page-align it, then convert.
2360 * sw->sw_nblks is in page-sized chunks now too.
2362 nblks &= ~(ctodb(1) - 1);
2363 nblks = dbtoc(nblks);
2366 * If we go beyond this, we get overflows in the radix
2369 mblocks = 0x40000000 / BLIST_META_RADIX;
2370 if (nblks > mblocks) {
2372 "WARNING: reducing swap size to maximum of %luMB per unit\n",
2373 mblocks / 1024 / 1024 * PAGE_SIZE);
2377 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2381 sp->sw_nblks = nblks;
2383 sp->sw_strategy = strategy;
2384 sp->sw_close = close;
2385 sp->sw_flags = flags;
2387 sp->sw_blist = blist_create(nblks, M_WAITOK);
2389 * Do not free the first blocks in order to avoid overwriting
2390 * any bsd label at the front of the partition
2392 blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE),
2393 nblks - howmany(BBSIZE, PAGE_SIZE));
2396 mtx_lock(&sw_dev_mtx);
2397 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2398 if (tsp->sw_end >= dvbase) {
2400 * We put one uncovered page between the devices
2401 * in order to definitively prevent any cross-device
2404 dvbase = tsp->sw_end + 1;
2407 sp->sw_first = dvbase;
2408 sp->sw_end = dvbase + nblks;
2409 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2411 swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE);
2412 swap_total += nblks;
2413 swapon_check_swzone();
2415 mtx_unlock(&sw_dev_mtx);
2416 EVENTHANDLER_INVOKE(swapon, sp);
2420 * SYSCALL: swapoff(devname)
2422 * Disable swapping on the given device.
2424 * XXX: Badly designed system call: it should use a device index
2425 * rather than filename as specification. We keep sw_vp around
2426 * only to make this work.
2428 #ifndef _SYS_SYSPROTO_H_
2429 struct swapoff_args {
2439 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2442 struct nameidata nd;
2446 error = priv_check(td, PRIV_SWAPOFF);
2450 sx_xlock(&swdev_syscall_lock);
2452 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2457 NDFREE(&nd, NDF_ONLY_PNBUF);
2460 mtx_lock(&sw_dev_mtx);
2461 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2462 if (sp->sw_vp == vp)
2465 mtx_unlock(&sw_dev_mtx);
2470 error = swapoff_one(sp, td->td_ucred);
2472 sx_xunlock(&swdev_syscall_lock);
2477 swapoff_one(struct swdevt *sp, struct ucred *cred)
2484 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2486 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2487 error = mac_system_check_swapoff(cred, sp->sw_vp);
2488 (void) VOP_UNLOCK(sp->sw_vp);
2492 nblks = sp->sw_nblks;
2495 * We can turn off this swap device safely only if the
2496 * available virtual memory in the system will fit the amount
2497 * of data we will have to page back in, plus an epsilon so
2498 * the system doesn't become critically low on swap space.
2500 if (vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
2504 * Prevent further allocations on this device.
2506 mtx_lock(&sw_dev_mtx);
2507 sp->sw_flags |= SW_CLOSING;
2508 swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2509 swap_total -= nblks;
2510 mtx_unlock(&sw_dev_mtx);
2513 * Page in the contents of the device and close it.
2515 swap_pager_swapoff(sp);
2517 sp->sw_close(curthread, sp);
2518 mtx_lock(&sw_dev_mtx);
2520 TAILQ_REMOVE(&swtailq, sp, sw_list);
2522 if (nswapdev == 0) {
2523 swap_pager_full = 2;
2524 swap_pager_almost_full = 1;
2528 mtx_unlock(&sw_dev_mtx);
2529 blist_destroy(sp->sw_blist);
2530 free(sp, M_VMPGDATA);
2537 struct swdevt *sp, *spt;
2538 const char *devname;
2541 sx_xlock(&swdev_syscall_lock);
2543 mtx_lock(&sw_dev_mtx);
2544 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2545 mtx_unlock(&sw_dev_mtx);
2546 if (vn_isdisk(sp->sw_vp, NULL))
2547 devname = devtoname(sp->sw_vp->v_rdev);
2550 error = swapoff_one(sp, thread0.td_ucred);
2552 printf("Cannot remove swap device %s (error=%d), "
2553 "skipping.\n", devname, error);
2554 } else if (bootverbose) {
2555 printf("Swap device %s removed.\n", devname);
2557 mtx_lock(&sw_dev_mtx);
2559 mtx_unlock(&sw_dev_mtx);
2561 sx_xunlock(&swdev_syscall_lock);
2565 swap_pager_status(int *total, int *used)
2571 mtx_lock(&sw_dev_mtx);
2572 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2573 *total += sp->sw_nblks;
2574 *used += sp->sw_used;
2576 mtx_unlock(&sw_dev_mtx);
2580 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2583 const char *tmp_devname;
2588 mtx_lock(&sw_dev_mtx);
2589 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2594 xs->xsw_version = XSWDEV_VERSION;
2595 xs->xsw_dev = sp->sw_dev;
2596 xs->xsw_flags = sp->sw_flags;
2597 xs->xsw_nblks = sp->sw_nblks;
2598 xs->xsw_used = sp->sw_used;
2599 if (devname != NULL) {
2600 if (vn_isdisk(sp->sw_vp, NULL))
2601 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2603 tmp_devname = "[file]";
2604 strncpy(devname, tmp_devname, len);
2609 mtx_unlock(&sw_dev_mtx);
2613 #if defined(COMPAT_FREEBSD11)
2614 #define XSWDEV_VERSION_11 1
2624 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2627 u_int xsw_dev1, xsw_dev2;
2635 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2638 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2639 struct xswdev32 xs32;
2641 #if defined(COMPAT_FREEBSD11)
2642 struct xswdev11 xs11;
2646 if (arg2 != 1) /* name length */
2648 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2651 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2652 if (req->oldlen == sizeof(xs32)) {
2653 xs32.xsw_version = XSWDEV_VERSION;
2654 xs32.xsw_dev1 = xs.xsw_dev;
2655 xs32.xsw_dev2 = xs.xsw_dev >> 32;
2656 xs32.xsw_flags = xs.xsw_flags;
2657 xs32.xsw_nblks = xs.xsw_nblks;
2658 xs32.xsw_used = xs.xsw_used;
2659 error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2663 #if defined(COMPAT_FREEBSD11)
2664 if (req->oldlen == sizeof(xs11)) {
2665 xs11.xsw_version = XSWDEV_VERSION_11;
2666 xs11.xsw_dev = xs.xsw_dev; /* truncation */
2667 xs11.xsw_flags = xs.xsw_flags;
2668 xs11.xsw_nblks = xs.xsw_nblks;
2669 xs11.xsw_used = xs.xsw_used;
2670 error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2674 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2678 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2679 "Number of swap devices");
2680 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2681 sysctl_vm_swap_info,
2682 "Swap statistics by device");
2685 * Count the approximate swap usage in pages for a vmspace. The
2686 * shadowed or not yet copied on write swap blocks are not accounted.
2687 * The map must be locked.
2690 vmspace_swap_count(struct vmspace *vmspace)
2700 map = &vmspace->vm_map;
2703 VM_MAP_ENTRY_FOREACH(cur, map) {
2704 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2706 object = cur->object.vm_object;
2707 if (object == NULL || object->type != OBJT_SWAP)
2709 VM_OBJECT_RLOCK(object);
2710 if (object->type != OBJT_SWAP)
2712 pi = OFF_TO_IDX(cur->offset);
2713 e = pi + OFF_TO_IDX(cur->end - cur->start);
2714 for (;; pi = sb->p + SWAP_META_PAGES) {
2715 sb = SWAP_PCTRIE_LOOKUP_GE(
2716 &object->un_pager.swp.swp_blks, pi);
2717 if (sb == NULL || sb->p >= e)
2719 for (i = 0; i < SWAP_META_PAGES; i++) {
2720 if (sb->p + i < e &&
2721 sb->d[i] != SWAPBLK_NONE)
2726 VM_OBJECT_RUNLOCK(object);
2734 * Swapping onto disk devices.
2738 static g_orphan_t swapgeom_orphan;
2740 static struct g_class g_swap_class = {
2742 .version = G_VERSION,
2743 .orphan = swapgeom_orphan,
2746 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2750 swapgeom_close_ev(void *arg, int flags)
2752 struct g_consumer *cp;
2755 g_access(cp, -1, -1, 0);
2757 g_destroy_consumer(cp);
2761 * Add a reference to the g_consumer for an inflight transaction.
2764 swapgeom_acquire(struct g_consumer *cp)
2767 mtx_assert(&sw_dev_mtx, MA_OWNED);
2772 * Remove a reference from the g_consumer. Post a close event if all
2773 * references go away, since the function might be called from the
2777 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2780 mtx_assert(&sw_dev_mtx, MA_OWNED);
2782 if (cp->index == 0) {
2783 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2789 swapgeom_done(struct bio *bp2)
2793 struct g_consumer *cp;
2795 bp = bp2->bio_caller2;
2797 bp->b_ioflags = bp2->bio_flags;
2799 bp->b_ioflags |= BIO_ERROR;
2800 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2801 bp->b_error = bp2->bio_error;
2802 bp->b_caller1 = NULL;
2804 sp = bp2->bio_caller1;
2805 mtx_lock(&sw_dev_mtx);
2806 swapgeom_release(cp, sp);
2807 mtx_unlock(&sw_dev_mtx);
2812 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2815 struct g_consumer *cp;
2817 mtx_lock(&sw_dev_mtx);
2820 mtx_unlock(&sw_dev_mtx);
2821 bp->b_error = ENXIO;
2822 bp->b_ioflags |= BIO_ERROR;
2826 swapgeom_acquire(cp);
2827 mtx_unlock(&sw_dev_mtx);
2828 if (bp->b_iocmd == BIO_WRITE)
2831 bio = g_alloc_bio();
2833 mtx_lock(&sw_dev_mtx);
2834 swapgeom_release(cp, sp);
2835 mtx_unlock(&sw_dev_mtx);
2836 bp->b_error = ENOMEM;
2837 bp->b_ioflags |= BIO_ERROR;
2838 printf("swap_pager: cannot allocate bio\n");
2843 bp->b_caller1 = bio;
2844 bio->bio_caller1 = sp;
2845 bio->bio_caller2 = bp;
2846 bio->bio_cmd = bp->b_iocmd;
2847 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2848 bio->bio_length = bp->b_bcount;
2849 bio->bio_done = swapgeom_done;
2850 if (!buf_mapped(bp)) {
2851 bio->bio_ma = bp->b_pages;
2852 bio->bio_data = unmapped_buf;
2853 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2854 bio->bio_ma_n = bp->b_npages;
2855 bio->bio_flags |= BIO_UNMAPPED;
2857 bio->bio_data = bp->b_data;
2860 g_io_request(bio, cp);
2865 swapgeom_orphan(struct g_consumer *cp)
2870 mtx_lock(&sw_dev_mtx);
2871 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2872 if (sp->sw_id == cp) {
2873 sp->sw_flags |= SW_CLOSING;
2878 * Drop reference we were created with. Do directly since we're in a
2879 * special context where we don't have to queue the call to
2880 * swapgeom_close_ev().
2883 destroy = ((sp != NULL) && (cp->index == 0));
2886 mtx_unlock(&sw_dev_mtx);
2888 swapgeom_close_ev(cp, 0);
2892 swapgeom_close(struct thread *td, struct swdevt *sw)
2894 struct g_consumer *cp;
2896 mtx_lock(&sw_dev_mtx);
2899 mtx_unlock(&sw_dev_mtx);
2902 * swapgeom_close() may be called from the biodone context,
2903 * where we cannot perform topology changes. Delegate the
2904 * work to the events thread.
2907 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2911 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2913 struct g_provider *pp;
2914 struct g_consumer *cp;
2915 static struct g_geom *gp;
2920 pp = g_dev_getprovider(dev);
2923 mtx_lock(&sw_dev_mtx);
2924 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2926 if (cp != NULL && cp->provider == pp) {
2927 mtx_unlock(&sw_dev_mtx);
2931 mtx_unlock(&sw_dev_mtx);
2933 gp = g_new_geomf(&g_swap_class, "swap");
2934 cp = g_new_consumer(gp);
2935 cp->index = 1; /* Number of active I/Os, plus one for being active. */
2936 cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2939 * XXX: Every time you think you can improve the margin for
2940 * footshooting, somebody depends on the ability to do so:
2941 * savecore(8) wants to write to our swapdev so we cannot
2942 * set an exclusive count :-(
2944 error = g_access(cp, 1, 1, 0);
2947 g_destroy_consumer(cp);
2950 nblks = pp->mediasize / DEV_BSIZE;
2951 swaponsomething(vp, cp, nblks, swapgeom_strategy,
2952 swapgeom_close, dev2udev(dev),
2953 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
2958 swapongeom(struct vnode *vp)
2962 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2963 if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) {
2967 error = swapongeom_locked(vp->v_rdev, vp);
2968 g_topology_unlock();
2977 * This is used mainly for network filesystem (read: probably only tested
2978 * with NFS) swapfiles.
2983 swapdev_strategy(struct buf *bp, struct swdevt *sp)
2987 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
2991 if (bp->b_iocmd == BIO_WRITE) {
2993 bufobj_wdrop(bp->b_bufobj);
2994 bufobj_wref(&vp2->v_bufobj);
2996 if (bp->b_bufobj != &vp2->v_bufobj)
2997 bp->b_bufobj = &vp2->v_bufobj;
2999 bp->b_iooffset = dbtob(bp->b_blkno);
3005 swapdev_close(struct thread *td, struct swdevt *sp)
3008 VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
3014 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
3021 mtx_lock(&sw_dev_mtx);
3022 TAILQ_FOREACH(sp, &swtailq, sw_list) {
3023 if (sp->sw_id == vp) {
3024 mtx_unlock(&sw_dev_mtx);
3028 mtx_unlock(&sw_dev_mtx);
3030 (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3032 error = mac_system_check_swapon(td->td_ucred, vp);
3035 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
3036 (void) VOP_UNLOCK(vp);
3040 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
3046 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
3050 new = nsw_wcount_async_max;
3051 error = sysctl_handle_int(oidp, &new, 0, req);
3052 if (error != 0 || req->newptr == NULL)
3055 if (new > nswbuf / 2 || new < 1)
3058 mtx_lock(&swbuf_mtx);
3059 while (nsw_wcount_async_max != new) {
3061 * Adjust difference. If the current async count is too low,
3062 * we will need to sqeeze our update slowly in. Sleep with a
3063 * higher priority than getpbuf() to finish faster.
3065 n = new - nsw_wcount_async_max;
3066 if (nsw_wcount_async + n >= 0) {
3067 nsw_wcount_async += n;
3068 nsw_wcount_async_max += n;
3069 wakeup(&nsw_wcount_async);
3071 nsw_wcount_async_max -= nsw_wcount_async;
3072 nsw_wcount_async = 0;
3073 msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
3077 mtx_unlock(&swbuf_mtx);
3083 swap_pager_update_writecount(vm_object_t object, vm_offset_t start,
3087 VM_OBJECT_WLOCK(object);
3088 KASSERT((object->flags & OBJ_ANON) == 0,
3089 ("Splittable object with writecount"));
3090 object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
3091 VM_OBJECT_WUNLOCK(object);
3095 swap_pager_release_writecount(vm_object_t object, vm_offset_t start,
3099 VM_OBJECT_WLOCK(object);
3100 KASSERT((object->flags & OBJ_ANON) == 0,
3101 ("Splittable object with writecount"));
3102 object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
3103 VM_OBJECT_WUNLOCK(object);