2 * Copyright (c) 1991 Regents of the University of California.
4 * Copyright (c) 1994 John S. Dyson
6 * Copyright (c) 1994 David Greenman
8 * Copyright (c) 2005 Yahoo! Technologies Norway AS
11 * This code is derived from software contributed to Berkeley by
12 * The Mach Operating System project at Carnegie-Mellon University.
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
42 * from: @(#)vm_pageout.c 7.4 (Berkeley) 5/7/91
45 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
46 * All rights reserved.
48 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
50 * Permission to use, copy, modify and distribute this software and
51 * its documentation is hereby granted, provided that both the copyright
52 * notice and this permission notice appear in all copies of the
53 * software, derivative works or modified versions, and any portions
54 * thereof, and that both notices appear in supporting documentation.
56 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
57 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
58 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
60 * Carnegie Mellon requests users of this software to return to
62 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
63 * School of Computer Science
64 * Carnegie Mellon University
65 * Pittsburgh PA 15213-3890
67 * any improvements or extensions that they make and grant Carnegie the
68 * rights to redistribute these changes.
71 #include <sys/cdefs.h>
72 __FBSDID("$FreeBSD$");
74 #include "opt_kstack_pages.h"
75 #include "opt_kstack_max_pages.h"
78 #include <sys/param.h>
79 #include <sys/systm.h>
80 #include <sys/limits.h>
81 #include <sys/kernel.h>
82 #include <sys/eventhandler.h>
84 #include <sys/mutex.h>
86 #include <sys/_kstack_cache.h>
87 #include <sys/kthread.h>
89 #include <sys/mount.h>
90 #include <sys/racct.h>
91 #include <sys/resourcevar.h>
92 #include <sys/sched.h>
94 #include <sys/signalvar.h>
97 #include <sys/vnode.h>
98 #include <sys/vmmeter.h>
99 #include <sys/rwlock.h>
101 #include <sys/sysctl.h>
104 #include <vm/vm_param.h>
105 #include <vm/vm_object.h>
106 #include <vm/vm_page.h>
107 #include <vm/vm_map.h>
108 #include <vm/vm_pageout.h>
109 #include <vm/vm_pager.h>
110 #include <vm/vm_phys.h>
111 #include <vm/swap_pager.h>
112 #include <vm/vm_extern.h>
115 /* the kernel process "vm_daemon" */
116 static void vm_daemon(void);
117 static struct proc *vmproc;
119 static struct kproc_desc vm_kp = {
124 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
126 static int vm_swap_enabled = 1;
127 static int vm_swap_idle_enabled = 0;
129 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled, CTLFLAG_RW,
131 "Enable entire process swapout");
132 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled, CTLFLAG_RW,
133 &vm_swap_idle_enabled, 0,
134 "Allow swapout on idle criteria");
137 * Swap_idle_threshold1 is the guaranteed swapped in time for a process
139 static int swap_idle_threshold1 = 2;
140 SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold1, CTLFLAG_RW,
141 &swap_idle_threshold1, 0,
142 "Guaranteed swapped in time for a process");
145 * Swap_idle_threshold2 is the time that a process can be idle before
146 * it will be swapped out, if idle swapping is enabled.
148 static int swap_idle_threshold2 = 10;
149 SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold2, CTLFLAG_RW,
150 &swap_idle_threshold2, 0,
151 "Time before a process will be swapped out");
153 static int vm_pageout_req_swapout; /* XXX */
154 static int vm_daemon_needed;
155 static struct mtx vm_daemon_mtx;
156 /* Allow for use by vm_pageout before vm_daemon is initialized. */
157 MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
159 static void swapclear(struct proc *);
160 static int swapout(struct proc *);
161 static void vm_swapout_map_deactivate_pages(vm_map_t, long);
162 static void vm_swapout_object_deactivate_pages(pmap_t, vm_object_t, long);
163 static void swapout_procs(int action);
164 static void vm_req_vmdaemon(int req);
165 static void vm_thread_swapin(struct thread *td);
166 static void vm_thread_swapout(struct thread *td);
169 * vm_swapout_object_deactivate_pages
171 * Deactivate enough pages to satisfy the inactive target
174 * The object and map must be locked.
177 vm_swapout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
180 vm_object_t backing_object, object;
182 int act_delta, remove_mode;
184 VM_OBJECT_ASSERT_LOCKED(first_object);
185 if ((first_object->flags & OBJ_FICTITIOUS) != 0)
187 for (object = first_object;; object = backing_object) {
188 if (pmap_resident_count(pmap) <= desired)
190 VM_OBJECT_ASSERT_LOCKED(object);
191 if ((object->flags & OBJ_UNMANAGED) != 0 ||
192 object->paging_in_progress != 0)
196 if (object->shadow_count > 1)
199 * Scan the object's entire memory queue.
201 TAILQ_FOREACH(p, &object->memq, listq) {
202 if (pmap_resident_count(pmap) <= desired)
206 if (vm_page_busied(p))
208 PCPU_INC(cnt.v_pdpages);
210 if (p->wire_count != 0 || p->hold_count != 0 ||
211 !pmap_page_exists_quick(pmap, p)) {
215 act_delta = pmap_ts_referenced(p);
216 if ((p->aflags & PGA_REFERENCED) != 0) {
219 vm_page_aflag_clear(p, PGA_REFERENCED);
221 if (!vm_page_active(p) && act_delta != 0) {
223 p->act_count += act_delta;
224 } else if (vm_page_active(p)) {
225 if (act_delta == 0) {
226 p->act_count -= min(p->act_count,
228 if (!remove_mode && p->act_count == 0) {
230 vm_page_deactivate(p);
235 if (p->act_count < ACT_MAX -
237 p->act_count += ACT_ADVANCE;
240 } else if (vm_page_inactive(p))
244 if ((backing_object = object->backing_object) == NULL)
246 VM_OBJECT_RLOCK(backing_object);
247 if (object != first_object)
248 VM_OBJECT_RUNLOCK(object);
251 if (object != first_object)
252 VM_OBJECT_RUNLOCK(object);
256 * deactivate some number of pages in a map, try to do it fairly, but
257 * that is really hard to do.
260 vm_swapout_map_deactivate_pages(vm_map_t map, long desired)
263 vm_object_t obj, bigobj;
266 if (!vm_map_trylock_read(map))
273 * first, search out the biggest object, and try to free pages from
276 tmpe = map->header.next;
277 while (tmpe != &map->header) {
278 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
279 obj = tmpe->object.vm_object;
280 if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
281 if (obj->shadow_count <= 1 &&
283 bigobj->resident_page_count <
284 obj->resident_page_count)) {
286 VM_OBJECT_RUNLOCK(bigobj);
289 VM_OBJECT_RUNLOCK(obj);
292 if (tmpe->wired_count > 0)
293 nothingwired = FALSE;
297 if (bigobj != NULL) {
298 vm_swapout_object_deactivate_pages(map->pmap, bigobj, desired);
299 VM_OBJECT_RUNLOCK(bigobj);
302 * Next, hunt around for other pages to deactivate. We actually
303 * do this search sort of wrong -- .text first is not the best idea.
305 tmpe = map->header.next;
306 while (tmpe != &map->header) {
307 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
309 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
310 obj = tmpe->object.vm_object;
312 VM_OBJECT_RLOCK(obj);
313 vm_swapout_object_deactivate_pages(map->pmap,
315 VM_OBJECT_RUNLOCK(obj);
322 * Remove all mappings if a process is swapped out, this will free page
325 if (desired == 0 && nothingwired) {
326 pmap_remove(vm_map_pmap(map), vm_map_min(map),
330 vm_map_unlock_read(map);
336 #define VM_SWAP_NORMAL 1
337 #define VM_SWAP_IDLE 2
344 vm_req_vmdaemon(VM_SWAP_NORMAL);
348 * Idle process swapout -- run once per second when pagedaemons are
352 vm_swapout_run_idle(void)
356 if (!vm_swap_idle_enabled || time_second == lsec)
358 vm_req_vmdaemon(VM_SWAP_IDLE);
363 vm_req_vmdaemon(int req)
365 static int lastrun = 0;
367 mtx_lock(&vm_daemon_mtx);
368 vm_pageout_req_swapout |= req;
369 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
370 wakeup(&vm_daemon_needed);
373 mtx_unlock(&vm_daemon_mtx);
379 struct rlimit rsslim;
383 int breakout, swapout_flags, tryagain, attempts;
385 uint64_t rsize, ravailable;
389 mtx_lock(&vm_daemon_mtx);
390 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
392 racct_enable ? hz : 0
397 swapout_flags = vm_pageout_req_swapout;
398 vm_pageout_req_swapout = 0;
399 mtx_unlock(&vm_daemon_mtx);
401 swapout_procs(swapout_flags);
404 * scan the processes for exceeding their rlimits or if
405 * process is swapped out -- deactivate pages
411 sx_slock(&allproc_lock);
412 FOREACH_PROC_IN_SYSTEM(p) {
413 vm_pindex_t limit, size;
416 * if this is a system process or if we have already
417 * looked at this process, skip it.
420 if (p->p_state != PRS_NORMAL ||
421 p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
426 * if the process is in a non-running type state,
430 FOREACH_THREAD_IN_PROC(p, td) {
432 if (!TD_ON_RUNQ(td) &&
433 !TD_IS_RUNNING(td) &&
434 !TD_IS_SLEEPING(td) &&
435 !TD_IS_SUSPENDED(td)) {
449 lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
451 qmin(rsslim.rlim_cur, rsslim.rlim_max));
454 * let processes that are swapped out really be
455 * swapped out set the limit to nothing (will force a
458 if ((p->p_flag & P_INMEM) == 0)
460 vm = vmspace_acquire_ref(p);
467 sx_sunlock(&allproc_lock);
469 size = vmspace_resident_count(vm);
471 vm_swapout_map_deactivate_pages(
473 size = vmspace_resident_count(vm);
477 rsize = IDX_TO_OFF(size);
479 if (p->p_state == PRS_NORMAL)
480 racct_set(p, RACCT_RSS, rsize);
481 ravailable = racct_get_available(p, RACCT_RSS);
483 if (rsize > ravailable) {
485 * Don't be overly aggressive; this
486 * might be an innocent process,
487 * and the limit could've been exceeded
488 * by some memory hog. Don't try
489 * to deactivate more than 1/4th
490 * of process' resident set size.
493 if (ravailable < rsize -
499 vm_swapout_map_deactivate_pages(
501 OFF_TO_IDX(ravailable));
502 /* Update RSS usage after paging out. */
503 size = vmspace_resident_count(vm);
504 rsize = IDX_TO_OFF(size);
506 if (p->p_state == PRS_NORMAL)
507 racct_set(p, RACCT_RSS, rsize);
509 if (rsize > ravailable)
515 sx_slock(&allproc_lock);
518 sx_sunlock(&allproc_lock);
519 if (tryagain != 0 && attempts <= 10) {
527 * Allow a thread's kernel stack to be paged out.
530 vm_thread_swapout(struct thread *td)
536 cpu_thread_swapout(td);
537 pages = td->td_kstack_pages;
538 ksobj = td->td_kstack_obj;
539 pmap_qremove(td->td_kstack, pages);
540 VM_OBJECT_WLOCK(ksobj);
541 for (i = 0; i < pages; i++) {
542 m = vm_page_lookup(ksobj, i);
544 panic("vm_thread_swapout: kstack already missing?");
547 vm_page_unwire(m, PQ_INACTIVE);
550 VM_OBJECT_WUNLOCK(ksobj);
554 * Bring the kernel stack for a specified thread back in.
557 vm_thread_swapin(struct thread *td)
560 vm_page_t ma[KSTACK_MAX_PAGES];
561 int a, count, i, j, pages, rv;
563 pages = td->td_kstack_pages;
564 ksobj = td->td_kstack_obj;
565 VM_OBJECT_WLOCK(ksobj);
566 (void)vm_page_grab_pages(ksobj, 0, VM_ALLOC_NORMAL | VM_ALLOC_WIRED, ma,
568 for (i = 0; i < pages;) {
569 vm_page_assert_xbusied(ma[i]);
570 if (ma[i]->valid == VM_PAGE_BITS_ALL) {
571 vm_page_xunbusy(ma[i]);
575 vm_object_pip_add(ksobj, 1);
576 for (j = i + 1; j < pages; j++)
577 if (ma[j]->valid == VM_PAGE_BITS_ALL)
579 rv = vm_pager_has_page(ksobj, ma[i]->pindex, NULL, &a);
580 KASSERT(rv == 1, ("%s: missing page %p", __func__, ma[i]));
581 count = min(a + 1, j - i);
582 rv = vm_pager_get_pages(ksobj, ma + i, count, NULL, NULL);
583 KASSERT(rv == VM_PAGER_OK, ("%s: cannot get kstack for proc %d",
584 __func__, td->td_proc->p_pid));
585 vm_object_pip_wakeup(ksobj);
586 for (j = i; j < i + count; j++)
587 vm_page_xunbusy(ma[j]);
590 VM_OBJECT_WUNLOCK(ksobj);
591 pmap_qenter(td->td_kstack, ma, pages);
592 cpu_thread_swapin(td);
596 faultin(struct proc *p)
600 PROC_LOCK_ASSERT(p, MA_OWNED);
602 * If another process is swapping in this process,
603 * just wait until it finishes.
605 if (p->p_flag & P_SWAPPINGIN) {
606 while (p->p_flag & P_SWAPPINGIN)
607 msleep(&p->p_flag, &p->p_mtx, PVM, "faultin", 0);
610 if ((p->p_flag & P_INMEM) == 0) {
612 * Don't let another thread swap process p out while we are
613 * busy swapping it in.
616 p->p_flag |= P_SWAPPINGIN;
620 * We hold no lock here because the list of threads
621 * can not change while all threads in the process are
624 FOREACH_THREAD_IN_PROC(p, td)
625 vm_thread_swapin(td);
632 /* Allow other threads to swap p out now. */
638 * This swapin algorithm attempts to swap-in processes only if there
639 * is enough space for them. Of course, if a process waits for a long
640 * time, it will be swapped in anyway.
647 int ppri, pri, slptime, swtime;
650 if (vm_page_count_min()) {
657 sx_slock(&allproc_lock);
658 FOREACH_PROC_IN_SYSTEM(p) {
660 if (p->p_state == PRS_NEW ||
661 p->p_flag & (P_SWAPPINGOUT | P_SWAPPINGIN | P_INMEM)) {
665 swtime = (ticks - p->p_swtick) / hz;
666 FOREACH_THREAD_IN_PROC(p, td) {
668 * An otherwise runnable thread of a process
669 * swapped out has only the TDI_SWAPPED bit set.
672 if (td->td_inhibitors == TDI_SWAPPED) {
673 slptime = (ticks - td->td_slptick) / hz;
674 pri = swtime + slptime;
675 if ((td->td_flags & TDF_SWAPINREQ) == 0)
676 pri -= p->p_nice * 8;
678 * if this thread is higher priority
679 * and there is enough space, then select
680 * this process instead of the previous
692 sx_sunlock(&allproc_lock);
695 * Nothing to do, back to sleep.
697 if ((p = pp) == NULL) {
698 tsleep(&proc0, PVM, "swapin", MAXSLP * hz / 2);
704 * Another process may be bringing or may have already
705 * brought this process in while we traverse all threads.
706 * Or, this process may even be being swapped out again.
708 if (p->p_flag & (P_INMEM | P_SWAPPINGOUT | P_SWAPPINGIN)) {
714 * We would like to bring someone in.
722 * First, if any processes have been sleeping or stopped for at least
723 * "swap_idle_threshold1" seconds, they are swapped out. If, however,
724 * no such processes exist, then the longest-sleeping or stopped
725 * process is swapped out. Finally, and only as a last resort, if
726 * there are no sleeping or stopped processes, the longest-resident
727 * process is swapped out.
730 swapout_procs(int action)
734 int minslptime, slptime;
740 sx_slock(&allproc_lock);
741 FOREACH_PROC_IN_SYSTEM(p) {
744 * Watch out for a process in
745 * creation. It may have no
746 * address space or lock yet.
748 if (p->p_state == PRS_NEW) {
753 * An aio daemon switches its
754 * address space while running.
755 * Perform a quick check whether
756 * a process has P_SYSTEM.
757 * Filter out exiting processes.
759 if ((p->p_flag & (P_SYSTEM | P_WEXIT)) != 0) {
765 sx_sunlock(&allproc_lock);
768 if (p->p_lock != 1 || (p->p_flag & (P_STOPPED_SINGLE |
769 P_TRACED | P_SYSTEM)) != 0)
773 * Only aiod changes vmspace. However, it will be
774 * skipped because of the if statement above checking
777 if ((p->p_flag & (P_INMEM | P_SWAPPINGOUT | P_SWAPPINGIN)) !=
781 switch (p->p_state) {
784 * Don't swap out processes in any sort
785 * of 'special' state.
791 * do not swapout a realtime process
792 * Check all the thread groups..
794 FOREACH_THREAD_IN_PROC(p, td) {
796 if (PRI_IS_REALTIME(td->td_pri_class)) {
800 slptime = (ticks - td->td_slptick) / hz;
802 * Guarantee swap_idle_threshold1
805 if (slptime < swap_idle_threshold1) {
811 * Do not swapout a process if it is
812 * waiting on a critical event of some
813 * kind or there is a thread whose
814 * pageable memory may be accessed.
816 * This could be refined to support
817 * swapping out a thread.
819 if (!thread_safetoswapout(td)) {
824 * If the system is under memory stress,
825 * or if we are swapping
826 * idle processes >= swap_idle_threshold2,
827 * then swap the process out.
829 if ((action & VM_SWAP_NORMAL) == 0 &&
830 ((action & VM_SWAP_IDLE) == 0 ||
831 slptime < swap_idle_threshold2)) {
836 if (minslptime > slptime)
837 minslptime = slptime;
842 * If the pageout daemon didn't free enough pages,
843 * or if this process is idle and the system is
844 * configured to swap proactively, swap it out.
846 if ((action & VM_SWAP_NORMAL) != 0 ||
847 ((action & VM_SWAP_IDLE) != 0 &&
848 minslptime > swap_idle_threshold2)) {
858 sx_slock(&allproc_lock);
861 sx_sunlock(&allproc_lock);
863 * If we swapped something out, and another process needed memory,
864 * then wakeup the sched process.
871 swapclear(struct proc *p)
875 PROC_LOCK_ASSERT(p, MA_OWNED);
877 FOREACH_THREAD_IN_PROC(p, td) {
879 td->td_flags |= TDF_INMEM;
880 td->td_flags &= ~TDF_SWAPINREQ;
883 if (setrunnable(td)) {
886 * XXX: We just cleared TDI_SWAPPED
887 * above and set TDF_INMEM, so this
888 * should never happen.
890 panic("not waking up swapper");
895 p->p_flag &= ~(P_SWAPPINGIN | P_SWAPPINGOUT);
896 p->p_flag |= P_INMEM;
900 swapout(struct proc *p)
904 PROC_LOCK_ASSERT(p, MA_OWNED);
907 * The states of this process and its threads may have changed
908 * by now. Assuming that there is only one pageout daemon thread,
909 * this process should still be in memory.
911 KASSERT((p->p_flag & (P_INMEM | P_SWAPPINGOUT | P_SWAPPINGIN)) ==
912 P_INMEM, ("swapout: lost a swapout race?"));
915 * Remember the resident count.
917 p->p_vmspace->vm_swrss = vmspace_resident_count(p->p_vmspace);
920 * Check and mark all threads before we proceed.
922 p->p_flag &= ~P_INMEM;
923 p->p_flag |= P_SWAPPINGOUT;
924 FOREACH_THREAD_IN_PROC(p, td) {
926 if (!thread_safetoswapout(td)) {
931 td->td_flags &= ~TDF_INMEM;
935 td = FIRST_THREAD_IN_PROC(p);
936 ++td->td_ru.ru_nswap;
940 * This list is stable because all threads are now prevented from
941 * running. The list is only modified in the context of a running
942 * thread in this process.
944 FOREACH_THREAD_IN_PROC(p, td)
945 vm_thread_swapout(td);
948 p->p_flag &= ~P_SWAPPINGOUT;