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>
77 #include <sys/systm.h>
79 #include <sys/kernel.h>
85 #include <sys/fcntl.h>
86 #include <sys/mount.h>
87 #include <sys/namei.h>
88 #include <sys/vnode.h>
89 #include <sys/malloc.h>
90 #include <sys/pctrie.h>
91 #include <sys/racct.h>
92 #include <sys/resource.h>
93 #include <sys/resourcevar.h>
94 #include <sys/rwlock.h>
96 #include <sys/sysctl.h>
97 #include <sys/sysproto.h>
98 #include <sys/blist.h>
101 #include <sys/vmmeter.h>
103 #include <security/mac/mac_framework.h>
107 #include <vm/vm_map.h>
108 #include <vm/vm_kern.h>
109 #include <vm/vm_object.h>
110 #include <vm/vm_page.h>
111 #include <vm/vm_pager.h>
112 #include <vm/vm_pageout.h>
113 #include <vm/vm_param.h>
114 #include <vm/swap_pager.h>
115 #include <vm/vm_extern.h>
118 #include <geom/geom.h>
121 * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64.
122 * The 64-page limit is due to the radix code (kern/subr_blist.c).
124 #ifndef MAX_PAGEOUT_CLUSTER
125 #define MAX_PAGEOUT_CLUSTER 32
128 #if !defined(SWB_NPAGES)
129 #define SWB_NPAGES MAX_PAGEOUT_CLUSTER
132 #define SWAP_META_PAGES PCTRIE_COUNT
135 * A swblk structure maps each page index within a
136 * SWAP_META_PAGES-aligned and sized range to the address of an
137 * on-disk swap block (or SWAPBLK_NONE). The collection of these
138 * mappings for an entire vm object is implemented as a pc-trie.
142 daddr_t d[SWAP_META_PAGES];
145 static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data");
146 static struct mtx sw_dev_mtx;
147 static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq);
148 static struct swdevt *swdevhd; /* Allocate from here next */
149 static int nswapdev; /* Number of swap devices */
150 int swap_pager_avail;
151 static struct sx swdev_syscall_lock; /* serialize swap(on|off) */
153 static u_long swap_reserved;
154 static u_long swap_total;
155 static int sysctl_page_shift(SYSCTL_HANDLER_ARGS);
156 SYSCTL_PROC(_vm, OID_AUTO, swap_reserved, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
157 &swap_reserved, 0, sysctl_page_shift, "A",
158 "Amount of swap storage needed to back all allocated anonymous memory.");
159 SYSCTL_PROC(_vm, OID_AUTO, swap_total, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE,
160 &swap_total, 0, sysctl_page_shift, "A",
161 "Total amount of available swap storage.");
163 static int overcommit = 0;
164 SYSCTL_INT(_vm, VM_OVERCOMMIT, overcommit, CTLFLAG_RW, &overcommit, 0,
165 "Configure virtual memory overcommit behavior. See tuning(7) "
167 static unsigned long swzone;
168 SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
169 "Actual size of swap metadata zone");
170 static unsigned long swap_maxpages;
171 SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
172 "Maximum amount of swap supported");
174 /* bits from overcommit */
175 #define SWAP_RESERVE_FORCE_ON (1 << 0)
176 #define SWAP_RESERVE_RLIMIT_ON (1 << 1)
177 #define SWAP_RESERVE_ALLOW_NONWIRED (1 << 2)
180 sysctl_page_shift(SYSCTL_HANDLER_ARGS)
183 u_long value = *(u_long *)arg1;
185 newval = ((uint64_t)value) << PAGE_SHIFT;
186 return (sysctl_handle_64(oidp, &newval, 0, req));
190 swap_reserve(vm_ooffset_t incr)
193 return (swap_reserve_by_cred(incr, curthread->td_ucred));
197 swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
199 u_long r, s, prev, pincr;
202 static struct timeval lastfail;
205 uip = cred->cr_ruidinfo;
207 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
213 error = racct_add(curproc, RACCT_SWAP, incr);
214 PROC_UNLOCK(curproc);
222 prev = atomic_fetchadd_long(&swap_reserved, pincr);
224 if (overcommit & SWAP_RESERVE_ALLOW_NONWIRED) {
225 s = vm_cnt.v_page_count - vm_cnt.v_free_reserved -
230 if ((overcommit & SWAP_RESERVE_FORCE_ON) == 0 || r <= s ||
231 (error = priv_check(curthread, PRIV_VM_SWAP_NOQUOTA)) == 0) {
234 prev = atomic_fetchadd_long(&swap_reserved, -pincr);
236 panic("swap_reserved < incr on overcommit fail");
239 prev = atomic_fetchadd_long(&uip->ui_vmsize, pincr);
240 if ((overcommit & SWAP_RESERVE_RLIMIT_ON) != 0 &&
241 prev + pincr > lim_cur(curthread, RLIMIT_SWAP) &&
242 priv_check(curthread, PRIV_VM_SWAP_NORLIMIT)) {
244 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pincr);
246 panic("uip->ui_vmsize < incr on overcommit fail");
249 if (!res && ppsratecheck(&lastfail, &curfail, 1)) {
250 printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
251 uip->ui_uid, curproc->p_pid, incr);
255 if (racct_enable && !res) {
257 racct_sub(curproc, RACCT_SWAP, incr);
258 PROC_UNLOCK(curproc);
266 swap_reserve_force(vm_ooffset_t incr)
271 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", __func__,
277 racct_add_force(curproc, RACCT_SWAP, incr);
280 atomic_add_long(&swap_reserved, pincr);
281 uip = curproc->p_ucred->cr_ruidinfo;
282 atomic_add_long(&uip->ui_vmsize, pincr);
283 PROC_UNLOCK(curproc);
287 swap_release(vm_ooffset_t decr)
292 cred = curproc->p_ucred;
293 swap_release_by_cred(decr, cred);
294 PROC_UNLOCK(curproc);
298 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
303 uip = cred->cr_ruidinfo;
305 KASSERT((decr & PAGE_MASK) == 0, ("%s: decr: %ju & PAGE_MASK", __func__,
309 prev = atomic_fetchadd_long(&swap_reserved, -pdecr);
311 panic("swap_reserved < decr");
313 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pdecr);
315 printf("negative vmsize for uid = %d\n", uip->ui_uid);
318 racct_sub_cred(cred, RACCT_SWAP, decr);
322 #define SWM_POP 0x01 /* pop out */
324 static int swap_pager_full = 2; /* swap space exhaustion (task killing) */
325 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
326 static struct mtx swbuf_mtx; /* to sync nsw_wcount_async */
327 static int nsw_wcount_async; /* limit async write buffers */
328 static int nsw_wcount_async_max;/* assigned maximum */
329 static int nsw_cluster_max; /* maximum VOP I/O allowed */
331 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
332 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
333 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
334 "Maximum running async swap ops");
335 static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS);
336 SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD |
337 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A",
338 "Swap Fragmentation Info");
340 static struct sx sw_alloc_sx;
343 * "named" and "unnamed" anon region objects. Try to reduce the overhead
344 * of searching a named list by hashing it just a little.
349 #define NOBJLIST(handle) \
350 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
352 static struct pagerlst swap_pager_object_list[NOBJLISTS];
353 static uma_zone_t swwbuf_zone;
354 static uma_zone_t swrbuf_zone;
355 static uma_zone_t swblk_zone;
356 static uma_zone_t swpctrie_zone;
359 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
360 * calls hooked from other parts of the VM system and do not appear here.
361 * (see vm/swap_pager.h).
364 swap_pager_alloc(void *handle, vm_ooffset_t size,
365 vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
366 static void swap_pager_dealloc(vm_object_t object);
367 static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
369 static int swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
370 int *, pgo_getpages_iodone_t, void *);
371 static void swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
373 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
374 static void swap_pager_init(void);
375 static void swap_pager_unswapped(vm_page_t);
376 static void swap_pager_swapoff(struct swdevt *sp);
378 struct pagerops swappagerops = {
379 .pgo_init = swap_pager_init, /* early system initialization of pager */
380 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */
381 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
382 .pgo_getpages = swap_pager_getpages, /* pagein */
383 .pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
384 .pgo_putpages = swap_pager_putpages, /* pageout */
385 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */
386 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
390 * swap_*() routines are externally accessible. swp_*() routines are
393 static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
394 static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
396 SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
397 "Maximum size of a swap block in pages");
399 static void swp_sizecheck(void);
400 static void swp_pager_async_iodone(struct buf *bp);
401 static bool swp_pager_swblk_empty(struct swblk *sb, int start, int limit);
402 static int swapongeom(struct vnode *);
403 static int swaponvp(struct thread *, struct vnode *, u_long);
404 static int swapoff_one(struct swdevt *sp, struct ucred *cred);
407 * Swap bitmap functions
409 static void swp_pager_freeswapspace(daddr_t blk, daddr_t npages);
410 static daddr_t swp_pager_getswapspace(int npages);
415 static daddr_t swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
416 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t);
417 static void swp_pager_meta_free_all(vm_object_t);
418 static daddr_t swp_pager_meta_ctl(vm_object_t, vm_pindex_t, int);
421 swp_pager_init_freerange(daddr_t *start, daddr_t *num)
424 *start = SWAPBLK_NONE;
429 swp_pager_update_freerange(daddr_t *start, daddr_t *num, daddr_t addr)
432 if (*start + *num == addr) {
435 swp_pager_freeswapspace(*start, *num);
442 swblk_trie_alloc(struct pctrie *ptree)
445 return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
446 M_USE_RESERVE : 0)));
450 swblk_trie_free(struct pctrie *ptree, void *node)
453 uma_zfree(swpctrie_zone, node);
456 PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
459 * SWP_SIZECHECK() - update swap_pager_full indication
461 * update the swap_pager_almost_full indication and warn when we are
462 * about to run out of swap space, using lowat/hiwat hysteresis.
464 * Clear swap_pager_full ( task killing ) indication when lowat is met.
466 * No restrictions on call
467 * This routine may not block.
473 if (swap_pager_avail < nswap_lowat) {
474 if (swap_pager_almost_full == 0) {
475 printf("swap_pager: out of swap space\n");
476 swap_pager_almost_full = 1;
480 if (swap_pager_avail > nswap_hiwat)
481 swap_pager_almost_full = 0;
486 * SWAP_PAGER_INIT() - initialize the swap pager!
488 * Expected to be started from system init. NOTE: This code is run
489 * before much else so be careful what you depend on. Most of the VM
490 * system has yet to be initialized at this point.
493 swap_pager_init(void)
496 * Initialize object lists
500 for (i = 0; i < NOBJLISTS; ++i)
501 TAILQ_INIT(&swap_pager_object_list[i]);
502 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
503 sx_init(&sw_alloc_sx, "swspsx");
504 sx_init(&swdev_syscall_lock, "swsysc");
508 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
510 * Expected to be started from pageout process once, prior to entering
514 swap_pager_swap_init(void)
519 * Number of in-transit swap bp operations. Don't
520 * exhaust the pbufs completely. Make sure we
521 * initialize workable values (0 will work for hysteresis
522 * but it isn't very efficient).
524 * The nsw_cluster_max is constrained by the bp->b_pages[]
525 * array (MAXPHYS/PAGE_SIZE) and our locally defined
526 * MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
527 * constrained by the swap device interleave stripe size.
529 * Currently we hardwire nsw_wcount_async to 4. This limit is
530 * designed to prevent other I/O from having high latencies due to
531 * our pageout I/O. The value 4 works well for one or two active swap
532 * devices but is probably a little low if you have more. Even so,
533 * a higher value would probably generate only a limited improvement
534 * with three or four active swap devices since the system does not
535 * typically have to pageout at extreme bandwidths. We will want
536 * at least 2 per swap devices, and 4 is a pretty good value if you
537 * have one NFS swap device due to the command/ack latency over NFS.
538 * So it all works out pretty well.
540 nsw_cluster_max = min((MAXPHYS/PAGE_SIZE), MAX_PAGEOUT_CLUSTER);
542 nsw_wcount_async = 4;
543 nsw_wcount_async_max = nsw_wcount_async;
544 mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF);
546 swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4);
547 swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2);
550 * Initialize our zone, taking the user's requested size or
551 * estimating the number we need based on the number of pages
554 n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) :
555 vm_cnt.v_page_count / 2;
556 swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
557 pctrie_zone_init, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM);
558 if (swpctrie_zone == NULL)
559 panic("failed to create swap pctrie zone.");
560 swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
561 NULL, NULL, _Alignof(struct swblk) - 1, UMA_ZONE_VM);
562 if (swblk_zone == NULL)
563 panic("failed to create swap blk zone.");
566 if (uma_zone_reserve_kva(swblk_zone, n))
569 * if the allocation failed, try a zone two thirds the
570 * size of the previous attempt.
576 * Often uma_zone_reserve_kva() cannot reserve exactly the
577 * requested size. Account for the difference when
578 * calculating swap_maxpages.
580 n = uma_zone_get_max(swblk_zone);
583 printf("Swap blk zone entries changed from %lu to %lu.\n",
585 swap_maxpages = n * SWAP_META_PAGES;
586 swzone = n * sizeof(struct swblk);
587 if (!uma_zone_reserve_kva(swpctrie_zone, n))
588 printf("Cannot reserve swap pctrie zone, "
589 "reduce kern.maxswzone.\n");
593 swap_pager_alloc_init(void *handle, struct ucred *cred, vm_ooffset_t size,
599 if (!swap_reserve_by_cred(size, cred))
605 * The un_pager.swp.swp_blks trie is initialized by
606 * vm_object_allocate() to ensure the correct order of
607 * visibility to other threads.
609 object = vm_object_allocate(OBJT_SWAP, OFF_TO_IDX(offset +
612 object->handle = handle;
615 object->charge = size;
621 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
622 * its metadata structures.
624 * This routine is called from the mmap and fork code to create a new
627 * This routine must ensure that no live duplicate is created for
628 * the named object request, which is protected against by
629 * holding the sw_alloc_sx lock in case handle != NULL.
632 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
633 vm_ooffset_t offset, struct ucred *cred)
637 if (handle != NULL) {
639 * Reference existing named region or allocate new one. There
640 * should not be a race here against swp_pager_meta_build()
641 * as called from vm_page_remove() in regards to the lookup
644 sx_xlock(&sw_alloc_sx);
645 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
646 if (object == NULL) {
647 object = swap_pager_alloc_init(handle, cred, size,
649 if (object != NULL) {
650 TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
651 object, pager_object_list);
654 sx_xunlock(&sw_alloc_sx);
656 object = swap_pager_alloc_init(handle, cred, size, offset);
662 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
664 * The swap backing for the object is destroyed. The code is
665 * designed such that we can reinstantiate it later, but this
666 * routine is typically called only when the entire object is
667 * about to be destroyed.
669 * The object must be locked.
672 swap_pager_dealloc(vm_object_t object)
675 VM_OBJECT_ASSERT_WLOCKED(object);
676 KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
679 * Remove from list right away so lookups will fail if we block for
680 * pageout completion.
682 if (object->handle != NULL) {
683 VM_OBJECT_WUNLOCK(object);
684 sx_xlock(&sw_alloc_sx);
685 TAILQ_REMOVE(NOBJLIST(object->handle), object,
687 sx_xunlock(&sw_alloc_sx);
688 VM_OBJECT_WLOCK(object);
691 vm_object_pip_wait(object, "swpdea");
694 * Free all remaining metadata. We only bother to free it from
695 * the swap meta data. We do not attempt to free swapblk's still
696 * associated with vm_page_t's for this object. We do not care
697 * if paging is still in progress on some objects.
699 swp_pager_meta_free_all(object);
700 object->handle = NULL;
701 object->type = OBJT_DEAD;
704 /************************************************************************
705 * SWAP PAGER BITMAP ROUTINES *
706 ************************************************************************/
709 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
711 * Allocate swap for the requested number of pages. The starting
712 * swap block number (a page index) is returned or SWAPBLK_NONE
713 * if the allocation failed.
715 * Also has the side effect of advising that somebody made a mistake
716 * when they configured swap and didn't configure enough.
718 * This routine may not sleep.
720 * We allocate in round-robin fashion from the configured devices.
723 swp_pager_getswapspace(int npages)
730 mtx_lock(&sw_dev_mtx);
732 for (i = 0; i < nswapdev; i++) {
734 sp = TAILQ_FIRST(&swtailq);
735 if (!(sp->sw_flags & SW_CLOSING)) {
736 blk = blist_alloc(sp->sw_blist, npages);
737 if (blk != SWAPBLK_NONE) {
739 sp->sw_used += npages;
740 swap_pager_avail -= npages;
742 swdevhd = TAILQ_NEXT(sp, sw_list);
746 sp = TAILQ_NEXT(sp, sw_list);
748 if (swap_pager_full != 2) {
749 printf("swap_pager_getswapspace(%d): failed\n", npages);
751 swap_pager_almost_full = 1;
755 mtx_unlock(&sw_dev_mtx);
760 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
763 return (blk >= sp->sw_first && blk < sp->sw_end);
767 swp_pager_strategy(struct buf *bp)
771 mtx_lock(&sw_dev_mtx);
772 TAILQ_FOREACH(sp, &swtailq, sw_list) {
773 if (swp_pager_isondev(bp->b_blkno, sp)) {
774 mtx_unlock(&sw_dev_mtx);
775 if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
776 unmapped_buf_allowed) {
777 bp->b_data = unmapped_buf;
780 pmap_qenter((vm_offset_t)bp->b_data,
781 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
783 sp->sw_strategy(bp, sp);
787 panic("Swapdev not found");
792 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
794 * This routine returns the specified swap blocks back to the bitmap.
796 * This routine may not sleep.
799 swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
805 mtx_lock(&sw_dev_mtx);
806 TAILQ_FOREACH(sp, &swtailq, sw_list) {
807 if (swp_pager_isondev(blk, sp)) {
808 sp->sw_used -= npages;
810 * If we are attempting to stop swapping on
811 * this device, we don't want to mark any
812 * blocks free lest they be reused.
814 if ((sp->sw_flags & SW_CLOSING) == 0) {
815 blist_free(sp->sw_blist, blk - sp->sw_first,
817 swap_pager_avail += npages;
820 mtx_unlock(&sw_dev_mtx);
824 panic("Swapdev not found");
828 * SYSCTL_SWAP_FRAGMENTATION() - produce raw swap space stats
831 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
838 error = sysctl_wire_old_buffer(req, 0);
841 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
842 mtx_lock(&sw_dev_mtx);
843 TAILQ_FOREACH(sp, &swtailq, sw_list) {
844 if (vn_isdisk(sp->sw_vp, NULL))
845 devname = devtoname(sp->sw_vp->v_rdev);
848 sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
849 blist_stats(sp->sw_blist, &sbuf);
851 mtx_unlock(&sw_dev_mtx);
852 error = sbuf_finish(&sbuf);
858 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
859 * range within an object.
861 * This is a globally accessible routine.
863 * This routine removes swapblk assignments from swap metadata.
865 * The external callers of this routine typically have already destroyed
866 * or renamed vm_page_t's associated with this range in the object so
869 * The object must be locked.
872 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
875 swp_pager_meta_free(object, start, size);
879 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
881 * Assigns swap blocks to the specified range within the object. The
882 * swap blocks are not zeroed. Any previous swap assignment is destroyed.
884 * Returns 0 on success, -1 on failure.
887 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
890 daddr_t blk = SWAPBLK_NONE;
891 vm_pindex_t beg = start; /* save start index */
892 daddr_t addr, n_free, s_free;
894 swp_pager_init_freerange(&s_free, &n_free);
895 VM_OBJECT_WLOCK(object);
899 while ((blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE) {
902 swp_pager_meta_free(object, beg, start - beg);
903 VM_OBJECT_WUNLOCK(object);
908 addr = swp_pager_meta_build(object, start, blk);
909 if (addr != SWAPBLK_NONE)
910 swp_pager_update_freerange(&s_free, &n_free, addr);
916 swp_pager_freeswapspace(s_free, n_free);
917 swp_pager_meta_free(object, start, n);
918 VM_OBJECT_WUNLOCK(object);
923 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
924 * and destroy the source.
926 * Copy any valid swapblks from the source to the destination. In
927 * cases where both the source and destination have a valid swapblk,
928 * we keep the destination's.
930 * This routine is allowed to sleep. It may sleep allocating metadata
931 * indirectly through swp_pager_meta_build() or if paging is still in
932 * progress on the source.
934 * The source object contains no vm_page_t's (which is just as well)
936 * The source object is of type OBJT_SWAP.
938 * The source and destination objects must be locked.
939 * Both object locks may temporarily be released.
942 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
943 vm_pindex_t offset, int destroysource)
946 daddr_t dstaddr, n_free, s_free, srcaddr;
948 VM_OBJECT_ASSERT_WLOCKED(srcobject);
949 VM_OBJECT_ASSERT_WLOCKED(dstobject);
952 * If destroysource is set, we remove the source object from the
953 * swap_pager internal queue now.
955 if (destroysource && srcobject->handle != NULL) {
956 vm_object_pip_add(srcobject, 1);
957 VM_OBJECT_WUNLOCK(srcobject);
958 vm_object_pip_add(dstobject, 1);
959 VM_OBJECT_WUNLOCK(dstobject);
960 sx_xlock(&sw_alloc_sx);
961 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
963 sx_xunlock(&sw_alloc_sx);
964 VM_OBJECT_WLOCK(dstobject);
965 vm_object_pip_wakeup(dstobject);
966 VM_OBJECT_WLOCK(srcobject);
967 vm_object_pip_wakeup(srcobject);
971 * Transfer source to destination.
973 swp_pager_init_freerange(&s_free, &n_free);
974 for (i = 0; i < dstobject->size; ++i) {
975 srcaddr = swp_pager_meta_ctl(srcobject, i + offset, SWM_POP);
976 if (srcaddr == SWAPBLK_NONE)
978 dstaddr = swp_pager_meta_ctl(dstobject, i, 0);
979 if (dstaddr != SWAPBLK_NONE) {
981 * Destination has valid swapblk or it is represented
982 * by a resident page. We destroy the source block.
984 swp_pager_update_freerange(&s_free, &n_free, srcaddr);
989 * Destination has no swapblk and is not resident,
992 * swp_pager_meta_build() can sleep.
994 vm_object_pip_add(srcobject, 1);
995 VM_OBJECT_WUNLOCK(srcobject);
996 vm_object_pip_add(dstobject, 1);
997 dstaddr = swp_pager_meta_build(dstobject, i, srcaddr);
998 KASSERT(dstaddr == SWAPBLK_NONE,
999 ("Unexpected destination swapblk"));
1000 vm_object_pip_wakeup(dstobject);
1001 VM_OBJECT_WLOCK(srcobject);
1002 vm_object_pip_wakeup(srcobject);
1004 swp_pager_freeswapspace(s_free, n_free);
1007 * Free left over swap blocks in source.
1009 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
1010 * double-remove the object from the swap queues.
1012 if (destroysource) {
1013 swp_pager_meta_free_all(srcobject);
1015 * Reverting the type is not necessary, the caller is going
1016 * to destroy srcobject directly, but I'm doing it here
1017 * for consistency since we've removed the object from its
1020 srcobject->type = OBJT_DEFAULT;
1025 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
1026 * the requested page.
1028 * We determine whether good backing store exists for the requested
1029 * page and return TRUE if it does, FALSE if it doesn't.
1031 * If TRUE, we also try to determine how much valid, contiguous backing
1032 * store exists before and after the requested page.
1035 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1041 VM_OBJECT_ASSERT_LOCKED(object);
1044 * do we have good backing store at the requested index ?
1046 blk0 = swp_pager_meta_ctl(object, pindex, 0);
1047 if (blk0 == SWAPBLK_NONE) {
1056 * find backwards-looking contiguous good backing store
1058 if (before != NULL) {
1059 for (i = 1; i < SWB_NPAGES; i++) {
1062 blk = swp_pager_meta_ctl(object, pindex - i, 0);
1063 if (blk != blk0 - i)
1070 * find forward-looking contiguous good backing store
1072 if (after != NULL) {
1073 for (i = 1; i < SWB_NPAGES; i++) {
1074 blk = swp_pager_meta_ctl(object, pindex + i, 0);
1075 if (blk != blk0 + i)
1084 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1086 * This removes any associated swap backing store, whether valid or
1087 * not, from the page.
1089 * This routine is typically called when a page is made dirty, at
1090 * which point any associated swap can be freed. MADV_FREE also
1091 * calls us in a special-case situation
1093 * NOTE!!! If the page is clean and the swap was valid, the caller
1094 * should make the page dirty before calling this routine. This routine
1095 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1098 * This routine may not sleep.
1100 * The object containing the page must be locked.
1103 swap_pager_unswapped(vm_page_t m)
1107 srcaddr = swp_pager_meta_ctl(m->object, m->pindex, SWM_POP);
1108 if (srcaddr != SWAPBLK_NONE)
1109 swp_pager_freeswapspace(srcaddr, 1);
1113 * swap_pager_getpages() - bring pages in from swap
1115 * Attempt to page in the pages in array "ma" of length "count". The
1116 * caller may optionally specify that additional pages preceding and
1117 * succeeding the specified range be paged in. The number of such pages
1118 * is returned in the "rbehind" and "rahead" parameters, and they will
1119 * be in the inactive queue upon return.
1121 * The pages in "ma" must be busied and will remain busied upon return.
1124 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count, int *rbehind,
1128 vm_page_t bm, mpred, msucc, p;
1131 int i, maxahead, maxbehind, reqcount;
1136 * Determine the final number of read-behind pages and
1137 * allocate them BEFORE releasing the object lock. Otherwise,
1138 * there can be a problematic race with vm_object_split().
1139 * Specifically, vm_object_split() might first transfer pages
1140 * that precede ma[0] in the current object to a new object,
1141 * and then this function incorrectly recreates those pages as
1142 * read-behind pages in the current object.
1144 if (!swap_pager_haspage(object, ma[0]->pindex, &maxbehind, &maxahead))
1145 return (VM_PAGER_FAIL);
1148 * Clip the readahead and readbehind ranges to exclude resident pages.
1150 if (rahead != NULL) {
1151 KASSERT(reqcount - 1 <= maxahead,
1152 ("page count %d extends beyond swap block", reqcount));
1153 *rahead = imin(*rahead, maxahead - (reqcount - 1));
1154 pindex = ma[reqcount - 1]->pindex;
1155 msucc = TAILQ_NEXT(ma[reqcount - 1], listq);
1156 if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1157 *rahead = msucc->pindex - pindex - 1;
1159 if (rbehind != NULL) {
1160 *rbehind = imin(*rbehind, maxbehind);
1161 pindex = ma[0]->pindex;
1162 mpred = TAILQ_PREV(ma[0], pglist, listq);
1163 if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1164 *rbehind = pindex - mpred->pindex - 1;
1168 for (i = 0; i < count; i++)
1169 ma[i]->oflags |= VPO_SWAPINPROG;
1172 * Allocate readahead and readbehind pages.
1174 if (rbehind != NULL) {
1175 for (i = 1; i <= *rbehind; i++) {
1176 p = vm_page_alloc(object, ma[0]->pindex - i,
1180 p->oflags |= VPO_SWAPINPROG;
1185 if (rahead != NULL) {
1186 for (i = 0; i < *rahead; i++) {
1187 p = vm_page_alloc(object,
1188 ma[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1191 p->oflags |= VPO_SWAPINPROG;
1195 if (rbehind != NULL)
1200 vm_object_pip_add(object, count);
1202 pindex = bm->pindex;
1203 blk = swp_pager_meta_ctl(object, pindex, 0);
1204 KASSERT(blk != SWAPBLK_NONE,
1205 ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1207 VM_OBJECT_WUNLOCK(object);
1208 bp = uma_zalloc(swrbuf_zone, M_WAITOK);
1209 /* Pages cannot leave the object while busy. */
1210 for (i = 0, p = bm; i < count; i++, p = TAILQ_NEXT(p, listq)) {
1211 MPASS(p->pindex == bm->pindex + i);
1215 bp->b_flags |= B_PAGING;
1216 bp->b_iocmd = BIO_READ;
1217 bp->b_iodone = swp_pager_async_iodone;
1218 bp->b_rcred = crhold(thread0.td_ucred);
1219 bp->b_wcred = crhold(thread0.td_ucred);
1221 bp->b_bcount = PAGE_SIZE * count;
1222 bp->b_bufsize = PAGE_SIZE * count;
1223 bp->b_npages = count;
1224 bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1225 bp->b_pgafter = rahead != NULL ? *rahead : 0;
1227 VM_CNT_INC(v_swapin);
1228 VM_CNT_ADD(v_swappgsin, count);
1231 * perform the I/O. NOTE!!! bp cannot be considered valid after
1232 * this point because we automatically release it on completion.
1233 * Instead, we look at the one page we are interested in which we
1234 * still hold a lock on even through the I/O completion.
1236 * The other pages in our ma[] array are also released on completion,
1237 * so we cannot assume they are valid anymore either.
1239 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1242 swp_pager_strategy(bp);
1245 * Wait for the pages we want to complete. VPO_SWAPINPROG is always
1246 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1247 * is set in the metadata for each page in the request.
1249 VM_OBJECT_WLOCK(object);
1250 while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) {
1251 ma[0]->oflags |= VPO_SWAPSLEEP;
1252 VM_CNT_INC(v_intrans);
1253 if (VM_OBJECT_SLEEP(object, &object->paging_in_progress, PSWP,
1254 "swread", hz * 20)) {
1256 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1257 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1262 * If we had an unrecoverable read error pages will not be valid.
1264 for (i = 0; i < reqcount; i++)
1265 if (ma[i]->valid != VM_PAGE_BITS_ALL)
1266 return (VM_PAGER_ERROR);
1268 return (VM_PAGER_OK);
1271 * A final note: in a low swap situation, we cannot deallocate swap
1272 * and mark a page dirty here because the caller is likely to mark
1273 * the page clean when we return, causing the page to possibly revert
1274 * to all-zero's later.
1279 * swap_pager_getpages_async():
1281 * Right now this is emulation of asynchronous operation on top of
1282 * swap_pager_getpages().
1285 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count,
1286 int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1290 r = swap_pager_getpages(object, ma, count, rbehind, rahead);
1291 VM_OBJECT_WUNLOCK(object);
1296 case VM_PAGER_ERROR:
1303 panic("unhandled swap_pager_getpages() error %d", r);
1305 (iodone)(arg, ma, count, error);
1306 VM_OBJECT_WLOCK(object);
1312 * swap_pager_putpages:
1314 * Assign swap (if necessary) and initiate I/O on the specified pages.
1316 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1317 * are automatically converted to SWAP objects.
1319 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1320 * vm_page reservation system coupled with properly written VFS devices
1321 * should ensure that no low-memory deadlock occurs. This is an area
1324 * The parent has N vm_object_pip_add() references prior to
1325 * calling us and will remove references for rtvals[] that are
1326 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1329 * The parent has soft-busy'd the pages it passes us and will unbusy
1330 * those whos rtvals[] entry is not set to VM_PAGER_PEND on return.
1331 * We need to unbusy the rest on I/O completion.
1334 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count,
1335 int flags, int *rtvals)
1339 daddr_t addr, n_free, s_free;
1341 swp_pager_init_freerange(&s_free, &n_free);
1342 if (count && ma[0]->object != object) {
1343 panic("swap_pager_putpages: object mismatch %p/%p",
1352 * Turn object into OBJT_SWAP
1353 * check for bogus sysops
1354 * force sync if not pageout process
1356 if (object->type != OBJT_SWAP) {
1357 addr = swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1358 KASSERT(addr == SWAPBLK_NONE,
1359 ("unexpected object swap block"));
1361 VM_OBJECT_WUNLOCK(object);
1364 if (curproc != pageproc)
1367 sync = (flags & VM_PAGER_PUT_SYNC) != 0;
1372 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1373 * The page is left dirty until the pageout operation completes
1376 for (i = 0; i < count; i += n) {
1382 * Maximum I/O size is limited by a number of factors.
1384 n = min(BLIST_MAX_ALLOC, count - i);
1385 n = min(n, nsw_cluster_max);
1388 * Get biggest block of swap we can. If we fail, fall
1389 * back and try to allocate a smaller block. Don't go
1390 * overboard trying to allocate space if it would overly
1394 (blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE &&
1399 if (blk == SWAPBLK_NONE) {
1400 for (j = 0; j < n; ++j)
1401 rtvals[i+j] = VM_PAGER_FAIL;
1406 * All I/O parameters have been satisfied, build the I/O
1407 * request and assign the swap space.
1410 mtx_lock(&swbuf_mtx);
1411 while (nsw_wcount_async == 0)
1412 msleep(&nsw_wcount_async, &swbuf_mtx, PVM,
1415 mtx_unlock(&swbuf_mtx);
1417 bp = uma_zalloc(swwbuf_zone, M_WAITOK);
1419 bp->b_flags = B_ASYNC;
1420 bp->b_flags |= B_PAGING;
1421 bp->b_iocmd = BIO_WRITE;
1423 bp->b_rcred = crhold(thread0.td_ucred);
1424 bp->b_wcred = crhold(thread0.td_ucred);
1425 bp->b_bcount = PAGE_SIZE * n;
1426 bp->b_bufsize = PAGE_SIZE * n;
1429 VM_OBJECT_WLOCK(object);
1430 for (j = 0; j < n; ++j) {
1431 vm_page_t mreq = ma[i+j];
1433 addr = swp_pager_meta_build(mreq->object, mreq->pindex,
1435 if (addr != SWAPBLK_NONE)
1436 swp_pager_update_freerange(&s_free, &n_free,
1438 MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1439 mreq->oflags |= VPO_SWAPINPROG;
1440 bp->b_pages[j] = mreq;
1442 VM_OBJECT_WUNLOCK(object);
1445 * Must set dirty range for NFS to work.
1448 bp->b_dirtyend = bp->b_bcount;
1450 VM_CNT_INC(v_swapout);
1451 VM_CNT_ADD(v_swappgsout, bp->b_npages);
1454 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1455 * can call the async completion routine at the end of a
1456 * synchronous I/O operation. Otherwise, our caller would
1457 * perform duplicate unbusy and wakeup operations on the page
1458 * and object, respectively.
1460 for (j = 0; j < n; j++)
1461 rtvals[i + j] = VM_PAGER_PEND;
1466 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1468 if (sync == FALSE) {
1469 bp->b_iodone = swp_pager_async_iodone;
1471 swp_pager_strategy(bp);
1478 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1480 bp->b_iodone = bdone;
1481 swp_pager_strategy(bp);
1484 * Wait for the sync I/O to complete.
1486 bwait(bp, PVM, "swwrt");
1489 * Now that we are through with the bp, we can call the
1490 * normal async completion, which frees everything up.
1492 swp_pager_async_iodone(bp);
1494 VM_OBJECT_WLOCK(object);
1495 swp_pager_freeswapspace(s_free, n_free);
1499 * swp_pager_async_iodone:
1501 * Completion routine for asynchronous reads and writes from/to swap.
1502 * Also called manually by synchronous code to finish up a bp.
1504 * This routine may not sleep.
1507 swp_pager_async_iodone(struct buf *bp)
1510 vm_object_t object = NULL;
1515 if (bp->b_ioflags & BIO_ERROR) {
1517 "swap_pager: I/O error - %s failed; blkno %ld,"
1518 "size %ld, error %d\n",
1519 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1527 * remove the mapping for kernel virtual
1530 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1532 bp->b_data = bp->b_kvabase;
1535 object = bp->b_pages[0]->object;
1536 VM_OBJECT_WLOCK(object);
1540 * cleanup pages. If an error occurs writing to swap, we are in
1541 * very serious trouble. If it happens to be a disk error, though,
1542 * we may be able to recover by reassigning the swap later on. So
1543 * in this case we remove the m->swapblk assignment for the page
1544 * but do not free it in the rlist. The errornous block(s) are thus
1545 * never reallocated as swap. Redirty the page and continue.
1547 for (i = 0; i < bp->b_npages; ++i) {
1548 vm_page_t m = bp->b_pages[i];
1550 m->oflags &= ~VPO_SWAPINPROG;
1551 if (m->oflags & VPO_SWAPSLEEP) {
1552 m->oflags &= ~VPO_SWAPSLEEP;
1553 wakeup(&object->paging_in_progress);
1556 if (bp->b_ioflags & BIO_ERROR) {
1558 * If an error occurs I'd love to throw the swapblk
1559 * away without freeing it back to swapspace, so it
1560 * can never be used again. But I can't from an
1563 if (bp->b_iocmd == BIO_READ) {
1565 * NOTE: for reads, m->dirty will probably
1566 * be overridden by the original caller of
1567 * getpages so don't play cute tricks here.
1572 * If a write error occurs, reactivate page
1573 * so it doesn't clog the inactive list,
1574 * then finish the I/O.
1576 MPASS(m->dirty == VM_PAGE_BITS_ALL);
1578 vm_page_activate(m);
1582 } else if (bp->b_iocmd == BIO_READ) {
1584 * NOTE: for reads, m->dirty will probably be
1585 * overridden by the original caller of getpages so
1586 * we cannot set them in order to free the underlying
1587 * swap in a low-swap situation. I don't think we'd
1588 * want to do that anyway, but it was an optimization
1589 * that existed in the old swapper for a time before
1590 * it got ripped out due to precisely this problem.
1592 KASSERT(!pmap_page_is_mapped(m),
1593 ("swp_pager_async_iodone: page %p is mapped", m));
1594 KASSERT(m->dirty == 0,
1595 ("swp_pager_async_iodone: page %p is dirty", m));
1597 m->valid = VM_PAGE_BITS_ALL;
1598 if (i < bp->b_pgbefore ||
1599 i >= bp->b_npages - bp->b_pgafter)
1600 vm_page_readahead_finish(m);
1603 * For write success, clear the dirty
1604 * status, then finish the I/O ( which decrements the
1605 * busy count and possibly wakes waiter's up ).
1606 * A page is only written to swap after a period of
1607 * inactivity. Therefore, we do not expect it to be
1610 KASSERT(!pmap_page_is_write_mapped(m),
1611 ("swp_pager_async_iodone: page %p is not write"
1615 vm_page_deactivate_noreuse(m);
1622 * adjust pip. NOTE: the original parent may still have its own
1623 * pip refs on the object.
1625 if (object != NULL) {
1626 vm_object_pip_wakeupn(object, bp->b_npages);
1627 VM_OBJECT_WUNLOCK(object);
1631 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1632 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1633 * trigger a KASSERT in relpbuf().
1637 bp->b_bufobj = NULL;
1640 * release the physical I/O buffer
1642 if (bp->b_flags & B_ASYNC) {
1643 mtx_lock(&swbuf_mtx);
1644 if (++nsw_wcount_async == 1)
1645 wakeup(&nsw_wcount_async);
1646 mtx_unlock(&swbuf_mtx);
1648 uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp);
1652 swap_pager_nswapdev(void)
1659 * SWP_PAGER_FORCE_PAGEIN() - force a swap block to be paged in
1661 * This routine dissociates the page at the given index within an object
1662 * from its backing store, paging it in if it does not reside in memory.
1663 * If the page is paged in, it is marked dirty and placed in the laundry
1664 * queue. The page is marked dirty because it no longer has backing
1665 * store. It is placed in the laundry queue because it has not been
1666 * accessed recently. Otherwise, it would already reside in memory.
1668 * We also attempt to swap in all other pages in the swap block.
1669 * However, we only guarantee that the one at the specified index is
1672 * XXX - The code to page the whole block in doesn't work, so we
1673 * revert to the one-by-one behavior for now. Sigh.
1676 swp_pager_force_pagein(vm_object_t object, vm_pindex_t pindex)
1680 vm_object_pip_add(object, 1);
1681 m = vm_page_grab(object, pindex, VM_ALLOC_NORMAL);
1682 if (m->valid == VM_PAGE_BITS_ALL) {
1683 vm_object_pip_wakeup(object);
1687 if (m->wire_count == 0 && m->queue == PQ_NONE)
1688 panic("page %p is neither wired nor queued", m);
1692 vm_pager_page_unswapped(m);
1696 if (swap_pager_getpages(object, &m, 1, NULL, NULL) != VM_PAGER_OK)
1697 panic("swap_pager_force_pagein: read from swap failed");/*XXX*/
1698 vm_object_pip_wakeup(object);
1704 vm_pager_page_unswapped(m);
1708 * swap_pager_swapoff:
1710 * Page in all of the pages that have been paged out to the
1711 * given device. The corresponding blocks in the bitmap must be
1712 * marked as allocated and the device must be flagged SW_CLOSING.
1713 * There may be no processes swapped out to the device.
1715 * This routine may block.
1718 swap_pager_swapoff(struct swdevt *sp)
1725 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1729 mtx_lock(&vm_object_list_mtx);
1730 TAILQ_FOREACH(object, &vm_object_list, object_list) {
1731 if (object->type != OBJT_SWAP)
1733 mtx_unlock(&vm_object_list_mtx);
1734 /* Depends on type-stability. */
1735 VM_OBJECT_WLOCK(object);
1738 * Dead objects are eventually terminated on their own.
1740 if ((object->flags & OBJ_DEAD) != 0)
1744 * Sync with fences placed after pctrie
1745 * initialization. We must not access pctrie below
1746 * unless we checked that our object is swap and not
1749 atomic_thread_fence_acq();
1750 if (object->type != OBJT_SWAP)
1753 for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1754 &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1755 pi = sb->p + SWAP_META_PAGES;
1756 for (i = 0; i < SWAP_META_PAGES; i++) {
1757 if (sb->d[i] == SWAPBLK_NONE)
1759 if (swp_pager_isondev(sb->d[i], sp))
1760 swp_pager_force_pagein(object,
1765 VM_OBJECT_WUNLOCK(object);
1766 mtx_lock(&vm_object_list_mtx);
1768 mtx_unlock(&vm_object_list_mtx);
1772 * Objects may be locked or paging to the device being
1773 * removed, so we will miss their pages and need to
1774 * make another pass. We have marked this device as
1775 * SW_CLOSING, so the activity should finish soon.
1778 if (retries > 100) {
1779 panic("swapoff: failed to locate %d swap blocks",
1782 pause("swpoff", hz / 20);
1785 EVENTHANDLER_INVOKE(swapoff, sp);
1788 /************************************************************************
1790 ************************************************************************
1792 * These routines manipulate the swap metadata stored in the
1795 * Swap metadata is implemented with a global hash and not directly
1796 * linked into the object. Instead the object simply contains
1797 * appropriate tracking counters.
1801 * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
1804 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
1808 MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
1809 for (i = start; i < limit; i++) {
1810 if (sb->d[i] != SWAPBLK_NONE)
1817 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
1819 * We first convert the object to a swap object if it is a default
1822 * The specified swapblk is added to the object's swap metadata. If
1823 * the swapblk is not valid, it is freed instead. Any previously
1824 * assigned swapblk is returned.
1827 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
1829 static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
1830 struct swblk *sb, *sb1;
1831 vm_pindex_t modpi, rdpi;
1832 daddr_t prev_swapblk;
1835 VM_OBJECT_ASSERT_WLOCKED(object);
1838 * Convert default object to swap object if necessary
1840 if (object->type != OBJT_SWAP) {
1841 pctrie_init(&object->un_pager.swp.swp_blks);
1844 * Ensure that swap_pager_swapoff()'s iteration over
1845 * object_list does not see a garbage pctrie.
1847 atomic_thread_fence_rel();
1849 object->type = OBJT_SWAP;
1850 KASSERT(object->handle == NULL, ("default pager with handle"));
1853 rdpi = rounddown(pindex, SWAP_META_PAGES);
1854 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
1856 if (swapblk == SWAPBLK_NONE)
1857 return (SWAPBLK_NONE);
1859 sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
1860 pageproc ? M_USE_RESERVE : 0));
1863 for (i = 0; i < SWAP_META_PAGES; i++)
1864 sb->d[i] = SWAPBLK_NONE;
1865 if (atomic_cmpset_int(&swblk_zone_exhausted,
1867 printf("swblk zone ok\n");
1870 VM_OBJECT_WUNLOCK(object);
1871 if (uma_zone_exhausted(swblk_zone)) {
1872 if (atomic_cmpset_int(&swblk_zone_exhausted,
1874 printf("swap blk zone exhausted, "
1875 "increase kern.maxswzone\n");
1876 vm_pageout_oom(VM_OOM_SWAPZ);
1877 pause("swzonxb", 10);
1879 uma_zwait(swblk_zone);
1880 VM_OBJECT_WLOCK(object);
1881 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
1885 * Somebody swapped out a nearby page,
1886 * allocating swblk at the rdpi index,
1887 * while we dropped the object lock.
1892 error = SWAP_PCTRIE_INSERT(
1893 &object->un_pager.swp.swp_blks, sb);
1895 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
1897 printf("swpctrie zone ok\n");
1900 VM_OBJECT_WUNLOCK(object);
1901 if (uma_zone_exhausted(swpctrie_zone)) {
1902 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
1904 printf("swap pctrie zone exhausted, "
1905 "increase kern.maxswzone\n");
1906 vm_pageout_oom(VM_OOM_SWAPZ);
1907 pause("swzonxp", 10);
1909 uma_zwait(swpctrie_zone);
1910 VM_OBJECT_WLOCK(object);
1911 sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
1914 uma_zfree(swblk_zone, sb);
1921 MPASS(sb->p == rdpi);
1923 modpi = pindex % SWAP_META_PAGES;
1924 /* Return prior contents of metadata. */
1925 prev_swapblk = sb->d[modpi];
1926 /* Enter block into metadata. */
1927 sb->d[modpi] = swapblk;
1930 * Free the swblk if we end up with the empty page run.
1932 if (swapblk == SWAPBLK_NONE &&
1933 swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
1934 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, rdpi);
1935 uma_zfree(swblk_zone, sb);
1937 return (prev_swapblk);
1941 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
1943 * The requested range of blocks is freed, with any associated swap
1944 * returned to the swap bitmap.
1946 * This routine will free swap metadata structures as they are cleaned
1947 * out. This routine does *NOT* operate on swap metadata associated
1948 * with resident pages.
1951 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count)
1954 daddr_t n_free, s_free;
1956 int i, limit, start;
1958 VM_OBJECT_ASSERT_WLOCKED(object);
1959 if (object->type != OBJT_SWAP || count == 0)
1962 swp_pager_init_freerange(&s_free, &n_free);
1963 last = pindex + count;
1965 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
1966 rounddown(pindex, SWAP_META_PAGES));
1967 if (sb == NULL || sb->p >= last)
1969 start = pindex > sb->p ? pindex - sb->p : 0;
1970 limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
1972 for (i = start; i < limit; i++) {
1973 if (sb->d[i] == SWAPBLK_NONE)
1975 swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
1976 sb->d[i] = SWAPBLK_NONE;
1978 pindex = sb->p + SWAP_META_PAGES;
1979 if (swp_pager_swblk_empty(sb, 0, start) &&
1980 swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
1981 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks,
1983 uma_zfree(swblk_zone, sb);
1986 swp_pager_freeswapspace(s_free, n_free);
1990 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
1992 * This routine locates and destroys all swap metadata associated with
1996 swp_pager_meta_free_all(vm_object_t object)
1999 daddr_t n_free, s_free;
2003 VM_OBJECT_ASSERT_WLOCKED(object);
2004 if (object->type != OBJT_SWAP)
2007 swp_pager_init_freerange(&s_free, &n_free);
2008 for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
2009 &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
2010 pindex = sb->p + SWAP_META_PAGES;
2011 for (i = 0; i < SWAP_META_PAGES; i++) {
2012 if (sb->d[i] == SWAPBLK_NONE)
2014 swp_pager_update_freerange(&s_free, &n_free, sb->d[i]);
2016 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
2017 uma_zfree(swblk_zone, sb);
2019 swp_pager_freeswapspace(s_free, n_free);
2023 * SWP_PAGER_METACTL() - misc control of swap meta data.
2025 * This routine is capable of looking up, or removing swapblk
2026 * assignments in the swap meta data. It returns the swapblk being
2027 * looked-up, popped, or SWAPBLK_NONE if the block was invalid.
2029 * When acting on a busy resident page and paging is in progress, we
2030 * have to wait until paging is complete but otherwise can act on the
2033 * SWM_POP remove from meta data but do not free it
2036 swp_pager_meta_ctl(vm_object_t object, vm_pindex_t pindex, int flags)
2041 if ((flags & SWM_POP) != 0)
2042 VM_OBJECT_ASSERT_WLOCKED(object);
2044 VM_OBJECT_ASSERT_LOCKED(object);
2047 * The meta data only exists if the object is OBJT_SWAP
2048 * and even then might not be allocated yet.
2050 if (object->type != OBJT_SWAP)
2051 return (SWAPBLK_NONE);
2053 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2054 rounddown(pindex, SWAP_META_PAGES));
2056 return (SWAPBLK_NONE);
2057 r1 = sb->d[pindex % SWAP_META_PAGES];
2058 if (r1 == SWAPBLK_NONE)
2059 return (SWAPBLK_NONE);
2060 if ((flags & SWM_POP) != 0) {
2061 sb->d[pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
2062 if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
2063 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks,
2064 rounddown(pindex, SWAP_META_PAGES));
2065 uma_zfree(swblk_zone, sb);
2072 * Returns the least page index which is greater than or equal to the
2073 * parameter pindex and for which there is a swap block allocated.
2074 * Returns object's size if the object's type is not swap or if there
2075 * are no allocated swap blocks for the object after the requested
2079 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2084 VM_OBJECT_ASSERT_LOCKED(object);
2085 if (object->type != OBJT_SWAP)
2086 return (object->size);
2088 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2089 rounddown(pindex, SWAP_META_PAGES));
2091 return (object->size);
2092 if (sb->p < pindex) {
2093 for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2094 if (sb->d[i] != SWAPBLK_NONE)
2097 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2098 roundup(pindex, SWAP_META_PAGES));
2100 return (object->size);
2102 for (i = 0; i < SWAP_META_PAGES; i++) {
2103 if (sb->d[i] != SWAPBLK_NONE)
2108 * We get here if a swblk is present in the trie but it
2109 * doesn't map any blocks.
2112 return (object->size);
2116 * System call swapon(name) enables swapping on device name,
2117 * which must be in the swdevsw. Return EBUSY
2118 * if already swapping on this device.
2120 #ifndef _SYS_SYSPROTO_H_
2121 struct swapon_args {
2131 sys_swapon(struct thread *td, struct swapon_args *uap)
2135 struct nameidata nd;
2138 error = priv_check(td, PRIV_SWAPON);
2142 sx_xlock(&swdev_syscall_lock);
2145 * Swap metadata may not fit in the KVM if we have physical
2148 if (swblk_zone == NULL) {
2153 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2159 NDFREE(&nd, NDF_ONLY_PNBUF);
2162 if (vn_isdisk(vp, &error)) {
2163 error = swapongeom(vp);
2164 } else if (vp->v_type == VREG &&
2165 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2166 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2168 * Allow direct swapping to NFS regular files in the same
2169 * way that nfs_mountroot() sets up diskless swapping.
2171 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2177 sx_xunlock(&swdev_syscall_lock);
2182 * Check that the total amount of swap currently configured does not
2183 * exceed half the theoretical maximum. If it does, print a warning
2187 swapon_check_swzone(void)
2189 unsigned long maxpages, npages;
2191 npages = swap_total;
2192 /* absolute maximum we can handle assuming 100% efficiency */
2193 maxpages = uma_zone_get_max(swblk_zone) * SWAP_META_PAGES;
2195 /* recommend using no more than half that amount */
2196 if (npages > maxpages / 2) {
2197 printf("warning: total configured swap (%lu pages) "
2198 "exceeds maximum recommended amount (%lu pages).\n",
2199 npages, maxpages / 2);
2200 printf("warning: increase kern.maxswzone "
2201 "or reduce amount of swap.\n");
2206 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2207 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2209 struct swdevt *sp, *tsp;
2214 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2215 * First chop nblks off to page-align it, then convert.
2217 * sw->sw_nblks is in page-sized chunks now too.
2219 nblks &= ~(ctodb(1) - 1);
2220 nblks = dbtoc(nblks);
2223 * If we go beyond this, we get overflows in the radix
2226 mblocks = 0x40000000 / BLIST_META_RADIX;
2227 if (nblks > mblocks) {
2229 "WARNING: reducing swap size to maximum of %luMB per unit\n",
2230 mblocks / 1024 / 1024 * PAGE_SIZE);
2234 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2239 sp->sw_nblks = nblks;
2241 sp->sw_strategy = strategy;
2242 sp->sw_close = close;
2243 sp->sw_flags = flags;
2245 sp->sw_blist = blist_create(nblks, M_WAITOK);
2247 * Do not free the first two block in order to avoid overwriting
2248 * any bsd label at the front of the partition
2250 blist_free(sp->sw_blist, 2, nblks - 2);
2253 mtx_lock(&sw_dev_mtx);
2254 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2255 if (tsp->sw_end >= dvbase) {
2257 * We put one uncovered page between the devices
2258 * in order to definitively prevent any cross-device
2261 dvbase = tsp->sw_end + 1;
2264 sp->sw_first = dvbase;
2265 sp->sw_end = dvbase + nblks;
2266 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2268 swap_pager_avail += nblks - 2;
2269 swap_total += nblks;
2270 swapon_check_swzone();
2272 mtx_unlock(&sw_dev_mtx);
2273 EVENTHANDLER_INVOKE(swapon, sp);
2277 * SYSCALL: swapoff(devname)
2279 * Disable swapping on the given device.
2281 * XXX: Badly designed system call: it should use a device index
2282 * rather than filename as specification. We keep sw_vp around
2283 * only to make this work.
2285 #ifndef _SYS_SYSPROTO_H_
2286 struct swapoff_args {
2296 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2299 struct nameidata nd;
2303 error = priv_check(td, PRIV_SWAPOFF);
2307 sx_xlock(&swdev_syscall_lock);
2309 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2314 NDFREE(&nd, NDF_ONLY_PNBUF);
2317 mtx_lock(&sw_dev_mtx);
2318 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2319 if (sp->sw_vp == vp)
2322 mtx_unlock(&sw_dev_mtx);
2327 error = swapoff_one(sp, td->td_ucred);
2329 sx_xunlock(&swdev_syscall_lock);
2334 swapoff_one(struct swdevt *sp, struct ucred *cred)
2341 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2343 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2344 error = mac_system_check_swapoff(cred, sp->sw_vp);
2345 (void) VOP_UNLOCK(sp->sw_vp, 0);
2349 nblks = sp->sw_nblks;
2352 * We can turn off this swap device safely only if the
2353 * available virtual memory in the system will fit the amount
2354 * of data we will have to page back in, plus an epsilon so
2355 * the system doesn't become critically low on swap space.
2357 if (vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
2361 * Prevent further allocations on this device.
2363 mtx_lock(&sw_dev_mtx);
2364 sp->sw_flags |= SW_CLOSING;
2365 swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2366 swap_total -= nblks;
2367 mtx_unlock(&sw_dev_mtx);
2370 * Page in the contents of the device and close it.
2372 swap_pager_swapoff(sp);
2374 sp->sw_close(curthread, sp);
2375 mtx_lock(&sw_dev_mtx);
2377 TAILQ_REMOVE(&swtailq, sp, sw_list);
2379 if (nswapdev == 0) {
2380 swap_pager_full = 2;
2381 swap_pager_almost_full = 1;
2385 mtx_unlock(&sw_dev_mtx);
2386 blist_destroy(sp->sw_blist);
2387 free(sp, M_VMPGDATA);
2394 struct swdevt *sp, *spt;
2395 const char *devname;
2398 sx_xlock(&swdev_syscall_lock);
2400 mtx_lock(&sw_dev_mtx);
2401 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2402 mtx_unlock(&sw_dev_mtx);
2403 if (vn_isdisk(sp->sw_vp, NULL))
2404 devname = devtoname(sp->sw_vp->v_rdev);
2407 error = swapoff_one(sp, thread0.td_ucred);
2409 printf("Cannot remove swap device %s (error=%d), "
2410 "skipping.\n", devname, error);
2411 } else if (bootverbose) {
2412 printf("Swap device %s removed.\n", devname);
2414 mtx_lock(&sw_dev_mtx);
2416 mtx_unlock(&sw_dev_mtx);
2418 sx_xunlock(&swdev_syscall_lock);
2422 swap_pager_status(int *total, int *used)
2428 mtx_lock(&sw_dev_mtx);
2429 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2430 *total += sp->sw_nblks;
2431 *used += sp->sw_used;
2433 mtx_unlock(&sw_dev_mtx);
2437 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2440 const char *tmp_devname;
2445 mtx_lock(&sw_dev_mtx);
2446 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2451 xs->xsw_version = XSWDEV_VERSION;
2452 xs->xsw_dev = sp->sw_dev;
2453 xs->xsw_flags = sp->sw_flags;
2454 xs->xsw_nblks = sp->sw_nblks;
2455 xs->xsw_used = sp->sw_used;
2456 if (devname != NULL) {
2457 if (vn_isdisk(sp->sw_vp, NULL))
2458 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2460 tmp_devname = "[file]";
2461 strncpy(devname, tmp_devname, len);
2466 mtx_unlock(&sw_dev_mtx);
2470 #if defined(COMPAT_FREEBSD11)
2471 #define XSWDEV_VERSION_11 1
2481 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2484 u_int xsw_dev1, xsw_dev2;
2492 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2495 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2496 struct xswdev32 xs32;
2498 #if defined(COMPAT_FREEBSD11)
2499 struct xswdev11 xs11;
2503 if (arg2 != 1) /* name length */
2505 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2508 #if defined(__amd64__) && defined(COMPAT_FREEBSD32)
2509 if (req->oldlen == sizeof(xs32)) {
2510 xs32.xsw_version = XSWDEV_VERSION;
2511 xs32.xsw_dev1 = xs.xsw_dev;
2512 xs32.xsw_dev2 = xs.xsw_dev >> 32;
2513 xs32.xsw_flags = xs.xsw_flags;
2514 xs32.xsw_nblks = xs.xsw_nblks;
2515 xs32.xsw_used = xs.xsw_used;
2516 error = SYSCTL_OUT(req, &xs32, sizeof(xs32));
2520 #if defined(COMPAT_FREEBSD11)
2521 if (req->oldlen == sizeof(xs11)) {
2522 xs11.xsw_version = XSWDEV_VERSION_11;
2523 xs11.xsw_dev = xs.xsw_dev; /* truncation */
2524 xs11.xsw_flags = xs.xsw_flags;
2525 xs11.xsw_nblks = xs.xsw_nblks;
2526 xs11.xsw_used = xs.xsw_used;
2527 error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2531 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2535 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2536 "Number of swap devices");
2537 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2538 sysctl_vm_swap_info,
2539 "Swap statistics by device");
2542 * Count the approximate swap usage in pages for a vmspace. The
2543 * shadowed or not yet copied on write swap blocks are not accounted.
2544 * The map must be locked.
2547 vmspace_swap_count(struct vmspace *vmspace)
2557 map = &vmspace->vm_map;
2560 for (cur = map->header.next; cur != &map->header; cur = cur->next) {
2561 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2563 object = cur->object.vm_object;
2564 if (object == NULL || object->type != OBJT_SWAP)
2566 VM_OBJECT_RLOCK(object);
2567 if (object->type != OBJT_SWAP)
2569 pi = OFF_TO_IDX(cur->offset);
2570 e = pi + OFF_TO_IDX(cur->end - cur->start);
2571 for (;; pi = sb->p + SWAP_META_PAGES) {
2572 sb = SWAP_PCTRIE_LOOKUP_GE(
2573 &object->un_pager.swp.swp_blks, pi);
2574 if (sb == NULL || sb->p >= e)
2576 for (i = 0; i < SWAP_META_PAGES; i++) {
2577 if (sb->p + i < e &&
2578 sb->d[i] != SWAPBLK_NONE)
2583 VM_OBJECT_RUNLOCK(object);
2591 * Swapping onto disk devices.
2595 static g_orphan_t swapgeom_orphan;
2597 static struct g_class g_swap_class = {
2599 .version = G_VERSION,
2600 .orphan = swapgeom_orphan,
2603 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2607 swapgeom_close_ev(void *arg, int flags)
2609 struct g_consumer *cp;
2612 g_access(cp, -1, -1, 0);
2614 g_destroy_consumer(cp);
2618 * Add a reference to the g_consumer for an inflight transaction.
2621 swapgeom_acquire(struct g_consumer *cp)
2624 mtx_assert(&sw_dev_mtx, MA_OWNED);
2629 * Remove a reference from the g_consumer. Post a close event if all
2630 * references go away, since the function might be called from the
2634 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2637 mtx_assert(&sw_dev_mtx, MA_OWNED);
2639 if (cp->index == 0) {
2640 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2646 swapgeom_done(struct bio *bp2)
2650 struct g_consumer *cp;
2652 bp = bp2->bio_caller2;
2654 bp->b_ioflags = bp2->bio_flags;
2656 bp->b_ioflags |= BIO_ERROR;
2657 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2658 bp->b_error = bp2->bio_error;
2659 bp->b_caller1 = NULL;
2661 sp = bp2->bio_caller1;
2662 mtx_lock(&sw_dev_mtx);
2663 swapgeom_release(cp, sp);
2664 mtx_unlock(&sw_dev_mtx);
2669 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2672 struct g_consumer *cp;
2674 mtx_lock(&sw_dev_mtx);
2677 mtx_unlock(&sw_dev_mtx);
2678 bp->b_error = ENXIO;
2679 bp->b_ioflags |= BIO_ERROR;
2683 swapgeom_acquire(cp);
2684 mtx_unlock(&sw_dev_mtx);
2685 if (bp->b_iocmd == BIO_WRITE)
2688 bio = g_alloc_bio();
2690 mtx_lock(&sw_dev_mtx);
2691 swapgeom_release(cp, sp);
2692 mtx_unlock(&sw_dev_mtx);
2693 bp->b_error = ENOMEM;
2694 bp->b_ioflags |= BIO_ERROR;
2699 bp->b_caller1 = bio;
2700 bio->bio_caller1 = sp;
2701 bio->bio_caller2 = bp;
2702 bio->bio_cmd = bp->b_iocmd;
2703 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2704 bio->bio_length = bp->b_bcount;
2705 bio->bio_done = swapgeom_done;
2706 if (!buf_mapped(bp)) {
2707 bio->bio_ma = bp->b_pages;
2708 bio->bio_data = unmapped_buf;
2709 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2710 bio->bio_ma_n = bp->b_npages;
2711 bio->bio_flags |= BIO_UNMAPPED;
2713 bio->bio_data = bp->b_data;
2716 g_io_request(bio, cp);
2721 swapgeom_orphan(struct g_consumer *cp)
2726 mtx_lock(&sw_dev_mtx);
2727 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2728 if (sp->sw_id == cp) {
2729 sp->sw_flags |= SW_CLOSING;
2734 * Drop reference we were created with. Do directly since we're in a
2735 * special context where we don't have to queue the call to
2736 * swapgeom_close_ev().
2739 destroy = ((sp != NULL) && (cp->index == 0));
2742 mtx_unlock(&sw_dev_mtx);
2744 swapgeom_close_ev(cp, 0);
2748 swapgeom_close(struct thread *td, struct swdevt *sw)
2750 struct g_consumer *cp;
2752 mtx_lock(&sw_dev_mtx);
2755 mtx_unlock(&sw_dev_mtx);
2758 * swapgeom_close() may be called from the biodone context,
2759 * where we cannot perform topology changes. Delegate the
2760 * work to the events thread.
2763 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2767 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2769 struct g_provider *pp;
2770 struct g_consumer *cp;
2771 static struct g_geom *gp;
2776 pp = g_dev_getprovider(dev);
2779 mtx_lock(&sw_dev_mtx);
2780 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2782 if (cp != NULL && cp->provider == pp) {
2783 mtx_unlock(&sw_dev_mtx);
2787 mtx_unlock(&sw_dev_mtx);
2789 gp = g_new_geomf(&g_swap_class, "swap");
2790 cp = g_new_consumer(gp);
2791 cp->index = 1; /* Number of active I/Os, plus one for being active. */
2792 cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2795 * XXX: Every time you think you can improve the margin for
2796 * footshooting, somebody depends on the ability to do so:
2797 * savecore(8) wants to write to our swapdev so we cannot
2798 * set an exclusive count :-(
2800 error = g_access(cp, 1, 1, 0);
2803 g_destroy_consumer(cp);
2806 nblks = pp->mediasize / DEV_BSIZE;
2807 swaponsomething(vp, cp, nblks, swapgeom_strategy,
2808 swapgeom_close, dev2udev(dev),
2809 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
2814 swapongeom(struct vnode *vp)
2818 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2819 if (vp->v_type != VCHR || (vp->v_iflag & VI_DOOMED) != 0) {
2823 error = swapongeom_locked(vp->v_rdev, vp);
2824 g_topology_unlock();
2833 * This is used mainly for network filesystem (read: probably only tested
2834 * with NFS) swapfiles.
2839 swapdev_strategy(struct buf *bp, struct swdevt *sp)
2843 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
2847 if (bp->b_iocmd == BIO_WRITE) {
2849 bufobj_wdrop(bp->b_bufobj);
2850 bufobj_wref(&vp2->v_bufobj);
2852 if (bp->b_bufobj != &vp2->v_bufobj)
2853 bp->b_bufobj = &vp2->v_bufobj;
2855 bp->b_iooffset = dbtob(bp->b_blkno);
2861 swapdev_close(struct thread *td, struct swdevt *sp)
2864 VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
2870 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
2877 mtx_lock(&sw_dev_mtx);
2878 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2879 if (sp->sw_id == vp) {
2880 mtx_unlock(&sw_dev_mtx);
2884 mtx_unlock(&sw_dev_mtx);
2886 (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2888 error = mac_system_check_swapon(td->td_ucred, vp);
2891 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
2892 (void) VOP_UNLOCK(vp, 0);
2896 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
2902 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
2906 new = nsw_wcount_async_max;
2907 error = sysctl_handle_int(oidp, &new, 0, req);
2908 if (error != 0 || req->newptr == NULL)
2911 if (new > nswbuf / 2 || new < 1)
2914 mtx_lock(&swbuf_mtx);
2915 while (nsw_wcount_async_max != new) {
2917 * Adjust difference. If the current async count is too low,
2918 * we will need to sqeeze our update slowly in. Sleep with a
2919 * higher priority than getpbuf() to finish faster.
2921 n = new - nsw_wcount_async_max;
2922 if (nsw_wcount_async + n >= 0) {
2923 nsw_wcount_async += n;
2924 nsw_wcount_async_max += n;
2925 wakeup(&nsw_wcount_async);
2927 nsw_wcount_async_max -= nsw_wcount_async;
2928 nsw_wcount_async = 0;
2929 msleep(&nsw_wcount_async, &swbuf_mtx, PSWP,
2933 mtx_unlock(&swbuf_mtx);