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)
204 if (vm_page_busied(p))
206 VM_CNT_INC(v_pdpages);
208 if (p->wire_count != 0 || p->hold_count != 0 ||
209 !pmap_page_exists_quick(pmap, p)) {
213 act_delta = pmap_ts_referenced(p);
214 if ((p->aflags & PGA_REFERENCED) != 0) {
217 vm_page_aflag_clear(p, PGA_REFERENCED);
219 if (!vm_page_active(p) && act_delta != 0) {
221 p->act_count += act_delta;
222 } else if (vm_page_active(p)) {
223 if (act_delta == 0) {
224 p->act_count -= min(p->act_count,
226 if (!remove_mode && p->act_count == 0) {
228 vm_page_deactivate(p);
233 if (p->act_count < ACT_MAX -
235 p->act_count += ACT_ADVANCE;
238 } else if (vm_page_inactive(p))
242 if ((backing_object = object->backing_object) == NULL)
244 VM_OBJECT_RLOCK(backing_object);
245 if (object != first_object)
246 VM_OBJECT_RUNLOCK(object);
249 if (object != first_object)
250 VM_OBJECT_RUNLOCK(object);
254 * deactivate some number of pages in a map, try to do it fairly, but
255 * that is really hard to do.
258 vm_swapout_map_deactivate_pages(vm_map_t map, long desired)
261 vm_object_t obj, bigobj;
264 if (!vm_map_trylock(map))
271 * first, search out the biggest object, and try to free pages from
274 tmpe = map->header.next;
275 while (tmpe != &map->header) {
276 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
277 obj = tmpe->object.vm_object;
278 if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
279 if (obj->shadow_count <= 1 &&
281 bigobj->resident_page_count <
282 obj->resident_page_count)) {
284 VM_OBJECT_RUNLOCK(bigobj);
287 VM_OBJECT_RUNLOCK(obj);
290 if (tmpe->wired_count > 0)
291 nothingwired = FALSE;
295 if (bigobj != NULL) {
296 vm_swapout_object_deactivate_pages(map->pmap, bigobj, desired);
297 VM_OBJECT_RUNLOCK(bigobj);
300 * Next, hunt around for other pages to deactivate. We actually
301 * do this search sort of wrong -- .text first is not the best idea.
303 tmpe = map->header.next;
304 while (tmpe != &map->header) {
305 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
307 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
308 obj = tmpe->object.vm_object;
310 VM_OBJECT_RLOCK(obj);
311 vm_swapout_object_deactivate_pages(map->pmap,
313 VM_OBJECT_RUNLOCK(obj);
320 * Remove all mappings if a process is swapped out, this will free page
323 if (desired == 0 && nothingwired) {
324 pmap_remove(vm_map_pmap(map), vm_map_min(map),
334 #define VM_SWAP_NORMAL 1
335 #define VM_SWAP_IDLE 2
342 vm_req_vmdaemon(VM_SWAP_NORMAL);
346 * Idle process swapout -- run once per second when pagedaemons are
350 vm_swapout_run_idle(void)
354 if (!vm_swap_idle_enabled || time_second == lsec)
356 vm_req_vmdaemon(VM_SWAP_IDLE);
361 vm_req_vmdaemon(int req)
363 static int lastrun = 0;
365 mtx_lock(&vm_daemon_mtx);
366 vm_pageout_req_swapout |= req;
367 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
368 wakeup(&vm_daemon_needed);
371 mtx_unlock(&vm_daemon_mtx);
377 struct rlimit rsslim;
381 int breakout, swapout_flags, tryagain, attempts;
383 uint64_t rsize, ravailable;
387 mtx_lock(&vm_daemon_mtx);
388 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
390 racct_enable ? hz : 0
395 swapout_flags = vm_pageout_req_swapout;
396 vm_pageout_req_swapout = 0;
397 mtx_unlock(&vm_daemon_mtx);
399 swapout_procs(swapout_flags);
402 * scan the processes for exceeding their rlimits or if
403 * process is swapped out -- deactivate pages
409 sx_slock(&allproc_lock);
410 FOREACH_PROC_IN_SYSTEM(p) {
411 vm_pindex_t limit, size;
414 * if this is a system process or if we have already
415 * looked at this process, skip it.
418 if (p->p_state != PRS_NORMAL ||
419 p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
424 * if the process is in a non-running type state,
428 FOREACH_THREAD_IN_PROC(p, td) {
430 if (!TD_ON_RUNQ(td) &&
431 !TD_IS_RUNNING(td) &&
432 !TD_IS_SLEEPING(td) &&
433 !TD_IS_SUSPENDED(td)) {
447 lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
449 qmin(rsslim.rlim_cur, rsslim.rlim_max));
452 * let processes that are swapped out really be
453 * swapped out set the limit to nothing (will force a
456 if ((p->p_flag & P_INMEM) == 0)
458 vm = vmspace_acquire_ref(p);
465 sx_sunlock(&allproc_lock);
467 size = vmspace_resident_count(vm);
469 vm_swapout_map_deactivate_pages(
471 size = vmspace_resident_count(vm);
475 rsize = IDX_TO_OFF(size);
477 if (p->p_state == PRS_NORMAL)
478 racct_set(p, RACCT_RSS, rsize);
479 ravailable = racct_get_available(p, RACCT_RSS);
481 if (rsize > ravailable) {
483 * Don't be overly aggressive; this
484 * might be an innocent process,
485 * and the limit could've been exceeded
486 * by some memory hog. Don't try
487 * to deactivate more than 1/4th
488 * of process' resident set size.
491 if (ravailable < rsize -
497 vm_swapout_map_deactivate_pages(
499 OFF_TO_IDX(ravailable));
500 /* Update RSS usage after paging out. */
501 size = vmspace_resident_count(vm);
502 rsize = IDX_TO_OFF(size);
504 if (p->p_state == PRS_NORMAL)
505 racct_set(p, RACCT_RSS, rsize);
507 if (rsize > ravailable)
513 sx_slock(&allproc_lock);
516 sx_sunlock(&allproc_lock);
517 if (tryagain != 0 && attempts <= 10)
523 * Allow a thread's kernel stack to be paged out.
526 vm_thread_swapout(struct thread *td)
532 cpu_thread_swapout(td);
533 pages = td->td_kstack_pages;
534 ksobj = td->td_kstack_obj;
535 pmap_qremove(td->td_kstack, pages);
536 VM_OBJECT_WLOCK(ksobj);
537 for (i = 0; i < pages; i++) {
538 m = vm_page_lookup(ksobj, i);
540 panic("vm_thread_swapout: kstack already missing?");
543 vm_page_unwire(m, PQ_INACTIVE);
546 VM_OBJECT_WUNLOCK(ksobj);
550 * Bring the kernel stack for a specified thread back in.
553 vm_thread_swapin(struct thread *td)
556 vm_page_t ma[KSTACK_MAX_PAGES];
559 pages = td->td_kstack_pages;
560 ksobj = td->td_kstack_obj;
561 VM_OBJECT_WLOCK(ksobj);
562 (void)vm_page_grab_pages(ksobj, 0, VM_ALLOC_NORMAL | VM_ALLOC_WIRED, ma,
564 for (int i = 0; i < pages;) {
567 vm_page_assert_xbusied(ma[i]);
568 if (ma[i]->valid == VM_PAGE_BITS_ALL) {
569 vm_page_xunbusy(ma[i]);
573 vm_object_pip_add(ksobj, 1);
574 for (j = i + 1; j < pages; j++)
575 if (ma[j]->valid == VM_PAGE_BITS_ALL)
577 rv = vm_pager_has_page(ksobj, ma[i]->pindex, NULL, &a);
578 KASSERT(rv == 1, ("%s: missing page %p", __func__, ma[i]));
579 count = min(a + 1, j - i);
580 rv = vm_pager_get_pages(ksobj, ma + i, count, NULL, NULL);
581 KASSERT(rv == VM_PAGER_OK, ("%s: cannot get kstack for proc %d",
582 __func__, td->td_proc->p_pid));
583 vm_object_pip_wakeup(ksobj);
584 for (j = i; j < i + count; j++)
585 vm_page_xunbusy(ma[j]);
588 VM_OBJECT_WUNLOCK(ksobj);
589 pmap_qenter(td->td_kstack, ma, pages);
590 cpu_thread_swapin(td);
594 faultin(struct proc *p)
598 PROC_LOCK_ASSERT(p, MA_OWNED);
600 * If another process is swapping in this process,
601 * just wait until it finishes.
603 if (p->p_flag & P_SWAPPINGIN) {
604 while (p->p_flag & P_SWAPPINGIN)
605 msleep(&p->p_flag, &p->p_mtx, PVM, "faultin", 0);
608 if ((p->p_flag & P_INMEM) == 0) {
610 * Don't let another thread swap process p out while we are
611 * busy swapping it in.
614 p->p_flag |= P_SWAPPINGIN;
618 * We hold no lock here because the list of threads
619 * can not change while all threads in the process are
622 FOREACH_THREAD_IN_PROC(p, td)
623 vm_thread_swapin(td);
630 /* Allow other threads to swap p out now. */
636 * This swapin algorithm attempts to swap-in processes only if there
637 * is enough space for them. Of course, if a process waits for a long
638 * time, it will be swapped in anyway.
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. (only if there is space).
717 * [What checks the space? ]
725 * First, if any processes have been sleeping or stopped for at least
726 * "swap_idle_threshold1" seconds, they are swapped out. If, however,
727 * no such processes exist, then the longest-sleeping or stopped
728 * process is swapped out. Finally, and only as a last resort, if
729 * there are no sleeping or stopped processes, the longest-resident
730 * process is swapped out.
733 swapout_procs(int action)
740 sx_slock(&allproc_lock);
741 FOREACH_PROC_IN_SYSTEM(p) {
743 int minslptime = 100000;
748 * Watch out for a process in
749 * creation. It may have no
750 * address space or lock yet.
752 if (p->p_state == PRS_NEW) {
757 * An aio daemon switches its
758 * address space while running.
759 * Perform a quick check whether
760 * a process has P_SYSTEM.
761 * Filter out exiting processes.
763 if ((p->p_flag & (P_SYSTEM | P_WEXIT)) != 0) {
769 sx_sunlock(&allproc_lock);
772 * Do not swapout a process that
773 * is waiting for VM data
774 * structures as there is a possible
775 * deadlock. Test this first as
778 * Lock the map until swapout
779 * finishes, or a thread of this
780 * process may attempt to alter
783 vm = vmspace_acquire_ref(p);
786 if (!vm_map_trylock(&vm->vm_map))
790 if (p->p_lock != 1 || (p->p_flag & (P_STOPPED_SINGLE |
791 P_TRACED | P_SYSTEM)) != 0)
795 * only aiod changes vmspace, however it will be
796 * skipped because of the if statement above checking
799 if ((p->p_flag & (P_INMEM|P_SWAPPINGOUT|P_SWAPPINGIN)) != P_INMEM)
802 switch (p->p_state) {
804 /* Don't swap out processes in any sort
805 * of 'special' state. */
810 * do not swapout a realtime process
811 * Check all the thread groups..
813 FOREACH_THREAD_IN_PROC(p, td) {
815 if (PRI_IS_REALTIME(td->td_pri_class)) {
819 slptime = (ticks - td->td_slptick) / hz;
821 * Guarantee swap_idle_threshold1
824 if (slptime < swap_idle_threshold1) {
830 * Do not swapout a process if it is
831 * waiting on a critical event of some
832 * kind or there is a thread whose
833 * pageable memory may be accessed.
835 * This could be refined to support
836 * swapping out a thread.
838 if (!thread_safetoswapout(td)) {
843 * If the system is under memory stress,
844 * or if we are swapping
845 * idle processes >= swap_idle_threshold2,
846 * then swap the process out.
848 if (((action & VM_SWAP_NORMAL) == 0) &&
849 (((action & VM_SWAP_IDLE) == 0) ||
850 (slptime < swap_idle_threshold2))) {
855 if (minslptime > slptime)
856 minslptime = slptime;
861 * If the pageout daemon didn't free enough pages,
862 * or if this process is idle and the system is
863 * configured to swap proactively, swap it out.
865 if ((action & VM_SWAP_NORMAL) ||
866 ((action & VM_SWAP_IDLE) &&
867 (minslptime > swap_idle_threshold2))) {
872 vm_map_unlock(&vm->vm_map);
879 vm_map_unlock(&vm->vm_map);
883 sx_slock(&allproc_lock);
886 sx_sunlock(&allproc_lock);
888 * If we swapped something out, and another process needed memory,
889 * then wakeup the sched process.
896 swapclear(struct proc *p)
900 PROC_LOCK_ASSERT(p, MA_OWNED);
902 FOREACH_THREAD_IN_PROC(p, td) {
904 td->td_flags |= TDF_INMEM;
905 td->td_flags &= ~TDF_SWAPINREQ;
908 if (setrunnable(td)) {
911 * XXX: We just cleared TDI_SWAPPED
912 * above and set TDF_INMEM, so this
913 * should never happen.
915 panic("not waking up swapper");
920 p->p_flag &= ~(P_SWAPPINGIN | P_SWAPPINGOUT);
921 p->p_flag |= P_INMEM;
925 swapout(struct proc *p)
929 PROC_LOCK_ASSERT(p, MA_OWNED);
932 * The states of this process and its threads may have changed
933 * by now. Assuming that there is only one pageout daemon thread,
934 * this process should still be in memory.
936 KASSERT((p->p_flag & (P_INMEM | P_SWAPPINGOUT | P_SWAPPINGIN)) ==
937 P_INMEM, ("swapout: lost a swapout race?"));
940 * remember the process resident count
942 p->p_vmspace->vm_swrss = vmspace_resident_count(p->p_vmspace);
944 * Check and mark all threads before we proceed.
946 p->p_flag &= ~P_INMEM;
947 p->p_flag |= P_SWAPPINGOUT;
948 FOREACH_THREAD_IN_PROC(p, td) {
950 if (!thread_safetoswapout(td)) {
955 td->td_flags &= ~TDF_INMEM;
959 td = FIRST_THREAD_IN_PROC(p);
960 ++td->td_ru.ru_nswap;
964 * This list is stable because all threads are now prevented from
965 * running. The list is only modified in the context of a running
966 * thread in this process.
968 FOREACH_THREAD_IN_PROC(p, td)
969 vm_thread_swapout(td);
972 p->p_flag &= ~P_SWAPPINGOUT;