2 * SPDX-License-Identifier: BSD-4-Clause
4 * Copyright (c) 1991 Regents of the University of California.
6 * Copyright (c) 1994 John S. Dyson
8 * Copyright (c) 1994 David Greenman
10 * Copyright (c) 2005 Yahoo! Technologies Norway AS
11 * All rights reserved.
13 * This code is derived from software contributed to Berkeley by
14 * The Mach Operating System project at Carnegie-Mellon University.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
24 * 3. All advertising materials mentioning features or use of this software
25 * must display the following acknowledgement:
26 * This product includes software developed by the University of
27 * California, Berkeley and its contributors.
28 * 4. Neither the name of the University nor the names of its contributors
29 * may be used to endorse or promote products derived from this software
30 * without specific prior written permission.
32 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
33 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
36 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
44 * from: @(#)vm_pageout.c 7.4 (Berkeley) 5/7/91
47 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
48 * All rights reserved.
50 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
52 * Permission to use, copy, modify and distribute this software and
53 * its documentation is hereby granted, provided that both the copyright
54 * notice and this permission notice appear in all copies of the
55 * software, derivative works or modified versions, and any portions
56 * thereof, and that both notices appear in supporting documentation.
58 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
59 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
60 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
62 * Carnegie Mellon requests users of this software to return to
64 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
65 * School of Computer Science
66 * Carnegie Mellon University
67 * Pittsburgh PA 15213-3890
69 * any improvements or extensions that they make and grant Carnegie the
70 * rights to redistribute these changes.
74 * The proverbial page-out daemon.
77 #include <sys/cdefs.h>
78 __FBSDID("$FreeBSD$");
82 #include <sys/param.h>
83 #include <sys/systm.h>
84 #include <sys/kernel.h>
85 #include <sys/eventhandler.h>
87 #include <sys/mutex.h>
89 #include <sys/kthread.h>
91 #include <sys/mount.h>
92 #include <sys/racct.h>
93 #include <sys/resourcevar.h>
94 #include <sys/sched.h>
96 #include <sys/signalvar.h>
99 #include <sys/vnode.h>
100 #include <sys/vmmeter.h>
101 #include <sys/rwlock.h>
103 #include <sys/sysctl.h>
106 #include <vm/vm_param.h>
107 #include <vm/vm_object.h>
108 #include <vm/vm_page.h>
109 #include <vm/vm_map.h>
110 #include <vm/vm_pageout.h>
111 #include <vm/vm_pager.h>
112 #include <vm/vm_phys.h>
113 #include <vm/swap_pager.h>
114 #include <vm/vm_extern.h>
118 * System initialization
121 /* the kernel process "vm_pageout"*/
122 static void vm_pageout(void);
123 static void vm_pageout_init(void);
124 static int vm_pageout_clean(vm_page_t m, int *numpagedout);
125 static int vm_pageout_cluster(vm_page_t m);
126 static bool vm_pageout_scan(struct vm_domain *vmd, int pass);
127 static void vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
128 int starting_page_shortage);
130 SYSINIT(pagedaemon_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, vm_pageout_init,
133 struct proc *pageproc;
135 static struct kproc_desc page_kp = {
140 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_SECOND, kproc_start,
143 SDT_PROVIDER_DEFINE(vm);
144 SDT_PROBE_DEFINE(vm, , , vm__lowmem_scan);
146 /* Pagedaemon activity rates, in subdivisions of one second. */
147 #define VM_LAUNDER_RATE 10
148 #define VM_INACT_SCAN_RATE 2
150 int vm_pageout_deficit; /* Estimated number of pages deficit */
151 u_int vm_pageout_wakeup_thresh;
152 static int vm_pageout_oom_seq = 12;
153 bool vm_pageout_wanted; /* Event on which pageout daemon sleeps */
154 bool vm_pages_needed; /* Are threads waiting for free pages? */
156 /* Pending request for dirty page laundering. */
159 VM_LAUNDRY_BACKGROUND,
161 } vm_laundry_request = VM_LAUNDRY_IDLE;
163 static int vm_pageout_update_period;
164 static int disable_swap_pageouts;
165 static int lowmem_period = 10;
166 static time_t lowmem_uptime;
167 static int swapdev_enabled;
169 static int vm_panic_on_oom = 0;
171 SYSCTL_INT(_vm, OID_AUTO, panic_on_oom,
172 CTLFLAG_RWTUN, &vm_panic_on_oom, 0,
173 "panic on out of memory instead of killing the largest process");
175 SYSCTL_INT(_vm, OID_AUTO, pageout_wakeup_thresh,
176 CTLFLAG_RWTUN, &vm_pageout_wakeup_thresh, 0,
177 "free page threshold for waking up the pageout daemon");
179 SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
180 CTLFLAG_RWTUN, &vm_pageout_update_period, 0,
181 "Maximum active LRU update period");
183 SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RWTUN, &lowmem_period, 0,
184 "Low memory callback period");
186 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
187 CTLFLAG_RWTUN, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
189 static int pageout_lock_miss;
190 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
191 CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
193 SYSCTL_INT(_vm, OID_AUTO, pageout_oom_seq,
194 CTLFLAG_RWTUN, &vm_pageout_oom_seq, 0,
195 "back-to-back calls to oom detector to start OOM");
197 static int act_scan_laundry_weight = 3;
198 SYSCTL_INT(_vm, OID_AUTO, act_scan_laundry_weight, CTLFLAG_RWTUN,
199 &act_scan_laundry_weight, 0,
200 "weight given to clean vs. dirty pages in active queue scans");
202 static u_int vm_background_launder_target;
203 SYSCTL_UINT(_vm, OID_AUTO, background_launder_target, CTLFLAG_RWTUN,
204 &vm_background_launder_target, 0,
205 "background laundering target, in pages");
207 static u_int vm_background_launder_rate = 4096;
208 SYSCTL_UINT(_vm, OID_AUTO, background_launder_rate, CTLFLAG_RWTUN,
209 &vm_background_launder_rate, 0,
210 "background laundering rate, in kilobytes per second");
212 static u_int vm_background_launder_max = 20 * 1024;
213 SYSCTL_UINT(_vm, OID_AUTO, background_launder_max, CTLFLAG_RWTUN,
214 &vm_background_launder_max, 0, "background laundering cap, in kilobytes");
216 int vm_pageout_page_count = 32;
218 int vm_page_max_wired; /* XXX max # of wired pages system-wide */
219 SYSCTL_INT(_vm, OID_AUTO, max_wired,
220 CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
222 static u_int isqrt(u_int num);
223 static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
224 static int vm_pageout_launder(struct vm_domain *vmd, int launder,
226 static void vm_pageout_laundry_worker(void *arg);
227 static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
230 * Initialize a dummy page for marking the caller's place in the specified
231 * paging queue. In principle, this function only needs to set the flag
232 * PG_MARKER. Nonetheless, it write busies and initializes the hold count
233 * to one as safety precautions.
236 vm_pageout_init_marker(vm_page_t marker, u_short queue)
239 bzero(marker, sizeof(*marker));
240 marker->flags = PG_MARKER;
241 marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
242 marker->queue = queue;
243 marker->hold_count = 1;
247 * vm_pageout_fallback_object_lock:
249 * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
250 * known to have failed and page queue must be either PQ_ACTIVE or
251 * PQ_INACTIVE. To avoid lock order violation, unlock the page queue
252 * while locking the vm object. Use marker page to detect page queue
253 * changes and maintain notion of next page on page queue. Return
254 * TRUE if no changes were detected, FALSE otherwise. vm object is
257 * This function depends on both the lock portion of struct vm_object
258 * and normal struct vm_page being type stable.
261 vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
263 struct vm_page marker;
264 struct vm_pagequeue *pq;
270 vm_pageout_init_marker(&marker, queue);
271 pq = vm_page_pagequeue(m);
274 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
275 vm_pagequeue_unlock(pq);
277 VM_OBJECT_WLOCK(object);
279 vm_pagequeue_lock(pq);
282 * The page's object might have changed, and/or the page might
283 * have moved from its original position in the queue. If the
284 * page's object has changed, then the caller should abandon
285 * processing the page because the wrong object lock was
286 * acquired. Use the marker's plinks.q, not the page's, to
287 * determine if the page has been moved. The state of the
288 * page's plinks.q can be indeterminate; whereas, the marker's
289 * plinks.q must be valid.
291 *next = TAILQ_NEXT(&marker, plinks.q);
292 unchanged = m->object == object &&
293 m == TAILQ_PREV(&marker, pglist, plinks.q);
294 KASSERT(!unchanged || m->queue == queue,
295 ("page %p queue %d %d", m, queue, m->queue));
296 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
301 * Lock the page while holding the page queue lock. Use marker page
302 * to detect page queue changes and maintain notion of next page on
303 * page queue. Return TRUE if no changes were detected, FALSE
304 * otherwise. The page is locked on return. The page queue lock might
305 * be dropped and reacquired.
307 * This function depends on normal struct vm_page being type stable.
310 vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
312 struct vm_page marker;
313 struct vm_pagequeue *pq;
317 vm_page_lock_assert(m, MA_NOTOWNED);
318 if (vm_page_trylock(m))
322 vm_pageout_init_marker(&marker, queue);
323 pq = vm_page_pagequeue(m);
325 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
326 vm_pagequeue_unlock(pq);
328 vm_pagequeue_lock(pq);
330 /* Page queue might have changed. */
331 *next = TAILQ_NEXT(&marker, plinks.q);
332 unchanged = m == TAILQ_PREV(&marker, pglist, plinks.q);
333 KASSERT(!unchanged || m->queue == queue,
334 ("page %p queue %d %d", m, queue, m->queue));
335 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
340 * Scan for pages at adjacent offsets within the given page's object that are
341 * eligible for laundering, form a cluster of these pages and the given page,
342 * and launder that cluster.
345 vm_pageout_cluster(vm_page_t m)
348 vm_page_t mc[2 * vm_pageout_page_count], p, pb, ps;
350 int ib, is, page_base, pageout_count;
352 vm_page_assert_locked(m);
354 VM_OBJECT_ASSERT_WLOCKED(object);
358 * We can't clean the page if it is busy or held.
360 vm_page_assert_unbusied(m);
361 KASSERT(m->hold_count == 0, ("page %p is held", m));
363 pmap_remove_write(m);
366 mc[vm_pageout_page_count] = pb = ps = m;
368 page_base = vm_pageout_page_count;
373 * We can cluster only if the page is not clean, busy, or held, and
374 * the page is in the laundry queue.
376 * During heavy mmap/modification loads the pageout
377 * daemon can really fragment the underlying file
378 * due to flushing pages out of order and not trying to
379 * align the clusters (which leaves sporadic out-of-order
380 * holes). To solve this problem we do the reverse scan
381 * first and attempt to align our cluster, then do a
382 * forward scan if room remains.
385 while (ib != 0 && pageout_count < vm_pageout_page_count) {
390 if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
394 vm_page_test_dirty(p);
400 if (!vm_page_in_laundry(p) ||
401 p->hold_count != 0) { /* may be undergoing I/O */
406 pmap_remove_write(p);
408 mc[--page_base] = pb = p;
413 * We are at an alignment boundary. Stop here, and switch
414 * directions. Do not clear ib.
416 if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
419 while (pageout_count < vm_pageout_page_count &&
420 pindex + is < object->size) {
421 if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
423 vm_page_test_dirty(p);
427 if (!vm_page_in_laundry(p) ||
428 p->hold_count != 0) { /* may be undergoing I/O */
432 pmap_remove_write(p);
434 mc[page_base + pageout_count] = ps = p;
440 * If we exhausted our forward scan, continue with the reverse scan
441 * when possible, even past an alignment boundary. This catches
442 * boundary conditions.
444 if (ib != 0 && pageout_count < vm_pageout_page_count)
447 return (vm_pageout_flush(&mc[page_base], pageout_count,
448 VM_PAGER_PUT_NOREUSE, 0, NULL, NULL));
452 * vm_pageout_flush() - launder the given pages
454 * The given pages are laundered. Note that we setup for the start of
455 * I/O ( i.e. busy the page ), mark it read-only, and bump the object
456 * reference count all in here rather then in the parent. If we want
457 * the parent to do more sophisticated things we may have to change
460 * Returned runlen is the count of pages between mreq and first
461 * page after mreq with status VM_PAGER_AGAIN.
462 * *eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
463 * for any page in runlen set.
466 vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
469 vm_object_t object = mc[0]->object;
470 int pageout_status[count];
474 VM_OBJECT_ASSERT_WLOCKED(object);
477 * Initiate I/O. Mark the pages busy and verify that they're valid
480 * We do not have to fixup the clean/dirty bits here... we can
481 * allow the pager to do it after the I/O completes.
483 * NOTE! mc[i]->dirty may be partial or fragmented due to an
484 * edge case with file fragments.
486 for (i = 0; i < count; i++) {
487 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
488 ("vm_pageout_flush: partially invalid page %p index %d/%d",
490 KASSERT((mc[i]->aflags & PGA_WRITEABLE) == 0,
491 ("vm_pageout_flush: writeable page %p", mc[i]));
492 vm_page_sbusy(mc[i]);
494 vm_object_pip_add(object, count);
496 vm_pager_put_pages(object, mc, count, flags, pageout_status);
498 runlen = count - mreq;
501 for (i = 0; i < count; i++) {
502 vm_page_t mt = mc[i];
504 KASSERT(pageout_status[i] == VM_PAGER_PEND ||
505 !pmap_page_is_write_mapped(mt),
506 ("vm_pageout_flush: page %p is not write protected", mt));
507 switch (pageout_status[i]) {
510 if (vm_page_in_laundry(mt))
511 vm_page_deactivate_noreuse(mt);
519 * The page is outside the object's range. We pretend
520 * that the page out worked and clean the page, so the
521 * changes will be lost if the page is reclaimed by
526 if (vm_page_in_laundry(mt))
527 vm_page_deactivate_noreuse(mt);
533 * If the page couldn't be paged out to swap because the
534 * pager wasn't able to find space, place the page in
535 * the PQ_UNSWAPPABLE holding queue. This is an
536 * optimization that prevents the page daemon from
537 * wasting CPU cycles on pages that cannot be reclaimed
538 * becase no swap device is configured.
540 * Otherwise, reactivate the page so that it doesn't
541 * clog the laundry and inactive queues. (We will try
542 * paging it out again later.)
545 if (object->type == OBJT_SWAP &&
546 pageout_status[i] == VM_PAGER_FAIL) {
547 vm_page_unswappable(mt);
550 vm_page_activate(mt);
552 if (eio != NULL && i >= mreq && i - mreq < runlen)
556 if (i >= mreq && i - mreq < runlen)
562 * If the operation is still going, leave the page busy to
563 * block all other accesses. Also, leave the paging in
564 * progress indicator set so that we don't attempt an object
567 if (pageout_status[i] != VM_PAGER_PEND) {
568 vm_object_pip_wakeup(object);
574 return (numpagedout);
578 vm_pageout_swapon(void *arg __unused, struct swdevt *sp __unused)
581 atomic_store_rel_int(&swapdev_enabled, 1);
585 vm_pageout_swapoff(void *arg __unused, struct swdevt *sp __unused)
588 if (swap_pager_nswapdev() == 1)
589 atomic_store_rel_int(&swapdev_enabled, 0);
593 * Attempt to acquire all of the necessary locks to launder a page and
594 * then call through the clustering layer to PUTPAGES. Wait a short
595 * time for a vnode lock.
597 * Requires the page and object lock on entry, releases both before return.
598 * Returns 0 on success and an errno otherwise.
601 vm_pageout_clean(vm_page_t m, int *numpagedout)
609 vm_page_assert_locked(m);
611 VM_OBJECT_ASSERT_WLOCKED(object);
617 * The object is already known NOT to be dead. It
618 * is possible for the vget() to block the whole
619 * pageout daemon, but the new low-memory handling
620 * code should prevent it.
622 * We can't wait forever for the vnode lock, we might
623 * deadlock due to a vn_read() getting stuck in
624 * vm_wait while holding this vnode. We skip the
625 * vnode if we can't get it in a reasonable amount
628 if (object->type == OBJT_VNODE) {
631 if (vp->v_type == VREG &&
632 vn_start_write(vp, &mp, V_NOWAIT) != 0) {
638 ("vp %p with NULL v_mount", vp));
639 vm_object_reference_locked(object);
641 VM_OBJECT_WUNLOCK(object);
642 lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
643 LK_SHARED : LK_EXCLUSIVE;
644 if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
649 VM_OBJECT_WLOCK(object);
652 * While the object and page were unlocked, the page
654 * (1) moved to a different queue,
655 * (2) reallocated to a different object,
656 * (3) reallocated to a different offset, or
659 if (!vm_page_in_laundry(m) || m->object != object ||
660 m->pindex != pindex || m->dirty == 0) {
667 * The page may have been busied or held while the object
668 * and page locks were released.
670 if (vm_page_busied(m) || m->hold_count != 0) {
678 * If a page is dirty, then it is either being washed
679 * (but not yet cleaned) or it is still in the
680 * laundry. If it is still in the laundry, then we
681 * start the cleaning operation.
683 if ((*numpagedout = vm_pageout_cluster(m)) == 0)
687 VM_OBJECT_WUNLOCK(object);
690 vm_page_lock_assert(m, MA_NOTOWNED);
694 vm_object_deallocate(object);
695 vn_finished_write(mp);
702 * Attempt to launder the specified number of pages.
704 * Returns the number of pages successfully laundered.
707 vm_pageout_launder(struct vm_domain *vmd, int launder, bool in_shortfall)
709 struct vm_pagequeue *pq;
712 int act_delta, error, maxscan, numpagedout, starting_target;
714 bool pageout_ok, queue_locked;
716 starting_target = launder;
720 * Scan the laundry queues for pages eligible to be laundered. We stop
721 * once the target number of dirty pages have been laundered, or once
722 * we've reached the end of the queue. A single iteration of this loop
723 * may cause more than one page to be laundered because of clustering.
725 * maxscan ensures that we don't re-examine requeued pages. Any
726 * additional pages written as part of a cluster are subtracted from
727 * maxscan since they must be taken from the laundry queue.
729 * As an optimization, we avoid laundering from PQ_UNSWAPPABLE when no
730 * swap devices are configured.
732 if (atomic_load_acq_int(&swapdev_enabled))
733 pq = &vmd->vmd_pagequeues[PQ_UNSWAPPABLE];
735 pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
738 vm_pagequeue_lock(pq);
739 maxscan = pq->pq_cnt;
741 for (m = TAILQ_FIRST(&pq->pq_pl);
742 m != NULL && maxscan-- > 0 && launder > 0;
744 vm_pagequeue_assert_locked(pq);
745 KASSERT(queue_locked, ("unlocked laundry queue"));
746 KASSERT(vm_page_in_laundry(m),
747 ("page %p has an inconsistent queue", m));
748 next = TAILQ_NEXT(m, plinks.q);
749 if ((m->flags & PG_MARKER) != 0)
751 KASSERT((m->flags & PG_FICTITIOUS) == 0,
752 ("PG_FICTITIOUS page %p cannot be in laundry queue", m));
753 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
754 ("VPO_UNMANAGED page %p cannot be in laundry queue", m));
755 if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
760 if ((!VM_OBJECT_TRYWLOCK(object) &&
761 (!vm_pageout_fallback_object_lock(m, &next) ||
762 m->hold_count != 0)) || vm_page_busied(m)) {
763 VM_OBJECT_WUNLOCK(object);
769 * Unlock the laundry queue, invalidating the 'next' pointer.
770 * Use a marker to remember our place in the laundry queue.
772 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_laundry_marker,
774 vm_pagequeue_unlock(pq);
775 queue_locked = false;
778 * Invalid pages can be easily freed. They cannot be
779 * mapped; vm_page_free() asserts this.
785 * If the page has been referenced and the object is not dead,
786 * reactivate or requeue the page depending on whether the
789 if ((m->aflags & PGA_REFERENCED) != 0) {
790 vm_page_aflag_clear(m, PGA_REFERENCED);
794 if (object->ref_count != 0)
795 act_delta += pmap_ts_referenced(m);
797 KASSERT(!pmap_page_is_mapped(m),
798 ("page %p is mapped", m));
800 if (act_delta != 0) {
801 if (object->ref_count != 0) {
802 VM_CNT_INC(v_reactivated);
806 * Increase the activation count if the page
807 * was referenced while in the laundry queue.
808 * This makes it less likely that the page will
809 * be returned prematurely to the inactive
812 m->act_count += act_delta + ACT_ADVANCE;
815 * If this was a background laundering, count
816 * activated pages towards our target. The
817 * purpose of background laundering is to ensure
818 * that pages are eventually cycled through the
819 * laundry queue, and an activation is a valid
825 } else if ((object->flags & OBJ_DEAD) == 0)
830 * If the page appears to be clean at the machine-independent
831 * layer, then remove all of its mappings from the pmap in
832 * anticipation of freeing it. If, however, any of the page's
833 * mappings allow write access, then the page may still be
834 * modified until the last of those mappings are removed.
836 if (object->ref_count != 0) {
837 vm_page_test_dirty(m);
843 * Clean pages are freed, and dirty pages are paged out unless
844 * they belong to a dead object. Requeueing dirty pages from
845 * dead objects is pointless, as they are being paged out and
846 * freed by the thread that destroyed the object.
852 } else if ((object->flags & OBJ_DEAD) == 0) {
853 if (object->type != OBJT_SWAP &&
854 object->type != OBJT_DEFAULT)
856 else if (disable_swap_pageouts)
862 vm_pagequeue_lock(pq);
864 vm_page_requeue_locked(m);
869 * Form a cluster with adjacent, dirty pages from the
870 * same object, and page out that entire cluster.
872 * The adjacent, dirty pages must also be in the
873 * laundry. However, their mappings are not checked
874 * for new references. Consequently, a recently
875 * referenced page may be paged out. However, that
876 * page will not be prematurely reclaimed. After page
877 * out, the page will be placed in the inactive queue,
878 * where any new references will be detected and the
881 error = vm_pageout_clean(m, &numpagedout);
883 launder -= numpagedout;
884 maxscan -= numpagedout - 1;
885 } else if (error == EDEADLK) {
893 VM_OBJECT_WUNLOCK(object);
896 vm_pagequeue_lock(pq);
899 next = TAILQ_NEXT(&vmd->vmd_laundry_marker, plinks.q);
900 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_laundry_marker, plinks.q);
902 vm_pagequeue_unlock(pq);
904 if (launder > 0 && pq == &vmd->vmd_pagequeues[PQ_UNSWAPPABLE]) {
905 pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
910 * Wakeup the sync daemon if we skipped a vnode in a writeable object
911 * and we didn't launder enough pages.
913 if (vnodes_skipped > 0 && launder > 0)
914 (void)speedup_syncer();
916 return (starting_target - launder);
920 * Compute the integer square root.
925 u_int bit, root, tmp;
927 bit = 1u << ((NBBY * sizeof(u_int)) - 2);
944 * Perform the work of the laundry thread: periodically wake up and determine
945 * whether any pages need to be laundered. If so, determine the number of pages
946 * that need to be laundered, and launder them.
949 vm_pageout_laundry_worker(void *arg)
951 struct vm_domain *domain;
952 struct vm_pagequeue *pq;
953 uint64_t nclean, ndirty;
954 u_int last_launder, wakeups;
955 int domidx, last_target, launder, shortfall, shortfall_cycle, target;
958 domidx = (uintptr_t)arg;
959 domain = &vm_dom[domidx];
960 pq = &domain->vmd_pagequeues[PQ_LAUNDRY];
961 KASSERT(domain->vmd_segs != 0, ("domain without segments"));
962 vm_pageout_init_marker(&domain->vmd_laundry_marker, PQ_LAUNDRY);
965 in_shortfall = false;
971 * Calls to these handlers are serialized by the swap syscall lock.
973 (void)EVENTHANDLER_REGISTER(swapon, vm_pageout_swapon, domain,
974 EVENTHANDLER_PRI_ANY);
975 (void)EVENTHANDLER_REGISTER(swapoff, vm_pageout_swapoff, domain,
976 EVENTHANDLER_PRI_ANY);
979 * The pageout laundry worker is never done, so loop forever.
982 KASSERT(target >= 0, ("negative target %d", target));
983 KASSERT(shortfall_cycle >= 0,
984 ("negative cycle %d", shortfall_cycle));
986 wakeups = VM_CNT_FETCH(v_pdwakeups);
989 * First determine whether we need to launder pages to meet a
990 * shortage of free pages.
994 shortfall_cycle = VM_LAUNDER_RATE / VM_INACT_SCAN_RATE;
996 } else if (!in_shortfall)
998 else if (shortfall_cycle == 0 || vm_laundry_target() <= 0) {
1000 * We recently entered shortfall and began laundering
1001 * pages. If we have completed that laundering run
1002 * (and we are no longer in shortfall) or we have met
1003 * our laundry target through other activity, then we
1004 * can stop laundering pages.
1006 in_shortfall = false;
1010 last_launder = wakeups;
1011 launder = target / shortfall_cycle--;
1015 * There's no immediate need to launder any pages; see if we
1016 * meet the conditions to perform background laundering:
1018 * 1. The ratio of dirty to clean inactive pages exceeds the
1019 * background laundering threshold and the pagedaemon has
1020 * been woken up to reclaim pages since our last
1022 * 2. we haven't yet reached the target of the current
1023 * background laundering run.
1025 * The background laundering threshold is not a constant.
1026 * Instead, it is a slowly growing function of the number of
1027 * page daemon wakeups since the last laundering. Thus, as the
1028 * ratio of dirty to clean inactive pages grows, the amount of
1029 * memory pressure required to trigger laundering decreases.
1032 nclean = vm_cnt.v_inactive_count + vm_cnt.v_free_count;
1033 ndirty = vm_cnt.v_laundry_count;
1034 if (target == 0 && wakeups != last_launder &&
1035 ndirty * isqrt(wakeups - last_launder) >= nclean) {
1036 target = vm_background_launder_target;
1040 * We have a non-zero background laundering target. If we've
1041 * laundered up to our maximum without observing a page daemon
1042 * wakeup, just stop. This is a safety belt that ensures we
1043 * don't launder an excessive amount if memory pressure is low
1044 * and the ratio of dirty to clean pages is large. Otherwise,
1045 * proceed at the background laundering rate.
1048 if (wakeups != last_launder) {
1049 last_launder = wakeups;
1050 last_target = target;
1051 } else if (last_target - target >=
1052 vm_background_launder_max * PAGE_SIZE / 1024) {
1055 launder = vm_background_launder_rate * PAGE_SIZE / 1024;
1056 launder /= VM_LAUNDER_RATE;
1057 if (launder > target)
1064 * Because of I/O clustering, the number of laundered
1065 * pages could exceed "target" by the maximum size of
1066 * a cluster minus one.
1068 target -= min(vm_pageout_launder(domain, launder,
1069 in_shortfall), target);
1070 pause("laundp", hz / VM_LAUNDER_RATE);
1074 * If we're not currently laundering pages and the page daemon
1075 * hasn't posted a new request, sleep until the page daemon
1078 vm_pagequeue_lock(pq);
1079 if (target == 0 && vm_laundry_request == VM_LAUNDRY_IDLE)
1080 (void)mtx_sleep(&vm_laundry_request,
1081 vm_pagequeue_lockptr(pq), PVM, "launds", 0);
1084 * If the pagedaemon has indicated that it's in shortfall, start
1085 * a shortfall laundering unless we're already in the middle of
1086 * one. This may preempt a background laundering.
1088 if (vm_laundry_request == VM_LAUNDRY_SHORTFALL &&
1089 (!in_shortfall || shortfall_cycle == 0)) {
1090 shortfall = vm_laundry_target() + vm_pageout_deficit;
1096 vm_laundry_request = VM_LAUNDRY_IDLE;
1097 vm_pagequeue_unlock(pq);
1102 * vm_pageout_scan does the dirty work for the pageout daemon.
1104 * pass == 0: Update active LRU/deactivate pages
1105 * pass >= 1: Free inactive pages
1107 * Returns true if pass was zero or enough pages were freed by the inactive
1108 * queue scan to meet the target.
1111 vm_pageout_scan(struct vm_domain *vmd, int pass)
1114 struct vm_pagequeue *pq;
1117 int act_delta, addl_page_shortage, deficit, inactq_shortage, maxscan;
1118 int page_shortage, scan_tick, scanned, starting_page_shortage;
1119 boolean_t queue_locked;
1122 * If we need to reclaim memory ask kernel caches to return
1123 * some. We rate limit to avoid thrashing.
1125 if (vmd == &vm_dom[0] && pass > 0 &&
1126 (time_uptime - lowmem_uptime) >= lowmem_period) {
1128 * Decrease registered cache sizes.
1130 SDT_PROBE0(vm, , , vm__lowmem_scan);
1131 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_PAGES);
1133 * We do this explicitly after the caches have been
1137 lowmem_uptime = time_uptime;
1141 * The addl_page_shortage is the number of temporarily
1142 * stuck pages in the inactive queue. In other words, the
1143 * number of pages from the inactive count that should be
1144 * discounted in setting the target for the active queue scan.
1146 addl_page_shortage = 0;
1149 * Calculate the number of pages that we want to free. This number
1150 * can be negative if many pages are freed between the wakeup call to
1151 * the page daemon and this calculation.
1154 deficit = atomic_readandclear_int(&vm_pageout_deficit);
1155 page_shortage = vm_paging_target() + deficit;
1157 page_shortage = deficit = 0;
1158 starting_page_shortage = page_shortage;
1161 * Start scanning the inactive queue for pages that we can free. The
1162 * scan will stop when we reach the target or we have scanned the
1163 * entire queue. (Note that m->act_count is not used to make
1164 * decisions for the inactive queue, only for the active queue.)
1166 pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
1167 maxscan = pq->pq_cnt;
1168 vm_pagequeue_lock(pq);
1169 queue_locked = TRUE;
1170 for (m = TAILQ_FIRST(&pq->pq_pl);
1171 m != NULL && maxscan-- > 0 && page_shortage > 0;
1173 vm_pagequeue_assert_locked(pq);
1174 KASSERT(queue_locked, ("unlocked inactive queue"));
1175 KASSERT(vm_page_inactive(m), ("Inactive queue %p", m));
1177 VM_CNT_INC(v_pdpages);
1178 next = TAILQ_NEXT(m, plinks.q);
1183 if (m->flags & PG_MARKER)
1186 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1187 ("Fictitious page %p cannot be in inactive queue", m));
1188 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1189 ("Unmanaged page %p cannot be in inactive queue", m));
1192 * The page or object lock acquisitions fail if the
1193 * page was removed from the queue or moved to a
1194 * different position within the queue. In either
1195 * case, addl_page_shortage should not be incremented.
1197 if (!vm_pageout_page_lock(m, &next))
1199 else if (m->hold_count != 0) {
1201 * Held pages are essentially stuck in the
1202 * queue. So, they ought to be discounted
1203 * from the inactive count. See the
1204 * calculation of inactq_shortage before the
1205 * loop over the active queue below.
1207 addl_page_shortage++;
1211 if (!VM_OBJECT_TRYWLOCK(object)) {
1212 if (!vm_pageout_fallback_object_lock(m, &next))
1214 else if (m->hold_count != 0) {
1215 addl_page_shortage++;
1219 if (vm_page_busied(m)) {
1221 * Don't mess with busy pages. Leave them at
1222 * the front of the queue. Most likely, they
1223 * are being paged out and will leave the
1224 * queue shortly after the scan finishes. So,
1225 * they ought to be discounted from the
1228 addl_page_shortage++;
1230 VM_OBJECT_WUNLOCK(object);
1235 KASSERT(m->hold_count == 0, ("Held page %p", m));
1238 * Dequeue the inactive page and unlock the inactive page
1239 * queue, invalidating the 'next' pointer. Dequeueing the
1240 * page here avoids a later reacquisition (and release) of
1241 * the inactive page queue lock when vm_page_activate(),
1242 * vm_page_free(), or vm_page_launder() is called. Use a
1243 * marker to remember our place in the inactive queue.
1245 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
1246 vm_page_dequeue_locked(m);
1247 vm_pagequeue_unlock(pq);
1248 queue_locked = FALSE;
1251 * Invalid pages can be easily freed. They cannot be
1252 * mapped, vm_page_free() asserts this.
1258 * If the page has been referenced and the object is not dead,
1259 * reactivate or requeue the page depending on whether the
1262 if ((m->aflags & PGA_REFERENCED) != 0) {
1263 vm_page_aflag_clear(m, PGA_REFERENCED);
1267 if (object->ref_count != 0) {
1268 act_delta += pmap_ts_referenced(m);
1270 KASSERT(!pmap_page_is_mapped(m),
1271 ("vm_pageout_scan: page %p is mapped", m));
1273 if (act_delta != 0) {
1274 if (object->ref_count != 0) {
1275 VM_CNT_INC(v_reactivated);
1276 vm_page_activate(m);
1279 * Increase the activation count if the page
1280 * was referenced while in the inactive queue.
1281 * This makes it less likely that the page will
1282 * be returned prematurely to the inactive
1285 m->act_count += act_delta + ACT_ADVANCE;
1287 } else if ((object->flags & OBJ_DEAD) == 0) {
1288 vm_pagequeue_lock(pq);
1289 queue_locked = TRUE;
1290 m->queue = PQ_INACTIVE;
1291 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
1292 vm_pagequeue_cnt_inc(pq);
1298 * If the page appears to be clean at the machine-independent
1299 * layer, then remove all of its mappings from the pmap in
1300 * anticipation of freeing it. If, however, any of the page's
1301 * mappings allow write access, then the page may still be
1302 * modified until the last of those mappings are removed.
1304 if (object->ref_count != 0) {
1305 vm_page_test_dirty(m);
1311 * Clean pages can be freed, but dirty pages must be sent back
1312 * to the laundry, unless they belong to a dead object.
1313 * Requeueing dirty pages from dead objects is pointless, as
1314 * they are being paged out and freed by the thread that
1315 * destroyed the object.
1317 if (m->dirty == 0) {
1320 VM_CNT_INC(v_dfree);
1322 } else if ((object->flags & OBJ_DEAD) == 0)
1326 VM_OBJECT_WUNLOCK(object);
1327 if (!queue_locked) {
1328 vm_pagequeue_lock(pq);
1329 queue_locked = TRUE;
1331 next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1332 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
1334 vm_pagequeue_unlock(pq);
1337 * Wake up the laundry thread so that it can perform any needed
1338 * laundering. If we didn't meet our target, we're in shortfall and
1339 * need to launder more aggressively. If PQ_LAUNDRY is empty and no
1340 * swap devices are configured, the laundry thread has no work to do, so
1341 * don't bother waking it up.
1343 if (vm_laundry_request == VM_LAUNDRY_IDLE &&
1344 starting_page_shortage > 0) {
1345 pq = &vm_dom[0].vmd_pagequeues[PQ_LAUNDRY];
1346 vm_pagequeue_lock(pq);
1347 if (pq->pq_cnt > 0 || atomic_load_acq_int(&swapdev_enabled)) {
1348 if (page_shortage > 0) {
1349 vm_laundry_request = VM_LAUNDRY_SHORTFALL;
1350 VM_CNT_INC(v_pdshortfalls);
1351 } else if (vm_laundry_request != VM_LAUNDRY_SHORTFALL)
1352 vm_laundry_request = VM_LAUNDRY_BACKGROUND;
1353 wakeup(&vm_laundry_request);
1355 vm_pagequeue_unlock(pq);
1359 * Wakeup the swapout daemon if we didn't free the targeted number of
1362 if (page_shortage > 0)
1366 * If the inactive queue scan fails repeatedly to meet its
1367 * target, kill the largest process.
1369 vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
1372 * Compute the number of pages we want to try to move from the
1373 * active queue to either the inactive or laundry queue.
1375 * When scanning active pages, we make clean pages count more heavily
1376 * towards the page shortage than dirty pages. This is because dirty
1377 * pages must be laundered before they can be reused and thus have less
1378 * utility when attempting to quickly alleviate a shortage. However,
1379 * this weighting also causes the scan to deactivate dirty pages more
1380 * more aggressively, improving the effectiveness of clustering and
1381 * ensuring that they can eventually be reused.
1383 inactq_shortage = vm_cnt.v_inactive_target - (vm_cnt.v_inactive_count +
1384 vm_cnt.v_laundry_count / act_scan_laundry_weight) +
1385 vm_paging_target() + deficit + addl_page_shortage;
1386 page_shortage *= act_scan_laundry_weight;
1388 pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1389 vm_pagequeue_lock(pq);
1390 maxscan = pq->pq_cnt;
1393 * If we're just idle polling attempt to visit every
1394 * active page within 'update_period' seconds.
1397 if (vm_pageout_update_period != 0) {
1398 min_scan = pq->pq_cnt;
1399 min_scan *= scan_tick - vmd->vmd_last_active_scan;
1400 min_scan /= hz * vm_pageout_update_period;
1403 if (min_scan > 0 || (inactq_shortage > 0 && maxscan > 0))
1404 vmd->vmd_last_active_scan = scan_tick;
1407 * Scan the active queue for pages that can be deactivated. Update
1408 * the per-page activity counter and use it to identify deactivation
1409 * candidates. Held pages may be deactivated.
1411 for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
1412 min_scan || (inactq_shortage > 0 && scanned < maxscan)); m = next,
1414 KASSERT(m->queue == PQ_ACTIVE,
1415 ("vm_pageout_scan: page %p isn't active", m));
1416 next = TAILQ_NEXT(m, plinks.q);
1417 if ((m->flags & PG_MARKER) != 0)
1419 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1420 ("Fictitious page %p cannot be in active queue", m));
1421 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1422 ("Unmanaged page %p cannot be in active queue", m));
1423 if (!vm_pageout_page_lock(m, &next)) {
1429 * The count for page daemon pages is updated after checking
1430 * the page for eligibility.
1432 VM_CNT_INC(v_pdpages);
1435 * Check to see "how much" the page has been used.
1437 if ((m->aflags & PGA_REFERENCED) != 0) {
1438 vm_page_aflag_clear(m, PGA_REFERENCED);
1444 * Perform an unsynchronized object ref count check. While
1445 * the page lock ensures that the page is not reallocated to
1446 * another object, in particular, one with unmanaged mappings
1447 * that cannot support pmap_ts_referenced(), two races are,
1448 * nonetheless, possible:
1449 * 1) The count was transitioning to zero, but we saw a non-
1450 * zero value. pmap_ts_referenced() will return zero
1451 * because the page is not mapped.
1452 * 2) The count was transitioning to one, but we saw zero.
1453 * This race delays the detection of a new reference. At
1454 * worst, we will deactivate and reactivate the page.
1456 if (m->object->ref_count != 0)
1457 act_delta += pmap_ts_referenced(m);
1460 * Advance or decay the act_count based on recent usage.
1462 if (act_delta != 0) {
1463 m->act_count += ACT_ADVANCE + act_delta;
1464 if (m->act_count > ACT_MAX)
1465 m->act_count = ACT_MAX;
1467 m->act_count -= min(m->act_count, ACT_DECLINE);
1470 * Move this page to the tail of the active, inactive or laundry
1471 * queue depending on usage.
1473 if (m->act_count == 0) {
1474 /* Dequeue to avoid later lock recursion. */
1475 vm_page_dequeue_locked(m);
1478 * When not short for inactive pages, let dirty pages go
1479 * through the inactive queue before moving to the
1480 * laundry queues. This gives them some extra time to
1481 * be reactivated, potentially avoiding an expensive
1482 * pageout. During a page shortage, the inactive queue
1483 * is necessarily small, so we may move dirty pages
1484 * directly to the laundry queue.
1486 if (inactq_shortage <= 0)
1487 vm_page_deactivate(m);
1490 * Calling vm_page_test_dirty() here would
1491 * require acquisition of the object's write
1492 * lock. However, during a page shortage,
1493 * directing dirty pages into the laundry
1494 * queue is only an optimization and not a
1495 * requirement. Therefore, we simply rely on
1496 * the opportunistic updates to the page's
1497 * dirty field by the pmap.
1499 if (m->dirty == 0) {
1500 vm_page_deactivate(m);
1502 act_scan_laundry_weight;
1509 vm_page_requeue_locked(m);
1512 vm_pagequeue_unlock(pq);
1514 vm_swapout_run_idle();
1515 return (page_shortage <= 0);
1518 static int vm_pageout_oom_vote;
1521 * The pagedaemon threads randlomly select one to perform the
1522 * OOM. Trying to kill processes before all pagedaemons
1523 * failed to reach free target is premature.
1526 vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
1527 int starting_page_shortage)
1531 if (starting_page_shortage <= 0 || starting_page_shortage !=
1533 vmd->vmd_oom_seq = 0;
1536 if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1538 vmd->vmd_oom = FALSE;
1539 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1545 * Do not follow the call sequence until OOM condition is
1548 vmd->vmd_oom_seq = 0;
1553 vmd->vmd_oom = TRUE;
1554 old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1555 if (old_vote != vm_ndomains - 1)
1559 * The current pagedaemon thread is the last in the quorum to
1560 * start OOM. Initiate the selection and signaling of the
1563 vm_pageout_oom(VM_OOM_MEM);
1566 * After one round of OOM terror, recall our vote. On the
1567 * next pass, current pagedaemon would vote again if the low
1568 * memory condition is still there, due to vmd_oom being
1571 vmd->vmd_oom = FALSE;
1572 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1576 * The OOM killer is the page daemon's action of last resort when
1577 * memory allocation requests have been stalled for a prolonged period
1578 * of time because it cannot reclaim memory. This function computes
1579 * the approximate number of physical pages that could be reclaimed if
1580 * the specified address space is destroyed.
1582 * Private, anonymous memory owned by the address space is the
1583 * principal resource that we expect to recover after an OOM kill.
1584 * Since the physical pages mapped by the address space's COW entries
1585 * are typically shared pages, they are unlikely to be released and so
1586 * they are not counted.
1588 * To get to the point where the page daemon runs the OOM killer, its
1589 * efforts to write-back vnode-backed pages may have stalled. This
1590 * could be caused by a memory allocation deadlock in the write path
1591 * that might be resolved by an OOM kill. Therefore, physical pages
1592 * belonging to vnode-backed objects are counted, because they might
1593 * be freed without being written out first if the address space holds
1594 * the last reference to an unlinked vnode.
1596 * Similarly, physical pages belonging to OBJT_PHYS objects are
1597 * counted because the address space might hold the last reference to
1601 vm_pageout_oom_pagecount(struct vmspace *vmspace)
1604 vm_map_entry_t entry;
1608 map = &vmspace->vm_map;
1609 KASSERT(!map->system_map, ("system map"));
1610 sx_assert(&map->lock, SA_LOCKED);
1612 for (entry = map->header.next; entry != &map->header;
1613 entry = entry->next) {
1614 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
1616 obj = entry->object.vm_object;
1619 if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
1620 obj->ref_count != 1)
1622 switch (obj->type) {
1627 res += obj->resident_page_count;
1635 vm_pageout_oom(int shortage)
1637 struct proc *p, *bigproc;
1638 vm_offset_t size, bigsize;
1644 * We keep the process bigproc locked once we find it to keep anyone
1645 * from messing with it; however, there is a possibility of
1646 * deadlock if process B is bigproc and one of its child processes
1647 * attempts to propagate a signal to B while we are waiting for A's
1648 * lock while walking this list. To avoid this, we don't block on
1649 * the process lock but just skip a process if it is already locked.
1653 sx_slock(&allproc_lock);
1654 FOREACH_PROC_IN_SYSTEM(p) {
1658 * If this is a system, protected or killed process, skip it.
1660 if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
1661 P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
1662 p->p_pid == 1 || P_KILLED(p) ||
1663 (p->p_pid < 48 && swap_pager_avail != 0)) {
1668 * If the process is in a non-running type state,
1669 * don't touch it. Check all the threads individually.
1672 FOREACH_THREAD_IN_PROC(p, td) {
1674 if (!TD_ON_RUNQ(td) &&
1675 !TD_IS_RUNNING(td) &&
1676 !TD_IS_SLEEPING(td) &&
1677 !TD_IS_SUSPENDED(td) &&
1678 !TD_IS_SWAPPED(td)) {
1690 * get the process size
1692 vm = vmspace_acquire_ref(p);
1699 sx_sunlock(&allproc_lock);
1700 if (!vm_map_trylock_read(&vm->vm_map)) {
1702 sx_slock(&allproc_lock);
1706 size = vmspace_swap_count(vm);
1707 if (shortage == VM_OOM_MEM)
1708 size += vm_pageout_oom_pagecount(vm);
1709 vm_map_unlock_read(&vm->vm_map);
1711 sx_slock(&allproc_lock);
1714 * If this process is bigger than the biggest one,
1717 if (size > bigsize) {
1718 if (bigproc != NULL)
1726 sx_sunlock(&allproc_lock);
1727 if (bigproc != NULL) {
1728 if (vm_panic_on_oom != 0)
1729 panic("out of swap space");
1731 killproc(bigproc, "out of swap space");
1732 sched_nice(bigproc, PRIO_MIN);
1734 PROC_UNLOCK(bigproc);
1735 wakeup(&vm_cnt.v_free_count);
1740 vm_pageout_worker(void *arg)
1742 struct vm_domain *domain;
1746 domidx = (uintptr_t)arg;
1747 domain = &vm_dom[domidx];
1752 * XXXKIB It could be useful to bind pageout daemon threads to
1753 * the cores belonging to the domain, from which vm_page_array
1757 KASSERT(domain->vmd_segs != 0, ("domain without segments"));
1758 domain->vmd_last_active_scan = ticks;
1759 vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
1760 vm_pageout_init_marker(&domain->vmd_inacthead, PQ_INACTIVE);
1761 TAILQ_INSERT_HEAD(&domain->vmd_pagequeues[PQ_INACTIVE].pq_pl,
1762 &domain->vmd_inacthead, plinks.q);
1765 * The pageout daemon worker is never done, so loop forever.
1768 mtx_lock(&vm_page_queue_free_mtx);
1771 * Generally, after a level >= 1 scan, if there are enough
1772 * free pages to wakeup the waiters, then they are already
1773 * awake. A call to vm_page_free() during the scan awakened
1774 * them. However, in the following case, this wakeup serves
1775 * to bound the amount of time that a thread might wait.
1776 * Suppose a thread's call to vm_page_alloc() fails, but
1777 * before that thread calls VM_WAIT, enough pages are freed by
1778 * other threads to alleviate the free page shortage. The
1779 * thread will, nonetheless, wait until another page is freed
1780 * or this wakeup is performed.
1782 if (vm_pages_needed && !vm_page_count_min()) {
1783 vm_pages_needed = false;
1784 wakeup(&vm_cnt.v_free_count);
1788 * Do not clear vm_pageout_wanted until we reach our free page
1789 * target. Otherwise, we may be awakened over and over again,
1792 if (vm_pageout_wanted && target_met)
1793 vm_pageout_wanted = false;
1796 * Might the page daemon receive a wakeup call?
1798 if (vm_pageout_wanted) {
1800 * No. Either vm_pageout_wanted was set by another
1801 * thread during the previous scan, which must have
1802 * been a level 0 scan, or vm_pageout_wanted was
1803 * already set and the scan failed to free enough
1804 * pages. If we haven't yet performed a level >= 1
1805 * (page reclamation) scan, then increase the level
1806 * and scan again now. Otherwise, sleep a bit and
1809 mtx_unlock(&vm_page_queue_free_mtx);
1811 pause("psleep", hz / VM_INACT_SCAN_RATE);
1815 * Yes. Sleep until pages need to be reclaimed or
1816 * have their reference stats updated.
1818 if (mtx_sleep(&vm_pageout_wanted,
1819 &vm_page_queue_free_mtx, PDROP | PVM, "psleep",
1821 VM_CNT_INC(v_pdwakeups);
1827 target_met = vm_pageout_scan(domain, pass);
1832 * vm_pageout_init initialises basic pageout daemon settings.
1835 vm_pageout_init(void)
1838 * Initialize some paging parameters.
1840 vm_cnt.v_interrupt_free_min = 2;
1841 if (vm_cnt.v_page_count < 2000)
1842 vm_pageout_page_count = 8;
1845 * v_free_reserved needs to include enough for the largest
1846 * swap pager structures plus enough for any pv_entry structs
1849 if (vm_cnt.v_page_count > 1024)
1850 vm_cnt.v_free_min = 4 + (vm_cnt.v_page_count - 1024) / 200;
1852 vm_cnt.v_free_min = 4;
1853 vm_cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1854 vm_cnt.v_interrupt_free_min;
1855 vm_cnt.v_free_reserved = vm_pageout_page_count +
1856 vm_cnt.v_pageout_free_min + (vm_cnt.v_page_count / 768);
1857 vm_cnt.v_free_severe = vm_cnt.v_free_min / 2;
1858 vm_cnt.v_free_target = 4 * vm_cnt.v_free_min + vm_cnt.v_free_reserved;
1859 vm_cnt.v_free_min += vm_cnt.v_free_reserved;
1860 vm_cnt.v_free_severe += vm_cnt.v_free_reserved;
1861 vm_cnt.v_inactive_target = (3 * vm_cnt.v_free_target) / 2;
1862 if (vm_cnt.v_inactive_target > vm_cnt.v_free_count / 3)
1863 vm_cnt.v_inactive_target = vm_cnt.v_free_count / 3;
1866 * Set the default wakeup threshold to be 10% above the minimum
1867 * page limit. This keeps the steady state out of shortfall.
1869 vm_pageout_wakeup_thresh = (vm_cnt.v_free_min / 10) * 11;
1872 * Set interval in seconds for active scan. We want to visit each
1873 * page at least once every ten minutes. This is to prevent worst
1874 * case paging behaviors with stale active LRU.
1876 if (vm_pageout_update_period == 0)
1877 vm_pageout_update_period = 600;
1879 /* XXX does not really belong here */
1880 if (vm_page_max_wired == 0)
1881 vm_page_max_wired = vm_cnt.v_free_count / 3;
1884 * Target amount of memory to move out of the laundry queue during a
1885 * background laundering. This is proportional to the amount of system
1888 vm_background_launder_target = (vm_cnt.v_free_target -
1889 vm_cnt.v_free_min) / 10;
1893 * vm_pageout is the high level pageout daemon.
1899 #ifdef VM_NUMA_ALLOC
1903 swap_pager_swap_init();
1904 error = kthread_add(vm_pageout_laundry_worker, NULL, curproc, NULL,
1905 0, 0, "laundry: dom0");
1907 panic("starting laundry for domain 0, error %d", error);
1908 #ifdef VM_NUMA_ALLOC
1909 for (i = 1; i < vm_ndomains; i++) {
1910 error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
1911 curproc, NULL, 0, 0, "dom%d", i);
1913 panic("starting pageout for domain %d, error %d\n",
1918 error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
1921 panic("starting uma_reclaim helper, error %d\n", error);
1922 vm_pageout_worker((void *)(uintptr_t)0);
1926 * Unless the free page queue lock is held by the caller, this function
1927 * should be regarded as advisory. Specifically, the caller should
1928 * not msleep() on &vm_cnt.v_free_count following this function unless
1929 * the free page queue lock is held until the msleep() is performed.
1932 pagedaemon_wakeup(void)
1935 if (!vm_pageout_wanted && curthread->td_proc != pageproc) {
1936 vm_pageout_wanted = true;
1937 wakeup(&vm_pageout_wanted);