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/resourcevar.h>
89 #include <sys/sched.h>
90 #include <sys/signalvar.h>
91 #include <sys/vnode.h>
92 #include <sys/vmmeter.h>
94 #include <sys/sysctl.h>
97 #include <vm/vm_param.h>
98 #include <vm/vm_object.h>
99 #include <vm/vm_page.h>
100 #include <vm/vm_map.h>
101 #include <vm/vm_pageout.h>
102 #include <vm/vm_pager.h>
103 #include <vm/swap_pager.h>
104 #include <vm/vm_extern.h>
107 #include <machine/mutex.h>
110 * System initialization
113 /* the kernel process "vm_pageout"*/
114 static void vm_pageout(void);
115 static int vm_pageout_clean(vm_page_t);
116 static void vm_pageout_pmap_collect(void);
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, &page_kp)
128 #if !defined(NO_SWAPPING)
129 /* the kernel process "vm_daemon"*/
130 static void vm_daemon(void);
131 static struct proc *vmproc;
133 static struct kproc_desc vm_kp = {
138 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp)
142 int vm_pages_needed; /* Event on which pageout daemon sleeps */
143 int vm_pageout_deficit; /* Estimated number of pages deficit */
144 int vm_pageout_pages_needed; /* flag saying that the pageout daemon needs pages */
146 #if !defined(NO_SWAPPING)
147 static int vm_pageout_req_swapout; /* XXX */
148 static int vm_daemon_needed;
150 static int vm_max_launder = 32;
151 static int vm_pageout_stats_max=0, vm_pageout_stats_interval = 0;
152 static int vm_pageout_full_stats_interval = 0;
153 static int vm_pageout_algorithm=0;
154 static int defer_swap_pageouts=0;
155 static int disable_swap_pageouts=0;
157 #if defined(NO_SWAPPING)
158 static int vm_swap_enabled=0;
159 static int vm_swap_idle_enabled=0;
161 static int vm_swap_enabled=1;
162 static int vm_swap_idle_enabled=0;
165 SYSCTL_INT(_vm, VM_PAGEOUT_ALGORITHM, pageout_algorithm,
166 CTLFLAG_RW, &vm_pageout_algorithm, 0, "LRU page mgmt");
168 SYSCTL_INT(_vm, OID_AUTO, max_launder,
169 CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
171 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_max,
172 CTLFLAG_RW, &vm_pageout_stats_max, 0, "Max pageout stats scan length");
174 SYSCTL_INT(_vm, OID_AUTO, pageout_full_stats_interval,
175 CTLFLAG_RW, &vm_pageout_full_stats_interval, 0, "Interval for full stats scan");
177 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_interval,
178 CTLFLAG_RW, &vm_pageout_stats_interval, 0, "Interval for partial stats scan");
180 #if defined(NO_SWAPPING)
181 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
182 CTLFLAG_RD, &vm_swap_enabled, 0, "");
183 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
184 CTLFLAG_RD, &vm_swap_idle_enabled, 0, "");
186 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
187 CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
188 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
189 CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
192 SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
193 CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
195 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
196 CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
198 static int pageout_lock_miss;
199 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
200 CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
202 #define VM_PAGEOUT_PAGE_COUNT 16
203 int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
205 int vm_page_max_wired; /* XXX max # of wired pages system-wide */
207 #if !defined(NO_SWAPPING)
208 static void vm_pageout_map_deactivate_pages(vm_map_t, long);
209 static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
210 static void vm_req_vmdaemon(void);
212 static void vm_pageout_page_stats(void);
215 * vm_pageout_fallback_object_lock:
217 * Lock vm object currently associated with `m'. VM_OBJECT_TRYLOCK is
218 * known to have failed and page queue must be either PQ_ACTIVE or
219 * PQ_INACTIVE. To avoid lock order violation, unlock the page queues
220 * while locking the vm object. Use marker page to detect page queue
221 * changes and maintain notion of next page on page queue. Return
222 * TRUE if no changes were detected, FALSE otherwise. vm object is
225 * This function depends on both the lock portion of struct vm_object
226 * and normal struct vm_page being type stable.
229 vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
231 struct vm_page marker;
237 * Initialize our marker
239 bzero(&marker, sizeof(marker));
240 marker.flags = PG_BUSY | PG_FICTITIOUS | PG_MARKER;
241 marker.queue = m->queue;
242 marker.wire_count = 1;
247 TAILQ_INSERT_AFTER(&vm_page_queues[queue].pl,
249 vm_page_unlock_queues();
250 VM_OBJECT_LOCK(object);
251 vm_page_lock_queues();
253 /* Page queue might have changed. */
254 *next = TAILQ_NEXT(&marker, pageq);
255 unchanged = (m->queue == queue &&
256 m->object == object &&
257 &marker == TAILQ_NEXT(m, pageq));
258 TAILQ_REMOVE(&vm_page_queues[queue].pl,
266 * Clean the page and remove it from the laundry.
268 * We set the busy bit to cause potential page faults on this page to
269 * block. Note the careful timing, however, the busy bit isn't set till
270 * late and we cannot do anything that will mess with the page.
277 vm_page_t mc[2*vm_pageout_page_count];
279 int ib, is, page_base;
280 vm_pindex_t pindex = m->pindex;
282 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
283 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
286 * It doesn't cost us anything to pageout OBJT_DEFAULT or OBJT_SWAP
287 * with the new swapper, but we could have serious problems paging
288 * out other object types if there is insufficient memory.
290 * Unfortunately, checking free memory here is far too late, so the
291 * check has been moved up a procedural level.
295 * Don't mess with the page if it's busy, held, or special
297 if ((m->hold_count != 0) ||
298 ((m->busy != 0) || (m->flags & (PG_BUSY|PG_UNMANAGED)))) {
302 mc[vm_pageout_page_count] = m;
304 page_base = vm_pageout_page_count;
309 * Scan object for clusterable pages.
311 * We can cluster ONLY if: ->> the page is NOT
312 * clean, wired, busy, held, or mapped into a
313 * buffer, and one of the following:
314 * 1) The page is inactive, or a seldom used
317 * 2) we force the issue.
319 * During heavy mmap/modification loads the pageout
320 * daemon can really fragment the underlying file
321 * due to flushing pages out of order and not trying
322 * align the clusters (which leave sporatic out-of-order
323 * holes). To solve this problem we do the reverse scan
324 * first and attempt to align our cluster, then do a
325 * forward scan if room remains.
329 while (ib && pageout_count < vm_pageout_page_count) {
337 if ((p = vm_page_lookup(object, pindex - ib)) == NULL) {
341 if (((p->queue - p->pc) == PQ_CACHE) ||
342 (p->flags & (PG_BUSY|PG_UNMANAGED)) || p->busy) {
346 vm_page_test_dirty(p);
347 if ((p->dirty & p->valid) == 0 ||
348 p->queue != PQ_INACTIVE ||
349 p->wire_count != 0 || /* may be held by buf cache */
350 p->hold_count != 0) { /* may be undergoing I/O */
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_lookup(object, pindex + is)) == NULL)
371 if (((p->queue - p->pc) == PQ_CACHE) ||
372 (p->flags & (PG_BUSY|PG_UNMANAGED)) || p->busy) {
375 vm_page_test_dirty(p);
376 if ((p->dirty & p->valid) == 0 ||
377 p->queue != PQ_INACTIVE ||
378 p->wire_count != 0 || /* may be held by buf cache */
379 p->hold_count != 0) { /* may be undergoing I/O */
382 mc[page_base + pageout_count] = p;
388 * If we exhausted our forward scan, continue with the reverse scan
389 * when possible, even past a page boundry. This catches boundry
392 if (ib && pageout_count < vm_pageout_page_count)
396 * we allow reads during pageouts...
398 return (vm_pageout_flush(&mc[page_base], pageout_count, 0));
402 * vm_pageout_flush() - launder the given pages
404 * The given pages are laundered. Note that we setup for the start of
405 * I/O ( i.e. busy the page ), mark it read-only, and bump the object
406 * reference count all in here rather then in the parent. If we want
407 * the parent to do more sophisticated things we may have to change
411 vm_pageout_flush(vm_page_t *mc, int count, int flags)
413 vm_object_t object = mc[0]->object;
414 int pageout_status[count];
418 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
419 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
421 * Initiate I/O. Bump the vm_page_t->busy counter and
422 * mark the pages read-only.
424 * We do not have to fixup the clean/dirty bits here... we can
425 * allow the pager to do it after the I/O completes.
427 * NOTE! mc[i]->dirty may be partial or fragmented due to an
428 * edge case with file fragments.
430 for (i = 0; i < count; i++) {
431 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
432 ("vm_pageout_flush: partially invalid page %p index %d/%d",
434 vm_page_io_start(mc[i]);
435 pmap_page_protect(mc[i], VM_PROT_READ);
437 vm_page_unlock_queues();
438 vm_object_pip_add(object, count);
440 vm_pager_put_pages(object, mc, count,
441 (flags | ((object == kernel_object) ? VM_PAGER_PUT_SYNC : 0)),
444 vm_page_lock_queues();
445 for (i = 0; i < count; i++) {
446 vm_page_t mt = mc[i];
448 KASSERT((mt->flags & PG_WRITEABLE) == 0,
449 ("vm_pageout_flush: page %p is not write protected", mt));
450 switch (pageout_status[i]) {
457 * Page outside of range of object. Right now we
458 * essentially lose the changes by pretending it
461 pmap_clear_modify(mt);
467 * If page couldn't be paged out, then reactivate the
468 * page so it doesn't clog the inactive list. (We
469 * will try paging out it again later).
471 vm_page_activate(mt);
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);
493 #if !defined(NO_SWAPPING)
495 * vm_pageout_object_deactivate_pages
497 * deactivate enough pages to satisfy the inactive target
498 * requirements or if vm_page_proc_limit is set, then
499 * deactivate all of the pages in the object and its
502 * The object and map must be locked.
505 vm_pageout_object_deactivate_pages(pmap, first_object, desired)
507 vm_object_t first_object;
510 vm_object_t backing_object, object;
512 int actcount, rcount, remove_mode;
514 VM_OBJECT_LOCK_ASSERT(first_object, MA_OWNED);
515 if (first_object->type == OBJT_DEVICE || first_object->type == OBJT_PHYS)
517 for (object = first_object;; object = backing_object) {
518 if (pmap_resident_count(pmap) <= desired)
520 if (object->paging_in_progress)
524 if (object->shadow_count > 1)
527 * scan the objects entire memory queue
529 rcount = object->resident_page_count;
530 p = TAILQ_FIRST(&object->memq);
531 vm_page_lock_queues();
532 while (p && (rcount-- > 0)) {
533 if (pmap_resident_count(pmap) <= desired) {
534 vm_page_unlock_queues();
537 next = TAILQ_NEXT(p, listq);
539 if (p->wire_count != 0 ||
540 p->hold_count != 0 ||
542 (p->flags & (PG_BUSY|PG_UNMANAGED)) ||
543 !pmap_page_exists_quick(pmap, p)) {
547 actcount = pmap_ts_referenced(p);
549 vm_page_flag_set(p, PG_REFERENCED);
550 } else if (p->flags & PG_REFERENCED) {
553 if ((p->queue != PQ_ACTIVE) &&
554 (p->flags & PG_REFERENCED)) {
556 p->act_count += actcount;
557 vm_page_flag_clear(p, PG_REFERENCED);
558 } else if (p->queue == PQ_ACTIVE) {
559 if ((p->flags & PG_REFERENCED) == 0) {
560 p->act_count -= min(p->act_count, ACT_DECLINE);
561 if (!remove_mode && (vm_pageout_algorithm || (p->act_count == 0))) {
563 vm_page_deactivate(p);
569 vm_page_flag_clear(p, PG_REFERENCED);
570 if (p->act_count < (ACT_MAX - ACT_ADVANCE))
571 p->act_count += ACT_ADVANCE;
574 } else if (p->queue == PQ_INACTIVE) {
579 vm_page_unlock_queues();
580 if ((backing_object = object->backing_object) == NULL)
582 VM_OBJECT_LOCK(backing_object);
583 if (object != first_object)
584 VM_OBJECT_UNLOCK(object);
587 if (object != first_object)
588 VM_OBJECT_UNLOCK(object);
592 * deactivate some number of pages in a map, try to do it fairly, but
593 * that is really hard to do.
596 vm_pageout_map_deactivate_pages(map, desired)
601 vm_object_t obj, bigobj;
604 if (!vm_map_trylock(map))
611 * first, search out the biggest object, and try to free pages from
614 tmpe = map->header.next;
615 while (tmpe != &map->header) {
616 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
617 obj = tmpe->object.vm_object;
618 if (obj != NULL && VM_OBJECT_TRYLOCK(obj)) {
619 if (obj->shadow_count <= 1 &&
621 bigobj->resident_page_count < obj->resident_page_count)) {
623 VM_OBJECT_UNLOCK(bigobj);
626 VM_OBJECT_UNLOCK(obj);
629 if (tmpe->wired_count > 0)
630 nothingwired = FALSE;
634 if (bigobj != NULL) {
635 vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
636 VM_OBJECT_UNLOCK(bigobj);
639 * Next, hunt around for other pages to deactivate. We actually
640 * do this search sort of wrong -- .text first is not the best idea.
642 tmpe = map->header.next;
643 while (tmpe != &map->header) {
644 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
646 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
647 obj = tmpe->object.vm_object;
650 vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
651 VM_OBJECT_UNLOCK(obj);
658 * Remove all mappings if a process is swapped out, this will free page
661 if (desired == 0 && nothingwired) {
662 pmap_remove(vm_map_pmap(map), vm_map_min(map),
667 #endif /* !defined(NO_SWAPPING) */
670 * This routine is very drastic, but can save the system
674 vm_pageout_pmap_collect(void)
678 static int warningdone;
680 if (pmap_pagedaemon_waken == 0)
682 if (warningdone < 5) {
683 printf("collecting pv entries -- suggest increasing PMAP_SHPGPERPROC\n");
686 vm_page_lock_queues();
687 for (i = 0; i < vm_page_array_size; i++) {
688 m = &vm_page_array[i];
689 if (m->wire_count || m->hold_count || m->busy ||
690 (m->flags & (PG_BUSY | PG_UNMANAGED)))
694 vm_page_unlock_queues();
695 pmap_pagedaemon_waken = 0;
699 * vm_pageout_scan does the dirty work for the pageout daemon.
702 vm_pageout_scan(int pass)
705 struct vm_page marker;
706 int page_shortage, maxscan, pcount;
707 int addl_page_shortage, addl_page_shortage_init;
708 struct proc *p, *bigproc;
710 vm_offset_t size, bigsize;
712 int actcount, cache_cur, cache_first_failure;
713 static int cache_last_free;
714 int vnodes_skipped = 0;
719 * Decrease registered cache sizes.
721 EVENTHANDLER_INVOKE(vm_lowmem, 0);
723 * We do this explicitly after the caches have been drained above.
727 * Do whatever cleanup that the pmap code can.
729 vm_pageout_pmap_collect();
731 addl_page_shortage_init = atomic_readandclear_int(&vm_pageout_deficit);
734 * Calculate the number of pages we want to either free or move
737 page_shortage = vm_paging_target() + addl_page_shortage_init;
740 * Initialize our marker
742 bzero(&marker, sizeof(marker));
743 marker.flags = PG_BUSY | PG_FICTITIOUS | PG_MARKER;
744 marker.queue = PQ_INACTIVE;
745 marker.wire_count = 1;
748 * Start scanning the inactive queue for pages we can move to the
749 * cache or free. The scan will stop when the target is reached or
750 * we have scanned the entire inactive queue. Note that m->act_count
751 * is not used to form decisions for the inactive queue, only for the
754 * maxlaunder limits the number of dirty pages we flush per scan.
755 * For most systems a smaller value (16 or 32) is more robust under
756 * extreme memory and disk pressure because any unnecessary writes
757 * to disk can result in extreme performance degredation. However,
758 * systems with excessive dirty pages (especially when MAP_NOSYNC is
759 * used) will die horribly with limited laundering. If the pageout
760 * daemon cannot clean enough pages in the first pass, we let it go
761 * all out in succeeding passes.
763 if ((maxlaunder = vm_max_launder) <= 1)
767 vm_page_lock_queues();
769 addl_page_shortage = addl_page_shortage_init;
770 maxscan = cnt.v_inactive_count;
772 for (m = TAILQ_FIRST(&vm_page_queues[PQ_INACTIVE].pl);
773 m != NULL && maxscan-- > 0 && page_shortage > 0;
778 if (m->queue != PQ_INACTIVE) {
782 next = TAILQ_NEXT(m, pageq);
788 if (m->flags & PG_MARKER)
792 * A held page may be undergoing I/O, so skip it.
796 addl_page_shortage++;
800 * Don't mess with busy pages, keep in the front of the
801 * queue, most likely are being paged out.
803 if (!VM_OBJECT_TRYLOCK(object) &&
804 (!vm_pageout_fallback_object_lock(m, &next) ||
805 m->hold_count != 0)) {
806 VM_OBJECT_UNLOCK(object);
807 addl_page_shortage++;
810 if (m->busy || (m->flags & PG_BUSY)) {
811 VM_OBJECT_UNLOCK(object);
812 addl_page_shortage++;
817 * If the object is not being used, we ignore previous
820 if (object->ref_count == 0) {
821 vm_page_flag_clear(m, PG_REFERENCED);
822 pmap_clear_reference(m);
825 * Otherwise, if the page has been referenced while in the
826 * inactive queue, we bump the "activation count" upwards,
827 * making it less likely that the page will be added back to
828 * the inactive queue prematurely again. Here we check the
829 * page tables (or emulated bits, if any), given the upper
830 * level VM system not knowing anything about existing
833 } else if (((m->flags & PG_REFERENCED) == 0) &&
834 (actcount = pmap_ts_referenced(m))) {
836 VM_OBJECT_UNLOCK(object);
837 m->act_count += (actcount + ACT_ADVANCE);
842 * If the upper level VM system knows about any page
843 * references, we activate the page. We also set the
844 * "activation count" higher than normal so that we will less
845 * likely place pages back onto the inactive queue again.
847 if ((m->flags & PG_REFERENCED) != 0) {
848 vm_page_flag_clear(m, PG_REFERENCED);
849 actcount = pmap_ts_referenced(m);
851 VM_OBJECT_UNLOCK(object);
852 m->act_count += (actcount + ACT_ADVANCE + 1);
857 * If the upper level VM system doesn't know anything about
858 * the page being dirty, we have to check for it again. As
859 * far as the VM code knows, any partially dirty pages are
862 if (m->dirty == 0 && !pmap_is_modified(m)) {
864 * Avoid a race condition: Unless write access is
865 * removed from the page, another processor could
866 * modify it before all access is removed by the call
867 * to vm_page_cache() below. If vm_page_cache() finds
868 * that the page has been modified when it removes all
869 * access, it panics because it cannot cache dirty
870 * pages. In principle, we could eliminate just write
871 * access here rather than all access. In the expected
872 * case, when there are no last instant modifications
873 * to the page, removing all access will be cheaper
876 if ((m->flags & PG_WRITEABLE) != 0)
884 * Invalid pages can be easily freed
890 } else if (m->dirty == 0) {
892 * Clean pages can be placed onto the cache queue.
893 * This effectively frees them.
897 } else if ((m->flags & PG_WINATCFLS) == 0 && pass == 0) {
899 * Dirty pages need to be paged out, but flushing
900 * a page is extremely expensive verses freeing
901 * a clean page. Rather then artificially limiting
902 * the number of pages we can flush, we instead give
903 * dirty pages extra priority on the inactive queue
904 * by forcing them to be cycled through the queue
905 * twice before being flushed, after which the
906 * (now clean) page will cycle through once more
907 * before being freed. This significantly extends
908 * the thrash point for a heavily loaded machine.
910 vm_page_flag_set(m, PG_WINATCFLS);
912 } else if (maxlaunder > 0) {
914 * We always want to try to flush some dirty pages if
915 * we encounter them, to keep the system stable.
916 * Normally this number is small, but under extreme
917 * pressure where there are insufficient clean pages
918 * on the inactive queue, we may have to go all out.
920 int swap_pageouts_ok;
921 struct vnode *vp = NULL;
924 if ((object->type != OBJT_SWAP) && (object->type != OBJT_DEFAULT)) {
925 swap_pageouts_ok = 1;
927 swap_pageouts_ok = !(defer_swap_pageouts || disable_swap_pageouts);
928 swap_pageouts_ok |= (!disable_swap_pageouts && defer_swap_pageouts &&
929 vm_page_count_min());
934 * We don't bother paging objects that are "dead".
935 * Those objects are in a "rundown" state.
937 if (!swap_pageouts_ok || (object->flags & OBJ_DEAD)) {
938 VM_OBJECT_UNLOCK(object);
944 * The object is already known NOT to be dead. It
945 * is possible for the vget() to block the whole
946 * pageout daemon, but the new low-memory handling
947 * code should prevent it.
949 * The previous code skipped locked vnodes and, worse,
950 * reordered pages in the queue. This results in
951 * completely non-deterministic operation and, on a
952 * busy system, can lead to extremely non-optimal
953 * pageouts. For example, it can cause clean pages
954 * to be freed and dirty pages to be moved to the end
955 * of the queue. Since dirty pages are also moved to
956 * the end of the queue once-cleaned, this gives
957 * way too large a weighting to defering the freeing
960 * We can't wait forever for the vnode lock, we might
961 * deadlock due to a vn_read() getting stuck in
962 * vm_wait while holding this vnode. We skip the
963 * vnode if we can't get it in a reasonable amount
966 if (object->type == OBJT_VNODE) {
969 if (vp->v_type == VREG)
970 vn_start_write(vp, &mp, V_NOWAIT);
971 vm_page_unlock_queues();
973 VM_OBJECT_UNLOCK(object);
974 if (vget(vp, LK_EXCLUSIVE | LK_INTERLOCK |
975 LK_TIMELOCK, curthread)) {
976 VM_OBJECT_LOCK(object);
977 vm_page_lock_queues();
979 vn_finished_write(mp);
980 if (object->flags & OBJ_MIGHTBEDIRTY)
982 VM_OBJECT_UNLOCK(object);
985 VM_OBJECT_LOCK(object);
986 vm_page_lock_queues();
988 * The page might have been moved to another
989 * queue during potential blocking in vget()
990 * above. The page might have been freed and
991 * reused for another vnode. The object might
992 * have been reused for another vnode.
994 if (m->queue != PQ_INACTIVE ||
995 m->object != object ||
996 object->handle != vp) {
997 if (object->flags & OBJ_MIGHTBEDIRTY)
999 goto unlock_and_continue;
1003 * The page may have been busied during the
1004 * blocking in vput(); We don't move the
1005 * page back onto the end of the queue so that
1006 * statistics are more correct if we don't.
1008 if (m->busy || (m->flags & PG_BUSY)) {
1009 goto unlock_and_continue;
1013 * If the page has become held it might
1014 * be undergoing I/O, so skip it
1016 if (m->hold_count) {
1017 vm_pageq_requeue(m);
1018 if (object->flags & OBJ_MIGHTBEDIRTY)
1020 goto unlock_and_continue;
1025 * If a page is dirty, then it is either being washed
1026 * (but not yet cleaned) or it is still in the
1027 * laundry. If it is still in the laundry, then we
1028 * start the cleaning operation.
1030 * This operation may cluster, invalidating the 'next'
1031 * pointer. To prevent an inordinate number of
1032 * restarts we use our marker to remember our place.
1034 * decrement page_shortage on success to account for
1035 * the (future) cleaned page. Otherwise we could wind
1036 * up laundering or cleaning too many pages.
1038 TAILQ_INSERT_AFTER(&vm_page_queues[PQ_INACTIVE].pl, m, &marker, pageq);
1039 if (vm_pageout_clean(m) != 0) {
1043 next = TAILQ_NEXT(&marker, pageq);
1044 TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE].pl, &marker, pageq);
1045 unlock_and_continue:
1046 VM_OBJECT_UNLOCK(object);
1048 vm_page_unlock_queues();
1050 vn_finished_write(mp);
1051 vm_page_lock_queues();
1055 VM_OBJECT_UNLOCK(object);
1059 * Compute the number of pages we want to try to move from the
1060 * active queue to the inactive queue.
1062 page_shortage = vm_paging_target() +
1063 cnt.v_inactive_target - cnt.v_inactive_count;
1064 page_shortage += addl_page_shortage;
1067 * Scan the active queue for things we can deactivate. We nominally
1068 * track the per-page activity counter and use it to locate
1069 * deactivation candidates.
1071 pcount = cnt.v_active_count;
1072 m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1074 while ((m != NULL) && (pcount-- > 0) && (page_shortage > 0)) {
1076 KASSERT(m->queue == PQ_ACTIVE,
1077 ("vm_pageout_scan: page %p isn't active", m));
1079 next = TAILQ_NEXT(m, pageq);
1081 if ((m->flags & PG_MARKER) != 0) {
1085 if (!VM_OBJECT_TRYLOCK(object) &&
1086 !vm_pageout_fallback_object_lock(m, &next)) {
1087 VM_OBJECT_UNLOCK(object);
1093 * Don't deactivate pages that are busy.
1095 if ((m->busy != 0) ||
1096 (m->flags & PG_BUSY) ||
1097 (m->hold_count != 0)) {
1098 VM_OBJECT_UNLOCK(object);
1099 vm_pageq_requeue(m);
1105 * The count for pagedaemon pages is done after checking the
1106 * page for eligibility...
1111 * Check to see "how much" the page has been used.
1114 if (object->ref_count != 0) {
1115 if (m->flags & PG_REFERENCED) {
1118 actcount += pmap_ts_referenced(m);
1120 m->act_count += ACT_ADVANCE + actcount;
1121 if (m->act_count > ACT_MAX)
1122 m->act_count = ACT_MAX;
1127 * Since we have "tested" this bit, we need to clear it now.
1129 vm_page_flag_clear(m, PG_REFERENCED);
1132 * Only if an object is currently being used, do we use the
1133 * page activation count stats.
1135 if (actcount && (object->ref_count != 0)) {
1136 vm_pageq_requeue(m);
1138 m->act_count -= min(m->act_count, ACT_DECLINE);
1139 if (vm_pageout_algorithm ||
1140 object->ref_count == 0 ||
1141 m->act_count == 0) {
1143 if (object->ref_count == 0) {
1148 vm_page_deactivate(m);
1150 vm_page_deactivate(m);
1153 vm_pageq_requeue(m);
1156 VM_OBJECT_UNLOCK(object);
1161 * We try to maintain some *really* free pages, this allows interrupt
1162 * code to be guaranteed space. Since both cache and free queues
1163 * are considered basically 'free', moving pages from cache to free
1164 * does not effect other calculations.
1166 cache_cur = cache_last_free;
1167 cache_first_failure = -1;
1168 while (cnt.v_free_count < cnt.v_free_reserved && (cache_cur =
1169 (cache_cur + PQ_PRIME2) & PQ_L2_MASK) != cache_first_failure) {
1170 TAILQ_FOREACH(m, &vm_page_queues[PQ_CACHE + cache_cur].pl,
1172 KASSERT(m->dirty == 0,
1173 ("Found dirty cache page %p", m));
1174 KASSERT(!pmap_page_is_mapped(m),
1175 ("Found mapped cache page %p", m));
1176 KASSERT((m->flags & PG_UNMANAGED) == 0,
1177 ("Found unmanaged cache page %p", m));
1178 KASSERT(m->wire_count == 0,
1179 ("Found wired cache page %p", m));
1180 if (m->hold_count == 0 && VM_OBJECT_TRYLOCK(object =
1182 KASSERT((m->flags & PG_BUSY) == 0 &&
1183 m->busy == 0, ("Found busy cache page %p",
1186 VM_OBJECT_UNLOCK(object);
1188 cache_last_free = cache_cur;
1189 cache_first_failure = -1;
1193 if (m == NULL && cache_first_failure == -1)
1194 cache_first_failure = cache_cur;
1196 vm_page_unlock_queues();
1197 #if !defined(NO_SWAPPING)
1199 * Idle process swapout -- run once per second.
1201 if (vm_swap_idle_enabled) {
1203 if (time_second != lsec) {
1204 vm_pageout_req_swapout |= VM_SWAP_IDLE;
1212 * If we didn't get enough free pages, and we have skipped a vnode
1213 * in a writeable object, wakeup the sync daemon. And kick swapout
1214 * if we did not get enough free pages.
1216 if (vm_paging_target() > 0) {
1217 if (vnodes_skipped && vm_page_count_min())
1218 (void) speedup_syncer();
1219 #if !defined(NO_SWAPPING)
1220 if (vm_swap_enabled && vm_page_count_target()) {
1222 vm_pageout_req_swapout |= VM_SWAP_NORMAL;
1228 * If we are critically low on one of RAM or swap and low on
1229 * the other, kill the largest process. However, we avoid
1230 * doing this on the first pass in order to give ourselves a
1231 * chance to flush out dirty vnode-backed pages and to allow
1232 * active pages to be moved to the inactive queue and reclaimed.
1234 * We keep the process bigproc locked once we find it to keep anyone
1235 * from messing with it; however, there is a possibility of
1236 * deadlock if process B is bigproc and one of it's child processes
1237 * attempts to propagate a signal to B while we are waiting for A's
1238 * lock while walking this list. To avoid this, we don't block on
1239 * the process lock but just skip a process if it is already locked.
1242 ((swap_pager_avail < 64 && vm_page_count_min()) ||
1243 (swap_pager_full && vm_paging_target() > 0))) {
1246 sx_slock(&allproc_lock);
1247 FOREACH_PROC_IN_SYSTEM(p) {
1250 if (PROC_TRYLOCK(p) == 0)
1253 * If this is a system or protected process, skip it.
1255 if ((p->p_flag & P_SYSTEM) || (p->p_pid == 1) ||
1256 (p->p_flag & P_PROTECTED) ||
1257 ((p->p_pid < 48) && (swap_pager_avail != 0))) {
1262 * If the process is in a non-running type state,
1263 * don't touch it. Check all the threads individually.
1265 mtx_lock_spin(&sched_lock);
1267 FOREACH_THREAD_IN_PROC(p, td) {
1268 if (!TD_ON_RUNQ(td) &&
1269 !TD_IS_RUNNING(td) &&
1270 !TD_IS_SLEEPING(td)) {
1276 mtx_unlock_spin(&sched_lock);
1280 mtx_unlock_spin(&sched_lock);
1282 * get the process size
1284 if (!vm_map_trylock_read(&p->p_vmspace->vm_map)) {
1288 size = vmspace_swap_count(p->p_vmspace);
1289 vm_map_unlock_read(&p->p_vmspace->vm_map);
1290 size += vmspace_resident_count(p->p_vmspace);
1292 * if the this process is bigger than the biggest one
1295 if (size > bigsize) {
1296 if (bigproc != NULL)
1297 PROC_UNLOCK(bigproc);
1303 sx_sunlock(&allproc_lock);
1304 if (bigproc != NULL) {
1305 killproc(bigproc, "out of swap space");
1306 mtx_lock_spin(&sched_lock);
1307 sched_nice(bigproc, PRIO_MIN);
1308 mtx_unlock_spin(&sched_lock);
1309 PROC_UNLOCK(bigproc);
1310 wakeup(&cnt.v_free_count);
1317 * This routine tries to maintain the pseudo LRU active queue,
1318 * so that during long periods of time where there is no paging,
1319 * that some statistic accumulation still occurs. This code
1320 * helps the situation where paging just starts to occur.
1323 vm_pageout_page_stats()
1327 int pcount,tpcount; /* Number of pages to check */
1328 static int fullintervalcount = 0;
1331 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1333 (cnt.v_inactive_target + cnt.v_cache_max + cnt.v_free_min) -
1334 (cnt.v_free_count + cnt.v_inactive_count + cnt.v_cache_count);
1336 if (page_shortage <= 0)
1339 pcount = cnt.v_active_count;
1340 fullintervalcount += vm_pageout_stats_interval;
1341 if (fullintervalcount < vm_pageout_full_stats_interval) {
1342 tpcount = (vm_pageout_stats_max * cnt.v_active_count) / cnt.v_page_count;
1343 if (pcount > tpcount)
1346 fullintervalcount = 0;
1349 m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1350 while ((m != NULL) && (pcount-- > 0)) {
1353 KASSERT(m->queue == PQ_ACTIVE,
1354 ("vm_pageout_page_stats: page %p isn't active", m));
1356 next = TAILQ_NEXT(m, pageq);
1359 if ((m->flags & PG_MARKER) != 0) {
1363 if (!VM_OBJECT_TRYLOCK(object) &&
1364 !vm_pageout_fallback_object_lock(m, &next)) {
1365 VM_OBJECT_UNLOCK(object);
1371 * Don't deactivate pages that are busy.
1373 if ((m->busy != 0) ||
1374 (m->flags & PG_BUSY) ||
1375 (m->hold_count != 0)) {
1376 VM_OBJECT_UNLOCK(object);
1377 vm_pageq_requeue(m);
1383 if (m->flags & PG_REFERENCED) {
1384 vm_page_flag_clear(m, PG_REFERENCED);
1388 actcount += pmap_ts_referenced(m);
1390 m->act_count += ACT_ADVANCE + actcount;
1391 if (m->act_count > ACT_MAX)
1392 m->act_count = ACT_MAX;
1393 vm_pageq_requeue(m);
1395 if (m->act_count == 0) {
1397 * We turn off page access, so that we have
1398 * more accurate RSS stats. We don't do this
1399 * in the normal page deactivation when the
1400 * system is loaded VM wise, because the
1401 * cost of the large number of page protect
1402 * operations would be higher than the value
1403 * of doing the operation.
1406 vm_page_deactivate(m);
1408 m->act_count -= min(m->act_count, ACT_DECLINE);
1409 vm_pageq_requeue(m);
1412 VM_OBJECT_UNLOCK(object);
1418 * vm_pageout is the high level pageout daemon.
1426 * Initialize some paging parameters.
1428 cnt.v_interrupt_free_min = 2;
1429 if (cnt.v_page_count < 2000)
1430 vm_pageout_page_count = 8;
1433 * v_free_reserved needs to include enough for the largest
1434 * swap pager structures plus enough for any pv_entry structs
1437 if (cnt.v_page_count > 1024)
1438 cnt.v_free_min = 4 + (cnt.v_page_count - 1024) / 200;
1441 cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1442 cnt.v_interrupt_free_min;
1443 cnt.v_free_reserved = vm_pageout_page_count +
1444 cnt.v_pageout_free_min + (cnt.v_page_count / 768) + PQ_L2_SIZE;
1445 cnt.v_free_severe = cnt.v_free_min / 2;
1446 cnt.v_free_min += cnt.v_free_reserved;
1447 cnt.v_free_severe += cnt.v_free_reserved;
1450 * v_free_target and v_cache_min control pageout hysteresis. Note
1451 * that these are more a measure of the VM cache queue hysteresis
1452 * then the VM free queue. Specifically, v_free_target is the
1453 * high water mark (free+cache pages).
1455 * v_free_reserved + v_cache_min (mostly means v_cache_min) is the
1456 * low water mark, while v_free_min is the stop. v_cache_min must
1457 * be big enough to handle memory needs while the pageout daemon
1458 * is signalled and run to free more pages.
1460 if (cnt.v_free_count > 6144)
1461 cnt.v_free_target = 4 * cnt.v_free_min + cnt.v_free_reserved;
1463 cnt.v_free_target = 2 * cnt.v_free_min + cnt.v_free_reserved;
1465 if (cnt.v_free_count > 2048) {
1466 cnt.v_cache_min = cnt.v_free_target;
1467 cnt.v_cache_max = 2 * cnt.v_cache_min;
1468 cnt.v_inactive_target = (3 * cnt.v_free_target) / 2;
1470 cnt.v_cache_min = 0;
1471 cnt.v_cache_max = 0;
1472 cnt.v_inactive_target = cnt.v_free_count / 4;
1474 if (cnt.v_inactive_target > cnt.v_free_count / 3)
1475 cnt.v_inactive_target = cnt.v_free_count / 3;
1477 /* XXX does not really belong here */
1478 if (vm_page_max_wired == 0)
1479 vm_page_max_wired = cnt.v_free_count / 3;
1481 if (vm_pageout_stats_max == 0)
1482 vm_pageout_stats_max = cnt.v_free_target;
1485 * Set interval in seconds for stats scan.
1487 if (vm_pageout_stats_interval == 0)
1488 vm_pageout_stats_interval = 5;
1489 if (vm_pageout_full_stats_interval == 0)
1490 vm_pageout_full_stats_interval = vm_pageout_stats_interval * 4;
1492 swap_pager_swap_init();
1495 * The pageout daemon is never done, so loop forever.
1498 vm_page_lock_queues();
1500 * If we have enough free memory, wakeup waiters. Do
1501 * not clear vm_pages_needed until we reach our target,
1502 * otherwise we may be woken up over and over again and
1503 * waste a lot of cpu.
1505 if (vm_pages_needed && !vm_page_count_min()) {
1506 if (!vm_paging_needed())
1507 vm_pages_needed = 0;
1508 wakeup(&cnt.v_free_count);
1510 if (vm_pages_needed) {
1512 * Still not done, take a second pass without waiting
1513 * (unlimited dirty cleaning), otherwise sleep a bit
1518 msleep(&vm_pages_needed, &vm_page_queue_mtx, PVM,
1522 * Good enough, sleep & handle stats. Prime the pass
1529 error = msleep(&vm_pages_needed, &vm_page_queue_mtx, PVM,
1530 "psleep", vm_pageout_stats_interval * hz);
1531 if (error && !vm_pages_needed) {
1533 vm_pageout_page_stats();
1534 vm_page_unlock_queues();
1538 if (vm_pages_needed)
1540 vm_page_unlock_queues();
1541 vm_pageout_scan(pass);
1546 * Unless the page queue lock is held by the caller, this function
1547 * should be regarded as advisory. Specifically, the caller should
1548 * not msleep() on &cnt.v_free_count following this function unless
1549 * the page queue lock is held until the msleep() is performed.
1555 if (!vm_pages_needed && curthread->td_proc != pageproc) {
1556 vm_pages_needed = 1;
1557 wakeup(&vm_pages_needed);
1561 #if !defined(NO_SWAPPING)
1565 static int lastrun = 0;
1567 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
1568 wakeup(&vm_daemon_needed);
1576 struct rlimit rsslim;
1583 tsleep(&vm_daemon_needed, PPAUSE, "psleep", 0);
1584 if (vm_pageout_req_swapout) {
1585 swapout_procs(vm_pageout_req_swapout);
1586 vm_pageout_req_swapout = 0;
1589 * scan the processes for exceeding their rlimits or if
1590 * process is swapped out -- deactivate pages
1592 sx_slock(&allproc_lock);
1593 LIST_FOREACH(p, &allproc, p_list) {
1594 vm_pindex_t limit, size;
1597 * if this is a system process or if we have already
1598 * looked at this process, skip it.
1601 if (p->p_flag & (P_SYSTEM | P_WEXIT)) {
1606 * if the process is in a non-running type state,
1609 mtx_lock_spin(&sched_lock);
1611 FOREACH_THREAD_IN_PROC(p, td) {
1612 if (!TD_ON_RUNQ(td) &&
1613 !TD_IS_RUNNING(td) &&
1614 !TD_IS_SLEEPING(td)) {
1619 mtx_unlock_spin(&sched_lock);
1627 lim_rlimit(p, RLIMIT_RSS, &rsslim);
1629 qmin(rsslim.rlim_cur, rsslim.rlim_max));
1632 * let processes that are swapped out really be
1633 * swapped out set the limit to nothing (will force a
1636 if ((p->p_sflag & PS_INMEM) == 0)
1637 limit = 0; /* XXX */
1640 size = vmspace_resident_count(p->p_vmspace);
1641 if (limit >= 0 && size >= limit) {
1642 vm_pageout_map_deactivate_pages(
1643 &p->p_vmspace->vm_map, limit);
1646 sx_sunlock(&allproc_lock);
1649 #endif /* !defined(NO_SWAPPING) */