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>
108 #include <machine/mutex.h>
111 * System initialization
114 /* the kernel process "vm_pageout"*/
115 static void vm_pageout(void);
116 static int vm_pageout_clean(vm_page_t);
117 static void vm_pageout_scan(int pass);
119 struct proc *pageproc;
121 static struct kproc_desc page_kp = {
126 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, kproc_start,
129 #if !defined(NO_SWAPPING)
130 /* the kernel process "vm_daemon"*/
131 static void vm_daemon(void);
132 static struct proc *vmproc;
134 static struct kproc_desc vm_kp = {
139 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
143 int vm_pages_needed; /* Event on which pageout daemon sleeps */
144 int vm_pageout_deficit; /* Estimated number of pages deficit */
145 int vm_pageout_pages_needed; /* flag saying that the pageout daemon needs pages */
147 #if !defined(NO_SWAPPING)
148 static int vm_pageout_req_swapout; /* XXX */
149 static int vm_daemon_needed;
150 static struct mtx vm_daemon_mtx;
151 /* Allow for use by vm_pageout before vm_daemon is initialized. */
152 MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
154 static int vm_max_launder = 32;
155 static int vm_pageout_stats_max=0, vm_pageout_stats_interval = 0;
156 static int vm_pageout_full_stats_interval = 0;
157 static int vm_pageout_algorithm=0;
158 static int defer_swap_pageouts=0;
159 static int disable_swap_pageouts=0;
161 #if defined(NO_SWAPPING)
162 static int vm_swap_enabled=0;
163 static int vm_swap_idle_enabled=0;
165 static int vm_swap_enabled=1;
166 static int vm_swap_idle_enabled=0;
169 SYSCTL_INT(_vm, VM_PAGEOUT_ALGORITHM, pageout_algorithm,
170 CTLFLAG_RW, &vm_pageout_algorithm, 0, "LRU page mgmt");
172 SYSCTL_INT(_vm, OID_AUTO, max_launder,
173 CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
175 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_max,
176 CTLFLAG_RW, &vm_pageout_stats_max, 0, "Max pageout stats scan length");
178 SYSCTL_INT(_vm, OID_AUTO, pageout_full_stats_interval,
179 CTLFLAG_RW, &vm_pageout_full_stats_interval, 0, "Interval for full stats scan");
181 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_interval,
182 CTLFLAG_RW, &vm_pageout_stats_interval, 0, "Interval for partial stats scan");
184 #if defined(NO_SWAPPING)
185 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
186 CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout");
187 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
188 CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
190 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
191 CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
192 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
193 CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
196 SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
197 CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
199 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
200 CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
202 static int pageout_lock_miss;
203 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
204 CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
206 #define VM_PAGEOUT_PAGE_COUNT 16
207 int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
209 int vm_page_max_wired; /* XXX max # of wired pages system-wide */
210 SYSCTL_INT(_vm, OID_AUTO, max_wired,
211 CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
213 #if !defined(NO_SWAPPING)
214 static void vm_pageout_map_deactivate_pages(vm_map_t, long);
215 static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
216 static void vm_req_vmdaemon(int req);
218 static void vm_pageout_page_stats(void);
221 * vm_pageout_fallback_object_lock:
223 * Lock vm object currently associated with `m'. VM_OBJECT_TRYLOCK is
224 * known to have failed and page queue must be either PQ_ACTIVE or
225 * PQ_INACTIVE. To avoid lock order violation, unlock the page queues
226 * while locking the vm object. Use marker page to detect page queue
227 * changes and maintain notion of next page on page queue. Return
228 * TRUE if no changes were detected, FALSE otherwise. vm object is
231 * This function depends on both the lock portion of struct vm_object
232 * and normal struct vm_page being type stable.
235 vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
237 struct vm_page marker;
243 * Initialize our marker
245 bzero(&marker, sizeof(marker));
246 marker.flags = PG_FICTITIOUS | PG_MARKER;
247 marker.oflags = VPO_BUSY;
248 marker.queue = m->queue;
249 marker.wire_count = 1;
254 TAILQ_INSERT_AFTER(&vm_page_queues[queue].pl,
256 vm_page_unlock_queues();
257 VM_OBJECT_LOCK(object);
258 vm_page_lock_queues();
260 /* Page queue might have changed. */
261 *next = TAILQ_NEXT(&marker, pageq);
262 unchanged = (m->queue == queue &&
263 m->object == object &&
264 &marker == TAILQ_NEXT(m, pageq));
265 TAILQ_REMOVE(&vm_page_queues[queue].pl,
273 * Clean the page and remove it from the laundry.
275 * We set the busy bit to cause potential page faults on this page to
276 * block. Note the careful timing, however, the busy bit isn't set till
277 * late and we cannot do anything that will mess with the page.
284 vm_page_t mc[2*vm_pageout_page_count];
286 int ib, is, page_base;
287 vm_pindex_t pindex = m->pindex;
289 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
290 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
293 * It doesn't cost us anything to pageout OBJT_DEFAULT or OBJT_SWAP
294 * with the new swapper, but we could have serious problems paging
295 * out other object types if there is insufficient memory.
297 * Unfortunately, checking free memory here is far too late, so the
298 * check has been moved up a procedural level.
302 * Can't clean the page if it's busy or held.
304 if ((m->hold_count != 0) ||
305 ((m->busy != 0) || (m->oflags & VPO_BUSY))) {
309 mc[vm_pageout_page_count] = m;
311 page_base = vm_pageout_page_count;
316 * Scan object for clusterable pages.
318 * We can cluster ONLY if: ->> the page is NOT
319 * clean, wired, busy, held, or mapped into a
320 * buffer, and one of the following:
321 * 1) The page is inactive, or a seldom used
324 * 2) we force the issue.
326 * During heavy mmap/modification loads the pageout
327 * daemon can really fragment the underlying file
328 * due to flushing pages out of order and not trying
329 * align the clusters (which leave sporatic out-of-order
330 * holes). To solve this problem we do the reverse scan
331 * first and attempt to align our cluster, then do a
332 * forward scan if room remains.
336 while (ib && pageout_count < vm_pageout_page_count) {
344 if ((p = vm_page_lookup(object, pindex - ib)) == NULL) {
348 if ((p->oflags & VPO_BUSY) || p->busy) {
352 vm_page_test_dirty(p);
353 if ((p->dirty & p->valid) == 0 ||
354 p->queue != PQ_INACTIVE ||
355 p->wire_count != 0 || /* may be held by buf cache */
356 p->hold_count != 0) { /* may be undergoing I/O */
364 * alignment boundry, stop here and switch directions. Do
367 if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
371 while (pageout_count < vm_pageout_page_count &&
372 pindex + is < object->size) {
375 if ((p = vm_page_lookup(object, pindex + is)) == NULL)
377 if ((p->oflags & VPO_BUSY) || p->busy) {
380 vm_page_test_dirty(p);
381 if ((p->dirty & p->valid) == 0 ||
382 p->queue != PQ_INACTIVE ||
383 p->wire_count != 0 || /* may be held by buf cache */
384 p->hold_count != 0) { /* may be undergoing I/O */
387 mc[page_base + pageout_count] = p;
393 * If we exhausted our forward scan, continue with the reverse scan
394 * when possible, even past a page boundry. This catches boundry
397 if (ib && pageout_count < vm_pageout_page_count)
401 * we allow reads during pageouts...
403 return (vm_pageout_flush(&mc[page_base], pageout_count, 0));
407 * vm_pageout_flush() - launder the given pages
409 * The given pages are laundered. Note that we setup for the start of
410 * I/O ( i.e. busy the page ), mark it read-only, and bump the object
411 * reference count all in here rather then in the parent. If we want
412 * the parent to do more sophisticated things we may have to change
416 vm_pageout_flush(vm_page_t *mc, int count, int flags)
418 vm_object_t object = mc[0]->object;
419 int pageout_status[count];
423 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
424 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
426 * Initiate I/O. Bump the vm_page_t->busy counter and
427 * mark the pages read-only.
429 * We do not have to fixup the clean/dirty bits here... we can
430 * allow the pager to do it after the I/O completes.
432 * NOTE! mc[i]->dirty may be partial or fragmented due to an
433 * edge case with file fragments.
435 for (i = 0; i < count; i++) {
436 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
437 ("vm_pageout_flush: partially invalid page %p index %d/%d",
439 vm_page_io_start(mc[i]);
440 pmap_remove_write(mc[i]);
442 vm_page_unlock_queues();
443 vm_object_pip_add(object, count);
445 vm_pager_put_pages(object, mc, count, flags, pageout_status);
447 vm_page_lock_queues();
448 for (i = 0; i < count; i++) {
449 vm_page_t mt = mc[i];
451 KASSERT(pageout_status[i] == VM_PAGER_PEND ||
452 (mt->flags & PG_WRITEABLE) == 0,
453 ("vm_pageout_flush: page %p is not write protected", mt));
454 switch (pageout_status[i]) {
461 * Page outside of range of object. Right now we
462 * essentially lose the changes by pretending it
465 pmap_clear_modify(mt);
471 * If page couldn't be paged out, then reactivate the
472 * page so it doesn't clog the inactive list. (We
473 * will try paging out it again later).
475 vm_page_activate(mt);
482 * If the operation is still going, leave the page busy to
483 * block all other accesses. Also, leave the paging in
484 * progress indicator set so that we don't attempt an object
487 if (pageout_status[i] != VM_PAGER_PEND) {
488 vm_object_pip_wakeup(object);
489 vm_page_io_finish(mt);
490 if (vm_page_count_severe())
491 vm_page_try_to_cache(mt);
497 #if !defined(NO_SWAPPING)
499 * vm_pageout_object_deactivate_pages
501 * deactivate enough pages to satisfy the inactive target
502 * requirements or if vm_page_proc_limit is set, then
503 * deactivate all of the pages in the object and its
506 * The object and map must be locked.
509 vm_pageout_object_deactivate_pages(pmap, first_object, desired)
511 vm_object_t first_object;
514 vm_object_t backing_object, object;
516 int actcount, rcount, remove_mode;
518 VM_OBJECT_LOCK_ASSERT(first_object, MA_OWNED);
519 if (first_object->type == OBJT_DEVICE || 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 pmap_remove(vm_map_pmap(map), vm_map_min(map),
672 #endif /* !defined(NO_SWAPPING) */
675 * vm_pageout_scan does the dirty work for the pageout daemon.
678 vm_pageout_scan(int pass)
681 struct vm_page marker;
682 int page_shortage, maxscan, pcount;
683 int addl_page_shortage, addl_page_shortage_init;
686 int vnodes_skipped = 0;
690 * Decrease registered cache sizes.
692 EVENTHANDLER_INVOKE(vm_lowmem, 0);
694 * We do this explicitly after the caches have been drained above.
698 addl_page_shortage_init = atomic_readandclear_int(&vm_pageout_deficit);
701 * Calculate the number of pages we want to either free or move
704 page_shortage = vm_paging_target() + addl_page_shortage_init;
707 * Initialize our marker
709 bzero(&marker, sizeof(marker));
710 marker.flags = PG_FICTITIOUS | PG_MARKER;
711 marker.oflags = VPO_BUSY;
712 marker.queue = PQ_INACTIVE;
713 marker.wire_count = 1;
716 * Start scanning the inactive queue for pages we can move to the
717 * cache or free. The scan will stop when the target is reached or
718 * we have scanned the entire inactive queue. Note that m->act_count
719 * is not used to form decisions for the inactive queue, only for the
722 * maxlaunder limits the number of dirty pages we flush per scan.
723 * For most systems a smaller value (16 or 32) is more robust under
724 * extreme memory and disk pressure because any unnecessary writes
725 * to disk can result in extreme performance degredation. However,
726 * systems with excessive dirty pages (especially when MAP_NOSYNC is
727 * used) will die horribly with limited laundering. If the pageout
728 * daemon cannot clean enough pages in the first pass, we let it go
729 * all out in succeeding passes.
731 if ((maxlaunder = vm_max_launder) <= 1)
735 vm_page_lock_queues();
737 addl_page_shortage = addl_page_shortage_init;
738 maxscan = cnt.v_inactive_count;
740 for (m = TAILQ_FIRST(&vm_page_queues[PQ_INACTIVE].pl);
741 m != NULL && maxscan-- > 0 && page_shortage > 0;
746 if (VM_PAGE_GETQUEUE(m) != PQ_INACTIVE) {
750 next = TAILQ_NEXT(m, pageq);
756 if (m->flags & PG_MARKER)
760 * A held page may be undergoing I/O, so skip it.
764 addl_page_shortage++;
768 * Don't mess with busy pages, keep in the front of the
769 * queue, most likely are being paged out.
771 if (!VM_OBJECT_TRYLOCK(object) &&
772 (!vm_pageout_fallback_object_lock(m, &next) ||
773 m->hold_count != 0)) {
774 VM_OBJECT_UNLOCK(object);
775 addl_page_shortage++;
778 if (m->busy || (m->oflags & VPO_BUSY)) {
779 VM_OBJECT_UNLOCK(object);
780 addl_page_shortage++;
785 * If the object is not being used, we ignore previous
788 if (object->ref_count == 0) {
789 vm_page_flag_clear(m, PG_REFERENCED);
790 pmap_clear_reference(m);
793 * Otherwise, if the page has been referenced while in the
794 * inactive queue, we bump the "activation count" upwards,
795 * making it less likely that the page will be added back to
796 * the inactive queue prematurely again. Here we check the
797 * page tables (or emulated bits, if any), given the upper
798 * level VM system not knowing anything about existing
801 } else if (((m->flags & PG_REFERENCED) == 0) &&
802 (actcount = pmap_ts_referenced(m))) {
804 VM_OBJECT_UNLOCK(object);
805 m->act_count += (actcount + ACT_ADVANCE);
810 * If the upper level VM system knows about any page
811 * references, we activate the page. We also set the
812 * "activation count" higher than normal so that we will less
813 * likely place pages back onto the inactive queue again.
815 if ((m->flags & PG_REFERENCED) != 0) {
816 vm_page_flag_clear(m, PG_REFERENCED);
817 actcount = pmap_ts_referenced(m);
819 VM_OBJECT_UNLOCK(object);
820 m->act_count += (actcount + ACT_ADVANCE + 1);
825 * If the upper level VM system doesn't know anything about
826 * the page being dirty, we have to check for it again. As
827 * far as the VM code knows, any partially dirty pages are
830 if (m->dirty == 0 && !pmap_is_modified(m)) {
832 * Avoid a race condition: Unless write access is
833 * removed from the page, another processor could
834 * modify it before all access is removed by the call
835 * to vm_page_cache() below. If vm_page_cache() finds
836 * that the page has been modified when it removes all
837 * access, it panics because it cannot cache dirty
838 * pages. In principle, we could eliminate just write
839 * access here rather than all access. In the expected
840 * case, when there are no last instant modifications
841 * to the page, removing all access will be cheaper
844 if ((m->flags & PG_WRITEABLE) != 0)
852 * Invalid pages can be easily freed
857 } else if (m->dirty == 0) {
859 * Clean pages can be placed onto the cache queue.
860 * This effectively frees them.
864 } else if ((m->flags & PG_WINATCFLS) == 0 && pass == 0) {
866 * Dirty pages need to be paged out, but flushing
867 * a page is extremely expensive verses freeing
868 * a clean page. Rather then artificially limiting
869 * the number of pages we can flush, we instead give
870 * dirty pages extra priority on the inactive queue
871 * by forcing them to be cycled through the queue
872 * twice before being flushed, after which the
873 * (now clean) page will cycle through once more
874 * before being freed. This significantly extends
875 * the thrash point for a heavily loaded machine.
877 vm_page_flag_set(m, PG_WINATCFLS);
879 } else if (maxlaunder > 0) {
881 * We always want to try to flush some dirty pages if
882 * we encounter them, to keep the system stable.
883 * Normally this number is small, but under extreme
884 * pressure where there are insufficient clean pages
885 * on the inactive queue, we may have to go all out.
887 int swap_pageouts_ok, vfslocked = 0;
888 struct vnode *vp = NULL;
889 struct mount *mp = NULL;
891 if ((object->type != OBJT_SWAP) && (object->type != OBJT_DEFAULT)) {
892 swap_pageouts_ok = 1;
894 swap_pageouts_ok = !(defer_swap_pageouts || disable_swap_pageouts);
895 swap_pageouts_ok |= (!disable_swap_pageouts && defer_swap_pageouts &&
896 vm_page_count_min());
901 * We don't bother paging objects that are "dead".
902 * Those objects are in a "rundown" state.
904 if (!swap_pageouts_ok || (object->flags & OBJ_DEAD)) {
905 VM_OBJECT_UNLOCK(object);
911 * Following operations may unlock
912 * vm_page_queue_mtx, invalidating the 'next'
913 * pointer. To prevent an inordinate number
914 * of restarts we use our marker to remember
918 TAILQ_INSERT_AFTER(&vm_page_queues[PQ_INACTIVE].pl,
921 * The object is already known NOT to be dead. It
922 * is possible for the vget() to block the whole
923 * pageout daemon, but the new low-memory handling
924 * code should prevent it.
926 * The previous code skipped locked vnodes and, worse,
927 * reordered pages in the queue. This results in
928 * completely non-deterministic operation and, on a
929 * busy system, can lead to extremely non-optimal
930 * pageouts. For example, it can cause clean pages
931 * to be freed and dirty pages to be moved to the end
932 * of the queue. Since dirty pages are also moved to
933 * the end of the queue once-cleaned, this gives
934 * way too large a weighting to defering the freeing
937 * We can't wait forever for the vnode lock, we might
938 * deadlock due to a vn_read() getting stuck in
939 * vm_wait while holding this vnode. We skip the
940 * vnode if we can't get it in a reasonable amount
943 if (object->type == OBJT_VNODE) {
945 if (vp->v_type == VREG &&
946 vn_start_write(vp, &mp, V_NOWAIT) != 0) {
948 ("vm_pageout_scan: mp != NULL"));
950 if (object->flags & OBJ_MIGHTBEDIRTY)
952 goto unlock_and_continue;
954 vm_page_unlock_queues();
955 vm_object_reference_locked(object);
956 VM_OBJECT_UNLOCK(object);
957 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
958 if (vget(vp, LK_EXCLUSIVE | LK_TIMELOCK,
960 VM_OBJECT_LOCK(object);
961 vm_page_lock_queues();
963 if (object->flags & OBJ_MIGHTBEDIRTY)
966 goto unlock_and_continue;
968 VM_OBJECT_LOCK(object);
969 vm_page_lock_queues();
971 * The page might have been moved to another
972 * queue during potential blocking in vget()
973 * above. The page might have been freed and
974 * reused for another vnode.
976 if (VM_PAGE_GETQUEUE(m) != PQ_INACTIVE ||
977 m->object != object ||
978 TAILQ_NEXT(m, pageq) != &marker) {
979 if (object->flags & OBJ_MIGHTBEDIRTY)
981 goto unlock_and_continue;
985 * The page may have been busied during the
986 * blocking in vget(). We don't move the
987 * page back onto the end of the queue so that
988 * statistics are more correct if we don't.
990 if (m->busy || (m->oflags & VPO_BUSY)) {
991 goto unlock_and_continue;
995 * If the page has become held it might
996 * be undergoing I/O, so skip it
1000 if (object->flags & OBJ_MIGHTBEDIRTY)
1002 goto unlock_and_continue;
1007 * If a page is dirty, then it is either being washed
1008 * (but not yet cleaned) or it is still in the
1009 * laundry. If it is still in the laundry, then we
1010 * start the cleaning operation.
1012 * decrement page_shortage on success to account for
1013 * the (future) cleaned page. Otherwise we could wind
1014 * up laundering or cleaning too many pages.
1016 if (vm_pageout_clean(m) != 0) {
1020 unlock_and_continue:
1021 VM_OBJECT_UNLOCK(object);
1023 vm_page_unlock_queues();
1026 VFS_UNLOCK_GIANT(vfslocked);
1027 vm_object_deallocate(object);
1028 vn_finished_write(mp);
1029 vm_page_lock_queues();
1031 next = TAILQ_NEXT(&marker, pageq);
1032 TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE].pl,
1036 VM_OBJECT_UNLOCK(object);
1040 * Compute the number of pages we want to try to move from the
1041 * active queue to the inactive queue.
1043 page_shortage = vm_paging_target() +
1044 cnt.v_inactive_target - cnt.v_inactive_count;
1045 page_shortage += addl_page_shortage;
1048 * Scan the active queue for things we can deactivate. We nominally
1049 * track the per-page activity counter and use it to locate
1050 * deactivation candidates.
1052 pcount = cnt.v_active_count;
1053 m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1055 while ((m != NULL) && (pcount-- > 0) && (page_shortage > 0)) {
1057 KASSERT(VM_PAGE_INQUEUE2(m, PQ_ACTIVE),
1058 ("vm_pageout_scan: page %p isn't active", m));
1060 next = TAILQ_NEXT(m, pageq);
1062 if ((m->flags & PG_MARKER) != 0) {
1066 if (!VM_OBJECT_TRYLOCK(object) &&
1067 !vm_pageout_fallback_object_lock(m, &next)) {
1068 VM_OBJECT_UNLOCK(object);
1074 * Don't deactivate pages that are busy.
1076 if ((m->busy != 0) ||
1077 (m->oflags & VPO_BUSY) ||
1078 (m->hold_count != 0)) {
1079 VM_OBJECT_UNLOCK(object);
1086 * The count for pagedaemon pages is done after checking the
1087 * page for eligibility...
1092 * Check to see "how much" the page has been used.
1095 if (object->ref_count != 0) {
1096 if (m->flags & PG_REFERENCED) {
1099 actcount += pmap_ts_referenced(m);
1101 m->act_count += ACT_ADVANCE + actcount;
1102 if (m->act_count > ACT_MAX)
1103 m->act_count = ACT_MAX;
1108 * Since we have "tested" this bit, we need to clear it now.
1110 vm_page_flag_clear(m, PG_REFERENCED);
1113 * Only if an object is currently being used, do we use the
1114 * page activation count stats.
1116 if (actcount && (object->ref_count != 0)) {
1119 m->act_count -= min(m->act_count, ACT_DECLINE);
1120 if (vm_pageout_algorithm ||
1121 object->ref_count == 0 ||
1122 m->act_count == 0) {
1124 if (object->ref_count == 0) {
1129 vm_page_deactivate(m);
1131 vm_page_deactivate(m);
1137 VM_OBJECT_UNLOCK(object);
1140 vm_page_unlock_queues();
1141 #if !defined(NO_SWAPPING)
1143 * Idle process swapout -- run once per second.
1145 if (vm_swap_idle_enabled) {
1147 if (time_second != lsec) {
1148 vm_req_vmdaemon(VM_SWAP_IDLE);
1155 * If we didn't get enough free pages, and we have skipped a vnode
1156 * in a writeable object, wakeup the sync daemon. And kick swapout
1157 * if we did not get enough free pages.
1159 if (vm_paging_target() > 0) {
1160 if (vnodes_skipped && vm_page_count_min())
1161 (void) speedup_syncer();
1162 #if !defined(NO_SWAPPING)
1163 if (vm_swap_enabled && vm_page_count_target())
1164 vm_req_vmdaemon(VM_SWAP_NORMAL);
1169 * If we are critically low on one of RAM or swap and low on
1170 * the other, kill the largest process. However, we avoid
1171 * doing this on the first pass in order to give ourselves a
1172 * chance to flush out dirty vnode-backed pages and to allow
1173 * active pages to be moved to the inactive queue and reclaimed.
1176 ((swap_pager_avail < 64 && vm_page_count_min()) ||
1177 (swap_pager_full && vm_paging_target() > 0)))
1178 vm_pageout_oom(VM_OOM_MEM);
1183 vm_pageout_oom(int shortage)
1185 struct proc *p, *bigproc;
1186 vm_offset_t size, bigsize;
1190 * We keep the process bigproc locked once we find it to keep anyone
1191 * from messing with it; however, there is a possibility of
1192 * deadlock if process B is bigproc and one of it's child processes
1193 * attempts to propagate a signal to B while we are waiting for A's
1194 * lock while walking this list. To avoid this, we don't block on
1195 * the process lock but just skip a process if it is already locked.
1199 sx_slock(&allproc_lock);
1200 FOREACH_PROC_IN_SYSTEM(p) {
1203 if (PROC_TRYLOCK(p) == 0)
1206 * If this is a system or protected process, skip it.
1208 if ((p->p_flag & P_SYSTEM) || (p->p_pid == 1) ||
1209 (p->p_flag & P_PROTECTED) ||
1210 ((p->p_pid < 48) && (swap_pager_avail != 0))) {
1215 * If the process is in a non-running type state,
1216 * don't touch it. Check all the threads individually.
1219 FOREACH_THREAD_IN_PROC(p, td) {
1221 if (!TD_ON_RUNQ(td) &&
1222 !TD_IS_RUNNING(td) &&
1223 !TD_IS_SLEEPING(td)) {
1235 * get the process size
1237 if (!vm_map_trylock_read(&p->p_vmspace->vm_map)) {
1241 size = vmspace_swap_count(p->p_vmspace);
1242 vm_map_unlock_read(&p->p_vmspace->vm_map);
1243 if (shortage == VM_OOM_MEM)
1244 size += vmspace_resident_count(p->p_vmspace);
1246 * if the this process is bigger than the biggest one
1249 if (size > bigsize) {
1250 if (bigproc != NULL)
1251 PROC_UNLOCK(bigproc);
1257 sx_sunlock(&allproc_lock);
1258 if (bigproc != NULL) {
1259 killproc(bigproc, "out of swap space");
1260 sched_nice(bigproc, PRIO_MIN);
1261 PROC_UNLOCK(bigproc);
1262 wakeup(&cnt.v_free_count);
1267 * This routine tries to maintain the pseudo LRU active queue,
1268 * so that during long periods of time where there is no paging,
1269 * that some statistic accumulation still occurs. This code
1270 * helps the situation where paging just starts to occur.
1273 vm_pageout_page_stats()
1277 int pcount,tpcount; /* Number of pages to check */
1278 static int fullintervalcount = 0;
1281 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1283 (cnt.v_inactive_target + cnt.v_cache_max + cnt.v_free_min) -
1284 (cnt.v_free_count + cnt.v_inactive_count + cnt.v_cache_count);
1286 if (page_shortage <= 0)
1289 pcount = cnt.v_active_count;
1290 fullintervalcount += vm_pageout_stats_interval;
1291 if (fullintervalcount < vm_pageout_full_stats_interval) {
1292 tpcount = (int64_t)vm_pageout_stats_max * cnt.v_active_count /
1294 if (pcount > tpcount)
1297 fullintervalcount = 0;
1300 m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1301 while ((m != NULL) && (pcount-- > 0)) {
1304 KASSERT(VM_PAGE_INQUEUE2(m, PQ_ACTIVE),
1305 ("vm_pageout_page_stats: page %p isn't active", m));
1307 next = TAILQ_NEXT(m, pageq);
1310 if ((m->flags & PG_MARKER) != 0) {
1314 if (!VM_OBJECT_TRYLOCK(object) &&
1315 !vm_pageout_fallback_object_lock(m, &next)) {
1316 VM_OBJECT_UNLOCK(object);
1322 * Don't deactivate pages that are busy.
1324 if ((m->busy != 0) ||
1325 (m->oflags & VPO_BUSY) ||
1326 (m->hold_count != 0)) {
1327 VM_OBJECT_UNLOCK(object);
1334 if (m->flags & PG_REFERENCED) {
1335 vm_page_flag_clear(m, PG_REFERENCED);
1339 actcount += pmap_ts_referenced(m);
1341 m->act_count += ACT_ADVANCE + actcount;
1342 if (m->act_count > ACT_MAX)
1343 m->act_count = ACT_MAX;
1346 if (m->act_count == 0) {
1348 * We turn off page access, so that we have
1349 * more accurate RSS stats. We don't do this
1350 * in the normal page deactivation when the
1351 * system is loaded VM wise, because the
1352 * cost of the large number of page protect
1353 * operations would be higher than the value
1354 * of doing the operation.
1357 vm_page_deactivate(m);
1359 m->act_count -= min(m->act_count, ACT_DECLINE);
1363 VM_OBJECT_UNLOCK(object);
1369 * vm_pageout is the high level pageout daemon.
1377 * Initialize some paging parameters.
1379 cnt.v_interrupt_free_min = 2;
1380 if (cnt.v_page_count < 2000)
1381 vm_pageout_page_count = 8;
1384 * v_free_reserved needs to include enough for the largest
1385 * swap pager structures plus enough for any pv_entry structs
1388 if (cnt.v_page_count > 1024)
1389 cnt.v_free_min = 4 + (cnt.v_page_count - 1024) / 200;
1392 cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1393 cnt.v_interrupt_free_min;
1394 cnt.v_free_reserved = vm_pageout_page_count +
1395 cnt.v_pageout_free_min + (cnt.v_page_count / 768);
1396 cnt.v_free_severe = cnt.v_free_min / 2;
1397 cnt.v_free_min += cnt.v_free_reserved;
1398 cnt.v_free_severe += cnt.v_free_reserved;
1401 * v_free_target and v_cache_min control pageout hysteresis. Note
1402 * that these are more a measure of the VM cache queue hysteresis
1403 * then the VM free queue. Specifically, v_free_target is the
1404 * high water mark (free+cache pages).
1406 * v_free_reserved + v_cache_min (mostly means v_cache_min) is the
1407 * low water mark, while v_free_min is the stop. v_cache_min must
1408 * be big enough to handle memory needs while the pageout daemon
1409 * is signalled and run to free more pages.
1411 if (cnt.v_free_count > 6144)
1412 cnt.v_free_target = 4 * cnt.v_free_min + cnt.v_free_reserved;
1414 cnt.v_free_target = 2 * cnt.v_free_min + cnt.v_free_reserved;
1416 if (cnt.v_free_count > 2048) {
1417 cnt.v_cache_min = cnt.v_free_target;
1418 cnt.v_cache_max = 2 * cnt.v_cache_min;
1419 cnt.v_inactive_target = (3 * cnt.v_free_target) / 2;
1421 cnt.v_cache_min = 0;
1422 cnt.v_cache_max = 0;
1423 cnt.v_inactive_target = cnt.v_free_count / 4;
1425 if (cnt.v_inactive_target > cnt.v_free_count / 3)
1426 cnt.v_inactive_target = cnt.v_free_count / 3;
1428 /* XXX does not really belong here */
1429 if (vm_page_max_wired == 0)
1430 vm_page_max_wired = cnt.v_free_count / 3;
1432 if (vm_pageout_stats_max == 0)
1433 vm_pageout_stats_max = cnt.v_free_target;
1436 * Set interval in seconds for stats scan.
1438 if (vm_pageout_stats_interval == 0)
1439 vm_pageout_stats_interval = 5;
1440 if (vm_pageout_full_stats_interval == 0)
1441 vm_pageout_full_stats_interval = vm_pageout_stats_interval * 4;
1443 swap_pager_swap_init();
1446 * The pageout daemon is never done, so loop forever.
1450 * If we have enough free memory, wakeup waiters. Do
1451 * not clear vm_pages_needed until we reach our target,
1452 * otherwise we may be woken up over and over again and
1453 * waste a lot of cpu.
1455 mtx_lock(&vm_page_queue_free_mtx);
1456 if (vm_pages_needed && !vm_page_count_min()) {
1457 if (!vm_paging_needed())
1458 vm_pages_needed = 0;
1459 wakeup(&cnt.v_free_count);
1461 if (vm_pages_needed) {
1463 * Still not done, take a second pass without waiting
1464 * (unlimited dirty cleaning), otherwise sleep a bit
1469 msleep(&vm_pages_needed,
1470 &vm_page_queue_free_mtx, PVM, "psleep",
1474 * Good enough, sleep & handle stats. Prime the pass
1481 error = msleep(&vm_pages_needed,
1482 &vm_page_queue_free_mtx, PVM, "psleep",
1483 vm_pageout_stats_interval * hz);
1484 if (error && !vm_pages_needed) {
1485 mtx_unlock(&vm_page_queue_free_mtx);
1487 vm_page_lock_queues();
1488 vm_pageout_page_stats();
1489 vm_page_unlock_queues();
1493 if (vm_pages_needed)
1495 mtx_unlock(&vm_page_queue_free_mtx);
1496 vm_pageout_scan(pass);
1501 * Unless the free page queue lock is held by the caller, this function
1502 * should be regarded as advisory. Specifically, the caller should
1503 * not msleep() on &cnt.v_free_count following this function unless
1504 * the free page queue lock is held until the msleep() is performed.
1510 if (!vm_pages_needed && curthread->td_proc != pageproc) {
1511 vm_pages_needed = 1;
1512 wakeup(&vm_pages_needed);
1516 #if !defined(NO_SWAPPING)
1518 vm_req_vmdaemon(int req)
1520 static int lastrun = 0;
1522 mtx_lock(&vm_daemon_mtx);
1523 vm_pageout_req_swapout |= req;
1524 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
1525 wakeup(&vm_daemon_needed);
1528 mtx_unlock(&vm_daemon_mtx);
1534 struct rlimit rsslim;
1537 int breakout, swapout_flags;
1540 mtx_lock(&vm_daemon_mtx);
1541 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep", 0);
1542 swapout_flags = vm_pageout_req_swapout;
1543 vm_pageout_req_swapout = 0;
1544 mtx_unlock(&vm_daemon_mtx);
1546 swapout_procs(swapout_flags);
1549 * scan the processes for exceeding their rlimits or if
1550 * process is swapped out -- deactivate pages
1552 sx_slock(&allproc_lock);
1553 FOREACH_PROC_IN_SYSTEM(p) {
1554 vm_pindex_t limit, size;
1557 * if this is a system process or if we have already
1558 * looked at this process, skip it.
1561 if (p->p_flag & (P_SYSTEM | P_WEXIT)) {
1566 * if the process is in a non-running type state,
1570 FOREACH_THREAD_IN_PROC(p, td) {
1572 if (!TD_ON_RUNQ(td) &&
1573 !TD_IS_RUNNING(td) &&
1574 !TD_IS_SLEEPING(td)) {
1588 lim_rlimit(p, RLIMIT_RSS, &rsslim);
1590 qmin(rsslim.rlim_cur, rsslim.rlim_max));
1593 * let processes that are swapped out really be
1594 * swapped out set the limit to nothing (will force a
1597 if ((p->p_flag & P_INMEM) == 0)
1598 limit = 0; /* XXX */
1601 size = vmspace_resident_count(p->p_vmspace);
1602 if (limit >= 0 && size >= limit) {
1603 vm_pageout_map_deactivate_pages(
1604 &p->p_vmspace->vm_map, limit);
1607 sx_sunlock(&allproc_lock);
1610 #endif /* !defined(NO_SWAPPING) */