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 <sys/param.h>
80 #include <sys/systm.h>
81 #include <sys/kernel.h>
82 #include <sys/eventhandler.h>
84 #include <sys/mutex.h>
86 #include <sys/kthread.h>
88 #include <sys/mount.h>
89 #include <sys/resourcevar.h>
90 #include <sys/sched.h>
91 #include <sys/signalvar.h>
92 #include <sys/vnode.h>
93 #include <sys/vmmeter.h>
95 #include <sys/sysctl.h>
98 #include <vm/vm_param.h>
99 #include <vm/vm_object.h>
100 #include <vm/vm_page.h>
101 #include <vm/vm_map.h>
102 #include <vm/vm_pageout.h>
103 #include <vm/vm_pager.h>
104 #include <vm/swap_pager.h>
105 #include <vm/vm_extern.h>
109 * System initialization
112 /* the kernel process "vm_pageout"*/
113 static void vm_pageout(void);
114 static int vm_pageout_clean(vm_page_t);
115 static void vm_pageout_scan(int pass);
117 struct proc *pageproc;
119 static struct kproc_desc page_kp = {
124 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, kproc_start,
127 #if !defined(NO_SWAPPING)
128 /* the kernel process "vm_daemon"*/
129 static void vm_daemon(void);
130 static struct proc *vmproc;
132 static struct kproc_desc vm_kp = {
137 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
141 int vm_pages_needed; /* Event on which pageout daemon sleeps */
142 int vm_pageout_deficit; /* Estimated number of pages deficit */
143 int vm_pageout_pages_needed; /* flag saying that the pageout daemon needs pages */
145 #if !defined(NO_SWAPPING)
146 static int vm_pageout_req_swapout; /* XXX */
147 static int vm_daemon_needed;
148 static struct mtx vm_daemon_mtx;
149 /* Allow for use by vm_pageout before vm_daemon is initialized. */
150 MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
152 static int vm_max_launder = 32;
153 static int vm_pageout_stats_max=0, vm_pageout_stats_interval = 0;
154 static int vm_pageout_full_stats_interval = 0;
155 static int vm_pageout_algorithm=0;
156 static int defer_swap_pageouts=0;
157 static int disable_swap_pageouts=0;
159 #if defined(NO_SWAPPING)
160 static int vm_swap_enabled=0;
161 static int vm_swap_idle_enabled=0;
163 static int vm_swap_enabled=1;
164 static int vm_swap_idle_enabled=0;
167 SYSCTL_INT(_vm, VM_PAGEOUT_ALGORITHM, pageout_algorithm,
168 CTLFLAG_RW, &vm_pageout_algorithm, 0, "LRU page mgmt");
170 SYSCTL_INT(_vm, OID_AUTO, max_launder,
171 CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
173 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_max,
174 CTLFLAG_RW, &vm_pageout_stats_max, 0, "Max pageout stats scan length");
176 SYSCTL_INT(_vm, OID_AUTO, pageout_full_stats_interval,
177 CTLFLAG_RW, &vm_pageout_full_stats_interval, 0, "Interval for full stats scan");
179 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_interval,
180 CTLFLAG_RW, &vm_pageout_stats_interval, 0, "Interval for partial stats scan");
182 #if defined(NO_SWAPPING)
183 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
184 CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout");
185 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
186 CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
188 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
189 CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
190 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
191 CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
194 SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
195 CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
197 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
198 CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
200 static int pageout_lock_miss;
201 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
202 CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
204 #define VM_PAGEOUT_PAGE_COUNT 16
205 int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
207 int vm_page_max_wired; /* XXX max # of wired pages system-wide */
208 SYSCTL_INT(_vm, OID_AUTO, max_wired,
209 CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
211 #if !defined(NO_SWAPPING)
212 static void vm_pageout_map_deactivate_pages(vm_map_t, long);
213 static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
214 static void vm_req_vmdaemon(int req);
216 static void vm_pageout_page_stats(void);
219 * vm_pageout_fallback_object_lock:
221 * Lock vm object currently associated with `m'. VM_OBJECT_TRYLOCK is
222 * known to have failed and page queue must be either PQ_ACTIVE or
223 * PQ_INACTIVE. To avoid lock order violation, unlock the page queues
224 * while locking the vm object. Use marker page to detect page queue
225 * changes and maintain notion of next page on page queue. Return
226 * TRUE if no changes were detected, FALSE otherwise. vm object is
229 * This function depends on both the lock portion of struct vm_object
230 * and normal struct vm_page being type stable.
233 vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
235 struct vm_page marker;
241 * Initialize our marker
243 bzero(&marker, sizeof(marker));
244 marker.flags = PG_FICTITIOUS | PG_MARKER;
245 marker.oflags = VPO_BUSY;
246 marker.queue = m->queue;
247 marker.wire_count = 1;
252 TAILQ_INSERT_AFTER(&vm_page_queues[queue].pl,
254 vm_page_unlock_queues();
255 VM_OBJECT_LOCK(object);
256 vm_page_lock_queues();
258 /* Page queue might have changed. */
259 *next = TAILQ_NEXT(&marker, pageq);
260 unchanged = (m->queue == queue &&
261 m->object == object &&
262 &marker == TAILQ_NEXT(m, pageq));
263 TAILQ_REMOVE(&vm_page_queues[queue].pl,
271 * Clean the page and remove it from the laundry.
273 * We set the busy bit to cause potential page faults on this page to
274 * block. Note the careful timing, however, the busy bit isn't set till
275 * late and we cannot do anything that will mess with the page.
282 vm_page_t mc[2*vm_pageout_page_count], pb, ps;
284 int ib, is, page_base;
285 vm_pindex_t pindex = m->pindex;
287 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
288 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
291 * It doesn't cost us anything to pageout OBJT_DEFAULT or OBJT_SWAP
292 * with the new swapper, but we could have serious problems paging
293 * out other object types if there is insufficient memory.
295 * Unfortunately, checking free memory here is far too late, so the
296 * check has been moved up a procedural level.
300 * Can't clean the page if it's busy or held.
302 if ((m->hold_count != 0) ||
303 ((m->busy != 0) || (m->oflags & VPO_BUSY))) {
307 mc[vm_pageout_page_count] = pb = ps = m;
309 page_base = vm_pageout_page_count;
314 * Scan object for clusterable pages.
316 * We can cluster ONLY if: ->> the page is NOT
317 * clean, wired, busy, held, or mapped into a
318 * buffer, and one of the following:
319 * 1) The page is inactive, or a seldom used
322 * 2) we force the issue.
324 * During heavy mmap/modification loads the pageout
325 * daemon can really fragment the underlying file
326 * due to flushing pages out of order and not trying
327 * align the clusters (which leave sporatic out-of-order
328 * holes). To solve this problem we do the reverse scan
329 * first and attempt to align our cluster, then do a
330 * forward scan if room remains.
334 while (ib && pageout_count < vm_pageout_page_count) {
342 if ((p = vm_page_prev(pb)) == NULL ||
343 (p->oflags & VPO_BUSY) != 0 || p->busy != 0) {
347 vm_page_test_dirty(p);
349 p->queue != PQ_INACTIVE ||
350 p->hold_count != 0) { /* may be undergoing I/O */
354 mc[--page_base] = pb = p;
358 * alignment boundry, stop here and switch directions. Do
361 if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
365 while (pageout_count < vm_pageout_page_count &&
366 pindex + is < object->size) {
369 if ((p = vm_page_next(ps)) == NULL ||
370 (p->oflags & VPO_BUSY) != 0 || p->busy != 0)
372 vm_page_test_dirty(p);
374 p->queue != PQ_INACTIVE ||
375 p->hold_count != 0) { /* may be undergoing I/O */
378 mc[page_base + pageout_count] = ps = p;
384 * If we exhausted our forward scan, continue with the reverse scan
385 * when possible, even past a page boundry. This catches boundry
388 if (ib && pageout_count < vm_pageout_page_count)
392 * we allow reads during pageouts...
394 return (vm_pageout_flush(&mc[page_base], pageout_count, 0, 0, NULL));
398 * vm_pageout_flush() - launder the given pages
400 * The given pages are laundered. Note that we setup for the start of
401 * I/O ( i.e. busy the page ), mark it read-only, and bump the object
402 * reference count all in here rather then in the parent. If we want
403 * the parent to do more sophisticated things we may have to change
406 * Returned runlen is the count of pages between mreq and first
407 * page after mreq with status VM_PAGER_AGAIN.
410 vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen)
412 vm_object_t object = mc[0]->object;
413 int pageout_status[count];
417 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
418 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
420 * Initiate I/O. Bump the vm_page_t->busy counter and
421 * mark the pages read-only.
423 * We do not have to fixup the clean/dirty bits here... we can
424 * allow the pager to do it after the I/O completes.
426 * NOTE! mc[i]->dirty may be partial or fragmented due to an
427 * edge case with file fragments.
429 for (i = 0; i < count; i++) {
430 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
431 ("vm_pageout_flush: partially invalid page %p index %d/%d",
433 vm_page_io_start(mc[i]);
434 pmap_remove_write(mc[i]);
436 vm_page_unlock_queues();
437 vm_object_pip_add(object, count);
439 vm_pager_put_pages(object, mc, count, flags, pageout_status);
441 runlen = count - mreq;
442 vm_page_lock_queues();
443 for (i = 0; i < count; i++) {
444 vm_page_t mt = mc[i];
446 KASSERT(pageout_status[i] == VM_PAGER_PEND ||
447 (mt->flags & PG_WRITEABLE) == 0,
448 ("vm_pageout_flush: page %p is not write protected", mt));
449 switch (pageout_status[i]) {
456 * Page outside of range of object. Right now we
457 * essentially lose the changes by pretending it
465 * If page couldn't be paged out, then reactivate the
466 * page so it doesn't clog the inactive list. (We
467 * will try paging out it again later).
469 vm_page_activate(mt);
472 if (i >= mreq && i - mreq < runlen)
478 * If the operation is still going, leave the page busy to
479 * block all other accesses. Also, leave the paging in
480 * progress indicator set so that we don't attempt an object
483 if (pageout_status[i] != VM_PAGER_PEND) {
484 vm_object_pip_wakeup(object);
485 vm_page_io_finish(mt);
486 if (vm_page_count_severe())
487 vm_page_try_to_cache(mt);
492 return (numpagedout);
495 #if !defined(NO_SWAPPING)
497 * vm_pageout_object_deactivate_pages
499 * deactivate enough pages to satisfy the inactive target
500 * requirements or if vm_page_proc_limit is set, then
501 * deactivate all of the pages in the object and its
504 * The object and map must be locked.
507 vm_pageout_object_deactivate_pages(pmap, first_object, desired)
509 vm_object_t first_object;
512 vm_object_t backing_object, object;
514 int actcount, rcount, remove_mode;
516 VM_OBJECT_LOCK_ASSERT(first_object, MA_OWNED);
517 if (first_object->type == OBJT_DEVICE ||
518 first_object->type == OBJT_SG ||
519 first_object->type == OBJT_PHYS)
521 for (object = first_object;; object = backing_object) {
522 if (pmap_resident_count(pmap) <= desired)
524 if (object->paging_in_progress)
528 if (object->shadow_count > 1)
531 * scan the objects entire memory queue
533 rcount = object->resident_page_count;
534 p = TAILQ_FIRST(&object->memq);
535 vm_page_lock_queues();
536 while (p && (rcount-- > 0)) {
537 if (pmap_resident_count(pmap) <= desired) {
538 vm_page_unlock_queues();
541 next = TAILQ_NEXT(p, listq);
543 if (p->wire_count != 0 ||
544 p->hold_count != 0 ||
546 (p->oflags & VPO_BUSY) ||
547 (p->flags & PG_UNMANAGED) ||
548 !pmap_page_exists_quick(pmap, p)) {
552 actcount = pmap_ts_referenced(p);
554 vm_page_flag_set(p, PG_REFERENCED);
555 } else if (p->flags & PG_REFERENCED) {
558 if ((p->queue != PQ_ACTIVE) &&
559 (p->flags & PG_REFERENCED)) {
561 p->act_count += actcount;
562 vm_page_flag_clear(p, PG_REFERENCED);
563 } else if (p->queue == PQ_ACTIVE) {
564 if ((p->flags & PG_REFERENCED) == 0) {
565 p->act_count -= min(p->act_count, ACT_DECLINE);
566 if (!remove_mode && (vm_pageout_algorithm || (p->act_count == 0))) {
568 vm_page_deactivate(p);
574 vm_page_flag_clear(p, PG_REFERENCED);
575 if (p->act_count < (ACT_MAX - ACT_ADVANCE))
576 p->act_count += ACT_ADVANCE;
579 } else if (p->queue == PQ_INACTIVE) {
584 vm_page_unlock_queues();
585 if ((backing_object = object->backing_object) == NULL)
587 VM_OBJECT_LOCK(backing_object);
588 if (object != first_object)
589 VM_OBJECT_UNLOCK(object);
592 if (object != first_object)
593 VM_OBJECT_UNLOCK(object);
597 * deactivate some number of pages in a map, try to do it fairly, but
598 * that is really hard to do.
601 vm_pageout_map_deactivate_pages(map, desired)
606 vm_object_t obj, bigobj;
609 if (!vm_map_trylock(map))
616 * first, search out the biggest object, and try to free pages from
619 tmpe = map->header.next;
620 while (tmpe != &map->header) {
621 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
622 obj = tmpe->object.vm_object;
623 if (obj != NULL && VM_OBJECT_TRYLOCK(obj)) {
624 if (obj->shadow_count <= 1 &&
626 bigobj->resident_page_count < obj->resident_page_count)) {
628 VM_OBJECT_UNLOCK(bigobj);
631 VM_OBJECT_UNLOCK(obj);
634 if (tmpe->wired_count > 0)
635 nothingwired = FALSE;
639 if (bigobj != NULL) {
640 vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
641 VM_OBJECT_UNLOCK(bigobj);
644 * Next, hunt around for other pages to deactivate. We actually
645 * do this search sort of wrong -- .text first is not the best idea.
647 tmpe = map->header.next;
648 while (tmpe != &map->header) {
649 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
651 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
652 obj = tmpe->object.vm_object;
655 vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
656 VM_OBJECT_UNLOCK(obj);
663 * Remove all mappings if a process is swapped out, this will free page
666 if (desired == 0 && nothingwired) {
667 tmpe = map->header.next;
668 while (tmpe != &map->header) {
669 pmap_remove(vm_map_pmap(map), tmpe->start, tmpe->end);
675 #endif /* !defined(NO_SWAPPING) */
678 * vm_pageout_scan does the dirty work for the pageout daemon.
681 vm_pageout_scan(int pass)
684 struct vm_page marker;
685 int page_shortage, maxscan, pcount;
686 int addl_page_shortage, addl_page_shortage_init;
689 int vnodes_skipped = 0;
693 * Decrease registered cache sizes.
695 EVENTHANDLER_INVOKE(vm_lowmem, 0);
697 * We do this explicitly after the caches have been drained above.
701 addl_page_shortage_init = atomic_readandclear_int(&vm_pageout_deficit);
704 * Calculate the number of pages we want to either free or move
707 page_shortage = vm_paging_target() + addl_page_shortage_init;
710 * Initialize our marker
712 bzero(&marker, sizeof(marker));
713 marker.flags = PG_FICTITIOUS | PG_MARKER;
714 marker.oflags = VPO_BUSY;
715 marker.queue = PQ_INACTIVE;
716 marker.wire_count = 1;
719 * Start scanning the inactive queue for pages we can move to the
720 * cache or free. The scan will stop when the target is reached or
721 * we have scanned the entire inactive queue. Note that m->act_count
722 * is not used to form decisions for the inactive queue, only for the
725 * maxlaunder limits the number of dirty pages we flush per scan.
726 * For most systems a smaller value (16 or 32) is more robust under
727 * extreme memory and disk pressure because any unnecessary writes
728 * to disk can result in extreme performance degredation. However,
729 * systems with excessive dirty pages (especially when MAP_NOSYNC is
730 * used) will die horribly with limited laundering. If the pageout
731 * daemon cannot clean enough pages in the first pass, we let it go
732 * all out in succeeding passes.
734 if ((maxlaunder = vm_max_launder) <= 1)
738 vm_page_lock_queues();
740 addl_page_shortage = addl_page_shortage_init;
741 maxscan = cnt.v_inactive_count;
743 for (m = TAILQ_FIRST(&vm_page_queues[PQ_INACTIVE].pl);
744 m != NULL && maxscan-- > 0 && page_shortage > 0;
749 if (VM_PAGE_GETQUEUE(m) != PQ_INACTIVE) {
753 next = TAILQ_NEXT(m, pageq);
759 if (m->flags & PG_MARKER)
763 * A held page may be undergoing I/O, so skip it.
767 addl_page_shortage++;
771 * Don't mess with busy pages, keep in the front of the
772 * queue, most likely are being paged out.
774 if (!VM_OBJECT_TRYLOCK(object) &&
775 (!vm_pageout_fallback_object_lock(m, &next) ||
776 m->hold_count != 0)) {
777 VM_OBJECT_UNLOCK(object);
778 addl_page_shortage++;
781 if (m->busy || (m->oflags & VPO_BUSY)) {
782 VM_OBJECT_UNLOCK(object);
783 addl_page_shortage++;
788 * If the object is not being used, we ignore previous
791 if (object->ref_count == 0) {
792 vm_page_flag_clear(m, PG_REFERENCED);
793 KASSERT(!pmap_page_is_mapped(m),
794 ("vm_pageout_scan: page %p is mapped", m));
797 * Otherwise, if the page has been referenced while in the
798 * inactive queue, we bump the "activation count" upwards,
799 * making it less likely that the page will be added back to
800 * the inactive queue prematurely again. Here we check the
801 * page tables (or emulated bits, if any), given the upper
802 * level VM system not knowing anything about existing
805 } else if (((m->flags & PG_REFERENCED) == 0) &&
806 (actcount = pmap_ts_referenced(m))) {
808 VM_OBJECT_UNLOCK(object);
809 m->act_count += (actcount + ACT_ADVANCE);
814 * If the upper level VM system knows about any page
815 * references, we activate the page. We also set the
816 * "activation count" higher than normal so that we will less
817 * likely place pages back onto the inactive queue again.
819 if ((m->flags & PG_REFERENCED) != 0) {
820 vm_page_flag_clear(m, PG_REFERENCED);
821 actcount = pmap_ts_referenced(m);
823 VM_OBJECT_UNLOCK(object);
824 m->act_count += (actcount + ACT_ADVANCE + 1);
829 * If the upper level VM system does not believe that the page
830 * is fully dirty, but it is mapped for write access, then we
831 * consult the pmap to see if the page's dirty status should
834 if (m->dirty != VM_PAGE_BITS_ALL &&
835 (m->flags & PG_WRITEABLE) != 0) {
837 * Avoid a race condition: Unless write access is
838 * removed from the page, another processor could
839 * modify it before all access is removed by the call
840 * to vm_page_cache() below. If vm_page_cache() finds
841 * that the page has been modified when it removes all
842 * access, it panics because it cannot cache dirty
843 * pages. In principle, we could eliminate just write
844 * access here rather than all access. In the expected
845 * case, when there are no last instant modifications
846 * to the page, removing all access will be cheaper
849 if (pmap_is_modified(m))
851 else if (m->dirty == 0)
857 * Invalid pages can be easily freed
862 } else if (m->dirty == 0) {
864 * Clean pages can be placed onto the cache queue.
865 * This effectively frees them.
869 } else if ((m->flags & PG_WINATCFLS) == 0 && pass == 0) {
871 * Dirty pages need to be paged out, but flushing
872 * a page is extremely expensive verses freeing
873 * a clean page. Rather then artificially limiting
874 * the number of pages we can flush, we instead give
875 * dirty pages extra priority on the inactive queue
876 * by forcing them to be cycled through the queue
877 * twice before being flushed, after which the
878 * (now clean) page will cycle through once more
879 * before being freed. This significantly extends
880 * the thrash point for a heavily loaded machine.
882 vm_page_flag_set(m, PG_WINATCFLS);
884 } else if (maxlaunder > 0) {
886 * We always want to try to flush some dirty pages if
887 * we encounter them, to keep the system stable.
888 * Normally this number is small, but under extreme
889 * pressure where there are insufficient clean pages
890 * on the inactive queue, we may have to go all out.
892 int swap_pageouts_ok, vfslocked = 0;
893 struct vnode *vp = NULL;
894 struct mount *mp = NULL;
896 if ((object->type != OBJT_SWAP) && (object->type != OBJT_DEFAULT)) {
897 swap_pageouts_ok = 1;
899 swap_pageouts_ok = !(defer_swap_pageouts || disable_swap_pageouts);
900 swap_pageouts_ok |= (!disable_swap_pageouts && defer_swap_pageouts &&
901 vm_page_count_min());
906 * We don't bother paging objects that are "dead".
907 * Those objects are in a "rundown" state.
909 if (!swap_pageouts_ok || (object->flags & OBJ_DEAD)) {
910 VM_OBJECT_UNLOCK(object);
916 * Following operations may unlock
917 * vm_page_queue_mtx, invalidating the 'next'
918 * pointer. To prevent an inordinate number
919 * of restarts we use our marker to remember
923 TAILQ_INSERT_AFTER(&vm_page_queues[PQ_INACTIVE].pl,
926 * The object is already known NOT to be dead. It
927 * is possible for the vget() to block the whole
928 * pageout daemon, but the new low-memory handling
929 * code should prevent it.
931 * The previous code skipped locked vnodes and, worse,
932 * reordered pages in the queue. This results in
933 * completely non-deterministic operation and, on a
934 * busy system, can lead to extremely non-optimal
935 * pageouts. For example, it can cause clean pages
936 * to be freed and dirty pages to be moved to the end
937 * of the queue. Since dirty pages are also moved to
938 * the end of the queue once-cleaned, this gives
939 * way too large a weighting to defering the freeing
942 * We can't wait forever for the vnode lock, we might
943 * deadlock due to a vn_read() getting stuck in
944 * vm_wait while holding this vnode. We skip the
945 * vnode if we can't get it in a reasonable amount
948 if (object->type == OBJT_VNODE) {
950 if (vp->v_type == VREG &&
951 vn_start_write(vp, &mp, V_NOWAIT) != 0) {
954 if (object->flags & OBJ_MIGHTBEDIRTY)
956 goto unlock_and_continue;
959 ("vp %p with NULL v_mount", vp));
960 vm_page_unlock_queues();
961 vm_object_reference_locked(object);
962 VM_OBJECT_UNLOCK(object);
963 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
964 if (vget(vp, LK_EXCLUSIVE | LK_TIMELOCK,
966 VM_OBJECT_LOCK(object);
967 vm_page_lock_queues();
969 if (object->flags & OBJ_MIGHTBEDIRTY)
972 goto unlock_and_continue;
974 VM_OBJECT_LOCK(object);
975 vm_page_lock_queues();
977 * The page might have been moved to another
978 * queue during potential blocking in vget()
979 * above. The page might have been freed and
980 * reused for another vnode.
982 if (VM_PAGE_GETQUEUE(m) != PQ_INACTIVE ||
983 m->object != object ||
984 TAILQ_NEXT(m, pageq) != &marker) {
985 if (object->flags & OBJ_MIGHTBEDIRTY)
987 goto unlock_and_continue;
991 * The page may have been busied during the
992 * blocking in vget(). We don't move the
993 * page back onto the end of the queue so that
994 * statistics are more correct if we don't.
996 if (m->busy || (m->oflags & VPO_BUSY)) {
997 goto unlock_and_continue;
1001 * If the page has become held it might
1002 * be undergoing I/O, so skip it
1004 if (m->hold_count) {
1006 if (object->flags & OBJ_MIGHTBEDIRTY)
1008 goto unlock_and_continue;
1013 * If a page is dirty, then it is either being washed
1014 * (but not yet cleaned) or it is still in the
1015 * laundry. If it is still in the laundry, then we
1016 * start the cleaning operation.
1018 * decrement page_shortage on success to account for
1019 * the (future) cleaned page. Otherwise we could wind
1020 * up laundering or cleaning too many pages.
1022 if (vm_pageout_clean(m) != 0) {
1026 unlock_and_continue:
1027 VM_OBJECT_UNLOCK(object);
1029 vm_page_unlock_queues();
1032 VFS_UNLOCK_GIANT(vfslocked);
1033 vm_object_deallocate(object);
1034 vn_finished_write(mp);
1035 vm_page_lock_queues();
1037 next = TAILQ_NEXT(&marker, pageq);
1038 TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE].pl,
1042 VM_OBJECT_UNLOCK(object);
1046 * Compute the number of pages we want to try to move from the
1047 * active queue to the inactive queue.
1049 page_shortage = vm_paging_target() +
1050 cnt.v_inactive_target - cnt.v_inactive_count;
1051 page_shortage += addl_page_shortage;
1054 * Scan the active queue for things we can deactivate. We nominally
1055 * track the per-page activity counter and use it to locate
1056 * deactivation candidates.
1058 pcount = cnt.v_active_count;
1059 m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1061 while ((m != NULL) && (pcount-- > 0) && (page_shortage > 0)) {
1063 KASSERT(VM_PAGE_INQUEUE2(m, PQ_ACTIVE),
1064 ("vm_pageout_scan: page %p isn't active", m));
1066 next = TAILQ_NEXT(m, pageq);
1068 if ((m->flags & PG_MARKER) != 0) {
1072 if (!VM_OBJECT_TRYLOCK(object) &&
1073 !vm_pageout_fallback_object_lock(m, &next)) {
1074 VM_OBJECT_UNLOCK(object);
1080 * Don't deactivate pages that are busy.
1082 if ((m->busy != 0) ||
1083 (m->oflags & VPO_BUSY) ||
1084 (m->hold_count != 0)) {
1085 VM_OBJECT_UNLOCK(object);
1092 * The count for pagedaemon pages is done after checking the
1093 * page for eligibility...
1098 * Check to see "how much" the page has been used.
1101 if (object->ref_count != 0) {
1102 if (m->flags & PG_REFERENCED) {
1105 actcount += pmap_ts_referenced(m);
1107 m->act_count += ACT_ADVANCE + actcount;
1108 if (m->act_count > ACT_MAX)
1109 m->act_count = ACT_MAX;
1114 * Since we have "tested" this bit, we need to clear it now.
1116 vm_page_flag_clear(m, PG_REFERENCED);
1119 * Only if an object is currently being used, do we use the
1120 * page activation count stats.
1122 if (actcount && (object->ref_count != 0)) {
1125 m->act_count -= min(m->act_count, ACT_DECLINE);
1126 if (vm_pageout_algorithm ||
1127 object->ref_count == 0 ||
1128 m->act_count == 0) {
1130 if (object->ref_count == 0) {
1135 vm_page_deactivate(m);
1137 vm_page_deactivate(m);
1143 VM_OBJECT_UNLOCK(object);
1146 vm_page_unlock_queues();
1147 #if !defined(NO_SWAPPING)
1149 * Idle process swapout -- run once per second.
1151 if (vm_swap_idle_enabled) {
1153 if (time_second != lsec) {
1154 vm_req_vmdaemon(VM_SWAP_IDLE);
1161 * If we didn't get enough free pages, and we have skipped a vnode
1162 * in a writeable object, wakeup the sync daemon. And kick swapout
1163 * if we did not get enough free pages.
1165 if (vm_paging_target() > 0) {
1166 if (vnodes_skipped && vm_page_count_min())
1167 (void) speedup_syncer();
1168 #if !defined(NO_SWAPPING)
1169 if (vm_swap_enabled && vm_page_count_target())
1170 vm_req_vmdaemon(VM_SWAP_NORMAL);
1175 * If we are critically low on one of RAM or swap and low on
1176 * the other, kill the largest process. However, we avoid
1177 * doing this on the first pass in order to give ourselves a
1178 * chance to flush out dirty vnode-backed pages and to allow
1179 * active pages to be moved to the inactive queue and reclaimed.
1182 ((swap_pager_avail < 64 && vm_page_count_min()) ||
1183 (swap_pager_full && vm_paging_target() > 0)))
1184 vm_pageout_oom(VM_OOM_MEM);
1189 vm_pageout_oom(int shortage)
1191 struct proc *p, *bigproc;
1192 vm_offset_t size, bigsize;
1197 * We keep the process bigproc locked once we find it to keep anyone
1198 * from messing with it; however, there is a possibility of
1199 * deadlock if process B is bigproc and one of it's child processes
1200 * attempts to propagate a signal to B while we are waiting for A's
1201 * lock while walking this list. To avoid this, we don't block on
1202 * the process lock but just skip a process if it is already locked.
1206 sx_slock(&allproc_lock);
1207 FOREACH_PROC_IN_SYSTEM(p) {
1210 if (PROC_TRYLOCK(p) == 0)
1213 * If this is a system, protected or killed process, skip it.
1215 if (p->p_state != PRS_NORMAL ||
1216 (p->p_flag & (P_INEXEC | P_PROTECTED | P_SYSTEM)) ||
1217 (p->p_pid == 1) || P_KILLED(p) ||
1218 ((p->p_pid < 48) && (swap_pager_avail != 0))) {
1223 * If the process is in a non-running type state,
1224 * don't touch it. Check all the threads individually.
1227 FOREACH_THREAD_IN_PROC(p, td) {
1229 if (!TD_ON_RUNQ(td) &&
1230 !TD_IS_RUNNING(td) &&
1231 !TD_IS_SLEEPING(td)) {
1243 * get the process size
1245 vm = vmspace_acquire_ref(p);
1250 if (!vm_map_trylock_read(&vm->vm_map)) {
1255 size = vmspace_swap_count(vm);
1256 vm_map_unlock_read(&vm->vm_map);
1257 if (shortage == VM_OOM_MEM)
1258 size += vmspace_resident_count(vm);
1261 * if the this process is bigger than the biggest one
1264 if (size > bigsize) {
1265 if (bigproc != NULL)
1266 PROC_UNLOCK(bigproc);
1272 sx_sunlock(&allproc_lock);
1273 if (bigproc != NULL) {
1274 killproc(bigproc, "out of swap space");
1275 sched_nice(bigproc, PRIO_MIN);
1276 PROC_UNLOCK(bigproc);
1277 wakeup(&cnt.v_free_count);
1282 * This routine tries to maintain the pseudo LRU active queue,
1283 * so that during long periods of time where there is no paging,
1284 * that some statistic accumulation still occurs. This code
1285 * helps the situation where paging just starts to occur.
1288 vm_pageout_page_stats()
1292 int pcount,tpcount; /* Number of pages to check */
1293 static int fullintervalcount = 0;
1296 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1298 (cnt.v_inactive_target + cnt.v_cache_max + cnt.v_free_min) -
1299 (cnt.v_free_count + cnt.v_inactive_count + cnt.v_cache_count);
1301 if (page_shortage <= 0)
1304 pcount = cnt.v_active_count;
1305 fullintervalcount += vm_pageout_stats_interval;
1306 if (fullintervalcount < vm_pageout_full_stats_interval) {
1307 tpcount = (int64_t)vm_pageout_stats_max * cnt.v_active_count /
1309 if (pcount > tpcount)
1312 fullintervalcount = 0;
1315 m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1316 while ((m != NULL) && (pcount-- > 0)) {
1319 KASSERT(VM_PAGE_INQUEUE2(m, PQ_ACTIVE),
1320 ("vm_pageout_page_stats: page %p isn't active", m));
1322 next = TAILQ_NEXT(m, pageq);
1325 if ((m->flags & PG_MARKER) != 0) {
1329 if (!VM_OBJECT_TRYLOCK(object) &&
1330 !vm_pageout_fallback_object_lock(m, &next)) {
1331 VM_OBJECT_UNLOCK(object);
1337 * Don't deactivate pages that are busy.
1339 if ((m->busy != 0) ||
1340 (m->oflags & VPO_BUSY) ||
1341 (m->hold_count != 0)) {
1342 VM_OBJECT_UNLOCK(object);
1349 if (m->flags & PG_REFERENCED) {
1350 vm_page_flag_clear(m, PG_REFERENCED);
1354 actcount += pmap_ts_referenced(m);
1356 m->act_count += ACT_ADVANCE + actcount;
1357 if (m->act_count > ACT_MAX)
1358 m->act_count = ACT_MAX;
1361 if (m->act_count == 0) {
1363 * We turn off page access, so that we have
1364 * more accurate RSS stats. We don't do this
1365 * in the normal page deactivation when the
1366 * system is loaded VM wise, because the
1367 * cost of the large number of page protect
1368 * operations would be higher than the value
1369 * of doing the operation.
1372 vm_page_deactivate(m);
1374 m->act_count -= min(m->act_count, ACT_DECLINE);
1378 VM_OBJECT_UNLOCK(object);
1384 * vm_pageout is the high level pageout daemon.
1392 * Initialize some paging parameters.
1394 cnt.v_interrupt_free_min = 2;
1395 if (cnt.v_page_count < 2000)
1396 vm_pageout_page_count = 8;
1399 * v_free_reserved needs to include enough for the largest
1400 * swap pager structures plus enough for any pv_entry structs
1403 if (cnt.v_page_count > 1024)
1404 cnt.v_free_min = 4 + (cnt.v_page_count - 1024) / 200;
1407 cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1408 cnt.v_interrupt_free_min;
1409 cnt.v_free_reserved = vm_pageout_page_count +
1410 cnt.v_pageout_free_min + (cnt.v_page_count / 768);
1411 cnt.v_free_severe = cnt.v_free_min / 2;
1412 cnt.v_free_min += cnt.v_free_reserved;
1413 cnt.v_free_severe += cnt.v_free_reserved;
1416 * v_free_target and v_cache_min control pageout hysteresis. Note
1417 * that these are more a measure of the VM cache queue hysteresis
1418 * then the VM free queue. Specifically, v_free_target is the
1419 * high water mark (free+cache pages).
1421 * v_free_reserved + v_cache_min (mostly means v_cache_min) is the
1422 * low water mark, while v_free_min is the stop. v_cache_min must
1423 * be big enough to handle memory needs while the pageout daemon
1424 * is signalled and run to free more pages.
1426 if (cnt.v_free_count > 6144)
1427 cnt.v_free_target = 4 * cnt.v_free_min + cnt.v_free_reserved;
1429 cnt.v_free_target = 2 * cnt.v_free_min + cnt.v_free_reserved;
1431 if (cnt.v_free_count > 2048) {
1432 cnt.v_cache_min = cnt.v_free_target;
1433 cnt.v_cache_max = 2 * cnt.v_cache_min;
1434 cnt.v_inactive_target = (3 * cnt.v_free_target) / 2;
1436 cnt.v_cache_min = 0;
1437 cnt.v_cache_max = 0;
1438 cnt.v_inactive_target = cnt.v_free_count / 4;
1440 if (cnt.v_inactive_target > cnt.v_free_count / 3)
1441 cnt.v_inactive_target = cnt.v_free_count / 3;
1443 /* XXX does not really belong here */
1444 if (vm_page_max_wired == 0)
1445 vm_page_max_wired = cnt.v_free_count / 3;
1447 if (vm_pageout_stats_max == 0)
1448 vm_pageout_stats_max = cnt.v_free_target;
1451 * Set interval in seconds for stats scan.
1453 if (vm_pageout_stats_interval == 0)
1454 vm_pageout_stats_interval = 5;
1455 if (vm_pageout_full_stats_interval == 0)
1456 vm_pageout_full_stats_interval = vm_pageout_stats_interval * 4;
1458 swap_pager_swap_init();
1461 * The pageout daemon is never done, so loop forever.
1465 * If we have enough free memory, wakeup waiters. Do
1466 * not clear vm_pages_needed until we reach our target,
1467 * otherwise we may be woken up over and over again and
1468 * waste a lot of cpu.
1470 mtx_lock(&vm_page_queue_free_mtx);
1471 if (vm_pages_needed && !vm_page_count_min()) {
1472 if (!vm_paging_needed())
1473 vm_pages_needed = 0;
1474 wakeup(&cnt.v_free_count);
1476 if (vm_pages_needed) {
1478 * Still not done, take a second pass without waiting
1479 * (unlimited dirty cleaning), otherwise sleep a bit
1484 msleep(&vm_pages_needed,
1485 &vm_page_queue_free_mtx, PVM, "psleep",
1489 * Good enough, sleep & handle stats. Prime the pass
1496 error = msleep(&vm_pages_needed,
1497 &vm_page_queue_free_mtx, PVM, "psleep",
1498 vm_pageout_stats_interval * hz);
1499 if (error && !vm_pages_needed) {
1500 mtx_unlock(&vm_page_queue_free_mtx);
1502 vm_page_lock_queues();
1503 vm_pageout_page_stats();
1504 vm_page_unlock_queues();
1508 if (vm_pages_needed)
1510 mtx_unlock(&vm_page_queue_free_mtx);
1511 vm_pageout_scan(pass);
1516 * Unless the free page queue lock is held by the caller, this function
1517 * should be regarded as advisory. Specifically, the caller should
1518 * not msleep() on &cnt.v_free_count following this function unless
1519 * the free page queue lock is held until the msleep() is performed.
1525 if (!vm_pages_needed && curthread->td_proc != pageproc) {
1526 vm_pages_needed = 1;
1527 wakeup(&vm_pages_needed);
1531 #if !defined(NO_SWAPPING)
1533 vm_req_vmdaemon(int req)
1535 static int lastrun = 0;
1537 mtx_lock(&vm_daemon_mtx);
1538 vm_pageout_req_swapout |= req;
1539 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
1540 wakeup(&vm_daemon_needed);
1543 mtx_unlock(&vm_daemon_mtx);
1549 struct rlimit rsslim;
1553 int breakout, swapout_flags;
1556 mtx_lock(&vm_daemon_mtx);
1557 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep", 0);
1558 swapout_flags = vm_pageout_req_swapout;
1559 vm_pageout_req_swapout = 0;
1560 mtx_unlock(&vm_daemon_mtx);
1562 swapout_procs(swapout_flags);
1565 * scan the processes for exceeding their rlimits or if
1566 * process is swapped out -- deactivate pages
1568 sx_slock(&allproc_lock);
1569 FOREACH_PROC_IN_SYSTEM(p) {
1570 vm_pindex_t limit, size;
1573 * if this is a system process or if we have already
1574 * looked at this process, skip it.
1577 if (p->p_state != PRS_NORMAL ||
1578 p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
1583 * if the process is in a non-running type state,
1587 FOREACH_THREAD_IN_PROC(p, td) {
1589 if (!TD_ON_RUNQ(td) &&
1590 !TD_IS_RUNNING(td) &&
1591 !TD_IS_SLEEPING(td)) {
1605 lim_rlimit(p, RLIMIT_RSS, &rsslim);
1607 qmin(rsslim.rlim_cur, rsslim.rlim_max));
1610 * let processes that are swapped out really be
1611 * swapped out set the limit to nothing (will force a
1614 if ((p->p_flag & P_INMEM) == 0)
1615 limit = 0; /* XXX */
1616 vm = vmspace_acquire_ref(p);
1621 size = vmspace_resident_count(vm);
1622 if (limit >= 0 && size >= limit) {
1623 vm_pageout_map_deactivate_pages(
1624 &vm->vm_map, limit);
1628 sx_sunlock(&allproc_lock);
1631 #endif /* !defined(NO_SWAPPING) */