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.
72 * The proverbial page-out daemon.
75 #include <sys/cdefs.h>
76 __FBSDID("$FreeBSD$");
79 #include "opt_kdtrace.h"
80 #include <sys/param.h>
81 #include <sys/systm.h>
82 #include <sys/kernel.h>
83 #include <sys/eventhandler.h>
85 #include <sys/mutex.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>
116 * System initialization
119 /* the kernel process "vm_pageout"*/
120 static void vm_pageout(void);
121 static void vm_pageout_init(void);
122 static int vm_pageout_clean(vm_page_t);
123 static void vm_pageout_scan(struct vm_domain *vmd, int pass);
124 static void vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
125 int starting_page_shortage);
127 SYSINIT(pagedaemon_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, vm_pageout_init,
130 struct proc *pageproc;
132 static struct kproc_desc page_kp = {
137 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_SECOND, kproc_start,
140 SDT_PROVIDER_DEFINE(vm);
141 SDT_PROBE_DEFINE(vm, , , vm__lowmem_cache);
142 SDT_PROBE_DEFINE(vm, , , vm__lowmem_scan);
144 #if !defined(NO_SWAPPING)
145 /* the kernel process "vm_daemon"*/
146 static void vm_daemon(void);
147 static struct proc *vmproc;
149 static struct kproc_desc vm_kp = {
154 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
158 int vm_pages_needed; /* Event on which pageout daemon sleeps */
159 int vm_pageout_deficit; /* Estimated number of pages deficit */
160 int vm_pageout_pages_needed; /* flag saying that the pageout daemon needs pages */
161 int vm_pageout_wakeup_thresh;
162 static int vm_pageout_oom_seq = 12;
164 #if !defined(NO_SWAPPING)
165 static int vm_pageout_req_swapout; /* XXX */
166 static int vm_daemon_needed;
167 static struct mtx vm_daemon_mtx;
168 /* Allow for use by vm_pageout before vm_daemon is initialized. */
169 MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
171 static int vm_max_launder = 32;
172 static int vm_pageout_update_period;
173 static int defer_swap_pageouts;
174 static int disable_swap_pageouts;
175 static int lowmem_period = 10;
176 static time_t lowmem_uptime;
178 #if defined(NO_SWAPPING)
179 static int vm_swap_enabled = 0;
180 static int vm_swap_idle_enabled = 0;
182 static int vm_swap_enabled = 1;
183 static int vm_swap_idle_enabled = 0;
186 SYSCTL_INT(_vm, OID_AUTO, pageout_wakeup_thresh,
187 CTLFLAG_RW, &vm_pageout_wakeup_thresh, 0,
188 "free page threshold for waking up the pageout daemon");
190 SYSCTL_INT(_vm, OID_AUTO, max_launder,
191 CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
193 SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
194 CTLFLAG_RW, &vm_pageout_update_period, 0,
195 "Maximum active LRU update period");
197 SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RW, &lowmem_period, 0,
198 "Low memory callback period");
200 #if defined(NO_SWAPPING)
201 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
202 CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout");
203 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
204 CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
206 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
207 CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
208 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
209 CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
212 SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
213 CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
215 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
216 CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
218 static int pageout_lock_miss;
219 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
220 CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
222 SYSCTL_INT(_vm, OID_AUTO, pageout_oom_seq,
223 CTLFLAG_RW, &vm_pageout_oom_seq, 0,
224 "back-to-back calls to oom detector to start OOM");
226 #define VM_PAGEOUT_PAGE_COUNT 16
227 int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
229 int vm_page_max_wired; /* XXX max # of wired pages system-wide */
230 SYSCTL_INT(_vm, OID_AUTO, max_wired,
231 CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
233 static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
234 static boolean_t vm_pageout_launder(struct vm_pagequeue *pq, int, vm_paddr_t,
236 #if !defined(NO_SWAPPING)
237 static void vm_pageout_map_deactivate_pages(vm_map_t, long);
238 static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
239 static void vm_req_vmdaemon(int req);
241 static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
244 * Initialize a dummy page for marking the caller's place in the specified
245 * paging queue. In principle, this function only needs to set the flag
246 * PG_MARKER. Nonetheless, it write busies and initializes the hold count
247 * to one as safety precautions.
250 vm_pageout_init_marker(vm_page_t marker, u_short queue)
253 bzero(marker, sizeof(*marker));
254 marker->flags = PG_MARKER;
255 marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
256 marker->queue = queue;
257 marker->hold_count = 1;
261 * vm_pageout_fallback_object_lock:
263 * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
264 * known to have failed and page queue must be either PQ_ACTIVE or
265 * PQ_INACTIVE. To avoid lock order violation, unlock the page queue
266 * while locking the vm object. Use marker page to detect page queue
267 * changes and maintain notion of next page on page queue. Return
268 * TRUE if no changes were detected, FALSE otherwise. vm object is
271 * This function depends on both the lock portion of struct vm_object
272 * and normal struct vm_page being type stable.
275 vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
277 struct vm_page marker;
278 struct vm_pagequeue *pq;
284 vm_pageout_init_marker(&marker, queue);
285 pq = vm_page_pagequeue(m);
288 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
289 vm_pagequeue_unlock(pq);
291 VM_OBJECT_WLOCK(object);
293 vm_pagequeue_lock(pq);
296 * The page's object might have changed, and/or the page might
297 * have moved from its original position in the queue. If the
298 * page's object has changed, then the caller should abandon
299 * processing the page because the wrong object lock was
300 * acquired. Use the marker's plinks.q, not the page's, to
301 * determine if the page has been moved. The state of the
302 * page's plinks.q can be indeterminate; whereas, the marker's
303 * plinks.q must be valid.
305 *next = TAILQ_NEXT(&marker, plinks.q);
306 unchanged = m->object == object &&
307 m == TAILQ_PREV(&marker, pglist, plinks.q);
308 KASSERT(!unchanged || m->queue == queue,
309 ("page %p queue %d %d", m, queue, m->queue));
310 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
315 * Lock the page while holding the page queue lock. Use marker page
316 * to detect page queue changes and maintain notion of next page on
317 * page queue. Return TRUE if no changes were detected, FALSE
318 * otherwise. The page is locked on return. The page queue lock might
319 * be dropped and reacquired.
321 * This function depends on normal struct vm_page being type stable.
324 vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
326 struct vm_page marker;
327 struct vm_pagequeue *pq;
331 vm_page_lock_assert(m, MA_NOTOWNED);
332 if (vm_page_trylock(m))
336 vm_pageout_init_marker(&marker, queue);
337 pq = vm_page_pagequeue(m);
339 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
340 vm_pagequeue_unlock(pq);
342 vm_pagequeue_lock(pq);
344 /* Page queue might have changed. */
345 *next = TAILQ_NEXT(&marker, plinks.q);
346 unchanged = m == TAILQ_PREV(&marker, pglist, plinks.q);
347 KASSERT(!unchanged || m->queue == queue,
348 ("page %p queue %d %d", m, queue, m->queue));
349 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
356 * Clean the page and remove it from the laundry.
358 * We set the busy bit to cause potential page faults on this page to
359 * block. Note the careful timing, however, the busy bit isn't set till
360 * late and we cannot do anything that will mess with the page.
363 vm_pageout_clean(vm_page_t m)
366 vm_page_t mc[2*vm_pageout_page_count], pb, ps;
368 int ib, is, page_base;
369 vm_pindex_t pindex = m->pindex;
371 vm_page_lock_assert(m, MA_OWNED);
373 VM_OBJECT_ASSERT_WLOCKED(object);
376 * It doesn't cost us anything to pageout OBJT_DEFAULT or OBJT_SWAP
377 * with the new swapper, but we could have serious problems paging
378 * out other object types if there is insufficient memory.
380 * Unfortunately, checking free memory here is far too late, so the
381 * check has been moved up a procedural level.
385 * Can't clean the page if it's busy or held.
387 vm_page_assert_unbusied(m);
388 KASSERT(m->hold_count == 0, ("vm_pageout_clean: page %p is held", m));
391 mc[vm_pageout_page_count] = pb = ps = m;
393 page_base = vm_pageout_page_count;
398 * Scan object for clusterable pages.
400 * We can cluster ONLY if: ->> the page is NOT
401 * clean, wired, busy, held, or mapped into a
402 * buffer, and one of the following:
403 * 1) The page is inactive, or a seldom used
406 * 2) we force the issue.
408 * During heavy mmap/modification loads the pageout
409 * daemon can really fragment the underlying file
410 * due to flushing pages out of order and not trying
411 * align the clusters (which leave sporatic out-of-order
412 * holes). To solve this problem we do the reverse scan
413 * first and attempt to align our cluster, then do a
414 * forward scan if room remains.
417 while (ib && pageout_count < vm_pageout_page_count) {
425 if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
429 vm_page_test_dirty(p);
435 if (p->queue != PQ_INACTIVE ||
436 p->hold_count != 0) { /* may be undergoing I/O */
442 mc[--page_base] = pb = p;
446 * alignment boundry, stop here and switch directions. Do
449 if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
453 while (pageout_count < vm_pageout_page_count &&
454 pindex + is < object->size) {
457 if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
459 vm_page_test_dirty(p);
463 if (p->queue != PQ_INACTIVE ||
464 p->hold_count != 0) { /* may be undergoing I/O */
469 mc[page_base + pageout_count] = ps = p;
475 * If we exhausted our forward scan, continue with the reverse scan
476 * when possible, even past a page boundry. This catches boundry
479 if (ib && pageout_count < vm_pageout_page_count)
483 * we allow reads during pageouts...
485 return (vm_pageout_flush(&mc[page_base], pageout_count, 0, 0, NULL,
490 * vm_pageout_flush() - launder the given pages
492 * The given pages are laundered. Note that we setup for the start of
493 * I/O ( i.e. busy the page ), mark it read-only, and bump the object
494 * reference count all in here rather then in the parent. If we want
495 * the parent to do more sophisticated things we may have to change
498 * Returned runlen is the count of pages between mreq and first
499 * page after mreq with status VM_PAGER_AGAIN.
500 * *eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
501 * for any page in runlen set.
504 vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
507 vm_object_t object = mc[0]->object;
508 int pageout_status[count];
512 VM_OBJECT_ASSERT_WLOCKED(object);
515 * Initiate I/O. Bump the vm_page_t->busy counter and
516 * mark the pages read-only.
518 * We do not have to fixup the clean/dirty bits here... we can
519 * allow the pager to do it after the I/O completes.
521 * NOTE! mc[i]->dirty may be partial or fragmented due to an
522 * edge case with file fragments.
524 for (i = 0; i < count; i++) {
525 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
526 ("vm_pageout_flush: partially invalid page %p index %d/%d",
528 vm_page_sbusy(mc[i]);
529 pmap_remove_write(mc[i]);
531 vm_object_pip_add(object, count);
533 vm_pager_put_pages(object, mc, count, flags, pageout_status);
535 runlen = count - mreq;
538 for (i = 0; i < count; i++) {
539 vm_page_t mt = mc[i];
541 KASSERT(pageout_status[i] == VM_PAGER_PEND ||
542 !pmap_page_is_write_mapped(mt),
543 ("vm_pageout_flush: page %p is not write protected", mt));
544 switch (pageout_status[i]) {
551 * Page outside of range of object. Right now we
552 * essentially lose the changes by pretending it
560 * If page couldn't be paged out, then reactivate the
561 * page so it doesn't clog the inactive list. (We
562 * will try paging out it again later).
565 vm_page_activate(mt);
567 if (eio != NULL && i >= mreq && i - mreq < runlen)
571 if (i >= mreq && i - mreq < runlen)
577 * If the operation is still going, leave the page busy to
578 * block all other accesses. Also, leave the paging in
579 * progress indicator set so that we don't attempt an object
582 if (pageout_status[i] != VM_PAGER_PEND) {
583 vm_object_pip_wakeup(object);
585 if (vm_page_count_severe()) {
587 vm_page_try_to_cache(mt);
594 return (numpagedout);
598 vm_pageout_launder(struct vm_pagequeue *pq, int tries, vm_paddr_t low,
605 vm_page_t m, m_tmp, next;
608 vm_pagequeue_lock(pq);
609 TAILQ_FOREACH_SAFE(m, &pq->pq_pl, plinks.q, next) {
610 if ((m->flags & PG_MARKER) != 0)
612 pa = VM_PAGE_TO_PHYS(m);
613 if (pa < low || pa + PAGE_SIZE > high)
615 if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
620 if ((!VM_OBJECT_TRYWLOCK(object) &&
621 (!vm_pageout_fallback_object_lock(m, &next) ||
622 m->hold_count != 0)) || vm_page_busied(m)) {
624 VM_OBJECT_WUNLOCK(object);
627 vm_page_test_dirty(m);
628 if (m->dirty == 0 && object->ref_count != 0)
632 if (tries == 0 || (object->flags & OBJ_DEAD) != 0) {
633 VM_OBJECT_WUNLOCK(object);
636 if (object->type == OBJT_VNODE) {
637 vm_pagequeue_unlock(pq);
639 vm_object_reference_locked(object);
640 VM_OBJECT_WUNLOCK(object);
641 (void)vn_start_write(vp, &mp, V_WAIT);
642 lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
643 LK_SHARED : LK_EXCLUSIVE;
644 vn_lock(vp, lockmode | LK_RETRY);
645 VM_OBJECT_WLOCK(object);
646 vm_object_page_clean(object, 0, 0, OBJPC_SYNC);
647 VM_OBJECT_WUNLOCK(object);
649 vm_object_deallocate(object);
650 vn_finished_write(mp);
652 } else if (object->type == OBJT_SWAP ||
653 object->type == OBJT_DEFAULT) {
654 vm_pagequeue_unlock(pq);
656 vm_pageout_flush(&m_tmp, 1, VM_PAGER_PUT_SYNC,
658 VM_OBJECT_WUNLOCK(object);
663 * Dequeue here to prevent lock recursion in
666 vm_page_dequeue_locked(m);
670 VM_OBJECT_WUNLOCK(object);
672 vm_pagequeue_unlock(pq);
677 * Increase the number of cached pages. The specified value, "tries",
678 * determines which categories of pages are cached:
680 * 0: All clean, inactive pages within the specified physical address range
681 * are cached. Will not sleep.
682 * 1: The vm_lowmem handlers are called. All inactive pages within
683 * the specified physical address range are cached. May sleep.
684 * 2: The vm_lowmem handlers are called. All inactive and active pages
685 * within the specified physical address range are cached. May sleep.
688 vm_pageout_grow_cache(int tries, vm_paddr_t low, vm_paddr_t high)
690 int actl, actmax, inactl, inactmax, dom, initial_dom;
691 static int start_dom = 0;
695 * Decrease registered cache sizes. The vm_lowmem handlers
696 * may acquire locks and/or sleep, so they can only be invoked
697 * when "tries" is greater than zero.
699 SDT_PROBE0(vm, , , vm__lowmem_cache);
700 EVENTHANDLER_INVOKE(vm_lowmem, 0);
703 * We do this explicitly after the caches have been drained
710 * Make the next scan start on the next domain.
712 initial_dom = atomic_fetchadd_int(&start_dom, 1) % vm_ndomains;
715 inactmax = cnt.v_inactive_count;
717 actmax = tries < 2 ? 0 : cnt.v_active_count;
721 * Scan domains in round-robin order, first inactive queues,
722 * then active. Since domain usually owns large physically
723 * contiguous chunk of memory, it makes sense to completely
724 * exhaust one domain before switching to next, while growing
725 * the pool of contiguous physical pages.
727 * Do not even start launder a domain which cannot contain
728 * the specified address range, as indicated by segments
729 * constituting the domain.
732 if (inactl < inactmax) {
733 if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
735 vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_INACTIVE],
740 if (++dom == vm_ndomains)
742 if (dom != initial_dom)
747 if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
749 vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_ACTIVE],
754 if (++dom == vm_ndomains)
756 if (dom != initial_dom)
761 #if !defined(NO_SWAPPING)
763 * vm_pageout_object_deactivate_pages
765 * Deactivate enough pages to satisfy the inactive target
768 * The object and map must be locked.
771 vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
774 vm_object_t backing_object, object;
776 int act_delta, remove_mode;
778 VM_OBJECT_ASSERT_LOCKED(first_object);
779 if ((first_object->flags & OBJ_FICTITIOUS) != 0)
781 for (object = first_object;; object = backing_object) {
782 if (pmap_resident_count(pmap) <= desired)
784 VM_OBJECT_ASSERT_LOCKED(object);
785 if ((object->flags & OBJ_UNMANAGED) != 0 ||
786 object->paging_in_progress != 0)
790 if (object->shadow_count > 1)
793 * Scan the object's entire memory queue.
795 TAILQ_FOREACH(p, &object->memq, listq) {
796 if (pmap_resident_count(pmap) <= desired)
798 if (vm_page_busied(p))
800 PCPU_INC(cnt.v_pdpages);
802 if (p->wire_count != 0 || p->hold_count != 0 ||
803 !pmap_page_exists_quick(pmap, p)) {
807 act_delta = pmap_ts_referenced(p);
808 if ((p->aflags & PGA_REFERENCED) != 0) {
811 vm_page_aflag_clear(p, PGA_REFERENCED);
813 if (p->queue != PQ_ACTIVE && act_delta != 0) {
815 p->act_count += act_delta;
816 } else if (p->queue == PQ_ACTIVE) {
817 if (act_delta == 0) {
818 p->act_count -= min(p->act_count,
820 if (!remove_mode && p->act_count == 0) {
822 vm_page_deactivate(p);
827 if (p->act_count < ACT_MAX -
829 p->act_count += ACT_ADVANCE;
832 } else if (p->queue == PQ_INACTIVE)
836 if ((backing_object = object->backing_object) == NULL)
838 VM_OBJECT_RLOCK(backing_object);
839 if (object != first_object)
840 VM_OBJECT_RUNLOCK(object);
843 if (object != first_object)
844 VM_OBJECT_RUNLOCK(object);
848 * deactivate some number of pages in a map, try to do it fairly, but
849 * that is really hard to do.
852 vm_pageout_map_deactivate_pages(map, desired)
857 vm_object_t obj, bigobj;
860 if (!vm_map_trylock(map))
867 * first, search out the biggest object, and try to free pages from
870 tmpe = map->header.next;
871 while (tmpe != &map->header) {
872 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
873 obj = tmpe->object.vm_object;
874 if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
875 if (obj->shadow_count <= 1 &&
877 bigobj->resident_page_count < obj->resident_page_count)) {
879 VM_OBJECT_RUNLOCK(bigobj);
882 VM_OBJECT_RUNLOCK(obj);
885 if (tmpe->wired_count > 0)
886 nothingwired = FALSE;
890 if (bigobj != NULL) {
891 vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
892 VM_OBJECT_RUNLOCK(bigobj);
895 * Next, hunt around for other pages to deactivate. We actually
896 * do this search sort of wrong -- .text first is not the best idea.
898 tmpe = map->header.next;
899 while (tmpe != &map->header) {
900 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
902 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
903 obj = tmpe->object.vm_object;
905 VM_OBJECT_RLOCK(obj);
906 vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
907 VM_OBJECT_RUNLOCK(obj);
915 * Remove all non-wired, managed mappings if a process is swapped out.
916 * This will free page table pages.
919 pmap_remove_pages(map->pmap);
922 * Remove all mappings if a process is swapped out, this will free page
925 if (desired == 0 && nothingwired) {
926 pmap_remove(vm_map_pmap(map), vm_map_min(map),
933 #endif /* !defined(NO_SWAPPING) */
936 * vm_pageout_scan does the dirty work for the pageout daemon.
938 * pass 0 - Update active LRU/deactivate pages
939 * pass 1 - Move inactive to cache or free
940 * pass 2 - Launder dirty pages
943 vm_pageout_scan(struct vm_domain *vmd, int pass)
946 struct vm_pagequeue *pq;
949 int act_delta, addl_page_shortage, deficit, maxscan, page_shortage;
950 int vnodes_skipped = 0;
951 int maxlaunder, scan_tick, scanned, starting_page_shortage;
953 boolean_t queue_locked;
956 * If we need to reclaim memory ask kernel caches to return
957 * some. We rate limit to avoid thrashing.
959 if (vmd == &vm_dom[0] && pass > 0 &&
960 (time_uptime - lowmem_uptime) >= lowmem_period) {
962 * Decrease registered cache sizes.
964 SDT_PROBE0(vm, , , vm__lowmem_scan);
965 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_PAGES);
967 * We do this explicitly after the caches have been
971 lowmem_uptime = time_uptime;
975 * The addl_page_shortage is the number of temporarily
976 * stuck pages in the inactive queue. In other words, the
977 * number of pages from the inactive count that should be
978 * discounted in setting the target for the active queue scan.
980 addl_page_shortage = 0;
983 * Calculate the number of pages we want to either free or move
987 deficit = atomic_readandclear_int(&vm_pageout_deficit);
988 page_shortage = vm_paging_target() + deficit;
990 page_shortage = deficit = 0;
991 starting_page_shortage = page_shortage;
994 * maxlaunder limits the number of dirty pages we flush per scan.
995 * For most systems a smaller value (16 or 32) is more robust under
996 * extreme memory and disk pressure because any unnecessary writes
997 * to disk can result in extreme performance degredation. However,
998 * systems with excessive dirty pages (especially when MAP_NOSYNC is
999 * used) will die horribly with limited laundering. If the pageout
1000 * daemon cannot clean enough pages in the first pass, we let it go
1001 * all out in succeeding passes.
1003 if ((maxlaunder = vm_max_launder) <= 1)
1009 * Start scanning the inactive queue for pages we can move to the
1010 * cache or free. The scan will stop when the target is reached or
1011 * we have scanned the entire inactive queue. Note that m->act_count
1012 * is not used to form decisions for the inactive queue, only for the
1015 pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
1016 maxscan = pq->pq_cnt;
1017 vm_pagequeue_lock(pq);
1018 queue_locked = TRUE;
1019 for (m = TAILQ_FIRST(&pq->pq_pl);
1020 m != NULL && maxscan-- > 0 && page_shortage > 0;
1022 vm_pagequeue_assert_locked(pq);
1023 KASSERT(queue_locked, ("unlocked inactive queue"));
1024 KASSERT(m->queue == PQ_INACTIVE, ("Inactive queue %p", m));
1026 PCPU_INC(cnt.v_pdpages);
1027 next = TAILQ_NEXT(m, plinks.q);
1032 if (m->flags & PG_MARKER)
1035 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1036 ("Fictitious page %p cannot be in inactive queue", m));
1037 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1038 ("Unmanaged page %p cannot be in inactive queue", m));
1041 * The page or object lock acquisitions fail if the
1042 * page was removed from the queue or moved to a
1043 * different position within the queue. In either
1044 * case, addl_page_shortage should not be incremented.
1046 if (!vm_pageout_page_lock(m, &next)) {
1051 if (!VM_OBJECT_TRYWLOCK(object) &&
1052 !vm_pageout_fallback_object_lock(m, &next)) {
1054 VM_OBJECT_WUNLOCK(object);
1059 * Don't mess with busy pages, keep them at at the
1060 * front of the queue, most likely they are being
1061 * paged out. Increment addl_page_shortage for busy
1062 * pages, because they may leave the inactive queue
1063 * shortly after page scan is finished.
1065 if (vm_page_busied(m)) {
1067 VM_OBJECT_WUNLOCK(object);
1068 addl_page_shortage++;
1073 * We unlock the inactive page queue, invalidating the
1074 * 'next' pointer. Use our marker to remember our
1077 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
1078 vm_pagequeue_unlock(pq);
1079 queue_locked = FALSE;
1082 * We bump the activation count if the page has been
1083 * referenced while in the inactive queue. This makes
1084 * it less likely that the page will be added back to the
1085 * inactive queue prematurely again. Here we check the
1086 * page tables (or emulated bits, if any), given the upper
1087 * level VM system not knowing anything about existing
1091 if ((m->aflags & PGA_REFERENCED) != 0) {
1092 vm_page_aflag_clear(m, PGA_REFERENCED);
1095 if (object->ref_count != 0) {
1096 act_delta += pmap_ts_referenced(m);
1098 KASSERT(!pmap_page_is_mapped(m),
1099 ("vm_pageout_scan: page %p is mapped", m));
1103 * If the upper level VM system knows about any page
1104 * references, we reactivate the page or requeue it.
1106 if (act_delta != 0) {
1107 if (object->ref_count) {
1108 vm_page_activate(m);
1109 m->act_count += act_delta + ACT_ADVANCE;
1111 vm_pagequeue_lock(pq);
1112 queue_locked = TRUE;
1113 vm_page_requeue_locked(m);
1115 VM_OBJECT_WUNLOCK(object);
1120 if (m->hold_count != 0) {
1122 VM_OBJECT_WUNLOCK(object);
1125 * Held pages are essentially stuck in the
1126 * queue. So, they ought to be discounted
1127 * from the inactive count. See the
1128 * calculation of the page_shortage for the
1129 * loop over the active queue below.
1131 addl_page_shortage++;
1136 * If the page appears to be clean at the machine-independent
1137 * layer, then remove all of its mappings from the pmap in
1138 * anticipation of placing it onto the cache queue. If,
1139 * however, any of the page's mappings allow write access,
1140 * then the page may still be modified until the last of those
1141 * mappings are removed.
1143 if (object->ref_count != 0) {
1144 vm_page_test_dirty(m);
1149 if (m->valid == 0) {
1151 * Invalid pages can be easily freed
1154 PCPU_INC(cnt.v_dfree);
1156 } else if (m->dirty == 0) {
1158 * Clean pages can be placed onto the cache queue.
1159 * This effectively frees them.
1163 } else if ((m->flags & PG_WINATCFLS) == 0 && pass < 2) {
1165 * Dirty pages need to be paged out, but flushing
1166 * a page is extremely expensive verses freeing
1167 * a clean page. Rather then artificially limiting
1168 * the number of pages we can flush, we instead give
1169 * dirty pages extra priority on the inactive queue
1170 * by forcing them to be cycled through the queue
1171 * twice before being flushed, after which the
1172 * (now clean) page will cycle through once more
1173 * before being freed. This significantly extends
1174 * the thrash point for a heavily loaded machine.
1176 m->flags |= PG_WINATCFLS;
1177 vm_pagequeue_lock(pq);
1178 queue_locked = TRUE;
1179 vm_page_requeue_locked(m);
1180 } else if (maxlaunder > 0) {
1182 * We always want to try to flush some dirty pages if
1183 * we encounter them, to keep the system stable.
1184 * Normally this number is small, but under extreme
1185 * pressure where there are insufficient clean pages
1186 * on the inactive queue, we may have to go all out.
1188 int swap_pageouts_ok;
1189 struct vnode *vp = NULL;
1190 struct mount *mp = NULL;
1192 if ((object->type != OBJT_SWAP) && (object->type != OBJT_DEFAULT)) {
1193 swap_pageouts_ok = 1;
1195 swap_pageouts_ok = !(defer_swap_pageouts || disable_swap_pageouts);
1196 swap_pageouts_ok |= (!disable_swap_pageouts && defer_swap_pageouts &&
1197 vm_page_count_min());
1202 * We don't bother paging objects that are "dead".
1203 * Those objects are in a "rundown" state.
1205 if (!swap_pageouts_ok || (object->flags & OBJ_DEAD)) {
1206 vm_pagequeue_lock(pq);
1208 VM_OBJECT_WUNLOCK(object);
1209 queue_locked = TRUE;
1210 vm_page_requeue_locked(m);
1215 * The object is already known NOT to be dead. It
1216 * is possible for the vget() to block the whole
1217 * pageout daemon, but the new low-memory handling
1218 * code should prevent it.
1220 * The previous code skipped locked vnodes and, worse,
1221 * reordered pages in the queue. This results in
1222 * completely non-deterministic operation and, on a
1223 * busy system, can lead to extremely non-optimal
1224 * pageouts. For example, it can cause clean pages
1225 * to be freed and dirty pages to be moved to the end
1226 * of the queue. Since dirty pages are also moved to
1227 * the end of the queue once-cleaned, this gives
1228 * way too large a weighting to defering the freeing
1231 * We can't wait forever for the vnode lock, we might
1232 * deadlock due to a vn_read() getting stuck in
1233 * vm_wait while holding this vnode. We skip the
1234 * vnode if we can't get it in a reasonable amount
1237 if (object->type == OBJT_VNODE) {
1239 vp = object->handle;
1240 if (vp->v_type == VREG &&
1241 vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1243 ++pageout_lock_miss;
1244 if (object->flags & OBJ_MIGHTBEDIRTY)
1246 goto unlock_and_continue;
1249 ("vp %p with NULL v_mount", vp));
1250 vm_object_reference_locked(object);
1251 VM_OBJECT_WUNLOCK(object);
1252 lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
1253 LK_SHARED : LK_EXCLUSIVE;
1254 if (vget(vp, lockmode | LK_TIMELOCK,
1256 VM_OBJECT_WLOCK(object);
1257 ++pageout_lock_miss;
1258 if (object->flags & OBJ_MIGHTBEDIRTY)
1261 goto unlock_and_continue;
1263 VM_OBJECT_WLOCK(object);
1265 vm_pagequeue_lock(pq);
1266 queue_locked = TRUE;
1268 * The page might have been moved to another
1269 * queue during potential blocking in vget()
1270 * above. The page might have been freed and
1271 * reused for another vnode.
1273 if (m->queue != PQ_INACTIVE ||
1274 m->object != object ||
1275 TAILQ_NEXT(m, plinks.q) != &vmd->vmd_marker) {
1277 if (object->flags & OBJ_MIGHTBEDIRTY)
1279 goto unlock_and_continue;
1283 * The page may have been busied during the
1284 * blocking in vget(). We don't move the
1285 * page back onto the end of the queue so that
1286 * statistics are more correct if we don't.
1288 if (vm_page_busied(m)) {
1290 addl_page_shortage++;
1291 goto unlock_and_continue;
1295 * If the page has become held it might
1296 * be undergoing I/O, so skip it
1298 if (m->hold_count != 0) {
1300 addl_page_shortage++;
1301 if (object->flags & OBJ_MIGHTBEDIRTY)
1303 goto unlock_and_continue;
1305 vm_pagequeue_unlock(pq);
1306 queue_locked = FALSE;
1310 * If a page is dirty, then it is either being washed
1311 * (but not yet cleaned) or it is still in the
1312 * laundry. If it is still in the laundry, then we
1313 * start the cleaning operation.
1315 * decrement page_shortage on success to account for
1316 * the (future) cleaned page. Otherwise we could wind
1317 * up laundering or cleaning too many pages.
1319 if (vm_pageout_clean(m) != 0) {
1323 unlock_and_continue:
1324 vm_page_lock_assert(m, MA_NOTOWNED);
1325 VM_OBJECT_WUNLOCK(object);
1328 vm_pagequeue_unlock(pq);
1329 queue_locked = FALSE;
1333 vm_object_deallocate(object);
1334 vn_finished_write(mp);
1336 vm_page_lock_assert(m, MA_NOTOWNED);
1340 VM_OBJECT_WUNLOCK(object);
1342 if (!queue_locked) {
1343 vm_pagequeue_lock(pq);
1344 queue_locked = TRUE;
1346 next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1347 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
1349 vm_pagequeue_unlock(pq);
1351 #if !defined(NO_SWAPPING)
1353 * Wakeup the swapout daemon if we didn't cache or free the targeted
1356 if (vm_swap_enabled && page_shortage > 0)
1357 vm_req_vmdaemon(VM_SWAP_NORMAL);
1361 * Wakeup the sync daemon if we skipped a vnode in a writeable object
1362 * and we didn't cache or free enough pages.
1364 if (vnodes_skipped > 0 && page_shortage > cnt.v_free_target -
1366 (void)speedup_syncer();
1369 * If the inactive queue scan fails repeatedly to meet its
1370 * target, kill the largest process.
1372 vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
1375 * Compute the number of pages we want to try to move from the
1376 * active queue to the inactive queue.
1378 page_shortage = cnt.v_inactive_target - cnt.v_inactive_count +
1379 vm_paging_target() + deficit + addl_page_shortage;
1381 pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1382 vm_pagequeue_lock(pq);
1383 maxscan = pq->pq_cnt;
1386 * If we're just idle polling attempt to visit every
1387 * active page within 'update_period' seconds.
1390 if (vm_pageout_update_period != 0) {
1391 min_scan = pq->pq_cnt;
1392 min_scan *= scan_tick - vmd->vmd_last_active_scan;
1393 min_scan /= hz * vm_pageout_update_period;
1396 if (min_scan > 0 || (page_shortage > 0 && maxscan > 0))
1397 vmd->vmd_last_active_scan = scan_tick;
1400 * Scan the active queue for pages that can be deactivated. Update
1401 * the per-page activity counter and use it to identify deactivation
1402 * candidates. Held pages may be deactivated.
1404 for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
1405 min_scan || (page_shortage > 0 && scanned < maxscan)); m = next,
1407 KASSERT(m->queue == PQ_ACTIVE,
1408 ("vm_pageout_scan: page %p isn't active", m));
1409 next = TAILQ_NEXT(m, plinks.q);
1410 if ((m->flags & PG_MARKER) != 0)
1412 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1413 ("Fictitious page %p cannot be in active queue", m));
1414 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1415 ("Unmanaged page %p cannot be in active queue", m));
1416 if (!vm_pageout_page_lock(m, &next)) {
1422 * The count for page daemon pages is updated after checking
1423 * the page for eligibility.
1425 PCPU_INC(cnt.v_pdpages);
1428 * Check to see "how much" the page has been used.
1431 if (m->aflags & PGA_REFERENCED) {
1432 vm_page_aflag_clear(m, PGA_REFERENCED);
1436 * Perform an unsynchronized object ref count check. While
1437 * the page lock ensures that the page is not reallocated to
1438 * another object, in particular, one with unmanaged mappings
1439 * that cannot support pmap_ts_referenced(), two races are,
1440 * nonetheless, possible:
1441 * 1) The count was transitioning to zero, but we saw a non-
1442 * zero value. pmap_ts_referenced() will return zero
1443 * because the page is not mapped.
1444 * 2) The count was transitioning to one, but we saw zero.
1445 * This race delays the detection of a new reference. At
1446 * worst, we will deactivate and reactivate the page.
1448 if (m->object->ref_count != 0)
1449 act_delta += pmap_ts_referenced(m);
1452 * Advance or decay the act_count based on recent usage.
1455 m->act_count += ACT_ADVANCE + act_delta;
1456 if (m->act_count > ACT_MAX)
1457 m->act_count = ACT_MAX;
1459 m->act_count -= min(m->act_count, ACT_DECLINE);
1460 act_delta = m->act_count;
1464 * Move this page to the tail of the active or inactive
1465 * queue depending on usage.
1467 if (act_delta == 0) {
1468 /* Dequeue to avoid later lock recursion. */
1469 vm_page_dequeue_locked(m);
1470 vm_page_deactivate(m);
1473 vm_page_requeue_locked(m);
1476 vm_pagequeue_unlock(pq);
1477 #if !defined(NO_SWAPPING)
1479 * Idle process swapout -- run once per second.
1481 if (vm_swap_idle_enabled) {
1483 if (time_second != lsec) {
1484 vm_req_vmdaemon(VM_SWAP_IDLE);
1491 static int vm_pageout_oom_vote;
1494 * The pagedaemon threads randlomly select one to perform the
1495 * OOM. Trying to kill processes before all pagedaemons
1496 * failed to reach free target is premature.
1499 vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
1500 int starting_page_shortage)
1504 if (starting_page_shortage <= 0 || starting_page_shortage !=
1506 vmd->vmd_oom_seq = 0;
1509 if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1511 vmd->vmd_oom = FALSE;
1512 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1518 * Do not follow the call sequence until OOM condition is
1521 vmd->vmd_oom_seq = 0;
1526 vmd->vmd_oom = TRUE;
1527 old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1528 if (old_vote != vm_ndomains - 1)
1532 * The current pagedaemon thread is the last in the quorum to
1533 * start OOM. Initiate the selection and signaling of the
1536 vm_pageout_oom(VM_OOM_MEM);
1539 * After one round of OOM terror, recall our vote. On the
1540 * next pass, current pagedaemon would vote again if the low
1541 * memory condition is still there, due to vmd_oom being
1544 vmd->vmd_oom = FALSE;
1545 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1549 * The OOM killer is the page daemon's action of last resort when
1550 * memory allocation requests have been stalled for a prolonged period
1551 * of time because it cannot reclaim memory. This function computes
1552 * the approximate number of physical pages that could be reclaimed if
1553 * the specified address space is destroyed.
1555 * Private, anonymous memory owned by the address space is the
1556 * principal resource that we expect to recover after an OOM kill.
1557 * Since the physical pages mapped by the address space's COW entries
1558 * are typically shared pages, they are unlikely to be released and so
1559 * they are not counted.
1561 * To get to the point where the page daemon runs the OOM killer, its
1562 * efforts to write-back vnode-backed pages may have stalled. This
1563 * could be caused by a memory allocation deadlock in the write path
1564 * that might be resolved by an OOM kill. Therefore, physical pages
1565 * belonging to vnode-backed objects are counted, because they might
1566 * be freed without being written out first if the address space holds
1567 * the last reference to an unlinked vnode.
1569 * Similarly, physical pages belonging to OBJT_PHYS objects are
1570 * counted because the address space might hold the last reference to
1574 vm_pageout_oom_pagecount(struct vmspace *vmspace)
1577 vm_map_entry_t entry;
1581 map = &vmspace->vm_map;
1582 KASSERT(!map->system_map, ("system map"));
1583 sx_assert(&map->lock, SA_LOCKED);
1585 for (entry = map->header.next; entry != &map->header;
1586 entry = entry->next) {
1587 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
1589 obj = entry->object.vm_object;
1592 if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
1593 obj->ref_count != 1)
1595 switch (obj->type) {
1600 res += obj->resident_page_count;
1608 vm_pageout_oom(int shortage)
1610 struct proc *p, *bigproc;
1611 vm_offset_t size, bigsize;
1617 * We keep the process bigproc locked once we find it to keep anyone
1618 * from messing with it; however, there is a possibility of
1619 * deadlock if process B is bigproc and one of it's child processes
1620 * attempts to propagate a signal to B while we are waiting for A's
1621 * lock while walking this list. To avoid this, we don't block on
1622 * the process lock but just skip a process if it is already locked.
1626 sx_slock(&allproc_lock);
1627 FOREACH_PROC_IN_SYSTEM(p) {
1631 * If this is a system, protected or killed process, skip it.
1633 if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
1634 P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
1635 p->p_pid == 1 || P_KILLED(p) ||
1636 (p->p_pid < 48 && swap_pager_avail != 0)) {
1641 * If the process is in a non-running type state,
1642 * don't touch it. Check all the threads individually.
1645 FOREACH_THREAD_IN_PROC(p, td) {
1647 if (!TD_ON_RUNQ(td) &&
1648 !TD_IS_RUNNING(td) &&
1649 !TD_IS_SLEEPING(td) &&
1650 !TD_IS_SUSPENDED(td) &&
1651 !TD_IS_SWAPPED(td)) {
1663 * get the process size
1665 vm = vmspace_acquire_ref(p);
1671 if (!vm_map_trylock_read(&vm->vm_map)) {
1678 size = vmspace_swap_count(vm);
1679 if (shortage == VM_OOM_MEM)
1680 size += vm_pageout_oom_pagecount(vm);
1681 vm_map_unlock_read(&vm->vm_map);
1685 * If this process is bigger than the biggest one,
1688 if (size > bigsize) {
1689 if (bigproc != NULL)
1697 sx_sunlock(&allproc_lock);
1698 if (bigproc != NULL) {
1700 killproc(bigproc, "out of swap space");
1701 sched_nice(bigproc, PRIO_MIN);
1703 PROC_UNLOCK(bigproc);
1704 wakeup(&cnt.v_free_count);
1709 vm_pageout_worker(void *arg)
1711 struct vm_domain *domain;
1714 domidx = (uintptr_t)arg;
1715 domain = &vm_dom[domidx];
1718 * XXXKIB It could be useful to bind pageout daemon threads to
1719 * the cores belonging to the domain, from which vm_page_array
1723 KASSERT(domain->vmd_segs != 0, ("domain without segments"));
1724 domain->vmd_last_active_scan = ticks;
1725 vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
1728 * The pageout daemon worker is never done, so loop forever.
1732 * If we have enough free memory, wakeup waiters. Do
1733 * not clear vm_pages_needed until we reach our target,
1734 * otherwise we may be woken up over and over again and
1735 * waste a lot of cpu.
1737 mtx_lock(&vm_page_queue_free_mtx);
1738 if (vm_pages_needed && !vm_page_count_min()) {
1739 if (!vm_paging_needed())
1740 vm_pages_needed = 0;
1741 wakeup(&cnt.v_free_count);
1743 if (vm_pages_needed) {
1745 * We're still not done. Either vm_pages_needed was
1746 * set by another thread during the previous scan
1747 * (typically, this happens during a level 0 scan) or
1748 * vm_pages_needed was already set and the scan failed
1749 * to free enough pages. If we haven't yet performed
1750 * a level >= 2 scan (unlimited dirty cleaning), then
1751 * upgrade the level and scan again now. Otherwise,
1752 * sleep a bit and try again later. While sleeping,
1753 * vm_pages_needed can be cleared.
1755 if (domain->vmd_pass > 1)
1756 msleep(&vm_pages_needed,
1757 &vm_page_queue_free_mtx, PVM, "psleep",
1761 * Good enough, sleep until required to refresh
1764 msleep(&vm_pages_needed, &vm_page_queue_free_mtx,
1767 if (vm_pages_needed) {
1771 domain->vmd_pass = 0;
1772 mtx_unlock(&vm_page_queue_free_mtx);
1773 vm_pageout_scan(domain, domain->vmd_pass);
1778 * vm_pageout_init initialises basic pageout daemon settings.
1781 vm_pageout_init(void)
1784 * Initialize some paging parameters.
1786 cnt.v_interrupt_free_min = 2;
1787 if (cnt.v_page_count < 2000)
1788 vm_pageout_page_count = 8;
1791 * v_free_reserved needs to include enough for the largest
1792 * swap pager structures plus enough for any pv_entry structs
1795 if (cnt.v_page_count > 1024)
1796 cnt.v_free_min = 4 + (cnt.v_page_count - 1024) / 200;
1799 cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1800 cnt.v_interrupt_free_min;
1801 cnt.v_free_reserved = vm_pageout_page_count +
1802 cnt.v_pageout_free_min + (cnt.v_page_count / 768);
1803 cnt.v_free_severe = cnt.v_free_min / 2;
1804 cnt.v_free_target = 4 * cnt.v_free_min + cnt.v_free_reserved;
1805 cnt.v_free_min += cnt.v_free_reserved;
1806 cnt.v_free_severe += cnt.v_free_reserved;
1807 cnt.v_inactive_target = (3 * cnt.v_free_target) / 2;
1808 if (cnt.v_inactive_target > cnt.v_free_count / 3)
1809 cnt.v_inactive_target = cnt.v_free_count / 3;
1812 * Set the default wakeup threshold to be 10% above the minimum
1813 * page limit. This keeps the steady state out of shortfall.
1815 vm_pageout_wakeup_thresh = (cnt.v_free_min / 10) * 11;
1818 * Set interval in seconds for active scan. We want to visit each
1819 * page at least once every ten minutes. This is to prevent worst
1820 * case paging behaviors with stale active LRU.
1822 if (vm_pageout_update_period == 0)
1823 vm_pageout_update_period = 600;
1825 /* XXX does not really belong here */
1826 if (vm_page_max_wired == 0)
1827 vm_page_max_wired = cnt.v_free_count / 3;
1831 * vm_pageout is the high level pageout daemon.
1841 swap_pager_swap_init();
1843 for (i = 1; i < vm_ndomains; i++) {
1844 error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
1845 curproc, NULL, 0, 0, "dom%d", i);
1847 panic("starting pageout for domain %d, error %d\n",
1852 error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
1855 panic("starting uma_reclaim helper, error %d\n", error);
1856 vm_pageout_worker((void *)(uintptr_t)0);
1860 * Unless the free page queue lock is held by the caller, this function
1861 * should be regarded as advisory. Specifically, the caller should
1862 * not msleep() on &cnt.v_free_count following this function unless
1863 * the free page queue lock is held until the msleep() is performed.
1866 pagedaemon_wakeup(void)
1869 if (!vm_pages_needed && curthread->td_proc != pageproc) {
1870 vm_pages_needed = 1;
1871 wakeup(&vm_pages_needed);
1875 #if !defined(NO_SWAPPING)
1877 vm_req_vmdaemon(int req)
1879 static int lastrun = 0;
1881 mtx_lock(&vm_daemon_mtx);
1882 vm_pageout_req_swapout |= req;
1883 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
1884 wakeup(&vm_daemon_needed);
1887 mtx_unlock(&vm_daemon_mtx);
1893 struct rlimit rsslim;
1897 int breakout, swapout_flags, tryagain, attempts;
1899 uint64_t rsize, ravailable;
1903 mtx_lock(&vm_daemon_mtx);
1904 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
1906 racct_enable ? hz : 0
1911 swapout_flags = vm_pageout_req_swapout;
1912 vm_pageout_req_swapout = 0;
1913 mtx_unlock(&vm_daemon_mtx);
1915 swapout_procs(swapout_flags);
1918 * scan the processes for exceeding their rlimits or if
1919 * process is swapped out -- deactivate pages
1925 sx_slock(&allproc_lock);
1926 FOREACH_PROC_IN_SYSTEM(p) {
1927 vm_pindex_t limit, size;
1930 * if this is a system process or if we have already
1931 * looked at this process, skip it.
1934 if (p->p_state != PRS_NORMAL ||
1935 p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
1940 * if the process is in a non-running type state,
1944 FOREACH_THREAD_IN_PROC(p, td) {
1946 if (!TD_ON_RUNQ(td) &&
1947 !TD_IS_RUNNING(td) &&
1948 !TD_IS_SLEEPING(td) &&
1949 !TD_IS_SUSPENDED(td)) {
1963 lim_rlimit(p, RLIMIT_RSS, &rsslim);
1965 qmin(rsslim.rlim_cur, rsslim.rlim_max));
1968 * let processes that are swapped out really be
1969 * swapped out set the limit to nothing (will force a
1972 if ((p->p_flag & P_INMEM) == 0)
1973 limit = 0; /* XXX */
1974 vm = vmspace_acquire_ref(p);
1979 size = vmspace_resident_count(vm);
1980 if (size >= limit) {
1981 vm_pageout_map_deactivate_pages(
1982 &vm->vm_map, limit);
1983 size = vmspace_resident_count(vm);
1987 rsize = IDX_TO_OFF(size);
1989 if (p->p_state == PRS_NORMAL)
1990 racct_set(p, RACCT_RSS, rsize);
1991 ravailable = racct_get_available(p, RACCT_RSS);
1993 if (rsize > ravailable) {
1995 * Don't be overly aggressive; this
1996 * might be an innocent process,
1997 * and the limit could've been exceeded
1998 * by some memory hog. Don't try
1999 * to deactivate more than 1/4th
2000 * of process' resident set size.
2002 if (attempts <= 8) {
2003 if (ravailable < rsize -
2005 ravailable = rsize -
2009 vm_pageout_map_deactivate_pages(
2011 OFF_TO_IDX(ravailable));
2012 /* Update RSS usage after paging out. */
2013 size = vmspace_resident_count(vm);
2014 rsize = IDX_TO_OFF(size);
2016 if (p->p_state == PRS_NORMAL)
2017 racct_set(p, RACCT_RSS, rsize);
2019 if (rsize > ravailable)
2026 sx_sunlock(&allproc_lock);
2027 if (tryagain != 0 && attempts <= 10)
2031 #endif /* !defined(NO_SWAPPING) */