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 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 time_t lowmem_uptime;
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 SYSCTL_INT(_vm, OID_AUTO, pageout_wakeup_thresh,
185 CTLFLAG_RW, &vm_pageout_wakeup_thresh, 0,
186 "free page threshold for waking up the pageout daemon");
188 SYSCTL_INT(_vm, OID_AUTO, max_launder,
189 CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
191 SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
192 CTLFLAG_RW, &vm_pageout_update_period, 0,
193 "Maximum active LRU update period");
195 SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RW, &lowmem_period, 0,
196 "Low memory callback period");
198 #if defined(NO_SWAPPING)
199 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
200 CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout");
201 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
202 CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
204 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
205 CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
206 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
207 CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
210 SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
211 CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
213 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
214 CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
216 static int pageout_lock_miss;
217 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
218 CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
220 #define VM_PAGEOUT_PAGE_COUNT 16
221 int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
223 int vm_page_max_wired; /* XXX max # of wired pages system-wide */
224 SYSCTL_INT(_vm, OID_AUTO, max_wired,
225 CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
227 static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
228 static boolean_t vm_pageout_launder(struct vm_pagequeue *pq, int, vm_paddr_t,
230 #if !defined(NO_SWAPPING)
231 static void vm_pageout_map_deactivate_pages(vm_map_t, long);
232 static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
233 static void vm_req_vmdaemon(int req);
235 static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
238 * Initialize a dummy page for marking the caller's place in the specified
239 * paging queue. In principle, this function only needs to set the flag
240 * PG_MARKER. Nonetheless, it wirte busies and initializes the hold count
241 * to one as safety precautions.
244 vm_pageout_init_marker(vm_page_t marker, u_short queue)
247 bzero(marker, sizeof(*marker));
248 marker->flags = PG_MARKER;
249 marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
250 marker->queue = queue;
251 marker->hold_count = 1;
255 * vm_pageout_fallback_object_lock:
257 * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
258 * known to have failed and page queue must be either PQ_ACTIVE or
259 * PQ_INACTIVE. To avoid lock order violation, unlock the page queues
260 * while locking the vm object. Use marker page to detect page queue
261 * changes and maintain notion of next page on page queue. Return
262 * TRUE if no changes were detected, FALSE otherwise. vm object is
265 * This function depends on both the lock portion of struct vm_object
266 * and normal struct vm_page being type stable.
269 vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
271 struct vm_page marker;
272 struct vm_pagequeue *pq;
278 vm_pageout_init_marker(&marker, queue);
279 pq = vm_page_pagequeue(m);
282 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
283 vm_pagequeue_unlock(pq);
285 VM_OBJECT_WLOCK(object);
287 vm_pagequeue_lock(pq);
289 /* Page queue might have changed. */
290 *next = TAILQ_NEXT(&marker, plinks.q);
291 unchanged = (m->queue == queue &&
292 m->object == object &&
293 &marker == TAILQ_NEXT(m, plinks.q));
294 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
299 * Lock the page while holding the page queue lock. Use marker page
300 * to detect page queue changes and maintain notion of next page on
301 * page queue. Return TRUE if no changes were detected, FALSE
302 * otherwise. The page is locked on return. The page queue lock might
303 * be dropped and reacquired.
305 * This function depends on normal struct vm_page being type stable.
308 vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
310 struct vm_page marker;
311 struct vm_pagequeue *pq;
315 vm_page_lock_assert(m, MA_NOTOWNED);
316 if (vm_page_trylock(m))
320 vm_pageout_init_marker(&marker, queue);
321 pq = vm_page_pagequeue(m);
323 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
324 vm_pagequeue_unlock(pq);
326 vm_pagequeue_lock(pq);
328 /* Page queue might have changed. */
329 *next = TAILQ_NEXT(&marker, plinks.q);
330 unchanged = (m->queue == queue && &marker == TAILQ_NEXT(m, plinks.q));
331 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
338 * Clean the page and remove it from the laundry.
340 * We set the busy bit to cause potential page faults on this page to
341 * block. Note the careful timing, however, the busy bit isn't set till
342 * late and we cannot do anything that will mess with the page.
345 vm_pageout_clean(vm_page_t m)
348 vm_page_t mc[2*vm_pageout_page_count], pb, ps;
350 int ib, is, page_base;
351 vm_pindex_t pindex = m->pindex;
353 vm_page_lock_assert(m, MA_OWNED);
355 VM_OBJECT_ASSERT_WLOCKED(object);
358 * It doesn't cost us anything to pageout OBJT_DEFAULT or OBJT_SWAP
359 * with the new swapper, but we could have serious problems paging
360 * out other object types if there is insufficient memory.
362 * Unfortunately, checking free memory here is far too late, so the
363 * check has been moved up a procedural level.
367 * Can't clean the page if it's busy or held.
369 vm_page_assert_unbusied(m);
370 KASSERT(m->hold_count == 0, ("vm_pageout_clean: page %p is held", m));
373 mc[vm_pageout_page_count] = pb = ps = m;
375 page_base = vm_pageout_page_count;
380 * Scan object for clusterable pages.
382 * We can cluster ONLY if: ->> the page is NOT
383 * clean, wired, busy, held, or mapped into a
384 * buffer, and one of the following:
385 * 1) The page is inactive, or a seldom used
388 * 2) we force the issue.
390 * During heavy mmap/modification loads the pageout
391 * daemon can really fragment the underlying file
392 * due to flushing pages out of order and not trying
393 * align the clusters (which leave sporatic out-of-order
394 * holes). To solve this problem we do the reverse scan
395 * first and attempt to align our cluster, then do a
396 * forward scan if room remains.
399 while (ib && pageout_count < vm_pageout_page_count) {
407 if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
411 vm_page_test_dirty(p);
417 if (p->queue != PQ_INACTIVE ||
418 p->hold_count != 0) { /* may be undergoing I/O */
424 mc[--page_base] = pb = p;
428 * alignment boundry, stop here and switch directions. Do
431 if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
435 while (pageout_count < vm_pageout_page_count &&
436 pindex + is < object->size) {
439 if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
441 vm_page_test_dirty(p);
445 if (p->queue != PQ_INACTIVE ||
446 p->hold_count != 0) { /* may be undergoing I/O */
451 mc[page_base + pageout_count] = ps = p;
457 * If we exhausted our forward scan, continue with the reverse scan
458 * when possible, even past a page boundry. This catches boundry
461 if (ib && pageout_count < vm_pageout_page_count)
465 * we allow reads during pageouts...
467 return (vm_pageout_flush(&mc[page_base], pageout_count, 0, 0, NULL,
472 * vm_pageout_flush() - launder the given pages
474 * The given pages are laundered. Note that we setup for the start of
475 * I/O ( i.e. busy the page ), mark it read-only, and bump the object
476 * reference count all in here rather then in the parent. If we want
477 * the parent to do more sophisticated things we may have to change
480 * Returned runlen is the count of pages between mreq and first
481 * page after mreq with status VM_PAGER_AGAIN.
482 * *eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
483 * for any page in runlen set.
486 vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
489 vm_object_t object = mc[0]->object;
490 int pageout_status[count];
494 VM_OBJECT_ASSERT_WLOCKED(object);
497 * Initiate I/O. Bump the vm_page_t->busy counter and
498 * mark the pages read-only.
500 * We do not have to fixup the clean/dirty bits here... we can
501 * allow the pager to do it after the I/O completes.
503 * NOTE! mc[i]->dirty may be partial or fragmented due to an
504 * edge case with file fragments.
506 for (i = 0; i < count; i++) {
507 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
508 ("vm_pageout_flush: partially invalid page %p index %d/%d",
510 vm_page_sbusy(mc[i]);
511 pmap_remove_write(mc[i]);
513 vm_object_pip_add(object, count);
515 vm_pager_put_pages(object, mc, count, flags, pageout_status);
517 runlen = count - mreq;
520 for (i = 0; i < count; i++) {
521 vm_page_t mt = mc[i];
523 KASSERT(pageout_status[i] == VM_PAGER_PEND ||
524 !pmap_page_is_write_mapped(mt),
525 ("vm_pageout_flush: page %p is not write protected", mt));
526 switch (pageout_status[i]) {
533 * Page outside of range of object. Right now we
534 * essentially lose the changes by pretending it
542 * If page couldn't be paged out, then reactivate the
543 * page so it doesn't clog the inactive list. (We
544 * will try paging out it again later).
547 vm_page_activate(mt);
549 if (eio != NULL && i >= mreq && i - mreq < runlen)
553 if (i >= mreq && i - mreq < runlen)
559 * If the operation is still going, leave the page busy to
560 * block all other accesses. Also, leave the paging in
561 * progress indicator set so that we don't attempt an object
564 if (pageout_status[i] != VM_PAGER_PEND) {
565 vm_object_pip_wakeup(object);
567 if (vm_page_count_severe()) {
569 vm_page_try_to_cache(mt);
576 return (numpagedout);
580 vm_pageout_launder(struct vm_pagequeue *pq, int tries, vm_paddr_t low,
587 vm_page_t m, m_tmp, next;
590 vm_pagequeue_lock(pq);
591 TAILQ_FOREACH_SAFE(m, &pq->pq_pl, plinks.q, next) {
592 if ((m->flags & PG_MARKER) != 0)
594 pa = VM_PAGE_TO_PHYS(m);
595 if (pa < low || pa + PAGE_SIZE > high)
597 if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
602 if ((!VM_OBJECT_TRYWLOCK(object) &&
603 (!vm_pageout_fallback_object_lock(m, &next) ||
604 m->hold_count != 0)) || vm_page_busied(m)) {
606 VM_OBJECT_WUNLOCK(object);
609 vm_page_test_dirty(m);
610 if (m->dirty == 0 && object->ref_count != 0)
614 if (tries == 0 || (object->flags & OBJ_DEAD) != 0) {
615 VM_OBJECT_WUNLOCK(object);
618 if (object->type == OBJT_VNODE) {
619 vm_pagequeue_unlock(pq);
621 vm_object_reference_locked(object);
622 VM_OBJECT_WUNLOCK(object);
623 (void)vn_start_write(vp, &mp, V_WAIT);
624 lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
625 LK_SHARED : LK_EXCLUSIVE;
626 vn_lock(vp, lockmode | LK_RETRY);
627 VM_OBJECT_WLOCK(object);
628 vm_object_page_clean(object, 0, 0, OBJPC_SYNC);
629 VM_OBJECT_WUNLOCK(object);
631 vm_object_deallocate(object);
632 vn_finished_write(mp);
634 } else if (object->type == OBJT_SWAP ||
635 object->type == OBJT_DEFAULT) {
636 vm_pagequeue_unlock(pq);
638 vm_pageout_flush(&m_tmp, 1, VM_PAGER_PUT_SYNC,
640 VM_OBJECT_WUNLOCK(object);
645 * Dequeue here to prevent lock recursion in
648 vm_page_dequeue_locked(m);
652 VM_OBJECT_WUNLOCK(object);
654 vm_pagequeue_unlock(pq);
659 * Increase the number of cached pages. The specified value, "tries",
660 * determines which categories of pages are cached:
662 * 0: All clean, inactive pages within the specified physical address range
663 * are cached. Will not sleep.
664 * 1: The vm_lowmem handlers are called. All inactive pages within
665 * the specified physical address range are cached. May sleep.
666 * 2: The vm_lowmem handlers are called. All inactive and active pages
667 * within the specified physical address range are cached. May sleep.
670 vm_pageout_grow_cache(int tries, vm_paddr_t low, vm_paddr_t high)
672 int actl, actmax, inactl, inactmax, dom, initial_dom;
673 static int start_dom = 0;
677 * Decrease registered cache sizes. The vm_lowmem handlers
678 * may acquire locks and/or sleep, so they can only be invoked
679 * when "tries" is greater than zero.
681 SDT_PROBE0(vm, , , vm__lowmem_cache);
682 EVENTHANDLER_INVOKE(vm_lowmem, 0);
685 * We do this explicitly after the caches have been drained
692 * Make the next scan start on the next domain.
694 initial_dom = atomic_fetchadd_int(&start_dom, 1) % vm_ndomains;
697 inactmax = cnt.v_inactive_count;
699 actmax = tries < 2 ? 0 : cnt.v_active_count;
703 * Scan domains in round-robin order, first inactive queues,
704 * then active. Since domain usually owns large physically
705 * contiguous chunk of memory, it makes sense to completely
706 * exhaust one domain before switching to next, while growing
707 * the pool of contiguous physical pages.
709 * Do not even start launder a domain which cannot contain
710 * the specified address range, as indicated by segments
711 * constituting the domain.
714 if (inactl < inactmax) {
715 if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
717 vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_INACTIVE],
722 if (++dom == vm_ndomains)
724 if (dom != initial_dom)
728 if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
730 vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_ACTIVE],
735 if (++dom == vm_ndomains)
737 if (dom != initial_dom)
742 #if !defined(NO_SWAPPING)
744 * vm_pageout_object_deactivate_pages
746 * Deactivate enough pages to satisfy the inactive target
749 * The object and map must be locked.
752 vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
755 vm_object_t backing_object, object;
757 int act_delta, remove_mode;
759 VM_OBJECT_ASSERT_LOCKED(first_object);
760 if ((first_object->flags & OBJ_FICTITIOUS) != 0)
762 for (object = first_object;; object = backing_object) {
763 if (pmap_resident_count(pmap) <= desired)
765 VM_OBJECT_ASSERT_LOCKED(object);
766 if ((object->flags & OBJ_UNMANAGED) != 0 ||
767 object->paging_in_progress != 0)
771 if (object->shadow_count > 1)
774 * Scan the object's entire memory queue.
776 TAILQ_FOREACH(p, &object->memq, listq) {
777 if (pmap_resident_count(pmap) <= desired)
779 if (vm_page_busied(p))
781 PCPU_INC(cnt.v_pdpages);
783 if (p->wire_count != 0 || p->hold_count != 0 ||
784 !pmap_page_exists_quick(pmap, p)) {
788 act_delta = pmap_ts_referenced(p);
789 if ((p->aflags & PGA_REFERENCED) != 0) {
792 vm_page_aflag_clear(p, PGA_REFERENCED);
794 if (p->queue != PQ_ACTIVE && act_delta != 0) {
796 p->act_count += act_delta;
797 } else if (p->queue == PQ_ACTIVE) {
798 if (act_delta == 0) {
799 p->act_count -= min(p->act_count,
801 if (!remove_mode && p->act_count == 0) {
803 vm_page_deactivate(p);
808 if (p->act_count < ACT_MAX -
810 p->act_count += ACT_ADVANCE;
813 } else if (p->queue == PQ_INACTIVE)
817 if ((backing_object = object->backing_object) == NULL)
819 VM_OBJECT_RLOCK(backing_object);
820 if (object != first_object)
821 VM_OBJECT_RUNLOCK(object);
824 if (object != first_object)
825 VM_OBJECT_RUNLOCK(object);
829 * deactivate some number of pages in a map, try to do it fairly, but
830 * that is really hard to do.
833 vm_pageout_map_deactivate_pages(map, desired)
838 vm_object_t obj, bigobj;
841 if (!vm_map_trylock(map))
848 * first, search out the biggest object, and try to free pages from
851 tmpe = map->header.next;
852 while (tmpe != &map->header) {
853 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
854 obj = tmpe->object.vm_object;
855 if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
856 if (obj->shadow_count <= 1 &&
858 bigobj->resident_page_count < obj->resident_page_count)) {
860 VM_OBJECT_RUNLOCK(bigobj);
863 VM_OBJECT_RUNLOCK(obj);
866 if (tmpe->wired_count > 0)
867 nothingwired = FALSE;
871 if (bigobj != NULL) {
872 vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
873 VM_OBJECT_RUNLOCK(bigobj);
876 * Next, hunt around for other pages to deactivate. We actually
877 * do this search sort of wrong -- .text first is not the best idea.
879 tmpe = map->header.next;
880 while (tmpe != &map->header) {
881 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
883 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
884 obj = tmpe->object.vm_object;
886 VM_OBJECT_RLOCK(obj);
887 vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
888 VM_OBJECT_RUNLOCK(obj);
896 * Remove all non-wired, managed mappings if a process is swapped out.
897 * This will free page table pages.
900 pmap_remove_pages(map->pmap);
903 * Remove all mappings if a process is swapped out, this will free page
906 if (desired == 0 && nothingwired) {
907 pmap_remove(vm_map_pmap(map), vm_map_min(map),
914 #endif /* !defined(NO_SWAPPING) */
917 * vm_pageout_scan does the dirty work for the pageout daemon.
919 * pass 0 - Update active LRU/deactivate pages
920 * pass 1 - Move inactive to cache or free
921 * pass 2 - Launder dirty pages
924 vm_pageout_scan(struct vm_domain *vmd, int pass)
927 struct vm_pagequeue *pq;
930 int act_delta, addl_page_shortage, deficit, maxscan, page_shortage;
931 int vnodes_skipped = 0;
932 int maxlaunder, scan_tick, scanned;
934 boolean_t queues_locked;
937 * If we need to reclaim memory ask kernel caches to return
938 * some. We rate limit to avoid thrashing.
940 if (vmd == &vm_dom[0] && pass > 0 &&
941 (time_uptime - lowmem_uptime) >= lowmem_period) {
943 * Decrease registered cache sizes.
945 SDT_PROBE0(vm, , , vm__lowmem_scan);
946 EVENTHANDLER_INVOKE(vm_lowmem, 0);
948 * We do this explicitly after the caches have been
952 lowmem_uptime = time_uptime;
956 * The addl_page_shortage is the number of temporarily
957 * stuck pages in the inactive queue. In other words, the
958 * number of pages from the inactive count that should be
959 * discounted in setting the target for the active queue scan.
961 addl_page_shortage = 0;
964 * Calculate the number of pages we want to either free or move
968 deficit = atomic_readandclear_int(&vm_pageout_deficit);
969 page_shortage = vm_paging_target() + deficit;
971 page_shortage = deficit = 0;
974 * maxlaunder limits the number of dirty pages we flush per scan.
975 * For most systems a smaller value (16 or 32) is more robust under
976 * extreme memory and disk pressure because any unnecessary writes
977 * to disk can result in extreme performance degredation. However,
978 * systems with excessive dirty pages (especially when MAP_NOSYNC is
979 * used) will die horribly with limited laundering. If the pageout
980 * daemon cannot clean enough pages in the first pass, we let it go
981 * all out in succeeding passes.
983 if ((maxlaunder = vm_max_launder) <= 1)
989 * Start scanning the inactive queue for pages we can move to the
990 * cache or free. The scan will stop when the target is reached or
991 * we have scanned the entire inactive queue. Note that m->act_count
992 * is not used to form decisions for the inactive queue, only for the
995 pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
996 maxscan = pq->pq_cnt;
997 vm_pagequeue_lock(pq);
998 queues_locked = TRUE;
999 for (m = TAILQ_FIRST(&pq->pq_pl);
1000 m != NULL && maxscan-- > 0 && page_shortage > 0;
1002 vm_pagequeue_assert_locked(pq);
1003 KASSERT(queues_locked, ("unlocked queues"));
1004 KASSERT(m->queue == PQ_INACTIVE, ("Inactive queue %p", m));
1006 PCPU_INC(cnt.v_pdpages);
1007 next = TAILQ_NEXT(m, plinks.q);
1012 if (m->flags & PG_MARKER)
1015 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1016 ("Fictitious page %p cannot be in inactive queue", m));
1017 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1018 ("Unmanaged page %p cannot be in inactive queue", m));
1021 * The page or object lock acquisitions fail if the
1022 * page was removed from the queue or moved to a
1023 * different position within the queue. In either
1024 * case, addl_page_shortage should not be incremented.
1026 if (!vm_pageout_page_lock(m, &next)) {
1031 if (!VM_OBJECT_TRYWLOCK(object) &&
1032 !vm_pageout_fallback_object_lock(m, &next)) {
1034 VM_OBJECT_WUNLOCK(object);
1039 * Don't mess with busy pages, keep them at at the
1040 * front of the queue, most likely they are being
1041 * paged out. Increment addl_page_shortage for busy
1042 * pages, because they may leave the inactive queue
1043 * shortly after page scan is finished.
1045 if (vm_page_busied(m)) {
1047 VM_OBJECT_WUNLOCK(object);
1048 addl_page_shortage++;
1053 * We unlock the inactive page queue, invalidating the
1054 * 'next' pointer. Use our marker to remember our
1057 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
1058 vm_pagequeue_unlock(pq);
1059 queues_locked = FALSE;
1062 * We bump the activation count if the page has been
1063 * referenced while in the inactive queue. This makes
1064 * it less likely that the page will be added back to the
1065 * inactive queue prematurely again. Here we check the
1066 * page tables (or emulated bits, if any), given the upper
1067 * level VM system not knowing anything about existing
1071 if ((m->aflags & PGA_REFERENCED) != 0) {
1072 vm_page_aflag_clear(m, PGA_REFERENCED);
1075 if (object->ref_count != 0) {
1076 act_delta += pmap_ts_referenced(m);
1078 KASSERT(!pmap_page_is_mapped(m),
1079 ("vm_pageout_scan: page %p is mapped", m));
1083 * If the upper level VM system knows about any page
1084 * references, we reactivate the page or requeue it.
1086 if (act_delta != 0) {
1087 if (object->ref_count) {
1088 vm_page_activate(m);
1089 m->act_count += act_delta + ACT_ADVANCE;
1091 vm_pagequeue_lock(pq);
1092 queues_locked = TRUE;
1093 vm_page_requeue_locked(m);
1095 VM_OBJECT_WUNLOCK(object);
1100 if (m->hold_count != 0) {
1102 VM_OBJECT_WUNLOCK(object);
1105 * Held pages are essentially stuck in the
1106 * queue. So, they ought to be discounted
1107 * from the inactive count. See the
1108 * calculation of the page_shortage for the
1109 * loop over the active queue below.
1111 addl_page_shortage++;
1116 * If the page appears to be clean at the machine-independent
1117 * layer, then remove all of its mappings from the pmap in
1118 * anticipation of placing it onto the cache queue. If,
1119 * however, any of the page's mappings allow write access,
1120 * then the page may still be modified until the last of those
1121 * mappings are removed.
1123 if (object->ref_count != 0) {
1124 vm_page_test_dirty(m);
1129 if (m->valid == 0) {
1131 * Invalid pages can be easily freed
1134 PCPU_INC(cnt.v_dfree);
1136 } else if (m->dirty == 0) {
1138 * Clean pages can be placed onto the cache queue.
1139 * This effectively frees them.
1143 } else if ((m->flags & PG_WINATCFLS) == 0 && pass < 2) {
1145 * Dirty pages need to be paged out, but flushing
1146 * a page is extremely expensive verses freeing
1147 * a clean page. Rather then artificially limiting
1148 * the number of pages we can flush, we instead give
1149 * dirty pages extra priority on the inactive queue
1150 * by forcing them to be cycled through the queue
1151 * twice before being flushed, after which the
1152 * (now clean) page will cycle through once more
1153 * before being freed. This significantly extends
1154 * the thrash point for a heavily loaded machine.
1156 m->flags |= PG_WINATCFLS;
1157 vm_pagequeue_lock(pq);
1158 queues_locked = TRUE;
1159 vm_page_requeue_locked(m);
1160 } else if (maxlaunder > 0) {
1162 * We always want to try to flush some dirty pages if
1163 * we encounter them, to keep the system stable.
1164 * Normally this number is small, but under extreme
1165 * pressure where there are insufficient clean pages
1166 * on the inactive queue, we may have to go all out.
1168 int swap_pageouts_ok;
1169 struct vnode *vp = NULL;
1170 struct mount *mp = NULL;
1172 if ((object->type != OBJT_SWAP) && (object->type != OBJT_DEFAULT)) {
1173 swap_pageouts_ok = 1;
1175 swap_pageouts_ok = !(defer_swap_pageouts || disable_swap_pageouts);
1176 swap_pageouts_ok |= (!disable_swap_pageouts && defer_swap_pageouts &&
1177 vm_page_count_min());
1182 * We don't bother paging objects that are "dead".
1183 * Those objects are in a "rundown" state.
1185 if (!swap_pageouts_ok || (object->flags & OBJ_DEAD)) {
1186 vm_pagequeue_lock(pq);
1188 VM_OBJECT_WUNLOCK(object);
1189 queues_locked = TRUE;
1190 vm_page_requeue_locked(m);
1195 * The object is already known NOT to be dead. It
1196 * is possible for the vget() to block the whole
1197 * pageout daemon, but the new low-memory handling
1198 * code should prevent it.
1200 * The previous code skipped locked vnodes and, worse,
1201 * reordered pages in the queue. This results in
1202 * completely non-deterministic operation and, on a
1203 * busy system, can lead to extremely non-optimal
1204 * pageouts. For example, it can cause clean pages
1205 * to be freed and dirty pages to be moved to the end
1206 * of the queue. Since dirty pages are also moved to
1207 * the end of the queue once-cleaned, this gives
1208 * way too large a weighting to defering the freeing
1211 * We can't wait forever for the vnode lock, we might
1212 * deadlock due to a vn_read() getting stuck in
1213 * vm_wait while holding this vnode. We skip the
1214 * vnode if we can't get it in a reasonable amount
1217 if (object->type == OBJT_VNODE) {
1219 vp = object->handle;
1220 if (vp->v_type == VREG &&
1221 vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1223 ++pageout_lock_miss;
1224 if (object->flags & OBJ_MIGHTBEDIRTY)
1226 goto unlock_and_continue;
1229 ("vp %p with NULL v_mount", vp));
1230 vm_object_reference_locked(object);
1231 VM_OBJECT_WUNLOCK(object);
1232 lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
1233 LK_SHARED : LK_EXCLUSIVE;
1234 if (vget(vp, lockmode | LK_TIMELOCK,
1236 VM_OBJECT_WLOCK(object);
1237 ++pageout_lock_miss;
1238 if (object->flags & OBJ_MIGHTBEDIRTY)
1241 goto unlock_and_continue;
1243 VM_OBJECT_WLOCK(object);
1245 vm_pagequeue_lock(pq);
1246 queues_locked = TRUE;
1248 * The page might have been moved to another
1249 * queue during potential blocking in vget()
1250 * above. The page might have been freed and
1251 * reused for another vnode.
1253 if (m->queue != PQ_INACTIVE ||
1254 m->object != object ||
1255 TAILQ_NEXT(m, plinks.q) != &vmd->vmd_marker) {
1257 if (object->flags & OBJ_MIGHTBEDIRTY)
1259 goto unlock_and_continue;
1263 * The page may have been busied during the
1264 * blocking in vget(). We don't move the
1265 * page back onto the end of the queue so that
1266 * statistics are more correct if we don't.
1268 if (vm_page_busied(m)) {
1270 addl_page_shortage++;
1271 goto unlock_and_continue;
1275 * If the page has become held it might
1276 * be undergoing I/O, so skip it
1278 if (m->hold_count != 0) {
1280 addl_page_shortage++;
1281 if (object->flags & OBJ_MIGHTBEDIRTY)
1283 goto unlock_and_continue;
1285 vm_pagequeue_unlock(pq);
1286 queues_locked = FALSE;
1290 * If a page is dirty, then it is either being washed
1291 * (but not yet cleaned) or it is still in the
1292 * laundry. If it is still in the laundry, then we
1293 * start the cleaning operation.
1295 * decrement page_shortage on success to account for
1296 * the (future) cleaned page. Otherwise we could wind
1297 * up laundering or cleaning too many pages.
1299 if (vm_pageout_clean(m) != 0) {
1303 unlock_and_continue:
1304 vm_page_lock_assert(m, MA_NOTOWNED);
1305 VM_OBJECT_WUNLOCK(object);
1307 if (queues_locked) {
1308 vm_pagequeue_unlock(pq);
1309 queues_locked = FALSE;
1313 vm_object_deallocate(object);
1314 vn_finished_write(mp);
1316 vm_page_lock_assert(m, MA_NOTOWNED);
1320 VM_OBJECT_WUNLOCK(object);
1322 if (!queues_locked) {
1323 vm_pagequeue_lock(pq);
1324 queues_locked = TRUE;
1326 next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1327 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
1329 vm_pagequeue_unlock(pq);
1331 #if !defined(NO_SWAPPING)
1333 * Wakeup the swapout daemon if we didn't cache or free the targeted
1336 if (vm_swap_enabled && page_shortage > 0)
1337 vm_req_vmdaemon(VM_SWAP_NORMAL);
1341 * Wakeup the sync daemon if we skipped a vnode in a writeable object
1342 * and we didn't cache or free enough pages.
1344 if (vnodes_skipped > 0 && page_shortage > cnt.v_free_target -
1346 (void)speedup_syncer();
1349 * Compute the number of pages we want to try to move from the
1350 * active queue to the inactive queue.
1352 page_shortage = cnt.v_inactive_target - cnt.v_inactive_count +
1353 vm_paging_target() + deficit + addl_page_shortage;
1355 pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1356 vm_pagequeue_lock(pq);
1357 maxscan = pq->pq_cnt;
1360 * If we're just idle polling attempt to visit every
1361 * active page within 'update_period' seconds.
1364 if (vm_pageout_update_period != 0) {
1365 min_scan = pq->pq_cnt;
1366 min_scan *= scan_tick - vmd->vmd_last_active_scan;
1367 min_scan /= hz * vm_pageout_update_period;
1370 if (min_scan > 0 || (page_shortage > 0 && maxscan > 0))
1371 vmd->vmd_last_active_scan = scan_tick;
1374 * Scan the active queue for pages that can be deactivated. Update
1375 * the per-page activity counter and use it to identify deactivation
1378 for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
1379 min_scan || (page_shortage > 0 && scanned < maxscan)); m = next,
1382 KASSERT(m->queue == PQ_ACTIVE,
1383 ("vm_pageout_scan: page %p isn't active", m));
1385 next = TAILQ_NEXT(m, plinks.q);
1386 if ((m->flags & PG_MARKER) != 0)
1388 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1389 ("Fictitious page %p cannot be in active queue", m));
1390 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1391 ("Unmanaged page %p cannot be in active queue", m));
1392 if (!vm_pageout_page_lock(m, &next)) {
1398 * The count for pagedaemon pages is done after checking the
1399 * page for eligibility...
1401 PCPU_INC(cnt.v_pdpages);
1404 * Check to see "how much" the page has been used.
1407 if (m->aflags & PGA_REFERENCED) {
1408 vm_page_aflag_clear(m, PGA_REFERENCED);
1412 * Unlocked object ref count check. Two races are possible.
1413 * 1) The ref was transitioning to zero and we saw non-zero,
1414 * the pmap bits will be checked unnecessarily.
1415 * 2) The ref was transitioning to one and we saw zero.
1416 * The page lock prevents a new reference to this page so
1417 * we need not check the reference bits.
1419 if (m->object->ref_count != 0)
1420 act_delta += pmap_ts_referenced(m);
1423 * Advance or decay the act_count based on recent usage.
1426 m->act_count += ACT_ADVANCE + act_delta;
1427 if (m->act_count > ACT_MAX)
1428 m->act_count = ACT_MAX;
1430 m->act_count -= min(m->act_count, ACT_DECLINE);
1431 act_delta = m->act_count;
1435 * Move this page to the tail of the active or inactive
1436 * queue depending on usage.
1438 if (act_delta == 0) {
1439 /* Dequeue to avoid later lock recursion. */
1440 vm_page_dequeue_locked(m);
1441 vm_page_deactivate(m);
1444 vm_page_requeue_locked(m);
1447 vm_pagequeue_unlock(pq);
1448 #if !defined(NO_SWAPPING)
1450 * Idle process swapout -- run once per second.
1452 if (vm_swap_idle_enabled) {
1454 if (time_second != lsec) {
1455 vm_req_vmdaemon(VM_SWAP_IDLE);
1462 * If we are critically low on one of RAM or swap and low on
1463 * the other, kill the largest process. However, we avoid
1464 * doing this on the first pass in order to give ourselves a
1465 * chance to flush out dirty vnode-backed pages and to allow
1466 * active pages to be moved to the inactive queue and reclaimed.
1468 vm_pageout_mightbe_oom(vmd, pass);
1471 static int vm_pageout_oom_vote;
1474 * The pagedaemon threads randlomly select one to perform the
1475 * OOM. Trying to kill processes before all pagedaemons
1476 * failed to reach free target is premature.
1479 vm_pageout_mightbe_oom(struct vm_domain *vmd, int pass)
1483 if (pass <= 1 || !((swap_pager_avail < 64 && vm_page_count_min()) ||
1484 (swap_pager_full && vm_paging_target() > 0))) {
1486 vmd->vmd_oom = FALSE;
1487 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1495 vmd->vmd_oom = TRUE;
1496 old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1497 if (old_vote != vm_ndomains - 1)
1501 * The current pagedaemon thread is the last in the quorum to
1502 * start OOM. Initiate the selection and signaling of the
1505 vm_pageout_oom(VM_OOM_MEM);
1508 * After one round of OOM terror, recall our vote. On the
1509 * next pass, current pagedaemon would vote again if the low
1510 * memory condition is still there, due to vmd_oom being
1513 vmd->vmd_oom = FALSE;
1514 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1518 vm_pageout_oom(int shortage)
1520 struct proc *p, *bigproc;
1521 vm_offset_t size, bigsize;
1526 * We keep the process bigproc locked once we find it to keep anyone
1527 * from messing with it; however, there is a possibility of
1528 * deadlock if process B is bigproc and one of it's child processes
1529 * attempts to propagate a signal to B while we are waiting for A's
1530 * lock while walking this list. To avoid this, we don't block on
1531 * the process lock but just skip a process if it is already locked.
1535 sx_slock(&allproc_lock);
1536 FOREACH_PROC_IN_SYSTEM(p) {
1542 * If this is a system, protected or killed process, skip it.
1544 if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
1545 P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
1546 p->p_pid == 1 || P_KILLED(p) ||
1547 (p->p_pid < 48 && swap_pager_avail != 0)) {
1552 * If the process is in a non-running type state,
1553 * don't touch it. Check all the threads individually.
1556 FOREACH_THREAD_IN_PROC(p, td) {
1558 if (!TD_ON_RUNQ(td) &&
1559 !TD_IS_RUNNING(td) &&
1560 !TD_IS_SLEEPING(td) &&
1561 !TD_IS_SUSPENDED(td)) {
1573 * get the process size
1575 vm = vmspace_acquire_ref(p);
1581 if (!vm_map_trylock_read(&vm->vm_map)) {
1588 size = vmspace_swap_count(vm);
1589 vm_map_unlock_read(&vm->vm_map);
1590 if (shortage == VM_OOM_MEM)
1591 size += vmspace_resident_count(vm);
1594 * if the this process is bigger than the biggest one
1597 if (size > bigsize) {
1598 if (bigproc != NULL)
1606 sx_sunlock(&allproc_lock);
1607 if (bigproc != NULL) {
1609 killproc(bigproc, "out of swap space");
1610 sched_nice(bigproc, PRIO_MIN);
1612 PROC_UNLOCK(bigproc);
1613 wakeup(&cnt.v_free_count);
1618 vm_pageout_worker(void *arg)
1620 struct vm_domain *domain;
1623 domidx = (uintptr_t)arg;
1624 domain = &vm_dom[domidx];
1627 * XXXKIB It could be useful to bind pageout daemon threads to
1628 * the cores belonging to the domain, from which vm_page_array
1632 KASSERT(domain->vmd_segs != 0, ("domain without segments"));
1633 domain->vmd_last_active_scan = ticks;
1634 vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
1637 * The pageout daemon worker is never done, so loop forever.
1641 * If we have enough free memory, wakeup waiters. Do
1642 * not clear vm_pages_needed until we reach our target,
1643 * otherwise we may be woken up over and over again and
1644 * waste a lot of cpu.
1646 mtx_lock(&vm_page_queue_free_mtx);
1647 if (vm_pages_needed && !vm_page_count_min()) {
1648 if (!vm_paging_needed())
1649 vm_pages_needed = 0;
1650 wakeup(&cnt.v_free_count);
1652 if (vm_pages_needed) {
1654 * We're still not done. Either vm_pages_needed was
1655 * set by another thread during the previous scan
1656 * (typically, this happens during a level 0 scan) or
1657 * vm_pages_needed was already set and the scan failed
1658 * to free enough pages. If we haven't yet performed
1659 * a level >= 2 scan (unlimited dirty cleaning), then
1660 * upgrade the level and scan again now. Otherwise,
1661 * sleep a bit and try again later. While sleeping,
1662 * vm_pages_needed can be cleared.
1664 if (domain->vmd_pass > 1)
1665 msleep(&vm_pages_needed,
1666 &vm_page_queue_free_mtx, PVM, "psleep",
1670 * Good enough, sleep until required to refresh
1673 msleep(&vm_pages_needed, &vm_page_queue_free_mtx,
1676 if (vm_pages_needed) {
1680 domain->vmd_pass = 0;
1681 mtx_unlock(&vm_page_queue_free_mtx);
1682 vm_pageout_scan(domain, domain->vmd_pass);
1687 * vm_pageout_init initialises basic pageout daemon settings.
1690 vm_pageout_init(void)
1693 * Initialize some paging parameters.
1695 cnt.v_interrupt_free_min = 2;
1696 if (cnt.v_page_count < 2000)
1697 vm_pageout_page_count = 8;
1700 * v_free_reserved needs to include enough for the largest
1701 * swap pager structures plus enough for any pv_entry structs
1704 if (cnt.v_page_count > 1024)
1705 cnt.v_free_min = 4 + (cnt.v_page_count - 1024) / 200;
1708 cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1709 cnt.v_interrupt_free_min;
1710 cnt.v_free_reserved = vm_pageout_page_count +
1711 cnt.v_pageout_free_min + (cnt.v_page_count / 768);
1712 cnt.v_free_severe = cnt.v_free_min / 2;
1713 cnt.v_free_target = 4 * cnt.v_free_min + cnt.v_free_reserved;
1714 cnt.v_free_min += cnt.v_free_reserved;
1715 cnt.v_free_severe += cnt.v_free_reserved;
1716 cnt.v_inactive_target = (3 * cnt.v_free_target) / 2;
1717 if (cnt.v_inactive_target > cnt.v_free_count / 3)
1718 cnt.v_inactive_target = cnt.v_free_count / 3;
1721 * Set the default wakeup threshold to be 10% above the minimum
1722 * page limit. This keeps the steady state out of shortfall.
1724 vm_pageout_wakeup_thresh = (cnt.v_free_min / 10) * 11;
1727 * Set interval in seconds for active scan. We want to visit each
1728 * page at least once every ten minutes. This is to prevent worst
1729 * case paging behaviors with stale active LRU.
1731 if (vm_pageout_update_period == 0)
1732 vm_pageout_update_period = 600;
1734 /* XXX does not really belong here */
1735 if (vm_page_max_wired == 0)
1736 vm_page_max_wired = cnt.v_free_count / 3;
1740 * vm_pageout is the high level pageout daemon.
1750 swap_pager_swap_init();
1752 for (i = 1; i < vm_ndomains; i++) {
1753 error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
1754 curproc, NULL, 0, 0, "dom%d", i);
1756 panic("starting pageout for domain %d, error %d\n",
1761 error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
1764 panic("starting uma_reclaim helper, error %d\n", error);
1765 vm_pageout_worker((void *)(uintptr_t)0);
1769 * Unless the free page queue lock is held by the caller, this function
1770 * should be regarded as advisory. Specifically, the caller should
1771 * not msleep() on &cnt.v_free_count following this function unless
1772 * the free page queue lock is held until the msleep() is performed.
1775 pagedaemon_wakeup(void)
1778 if (!vm_pages_needed && curthread->td_proc != pageproc) {
1779 vm_pages_needed = 1;
1780 wakeup(&vm_pages_needed);
1784 #if !defined(NO_SWAPPING)
1786 vm_req_vmdaemon(int req)
1788 static int lastrun = 0;
1790 mtx_lock(&vm_daemon_mtx);
1791 vm_pageout_req_swapout |= req;
1792 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
1793 wakeup(&vm_daemon_needed);
1796 mtx_unlock(&vm_daemon_mtx);
1802 struct rlimit rsslim;
1806 int breakout, swapout_flags, tryagain, attempts;
1808 uint64_t rsize, ravailable;
1812 mtx_lock(&vm_daemon_mtx);
1813 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
1815 racct_enable ? hz : 0
1820 swapout_flags = vm_pageout_req_swapout;
1821 vm_pageout_req_swapout = 0;
1822 mtx_unlock(&vm_daemon_mtx);
1824 swapout_procs(swapout_flags);
1827 * scan the processes for exceeding their rlimits or if
1828 * process is swapped out -- deactivate pages
1834 sx_slock(&allproc_lock);
1835 FOREACH_PROC_IN_SYSTEM(p) {
1836 vm_pindex_t limit, size;
1839 * if this is a system process or if we have already
1840 * looked at this process, skip it.
1843 if (p->p_state != PRS_NORMAL ||
1844 p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
1849 * if the process is in a non-running type state,
1853 FOREACH_THREAD_IN_PROC(p, td) {
1855 if (!TD_ON_RUNQ(td) &&
1856 !TD_IS_RUNNING(td) &&
1857 !TD_IS_SLEEPING(td) &&
1858 !TD_IS_SUSPENDED(td)) {
1872 lim_rlimit(p, RLIMIT_RSS, &rsslim);
1874 qmin(rsslim.rlim_cur, rsslim.rlim_max));
1877 * let processes that are swapped out really be
1878 * swapped out set the limit to nothing (will force a
1881 if ((p->p_flag & P_INMEM) == 0)
1882 limit = 0; /* XXX */
1883 vm = vmspace_acquire_ref(p);
1888 size = vmspace_resident_count(vm);
1889 if (size >= limit) {
1890 vm_pageout_map_deactivate_pages(
1891 &vm->vm_map, limit);
1895 rsize = IDX_TO_OFF(size);
1897 racct_set(p, RACCT_RSS, rsize);
1898 ravailable = racct_get_available(p, RACCT_RSS);
1900 if (rsize > ravailable) {
1902 * Don't be overly aggressive; this
1903 * might be an innocent process,
1904 * and the limit could've been exceeded
1905 * by some memory hog. Don't try
1906 * to deactivate more than 1/4th
1907 * of process' resident set size.
1909 if (attempts <= 8) {
1910 if (ravailable < rsize -
1912 ravailable = rsize -
1916 vm_pageout_map_deactivate_pages(
1918 OFF_TO_IDX(ravailable));
1919 /* Update RSS usage after paging out. */
1920 size = vmspace_resident_count(vm);
1921 rsize = IDX_TO_OFF(size);
1923 racct_set(p, RACCT_RSS, rsize);
1925 if (rsize > ravailable)
1932 sx_sunlock(&allproc_lock);
1933 if (tryagain != 0 && attempts <= 10)
1937 #endif /* !defined(NO_SWAPPING) */