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);
122 static void vm_pageout_scan(struct vm_domain *vmd, int pass);
123 static void vm_pageout_mightbe_oom(struct vm_domain *vmd, int pass);
125 SYSINIT(pagedaemon_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, vm_pageout_init,
128 struct proc *pageproc;
130 static struct kproc_desc page_kp = {
135 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_SECOND, kproc_start,
138 SDT_PROVIDER_DEFINE(vm);
139 SDT_PROBE_DEFINE(vm, , , vm__lowmem_cache);
140 SDT_PROBE_DEFINE(vm, , , vm__lowmem_scan);
142 #if !defined(NO_SWAPPING)
143 /* the kernel process "vm_daemon"*/
144 static void vm_daemon(void);
145 static struct proc *vmproc;
147 static struct kproc_desc vm_kp = {
152 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
156 int vm_pages_needed; /* Event on which pageout daemon sleeps */
157 int vm_pageout_deficit; /* Estimated number of pages deficit */
158 int vm_pageout_pages_needed; /* flag saying that the pageout daemon needs pages */
159 int vm_pageout_wakeup_thresh;
161 #if !defined(NO_SWAPPING)
162 static int vm_pageout_req_swapout; /* XXX */
163 static int vm_daemon_needed;
164 static struct mtx vm_daemon_mtx;
165 /* Allow for use by vm_pageout before vm_daemon is initialized. */
166 MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
168 static int vm_max_launder = 32;
169 static int vm_pageout_update_period;
170 static int defer_swap_pageouts;
171 static int disable_swap_pageouts;
172 static int lowmem_period = 10;
173 static int lowmem_ticks;
175 #if defined(NO_SWAPPING)
176 static int vm_swap_enabled = 0;
177 static int vm_swap_idle_enabled = 0;
179 static int vm_swap_enabled = 1;
180 static int vm_swap_idle_enabled = 0;
183 SYSCTL_INT(_vm, OID_AUTO, pageout_wakeup_thresh,
184 CTLFLAG_RW, &vm_pageout_wakeup_thresh, 0,
185 "free page threshold for waking up the pageout daemon");
187 SYSCTL_INT(_vm, OID_AUTO, max_launder,
188 CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
190 SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
191 CTLFLAG_RW, &vm_pageout_update_period, 0,
192 "Maximum active LRU update period");
194 SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RW, &lowmem_period, 0,
195 "Low memory callback period");
197 #if defined(NO_SWAPPING)
198 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
199 CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout");
200 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
201 CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
203 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
204 CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
205 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
206 CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
209 SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
210 CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
212 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
213 CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
215 static int pageout_lock_miss;
216 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
217 CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
219 #define VM_PAGEOUT_PAGE_COUNT 16
220 int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
222 int vm_page_max_wired; /* XXX max # of wired pages system-wide */
223 SYSCTL_INT(_vm, OID_AUTO, max_wired,
224 CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
226 static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
227 static boolean_t vm_pageout_launder(struct vm_pagequeue *pq, int, vm_paddr_t,
229 #if !defined(NO_SWAPPING)
230 static void vm_pageout_map_deactivate_pages(vm_map_t, long);
231 static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
232 static void vm_req_vmdaemon(int req);
234 static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
237 * Initialize a dummy page for marking the caller's place in the specified
238 * paging queue. In principle, this function only needs to set the flag
239 * PG_MARKER. Nonetheless, it wirte busies and initializes the hold count
240 * to one as safety precautions.
243 vm_pageout_init_marker(vm_page_t marker, u_short queue)
246 bzero(marker, sizeof(*marker));
247 marker->flags = PG_MARKER;
248 marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
249 marker->queue = queue;
250 marker->hold_count = 1;
254 * vm_pageout_fallback_object_lock:
256 * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
257 * known to have failed and page queue must be either PQ_ACTIVE or
258 * PQ_INACTIVE. To avoid lock order violation, unlock the page queues
259 * while locking the vm object. Use marker page to detect page queue
260 * changes and maintain notion of next page on page queue. Return
261 * TRUE if no changes were detected, FALSE otherwise. vm object is
264 * This function depends on both the lock portion of struct vm_object
265 * and normal struct vm_page being type stable.
268 vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
270 struct vm_page marker;
271 struct vm_pagequeue *pq;
277 vm_pageout_init_marker(&marker, queue);
278 pq = vm_page_pagequeue(m);
281 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
282 vm_pagequeue_unlock(pq);
284 VM_OBJECT_WLOCK(object);
286 vm_pagequeue_lock(pq);
288 /* Page queue might have changed. */
289 *next = TAILQ_NEXT(&marker, plinks.q);
290 unchanged = (m->queue == queue &&
291 m->object == object &&
292 &marker == TAILQ_NEXT(m, plinks.q));
293 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
298 * Lock the page while holding the page queue lock. Use marker page
299 * to detect page queue changes and maintain notion of next page on
300 * page queue. Return TRUE if no changes were detected, FALSE
301 * otherwise. The page is locked on return. The page queue lock might
302 * be dropped and reacquired.
304 * This function depends on normal struct vm_page being type stable.
307 vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
309 struct vm_page marker;
310 struct vm_pagequeue *pq;
314 vm_page_lock_assert(m, MA_NOTOWNED);
315 if (vm_page_trylock(m))
319 vm_pageout_init_marker(&marker, queue);
320 pq = vm_page_pagequeue(m);
322 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
323 vm_pagequeue_unlock(pq);
325 vm_pagequeue_lock(pq);
327 /* Page queue might have changed. */
328 *next = TAILQ_NEXT(&marker, plinks.q);
329 unchanged = (m->queue == queue && &marker == TAILQ_NEXT(m, plinks.q));
330 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
337 * Clean the page and remove it from the laundry.
339 * We set the busy bit to cause potential page faults on this page to
340 * block. Note the careful timing, however, the busy bit isn't set till
341 * late and we cannot do anything that will mess with the page.
344 vm_pageout_clean(vm_page_t m)
347 vm_page_t mc[2*vm_pageout_page_count], pb, ps;
349 int ib, is, page_base;
350 vm_pindex_t pindex = m->pindex;
352 vm_page_lock_assert(m, MA_OWNED);
354 VM_OBJECT_ASSERT_WLOCKED(object);
357 * It doesn't cost us anything to pageout OBJT_DEFAULT or OBJT_SWAP
358 * with the new swapper, but we could have serious problems paging
359 * out other object types if there is insufficient memory.
361 * Unfortunately, checking free memory here is far too late, so the
362 * check has been moved up a procedural level.
366 * Can't clean the page if it's busy or held.
368 vm_page_assert_unbusied(m);
369 KASSERT(m->hold_count == 0, ("vm_pageout_clean: page %p is held", m));
372 mc[vm_pageout_page_count] = pb = ps = m;
374 page_base = vm_pageout_page_count;
379 * Scan object for clusterable pages.
381 * We can cluster ONLY if: ->> the page is NOT
382 * clean, wired, busy, held, or mapped into a
383 * buffer, and one of the following:
384 * 1) The page is inactive, or a seldom used
387 * 2) we force the issue.
389 * During heavy mmap/modification loads the pageout
390 * daemon can really fragment the underlying file
391 * due to flushing pages out of order and not trying
392 * align the clusters (which leave sporatic out-of-order
393 * holes). To solve this problem we do the reverse scan
394 * first and attempt to align our cluster, then do a
395 * forward scan if room remains.
398 while (ib && pageout_count < vm_pageout_page_count) {
406 if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
411 vm_page_test_dirty(p);
413 p->queue != PQ_INACTIVE ||
414 p->hold_count != 0) { /* may be undergoing I/O */
420 mc[--page_base] = pb = p;
424 * alignment boundry, stop here and switch directions. Do
427 if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
431 while (pageout_count < vm_pageout_page_count &&
432 pindex + is < object->size) {
435 if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
438 vm_page_test_dirty(p);
440 p->queue != PQ_INACTIVE ||
441 p->hold_count != 0) { /* may be undergoing I/O */
446 mc[page_base + pageout_count] = ps = p;
452 * If we exhausted our forward scan, continue with the reverse scan
453 * when possible, even past a page boundry. This catches boundry
456 if (ib && pageout_count < vm_pageout_page_count)
460 * we allow reads during pageouts...
462 return (vm_pageout_flush(&mc[page_base], pageout_count, 0, 0, NULL,
467 * vm_pageout_flush() - launder the given pages
469 * The given pages are laundered. Note that we setup for the start of
470 * I/O ( i.e. busy the page ), mark it read-only, and bump the object
471 * reference count all in here rather then in the parent. If we want
472 * the parent to do more sophisticated things we may have to change
475 * Returned runlen is the count of pages between mreq and first
476 * page after mreq with status VM_PAGER_AGAIN.
477 * *eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
478 * for any page in runlen set.
481 vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
484 vm_object_t object = mc[0]->object;
485 int pageout_status[count];
489 VM_OBJECT_ASSERT_WLOCKED(object);
492 * Initiate I/O. Bump the vm_page_t->busy counter and
493 * mark the pages read-only.
495 * We do not have to fixup the clean/dirty bits here... we can
496 * allow the pager to do it after the I/O completes.
498 * NOTE! mc[i]->dirty may be partial or fragmented due to an
499 * edge case with file fragments.
501 for (i = 0; i < count; i++) {
502 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
503 ("vm_pageout_flush: partially invalid page %p index %d/%d",
505 vm_page_sbusy(mc[i]);
506 pmap_remove_write(mc[i]);
508 vm_object_pip_add(object, count);
510 vm_pager_put_pages(object, mc, count, flags, pageout_status);
512 runlen = count - mreq;
515 for (i = 0; i < count; i++) {
516 vm_page_t mt = mc[i];
518 KASSERT(pageout_status[i] == VM_PAGER_PEND ||
519 !pmap_page_is_write_mapped(mt),
520 ("vm_pageout_flush: page %p is not write protected", mt));
521 switch (pageout_status[i]) {
528 * Page outside of range of object. Right now we
529 * essentially lose the changes by pretending it
537 * If page couldn't be paged out, then reactivate the
538 * page so it doesn't clog the inactive list. (We
539 * will try paging out it again later).
542 vm_page_activate(mt);
544 if (eio != NULL && i >= mreq && i - mreq < runlen)
548 if (i >= mreq && i - mreq < runlen)
554 * If the operation is still going, leave the page busy to
555 * block all other accesses. Also, leave the paging in
556 * progress indicator set so that we don't attempt an object
559 if (pageout_status[i] != VM_PAGER_PEND) {
560 vm_object_pip_wakeup(object);
562 if (vm_page_count_severe()) {
564 vm_page_try_to_cache(mt);
571 return (numpagedout);
575 vm_pageout_launder(struct vm_pagequeue *pq, int tries, vm_paddr_t low,
582 vm_page_t m, m_tmp, next;
585 vm_pagequeue_lock(pq);
586 TAILQ_FOREACH_SAFE(m, &pq->pq_pl, plinks.q, next) {
587 if ((m->flags & PG_MARKER) != 0)
589 pa = VM_PAGE_TO_PHYS(m);
590 if (pa < low || pa + PAGE_SIZE > high)
592 if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
597 if ((!VM_OBJECT_TRYWLOCK(object) &&
598 (!vm_pageout_fallback_object_lock(m, &next) ||
599 m->hold_count != 0)) || vm_page_busied(m)) {
601 VM_OBJECT_WUNLOCK(object);
604 vm_page_test_dirty(m);
605 if (m->dirty == 0 && object->ref_count != 0)
609 if (tries == 0 || (object->flags & OBJ_DEAD) != 0) {
610 VM_OBJECT_WUNLOCK(object);
613 if (object->type == OBJT_VNODE) {
614 vm_pagequeue_unlock(pq);
616 vm_object_reference_locked(object);
617 VM_OBJECT_WUNLOCK(object);
618 (void)vn_start_write(vp, &mp, V_WAIT);
619 lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
620 LK_SHARED : LK_EXCLUSIVE;
621 vn_lock(vp, lockmode | LK_RETRY);
622 VM_OBJECT_WLOCK(object);
623 vm_object_page_clean(object, 0, 0, OBJPC_SYNC);
624 VM_OBJECT_WUNLOCK(object);
626 vm_object_deallocate(object);
627 vn_finished_write(mp);
629 } else if (object->type == OBJT_SWAP ||
630 object->type == OBJT_DEFAULT) {
631 vm_pagequeue_unlock(pq);
633 vm_pageout_flush(&m_tmp, 1, VM_PAGER_PUT_SYNC,
635 VM_OBJECT_WUNLOCK(object);
640 * Dequeue here to prevent lock recursion in
643 vm_page_dequeue_locked(m);
647 VM_OBJECT_WUNLOCK(object);
649 vm_pagequeue_unlock(pq);
654 * Increase the number of cached pages. The specified value, "tries",
655 * determines which categories of pages are cached:
657 * 0: All clean, inactive pages within the specified physical address range
658 * are cached. Will not sleep.
659 * 1: The vm_lowmem handlers are called. All inactive pages within
660 * the specified physical address range are cached. May sleep.
661 * 2: The vm_lowmem handlers are called. All inactive and active pages
662 * within the specified physical address range are cached. May sleep.
665 vm_pageout_grow_cache(int tries, vm_paddr_t low, vm_paddr_t high)
667 int actl, actmax, inactl, inactmax, dom, initial_dom;
668 static int start_dom = 0;
672 * Decrease registered cache sizes. The vm_lowmem handlers
673 * may acquire locks and/or sleep, so they can only be invoked
674 * when "tries" is greater than zero.
676 SDT_PROBE0(vm, , , vm__lowmem_cache);
677 EVENTHANDLER_INVOKE(vm_lowmem, 0);
680 * We do this explicitly after the caches have been drained
687 * Make the next scan start on the next domain.
689 initial_dom = atomic_fetchadd_int(&start_dom, 1) % vm_ndomains;
692 inactmax = cnt.v_inactive_count;
694 actmax = tries < 2 ? 0 : cnt.v_active_count;
698 * Scan domains in round-robin order, first inactive queues,
699 * then active. Since domain usually owns large physically
700 * contiguous chunk of memory, it makes sense to completely
701 * exhaust one domain before switching to next, while growing
702 * the pool of contiguous physical pages.
704 * Do not even start launder a domain which cannot contain
705 * the specified address range, as indicated by segments
706 * constituting the domain.
709 if (inactl < inactmax) {
710 if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
712 vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_INACTIVE],
717 if (++dom == vm_ndomains)
719 if (dom != initial_dom)
723 if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
725 vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_ACTIVE],
730 if (++dom == vm_ndomains)
732 if (dom != initial_dom)
737 #if !defined(NO_SWAPPING)
739 * vm_pageout_object_deactivate_pages
741 * Deactivate enough pages to satisfy the inactive target
744 * The object and map must be locked.
747 vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
750 vm_object_t backing_object, object;
752 int act_delta, remove_mode;
754 VM_OBJECT_ASSERT_LOCKED(first_object);
755 if ((first_object->flags & OBJ_FICTITIOUS) != 0)
757 for (object = first_object;; object = backing_object) {
758 if (pmap_resident_count(pmap) <= desired)
760 VM_OBJECT_ASSERT_LOCKED(object);
761 if ((object->flags & OBJ_UNMANAGED) != 0 ||
762 object->paging_in_progress != 0)
766 if (object->shadow_count > 1)
769 * Scan the object's entire memory queue.
771 TAILQ_FOREACH(p, &object->memq, listq) {
772 if (pmap_resident_count(pmap) <= desired)
774 if (vm_page_busied(p))
776 PCPU_INC(cnt.v_pdpages);
778 if (p->wire_count != 0 || p->hold_count != 0 ||
779 !pmap_page_exists_quick(pmap, p)) {
783 act_delta = pmap_ts_referenced(p);
784 if ((p->aflags & PGA_REFERENCED) != 0) {
787 vm_page_aflag_clear(p, PGA_REFERENCED);
789 if (p->queue != PQ_ACTIVE && act_delta != 0) {
791 p->act_count += act_delta;
792 } else if (p->queue == PQ_ACTIVE) {
793 if (act_delta == 0) {
794 p->act_count -= min(p->act_count,
796 if (!remove_mode && p->act_count == 0) {
798 vm_page_deactivate(p);
803 if (p->act_count < ACT_MAX -
805 p->act_count += ACT_ADVANCE;
808 } else if (p->queue == PQ_INACTIVE)
812 if ((backing_object = object->backing_object) == NULL)
814 VM_OBJECT_RLOCK(backing_object);
815 if (object != first_object)
816 VM_OBJECT_RUNLOCK(object);
819 if (object != first_object)
820 VM_OBJECT_RUNLOCK(object);
824 * deactivate some number of pages in a map, try to do it fairly, but
825 * that is really hard to do.
828 vm_pageout_map_deactivate_pages(map, desired)
833 vm_object_t obj, bigobj;
836 if (!vm_map_trylock(map))
843 * first, search out the biggest object, and try to free pages from
846 tmpe = map->header.next;
847 while (tmpe != &map->header) {
848 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
849 obj = tmpe->object.vm_object;
850 if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
851 if (obj->shadow_count <= 1 &&
853 bigobj->resident_page_count < obj->resident_page_count)) {
855 VM_OBJECT_RUNLOCK(bigobj);
858 VM_OBJECT_RUNLOCK(obj);
861 if (tmpe->wired_count > 0)
862 nothingwired = FALSE;
866 if (bigobj != NULL) {
867 vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
868 VM_OBJECT_RUNLOCK(bigobj);
871 * Next, hunt around for other pages to deactivate. We actually
872 * do this search sort of wrong -- .text first is not the best idea.
874 tmpe = map->header.next;
875 while (tmpe != &map->header) {
876 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
878 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
879 obj = tmpe->object.vm_object;
881 VM_OBJECT_RLOCK(obj);
882 vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
883 VM_OBJECT_RUNLOCK(obj);
891 * Remove all non-wired, managed mappings if a process is swapped out.
892 * This will free page table pages.
895 pmap_remove_pages(map->pmap);
898 * Remove all mappings if a process is swapped out, this will free page
901 if (desired == 0 && nothingwired) {
902 pmap_remove(vm_map_pmap(map), vm_map_min(map),
909 #endif /* !defined(NO_SWAPPING) */
912 * vm_pageout_scan does the dirty work for the pageout daemon.
914 * pass 0 - Update active LRU/deactivate pages
915 * pass 1 - Move inactive to cache or free
916 * pass 2 - Launder dirty pages
919 vm_pageout_scan(struct vm_domain *vmd, int pass)
922 struct vm_pagequeue *pq;
924 int act_delta, addl_page_shortage, deficit, maxscan, page_shortage;
925 int vnodes_skipped = 0;
928 boolean_t queues_locked;
931 * If we need to reclaim memory ask kernel caches to return
932 * some. We rate limit to avoid thrashing.
934 if (vmd == &vm_dom[0] && pass > 0 &&
935 (ticks - lowmem_ticks) / hz >= lowmem_period) {
937 * Decrease registered cache sizes.
939 SDT_PROBE0(vm, , , vm__lowmem_scan);
940 EVENTHANDLER_INVOKE(vm_lowmem, 0);
942 * We do this explicitly after the caches have been
946 lowmem_ticks = ticks;
950 * The addl_page_shortage is the number of temporarily
951 * stuck pages in the inactive queue. In other words, the
952 * number of pages from the inactive count that should be
953 * discounted in setting the target for the active queue scan.
955 addl_page_shortage = 0;
958 * Calculate the number of pages we want to either free or move
962 deficit = atomic_readandclear_int(&vm_pageout_deficit);
963 page_shortage = vm_paging_target() + deficit;
965 page_shortage = deficit = 0;
968 * maxlaunder limits the number of dirty pages we flush per scan.
969 * For most systems a smaller value (16 or 32) is more robust under
970 * extreme memory and disk pressure because any unnecessary writes
971 * to disk can result in extreme performance degredation. However,
972 * systems with excessive dirty pages (especially when MAP_NOSYNC is
973 * used) will die horribly with limited laundering. If the pageout
974 * daemon cannot clean enough pages in the first pass, we let it go
975 * all out in succeeding passes.
977 if ((maxlaunder = vm_max_launder) <= 1)
983 * Start scanning the inactive queue for pages we can move to the
984 * cache or free. The scan will stop when the target is reached or
985 * we have scanned the entire inactive queue. Note that m->act_count
986 * is not used to form decisions for the inactive queue, only for the
989 pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
990 maxscan = pq->pq_cnt;
991 vm_pagequeue_lock(pq);
992 queues_locked = TRUE;
993 for (m = TAILQ_FIRST(&pq->pq_pl);
994 m != NULL && maxscan-- > 0 && page_shortage > 0;
996 vm_pagequeue_assert_locked(pq);
997 KASSERT(queues_locked, ("unlocked queues"));
998 KASSERT(m->queue == PQ_INACTIVE, ("Inactive queue %p", m));
1000 PCPU_INC(cnt.v_pdpages);
1001 next = TAILQ_NEXT(m, plinks.q);
1006 if (m->flags & PG_MARKER)
1009 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1010 ("Fictitious page %p cannot be in inactive queue", m));
1011 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1012 ("Unmanaged page %p cannot be in inactive queue", m));
1015 * The page or object lock acquisitions fail if the
1016 * page was removed from the queue or moved to a
1017 * different position within the queue. In either
1018 * case, addl_page_shortage should not be incremented.
1020 if (!vm_pageout_page_lock(m, &next)) {
1025 if (!VM_OBJECT_TRYWLOCK(object) &&
1026 !vm_pageout_fallback_object_lock(m, &next)) {
1028 VM_OBJECT_WUNLOCK(object);
1033 * Don't mess with busy pages, keep them at at the
1034 * front of the queue, most likely they are being
1035 * paged out. Increment addl_page_shortage for busy
1036 * pages, because they may leave the inactive queue
1037 * shortly after page scan is finished.
1039 if (vm_page_busied(m)) {
1041 VM_OBJECT_WUNLOCK(object);
1042 addl_page_shortage++;
1047 * We unlock the inactive page queue, invalidating the
1048 * 'next' pointer. Use our marker to remember our
1051 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
1052 vm_pagequeue_unlock(pq);
1053 queues_locked = FALSE;
1056 * We bump the activation count if the page has been
1057 * referenced while in the inactive queue. This makes
1058 * it less likely that the page will be added back to the
1059 * inactive queue prematurely again. Here we check the
1060 * page tables (or emulated bits, if any), given the upper
1061 * level VM system not knowing anything about existing
1065 if ((m->aflags & PGA_REFERENCED) != 0) {
1066 vm_page_aflag_clear(m, PGA_REFERENCED);
1069 if (object->ref_count != 0) {
1070 act_delta += pmap_ts_referenced(m);
1072 KASSERT(!pmap_page_is_mapped(m),
1073 ("vm_pageout_scan: page %p is mapped", m));
1077 * If the upper level VM system knows about any page
1078 * references, we reactivate the page or requeue it.
1080 if (act_delta != 0) {
1081 if (object->ref_count) {
1082 vm_page_activate(m);
1083 m->act_count += act_delta + ACT_ADVANCE;
1085 vm_pagequeue_lock(pq);
1086 queues_locked = TRUE;
1087 vm_page_requeue_locked(m);
1089 VM_OBJECT_WUNLOCK(object);
1094 if (m->hold_count != 0) {
1096 VM_OBJECT_WUNLOCK(object);
1099 * Held pages are essentially stuck in the
1100 * queue. So, they ought to be discounted
1101 * from the inactive count. See the
1102 * calculation of the page_shortage for the
1103 * loop over the active queue below.
1105 addl_page_shortage++;
1110 * If the page appears to be clean at the machine-independent
1111 * layer, then remove all of its mappings from the pmap in
1112 * anticipation of placing it onto the cache queue. If,
1113 * however, any of the page's mappings allow write access,
1114 * then the page may still be modified until the last of those
1115 * mappings are removed.
1117 vm_page_test_dirty(m);
1118 if (m->dirty == 0 && object->ref_count != 0)
1121 if (m->valid == 0) {
1123 * Invalid pages can be easily freed
1126 PCPU_INC(cnt.v_dfree);
1128 } else if (m->dirty == 0) {
1130 * Clean pages can be placed onto the cache queue.
1131 * This effectively frees them.
1135 } else if ((m->flags & PG_WINATCFLS) == 0 && pass < 2) {
1137 * Dirty pages need to be paged out, but flushing
1138 * a page is extremely expensive verses freeing
1139 * a clean page. Rather then artificially limiting
1140 * the number of pages we can flush, we instead give
1141 * dirty pages extra priority on the inactive queue
1142 * by forcing them to be cycled through the queue
1143 * twice before being flushed, after which the
1144 * (now clean) page will cycle through once more
1145 * before being freed. This significantly extends
1146 * the thrash point for a heavily loaded machine.
1148 m->flags |= PG_WINATCFLS;
1149 vm_pagequeue_lock(pq);
1150 queues_locked = TRUE;
1151 vm_page_requeue_locked(m);
1152 } else if (maxlaunder > 0) {
1154 * We always want to try to flush some dirty pages if
1155 * we encounter them, to keep the system stable.
1156 * Normally this number is small, but under extreme
1157 * pressure where there are insufficient clean pages
1158 * on the inactive queue, we may have to go all out.
1160 int swap_pageouts_ok;
1161 struct vnode *vp = NULL;
1162 struct mount *mp = NULL;
1164 if ((object->type != OBJT_SWAP) && (object->type != OBJT_DEFAULT)) {
1165 swap_pageouts_ok = 1;
1167 swap_pageouts_ok = !(defer_swap_pageouts || disable_swap_pageouts);
1168 swap_pageouts_ok |= (!disable_swap_pageouts && defer_swap_pageouts &&
1169 vm_page_count_min());
1174 * We don't bother paging objects that are "dead".
1175 * Those objects are in a "rundown" state.
1177 if (!swap_pageouts_ok || (object->flags & OBJ_DEAD)) {
1178 vm_pagequeue_lock(pq);
1180 VM_OBJECT_WUNLOCK(object);
1181 queues_locked = TRUE;
1182 vm_page_requeue_locked(m);
1187 * The object is already known NOT to be dead. It
1188 * is possible for the vget() to block the whole
1189 * pageout daemon, but the new low-memory handling
1190 * code should prevent it.
1192 * The previous code skipped locked vnodes and, worse,
1193 * reordered pages in the queue. This results in
1194 * completely non-deterministic operation and, on a
1195 * busy system, can lead to extremely non-optimal
1196 * pageouts. For example, it can cause clean pages
1197 * to be freed and dirty pages to be moved to the end
1198 * of the queue. Since dirty pages are also moved to
1199 * the end of the queue once-cleaned, this gives
1200 * way too large a weighting to defering the freeing
1203 * We can't wait forever for the vnode lock, we might
1204 * deadlock due to a vn_read() getting stuck in
1205 * vm_wait while holding this vnode. We skip the
1206 * vnode if we can't get it in a reasonable amount
1209 if (object->type == OBJT_VNODE) {
1211 vp = object->handle;
1212 if (vp->v_type == VREG &&
1213 vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1215 ++pageout_lock_miss;
1216 if (object->flags & OBJ_MIGHTBEDIRTY)
1218 goto unlock_and_continue;
1221 ("vp %p with NULL v_mount", vp));
1222 vm_object_reference_locked(object);
1223 VM_OBJECT_WUNLOCK(object);
1224 lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
1225 LK_SHARED : LK_EXCLUSIVE;
1226 if (vget(vp, lockmode | LK_TIMELOCK,
1228 VM_OBJECT_WLOCK(object);
1229 ++pageout_lock_miss;
1230 if (object->flags & OBJ_MIGHTBEDIRTY)
1233 goto unlock_and_continue;
1235 VM_OBJECT_WLOCK(object);
1237 vm_pagequeue_lock(pq);
1238 queues_locked = TRUE;
1240 * The page might have been moved to another
1241 * queue during potential blocking in vget()
1242 * above. The page might have been freed and
1243 * reused for another vnode.
1245 if (m->queue != PQ_INACTIVE ||
1246 m->object != object ||
1247 TAILQ_NEXT(m, plinks.q) != &vmd->vmd_marker) {
1249 if (object->flags & OBJ_MIGHTBEDIRTY)
1251 goto unlock_and_continue;
1255 * The page may have been busied during the
1256 * blocking in vget(). We don't move the
1257 * page back onto the end of the queue so that
1258 * statistics are more correct if we don't.
1260 if (vm_page_busied(m)) {
1262 addl_page_shortage++;
1263 goto unlock_and_continue;
1267 * If the page has become held it might
1268 * be undergoing I/O, so skip it
1270 if (m->hold_count != 0) {
1272 addl_page_shortage++;
1273 if (object->flags & OBJ_MIGHTBEDIRTY)
1275 goto unlock_and_continue;
1277 vm_pagequeue_unlock(pq);
1278 queues_locked = FALSE;
1282 * If a page is dirty, then it is either being washed
1283 * (but not yet cleaned) or it is still in the
1284 * laundry. If it is still in the laundry, then we
1285 * start the cleaning operation.
1287 * decrement page_shortage on success to account for
1288 * the (future) cleaned page. Otherwise we could wind
1289 * up laundering or cleaning too many pages.
1291 if (vm_pageout_clean(m) != 0) {
1295 unlock_and_continue:
1296 vm_page_lock_assert(m, MA_NOTOWNED);
1297 VM_OBJECT_WUNLOCK(object);
1299 if (queues_locked) {
1300 vm_pagequeue_unlock(pq);
1301 queues_locked = FALSE;
1305 vm_object_deallocate(object);
1306 vn_finished_write(mp);
1308 vm_page_lock_assert(m, MA_NOTOWNED);
1312 VM_OBJECT_WUNLOCK(object);
1314 if (!queues_locked) {
1315 vm_pagequeue_lock(pq);
1316 queues_locked = TRUE;
1318 next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1319 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
1321 vm_pagequeue_unlock(pq);
1323 #if !defined(NO_SWAPPING)
1325 * Wakeup the swapout daemon if we didn't cache or free the targeted
1328 if (vm_swap_enabled && page_shortage > 0)
1329 vm_req_vmdaemon(VM_SWAP_NORMAL);
1333 * Wakeup the sync daemon if we skipped a vnode in a writeable object
1334 * and we didn't cache or free enough pages.
1336 if (vnodes_skipped > 0 && page_shortage > cnt.v_free_target -
1338 (void)speedup_syncer();
1341 * Compute the number of pages we want to try to move from the
1342 * active queue to the inactive queue.
1344 page_shortage = cnt.v_inactive_target - cnt.v_inactive_count +
1345 vm_paging_target() + deficit + addl_page_shortage;
1347 pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1348 vm_pagequeue_lock(pq);
1349 maxscan = pq->pq_cnt;
1352 * If we're just idle polling attempt to visit every
1353 * active page within 'update_period' seconds.
1355 if (pass == 0 && vm_pageout_update_period != 0) {
1356 maxscan /= vm_pageout_update_period;
1357 page_shortage = maxscan;
1361 * Scan the active queue for things we can deactivate. We nominally
1362 * track the per-page activity counter and use it to locate
1363 * deactivation candidates.
1365 m = TAILQ_FIRST(&pq->pq_pl);
1366 while (m != NULL && maxscan-- > 0 && page_shortage > 0) {
1368 KASSERT(m->queue == PQ_ACTIVE,
1369 ("vm_pageout_scan: page %p isn't active", m));
1371 next = TAILQ_NEXT(m, plinks.q);
1372 if ((m->flags & PG_MARKER) != 0) {
1376 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1377 ("Fictitious page %p cannot be in active queue", m));
1378 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1379 ("Unmanaged page %p cannot be in active queue", m));
1380 if (!vm_pageout_page_lock(m, &next)) {
1387 * The count for pagedaemon pages is done after checking the
1388 * page for eligibility...
1390 PCPU_INC(cnt.v_pdpages);
1393 * Check to see "how much" the page has been used.
1396 if (m->aflags & PGA_REFERENCED) {
1397 vm_page_aflag_clear(m, PGA_REFERENCED);
1401 * Unlocked object ref count check. Two races are possible.
1402 * 1) The ref was transitioning to zero and we saw non-zero,
1403 * the pmap bits will be checked unnecessarily.
1404 * 2) The ref was transitioning to one and we saw zero.
1405 * The page lock prevents a new reference to this page so
1406 * we need not check the reference bits.
1408 if (m->object->ref_count != 0)
1409 act_delta += pmap_ts_referenced(m);
1412 * Advance or decay the act_count based on recent usage.
1415 m->act_count += ACT_ADVANCE + act_delta;
1416 if (m->act_count > ACT_MAX)
1417 m->act_count = ACT_MAX;
1419 m->act_count -= min(m->act_count, ACT_DECLINE);
1420 act_delta = m->act_count;
1424 * Move this page to the tail of the active or inactive
1425 * queue depending on usage.
1427 if (act_delta == 0) {
1428 /* Dequeue to avoid later lock recursion. */
1429 vm_page_dequeue_locked(m);
1430 vm_page_deactivate(m);
1433 vm_page_requeue_locked(m);
1437 vm_pagequeue_unlock(pq);
1438 #if !defined(NO_SWAPPING)
1440 * Idle process swapout -- run once per second.
1442 if (vm_swap_idle_enabled) {
1444 if (time_second != lsec) {
1445 vm_req_vmdaemon(VM_SWAP_IDLE);
1452 * If we are critically low on one of RAM or swap and low on
1453 * the other, kill the largest process. However, we avoid
1454 * doing this on the first pass in order to give ourselves a
1455 * chance to flush out dirty vnode-backed pages and to allow
1456 * active pages to be moved to the inactive queue and reclaimed.
1458 vm_pageout_mightbe_oom(vmd, pass);
1461 static int vm_pageout_oom_vote;
1464 * The pagedaemon threads randlomly select one to perform the
1465 * OOM. Trying to kill processes before all pagedaemons
1466 * failed to reach free target is premature.
1469 vm_pageout_mightbe_oom(struct vm_domain *vmd, int pass)
1473 if (pass <= 1 || !((swap_pager_avail < 64 && vm_page_count_min()) ||
1474 (swap_pager_full && vm_paging_target() > 0))) {
1476 vmd->vmd_oom = FALSE;
1477 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1485 vmd->vmd_oom = TRUE;
1486 old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1487 if (old_vote != vm_ndomains - 1)
1491 * The current pagedaemon thread is the last in the quorum to
1492 * start OOM. Initiate the selection and signaling of the
1495 vm_pageout_oom(VM_OOM_MEM);
1498 * After one round of OOM terror, recall our vote. On the
1499 * next pass, current pagedaemon would vote again if the low
1500 * memory condition is still there, due to vmd_oom being
1503 vmd->vmd_oom = FALSE;
1504 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1508 vm_pageout_oom(int shortage)
1510 struct proc *p, *bigproc;
1511 vm_offset_t size, bigsize;
1516 * We keep the process bigproc locked once we find it to keep anyone
1517 * from messing with it; however, there is a possibility of
1518 * deadlock if process B is bigproc and one of it's child processes
1519 * attempts to propagate a signal to B while we are waiting for A's
1520 * lock while walking this list. To avoid this, we don't block on
1521 * the process lock but just skip a process if it is already locked.
1525 sx_slock(&allproc_lock);
1526 FOREACH_PROC_IN_SYSTEM(p) {
1532 * If this is a system, protected or killed process, skip it.
1534 if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
1535 P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
1536 p->p_pid == 1 || P_KILLED(p) ||
1537 (p->p_pid < 48 && swap_pager_avail != 0)) {
1542 * If the process is in a non-running type state,
1543 * don't touch it. Check all the threads individually.
1546 FOREACH_THREAD_IN_PROC(p, td) {
1548 if (!TD_ON_RUNQ(td) &&
1549 !TD_IS_RUNNING(td) &&
1550 !TD_IS_SLEEPING(td) &&
1551 !TD_IS_SUSPENDED(td)) {
1563 * get the process size
1565 vm = vmspace_acquire_ref(p);
1571 if (!vm_map_trylock_read(&vm->vm_map)) {
1578 size = vmspace_swap_count(vm);
1579 vm_map_unlock_read(&vm->vm_map);
1580 if (shortage == VM_OOM_MEM)
1581 size += vmspace_resident_count(vm);
1584 * if the this process is bigger than the biggest one
1587 if (size > bigsize) {
1588 if (bigproc != NULL)
1596 sx_sunlock(&allproc_lock);
1597 if (bigproc != NULL) {
1599 killproc(bigproc, "out of swap space");
1600 sched_nice(bigproc, PRIO_MIN);
1602 PROC_UNLOCK(bigproc);
1603 wakeup(&cnt.v_free_count);
1608 vm_pageout_worker(void *arg)
1610 struct vm_domain *domain;
1613 domidx = (uintptr_t)arg;
1614 domain = &vm_dom[domidx];
1617 * XXXKIB It could be useful to bind pageout daemon threads to
1618 * the cores belonging to the domain, from which vm_page_array
1622 KASSERT(domain->vmd_segs != 0, ("domain without segments"));
1623 vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
1626 * The pageout daemon worker is never done, so loop forever.
1630 * If we have enough free memory, wakeup waiters. Do
1631 * not clear vm_pages_needed until we reach our target,
1632 * otherwise we may be woken up over and over again and
1633 * waste a lot of cpu.
1635 mtx_lock(&vm_page_queue_free_mtx);
1636 if (vm_pages_needed && !vm_page_count_min()) {
1637 if (!vm_paging_needed())
1638 vm_pages_needed = 0;
1639 wakeup(&cnt.v_free_count);
1641 if (vm_pages_needed) {
1643 * Still not done, take a second pass without waiting
1644 * (unlimited dirty cleaning), otherwise sleep a bit
1647 if (domain->vmd_pass > 1)
1648 msleep(&vm_pages_needed,
1649 &vm_page_queue_free_mtx, PVM, "psleep",
1653 * Good enough, sleep until required to refresh
1656 domain->vmd_pass = 0;
1657 msleep(&vm_pages_needed, &vm_page_queue_free_mtx,
1661 if (vm_pages_needed) {
1665 mtx_unlock(&vm_page_queue_free_mtx);
1666 vm_pageout_scan(domain, domain->vmd_pass);
1671 * vm_pageout_init initialises basic pageout daemon settings.
1674 vm_pageout_init(void)
1677 * Initialize some paging parameters.
1679 cnt.v_interrupt_free_min = 2;
1680 if (cnt.v_page_count < 2000)
1681 vm_pageout_page_count = 8;
1684 * v_free_reserved needs to include enough for the largest
1685 * swap pager structures plus enough for any pv_entry structs
1688 if (cnt.v_page_count > 1024)
1689 cnt.v_free_min = 4 + (cnt.v_page_count - 1024) / 200;
1692 cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1693 cnt.v_interrupt_free_min;
1694 cnt.v_free_reserved = vm_pageout_page_count +
1695 cnt.v_pageout_free_min + (cnt.v_page_count / 768);
1696 cnt.v_free_severe = cnt.v_free_min / 2;
1697 cnt.v_free_target = 4 * cnt.v_free_min + cnt.v_free_reserved;
1698 cnt.v_free_min += cnt.v_free_reserved;
1699 cnt.v_free_severe += cnt.v_free_reserved;
1700 cnt.v_inactive_target = (3 * cnt.v_free_target) / 2;
1701 if (cnt.v_inactive_target > cnt.v_free_count / 3)
1702 cnt.v_inactive_target = cnt.v_free_count / 3;
1705 * Set the default wakeup threshold to be 10% above the minimum
1706 * page limit. This keeps the steady state out of shortfall.
1708 vm_pageout_wakeup_thresh = (cnt.v_free_min / 10) * 11;
1711 * Set interval in seconds for active scan. We want to visit each
1712 * page at least once every ten minutes. This is to prevent worst
1713 * case paging behaviors with stale active LRU.
1715 if (vm_pageout_update_period == 0)
1716 vm_pageout_update_period = 600;
1718 /* XXX does not really belong here */
1719 if (vm_page_max_wired == 0)
1720 vm_page_max_wired = cnt.v_free_count / 3;
1724 * vm_pageout is the high level pageout daemon.
1734 swap_pager_swap_init();
1736 for (i = 1; i < vm_ndomains; i++) {
1737 error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
1738 curproc, NULL, 0, 0, "dom%d", i);
1740 panic("starting pageout for domain %d, error %d\n",
1745 error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
1748 panic("starting uma_reclaim helper, error %d\n", error);
1749 vm_pageout_worker((void *)(uintptr_t)0);
1753 * Unless the free page queue lock is held by the caller, this function
1754 * should be regarded as advisory. Specifically, the caller should
1755 * not msleep() on &cnt.v_free_count following this function unless
1756 * the free page queue lock is held until the msleep() is performed.
1759 pagedaemon_wakeup(void)
1762 if (!vm_pages_needed && curthread->td_proc != pageproc) {
1763 vm_pages_needed = 1;
1764 wakeup(&vm_pages_needed);
1768 #if !defined(NO_SWAPPING)
1770 vm_req_vmdaemon(int req)
1772 static int lastrun = 0;
1774 mtx_lock(&vm_daemon_mtx);
1775 vm_pageout_req_swapout |= req;
1776 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
1777 wakeup(&vm_daemon_needed);
1780 mtx_unlock(&vm_daemon_mtx);
1786 struct rlimit rsslim;
1790 int breakout, swapout_flags, tryagain, attempts;
1792 uint64_t rsize, ravailable;
1796 mtx_lock(&vm_daemon_mtx);
1797 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
1799 racct_enable ? hz : 0
1804 swapout_flags = vm_pageout_req_swapout;
1805 vm_pageout_req_swapout = 0;
1806 mtx_unlock(&vm_daemon_mtx);
1808 swapout_procs(swapout_flags);
1811 * scan the processes for exceeding their rlimits or if
1812 * process is swapped out -- deactivate pages
1818 sx_slock(&allproc_lock);
1819 FOREACH_PROC_IN_SYSTEM(p) {
1820 vm_pindex_t limit, size;
1823 * if this is a system process or if we have already
1824 * looked at this process, skip it.
1827 if (p->p_state != PRS_NORMAL ||
1828 p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
1833 * if the process is in a non-running type state,
1837 FOREACH_THREAD_IN_PROC(p, td) {
1839 if (!TD_ON_RUNQ(td) &&
1840 !TD_IS_RUNNING(td) &&
1841 !TD_IS_SLEEPING(td) &&
1842 !TD_IS_SUSPENDED(td)) {
1856 lim_rlimit(p, RLIMIT_RSS, &rsslim);
1858 qmin(rsslim.rlim_cur, rsslim.rlim_max));
1861 * let processes that are swapped out really be
1862 * swapped out set the limit to nothing (will force a
1865 if ((p->p_flag & P_INMEM) == 0)
1866 limit = 0; /* XXX */
1867 vm = vmspace_acquire_ref(p);
1872 size = vmspace_resident_count(vm);
1873 if (size >= limit) {
1874 vm_pageout_map_deactivate_pages(
1875 &vm->vm_map, limit);
1879 rsize = IDX_TO_OFF(size);
1881 racct_set(p, RACCT_RSS, rsize);
1882 ravailable = racct_get_available(p, RACCT_RSS);
1884 if (rsize > ravailable) {
1886 * Don't be overly aggressive; this
1887 * might be an innocent process,
1888 * and the limit could've been exceeded
1889 * by some memory hog. Don't try
1890 * to deactivate more than 1/4th
1891 * of process' resident set size.
1893 if (attempts <= 8) {
1894 if (ravailable < rsize -
1896 ravailable = rsize -
1900 vm_pageout_map_deactivate_pages(
1902 OFF_TO_IDX(ravailable));
1903 /* Update RSS usage after paging out. */
1904 size = vmspace_resident_count(vm);
1905 rsize = IDX_TO_OFF(size);
1907 racct_set(p, RACCT_RSS, rsize);
1909 if (rsize > ravailable)
1916 sx_sunlock(&allproc_lock);
1917 if (tryagain != 0 && attempts <= 10)
1921 #endif /* !defined(NO_SWAPPING) */