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 int vm_pageout_page_count = 32;
255 int vm_page_max_wired; /* XXX max # of wired pages system-wide */
256 SYSCTL_INT(_vm, OID_AUTO, max_wired,
257 CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
259 static u_int isqrt(u_int num);
260 static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
261 static int vm_pageout_launder(struct vm_domain *vmd, int launder,
263 static void vm_pageout_laundry_worker(void *arg);
264 #if !defined(NO_SWAPPING)
265 static void vm_pageout_map_deactivate_pages(vm_map_t, long);
266 static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
267 static void vm_req_vmdaemon(int req);
269 static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
272 * Initialize a dummy page for marking the caller's place in the specified
273 * paging queue. In principle, this function only needs to set the flag
274 * PG_MARKER. Nonetheless, it write busies and initializes the hold count
275 * to one as safety precautions.
278 vm_pageout_init_marker(vm_page_t marker, u_short queue)
281 bzero(marker, sizeof(*marker));
282 marker->flags = PG_MARKER;
283 marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
284 marker->queue = queue;
285 marker->hold_count = 1;
289 * vm_pageout_fallback_object_lock:
291 * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
292 * known to have failed and page queue must be either PQ_ACTIVE or
293 * PQ_INACTIVE. To avoid lock order violation, unlock the page queue
294 * while locking the vm object. Use marker page to detect page queue
295 * changes and maintain notion of next page on page queue. Return
296 * TRUE if no changes were detected, FALSE otherwise. vm object is
299 * This function depends on both the lock portion of struct vm_object
300 * and normal struct vm_page being type stable.
303 vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
305 struct vm_page marker;
306 struct vm_pagequeue *pq;
312 vm_pageout_init_marker(&marker, queue);
313 pq = vm_page_pagequeue(m);
316 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
317 vm_pagequeue_unlock(pq);
319 VM_OBJECT_WLOCK(object);
321 vm_pagequeue_lock(pq);
324 * The page's object might have changed, and/or the page might
325 * have moved from its original position in the queue. If the
326 * page's object has changed, then the caller should abandon
327 * processing the page because the wrong object lock was
328 * acquired. Use the marker's plinks.q, not the page's, to
329 * determine if the page has been moved. The state of the
330 * page's plinks.q can be indeterminate; whereas, the marker's
331 * plinks.q must be valid.
333 *next = TAILQ_NEXT(&marker, plinks.q);
334 unchanged = m->object == object &&
335 m == TAILQ_PREV(&marker, pglist, plinks.q);
336 KASSERT(!unchanged || m->queue == queue,
337 ("page %p queue %d %d", m, queue, m->queue));
338 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
343 * Lock the page while holding the page queue lock. Use marker page
344 * to detect page queue changes and maintain notion of next page on
345 * page queue. Return TRUE if no changes were detected, FALSE
346 * otherwise. The page is locked on return. The page queue lock might
347 * be dropped and reacquired.
349 * This function depends on normal struct vm_page being type stable.
352 vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
354 struct vm_page marker;
355 struct vm_pagequeue *pq;
359 vm_page_lock_assert(m, MA_NOTOWNED);
360 if (vm_page_trylock(m))
364 vm_pageout_init_marker(&marker, queue);
365 pq = vm_page_pagequeue(m);
367 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
368 vm_pagequeue_unlock(pq);
370 vm_pagequeue_lock(pq);
372 /* Page queue might have changed. */
373 *next = TAILQ_NEXT(&marker, plinks.q);
374 unchanged = m == TAILQ_PREV(&marker, pglist, plinks.q);
375 KASSERT(!unchanged || m->queue == queue,
376 ("page %p queue %d %d", m, queue, m->queue));
377 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
382 * Scan for pages at adjacent offsets within the given page's object that are
383 * eligible for laundering, form a cluster of these pages and the given page,
384 * and launder that cluster.
387 vm_pageout_cluster(vm_page_t m)
390 vm_page_t mc[2 * vm_pageout_page_count], p, pb, ps;
392 int ib, is, page_base, pageout_count;
394 vm_page_assert_locked(m);
396 VM_OBJECT_ASSERT_WLOCKED(object);
400 * We can't clean the page if it is busy or held.
402 vm_page_assert_unbusied(m);
403 KASSERT(m->hold_count == 0, ("page %p is held", m));
406 mc[vm_pageout_page_count] = pb = ps = m;
408 page_base = vm_pageout_page_count;
413 * We can cluster only if the page is not clean, busy, or held, and
414 * the page is in the laundry queue.
416 * During heavy mmap/modification loads the pageout
417 * daemon can really fragment the underlying file
418 * due to flushing pages out of order and not trying to
419 * align the clusters (which leaves sporadic out-of-order
420 * holes). To solve this problem we do the reverse scan
421 * first and attempt to align our cluster, then do a
422 * forward scan if room remains.
425 while (ib != 0 && pageout_count < vm_pageout_page_count) {
430 if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
434 vm_page_test_dirty(p);
440 if (!vm_page_in_laundry(p) ||
441 p->hold_count != 0) { /* may be undergoing I/O */
447 mc[--page_base] = pb = p;
452 * We are at an alignment boundary. Stop here, and switch
453 * directions. Do not clear ib.
455 if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
458 while (pageout_count < vm_pageout_page_count &&
459 pindex + is < object->size) {
460 if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
462 vm_page_test_dirty(p);
466 if (!vm_page_in_laundry(p) ||
467 p->hold_count != 0) { /* may be undergoing I/O */
472 mc[page_base + pageout_count] = ps = p;
478 * If we exhausted our forward scan, continue with the reverse scan
479 * when possible, even past an alignment boundary. This catches
480 * boundary conditions.
482 if (ib != 0 && pageout_count < vm_pageout_page_count)
485 return (vm_pageout_flush(&mc[page_base], pageout_count, 0, 0, NULL,
490 * vm_pageout_flush() - launder the given pages
492 * The given pages are laundered. Note that we setup for the start of
493 * I/O ( i.e. busy the page ), mark it read-only, and bump the object
494 * reference count all in here rather then in the parent. If we want
495 * the parent to do more sophisticated things we may have to change
498 * Returned runlen is the count of pages between mreq and first
499 * page after mreq with status VM_PAGER_AGAIN.
500 * *eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
501 * for any page in runlen set.
504 vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
507 vm_object_t object = mc[0]->object;
508 int pageout_status[count];
512 VM_OBJECT_ASSERT_WLOCKED(object);
515 * Initiate I/O. Bump the vm_page_t->busy counter and
516 * mark the pages read-only.
518 * We do not have to fixup the clean/dirty bits here... we can
519 * allow the pager to do it after the I/O completes.
521 * NOTE! mc[i]->dirty may be partial or fragmented due to an
522 * edge case with file fragments.
524 for (i = 0; i < count; i++) {
525 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
526 ("vm_pageout_flush: partially invalid page %p index %d/%d",
528 vm_page_sbusy(mc[i]);
529 pmap_remove_write(mc[i]);
531 vm_object_pip_add(object, count);
533 vm_pager_put_pages(object, mc, count, flags, pageout_status);
535 runlen = count - mreq;
538 for (i = 0; i < count; i++) {
539 vm_page_t mt = mc[i];
541 KASSERT(pageout_status[i] == VM_PAGER_PEND ||
542 !pmap_page_is_write_mapped(mt),
543 ("vm_pageout_flush: page %p is not write protected", mt));
544 switch (pageout_status[i]) {
547 if (vm_page_in_laundry(mt))
548 vm_page_deactivate_noreuse(mt);
556 * The page is outside the object's range. We pretend
557 * that the page out worked and clean the page, so the
558 * changes will be lost if the page is reclaimed by
563 if (vm_page_in_laundry(mt))
564 vm_page_deactivate_noreuse(mt);
570 * If the page couldn't be paged out, then reactivate
571 * it so that it doesn't clog the laundry and inactive
572 * queues. (We will try paging it out again later).
575 vm_page_activate(mt);
577 if (eio != NULL && i >= mreq && i - mreq < runlen)
581 if (i >= mreq && i - mreq < runlen)
587 * If the operation is still going, leave the page busy to
588 * block all other accesses. Also, leave the paging in
589 * progress indicator set so that we don't attempt an object
592 if (pageout_status[i] != VM_PAGER_PEND) {
593 vm_object_pip_wakeup(object);
599 return (numpagedout);
602 #if !defined(NO_SWAPPING)
604 * vm_pageout_object_deactivate_pages
606 * Deactivate enough pages to satisfy the inactive target
609 * The object and map must be locked.
612 vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
615 vm_object_t backing_object, object;
617 int act_delta, remove_mode;
619 VM_OBJECT_ASSERT_LOCKED(first_object);
620 if ((first_object->flags & OBJ_FICTITIOUS) != 0)
622 for (object = first_object;; object = backing_object) {
623 if (pmap_resident_count(pmap) <= desired)
625 VM_OBJECT_ASSERT_LOCKED(object);
626 if ((object->flags & OBJ_UNMANAGED) != 0 ||
627 object->paging_in_progress != 0)
631 if (object->shadow_count > 1)
634 * Scan the object's entire memory queue.
636 TAILQ_FOREACH(p, &object->memq, listq) {
637 if (pmap_resident_count(pmap) <= desired)
639 if (vm_page_busied(p))
641 PCPU_INC(cnt.v_pdpages);
643 if (p->wire_count != 0 || p->hold_count != 0 ||
644 !pmap_page_exists_quick(pmap, p)) {
648 act_delta = pmap_ts_referenced(p);
649 if ((p->aflags & PGA_REFERENCED) != 0) {
652 vm_page_aflag_clear(p, PGA_REFERENCED);
654 if (!vm_page_active(p) && act_delta != 0) {
656 p->act_count += act_delta;
657 } else if (vm_page_active(p)) {
658 if (act_delta == 0) {
659 p->act_count -= min(p->act_count,
661 if (!remove_mode && p->act_count == 0) {
663 vm_page_deactivate(p);
668 if (p->act_count < ACT_MAX -
670 p->act_count += ACT_ADVANCE;
673 } else if (vm_page_inactive(p))
677 if ((backing_object = object->backing_object) == NULL)
679 VM_OBJECT_RLOCK(backing_object);
680 if (object != first_object)
681 VM_OBJECT_RUNLOCK(object);
684 if (object != first_object)
685 VM_OBJECT_RUNLOCK(object);
689 * deactivate some number of pages in a map, try to do it fairly, but
690 * that is really hard to do.
693 vm_pageout_map_deactivate_pages(map, desired)
698 vm_object_t obj, bigobj;
701 if (!vm_map_trylock(map))
708 * first, search out the biggest object, and try to free pages from
711 tmpe = map->header.next;
712 while (tmpe != &map->header) {
713 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
714 obj = tmpe->object.vm_object;
715 if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
716 if (obj->shadow_count <= 1 &&
718 bigobj->resident_page_count < obj->resident_page_count)) {
720 VM_OBJECT_RUNLOCK(bigobj);
723 VM_OBJECT_RUNLOCK(obj);
726 if (tmpe->wired_count > 0)
727 nothingwired = FALSE;
731 if (bigobj != NULL) {
732 vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
733 VM_OBJECT_RUNLOCK(bigobj);
736 * Next, hunt around for other pages to deactivate. We actually
737 * do this search sort of wrong -- .text first is not the best idea.
739 tmpe = map->header.next;
740 while (tmpe != &map->header) {
741 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
743 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
744 obj = tmpe->object.vm_object;
746 VM_OBJECT_RLOCK(obj);
747 vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
748 VM_OBJECT_RUNLOCK(obj);
755 * Remove all mappings if a process is swapped out, this will free page
758 if (desired == 0 && nothingwired) {
759 pmap_remove(vm_map_pmap(map), vm_map_min(map),
765 #endif /* !defined(NO_SWAPPING) */
768 * Attempt to acquire all of the necessary locks to launder a page and
769 * then call through the clustering layer to PUTPAGES. Wait a short
770 * time for a vnode lock.
772 * Requires the page and object lock on entry, releases both before return.
773 * Returns 0 on success and an errno otherwise.
776 vm_pageout_clean(vm_page_t m, int *numpagedout)
784 vm_page_assert_locked(m);
786 VM_OBJECT_ASSERT_WLOCKED(object);
792 * The object is already known NOT to be dead. It
793 * is possible for the vget() to block the whole
794 * pageout daemon, but the new low-memory handling
795 * code should prevent it.
797 * We can't wait forever for the vnode lock, we might
798 * deadlock due to a vn_read() getting stuck in
799 * vm_wait while holding this vnode. We skip the
800 * vnode if we can't get it in a reasonable amount
803 if (object->type == OBJT_VNODE) {
806 if (vp->v_type == VREG &&
807 vn_start_write(vp, &mp, V_NOWAIT) != 0) {
813 ("vp %p with NULL v_mount", vp));
814 vm_object_reference_locked(object);
816 VM_OBJECT_WUNLOCK(object);
817 lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
818 LK_SHARED : LK_EXCLUSIVE;
819 if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
824 VM_OBJECT_WLOCK(object);
827 * While the object and page were unlocked, the page
829 * (1) moved to a different queue,
830 * (2) reallocated to a different object,
831 * (3) reallocated to a different offset, or
834 if (!vm_page_in_laundry(m) || m->object != object ||
835 m->pindex != pindex || m->dirty == 0) {
842 * The page may have been busied or held while the object
843 * and page locks were released.
845 if (vm_page_busied(m) || m->hold_count != 0) {
853 * If a page is dirty, then it is either being washed
854 * (but not yet cleaned) or it is still in the
855 * laundry. If it is still in the laundry, then we
856 * start the cleaning operation.
858 if ((*numpagedout = vm_pageout_cluster(m)) == 0)
862 VM_OBJECT_WUNLOCK(object);
865 vm_page_lock_assert(m, MA_NOTOWNED);
869 vm_object_deallocate(object);
870 vn_finished_write(mp);
877 * Attempt to launder the specified number of pages.
879 * Returns the number of pages successfully laundered.
882 vm_pageout_launder(struct vm_domain *vmd, int launder, bool in_shortfall)
884 struct vm_pagequeue *pq;
887 int act_delta, error, maxscan, numpagedout, starting_target;
889 bool pageout_ok, queue_locked;
891 starting_target = launder;
895 * Scan the laundry queue for pages eligible to be laundered. We stop
896 * once the target number of dirty pages have been laundered, or once
897 * we've reached the end of the queue. A single iteration of this loop
898 * may cause more than one page to be laundered because of clustering.
900 * maxscan ensures that we don't re-examine requeued pages. Any
901 * additional pages written as part of a cluster are subtracted from
902 * maxscan since they must be taken from the laundry queue.
904 pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
905 maxscan = pq->pq_cnt;
907 vm_pagequeue_lock(pq);
909 for (m = TAILQ_FIRST(&pq->pq_pl);
910 m != NULL && maxscan-- > 0 && launder > 0;
912 vm_pagequeue_assert_locked(pq);
913 KASSERT(queue_locked, ("unlocked laundry queue"));
914 KASSERT(vm_page_in_laundry(m),
915 ("page %p has an inconsistent queue", m));
916 next = TAILQ_NEXT(m, plinks.q);
917 if ((m->flags & PG_MARKER) != 0)
919 KASSERT((m->flags & PG_FICTITIOUS) == 0,
920 ("PG_FICTITIOUS page %p cannot be in laundry queue", m));
921 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
922 ("VPO_UNMANAGED page %p cannot be in laundry queue", m));
923 if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
928 if ((!VM_OBJECT_TRYWLOCK(object) &&
929 (!vm_pageout_fallback_object_lock(m, &next) ||
930 m->hold_count != 0)) || vm_page_busied(m)) {
931 VM_OBJECT_WUNLOCK(object);
937 * Unlock the laundry queue, invalidating the 'next' pointer.
938 * Use a marker to remember our place in the laundry queue.
940 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_laundry_marker,
942 vm_pagequeue_unlock(pq);
943 queue_locked = false;
946 * Invalid pages can be easily freed. They cannot be
947 * mapped; vm_page_free() asserts this.
953 * If the page has been referenced and the object is not dead,
954 * reactivate or requeue the page depending on whether the
957 if ((m->aflags & PGA_REFERENCED) != 0) {
958 vm_page_aflag_clear(m, PGA_REFERENCED);
962 if (object->ref_count != 0)
963 act_delta += pmap_ts_referenced(m);
965 KASSERT(!pmap_page_is_mapped(m),
966 ("page %p is mapped", m));
968 if (act_delta != 0) {
969 if (object->ref_count != 0) {
970 PCPU_INC(cnt.v_reactivated);
974 * Increase the activation count if the page
975 * was referenced while in the laundry queue.
976 * This makes it less likely that the page will
977 * be returned prematurely to the inactive
980 m->act_count += act_delta + ACT_ADVANCE;
983 * If this was a background laundering, count
984 * activated pages towards our target. The
985 * purpose of background laundering is to ensure
986 * that pages are eventually cycled through the
987 * laundry queue, and an activation is a valid
993 } else if ((object->flags & OBJ_DEAD) == 0)
998 * If the page appears to be clean at the machine-independent
999 * layer, then remove all of its mappings from the pmap in
1000 * anticipation of freeing it. If, however, any of the page's
1001 * mappings allow write access, then the page may still be
1002 * modified until the last of those mappings are removed.
1004 if (object->ref_count != 0) {
1005 vm_page_test_dirty(m);
1011 * Clean pages are freed, and dirty pages are paged out unless
1012 * they belong to a dead object. Requeueing dirty pages from
1013 * dead objects is pointless, as they are being paged out and
1014 * freed by the thread that destroyed the object.
1016 if (m->dirty == 0) {
1019 PCPU_INC(cnt.v_dfree);
1020 } else if ((object->flags & OBJ_DEAD) == 0) {
1021 if (object->type != OBJT_SWAP &&
1022 object->type != OBJT_DEFAULT)
1024 else if (disable_swap_pageouts)
1030 vm_pagequeue_lock(pq);
1031 queue_locked = true;
1032 vm_page_requeue_locked(m);
1037 * Form a cluster with adjacent, dirty pages from the
1038 * same object, and page out that entire cluster.
1040 * The adjacent, dirty pages must also be in the
1041 * laundry. However, their mappings are not checked
1042 * for new references. Consequently, a recently
1043 * referenced page may be paged out. However, that
1044 * page will not be prematurely reclaimed. After page
1045 * out, the page will be placed in the inactive queue,
1046 * where any new references will be detected and the
1049 error = vm_pageout_clean(m, &numpagedout);
1051 launder -= numpagedout;
1052 maxscan -= numpagedout - 1;
1053 } else if (error == EDEADLK) {
1054 pageout_lock_miss++;
1061 VM_OBJECT_WUNLOCK(object);
1063 if (!queue_locked) {
1064 vm_pagequeue_lock(pq);
1065 queue_locked = true;
1067 next = TAILQ_NEXT(&vmd->vmd_laundry_marker, plinks.q);
1068 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_laundry_marker, plinks.q);
1070 vm_pagequeue_unlock(pq);
1073 * Wakeup the sync daemon if we skipped a vnode in a writeable object
1074 * and we didn't launder enough pages.
1076 if (vnodes_skipped > 0 && launder > 0)
1077 (void)speedup_syncer();
1079 return (starting_target - launder);
1083 * Compute the integer square root.
1088 u_int bit, root, tmp;
1090 bit = 1u << ((NBBY * sizeof(u_int)) - 2);
1107 * Perform the work of the laundry thread: periodically wake up and determine
1108 * whether any pages need to be laundered. If so, determine the number of pages
1109 * that need to be laundered, and launder them.
1112 vm_pageout_laundry_worker(void *arg)
1114 struct vm_domain *domain;
1115 struct vm_pagequeue *pq;
1116 uint64_t nclean, ndirty;
1117 u_int last_launder, wakeups;
1118 int domidx, last_target, launder, shortfall, shortfall_cycle, target;
1121 domidx = (uintptr_t)arg;
1122 domain = &vm_dom[domidx];
1123 pq = &domain->vmd_pagequeues[PQ_LAUNDRY];
1124 KASSERT(domain->vmd_segs != 0, ("domain without segments"));
1125 vm_pageout_init_marker(&domain->vmd_laundry_marker, PQ_LAUNDRY);
1128 in_shortfall = false;
1129 shortfall_cycle = 0;
1134 * The pageout laundry worker is never done, so loop forever.
1137 KASSERT(target >= 0, ("negative target %d", target));
1138 KASSERT(shortfall_cycle >= 0,
1139 ("negative cycle %d", shortfall_cycle));
1141 wakeups = VM_METER_PCPU_CNT(v_pdwakeups);
1144 * First determine whether we need to launder pages to meet a
1145 * shortage of free pages.
1147 if (shortfall > 0) {
1148 in_shortfall = true;
1149 shortfall_cycle = VM_LAUNDER_RATE / VM_INACT_SCAN_RATE;
1151 } else if (!in_shortfall)
1153 else if (shortfall_cycle == 0 || vm_laundry_target() <= 0) {
1155 * We recently entered shortfall and began laundering
1156 * pages. If we have completed that laundering run
1157 * (and we are no longer in shortfall) or we have met
1158 * our laundry target through other activity, then we
1159 * can stop laundering pages.
1161 in_shortfall = false;
1165 last_launder = wakeups;
1166 launder = target / shortfall_cycle--;
1170 * There's no immediate need to launder any pages; see if we
1171 * meet the conditions to perform background laundering:
1173 * 1. The ratio of dirty to clean inactive pages exceeds the
1174 * background laundering threshold and the pagedaemon has
1175 * been woken up to reclaim pages since our last
1177 * 2. we haven't yet reached the target of the current
1178 * background laundering run.
1180 * The background laundering threshold is not a constant.
1181 * Instead, it is a slowly growing function of the number of
1182 * page daemon wakeups since the last laundering. Thus, as the
1183 * ratio of dirty to clean inactive pages grows, the amount of
1184 * memory pressure required to trigger laundering decreases.
1187 nclean = vm_cnt.v_inactive_count + vm_cnt.v_free_count;
1188 ndirty = vm_cnt.v_laundry_count;
1189 if (target == 0 && wakeups != last_launder &&
1190 ndirty * isqrt(wakeups - last_launder) >= nclean) {
1191 target = vm_background_launder_target;
1195 * We have a non-zero background laundering target. If we've
1196 * laundered up to our maximum without observing a page daemon
1197 * wakeup, just stop. This is a safety belt that ensures we
1198 * don't launder an excessive amount if memory pressure is low
1199 * and the ratio of dirty to clean pages is large. Otherwise,
1200 * proceed at the background laundering rate.
1203 if (wakeups != last_launder) {
1204 last_launder = wakeups;
1205 last_target = target;
1206 } else if (last_target - target >=
1207 vm_background_launder_max * PAGE_SIZE / 1024) {
1210 launder = vm_background_launder_rate * PAGE_SIZE / 1024;
1211 launder /= VM_LAUNDER_RATE;
1212 if (launder > target)
1219 * Because of I/O clustering, the number of laundered
1220 * pages could exceed "target" by the maximum size of
1221 * a cluster minus one.
1223 target -= min(vm_pageout_launder(domain, launder,
1224 in_shortfall), target);
1225 pause("laundp", hz / VM_LAUNDER_RATE);
1229 * If we're not currently laundering pages and the page daemon
1230 * hasn't posted a new request, sleep until the page daemon
1233 vm_pagequeue_lock(pq);
1234 if (target == 0 && vm_laundry_request == VM_LAUNDRY_IDLE)
1235 (void)mtx_sleep(&vm_laundry_request,
1236 vm_pagequeue_lockptr(pq), PVM, "launds", 0);
1239 * If the pagedaemon has indicated that it's in shortfall, start
1240 * a shortfall laundering unless we're already in the middle of
1241 * one. This may preempt a background laundering.
1243 if (vm_laundry_request == VM_LAUNDRY_SHORTFALL &&
1244 (!in_shortfall || shortfall_cycle == 0)) {
1245 shortfall = vm_laundry_target() + vm_pageout_deficit;
1251 vm_laundry_request = VM_LAUNDRY_IDLE;
1252 vm_pagequeue_unlock(pq);
1257 * vm_pageout_scan does the dirty work for the pageout daemon.
1259 * pass == 0: Update active LRU/deactivate pages
1260 * pass >= 1: Free inactive pages
1262 * Returns true if pass was zero or enough pages were freed by the inactive
1263 * queue scan to meet the target.
1266 vm_pageout_scan(struct vm_domain *vmd, int pass)
1269 struct vm_pagequeue *pq;
1272 int act_delta, addl_page_shortage, deficit, inactq_shortage, maxscan;
1273 int page_shortage, scan_tick, scanned, starting_page_shortage;
1274 boolean_t queue_locked;
1277 * If we need to reclaim memory ask kernel caches to return
1278 * some. We rate limit to avoid thrashing.
1280 if (vmd == &vm_dom[0] && pass > 0 &&
1281 (time_uptime - lowmem_uptime) >= lowmem_period) {
1283 * Decrease registered cache sizes.
1285 SDT_PROBE0(vm, , , vm__lowmem_scan);
1286 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_PAGES);
1288 * We do this explicitly after the caches have been
1292 lowmem_uptime = time_uptime;
1296 * The addl_page_shortage is the number of temporarily
1297 * stuck pages in the inactive queue. In other words, the
1298 * number of pages from the inactive count that should be
1299 * discounted in setting the target for the active queue scan.
1301 addl_page_shortage = 0;
1304 * Calculate the number of pages that we want to free. This number
1305 * can be negative if many pages are freed between the wakeup call to
1306 * the page daemon and this calculation.
1309 deficit = atomic_readandclear_int(&vm_pageout_deficit);
1310 page_shortage = vm_paging_target() + deficit;
1312 page_shortage = deficit = 0;
1313 starting_page_shortage = page_shortage;
1316 * Start scanning the inactive queue for pages that we can free. The
1317 * scan will stop when we reach the target or we have scanned the
1318 * entire queue. (Note that m->act_count is not used to make
1319 * decisions for the inactive queue, only for the active queue.)
1321 pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
1322 maxscan = pq->pq_cnt;
1323 vm_pagequeue_lock(pq);
1324 queue_locked = TRUE;
1325 for (m = TAILQ_FIRST(&pq->pq_pl);
1326 m != NULL && maxscan-- > 0 && page_shortage > 0;
1328 vm_pagequeue_assert_locked(pq);
1329 KASSERT(queue_locked, ("unlocked inactive queue"));
1330 KASSERT(vm_page_inactive(m), ("Inactive queue %p", m));
1332 PCPU_INC(cnt.v_pdpages);
1333 next = TAILQ_NEXT(m, plinks.q);
1338 if (m->flags & PG_MARKER)
1341 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1342 ("Fictitious page %p cannot be in inactive queue", m));
1343 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1344 ("Unmanaged page %p cannot be in inactive queue", m));
1347 * The page or object lock acquisitions fail if the
1348 * page was removed from the queue or moved to a
1349 * different position within the queue. In either
1350 * case, addl_page_shortage should not be incremented.
1352 if (!vm_pageout_page_lock(m, &next))
1354 else if (m->hold_count != 0) {
1356 * Held pages are essentially stuck in the
1357 * queue. So, they ought to be discounted
1358 * from the inactive count. See the
1359 * calculation of inactq_shortage before the
1360 * loop over the active queue below.
1362 addl_page_shortage++;
1366 if (!VM_OBJECT_TRYWLOCK(object)) {
1367 if (!vm_pageout_fallback_object_lock(m, &next))
1369 else if (m->hold_count != 0) {
1370 addl_page_shortage++;
1374 if (vm_page_busied(m)) {
1376 * Don't mess with busy pages. Leave them at
1377 * the front of the queue. Most likely, they
1378 * are being paged out and will leave the
1379 * queue shortly after the scan finishes. So,
1380 * they ought to be discounted from the
1383 addl_page_shortage++;
1385 VM_OBJECT_WUNLOCK(object);
1390 KASSERT(m->hold_count == 0, ("Held page %p", m));
1393 * Dequeue the inactive page and unlock the inactive page
1394 * queue, invalidating the 'next' pointer. Dequeueing the
1395 * page here avoids a later reacquisition (and release) of
1396 * the inactive page queue lock when vm_page_activate(),
1397 * vm_page_free(), or vm_page_launder() is called. Use a
1398 * marker to remember our place in the inactive queue.
1400 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
1401 vm_page_dequeue_locked(m);
1402 vm_pagequeue_unlock(pq);
1403 queue_locked = FALSE;
1406 * Invalid pages can be easily freed. They cannot be
1407 * mapped, vm_page_free() asserts this.
1413 * If the page has been referenced and the object is not dead,
1414 * reactivate or requeue the page depending on whether the
1417 if ((m->aflags & PGA_REFERENCED) != 0) {
1418 vm_page_aflag_clear(m, PGA_REFERENCED);
1422 if (object->ref_count != 0) {
1423 act_delta += pmap_ts_referenced(m);
1425 KASSERT(!pmap_page_is_mapped(m),
1426 ("vm_pageout_scan: page %p is mapped", m));
1428 if (act_delta != 0) {
1429 if (object->ref_count != 0) {
1430 PCPU_INC(cnt.v_reactivated);
1431 vm_page_activate(m);
1434 * Increase the activation count if the page
1435 * was referenced while in the inactive queue.
1436 * This makes it less likely that the page will
1437 * be returned prematurely to the inactive
1440 m->act_count += act_delta + ACT_ADVANCE;
1442 } else if ((object->flags & OBJ_DEAD) == 0) {
1443 vm_pagequeue_lock(pq);
1444 queue_locked = TRUE;
1445 m->queue = PQ_INACTIVE;
1446 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
1447 vm_pagequeue_cnt_inc(pq);
1453 * If the page appears to be clean at the machine-independent
1454 * layer, then remove all of its mappings from the pmap in
1455 * anticipation of freeing it. If, however, any of the page's
1456 * mappings allow write access, then the page may still be
1457 * modified until the last of those mappings are removed.
1459 if (object->ref_count != 0) {
1460 vm_page_test_dirty(m);
1466 * Clean pages can be freed, but dirty pages must be sent back
1467 * to the laundry, unless they belong to a dead object.
1468 * Requeueing dirty pages from dead objects is pointless, as
1469 * they are being paged out and freed by the thread that
1470 * destroyed the object.
1472 if (m->dirty == 0) {
1475 PCPU_INC(cnt.v_dfree);
1477 } else if ((object->flags & OBJ_DEAD) == 0)
1481 VM_OBJECT_WUNLOCK(object);
1482 if (!queue_locked) {
1483 vm_pagequeue_lock(pq);
1484 queue_locked = TRUE;
1486 next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1487 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
1489 vm_pagequeue_unlock(pq);
1492 * Wake up the laundry thread so that it can perform any needed
1493 * laundering. If we didn't meet our target, we're in shortfall and
1494 * need to launder more aggressively.
1496 if (vm_laundry_request == VM_LAUNDRY_IDLE &&
1497 starting_page_shortage > 0) {
1498 pq = &vm_dom[0].vmd_pagequeues[PQ_LAUNDRY];
1499 vm_pagequeue_lock(pq);
1500 if (page_shortage > 0) {
1501 vm_laundry_request = VM_LAUNDRY_SHORTFALL;
1502 PCPU_INC(cnt.v_pdshortfalls);
1503 } else if (vm_laundry_request != VM_LAUNDRY_SHORTFALL)
1504 vm_laundry_request = VM_LAUNDRY_BACKGROUND;
1505 wakeup(&vm_laundry_request);
1506 vm_pagequeue_unlock(pq);
1509 #if !defined(NO_SWAPPING)
1511 * Wakeup the swapout daemon if we didn't free the targeted number of
1514 if (vm_swap_enabled && page_shortage > 0)
1515 vm_req_vmdaemon(VM_SWAP_NORMAL);
1519 * If the inactive queue scan fails repeatedly to meet its
1520 * target, kill the largest process.
1522 vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
1525 * Compute the number of pages we want to try to move from the
1526 * active queue to either the inactive or laundry queue.
1528 * When scanning active pages, we make clean pages count more heavily
1529 * towards the page shortage than dirty pages. This is because dirty
1530 * pages must be laundered before they can be reused and thus have less
1531 * utility when attempting to quickly alleviate a shortage. However,
1532 * this weighting also causes the scan to deactivate dirty pages more
1533 * more aggressively, improving the effectiveness of clustering and
1534 * ensuring that they can eventually be reused.
1536 inactq_shortage = vm_cnt.v_inactive_target - (vm_cnt.v_inactive_count +
1537 vm_cnt.v_laundry_count / act_scan_laundry_weight) +
1538 vm_paging_target() + deficit + addl_page_shortage;
1539 page_shortage *= act_scan_laundry_weight;
1541 pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1542 vm_pagequeue_lock(pq);
1543 maxscan = pq->pq_cnt;
1546 * If we're just idle polling attempt to visit every
1547 * active page within 'update_period' seconds.
1550 if (vm_pageout_update_period != 0) {
1551 min_scan = pq->pq_cnt;
1552 min_scan *= scan_tick - vmd->vmd_last_active_scan;
1553 min_scan /= hz * vm_pageout_update_period;
1556 if (min_scan > 0 || (inactq_shortage > 0 && maxscan > 0))
1557 vmd->vmd_last_active_scan = scan_tick;
1560 * Scan the active queue for pages that can be deactivated. Update
1561 * the per-page activity counter and use it to identify deactivation
1562 * candidates. Held pages may be deactivated.
1564 for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
1565 min_scan || (inactq_shortage > 0 && scanned < maxscan)); m = next,
1567 KASSERT(m->queue == PQ_ACTIVE,
1568 ("vm_pageout_scan: page %p isn't active", m));
1569 next = TAILQ_NEXT(m, plinks.q);
1570 if ((m->flags & PG_MARKER) != 0)
1572 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1573 ("Fictitious page %p cannot be in active queue", m));
1574 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1575 ("Unmanaged page %p cannot be in active queue", m));
1576 if (!vm_pageout_page_lock(m, &next)) {
1582 * The count for page daemon pages is updated after checking
1583 * the page for eligibility.
1585 PCPU_INC(cnt.v_pdpages);
1588 * Check to see "how much" the page has been used.
1590 if ((m->aflags & PGA_REFERENCED) != 0) {
1591 vm_page_aflag_clear(m, PGA_REFERENCED);
1597 * Perform an unsynchronized object ref count check. While
1598 * the page lock ensures that the page is not reallocated to
1599 * another object, in particular, one with unmanaged mappings
1600 * that cannot support pmap_ts_referenced(), two races are,
1601 * nonetheless, possible:
1602 * 1) The count was transitioning to zero, but we saw a non-
1603 * zero value. pmap_ts_referenced() will return zero
1604 * because the page is not mapped.
1605 * 2) The count was transitioning to one, but we saw zero.
1606 * This race delays the detection of a new reference. At
1607 * worst, we will deactivate and reactivate the page.
1609 if (m->object->ref_count != 0)
1610 act_delta += pmap_ts_referenced(m);
1613 * Advance or decay the act_count based on recent usage.
1615 if (act_delta != 0) {
1616 m->act_count += ACT_ADVANCE + act_delta;
1617 if (m->act_count > ACT_MAX)
1618 m->act_count = ACT_MAX;
1620 m->act_count -= min(m->act_count, ACT_DECLINE);
1623 * Move this page to the tail of the active, inactive or laundry
1624 * queue depending on usage.
1626 if (m->act_count == 0) {
1627 /* Dequeue to avoid later lock recursion. */
1628 vm_page_dequeue_locked(m);
1631 * When not short for inactive pages, let dirty pages go
1632 * through the inactive queue before moving to the
1633 * laundry queues. This gives them some extra time to
1634 * be reactivated, potentially avoiding an expensive
1635 * pageout. During a page shortage, the inactive queue
1636 * is necessarily small, so we may move dirty pages
1637 * directly to the laundry queue.
1639 if (inactq_shortage <= 0)
1640 vm_page_deactivate(m);
1643 * Calling vm_page_test_dirty() here would
1644 * require acquisition of the object's write
1645 * lock. However, during a page shortage,
1646 * directing dirty pages into the laundry
1647 * queue is only an optimization and not a
1648 * requirement. Therefore, we simply rely on
1649 * the opportunistic updates to the page's
1650 * dirty field by the pmap.
1652 if (m->dirty == 0) {
1653 vm_page_deactivate(m);
1655 act_scan_laundry_weight;
1662 vm_page_requeue_locked(m);
1665 vm_pagequeue_unlock(pq);
1666 #if !defined(NO_SWAPPING)
1668 * Idle process swapout -- run once per second.
1670 if (vm_swap_idle_enabled) {
1672 if (time_second != lsec) {
1673 vm_req_vmdaemon(VM_SWAP_IDLE);
1678 return (page_shortage <= 0);
1681 static int vm_pageout_oom_vote;
1684 * The pagedaemon threads randlomly select one to perform the
1685 * OOM. Trying to kill processes before all pagedaemons
1686 * failed to reach free target is premature.
1689 vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
1690 int starting_page_shortage)
1694 if (starting_page_shortage <= 0 || starting_page_shortage !=
1696 vmd->vmd_oom_seq = 0;
1699 if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1701 vmd->vmd_oom = FALSE;
1702 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1708 * Do not follow the call sequence until OOM condition is
1711 vmd->vmd_oom_seq = 0;
1716 vmd->vmd_oom = TRUE;
1717 old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1718 if (old_vote != vm_ndomains - 1)
1722 * The current pagedaemon thread is the last in the quorum to
1723 * start OOM. Initiate the selection and signaling of the
1726 vm_pageout_oom(VM_OOM_MEM);
1729 * After one round of OOM terror, recall our vote. On the
1730 * next pass, current pagedaemon would vote again if the low
1731 * memory condition is still there, due to vmd_oom being
1734 vmd->vmd_oom = FALSE;
1735 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1739 * The OOM killer is the page daemon's action of last resort when
1740 * memory allocation requests have been stalled for a prolonged period
1741 * of time because it cannot reclaim memory. This function computes
1742 * the approximate number of physical pages that could be reclaimed if
1743 * the specified address space is destroyed.
1745 * Private, anonymous memory owned by the address space is the
1746 * principal resource that we expect to recover after an OOM kill.
1747 * Since the physical pages mapped by the address space's COW entries
1748 * are typically shared pages, they are unlikely to be released and so
1749 * they are not counted.
1751 * To get to the point where the page daemon runs the OOM killer, its
1752 * efforts to write-back vnode-backed pages may have stalled. This
1753 * could be caused by a memory allocation deadlock in the write path
1754 * that might be resolved by an OOM kill. Therefore, physical pages
1755 * belonging to vnode-backed objects are counted, because they might
1756 * be freed without being written out first if the address space holds
1757 * the last reference to an unlinked vnode.
1759 * Similarly, physical pages belonging to OBJT_PHYS objects are
1760 * counted because the address space might hold the last reference to
1764 vm_pageout_oom_pagecount(struct vmspace *vmspace)
1767 vm_map_entry_t entry;
1771 map = &vmspace->vm_map;
1772 KASSERT(!map->system_map, ("system map"));
1773 sx_assert(&map->lock, SA_LOCKED);
1775 for (entry = map->header.next; entry != &map->header;
1776 entry = entry->next) {
1777 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
1779 obj = entry->object.vm_object;
1782 if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
1783 obj->ref_count != 1)
1785 switch (obj->type) {
1790 res += obj->resident_page_count;
1798 vm_pageout_oom(int shortage)
1800 struct proc *p, *bigproc;
1801 vm_offset_t size, bigsize;
1807 * We keep the process bigproc locked once we find it to keep anyone
1808 * from messing with it; however, there is a possibility of
1809 * deadlock if process B is bigproc and one of it's child processes
1810 * attempts to propagate a signal to B while we are waiting for A's
1811 * lock while walking this list. To avoid this, we don't block on
1812 * the process lock but just skip a process if it is already locked.
1816 sx_slock(&allproc_lock);
1817 FOREACH_PROC_IN_SYSTEM(p) {
1821 * If this is a system, protected or killed process, skip it.
1823 if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
1824 P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
1825 p->p_pid == 1 || P_KILLED(p) ||
1826 (p->p_pid < 48 && swap_pager_avail != 0)) {
1831 * If the process is in a non-running type state,
1832 * don't touch it. Check all the threads individually.
1835 FOREACH_THREAD_IN_PROC(p, td) {
1837 if (!TD_ON_RUNQ(td) &&
1838 !TD_IS_RUNNING(td) &&
1839 !TD_IS_SLEEPING(td) &&
1840 !TD_IS_SUSPENDED(td) &&
1841 !TD_IS_SWAPPED(td)) {
1853 * get the process size
1855 vm = vmspace_acquire_ref(p);
1862 sx_sunlock(&allproc_lock);
1863 if (!vm_map_trylock_read(&vm->vm_map)) {
1865 sx_slock(&allproc_lock);
1869 size = vmspace_swap_count(vm);
1870 if (shortage == VM_OOM_MEM)
1871 size += vm_pageout_oom_pagecount(vm);
1872 vm_map_unlock_read(&vm->vm_map);
1874 sx_slock(&allproc_lock);
1877 * If this process is bigger than the biggest one,
1880 if (size > bigsize) {
1881 if (bigproc != NULL)
1889 sx_sunlock(&allproc_lock);
1890 if (bigproc != NULL) {
1891 if (vm_panic_on_oom != 0)
1892 panic("out of swap space");
1894 killproc(bigproc, "out of swap space");
1895 sched_nice(bigproc, PRIO_MIN);
1897 PROC_UNLOCK(bigproc);
1898 wakeup(&vm_cnt.v_free_count);
1903 vm_pageout_worker(void *arg)
1905 struct vm_domain *domain;
1909 domidx = (uintptr_t)arg;
1910 domain = &vm_dom[domidx];
1915 * XXXKIB It could be useful to bind pageout daemon threads to
1916 * the cores belonging to the domain, from which vm_page_array
1920 KASSERT(domain->vmd_segs != 0, ("domain without segments"));
1921 domain->vmd_last_active_scan = ticks;
1922 vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
1923 vm_pageout_init_marker(&domain->vmd_inacthead, PQ_INACTIVE);
1924 TAILQ_INSERT_HEAD(&domain->vmd_pagequeues[PQ_INACTIVE].pq_pl,
1925 &domain->vmd_inacthead, plinks.q);
1928 * The pageout daemon worker is never done, so loop forever.
1931 mtx_lock(&vm_page_queue_free_mtx);
1934 * Generally, after a level >= 1 scan, if there are enough
1935 * free pages to wakeup the waiters, then they are already
1936 * awake. A call to vm_page_free() during the scan awakened
1937 * them. However, in the following case, this wakeup serves
1938 * to bound the amount of time that a thread might wait.
1939 * Suppose a thread's call to vm_page_alloc() fails, but
1940 * before that thread calls VM_WAIT, enough pages are freed by
1941 * other threads to alleviate the free page shortage. The
1942 * thread will, nonetheless, wait until another page is freed
1943 * or this wakeup is performed.
1945 if (vm_pages_needed && !vm_page_count_min()) {
1946 vm_pages_needed = false;
1947 wakeup(&vm_cnt.v_free_count);
1951 * Do not clear vm_pageout_wanted until we reach our free page
1952 * target. Otherwise, we may be awakened over and over again,
1955 if (vm_pageout_wanted && target_met)
1956 vm_pageout_wanted = false;
1959 * Might the page daemon receive a wakeup call?
1961 if (vm_pageout_wanted) {
1963 * No. Either vm_pageout_wanted was set by another
1964 * thread during the previous scan, which must have
1965 * been a level 0 scan, or vm_pageout_wanted was
1966 * already set and the scan failed to free enough
1967 * pages. If we haven't yet performed a level >= 1
1968 * (page reclamation) scan, then increase the level
1969 * and scan again now. Otherwise, sleep a bit and
1972 mtx_unlock(&vm_page_queue_free_mtx);
1974 pause("psleep", hz / VM_INACT_SCAN_RATE);
1978 * Yes. Sleep until pages need to be reclaimed or
1979 * have their reference stats updated.
1981 if (mtx_sleep(&vm_pageout_wanted,
1982 &vm_page_queue_free_mtx, PDROP | PVM, "psleep",
1984 PCPU_INC(cnt.v_pdwakeups);
1990 target_met = vm_pageout_scan(domain, pass);
1995 * vm_pageout_init initialises basic pageout daemon settings.
1998 vm_pageout_init(void)
2001 * Initialize some paging parameters.
2003 vm_cnt.v_interrupt_free_min = 2;
2004 if (vm_cnt.v_page_count < 2000)
2005 vm_pageout_page_count = 8;
2008 * v_free_reserved needs to include enough for the largest
2009 * swap pager structures plus enough for any pv_entry structs
2012 if (vm_cnt.v_page_count > 1024)
2013 vm_cnt.v_free_min = 4 + (vm_cnt.v_page_count - 1024) / 200;
2015 vm_cnt.v_free_min = 4;
2016 vm_cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
2017 vm_cnt.v_interrupt_free_min;
2018 vm_cnt.v_free_reserved = vm_pageout_page_count +
2019 vm_cnt.v_pageout_free_min + (vm_cnt.v_page_count / 768);
2020 vm_cnt.v_free_severe = vm_cnt.v_free_min / 2;
2021 vm_cnt.v_free_target = 4 * vm_cnt.v_free_min + vm_cnt.v_free_reserved;
2022 vm_cnt.v_free_min += vm_cnt.v_free_reserved;
2023 vm_cnt.v_free_severe += vm_cnt.v_free_reserved;
2024 vm_cnt.v_inactive_target = (3 * vm_cnt.v_free_target) / 2;
2025 if (vm_cnt.v_inactive_target > vm_cnt.v_free_count / 3)
2026 vm_cnt.v_inactive_target = vm_cnt.v_free_count / 3;
2029 * Set the default wakeup threshold to be 10% above the minimum
2030 * page limit. This keeps the steady state out of shortfall.
2032 vm_pageout_wakeup_thresh = (vm_cnt.v_free_min / 10) * 11;
2035 * Set interval in seconds for active scan. We want to visit each
2036 * page at least once every ten minutes. This is to prevent worst
2037 * case paging behaviors with stale active LRU.
2039 if (vm_pageout_update_period == 0)
2040 vm_pageout_update_period = 600;
2042 /* XXX does not really belong here */
2043 if (vm_page_max_wired == 0)
2044 vm_page_max_wired = vm_cnt.v_free_count / 3;
2047 * Target amount of memory to move out of the laundry queue during a
2048 * background laundering. This is proportional to the amount of system
2051 vm_background_launder_target = (vm_cnt.v_free_target -
2052 vm_cnt.v_free_min) / 10;
2056 * vm_pageout is the high level pageout daemon.
2062 #ifdef VM_NUMA_ALLOC
2066 swap_pager_swap_init();
2067 error = kthread_add(vm_pageout_laundry_worker, NULL, curproc, NULL,
2068 0, 0, "laundry: dom0");
2070 panic("starting laundry for domain 0, error %d", error);
2071 #ifdef VM_NUMA_ALLOC
2072 for (i = 1; i < vm_ndomains; i++) {
2073 error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
2074 curproc, NULL, 0, 0, "dom%d", i);
2076 panic("starting pageout for domain %d, error %d\n",
2081 error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
2084 panic("starting uma_reclaim helper, error %d\n", error);
2085 vm_pageout_worker((void *)(uintptr_t)0);
2089 * Unless the free page queue lock is held by the caller, this function
2090 * should be regarded as advisory. Specifically, the caller should
2091 * not msleep() on &vm_cnt.v_free_count following this function unless
2092 * the free page queue lock is held until the msleep() is performed.
2095 pagedaemon_wakeup(void)
2098 if (!vm_pageout_wanted && curthread->td_proc != pageproc) {
2099 vm_pageout_wanted = true;
2100 wakeup(&vm_pageout_wanted);
2104 #if !defined(NO_SWAPPING)
2106 vm_req_vmdaemon(int req)
2108 static int lastrun = 0;
2110 mtx_lock(&vm_daemon_mtx);
2111 vm_pageout_req_swapout |= req;
2112 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
2113 wakeup(&vm_daemon_needed);
2116 mtx_unlock(&vm_daemon_mtx);
2122 struct rlimit rsslim;
2126 int breakout, swapout_flags, tryagain, attempts;
2128 uint64_t rsize, ravailable;
2132 mtx_lock(&vm_daemon_mtx);
2133 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
2135 racct_enable ? hz : 0
2140 swapout_flags = vm_pageout_req_swapout;
2141 vm_pageout_req_swapout = 0;
2142 mtx_unlock(&vm_daemon_mtx);
2144 swapout_procs(swapout_flags);
2147 * scan the processes for exceeding their rlimits or if
2148 * process is swapped out -- deactivate pages
2154 sx_slock(&allproc_lock);
2155 FOREACH_PROC_IN_SYSTEM(p) {
2156 vm_pindex_t limit, size;
2159 * if this is a system process or if we have already
2160 * looked at this process, skip it.
2163 if (p->p_state != PRS_NORMAL ||
2164 p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
2169 * if the process is in a non-running type state,
2173 FOREACH_THREAD_IN_PROC(p, td) {
2175 if (!TD_ON_RUNQ(td) &&
2176 !TD_IS_RUNNING(td) &&
2177 !TD_IS_SLEEPING(td) &&
2178 !TD_IS_SUSPENDED(td)) {
2192 lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
2194 qmin(rsslim.rlim_cur, rsslim.rlim_max));
2197 * let processes that are swapped out really be
2198 * swapped out set the limit to nothing (will force a
2201 if ((p->p_flag & P_INMEM) == 0)
2202 limit = 0; /* XXX */
2203 vm = vmspace_acquire_ref(p);
2210 sx_sunlock(&allproc_lock);
2212 size = vmspace_resident_count(vm);
2213 if (size >= limit) {
2214 vm_pageout_map_deactivate_pages(
2215 &vm->vm_map, limit);
2216 size = vmspace_resident_count(vm);
2220 rsize = IDX_TO_OFF(size);
2222 if (p->p_state == PRS_NORMAL)
2223 racct_set(p, RACCT_RSS, rsize);
2224 ravailable = racct_get_available(p, RACCT_RSS);
2226 if (rsize > ravailable) {
2228 * Don't be overly aggressive; this
2229 * might be an innocent process,
2230 * and the limit could've been exceeded
2231 * by some memory hog. Don't try
2232 * to deactivate more than 1/4th
2233 * of process' resident set size.
2235 if (attempts <= 8) {
2236 if (ravailable < rsize -
2238 ravailable = rsize -
2242 vm_pageout_map_deactivate_pages(
2244 OFF_TO_IDX(ravailable));
2245 /* Update RSS usage after paging out. */
2246 size = vmspace_resident_count(vm);
2247 rsize = IDX_TO_OFF(size);
2249 if (p->p_state == PRS_NORMAL)
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) */