2 * SPDX-License-Identifier: (BSD-4-Clause AND MIT-CMU)
4 * Copyright (c) 1991 Regents of the University of California.
6 * Copyright (c) 1994 John S. Dyson
8 * Copyright (c) 1994 David Greenman
10 * Copyright (c) 2005 Yahoo! Technologies Norway AS
11 * All rights reserved.
13 * This code is derived from software contributed to Berkeley by
14 * The Mach Operating System project at Carnegie-Mellon University.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
24 * 3. All advertising materials mentioning features or use of this software
25 * must display the following acknowledgement:
26 * This product includes software developed by the University of
27 * California, Berkeley and its contributors.
28 * 4. Neither the name of the University nor the names of its contributors
29 * may be used to endorse or promote products derived from this software
30 * without specific prior written permission.
32 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
33 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
36 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
44 * from: @(#)vm_pageout.c 7.4 (Berkeley) 5/7/91
47 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
48 * All rights reserved.
50 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
52 * Permission to use, copy, modify and distribute this software and
53 * its documentation is hereby granted, provided that both the copyright
54 * notice and this permission notice appear in all copies of the
55 * software, derivative works or modified versions, and any portions
56 * thereof, and that both notices appear in supporting documentation.
58 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
59 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
60 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
62 * Carnegie Mellon requests users of this software to return to
64 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
65 * School of Computer Science
66 * Carnegie Mellon University
67 * Pittsburgh PA 15213-3890
69 * any improvements or extensions that they make and grant Carnegie the
70 * rights to redistribute these changes.
73 #include <sys/cdefs.h>
74 __FBSDID("$FreeBSD$");
76 #include "opt_kstack_pages.h"
77 #include "opt_kstack_max_pages.h"
80 #include <sys/param.h>
81 #include <sys/systm.h>
82 #include <sys/limits.h>
83 #include <sys/kernel.h>
84 #include <sys/eventhandler.h>
86 #include <sys/mutex.h>
88 #include <sys/_kstack_cache.h>
89 #include <sys/kthread.h>
91 #include <sys/mount.h>
92 #include <sys/racct.h>
93 #include <sys/resourcevar.h>
94 #include <sys/sched.h>
96 #include <sys/signalvar.h>
99 #include <sys/vnode.h>
100 #include <sys/vmmeter.h>
101 #include <sys/rwlock.h>
103 #include <sys/sysctl.h>
106 #include <vm/vm_param.h>
107 #include <vm/vm_object.h>
108 #include <vm/vm_page.h>
109 #include <vm/vm_map.h>
110 #include <vm/vm_pageout.h>
111 #include <vm/vm_pager.h>
112 #include <vm/vm_phys.h>
113 #include <vm/swap_pager.h>
114 #include <vm/vm_extern.h>
117 /* the kernel process "vm_daemon" */
118 static void vm_daemon(void);
119 static struct proc *vmproc;
121 static struct kproc_desc vm_kp = {
126 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
128 static int vm_swap_enabled = 1;
129 static int vm_swap_idle_enabled = 0;
131 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled, CTLFLAG_RW,
133 "Enable entire process swapout");
134 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled, CTLFLAG_RW,
135 &vm_swap_idle_enabled, 0,
136 "Allow swapout on idle criteria");
139 * Swap_idle_threshold1 is the guaranteed swapped in time for a process
141 static int swap_idle_threshold1 = 2;
142 SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold1, CTLFLAG_RW,
143 &swap_idle_threshold1, 0,
144 "Guaranteed swapped in time for a process");
147 * Swap_idle_threshold2 is the time that a process can be idle before
148 * it will be swapped out, if idle swapping is enabled.
150 static int swap_idle_threshold2 = 10;
151 SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold2, CTLFLAG_RW,
152 &swap_idle_threshold2, 0,
153 "Time before a process will be swapped out");
155 static int vm_pageout_req_swapout; /* XXX */
156 static int vm_daemon_needed;
157 static struct mtx vm_daemon_mtx;
158 /* Allow for use by vm_pageout before vm_daemon is initialized. */
159 MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
161 static void swapclear(struct proc *);
162 static int swapout(struct proc *);
163 static void vm_swapout_map_deactivate_pages(vm_map_t, long);
164 static void vm_swapout_object_deactivate_pages(pmap_t, vm_object_t, long);
165 static void swapout_procs(int action);
166 static void vm_req_vmdaemon(int req);
167 static void vm_thread_swapin(struct thread *td);
168 static void vm_thread_swapout(struct thread *td);
171 * vm_swapout_object_deactivate_pages
173 * Deactivate enough pages to satisfy the inactive target
176 * The object and map must be locked.
179 vm_swapout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
182 vm_object_t backing_object, object;
184 int act_delta, remove_mode;
186 VM_OBJECT_ASSERT_LOCKED(first_object);
187 if ((first_object->flags & OBJ_FICTITIOUS) != 0)
189 for (object = first_object;; object = backing_object) {
190 if (pmap_resident_count(pmap) <= desired)
192 VM_OBJECT_ASSERT_LOCKED(object);
193 if ((object->flags & OBJ_UNMANAGED) != 0 ||
194 object->paging_in_progress != 0)
198 if (object->shadow_count > 1)
201 * Scan the object's entire memory queue.
203 TAILQ_FOREACH(p, &object->memq, listq) {
204 if (pmap_resident_count(pmap) <= desired)
208 if (vm_page_busied(p))
210 VM_CNT_INC(v_pdpages);
212 if (vm_page_held(p) ||
213 !pmap_page_exists_quick(pmap, p)) {
217 act_delta = pmap_ts_referenced(p);
218 if ((p->aflags & PGA_REFERENCED) != 0) {
221 vm_page_aflag_clear(p, PGA_REFERENCED);
223 if (!vm_page_active(p) && act_delta != 0) {
225 p->act_count += act_delta;
226 } else if (vm_page_active(p)) {
227 if (act_delta == 0) {
228 p->act_count -= min(p->act_count,
230 if (!remove_mode && p->act_count == 0) {
232 vm_page_deactivate(p);
237 if (p->act_count < ACT_MAX -
239 p->act_count += ACT_ADVANCE;
242 } else if (vm_page_inactive(p))
246 if ((backing_object = object->backing_object) == NULL)
248 VM_OBJECT_RLOCK(backing_object);
249 if (object != first_object)
250 VM_OBJECT_RUNLOCK(object);
253 if (object != first_object)
254 VM_OBJECT_RUNLOCK(object);
258 * deactivate some number of pages in a map, try to do it fairly, but
259 * that is really hard to do.
262 vm_swapout_map_deactivate_pages(vm_map_t map, long desired)
265 vm_object_t obj, bigobj;
268 if (!vm_map_trylock_read(map))
275 * first, search out the biggest object, and try to free pages from
278 tmpe = map->header.next;
279 while (tmpe != &map->header) {
280 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
281 obj = tmpe->object.vm_object;
282 if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
283 if (obj->shadow_count <= 1 &&
285 bigobj->resident_page_count <
286 obj->resident_page_count)) {
288 VM_OBJECT_RUNLOCK(bigobj);
291 VM_OBJECT_RUNLOCK(obj);
294 if (tmpe->wired_count > 0)
295 nothingwired = FALSE;
299 if (bigobj != NULL) {
300 vm_swapout_object_deactivate_pages(map->pmap, bigobj, desired);
301 VM_OBJECT_RUNLOCK(bigobj);
304 * Next, hunt around for other pages to deactivate. We actually
305 * do this search sort of wrong -- .text first is not the best idea.
307 tmpe = map->header.next;
308 while (tmpe != &map->header) {
309 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
311 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
312 obj = tmpe->object.vm_object;
314 VM_OBJECT_RLOCK(obj);
315 vm_swapout_object_deactivate_pages(map->pmap,
317 VM_OBJECT_RUNLOCK(obj);
324 * Remove all mappings if a process is swapped out, this will free page
327 if (desired == 0 && nothingwired) {
328 pmap_remove(vm_map_pmap(map), vm_map_min(map),
332 vm_map_unlock_read(map);
338 #define VM_SWAP_NORMAL 1
339 #define VM_SWAP_IDLE 2
346 vm_req_vmdaemon(VM_SWAP_NORMAL);
350 * Idle process swapout -- run once per second when pagedaemons are
354 vm_swapout_run_idle(void)
358 if (!vm_swap_idle_enabled || time_second == lsec)
360 vm_req_vmdaemon(VM_SWAP_IDLE);
365 vm_req_vmdaemon(int req)
367 static int lastrun = 0;
369 mtx_lock(&vm_daemon_mtx);
370 vm_pageout_req_swapout |= req;
371 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
372 wakeup(&vm_daemon_needed);
375 mtx_unlock(&vm_daemon_mtx);
381 struct rlimit rsslim;
385 int breakout, swapout_flags, tryagain, attempts;
387 uint64_t rsize, ravailable;
391 mtx_lock(&vm_daemon_mtx);
392 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
394 racct_enable ? hz : 0
399 swapout_flags = vm_pageout_req_swapout;
400 vm_pageout_req_swapout = 0;
401 mtx_unlock(&vm_daemon_mtx);
403 swapout_procs(swapout_flags);
406 * scan the processes for exceeding their rlimits or if
407 * process is swapped out -- deactivate pages
413 sx_slock(&allproc_lock);
414 FOREACH_PROC_IN_SYSTEM(p) {
415 vm_pindex_t limit, size;
418 * if this is a system process or if we have already
419 * looked at this process, skip it.
422 if (p->p_state != PRS_NORMAL ||
423 p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
428 * if the process is in a non-running type state,
432 FOREACH_THREAD_IN_PROC(p, td) {
434 if (!TD_ON_RUNQ(td) &&
435 !TD_IS_RUNNING(td) &&
436 !TD_IS_SLEEPING(td) &&
437 !TD_IS_SUSPENDED(td)) {
451 lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
453 qmin(rsslim.rlim_cur, rsslim.rlim_max));
456 * let processes that are swapped out really be
457 * swapped out set the limit to nothing (will force a
460 if ((p->p_flag & P_INMEM) == 0)
462 vm = vmspace_acquire_ref(p);
469 sx_sunlock(&allproc_lock);
471 size = vmspace_resident_count(vm);
473 vm_swapout_map_deactivate_pages(
475 size = vmspace_resident_count(vm);
479 rsize = IDX_TO_OFF(size);
481 if (p->p_state == PRS_NORMAL)
482 racct_set(p, RACCT_RSS, rsize);
483 ravailable = racct_get_available(p, RACCT_RSS);
485 if (rsize > ravailable) {
487 * Don't be overly aggressive; this
488 * might be an innocent process,
489 * and the limit could've been exceeded
490 * by some memory hog. Don't try
491 * to deactivate more than 1/4th
492 * of process' resident set size.
495 if (ravailable < rsize -
501 vm_swapout_map_deactivate_pages(
503 OFF_TO_IDX(ravailable));
504 /* Update RSS usage after paging out. */
505 size = vmspace_resident_count(vm);
506 rsize = IDX_TO_OFF(size);
508 if (p->p_state == PRS_NORMAL)
509 racct_set(p, RACCT_RSS, rsize);
511 if (rsize > ravailable)
517 sx_slock(&allproc_lock);
520 sx_sunlock(&allproc_lock);
521 if (tryagain != 0 && attempts <= 10) {
529 * Allow a thread's kernel stack to be paged out.
532 vm_thread_swapout(struct thread *td)
538 cpu_thread_swapout(td);
539 pages = td->td_kstack_pages;
540 ksobj = td->td_kstack_obj;
541 pmap_qremove(td->td_kstack, pages);
542 VM_OBJECT_WLOCK(ksobj);
543 for (i = 0; i < pages; i++) {
544 m = vm_page_lookup(ksobj, i);
546 panic("vm_thread_swapout: kstack already missing?");
549 vm_page_unwire(m, PQ_LAUNDRY);
552 VM_OBJECT_WUNLOCK(ksobj);
556 * Bring the kernel stack for a specified thread back in.
559 vm_thread_swapin(struct thread *td)
562 vm_page_t ma[KSTACK_MAX_PAGES];
563 int a, count, i, j, pages, rv;
565 pages = td->td_kstack_pages;
566 ksobj = td->td_kstack_obj;
567 VM_OBJECT_WLOCK(ksobj);
568 (void)vm_page_grab_pages(ksobj, 0, VM_ALLOC_NORMAL | VM_ALLOC_WIRED, ma,
570 for (i = 0; i < pages;) {
571 vm_page_assert_xbusied(ma[i]);
572 if (ma[i]->valid == VM_PAGE_BITS_ALL) {
573 vm_page_xunbusy(ma[i]);
577 vm_object_pip_add(ksobj, 1);
578 for (j = i + 1; j < pages; j++)
579 if (ma[j]->valid == VM_PAGE_BITS_ALL)
581 rv = vm_pager_has_page(ksobj, ma[i]->pindex, NULL, &a);
582 KASSERT(rv == 1, ("%s: missing page %p", __func__, ma[i]));
583 count = min(a + 1, j - i);
584 rv = vm_pager_get_pages(ksobj, ma + i, count, NULL, NULL);
585 KASSERT(rv == VM_PAGER_OK, ("%s: cannot get kstack for proc %d",
586 __func__, td->td_proc->p_pid));
587 vm_object_pip_wakeup(ksobj);
588 for (j = i; j < i + count; j++)
589 vm_page_xunbusy(ma[j]);
592 VM_OBJECT_WUNLOCK(ksobj);
593 pmap_qenter(td->td_kstack, ma, pages);
594 cpu_thread_swapin(td);
598 faultin(struct proc *p)
602 PROC_LOCK_ASSERT(p, MA_OWNED);
604 * If another process is swapping in this process,
605 * just wait until it finishes.
607 if (p->p_flag & P_SWAPPINGIN) {
608 while (p->p_flag & P_SWAPPINGIN)
609 msleep(&p->p_flag, &p->p_mtx, PVM, "faultin", 0);
612 if ((p->p_flag & P_INMEM) == 0) {
614 * Don't let another thread swap process p out while we are
615 * busy swapping it in.
618 p->p_flag |= P_SWAPPINGIN;
622 * We hold no lock here because the list of threads
623 * can not change while all threads in the process are
626 FOREACH_THREAD_IN_PROC(p, td)
627 vm_thread_swapin(td);
634 /* Allow other threads to swap p out now. */
640 * This swapin algorithm attempts to swap-in processes only if there
641 * is enough space for them. Of course, if a process waits for a long
642 * time, it will be swapped in anyway.
649 int ppri, pri, slptime, swtime;
652 if (vm_page_count_min()) {
659 sx_slock(&allproc_lock);
660 FOREACH_PROC_IN_SYSTEM(p) {
662 if (p->p_state == PRS_NEW ||
663 p->p_flag & (P_SWAPPINGOUT | P_SWAPPINGIN | P_INMEM)) {
667 swtime = (ticks - p->p_swtick) / hz;
668 FOREACH_THREAD_IN_PROC(p, td) {
670 * An otherwise runnable thread of a process
671 * swapped out has only the TDI_SWAPPED bit set.
674 if (td->td_inhibitors == TDI_SWAPPED) {
675 slptime = (ticks - td->td_slptick) / hz;
676 pri = swtime + slptime;
677 if ((td->td_flags & TDF_SWAPINREQ) == 0)
678 pri -= p->p_nice * 8;
680 * if this thread is higher priority
681 * and there is enough space, then select
682 * this process instead of the previous
694 sx_sunlock(&allproc_lock);
697 * Nothing to do, back to sleep.
699 if ((p = pp) == NULL) {
700 tsleep(&proc0, PVM, "swapin", MAXSLP * hz / 2);
706 * Another process may be bringing or may have already
707 * brought this process in while we traverse all threads.
708 * Or, this process may even be being swapped out again.
710 if (p->p_flag & (P_INMEM | P_SWAPPINGOUT | P_SWAPPINGIN)) {
716 * We would like to bring someone in.
724 * First, if any processes have been sleeping or stopped for at least
725 * "swap_idle_threshold1" seconds, they are swapped out. If, however,
726 * no such processes exist, then the longest-sleeping or stopped
727 * process is swapped out. Finally, and only as a last resort, if
728 * there are no sleeping or stopped processes, the longest-resident
729 * process is swapped out.
732 swapout_procs(int action)
737 bool didswap, doswap;
739 MPASS((action & (VM_SWAP_NORMAL | VM_SWAP_IDLE)) != 0);
742 sx_slock(&allproc_lock);
743 FOREACH_PROC_IN_SYSTEM(p) {
745 * Filter out not yet fully constructed processes. Do
746 * not swap out held processes. Avoid processes which
747 * are system, exiting, execing, traced, already swapped
748 * out or are in the process of being swapped in or out.
751 if (p->p_state != PRS_NORMAL || p->p_lock != 0 || (p->p_flag &
752 (P_SYSTEM | P_WEXIT | P_INEXEC | P_STOPPED_SINGLE |
753 P_TRACED | P_SWAPPINGOUT | P_SWAPPINGIN | P_INMEM)) !=
760 * Further consideration of this process for swap out
761 * requires iterating over its threads. We release
762 * allproc_lock here so that process creation and
763 * destruction are not blocked while we iterate.
765 * To later reacquire allproc_lock and resume
766 * iteration over the allproc list, we will first have
767 * to release the lock on the process. We place a
768 * hold on the process so that it remains in the
769 * allproc list while it is unlocked.
772 sx_sunlock(&allproc_lock);
775 * Do not swapout a realtime process.
776 * Guarantee swap_idle_threshold1 time in memory.
777 * If the system is under memory stress, or if we are
778 * swapping idle processes >= swap_idle_threshold2,
779 * then swap the process out.
782 FOREACH_THREAD_IN_PROC(p, td) {
784 slptime = (ticks - td->td_slptick) / hz;
785 if (PRI_IS_REALTIME(td->td_pri_class) ||
786 slptime < swap_idle_threshold1 ||
787 !thread_safetoswapout(td) ||
788 ((action & VM_SWAP_NORMAL) == 0 &&
789 slptime < swap_idle_threshold2))
795 if (doswap && swapout(p) == 0)
799 sx_slock(&allproc_lock);
802 sx_sunlock(&allproc_lock);
805 * If we swapped something out, and another process needed memory,
806 * then wakeup the sched process.
813 swapclear(struct proc *p)
817 PROC_LOCK_ASSERT(p, MA_OWNED);
819 FOREACH_THREAD_IN_PROC(p, td) {
821 td->td_flags |= TDF_INMEM;
822 td->td_flags &= ~TDF_SWAPINREQ;
825 if (setrunnable(td)) {
828 * XXX: We just cleared TDI_SWAPPED
829 * above and set TDF_INMEM, so this
830 * should never happen.
832 panic("not waking up swapper");
837 p->p_flag &= ~(P_SWAPPINGIN | P_SWAPPINGOUT);
838 p->p_flag |= P_INMEM;
842 swapout(struct proc *p)
846 PROC_LOCK_ASSERT(p, MA_OWNED);
849 * The states of this process and its threads may have changed
850 * by now. Assuming that there is only one pageout daemon thread,
851 * this process should still be in memory.
853 KASSERT((p->p_flag & (P_INMEM | P_SWAPPINGOUT | P_SWAPPINGIN)) ==
854 P_INMEM, ("swapout: lost a swapout race?"));
857 * Remember the resident count.
859 p->p_vmspace->vm_swrss = vmspace_resident_count(p->p_vmspace);
862 * Check and mark all threads before we proceed.
864 p->p_flag &= ~P_INMEM;
865 p->p_flag |= P_SWAPPINGOUT;
866 FOREACH_THREAD_IN_PROC(p, td) {
868 if (!thread_safetoswapout(td)) {
873 td->td_flags &= ~TDF_INMEM;
877 td = FIRST_THREAD_IN_PROC(p);
878 ++td->td_ru.ru_nswap;
882 * This list is stable because all threads are now prevented from
883 * running. The list is only modified in the context of a running
884 * thread in this process.
886 FOREACH_THREAD_IN_PROC(p, td)
887 vm_thread_swapout(td);
890 p->p_flag &= ~P_SWAPPINGOUT;