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$");
74 #include "opt_compat.h"
78 #include <sys/param.h>
79 #include <sys/systm.h>
81 #include <sys/kernel.h>
87 #include <sys/fcntl.h>
88 #include <sys/mount.h>
89 #include <sys/namei.h>
90 #include <sys/vnode.h>
91 #include <sys/malloc.h>
92 #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/blist.h>
101 #include <sys/lock.h>
103 #include <sys/vmmeter.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 vm_ooffset_t swap_total;
156 SYSCTL_QUAD(_vm, OID_AUTO, swap_total, CTLFLAG_RD, &swap_total, 0,
157 "Total amount of available swap storage.");
158 static vm_ooffset_t swap_reserved;
159 SYSCTL_QUAD(_vm, OID_AUTO, swap_reserved, CTLFLAG_RD, &swap_reserved, 0,
160 "Amount of swap storage needed to back all allocated anonymous memory.");
161 static int overcommit = 0;
162 SYSCTL_INT(_vm, VM_OVERCOMMIT, overcommit, CTLFLAG_RW, &overcommit, 0,
163 "Configure virtual memory overcommit behavior. See tuning(7) "
165 static unsigned long swzone;
166 SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0,
167 "Actual size of swap metadata zone");
168 static unsigned long swap_maxpages;
169 SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0,
170 "Maximum amount of swap supported");
172 /* bits from overcommit */
173 #define SWAP_RESERVE_FORCE_ON (1 << 0)
174 #define SWAP_RESERVE_RLIMIT_ON (1 << 1)
175 #define SWAP_RESERVE_ALLOW_NONWIRED (1 << 2)
178 swap_reserve(vm_ooffset_t incr)
181 return (swap_reserve_by_cred(incr, curthread->td_ucred));
185 swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred)
190 static struct timeval lastfail;
193 uip = cred->cr_ruidinfo;
195 if (incr & PAGE_MASK)
196 panic("swap_reserve: & PAGE_MASK");
201 error = racct_add(curproc, RACCT_SWAP, incr);
202 PROC_UNLOCK(curproc);
209 mtx_lock(&sw_dev_mtx);
210 r = swap_reserved + incr;
211 if (overcommit & SWAP_RESERVE_ALLOW_NONWIRED) {
212 s = vm_cnt.v_page_count - vm_cnt.v_free_reserved -
218 if ((overcommit & SWAP_RESERVE_FORCE_ON) == 0 || r <= s ||
219 (error = priv_check(curthread, PRIV_VM_SWAP_NOQUOTA)) == 0) {
223 mtx_unlock(&sw_dev_mtx);
226 UIDINFO_VMSIZE_LOCK(uip);
227 if ((overcommit & SWAP_RESERVE_RLIMIT_ON) != 0 &&
228 uip->ui_vmsize + incr > lim_cur(curthread, RLIMIT_SWAP) &&
229 priv_check(curthread, PRIV_VM_SWAP_NORLIMIT))
232 uip->ui_vmsize += incr;
233 UIDINFO_VMSIZE_UNLOCK(uip);
235 mtx_lock(&sw_dev_mtx);
236 swap_reserved -= incr;
237 mtx_unlock(&sw_dev_mtx);
240 if (!res && ppsratecheck(&lastfail, &curfail, 1)) {
241 printf("uid %d, pid %d: swap reservation for %jd bytes failed\n",
242 uip->ui_uid, curproc->p_pid, incr);
248 racct_sub(curproc, RACCT_SWAP, incr);
249 PROC_UNLOCK(curproc);
257 swap_reserve_force(vm_ooffset_t incr)
261 mtx_lock(&sw_dev_mtx);
262 swap_reserved += incr;
263 mtx_unlock(&sw_dev_mtx);
267 racct_add_force(curproc, RACCT_SWAP, incr);
268 PROC_UNLOCK(curproc);
271 uip = curthread->td_ucred->cr_ruidinfo;
273 UIDINFO_VMSIZE_LOCK(uip);
274 uip->ui_vmsize += incr;
275 UIDINFO_VMSIZE_UNLOCK(uip);
276 PROC_UNLOCK(curproc);
280 swap_release(vm_ooffset_t decr)
285 cred = curthread->td_ucred;
286 swap_release_by_cred(decr, cred);
287 PROC_UNLOCK(curproc);
291 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred)
295 uip = cred->cr_ruidinfo;
297 if (decr & PAGE_MASK)
298 panic("swap_release: & PAGE_MASK");
300 mtx_lock(&sw_dev_mtx);
301 if (swap_reserved < decr)
302 panic("swap_reserved < decr");
303 swap_reserved -= decr;
304 mtx_unlock(&sw_dev_mtx);
306 UIDINFO_VMSIZE_LOCK(uip);
307 if (uip->ui_vmsize < decr)
308 printf("negative vmsize for uid = %d\n", uip->ui_uid);
309 uip->ui_vmsize -= decr;
310 UIDINFO_VMSIZE_UNLOCK(uip);
312 racct_sub_cred(cred, RACCT_SWAP, decr);
315 #define SWM_POP 0x01 /* pop out */
317 static int swap_pager_full = 2; /* swap space exhaustion (task killing) */
318 static int swap_pager_almost_full = 1; /* swap space exhaustion (w/hysteresis)*/
319 static int nsw_rcount; /* free read buffers */
320 static int nsw_wcount_sync; /* limit write buffers / synchronous */
321 static int nsw_wcount_async; /* limit write buffers / asynchronous */
322 static int nsw_wcount_async_max;/* assigned maximum */
323 static int nsw_cluster_max; /* maximum VOP I/O allowed */
325 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS);
326 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW |
327 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I",
328 "Maximum running async swap ops");
329 static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS);
330 SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD |
331 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A",
332 "Swap Fragmentation Info");
334 static struct sx sw_alloc_sx;
337 * "named" and "unnamed" anon region objects. Try to reduce the overhead
338 * of searching a named list by hashing it just a little.
343 #define NOBJLIST(handle) \
344 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)])
346 static struct pagerlst swap_pager_object_list[NOBJLISTS];
347 static uma_zone_t swblk_zone;
348 static uma_zone_t swpctrie_zone;
351 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure
352 * calls hooked from other parts of the VM system and do not appear here.
353 * (see vm/swap_pager.h).
356 swap_pager_alloc(void *handle, vm_ooffset_t size,
357 vm_prot_t prot, vm_ooffset_t offset, struct ucred *);
358 static void swap_pager_dealloc(vm_object_t object);
359 static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int *,
361 static int swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *,
362 int *, pgo_getpages_iodone_t, void *);
363 static void swap_pager_putpages(vm_object_t, vm_page_t *, int, boolean_t, int *);
365 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after);
366 static void swap_pager_init(void);
367 static void swap_pager_unswapped(vm_page_t);
368 static void swap_pager_swapoff(struct swdevt *sp);
370 struct pagerops swappagerops = {
371 .pgo_init = swap_pager_init, /* early system initialization of pager */
372 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */
373 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */
374 .pgo_getpages = swap_pager_getpages, /* pagein */
375 .pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */
376 .pgo_putpages = swap_pager_putpages, /* pageout */
377 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */
378 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */
382 * swap_*() routines are externally accessible. swp_*() routines are
385 static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */
386 static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */
388 SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0,
389 "Maximum size of a swap block in pages");
391 static void swp_sizecheck(void);
392 static void swp_pager_async_iodone(struct buf *bp);
393 static bool swp_pager_swblk_empty(struct swblk *sb, int start, int limit);
394 static int swapongeom(struct vnode *);
395 static int swaponvp(struct thread *, struct vnode *, u_long);
396 static int swapoff_one(struct swdevt *sp, struct ucred *cred);
399 * Swap bitmap functions
401 static void swp_pager_freeswapspace(daddr_t blk, daddr_t npages);
402 static daddr_t swp_pager_getswapspace(int npages);
407 static void swp_pager_meta_build(vm_object_t, vm_pindex_t, daddr_t);
408 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t);
409 static void swp_pager_meta_free_all(vm_object_t);
410 static daddr_t swp_pager_meta_ctl(vm_object_t, vm_pindex_t, int);
413 swblk_trie_alloc(struct pctrie *ptree)
416 return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ?
417 M_USE_RESERVE : 0)));
421 swblk_trie_free(struct pctrie *ptree, void *node)
424 uma_zfree(swpctrie_zone, node);
427 PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free);
430 * SWP_SIZECHECK() - update swap_pager_full indication
432 * update the swap_pager_almost_full indication and warn when we are
433 * about to run out of swap space, using lowat/hiwat hysteresis.
435 * Clear swap_pager_full ( task killing ) indication when lowat is met.
437 * No restrictions on call
438 * This routine may not block.
444 if (swap_pager_avail < nswap_lowat) {
445 if (swap_pager_almost_full == 0) {
446 printf("swap_pager: out of swap space\n");
447 swap_pager_almost_full = 1;
451 if (swap_pager_avail > nswap_hiwat)
452 swap_pager_almost_full = 0;
457 * SWAP_PAGER_INIT() - initialize the swap pager!
459 * Expected to be started from system init. NOTE: This code is run
460 * before much else so be careful what you depend on. Most of the VM
461 * system has yet to be initialized at this point.
464 swap_pager_init(void)
467 * Initialize object lists
471 for (i = 0; i < NOBJLISTS; ++i)
472 TAILQ_INIT(&swap_pager_object_list[i]);
473 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF);
474 sx_init(&sw_alloc_sx, "swspsx");
475 sx_init(&swdev_syscall_lock, "swsysc");
479 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process
481 * Expected to be started from pageout process once, prior to entering
485 swap_pager_swap_init(void)
490 * Number of in-transit swap bp operations. Don't
491 * exhaust the pbufs completely. Make sure we
492 * initialize workable values (0 will work for hysteresis
493 * but it isn't very efficient).
495 * The nsw_cluster_max is constrained by the bp->b_pages[]
496 * array (MAXPHYS/PAGE_SIZE) and our locally defined
497 * MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are
498 * constrained by the swap device interleave stripe size.
500 * Currently we hardwire nsw_wcount_async to 4. This limit is
501 * designed to prevent other I/O from having high latencies due to
502 * our pageout I/O. The value 4 works well for one or two active swap
503 * devices but is probably a little low if you have more. Even so,
504 * a higher value would probably generate only a limited improvement
505 * with three or four active swap devices since the system does not
506 * typically have to pageout at extreme bandwidths. We will want
507 * at least 2 per swap devices, and 4 is a pretty good value if you
508 * have one NFS swap device due to the command/ack latency over NFS.
509 * So it all works out pretty well.
511 nsw_cluster_max = min((MAXPHYS/PAGE_SIZE), MAX_PAGEOUT_CLUSTER);
514 nsw_rcount = (nswbuf + 1) / 2;
515 nsw_wcount_sync = (nswbuf + 3) / 4;
516 nsw_wcount_async = 4;
517 nsw_wcount_async_max = nsw_wcount_async;
518 mtx_unlock(&pbuf_mtx);
521 * Initialize our zone, guessing on the number we need based
522 * on the number of pages in the system.
524 n = vm_cnt.v_page_count / 2;
525 if (maxswzone && n > maxswzone / sizeof(struct swblk))
526 n = maxswzone / sizeof(struct swblk);
527 swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL,
528 pctrie_zone_init, NULL, UMA_ALIGN_PTR,
529 UMA_ZONE_NOFREE | UMA_ZONE_VM);
530 if (swpctrie_zone == NULL)
531 panic("failed to create swap pctrie zone.");
532 swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL,
533 NULL, NULL, _Alignof(struct swblk) - 1,
534 UMA_ZONE_NOFREE | UMA_ZONE_VM);
535 if (swblk_zone == NULL)
536 panic("failed to create swap blk zone.");
539 if (uma_zone_reserve_kva(swblk_zone, n))
542 * if the allocation failed, try a zone two thirds the
543 * size of the previous attempt.
549 * Often uma_zone_reserve_kva() cannot reserve exactly the
550 * requested size. Account for the difference when
551 * calculating swap_maxpages.
553 n = uma_zone_get_max(swblk_zone);
556 printf("Swap blk zone entries reduced from %lu to %lu.\n",
558 swap_maxpages = n * SWAP_META_PAGES;
559 swzone = n * sizeof(struct swblk);
560 if (!uma_zone_reserve_kva(swpctrie_zone, n))
561 printf("Cannot reserve swap pctrie zone, "
562 "reduce kern.maxswzone.\n");
566 swap_pager_alloc_init(void *handle, struct ucred *cred, vm_ooffset_t size,
572 if (!swap_reserve_by_cred(size, cred))
578 * The un_pager.swp.swp_blks trie is initialized by
579 * vm_object_allocate() to ensure the correct order of
580 * visibility to other threads.
582 object = vm_object_allocate(OBJT_SWAP, OFF_TO_IDX(offset +
585 object->handle = handle;
588 object->charge = size;
594 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate
595 * its metadata structures.
597 * This routine is called from the mmap and fork code to create a new
600 * This routine must ensure that no live duplicate is created for
601 * the named object request, which is protected against by
602 * holding the sw_alloc_sx lock in case handle != NULL.
605 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
606 vm_ooffset_t offset, struct ucred *cred)
610 if (handle != NULL) {
612 * Reference existing named region or allocate new one. There
613 * should not be a race here against swp_pager_meta_build()
614 * as called from vm_page_remove() in regards to the lookup
617 sx_xlock(&sw_alloc_sx);
618 object = vm_pager_object_lookup(NOBJLIST(handle), handle);
619 if (object == NULL) {
620 object = swap_pager_alloc_init(handle, cred, size,
622 if (object != NULL) {
623 TAILQ_INSERT_TAIL(NOBJLIST(object->handle),
624 object, pager_object_list);
627 sx_xunlock(&sw_alloc_sx);
629 object = swap_pager_alloc_init(handle, cred, size, offset);
635 * SWAP_PAGER_DEALLOC() - remove swap metadata from object
637 * The swap backing for the object is destroyed. The code is
638 * designed such that we can reinstantiate it later, but this
639 * routine is typically called only when the entire object is
640 * about to be destroyed.
642 * The object must be locked.
645 swap_pager_dealloc(vm_object_t object)
648 VM_OBJECT_ASSERT_WLOCKED(object);
649 KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj"));
652 * Remove from list right away so lookups will fail if we block for
653 * pageout completion.
655 if (object->handle != NULL) {
656 VM_OBJECT_WUNLOCK(object);
657 sx_xlock(&sw_alloc_sx);
658 TAILQ_REMOVE(NOBJLIST(object->handle), object,
660 sx_xunlock(&sw_alloc_sx);
661 VM_OBJECT_WLOCK(object);
664 vm_object_pip_wait(object, "swpdea");
667 * Free all remaining metadata. We only bother to free it from
668 * the swap meta data. We do not attempt to free swapblk's still
669 * associated with vm_page_t's for this object. We do not care
670 * if paging is still in progress on some objects.
672 swp_pager_meta_free_all(object);
673 object->handle = NULL;
674 object->type = OBJT_DEAD;
677 /************************************************************************
678 * SWAP PAGER BITMAP ROUTINES *
679 ************************************************************************/
682 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space
684 * Allocate swap for the requested number of pages. The starting
685 * swap block number (a page index) is returned or SWAPBLK_NONE
686 * if the allocation failed.
688 * Also has the side effect of advising that somebody made a mistake
689 * when they configured swap and didn't configure enough.
691 * This routine may not sleep.
693 * We allocate in round-robin fashion from the configured devices.
696 swp_pager_getswapspace(int npages)
703 mtx_lock(&sw_dev_mtx);
705 for (i = 0; i < nswapdev; i++) {
707 sp = TAILQ_FIRST(&swtailq);
708 if (!(sp->sw_flags & SW_CLOSING)) {
709 blk = blist_alloc(sp->sw_blist, npages);
710 if (blk != SWAPBLK_NONE) {
712 sp->sw_used += npages;
713 swap_pager_avail -= npages;
715 swdevhd = TAILQ_NEXT(sp, sw_list);
719 sp = TAILQ_NEXT(sp, sw_list);
721 if (swap_pager_full != 2) {
722 printf("swap_pager_getswapspace(%d): failed\n", npages);
724 swap_pager_almost_full = 1;
728 mtx_unlock(&sw_dev_mtx);
733 swp_pager_isondev(daddr_t blk, struct swdevt *sp)
736 return (blk >= sp->sw_first && blk < sp->sw_end);
740 swp_pager_strategy(struct buf *bp)
744 mtx_lock(&sw_dev_mtx);
745 TAILQ_FOREACH(sp, &swtailq, sw_list) {
746 if (bp->b_blkno >= sp->sw_first && bp->b_blkno < sp->sw_end) {
747 mtx_unlock(&sw_dev_mtx);
748 if ((sp->sw_flags & SW_UNMAPPED) != 0 &&
749 unmapped_buf_allowed) {
750 bp->b_data = unmapped_buf;
753 pmap_qenter((vm_offset_t)bp->b_data,
754 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE);
756 sp->sw_strategy(bp, sp);
760 panic("Swapdev not found");
765 * SWP_PAGER_FREESWAPSPACE() - free raw swap space
767 * This routine returns the specified swap blocks back to the bitmap.
769 * This routine may not sleep.
772 swp_pager_freeswapspace(daddr_t blk, daddr_t npages)
778 mtx_lock(&sw_dev_mtx);
779 TAILQ_FOREACH(sp, &swtailq, sw_list) {
780 if (blk >= sp->sw_first && blk < sp->sw_end) {
781 sp->sw_used -= npages;
783 * If we are attempting to stop swapping on
784 * this device, we don't want to mark any
785 * blocks free lest they be reused.
787 if ((sp->sw_flags & SW_CLOSING) == 0) {
788 blist_free(sp->sw_blist, blk - sp->sw_first,
790 swap_pager_avail += npages;
793 mtx_unlock(&sw_dev_mtx);
797 panic("Swapdev not found");
801 * SYSCTL_SWAP_FRAGMENTATION() - produce raw swap space stats
804 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS)
811 error = sysctl_wire_old_buffer(req, 0);
814 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
815 mtx_lock(&sw_dev_mtx);
816 TAILQ_FOREACH(sp, &swtailq, sw_list) {
817 if (vn_isdisk(sp->sw_vp, NULL))
818 devname = devtoname(sp->sw_vp->v_rdev);
821 sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname);
822 blist_stats(sp->sw_blist, &sbuf);
824 mtx_unlock(&sw_dev_mtx);
825 error = sbuf_finish(&sbuf);
831 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page
832 * range within an object.
834 * This is a globally accessible routine.
836 * This routine removes swapblk assignments from swap metadata.
838 * The external callers of this routine typically have already destroyed
839 * or renamed vm_page_t's associated with this range in the object so
842 * The object must be locked.
845 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size)
848 swp_pager_meta_free(object, start, size);
852 * SWAP_PAGER_RESERVE() - reserve swap blocks in object
854 * Assigns swap blocks to the specified range within the object. The
855 * swap blocks are not zeroed. Any previous swap assignment is destroyed.
857 * Returns 0 on success, -1 on failure.
860 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_size_t size)
863 daddr_t blk = SWAPBLK_NONE;
864 vm_pindex_t beg = start; /* save start index */
866 VM_OBJECT_WLOCK(object);
870 while ((blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE) {
873 swp_pager_meta_free(object, beg, start - beg);
874 VM_OBJECT_WUNLOCK(object);
879 swp_pager_meta_build(object, start, blk);
885 swp_pager_meta_free(object, start, n);
886 VM_OBJECT_WUNLOCK(object);
891 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager
892 * and destroy the source.
894 * Copy any valid swapblks from the source to the destination. In
895 * cases where both the source and destination have a valid swapblk,
896 * we keep the destination's.
898 * This routine is allowed to sleep. It may sleep allocating metadata
899 * indirectly through swp_pager_meta_build() or if paging is still in
900 * progress on the source.
902 * The source object contains no vm_page_t's (which is just as well)
904 * The source object is of type OBJT_SWAP.
906 * The source and destination objects must be locked.
907 * Both object locks may temporarily be released.
910 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject,
911 vm_pindex_t offset, int destroysource)
914 daddr_t dstaddr, first_free, num_free, srcaddr;
916 VM_OBJECT_ASSERT_WLOCKED(srcobject);
917 VM_OBJECT_ASSERT_WLOCKED(dstobject);
920 * If destroysource is set, we remove the source object from the
921 * swap_pager internal queue now.
923 if (destroysource && srcobject->handle != NULL) {
924 vm_object_pip_add(srcobject, 1);
925 VM_OBJECT_WUNLOCK(srcobject);
926 vm_object_pip_add(dstobject, 1);
927 VM_OBJECT_WUNLOCK(dstobject);
928 sx_xlock(&sw_alloc_sx);
929 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject,
931 sx_xunlock(&sw_alloc_sx);
932 VM_OBJECT_WLOCK(dstobject);
933 vm_object_pip_wakeup(dstobject);
934 VM_OBJECT_WLOCK(srcobject);
935 vm_object_pip_wakeup(srcobject);
939 * Transfer source to destination.
941 first_free = SWAPBLK_NONE;
943 for (i = 0; i < dstobject->size; ++i) {
944 srcaddr = swp_pager_meta_ctl(srcobject, i + offset, SWM_POP);
945 if (srcaddr == SWAPBLK_NONE)
947 dstaddr = swp_pager_meta_ctl(dstobject, i, 0);
948 if (dstaddr == SWAPBLK_NONE) {
950 * Destination has no swapblk and is not resident,
953 * swp_pager_meta_build() can sleep.
955 vm_object_pip_add(srcobject, 1);
956 VM_OBJECT_WUNLOCK(srcobject);
957 vm_object_pip_add(dstobject, 1);
958 swp_pager_meta_build(dstobject, i, srcaddr);
959 vm_object_pip_wakeup(dstobject);
960 VM_OBJECT_WLOCK(srcobject);
961 vm_object_pip_wakeup(srcobject);
964 * Destination has valid swapblk or it is represented
965 * by a resident page. We destroy the sourceblock.
967 if (first_free + num_free == srcaddr)
970 swp_pager_freeswapspace(first_free, num_free);
971 first_free = srcaddr;
976 swp_pager_freeswapspace(first_free, num_free);
979 * Free left over swap blocks in source.
981 * We have to revert the type to OBJT_DEFAULT so we do not accidentally
982 * double-remove the object from the swap queues.
985 swp_pager_meta_free_all(srcobject);
987 * Reverting the type is not necessary, the caller is going
988 * to destroy srcobject directly, but I'm doing it here
989 * for consistency since we've removed the object from its
992 srcobject->type = OBJT_DEFAULT;
997 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for
998 * the requested page.
1000 * We determine whether good backing store exists for the requested
1001 * page and return TRUE if it does, FALSE if it doesn't.
1003 * If TRUE, we also try to determine how much valid, contiguous backing
1004 * store exists before and after the requested page.
1007 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before,
1013 VM_OBJECT_ASSERT_LOCKED(object);
1016 * do we have good backing store at the requested index ?
1018 blk0 = swp_pager_meta_ctl(object, pindex, 0);
1019 if (blk0 == SWAPBLK_NONE) {
1028 * find backwards-looking contiguous good backing store
1030 if (before != NULL) {
1031 for (i = 1; i < SWB_NPAGES; i++) {
1034 blk = swp_pager_meta_ctl(object, pindex - i, 0);
1035 if (blk != blk0 - i)
1042 * find forward-looking contiguous good backing store
1044 if (after != NULL) {
1045 for (i = 1; i < SWB_NPAGES; i++) {
1046 blk = swp_pager_meta_ctl(object, pindex + i, 0);
1047 if (blk != blk0 + i)
1056 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page
1058 * This removes any associated swap backing store, whether valid or
1059 * not, from the page.
1061 * This routine is typically called when a page is made dirty, at
1062 * which point any associated swap can be freed. MADV_FREE also
1063 * calls us in a special-case situation
1065 * NOTE!!! If the page is clean and the swap was valid, the caller
1066 * should make the page dirty before calling this routine. This routine
1067 * does NOT change the m->dirty status of the page. Also: MADV_FREE
1070 * This routine may not sleep.
1072 * The object containing the page must be locked.
1075 swap_pager_unswapped(vm_page_t m)
1079 srcaddr = swp_pager_meta_ctl(m->object, m->pindex, SWM_POP);
1080 if (srcaddr != SWAPBLK_NONE)
1081 swp_pager_freeswapspace(srcaddr, 1);
1085 * swap_pager_getpages() - bring pages in from swap
1087 * Attempt to page in the pages in array "m" of length "count". The caller
1088 * may optionally specify that additional pages preceding and succeeding
1089 * the specified range be paged in. The number of such pages is returned
1090 * in the "rbehind" and "rahead" parameters, and they will be in the
1091 * inactive queue upon return.
1093 * The pages in "m" must be busied and will remain busied upon return.
1096 swap_pager_getpages(vm_object_t object, vm_page_t *m, int count, int *rbehind,
1100 vm_page_t mpred, msucc, p;
1103 int i, j, maxahead, maxbehind, reqcount, shift;
1107 VM_OBJECT_WUNLOCK(object);
1108 bp = getpbuf(&nsw_rcount);
1109 VM_OBJECT_WLOCK(object);
1111 if (!swap_pager_haspage(object, m[0]->pindex, &maxbehind, &maxahead)) {
1112 relpbuf(bp, &nsw_rcount);
1113 return (VM_PAGER_FAIL);
1117 * Clip the readahead and readbehind ranges to exclude resident pages.
1119 if (rahead != NULL) {
1120 KASSERT(reqcount - 1 <= maxahead,
1121 ("page count %d extends beyond swap block", reqcount));
1122 *rahead = imin(*rahead, maxahead - (reqcount - 1));
1123 pindex = m[reqcount - 1]->pindex;
1124 msucc = TAILQ_NEXT(m[reqcount - 1], listq);
1125 if (msucc != NULL && msucc->pindex - pindex - 1 < *rahead)
1126 *rahead = msucc->pindex - pindex - 1;
1128 if (rbehind != NULL) {
1129 *rbehind = imin(*rbehind, maxbehind);
1130 pindex = m[0]->pindex;
1131 mpred = TAILQ_PREV(m[0], pglist, listq);
1132 if (mpred != NULL && pindex - mpred->pindex - 1 < *rbehind)
1133 *rbehind = pindex - mpred->pindex - 1;
1137 * Allocate readahead and readbehind pages.
1139 shift = rbehind != NULL ? *rbehind : 0;
1141 for (i = 1; i <= shift; i++) {
1142 p = vm_page_alloc(object, m[0]->pindex - i,
1145 /* Shift allocated pages to the left. */
1146 for (j = 0; j < i - 1; j++)
1148 bp->b_pages[j + shift - i + 1];
1151 bp->b_pages[shift - i] = p;
1156 for (i = 0; i < reqcount; i++)
1157 bp->b_pages[i + shift] = m[i];
1158 if (rahead != NULL) {
1159 for (i = 0; i < *rahead; i++) {
1160 p = vm_page_alloc(object,
1161 m[reqcount - 1]->pindex + i + 1, VM_ALLOC_NORMAL);
1164 bp->b_pages[shift + reqcount + i] = p;
1168 if (rbehind != NULL)
1173 vm_object_pip_add(object, count);
1175 for (i = 0; i < count; i++)
1176 bp->b_pages[i]->oflags |= VPO_SWAPINPROG;
1178 pindex = bp->b_pages[0]->pindex;
1179 blk = swp_pager_meta_ctl(object, pindex, 0);
1180 KASSERT(blk != SWAPBLK_NONE,
1181 ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex));
1183 VM_OBJECT_WUNLOCK(object);
1185 bp->b_flags |= B_PAGING;
1186 bp->b_iocmd = BIO_READ;
1187 bp->b_iodone = swp_pager_async_iodone;
1188 bp->b_rcred = crhold(thread0.td_ucred);
1189 bp->b_wcred = crhold(thread0.td_ucred);
1191 bp->b_bcount = PAGE_SIZE * count;
1192 bp->b_bufsize = PAGE_SIZE * count;
1193 bp->b_npages = count;
1194 bp->b_pgbefore = rbehind != NULL ? *rbehind : 0;
1195 bp->b_pgafter = rahead != NULL ? *rahead : 0;
1197 VM_CNT_INC(v_swapin);
1198 VM_CNT_ADD(v_swappgsin, count);
1201 * perform the I/O. NOTE!!! bp cannot be considered valid after
1202 * this point because we automatically release it on completion.
1203 * Instead, we look at the one page we are interested in which we
1204 * still hold a lock on even through the I/O completion.
1206 * The other pages in our m[] array are also released on completion,
1207 * so we cannot assume they are valid anymore either.
1209 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1212 swp_pager_strategy(bp);
1215 * Wait for the pages we want to complete. VPO_SWAPINPROG is always
1216 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE
1217 * is set in the metadata for each page in the request.
1219 VM_OBJECT_WLOCK(object);
1220 while ((m[0]->oflags & VPO_SWAPINPROG) != 0) {
1221 m[0]->oflags |= VPO_SWAPSLEEP;
1222 VM_CNT_INC(v_intrans);
1223 if (VM_OBJECT_SLEEP(object, &object->paging_in_progress, PSWP,
1224 "swread", hz * 20)) {
1226 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n",
1227 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount);
1232 * If we had an unrecoverable read error pages will not be valid.
1234 for (i = 0; i < reqcount; i++)
1235 if (m[i]->valid != VM_PAGE_BITS_ALL)
1236 return (VM_PAGER_ERROR);
1238 return (VM_PAGER_OK);
1241 * A final note: in a low swap situation, we cannot deallocate swap
1242 * and mark a page dirty here because the caller is likely to mark
1243 * the page clean when we return, causing the page to possibly revert
1244 * to all-zero's later.
1249 * swap_pager_getpages_async():
1251 * Right now this is emulation of asynchronous operation on top of
1252 * swap_pager_getpages().
1255 swap_pager_getpages_async(vm_object_t object, vm_page_t *m, int count,
1256 int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg)
1260 r = swap_pager_getpages(object, m, count, rbehind, rahead);
1261 VM_OBJECT_WUNLOCK(object);
1266 case VM_PAGER_ERROR:
1273 panic("unhandled swap_pager_getpages() error %d", r);
1275 (iodone)(arg, m, count, error);
1276 VM_OBJECT_WLOCK(object);
1282 * swap_pager_putpages:
1284 * Assign swap (if necessary) and initiate I/O on the specified pages.
1286 * We support both OBJT_DEFAULT and OBJT_SWAP objects. DEFAULT objects
1287 * are automatically converted to SWAP objects.
1289 * In a low memory situation we may block in VOP_STRATEGY(), but the new
1290 * vm_page reservation system coupled with properly written VFS devices
1291 * should ensure that no low-memory deadlock occurs. This is an area
1294 * The parent has N vm_object_pip_add() references prior to
1295 * calling us and will remove references for rtvals[] that are
1296 * not set to VM_PAGER_PEND. We need to remove the rest on I/O
1299 * The parent has soft-busy'd the pages it passes us and will unbusy
1300 * those whos rtvals[] entry is not set to VM_PAGER_PEND on return.
1301 * We need to unbusy the rest on I/O completion.
1304 swap_pager_putpages(vm_object_t object, vm_page_t *m, int count,
1305 int flags, int *rtvals)
1310 if (count && m[0]->object != object) {
1311 panic("swap_pager_putpages: object mismatch %p/%p",
1320 * Turn object into OBJT_SWAP
1321 * check for bogus sysops
1322 * force sync if not pageout process
1324 if (object->type != OBJT_SWAP)
1325 swp_pager_meta_build(object, 0, SWAPBLK_NONE);
1326 VM_OBJECT_WUNLOCK(object);
1329 if (curproc != pageproc)
1332 sync = (flags & VM_PAGER_PUT_SYNC) != 0;
1337 * Assign swap blocks and issue I/O. We reallocate swap on the fly.
1338 * The page is left dirty until the pageout operation completes
1341 for (i = 0; i < count; i += n) {
1347 * Maximum I/O size is limited by a number of factors.
1349 n = min(BLIST_MAX_ALLOC, count - i);
1350 n = min(n, nsw_cluster_max);
1353 * Get biggest block of swap we can. If we fail, fall
1354 * back and try to allocate a smaller block. Don't go
1355 * overboard trying to allocate space if it would overly
1359 (blk = swp_pager_getswapspace(n)) == SWAPBLK_NONE &&
1364 if (blk == SWAPBLK_NONE) {
1365 for (j = 0; j < n; ++j)
1366 rtvals[i+j] = VM_PAGER_FAIL;
1371 * All I/O parameters have been satisfied, build the I/O
1372 * request and assign the swap space.
1375 bp = getpbuf(&nsw_wcount_sync);
1377 bp = getpbuf(&nsw_wcount_async);
1378 bp->b_flags = B_ASYNC;
1380 bp->b_flags |= B_PAGING;
1381 bp->b_iocmd = BIO_WRITE;
1383 bp->b_rcred = crhold(thread0.td_ucred);
1384 bp->b_wcred = crhold(thread0.td_ucred);
1385 bp->b_bcount = PAGE_SIZE * n;
1386 bp->b_bufsize = PAGE_SIZE * n;
1389 VM_OBJECT_WLOCK(object);
1390 for (j = 0; j < n; ++j) {
1391 vm_page_t mreq = m[i+j];
1393 swp_pager_meta_build(
1398 MPASS(mreq->dirty == VM_PAGE_BITS_ALL);
1399 mreq->oflags |= VPO_SWAPINPROG;
1400 bp->b_pages[j] = mreq;
1402 VM_OBJECT_WUNLOCK(object);
1405 * Must set dirty range for NFS to work.
1408 bp->b_dirtyend = bp->b_bcount;
1410 VM_CNT_INC(v_swapout);
1411 VM_CNT_ADD(v_swappgsout, bp->b_npages);
1414 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we
1415 * can call the async completion routine at the end of a
1416 * synchronous I/O operation. Otherwise, our caller would
1417 * perform duplicate unbusy and wakeup operations on the page
1418 * and object, respectively.
1420 for (j = 0; j < n; j++)
1421 rtvals[i + j] = VM_PAGER_PEND;
1426 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1428 if (sync == FALSE) {
1429 bp->b_iodone = swp_pager_async_iodone;
1431 swp_pager_strategy(bp);
1438 * NOTE: b_blkno is destroyed by the call to swapdev_strategy
1440 bp->b_iodone = bdone;
1441 swp_pager_strategy(bp);
1444 * Wait for the sync I/O to complete.
1446 bwait(bp, PVM, "swwrt");
1449 * Now that we are through with the bp, we can call the
1450 * normal async completion, which frees everything up.
1452 swp_pager_async_iodone(bp);
1454 VM_OBJECT_WLOCK(object);
1458 * swp_pager_async_iodone:
1460 * Completion routine for asynchronous reads and writes from/to swap.
1461 * Also called manually by synchronous code to finish up a bp.
1463 * This routine may not sleep.
1466 swp_pager_async_iodone(struct buf *bp)
1469 vm_object_t object = NULL;
1474 if (bp->b_ioflags & BIO_ERROR) {
1476 "swap_pager: I/O error - %s failed; blkno %ld,"
1477 "size %ld, error %d\n",
1478 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"),
1486 * remove the mapping for kernel virtual
1489 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages);
1491 bp->b_data = bp->b_kvabase;
1494 object = bp->b_pages[0]->object;
1495 VM_OBJECT_WLOCK(object);
1499 * cleanup pages. If an error occurs writing to swap, we are in
1500 * very serious trouble. If it happens to be a disk error, though,
1501 * we may be able to recover by reassigning the swap later on. So
1502 * in this case we remove the m->swapblk assignment for the page
1503 * but do not free it in the rlist. The errornous block(s) are thus
1504 * never reallocated as swap. Redirty the page and continue.
1506 for (i = 0; i < bp->b_npages; ++i) {
1507 vm_page_t m = bp->b_pages[i];
1509 m->oflags &= ~VPO_SWAPINPROG;
1510 if (m->oflags & VPO_SWAPSLEEP) {
1511 m->oflags &= ~VPO_SWAPSLEEP;
1512 wakeup(&object->paging_in_progress);
1515 if (bp->b_ioflags & BIO_ERROR) {
1517 * If an error occurs I'd love to throw the swapblk
1518 * away without freeing it back to swapspace, so it
1519 * can never be used again. But I can't from an
1522 if (bp->b_iocmd == BIO_READ) {
1524 * NOTE: for reads, m->dirty will probably
1525 * be overridden by the original caller of
1526 * getpages so don't play cute tricks here.
1531 * If a write error occurs, reactivate page
1532 * so it doesn't clog the inactive list,
1533 * then finish the I/O.
1535 MPASS(m->dirty == VM_PAGE_BITS_ALL);
1537 vm_page_activate(m);
1541 } else if (bp->b_iocmd == BIO_READ) {
1543 * NOTE: for reads, m->dirty will probably be
1544 * overridden by the original caller of getpages so
1545 * we cannot set them in order to free the underlying
1546 * swap in a low-swap situation. I don't think we'd
1547 * want to do that anyway, but it was an optimization
1548 * that existed in the old swapper for a time before
1549 * it got ripped out due to precisely this problem.
1551 KASSERT(!pmap_page_is_mapped(m),
1552 ("swp_pager_async_iodone: page %p is mapped", m));
1553 KASSERT(m->dirty == 0,
1554 ("swp_pager_async_iodone: page %p is dirty", m));
1556 m->valid = VM_PAGE_BITS_ALL;
1557 if (i < bp->b_pgbefore ||
1558 i >= bp->b_npages - bp->b_pgafter)
1559 vm_page_readahead_finish(m);
1562 * For write success, clear the dirty
1563 * status, then finish the I/O ( which decrements the
1564 * busy count and possibly wakes waiter's up ).
1565 * A page is only written to swap after a period of
1566 * inactivity. Therefore, we do not expect it to be
1569 KASSERT(!pmap_page_is_write_mapped(m),
1570 ("swp_pager_async_iodone: page %p is not write"
1574 vm_page_deactivate_noreuse(m);
1581 * adjust pip. NOTE: the original parent may still have its own
1582 * pip refs on the object.
1584 if (object != NULL) {
1585 vm_object_pip_wakeupn(object, bp->b_npages);
1586 VM_OBJECT_WUNLOCK(object);
1590 * swapdev_strategy() manually sets b_vp and b_bufobj before calling
1591 * bstrategy(). Set them back to NULL now we're done with it, or we'll
1592 * trigger a KASSERT in relpbuf().
1596 bp->b_bufobj = NULL;
1599 * release the physical I/O buffer
1603 ((bp->b_iocmd == BIO_READ) ? &nsw_rcount :
1604 ((bp->b_flags & B_ASYNC) ?
1613 swap_pager_nswapdev(void)
1620 * SWP_PAGER_FORCE_PAGEIN() - force a swap block to be paged in
1622 * This routine dissociates the page at the given index within an object
1623 * from its backing store, paging it in if it does not reside in memory.
1624 * If the page is paged in, it is marked dirty and placed in the laundry
1625 * queue. The page is marked dirty because it no longer has backing
1626 * store. It is placed in the laundry queue because it has not been
1627 * accessed recently. Otherwise, it would already reside in memory.
1629 * We also attempt to swap in all other pages in the swap block.
1630 * However, we only guarantee that the one at the specified index is
1633 * XXX - The code to page the whole block in doesn't work, so we
1634 * revert to the one-by-one behavior for now. Sigh.
1637 swp_pager_force_pagein(vm_object_t object, vm_pindex_t pindex)
1641 vm_object_pip_add(object, 1);
1642 m = vm_page_grab(object, pindex, VM_ALLOC_NORMAL);
1643 if (m->valid == VM_PAGE_BITS_ALL) {
1644 vm_object_pip_wakeup(object);
1648 if (m->wire_count == 0 && m->queue == PQ_NONE)
1649 panic("page %p is neither wired nor queued", m);
1653 vm_pager_page_unswapped(m);
1657 if (swap_pager_getpages(object, &m, 1, NULL, NULL) != VM_PAGER_OK)
1658 panic("swap_pager_force_pagein: read from swap failed");/*XXX*/
1659 vm_object_pip_wakeup(object);
1665 vm_pager_page_unswapped(m);
1669 * swap_pager_swapoff:
1671 * Page in all of the pages that have been paged out to the
1672 * given device. The corresponding blocks in the bitmap must be
1673 * marked as allocated and the device must be flagged SW_CLOSING.
1674 * There may be no processes swapped out to the device.
1676 * This routine may block.
1679 swap_pager_swapoff(struct swdevt *sp)
1686 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
1690 mtx_lock(&vm_object_list_mtx);
1691 TAILQ_FOREACH(object, &vm_object_list, object_list) {
1692 if (object->type != OBJT_SWAP)
1694 mtx_unlock(&vm_object_list_mtx);
1695 /* Depends on type-stability. */
1696 VM_OBJECT_WLOCK(object);
1699 * Dead objects are eventually terminated on their own.
1701 if ((object->flags & OBJ_DEAD) != 0)
1705 * Sync with fences placed after pctrie
1706 * initialization. We must not access pctrie below
1707 * unless we checked that our object is swap and not
1710 atomic_thread_fence_acq();
1711 if (object->type != OBJT_SWAP)
1714 for (pi = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1715 &object->un_pager.swp.swp_blks, pi)) != NULL; ) {
1716 pi = sb->p + SWAP_META_PAGES;
1717 for (i = 0; i < SWAP_META_PAGES; i++) {
1718 if (sb->d[i] == SWAPBLK_NONE)
1720 if (swp_pager_isondev(sb->d[i], sp))
1721 swp_pager_force_pagein(object,
1726 VM_OBJECT_WUNLOCK(object);
1727 mtx_lock(&vm_object_list_mtx);
1729 mtx_unlock(&vm_object_list_mtx);
1733 * Objects may be locked or paging to the device being
1734 * removed, so we will miss their pages and need to
1735 * make another pass. We have marked this device as
1736 * SW_CLOSING, so the activity should finish soon.
1739 if (retries > 100) {
1740 panic("swapoff: failed to locate %d swap blocks",
1743 pause("swpoff", hz / 20);
1746 EVENTHANDLER_INVOKE(swapoff, sp);
1749 /************************************************************************
1751 ************************************************************************
1753 * These routines manipulate the swap metadata stored in the
1756 * Swap metadata is implemented with a global hash and not directly
1757 * linked into the object. Instead the object simply contains
1758 * appropriate tracking counters.
1762 * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free?
1765 swp_pager_swblk_empty(struct swblk *sb, int start, int limit)
1769 MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES);
1770 for (i = start; i < limit; i++) {
1771 if (sb->d[i] != SWAPBLK_NONE)
1778 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object
1780 * We first convert the object to a swap object if it is a default
1783 * The specified swapblk is added to the object's swap metadata. If
1784 * the swapblk is not valid, it is freed instead. Any previously
1785 * assigned swapblk is freed.
1788 swp_pager_meta_build(vm_object_t object, vm_pindex_t pindex, daddr_t swapblk)
1790 static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted;
1791 struct swblk *sb, *sb1;
1792 vm_pindex_t modpi, rdpi;
1795 VM_OBJECT_ASSERT_WLOCKED(object);
1798 * Convert default object to swap object if necessary
1800 if (object->type != OBJT_SWAP) {
1801 pctrie_init(&object->un_pager.swp.swp_blks);
1804 * Ensure that swap_pager_swapoff()'s iteration over
1805 * object_list does not see a garbage pctrie.
1807 atomic_thread_fence_rel();
1809 object->type = OBJT_SWAP;
1810 KASSERT(object->handle == NULL, ("default pager with handle"));
1813 rdpi = rounddown(pindex, SWAP_META_PAGES);
1814 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, rdpi);
1816 if (swapblk == SWAPBLK_NONE)
1819 sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc ==
1820 pageproc ? M_USE_RESERVE : 0));
1823 for (i = 0; i < SWAP_META_PAGES; i++)
1824 sb->d[i] = SWAPBLK_NONE;
1825 if (atomic_cmpset_int(&swblk_zone_exhausted,
1827 printf("swblk zone ok\n");
1830 VM_OBJECT_WUNLOCK(object);
1831 if (uma_zone_exhausted(swblk_zone)) {
1832 if (atomic_cmpset_int(&swblk_zone_exhausted,
1834 printf("swap blk zone exhausted, "
1835 "increase kern.maxswzone\n");
1836 vm_pageout_oom(VM_OOM_SWAPZ);
1837 pause("swzonxb", 10);
1839 uma_zwait(swblk_zone);
1840 VM_OBJECT_WLOCK(object);
1841 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
1845 * Somebody swapped out a nearby page,
1846 * allocating swblk at the rdpi index,
1847 * while we dropped the object lock.
1852 error = SWAP_PCTRIE_INSERT(
1853 &object->un_pager.swp.swp_blks, sb);
1855 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
1857 printf("swpctrie zone ok\n");
1860 VM_OBJECT_WUNLOCK(object);
1861 if (uma_zone_exhausted(swpctrie_zone)) {
1862 if (atomic_cmpset_int(&swpctrie_zone_exhausted,
1864 printf("swap pctrie zone exhausted, "
1865 "increase kern.maxswzone\n");
1866 vm_pageout_oom(VM_OOM_SWAPZ);
1867 pause("swzonxp", 10);
1869 uma_zwait(swpctrie_zone);
1870 VM_OBJECT_WLOCK(object);
1871 sb1 = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
1874 uma_zfree(swblk_zone, sb);
1881 MPASS(sb->p == rdpi);
1883 modpi = pindex % SWAP_META_PAGES;
1884 /* Delete prior contents of metadata. */
1885 if (sb->d[modpi] != SWAPBLK_NONE)
1886 swp_pager_freeswapspace(sb->d[modpi], 1);
1887 /* Enter block into metadata. */
1888 sb->d[modpi] = swapblk;
1891 * Free the swblk if we end up with the empty page run.
1893 if (swapblk == SWAPBLK_NONE &&
1894 swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
1895 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, rdpi);
1896 uma_zfree(swblk_zone, sb);
1901 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata
1903 * The requested range of blocks is freed, with any associated swap
1904 * returned to the swap bitmap.
1906 * This routine will free swap metadata structures as they are cleaned
1907 * out. This routine does *NOT* operate on swap metadata associated
1908 * with resident pages.
1911 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count)
1914 daddr_t first_free, num_free;
1916 int i, limit, start;
1918 VM_OBJECT_ASSERT_WLOCKED(object);
1919 if (object->type != OBJT_SWAP || count == 0)
1922 first_free = SWAPBLK_NONE;
1924 last = pindex + count;
1926 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
1927 rounddown(pindex, SWAP_META_PAGES));
1928 if (sb == NULL || sb->p >= last)
1930 start = pindex > sb->p ? pindex - sb->p : 0;
1931 limit = last - sb->p < SWAP_META_PAGES ? last - sb->p :
1933 for (i = start; i < limit; i++) {
1934 if (sb->d[i] == SWAPBLK_NONE)
1936 if (first_free + num_free == sb->d[i])
1939 swp_pager_freeswapspace(first_free, num_free);
1940 first_free = sb->d[i];
1943 sb->d[i] = SWAPBLK_NONE;
1945 if (swp_pager_swblk_empty(sb, 0, start) &&
1946 swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) {
1947 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks,
1949 uma_zfree(swblk_zone, sb);
1951 pindex = sb->p + SWAP_META_PAGES;
1953 swp_pager_freeswapspace(first_free, num_free);
1957 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object
1959 * This routine locates and destroys all swap metadata associated with
1963 swp_pager_meta_free_all(vm_object_t object)
1966 daddr_t first_free, num_free;
1970 VM_OBJECT_ASSERT_WLOCKED(object);
1971 if (object->type != OBJT_SWAP)
1974 first_free = SWAPBLK_NONE;
1976 for (pindex = 0; (sb = SWAP_PCTRIE_LOOKUP_GE(
1977 &object->un_pager.swp.swp_blks, pindex)) != NULL;) {
1978 pindex = sb->p + SWAP_META_PAGES;
1979 for (i = 0; i < SWAP_META_PAGES; i++) {
1980 if (sb->d[i] == SWAPBLK_NONE)
1982 if (first_free + num_free == sb->d[i])
1985 swp_pager_freeswapspace(first_free, num_free);
1986 first_free = sb->d[i];
1990 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p);
1991 uma_zfree(swblk_zone, sb);
1993 swp_pager_freeswapspace(first_free, num_free);
1997 * SWP_PAGER_METACTL() - misc control of swap meta data.
1999 * This routine is capable of looking up, or removing swapblk
2000 * assignments in the swap meta data. It returns the swapblk being
2001 * looked-up, popped, or SWAPBLK_NONE if the block was invalid.
2003 * When acting on a busy resident page and paging is in progress, we
2004 * have to wait until paging is complete but otherwise can act on the
2007 * SWM_POP remove from meta data but do not free it
2010 swp_pager_meta_ctl(vm_object_t object, vm_pindex_t pindex, int flags)
2015 if ((flags & SWM_POP) != 0)
2016 VM_OBJECT_ASSERT_WLOCKED(object);
2018 VM_OBJECT_ASSERT_LOCKED(object);
2021 * The meta data only exists if the object is OBJT_SWAP
2022 * and even then might not be allocated yet.
2024 if (object->type != OBJT_SWAP)
2025 return (SWAPBLK_NONE);
2027 sb = SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks,
2028 rounddown(pindex, SWAP_META_PAGES));
2030 return (SWAPBLK_NONE);
2031 r1 = sb->d[pindex % SWAP_META_PAGES];
2032 if (r1 == SWAPBLK_NONE)
2033 return (SWAPBLK_NONE);
2034 if ((flags & SWM_POP) != 0) {
2035 sb->d[pindex % SWAP_META_PAGES] = SWAPBLK_NONE;
2036 if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) {
2037 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks,
2038 rounddown(pindex, SWAP_META_PAGES));
2039 uma_zfree(swblk_zone, sb);
2046 * Returns the least page index which is greater than or equal to the
2047 * parameter pindex and for which there is a swap block allocated.
2048 * Returns object's size if the object's type is not swap or if there
2049 * are no allocated swap blocks for the object after the requested
2053 swap_pager_find_least(vm_object_t object, vm_pindex_t pindex)
2058 VM_OBJECT_ASSERT_LOCKED(object);
2059 if (object->type != OBJT_SWAP)
2060 return (object->size);
2062 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2063 rounddown(pindex, SWAP_META_PAGES));
2065 return (object->size);
2066 if (sb->p < pindex) {
2067 for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) {
2068 if (sb->d[i] != SWAPBLK_NONE)
2071 sb = SWAP_PCTRIE_LOOKUP_GE(&object->un_pager.swp.swp_blks,
2072 roundup(pindex, SWAP_META_PAGES));
2074 return (object->size);
2076 for (i = 0; i < SWAP_META_PAGES; i++) {
2077 if (sb->d[i] != SWAPBLK_NONE)
2082 * We get here if a swblk is present in the trie but it
2083 * doesn't map any blocks.
2086 return (object->size);
2090 * System call swapon(name) enables swapping on device name,
2091 * which must be in the swdevsw. Return EBUSY
2092 * if already swapping on this device.
2094 #ifndef _SYS_SYSPROTO_H_
2095 struct swapon_args {
2105 sys_swapon(struct thread *td, struct swapon_args *uap)
2109 struct nameidata nd;
2112 error = priv_check(td, PRIV_SWAPON);
2116 sx_xlock(&swdev_syscall_lock);
2119 * Swap metadata may not fit in the KVM if we have physical
2122 if (swblk_zone == NULL) {
2127 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | AUDITVNODE1, UIO_USERSPACE,
2133 NDFREE(&nd, NDF_ONLY_PNBUF);
2136 if (vn_isdisk(vp, &error)) {
2137 error = swapongeom(vp);
2138 } else if (vp->v_type == VREG &&
2139 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 &&
2140 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) {
2142 * Allow direct swapping to NFS regular files in the same
2143 * way that nfs_mountroot() sets up diskless swapping.
2145 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE);
2151 sx_xunlock(&swdev_syscall_lock);
2156 * Check that the total amount of swap currently configured does not
2157 * exceed half the theoretical maximum. If it does, print a warning
2161 swapon_check_swzone(void)
2163 unsigned long maxpages, npages;
2165 npages = swap_total / PAGE_SIZE;
2166 /* absolute maximum we can handle assuming 100% efficiency */
2167 maxpages = uma_zone_get_max(swblk_zone) * SWAP_META_PAGES;
2169 /* recommend using no more than half that amount */
2170 if (npages > maxpages / 2) {
2171 printf("warning: total configured swap (%lu pages) "
2172 "exceeds maximum recommended amount (%lu pages).\n",
2173 npages, maxpages / 2);
2174 printf("warning: increase kern.maxswzone "
2175 "or reduce amount of swap.\n");
2180 swaponsomething(struct vnode *vp, void *id, u_long nblks,
2181 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags)
2183 struct swdevt *sp, *tsp;
2188 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks.
2189 * First chop nblks off to page-align it, then convert.
2191 * sw->sw_nblks is in page-sized chunks now too.
2193 nblks &= ~(ctodb(1) - 1);
2194 nblks = dbtoc(nblks);
2197 * If we go beyond this, we get overflows in the radix
2200 mblocks = 0x40000000 / BLIST_META_RADIX;
2201 if (nblks > mblocks) {
2203 "WARNING: reducing swap size to maximum of %luMB per unit\n",
2204 mblocks / 1024 / 1024 * PAGE_SIZE);
2208 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO);
2213 sp->sw_nblks = nblks;
2215 sp->sw_strategy = strategy;
2216 sp->sw_close = close;
2217 sp->sw_flags = flags;
2219 sp->sw_blist = blist_create(nblks, M_WAITOK);
2221 * Do not free the first two block in order to avoid overwriting
2222 * any bsd label at the front of the partition
2224 blist_free(sp->sw_blist, 2, nblks - 2);
2227 mtx_lock(&sw_dev_mtx);
2228 TAILQ_FOREACH(tsp, &swtailq, sw_list) {
2229 if (tsp->sw_end >= dvbase) {
2231 * We put one uncovered page between the devices
2232 * in order to definitively prevent any cross-device
2235 dvbase = tsp->sw_end + 1;
2238 sp->sw_first = dvbase;
2239 sp->sw_end = dvbase + nblks;
2240 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list);
2242 swap_pager_avail += nblks - 2;
2243 swap_total += (vm_ooffset_t)nblks * PAGE_SIZE;
2244 swapon_check_swzone();
2246 mtx_unlock(&sw_dev_mtx);
2247 EVENTHANDLER_INVOKE(swapon, sp);
2251 * SYSCALL: swapoff(devname)
2253 * Disable swapping on the given device.
2255 * XXX: Badly designed system call: it should use a device index
2256 * rather than filename as specification. We keep sw_vp around
2257 * only to make this work.
2259 #ifndef _SYS_SYSPROTO_H_
2260 struct swapoff_args {
2270 sys_swapoff(struct thread *td, struct swapoff_args *uap)
2273 struct nameidata nd;
2277 error = priv_check(td, PRIV_SWAPOFF);
2281 sx_xlock(&swdev_syscall_lock);
2283 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, UIO_USERSPACE, uap->name,
2288 NDFREE(&nd, NDF_ONLY_PNBUF);
2291 mtx_lock(&sw_dev_mtx);
2292 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2293 if (sp->sw_vp == vp)
2296 mtx_unlock(&sw_dev_mtx);
2301 error = swapoff_one(sp, td->td_ucred);
2303 sx_xunlock(&swdev_syscall_lock);
2308 swapoff_one(struct swdevt *sp, struct ucred *cred)
2315 sx_assert(&swdev_syscall_lock, SA_XLOCKED);
2317 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY);
2318 error = mac_system_check_swapoff(cred, sp->sw_vp);
2319 (void) VOP_UNLOCK(sp->sw_vp, 0);
2323 nblks = sp->sw_nblks;
2326 * We can turn off this swap device safely only if the
2327 * available virtual memory in the system will fit the amount
2328 * of data we will have to page back in, plus an epsilon so
2329 * the system doesn't become critically low on swap space.
2331 if (vm_free_count() + swap_pager_avail < nblks + nswap_lowat)
2335 * Prevent further allocations on this device.
2337 mtx_lock(&sw_dev_mtx);
2338 sp->sw_flags |= SW_CLOSING;
2339 swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks);
2340 swap_total -= (vm_ooffset_t)nblks * PAGE_SIZE;
2341 mtx_unlock(&sw_dev_mtx);
2344 * Page in the contents of the device and close it.
2346 swap_pager_swapoff(sp);
2348 sp->sw_close(curthread, sp);
2349 mtx_lock(&sw_dev_mtx);
2351 TAILQ_REMOVE(&swtailq, sp, sw_list);
2353 if (nswapdev == 0) {
2354 swap_pager_full = 2;
2355 swap_pager_almost_full = 1;
2359 mtx_unlock(&sw_dev_mtx);
2360 blist_destroy(sp->sw_blist);
2361 free(sp, M_VMPGDATA);
2368 struct swdevt *sp, *spt;
2369 const char *devname;
2372 sx_xlock(&swdev_syscall_lock);
2374 mtx_lock(&sw_dev_mtx);
2375 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) {
2376 mtx_unlock(&sw_dev_mtx);
2377 if (vn_isdisk(sp->sw_vp, NULL))
2378 devname = devtoname(sp->sw_vp->v_rdev);
2381 error = swapoff_one(sp, thread0.td_ucred);
2383 printf("Cannot remove swap device %s (error=%d), "
2384 "skipping.\n", devname, error);
2385 } else if (bootverbose) {
2386 printf("Swap device %s removed.\n", devname);
2388 mtx_lock(&sw_dev_mtx);
2390 mtx_unlock(&sw_dev_mtx);
2392 sx_xunlock(&swdev_syscall_lock);
2396 swap_pager_status(int *total, int *used)
2402 mtx_lock(&sw_dev_mtx);
2403 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2404 *total += sp->sw_nblks;
2405 *used += sp->sw_used;
2407 mtx_unlock(&sw_dev_mtx);
2411 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len)
2414 const char *tmp_devname;
2419 mtx_lock(&sw_dev_mtx);
2420 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2425 xs->xsw_version = XSWDEV_VERSION;
2426 xs->xsw_dev = sp->sw_dev;
2427 xs->xsw_flags = sp->sw_flags;
2428 xs->xsw_nblks = sp->sw_nblks;
2429 xs->xsw_used = sp->sw_used;
2430 if (devname != NULL) {
2431 if (vn_isdisk(sp->sw_vp, NULL))
2432 tmp_devname = devtoname(sp->sw_vp->v_rdev);
2434 tmp_devname = "[file]";
2435 strncpy(devname, tmp_devname, len);
2440 mtx_unlock(&sw_dev_mtx);
2444 #if defined(COMPAT_FREEBSD11)
2445 #define XSWDEV_VERSION_11 1
2456 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS)
2459 #if defined(COMPAT_FREEBSD11)
2460 struct xswdev11 xs11;
2464 if (arg2 != 1) /* name length */
2466 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0);
2469 #if defined(COMPAT_FREEBSD11)
2470 if (req->oldlen == sizeof(xs11)) {
2471 xs11.xsw_version = XSWDEV_VERSION_11;
2472 xs11.xsw_dev = xs.xsw_dev; /* truncation */
2473 xs11.xsw_flags = xs.xsw_flags;
2474 xs11.xsw_nblks = xs.xsw_nblks;
2475 xs11.xsw_used = xs.xsw_used;
2476 error = SYSCTL_OUT(req, &xs11, sizeof(xs11));
2479 error = SYSCTL_OUT(req, &xs, sizeof(xs));
2483 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0,
2484 "Number of swap devices");
2485 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE,
2486 sysctl_vm_swap_info,
2487 "Swap statistics by device");
2490 * Count the approximate swap usage in pages for a vmspace. The
2491 * shadowed or not yet copied on write swap blocks are not accounted.
2492 * The map must be locked.
2495 vmspace_swap_count(struct vmspace *vmspace)
2505 map = &vmspace->vm_map;
2508 for (cur = map->header.next; cur != &map->header; cur = cur->next) {
2509 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2511 object = cur->object.vm_object;
2512 if (object == NULL || object->type != OBJT_SWAP)
2514 VM_OBJECT_RLOCK(object);
2515 if (object->type != OBJT_SWAP)
2517 pi = OFF_TO_IDX(cur->offset);
2518 e = pi + OFF_TO_IDX(cur->end - cur->start);
2519 for (;; pi = sb->p + SWAP_META_PAGES) {
2520 sb = SWAP_PCTRIE_LOOKUP_GE(
2521 &object->un_pager.swp.swp_blks, pi);
2522 if (sb == NULL || sb->p >= e)
2524 for (i = 0; i < SWAP_META_PAGES; i++) {
2525 if (sb->p + i < e &&
2526 sb->d[i] != SWAPBLK_NONE)
2531 VM_OBJECT_RUNLOCK(object);
2539 * Swapping onto disk devices.
2543 static g_orphan_t swapgeom_orphan;
2545 static struct g_class g_swap_class = {
2547 .version = G_VERSION,
2548 .orphan = swapgeom_orphan,
2551 DECLARE_GEOM_CLASS(g_swap_class, g_class);
2555 swapgeom_close_ev(void *arg, int flags)
2557 struct g_consumer *cp;
2560 g_access(cp, -1, -1, 0);
2562 g_destroy_consumer(cp);
2566 * Add a reference to the g_consumer for an inflight transaction.
2569 swapgeom_acquire(struct g_consumer *cp)
2572 mtx_assert(&sw_dev_mtx, MA_OWNED);
2577 * Remove a reference from the g_consumer. Post a close event if all
2578 * references go away, since the function might be called from the
2582 swapgeom_release(struct g_consumer *cp, struct swdevt *sp)
2585 mtx_assert(&sw_dev_mtx, MA_OWNED);
2587 if (cp->index == 0) {
2588 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0)
2594 swapgeom_done(struct bio *bp2)
2598 struct g_consumer *cp;
2600 bp = bp2->bio_caller2;
2602 bp->b_ioflags = bp2->bio_flags;
2604 bp->b_ioflags |= BIO_ERROR;
2605 bp->b_resid = bp->b_bcount - bp2->bio_completed;
2606 bp->b_error = bp2->bio_error;
2608 sp = bp2->bio_caller1;
2609 mtx_lock(&sw_dev_mtx);
2610 swapgeom_release(cp, sp);
2611 mtx_unlock(&sw_dev_mtx);
2616 swapgeom_strategy(struct buf *bp, struct swdevt *sp)
2619 struct g_consumer *cp;
2621 mtx_lock(&sw_dev_mtx);
2624 mtx_unlock(&sw_dev_mtx);
2625 bp->b_error = ENXIO;
2626 bp->b_ioflags |= BIO_ERROR;
2630 swapgeom_acquire(cp);
2631 mtx_unlock(&sw_dev_mtx);
2632 if (bp->b_iocmd == BIO_WRITE)
2635 bio = g_alloc_bio();
2637 mtx_lock(&sw_dev_mtx);
2638 swapgeom_release(cp, sp);
2639 mtx_unlock(&sw_dev_mtx);
2640 bp->b_error = ENOMEM;
2641 bp->b_ioflags |= BIO_ERROR;
2646 bio->bio_caller1 = sp;
2647 bio->bio_caller2 = bp;
2648 bio->bio_cmd = bp->b_iocmd;
2649 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE;
2650 bio->bio_length = bp->b_bcount;
2651 bio->bio_done = swapgeom_done;
2652 if (!buf_mapped(bp)) {
2653 bio->bio_ma = bp->b_pages;
2654 bio->bio_data = unmapped_buf;
2655 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK;
2656 bio->bio_ma_n = bp->b_npages;
2657 bio->bio_flags |= BIO_UNMAPPED;
2659 bio->bio_data = bp->b_data;
2662 g_io_request(bio, cp);
2667 swapgeom_orphan(struct g_consumer *cp)
2672 mtx_lock(&sw_dev_mtx);
2673 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2674 if (sp->sw_id == cp) {
2675 sp->sw_flags |= SW_CLOSING;
2680 * Drop reference we were created with. Do directly since we're in a
2681 * special context where we don't have to queue the call to
2682 * swapgeom_close_ev().
2685 destroy = ((sp != NULL) && (cp->index == 0));
2688 mtx_unlock(&sw_dev_mtx);
2690 swapgeom_close_ev(cp, 0);
2694 swapgeom_close(struct thread *td, struct swdevt *sw)
2696 struct g_consumer *cp;
2698 mtx_lock(&sw_dev_mtx);
2701 mtx_unlock(&sw_dev_mtx);
2704 * swapgeom_close() may be called from the biodone context,
2705 * where we cannot perform topology changes. Delegate the
2706 * work to the events thread.
2709 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL);
2713 swapongeom_locked(struct cdev *dev, struct vnode *vp)
2715 struct g_provider *pp;
2716 struct g_consumer *cp;
2717 static struct g_geom *gp;
2722 pp = g_dev_getprovider(dev);
2725 mtx_lock(&sw_dev_mtx);
2726 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2728 if (cp != NULL && cp->provider == pp) {
2729 mtx_unlock(&sw_dev_mtx);
2733 mtx_unlock(&sw_dev_mtx);
2735 gp = g_new_geomf(&g_swap_class, "swap");
2736 cp = g_new_consumer(gp);
2737 cp->index = 1; /* Number of active I/Os, plus one for being active. */
2738 cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE;
2741 * XXX: Every time you think you can improve the margin for
2742 * footshooting, somebody depends on the ability to do so:
2743 * savecore(8) wants to write to our swapdev so we cannot
2744 * set an exclusive count :-(
2746 error = g_access(cp, 1, 1, 0);
2749 g_destroy_consumer(cp);
2752 nblks = pp->mediasize / DEV_BSIZE;
2753 swaponsomething(vp, cp, nblks, swapgeom_strategy,
2754 swapgeom_close, dev2udev(dev),
2755 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0);
2760 swapongeom(struct vnode *vp)
2764 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2765 if (vp->v_type != VCHR || (vp->v_iflag & VI_DOOMED) != 0) {
2769 error = swapongeom_locked(vp->v_rdev, vp);
2770 g_topology_unlock();
2779 * This is used mainly for network filesystem (read: probably only tested
2780 * with NFS) swapfiles.
2785 swapdev_strategy(struct buf *bp, struct swdevt *sp)
2789 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first);
2793 if (bp->b_iocmd == BIO_WRITE) {
2795 bufobj_wdrop(bp->b_bufobj);
2796 bufobj_wref(&vp2->v_bufobj);
2798 if (bp->b_bufobj != &vp2->v_bufobj)
2799 bp->b_bufobj = &vp2->v_bufobj;
2801 bp->b_iooffset = dbtob(bp->b_blkno);
2807 swapdev_close(struct thread *td, struct swdevt *sp)
2810 VOP_CLOSE(sp->sw_vp, FREAD | FWRITE, td->td_ucred, td);
2816 swaponvp(struct thread *td, struct vnode *vp, u_long nblks)
2823 mtx_lock(&sw_dev_mtx);
2824 TAILQ_FOREACH(sp, &swtailq, sw_list) {
2825 if (sp->sw_id == vp) {
2826 mtx_unlock(&sw_dev_mtx);
2830 mtx_unlock(&sw_dev_mtx);
2832 (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2834 error = mac_system_check_swapon(td->td_ucred, vp);
2837 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL);
2838 (void) VOP_UNLOCK(vp, 0);
2842 swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close,
2848 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS)
2852 new = nsw_wcount_async_max;
2853 error = sysctl_handle_int(oidp, &new, 0, req);
2854 if (error != 0 || req->newptr == NULL)
2857 if (new > nswbuf / 2 || new < 1)
2860 mtx_lock(&pbuf_mtx);
2861 while (nsw_wcount_async_max != new) {
2863 * Adjust difference. If the current async count is too low,
2864 * we will need to sqeeze our update slowly in. Sleep with a
2865 * higher priority than getpbuf() to finish faster.
2867 n = new - nsw_wcount_async_max;
2868 if (nsw_wcount_async + n >= 0) {
2869 nsw_wcount_async += n;
2870 nsw_wcount_async_max += n;
2871 wakeup(&nsw_wcount_async);
2873 nsw_wcount_async_max -= nsw_wcount_async;
2874 nsw_wcount_async = 0;
2875 msleep(&nsw_wcount_async, &pbuf_mtx, PSWP,
2879 mtx_unlock(&pbuf_mtx);