2 * Copyright (c) 1991 Regents of the University of California.
4 * Copyright (c) 1994 John S. Dyson
6 * Copyright (c) 1994 David Greenman
8 * Copyright (c) 2005 Yahoo! Technologies Norway AS
11 * This code is derived from software contributed to Berkeley by
12 * The Mach Operating System project at Carnegie-Mellon University.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 * 3. All advertising materials mentioning features or use of this software
23 * must display the following acknowledgement:
24 * This product includes software developed by the University of
25 * California, Berkeley and its contributors.
26 * 4. Neither the name of the University nor the names of its contributors
27 * may be used to endorse or promote products derived from this software
28 * without specific prior written permission.
30 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42 * from: @(#)vm_pageout.c 7.4 (Berkeley) 5/7/91
45 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
46 * All rights reserved.
48 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
50 * Permission to use, copy, modify and distribute this software and
51 * its documentation is hereby granted, provided that both the copyright
52 * notice and this permission notice appear in all copies of the
53 * software, derivative works or modified versions, and any portions
54 * thereof, and that both notices appear in supporting documentation.
56 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
57 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
58 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
60 * Carnegie Mellon requests users of this software to return to
62 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
63 * School of Computer Science
64 * Carnegie Mellon University
65 * Pittsburgh PA 15213-3890
67 * any improvements or extensions that they make and grant Carnegie the
68 * rights to redistribute these changes.
72 * The proverbial page-out daemon.
75 #include <sys/cdefs.h>
76 __FBSDID("$FreeBSD$");
80 #include <sys/param.h>
81 #include <sys/systm.h>
82 #include <sys/kernel.h>
83 #include <sys/eventhandler.h>
85 #include <sys/mutex.h>
87 #include <sys/kthread.h>
89 #include <sys/mount.h>
90 #include <sys/racct.h>
91 #include <sys/resourcevar.h>
92 #include <sys/sched.h>
94 #include <sys/signalvar.h>
97 #include <sys/vnode.h>
98 #include <sys/vmmeter.h>
99 #include <sys/rwlock.h>
101 #include <sys/sysctl.h>
104 #include <vm/vm_param.h>
105 #include <vm/vm_object.h>
106 #include <vm/vm_page.h>
107 #include <vm/vm_map.h>
108 #include <vm/vm_pageout.h>
109 #include <vm/vm_pager.h>
110 #include <vm/vm_phys.h>
111 #include <vm/swap_pager.h>
112 #include <vm/vm_extern.h>
116 * System initialization
119 /* the kernel process "vm_pageout"*/
120 static void vm_pageout(void);
121 static void vm_pageout_init(void);
122 static int vm_pageout_clean(vm_page_t m, int *numpagedout);
123 static int vm_pageout_cluster(vm_page_t m);
124 static bool vm_pageout_scan(struct vm_domain *vmd, int pass);
125 static void vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
126 int starting_page_shortage);
128 SYSINIT(pagedaemon_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, vm_pageout_init,
131 struct proc *pageproc;
133 static struct kproc_desc page_kp = {
138 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_SECOND, kproc_start,
141 SDT_PROVIDER_DEFINE(vm);
142 SDT_PROBE_DEFINE(vm, , , vm__lowmem_scan);
144 #if !defined(NO_SWAPPING)
145 /* the kernel process "vm_daemon"*/
146 static void vm_daemon(void);
147 static struct proc *vmproc;
149 static struct kproc_desc vm_kp = {
154 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
157 /* Pagedaemon activity rates, in subdivisions of one second. */
158 #define VM_LAUNDER_RATE 10
159 #define VM_INACT_SCAN_RATE 2
161 int vm_pageout_deficit; /* Estimated number of pages deficit */
162 u_int vm_pageout_wakeup_thresh;
163 static int vm_pageout_oom_seq = 12;
164 bool vm_pageout_wanted; /* Event on which pageout daemon sleeps */
165 bool vm_pages_needed; /* Are threads waiting for free pages? */
167 /* Pending request for dirty page laundering. */
170 VM_LAUNDRY_BACKGROUND,
172 } vm_laundry_request = VM_LAUNDRY_IDLE;
174 #if !defined(NO_SWAPPING)
175 static int vm_pageout_req_swapout; /* XXX */
176 static int vm_daemon_needed;
177 static struct mtx vm_daemon_mtx;
178 /* Allow for use by vm_pageout before vm_daemon is initialized. */
179 MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
181 static int vm_pageout_update_period;
182 static int disable_swap_pageouts;
183 static int lowmem_period = 10;
184 static time_t lowmem_uptime;
186 #if defined(NO_SWAPPING)
187 static int vm_swap_enabled = 0;
188 static int vm_swap_idle_enabled = 0;
190 static int vm_swap_enabled = 1;
191 static int vm_swap_idle_enabled = 0;
194 static int vm_panic_on_oom = 0;
196 SYSCTL_INT(_vm, OID_AUTO, panic_on_oom,
197 CTLFLAG_RWTUN, &vm_panic_on_oom, 0,
198 "panic on out of memory instead of killing the largest process");
200 SYSCTL_INT(_vm, OID_AUTO, pageout_wakeup_thresh,
201 CTLFLAG_RW, &vm_pageout_wakeup_thresh, 0,
202 "free page threshold for waking up the pageout daemon");
204 SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
205 CTLFLAG_RW, &vm_pageout_update_period, 0,
206 "Maximum active LRU update period");
208 SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RW, &lowmem_period, 0,
209 "Low memory callback period");
211 #if defined(NO_SWAPPING)
212 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
213 CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout");
214 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
215 CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
217 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
218 CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
219 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
220 CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
223 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
224 CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
226 static int pageout_lock_miss;
227 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
228 CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
230 SYSCTL_INT(_vm, OID_AUTO, pageout_oom_seq,
231 CTLFLAG_RW, &vm_pageout_oom_seq, 0,
232 "back-to-back calls to oom detector to start OOM");
234 static int act_scan_laundry_weight = 3;
235 SYSCTL_INT(_vm, OID_AUTO, act_scan_laundry_weight, CTLFLAG_RW,
236 &act_scan_laundry_weight, 0,
237 "weight given to clean vs. dirty pages in active queue scans");
239 static u_int vm_background_launder_target;
240 SYSCTL_UINT(_vm, OID_AUTO, background_launder_target, CTLFLAG_RW,
241 &vm_background_launder_target, 0,
242 "background laundering target, in pages");
244 static u_int vm_background_launder_rate = 4096;
245 SYSCTL_UINT(_vm, OID_AUTO, background_launder_rate, CTLFLAG_RW,
246 &vm_background_launder_rate, 0,
247 "background laundering rate, in kilobytes per second");
249 static u_int vm_background_launder_max = 20 * 1024;
250 SYSCTL_UINT(_vm, OID_AUTO, background_launder_max, CTLFLAG_RW,
251 &vm_background_launder_max, 0, "background laundering cap, in kilobytes");
253 #define VM_PAGEOUT_PAGE_COUNT 16
254 int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
256 int vm_page_max_wired; /* XXX max # of wired pages system-wide */
257 SYSCTL_INT(_vm, OID_AUTO, max_wired,
258 CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
260 static u_int isqrt(u_int num);
261 static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
262 static int vm_pageout_launder(struct vm_domain *vmd, int launder,
264 static void vm_pageout_laundry_worker(void *arg);
265 #if !defined(NO_SWAPPING)
266 static void vm_pageout_map_deactivate_pages(vm_map_t, long);
267 static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
268 static void vm_req_vmdaemon(int req);
270 static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
273 * Initialize a dummy page for marking the caller's place in the specified
274 * paging queue. In principle, this function only needs to set the flag
275 * PG_MARKER. Nonetheless, it write busies and initializes the hold count
276 * to one as safety precautions.
279 vm_pageout_init_marker(vm_page_t marker, u_short queue)
282 bzero(marker, sizeof(*marker));
283 marker->flags = PG_MARKER;
284 marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
285 marker->queue = queue;
286 marker->hold_count = 1;
290 * vm_pageout_fallback_object_lock:
292 * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
293 * known to have failed and page queue must be either PQ_ACTIVE or
294 * PQ_INACTIVE. To avoid lock order violation, unlock the page queue
295 * while locking the vm object. Use marker page to detect page queue
296 * changes and maintain notion of next page on page queue. Return
297 * TRUE if no changes were detected, FALSE otherwise. vm object is
300 * This function depends on both the lock portion of struct vm_object
301 * and normal struct vm_page being type stable.
304 vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
306 struct vm_page marker;
307 struct vm_pagequeue *pq;
313 vm_pageout_init_marker(&marker, queue);
314 pq = vm_page_pagequeue(m);
317 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
318 vm_pagequeue_unlock(pq);
320 VM_OBJECT_WLOCK(object);
322 vm_pagequeue_lock(pq);
325 * The page's object might have changed, and/or the page might
326 * have moved from its original position in the queue. If the
327 * page's object has changed, then the caller should abandon
328 * processing the page because the wrong object lock was
329 * acquired. Use the marker's plinks.q, not the page's, to
330 * determine if the page has been moved. The state of the
331 * page's plinks.q can be indeterminate; whereas, the marker's
332 * plinks.q must be valid.
334 *next = TAILQ_NEXT(&marker, plinks.q);
335 unchanged = m->object == object &&
336 m == TAILQ_PREV(&marker, pglist, plinks.q);
337 KASSERT(!unchanged || m->queue == queue,
338 ("page %p queue %d %d", m, queue, m->queue));
339 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
344 * Lock the page while holding the page queue lock. Use marker page
345 * to detect page queue changes and maintain notion of next page on
346 * page queue. Return TRUE if no changes were detected, FALSE
347 * otherwise. The page is locked on return. The page queue lock might
348 * be dropped and reacquired.
350 * This function depends on normal struct vm_page being type stable.
353 vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
355 struct vm_page marker;
356 struct vm_pagequeue *pq;
360 vm_page_lock_assert(m, MA_NOTOWNED);
361 if (vm_page_trylock(m))
365 vm_pageout_init_marker(&marker, queue);
366 pq = vm_page_pagequeue(m);
368 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
369 vm_pagequeue_unlock(pq);
371 vm_pagequeue_lock(pq);
373 /* Page queue might have changed. */
374 *next = TAILQ_NEXT(&marker, plinks.q);
375 unchanged = m == TAILQ_PREV(&marker, pglist, plinks.q);
376 KASSERT(!unchanged || m->queue == queue,
377 ("page %p queue %d %d", m, queue, m->queue));
378 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
383 * Scan for pages at adjacent offsets within the given page's object that are
384 * eligible for laundering, form a cluster of these pages and the given page,
385 * and launder that cluster.
388 vm_pageout_cluster(vm_page_t m)
391 vm_page_t mc[2 * vm_pageout_page_count], p, pb, ps;
393 int ib, is, page_base, pageout_count;
395 vm_page_assert_locked(m);
397 VM_OBJECT_ASSERT_WLOCKED(object);
401 * We can't clean the page if it is busy or held.
403 vm_page_assert_unbusied(m);
404 KASSERT(m->hold_count == 0, ("page %p is held", m));
407 mc[vm_pageout_page_count] = pb = ps = m;
409 page_base = vm_pageout_page_count;
414 * We can cluster only if the page is not clean, busy, or held, and
415 * the page is in the laundry queue.
417 * During heavy mmap/modification loads the pageout
418 * daemon can really fragment the underlying file
419 * due to flushing pages out of order and not trying to
420 * align the clusters (which leaves sporadic out-of-order
421 * holes). To solve this problem we do the reverse scan
422 * first and attempt to align our cluster, then do a
423 * forward scan if room remains.
426 while (ib != 0 && pageout_count < vm_pageout_page_count) {
431 if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
435 vm_page_test_dirty(p);
441 if (!vm_page_in_laundry(p) ||
442 p->hold_count != 0) { /* may be undergoing I/O */
448 mc[--page_base] = pb = p;
453 * We are at an alignment boundary. Stop here, and switch
454 * directions. Do not clear ib.
456 if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
459 while (pageout_count < vm_pageout_page_count &&
460 pindex + is < object->size) {
461 if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
463 vm_page_test_dirty(p);
467 if (!vm_page_in_laundry(p) ||
468 p->hold_count != 0) { /* may be undergoing I/O */
473 mc[page_base + pageout_count] = ps = p;
479 * If we exhausted our forward scan, continue with the reverse scan
480 * when possible, even past an alignment boundary. This catches
481 * boundary conditions.
483 if (ib != 0 && pageout_count < vm_pageout_page_count)
486 return (vm_pageout_flush(&mc[page_base], pageout_count,
487 VM_PAGER_PUT_NOREUSE, 0, NULL, NULL));
491 * vm_pageout_flush() - launder the given pages
493 * The given pages are laundered. Note that we setup for the start of
494 * I/O ( i.e. busy the page ), mark it read-only, and bump the object
495 * reference count all in here rather then in the parent. If we want
496 * the parent to do more sophisticated things we may have to change
499 * Returned runlen is the count of pages between mreq and first
500 * page after mreq with status VM_PAGER_AGAIN.
501 * *eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
502 * for any page in runlen set.
505 vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
508 vm_object_t object = mc[0]->object;
509 int pageout_status[count];
513 VM_OBJECT_ASSERT_WLOCKED(object);
516 * Initiate I/O. Bump the vm_page_t->busy counter and
517 * mark the pages read-only.
519 * We do not have to fixup the clean/dirty bits here... we can
520 * allow the pager to do it after the I/O completes.
522 * NOTE! mc[i]->dirty may be partial or fragmented due to an
523 * edge case with file fragments.
525 for (i = 0; i < count; i++) {
526 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
527 ("vm_pageout_flush: partially invalid page %p index %d/%d",
529 vm_page_sbusy(mc[i]);
530 pmap_remove_write(mc[i]);
532 vm_object_pip_add(object, count);
534 vm_pager_put_pages(object, mc, count, flags, pageout_status);
536 runlen = count - mreq;
539 for (i = 0; i < count; i++) {
540 vm_page_t mt = mc[i];
542 KASSERT(pageout_status[i] == VM_PAGER_PEND ||
543 !pmap_page_is_write_mapped(mt),
544 ("vm_pageout_flush: page %p is not write protected", mt));
545 switch (pageout_status[i]) {
548 if (vm_page_in_laundry(mt))
549 vm_page_deactivate_noreuse(mt);
557 * The page is outside the object's range. We pretend
558 * that the page out worked and clean the page, so the
559 * changes will be lost if the page is reclaimed by
564 if (vm_page_in_laundry(mt))
565 vm_page_deactivate_noreuse(mt);
571 * If the page couldn't be paged out, then reactivate
572 * it so that it doesn't clog the laundry and inactive
573 * queues. (We will try paging it out again later).
576 vm_page_activate(mt);
578 if (eio != NULL && i >= mreq && i - mreq < runlen)
582 if (i >= mreq && i - mreq < runlen)
588 * If the operation is still going, leave the page busy to
589 * block all other accesses. Also, leave the paging in
590 * progress indicator set so that we don't attempt an object
593 if (pageout_status[i] != VM_PAGER_PEND) {
594 vm_object_pip_wakeup(object);
600 return (numpagedout);
603 #if !defined(NO_SWAPPING)
605 * vm_pageout_object_deactivate_pages
607 * Deactivate enough pages to satisfy the inactive target
610 * The object and map must be locked.
613 vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
616 vm_object_t backing_object, object;
618 int act_delta, remove_mode;
620 VM_OBJECT_ASSERT_LOCKED(first_object);
621 if ((first_object->flags & OBJ_FICTITIOUS) != 0)
623 for (object = first_object;; object = backing_object) {
624 if (pmap_resident_count(pmap) <= desired)
626 VM_OBJECT_ASSERT_LOCKED(object);
627 if ((object->flags & OBJ_UNMANAGED) != 0 ||
628 object->paging_in_progress != 0)
632 if (object->shadow_count > 1)
635 * Scan the object's entire memory queue.
637 TAILQ_FOREACH(p, &object->memq, listq) {
638 if (pmap_resident_count(pmap) <= desired)
640 if (vm_page_busied(p))
642 PCPU_INC(cnt.v_pdpages);
644 if (p->wire_count != 0 || p->hold_count != 0 ||
645 !pmap_page_exists_quick(pmap, p)) {
649 act_delta = pmap_ts_referenced(p);
650 if ((p->aflags & PGA_REFERENCED) != 0) {
653 vm_page_aflag_clear(p, PGA_REFERENCED);
655 if (!vm_page_active(p) && act_delta != 0) {
657 p->act_count += act_delta;
658 } else if (vm_page_active(p)) {
659 if (act_delta == 0) {
660 p->act_count -= min(p->act_count,
662 if (!remove_mode && p->act_count == 0) {
664 vm_page_deactivate(p);
669 if (p->act_count < ACT_MAX -
671 p->act_count += ACT_ADVANCE;
674 } else if (vm_page_inactive(p))
678 if ((backing_object = object->backing_object) == NULL)
680 VM_OBJECT_RLOCK(backing_object);
681 if (object != first_object)
682 VM_OBJECT_RUNLOCK(object);
685 if (object != first_object)
686 VM_OBJECT_RUNLOCK(object);
690 * deactivate some number of pages in a map, try to do it fairly, but
691 * that is really hard to do.
694 vm_pageout_map_deactivate_pages(map, desired)
699 vm_object_t obj, bigobj;
702 if (!vm_map_trylock(map))
709 * first, search out the biggest object, and try to free pages from
712 tmpe = map->header.next;
713 while (tmpe != &map->header) {
714 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
715 obj = tmpe->object.vm_object;
716 if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
717 if (obj->shadow_count <= 1 &&
719 bigobj->resident_page_count < obj->resident_page_count)) {
721 VM_OBJECT_RUNLOCK(bigobj);
724 VM_OBJECT_RUNLOCK(obj);
727 if (tmpe->wired_count > 0)
728 nothingwired = FALSE;
732 if (bigobj != NULL) {
733 vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
734 VM_OBJECT_RUNLOCK(bigobj);
737 * Next, hunt around for other pages to deactivate. We actually
738 * do this search sort of wrong -- .text first is not the best idea.
740 tmpe = map->header.next;
741 while (tmpe != &map->header) {
742 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
744 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
745 obj = tmpe->object.vm_object;
747 VM_OBJECT_RLOCK(obj);
748 vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
749 VM_OBJECT_RUNLOCK(obj);
756 * Remove all mappings if a process is swapped out, this will free page
759 if (desired == 0 && nothingwired) {
760 pmap_remove(vm_map_pmap(map), vm_map_min(map),
766 #endif /* !defined(NO_SWAPPING) */
769 * Attempt to acquire all of the necessary locks to launder a page and
770 * then call through the clustering layer to PUTPAGES. Wait a short
771 * time for a vnode lock.
773 * Requires the page and object lock on entry, releases both before return.
774 * Returns 0 on success and an errno otherwise.
777 vm_pageout_clean(vm_page_t m, int *numpagedout)
785 vm_page_assert_locked(m);
787 VM_OBJECT_ASSERT_WLOCKED(object);
793 * The object is already known NOT to be dead. It
794 * is possible for the vget() to block the whole
795 * pageout daemon, but the new low-memory handling
796 * code should prevent it.
798 * We can't wait forever for the vnode lock, we might
799 * deadlock due to a vn_read() getting stuck in
800 * vm_wait while holding this vnode. We skip the
801 * vnode if we can't get it in a reasonable amount
804 if (object->type == OBJT_VNODE) {
807 if (vp->v_type == VREG &&
808 vn_start_write(vp, &mp, V_NOWAIT) != 0) {
814 ("vp %p with NULL v_mount", vp));
815 vm_object_reference_locked(object);
817 VM_OBJECT_WUNLOCK(object);
818 lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
819 LK_SHARED : LK_EXCLUSIVE;
820 if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
825 VM_OBJECT_WLOCK(object);
828 * While the object and page were unlocked, the page
830 * (1) moved to a different queue,
831 * (2) reallocated to a different object,
832 * (3) reallocated to a different offset, or
835 if (!vm_page_in_laundry(m) || m->object != object ||
836 m->pindex != pindex || m->dirty == 0) {
843 * The page may have been busied or held while the object
844 * and page locks were released.
846 if (vm_page_busied(m) || m->hold_count != 0) {
854 * If a page is dirty, then it is either being washed
855 * (but not yet cleaned) or it is still in the
856 * laundry. If it is still in the laundry, then we
857 * start the cleaning operation.
859 if ((*numpagedout = vm_pageout_cluster(m)) == 0)
863 VM_OBJECT_WUNLOCK(object);
866 vm_page_lock_assert(m, MA_NOTOWNED);
870 vm_object_deallocate(object);
871 vn_finished_write(mp);
878 * Attempt to launder the specified number of pages.
880 * Returns the number of pages successfully laundered.
883 vm_pageout_launder(struct vm_domain *vmd, int launder, bool in_shortfall)
885 struct vm_pagequeue *pq;
888 int act_delta, error, maxscan, numpagedout, starting_target;
890 bool pageout_ok, queue_locked;
892 starting_target = launder;
896 * Scan the laundry queue for pages eligible to be laundered. We stop
897 * once the target number of dirty pages have been laundered, or once
898 * we've reached the end of the queue. A single iteration of this loop
899 * may cause more than one page to be laundered because of clustering.
901 * maxscan ensures that we don't re-examine requeued pages. Any
902 * additional pages written as part of a cluster are subtracted from
903 * maxscan since they must be taken from the laundry queue.
905 pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
906 maxscan = pq->pq_cnt;
908 vm_pagequeue_lock(pq);
910 for (m = TAILQ_FIRST(&pq->pq_pl);
911 m != NULL && maxscan-- > 0 && launder > 0;
913 vm_pagequeue_assert_locked(pq);
914 KASSERT(queue_locked, ("unlocked laundry queue"));
915 KASSERT(vm_page_in_laundry(m),
916 ("page %p has an inconsistent queue", m));
917 next = TAILQ_NEXT(m, plinks.q);
918 if ((m->flags & PG_MARKER) != 0)
920 KASSERT((m->flags & PG_FICTITIOUS) == 0,
921 ("PG_FICTITIOUS page %p cannot be in laundry queue", m));
922 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
923 ("VPO_UNMANAGED page %p cannot be in laundry queue", m));
924 if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
929 if ((!VM_OBJECT_TRYWLOCK(object) &&
930 (!vm_pageout_fallback_object_lock(m, &next) ||
931 m->hold_count != 0)) || vm_page_busied(m)) {
932 VM_OBJECT_WUNLOCK(object);
938 * Unlock the laundry queue, invalidating the 'next' pointer.
939 * Use a marker to remember our place in the laundry queue.
941 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_laundry_marker,
943 vm_pagequeue_unlock(pq);
944 queue_locked = false;
947 * Invalid pages can be easily freed. They cannot be
948 * mapped; vm_page_free() asserts this.
954 * If the page has been referenced and the object is not dead,
955 * reactivate or requeue the page depending on whether the
958 if ((m->aflags & PGA_REFERENCED) != 0) {
959 vm_page_aflag_clear(m, PGA_REFERENCED);
963 if (object->ref_count != 0)
964 act_delta += pmap_ts_referenced(m);
966 KASSERT(!pmap_page_is_mapped(m),
967 ("page %p is mapped", m));
969 if (act_delta != 0) {
970 if (object->ref_count != 0) {
971 PCPU_INC(cnt.v_reactivated);
975 * Increase the activation count if the page
976 * was referenced while in the laundry queue.
977 * This makes it less likely that the page will
978 * be returned prematurely to the inactive
981 m->act_count += act_delta + ACT_ADVANCE;
984 * If this was a background laundering, count
985 * activated pages towards our target. The
986 * purpose of background laundering is to ensure
987 * that pages are eventually cycled through the
988 * laundry queue, and an activation is a valid
994 } else if ((object->flags & OBJ_DEAD) == 0)
999 * If the page appears to be clean at the machine-independent
1000 * layer, then remove all of its mappings from the pmap in
1001 * anticipation of freeing it. If, however, any of the page's
1002 * mappings allow write access, then the page may still be
1003 * modified until the last of those mappings are removed.
1005 if (object->ref_count != 0) {
1006 vm_page_test_dirty(m);
1012 * Clean pages are freed, and dirty pages are paged out unless
1013 * they belong to a dead object. Requeueing dirty pages from
1014 * dead objects is pointless, as they are being paged out and
1015 * freed by the thread that destroyed the object.
1017 if (m->dirty == 0) {
1020 PCPU_INC(cnt.v_dfree);
1021 } else if ((object->flags & OBJ_DEAD) == 0) {
1022 if (object->type != OBJT_SWAP &&
1023 object->type != OBJT_DEFAULT)
1025 else if (disable_swap_pageouts)
1031 vm_pagequeue_lock(pq);
1032 queue_locked = true;
1033 vm_page_requeue_locked(m);
1038 * Form a cluster with adjacent, dirty pages from the
1039 * same object, and page out that entire cluster.
1041 * The adjacent, dirty pages must also be in the
1042 * laundry. However, their mappings are not checked
1043 * for new references. Consequently, a recently
1044 * referenced page may be paged out. However, that
1045 * page will not be prematurely reclaimed. After page
1046 * out, the page will be placed in the inactive queue,
1047 * where any new references will be detected and the
1050 error = vm_pageout_clean(m, &numpagedout);
1052 launder -= numpagedout;
1053 maxscan -= numpagedout - 1;
1054 } else if (error == EDEADLK) {
1055 pageout_lock_miss++;
1062 VM_OBJECT_WUNLOCK(object);
1064 if (!queue_locked) {
1065 vm_pagequeue_lock(pq);
1066 queue_locked = true;
1068 next = TAILQ_NEXT(&vmd->vmd_laundry_marker, plinks.q);
1069 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_laundry_marker, plinks.q);
1071 vm_pagequeue_unlock(pq);
1074 * Wakeup the sync daemon if we skipped a vnode in a writeable object
1075 * and we didn't launder enough pages.
1077 if (vnodes_skipped > 0 && launder > 0)
1078 (void)speedup_syncer();
1080 return (starting_target - launder);
1084 * Compute the integer square root.
1089 u_int bit, root, tmp;
1091 bit = 1u << ((NBBY * sizeof(u_int)) - 2);
1108 * Perform the work of the laundry thread: periodically wake up and determine
1109 * whether any pages need to be laundered. If so, determine the number of pages
1110 * that need to be laundered, and launder them.
1113 vm_pageout_laundry_worker(void *arg)
1115 struct vm_domain *domain;
1116 struct vm_pagequeue *pq;
1117 uint64_t nclean, ndirty;
1118 u_int last_launder, wakeups;
1119 int domidx, last_target, launder, shortfall, shortfall_cycle, target;
1122 domidx = (uintptr_t)arg;
1123 domain = &vm_dom[domidx];
1124 pq = &domain->vmd_pagequeues[PQ_LAUNDRY];
1125 KASSERT(domain->vmd_segs != 0, ("domain without segments"));
1126 vm_pageout_init_marker(&domain->vmd_laundry_marker, PQ_LAUNDRY);
1129 in_shortfall = false;
1130 shortfall_cycle = 0;
1135 * The pageout laundry worker is never done, so loop forever.
1138 KASSERT(target >= 0, ("negative target %d", target));
1139 KASSERT(shortfall_cycle >= 0,
1140 ("negative cycle %d", shortfall_cycle));
1142 wakeups = VM_METER_PCPU_CNT(v_pdwakeups);
1145 * First determine whether we need to launder pages to meet a
1146 * shortage of free pages.
1148 if (shortfall > 0) {
1149 in_shortfall = true;
1150 shortfall_cycle = VM_LAUNDER_RATE / VM_INACT_SCAN_RATE;
1152 } else if (!in_shortfall)
1154 else if (shortfall_cycle == 0 || vm_laundry_target() <= 0) {
1156 * We recently entered shortfall and began laundering
1157 * pages. If we have completed that laundering run
1158 * (and we are no longer in shortfall) or we have met
1159 * our laundry target through other activity, then we
1160 * can stop laundering pages.
1162 in_shortfall = false;
1166 last_launder = wakeups;
1167 launder = target / shortfall_cycle--;
1171 * There's no immediate need to launder any pages; see if we
1172 * meet the conditions to perform background laundering:
1174 * 1. The ratio of dirty to clean inactive pages exceeds the
1175 * background laundering threshold and the pagedaemon has
1176 * been woken up to reclaim pages since our last
1178 * 2. we haven't yet reached the target of the current
1179 * background laundering run.
1181 * The background laundering threshold is not a constant.
1182 * Instead, it is a slowly growing function of the number of
1183 * page daemon wakeups since the last laundering. Thus, as the
1184 * ratio of dirty to clean inactive pages grows, the amount of
1185 * memory pressure required to trigger laundering decreases.
1188 nclean = vm_cnt.v_inactive_count + vm_cnt.v_free_count;
1189 ndirty = vm_cnt.v_laundry_count;
1190 if (target == 0 && wakeups != last_launder &&
1191 ndirty * isqrt(wakeups - last_launder) >= nclean) {
1192 target = vm_background_launder_target;
1196 * We have a non-zero background laundering target. If we've
1197 * laundered up to our maximum without observing a page daemon
1198 * wakeup, just stop. This is a safety belt that ensures we
1199 * don't launder an excessive amount if memory pressure is low
1200 * and the ratio of dirty to clean pages is large. Otherwise,
1201 * proceed at the background laundering rate.
1204 if (wakeups != last_launder) {
1205 last_launder = wakeups;
1206 last_target = target;
1207 } else if (last_target - target >=
1208 vm_background_launder_max * PAGE_SIZE / 1024) {
1211 launder = vm_background_launder_rate * PAGE_SIZE / 1024;
1212 launder /= VM_LAUNDER_RATE;
1213 if (launder > target)
1220 * Because of I/O clustering, the number of laundered
1221 * pages could exceed "target" by the maximum size of
1222 * a cluster minus one.
1224 target -= min(vm_pageout_launder(domain, launder,
1225 in_shortfall), target);
1226 pause("laundp", hz / VM_LAUNDER_RATE);
1230 * If we're not currently laundering pages and the page daemon
1231 * hasn't posted a new request, sleep until the page daemon
1234 vm_pagequeue_lock(pq);
1235 if (target == 0 && vm_laundry_request == VM_LAUNDRY_IDLE)
1236 (void)mtx_sleep(&vm_laundry_request,
1237 vm_pagequeue_lockptr(pq), PVM, "launds", 0);
1240 * If the pagedaemon has indicated that it's in shortfall, start
1241 * a shortfall laundering unless we're already in the middle of
1242 * one. This may preempt a background laundering.
1244 if (vm_laundry_request == VM_LAUNDRY_SHORTFALL &&
1245 (!in_shortfall || shortfall_cycle == 0)) {
1246 shortfall = vm_laundry_target() + vm_pageout_deficit;
1252 vm_laundry_request = VM_LAUNDRY_IDLE;
1253 vm_pagequeue_unlock(pq);
1258 * vm_pageout_scan does the dirty work for the pageout daemon.
1260 * pass == 0: Update active LRU/deactivate pages
1261 * pass >= 1: Free inactive pages
1263 * Returns true if pass was zero or enough pages were freed by the inactive
1264 * queue scan to meet the target.
1267 vm_pageout_scan(struct vm_domain *vmd, int pass)
1270 struct vm_pagequeue *pq;
1273 int act_delta, addl_page_shortage, deficit, inactq_shortage, maxscan;
1274 int page_shortage, scan_tick, scanned, starting_page_shortage;
1275 boolean_t queue_locked;
1278 * If we need to reclaim memory ask kernel caches to return
1279 * some. We rate limit to avoid thrashing.
1281 if (vmd == &vm_dom[0] && pass > 0 &&
1282 (time_uptime - lowmem_uptime) >= lowmem_period) {
1284 * Decrease registered cache sizes.
1286 SDT_PROBE0(vm, , , vm__lowmem_scan);
1287 EVENTHANDLER_INVOKE(vm_lowmem, 0);
1289 * We do this explicitly after the caches have been
1293 lowmem_uptime = time_uptime;
1297 * The addl_page_shortage is the number of temporarily
1298 * stuck pages in the inactive queue. In other words, the
1299 * number of pages from the inactive count that should be
1300 * discounted in setting the target for the active queue scan.
1302 addl_page_shortage = 0;
1305 * Calculate the number of pages that we want to free. This number
1306 * can be negative if many pages are freed between the wakeup call to
1307 * the page daemon and this calculation.
1310 deficit = atomic_readandclear_int(&vm_pageout_deficit);
1311 page_shortage = vm_paging_target() + deficit;
1313 page_shortage = deficit = 0;
1314 starting_page_shortage = page_shortage;
1317 * Start scanning the inactive queue for pages that we can free. The
1318 * scan will stop when we reach the target or we have scanned the
1319 * entire queue. (Note that m->act_count is not used to make
1320 * decisions for the inactive queue, only for the active queue.)
1322 pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
1323 maxscan = pq->pq_cnt;
1324 vm_pagequeue_lock(pq);
1325 queue_locked = TRUE;
1326 for (m = TAILQ_FIRST(&pq->pq_pl);
1327 m != NULL && maxscan-- > 0 && page_shortage > 0;
1329 vm_pagequeue_assert_locked(pq);
1330 KASSERT(queue_locked, ("unlocked inactive queue"));
1331 KASSERT(vm_page_inactive(m), ("Inactive queue %p", m));
1333 PCPU_INC(cnt.v_pdpages);
1334 next = TAILQ_NEXT(m, plinks.q);
1339 if (m->flags & PG_MARKER)
1342 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1343 ("Fictitious page %p cannot be in inactive queue", m));
1344 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1345 ("Unmanaged page %p cannot be in inactive queue", m));
1348 * The page or object lock acquisitions fail if the
1349 * page was removed from the queue or moved to a
1350 * different position within the queue. In either
1351 * case, addl_page_shortage should not be incremented.
1353 if (!vm_pageout_page_lock(m, &next))
1355 else if (m->hold_count != 0) {
1357 * Held pages are essentially stuck in the
1358 * queue. So, they ought to be discounted
1359 * from the inactive count. See the
1360 * calculation of inactq_shortage before the
1361 * loop over the active queue below.
1363 addl_page_shortage++;
1367 if (!VM_OBJECT_TRYWLOCK(object)) {
1368 if (!vm_pageout_fallback_object_lock(m, &next))
1370 else if (m->hold_count != 0) {
1371 addl_page_shortage++;
1375 if (vm_page_busied(m)) {
1377 * Don't mess with busy pages. Leave them at
1378 * the front of the queue. Most likely, they
1379 * are being paged out and will leave the
1380 * queue shortly after the scan finishes. So,
1381 * they ought to be discounted from the
1384 addl_page_shortage++;
1386 VM_OBJECT_WUNLOCK(object);
1391 KASSERT(m->hold_count == 0, ("Held page %p", m));
1394 * Dequeue the inactive page and unlock the inactive page
1395 * queue, invalidating the 'next' pointer. Dequeueing the
1396 * page here avoids a later reacquisition (and release) of
1397 * the inactive page queue lock when vm_page_activate(),
1398 * vm_page_free(), or vm_page_launder() is called. Use a
1399 * marker to remember our place in the inactive queue.
1401 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
1402 vm_page_dequeue_locked(m);
1403 vm_pagequeue_unlock(pq);
1404 queue_locked = FALSE;
1407 * Invalid pages can be easily freed. They cannot be
1408 * mapped, vm_page_free() asserts this.
1414 * If the page has been referenced and the object is not dead,
1415 * reactivate or requeue the page depending on whether the
1418 if ((m->aflags & PGA_REFERENCED) != 0) {
1419 vm_page_aflag_clear(m, PGA_REFERENCED);
1423 if (object->ref_count != 0) {
1424 act_delta += pmap_ts_referenced(m);
1426 KASSERT(!pmap_page_is_mapped(m),
1427 ("vm_pageout_scan: page %p is mapped", m));
1429 if (act_delta != 0) {
1430 if (object->ref_count != 0) {
1431 PCPU_INC(cnt.v_reactivated);
1432 vm_page_activate(m);
1435 * Increase the activation count if the page
1436 * was referenced while in the inactive queue.
1437 * This makes it less likely that the page will
1438 * be returned prematurely to the inactive
1441 m->act_count += act_delta + ACT_ADVANCE;
1443 } else if ((object->flags & OBJ_DEAD) == 0) {
1444 vm_pagequeue_lock(pq);
1445 queue_locked = TRUE;
1446 m->queue = PQ_INACTIVE;
1447 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
1448 vm_pagequeue_cnt_inc(pq);
1454 * If the page appears to be clean at the machine-independent
1455 * layer, then remove all of its mappings from the pmap in
1456 * anticipation of freeing it. If, however, any of the page's
1457 * mappings allow write access, then the page may still be
1458 * modified until the last of those mappings are removed.
1460 if (object->ref_count != 0) {
1461 vm_page_test_dirty(m);
1467 * Clean pages can be freed, but dirty pages must be sent back
1468 * to the laundry, unless they belong to a dead object.
1469 * Requeueing dirty pages from dead objects is pointless, as
1470 * they are being paged out and freed by the thread that
1471 * destroyed the object.
1473 if (m->dirty == 0) {
1476 PCPU_INC(cnt.v_dfree);
1478 } else if ((object->flags & OBJ_DEAD) == 0)
1482 VM_OBJECT_WUNLOCK(object);
1483 if (!queue_locked) {
1484 vm_pagequeue_lock(pq);
1485 queue_locked = TRUE;
1487 next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1488 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
1490 vm_pagequeue_unlock(pq);
1493 * Wake up the laundry thread so that it can perform any needed
1494 * laundering. If we didn't meet our target, we're in shortfall and
1495 * need to launder more aggressively.
1497 if (vm_laundry_request == VM_LAUNDRY_IDLE &&
1498 starting_page_shortage > 0) {
1499 pq = &vm_dom[0].vmd_pagequeues[PQ_LAUNDRY];
1500 vm_pagequeue_lock(pq);
1501 if (page_shortage > 0) {
1502 vm_laundry_request = VM_LAUNDRY_SHORTFALL;
1503 PCPU_INC(cnt.v_pdshortfalls);
1504 } else if (vm_laundry_request != VM_LAUNDRY_SHORTFALL)
1505 vm_laundry_request = VM_LAUNDRY_BACKGROUND;
1506 wakeup(&vm_laundry_request);
1507 vm_pagequeue_unlock(pq);
1510 #if !defined(NO_SWAPPING)
1512 * Wakeup the swapout daemon if we didn't free the targeted number of
1515 if (vm_swap_enabled && page_shortage > 0)
1516 vm_req_vmdaemon(VM_SWAP_NORMAL);
1520 * If the inactive queue scan fails repeatedly to meet its
1521 * target, kill the largest process.
1523 vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
1526 * Compute the number of pages we want to try to move from the
1527 * active queue to either the inactive or laundry queue.
1529 * When scanning active pages, we make clean pages count more heavily
1530 * towards the page shortage than dirty pages. This is because dirty
1531 * pages must be laundered before they can be reused and thus have less
1532 * utility when attempting to quickly alleviate a shortage. However,
1533 * this weighting also causes the scan to deactivate dirty pages more
1534 * more aggressively, improving the effectiveness of clustering and
1535 * ensuring that they can eventually be reused.
1537 inactq_shortage = vm_cnt.v_inactive_target - (vm_cnt.v_inactive_count +
1538 vm_cnt.v_laundry_count / act_scan_laundry_weight) +
1539 vm_paging_target() + deficit + addl_page_shortage;
1540 page_shortage *= act_scan_laundry_weight;
1542 pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1543 vm_pagequeue_lock(pq);
1544 maxscan = pq->pq_cnt;
1547 * If we're just idle polling attempt to visit every
1548 * active page within 'update_period' seconds.
1551 if (vm_pageout_update_period != 0) {
1552 min_scan = pq->pq_cnt;
1553 min_scan *= scan_tick - vmd->vmd_last_active_scan;
1554 min_scan /= hz * vm_pageout_update_period;
1557 if (min_scan > 0 || (inactq_shortage > 0 && maxscan > 0))
1558 vmd->vmd_last_active_scan = scan_tick;
1561 * Scan the active queue for pages that can be deactivated. Update
1562 * the per-page activity counter and use it to identify deactivation
1563 * candidates. Held pages may be deactivated.
1565 for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
1566 min_scan || (inactq_shortage > 0 && scanned < maxscan)); m = next,
1568 KASSERT(m->queue == PQ_ACTIVE,
1569 ("vm_pageout_scan: page %p isn't active", m));
1570 next = TAILQ_NEXT(m, plinks.q);
1571 if ((m->flags & PG_MARKER) != 0)
1573 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1574 ("Fictitious page %p cannot be in active queue", m));
1575 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1576 ("Unmanaged page %p cannot be in active queue", m));
1577 if (!vm_pageout_page_lock(m, &next)) {
1583 * The count for page daemon pages is updated after checking
1584 * the page for eligibility.
1586 PCPU_INC(cnt.v_pdpages);
1589 * Check to see "how much" the page has been used.
1591 if ((m->aflags & PGA_REFERENCED) != 0) {
1592 vm_page_aflag_clear(m, PGA_REFERENCED);
1598 * Perform an unsynchronized object ref count check. While
1599 * the page lock ensures that the page is not reallocated to
1600 * another object, in particular, one with unmanaged mappings
1601 * that cannot support pmap_ts_referenced(), two races are,
1602 * nonetheless, possible:
1603 * 1) The count was transitioning to zero, but we saw a non-
1604 * zero value. pmap_ts_referenced() will return zero
1605 * because the page is not mapped.
1606 * 2) The count was transitioning to one, but we saw zero.
1607 * This race delays the detection of a new reference. At
1608 * worst, we will deactivate and reactivate the page.
1610 if (m->object->ref_count != 0)
1611 act_delta += pmap_ts_referenced(m);
1614 * Advance or decay the act_count based on recent usage.
1616 if (act_delta != 0) {
1617 m->act_count += ACT_ADVANCE + act_delta;
1618 if (m->act_count > ACT_MAX)
1619 m->act_count = ACT_MAX;
1621 m->act_count -= min(m->act_count, ACT_DECLINE);
1624 * Move this page to the tail of the active, inactive or laundry
1625 * queue depending on usage.
1627 if (m->act_count == 0) {
1628 /* Dequeue to avoid later lock recursion. */
1629 vm_page_dequeue_locked(m);
1632 * When not short for inactive pages, let dirty pages go
1633 * through the inactive queue before moving to the
1634 * laundry queues. This gives them some extra time to
1635 * be reactivated, potentially avoiding an expensive
1636 * pageout. During a page shortage, the inactive queue
1637 * is necessarily small, so we may move dirty pages
1638 * directly to the laundry queue.
1640 if (inactq_shortage <= 0)
1641 vm_page_deactivate(m);
1644 * Calling vm_page_test_dirty() here would
1645 * require acquisition of the object's write
1646 * lock. However, during a page shortage,
1647 * directing dirty pages into the laundry
1648 * queue is only an optimization and not a
1649 * requirement. Therefore, we simply rely on
1650 * the opportunistic updates to the page's
1651 * dirty field by the pmap.
1653 if (m->dirty == 0) {
1654 vm_page_deactivate(m);
1656 act_scan_laundry_weight;
1663 vm_page_requeue_locked(m);
1666 vm_pagequeue_unlock(pq);
1667 #if !defined(NO_SWAPPING)
1669 * Idle process swapout -- run once per second when we are reclaiming
1672 if (vm_swap_idle_enabled && pass > 0) {
1674 if (time_second != lsec) {
1675 vm_req_vmdaemon(VM_SWAP_IDLE);
1680 return (page_shortage <= 0);
1683 static int vm_pageout_oom_vote;
1686 * The pagedaemon threads randlomly select one to perform the
1687 * OOM. Trying to kill processes before all pagedaemons
1688 * failed to reach free target is premature.
1691 vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
1692 int starting_page_shortage)
1696 if (starting_page_shortage <= 0 || starting_page_shortage !=
1698 vmd->vmd_oom_seq = 0;
1701 if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1703 vmd->vmd_oom = FALSE;
1704 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1710 * Do not follow the call sequence until OOM condition is
1713 vmd->vmd_oom_seq = 0;
1718 vmd->vmd_oom = TRUE;
1719 old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1720 if (old_vote != vm_ndomains - 1)
1724 * The current pagedaemon thread is the last in the quorum to
1725 * start OOM. Initiate the selection and signaling of the
1728 vm_pageout_oom(VM_OOM_MEM);
1731 * After one round of OOM terror, recall our vote. On the
1732 * next pass, current pagedaemon would vote again if the low
1733 * memory condition is still there, due to vmd_oom being
1736 vmd->vmd_oom = FALSE;
1737 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1741 * The OOM killer is the page daemon's action of last resort when
1742 * memory allocation requests have been stalled for a prolonged period
1743 * of time because it cannot reclaim memory. This function computes
1744 * the approximate number of physical pages that could be reclaimed if
1745 * the specified address space is destroyed.
1747 * Private, anonymous memory owned by the address space is the
1748 * principal resource that we expect to recover after an OOM kill.
1749 * Since the physical pages mapped by the address space's COW entries
1750 * are typically shared pages, they are unlikely to be released and so
1751 * they are not counted.
1753 * To get to the point where the page daemon runs the OOM killer, its
1754 * efforts to write-back vnode-backed pages may have stalled. This
1755 * could be caused by a memory allocation deadlock in the write path
1756 * that might be resolved by an OOM kill. Therefore, physical pages
1757 * belonging to vnode-backed objects are counted, because they might
1758 * be freed without being written out first if the address space holds
1759 * the last reference to an unlinked vnode.
1761 * Similarly, physical pages belonging to OBJT_PHYS objects are
1762 * counted because the address space might hold the last reference to
1766 vm_pageout_oom_pagecount(struct vmspace *vmspace)
1769 vm_map_entry_t entry;
1773 map = &vmspace->vm_map;
1774 KASSERT(!map->system_map, ("system map"));
1775 sx_assert(&map->lock, SA_LOCKED);
1777 for (entry = map->header.next; entry != &map->header;
1778 entry = entry->next) {
1779 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
1781 obj = entry->object.vm_object;
1784 if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
1785 obj->ref_count != 1)
1787 switch (obj->type) {
1792 res += obj->resident_page_count;
1800 vm_pageout_oom(int shortage)
1802 struct proc *p, *bigproc;
1803 vm_offset_t size, bigsize;
1808 * We keep the process bigproc locked once we find it to keep anyone
1809 * from messing with it; however, there is a possibility of
1810 * deadlock if process B is bigproc and one of its child processes
1811 * attempts to propagate a signal to B while we are waiting for A's
1812 * lock while walking this list. To avoid this, we don't block on
1813 * the process lock but just skip a process if it is already locked.
1817 sx_slock(&allproc_lock);
1818 FOREACH_PROC_IN_SYSTEM(p) {
1824 * If this is a system, protected or killed process, skip it.
1826 if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
1827 P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
1828 p->p_pid == 1 || P_KILLED(p) ||
1829 (p->p_pid < 48 && swap_pager_avail != 0)) {
1834 * If the process is in a non-running type state,
1835 * don't touch it. Check all the threads individually.
1838 FOREACH_THREAD_IN_PROC(p, td) {
1840 if (!TD_ON_RUNQ(td) &&
1841 !TD_IS_RUNNING(td) &&
1842 !TD_IS_SLEEPING(td) &&
1843 !TD_IS_SUSPENDED(td) &&
1844 !TD_IS_SWAPPED(td)) {
1856 * get the process size
1858 vm = vmspace_acquire_ref(p);
1865 sx_sunlock(&allproc_lock);
1866 if (!vm_map_trylock_read(&vm->vm_map)) {
1868 sx_slock(&allproc_lock);
1872 size = vmspace_swap_count(vm);
1873 if (shortage == VM_OOM_MEM)
1874 size += vm_pageout_oom_pagecount(vm);
1875 vm_map_unlock_read(&vm->vm_map);
1877 sx_slock(&allproc_lock);
1880 * If this process is bigger than the biggest one,
1883 if (size > bigsize) {
1884 if (bigproc != NULL)
1892 sx_sunlock(&allproc_lock);
1893 if (bigproc != NULL) {
1894 if (vm_panic_on_oom != 0)
1895 panic("out of swap space");
1897 killproc(bigproc, "out of swap space");
1898 sched_nice(bigproc, PRIO_MIN);
1900 PROC_UNLOCK(bigproc);
1901 wakeup(&vm_cnt.v_free_count);
1906 vm_pageout_worker(void *arg)
1908 struct vm_domain *domain;
1912 domidx = (uintptr_t)arg;
1913 domain = &vm_dom[domidx];
1918 * XXXKIB It could be useful to bind pageout daemon threads to
1919 * the cores belonging to the domain, from which vm_page_array
1923 KASSERT(domain->vmd_segs != 0, ("domain without segments"));
1924 domain->vmd_last_active_scan = ticks;
1925 vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
1926 vm_pageout_init_marker(&domain->vmd_inacthead, PQ_INACTIVE);
1927 TAILQ_INSERT_HEAD(&domain->vmd_pagequeues[PQ_INACTIVE].pq_pl,
1928 &domain->vmd_inacthead, plinks.q);
1931 * The pageout daemon worker is never done, so loop forever.
1934 mtx_lock(&vm_page_queue_free_mtx);
1937 * Generally, after a level >= 1 scan, if there are enough
1938 * free pages to wakeup the waiters, then they are already
1939 * awake. A call to vm_page_free() during the scan awakened
1940 * them. However, in the following case, this wakeup serves
1941 * to bound the amount of time that a thread might wait.
1942 * Suppose a thread's call to vm_page_alloc() fails, but
1943 * before that thread calls VM_WAIT, enough pages are freed by
1944 * other threads to alleviate the free page shortage. The
1945 * thread will, nonetheless, wait until another page is freed
1946 * or this wakeup is performed.
1948 if (vm_pages_needed && !vm_page_count_min()) {
1949 vm_pages_needed = false;
1950 wakeup(&vm_cnt.v_free_count);
1954 * Do not clear vm_pageout_wanted until we reach our free page
1955 * target. Otherwise, we may be awakened over and over again,
1958 if (vm_pageout_wanted && target_met)
1959 vm_pageout_wanted = false;
1962 * Might the page daemon receive a wakeup call?
1964 if (vm_pageout_wanted) {
1966 * No. Either vm_pageout_wanted was set by another
1967 * thread during the previous scan, which must have
1968 * been a level 0 scan, or vm_pageout_wanted was
1969 * already set and the scan failed to free enough
1970 * pages. If we haven't yet performed a level >= 1
1971 * (page reclamation) scan, then increase the level
1972 * and scan again now. Otherwise, sleep a bit and
1975 mtx_unlock(&vm_page_queue_free_mtx);
1977 pause("psleep", hz / VM_INACT_SCAN_RATE);
1981 * Yes. Sleep until pages need to be reclaimed or
1982 * have their reference stats updated.
1984 if (mtx_sleep(&vm_pageout_wanted,
1985 &vm_page_queue_free_mtx, PDROP | PVM, "psleep",
1987 PCPU_INC(cnt.v_pdwakeups);
1993 target_met = vm_pageout_scan(domain, pass);
1998 * vm_pageout_init initialises basic pageout daemon settings.
2001 vm_pageout_init(void)
2004 * Initialize some paging parameters.
2006 vm_cnt.v_interrupt_free_min = 2;
2007 if (vm_cnt.v_page_count < 2000)
2008 vm_pageout_page_count = 8;
2011 * v_free_reserved needs to include enough for the largest
2012 * swap pager structures plus enough for any pv_entry structs
2015 if (vm_cnt.v_page_count > 1024)
2016 vm_cnt.v_free_min = 4 + (vm_cnt.v_page_count - 1024) / 200;
2018 vm_cnt.v_free_min = 4;
2019 vm_cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
2020 vm_cnt.v_interrupt_free_min;
2021 vm_cnt.v_free_reserved = vm_pageout_page_count +
2022 vm_cnt.v_pageout_free_min + (vm_cnt.v_page_count / 768);
2023 vm_cnt.v_free_severe = vm_cnt.v_free_min / 2;
2024 vm_cnt.v_free_target = 4 * vm_cnt.v_free_min + vm_cnt.v_free_reserved;
2025 vm_cnt.v_free_min += vm_cnt.v_free_reserved;
2026 vm_cnt.v_free_severe += vm_cnt.v_free_reserved;
2027 vm_cnt.v_inactive_target = (3 * vm_cnt.v_free_target) / 2;
2028 if (vm_cnt.v_inactive_target > vm_cnt.v_free_count / 3)
2029 vm_cnt.v_inactive_target = vm_cnt.v_free_count / 3;
2032 * Set the default wakeup threshold to be 10% above the minimum
2033 * page limit. This keeps the steady state out of shortfall.
2035 vm_pageout_wakeup_thresh = (vm_cnt.v_free_min / 10) * 11;
2038 * Set interval in seconds for active scan. We want to visit each
2039 * page at least once every ten minutes. This is to prevent worst
2040 * case paging behaviors with stale active LRU.
2042 if (vm_pageout_update_period == 0)
2043 vm_pageout_update_period = 600;
2045 /* XXX does not really belong here */
2046 if (vm_page_max_wired == 0)
2047 vm_page_max_wired = vm_cnt.v_free_count / 3;
2050 * Target amount of memory to move out of the laundry queue during a
2051 * background laundering. This is proportional to the amount of system
2054 vm_background_launder_target = (vm_cnt.v_free_target -
2055 vm_cnt.v_free_min) / 10;
2059 * vm_pageout is the high level pageout daemon.
2065 #ifdef VM_NUMA_ALLOC
2069 swap_pager_swap_init();
2070 error = kthread_add(vm_pageout_laundry_worker, NULL, curproc, NULL,
2071 0, 0, "laundry: dom0");
2073 panic("starting laundry for domain 0, error %d", error);
2074 #ifdef VM_NUMA_ALLOC
2075 for (i = 1; i < vm_ndomains; i++) {
2076 error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
2077 curproc, NULL, 0, 0, "dom%d", i);
2079 panic("starting pageout for domain %d, error %d\n",
2084 error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
2087 panic("starting uma_reclaim helper, error %d\n", error);
2088 vm_pageout_worker((void *)(uintptr_t)0);
2092 * Unless the free page queue lock is held by the caller, this function
2093 * should be regarded as advisory. Specifically, the caller should
2094 * not msleep() on &vm_cnt.v_free_count following this function unless
2095 * the free page queue lock is held until the msleep() is performed.
2098 pagedaemon_wakeup(void)
2101 if (!vm_pageout_wanted && curthread->td_proc != pageproc) {
2102 vm_pageout_wanted = true;
2103 wakeup(&vm_pageout_wanted);
2107 #if !defined(NO_SWAPPING)
2109 vm_req_vmdaemon(int req)
2111 static int lastrun = 0;
2113 mtx_lock(&vm_daemon_mtx);
2114 vm_pageout_req_swapout |= req;
2115 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
2116 wakeup(&vm_daemon_needed);
2119 mtx_unlock(&vm_daemon_mtx);
2125 struct rlimit rsslim;
2129 int breakout, swapout_flags, tryagain, attempts;
2131 uint64_t rsize, ravailable;
2135 mtx_lock(&vm_daemon_mtx);
2136 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
2138 racct_enable ? hz : 0
2143 swapout_flags = vm_pageout_req_swapout;
2144 vm_pageout_req_swapout = 0;
2145 mtx_unlock(&vm_daemon_mtx);
2147 swapout_procs(swapout_flags);
2150 * scan the processes for exceeding their rlimits or if
2151 * process is swapped out -- deactivate pages
2157 sx_slock(&allproc_lock);
2158 FOREACH_PROC_IN_SYSTEM(p) {
2159 vm_pindex_t limit, size;
2162 * if this is a system process or if we have already
2163 * looked at this process, skip it.
2166 if (p->p_state != PRS_NORMAL ||
2167 p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
2172 * if the process is in a non-running type state,
2176 FOREACH_THREAD_IN_PROC(p, td) {
2178 if (!TD_ON_RUNQ(td) &&
2179 !TD_IS_RUNNING(td) &&
2180 !TD_IS_SLEEPING(td) &&
2181 !TD_IS_SUSPENDED(td)) {
2195 lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
2197 qmin(rsslim.rlim_cur, rsslim.rlim_max));
2200 * let processes that are swapped out really be
2201 * swapped out set the limit to nothing (will force a
2204 if ((p->p_flag & P_INMEM) == 0)
2205 limit = 0; /* XXX */
2206 vm = vmspace_acquire_ref(p);
2213 sx_sunlock(&allproc_lock);
2215 size = vmspace_resident_count(vm);
2216 if (size >= limit) {
2217 vm_pageout_map_deactivate_pages(
2218 &vm->vm_map, limit);
2222 rsize = IDX_TO_OFF(size);
2224 racct_set(p, RACCT_RSS, rsize);
2225 ravailable = racct_get_available(p, RACCT_RSS);
2227 if (rsize > ravailable) {
2229 * Don't be overly aggressive; this
2230 * might be an innocent process,
2231 * and the limit could've been exceeded
2232 * by some memory hog. Don't try
2233 * to deactivate more than 1/4th
2234 * of process' resident set size.
2236 if (attempts <= 8) {
2237 if (ravailable < rsize -
2239 ravailable = rsize -
2243 vm_pageout_map_deactivate_pages(
2245 OFF_TO_IDX(ravailable));
2246 /* Update RSS usage after paging out. */
2247 size = vmspace_resident_count(vm);
2248 rsize = IDX_TO_OFF(size);
2250 racct_set(p, RACCT_RSS, rsize);
2252 if (rsize > ravailable)
2258 sx_slock(&allproc_lock);
2261 sx_sunlock(&allproc_lock);
2262 if (tryagain != 0 && attempts <= 10)
2266 #endif /* !defined(NO_SWAPPING) */