kernel - Adjust emergency pager
[dragonfly.git] / sys / vm / vm_pageout.c
blob67b85750174a6ec94d0e9198b98b5f3c9c3e323e
1 /*
2 * Copyright (c) 1991 Regents of the University of California.
3 * All rights reserved.
4 * Copyright (c) 1994 John S. Dyson
5 * All rights reserved.
6 * Copyright (c) 1994 David Greenman
7 * All rights reserved.
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
14 * are met:
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
34 * SUCH DAMAGE.
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.
71 #include "opt_vm.h"
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/kernel.h>
75 #include <sys/proc.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>
81 #include <sys/sysctl.h>
83 #include <vm/vm.h>
84 #include <vm/vm_param.h>
85 #include <sys/lock.h>
86 #include <vm/vm_object.h>
87 #include <vm/vm_page.h>
88 #include <vm/vm_map.h>
89 #include <vm/vm_pageout.h>
90 #include <vm/vm_pager.h>
91 #include <vm/swap_pager.h>
92 #include <vm/vm_extern.h>
94 #include <sys/thread2.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, int *max_launderp,
104 int *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 static 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 = {
119 "vmdaemon",
120 vm_daemon,
121 &vmthread
123 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
124 #endif
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;
135 #endif
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;
149 #else
150 static int vm_swap_enabled=1;
151 static int vm_swap_idle_enabled=0;
152 #endif
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, "");
189 #else
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");
194 #endif
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);
210 #endif
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.
230 static __inline int
231 PQAVERAGE(int n)
233 int avg;
235 if (n >= 0) {
236 avg = ((n + (PQ_L2_SIZE - 1)) / (PQ_L2_SIZE / 2) + 1);
237 } else {
238 avg = ((n - (PQ_L2_SIZE - 1)) / (PQ_L2_SIZE / 2) - 1);
240 return avg;
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.
249 static int
250 vm_pageout_clean_helper(vm_page_t m, int vmflush_flags)
252 vm_object_t object;
253 vm_page_t mc[BLIST_MAX_ALLOC];
254 int error;
255 int ib, is, page_base;
256 vm_pindex_t pindex = m->pindex;
258 object = m->object;
261 * Don't mess with the page if it's held or special.
263 * XXX do we really need to check hold_count here? hold_count
264 * isn't supposed to mess with vm_page ops except prevent the
265 * page from being reused.
267 if (m->hold_count != 0 || (m->flags & PG_UNMANAGED)) {
268 vm_page_wakeup(m);
269 return 0;
273 * Place page in cluster. Align cluster for optimal swap space
274 * allocation (whether it is swap or not). This is typically ~16-32
275 * pages, which also tends to align the cluster to multiples of the
276 * filesystem block size if backed by a filesystem.
278 page_base = pindex % BLIST_MAX_ALLOC;
279 mc[page_base] = m;
280 ib = page_base - 1;
281 is = page_base + 1;
284 * Scan object for clusterable pages.
286 * We can cluster ONLY if: ->> the page is NOT
287 * clean, wired, busy, held, or mapped into a
288 * buffer, and one of the following:
289 * 1) The page is inactive, or a seldom used
290 * active page.
291 * -or-
292 * 2) we force the issue.
294 * During heavy mmap/modification loads the pageout
295 * daemon can really fragment the underlying file
296 * due to flushing pages out of order and not trying
297 * align the clusters (which leave sporatic out-of-order
298 * holes). To solve this problem we do the reverse scan
299 * first and attempt to align our cluster, then do a
300 * forward scan if room remains.
302 vm_object_hold(object);
304 while (ib >= 0) {
305 vm_page_t p;
307 p = vm_page_lookup_busy_try(object, pindex - page_base + ib,
308 TRUE, &error);
309 if (error || p == NULL)
310 break;
311 if ((p->queue - p->pc) == PQ_CACHE ||
312 (p->flags & PG_UNMANAGED)) {
313 vm_page_wakeup(p);
314 break;
316 vm_page_test_dirty(p);
317 if (((p->dirty & p->valid) == 0 &&
318 (p->flags & PG_NEED_COMMIT) == 0) ||
319 p->wire_count != 0 || /* may be held by buf cache */
320 p->hold_count != 0) { /* may be undergoing I/O */
321 vm_page_wakeup(p);
322 break;
324 if (p->queue - p->pc != PQ_INACTIVE) {
325 if (p->queue - p->pc != PQ_ACTIVE ||
326 (vmflush_flags & VM_PAGER_ALLOW_ACTIVE) == 0) {
327 vm_page_wakeup(p);
328 break;
333 * Try to maintain page groupings in the cluster.
335 if (m->flags & PG_WINATCFLS)
336 vm_page_flag_set(p, PG_WINATCFLS);
337 else
338 vm_page_flag_clear(p, PG_WINATCFLS);
339 p->act_count = m->act_count;
341 mc[ib] = p;
342 --ib;
344 ++ib; /* fixup */
346 while (is < BLIST_MAX_ALLOC &&
347 pindex - page_base + is < object->size) {
348 vm_page_t p;
350 p = vm_page_lookup_busy_try(object, pindex - page_base + is,
351 TRUE, &error);
352 if (error || p == NULL)
353 break;
354 if (((p->queue - p->pc) == PQ_CACHE) ||
355 (p->flags & PG_UNMANAGED)) {
356 vm_page_wakeup(p);
357 break;
359 vm_page_test_dirty(p);
360 if (((p->dirty & p->valid) == 0 &&
361 (p->flags & PG_NEED_COMMIT) == 0) ||
362 p->wire_count != 0 || /* may be held by buf cache */
363 p->hold_count != 0) { /* may be undergoing I/O */
364 vm_page_wakeup(p);
365 break;
367 if (p->queue - p->pc != PQ_INACTIVE) {
368 if (p->queue - p->pc != PQ_ACTIVE ||
369 (vmflush_flags & VM_PAGER_ALLOW_ACTIVE) == 0) {
370 vm_page_wakeup(p);
371 break;
376 * Try to maintain page groupings in the cluster.
378 if (m->flags & PG_WINATCFLS)
379 vm_page_flag_set(p, PG_WINATCFLS);
380 else
381 vm_page_flag_clear(p, PG_WINATCFLS);
382 p->act_count = m->act_count;
384 mc[is] = p;
385 ++is;
388 vm_object_drop(object);
391 * we allow reads during pageouts...
393 return vm_pageout_flush(&mc[ib], is - ib, vmflush_flags);
397 * vm_pageout_flush() - launder the given pages
399 * The given pages are laundered. Note that we setup for the start of
400 * I/O ( i.e. busy the page ), mark it read-only, and bump the object
401 * reference count all in here rather then in the parent. If we want
402 * the parent to do more sophisticated things we may have to change
403 * the ordering.
405 * The pages in the array must be busied by the caller and will be
406 * unbusied by this function.
409 vm_pageout_flush(vm_page_t *mc, int count, int vmflush_flags)
411 vm_object_t object;
412 int pageout_status[count];
413 int numpagedout = 0;
414 int i;
417 * Initiate I/O. Bump the vm_page_t->busy counter.
419 for (i = 0; i < count; i++) {
420 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
421 ("vm_pageout_flush page %p index %d/%d: partially "
422 "invalid page", mc[i], i, count));
423 vm_page_io_start(mc[i]);
427 * We must make the pages read-only. This will also force the
428 * modified bit in the related pmaps to be cleared. The pager
429 * cannot clear the bit for us since the I/O completion code
430 * typically runs from an interrupt. The act of making the page
431 * read-only handles the case for us.
433 * Then we can unbusy the pages, we still hold a reference by virtue
434 * of our soft-busy.
436 for (i = 0; i < count; i++) {
437 if (vmflush_flags & VM_PAGER_TRY_TO_CACHE)
438 vm_page_protect(mc[i], VM_PROT_NONE);
439 else
440 vm_page_protect(mc[i], VM_PROT_READ);
441 vm_page_wakeup(mc[i]);
444 object = mc[0]->object;
445 vm_object_pip_add(object, count);
447 vm_pager_put_pages(object, mc, count,
448 (vmflush_flags |
449 ((object == &kernel_object) ?
450 VM_PAGER_PUT_SYNC : 0)),
451 pageout_status);
453 for (i = 0; i < count; i++) {
454 vm_page_t mt = mc[i];
456 switch (pageout_status[i]) {
457 case VM_PAGER_OK:
458 numpagedout++;
459 break;
460 case VM_PAGER_PEND:
461 numpagedout++;
462 break;
463 case VM_PAGER_BAD:
465 * Page outside of range of object. Right now we
466 * essentially lose the changes by pretending it
467 * worked.
469 vm_page_busy_wait(mt, FALSE, "pgbad");
470 pmap_clear_modify(mt);
471 vm_page_undirty(mt);
472 vm_page_wakeup(mt);
473 break;
474 case VM_PAGER_ERROR:
475 case VM_PAGER_FAIL:
477 * A page typically cannot be paged out when we
478 * have run out of swap. We leave the page
479 * marked inactive and will try to page it out
480 * again later.
482 * Starvation of the active page list is used to
483 * determine when the system is massively memory
484 * starved.
486 break;
487 case VM_PAGER_AGAIN:
488 break;
492 * If not PENDing this was a synchronous operation and we
493 * clean up after the I/O. If it is PENDing the mess is
494 * cleaned up asynchronously.
496 * Also nominally act on the caller's wishes if the caller
497 * wants to try to really clean (cache or free) the page.
499 * Also nominally deactivate the page if the system is
500 * memory-stressed.
502 if (pageout_status[i] != VM_PAGER_PEND) {
503 vm_page_busy_wait(mt, FALSE, "pgouw");
504 vm_page_io_finish(mt);
505 if (vmflush_flags & VM_PAGER_TRY_TO_CACHE) {
506 vm_page_try_to_cache(mt);
507 } else if (vm_page_count_severe()) {
508 vm_page_deactivate(mt);
509 vm_page_wakeup(mt);
510 } else {
511 vm_page_wakeup(mt);
513 vm_object_pip_wakeup(object);
516 return numpagedout;
519 #if !defined(NO_SWAPPING)
522 * Callback function, page busied for us. We must dispose of the busy
523 * condition. Any related pmap pages may be held but will not be locked.
525 static
527 vm_pageout_mdp_callback(struct pmap_pgscan_info *info, vm_offset_t va,
528 vm_page_t p)
530 int actcount;
531 int cleanit = 0;
534 * Basic tests - There should never be a marker, and we can stop
535 * once the RSS is below the required level.
537 KKASSERT((p->flags & PG_MARKER) == 0);
538 if (pmap_resident_tlnw_count(info->pmap) <= info->limit) {
539 vm_page_wakeup(p);
540 return(-1);
543 mycpu->gd_cnt.v_pdpages++;
545 if (p->wire_count || p->hold_count || (p->flags & PG_UNMANAGED)) {
546 vm_page_wakeup(p);
547 goto done;
550 ++info->actioncount;
553 * Check if the page has been referened recently. If it has,
554 * activate it and skip.
556 actcount = pmap_ts_referenced(p);
557 if (actcount) {
558 vm_page_flag_set(p, PG_REFERENCED);
559 } else if (p->flags & PG_REFERENCED) {
560 actcount = 1;
563 if (actcount) {
564 if (p->queue - p->pc != PQ_ACTIVE) {
565 vm_page_and_queue_spin_lock(p);
566 if (p->queue - p->pc != PQ_ACTIVE) {
567 vm_page_and_queue_spin_unlock(p);
568 vm_page_activate(p);
569 } else {
570 vm_page_and_queue_spin_unlock(p);
572 } else {
573 p->act_count += actcount;
574 if (p->act_count > ACT_MAX)
575 p->act_count = ACT_MAX;
577 vm_page_flag_clear(p, PG_REFERENCED);
578 vm_page_wakeup(p);
579 goto done;
583 * Remove the page from this particular pmap. Once we do this, our
584 * pmap scans will not see it again (unless it gets faulted in), so
585 * we must actively dispose of or deal with the page.
587 pmap_remove_specific(info->pmap, p);
590 * If the page is not mapped to another process (i.e. as would be
591 * typical if this were a shared page from a library) then deactivate
592 * the page and clean it in two passes only.
594 * If the page hasn't been referenced since the last check, remove it
595 * from the pmap. If it is no longer mapped, deactivate it
596 * immediately, accelerating the normal decline.
598 * Once the page has been removed from the pmap the RSS code no
599 * longer tracks it so we have to make sure that it is staged for
600 * potential flush action.
602 if ((p->flags & PG_MAPPED) == 0) {
603 if (p->queue - p->pc == PQ_ACTIVE) {
604 vm_page_deactivate(p);
606 if (p->queue - p->pc == PQ_INACTIVE) {
607 cleanit = 1;
612 * Ok, try to fully clean the page and any nearby pages such that at
613 * least the requested page is freed or moved to the cache queue.
615 * We usually do this synchronously to allow us to get the page into
616 * the CACHE queue quickly, which will prevent memory exhaustion if
617 * a process with a memoryuse limit is running away. However, the
618 * sysadmin may desire to set vm.swap_user_async which relaxes this
619 * and improves write performance.
621 if (cleanit) {
622 int max_launder = 0x7FFF;
623 int vnodes_skipped = 0;
624 int vmflush_flags;
625 struct vnode *vpfailed = NULL;
627 info->offset = va;
629 if (vm_pageout_memuse_mode >= 2) {
630 vmflush_flags = VM_PAGER_TRY_TO_CACHE |
631 VM_PAGER_ALLOW_ACTIVE;
632 if (swap_user_async == 0)
633 vmflush_flags |= VM_PAGER_PUT_SYNC;
634 vm_page_flag_set(p, PG_WINATCFLS);
635 info->cleancount +=
636 vm_pageout_page(p, &max_launder,
637 &vnodes_skipped,
638 &vpfailed, 1, vmflush_flags);
639 } else {
640 vm_page_wakeup(p);
641 ++info->cleancount;
643 } else {
644 vm_page_wakeup(p);
648 * Must be at end to avoid SMP races.
650 done:
651 lwkt_user_yield();
652 return 0;
656 * Deactivate some number of pages in a map due to set RLIMIT_RSS limits.
657 * that is relatively difficult to do. We try to keep track of where we
658 * left off last time to reduce scan overhead.
660 * Called when vm_pageout_memuse_mode is >= 1.
662 void
663 vm_pageout_map_deactivate_pages(vm_map_t map, vm_pindex_t limit)
665 vm_offset_t pgout_offset;
666 struct pmap_pgscan_info info;
667 int retries = 3;
669 pgout_offset = map->pgout_offset;
670 again:
671 #if 0
672 kprintf("%016jx ", pgout_offset);
673 #endif
674 if (pgout_offset < VM_MIN_USER_ADDRESS)
675 pgout_offset = VM_MIN_USER_ADDRESS;
676 if (pgout_offset >= VM_MAX_USER_ADDRESS)
677 pgout_offset = 0;
678 info.pmap = vm_map_pmap(map);
679 info.limit = limit;
680 info.beg_addr = pgout_offset;
681 info.end_addr = VM_MAX_USER_ADDRESS;
682 info.callback = vm_pageout_mdp_callback;
683 info.cleancount = 0;
684 info.actioncount = 0;
685 info.busycount = 0;
687 pmap_pgscan(&info);
688 pgout_offset = info.offset;
689 #if 0
690 kprintf("%016jx %08lx %08lx\n", pgout_offset,
691 info.cleancount, info.actioncount);
692 #endif
694 if (pgout_offset != VM_MAX_USER_ADDRESS &&
695 pmap_resident_tlnw_count(vm_map_pmap(map)) > limit) {
696 goto again;
697 } else if (retries &&
698 pmap_resident_tlnw_count(vm_map_pmap(map)) > limit) {
699 --retries;
700 goto again;
702 map->pgout_offset = pgout_offset;
704 #endif
707 * Called when the pageout scan wants to free a page. We no longer
708 * try to cycle the vm_object here with a reference & dealloc, which can
709 * cause a non-trivial object collapse in a critical path.
711 * It is unclear why we cycled the ref_count in the past, perhaps to try
712 * to optimize shadow chain collapses but I don't quite see why it would
713 * be necessary. An OBJ_DEAD object should terminate any and all vm_pages
714 * synchronously and not have to be kicked-start.
716 static void
717 vm_pageout_page_free(vm_page_t m)
719 vm_page_protect(m, VM_PROT_NONE);
720 vm_page_free(m);
724 * vm_pageout_scan does the dirty work for the pageout daemon.
726 struct vm_pageout_scan_info {
727 struct proc *bigproc;
728 vm_offset_t bigsize;
731 static int vm_pageout_scan_callback(struct proc *p, void *data);
734 * Scan inactive queue
736 * WARNING! Can be called from two pagedaemon threads simultaneously.
738 static int
739 vm_pageout_scan_inactive(int pass, int q, int avail_shortage,
740 int *vnodes_skipped)
742 vm_page_t m;
743 struct vm_page marker;
744 struct vnode *vpfailed; /* warning, allowed to be stale */
745 int maxscan;
746 int delta = 0;
747 int max_launder;
748 int isep;
750 isep = (curthread == emergpager);
753 * Start scanning the inactive queue for pages we can move to the
754 * cache or free. The scan will stop when the target is reached or
755 * we have scanned the entire inactive queue. Note that m->act_count
756 * is not used to form decisions for the inactive queue, only for the
757 * active queue.
759 * max_launder limits the number of dirty pages we flush per scan.
760 * For most systems a smaller value (16 or 32) is more robust under
761 * extreme memory and disk pressure because any unnecessary writes
762 * to disk can result in extreme performance degredation. However,
763 * systems with excessive dirty pages (especially when MAP_NOSYNC is
764 * used) will die horribly with limited laundering. If the pageout
765 * daemon cannot clean enough pages in the first pass, we let it go
766 * all out in succeeding passes.
768 * NOTE! THE EMERGENCY PAGER (isep) DOES NOT LAUNDER VNODE-BACKED
769 * PAGES.
771 if ((max_launder = vm_max_launder) <= 1)
772 max_launder = 1;
773 if (pass)
774 max_launder = 10000;
777 * Initialize our marker
779 bzero(&marker, sizeof(marker));
780 marker.flags = PG_BUSY | PG_FICTITIOUS | PG_MARKER;
781 marker.queue = PQ_INACTIVE + q;
782 marker.pc = q;
783 marker.wire_count = 1;
786 * Inactive queue scan.
788 * NOTE: The vm_page must be spinlocked before the queue to avoid
789 * deadlocks, so it is easiest to simply iterate the loop
790 * with the queue unlocked at the top.
792 vpfailed = NULL;
794 vm_page_queues_spin_lock(PQ_INACTIVE + q);
795 TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE + q].pl, &marker, pageq);
796 maxscan = vm_page_queues[PQ_INACTIVE + q].lcnt;
799 * Queue locked at top of loop to avoid stack marker issues.
801 while ((m = TAILQ_NEXT(&marker, pageq)) != NULL &&
802 maxscan-- > 0 && avail_shortage - delta > 0)
804 int count;
806 KKASSERT(m->queue == PQ_INACTIVE + q);
807 TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE + q].pl,
808 &marker, pageq);
809 TAILQ_INSERT_AFTER(&vm_page_queues[PQ_INACTIVE + q].pl, m,
810 &marker, pageq);
811 mycpu->gd_cnt.v_pdpages++;
814 * Skip marker pages (atomic against other markers to avoid
815 * infinite hop-over scans).
817 if (m->flags & PG_MARKER)
818 continue;
821 * Try to busy the page. Don't mess with pages which are
822 * already busy or reorder them in the queue.
824 if (vm_page_busy_try(m, TRUE))
825 continue;
828 * Remaining operations run with the page busy and neither
829 * the page or the queue will be spin-locked.
831 vm_page_queues_spin_unlock(PQ_INACTIVE + q);
832 KKASSERT(m->queue == PQ_INACTIVE + q);
835 * The emergency pager runs when the primary pager gets
836 * stuck, which typically means the primary pager deadlocked
837 * on a vnode-backed page. Therefore, the emergency pager
838 * must skip vnode-backed pages.
840 if (isep) {
841 if (m->object && m->object->type == OBJT_VNODE) {
842 vm_page_wakeup(m);
843 vm_page_queues_spin_lock(PQ_INACTIVE + q);
844 lwkt_yield();
845 continue;
850 * Try to pageout the page and perhaps other nearby pages.
852 count = vm_pageout_page(m, &max_launder, vnodes_skipped,
853 &vpfailed, pass, 0);
854 delta += count;
857 * Systems with a ton of memory can wind up with huge
858 * deactivation counts. Because the inactive scan is
859 * doing a lot of flushing, the combination can result
860 * in excessive paging even in situations where other
861 * unrelated threads free up sufficient VM.
863 * To deal with this we abort the nominal active->inactive
864 * scan before we hit the inactive target when free+cache
865 * levels have reached a reasonable target.
867 * When deciding to stop early we need to add some slop to
868 * the test and we need to return full completion to the caller
869 * to prevent the caller from thinking there is something
870 * wrong and issuing a low-memory+swap warning or pkill.
872 * A deficit forces paging regardless of the state of the
873 * VM page queues (used for RSS enforcement).
875 lwkt_yield();
876 vm_page_queues_spin_lock(PQ_INACTIVE + q);
877 if (vm_paging_target() < -vm_max_launder) {
879 * Stopping early, return full completion to caller.
881 if (delta < avail_shortage)
882 delta = avail_shortage;
883 break;
887 /* page queue still spin-locked */
888 TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE + q].pl, &marker, pageq);
889 vm_page_queues_spin_unlock(PQ_INACTIVE + q);
891 return (delta);
895 * Pageout the specified page, return the total number of pages paged out
896 * (this routine may cluster).
898 * The page must be busied and soft-busied by the caller and will be disposed
899 * of by this function.
901 static int
902 vm_pageout_page(vm_page_t m, int *max_launderp, int *vnodes_skippedp,
903 struct vnode **vpfailedp, int pass, int vmflush_flags)
905 vm_object_t object;
906 int actcount;
907 int count = 0;
910 * It is possible for a page to be busied ad-hoc (e.g. the
911 * pmap_collect() code) and wired and race against the
912 * allocation of a new page. vm_page_alloc() may be forced
913 * to deactivate the wired page in which case it winds up
914 * on the inactive queue and must be handled here. We
915 * correct the problem simply by unqueuing the page.
917 if (m->wire_count) {
918 vm_page_unqueue_nowakeup(m);
919 vm_page_wakeup(m);
920 kprintf("WARNING: pagedaemon: wired page on "
921 "inactive queue %p\n", m);
922 return 0;
926 * A held page may be undergoing I/O, so skip it.
928 if (m->hold_count) {
929 vm_page_and_queue_spin_lock(m);
930 if (m->queue - m->pc == PQ_INACTIVE) {
931 TAILQ_REMOVE(
932 &vm_page_queues[m->queue].pl, m, pageq);
933 TAILQ_INSERT_TAIL(
934 &vm_page_queues[m->queue].pl, m, pageq);
935 ++vm_swapcache_inactive_heuristic;
937 vm_page_and_queue_spin_unlock(m);
938 vm_page_wakeup(m);
939 return 0;
942 if (m->object == NULL || m->object->ref_count == 0) {
944 * If the object is not being used, we ignore previous
945 * references.
947 vm_page_flag_clear(m, PG_REFERENCED);
948 pmap_clear_reference(m);
949 /* fall through to end */
950 } else if (((m->flags & PG_REFERENCED) == 0) &&
951 (actcount = pmap_ts_referenced(m))) {
953 * Otherwise, if the page has been referenced while
954 * in the inactive queue, we bump the "activation
955 * count" upwards, making it less likely that the
956 * page will be added back to the inactive queue
957 * prematurely again. Here we check the page tables
958 * (or emulated bits, if any), given the upper level
959 * VM system not knowing anything about existing
960 * references.
962 vm_page_activate(m);
963 m->act_count += (actcount + ACT_ADVANCE);
964 vm_page_wakeup(m);
965 return 0;
969 * (m) is still busied.
971 * If the upper level VM system knows about any page
972 * references, we activate the page. We also set the
973 * "activation count" higher than normal so that we will less
974 * likely place pages back onto the inactive queue again.
976 if ((m->flags & PG_REFERENCED) != 0) {
977 vm_page_flag_clear(m, PG_REFERENCED);
978 actcount = pmap_ts_referenced(m);
979 vm_page_activate(m);
980 m->act_count += (actcount + ACT_ADVANCE + 1);
981 vm_page_wakeup(m);
982 return 0;
986 * If the upper level VM system doesn't know anything about
987 * the page being dirty, we have to check for it again. As
988 * far as the VM code knows, any partially dirty pages are
989 * fully dirty.
991 * Pages marked PG_WRITEABLE may be mapped into the user
992 * address space of a process running on another cpu. A
993 * user process (without holding the MP lock) running on
994 * another cpu may be able to touch the page while we are
995 * trying to remove it. vm_page_cache() will handle this
996 * case for us.
998 if (m->dirty == 0) {
999 vm_page_test_dirty(m);
1000 } else {
1001 vm_page_dirty(m);
1004 if (m->valid == 0 && (m->flags & PG_NEED_COMMIT) == 0) {
1006 * Invalid pages can be easily freed
1008 vm_pageout_page_free(m);
1009 mycpu->gd_cnt.v_dfree++;
1010 ++count;
1011 } else if (m->dirty == 0 && (m->flags & PG_NEED_COMMIT) == 0) {
1013 * Clean pages can be placed onto the cache queue.
1014 * This effectively frees them.
1016 vm_page_cache(m);
1017 ++count;
1018 } else if ((m->flags & PG_WINATCFLS) == 0 && pass == 0) {
1020 * Dirty pages need to be paged out, but flushing
1021 * a page is extremely expensive verses freeing
1022 * a clean page. Rather then artificially limiting
1023 * the number of pages we can flush, we instead give
1024 * dirty pages extra priority on the inactive queue
1025 * by forcing them to be cycled through the queue
1026 * twice before being flushed, after which the
1027 * (now clean) page will cycle through once more
1028 * before being freed. This significantly extends
1029 * the thrash point for a heavily loaded machine.
1031 vm_page_flag_set(m, PG_WINATCFLS);
1032 vm_page_and_queue_spin_lock(m);
1033 if (m->queue - m->pc == PQ_INACTIVE) {
1034 TAILQ_REMOVE(
1035 &vm_page_queues[m->queue].pl, m, pageq);
1036 TAILQ_INSERT_TAIL(
1037 &vm_page_queues[m->queue].pl, m, pageq);
1038 ++vm_swapcache_inactive_heuristic;
1040 vm_page_and_queue_spin_unlock(m);
1041 vm_page_wakeup(m);
1042 } else if (*max_launderp > 0) {
1044 * We always want to try to flush some dirty pages if
1045 * we encounter them, to keep the system stable.
1046 * Normally this number is small, but under extreme
1047 * pressure where there are insufficient clean pages
1048 * on the inactive queue, we may have to go all out.
1050 int swap_pageouts_ok;
1051 struct vnode *vp = NULL;
1053 swap_pageouts_ok = 0;
1054 object = m->object;
1055 if (object &&
1056 (object->type != OBJT_SWAP) &&
1057 (object->type != OBJT_DEFAULT)) {
1058 swap_pageouts_ok = 1;
1059 } else {
1060 swap_pageouts_ok = !(defer_swap_pageouts ||
1061 disable_swap_pageouts);
1062 swap_pageouts_ok |= (!disable_swap_pageouts &&
1063 defer_swap_pageouts &&
1064 vm_page_count_min(0));
1068 * We don't bother paging objects that are "dead".
1069 * Those objects are in a "rundown" state.
1071 if (!swap_pageouts_ok ||
1072 (object == NULL) ||
1073 (object->flags & OBJ_DEAD)) {
1074 vm_page_and_queue_spin_lock(m);
1075 if (m->queue - m->pc == PQ_INACTIVE) {
1076 TAILQ_REMOVE(
1077 &vm_page_queues[m->queue].pl,
1078 m, pageq);
1079 TAILQ_INSERT_TAIL(
1080 &vm_page_queues[m->queue].pl,
1081 m, pageq);
1082 ++vm_swapcache_inactive_heuristic;
1084 vm_page_and_queue_spin_unlock(m);
1085 vm_page_wakeup(m);
1086 return 0;
1090 * (m) is still busied.
1092 * The object is already known NOT to be dead. It
1093 * is possible for the vget() to block the whole
1094 * pageout daemon, but the new low-memory handling
1095 * code should prevent it.
1097 * The previous code skipped locked vnodes and, worse,
1098 * reordered pages in the queue. This results in
1099 * completely non-deterministic operation because,
1100 * quite often, a vm_fault has initiated an I/O and
1101 * is holding a locked vnode at just the point where
1102 * the pageout daemon is woken up.
1104 * We can't wait forever for the vnode lock, we might
1105 * deadlock due to a vn_read() getting stuck in
1106 * vm_wait while holding this vnode. We skip the
1107 * vnode if we can't get it in a reasonable amount
1108 * of time.
1110 * vpfailed is used to (try to) avoid the case where
1111 * a large number of pages are associated with a
1112 * locked vnode, which could cause the pageout daemon
1113 * to stall for an excessive amount of time.
1115 if (object->type == OBJT_VNODE) {
1116 int flags;
1118 vp = object->handle;
1119 flags = LK_EXCLUSIVE;
1120 if (vp == *vpfailedp)
1121 flags |= LK_NOWAIT;
1122 else
1123 flags |= LK_TIMELOCK;
1124 vm_page_hold(m);
1125 vm_page_wakeup(m);
1128 * We have unbusied (m) temporarily so we can
1129 * acquire the vp lock without deadlocking.
1130 * (m) is held to prevent destruction.
1132 if (vget(vp, flags) != 0) {
1133 *vpfailedp = vp;
1134 ++pageout_lock_miss;
1135 if (object->flags & OBJ_MIGHTBEDIRTY)
1136 ++*vnodes_skippedp;
1137 vm_page_unhold(m);
1138 return 0;
1142 * The page might have been moved to another
1143 * queue during potential blocking in vget()
1144 * above. The page might have been freed and
1145 * reused for another vnode. The object might
1146 * have been reused for another vnode.
1148 if (m->queue - m->pc != PQ_INACTIVE ||
1149 m->object != object ||
1150 object->handle != vp) {
1151 if (object->flags & OBJ_MIGHTBEDIRTY)
1152 ++*vnodes_skippedp;
1153 vput(vp);
1154 vm_page_unhold(m);
1155 return 0;
1159 * The page may have been busied during the
1160 * blocking in vput(); We don't move the
1161 * page back onto the end of the queue so that
1162 * statistics are more correct if we don't.
1164 if (vm_page_busy_try(m, TRUE)) {
1165 vput(vp);
1166 vm_page_unhold(m);
1167 return 0;
1169 vm_page_unhold(m);
1172 * (m) is busied again
1174 * We own the busy bit and remove our hold
1175 * bit. If the page is still held it
1176 * might be undergoing I/O, so skip it.
1178 if (m->hold_count) {
1179 vm_page_and_queue_spin_lock(m);
1180 if (m->queue - m->pc == PQ_INACTIVE) {
1181 TAILQ_REMOVE(&vm_page_queues[m->queue].pl, m, pageq);
1182 TAILQ_INSERT_TAIL(&vm_page_queues[m->queue].pl, m, pageq);
1183 ++vm_swapcache_inactive_heuristic;
1185 vm_page_and_queue_spin_unlock(m);
1186 if (object->flags & OBJ_MIGHTBEDIRTY)
1187 ++*vnodes_skippedp;
1188 vm_page_wakeup(m);
1189 vput(vp);
1190 return 0;
1192 /* (m) is left busied as we fall through */
1196 * page is busy and not held here.
1198 * If a page is dirty, then it is either being washed
1199 * (but not yet cleaned) or it is still in the
1200 * laundry. If it is still in the laundry, then we
1201 * start the cleaning operation.
1203 * decrement inactive_shortage on success to account
1204 * for the (future) cleaned page. Otherwise we
1205 * could wind up laundering or cleaning too many
1206 * pages.
1208 * NOTE: Cleaning the page here does not cause
1209 * force_deficit to be adjusted, because the
1210 * page is not being freed or moved to the
1211 * cache.
1213 count = vm_pageout_clean_helper(m, vmflush_flags);
1214 *max_launderp -= count;
1217 * Clean ate busy, page no longer accessible
1219 if (vp != NULL)
1220 vput(vp);
1221 } else {
1222 vm_page_wakeup(m);
1224 return count;
1228 * Scan active queue
1230 * WARNING! Can be called from two pagedaemon threads simultaneously.
1232 static int
1233 vm_pageout_scan_active(int pass, int q,
1234 int avail_shortage, int inactive_shortage,
1235 int *recycle_countp)
1237 struct vm_page marker;
1238 vm_page_t m;
1239 int actcount;
1240 int delta = 0;
1241 int maxscan;
1242 int isep;
1244 isep = (curthread == emergpager);
1247 * We want to move pages from the active queue to the inactive
1248 * queue to get the inactive queue to the inactive target. If
1249 * we still have a page shortage from above we try to directly free
1250 * clean pages instead of moving them.
1252 * If we do still have a shortage we keep track of the number of
1253 * pages we free or cache (recycle_count) as a measure of thrashing
1254 * between the active and inactive queues.
1256 * If we were able to completely satisfy the free+cache targets
1257 * from the inactive pool we limit the number of pages we move
1258 * from the active pool to the inactive pool to 2x the pages we
1259 * had removed from the inactive pool (with a minimum of 1/5 the
1260 * inactive target). If we were not able to completely satisfy
1261 * the free+cache targets we go for the whole target aggressively.
1263 * NOTE: Both variables can end up negative.
1264 * NOTE: We are still in a critical section.
1266 * NOTE! THE EMERGENCY PAGER (isep) DOES NOT LAUNDER VNODE-BACKED
1267 * PAGES.
1270 bzero(&marker, sizeof(marker));
1271 marker.flags = PG_BUSY | PG_FICTITIOUS | PG_MARKER;
1272 marker.queue = PQ_ACTIVE + q;
1273 marker.pc = q;
1274 marker.wire_count = 1;
1276 vm_page_queues_spin_lock(PQ_ACTIVE + q);
1277 TAILQ_INSERT_HEAD(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1278 maxscan = vm_page_queues[PQ_ACTIVE + q].lcnt;
1281 * Queue locked at top of loop to avoid stack marker issues.
1283 while ((m = TAILQ_NEXT(&marker, pageq)) != NULL &&
1284 maxscan-- > 0 && (avail_shortage - delta > 0 ||
1285 inactive_shortage > 0))
1287 KKASSERT(m->queue == PQ_ACTIVE + q);
1288 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl,
1289 &marker, pageq);
1290 TAILQ_INSERT_AFTER(&vm_page_queues[PQ_ACTIVE + q].pl, m,
1291 &marker, pageq);
1294 * Skip marker pages (atomic against other markers to avoid
1295 * infinite hop-over scans).
1297 if (m->flags & PG_MARKER)
1298 continue;
1301 * Try to busy the page. Don't mess with pages which are
1302 * already busy or reorder them in the queue.
1304 if (vm_page_busy_try(m, TRUE))
1305 continue;
1308 * Remaining operations run with the page busy and neither
1309 * the page or the queue will be spin-locked.
1311 vm_page_queues_spin_unlock(PQ_ACTIVE + q);
1312 KKASSERT(m->queue == PQ_ACTIVE + q);
1315 * Don't deactivate pages that are held, even if we can
1316 * busy them. (XXX why not?)
1318 if (m->hold_count != 0) {
1319 vm_page_and_queue_spin_lock(m);
1320 if (m->queue - m->pc == PQ_ACTIVE) {
1321 TAILQ_REMOVE(
1322 &vm_page_queues[PQ_ACTIVE + q].pl,
1323 m, pageq);
1324 TAILQ_INSERT_TAIL(
1325 &vm_page_queues[PQ_ACTIVE + q].pl,
1326 m, pageq);
1328 vm_page_and_queue_spin_unlock(m);
1329 vm_page_wakeup(m);
1330 goto next;
1334 * The emergency pager ignores vnode-backed pages as these
1335 * are the pages that probably bricked the main pager.
1337 if (isep && m->object && m->object->type == OBJT_VNODE) {
1338 vm_page_and_queue_spin_lock(m);
1339 if (m->queue - m->pc == PQ_ACTIVE) {
1340 TAILQ_REMOVE(
1341 &vm_page_queues[PQ_ACTIVE + q].pl,
1342 m, pageq);
1343 TAILQ_INSERT_TAIL(
1344 &vm_page_queues[PQ_ACTIVE + q].pl,
1345 m, pageq);
1347 vm_page_and_queue_spin_unlock(m);
1348 vm_page_wakeup(m);
1349 goto next;
1353 * The count for pagedaemon pages is done after checking the
1354 * page for eligibility...
1356 mycpu->gd_cnt.v_pdpages++;
1359 * Check to see "how much" the page has been used and clear
1360 * the tracking access bits. If the object has no references
1361 * don't bother paying the expense.
1363 actcount = 0;
1364 if (m->object && m->object->ref_count != 0) {
1365 if (m->flags & PG_REFERENCED)
1366 ++actcount;
1367 actcount += pmap_ts_referenced(m);
1368 if (actcount) {
1369 m->act_count += ACT_ADVANCE + actcount;
1370 if (m->act_count > ACT_MAX)
1371 m->act_count = ACT_MAX;
1374 vm_page_flag_clear(m, PG_REFERENCED);
1377 * actcount is only valid if the object ref_count is non-zero.
1378 * If the page does not have an object, actcount will be zero.
1380 if (actcount && m->object->ref_count != 0) {
1381 vm_page_and_queue_spin_lock(m);
1382 if (m->queue - m->pc == PQ_ACTIVE) {
1383 TAILQ_REMOVE(
1384 &vm_page_queues[PQ_ACTIVE + q].pl,
1385 m, pageq);
1386 TAILQ_INSERT_TAIL(
1387 &vm_page_queues[PQ_ACTIVE + q].pl,
1388 m, pageq);
1390 vm_page_and_queue_spin_unlock(m);
1391 vm_page_wakeup(m);
1392 } else {
1393 switch(m->object->type) {
1394 case OBJT_DEFAULT:
1395 case OBJT_SWAP:
1396 m->act_count -= min(m->act_count,
1397 vm_anonmem_decline);
1398 break;
1399 default:
1400 m->act_count -= min(m->act_count,
1401 vm_filemem_decline);
1402 break;
1404 if (vm_pageout_algorithm ||
1405 (m->object == NULL) ||
1406 (m->object && (m->object->ref_count == 0)) ||
1407 m->act_count < pass + 1
1410 * Deactivate the page. If we had a
1411 * shortage from our inactive scan try to
1412 * free (cache) the page instead.
1414 * Don't just blindly cache the page if
1415 * we do not have a shortage from the
1416 * inactive scan, that could lead to
1417 * gigabytes being moved.
1419 --inactive_shortage;
1420 if (avail_shortage - delta > 0 ||
1421 (m->object && (m->object->ref_count == 0)))
1423 if (avail_shortage - delta > 0)
1424 ++*recycle_countp;
1425 vm_page_protect(m, VM_PROT_NONE);
1426 if (m->dirty == 0 &&
1427 (m->flags & PG_NEED_COMMIT) == 0 &&
1428 avail_shortage - delta > 0) {
1429 vm_page_cache(m);
1430 } else {
1431 vm_page_deactivate(m);
1432 vm_page_wakeup(m);
1434 } else {
1435 vm_page_deactivate(m);
1436 vm_page_wakeup(m);
1438 ++delta;
1439 } else {
1440 vm_page_and_queue_spin_lock(m);
1441 if (m->queue - m->pc == PQ_ACTIVE) {
1442 TAILQ_REMOVE(
1443 &vm_page_queues[PQ_ACTIVE + q].pl,
1444 m, pageq);
1445 TAILQ_INSERT_TAIL(
1446 &vm_page_queues[PQ_ACTIVE + q].pl,
1447 m, pageq);
1449 vm_page_and_queue_spin_unlock(m);
1450 vm_page_wakeup(m);
1453 next:
1454 lwkt_yield();
1455 vm_page_queues_spin_lock(PQ_ACTIVE + q);
1459 * Clean out our local marker.
1461 * Page queue still spin-locked.
1463 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1464 vm_page_queues_spin_unlock(PQ_ACTIVE + q);
1466 return (delta);
1470 * The number of actually free pages can drop down to v_free_reserved,
1471 * we try to build the free count back above v_free_min. Note that
1472 * vm_paging_needed() also returns TRUE if v_free_count is not at
1473 * least v_free_min so that is the minimum we must build the free
1474 * count to.
1476 * We use a slightly higher target to improve hysteresis,
1477 * ((v_free_target + v_free_min) / 2). Since v_free_target
1478 * is usually the same as v_cache_min this maintains about
1479 * half the pages in the free queue as are in the cache queue,
1480 * providing pretty good pipelining for pageout operation.
1482 * The system operator can manipulate vm.v_cache_min and
1483 * vm.v_free_target to tune the pageout demon. Be sure
1484 * to keep vm.v_free_min < vm.v_free_target.
1486 * Note that the original paging target is to get at least
1487 * (free_min + cache_min) into (free + cache). The slightly
1488 * higher target will shift additional pages from cache to free
1489 * without effecting the original paging target in order to
1490 * maintain better hysteresis and not have the free count always
1491 * be dead-on v_free_min.
1493 * NOTE: we are still in a critical section.
1495 * Pages moved from PQ_CACHE to totally free are not counted in the
1496 * pages_freed counter.
1498 * WARNING! Can be called from two pagedaemon threads simultaneously.
1500 static void
1501 vm_pageout_scan_cache(int avail_shortage, int pass,
1502 int vnodes_skipped, int recycle_count)
1504 static int lastkillticks;
1505 struct vm_pageout_scan_info info;
1506 vm_page_t m;
1507 int isep;
1509 isep = (curthread == emergpager);
1511 while (vmstats.v_free_count <
1512 (vmstats.v_free_min + vmstats.v_free_target) / 2) {
1514 * This steals some code from vm/vm_page.c
1516 static int cache_rover = 0;
1518 m = vm_page_list_find(PQ_CACHE, cache_rover & PQ_L2_MASK);
1519 if (m == NULL)
1520 break;
1521 /* page is returned removed from its queue and spinlocked */
1522 if (vm_page_busy_try(m, TRUE)) {
1523 vm_page_deactivate_locked(m);
1524 vm_page_spin_unlock(m);
1525 continue;
1527 vm_page_spin_unlock(m);
1528 pagedaemon_wakeup();
1529 lwkt_yield();
1532 * Remaining operations run with the page busy and neither
1533 * the page or the queue will be spin-locked.
1535 if ((m->flags & (PG_UNMANAGED | PG_NEED_COMMIT)) ||
1536 m->hold_count ||
1537 m->wire_count) {
1538 vm_page_deactivate(m);
1539 vm_page_wakeup(m);
1540 continue;
1542 KKASSERT((m->flags & PG_MAPPED) == 0);
1543 KKASSERT(m->dirty == 0);
1544 cache_rover += PQ_PRIME2;
1545 vm_pageout_page_free(m);
1546 mycpu->gd_cnt.v_dfree++;
1549 #if !defined(NO_SWAPPING)
1551 * Idle process swapout -- run once per second.
1553 if (vm_swap_idle_enabled) {
1554 static time_t lsec;
1555 if (time_uptime != lsec) {
1556 atomic_set_int(&vm_pageout_req_swapout, VM_SWAP_IDLE);
1557 vm_req_vmdaemon();
1558 lsec = time_uptime;
1561 #endif
1564 * If we didn't get enough free pages, and we have skipped a vnode
1565 * in a writeable object, wakeup the sync daemon. And kick swapout
1566 * if we did not get enough free pages.
1568 if (vm_paging_target() > 0) {
1569 if (vnodes_skipped && vm_page_count_min(0))
1570 speedup_syncer(NULL);
1571 #if !defined(NO_SWAPPING)
1572 if (vm_swap_enabled && vm_page_count_target()) {
1573 atomic_set_int(&vm_pageout_req_swapout, VM_SWAP_NORMAL);
1574 vm_req_vmdaemon();
1576 #endif
1580 * Handle catastrophic conditions. Under good conditions we should
1581 * be at the target, well beyond our minimum. If we could not even
1582 * reach our minimum the system is under heavy stress. But just being
1583 * under heavy stress does not trigger process killing.
1585 * We consider ourselves to have run out of memory if the swap pager
1586 * is full and avail_shortage is still positive. The secondary check
1587 * ensures that we do not kill processes if the instantanious
1588 * availability is good, even if the pageout demon pass says it
1589 * couldn't get to the target.
1591 * NOTE! THE EMERGENCY PAGER (isep) DOES NOT HANDLE SWAP FULL
1592 * SITUATIONS.
1594 if (swap_pager_almost_full &&
1595 pass > 0 &&
1596 isep == 0 &&
1597 (vm_page_count_min(recycle_count) || avail_shortage > 0)) {
1598 kprintf("Warning: system low on memory+swap "
1599 "shortage %d for %d ticks!\n",
1600 avail_shortage, ticks - swap_fail_ticks);
1601 if (bootverbose)
1602 kprintf("Metrics: spaf=%d spf=%d pass=%d avail=%d target=%d last=%u\n",
1603 swap_pager_almost_full,
1604 swap_pager_full,
1605 pass,
1606 avail_shortage,
1607 vm_paging_target(),
1608 (unsigned int)(ticks - lastkillticks));
1610 if (swap_pager_full &&
1611 pass > 1 &&
1612 isep == 0 &&
1613 avail_shortage > 0 &&
1614 vm_paging_target() > 0 &&
1615 (unsigned int)(ticks - lastkillticks) >= hz) {
1617 * Kill something, maximum rate once per second to give
1618 * the process time to free up sufficient memory.
1620 lastkillticks = ticks;
1621 info.bigproc = NULL;
1622 info.bigsize = 0;
1623 allproc_scan(vm_pageout_scan_callback, &info, 0);
1624 if (info.bigproc != NULL) {
1625 kprintf("Try to kill process %d %s\n",
1626 info.bigproc->p_pid, info.bigproc->p_comm);
1627 info.bigproc->p_nice = PRIO_MIN;
1628 info.bigproc->p_usched->resetpriority(
1629 FIRST_LWP_IN_PROC(info.bigproc));
1630 atomic_set_int(&info.bigproc->p_flags, P_LOWMEMKILL);
1631 killproc(info.bigproc, "out of swap space");
1632 wakeup(&vmstats.v_free_count);
1633 PRELE(info.bigproc);
1638 static int
1639 vm_pageout_scan_callback(struct proc *p, void *data)
1641 struct vm_pageout_scan_info *info = data;
1642 vm_offset_t size;
1645 * Never kill system processes or init. If we have configured swap
1646 * then try to avoid killing low-numbered pids.
1648 if ((p->p_flags & P_SYSTEM) || (p->p_pid == 1) ||
1649 ((p->p_pid < 48) && (vm_swap_size != 0))) {
1650 return (0);
1653 lwkt_gettoken(&p->p_token);
1656 * if the process is in a non-running type state,
1657 * don't touch it.
1659 if (p->p_stat != SACTIVE && p->p_stat != SSTOP && p->p_stat != SCORE) {
1660 lwkt_reltoken(&p->p_token);
1661 return (0);
1665 * Get the approximate process size. Note that anonymous pages
1666 * with backing swap will be counted twice, but there should not
1667 * be too many such pages due to the stress the VM system is
1668 * under at this point.
1670 size = vmspace_anonymous_count(p->p_vmspace) +
1671 vmspace_swap_count(p->p_vmspace);
1674 * If the this process is bigger than the biggest one
1675 * remember it.
1677 if (info->bigsize < size) {
1678 if (info->bigproc)
1679 PRELE(info->bigproc);
1680 PHOLD(p);
1681 info->bigproc = p;
1682 info->bigsize = size;
1684 lwkt_reltoken(&p->p_token);
1685 lwkt_yield();
1687 return(0);
1691 * This routine tries to maintain the pseudo LRU active queue,
1692 * so that during long periods of time where there is no paging,
1693 * that some statistic accumulation still occurs. This code
1694 * helps the situation where paging just starts to occur.
1696 static void
1697 vm_pageout_page_stats(int q)
1699 static int fullintervalcount = 0;
1700 struct vm_page marker;
1701 vm_page_t m;
1702 int pcount, tpcount; /* Number of pages to check */
1703 int page_shortage;
1705 page_shortage = (vmstats.v_inactive_target + vmstats.v_cache_max +
1706 vmstats.v_free_min) -
1707 (vmstats.v_free_count + vmstats.v_inactive_count +
1708 vmstats.v_cache_count);
1710 if (page_shortage <= 0)
1711 return;
1713 pcount = vm_page_queues[PQ_ACTIVE + q].lcnt;
1714 fullintervalcount += vm_pageout_stats_interval;
1715 if (fullintervalcount < vm_pageout_full_stats_interval) {
1716 tpcount = (vm_pageout_stats_max * pcount) /
1717 vmstats.v_page_count + 1;
1718 if (pcount > tpcount)
1719 pcount = tpcount;
1720 } else {
1721 fullintervalcount = 0;
1724 bzero(&marker, sizeof(marker));
1725 marker.flags = PG_BUSY | PG_FICTITIOUS | PG_MARKER;
1726 marker.queue = PQ_ACTIVE + q;
1727 marker.pc = q;
1728 marker.wire_count = 1;
1730 vm_page_queues_spin_lock(PQ_ACTIVE + q);
1731 TAILQ_INSERT_HEAD(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1734 * Queue locked at top of loop to avoid stack marker issues.
1736 while ((m = TAILQ_NEXT(&marker, pageq)) != NULL &&
1737 pcount-- > 0)
1739 int actcount;
1741 KKASSERT(m->queue == PQ_ACTIVE + q);
1742 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1743 TAILQ_INSERT_AFTER(&vm_page_queues[PQ_ACTIVE + q].pl, m,
1744 &marker, pageq);
1747 * Skip marker pages (atomic against other markers to avoid
1748 * infinite hop-over scans).
1750 if (m->flags & PG_MARKER)
1751 continue;
1754 * Ignore pages we can't busy
1756 if (vm_page_busy_try(m, TRUE))
1757 continue;
1760 * Remaining operations run with the page busy and neither
1761 * the page or the queue will be spin-locked.
1763 vm_page_queues_spin_unlock(PQ_ACTIVE + q);
1764 KKASSERT(m->queue == PQ_ACTIVE + q);
1767 * We now have a safely busied page, the page and queue
1768 * spinlocks have been released.
1770 * Ignore held pages
1772 if (m->hold_count) {
1773 vm_page_wakeup(m);
1774 goto next;
1778 * Calculate activity
1780 actcount = 0;
1781 if (m->flags & PG_REFERENCED) {
1782 vm_page_flag_clear(m, PG_REFERENCED);
1783 actcount += 1;
1785 actcount += pmap_ts_referenced(m);
1788 * Update act_count and move page to end of queue.
1790 if (actcount) {
1791 m->act_count += ACT_ADVANCE + actcount;
1792 if (m->act_count > ACT_MAX)
1793 m->act_count = ACT_MAX;
1794 vm_page_and_queue_spin_lock(m);
1795 if (m->queue - m->pc == PQ_ACTIVE) {
1796 TAILQ_REMOVE(
1797 &vm_page_queues[PQ_ACTIVE + q].pl,
1798 m, pageq);
1799 TAILQ_INSERT_TAIL(
1800 &vm_page_queues[PQ_ACTIVE + q].pl,
1801 m, pageq);
1803 vm_page_and_queue_spin_unlock(m);
1804 vm_page_wakeup(m);
1805 goto next;
1808 if (m->act_count == 0) {
1810 * We turn off page access, so that we have
1811 * more accurate RSS stats. We don't do this
1812 * in the normal page deactivation when the
1813 * system is loaded VM wise, because the
1814 * cost of the large number of page protect
1815 * operations would be higher than the value
1816 * of doing the operation.
1818 * We use the marker to save our place so
1819 * we can release the spin lock. both (m)
1820 * and (next) will be invalid.
1822 vm_page_protect(m, VM_PROT_NONE);
1823 vm_page_deactivate(m);
1824 } else {
1825 m->act_count -= min(m->act_count, ACT_DECLINE);
1826 vm_page_and_queue_spin_lock(m);
1827 if (m->queue - m->pc == PQ_ACTIVE) {
1828 TAILQ_REMOVE(
1829 &vm_page_queues[PQ_ACTIVE + q].pl,
1830 m, pageq);
1831 TAILQ_INSERT_TAIL(
1832 &vm_page_queues[PQ_ACTIVE + q].pl,
1833 m, pageq);
1835 vm_page_and_queue_spin_unlock(m);
1837 vm_page_wakeup(m);
1838 next:
1839 vm_page_queues_spin_lock(PQ_ACTIVE + q);
1843 * Remove our local marker
1845 * Page queue still spin-locked.
1847 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1848 vm_page_queues_spin_unlock(PQ_ACTIVE + q);
1851 static int
1852 vm_pageout_free_page_calc(vm_size_t count)
1854 if (count < vmstats.v_page_count)
1855 return 0;
1857 * free_reserved needs to include enough for the largest swap pager
1858 * structures plus enough for any pv_entry structs when paging.
1860 * v_free_min normal allocations
1861 * v_free_reserved system allocations
1862 * v_pageout_free_min allocations by pageout daemon
1863 * v_interrupt_free_min low level allocations (e.g swap structures)
1865 if (vmstats.v_page_count > 1024)
1866 vmstats.v_free_min = 64 + (vmstats.v_page_count - 1024) / 200;
1867 else
1868 vmstats.v_free_min = 64;
1871 * Make sure the vmmeter slop can't blow out our global minimums.
1873 * However, to accomodate weird configurations (vkernels with many
1874 * cpus and little memory, or artifically reduced hw.physmem), do
1875 * not allow v_free_min to exceed 1/20 of ram or the pageout demon
1876 * will go out of control.
1878 if (vmstats.v_free_min < VMMETER_SLOP_COUNT * ncpus * 10)
1879 vmstats.v_free_min = VMMETER_SLOP_COUNT * ncpus * 10;
1880 if (vmstats.v_free_min > vmstats.v_page_count / 20)
1881 vmstats.v_free_min = vmstats.v_page_count / 20;
1883 vmstats.v_free_reserved = vmstats.v_free_min * 4 / 8 + 7;
1884 vmstats.v_free_severe = vmstats.v_free_min * 4 / 8 + 0;
1885 vmstats.v_pageout_free_min = vmstats.v_free_min * 2 / 8 + 7;
1886 vmstats.v_interrupt_free_min = vmstats.v_free_min * 1 / 8 + 7;
1888 return 1;
1893 * vm_pageout is the high level pageout daemon. TWO kernel threads run
1894 * this daemon, the primary pageout daemon and the emergency pageout daemon.
1896 * The emergency pageout daemon takes over when the primary pageout daemon
1897 * deadlocks. The emergency pageout daemon ONLY pages out to swap, thus
1898 * avoiding the many low-memory deadlocks which can occur when paging out
1899 * to VFS's.
1901 static void
1902 vm_pageout_thread(void)
1904 int pass;
1905 int q;
1906 int q1iterator = 0;
1907 int q2iterator = 0;
1908 int isep;
1909 int emrunning;
1911 curthread->td_flags |= TDF_SYSTHREAD;
1914 * We only need to setup once.
1916 isep = 0;
1917 emrunning = 0;
1918 if (curthread == emergpager) {
1919 isep = 1;
1920 goto skip_setup;
1924 * Initialize some paging parameters.
1926 vm_pageout_free_page_calc(vmstats.v_page_count);
1929 * v_free_target and v_cache_min control pageout hysteresis. Note
1930 * that these are more a measure of the VM cache queue hysteresis
1931 * then the VM free queue. Specifically, v_free_target is the
1932 * high water mark (free+cache pages).
1934 * v_free_reserved + v_cache_min (mostly means v_cache_min) is the
1935 * low water mark, while v_free_min is the stop. v_cache_min must
1936 * be big enough to handle memory needs while the pageout daemon
1937 * is signalled and run to free more pages.
1939 if (vmstats.v_free_count > 6144)
1940 vmstats.v_free_target = 4 * vmstats.v_free_min +
1941 vmstats.v_free_reserved;
1942 else
1943 vmstats.v_free_target = 2 * vmstats.v_free_min +
1944 vmstats.v_free_reserved;
1947 * NOTE: With the new buffer cache b_act_count we want the default
1948 * inactive target to be a percentage of available memory.
1950 * The inactive target essentially determines the minimum
1951 * number of 'temporary' pages capable of caching one-time-use
1952 * files when the VM system is otherwise full of pages
1953 * belonging to multi-time-use files or active program data.
1955 * NOTE: The inactive target is aggressively persued only if the
1956 * inactive queue becomes too small. If the inactive queue
1957 * is large enough to satisfy page movement to free+cache
1958 * then it is repopulated more slowly from the active queue.
1959 * This allows a general inactive_target default to be set.
1961 * There is an issue here for processes which sit mostly idle
1962 * 'overnight', such as sshd, tcsh, and X. Any movement from
1963 * the active queue will eventually cause such pages to
1964 * recycle eventually causing a lot of paging in the morning.
1965 * To reduce the incidence of this pages cycled out of the
1966 * buffer cache are moved directly to the inactive queue if
1967 * they were only used once or twice.
1969 * The vfs.vm_cycle_point sysctl can be used to adjust this.
1970 * Increasing the value (up to 64) increases the number of
1971 * buffer recyclements which go directly to the inactive queue.
1973 if (vmstats.v_free_count > 2048) {
1974 vmstats.v_cache_min = vmstats.v_free_target;
1975 vmstats.v_cache_max = 2 * vmstats.v_cache_min;
1976 } else {
1977 vmstats.v_cache_min = 0;
1978 vmstats.v_cache_max = 0;
1980 vmstats.v_inactive_target = vmstats.v_free_count / 4;
1982 /* XXX does not really belong here */
1983 if (vm_page_max_wired == 0)
1984 vm_page_max_wired = vmstats.v_free_count / 3;
1986 if (vm_pageout_stats_max == 0)
1987 vm_pageout_stats_max = vmstats.v_free_target;
1990 * Set interval in seconds for stats scan.
1992 if (vm_pageout_stats_interval == 0)
1993 vm_pageout_stats_interval = 5;
1994 if (vm_pageout_full_stats_interval == 0)
1995 vm_pageout_full_stats_interval = vm_pageout_stats_interval * 4;
1999 * Set maximum free per pass
2001 if (vm_pageout_stats_free_max == 0)
2002 vm_pageout_stats_free_max = 5;
2004 swap_pager_swap_init();
2005 pass = 0;
2007 atomic_swap_int(&sequence_emerg_pager, 1);
2008 wakeup(&sequence_emerg_pager);
2010 skip_setup:
2012 * Sequence emergency pager startup
2014 if (isep) {
2015 while (sequence_emerg_pager == 0)
2016 tsleep(&sequence_emerg_pager, 0, "pstartup", hz);
2020 * The pageout daemon is never done, so loop forever.
2022 * WARNING! This code is being executed by two kernel threads
2023 * potentially simultaneously.
2025 while (TRUE) {
2026 int error;
2027 int avail_shortage;
2028 int inactive_shortage;
2029 int vnodes_skipped = 0;
2030 int recycle_count = 0;
2031 int tmp;
2034 * Wait for an action request. If we timeout check to
2035 * see if paging is needed (in case the normal wakeup
2036 * code raced us).
2038 if (isep) {
2040 * Emergency pagedaemon monitors the primary
2041 * pagedaemon while vm_pages_needed != 0.
2043 * The emergency pagedaemon only runs if VM paging
2044 * is needed and the primary pagedaemon has not
2045 * updated vm_pagedaemon_time for more than 2 seconds.
2047 if (vm_pages_needed)
2048 tsleep(&vm_pagedaemon_time, 0, "psleep", hz);
2049 else
2050 tsleep(&vm_pagedaemon_time, 0, "psleep", hz*10);
2051 if (vm_pages_needed == 0) {
2052 pass = 0;
2053 continue;
2055 if ((int)(ticks - vm_pagedaemon_time) < hz * 2) {
2056 if (emrunning) {
2057 emrunning = 0;
2058 kprintf("Emergency pager finished\n");
2060 pass = 0;
2061 continue;
2063 if (emrunning == 0) {
2064 emrunning = 1;
2065 kprintf("Emergency pager running\n");
2067 } else {
2069 * Primary pagedaemon
2071 if (vm_pages_needed == 0) {
2072 error = tsleep(&vm_pages_needed,
2073 0, "psleep",
2074 vm_pageout_stats_interval * hz);
2075 if (error &&
2076 vm_paging_needed() == 0 &&
2077 vm_pages_needed == 0) {
2078 for (q = 0; q < PQ_L2_SIZE; ++q)
2079 vm_pageout_page_stats(q);
2080 continue;
2082 vm_pagedaemon_time = ticks;
2083 vm_pages_needed = 1;
2086 * Wake the emergency pagedaemon up so it
2087 * can monitor us. It will automatically
2088 * go back into a long sleep when
2089 * vm_pages_needed returns to 0.
2091 wakeup(&vm_pagedaemon_time);
2095 mycpu->gd_cnt.v_pdwakeups++;
2098 * Scan for INACTIVE->CLEAN/PAGEOUT
2100 * This routine tries to avoid thrashing the system with
2101 * unnecessary activity.
2103 * Calculate our target for the number of free+cache pages we
2104 * want to get to. This is higher then the number that causes
2105 * allocations to stall (severe) in order to provide hysteresis,
2106 * and if we don't make it all the way but get to the minimum
2107 * we're happy. Goose it a bit if there are multiple requests
2108 * for memory.
2110 * Don't reduce avail_shortage inside the loop or the
2111 * PQAVERAGE() calculation will break.
2113 * NOTE! deficit is differentiated from avail_shortage as
2114 * REQUIRING at least (deficit) pages to be cleaned,
2115 * even if the page queues are in good shape. This
2116 * is used primarily for handling per-process
2117 * RLIMIT_RSS and may also see small values when
2118 * processes block due to low memory.
2120 vmstats_rollup();
2121 if (isep == 0)
2122 vm_pagedaemon_time = ticks;
2123 avail_shortage = vm_paging_target() + vm_pageout_deficit;
2124 vm_pageout_deficit = 0;
2126 if (avail_shortage > 0) {
2127 int delta = 0;
2129 for (q = 0; q < PQ_L2_SIZE; ++q) {
2130 delta += vm_pageout_scan_inactive(
2131 pass,
2132 (q + q1iterator) & PQ_L2_MASK,
2133 PQAVERAGE(avail_shortage),
2134 &vnodes_skipped);
2135 if (avail_shortage - delta <= 0)
2136 break;
2138 avail_shortage -= delta;
2139 q1iterator = q + 1;
2143 * Figure out how many active pages we must deactivate. If
2144 * we were able to reach our target with just the inactive
2145 * scan above we limit the number of active pages we
2146 * deactivate to reduce unnecessary work.
2148 vmstats_rollup();
2149 if (isep == 0)
2150 vm_pagedaemon_time = ticks;
2151 inactive_shortage = vmstats.v_inactive_target -
2152 vmstats.v_inactive_count;
2155 * If we were unable to free sufficient inactive pages to
2156 * satisfy the free/cache queue requirements then simply
2157 * reaching the inactive target may not be good enough.
2158 * Try to deactivate pages in excess of the target based
2159 * on the shortfall.
2161 * However to prevent thrashing the VM system do not
2162 * deactivate more than an additional 1/10 the inactive
2163 * target's worth of active pages.
2165 if (avail_shortage > 0) {
2166 tmp = avail_shortage * 2;
2167 if (tmp > vmstats.v_inactive_target / 10)
2168 tmp = vmstats.v_inactive_target / 10;
2169 inactive_shortage += tmp;
2173 * Only trigger a pmap cleanup on inactive shortage.
2175 if (isep == 0 && inactive_shortage > 0) {
2176 pmap_collect();
2180 * Scan for ACTIVE->INACTIVE
2182 * Only trigger on inactive shortage. Triggering on
2183 * avail_shortage can starve the active queue with
2184 * unnecessary active->inactive transitions and destroy
2185 * performance.
2187 * If this is the emergency pager, always try to move
2188 * a few pages from active to inactive because the inactive
2189 * queue might have enough pages, but not enough anonymous
2190 * pages.
2192 if (isep && inactive_shortage < vm_emerg_launder)
2193 inactive_shortage = vm_emerg_launder;
2195 if (/*avail_shortage > 0 ||*/ inactive_shortage > 0) {
2196 int delta = 0;
2198 for (q = 0; q < PQ_L2_SIZE; ++q) {
2199 delta += vm_pageout_scan_active(
2200 pass,
2201 (q + q2iterator) & PQ_L2_MASK,
2202 PQAVERAGE(avail_shortage),
2203 PQAVERAGE(inactive_shortage),
2204 &recycle_count);
2205 if (inactive_shortage - delta <= 0 &&
2206 avail_shortage - delta <= 0) {
2207 break;
2210 inactive_shortage -= delta;
2211 avail_shortage -= delta;
2212 q2iterator = q + 1;
2216 * Scan for CACHE->FREE
2218 * Finally free enough cache pages to meet our free page
2219 * requirement and take more drastic measures if we are
2220 * still in trouble.
2222 vmstats_rollup();
2223 if (isep == 0)
2224 vm_pagedaemon_time = ticks;
2225 vm_pageout_scan_cache(avail_shortage, pass,
2226 vnodes_skipped, recycle_count);
2229 * Wait for more work.
2231 if (avail_shortage > 0) {
2232 ++pass;
2233 if (pass < 10 && vm_pages_needed > 1) {
2235 * Normal operation, additional processes
2236 * have already kicked us. Retry immediately
2237 * unless swap space is completely full in
2238 * which case delay a bit.
2240 if (swap_pager_full) {
2241 tsleep(&vm_pages_needed, 0, "pdelay",
2242 hz / 5);
2243 } /* else immediate retry */
2244 } else if (pass < 10) {
2246 * Normal operation, fewer processes. Delay
2247 * a bit but allow wakeups. vm_pages_needed
2248 * is only adjusted against the primary
2249 * pagedaemon here.
2251 if (isep == 0)
2252 vm_pages_needed = 0;
2253 tsleep(&vm_pages_needed, 0, "pdelay", hz / 10);
2254 if (isep == 0)
2255 vm_pages_needed = 1;
2256 } else if (swap_pager_full == 0) {
2258 * We've taken too many passes, forced delay.
2260 tsleep(&vm_pages_needed, 0, "pdelay", hz / 10);
2261 } else {
2263 * Running out of memory, catastrophic
2264 * back-off to one-second intervals.
2266 tsleep(&vm_pages_needed, 0, "pdelay", hz);
2268 } else if (vm_pages_needed) {
2270 * Interlocked wakeup of waiters (non-optional).
2272 * Similar to vm_page_free_wakeup() in vm_page.c,
2273 * wake
2275 pass = 0;
2276 if (!vm_page_count_min(vm_page_free_hysteresis) ||
2277 !vm_page_count_target()) {
2278 vm_pages_needed = 0;
2279 wakeup(&vmstats.v_free_count);
2281 } else {
2282 pass = 0;
2287 static struct kproc_desc pg1_kp = {
2288 "pagedaemon",
2289 vm_pageout_thread,
2290 &pagethread
2292 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, kproc_start, &pg1_kp);
2294 static struct kproc_desc pg2_kp = {
2295 "emergpager",
2296 vm_pageout_thread,
2297 &emergpager
2299 SYSINIT(emergpager, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY, kproc_start, &pg2_kp);
2303 * Called after allocating a page out of the cache or free queue
2304 * to possibly wake the pagedaemon up to replentish our supply.
2306 * We try to generate some hysteresis by waking the pagedaemon up
2307 * when our free+cache pages go below the free_min+cache_min level.
2308 * The pagedaemon tries to get the count back up to at least the
2309 * minimum, and through to the target level if possible.
2311 * If the pagedaemon is already active bump vm_pages_needed as a hint
2312 * that there are even more requests pending.
2314 * SMP races ok?
2315 * No requirements.
2317 void
2318 pagedaemon_wakeup(void)
2320 if (vm_paging_needed() && curthread != pagethread) {
2321 if (vm_pages_needed == 0) {
2322 vm_pages_needed = 1; /* SMP race ok */
2323 wakeup(&vm_pages_needed);
2324 } else if (vm_page_count_min(0)) {
2325 ++vm_pages_needed; /* SMP race ok */
2330 #if !defined(NO_SWAPPING)
2333 * SMP races ok?
2334 * No requirements.
2336 static void
2337 vm_req_vmdaemon(void)
2339 static int lastrun = 0;
2341 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
2342 wakeup(&vm_daemon_needed);
2343 lastrun = ticks;
2347 static int vm_daemon_callback(struct proc *p, void *data __unused);
2350 * No requirements.
2352 static void
2353 vm_daemon(void)
2355 int req_swapout;
2357 while (TRUE) {
2358 tsleep(&vm_daemon_needed, 0, "psleep", 0);
2359 req_swapout = atomic_swap_int(&vm_pageout_req_swapout, 0);
2362 * forced swapouts
2364 if (req_swapout)
2365 swapout_procs(vm_pageout_req_swapout);
2368 * scan the processes for exceeding their rlimits or if
2369 * process is swapped out -- deactivate pages
2371 allproc_scan(vm_daemon_callback, NULL, 0);
2375 static int
2376 vm_daemon_callback(struct proc *p, void *data __unused)
2378 struct vmspace *vm;
2379 vm_pindex_t limit, size;
2382 * if this is a system process or if we have already
2383 * looked at this process, skip it.
2385 lwkt_gettoken(&p->p_token);
2387 if (p->p_flags & (P_SYSTEM | P_WEXIT)) {
2388 lwkt_reltoken(&p->p_token);
2389 return (0);
2393 * if the process is in a non-running type state,
2394 * don't touch it.
2396 if (p->p_stat != SACTIVE && p->p_stat != SSTOP && p->p_stat != SCORE) {
2397 lwkt_reltoken(&p->p_token);
2398 return (0);
2402 * get a limit
2404 limit = OFF_TO_IDX(qmin(p->p_rlimit[RLIMIT_RSS].rlim_cur,
2405 p->p_rlimit[RLIMIT_RSS].rlim_max));
2408 * let processes that are swapped out really be
2409 * swapped out. Set the limit to nothing to get as
2410 * many pages out to swap as possible.
2412 if (p->p_flags & P_SWAPPEDOUT)
2413 limit = 0;
2415 vm = p->p_vmspace;
2416 vmspace_hold(vm);
2417 size = pmap_resident_tlnw_count(&vm->vm_pmap);
2418 if (limit >= 0 && size > 4096 &&
2419 size - 4096 >= limit && vm_pageout_memuse_mode >= 1) {
2420 vm_pageout_map_deactivate_pages(&vm->vm_map, limit);
2422 vmspace_drop(vm);
2424 lwkt_reltoken(&p->p_token);
2426 return (0);
2429 #endif