2 * Copyright (c) 1991 Regents of the University of California.
4 * Copyright (c) 1994 John S. Dyson
6 * Copyright (c) 1994 David Greenman
9 * This code is derived from software contributed to Berkeley by
10 * The Mach Operating System project at Carnegie-Mellon University.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * from: @(#)vm_pageout.c 7.4 (Berkeley) 5/7/91
39 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
40 * All rights reserved.
42 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
44 * Permission to use, copy, modify and distribute this software and
45 * its documentation is hereby granted, provided that both the copyright
46 * notice and this permission notice appear in all copies of the
47 * software, derivative works or modified versions, and any portions
48 * thereof, and that both notices appear in supporting documentation.
50 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
51 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
52 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
54 * Carnegie Mellon requests users of this software to return to
56 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
57 * School of Computer Science
58 * Carnegie Mellon University
59 * Pittsburgh PA 15213-3890
61 * any improvements or extensions that they make and grant Carnegie the
62 * rights to redistribute these changes.
64 * $FreeBSD: src/sys/vm/vm_pageout.c,v 1.151.2.15 2002/12/29 18:21:04 dillon Exp $
68 * The proverbial page-out daemon.
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/kernel.h>
76 #include <sys/kthread.h>
77 #include <sys/resourcevar.h>
78 #include <sys/signalvar.h>
79 #include <sys/vnode.h>
80 #include <sys/vmmeter.h>
82 #include <sys/sysctl.h>
85 #include <vm/vm_param.h>
87 #include <vm/vm_object.h>
88 #include <vm/vm_page.h>
89 #include <vm/vm_map.h>
90 #include <vm/vm_pageout.h>
91 #include <vm/vm_pager.h>
92 #include <vm/swap_pager.h>
93 #include <vm/vm_extern.h>
95 #include <sys/spinlock2.h>
96 #include <vm/vm_page2.h>
99 * System initialization
102 /* the kernel process "vm_pageout"*/
103 static int vm_pageout_page(vm_page_t m, long *max_launderp,
104 long *vnodes_skippedp, struct vnode **vpfailedp,
105 int pass, int vmflush_flags);
106 static int vm_pageout_clean_helper (vm_page_t, int);
107 static void vm_pageout_free_page_calc (vm_size_t count);
108 static void vm_pageout_page_free(vm_page_t m) ;
109 struct thread *emergpager;
110 struct thread *pagethread;
111 static int sequence_emerg_pager;
113 #if !defined(NO_SWAPPING)
114 /* the kernel process "vm_daemon"*/
115 static void vm_daemon (void);
116 static struct thread *vmthread;
118 static struct kproc_desc vm_kp = {
123 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
126 int vm_pages_needed = 0; /* Event on which pageout daemon sleeps */
127 int vm_pageout_deficit = 0; /* Estimated number of pages deficit */
128 int vm_pageout_pages_needed = 0;/* pageout daemon needs pages */
129 int vm_page_free_hysteresis = 16;
130 static int vm_pagedaemon_time;
132 #if !defined(NO_SWAPPING)
133 static int vm_pageout_req_swapout;
134 static int vm_daemon_needed;
136 __read_mostly static int vm_max_launder = 4096;
137 __read_mostly static int vm_emerg_launder = 100;
138 __read_mostly static int vm_pageout_stats_max=0, vm_pageout_stats_interval = 0;
139 __read_mostly static int vm_pageout_full_stats_interval = 0;
140 __read_mostly static int vm_pageout_stats_free_max=0, vm_pageout_algorithm=0;
141 __read_mostly static int defer_swap_pageouts=0;
142 __read_mostly static int disable_swap_pageouts=0;
143 __read_mostly static u_int vm_anonmem_decline = ACT_DECLINE;
144 __read_mostly static u_int vm_filemem_decline = ACT_DECLINE * 2;
145 __read_mostly static int vm_pageout_debug;
147 #if defined(NO_SWAPPING)
148 __read_mostly static int vm_swap_enabled=0;
149 __read_mostly static int vm_swap_idle_enabled=0;
151 __read_mostly static int vm_swap_enabled=1;
152 __read_mostly static int vm_swap_idle_enabled=0;
155 /* 0-disable, 1-passive, 2-active swp*/
156 __read_mostly int vm_pageout_memuse_mode=1;
158 SYSCTL_UINT(_vm, VM_PAGEOUT_ALGORITHM, anonmem_decline,
159 CTLFLAG_RW, &vm_anonmem_decline, 0, "active->inactive anon memory");
161 SYSCTL_INT(_vm, VM_PAGEOUT_ALGORITHM, filemem_decline,
162 CTLFLAG_RW, &vm_filemem_decline, 0, "active->inactive file cache");
164 SYSCTL_INT(_vm, OID_AUTO, page_free_hysteresis,
165 CTLFLAG_RW, &vm_page_free_hysteresis, 0,
166 "Free more pages than the minimum required");
168 SYSCTL_INT(_vm, OID_AUTO, max_launder,
169 CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
170 SYSCTL_INT(_vm, OID_AUTO, emerg_launder,
171 CTLFLAG_RW, &vm_emerg_launder, 0, "Emergency pager minimum");
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 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_free_max,
183 CTLFLAG_RW, &vm_pageout_stats_free_max, 0, "Not implemented");
184 SYSCTL_INT(_vm, OID_AUTO, pageout_memuse_mode,
185 CTLFLAG_RW, &vm_pageout_memuse_mode, 0, "memoryuse resource mode");
186 SYSCTL_INT(_vm, OID_AUTO, pageout_debug,
187 CTLFLAG_RW, &vm_pageout_debug, 0, "debug pageout pages (count)");
190 #if defined(NO_SWAPPING)
191 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
192 CTLFLAG_RD, &vm_swap_enabled, 0, "");
193 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
194 CTLFLAG_RD, &vm_swap_idle_enabled, 0, "");
196 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
197 CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
198 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
199 CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
202 SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
203 CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
205 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
206 CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
208 static int pageout_lock_miss;
209 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
210 CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
212 int vm_page_max_wired; /* XXX max # of wired pages system-wide */
214 #if !defined(NO_SWAPPING)
215 static void vm_req_vmdaemon (void);
217 static void vm_pageout_page_stats(int q);
220 * Calculate approximately how many pages on each queue to try to
221 * clean. An exact calculation creates an edge condition when the
222 * queues are unbalanced so add significant slop. The queue scans
223 * will stop early when targets are reached and will start where they
224 * left off on the next pass.
226 * We need to be generous here because there are all sorts of loading
227 * conditions that can cause edge cases if try to average over all queues.
228 * In particular, storage subsystems have become so fast that paging
229 * activity can become quite frantic. Eventually we will probably need
230 * two paging threads, one for dirty pages and one for clean, to deal
231 * with the bandwidth requirements.
233 * So what we do is calculate a value that can be satisfied nominally by
234 * only having to scan half the queues.
242 avg = ((n + (PQ_L2_SIZE - 1)) / (PQ_L2_SIZE / 2) + 1);
244 avg = ((n - (PQ_L2_SIZE - 1)) / (PQ_L2_SIZE / 2) - 1);
250 * vm_pageout_clean_helper:
252 * Clean the page and remove it from the laundry. The page must be busied
253 * by the caller and will be disposed of (put away, flushed) by this routine.
256 vm_pageout_clean_helper(vm_page_t m, int vmflush_flags)
259 vm_page_t mc[BLIST_MAX_ALLOC];
261 int ib, is, page_base;
262 vm_pindex_t pindex = m->pindex;
267 * Don't mess with the page if it's held or special. Theoretically
268 * we can pageout held pages but there is no real need to press our
271 if (m->hold_count != 0 || (m->flags & PG_UNQUEUED)) {
277 * Place page in cluster. Align cluster for optimal swap space
278 * allocation (whether it is swap or not). This is typically ~16-32
279 * pages, which also tends to align the cluster to multiples of the
280 * filesystem block size if backed by a filesystem.
282 page_base = pindex % BLIST_MAX_ALLOC;
288 * Scan object for clusterable pages.
290 * We can cluster ONLY if: ->> the page is NOT
291 * clean, wired, busy, held, or mapped into a
292 * buffer, and one of the following:
293 * 1) The page is inactive, or a seldom used
296 * 2) we force the issue.
298 * During heavy mmap/modification loads the pageout
299 * daemon can really fragment the underlying file
300 * due to flushing pages out of order and not trying
301 * align the clusters (which leave sporatic out-of-order
302 * holes). To solve this problem we do the reverse scan
303 * first and attempt to align our cluster, then do a
304 * forward scan if room remains.
306 vm_object_hold(object);
311 p = vm_page_lookup_busy_try(object, pindex - page_base + ib,
313 if (error || p == NULL)
315 if ((p->queue - p->pc) == PQ_CACHE ||
316 (p->flags & PG_UNQUEUED)) {
320 vm_page_test_dirty(p);
321 if (((p->dirty & p->valid) == 0 &&
322 (p->flags & PG_NEED_COMMIT) == 0) ||
323 p->wire_count != 0 || /* may be held by buf cache */
324 p->hold_count != 0) { /* may be undergoing I/O */
328 if (p->queue - p->pc != PQ_INACTIVE) {
329 if (p->queue - p->pc != PQ_ACTIVE ||
330 (vmflush_flags & VM_PAGER_ALLOW_ACTIVE) == 0) {
337 * Try to maintain page groupings in the cluster.
339 if (m->flags & PG_WINATCFLS)
340 vm_page_flag_set(p, PG_WINATCFLS);
342 vm_page_flag_clear(p, PG_WINATCFLS);
343 p->act_count = m->act_count;
350 while (is < BLIST_MAX_ALLOC &&
351 pindex - page_base + is < object->size) {
354 p = vm_page_lookup_busy_try(object, pindex - page_base + is,
356 if (error || p == NULL)
358 if (((p->queue - p->pc) == PQ_CACHE) ||
359 (p->flags & PG_UNQUEUED)) {
363 vm_page_test_dirty(p);
364 if (((p->dirty & p->valid) == 0 &&
365 (p->flags & PG_NEED_COMMIT) == 0) ||
366 p->wire_count != 0 || /* may be held by buf cache */
367 p->hold_count != 0) { /* may be undergoing I/O */
371 if (p->queue - p->pc != PQ_INACTIVE) {
372 if (p->queue - p->pc != PQ_ACTIVE ||
373 (vmflush_flags & VM_PAGER_ALLOW_ACTIVE) == 0) {
380 * Try to maintain page groupings in the cluster.
382 if (m->flags & PG_WINATCFLS)
383 vm_page_flag_set(p, PG_WINATCFLS);
385 vm_page_flag_clear(p, PG_WINATCFLS);
386 p->act_count = m->act_count;
392 vm_object_drop(object);
395 * we allow reads during pageouts...
397 return vm_pageout_flush(&mc[ib], is - ib, vmflush_flags);
401 * vm_pageout_flush() - launder the given pages
403 * The given pages are laundered. Note that we setup for the start of
404 * I/O ( i.e. busy the page ), mark it read-only, and bump the object
405 * reference count all in here rather then in the parent. If we want
406 * the parent to do more sophisticated things we may have to change
409 * The pages in the array must be busied by the caller and will be
410 * unbusied by this function.
413 vm_pageout_flush(vm_page_t *mc, int count, int vmflush_flags)
416 int pageout_status[count];
421 if (vm_pageout_debug > 0) {
429 * Initiate I/O. Bump the vm_page_t->busy counter.
431 for (i = 0; i < count; i++) {
432 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
433 ("vm_pageout_flush page %p index %d/%d: partially "
434 "invalid page", mc[i], i, count));
435 vm_page_io_start(mc[i]);
439 * We must make the pages read-only. This will also force the
440 * modified bit in the related pmaps to be cleared. The pager
441 * cannot clear the bit for us since the I/O completion code
442 * typically runs from an interrupt. The act of making the page
443 * read-only handles the case for us.
445 * Then we can unbusy the pages, we still hold a reference by virtue
449 kprintf("pageout: ");
450 for (i = 0; i < count; i++) {
451 if (vmflush_flags & VM_PAGER_TRY_TO_CACHE)
452 vm_page_protect(mc[i], VM_PROT_NONE);
454 vm_page_protect(mc[i], VM_PROT_READ);
455 vm_page_wakeup(mc[i]);
457 kprintf(" %p", mc[i]);
462 object = mc[0]->object;
463 vm_object_pip_add(object, count);
465 vm_pager_put_pages(object, mc, count,
467 ((object == &kernel_object) ?
468 VM_PAGER_PUT_SYNC : 0)),
473 for (i = 0; i < count; i++) {
474 vm_page_t mt = mc[i];
477 kprintf(" S%d", pageout_status[i]);
479 switch (pageout_status[i]) {
488 * Page outside of range of object. Right now we
489 * essentially lose the changes by pretending it
492 vm_page_busy_wait(mt, FALSE, "pgbad");
493 pmap_clear_modify(mt);
500 * A page typically cannot be paged out when we
501 * have run out of swap. We leave the page
502 * marked inactive and will try to page it out
505 * Starvation of the active page list is used to
506 * determine when the system is massively memory
515 * If not PENDing this was a synchronous operation and we
516 * clean up after the I/O. If it is PENDing the mess is
517 * cleaned up asynchronously.
519 * Also nominally act on the caller's wishes if the caller
520 * wants to try to really clean (cache or free) the page.
522 * Also nominally deactivate the page if the system is
525 if (pageout_status[i] != VM_PAGER_PEND) {
526 vm_page_busy_wait(mt, FALSE, "pgouw");
527 vm_page_io_finish(mt);
528 if (vmflush_flags & VM_PAGER_TRY_TO_CACHE) {
529 vm_page_try_to_cache(mt);
531 kprintf("A[pq_cache=%d]",
532 ((mt->queue - mt->pc) == PQ_CACHE));
533 } else if (vm_page_count_severe()) {
534 vm_page_deactivate(mt);
543 vm_object_pip_wakeup(object);
551 #if !defined(NO_SWAPPING)
554 * Callback function, page busied for us. We must dispose of the busy
555 * condition. Any related pmap pages may be held but will not be locked.
559 vm_pageout_mdp_callback(struct pmap_pgscan_info *info, vm_offset_t va,
566 * Basic tests - There should never be a marker, and we can stop
567 * once the RSS is below the required level.
569 KKASSERT((p->flags & PG_MARKER) == 0);
570 if (pmap_resident_tlnw_count(info->pmap) <= info->limit) {
575 mycpu->gd_cnt.v_pdpages++;
577 if (p->wire_count || p->hold_count || (p->flags & PG_UNQUEUED)) {
585 * Check if the page has been referened recently. If it has,
586 * activate it and skip.
588 actcount = pmap_ts_referenced(p);
590 vm_page_flag_set(p, PG_REFERENCED);
591 } else if (p->flags & PG_REFERENCED) {
596 if (p->queue - p->pc != PQ_ACTIVE) {
597 vm_page_and_queue_spin_lock(p);
598 if (p->queue - p->pc != PQ_ACTIVE) {
599 vm_page_and_queue_spin_unlock(p);
602 vm_page_and_queue_spin_unlock(p);
605 p->act_count += actcount;
606 if (p->act_count > ACT_MAX)
607 p->act_count = ACT_MAX;
609 vm_page_flag_clear(p, PG_REFERENCED);
615 * Remove the page from this particular pmap. Once we do this, our
616 * pmap scans will not see it again (unless it gets faulted in), so
617 * we must actively dispose of or deal with the page.
619 pmap_remove_specific(info->pmap, p);
622 * If the page is not mapped to another process (i.e. as would be
623 * typical if this were a shared page from a library) then deactivate
624 * the page and clean it in two passes only.
626 * If the page hasn't been referenced since the last check, remove it
627 * from the pmap. If it is no longer mapped, deactivate it
628 * immediately, accelerating the normal decline.
630 * Once the page has been removed from the pmap the RSS code no
631 * longer tracks it so we have to make sure that it is staged for
632 * potential flush action.
634 if ((p->flags & PG_MAPPED) == 0 ||
635 (pmap_mapped_sync(p) & PG_MAPPED) == 0) {
636 if (p->queue - p->pc == PQ_ACTIVE) {
637 vm_page_deactivate(p);
639 if (p->queue - p->pc == PQ_INACTIVE) {
645 * Ok, try to fully clean the page and any nearby pages such that at
646 * least the requested page is freed or moved to the cache queue.
648 * We usually do this synchronously to allow us to get the page into
649 * the CACHE queue quickly, which will prevent memory exhaustion if
650 * a process with a memoryuse limit is running away. However, the
651 * sysadmin may desire to set vm.swap_user_async which relaxes this
652 * and improves write performance.
655 long max_launder = 0x7FFF;
656 long vnodes_skipped = 0;
658 struct vnode *vpfailed = NULL;
662 if (vm_pageout_memuse_mode >= 2) {
663 vmflush_flags = VM_PAGER_TRY_TO_CACHE |
664 VM_PAGER_ALLOW_ACTIVE;
665 if (swap_user_async == 0)
666 vmflush_flags |= VM_PAGER_PUT_SYNC;
667 vm_page_flag_set(p, PG_WINATCFLS);
669 vm_pageout_page(p, &max_launder,
671 &vpfailed, 1, vmflush_flags);
681 * Must be at end to avoid SMP races.
689 * Deactivate some number of pages in a map due to set RLIMIT_RSS limits.
690 * that is relatively difficult to do. We try to keep track of where we
691 * left off last time to reduce scan overhead.
693 * Called when vm_pageout_memuse_mode is >= 1.
696 vm_pageout_map_deactivate_pages(vm_map_t map, vm_pindex_t limit)
698 vm_offset_t pgout_offset;
699 struct pmap_pgscan_info info;
702 pgout_offset = map->pgout_offset;
705 kprintf("%016jx ", pgout_offset);
707 if (pgout_offset < VM_MIN_USER_ADDRESS)
708 pgout_offset = VM_MIN_USER_ADDRESS;
709 if (pgout_offset >= VM_MAX_USER_ADDRESS)
711 info.pmap = vm_map_pmap(map);
713 info.beg_addr = pgout_offset;
714 info.end_addr = VM_MAX_USER_ADDRESS;
715 info.callback = vm_pageout_mdp_callback;
717 info.actioncount = 0;
721 pgout_offset = info.offset;
723 kprintf("%016jx %08lx %08lx\n", pgout_offset,
724 info.cleancount, info.actioncount);
727 if (pgout_offset != VM_MAX_USER_ADDRESS &&
728 pmap_resident_tlnw_count(vm_map_pmap(map)) > limit) {
730 } else if (retries &&
731 pmap_resident_tlnw_count(vm_map_pmap(map)) > limit) {
735 map->pgout_offset = pgout_offset;
740 * Called when the pageout scan wants to free a page. We no longer
741 * try to cycle the vm_object here with a reference & dealloc, which can
742 * cause a non-trivial object collapse in a critical path.
744 * It is unclear why we cycled the ref_count in the past, perhaps to try
745 * to optimize shadow chain collapses but I don't quite see why it would
746 * be necessary. An OBJ_DEAD object should terminate any and all vm_pages
747 * synchronously and not have to be kicked-start.
750 vm_pageout_page_free(vm_page_t m)
752 vm_page_protect(m, VM_PROT_NONE);
757 * vm_pageout_scan does the dirty work for the pageout daemon.
759 struct vm_pageout_scan_info {
760 struct proc *bigproc;
764 static int vm_pageout_scan_callback(struct proc *p, void *data);
767 * Scan inactive queue
769 * WARNING! Can be called from two pagedaemon threads simultaneously.
772 vm_pageout_scan_inactive(int pass, int q, long avail_shortage,
773 long *vnodes_skipped)
776 struct vm_page marker;
777 struct vnode *vpfailed; /* warning, allowed to be stale */
784 isep = (curthread == emergpager);
787 * Start scanning the inactive queue for pages we can move to the
788 * cache or free. The scan will stop when the target is reached or
789 * we have scanned the entire inactive queue. Note that m->act_count
790 * is not used to form decisions for the inactive queue, only for the
793 * max_launder limits the number of dirty pages we flush per scan.
794 * For most systems a smaller value (16 or 32) is more robust under
795 * extreme memory and disk pressure because any unnecessary writes
796 * to disk can result in extreme performance degredation. However,
797 * systems with excessive dirty pages (especially when MAP_NOSYNC is
798 * used) will die horribly with limited laundering. If the pageout
799 * daemon cannot clean enough pages in the first pass, we let it go
800 * all out in succeeding passes.
802 * NOTE! THE EMERGENCY PAGER (isep) DOES NOT LAUNDER VNODE-BACKED
805 if ((max_launder = vm_max_launder) <= 1)
811 * Initialize our marker
813 bzero(&marker, sizeof(marker));
814 marker.flags = PG_FICTITIOUS | PG_MARKER;
815 marker.busy_count = PBUSY_LOCKED;
816 marker.queue = PQ_INACTIVE + q;
818 marker.wire_count = 1;
821 * Inactive queue scan.
823 * NOTE: The vm_page must be spinlocked before the queue to avoid
824 * deadlocks, so it is easiest to simply iterate the loop
825 * with the queue unlocked at the top.
829 vm_page_queues_spin_lock(PQ_INACTIVE + q);
830 TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE + q].pl, &marker, pageq);
831 maxscan = vm_page_queues[PQ_INACTIVE + q].lcnt;
834 * Queue locked at top of loop to avoid stack marker issues.
836 while ((m = TAILQ_NEXT(&marker, pageq)) != NULL &&
837 maxscan-- > 0 && avail_shortage - delta > 0)
841 KKASSERT(m->queue == PQ_INACTIVE + q);
842 TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE + q].pl,
844 TAILQ_INSERT_AFTER(&vm_page_queues[PQ_INACTIVE + q].pl, m,
846 mycpu->gd_cnt.v_pdpages++;
849 * Skip marker pages (atomic against other markers to avoid
850 * infinite hop-over scans).
852 if (m->flags & PG_MARKER)
856 * Try to busy the page. Don't mess with pages which are
857 * already busy or reorder them in the queue.
859 if (vm_page_busy_try(m, TRUE))
863 * Remaining operations run with the page busy and neither
864 * the page or the queue will be spin-locked.
866 KKASSERT(m->queue == PQ_INACTIVE + q);
867 vm_page_queues_spin_unlock(PQ_INACTIVE + q);
870 * The emergency pager runs when the primary pager gets
871 * stuck, which typically means the primary pager deadlocked
872 * on a vnode-backed page. Therefore, the emergency pager
873 * must skip any complex objects.
875 * We disallow VNODEs unless they are VCHR whos device ops
876 * does not flag D_NOEMERGPGR.
878 if (isep && m->object) {
881 switch(m->object->type) {
885 * Allow anonymous memory and assume that
886 * swap devices are not complex, since its
887 * kinda worthless if we can't swap out dirty
893 * Allow VCHR device if the D_NOEMERGPGR
894 * flag is not set, deny other vnode types
895 * as being too complex.
897 vp = m->object->handle;
898 if (vp && vp->v_type == VCHR &&
899 vp->v_rdev && vp->v_rdev->si_ops &&
900 (vp->v_rdev->si_ops->head.flags &
901 D_NOEMERGPGR) == 0) {
904 /* Deny - fall through */
910 vm_page_queues_spin_lock(PQ_INACTIVE + q);
917 * Try to pageout the page and perhaps other nearby pages.
918 * We want to get the pages into the cache on the second
919 * pass. Otherwise the pages can wind up just cycling in
920 * the inactive queue, getting flushed over and over again.
922 if (m->flags & PG_WINATCFLS)
923 vmflush_flags = VM_PAGER_TRY_TO_CACHE;
926 count = vm_pageout_page(m, &max_launder, vnodes_skipped,
927 &vpfailed, pass, vmflush_flags);
931 * Systems with a ton of memory can wind up with huge
932 * deactivation counts. Because the inactive scan is
933 * doing a lot of flushing, the combination can result
934 * in excessive paging even in situations where other
935 * unrelated threads free up sufficient VM.
937 * To deal with this we abort the nominal active->inactive
938 * scan before we hit the inactive target when free+cache
939 * levels have reached a reasonable target.
941 * When deciding to stop early we need to add some slop to
942 * the test and we need to return full completion to the caller
943 * to prevent the caller from thinking there is something
944 * wrong and issuing a low-memory+swap warning or pkill.
946 * A deficit forces paging regardless of the state of the
947 * VM page queues (used for RSS enforcement).
950 vm_page_queues_spin_lock(PQ_INACTIVE + q);
951 if (vm_paging_target() < -vm_max_launder) {
953 * Stopping early, return full completion to caller.
955 if (delta < avail_shortage)
956 delta = avail_shortage;
961 /* page queue still spin-locked */
962 TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE + q].pl, &marker, pageq);
963 vm_page_queues_spin_unlock(PQ_INACTIVE + q);
969 * Pageout the specified page, return the total number of pages paged out
970 * (this routine may cluster).
972 * The page must be busied and soft-busied by the caller and will be disposed
973 * of by this function.
976 vm_pageout_page(vm_page_t m, long *max_launderp, long *vnodes_skippedp,
977 struct vnode **vpfailedp, int pass, int vmflush_flags)
984 * Wiring no longer removes a page from its queue. The last unwiring
985 * will requeue the page. Obviously wired pages cannot be paged out
986 * so unqueue it and return.
989 vm_page_unqueue_nowakeup(m);
995 * A held page may be undergoing I/O, so skip it.
998 vm_page_and_queue_spin_lock(m);
999 if (m->queue - m->pc == PQ_INACTIVE) {
1001 &vm_page_queues[m->queue].pl, m, pageq);
1003 &vm_page_queues[m->queue].pl, m, pageq);
1005 vm_page_and_queue_spin_unlock(m);
1010 if (m->object == NULL || m->object->ref_count == 0) {
1012 * If the object is not being used, we ignore previous
1015 vm_page_flag_clear(m, PG_REFERENCED);
1016 pmap_clear_reference(m);
1017 /* fall through to end */
1018 } else if (((m->flags & PG_REFERENCED) == 0) &&
1019 (actcount = pmap_ts_referenced(m))) {
1021 * Otherwise, if the page has been referenced while
1022 * in the inactive queue, we bump the "activation
1023 * count" upwards, making it less likely that the
1024 * page will be added back to the inactive queue
1025 * prematurely again. Here we check the page tables
1026 * (or emulated bits, if any), given the upper level
1027 * VM system not knowing anything about existing
1030 vm_page_activate(m);
1031 m->act_count += (actcount + ACT_ADVANCE);
1037 * (m) is still busied.
1039 * If the upper level VM system knows about any page
1040 * references, we activate the page. We also set the
1041 * "activation count" higher than normal so that we will less
1042 * likely place pages back onto the inactive queue again.
1044 if ((m->flags & PG_REFERENCED) != 0) {
1045 vm_page_flag_clear(m, PG_REFERENCED);
1046 actcount = pmap_ts_referenced(m);
1047 vm_page_activate(m);
1048 m->act_count += (actcount + ACT_ADVANCE + 1);
1054 * If the upper level VM system doesn't know anything about
1055 * the page being dirty, we have to check for it again. As
1056 * far as the VM code knows, any partially dirty pages are
1059 * Pages marked PG_WRITEABLE may be mapped into the user
1060 * address space of a process running on another cpu. A
1061 * user process (without holding the MP lock) running on
1062 * another cpu may be able to touch the page while we are
1063 * trying to remove it. vm_page_cache() will handle this
1066 if (m->dirty == 0) {
1067 vm_page_test_dirty(m);
1072 if (m->valid == 0 && (m->flags & PG_NEED_COMMIT) == 0) {
1074 * Invalid pages can be easily freed
1076 vm_pageout_page_free(m);
1077 mycpu->gd_cnt.v_dfree++;
1079 } else if (m->dirty == 0 && (m->flags & PG_NEED_COMMIT) == 0) {
1081 * Clean pages can be placed onto the cache queue.
1082 * This effectively frees them.
1086 } else if ((m->flags & PG_WINATCFLS) == 0 && pass == 0) {
1088 * Dirty pages need to be paged out, but flushing
1089 * a page is extremely expensive verses freeing
1090 * a clean page. Rather then artificially limiting
1091 * the number of pages we can flush, we instead give
1092 * dirty pages extra priority on the inactive queue
1093 * by forcing them to be cycled through the queue
1094 * twice before being flushed, after which the
1095 * (now clean) page will cycle through once more
1096 * before being freed. This significantly extends
1097 * the thrash point for a heavily loaded machine.
1099 vm_page_flag_set(m, PG_WINATCFLS);
1100 vm_page_and_queue_spin_lock(m);
1101 if (m->queue - m->pc == PQ_INACTIVE) {
1103 &vm_page_queues[m->queue].pl, m, pageq);
1105 &vm_page_queues[m->queue].pl, m, pageq);
1107 vm_page_and_queue_spin_unlock(m);
1109 } else if (*max_launderp > 0) {
1111 * We always want to try to flush some dirty pages if
1112 * we encounter them, to keep the system stable.
1113 * Normally this number is small, but under extreme
1114 * pressure where there are insufficient clean pages
1115 * on the inactive queue, we may have to go all out.
1117 int swap_pageouts_ok;
1118 struct vnode *vp = NULL;
1120 swap_pageouts_ok = 0;
1123 (object->type != OBJT_SWAP) &&
1124 (object->type != OBJT_DEFAULT)) {
1125 swap_pageouts_ok = 1;
1127 swap_pageouts_ok = !(defer_swap_pageouts ||
1128 disable_swap_pageouts);
1129 swap_pageouts_ok |= (!disable_swap_pageouts &&
1130 defer_swap_pageouts &&
1131 vm_page_count_min(0));
1135 * We don't bother paging objects that are "dead".
1136 * Those objects are in a "rundown" state.
1138 if (!swap_pageouts_ok ||
1140 (object->flags & OBJ_DEAD)) {
1141 vm_page_and_queue_spin_lock(m);
1142 if (m->queue - m->pc == PQ_INACTIVE) {
1144 &vm_page_queues[m->queue].pl,
1147 &vm_page_queues[m->queue].pl,
1150 vm_page_and_queue_spin_unlock(m);
1156 * (m) is still busied.
1158 * The object is already known NOT to be dead. It
1159 * is possible for the vget() to block the whole
1160 * pageout daemon, but the new low-memory handling
1161 * code should prevent it.
1163 * The previous code skipped locked vnodes and, worse,
1164 * reordered pages in the queue. This results in
1165 * completely non-deterministic operation because,
1166 * quite often, a vm_fault has initiated an I/O and
1167 * is holding a locked vnode at just the point where
1168 * the pageout daemon is woken up.
1170 * We can't wait forever for the vnode lock, we might
1171 * deadlock due to a vn_read() getting stuck in
1172 * vm_wait while holding this vnode. We skip the
1173 * vnode if we can't get it in a reasonable amount
1176 * vpfailed is used to (try to) avoid the case where
1177 * a large number of pages are associated with a
1178 * locked vnode, which could cause the pageout daemon
1179 * to stall for an excessive amount of time.
1181 if (object->type == OBJT_VNODE) {
1184 vp = object->handle;
1185 flags = LK_EXCLUSIVE;
1186 if (vp == *vpfailedp)
1189 flags |= LK_TIMELOCK;
1194 * We have unbusied (m) temporarily so we can
1195 * acquire the vp lock without deadlocking.
1196 * (m) is held to prevent destruction.
1198 if (vget(vp, flags) != 0) {
1200 ++pageout_lock_miss;
1201 if (object->flags & OBJ_MIGHTBEDIRTY)
1208 * The page might have been moved to another
1209 * queue during potential blocking in vget()
1210 * above. The page might have been freed and
1211 * reused for another vnode. The object might
1212 * have been reused for another vnode.
1214 if (m->queue - m->pc != PQ_INACTIVE ||
1215 m->object != object ||
1216 object->handle != vp) {
1217 if (object->flags & OBJ_MIGHTBEDIRTY)
1225 * The page may have been busied during the
1226 * blocking in vput(); We don't move the
1227 * page back onto the end of the queue so that
1228 * statistics are more correct if we don't.
1230 if (vm_page_busy_try(m, TRUE)) {
1238 * If it was wired while we didn't own it.
1240 if (m->wire_count) {
1241 vm_page_unqueue_nowakeup(m);
1248 * (m) is busied again
1250 * We own the busy bit and remove our hold
1251 * bit. If the page is still held it
1252 * might be undergoing I/O, so skip it.
1254 if (m->hold_count) {
1255 vm_page_and_queue_spin_lock(m);
1256 if (m->queue - m->pc == PQ_INACTIVE) {
1257 TAILQ_REMOVE(&vm_page_queues[m->queue].pl, m, pageq);
1258 TAILQ_INSERT_TAIL(&vm_page_queues[m->queue].pl, m, pageq);
1260 vm_page_and_queue_spin_unlock(m);
1261 if (object->flags & OBJ_MIGHTBEDIRTY)
1267 /* (m) is left busied as we fall through */
1271 * page is busy and not held here.
1273 * If a page is dirty, then it is either being washed
1274 * (but not yet cleaned) or it is still in the
1275 * laundry. If it is still in the laundry, then we
1276 * start the cleaning operation.
1278 * decrement inactive_shortage on success to account
1279 * for the (future) cleaned page. Otherwise we
1280 * could wind up laundering or cleaning too many
1283 * NOTE: Cleaning the page here does not cause
1284 * force_deficit to be adjusted, because the
1285 * page is not being freed or moved to the
1288 count = vm_pageout_clean_helper(m, vmflush_flags);
1289 *max_launderp -= count;
1292 * Clean ate busy, page no longer accessible
1305 * WARNING! Can be called from two pagedaemon threads simultaneously.
1308 vm_pageout_scan_active(int pass, int q,
1309 long avail_shortage, long inactive_shortage,
1310 long *recycle_countp)
1312 struct vm_page marker;
1319 isep = (curthread == emergpager);
1322 * We want to move pages from the active queue to the inactive
1323 * queue to get the inactive queue to the inactive target. If
1324 * we still have a page shortage from above we try to directly free
1325 * clean pages instead of moving them.
1327 * If we do still have a shortage we keep track of the number of
1328 * pages we free or cache (recycle_count) as a measure of thrashing
1329 * between the active and inactive queues.
1331 * If we were able to completely satisfy the free+cache targets
1332 * from the inactive pool we limit the number of pages we move
1333 * from the active pool to the inactive pool to 2x the pages we
1334 * had removed from the inactive pool (with a minimum of 1/5 the
1335 * inactive target). If we were not able to completely satisfy
1336 * the free+cache targets we go for the whole target aggressively.
1338 * NOTE: Both variables can end up negative.
1339 * NOTE: We are still in a critical section.
1341 * NOTE! THE EMERGENCY PAGER (isep) DOES NOT LAUNDER VNODE-BACKED
1345 bzero(&marker, sizeof(marker));
1346 marker.flags = PG_FICTITIOUS | PG_MARKER;
1347 marker.busy_count = PBUSY_LOCKED;
1348 marker.queue = PQ_ACTIVE + q;
1350 marker.wire_count = 1;
1352 vm_page_queues_spin_lock(PQ_ACTIVE + q);
1353 TAILQ_INSERT_HEAD(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1354 maxscan = vm_page_queues[PQ_ACTIVE + q].lcnt;
1357 * Queue locked at top of loop to avoid stack marker issues.
1359 while ((m = TAILQ_NEXT(&marker, pageq)) != NULL &&
1360 maxscan-- > 0 && (avail_shortage - delta > 0 ||
1361 inactive_shortage > 0))
1363 KKASSERT(m->queue == PQ_ACTIVE + q);
1364 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl,
1366 TAILQ_INSERT_AFTER(&vm_page_queues[PQ_ACTIVE + q].pl, m,
1370 * Skip marker pages (atomic against other markers to avoid
1371 * infinite hop-over scans).
1373 if (m->flags & PG_MARKER)
1377 * Try to busy the page. Don't mess with pages which are
1378 * already busy or reorder them in the queue.
1380 if (vm_page_busy_try(m, TRUE))
1384 * Remaining operations run with the page busy and neither
1385 * the page or the queue will be spin-locked.
1387 KKASSERT(m->queue == PQ_ACTIVE + q);
1388 vm_page_queues_spin_unlock(PQ_ACTIVE + q);
1392 * Don't deactivate pages that are held, even if we can
1393 * busy them. (XXX why not?)
1395 if (m->hold_count) {
1396 vm_page_and_queue_spin_lock(m);
1397 if (m->queue - m->pc == PQ_ACTIVE) {
1399 &vm_page_queues[PQ_ACTIVE + q].pl,
1402 &vm_page_queues[PQ_ACTIVE + q].pl,
1405 vm_page_and_queue_spin_unlock(m);
1411 * We can just remove wired pages from the queue
1413 if (m->wire_count) {
1414 vm_page_unqueue_nowakeup(m);
1420 * The emergency pager ignores vnode-backed pages as these
1421 * are the pages that probably bricked the main pager.
1423 if (isep && m->object && m->object->type == OBJT_VNODE) {
1424 vm_page_and_queue_spin_lock(m);
1425 if (m->queue - m->pc == PQ_ACTIVE) {
1427 &vm_page_queues[PQ_ACTIVE + q].pl,
1430 &vm_page_queues[PQ_ACTIVE + q].pl,
1433 vm_page_and_queue_spin_unlock(m);
1439 * The count for pagedaemon pages is done after checking the
1440 * page for eligibility...
1442 mycpu->gd_cnt.v_pdpages++;
1445 * Check to see "how much" the page has been used and clear
1446 * the tracking access bits. If the object has no references
1447 * don't bother paying the expense.
1450 if (m->object && m->object->ref_count != 0) {
1451 if (m->flags & PG_REFERENCED)
1453 actcount += pmap_ts_referenced(m);
1455 m->act_count += ACT_ADVANCE + actcount;
1456 if (m->act_count > ACT_MAX)
1457 m->act_count = ACT_MAX;
1460 vm_page_flag_clear(m, PG_REFERENCED);
1463 * actcount is only valid if the object ref_count is non-zero.
1464 * If the page does not have an object, actcount will be zero.
1466 if (actcount && m->object->ref_count != 0) {
1467 vm_page_and_queue_spin_lock(m);
1468 if (m->queue - m->pc == PQ_ACTIVE) {
1470 &vm_page_queues[PQ_ACTIVE + q].pl,
1473 &vm_page_queues[PQ_ACTIVE + q].pl,
1476 vm_page_and_queue_spin_unlock(m);
1479 switch(m->object->type) {
1482 m->act_count -= min(m->act_count,
1483 vm_anonmem_decline);
1486 m->act_count -= min(m->act_count,
1487 vm_filemem_decline);
1490 if (vm_pageout_algorithm ||
1491 (m->object == NULL) ||
1492 (m->object && (m->object->ref_count == 0)) ||
1493 m->act_count < pass + 1
1496 * Deactivate the page. If we had a
1497 * shortage from our inactive scan try to
1498 * free (cache) the page instead.
1500 * Don't just blindly cache the page if
1501 * we do not have a shortage from the
1502 * inactive scan, that could lead to
1503 * gigabytes being moved.
1505 --inactive_shortage;
1506 if (avail_shortage - delta > 0 ||
1507 (m->object && (m->object->ref_count == 0)))
1509 if (avail_shortage - delta > 0)
1511 vm_page_protect(m, VM_PROT_NONE);
1512 if (m->dirty == 0 &&
1513 (m->flags & PG_NEED_COMMIT) == 0 &&
1514 avail_shortage - delta > 0) {
1517 vm_page_deactivate(m);
1521 vm_page_deactivate(m);
1526 vm_page_and_queue_spin_lock(m);
1527 if (m->queue - m->pc == PQ_ACTIVE) {
1529 &vm_page_queues[PQ_ACTIVE + q].pl,
1532 &vm_page_queues[PQ_ACTIVE + q].pl,
1535 vm_page_and_queue_spin_unlock(m);
1541 vm_page_queues_spin_lock(PQ_ACTIVE + q);
1545 * Clean out our local marker.
1547 * Page queue still spin-locked.
1549 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1550 vm_page_queues_spin_unlock(PQ_ACTIVE + q);
1556 * The number of actually free pages can drop down to v_free_reserved,
1557 * we try to build the free count back above v_free_min. Note that
1558 * vm_paging_needed() also returns TRUE if v_free_count is not at
1559 * least v_free_min so that is the minimum we must build the free
1562 * We use a slightly higher target to improve hysteresis,
1563 * ((v_free_target + v_free_min) / 2). Since v_free_target
1564 * is usually the same as v_cache_min this maintains about
1565 * half the pages in the free queue as are in the cache queue,
1566 * providing pretty good pipelining for pageout operation.
1568 * The system operator can manipulate vm.v_cache_min and
1569 * vm.v_free_target to tune the pageout demon. Be sure
1570 * to keep vm.v_free_min < vm.v_free_target.
1572 * Note that the original paging target is to get at least
1573 * (free_min + cache_min) into (free + cache). The slightly
1574 * higher target will shift additional pages from cache to free
1575 * without effecting the original paging target in order to
1576 * maintain better hysteresis and not have the free count always
1577 * be dead-on v_free_min.
1579 * NOTE: we are still in a critical section.
1581 * Pages moved from PQ_CACHE to totally free are not counted in the
1582 * pages_freed counter.
1584 * WARNING! Can be called from two pagedaemon threads simultaneously.
1587 vm_pageout_scan_cache(long avail_shortage, int pass,
1588 long vnodes_skipped, long recycle_count)
1590 static int lastkillticks;
1591 struct vm_pageout_scan_info info;
1595 isep = (curthread == emergpager);
1597 while (vmstats.v_free_count <
1598 (vmstats.v_free_min + vmstats.v_free_target) / 2) {
1600 * This steals some code from vm/vm_page.c
1602 * Create two rovers and adjust the code to reduce
1603 * chances of them winding up at the same index (which
1604 * can cause a lot of contention).
1606 static int cache_rover[2] = { 0, PQ_L2_MASK / 2 };
1608 if (((cache_rover[0] ^ cache_rover[1]) & PQ_L2_MASK) == 0)
1611 m = vm_page_list_find(PQ_CACHE, cache_rover[isep] & PQ_L2_MASK);
1616 * If the busy attempt fails we can still deactivate the page.
1618 /* page is returned removed from its queue and spinlocked */
1619 if (vm_page_busy_try(m, TRUE)) {
1620 vm_page_deactivate_locked(m);
1621 vm_page_spin_unlock(m);
1624 vm_page_spin_unlock(m);
1625 pagedaemon_wakeup();
1629 * Remaining operations run with the page busy and neither
1630 * the page or the queue will be spin-locked.
1632 if ((m->flags & (PG_UNQUEUED | PG_NEED_COMMIT)) ||
1635 vm_page_deactivate(m);
1639 pmap_mapped_sync(m);
1640 KKASSERT((m->flags & PG_MAPPED) == 0);
1641 KKASSERT(m->dirty == 0);
1642 vm_pageout_page_free(m);
1643 mycpu->gd_cnt.v_dfree++;
1646 cache_rover[1] -= PQ_PRIME2;
1648 cache_rover[0] += PQ_PRIME2;
1651 #if !defined(NO_SWAPPING)
1653 * Idle process swapout -- run once per second.
1655 if (vm_swap_idle_enabled) {
1657 if (time_uptime != lsec) {
1658 atomic_set_int(&vm_pageout_req_swapout, VM_SWAP_IDLE);
1666 * If we didn't get enough free pages, and we have skipped a vnode
1667 * in a writeable object, wakeup the sync daemon. And kick swapout
1668 * if we did not get enough free pages.
1670 if (vm_paging_target() > 0) {
1671 if (vnodes_skipped && vm_page_count_min(0))
1672 speedup_syncer(NULL);
1673 #if !defined(NO_SWAPPING)
1674 if (vm_swap_enabled && vm_page_count_target()) {
1675 atomic_set_int(&vm_pageout_req_swapout, VM_SWAP_NORMAL);
1682 * Handle catastrophic conditions. Under good conditions we should
1683 * be at the target, well beyond our minimum. If we could not even
1684 * reach our minimum the system is under heavy stress. But just being
1685 * under heavy stress does not trigger process killing.
1687 * We consider ourselves to have run out of memory if the swap pager
1688 * is full and avail_shortage is still positive. The secondary check
1689 * ensures that we do not kill processes if the instantanious
1690 * availability is good, even if the pageout demon pass says it
1691 * couldn't get to the target.
1693 * NOTE! THE EMERGENCY PAGER (isep) DOES NOT HANDLE SWAP FULL
1696 if (swap_pager_almost_full &&
1699 (vm_page_count_min(recycle_count) || avail_shortage > 0)) {
1700 kprintf("Warning: system low on memory+swap "
1701 "shortage %ld for %d ticks!\n",
1702 avail_shortage, ticks - swap_fail_ticks);
1704 kprintf("Metrics: spaf=%d spf=%d pass=%d "
1705 "avail=%ld target=%ld last=%u\n",
1706 swap_pager_almost_full,
1711 (unsigned int)(ticks - lastkillticks));
1713 if (swap_pager_full &&
1716 avail_shortage > 0 &&
1717 vm_paging_target() > 0 &&
1718 (unsigned int)(ticks - lastkillticks) >= hz) {
1720 * Kill something, maximum rate once per second to give
1721 * the process time to free up sufficient memory.
1723 lastkillticks = ticks;
1724 info.bigproc = NULL;
1726 allproc_scan(vm_pageout_scan_callback, &info, 0);
1727 if (info.bigproc != NULL) {
1728 kprintf("Try to kill process %d %s\n",
1729 info.bigproc->p_pid, info.bigproc->p_comm);
1730 info.bigproc->p_nice = PRIO_MIN;
1731 info.bigproc->p_usched->resetpriority(
1732 FIRST_LWP_IN_PROC(info.bigproc));
1733 atomic_set_int(&info.bigproc->p_flags, P_LOWMEMKILL);
1734 killproc(info.bigproc, "out of swap space");
1735 wakeup(&vmstats.v_free_count);
1736 PRELE(info.bigproc);
1742 vm_pageout_scan_callback(struct proc *p, void *data)
1744 struct vm_pageout_scan_info *info = data;
1748 * Never kill system processes or init. If we have configured swap
1749 * then try to avoid killing low-numbered pids.
1751 if ((p->p_flags & P_SYSTEM) || (p->p_pid == 1) ||
1752 ((p->p_pid < 48) && (vm_swap_size != 0))) {
1756 lwkt_gettoken(&p->p_token);
1759 * if the process is in a non-running type state,
1762 if (p->p_stat != SACTIVE && p->p_stat != SSTOP && p->p_stat != SCORE) {
1763 lwkt_reltoken(&p->p_token);
1768 * Get the approximate process size. Note that anonymous pages
1769 * with backing swap will be counted twice, but there should not
1770 * be too many such pages due to the stress the VM system is
1771 * under at this point.
1773 size = vmspace_anonymous_count(p->p_vmspace) +
1774 vmspace_swap_count(p->p_vmspace);
1777 * If the this process is bigger than the biggest one
1780 if (info->bigsize < size) {
1782 PRELE(info->bigproc);
1785 info->bigsize = size;
1787 lwkt_reltoken(&p->p_token);
1794 * This old guy slowly walks PQ_HOLD looking for pages which need to be
1795 * moved back to PQ_FREE. It is possible for pages to accumulate here
1796 * when vm_page_free() races against vm_page_unhold(), resulting in a
1797 * page being left on a PQ_HOLD queue with hold_count == 0.
1799 * It is easier to handle this edge condition here, in non-critical code,
1800 * rather than enforce a spin-lock for every 1->0 transition in
1803 * NOTE: TAILQ_FOREACH becomes invalid the instant we unlock the queue.
1806 vm_pageout_scan_hold(int q)
1810 vm_page_queues_spin_lock(PQ_HOLD + q);
1811 TAILQ_FOREACH(m, &vm_page_queues[PQ_HOLD + q].pl, pageq) {
1812 if (m->flags & PG_MARKER)
1816 * Process one page and return
1820 kprintf("DEBUG: pageout HOLD->FREE %p\n", m);
1822 vm_page_queues_spin_unlock(PQ_HOLD + q);
1823 vm_page_unhold(m); /* reprocess */
1826 vm_page_queues_spin_unlock(PQ_HOLD + q);
1830 * This routine tries to maintain the pseudo LRU active queue,
1831 * so that during long periods of time where there is no paging,
1832 * that some statistic accumulation still occurs. This code
1833 * helps the situation where paging just starts to occur.
1836 vm_pageout_page_stats(int q)
1838 static int fullintervalcount = 0;
1839 struct vm_page marker;
1841 long pcount, tpcount; /* Number of pages to check */
1844 page_shortage = (vmstats.v_inactive_target + vmstats.v_cache_max +
1845 vmstats.v_free_min) -
1846 (vmstats.v_free_count + vmstats.v_inactive_count +
1847 vmstats.v_cache_count);
1849 if (page_shortage <= 0)
1852 pcount = vm_page_queues[PQ_ACTIVE + q].lcnt;
1853 fullintervalcount += vm_pageout_stats_interval;
1854 if (fullintervalcount < vm_pageout_full_stats_interval) {
1855 tpcount = (vm_pageout_stats_max * pcount) /
1856 vmstats.v_page_count + 1;
1857 if (pcount > tpcount)
1860 fullintervalcount = 0;
1863 bzero(&marker, sizeof(marker));
1864 marker.flags = PG_FICTITIOUS | PG_MARKER;
1865 marker.busy_count = PBUSY_LOCKED;
1866 marker.queue = PQ_ACTIVE + q;
1868 marker.wire_count = 1;
1870 vm_page_queues_spin_lock(PQ_ACTIVE + q);
1871 TAILQ_INSERT_HEAD(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1874 * Queue locked at top of loop to avoid stack marker issues.
1876 while ((m = TAILQ_NEXT(&marker, pageq)) != NULL &&
1881 KKASSERT(m->queue == PQ_ACTIVE + q);
1882 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1883 TAILQ_INSERT_AFTER(&vm_page_queues[PQ_ACTIVE + q].pl, m,
1887 * Skip marker pages (atomic against other markers to avoid
1888 * infinite hop-over scans).
1890 if (m->flags & PG_MARKER)
1894 * Ignore pages we can't busy
1896 if (vm_page_busy_try(m, TRUE))
1900 * Remaining operations run with the page busy and neither
1901 * the page or the queue will be spin-locked.
1903 KKASSERT(m->queue == PQ_ACTIVE + q);
1904 vm_page_queues_spin_unlock(PQ_ACTIVE + q);
1907 * We can just remove wired pages from the queue
1909 if (m->wire_count) {
1910 vm_page_unqueue_nowakeup(m);
1917 * We now have a safely busied page, the page and queue
1918 * spinlocks have been released.
1920 * Ignore held and wired pages
1922 if (m->hold_count || m->wire_count) {
1928 * Calculate activity
1931 if (m->flags & PG_REFERENCED) {
1932 vm_page_flag_clear(m, PG_REFERENCED);
1935 actcount += pmap_ts_referenced(m);
1938 * Update act_count and move page to end of queue.
1941 m->act_count += ACT_ADVANCE + actcount;
1942 if (m->act_count > ACT_MAX)
1943 m->act_count = ACT_MAX;
1944 vm_page_and_queue_spin_lock(m);
1945 if (m->queue - m->pc == PQ_ACTIVE) {
1947 &vm_page_queues[PQ_ACTIVE + q].pl,
1950 &vm_page_queues[PQ_ACTIVE + q].pl,
1953 vm_page_and_queue_spin_unlock(m);
1958 if (m->act_count == 0) {
1960 * We turn off page access, so that we have
1961 * more accurate RSS stats. We don't do this
1962 * in the normal page deactivation when the
1963 * system is loaded VM wise, because the
1964 * cost of the large number of page protect
1965 * operations would be higher than the value
1966 * of doing the operation.
1968 * We use the marker to save our place so
1969 * we can release the spin lock. both (m)
1970 * and (next) will be invalid.
1972 vm_page_protect(m, VM_PROT_NONE);
1973 vm_page_deactivate(m);
1975 m->act_count -= min(m->act_count, ACT_DECLINE);
1976 vm_page_and_queue_spin_lock(m);
1977 if (m->queue - m->pc == PQ_ACTIVE) {
1979 &vm_page_queues[PQ_ACTIVE + q].pl,
1982 &vm_page_queues[PQ_ACTIVE + q].pl,
1985 vm_page_and_queue_spin_unlock(m);
1989 vm_page_queues_spin_lock(PQ_ACTIVE + q);
1993 * Remove our local marker
1995 * Page queue still spin-locked.
1997 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1998 vm_page_queues_spin_unlock(PQ_ACTIVE + q);
2002 vm_pageout_free_page_calc(vm_size_t count)
2005 * v_free_min normal allocations
2006 * v_free_reserved system allocations
2007 * v_pageout_free_min allocations by pageout daemon
2008 * v_interrupt_free_min low level allocations (e.g swap structures)
2010 * v_free_min is used to generate several other baselines, and they
2011 * can get pretty silly on systems with a lot of memory.
2013 vmstats.v_free_min = 64 + vmstats.v_page_count / 200;
2014 vmstats.v_free_reserved = vmstats.v_free_min * 4 / 8 + 7;
2015 vmstats.v_free_severe = vmstats.v_free_min * 4 / 8 + 0;
2016 vmstats.v_pageout_free_min = vmstats.v_free_min * 2 / 8 + 7;
2017 vmstats.v_interrupt_free_min = vmstats.v_free_min * 1 / 8 + 7;
2022 * vm_pageout is the high level pageout daemon. TWO kernel threads run
2023 * this daemon, the primary pageout daemon and the emergency pageout daemon.
2025 * The emergency pageout daemon takes over when the primary pageout daemon
2026 * deadlocks. The emergency pageout daemon ONLY pages out to swap, thus
2027 * avoiding the many low-memory deadlocks which can occur when paging out
2031 vm_pageout_thread(void)
2040 curthread->td_flags |= TDF_SYSTHREAD;
2043 * We only need to setup once.
2046 if (curthread == emergpager) {
2052 * Initialize some paging parameters.
2054 vm_pageout_free_page_calc(vmstats.v_page_count);
2057 * v_free_target and v_cache_min control pageout hysteresis. Note
2058 * that these are more a measure of the VM cache queue hysteresis
2059 * then the VM free queue. Specifically, v_free_target is the
2060 * high water mark (free+cache pages).
2062 * v_free_reserved + v_cache_min (mostly means v_cache_min) is the
2063 * low water mark, while v_free_min is the stop. v_cache_min must
2064 * be big enough to handle memory needs while the pageout daemon
2065 * is signalled and run to free more pages.
2067 vmstats.v_free_target = 4 * vmstats.v_free_min +
2068 vmstats.v_free_reserved;
2071 * NOTE: With the new buffer cache b_act_count we want the default
2072 * inactive target to be a percentage of available memory.
2074 * The inactive target essentially determines the minimum
2075 * number of 'temporary' pages capable of caching one-time-use
2076 * files when the VM system is otherwise full of pages
2077 * belonging to multi-time-use files or active program data.
2079 * NOTE: The inactive target is aggressively persued only if the
2080 * inactive queue becomes too small. If the inactive queue
2081 * is large enough to satisfy page movement to free+cache
2082 * then it is repopulated more slowly from the active queue.
2083 * This allows a general inactive_target default to be set.
2085 * There is an issue here for processes which sit mostly idle
2086 * 'overnight', such as sshd, tcsh, and X. Any movement from
2087 * the active queue will eventually cause such pages to
2088 * recycle eventually causing a lot of paging in the morning.
2089 * To reduce the incidence of this pages cycled out of the
2090 * buffer cache are moved directly to the inactive queue if
2091 * they were only used once or twice.
2093 * The vfs.vm_cycle_point sysctl can be used to adjust this.
2094 * Increasing the value (up to 64) increases the number of
2095 * buffer recyclements which go directly to the inactive queue.
2097 if (vmstats.v_free_count > 2048) {
2098 vmstats.v_cache_min = vmstats.v_free_target;
2099 vmstats.v_cache_max = 2 * vmstats.v_cache_min;
2101 vmstats.v_cache_min = 0;
2102 vmstats.v_cache_max = 0;
2104 vmstats.v_inactive_target = vmstats.v_free_count / 4;
2106 /* XXX does not really belong here */
2107 if (vm_page_max_wired == 0)
2108 vm_page_max_wired = vmstats.v_free_count / 3;
2110 if (vm_pageout_stats_max == 0)
2111 vm_pageout_stats_max = vmstats.v_free_target;
2114 * Set interval in seconds for stats scan.
2116 if (vm_pageout_stats_interval == 0)
2117 vm_pageout_stats_interval = 5;
2118 if (vm_pageout_full_stats_interval == 0)
2119 vm_pageout_full_stats_interval = vm_pageout_stats_interval * 4;
2123 * Set maximum free per pass
2125 if (vm_pageout_stats_free_max == 0)
2126 vm_pageout_stats_free_max = 5;
2128 swap_pager_swap_init();
2131 atomic_swap_int(&sequence_emerg_pager, 1);
2132 wakeup(&sequence_emerg_pager);
2136 * Sequence emergency pager startup
2139 while (sequence_emerg_pager == 0)
2140 tsleep(&sequence_emerg_pager, 0, "pstartup", hz);
2144 * The pageout daemon is never done, so loop forever.
2146 * WARNING! This code is being executed by two kernel threads
2147 * potentially simultaneously.
2151 long avail_shortage;
2152 long inactive_shortage;
2153 long vnodes_skipped = 0;
2154 long recycle_count = 0;
2158 * Wait for an action request. If we timeout check to
2159 * see if paging is needed (in case the normal wakeup
2164 * Emergency pagedaemon monitors the primary
2165 * pagedaemon while vm_pages_needed != 0.
2167 * The emergency pagedaemon only runs if VM paging
2168 * is needed and the primary pagedaemon has not
2169 * updated vm_pagedaemon_time for more than 2 seconds.
2171 if (vm_pages_needed)
2172 tsleep(&vm_pagedaemon_time, 0, "psleep", hz);
2174 tsleep(&vm_pagedaemon_time, 0, "psleep", hz*10);
2175 if (vm_pages_needed == 0) {
2179 if ((int)(ticks - vm_pagedaemon_time) < hz * 2) {
2185 * Primary pagedaemon
2187 * NOTE: We unconditionally cleanup PQ_HOLD even
2188 * when there is no work to do.
2190 vm_pageout_scan_hold(q3iterator & PQ_L2_MASK);
2193 if (vm_pages_needed == 0) {
2194 error = tsleep(&vm_pages_needed,
2196 vm_pageout_stats_interval * hz);
2198 vm_paging_needed(0) == 0 &&
2199 vm_pages_needed == 0) {
2200 for (q = 0; q < PQ_L2_SIZE; ++q)
2201 vm_pageout_page_stats(q);
2204 vm_pagedaemon_time = ticks;
2205 vm_pages_needed = 1;
2208 * Wake the emergency pagedaemon up so it
2209 * can monitor us. It will automatically
2210 * go back into a long sleep when
2211 * vm_pages_needed returns to 0.
2213 wakeup(&vm_pagedaemon_time);
2217 mycpu->gd_cnt.v_pdwakeups++;
2220 * Scan for INACTIVE->CLEAN/PAGEOUT
2222 * This routine tries to avoid thrashing the system with
2223 * unnecessary activity.
2225 * Calculate our target for the number of free+cache pages we
2226 * want to get to. This is higher then the number that causes
2227 * allocations to stall (severe) in order to provide hysteresis,
2228 * and if we don't make it all the way but get to the minimum
2229 * we're happy. Goose it a bit if there are multiple requests
2232 * Don't reduce avail_shortage inside the loop or the
2233 * PQAVERAGE() calculation will break.
2235 * NOTE! deficit is differentiated from avail_shortage as
2236 * REQUIRING at least (deficit) pages to be cleaned,
2237 * even if the page queues are in good shape. This
2238 * is used primarily for handling per-process
2239 * RLIMIT_RSS and may also see small values when
2240 * processes block due to low memory.
2244 vm_pagedaemon_time = ticks;
2245 avail_shortage = vm_paging_target() + vm_pageout_deficit;
2246 vm_pageout_deficit = 0;
2248 if (avail_shortage > 0) {
2253 for (q = 0; q < PQ_L2_SIZE; ++q) {
2254 delta += vm_pageout_scan_inactive(
2257 PQAVERAGE(avail_shortage),
2263 if (avail_shortage - delta <= 0)
2266 avail_shortage -= delta;
2271 * Figure out how many active pages we must deactivate. If
2272 * we were able to reach our target with just the inactive
2273 * scan above we limit the number of active pages we
2274 * deactivate to reduce unnecessary work.
2278 vm_pagedaemon_time = ticks;
2279 inactive_shortage = vmstats.v_inactive_target -
2280 vmstats.v_inactive_count;
2283 * If we were unable to free sufficient inactive pages to
2284 * satisfy the free/cache queue requirements then simply
2285 * reaching the inactive target may not be good enough.
2286 * Try to deactivate pages in excess of the target based
2289 * However to prevent thrashing the VM system do not
2290 * deactivate more than an additional 1/10 the inactive
2291 * target's worth of active pages.
2293 if (avail_shortage > 0) {
2294 tmp = avail_shortage * 2;
2295 if (tmp > vmstats.v_inactive_target / 10)
2296 tmp = vmstats.v_inactive_target / 10;
2297 inactive_shortage += tmp;
2301 * Only trigger a pmap cleanup on inactive shortage.
2303 if (isep == 0 && inactive_shortage > 0) {
2308 * Scan for ACTIVE->INACTIVE
2310 * Only trigger on inactive shortage. Triggering on
2311 * avail_shortage can starve the active queue with
2312 * unnecessary active->inactive transitions and destroy
2315 * If this is the emergency pager, always try to move
2316 * a few pages from active to inactive because the inactive
2317 * queue might have enough pages, but not enough anonymous
2320 if (isep && inactive_shortage < vm_emerg_launder)
2321 inactive_shortage = vm_emerg_launder;
2323 if (/*avail_shortage > 0 ||*/ inactive_shortage > 0) {
2328 for (q = 0; q < PQ_L2_SIZE; ++q) {
2329 delta += vm_pageout_scan_active(
2332 PQAVERAGE(avail_shortage),
2333 PQAVERAGE(inactive_shortage),
2339 if (inactive_shortage - delta <= 0 &&
2340 avail_shortage - delta <= 0) {
2344 inactive_shortage -= delta;
2345 avail_shortage -= delta;
2350 * Scan for CACHE->FREE
2352 * Finally free enough cache pages to meet our free page
2353 * requirement and take more drastic measures if we are
2358 vm_pagedaemon_time = ticks;
2359 vm_pageout_scan_cache(avail_shortage, pass,
2360 vnodes_skipped, recycle_count);
2363 * Wait for more work.
2365 if (avail_shortage > 0) {
2367 if (pass < 10 && vm_pages_needed > 1) {
2369 * Normal operation, additional processes
2370 * have already kicked us. Retry immediately
2371 * unless swap space is completely full in
2372 * which case delay a bit.
2374 if (swap_pager_full) {
2375 tsleep(&vm_pages_needed, 0, "pdelay",
2377 } /* else immediate retry */
2378 } else if (pass < 10) {
2380 * Normal operation, fewer processes. Delay
2381 * a bit but allow wakeups. vm_pages_needed
2382 * is only adjusted against the primary
2386 vm_pages_needed = 0;
2387 tsleep(&vm_pages_needed, 0, "pdelay", hz / 10);
2389 vm_pages_needed = 1;
2390 } else if (swap_pager_full == 0) {
2392 * We've taken too many passes, forced delay.
2394 tsleep(&vm_pages_needed, 0, "pdelay", hz / 10);
2397 * Running out of memory, catastrophic
2398 * back-off to one-second intervals.
2400 tsleep(&vm_pages_needed, 0, "pdelay", hz);
2402 } else if (vm_pages_needed) {
2404 * Interlocked wakeup of waiters (non-optional).
2406 * Similar to vm_page_free_wakeup() in vm_page.c,
2410 if (!vm_page_count_min(vm_page_free_hysteresis) ||
2411 !vm_page_count_target()) {
2412 vm_pages_needed = 0;
2413 wakeup(&vmstats.v_free_count);
2421 static struct kproc_desc pg1_kp = {
2426 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, kproc_start, &pg1_kp);
2428 static struct kproc_desc pg2_kp = {
2433 SYSINIT(emergpager, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY, kproc_start, &pg2_kp);
2437 * Called after allocating a page out of the cache or free queue
2438 * to possibly wake the pagedaemon up to replentish our supply.
2440 * We try to generate some hysteresis by waking the pagedaemon up
2441 * when our free+cache pages go below the free_min+cache_min level.
2442 * The pagedaemon tries to get the count back up to at least the
2443 * minimum, and through to the target level if possible.
2445 * If the pagedaemon is already active bump vm_pages_needed as a hint
2446 * that there are even more requests pending.
2452 pagedaemon_wakeup(void)
2454 if (vm_paging_needed(0) && curthread != pagethread) {
2455 if (vm_pages_needed == 0) {
2456 vm_pages_needed = 1; /* SMP race ok */
2457 wakeup(&vm_pages_needed);
2458 } else if (vm_page_count_min(0)) {
2459 ++vm_pages_needed; /* SMP race ok */
2464 #if !defined(NO_SWAPPING)
2471 vm_req_vmdaemon(void)
2473 static int lastrun = 0;
2475 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
2476 wakeup(&vm_daemon_needed);
2481 static int vm_daemon_callback(struct proc *p, void *data __unused);
2492 tsleep(&vm_daemon_needed, 0, "psleep", 0);
2493 req_swapout = atomic_swap_int(&vm_pageout_req_swapout, 0);
2499 swapout_procs(vm_pageout_req_swapout);
2502 * scan the processes for exceeding their rlimits or if
2503 * process is swapped out -- deactivate pages
2505 allproc_scan(vm_daemon_callback, NULL, 0);
2510 vm_daemon_callback(struct proc *p, void *data __unused)
2513 vm_pindex_t limit, size;
2516 * if this is a system process or if we have already
2517 * looked at this process, skip it.
2519 lwkt_gettoken(&p->p_token);
2521 if (p->p_flags & (P_SYSTEM | P_WEXIT)) {
2522 lwkt_reltoken(&p->p_token);
2527 * if the process is in a non-running type state,
2530 if (p->p_stat != SACTIVE && p->p_stat != SSTOP && p->p_stat != SCORE) {
2531 lwkt_reltoken(&p->p_token);
2538 limit = OFF_TO_IDX(qmin(p->p_rlimit[RLIMIT_RSS].rlim_cur,
2539 p->p_rlimit[RLIMIT_RSS].rlim_max));
2542 * let processes that are swapped out really be
2543 * swapped out. Set the limit to nothing to get as
2544 * many pages out to swap as possible.
2546 if (p->p_flags & P_SWAPPEDOUT)
2551 size = pmap_resident_tlnw_count(&vm->vm_pmap);
2552 if (limit >= 0 && size > 4096 &&
2553 size - 4096 >= limit && vm_pageout_memuse_mode >= 1) {
2554 vm_pageout_map_deactivate_pages(&vm->vm_map, limit);
2558 lwkt_reltoken(&p->p_token);