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>
96 #include <sys/vnode.h>
97 #include <sys/vmmeter.h>
98 #include <sys/rwlock.h>
100 #include <sys/sysctl.h>
103 #include <vm/vm_param.h>
104 #include <vm/vm_object.h>
105 #include <vm/vm_page.h>
106 #include <vm/vm_map.h>
107 #include <vm/vm_pageout.h>
108 #include <vm/vm_pager.h>
109 #include <vm/vm_phys.h>
110 #include <vm/swap_pager.h>
111 #include <vm/vm_extern.h>
115 * System initialization
118 /* the kernel process "vm_pageout"*/
119 static void vm_pageout(void);
120 static void vm_pageout_init(void);
121 static int vm_pageout_clean(vm_page_t m);
122 static int vm_pageout_cluster(vm_page_t m);
123 static void vm_pageout_scan(struct vm_domain *vmd, int pass);
124 static void vm_pageout_mightbe_oom(struct vm_domain *vmd, int pass);
126 SYSINIT(pagedaemon_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, vm_pageout_init,
129 struct proc *pageproc;
131 static struct kproc_desc page_kp = {
136 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_SECOND, kproc_start,
139 SDT_PROVIDER_DEFINE(vm);
140 SDT_PROBE_DEFINE(vm, , , vm__lowmem_cache);
141 SDT_PROBE_DEFINE(vm, , , vm__lowmem_scan);
143 #if !defined(NO_SWAPPING)
144 /* the kernel process "vm_daemon"*/
145 static void vm_daemon(void);
146 static struct proc *vmproc;
148 static struct kproc_desc vm_kp = {
153 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
157 int vm_pages_needed; /* Event on which pageout daemon sleeps */
158 int vm_pageout_deficit; /* Estimated number of pages deficit */
159 int vm_pageout_pages_needed; /* flag saying that the pageout daemon needs pages */
160 int vm_pageout_wakeup_thresh;
162 #if !defined(NO_SWAPPING)
163 static int vm_pageout_req_swapout; /* XXX */
164 static int vm_daemon_needed;
165 static struct mtx vm_daemon_mtx;
166 /* Allow for use by vm_pageout before vm_daemon is initialized. */
167 MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
169 static int vm_max_launder = 32;
170 static int vm_pageout_update_period;
171 static int defer_swap_pageouts;
172 static int disable_swap_pageouts;
173 static int lowmem_period = 10;
174 static int lowmem_ticks;
176 #if defined(NO_SWAPPING)
177 static int vm_swap_enabled = 0;
178 static int vm_swap_idle_enabled = 0;
180 static int vm_swap_enabled = 1;
181 static int vm_swap_idle_enabled = 0;
184 static int vm_panic_on_oom = 0;
186 SYSCTL_INT(_vm, OID_AUTO, panic_on_oom,
187 CTLFLAG_RWTUN, &vm_panic_on_oom, 0,
188 "panic on out of memory instead of killing the largest process");
190 SYSCTL_INT(_vm, OID_AUTO, pageout_wakeup_thresh,
191 CTLFLAG_RW, &vm_pageout_wakeup_thresh, 0,
192 "free page threshold for waking up the pageout daemon");
194 SYSCTL_INT(_vm, OID_AUTO, max_launder,
195 CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
197 SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
198 CTLFLAG_RW, &vm_pageout_update_period, 0,
199 "Maximum active LRU update period");
201 SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RW, &lowmem_period, 0,
202 "Low memory callback period");
204 #if defined(NO_SWAPPING)
205 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
206 CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout");
207 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
208 CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
210 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
211 CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
212 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
213 CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
216 SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
217 CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
219 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
220 CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
222 static int pageout_lock_miss;
223 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
224 CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
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 wirte 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 queues
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);
295 /* Page queue might have changed. */
296 *next = TAILQ_NEXT(&marker, plinks.q);
297 unchanged = (m->queue == queue &&
298 m->object == object &&
299 &marker == TAILQ_NEXT(m, plinks.q));
300 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
305 * Lock the page while holding the page queue lock. Use marker page
306 * to detect page queue changes and maintain notion of next page on
307 * page queue. Return TRUE if no changes were detected, FALSE
308 * otherwise. The page is locked on return. The page queue lock might
309 * be dropped and reacquired.
311 * This function depends on normal struct vm_page being type stable.
314 vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
316 struct vm_page marker;
317 struct vm_pagequeue *pq;
321 vm_page_lock_assert(m, MA_NOTOWNED);
322 if (vm_page_trylock(m))
326 vm_pageout_init_marker(&marker, queue);
327 pq = vm_page_pagequeue(m);
329 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
330 vm_pagequeue_unlock(pq);
332 vm_pagequeue_lock(pq);
334 /* Page queue might have changed. */
335 *next = TAILQ_NEXT(&marker, plinks.q);
336 unchanged = (m->queue == queue && &marker == TAILQ_NEXT(m, plinks.q));
337 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
344 * Clean the page and remove it from the laundry.
346 * We set the busy bit to cause potential page faults on this page to
347 * block. Note the careful timing, however, the busy bit isn't set till
348 * late and we cannot do anything that will mess with the page.
351 vm_pageout_cluster(vm_page_t m)
354 vm_page_t mc[2*vm_pageout_page_count], pb, ps;
356 int ib, is, page_base;
357 vm_pindex_t pindex = m->pindex;
359 vm_page_lock_assert(m, MA_OWNED);
361 VM_OBJECT_ASSERT_WLOCKED(object);
364 * It doesn't cost us anything to pageout OBJT_DEFAULT or OBJT_SWAP
365 * with the new swapper, but we could have serious problems paging
366 * out other object types if there is insufficient memory.
368 * Unfortunately, checking free memory here is far too late, so the
369 * check has been moved up a procedural level.
373 * Can't clean the page if it's busy or held.
375 vm_page_assert_unbusied(m);
376 KASSERT(m->hold_count == 0, ("vm_pageout_clean: page %p is held", m));
379 mc[vm_pageout_page_count] = pb = ps = m;
381 page_base = vm_pageout_page_count;
386 * Scan object for clusterable pages.
388 * We can cluster ONLY if: ->> the page is NOT
389 * clean, wired, busy, held, or mapped into a
390 * buffer, and one of the following:
391 * 1) The page is inactive, or a seldom used
394 * 2) we force the issue.
396 * During heavy mmap/modification loads the pageout
397 * daemon can really fragment the underlying file
398 * due to flushing pages out of order and not trying
399 * align the clusters (which leave sporatic out-of-order
400 * holes). To solve this problem we do the reverse scan
401 * first and attempt to align our cluster, then do a
402 * forward scan if room remains.
405 while (ib && pageout_count < vm_pageout_page_count) {
413 if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
418 vm_page_test_dirty(p);
420 p->queue != PQ_INACTIVE ||
421 p->hold_count != 0) { /* may be undergoing I/O */
427 mc[--page_base] = pb = p;
431 * alignment boundry, stop here and switch directions. Do
434 if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
438 while (pageout_count < vm_pageout_page_count &&
439 pindex + is < object->size) {
442 if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
445 vm_page_test_dirty(p);
447 p->queue != PQ_INACTIVE ||
448 p->hold_count != 0) { /* may be undergoing I/O */
453 mc[page_base + pageout_count] = ps = p;
459 * If we exhausted our forward scan, continue with the reverse scan
460 * when possible, even past a page boundry. This catches boundry
463 if (ib && pageout_count < vm_pageout_page_count)
467 * we allow reads during pageouts...
469 return (vm_pageout_flush(&mc[page_base], pageout_count, 0, 0, NULL,
474 * vm_pageout_flush() - launder the given pages
476 * The given pages are laundered. Note that we setup for the start of
477 * I/O ( i.e. busy the page ), mark it read-only, and bump the object
478 * reference count all in here rather then in the parent. If we want
479 * the parent to do more sophisticated things we may have to change
482 * Returned runlen is the count of pages between mreq and first
483 * page after mreq with status VM_PAGER_AGAIN.
484 * *eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
485 * for any page in runlen set.
488 vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
491 vm_object_t object = mc[0]->object;
492 int pageout_status[count];
496 VM_OBJECT_ASSERT_WLOCKED(object);
499 * Initiate I/O. Bump the vm_page_t->busy counter and
500 * mark the pages read-only.
502 * We do not have to fixup the clean/dirty bits here... we can
503 * allow the pager to do it after the I/O completes.
505 * NOTE! mc[i]->dirty may be partial or fragmented due to an
506 * edge case with file fragments.
508 for (i = 0; i < count; i++) {
509 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
510 ("vm_pageout_flush: partially invalid page %p index %d/%d",
512 vm_page_sbusy(mc[i]);
513 pmap_remove_write(mc[i]);
515 vm_object_pip_add(object, count);
517 vm_pager_put_pages(object, mc, count, flags, pageout_status);
519 runlen = count - mreq;
522 for (i = 0; i < count; i++) {
523 vm_page_t mt = mc[i];
525 KASSERT(pageout_status[i] == VM_PAGER_PEND ||
526 !pmap_page_is_write_mapped(mt),
527 ("vm_pageout_flush: page %p is not write protected", mt));
528 switch (pageout_status[i]) {
535 * Page outside of range of object. Right now we
536 * essentially lose the changes by pretending it
544 * If page couldn't be paged out, then reactivate the
545 * page so it doesn't clog the inactive list. (We
546 * will try paging out it again later).
549 vm_page_activate(mt);
551 if (eio != NULL && i >= mreq && i - mreq < runlen)
555 if (i >= mreq && i - mreq < runlen)
561 * If the operation is still going, leave the page busy to
562 * block all other accesses. Also, leave the paging in
563 * progress indicator set so that we don't attempt an object
566 if (pageout_status[i] != VM_PAGER_PEND) {
567 vm_object_pip_wakeup(object);
573 return (numpagedout);
577 vm_pageout_launder(struct vm_pagequeue *pq, int tries, vm_paddr_t low,
584 vm_page_t m, m_tmp, next;
587 vm_pagequeue_lock(pq);
588 TAILQ_FOREACH_SAFE(m, &pq->pq_pl, plinks.q, next) {
589 if ((m->flags & PG_MARKER) != 0)
591 pa = VM_PAGE_TO_PHYS(m);
592 if (pa < low || pa + PAGE_SIZE > high)
594 if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
599 if ((!VM_OBJECT_TRYWLOCK(object) &&
600 (!vm_pageout_fallback_object_lock(m, &next) ||
601 m->hold_count != 0)) || vm_page_busied(m)) {
603 VM_OBJECT_WUNLOCK(object);
606 vm_page_test_dirty(m);
607 if (m->dirty == 0 && object->ref_count != 0)
611 if (tries == 0 || (object->flags & OBJ_DEAD) != 0) {
612 VM_OBJECT_WUNLOCK(object);
615 if (object->type == OBJT_VNODE) {
616 vm_pagequeue_unlock(pq);
618 vm_object_reference_locked(object);
619 VM_OBJECT_WUNLOCK(object);
620 (void)vn_start_write(vp, &mp, V_WAIT);
621 lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
622 LK_SHARED : LK_EXCLUSIVE;
623 vn_lock(vp, lockmode | LK_RETRY);
624 VM_OBJECT_WLOCK(object);
625 vm_object_page_clean(object, 0, 0, OBJPC_SYNC);
626 VM_OBJECT_WUNLOCK(object);
628 vm_object_deallocate(object);
629 vn_finished_write(mp);
631 } else if (object->type == OBJT_SWAP ||
632 object->type == OBJT_DEFAULT) {
633 vm_pagequeue_unlock(pq);
635 vm_pageout_flush(&m_tmp, 1, VM_PAGER_PUT_SYNC,
637 VM_OBJECT_WUNLOCK(object);
642 * Dequeue here to prevent lock recursion in
645 vm_page_dequeue_locked(m);
649 VM_OBJECT_WUNLOCK(object);
651 vm_pagequeue_unlock(pq);
656 * Increase the number of cached pages. The specified value, "tries",
657 * determines which categories of pages are cached:
659 * 0: All clean, inactive pages within the specified physical address range
660 * are cached. Will not sleep.
661 * 1: The vm_lowmem handlers are called. All inactive pages within
662 * the specified physical address range are cached. May sleep.
663 * 2: The vm_lowmem handlers are called. All inactive and active pages
664 * within the specified physical address range are cached. May sleep.
667 vm_pageout_grow_cache(int tries, vm_paddr_t low, vm_paddr_t high)
669 int actl, actmax, inactl, inactmax, dom, initial_dom;
670 static int start_dom = 0;
674 * Decrease registered cache sizes. The vm_lowmem handlers
675 * may acquire locks and/or sleep, so they can only be invoked
676 * when "tries" is greater than zero.
678 SDT_PROBE0(vm, , , vm__lowmem_cache);
679 EVENTHANDLER_INVOKE(vm_lowmem, 0);
682 * We do this explicitly after the caches have been drained
689 * Make the next scan start on the next domain.
691 initial_dom = atomic_fetchadd_int(&start_dom, 1) % vm_ndomains;
694 inactmax = vm_cnt.v_inactive_count;
696 actmax = tries < 2 ? 0 : vm_cnt.v_active_count;
700 * Scan domains in round-robin order, first inactive queues,
701 * then active. Since domain usually owns large physically
702 * contiguous chunk of memory, it makes sense to completely
703 * exhaust one domain before switching to next, while growing
704 * the pool of contiguous physical pages.
706 * Do not even start launder a domain which cannot contain
707 * the specified address range, as indicated by segments
708 * constituting the domain.
711 if (inactl < inactmax) {
712 if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
714 vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_INACTIVE],
719 if (++dom == vm_ndomains)
721 if (dom != initial_dom)
725 if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
727 vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_ACTIVE],
732 if (++dom == vm_ndomains)
734 if (dom != initial_dom)
739 #if !defined(NO_SWAPPING)
741 * vm_pageout_object_deactivate_pages
743 * Deactivate enough pages to satisfy the inactive target
746 * The object and map must be locked.
749 vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
752 vm_object_t backing_object, object;
754 int act_delta, remove_mode;
756 VM_OBJECT_ASSERT_LOCKED(first_object);
757 if ((first_object->flags & OBJ_FICTITIOUS) != 0)
759 for (object = first_object;; object = backing_object) {
760 if (pmap_resident_count(pmap) <= desired)
762 VM_OBJECT_ASSERT_LOCKED(object);
763 if ((object->flags & OBJ_UNMANAGED) != 0 ||
764 object->paging_in_progress != 0)
768 if (object->shadow_count > 1)
771 * Scan the object's entire memory queue.
773 TAILQ_FOREACH(p, &object->memq, listq) {
774 if (pmap_resident_count(pmap) <= desired)
776 if (vm_page_busied(p))
778 PCPU_INC(cnt.v_pdpages);
780 if (p->wire_count != 0 || p->hold_count != 0 ||
781 !pmap_page_exists_quick(pmap, p)) {
785 act_delta = pmap_ts_referenced(p);
786 if ((p->aflags & PGA_REFERENCED) != 0) {
789 vm_page_aflag_clear(p, PGA_REFERENCED);
791 if (p->queue != PQ_ACTIVE && act_delta != 0) {
793 p->act_count += act_delta;
794 } else if (p->queue == PQ_ACTIVE) {
795 if (act_delta == 0) {
796 p->act_count -= min(p->act_count,
798 if (!remove_mode && p->act_count == 0) {
800 vm_page_deactivate(p);
805 if (p->act_count < ACT_MAX -
807 p->act_count += ACT_ADVANCE;
810 } else if (p->queue == PQ_INACTIVE)
814 if ((backing_object = object->backing_object) == NULL)
816 VM_OBJECT_RLOCK(backing_object);
817 if (object != first_object)
818 VM_OBJECT_RUNLOCK(object);
821 if (object != first_object)
822 VM_OBJECT_RUNLOCK(object);
826 * deactivate some number of pages in a map, try to do it fairly, but
827 * that is really hard to do.
830 vm_pageout_map_deactivate_pages(map, desired)
835 vm_object_t obj, bigobj;
838 if (!vm_map_trylock(map))
845 * first, search out the biggest object, and try to free pages from
848 tmpe = map->header.next;
849 while (tmpe != &map->header) {
850 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
851 obj = tmpe->object.vm_object;
852 if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
853 if (obj->shadow_count <= 1 &&
855 bigobj->resident_page_count < obj->resident_page_count)) {
857 VM_OBJECT_RUNLOCK(bigobj);
860 VM_OBJECT_RUNLOCK(obj);
863 if (tmpe->wired_count > 0)
864 nothingwired = FALSE;
868 if (bigobj != NULL) {
869 vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
870 VM_OBJECT_RUNLOCK(bigobj);
873 * Next, hunt around for other pages to deactivate. We actually
874 * do this search sort of wrong -- .text first is not the best idea.
876 tmpe = map->header.next;
877 while (tmpe != &map->header) {
878 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
880 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
881 obj = tmpe->object.vm_object;
883 VM_OBJECT_RLOCK(obj);
884 vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
885 VM_OBJECT_RUNLOCK(obj);
892 * Remove all mappings if a process is swapped out, this will free page
895 if (desired == 0 && nothingwired) {
896 pmap_remove(vm_map_pmap(map), vm_map_min(map),
902 #endif /* !defined(NO_SWAPPING) */
905 * Attempt to acquire all of the necessary locks to launder a page and
906 * then call through the clustering layer to PUTPAGES. Wait a short
907 * time for a vnode lock.
909 * Requires the page and object lock on entry, releases both before return.
910 * Returns 0 on success and an errno otherwise.
913 vm_pageout_clean(vm_page_t m)
921 vm_page_assert_locked(m);
923 VM_OBJECT_ASSERT_WLOCKED(object);
929 * The object is already known NOT to be dead. It
930 * is possible for the vget() to block the whole
931 * pageout daemon, but the new low-memory handling
932 * code should prevent it.
934 * We can't wait forever for the vnode lock, we might
935 * deadlock due to a vn_read() getting stuck in
936 * vm_wait while holding this vnode. We skip the
937 * vnode if we can't get it in a reasonable amount
940 if (object->type == OBJT_VNODE) {
943 if (vp->v_type == VREG &&
944 vn_start_write(vp, &mp, V_NOWAIT) != 0) {
950 ("vp %p with NULL v_mount", vp));
951 vm_object_reference_locked(object);
953 VM_OBJECT_WUNLOCK(object);
954 lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
955 LK_SHARED : LK_EXCLUSIVE;
956 if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
961 VM_OBJECT_WLOCK(object);
964 * While the object and page were unlocked, the page
966 * (1) moved to a different queue,
967 * (2) reallocated to a different object,
968 * (3) reallocated to a different offset, or
971 if (m->queue != PQ_INACTIVE || m->object != object ||
972 m->pindex != pindex || m->dirty == 0) {
979 * The page may have been busied or held while the object
980 * and page locks were released.
982 if (vm_page_busied(m) || m->hold_count != 0) {
990 * If a page is dirty, then it is either being washed
991 * (but not yet cleaned) or it is still in the
992 * laundry. If it is still in the laundry, then we
993 * start the cleaning operation.
995 if (vm_pageout_cluster(m) == 0)
999 VM_OBJECT_WUNLOCK(object);
1002 vm_page_lock_assert(m, MA_NOTOWNED);
1006 vm_object_deallocate(object);
1007 vn_finished_write(mp);
1014 * vm_pageout_scan does the dirty work for the pageout daemon.
1016 * pass 0 - Update active LRU/deactivate pages
1017 * pass 1 - Move inactive to cache or free
1018 * pass 2 - Launder dirty pages
1021 vm_pageout_scan(struct vm_domain *vmd, int pass)
1024 struct vm_pagequeue *pq;
1027 int act_delta, addl_page_shortage, deficit, maxscan, page_shortage;
1028 int vnodes_skipped = 0;
1029 int maxlaunder, scan_tick, scanned;
1030 boolean_t queues_locked;
1033 * If we need to reclaim memory ask kernel caches to return
1034 * some. We rate limit to avoid thrashing.
1036 if (vmd == &vm_dom[0] && pass > 0 &&
1037 (ticks - lowmem_ticks) / hz >= lowmem_period) {
1039 * Decrease registered cache sizes.
1041 SDT_PROBE0(vm, , , vm__lowmem_scan);
1042 EVENTHANDLER_INVOKE(vm_lowmem, 0);
1044 * We do this explicitly after the caches have been
1048 lowmem_ticks = ticks;
1052 * The addl_page_shortage is the number of temporarily
1053 * stuck pages in the inactive queue. In other words, the
1054 * number of pages from the inactive count that should be
1055 * discounted in setting the target for the active queue scan.
1057 addl_page_shortage = 0;
1060 * Calculate the number of pages we want to either free or move
1064 deficit = atomic_readandclear_int(&vm_pageout_deficit);
1065 page_shortage = vm_paging_target() + deficit;
1067 page_shortage = deficit = 0;
1070 * maxlaunder limits the number of dirty pages we flush per scan.
1071 * For most systems a smaller value (16 or 32) is more robust under
1072 * extreme memory and disk pressure because any unnecessary writes
1073 * to disk can result in extreme performance degredation. However,
1074 * systems with excessive dirty pages (especially when MAP_NOSYNC is
1075 * used) will die horribly with limited laundering. If the pageout
1076 * daemon cannot clean enough pages in the first pass, we let it go
1077 * all out in succeeding passes.
1079 if ((maxlaunder = vm_max_launder) <= 1)
1085 * Start scanning the inactive queue for pages we can move to the
1086 * cache or free. The scan will stop when the target is reached or
1087 * we have scanned the entire inactive queue. Note that m->act_count
1088 * is not used to form decisions for the inactive queue, only for the
1091 pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
1092 maxscan = pq->pq_cnt;
1093 vm_pagequeue_lock(pq);
1094 queues_locked = TRUE;
1095 for (m = TAILQ_FIRST(&pq->pq_pl);
1096 m != NULL && maxscan-- > 0 && page_shortage > 0;
1098 vm_pagequeue_assert_locked(pq);
1099 KASSERT(queues_locked, ("unlocked queues"));
1100 KASSERT(m->queue == PQ_INACTIVE, ("Inactive queue %p", m));
1102 PCPU_INC(cnt.v_pdpages);
1103 next = TAILQ_NEXT(m, plinks.q);
1108 if (m->flags & PG_MARKER)
1111 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1112 ("Fictitious page %p cannot be in inactive queue", m));
1113 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1114 ("Unmanaged page %p cannot be in inactive queue", m));
1117 * The page or object lock acquisitions fail if the
1118 * page was removed from the queue or moved to a
1119 * different position within the queue. In either
1120 * case, addl_page_shortage should not be incremented.
1122 if (!vm_pageout_page_lock(m, &next)) {
1127 if (!VM_OBJECT_TRYWLOCK(object) &&
1128 !vm_pageout_fallback_object_lock(m, &next)) {
1130 VM_OBJECT_WUNLOCK(object);
1135 * Don't mess with busy pages, keep them at at the
1136 * front of the queue, most likely they are being
1137 * paged out. Increment addl_page_shortage for busy
1138 * pages, because they may leave the inactive queue
1139 * shortly after page scan is finished.
1141 if (vm_page_busied(m)) {
1143 VM_OBJECT_WUNLOCK(object);
1144 addl_page_shortage++;
1149 * We unlock the inactive page queue, invalidating the
1150 * 'next' pointer. Use our marker to remember our
1153 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
1154 vm_pagequeue_unlock(pq);
1155 queues_locked = FALSE;
1158 * Invalid pages can be easily freed. They cannot be
1159 * mapped, vm_page_free() asserts this.
1161 if (m->valid == 0 && m->hold_count == 0) {
1163 PCPU_INC(cnt.v_dfree);
1169 * We bump the activation count if the page has been
1170 * referenced while in the inactive queue. This makes
1171 * it less likely that the page will be added back to the
1172 * inactive queue prematurely again. Here we check the
1173 * page tables (or emulated bits, if any), given the upper
1174 * level VM system not knowing anything about existing
1177 if ((m->aflags & PGA_REFERENCED) != 0) {
1178 vm_page_aflag_clear(m, PGA_REFERENCED);
1182 if (object->ref_count != 0) {
1183 act_delta += pmap_ts_referenced(m);
1185 KASSERT(!pmap_page_is_mapped(m),
1186 ("vm_pageout_scan: page %p is mapped", m));
1190 * If the upper level VM system knows about any page
1191 * references, we reactivate the page or requeue it.
1193 if (act_delta != 0) {
1194 if (object->ref_count != 0) {
1195 vm_page_activate(m);
1196 m->act_count += act_delta + ACT_ADVANCE;
1198 vm_pagequeue_lock(pq);
1199 queues_locked = TRUE;
1200 vm_page_requeue_locked(m);
1205 if (m->hold_count != 0) {
1207 * Held pages are essentially stuck in the
1208 * queue. So, they ought to be discounted
1209 * from the inactive count. See the
1210 * calculation of the page_shortage for the
1211 * loop over the active queue below.
1213 addl_page_shortage++;
1218 * If the page appears to be clean at the machine-independent
1219 * layer, then remove all of its mappings from the pmap in
1220 * anticipation of placing it onto the cache queue. If,
1221 * however, any of the page's mappings allow write access,
1222 * then the page may still be modified until the last of those
1223 * mappings are removed.
1225 if (object->ref_count != 0) {
1226 vm_page_test_dirty(m);
1231 if (m->dirty == 0) {
1233 * Clean pages can be freed.
1236 PCPU_INC(cnt.v_dfree);
1238 } else if ((m->flags & PG_WINATCFLS) == 0 && pass < 2) {
1240 * Dirty pages need to be paged out, but flushing
1241 * a page is extremely expensive versus freeing
1242 * a clean page. Rather then artificially limiting
1243 * the number of pages we can flush, we instead give
1244 * dirty pages extra priority on the inactive queue
1245 * by forcing them to be cycled through the queue
1246 * twice before being flushed, after which the
1247 * (now clean) page will cycle through once more
1248 * before being freed. This significantly extends
1249 * the thrash point for a heavily loaded machine.
1251 m->flags |= PG_WINATCFLS;
1252 vm_pagequeue_lock(pq);
1253 queues_locked = TRUE;
1254 vm_page_requeue_locked(m);
1255 } else if (maxlaunder > 0) {
1257 * We always want to try to flush some dirty pages if
1258 * we encounter them, to keep the system stable.
1259 * Normally this number is small, but under extreme
1260 * pressure where there are insufficient clean pages
1261 * on the inactive queue, we may have to go all out.
1263 int swap_pageouts_ok;
1266 if ((object->type != OBJT_SWAP) && (object->type != OBJT_DEFAULT)) {
1267 swap_pageouts_ok = 1;
1269 swap_pageouts_ok = !(defer_swap_pageouts || disable_swap_pageouts);
1270 swap_pageouts_ok |= (!disable_swap_pageouts && defer_swap_pageouts &&
1271 vm_page_count_min());
1276 * We don't bother paging objects that are "dead".
1277 * Those objects are in a "rundown" state.
1279 if (!swap_pageouts_ok || (object->flags & OBJ_DEAD)) {
1280 vm_pagequeue_lock(pq);
1282 VM_OBJECT_WUNLOCK(object);
1283 queues_locked = TRUE;
1284 vm_page_requeue_locked(m);
1287 error = vm_pageout_clean(m);
1289 * Decrement page_shortage on success to account for
1290 * the (future) cleaned page. Otherwise we could wind
1291 * up laundering or cleaning too many pages.
1296 } else if (error == EDEADLK) {
1297 pageout_lock_miss++;
1299 } else if (error == EBUSY) {
1300 addl_page_shortage++;
1302 vm_page_lock_assert(m, MA_NOTOWNED);
1307 VM_OBJECT_WUNLOCK(object);
1309 if (!queues_locked) {
1310 vm_pagequeue_lock(pq);
1311 queues_locked = TRUE;
1313 next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1314 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
1316 vm_pagequeue_unlock(pq);
1318 #if !defined(NO_SWAPPING)
1320 * Wakeup the swapout daemon if we didn't cache or free the targeted
1323 if (vm_swap_enabled && page_shortage > 0)
1324 vm_req_vmdaemon(VM_SWAP_NORMAL);
1328 * Wakeup the sync daemon if we skipped a vnode in a writeable object
1329 * and we didn't cache or free enough pages.
1331 if (vnodes_skipped > 0 && page_shortage > vm_cnt.v_free_target -
1333 (void)speedup_syncer();
1336 * Compute the number of pages we want to try to move from the
1337 * active queue to the inactive queue.
1339 page_shortage = vm_cnt.v_inactive_target - vm_cnt.v_inactive_count +
1340 vm_paging_target() + deficit + addl_page_shortage;
1342 pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1343 vm_pagequeue_lock(pq);
1344 maxscan = pq->pq_cnt;
1347 * If we're just idle polling attempt to visit every
1348 * active page within 'update_period' seconds.
1351 if (vm_pageout_update_period != 0) {
1352 min_scan = pq->pq_cnt;
1353 min_scan *= scan_tick - vmd->vmd_last_active_scan;
1354 min_scan /= hz * vm_pageout_update_period;
1357 if (min_scan > 0 || (page_shortage > 0 && maxscan > 0))
1358 vmd->vmd_last_active_scan = scan_tick;
1361 * Scan the active queue for pages that can be deactivated. Update
1362 * the per-page activity counter and use it to identify deactivation
1365 for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
1366 min_scan || (page_shortage > 0 && scanned < maxscan)); m = next,
1369 KASSERT(m->queue == PQ_ACTIVE,
1370 ("vm_pageout_scan: page %p isn't active", m));
1372 next = TAILQ_NEXT(m, plinks.q);
1373 if ((m->flags & PG_MARKER) != 0)
1375 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1376 ("Fictitious page %p cannot be in active queue", m));
1377 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1378 ("Unmanaged page %p cannot be in active queue", m));
1379 if (!vm_pageout_page_lock(m, &next)) {
1385 * The count for pagedaemon pages is done after checking the
1386 * page for eligibility...
1388 PCPU_INC(cnt.v_pdpages);
1391 * Check to see "how much" the page has been used.
1393 if ((m->aflags & PGA_REFERENCED) != 0) {
1394 vm_page_aflag_clear(m, PGA_REFERENCED);
1400 * Unlocked object ref count check. Two races are possible.
1401 * 1) The ref was transitioning to zero and we saw non-zero,
1402 * the pmap bits will be checked unnecessarily.
1403 * 2) The ref was transitioning to one and we saw zero.
1404 * The page lock prevents a new reference to this page so
1405 * we need not check the reference bits.
1407 if (m->object->ref_count != 0)
1408 act_delta += pmap_ts_referenced(m);
1411 * Advance or decay the act_count based on recent usage.
1413 if (act_delta != 0) {
1414 m->act_count += ACT_ADVANCE + act_delta;
1415 if (m->act_count > ACT_MAX)
1416 m->act_count = ACT_MAX;
1418 m->act_count -= min(m->act_count, ACT_DECLINE);
1421 * Move this page to the tail of the active or inactive
1422 * queue depending on usage.
1424 if (m->act_count == 0) {
1425 /* Dequeue to avoid later lock recursion. */
1426 vm_page_dequeue_locked(m);
1427 vm_page_deactivate(m);
1430 vm_page_requeue_locked(m);
1433 vm_pagequeue_unlock(pq);
1434 #if !defined(NO_SWAPPING)
1436 * Idle process swapout -- run once per second.
1438 if (vm_swap_idle_enabled) {
1440 if (time_second != lsec) {
1441 vm_req_vmdaemon(VM_SWAP_IDLE);
1448 * If we are critically low on one of RAM or swap and low on
1449 * the other, kill the largest process. However, we avoid
1450 * doing this on the first pass in order to give ourselves a
1451 * chance to flush out dirty vnode-backed pages and to allow
1452 * active pages to be moved to the inactive queue and reclaimed.
1454 vm_pageout_mightbe_oom(vmd, pass);
1457 static int vm_pageout_oom_vote;
1460 * The pagedaemon threads randlomly select one to perform the
1461 * OOM. Trying to kill processes before all pagedaemons
1462 * failed to reach free target is premature.
1465 vm_pageout_mightbe_oom(struct vm_domain *vmd, int pass)
1469 if (pass <= 1 || !((swap_pager_avail < 64 && vm_page_count_min()) ||
1470 (swap_pager_full && vm_paging_target() > 0))) {
1472 vmd->vmd_oom = FALSE;
1473 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1481 vmd->vmd_oom = TRUE;
1482 old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1483 if (old_vote != vm_ndomains - 1)
1487 * The current pagedaemon thread is the last in the quorum to
1488 * start OOM. Initiate the selection and signaling of the
1491 vm_pageout_oom(VM_OOM_MEM);
1494 * After one round of OOM terror, recall our vote. On the
1495 * next pass, current pagedaemon would vote again if the low
1496 * memory condition is still there, due to vmd_oom being
1499 vmd->vmd_oom = FALSE;
1500 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1504 vm_pageout_oom(int shortage)
1506 struct proc *p, *bigproc;
1507 vm_offset_t size, bigsize;
1512 * We keep the process bigproc locked once we find it to keep anyone
1513 * from messing with it; however, there is a possibility of
1514 * deadlock if process B is bigproc and one of it's child processes
1515 * attempts to propagate a signal to B while we are waiting for A's
1516 * lock while walking this list. To avoid this, we don't block on
1517 * the process lock but just skip a process if it is already locked.
1521 sx_slock(&allproc_lock);
1522 FOREACH_PROC_IN_SYSTEM(p) {
1528 * If this is a system, protected or killed process, skip it.
1530 if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
1531 P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
1532 p->p_pid == 1 || P_KILLED(p) ||
1533 (p->p_pid < 48 && swap_pager_avail != 0)) {
1538 * If the process is in a non-running type state,
1539 * don't touch it. Check all the threads individually.
1542 FOREACH_THREAD_IN_PROC(p, td) {
1544 if (!TD_ON_RUNQ(td) &&
1545 !TD_IS_RUNNING(td) &&
1546 !TD_IS_SLEEPING(td) &&
1547 !TD_IS_SUSPENDED(td)) {
1559 * get the process size
1561 vm = vmspace_acquire_ref(p);
1567 if (!vm_map_trylock_read(&vm->vm_map)) {
1574 size = vmspace_swap_count(vm);
1575 vm_map_unlock_read(&vm->vm_map);
1576 if (shortage == VM_OOM_MEM)
1577 size += vmspace_resident_count(vm);
1580 * if the this process is bigger than the biggest one
1583 if (size > bigsize) {
1584 if (bigproc != NULL)
1592 sx_sunlock(&allproc_lock);
1593 if (bigproc != NULL) {
1594 if (vm_panic_on_oom != 0)
1595 panic("out of swap space");
1597 killproc(bigproc, "out of swap space");
1598 sched_nice(bigproc, PRIO_MIN);
1600 PROC_UNLOCK(bigproc);
1601 wakeup(&vm_cnt.v_free_count);
1606 vm_pageout_worker(void *arg)
1608 struct vm_domain *domain;
1611 domidx = (uintptr_t)arg;
1612 domain = &vm_dom[domidx];
1615 * XXXKIB It could be useful to bind pageout daemon threads to
1616 * the cores belonging to the domain, from which vm_page_array
1620 KASSERT(domain->vmd_segs != 0, ("domain without segments"));
1621 domain->vmd_last_active_scan = ticks;
1622 vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
1625 * The pageout daemon worker is never done, so loop forever.
1629 * If we have enough free memory, wakeup waiters. Do
1630 * not clear vm_pages_needed until we reach our target,
1631 * otherwise we may be woken up over and over again and
1632 * waste a lot of cpu.
1634 mtx_lock(&vm_page_queue_free_mtx);
1635 if (vm_pages_needed && !vm_page_count_min()) {
1636 if (!vm_paging_needed())
1637 vm_pages_needed = 0;
1638 wakeup(&vm_cnt.v_free_count);
1640 if (vm_pages_needed) {
1642 * Still not done, take a second pass without waiting
1643 * (unlimited dirty cleaning), otherwise sleep a bit
1646 if (domain->vmd_pass > 1)
1647 msleep(&vm_pages_needed,
1648 &vm_page_queue_free_mtx, PVM, "psleep",
1652 * Good enough, sleep until required to refresh
1655 domain->vmd_pass = 0;
1656 msleep(&vm_pages_needed, &vm_page_queue_free_mtx,
1660 if (vm_pages_needed) {
1661 vm_cnt.v_pdwakeups++;
1664 mtx_unlock(&vm_page_queue_free_mtx);
1665 vm_pageout_scan(domain, domain->vmd_pass);
1670 * vm_pageout_init initialises basic pageout daemon settings.
1673 vm_pageout_init(void)
1676 * Initialize some paging parameters.
1678 vm_cnt.v_interrupt_free_min = 2;
1679 if (vm_cnt.v_page_count < 2000)
1680 vm_pageout_page_count = 8;
1683 * v_free_reserved needs to include enough for the largest
1684 * swap pager structures plus enough for any pv_entry structs
1687 if (vm_cnt.v_page_count > 1024)
1688 vm_cnt.v_free_min = 4 + (vm_cnt.v_page_count - 1024) / 200;
1690 vm_cnt.v_free_min = 4;
1691 vm_cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1692 vm_cnt.v_interrupt_free_min;
1693 vm_cnt.v_free_reserved = vm_pageout_page_count +
1694 vm_cnt.v_pageout_free_min + (vm_cnt.v_page_count / 768);
1695 vm_cnt.v_free_severe = vm_cnt.v_free_min / 2;
1696 vm_cnt.v_free_target = 4 * vm_cnt.v_free_min + vm_cnt.v_free_reserved;
1697 vm_cnt.v_free_min += vm_cnt.v_free_reserved;
1698 vm_cnt.v_free_severe += vm_cnt.v_free_reserved;
1699 vm_cnt.v_inactive_target = (3 * vm_cnt.v_free_target) / 2;
1700 if (vm_cnt.v_inactive_target > vm_cnt.v_free_count / 3)
1701 vm_cnt.v_inactive_target = vm_cnt.v_free_count / 3;
1704 * Set the default wakeup threshold to be 10% above the minimum
1705 * page limit. This keeps the steady state out of shortfall.
1707 vm_pageout_wakeup_thresh = (vm_cnt.v_free_min / 10) * 11;
1710 * Set interval in seconds for active scan. We want to visit each
1711 * page at least once every ten minutes. This is to prevent worst
1712 * case paging behaviors with stale active LRU.
1714 if (vm_pageout_update_period == 0)
1715 vm_pageout_update_period = 600;
1717 /* XXX does not really belong here */
1718 if (vm_page_max_wired == 0)
1719 vm_page_max_wired = vm_cnt.v_free_count / 3;
1723 * vm_pageout is the high level pageout daemon.
1733 swap_pager_swap_init();
1735 for (i = 1; i < vm_ndomains; i++) {
1736 error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
1737 curproc, NULL, 0, 0, "dom%d", i);
1739 panic("starting pageout for domain %d, error %d\n",
1744 error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
1747 panic("starting uma_reclaim helper, error %d\n", error);
1748 vm_pageout_worker((void *)(uintptr_t)0);
1752 * Unless the free page queue lock is held by the caller, this function
1753 * should be regarded as advisory. Specifically, the caller should
1754 * not msleep() on &vm_cnt.v_free_count following this function unless
1755 * the free page queue lock is held until the msleep() is performed.
1758 pagedaemon_wakeup(void)
1761 if (!vm_pages_needed && curthread->td_proc != pageproc) {
1762 vm_pages_needed = 1;
1763 wakeup(&vm_pages_needed);
1767 #if !defined(NO_SWAPPING)
1769 vm_req_vmdaemon(int req)
1771 static int lastrun = 0;
1773 mtx_lock(&vm_daemon_mtx);
1774 vm_pageout_req_swapout |= req;
1775 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
1776 wakeup(&vm_daemon_needed);
1779 mtx_unlock(&vm_daemon_mtx);
1785 struct rlimit rsslim;
1789 int breakout, swapout_flags, tryagain, attempts;
1791 uint64_t rsize, ravailable;
1795 mtx_lock(&vm_daemon_mtx);
1796 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
1798 racct_enable ? hz : 0
1803 swapout_flags = vm_pageout_req_swapout;
1804 vm_pageout_req_swapout = 0;
1805 mtx_unlock(&vm_daemon_mtx);
1807 swapout_procs(swapout_flags);
1810 * scan the processes for exceeding their rlimits or if
1811 * process is swapped out -- deactivate pages
1817 sx_slock(&allproc_lock);
1818 FOREACH_PROC_IN_SYSTEM(p) {
1819 vm_pindex_t limit, size;
1822 * if this is a system process or if we have already
1823 * looked at this process, skip it.
1826 if (p->p_state != PRS_NORMAL ||
1827 p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
1832 * if the process is in a non-running type state,
1836 FOREACH_THREAD_IN_PROC(p, td) {
1838 if (!TD_ON_RUNQ(td) &&
1839 !TD_IS_RUNNING(td) &&
1840 !TD_IS_SLEEPING(td) &&
1841 !TD_IS_SUSPENDED(td)) {
1855 lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
1857 qmin(rsslim.rlim_cur, rsslim.rlim_max));
1860 * let processes that are swapped out really be
1861 * swapped out set the limit to nothing (will force a
1864 if ((p->p_flag & P_INMEM) == 0)
1865 limit = 0; /* XXX */
1866 vm = vmspace_acquire_ref(p);
1871 size = vmspace_resident_count(vm);
1872 if (size >= limit) {
1873 vm_pageout_map_deactivate_pages(
1874 &vm->vm_map, limit);
1878 rsize = IDX_TO_OFF(size);
1880 racct_set(p, RACCT_RSS, rsize);
1881 ravailable = racct_get_available(p, RACCT_RSS);
1883 if (rsize > ravailable) {
1885 * Don't be overly aggressive; this
1886 * might be an innocent process,
1887 * and the limit could've been exceeded
1888 * by some memory hog. Don't try
1889 * to deactivate more than 1/4th
1890 * of process' resident set size.
1892 if (attempts <= 8) {
1893 if (ravailable < rsize -
1895 ravailable = rsize -
1899 vm_pageout_map_deactivate_pages(
1901 OFF_TO_IDX(ravailable));
1902 /* Update RSS usage after paging out. */
1903 size = vmspace_resident_count(vm);
1904 rsize = IDX_TO_OFF(size);
1906 racct_set(p, RACCT_RSS, rsize);
1908 if (rsize > ravailable)
1915 sx_sunlock(&allproc_lock);
1916 if (tryagain != 0 && attempts <= 10)
1920 #endif /* !defined(NO_SWAPPING) */