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 int 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 static int vm_max_launder = 4096;
137 static int vm_emerg_launder = 100;
138 static int vm_pageout_stats_max=0, vm_pageout_stats_interval = 0;
139 static int vm_pageout_full_stats_interval = 0;
140 static int vm_pageout_stats_free_max=0, vm_pageout_algorithm=0;
141 static int defer_swap_pageouts=0;
142 static int disable_swap_pageouts=0;
143 static u_int vm_anonmem_decline = ACT_DECLINE;
144 static u_int vm_filemem_decline = ACT_DECLINE * 2;
146 #if defined(NO_SWAPPING)
147 static int vm_swap_enabled=0;
148 static int vm_swap_idle_enabled=0;
150 static int vm_swap_enabled=1;
151 static int vm_swap_idle_enabled=0;
153 int vm_pageout_memuse_mode=1; /* 0-disable, 1-passive, 2-active swp*/
155 SYSCTL_UINT(_vm, VM_PAGEOUT_ALGORITHM, anonmem_decline,
156 CTLFLAG_RW, &vm_anonmem_decline, 0, "active->inactive anon memory");
158 SYSCTL_INT(_vm, VM_PAGEOUT_ALGORITHM, filemem_decline,
159 CTLFLAG_RW, &vm_filemem_decline, 0, "active->inactive file cache");
161 SYSCTL_INT(_vm, OID_AUTO, page_free_hysteresis,
162 CTLFLAG_RW, &vm_page_free_hysteresis, 0,
163 "Free more pages than the minimum required");
165 SYSCTL_INT(_vm, OID_AUTO, max_launder,
166 CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
167 SYSCTL_INT(_vm, OID_AUTO, emerg_launder,
168 CTLFLAG_RW, &vm_emerg_launder, 0, "Emergency pager minimum");
170 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_max,
171 CTLFLAG_RW, &vm_pageout_stats_max, 0, "Max pageout stats scan length");
173 SYSCTL_INT(_vm, OID_AUTO, pageout_full_stats_interval,
174 CTLFLAG_RW, &vm_pageout_full_stats_interval, 0, "Interval for full stats scan");
176 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_interval,
177 CTLFLAG_RW, &vm_pageout_stats_interval, 0, "Interval for partial stats scan");
179 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_free_max,
180 CTLFLAG_RW, &vm_pageout_stats_free_max, 0, "Not implemented");
181 SYSCTL_INT(_vm, OID_AUTO, pageout_memuse_mode,
182 CTLFLAG_RW, &vm_pageout_memuse_mode, 0, "memoryuse resource mode");
184 #if defined(NO_SWAPPING)
185 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
186 CTLFLAG_RD, &vm_swap_enabled, 0, "");
187 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
188 CTLFLAG_RD, &vm_swap_idle_enabled, 0, "");
190 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
191 CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
192 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
193 CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
196 SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
197 CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
199 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
200 CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
202 static int pageout_lock_miss;
203 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
204 CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
206 int vm_page_max_wired; /* XXX max # of wired pages system-wide */
208 #if !defined(NO_SWAPPING)
209 static void vm_req_vmdaemon (void);
211 static void vm_pageout_page_stats(int q);
214 * Calculate approximately how many pages on each queue to try to
215 * clean. An exact calculation creates an edge condition when the
216 * queues are unbalanced so add significant slop. The queue scans
217 * will stop early when targets are reached and will start where they
218 * left off on the next pass.
220 * We need to be generous here because there are all sorts of loading
221 * conditions that can cause edge cases if try to average over all queues.
222 * In particular, storage subsystems have become so fast that paging
223 * activity can become quite frantic. Eventually we will probably need
224 * two paging threads, one for dirty pages and one for clean, to deal
225 * with the bandwidth requirements.
227 * So what we do is calculate a value that can be satisfied nominally by
228 * only having to scan half the queues.
236 avg = ((n + (PQ_L2_SIZE - 1)) / (PQ_L2_SIZE / 2) + 1);
238 avg = ((n - (PQ_L2_SIZE - 1)) / (PQ_L2_SIZE / 2) - 1);
244 * vm_pageout_clean_helper:
246 * Clean the page and remove it from the laundry. The page must be busied
247 * by the caller and will be disposed of (put away, flushed) by this routine.
250 vm_pageout_clean_helper(vm_page_t m, int vmflush_flags)
253 vm_page_t mc[BLIST_MAX_ALLOC];
255 int ib, is, page_base;
256 vm_pindex_t pindex = m->pindex;
261 * Don't mess with the page if it's held or special. Theoretically
262 * we can pageout held pages but there is no real need to press our
265 if (m->hold_count != 0 || (m->flags & PG_UNMANAGED)) {
271 * Place page in cluster. Align cluster for optimal swap space
272 * allocation (whether it is swap or not). This is typically ~16-32
273 * pages, which also tends to align the cluster to multiples of the
274 * filesystem block size if backed by a filesystem.
276 page_base = pindex % BLIST_MAX_ALLOC;
282 * Scan object for clusterable pages.
284 * We can cluster ONLY if: ->> the page is NOT
285 * clean, wired, busy, held, or mapped into a
286 * buffer, and one of the following:
287 * 1) The page is inactive, or a seldom used
290 * 2) we force the issue.
292 * During heavy mmap/modification loads the pageout
293 * daemon can really fragment the underlying file
294 * due to flushing pages out of order and not trying
295 * align the clusters (which leave sporatic out-of-order
296 * holes). To solve this problem we do the reverse scan
297 * first and attempt to align our cluster, then do a
298 * forward scan if room remains.
300 vm_object_hold(object);
305 p = vm_page_lookup_busy_try(object, pindex - page_base + ib,
307 if (error || p == NULL)
309 if ((p->queue - p->pc) == PQ_CACHE ||
310 (p->flags & PG_UNMANAGED)) {
314 vm_page_test_dirty(p);
315 if (((p->dirty & p->valid) == 0 &&
316 (p->flags & PG_NEED_COMMIT) == 0) ||
317 p->wire_count != 0 || /* may be held by buf cache */
318 p->hold_count != 0) { /* may be undergoing I/O */
322 if (p->queue - p->pc != PQ_INACTIVE) {
323 if (p->queue - p->pc != PQ_ACTIVE ||
324 (vmflush_flags & VM_PAGER_ALLOW_ACTIVE) == 0) {
331 * Try to maintain page groupings in the cluster.
333 if (m->flags & PG_WINATCFLS)
334 vm_page_flag_set(p, PG_WINATCFLS);
336 vm_page_flag_clear(p, PG_WINATCFLS);
337 p->act_count = m->act_count;
344 while (is < BLIST_MAX_ALLOC &&
345 pindex - page_base + is < object->size) {
348 p = vm_page_lookup_busy_try(object, pindex - page_base + is,
350 if (error || p == NULL)
352 if (((p->queue - p->pc) == PQ_CACHE) ||
353 (p->flags & PG_UNMANAGED)) {
357 vm_page_test_dirty(p);
358 if (((p->dirty & p->valid) == 0 &&
359 (p->flags & PG_NEED_COMMIT) == 0) ||
360 p->wire_count != 0 || /* may be held by buf cache */
361 p->hold_count != 0) { /* may be undergoing I/O */
365 if (p->queue - p->pc != PQ_INACTIVE) {
366 if (p->queue - p->pc != PQ_ACTIVE ||
367 (vmflush_flags & VM_PAGER_ALLOW_ACTIVE) == 0) {
374 * Try to maintain page groupings in the cluster.
376 if (m->flags & PG_WINATCFLS)
377 vm_page_flag_set(p, PG_WINATCFLS);
379 vm_page_flag_clear(p, PG_WINATCFLS);
380 p->act_count = m->act_count;
386 vm_object_drop(object);
389 * we allow reads during pageouts...
391 return vm_pageout_flush(&mc[ib], is - ib, vmflush_flags);
395 * vm_pageout_flush() - launder the given pages
397 * The given pages are laundered. Note that we setup for the start of
398 * I/O ( i.e. busy the page ), mark it read-only, and bump the object
399 * reference count all in here rather then in the parent. If we want
400 * the parent to do more sophisticated things we may have to change
403 * The pages in the array must be busied by the caller and will be
404 * unbusied by this function.
407 vm_pageout_flush(vm_page_t *mc, int count, int vmflush_flags)
410 int pageout_status[count];
415 * Initiate I/O. Bump the vm_page_t->busy counter.
417 for (i = 0; i < count; i++) {
418 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
419 ("vm_pageout_flush page %p index %d/%d: partially "
420 "invalid page", mc[i], i, count));
421 vm_page_io_start(mc[i]);
425 * We must make the pages read-only. This will also force the
426 * modified bit in the related pmaps to be cleared. The pager
427 * cannot clear the bit for us since the I/O completion code
428 * typically runs from an interrupt. The act of making the page
429 * read-only handles the case for us.
431 * Then we can unbusy the pages, we still hold a reference by virtue
434 for (i = 0; i < count; i++) {
435 if (vmflush_flags & VM_PAGER_TRY_TO_CACHE)
436 vm_page_protect(mc[i], VM_PROT_NONE);
438 vm_page_protect(mc[i], VM_PROT_READ);
439 vm_page_wakeup(mc[i]);
442 object = mc[0]->object;
443 vm_object_pip_add(object, count);
445 vm_pager_put_pages(object, mc, count,
447 ((object == &kernel_object) ?
448 VM_PAGER_PUT_SYNC : 0)),
451 for (i = 0; i < count; i++) {
452 vm_page_t mt = mc[i];
454 switch (pageout_status[i]) {
463 * Page outside of range of object. Right now we
464 * essentially lose the changes by pretending it
467 vm_page_busy_wait(mt, FALSE, "pgbad");
468 pmap_clear_modify(mt);
475 * A page typically cannot be paged out when we
476 * have run out of swap. We leave the page
477 * marked inactive and will try to page it out
480 * Starvation of the active page list is used to
481 * determine when the system is massively memory
490 * If not PENDing this was a synchronous operation and we
491 * clean up after the I/O. If it is PENDing the mess is
492 * cleaned up asynchronously.
494 * Also nominally act on the caller's wishes if the caller
495 * wants to try to really clean (cache or free) the page.
497 * Also nominally deactivate the page if the system is
500 if (pageout_status[i] != VM_PAGER_PEND) {
501 vm_page_busy_wait(mt, FALSE, "pgouw");
502 vm_page_io_finish(mt);
503 if (vmflush_flags & VM_PAGER_TRY_TO_CACHE) {
504 vm_page_try_to_cache(mt);
505 } else if (vm_page_count_severe()) {
506 vm_page_deactivate(mt);
511 vm_object_pip_wakeup(object);
517 #if !defined(NO_SWAPPING)
520 * Callback function, page busied for us. We must dispose of the busy
521 * condition. Any related pmap pages may be held but will not be locked.
525 vm_pageout_mdp_callback(struct pmap_pgscan_info *info, vm_offset_t va,
532 * Basic tests - There should never be a marker, and we can stop
533 * once the RSS is below the required level.
535 KKASSERT((p->flags & PG_MARKER) == 0);
536 if (pmap_resident_tlnw_count(info->pmap) <= info->limit) {
541 mycpu->gd_cnt.v_pdpages++;
543 if (p->wire_count || p->hold_count || (p->flags & PG_UNMANAGED)) {
551 * Check if the page has been referened recently. If it has,
552 * activate it and skip.
554 actcount = pmap_ts_referenced(p);
556 vm_page_flag_set(p, PG_REFERENCED);
557 } else if (p->flags & PG_REFERENCED) {
562 if (p->queue - p->pc != PQ_ACTIVE) {
563 vm_page_and_queue_spin_lock(p);
564 if (p->queue - p->pc != PQ_ACTIVE) {
565 vm_page_and_queue_spin_unlock(p);
568 vm_page_and_queue_spin_unlock(p);
571 p->act_count += actcount;
572 if (p->act_count > ACT_MAX)
573 p->act_count = ACT_MAX;
575 vm_page_flag_clear(p, PG_REFERENCED);
581 * Remove the page from this particular pmap. Once we do this, our
582 * pmap scans will not see it again (unless it gets faulted in), so
583 * we must actively dispose of or deal with the page.
585 pmap_remove_specific(info->pmap, p);
588 * If the page is not mapped to another process (i.e. as would be
589 * typical if this were a shared page from a library) then deactivate
590 * the page and clean it in two passes only.
592 * If the page hasn't been referenced since the last check, remove it
593 * from the pmap. If it is no longer mapped, deactivate it
594 * immediately, accelerating the normal decline.
596 * Once the page has been removed from the pmap the RSS code no
597 * longer tracks it so we have to make sure that it is staged for
598 * potential flush action.
600 if ((p->flags & PG_MAPPED) == 0) {
601 if (p->queue - p->pc == PQ_ACTIVE) {
602 vm_page_deactivate(p);
604 if (p->queue - p->pc == PQ_INACTIVE) {
610 * Ok, try to fully clean the page and any nearby pages such that at
611 * least the requested page is freed or moved to the cache queue.
613 * We usually do this synchronously to allow us to get the page into
614 * the CACHE queue quickly, which will prevent memory exhaustion if
615 * a process with a memoryuse limit is running away. However, the
616 * sysadmin may desire to set vm.swap_user_async which relaxes this
617 * and improves write performance.
620 long max_launder = 0x7FFF;
621 long vnodes_skipped = 0;
623 struct vnode *vpfailed = NULL;
627 if (vm_pageout_memuse_mode >= 2) {
628 vmflush_flags = VM_PAGER_TRY_TO_CACHE |
629 VM_PAGER_ALLOW_ACTIVE;
630 if (swap_user_async == 0)
631 vmflush_flags |= VM_PAGER_PUT_SYNC;
632 vm_page_flag_set(p, PG_WINATCFLS);
634 vm_pageout_page(p, &max_launder,
636 &vpfailed, 1, vmflush_flags);
646 * Must be at end to avoid SMP races.
654 * Deactivate some number of pages in a map due to set RLIMIT_RSS limits.
655 * that is relatively difficult to do. We try to keep track of where we
656 * left off last time to reduce scan overhead.
658 * Called when vm_pageout_memuse_mode is >= 1.
661 vm_pageout_map_deactivate_pages(vm_map_t map, vm_pindex_t limit)
663 vm_offset_t pgout_offset;
664 struct pmap_pgscan_info info;
667 pgout_offset = map->pgout_offset;
670 kprintf("%016jx ", pgout_offset);
672 if (pgout_offset < VM_MIN_USER_ADDRESS)
673 pgout_offset = VM_MIN_USER_ADDRESS;
674 if (pgout_offset >= VM_MAX_USER_ADDRESS)
676 info.pmap = vm_map_pmap(map);
678 info.beg_addr = pgout_offset;
679 info.end_addr = VM_MAX_USER_ADDRESS;
680 info.callback = vm_pageout_mdp_callback;
682 info.actioncount = 0;
686 pgout_offset = info.offset;
688 kprintf("%016jx %08lx %08lx\n", pgout_offset,
689 info.cleancount, info.actioncount);
692 if (pgout_offset != VM_MAX_USER_ADDRESS &&
693 pmap_resident_tlnw_count(vm_map_pmap(map)) > limit) {
695 } else if (retries &&
696 pmap_resident_tlnw_count(vm_map_pmap(map)) > limit) {
700 map->pgout_offset = pgout_offset;
705 * Called when the pageout scan wants to free a page. We no longer
706 * try to cycle the vm_object here with a reference & dealloc, which can
707 * cause a non-trivial object collapse in a critical path.
709 * It is unclear why we cycled the ref_count in the past, perhaps to try
710 * to optimize shadow chain collapses but I don't quite see why it would
711 * be necessary. An OBJ_DEAD object should terminate any and all vm_pages
712 * synchronously and not have to be kicked-start.
715 vm_pageout_page_free(vm_page_t m)
717 vm_page_protect(m, VM_PROT_NONE);
722 * vm_pageout_scan does the dirty work for the pageout daemon.
724 struct vm_pageout_scan_info {
725 struct proc *bigproc;
729 static int vm_pageout_scan_callback(struct proc *p, void *data);
732 * Scan inactive queue
734 * WARNING! Can be called from two pagedaemon threads simultaneously.
737 vm_pageout_scan_inactive(int pass, int q, long avail_shortage,
738 long *vnodes_skipped)
741 struct vm_page marker;
742 struct vnode *vpfailed; /* warning, allowed to be stale */
748 isep = (curthread == emergpager);
751 * Start scanning the inactive queue for pages we can move to the
752 * cache or free. The scan will stop when the target is reached or
753 * we have scanned the entire inactive queue. Note that m->act_count
754 * is not used to form decisions for the inactive queue, only for the
757 * max_launder limits the number of dirty pages we flush per scan.
758 * For most systems a smaller value (16 or 32) is more robust under
759 * extreme memory and disk pressure because any unnecessary writes
760 * to disk can result in extreme performance degredation. However,
761 * systems with excessive dirty pages (especially when MAP_NOSYNC is
762 * used) will die horribly with limited laundering. If the pageout
763 * daemon cannot clean enough pages in the first pass, we let it go
764 * all out in succeeding passes.
766 * NOTE! THE EMERGENCY PAGER (isep) DOES NOT LAUNDER VNODE-BACKED
769 if ((max_launder = vm_max_launder) <= 1)
775 * Initialize our marker
777 bzero(&marker, sizeof(marker));
778 marker.flags = PG_FICTITIOUS | PG_MARKER;
779 marker.busy_count = PBUSY_LOCKED;
780 marker.queue = PQ_INACTIVE + q;
782 marker.wire_count = 1;
785 * Inactive queue scan.
787 * NOTE: The vm_page must be spinlocked before the queue to avoid
788 * deadlocks, so it is easiest to simply iterate the loop
789 * with the queue unlocked at the top.
793 vm_page_queues_spin_lock(PQ_INACTIVE + q);
794 TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE + q].pl, &marker, pageq);
795 maxscan = vm_page_queues[PQ_INACTIVE + q].lcnt;
798 * Queue locked at top of loop to avoid stack marker issues.
800 while ((m = TAILQ_NEXT(&marker, pageq)) != NULL &&
801 maxscan-- > 0 && avail_shortage - delta > 0)
805 KKASSERT(m->queue == PQ_INACTIVE + q);
806 TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE + q].pl,
808 TAILQ_INSERT_AFTER(&vm_page_queues[PQ_INACTIVE + q].pl, m,
810 mycpu->gd_cnt.v_pdpages++;
813 * Skip marker pages (atomic against other markers to avoid
814 * infinite hop-over scans).
816 if (m->flags & PG_MARKER)
820 * Try to busy the page. Don't mess with pages which are
821 * already busy or reorder them in the queue.
823 if (vm_page_busy_try(m, TRUE))
827 * Remaining operations run with the page busy and neither
828 * the page or the queue will be spin-locked.
830 KKASSERT(m->queue == PQ_INACTIVE + q);
831 vm_page_queues_spin_unlock(PQ_INACTIVE + q);
834 * The emergency pager runs when the primary pager gets
835 * stuck, which typically means the primary pager deadlocked
836 * on a vnode-backed page. Therefore, the emergency pager
837 * must skip any complex objects.
839 * We disallow VNODEs unless they are VCHR whos device ops
840 * does not flag D_NOEMERGPGR.
842 if (isep && m->object) {
845 switch(m->object->type) {
849 * Allow anonymous memory and assume that
850 * swap devices are not complex, since its
851 * kinda worthless if we can't swap out dirty
857 * Allow VCHR device if the D_NOEMERGPGR
858 * flag is not set, deny other vnode types
859 * as being too complex.
861 vp = m->object->handle;
862 if (vp && vp->v_type == VCHR &&
863 vp->v_rdev && vp->v_rdev->si_ops &&
864 (vp->v_rdev->si_ops->head.flags &
865 D_NOEMERGPGR) == 0) {
868 /* Deny - fall through */
874 vm_page_queues_spin_lock(PQ_INACTIVE + q);
881 * Try to pageout the page and perhaps other nearby pages.
883 count = vm_pageout_page(m, &max_launder, vnodes_skipped,
888 * Systems with a ton of memory can wind up with huge
889 * deactivation counts. Because the inactive scan is
890 * doing a lot of flushing, the combination can result
891 * in excessive paging even in situations where other
892 * unrelated threads free up sufficient VM.
894 * To deal with this we abort the nominal active->inactive
895 * scan before we hit the inactive target when free+cache
896 * levels have reached a reasonable target.
898 * When deciding to stop early we need to add some slop to
899 * the test and we need to return full completion to the caller
900 * to prevent the caller from thinking there is something
901 * wrong and issuing a low-memory+swap warning or pkill.
903 * A deficit forces paging regardless of the state of the
904 * VM page queues (used for RSS enforcement).
907 vm_page_queues_spin_lock(PQ_INACTIVE + q);
908 if (vm_paging_target() < -vm_max_launder) {
910 * Stopping early, return full completion to caller.
912 if (delta < avail_shortage)
913 delta = avail_shortage;
918 /* page queue still spin-locked */
919 TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE + q].pl, &marker, pageq);
920 vm_page_queues_spin_unlock(PQ_INACTIVE + q);
926 * Pageout the specified page, return the total number of pages paged out
927 * (this routine may cluster).
929 * The page must be busied and soft-busied by the caller and will be disposed
930 * of by this function.
933 vm_pageout_page(vm_page_t m, long *max_launderp, long *vnodes_skippedp,
934 struct vnode **vpfailedp, int pass, int vmflush_flags)
941 * Wiring no longer removes a page from its queue. The last unwiring
942 * will requeue the page. Obviously wired pages cannot be paged out
943 * so unqueue it and return.
946 vm_page_unqueue_nowakeup(m);
952 * A held page may be undergoing I/O, so skip it.
955 vm_page_and_queue_spin_lock(m);
956 if (m->queue - m->pc == PQ_INACTIVE) {
958 &vm_page_queues[m->queue].pl, m, pageq);
960 &vm_page_queues[m->queue].pl, m, pageq);
961 ++vm_swapcache_inactive_heuristic;
963 vm_page_and_queue_spin_unlock(m);
968 if (m->object == NULL || m->object->ref_count == 0) {
970 * If the object is not being used, we ignore previous
973 vm_page_flag_clear(m, PG_REFERENCED);
974 pmap_clear_reference(m);
975 /* fall through to end */
976 } else if (((m->flags & PG_REFERENCED) == 0) &&
977 (actcount = pmap_ts_referenced(m))) {
979 * Otherwise, if the page has been referenced while
980 * in the inactive queue, we bump the "activation
981 * count" upwards, making it less likely that the
982 * page will be added back to the inactive queue
983 * prematurely again. Here we check the page tables
984 * (or emulated bits, if any), given the upper level
985 * VM system not knowing anything about existing
989 m->act_count += (actcount + ACT_ADVANCE);
995 * (m) is still busied.
997 * If the upper level VM system knows about any page
998 * references, we activate the page. We also set the
999 * "activation count" higher than normal so that we will less
1000 * likely place pages back onto the inactive queue again.
1002 if ((m->flags & PG_REFERENCED) != 0) {
1003 vm_page_flag_clear(m, PG_REFERENCED);
1004 actcount = pmap_ts_referenced(m);
1005 vm_page_activate(m);
1006 m->act_count += (actcount + ACT_ADVANCE + 1);
1012 * If the upper level VM system doesn't know anything about
1013 * the page being dirty, we have to check for it again. As
1014 * far as the VM code knows, any partially dirty pages are
1017 * Pages marked PG_WRITEABLE may be mapped into the user
1018 * address space of a process running on another cpu. A
1019 * user process (without holding the MP lock) running on
1020 * another cpu may be able to touch the page while we are
1021 * trying to remove it. vm_page_cache() will handle this
1024 if (m->dirty == 0) {
1025 vm_page_test_dirty(m);
1030 if (m->valid == 0 && (m->flags & PG_NEED_COMMIT) == 0) {
1032 * Invalid pages can be easily freed
1034 vm_pageout_page_free(m);
1035 mycpu->gd_cnt.v_dfree++;
1037 } else if (m->dirty == 0 && (m->flags & PG_NEED_COMMIT) == 0) {
1039 * Clean pages can be placed onto the cache queue.
1040 * This effectively frees them.
1044 } else if ((m->flags & PG_WINATCFLS) == 0 && pass == 0) {
1046 * Dirty pages need to be paged out, but flushing
1047 * a page is extremely expensive verses freeing
1048 * a clean page. Rather then artificially limiting
1049 * the number of pages we can flush, we instead give
1050 * dirty pages extra priority on the inactive queue
1051 * by forcing them to be cycled through the queue
1052 * twice before being flushed, after which the
1053 * (now clean) page will cycle through once more
1054 * before being freed. This significantly extends
1055 * the thrash point for a heavily loaded machine.
1057 vm_page_flag_set(m, PG_WINATCFLS);
1058 vm_page_and_queue_spin_lock(m);
1059 if (m->queue - m->pc == PQ_INACTIVE) {
1061 &vm_page_queues[m->queue].pl, m, pageq);
1063 &vm_page_queues[m->queue].pl, m, pageq);
1064 ++vm_swapcache_inactive_heuristic;
1066 vm_page_and_queue_spin_unlock(m);
1068 } else if (*max_launderp > 0) {
1070 * We always want to try to flush some dirty pages if
1071 * we encounter them, to keep the system stable.
1072 * Normally this number is small, but under extreme
1073 * pressure where there are insufficient clean pages
1074 * on the inactive queue, we may have to go all out.
1076 int swap_pageouts_ok;
1077 struct vnode *vp = NULL;
1079 swap_pageouts_ok = 0;
1082 (object->type != OBJT_SWAP) &&
1083 (object->type != OBJT_DEFAULT)) {
1084 swap_pageouts_ok = 1;
1086 swap_pageouts_ok = !(defer_swap_pageouts ||
1087 disable_swap_pageouts);
1088 swap_pageouts_ok |= (!disable_swap_pageouts &&
1089 defer_swap_pageouts &&
1090 vm_page_count_min(0));
1094 * We don't bother paging objects that are "dead".
1095 * Those objects are in a "rundown" state.
1097 if (!swap_pageouts_ok ||
1099 (object->flags & OBJ_DEAD)) {
1100 vm_page_and_queue_spin_lock(m);
1101 if (m->queue - m->pc == PQ_INACTIVE) {
1103 &vm_page_queues[m->queue].pl,
1106 &vm_page_queues[m->queue].pl,
1108 ++vm_swapcache_inactive_heuristic;
1110 vm_page_and_queue_spin_unlock(m);
1116 * (m) is still busied.
1118 * The object is already known NOT to be dead. It
1119 * is possible for the vget() to block the whole
1120 * pageout daemon, but the new low-memory handling
1121 * code should prevent it.
1123 * The previous code skipped locked vnodes and, worse,
1124 * reordered pages in the queue. This results in
1125 * completely non-deterministic operation because,
1126 * quite often, a vm_fault has initiated an I/O and
1127 * is holding a locked vnode at just the point where
1128 * the pageout daemon is woken up.
1130 * We can't wait forever for the vnode lock, we might
1131 * deadlock due to a vn_read() getting stuck in
1132 * vm_wait while holding this vnode. We skip the
1133 * vnode if we can't get it in a reasonable amount
1136 * vpfailed is used to (try to) avoid the case where
1137 * a large number of pages are associated with a
1138 * locked vnode, which could cause the pageout daemon
1139 * to stall for an excessive amount of time.
1141 if (object->type == OBJT_VNODE) {
1144 vp = object->handle;
1145 flags = LK_EXCLUSIVE;
1146 if (vp == *vpfailedp)
1149 flags |= LK_TIMELOCK;
1154 * We have unbusied (m) temporarily so we can
1155 * acquire the vp lock without deadlocking.
1156 * (m) is held to prevent destruction.
1158 if (vget(vp, flags) != 0) {
1160 ++pageout_lock_miss;
1161 if (object->flags & OBJ_MIGHTBEDIRTY)
1168 * The page might have been moved to another
1169 * queue during potential blocking in vget()
1170 * above. The page might have been freed and
1171 * reused for another vnode. The object might
1172 * have been reused for another vnode.
1174 if (m->queue - m->pc != PQ_INACTIVE ||
1175 m->object != object ||
1176 object->handle != vp) {
1177 if (object->flags & OBJ_MIGHTBEDIRTY)
1185 * The page may have been busied during the
1186 * blocking in vput(); We don't move the
1187 * page back onto the end of the queue so that
1188 * statistics are more correct if we don't.
1190 if (vm_page_busy_try(m, TRUE)) {
1198 * If it was wired while we didn't own it.
1200 if (m->wire_count) {
1201 vm_page_unqueue_nowakeup(m);
1208 * (m) is busied again
1210 * We own the busy bit and remove our hold
1211 * bit. If the page is still held it
1212 * might be undergoing I/O, so skip it.
1214 if (m->hold_count) {
1215 vm_page_and_queue_spin_lock(m);
1216 if (m->queue - m->pc == PQ_INACTIVE) {
1217 TAILQ_REMOVE(&vm_page_queues[m->queue].pl, m, pageq);
1218 TAILQ_INSERT_TAIL(&vm_page_queues[m->queue].pl, m, pageq);
1219 ++vm_swapcache_inactive_heuristic;
1221 vm_page_and_queue_spin_unlock(m);
1222 if (object->flags & OBJ_MIGHTBEDIRTY)
1228 /* (m) is left busied as we fall through */
1232 * page is busy and not held here.
1234 * If a page is dirty, then it is either being washed
1235 * (but not yet cleaned) or it is still in the
1236 * laundry. If it is still in the laundry, then we
1237 * start the cleaning operation.
1239 * decrement inactive_shortage on success to account
1240 * for the (future) cleaned page. Otherwise we
1241 * could wind up laundering or cleaning too many
1244 * NOTE: Cleaning the page here does not cause
1245 * force_deficit to be adjusted, because the
1246 * page is not being freed or moved to the
1249 count = vm_pageout_clean_helper(m, vmflush_flags);
1250 *max_launderp -= count;
1253 * Clean ate busy, page no longer accessible
1266 * WARNING! Can be called from two pagedaemon threads simultaneously.
1269 vm_pageout_scan_active(int pass, int q,
1270 long avail_shortage, long inactive_shortage,
1271 long *recycle_countp)
1273 struct vm_page marker;
1280 isep = (curthread == emergpager);
1283 * We want to move pages from the active queue to the inactive
1284 * queue to get the inactive queue to the inactive target. If
1285 * we still have a page shortage from above we try to directly free
1286 * clean pages instead of moving them.
1288 * If we do still have a shortage we keep track of the number of
1289 * pages we free or cache (recycle_count) as a measure of thrashing
1290 * between the active and inactive queues.
1292 * If we were able to completely satisfy the free+cache targets
1293 * from the inactive pool we limit the number of pages we move
1294 * from the active pool to the inactive pool to 2x the pages we
1295 * had removed from the inactive pool (with a minimum of 1/5 the
1296 * inactive target). If we were not able to completely satisfy
1297 * the free+cache targets we go for the whole target aggressively.
1299 * NOTE: Both variables can end up negative.
1300 * NOTE: We are still in a critical section.
1302 * NOTE! THE EMERGENCY PAGER (isep) DOES NOT LAUNDER VNODE-BACKED
1306 bzero(&marker, sizeof(marker));
1307 marker.flags = PG_FICTITIOUS | PG_MARKER;
1308 marker.busy_count = PBUSY_LOCKED;
1309 marker.queue = PQ_ACTIVE + q;
1311 marker.wire_count = 1;
1313 vm_page_queues_spin_lock(PQ_ACTIVE + q);
1314 TAILQ_INSERT_HEAD(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1315 maxscan = vm_page_queues[PQ_ACTIVE + q].lcnt;
1318 * Queue locked at top of loop to avoid stack marker issues.
1320 while ((m = TAILQ_NEXT(&marker, pageq)) != NULL &&
1321 maxscan-- > 0 && (avail_shortage - delta > 0 ||
1322 inactive_shortage > 0))
1324 KKASSERT(m->queue == PQ_ACTIVE + q);
1325 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl,
1327 TAILQ_INSERT_AFTER(&vm_page_queues[PQ_ACTIVE + q].pl, m,
1331 * Skip marker pages (atomic against other markers to avoid
1332 * infinite hop-over scans).
1334 if (m->flags & PG_MARKER)
1338 * Try to busy the page. Don't mess with pages which are
1339 * already busy or reorder them in the queue.
1341 if (vm_page_busy_try(m, TRUE))
1345 * Remaining operations run with the page busy and neither
1346 * the page or the queue will be spin-locked.
1348 KKASSERT(m->queue == PQ_ACTIVE + q);
1349 vm_page_queues_spin_unlock(PQ_ACTIVE + q);
1353 * Don't deactivate pages that are held, even if we can
1354 * busy them. (XXX why not?)
1356 if (m->hold_count) {
1357 vm_page_and_queue_spin_lock(m);
1358 if (m->queue - m->pc == PQ_ACTIVE) {
1360 &vm_page_queues[PQ_ACTIVE + q].pl,
1363 &vm_page_queues[PQ_ACTIVE + q].pl,
1366 vm_page_and_queue_spin_unlock(m);
1372 * We can just remove wired pages from the queue
1374 if (m->wire_count) {
1375 vm_page_unqueue_nowakeup(m);
1381 * The emergency pager ignores vnode-backed pages as these
1382 * are the pages that probably bricked the main pager.
1384 if (isep && m->object && m->object->type == OBJT_VNODE) {
1385 vm_page_and_queue_spin_lock(m);
1386 if (m->queue - m->pc == PQ_ACTIVE) {
1388 &vm_page_queues[PQ_ACTIVE + q].pl,
1391 &vm_page_queues[PQ_ACTIVE + q].pl,
1394 vm_page_and_queue_spin_unlock(m);
1400 * The count for pagedaemon pages is done after checking the
1401 * page for eligibility...
1403 mycpu->gd_cnt.v_pdpages++;
1406 * Check to see "how much" the page has been used and clear
1407 * the tracking access bits. If the object has no references
1408 * don't bother paying the expense.
1411 if (m->object && m->object->ref_count != 0) {
1412 if (m->flags & PG_REFERENCED)
1414 actcount += pmap_ts_referenced(m);
1416 m->act_count += ACT_ADVANCE + actcount;
1417 if (m->act_count > ACT_MAX)
1418 m->act_count = ACT_MAX;
1421 vm_page_flag_clear(m, PG_REFERENCED);
1424 * actcount is only valid if the object ref_count is non-zero.
1425 * If the page does not have an object, actcount will be zero.
1427 if (actcount && m->object->ref_count != 0) {
1428 vm_page_and_queue_spin_lock(m);
1429 if (m->queue - m->pc == PQ_ACTIVE) {
1431 &vm_page_queues[PQ_ACTIVE + q].pl,
1434 &vm_page_queues[PQ_ACTIVE + q].pl,
1437 vm_page_and_queue_spin_unlock(m);
1440 switch(m->object->type) {
1443 m->act_count -= min(m->act_count,
1444 vm_anonmem_decline);
1447 m->act_count -= min(m->act_count,
1448 vm_filemem_decline);
1451 if (vm_pageout_algorithm ||
1452 (m->object == NULL) ||
1453 (m->object && (m->object->ref_count == 0)) ||
1454 m->act_count < pass + 1
1457 * Deactivate the page. If we had a
1458 * shortage from our inactive scan try to
1459 * free (cache) the page instead.
1461 * Don't just blindly cache the page if
1462 * we do not have a shortage from the
1463 * inactive scan, that could lead to
1464 * gigabytes being moved.
1466 --inactive_shortage;
1467 if (avail_shortage - delta > 0 ||
1468 (m->object && (m->object->ref_count == 0)))
1470 if (avail_shortage - delta > 0)
1472 vm_page_protect(m, VM_PROT_NONE);
1473 if (m->dirty == 0 &&
1474 (m->flags & PG_NEED_COMMIT) == 0 &&
1475 avail_shortage - delta > 0) {
1478 vm_page_deactivate(m);
1482 vm_page_deactivate(m);
1487 vm_page_and_queue_spin_lock(m);
1488 if (m->queue - m->pc == PQ_ACTIVE) {
1490 &vm_page_queues[PQ_ACTIVE + q].pl,
1493 &vm_page_queues[PQ_ACTIVE + q].pl,
1496 vm_page_and_queue_spin_unlock(m);
1502 vm_page_queues_spin_lock(PQ_ACTIVE + q);
1506 * Clean out our local marker.
1508 * Page queue still spin-locked.
1510 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1511 vm_page_queues_spin_unlock(PQ_ACTIVE + q);
1517 * The number of actually free pages can drop down to v_free_reserved,
1518 * we try to build the free count back above v_free_min. Note that
1519 * vm_paging_needed() also returns TRUE if v_free_count is not at
1520 * least v_free_min so that is the minimum we must build the free
1523 * We use a slightly higher target to improve hysteresis,
1524 * ((v_free_target + v_free_min) / 2). Since v_free_target
1525 * is usually the same as v_cache_min this maintains about
1526 * half the pages in the free queue as are in the cache queue,
1527 * providing pretty good pipelining for pageout operation.
1529 * The system operator can manipulate vm.v_cache_min and
1530 * vm.v_free_target to tune the pageout demon. Be sure
1531 * to keep vm.v_free_min < vm.v_free_target.
1533 * Note that the original paging target is to get at least
1534 * (free_min + cache_min) into (free + cache). The slightly
1535 * higher target will shift additional pages from cache to free
1536 * without effecting the original paging target in order to
1537 * maintain better hysteresis and not have the free count always
1538 * be dead-on v_free_min.
1540 * NOTE: we are still in a critical section.
1542 * Pages moved from PQ_CACHE to totally free are not counted in the
1543 * pages_freed counter.
1545 * WARNING! Can be called from two pagedaemon threads simultaneously.
1548 vm_pageout_scan_cache(long avail_shortage, int pass,
1549 long vnodes_skipped, long recycle_count)
1551 static int lastkillticks;
1552 struct vm_pageout_scan_info info;
1556 isep = (curthread == emergpager);
1558 while (vmstats.v_free_count <
1559 (vmstats.v_free_min + vmstats.v_free_target) / 2) {
1561 * This steals some code from vm/vm_page.c
1563 * Create two rovers and adjust the code to reduce
1564 * chances of them winding up at the same index (which
1565 * can cause a lot of contention).
1567 static int cache_rover[2] = { 0, PQ_L2_MASK / 2 };
1569 if (((cache_rover[0] ^ cache_rover[1]) & PQ_L2_MASK) == 0)
1572 m = vm_page_list_find(PQ_CACHE, cache_rover[isep] & PQ_L2_MASK);
1577 * If the busy attempt fails we can still deactivate the page.
1579 /* page is returned removed from its queue and spinlocked */
1580 if (vm_page_busy_try(m, TRUE)) {
1581 vm_page_deactivate_locked(m);
1582 vm_page_spin_unlock(m);
1585 vm_page_spin_unlock(m);
1586 pagedaemon_wakeup();
1590 * Remaining operations run with the page busy and neither
1591 * the page or the queue will be spin-locked.
1593 if ((m->flags & (PG_UNMANAGED | PG_NEED_COMMIT)) ||
1596 vm_page_deactivate(m);
1600 KKASSERT((m->flags & PG_MAPPED) == 0);
1601 KKASSERT(m->dirty == 0);
1602 vm_pageout_page_free(m);
1603 mycpu->gd_cnt.v_dfree++;
1606 cache_rover[1] -= PQ_PRIME2;
1608 cache_rover[0] += PQ_PRIME2;
1611 #if !defined(NO_SWAPPING)
1613 * Idle process swapout -- run once per second.
1615 if (vm_swap_idle_enabled) {
1617 if (time_uptime != lsec) {
1618 atomic_set_int(&vm_pageout_req_swapout, VM_SWAP_IDLE);
1626 * If we didn't get enough free pages, and we have skipped a vnode
1627 * in a writeable object, wakeup the sync daemon. And kick swapout
1628 * if we did not get enough free pages.
1630 if (vm_paging_target() > 0) {
1631 if (vnodes_skipped && vm_page_count_min(0))
1632 speedup_syncer(NULL);
1633 #if !defined(NO_SWAPPING)
1634 if (vm_swap_enabled && vm_page_count_target()) {
1635 atomic_set_int(&vm_pageout_req_swapout, VM_SWAP_NORMAL);
1642 * Handle catastrophic conditions. Under good conditions we should
1643 * be at the target, well beyond our minimum. If we could not even
1644 * reach our minimum the system is under heavy stress. But just being
1645 * under heavy stress does not trigger process killing.
1647 * We consider ourselves to have run out of memory if the swap pager
1648 * is full and avail_shortage is still positive. The secondary check
1649 * ensures that we do not kill processes if the instantanious
1650 * availability is good, even if the pageout demon pass says it
1651 * couldn't get to the target.
1653 * NOTE! THE EMERGENCY PAGER (isep) DOES NOT HANDLE SWAP FULL
1656 if (swap_pager_almost_full &&
1659 (vm_page_count_min(recycle_count) || avail_shortage > 0)) {
1660 kprintf("Warning: system low on memory+swap "
1661 "shortage %ld for %d ticks!\n",
1662 avail_shortage, ticks - swap_fail_ticks);
1664 kprintf("Metrics: spaf=%d spf=%d pass=%d "
1665 "avail=%ld target=%ld last=%u\n",
1666 swap_pager_almost_full,
1671 (unsigned int)(ticks - lastkillticks));
1673 if (swap_pager_full &&
1676 avail_shortage > 0 &&
1677 vm_paging_target() > 0 &&
1678 (unsigned int)(ticks - lastkillticks) >= hz) {
1680 * Kill something, maximum rate once per second to give
1681 * the process time to free up sufficient memory.
1683 lastkillticks = ticks;
1684 info.bigproc = NULL;
1686 allproc_scan(vm_pageout_scan_callback, &info, 0);
1687 if (info.bigproc != NULL) {
1688 kprintf("Try to kill process %d %s\n",
1689 info.bigproc->p_pid, info.bigproc->p_comm);
1690 info.bigproc->p_nice = PRIO_MIN;
1691 info.bigproc->p_usched->resetpriority(
1692 FIRST_LWP_IN_PROC(info.bigproc));
1693 atomic_set_int(&info.bigproc->p_flags, P_LOWMEMKILL);
1694 killproc(info.bigproc, "out of swap space");
1695 wakeup(&vmstats.v_free_count);
1696 PRELE(info.bigproc);
1702 vm_pageout_scan_callback(struct proc *p, void *data)
1704 struct vm_pageout_scan_info *info = data;
1708 * Never kill system processes or init. If we have configured swap
1709 * then try to avoid killing low-numbered pids.
1711 if ((p->p_flags & P_SYSTEM) || (p->p_pid == 1) ||
1712 ((p->p_pid < 48) && (vm_swap_size != 0))) {
1716 lwkt_gettoken(&p->p_token);
1719 * if the process is in a non-running type state,
1722 if (p->p_stat != SACTIVE && p->p_stat != SSTOP && p->p_stat != SCORE) {
1723 lwkt_reltoken(&p->p_token);
1728 * Get the approximate process size. Note that anonymous pages
1729 * with backing swap will be counted twice, but there should not
1730 * be too many such pages due to the stress the VM system is
1731 * under at this point.
1733 size = vmspace_anonymous_count(p->p_vmspace) +
1734 vmspace_swap_count(p->p_vmspace);
1737 * If the this process is bigger than the biggest one
1740 if (info->bigsize < size) {
1742 PRELE(info->bigproc);
1745 info->bigsize = size;
1747 lwkt_reltoken(&p->p_token);
1754 * This old guy slowly walks PQ_HOLD looking for pages which need to be
1755 * moved back to PQ_FREE. It is possible for pages to accumulate here
1756 * when vm_page_free() races against vm_page_unhold(), resulting in a
1757 * page being left on a PQ_HOLD queue with hold_count == 0.
1759 * It is easier to handle this edge condition here, in non-critical code,
1760 * rather than enforce a spin-lock for every 1->0 transition in
1763 * NOTE: TAILQ_FOREACH becomes invalid the instant we unlock the queue.
1766 vm_pageout_scan_hold(int q)
1770 vm_page_queues_spin_lock(PQ_HOLD + q);
1771 TAILQ_FOREACH(m, &vm_page_queues[PQ_HOLD + q].pl, pageq) {
1772 if (m->flags & PG_MARKER)
1776 * Process one page and return
1780 kprintf("DEBUG: pageout HOLD->FREE %p\n", m);
1782 vm_page_queues_spin_unlock(PQ_HOLD + q);
1783 vm_page_unhold(m); /* reprocess */
1786 vm_page_queues_spin_unlock(PQ_HOLD + q);
1790 * This routine tries to maintain the pseudo LRU active queue,
1791 * so that during long periods of time where there is no paging,
1792 * that some statistic accumulation still occurs. This code
1793 * helps the situation where paging just starts to occur.
1796 vm_pageout_page_stats(int q)
1798 static int fullintervalcount = 0;
1799 struct vm_page marker;
1801 long pcount, tpcount; /* Number of pages to check */
1804 page_shortage = (vmstats.v_inactive_target + vmstats.v_cache_max +
1805 vmstats.v_free_min) -
1806 (vmstats.v_free_count + vmstats.v_inactive_count +
1807 vmstats.v_cache_count);
1809 if (page_shortage <= 0)
1812 pcount = vm_page_queues[PQ_ACTIVE + q].lcnt;
1813 fullintervalcount += vm_pageout_stats_interval;
1814 if (fullintervalcount < vm_pageout_full_stats_interval) {
1815 tpcount = (vm_pageout_stats_max * pcount) /
1816 vmstats.v_page_count + 1;
1817 if (pcount > tpcount)
1820 fullintervalcount = 0;
1823 bzero(&marker, sizeof(marker));
1824 marker.flags = PG_FICTITIOUS | PG_MARKER;
1825 marker.busy_count = PBUSY_LOCKED;
1826 marker.queue = PQ_ACTIVE + q;
1828 marker.wire_count = 1;
1830 vm_page_queues_spin_lock(PQ_ACTIVE + q);
1831 TAILQ_INSERT_HEAD(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1834 * Queue locked at top of loop to avoid stack marker issues.
1836 while ((m = TAILQ_NEXT(&marker, pageq)) != NULL &&
1841 KKASSERT(m->queue == PQ_ACTIVE + q);
1842 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1843 TAILQ_INSERT_AFTER(&vm_page_queues[PQ_ACTIVE + q].pl, m,
1847 * Skip marker pages (atomic against other markers to avoid
1848 * infinite hop-over scans).
1850 if (m->flags & PG_MARKER)
1854 * Ignore pages we can't busy
1856 if (vm_page_busy_try(m, TRUE))
1860 * Remaining operations run with the page busy and neither
1861 * the page or the queue will be spin-locked.
1863 KKASSERT(m->queue == PQ_ACTIVE + q);
1864 vm_page_queues_spin_unlock(PQ_ACTIVE + q);
1867 * We can just remove wired pages from the queue
1869 if (m->wire_count) {
1870 vm_page_unqueue_nowakeup(m);
1877 * We now have a safely busied page, the page and queue
1878 * spinlocks have been released.
1880 * Ignore held and wired pages
1882 if (m->hold_count || m->wire_count) {
1888 * Calculate activity
1891 if (m->flags & PG_REFERENCED) {
1892 vm_page_flag_clear(m, PG_REFERENCED);
1895 actcount += pmap_ts_referenced(m);
1898 * Update act_count and move page to end of queue.
1901 m->act_count += ACT_ADVANCE + actcount;
1902 if (m->act_count > ACT_MAX)
1903 m->act_count = ACT_MAX;
1904 vm_page_and_queue_spin_lock(m);
1905 if (m->queue - m->pc == PQ_ACTIVE) {
1907 &vm_page_queues[PQ_ACTIVE + q].pl,
1910 &vm_page_queues[PQ_ACTIVE + q].pl,
1913 vm_page_and_queue_spin_unlock(m);
1918 if (m->act_count == 0) {
1920 * We turn off page access, so that we have
1921 * more accurate RSS stats. We don't do this
1922 * in the normal page deactivation when the
1923 * system is loaded VM wise, because the
1924 * cost of the large number of page protect
1925 * operations would be higher than the value
1926 * of doing the operation.
1928 * We use the marker to save our place so
1929 * we can release the spin lock. both (m)
1930 * and (next) will be invalid.
1932 vm_page_protect(m, VM_PROT_NONE);
1933 vm_page_deactivate(m);
1935 m->act_count -= min(m->act_count, ACT_DECLINE);
1936 vm_page_and_queue_spin_lock(m);
1937 if (m->queue - m->pc == PQ_ACTIVE) {
1939 &vm_page_queues[PQ_ACTIVE + q].pl,
1942 &vm_page_queues[PQ_ACTIVE + q].pl,
1945 vm_page_and_queue_spin_unlock(m);
1949 vm_page_queues_spin_lock(PQ_ACTIVE + q);
1953 * Remove our local marker
1955 * Page queue still spin-locked.
1957 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1958 vm_page_queues_spin_unlock(PQ_ACTIVE + q);
1962 vm_pageout_free_page_calc(vm_size_t count)
1964 if (count < vmstats.v_page_count)
1967 * free_reserved needs to include enough for the largest swap pager
1968 * structures plus enough for any pv_entry structs when paging.
1970 * v_free_min normal allocations
1971 * v_free_reserved system allocations
1972 * v_pageout_free_min allocations by pageout daemon
1973 * v_interrupt_free_min low level allocations (e.g swap structures)
1975 if (vmstats.v_page_count > 1024)
1976 vmstats.v_free_min = 64 + (vmstats.v_page_count - 1024) / 200;
1978 vmstats.v_free_min = 64;
1981 * Make sure the vmmeter slop can't blow out our global minimums.
1983 * However, to accomodate weird configurations (vkernels with many
1984 * cpus and little memory, or artifically reduced hw.physmem), do
1985 * not allow v_free_min to exceed 1/20 of ram or the pageout demon
1986 * will go out of control.
1988 if (vmstats.v_free_min < VMMETER_SLOP_COUNT * ncpus * 10)
1989 vmstats.v_free_min = VMMETER_SLOP_COUNT * ncpus * 10;
1990 if (vmstats.v_free_min > vmstats.v_page_count / 20)
1991 vmstats.v_free_min = vmstats.v_page_count / 20;
1993 vmstats.v_free_reserved = vmstats.v_free_min * 4 / 8 + 7;
1994 vmstats.v_free_severe = vmstats.v_free_min * 4 / 8 + 0;
1995 vmstats.v_pageout_free_min = vmstats.v_free_min * 2 / 8 + 7;
1996 vmstats.v_interrupt_free_min = vmstats.v_free_min * 1 / 8 + 7;
2003 * vm_pageout is the high level pageout daemon. TWO kernel threads run
2004 * this daemon, the primary pageout daemon and the emergency pageout daemon.
2006 * The emergency pageout daemon takes over when the primary pageout daemon
2007 * deadlocks. The emergency pageout daemon ONLY pages out to swap, thus
2008 * avoiding the many low-memory deadlocks which can occur when paging out
2012 vm_pageout_thread(void)
2021 curthread->td_flags |= TDF_SYSTHREAD;
2024 * We only need to setup once.
2027 if (curthread == emergpager) {
2033 * Initialize some paging parameters.
2035 vm_pageout_free_page_calc(vmstats.v_page_count);
2038 * v_free_target and v_cache_min control pageout hysteresis. Note
2039 * that these are more a measure of the VM cache queue hysteresis
2040 * then the VM free queue. Specifically, v_free_target is the
2041 * high water mark (free+cache pages).
2043 * v_free_reserved + v_cache_min (mostly means v_cache_min) is the
2044 * low water mark, while v_free_min is the stop. v_cache_min must
2045 * be big enough to handle memory needs while the pageout daemon
2046 * is signalled and run to free more pages.
2048 if (vmstats.v_free_count > 6144)
2049 vmstats.v_free_target = 4 * vmstats.v_free_min +
2050 vmstats.v_free_reserved;
2052 vmstats.v_free_target = 2 * vmstats.v_free_min +
2053 vmstats.v_free_reserved;
2056 * NOTE: With the new buffer cache b_act_count we want the default
2057 * inactive target to be a percentage of available memory.
2059 * The inactive target essentially determines the minimum
2060 * number of 'temporary' pages capable of caching one-time-use
2061 * files when the VM system is otherwise full of pages
2062 * belonging to multi-time-use files or active program data.
2064 * NOTE: The inactive target is aggressively persued only if the
2065 * inactive queue becomes too small. If the inactive queue
2066 * is large enough to satisfy page movement to free+cache
2067 * then it is repopulated more slowly from the active queue.
2068 * This allows a general inactive_target default to be set.
2070 * There is an issue here for processes which sit mostly idle
2071 * 'overnight', such as sshd, tcsh, and X. Any movement from
2072 * the active queue will eventually cause such pages to
2073 * recycle eventually causing a lot of paging in the morning.
2074 * To reduce the incidence of this pages cycled out of the
2075 * buffer cache are moved directly to the inactive queue if
2076 * they were only used once or twice.
2078 * The vfs.vm_cycle_point sysctl can be used to adjust this.
2079 * Increasing the value (up to 64) increases the number of
2080 * buffer recyclements which go directly to the inactive queue.
2082 if (vmstats.v_free_count > 2048) {
2083 vmstats.v_cache_min = vmstats.v_free_target;
2084 vmstats.v_cache_max = 2 * vmstats.v_cache_min;
2086 vmstats.v_cache_min = 0;
2087 vmstats.v_cache_max = 0;
2089 vmstats.v_inactive_target = vmstats.v_free_count / 4;
2091 /* XXX does not really belong here */
2092 if (vm_page_max_wired == 0)
2093 vm_page_max_wired = vmstats.v_free_count / 3;
2095 if (vm_pageout_stats_max == 0)
2096 vm_pageout_stats_max = vmstats.v_free_target;
2099 * Set interval in seconds for stats scan.
2101 if (vm_pageout_stats_interval == 0)
2102 vm_pageout_stats_interval = 5;
2103 if (vm_pageout_full_stats_interval == 0)
2104 vm_pageout_full_stats_interval = vm_pageout_stats_interval * 4;
2108 * Set maximum free per pass
2110 if (vm_pageout_stats_free_max == 0)
2111 vm_pageout_stats_free_max = 5;
2113 swap_pager_swap_init();
2116 atomic_swap_int(&sequence_emerg_pager, 1);
2117 wakeup(&sequence_emerg_pager);
2121 * Sequence emergency pager startup
2124 while (sequence_emerg_pager == 0)
2125 tsleep(&sequence_emerg_pager, 0, "pstartup", hz);
2129 * The pageout daemon is never done, so loop forever.
2131 * WARNING! This code is being executed by two kernel threads
2132 * potentially simultaneously.
2136 long avail_shortage;
2137 long inactive_shortage;
2138 long vnodes_skipped = 0;
2139 long recycle_count = 0;
2143 * Wait for an action request. If we timeout check to
2144 * see if paging is needed (in case the normal wakeup
2149 * Emergency pagedaemon monitors the primary
2150 * pagedaemon while vm_pages_needed != 0.
2152 * The emergency pagedaemon only runs if VM paging
2153 * is needed and the primary pagedaemon has not
2154 * updated vm_pagedaemon_time for more than 2 seconds.
2156 if (vm_pages_needed)
2157 tsleep(&vm_pagedaemon_time, 0, "psleep", hz);
2159 tsleep(&vm_pagedaemon_time, 0, "psleep", hz*10);
2160 if (vm_pages_needed == 0) {
2164 if ((int)(ticks - vm_pagedaemon_time) < hz * 2) {
2170 * Primary pagedaemon
2172 * NOTE: We unconditionally cleanup PQ_HOLD even
2173 * when there is no work to do.
2175 vm_pageout_scan_hold(q3iterator & PQ_L2_MASK);
2178 if (vm_pages_needed == 0) {
2179 error = tsleep(&vm_pages_needed,
2181 vm_pageout_stats_interval * hz);
2183 vm_paging_needed() == 0 &&
2184 vm_pages_needed == 0) {
2185 for (q = 0; q < PQ_L2_SIZE; ++q)
2186 vm_pageout_page_stats(q);
2189 vm_pagedaemon_time = ticks;
2190 vm_pages_needed = 1;
2193 * Wake the emergency pagedaemon up so it
2194 * can monitor us. It will automatically
2195 * go back into a long sleep when
2196 * vm_pages_needed returns to 0.
2198 wakeup(&vm_pagedaemon_time);
2202 mycpu->gd_cnt.v_pdwakeups++;
2205 * Scan for INACTIVE->CLEAN/PAGEOUT
2207 * This routine tries to avoid thrashing the system with
2208 * unnecessary activity.
2210 * Calculate our target for the number of free+cache pages we
2211 * want to get to. This is higher then the number that causes
2212 * allocations to stall (severe) in order to provide hysteresis,
2213 * and if we don't make it all the way but get to the minimum
2214 * we're happy. Goose it a bit if there are multiple requests
2217 * Don't reduce avail_shortage inside the loop or the
2218 * PQAVERAGE() calculation will break.
2220 * NOTE! deficit is differentiated from avail_shortage as
2221 * REQUIRING at least (deficit) pages to be cleaned,
2222 * even if the page queues are in good shape. This
2223 * is used primarily for handling per-process
2224 * RLIMIT_RSS and may also see small values when
2225 * processes block due to low memory.
2229 vm_pagedaemon_time = ticks;
2230 avail_shortage = vm_paging_target() + vm_pageout_deficit;
2231 vm_pageout_deficit = 0;
2233 if (avail_shortage > 0) {
2238 for (q = 0; q < PQ_L2_SIZE; ++q) {
2239 delta += vm_pageout_scan_inactive(
2242 PQAVERAGE(avail_shortage),
2248 if (avail_shortage - delta <= 0)
2251 avail_shortage -= delta;
2256 * Figure out how many active pages we must deactivate. If
2257 * we were able to reach our target with just the inactive
2258 * scan above we limit the number of active pages we
2259 * deactivate to reduce unnecessary work.
2263 vm_pagedaemon_time = ticks;
2264 inactive_shortage = vmstats.v_inactive_target -
2265 vmstats.v_inactive_count;
2268 * If we were unable to free sufficient inactive pages to
2269 * satisfy the free/cache queue requirements then simply
2270 * reaching the inactive target may not be good enough.
2271 * Try to deactivate pages in excess of the target based
2274 * However to prevent thrashing the VM system do not
2275 * deactivate more than an additional 1/10 the inactive
2276 * target's worth of active pages.
2278 if (avail_shortage > 0) {
2279 tmp = avail_shortage * 2;
2280 if (tmp > vmstats.v_inactive_target / 10)
2281 tmp = vmstats.v_inactive_target / 10;
2282 inactive_shortage += tmp;
2286 * Only trigger a pmap cleanup on inactive shortage.
2288 if (isep == 0 && inactive_shortage > 0) {
2293 * Scan for ACTIVE->INACTIVE
2295 * Only trigger on inactive shortage. Triggering on
2296 * avail_shortage can starve the active queue with
2297 * unnecessary active->inactive transitions and destroy
2300 * If this is the emergency pager, always try to move
2301 * a few pages from active to inactive because the inactive
2302 * queue might have enough pages, but not enough anonymous
2305 if (isep && inactive_shortage < vm_emerg_launder)
2306 inactive_shortage = vm_emerg_launder;
2308 if (/*avail_shortage > 0 ||*/ inactive_shortage > 0) {
2313 for (q = 0; q < PQ_L2_SIZE; ++q) {
2314 delta += vm_pageout_scan_active(
2317 PQAVERAGE(avail_shortage),
2318 PQAVERAGE(inactive_shortage),
2324 if (inactive_shortage - delta <= 0 &&
2325 avail_shortage - delta <= 0) {
2329 inactive_shortage -= delta;
2330 avail_shortage -= delta;
2335 * Scan for CACHE->FREE
2337 * Finally free enough cache pages to meet our free page
2338 * requirement and take more drastic measures if we are
2343 vm_pagedaemon_time = ticks;
2344 vm_pageout_scan_cache(avail_shortage, pass,
2345 vnodes_skipped, recycle_count);
2348 * Wait for more work.
2350 if (avail_shortage > 0) {
2352 if (pass < 10 && vm_pages_needed > 1) {
2354 * Normal operation, additional processes
2355 * have already kicked us. Retry immediately
2356 * unless swap space is completely full in
2357 * which case delay a bit.
2359 if (swap_pager_full) {
2360 tsleep(&vm_pages_needed, 0, "pdelay",
2362 } /* else immediate retry */
2363 } else if (pass < 10) {
2365 * Normal operation, fewer processes. Delay
2366 * a bit but allow wakeups. vm_pages_needed
2367 * is only adjusted against the primary
2371 vm_pages_needed = 0;
2372 tsleep(&vm_pages_needed, 0, "pdelay", hz / 10);
2374 vm_pages_needed = 1;
2375 } else if (swap_pager_full == 0) {
2377 * We've taken too many passes, forced delay.
2379 tsleep(&vm_pages_needed, 0, "pdelay", hz / 10);
2382 * Running out of memory, catastrophic
2383 * back-off to one-second intervals.
2385 tsleep(&vm_pages_needed, 0, "pdelay", hz);
2387 } else if (vm_pages_needed) {
2389 * Interlocked wakeup of waiters (non-optional).
2391 * Similar to vm_page_free_wakeup() in vm_page.c,
2395 if (!vm_page_count_min(vm_page_free_hysteresis) ||
2396 !vm_page_count_target()) {
2397 vm_pages_needed = 0;
2398 wakeup(&vmstats.v_free_count);
2406 static struct kproc_desc pg1_kp = {
2411 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, kproc_start, &pg1_kp);
2413 static struct kproc_desc pg2_kp = {
2418 SYSINIT(emergpager, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY, kproc_start, &pg2_kp);
2422 * Called after allocating a page out of the cache or free queue
2423 * to possibly wake the pagedaemon up to replentish our supply.
2425 * We try to generate some hysteresis by waking the pagedaemon up
2426 * when our free+cache pages go below the free_min+cache_min level.
2427 * The pagedaemon tries to get the count back up to at least the
2428 * minimum, and through to the target level if possible.
2430 * If the pagedaemon is already active bump vm_pages_needed as a hint
2431 * that there are even more requests pending.
2437 pagedaemon_wakeup(void)
2439 if (vm_paging_needed() && curthread != pagethread) {
2440 if (vm_pages_needed == 0) {
2441 vm_pages_needed = 1; /* SMP race ok */
2442 wakeup(&vm_pages_needed);
2443 } else if (vm_page_count_min(0)) {
2444 ++vm_pages_needed; /* SMP race ok */
2449 #if !defined(NO_SWAPPING)
2456 vm_req_vmdaemon(void)
2458 static int lastrun = 0;
2460 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
2461 wakeup(&vm_daemon_needed);
2466 static int vm_daemon_callback(struct proc *p, void *data __unused);
2477 tsleep(&vm_daemon_needed, 0, "psleep", 0);
2478 req_swapout = atomic_swap_int(&vm_pageout_req_swapout, 0);
2484 swapout_procs(vm_pageout_req_swapout);
2487 * scan the processes for exceeding their rlimits or if
2488 * process is swapped out -- deactivate pages
2490 allproc_scan(vm_daemon_callback, NULL, 0);
2495 vm_daemon_callback(struct proc *p, void *data __unused)
2498 vm_pindex_t limit, size;
2501 * if this is a system process or if we have already
2502 * looked at this process, skip it.
2504 lwkt_gettoken(&p->p_token);
2506 if (p->p_flags & (P_SYSTEM | P_WEXIT)) {
2507 lwkt_reltoken(&p->p_token);
2512 * if the process is in a non-running type state,
2515 if (p->p_stat != SACTIVE && p->p_stat != SSTOP && p->p_stat != SCORE) {
2516 lwkt_reltoken(&p->p_token);
2523 limit = OFF_TO_IDX(qmin(p->p_rlimit[RLIMIT_RSS].rlim_cur,
2524 p->p_rlimit[RLIMIT_RSS].rlim_max));
2527 * let processes that are swapped out really be
2528 * swapped out. Set the limit to nothing to get as
2529 * many pages out to swap as possible.
2531 if (p->p_flags & P_SWAPPEDOUT)
2536 size = pmap_resident_tlnw_count(&vm->vm_pmap);
2537 if (limit >= 0 && size > 4096 &&
2538 size - 4096 >= limit && vm_pageout_memuse_mode >= 1) {
2539 vm_pageout_map_deactivate_pages(&vm->vm_map, limit);
2543 lwkt_reltoken(&p->p_token);