2 * SPDX-License-Identifier: (BSD-4-Clause AND MIT-CMU)
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/vm_pagequeue.h>
114 #include <vm/swap_pager.h>
115 #include <vm/vm_extern.h>
119 * System initialization
122 /* the kernel process "vm_pageout"*/
123 static void vm_pageout(void);
124 static void vm_pageout_init(void);
125 static int vm_pageout_clean(vm_page_t m, int *numpagedout);
126 static int vm_pageout_cluster(vm_page_t m);
127 static bool vm_pageout_scan(struct vm_domain *vmd, int pass);
128 static void vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
129 int starting_page_shortage);
131 SYSINIT(pagedaemon_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, vm_pageout_init,
134 struct proc *pageproc;
136 static struct kproc_desc page_kp = {
141 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_SECOND, kproc_start,
144 SDT_PROVIDER_DEFINE(vm);
145 SDT_PROBE_DEFINE(vm, , , vm__lowmem_scan);
147 /* Pagedaemon activity rates, in subdivisions of one second. */
148 #define VM_LAUNDER_RATE 10
149 #define VM_INACT_SCAN_RATE 2
151 static int vm_pageout_oom_seq = 12;
153 static int vm_pageout_update_period;
154 static int disable_swap_pageouts;
155 static int lowmem_period = 10;
156 static time_t lowmem_uptime;
157 static int swapdev_enabled;
159 static int vm_panic_on_oom = 0;
161 SYSCTL_INT(_vm, OID_AUTO, panic_on_oom,
162 CTLFLAG_RWTUN, &vm_panic_on_oom, 0,
163 "panic on out of memory instead of killing the largest process");
165 SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
166 CTLFLAG_RWTUN, &vm_pageout_update_period, 0,
167 "Maximum active LRU update period");
169 SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RWTUN, &lowmem_period, 0,
170 "Low memory callback period");
172 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
173 CTLFLAG_RWTUN, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
175 static int pageout_lock_miss;
176 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
177 CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
179 SYSCTL_INT(_vm, OID_AUTO, pageout_oom_seq,
180 CTLFLAG_RWTUN, &vm_pageout_oom_seq, 0,
181 "back-to-back calls to oom detector to start OOM");
183 static int act_scan_laundry_weight = 3;
184 SYSCTL_INT(_vm, OID_AUTO, act_scan_laundry_weight, CTLFLAG_RWTUN,
185 &act_scan_laundry_weight, 0,
186 "weight given to clean vs. dirty pages in active queue scans");
188 static u_int vm_background_launder_rate = 4096;
189 SYSCTL_UINT(_vm, OID_AUTO, background_launder_rate, CTLFLAG_RWTUN,
190 &vm_background_launder_rate, 0,
191 "background laundering rate, in kilobytes per second");
193 static u_int vm_background_launder_max = 20 * 1024;
194 SYSCTL_UINT(_vm, OID_AUTO, background_launder_max, CTLFLAG_RWTUN,
195 &vm_background_launder_max, 0, "background laundering cap, in kilobytes");
197 int vm_pageout_page_count = 32;
199 int vm_page_max_wired; /* XXX max # of wired pages system-wide */
200 SYSCTL_INT(_vm, OID_AUTO, max_wired,
201 CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
203 static u_int isqrt(u_int num);
204 static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
205 static int vm_pageout_launder(struct vm_domain *vmd, int launder,
207 static void vm_pageout_laundry_worker(void *arg);
208 static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
211 * Initialize a dummy page for marking the caller's place in the specified
212 * paging queue. In principle, this function only needs to set the flag
213 * PG_MARKER. Nonetheless, it write busies and initializes the hold count
214 * to one as safety precautions.
217 vm_pageout_init_marker(vm_page_t marker, u_short queue)
220 bzero(marker, sizeof(*marker));
221 marker->flags = PG_MARKER;
222 marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
223 marker->queue = queue;
224 marker->hold_count = 1;
228 * vm_pageout_fallback_object_lock:
230 * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
231 * known to have failed and page queue must be either PQ_ACTIVE or
232 * PQ_INACTIVE. To avoid lock order violation, unlock the page queue
233 * while locking the vm object. Use marker page to detect page queue
234 * changes and maintain notion of next page on page queue. Return
235 * TRUE if no changes were detected, FALSE otherwise. vm object is
238 * This function depends on both the lock portion of struct vm_object
239 * and normal struct vm_page being type stable.
242 vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
244 struct vm_page marker;
245 struct vm_pagequeue *pq;
251 vm_pageout_init_marker(&marker, queue);
252 pq = vm_page_pagequeue(m);
255 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
256 vm_pagequeue_unlock(pq);
258 VM_OBJECT_WLOCK(object);
260 vm_pagequeue_lock(pq);
263 * The page's object might have changed, and/or the page might
264 * have moved from its original position in the queue. If the
265 * page's object has changed, then the caller should abandon
266 * processing the page because the wrong object lock was
267 * acquired. Use the marker's plinks.q, not the page's, to
268 * determine if the page has been moved. The state of the
269 * page's plinks.q can be indeterminate; whereas, the marker's
270 * plinks.q must be valid.
272 *next = TAILQ_NEXT(&marker, plinks.q);
273 unchanged = m->object == object &&
274 m == TAILQ_PREV(&marker, pglist, plinks.q);
275 KASSERT(!unchanged || m->queue == queue,
276 ("page %p queue %d %d", m, queue, m->queue));
277 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
282 * Lock the page while holding the page queue lock. Use marker page
283 * to detect page queue changes and maintain notion of next page on
284 * page queue. Return TRUE if no changes were detected, FALSE
285 * otherwise. The page is locked on return. The page queue lock might
286 * be dropped and reacquired.
288 * This function depends on normal struct vm_page being type stable.
291 vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
293 struct vm_page marker;
294 struct vm_pagequeue *pq;
298 vm_page_lock_assert(m, MA_NOTOWNED);
299 if (vm_page_trylock(m))
303 vm_pageout_init_marker(&marker, queue);
304 pq = vm_page_pagequeue(m);
306 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
307 vm_pagequeue_unlock(pq);
309 vm_pagequeue_lock(pq);
311 /* Page queue might have changed. */
312 *next = TAILQ_NEXT(&marker, plinks.q);
313 unchanged = m == TAILQ_PREV(&marker, pglist, plinks.q);
314 KASSERT(!unchanged || m->queue == queue,
315 ("page %p queue %d %d", m, queue, m->queue));
316 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
321 * Scan for pages at adjacent offsets within the given page's object that are
322 * eligible for laundering, form a cluster of these pages and the given page,
323 * and launder that cluster.
326 vm_pageout_cluster(vm_page_t m)
329 vm_page_t mc[2 * vm_pageout_page_count], p, pb, ps;
331 int ib, is, page_base, pageout_count;
333 vm_page_assert_locked(m);
335 VM_OBJECT_ASSERT_WLOCKED(object);
338 vm_page_assert_unbusied(m);
339 KASSERT(!vm_page_held(m), ("page %p is held", m));
341 pmap_remove_write(m);
344 mc[vm_pageout_page_count] = pb = ps = m;
346 page_base = vm_pageout_page_count;
351 * We can cluster only if the page is not clean, busy, or held, and
352 * the page is in the laundry queue.
354 * During heavy mmap/modification loads the pageout
355 * daemon can really fragment the underlying file
356 * due to flushing pages out of order and not trying to
357 * align the clusters (which leaves sporadic out-of-order
358 * holes). To solve this problem we do the reverse scan
359 * first and attempt to align our cluster, then do a
360 * forward scan if room remains.
363 while (ib != 0 && pageout_count < vm_pageout_page_count) {
368 if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
372 vm_page_test_dirty(p);
378 if (!vm_page_in_laundry(p) || vm_page_held(p)) {
383 pmap_remove_write(p);
385 mc[--page_base] = pb = p;
390 * We are at an alignment boundary. Stop here, and switch
391 * directions. Do not clear ib.
393 if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
396 while (pageout_count < vm_pageout_page_count &&
397 pindex + is < object->size) {
398 if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
400 vm_page_test_dirty(p);
404 if (!vm_page_in_laundry(p) || vm_page_held(p)) {
408 pmap_remove_write(p);
410 mc[page_base + pageout_count] = ps = p;
416 * If we exhausted our forward scan, continue with the reverse scan
417 * when possible, even past an alignment boundary. This catches
418 * boundary conditions.
420 if (ib != 0 && pageout_count < vm_pageout_page_count)
423 return (vm_pageout_flush(&mc[page_base], pageout_count,
424 VM_PAGER_PUT_NOREUSE, 0, NULL, NULL));
428 * vm_pageout_flush() - launder the given pages
430 * The given pages are laundered. Note that we setup for the start of
431 * I/O ( i.e. busy the page ), mark it read-only, and bump the object
432 * reference count all in here rather then in the parent. If we want
433 * the parent to do more sophisticated things we may have to change
436 * Returned runlen is the count of pages between mreq and first
437 * page after mreq with status VM_PAGER_AGAIN.
438 * *eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
439 * for any page in runlen set.
442 vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
445 vm_object_t object = mc[0]->object;
446 int pageout_status[count];
450 VM_OBJECT_ASSERT_WLOCKED(object);
453 * Initiate I/O. Mark the pages busy and verify that they're valid
456 * We do not have to fixup the clean/dirty bits here... we can
457 * allow the pager to do it after the I/O completes.
459 * NOTE! mc[i]->dirty may be partial or fragmented due to an
460 * edge case with file fragments.
462 for (i = 0; i < count; i++) {
463 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
464 ("vm_pageout_flush: partially invalid page %p index %d/%d",
466 KASSERT((mc[i]->aflags & PGA_WRITEABLE) == 0,
467 ("vm_pageout_flush: writeable page %p", mc[i]));
468 vm_page_sbusy(mc[i]);
470 vm_object_pip_add(object, count);
472 vm_pager_put_pages(object, mc, count, flags, pageout_status);
474 runlen = count - mreq;
477 for (i = 0; i < count; i++) {
478 vm_page_t mt = mc[i];
480 KASSERT(pageout_status[i] == VM_PAGER_PEND ||
481 !pmap_page_is_write_mapped(mt),
482 ("vm_pageout_flush: page %p is not write protected", mt));
483 switch (pageout_status[i]) {
486 if (vm_page_in_laundry(mt))
487 vm_page_deactivate_noreuse(mt);
495 * The page is outside the object's range. We pretend
496 * that the page out worked and clean the page, so the
497 * changes will be lost if the page is reclaimed by
502 if (vm_page_in_laundry(mt))
503 vm_page_deactivate_noreuse(mt);
509 * If the page couldn't be paged out to swap because the
510 * pager wasn't able to find space, place the page in
511 * the PQ_UNSWAPPABLE holding queue. This is an
512 * optimization that prevents the page daemon from
513 * wasting CPU cycles on pages that cannot be reclaimed
514 * becase no swap device is configured.
516 * Otherwise, reactivate the page so that it doesn't
517 * clog the laundry and inactive queues. (We will try
518 * paging it out again later.)
521 if (object->type == OBJT_SWAP &&
522 pageout_status[i] == VM_PAGER_FAIL) {
523 vm_page_unswappable(mt);
526 vm_page_activate(mt);
528 if (eio != NULL && i >= mreq && i - mreq < runlen)
532 if (i >= mreq && i - mreq < runlen)
538 * If the operation is still going, leave the page busy to
539 * block all other accesses. Also, leave the paging in
540 * progress indicator set so that we don't attempt an object
543 if (pageout_status[i] != VM_PAGER_PEND) {
544 vm_object_pip_wakeup(object);
550 return (numpagedout);
554 vm_pageout_swapon(void *arg __unused, struct swdevt *sp __unused)
557 atomic_store_rel_int(&swapdev_enabled, 1);
561 vm_pageout_swapoff(void *arg __unused, struct swdevt *sp __unused)
564 if (swap_pager_nswapdev() == 1)
565 atomic_store_rel_int(&swapdev_enabled, 0);
569 * Attempt to acquire all of the necessary locks to launder a page and
570 * then call through the clustering layer to PUTPAGES. Wait a short
571 * time for a vnode lock.
573 * Requires the page and object lock on entry, releases both before return.
574 * Returns 0 on success and an errno otherwise.
577 vm_pageout_clean(vm_page_t m, int *numpagedout)
585 vm_page_assert_locked(m);
587 VM_OBJECT_ASSERT_WLOCKED(object);
593 * The object is already known NOT to be dead. It
594 * is possible for the vget() to block the whole
595 * pageout daemon, but the new low-memory handling
596 * code should prevent it.
598 * We can't wait forever for the vnode lock, we might
599 * deadlock due to a vn_read() getting stuck in
600 * vm_wait while holding this vnode. We skip the
601 * vnode if we can't get it in a reasonable amount
604 if (object->type == OBJT_VNODE) {
607 if (vp->v_type == VREG &&
608 vn_start_write(vp, &mp, V_NOWAIT) != 0) {
614 ("vp %p with NULL v_mount", vp));
615 vm_object_reference_locked(object);
617 VM_OBJECT_WUNLOCK(object);
618 lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
619 LK_SHARED : LK_EXCLUSIVE;
620 if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
625 VM_OBJECT_WLOCK(object);
628 * Ensure that the object and vnode were not disassociated
629 * while locks were dropped.
631 if (vp->v_object != object) {
638 * While the object and page were unlocked, the page
640 * (1) moved to a different queue,
641 * (2) reallocated to a different object,
642 * (3) reallocated to a different offset, or
645 if (!vm_page_in_laundry(m) || m->object != object ||
646 m->pindex != pindex || m->dirty == 0) {
653 * The page may have been busied or referenced while the object
654 * and page locks were released.
656 if (vm_page_busied(m) || vm_page_held(m)) {
664 * If a page is dirty, then it is either being washed
665 * (but not yet cleaned) or it is still in the
666 * laundry. If it is still in the laundry, then we
667 * start the cleaning operation.
669 if ((*numpagedout = vm_pageout_cluster(m)) == 0)
673 VM_OBJECT_WUNLOCK(object);
676 vm_page_lock_assert(m, MA_NOTOWNED);
680 vm_object_deallocate(object);
681 vn_finished_write(mp);
688 * Attempt to launder the specified number of pages.
690 * Returns the number of pages successfully laundered.
693 vm_pageout_launder(struct vm_domain *vmd, int launder, bool in_shortfall)
695 struct vm_pagequeue *pq;
698 int act_delta, error, maxscan, numpagedout, starting_target;
700 bool pageout_ok, queue_locked;
702 starting_target = launder;
706 * Scan the laundry queues for pages eligible to be laundered. We stop
707 * once the target number of dirty pages have been laundered, or once
708 * we've reached the end of the queue. A single iteration of this loop
709 * may cause more than one page to be laundered because of clustering.
711 * maxscan ensures that we don't re-examine requeued pages. Any
712 * additional pages written as part of a cluster are subtracted from
713 * maxscan since they must be taken from the laundry queue.
715 * As an optimization, we avoid laundering from PQ_UNSWAPPABLE when no
716 * swap devices are configured.
718 if (atomic_load_acq_int(&swapdev_enabled))
719 pq = &vmd->vmd_pagequeues[PQ_UNSWAPPABLE];
721 pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
724 vm_pagequeue_lock(pq);
725 maxscan = pq->pq_cnt;
727 for (m = TAILQ_FIRST(&pq->pq_pl);
728 m != NULL && maxscan-- > 0 && launder > 0;
730 vm_pagequeue_assert_locked(pq);
731 KASSERT(queue_locked, ("unlocked laundry queue"));
732 KASSERT(vm_page_in_laundry(m),
733 ("page %p has an inconsistent queue", m));
734 next = TAILQ_NEXT(m, plinks.q);
735 if ((m->flags & PG_MARKER) != 0)
737 KASSERT((m->flags & PG_FICTITIOUS) == 0,
738 ("PG_FICTITIOUS page %p cannot be in laundry queue", m));
739 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
740 ("VPO_UNMANAGED page %p cannot be in laundry queue", m));
741 if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
745 if (m->wire_count != 0) {
746 vm_page_dequeue_locked(m);
751 if ((!VM_OBJECT_TRYWLOCK(object) &&
752 (!vm_pageout_fallback_object_lock(m, &next) ||
753 vm_page_held(m))) || vm_page_busied(m)) {
754 VM_OBJECT_WUNLOCK(object);
755 if (m->wire_count != 0 && vm_page_pagequeue(m) == pq)
756 vm_page_dequeue_locked(m);
762 * Unlock the laundry queue, invalidating the 'next' pointer.
763 * Use a marker to remember our place in the laundry queue.
765 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_laundry_marker,
767 vm_pagequeue_unlock(pq);
768 queue_locked = false;
771 * Invalid pages can be easily freed. They cannot be
772 * mapped; vm_page_free() asserts this.
778 * If the page has been referenced and the object is not dead,
779 * reactivate or requeue the page depending on whether the
782 if ((m->aflags & PGA_REFERENCED) != 0) {
783 vm_page_aflag_clear(m, PGA_REFERENCED);
787 if (object->ref_count != 0)
788 act_delta += pmap_ts_referenced(m);
790 KASSERT(!pmap_page_is_mapped(m),
791 ("page %p is mapped", m));
793 if (act_delta != 0) {
794 if (object->ref_count != 0) {
795 VM_CNT_INC(v_reactivated);
799 * Increase the activation count if the page
800 * was referenced while in the laundry queue.
801 * This makes it less likely that the page will
802 * be returned prematurely to the inactive
805 m->act_count += act_delta + ACT_ADVANCE;
808 * If this was a background laundering, count
809 * activated pages towards our target. The
810 * purpose of background laundering is to ensure
811 * that pages are eventually cycled through the
812 * laundry queue, and an activation is a valid
818 } else if ((object->flags & OBJ_DEAD) == 0)
823 * If the page appears to be clean at the machine-independent
824 * layer, then remove all of its mappings from the pmap in
825 * anticipation of freeing it. If, however, any of the page's
826 * mappings allow write access, then the page may still be
827 * modified until the last of those mappings are removed.
829 if (object->ref_count != 0) {
830 vm_page_test_dirty(m);
836 * Clean pages are freed, and dirty pages are paged out unless
837 * they belong to a dead object. Requeueing dirty pages from
838 * dead objects is pointless, as they are being paged out and
839 * freed by the thread that destroyed the object.
845 } else if ((object->flags & OBJ_DEAD) == 0) {
846 if (object->type != OBJT_SWAP &&
847 object->type != OBJT_DEFAULT)
849 else if (disable_swap_pageouts)
855 vm_pagequeue_lock(pq);
857 vm_page_requeue_locked(m);
862 * Form a cluster with adjacent, dirty pages from the
863 * same object, and page out that entire cluster.
865 * The adjacent, dirty pages must also be in the
866 * laundry. However, their mappings are not checked
867 * for new references. Consequently, a recently
868 * referenced page may be paged out. However, that
869 * page will not be prematurely reclaimed. After page
870 * out, the page will be placed in the inactive queue,
871 * where any new references will be detected and the
874 error = vm_pageout_clean(m, &numpagedout);
876 launder -= numpagedout;
877 maxscan -= numpagedout - 1;
878 } else if (error == EDEADLK) {
886 VM_OBJECT_WUNLOCK(object);
889 vm_pagequeue_lock(pq);
892 next = TAILQ_NEXT(&vmd->vmd_laundry_marker, plinks.q);
893 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_laundry_marker, plinks.q);
895 vm_pagequeue_unlock(pq);
897 if (launder > 0 && pq == &vmd->vmd_pagequeues[PQ_UNSWAPPABLE]) {
898 pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
903 * Wakeup the sync daemon if we skipped a vnode in a writeable object
904 * and we didn't launder enough pages.
906 if (vnodes_skipped > 0 && launder > 0)
907 (void)speedup_syncer();
909 return (starting_target - launder);
913 * Compute the integer square root.
918 u_int bit, root, tmp;
920 bit = 1u << ((NBBY * sizeof(u_int)) - 2);
937 * Perform the work of the laundry thread: periodically wake up and determine
938 * whether any pages need to be laundered. If so, determine the number of pages
939 * that need to be laundered, and launder them.
942 vm_pageout_laundry_worker(void *arg)
944 struct vm_domain *vmd;
945 struct vm_pagequeue *pq;
946 uint64_t nclean, ndirty;
947 u_int inactq_scans, last_launder;
948 int domain, last_target, launder, shortfall, shortfall_cycle, target;
951 domain = (uintptr_t)arg;
952 vmd = VM_DOMAIN(domain);
953 pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
954 KASSERT(vmd->vmd_segs != 0, ("domain without segments"));
955 vm_pageout_init_marker(&vmd->vmd_laundry_marker, PQ_LAUNDRY);
958 in_shortfall = false;
965 * Calls to these handlers are serialized by the swap syscall lock.
967 (void)EVENTHANDLER_REGISTER(swapon, vm_pageout_swapon, vmd,
968 EVENTHANDLER_PRI_ANY);
969 (void)EVENTHANDLER_REGISTER(swapoff, vm_pageout_swapoff, vmd,
970 EVENTHANDLER_PRI_ANY);
973 * The pageout laundry worker is never done, so loop forever.
976 KASSERT(target >= 0, ("negative target %d", target));
977 KASSERT(shortfall_cycle >= 0,
978 ("negative cycle %d", shortfall_cycle));
982 * First determine whether we need to launder pages to meet a
983 * shortage of free pages.
987 shortfall_cycle = VM_LAUNDER_RATE / VM_INACT_SCAN_RATE;
989 } else if (!in_shortfall)
991 else if (shortfall_cycle == 0 || vm_laundry_target(vmd) <= 0) {
993 * We recently entered shortfall and began laundering
994 * pages. If we have completed that laundering run
995 * (and we are no longer in shortfall) or we have met
996 * our laundry target through other activity, then we
997 * can stop laundering pages.
999 in_shortfall = false;
1003 last_launder = inactq_scans;
1004 launder = target / shortfall_cycle--;
1008 * There's no immediate need to launder any pages; see if we
1009 * meet the conditions to perform background laundering:
1011 * 1. The ratio of dirty to clean inactive pages exceeds the
1012 * background laundering threshold and the pagedaemon has
1013 * been woken up to reclaim pages since our last
1015 * 2. we haven't yet reached the target of the current
1016 * background laundering run.
1018 * The background laundering threshold is not a constant.
1019 * Instead, it is a slowly growing function of the number of
1020 * page daemon scans since the last laundering. Thus, as the
1021 * ratio of dirty to clean inactive pages grows, the amount of
1022 * memory pressure required to trigger laundering decreases.
1025 nclean = vmd->vmd_free_count +
1026 vmd->vmd_pagequeues[PQ_INACTIVE].pq_cnt;
1027 ndirty = vmd->vmd_pagequeues[PQ_LAUNDRY].pq_cnt;
1028 if (target == 0 && inactq_scans != last_launder &&
1029 ndirty * isqrt(inactq_scans - last_launder) >= nclean) {
1030 target = vmd->vmd_background_launder_target;
1034 * We have a non-zero background laundering target. If we've
1035 * laundered up to our maximum without observing a page daemon
1036 * request, just stop. This is a safety belt that ensures we
1037 * don't launder an excessive amount if memory pressure is low
1038 * and the ratio of dirty to clean pages is large. Otherwise,
1039 * proceed at the background laundering rate.
1042 if (inactq_scans != last_launder) {
1043 last_launder = inactq_scans;
1044 last_target = target;
1045 } else if (last_target - target >=
1046 vm_background_launder_max * PAGE_SIZE / 1024) {
1049 launder = vm_background_launder_rate * PAGE_SIZE / 1024;
1050 launder /= VM_LAUNDER_RATE;
1051 if (launder > target)
1058 * Because of I/O clustering, the number of laundered
1059 * pages could exceed "target" by the maximum size of
1060 * a cluster minus one.
1062 target -= min(vm_pageout_launder(vmd, launder,
1063 in_shortfall), target);
1064 pause("laundp", hz / VM_LAUNDER_RATE);
1068 * If we're not currently laundering pages and the page daemon
1069 * hasn't posted a new request, sleep until the page daemon
1072 vm_pagequeue_lock(pq);
1073 if (target == 0 && vmd->vmd_laundry_request == VM_LAUNDRY_IDLE)
1074 (void)mtx_sleep(&vmd->vmd_laundry_request,
1075 vm_pagequeue_lockptr(pq), PVM, "launds", 0);
1078 * If the pagedaemon has indicated that it's in shortfall, start
1079 * a shortfall laundering unless we're already in the middle of
1080 * one. This may preempt a background laundering.
1082 if (vmd->vmd_laundry_request == VM_LAUNDRY_SHORTFALL &&
1083 (!in_shortfall || shortfall_cycle == 0)) {
1084 shortfall = vm_laundry_target(vmd) +
1085 vmd->vmd_pageout_deficit;
1091 vmd->vmd_laundry_request = VM_LAUNDRY_IDLE;
1092 inactq_scans = vmd->vmd_inactq_scans;
1093 vm_pagequeue_unlock(pq);
1098 * vm_pageout_scan does the dirty work for the pageout daemon.
1100 * pass == 0: Update active LRU/deactivate pages
1101 * pass >= 1: Free inactive pages
1103 * Returns true if pass was zero or enough pages were freed by the inactive
1104 * queue scan to meet the target.
1107 vm_pageout_scan(struct vm_domain *vmd, int pass)
1110 struct vm_pagequeue *pq;
1113 int act_delta, addl_page_shortage, deficit, inactq_shortage, maxscan;
1114 int page_shortage, scan_tick, scanned, starting_page_shortage;
1115 boolean_t queue_locked;
1118 * If we need to reclaim memory ask kernel caches to return
1119 * some. We rate limit to avoid thrashing.
1121 if (vmd == VM_DOMAIN(0) && pass > 0 &&
1122 (time_uptime - lowmem_uptime) >= lowmem_period) {
1124 * Decrease registered cache sizes.
1126 SDT_PROBE0(vm, , , vm__lowmem_scan);
1127 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_PAGES);
1129 * We do this explicitly after the caches have been
1133 lowmem_uptime = time_uptime;
1137 * The addl_page_shortage is the number of temporarily
1138 * stuck pages in the inactive queue. In other words, the
1139 * number of pages from the inactive count that should be
1140 * discounted in setting the target for the active queue scan.
1142 addl_page_shortage = 0;
1145 * Calculate the number of pages that we want to free. This number
1146 * can be negative if many pages are freed between the wakeup call to
1147 * the page daemon and this calculation.
1150 deficit = atomic_readandclear_int(&vmd->vmd_pageout_deficit);
1151 page_shortage = vm_paging_target(vmd) + deficit;
1153 page_shortage = deficit = 0;
1154 starting_page_shortage = page_shortage;
1157 * Start scanning the inactive queue for pages that we can free. The
1158 * scan will stop when we reach the target or we have scanned the
1159 * entire queue. (Note that m->act_count is not used to make
1160 * decisions for the inactive queue, only for the active queue.)
1162 pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
1163 maxscan = pq->pq_cnt;
1164 vm_pagequeue_lock(pq);
1165 queue_locked = TRUE;
1166 for (m = TAILQ_FIRST(&pq->pq_pl);
1167 m != NULL && maxscan-- > 0 && page_shortage > 0;
1169 vm_pagequeue_assert_locked(pq);
1170 KASSERT(queue_locked, ("unlocked inactive queue"));
1171 KASSERT(vm_page_inactive(m), ("Inactive queue %p", m));
1173 VM_CNT_INC(v_pdpages);
1174 next = TAILQ_NEXT(m, plinks.q);
1179 if (m->flags & PG_MARKER)
1182 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1183 ("Fictitious page %p cannot be in inactive queue", m));
1184 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1185 ("Unmanaged page %p cannot be in inactive queue", m));
1188 * The page or object lock acquisitions fail if the
1189 * page was removed from the queue or moved to a
1190 * different position within the queue. In either
1191 * case, addl_page_shortage should not be incremented.
1193 if (!vm_pageout_page_lock(m, &next))
1195 else if (m->wire_count != 0) {
1197 * Wired pages may not be freed, and unwiring a queued
1198 * page will cause it to be requeued. Thus, remove them
1199 * from the queue now to avoid unnecessary revisits.
1201 vm_page_dequeue_locked(m);
1202 addl_page_shortage++;
1204 } else if (m->hold_count != 0) {
1206 * Held pages are essentially stuck in the
1207 * queue. So, they ought to be discounted
1208 * from the inactive count. See the
1209 * calculation of inactq_shortage before the
1210 * loop over the active queue below.
1212 addl_page_shortage++;
1216 if (!VM_OBJECT_TRYWLOCK(object)) {
1217 if (!vm_pageout_fallback_object_lock(m, &next))
1219 else if (m->wire_count != 0) {
1220 vm_page_dequeue_locked(m);
1221 addl_page_shortage++;
1223 } else if (m->hold_count != 0) {
1224 addl_page_shortage++;
1228 if (vm_page_busied(m)) {
1230 * Don't mess with busy pages. Leave them at
1231 * the front of the queue. Most likely, they
1232 * are being paged out and will leave the
1233 * queue shortly after the scan finishes. So,
1234 * they ought to be discounted from the
1237 addl_page_shortage++;
1239 VM_OBJECT_WUNLOCK(object);
1244 KASSERT(!vm_page_held(m), ("Held page %p", m));
1247 * Dequeue the inactive page and unlock the inactive page
1248 * queue, invalidating the 'next' pointer. Dequeueing the
1249 * page here avoids a later reacquisition (and release) of
1250 * the inactive page queue lock when vm_page_activate(),
1251 * vm_page_free(), or vm_page_launder() is called. Use a
1252 * marker to remember our place in the inactive queue.
1254 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
1255 vm_page_dequeue_locked(m);
1256 vm_pagequeue_unlock(pq);
1257 queue_locked = FALSE;
1260 * Invalid pages can be easily freed. They cannot be
1261 * mapped, vm_page_free() asserts this.
1267 * If the page has been referenced and the object is not dead,
1268 * reactivate or requeue the page depending on whether the
1271 if ((m->aflags & PGA_REFERENCED) != 0) {
1272 vm_page_aflag_clear(m, PGA_REFERENCED);
1276 if (object->ref_count != 0) {
1277 act_delta += pmap_ts_referenced(m);
1279 KASSERT(!pmap_page_is_mapped(m),
1280 ("vm_pageout_scan: page %p is mapped", m));
1282 if (act_delta != 0) {
1283 if (object->ref_count != 0) {
1284 VM_CNT_INC(v_reactivated);
1285 vm_page_activate(m);
1288 * Increase the activation count if the page
1289 * was referenced while in the inactive queue.
1290 * This makes it less likely that the page will
1291 * be returned prematurely to the inactive
1294 m->act_count += act_delta + ACT_ADVANCE;
1296 } else if ((object->flags & OBJ_DEAD) == 0) {
1297 vm_pagequeue_lock(pq);
1298 queue_locked = TRUE;
1299 m->queue = PQ_INACTIVE;
1300 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
1301 vm_pagequeue_cnt_inc(pq);
1307 * If the page appears to be clean at the machine-independent
1308 * layer, then remove all of its mappings from the pmap in
1309 * anticipation of freeing it. If, however, any of the page's
1310 * mappings allow write access, then the page may still be
1311 * modified until the last of those mappings are removed.
1313 if (object->ref_count != 0) {
1314 vm_page_test_dirty(m);
1320 * Clean pages can be freed, but dirty pages must be sent back
1321 * to the laundry, unless they belong to a dead object.
1322 * Requeueing dirty pages from dead objects is pointless, as
1323 * they are being paged out and freed by the thread that
1324 * destroyed the object.
1326 if (m->dirty == 0) {
1329 VM_CNT_INC(v_dfree);
1331 } else if ((object->flags & OBJ_DEAD) == 0)
1335 VM_OBJECT_WUNLOCK(object);
1336 if (!queue_locked) {
1337 vm_pagequeue_lock(pq);
1338 queue_locked = TRUE;
1340 next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1341 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
1343 vm_pagequeue_unlock(pq);
1346 * Wake up the laundry thread so that it can perform any needed
1347 * laundering. If we didn't meet our target, we're in shortfall and
1348 * need to launder more aggressively. If PQ_LAUNDRY is empty and no
1349 * swap devices are configured, the laundry thread has no work to do, so
1350 * don't bother waking it up.
1352 * The laundry thread uses the number of inactive queue scans elapsed
1353 * since the last laundering to determine whether to launder again, so
1356 if (starting_page_shortage > 0) {
1357 pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
1358 vm_pagequeue_lock(pq);
1359 if (vmd->vmd_laundry_request == VM_LAUNDRY_IDLE &&
1360 (pq->pq_cnt > 0 || atomic_load_acq_int(&swapdev_enabled))) {
1361 if (page_shortage > 0) {
1362 vmd->vmd_laundry_request = VM_LAUNDRY_SHORTFALL;
1363 VM_CNT_INC(v_pdshortfalls);
1364 } else if (vmd->vmd_laundry_request !=
1365 VM_LAUNDRY_SHORTFALL)
1366 vmd->vmd_laundry_request =
1367 VM_LAUNDRY_BACKGROUND;
1368 wakeup(&vmd->vmd_laundry_request);
1370 vmd->vmd_inactq_scans++;
1371 vm_pagequeue_unlock(pq);
1375 * Wakeup the swapout daemon if we didn't free the targeted number of
1378 if (page_shortage > 0)
1382 * If the inactive queue scan fails repeatedly to meet its
1383 * target, kill the largest process.
1385 vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
1388 * Compute the number of pages we want to try to move from the
1389 * active queue to either the inactive or laundry queue.
1391 * When scanning active pages, we make clean pages count more heavily
1392 * towards the page shortage than dirty pages. This is because dirty
1393 * pages must be laundered before they can be reused and thus have less
1394 * utility when attempting to quickly alleviate a shortage. However,
1395 * this weighting also causes the scan to deactivate dirty pages more
1396 * more aggressively, improving the effectiveness of clustering and
1397 * ensuring that they can eventually be reused.
1399 inactq_shortage = vmd->vmd_inactive_target - (pq->pq_cnt +
1400 vmd->vmd_pagequeues[PQ_LAUNDRY].pq_cnt / act_scan_laundry_weight) +
1401 vm_paging_target(vmd) + deficit + addl_page_shortage;
1402 inactq_shortage *= act_scan_laundry_weight;
1404 pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1405 vm_pagequeue_lock(pq);
1406 maxscan = pq->pq_cnt;
1409 * If we're just idle polling attempt to visit every
1410 * active page within 'update_period' seconds.
1413 if (vm_pageout_update_period != 0) {
1414 min_scan = pq->pq_cnt;
1415 min_scan *= scan_tick - vmd->vmd_last_active_scan;
1416 min_scan /= hz * vm_pageout_update_period;
1419 if (min_scan > 0 || (inactq_shortage > 0 && maxscan > 0))
1420 vmd->vmd_last_active_scan = scan_tick;
1423 * Scan the active queue for pages that can be deactivated. Update
1424 * the per-page activity counter and use it to identify deactivation
1425 * candidates. Held pages may be deactivated.
1427 for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
1428 min_scan || (inactq_shortage > 0 && scanned < maxscan)); m = next,
1430 KASSERT(m->queue == PQ_ACTIVE,
1431 ("vm_pageout_scan: page %p isn't active", m));
1432 next = TAILQ_NEXT(m, plinks.q);
1433 if ((m->flags & PG_MARKER) != 0)
1435 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1436 ("Fictitious page %p cannot be in active queue", m));
1437 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1438 ("Unmanaged page %p cannot be in active queue", m));
1439 if (!vm_pageout_page_lock(m, &next)) {
1445 * The count for page daemon pages is updated after checking
1446 * the page for eligibility.
1448 VM_CNT_INC(v_pdpages);
1451 * Wired pages are dequeued lazily.
1453 if (m->wire_count != 0) {
1454 vm_page_dequeue_locked(m);
1460 * Check to see "how much" the page has been used.
1462 if ((m->aflags & PGA_REFERENCED) != 0) {
1463 vm_page_aflag_clear(m, PGA_REFERENCED);
1469 * Perform an unsynchronized object ref count check. While
1470 * the page lock ensures that the page is not reallocated to
1471 * another object, in particular, one with unmanaged mappings
1472 * that cannot support pmap_ts_referenced(), two races are,
1473 * nonetheless, possible:
1474 * 1) The count was transitioning to zero, but we saw a non-
1475 * zero value. pmap_ts_referenced() will return zero
1476 * because the page is not mapped.
1477 * 2) The count was transitioning to one, but we saw zero.
1478 * This race delays the detection of a new reference. At
1479 * worst, we will deactivate and reactivate the page.
1481 if (m->object->ref_count != 0)
1482 act_delta += pmap_ts_referenced(m);
1485 * Advance or decay the act_count based on recent usage.
1487 if (act_delta != 0) {
1488 m->act_count += ACT_ADVANCE + act_delta;
1489 if (m->act_count > ACT_MAX)
1490 m->act_count = ACT_MAX;
1492 m->act_count -= min(m->act_count, ACT_DECLINE);
1495 * Move this page to the tail of the active, inactive or laundry
1496 * queue depending on usage.
1498 if (m->act_count == 0) {
1499 /* Dequeue to avoid later lock recursion. */
1500 vm_page_dequeue_locked(m);
1503 * When not short for inactive pages, let dirty pages go
1504 * through the inactive queue before moving to the
1505 * laundry queues. This gives them some extra time to
1506 * be reactivated, potentially avoiding an expensive
1507 * pageout. During a page shortage, the inactive queue
1508 * is necessarily small, so we may move dirty pages
1509 * directly to the laundry queue.
1511 if (inactq_shortage <= 0)
1512 vm_page_deactivate(m);
1515 * Calling vm_page_test_dirty() here would
1516 * require acquisition of the object's write
1517 * lock. However, during a page shortage,
1518 * directing dirty pages into the laundry
1519 * queue is only an optimization and not a
1520 * requirement. Therefore, we simply rely on
1521 * the opportunistic updates to the page's
1522 * dirty field by the pmap.
1524 if (m->dirty == 0) {
1525 vm_page_deactivate(m);
1527 act_scan_laundry_weight;
1534 vm_page_requeue_locked(m);
1537 vm_pagequeue_unlock(pq);
1539 vm_swapout_run_idle();
1540 return (page_shortage <= 0);
1543 static int vm_pageout_oom_vote;
1546 * The pagedaemon threads randlomly select one to perform the
1547 * OOM. Trying to kill processes before all pagedaemons
1548 * failed to reach free target is premature.
1551 vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
1552 int starting_page_shortage)
1556 if (starting_page_shortage <= 0 || starting_page_shortage !=
1558 vmd->vmd_oom_seq = 0;
1561 if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1563 vmd->vmd_oom = FALSE;
1564 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1570 * Do not follow the call sequence until OOM condition is
1573 vmd->vmd_oom_seq = 0;
1578 vmd->vmd_oom = TRUE;
1579 old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1580 if (old_vote != vm_ndomains - 1)
1584 * The current pagedaemon thread is the last in the quorum to
1585 * start OOM. Initiate the selection and signaling of the
1588 vm_pageout_oom(VM_OOM_MEM);
1591 * After one round of OOM terror, recall our vote. On the
1592 * next pass, current pagedaemon would vote again if the low
1593 * memory condition is still there, due to vmd_oom being
1596 vmd->vmd_oom = FALSE;
1597 atomic_subtract_int(&vm_pageout_oom_vote, 1);
1601 * The OOM killer is the page daemon's action of last resort when
1602 * memory allocation requests have been stalled for a prolonged period
1603 * of time because it cannot reclaim memory. This function computes
1604 * the approximate number of physical pages that could be reclaimed if
1605 * the specified address space is destroyed.
1607 * Private, anonymous memory owned by the address space is the
1608 * principal resource that we expect to recover after an OOM kill.
1609 * Since the physical pages mapped by the address space's COW entries
1610 * are typically shared pages, they are unlikely to be released and so
1611 * they are not counted.
1613 * To get to the point where the page daemon runs the OOM killer, its
1614 * efforts to write-back vnode-backed pages may have stalled. This
1615 * could be caused by a memory allocation deadlock in the write path
1616 * that might be resolved by an OOM kill. Therefore, physical pages
1617 * belonging to vnode-backed objects are counted, because they might
1618 * be freed without being written out first if the address space holds
1619 * the last reference to an unlinked vnode.
1621 * Similarly, physical pages belonging to OBJT_PHYS objects are
1622 * counted because the address space might hold the last reference to
1626 vm_pageout_oom_pagecount(struct vmspace *vmspace)
1629 vm_map_entry_t entry;
1633 map = &vmspace->vm_map;
1634 KASSERT(!map->system_map, ("system map"));
1635 sx_assert(&map->lock, SA_LOCKED);
1637 for (entry = map->header.next; entry != &map->header;
1638 entry = entry->next) {
1639 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
1641 obj = entry->object.vm_object;
1644 if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
1645 obj->ref_count != 1)
1647 switch (obj->type) {
1652 res += obj->resident_page_count;
1660 vm_pageout_oom(int shortage)
1662 struct proc *p, *bigproc;
1663 vm_offset_t size, bigsize;
1669 * We keep the process bigproc locked once we find it to keep anyone
1670 * from messing with it; however, there is a possibility of
1671 * deadlock if process B is bigproc and one of its child processes
1672 * attempts to propagate a signal to B while we are waiting for A's
1673 * lock while walking this list. To avoid this, we don't block on
1674 * the process lock but just skip a process if it is already locked.
1678 sx_slock(&allproc_lock);
1679 FOREACH_PROC_IN_SYSTEM(p) {
1683 * If this is a system, protected or killed process, skip it.
1685 if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
1686 P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
1687 p->p_pid == 1 || P_KILLED(p) ||
1688 (p->p_pid < 48 && swap_pager_avail != 0)) {
1693 * If the process is in a non-running type state,
1694 * don't touch it. Check all the threads individually.
1697 FOREACH_THREAD_IN_PROC(p, td) {
1699 if (!TD_ON_RUNQ(td) &&
1700 !TD_IS_RUNNING(td) &&
1701 !TD_IS_SLEEPING(td) &&
1702 !TD_IS_SUSPENDED(td) &&
1703 !TD_IS_SWAPPED(td)) {
1715 * get the process size
1717 vm = vmspace_acquire_ref(p);
1724 sx_sunlock(&allproc_lock);
1725 if (!vm_map_trylock_read(&vm->vm_map)) {
1727 sx_slock(&allproc_lock);
1731 size = vmspace_swap_count(vm);
1732 if (shortage == VM_OOM_MEM)
1733 size += vm_pageout_oom_pagecount(vm);
1734 vm_map_unlock_read(&vm->vm_map);
1736 sx_slock(&allproc_lock);
1739 * If this process is bigger than the biggest one,
1742 if (size > bigsize) {
1743 if (bigproc != NULL)
1751 sx_sunlock(&allproc_lock);
1752 if (bigproc != NULL) {
1753 if (vm_panic_on_oom != 0)
1754 panic("out of swap space");
1756 killproc(bigproc, "out of swap space");
1757 sched_nice(bigproc, PRIO_MIN);
1759 PROC_UNLOCK(bigproc);
1764 vm_pageout_worker(void *arg)
1766 struct vm_domain *vmd;
1770 domain = (uintptr_t)arg;
1771 vmd = VM_DOMAIN(domain);
1776 * XXXKIB It could be useful to bind pageout daemon threads to
1777 * the cores belonging to the domain, from which vm_page_array
1781 KASSERT(vmd->vmd_segs != 0, ("domain without segments"));
1782 vmd->vmd_last_active_scan = ticks;
1783 vm_pageout_init_marker(&vmd->vmd_marker, PQ_INACTIVE);
1784 vm_pageout_init_marker(&vmd->vmd_inacthead, PQ_INACTIVE);
1785 TAILQ_INSERT_HEAD(&vmd->vmd_pagequeues[PQ_INACTIVE].pq_pl,
1786 &vmd->vmd_inacthead, plinks.q);
1789 * The pageout daemon worker is never done, so loop forever.
1792 vm_domain_free_lock(vmd);
1795 * Do not clear vmd_pageout_wanted until we reach our free page
1796 * target. Otherwise, we may be awakened over and over again,
1799 if (vmd->vmd_pageout_wanted && target_met)
1800 vmd->vmd_pageout_wanted = false;
1803 * Might the page daemon receive a wakeup call?
1805 if (vmd->vmd_pageout_wanted) {
1807 * No. Either vmd_pageout_wanted was set by another
1808 * thread during the previous scan, which must have
1809 * been a level 0 scan, or vmd_pageout_wanted was
1810 * already set and the scan failed to free enough
1811 * pages. If we haven't yet performed a level >= 1
1812 * (page reclamation) scan, then increase the level
1813 * and scan again now. Otherwise, sleep a bit and
1816 vm_domain_free_unlock(vmd);
1818 pause("pwait", hz / VM_INACT_SCAN_RATE);
1822 * Yes. If threads are still sleeping in vm_wait()
1823 * then we immediately start a new scan. Otherwise,
1824 * sleep until the next wakeup or until pages need to
1825 * have their reference stats updated.
1827 if (mtx_sleep(&vmd->vmd_pageout_wanted,
1828 vm_domain_free_lockptr(vmd), PDROP | PVM,
1829 "psleep", hz) == 0) {
1830 VM_CNT_INC(v_pdwakeups);
1836 target_met = vm_pageout_scan(vmd, pass);
1841 * vm_pageout_init initialises basic pageout daemon settings.
1844 vm_pageout_init_domain(int domain)
1846 struct vm_domain *vmd;
1848 vmd = VM_DOMAIN(domain);
1849 vmd->vmd_interrupt_free_min = 2;
1852 * v_free_reserved needs to include enough for the largest
1853 * swap pager structures plus enough for any pv_entry structs
1856 if (vmd->vmd_page_count > 1024)
1857 vmd->vmd_free_min = 4 + (vmd->vmd_page_count - 1024) / 200;
1859 vmd->vmd_free_min = 4;
1860 vmd->vmd_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1861 vmd->vmd_interrupt_free_min;
1862 vmd->vmd_free_reserved = vm_pageout_page_count +
1863 vmd->vmd_pageout_free_min + (vmd->vmd_page_count / 768);
1864 vmd->vmd_free_severe = vmd->vmd_free_min / 2;
1865 vmd->vmd_free_target = 4 * vmd->vmd_free_min + vmd->vmd_free_reserved;
1866 vmd->vmd_free_min += vmd->vmd_free_reserved;
1867 vmd->vmd_free_severe += vmd->vmd_free_reserved;
1868 vmd->vmd_inactive_target = (3 * vmd->vmd_free_target) / 2;
1869 if (vmd->vmd_inactive_target > vmd->vmd_free_count / 3)
1870 vmd->vmd_inactive_target = vmd->vmd_free_count / 3;
1873 * Set the default wakeup threshold to be 10% above the minimum
1874 * page limit. This keeps the steady state out of shortfall.
1876 vmd->vmd_pageout_wakeup_thresh = (vmd->vmd_free_min / 10) * 11;
1879 * Target amount of memory to move out of the laundry queue during a
1880 * background laundering. This is proportional to the amount of system
1883 vmd->vmd_background_launder_target = (vmd->vmd_free_target -
1884 vmd->vmd_free_min) / 10;
1888 vm_pageout_init(void)
1894 * Initialize some paging parameters.
1896 if (vm_cnt.v_page_count < 2000)
1897 vm_pageout_page_count = 8;
1900 for (i = 0; i < vm_ndomains; i++) {
1901 struct vm_domain *vmd;
1903 vm_pageout_init_domain(i);
1905 vm_cnt.v_free_reserved += vmd->vmd_free_reserved;
1906 vm_cnt.v_free_target += vmd->vmd_free_target;
1907 vm_cnt.v_free_min += vmd->vmd_free_min;
1908 vm_cnt.v_inactive_target += vmd->vmd_inactive_target;
1909 vm_cnt.v_pageout_free_min += vmd->vmd_pageout_free_min;
1910 vm_cnt.v_interrupt_free_min += vmd->vmd_interrupt_free_min;
1911 vm_cnt.v_free_severe += vmd->vmd_free_severe;
1912 freecount += vmd->vmd_free_count;
1916 * Set interval in seconds for active scan. We want to visit each
1917 * page at least once every ten minutes. This is to prevent worst
1918 * case paging behaviors with stale active LRU.
1920 if (vm_pageout_update_period == 0)
1921 vm_pageout_update_period = 600;
1923 if (vm_page_max_wired == 0)
1924 vm_page_max_wired = freecount / 3;
1928 * vm_pageout is the high level pageout daemon.
1936 swap_pager_swap_init();
1937 error = kthread_add(vm_pageout_laundry_worker, NULL, curproc, NULL,
1938 0, 0, "laundry: dom0");
1940 panic("starting laundry for domain 0, error %d", error);
1941 for (i = 1; i < vm_ndomains; i++) {
1942 error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
1943 curproc, NULL, 0, 0, "dom%d", i);
1945 panic("starting pageout for domain %d, error %d\n",
1948 error = kthread_add(vm_pageout_laundry_worker,
1949 (void *)(uintptr_t)i, curproc, NULL, 0, 0,
1950 "laundry: dom%d", i);
1952 panic("starting laundry for domain %d, error %d",
1955 error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
1958 panic("starting uma_reclaim helper, error %d\n", error);
1959 vm_pageout_worker((void *)(uintptr_t)0);
1963 * Perform an advisory wakeup of the page daemon.
1966 pagedaemon_wakeup(int domain)
1968 struct vm_domain *vmd;
1970 vmd = VM_DOMAIN(domain);
1971 vm_domain_free_assert_unlocked(vmd);
1973 if (!vmd->vmd_pageout_wanted && curthread->td_proc != pageproc) {
1974 vmd->vmd_pageout_wanted = true;
1975 wakeup(&vmd->vmd_pageout_wanted);