xref: /freebsd/sys/vm/vm_pageout.c (revision 57cd81a3575a90d6d8698080a2d746fc6ecba675)
160727d8bSWarner Losh /*-
2df57947fSPedro F. Giffuni  * SPDX-License-Identifier: BSD-4-Clause
3df57947fSPedro F. Giffuni  *
426f9a767SRodney W. Grimes  * Copyright (c) 1991 Regents of the University of California.
526f9a767SRodney W. Grimes  * All rights reserved.
626f9a767SRodney W. Grimes  * Copyright (c) 1994 John S. Dyson
726f9a767SRodney W. Grimes  * All rights reserved.
826f9a767SRodney W. Grimes  * Copyright (c) 1994 David Greenman
926f9a767SRodney W. Grimes  * All rights reserved.
108dbca793STor Egge  * Copyright (c) 2005 Yahoo! Technologies Norway AS
118dbca793STor Egge  * All rights reserved.
12df8bae1dSRodney W. Grimes  *
13df8bae1dSRodney W. Grimes  * This code is derived from software contributed to Berkeley by
14df8bae1dSRodney W. Grimes  * The Mach Operating System project at Carnegie-Mellon University.
15df8bae1dSRodney W. Grimes  *
16df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
17df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
18df8bae1dSRodney W. Grimes  * are met:
19df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
20df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
21df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
22df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
23df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
24df8bae1dSRodney W. Grimes  * 3. All advertising materials mentioning features or use of this software
255929bcfaSPhilippe Charnier  *    must display the following acknowledgement:
26df8bae1dSRodney W. Grimes  *	This product includes software developed by the University of
27df8bae1dSRodney W. Grimes  *	California, Berkeley and its contributors.
28df8bae1dSRodney W. Grimes  * 4. Neither the name of the University nor the names of its contributors
29df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
30df8bae1dSRodney W. Grimes  *    without specific prior written permission.
31df8bae1dSRodney W. Grimes  *
32df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
33df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
36df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
43df8bae1dSRodney W. Grimes  *
443c4dd356SDavid Greenman  *	from: @(#)vm_pageout.c	7.4 (Berkeley) 5/7/91
45df8bae1dSRodney W. Grimes  *
46df8bae1dSRodney W. Grimes  *
47df8bae1dSRodney W. Grimes  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
48df8bae1dSRodney W. Grimes  * All rights reserved.
49df8bae1dSRodney W. Grimes  *
50df8bae1dSRodney W. Grimes  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
51df8bae1dSRodney W. Grimes  *
52df8bae1dSRodney W. Grimes  * Permission to use, copy, modify and distribute this software and
53df8bae1dSRodney W. Grimes  * its documentation is hereby granted, provided that both the copyright
54df8bae1dSRodney W. Grimes  * notice and this permission notice appear in all copies of the
55df8bae1dSRodney W. Grimes  * software, derivative works or modified versions, and any portions
56df8bae1dSRodney W. Grimes  * thereof, and that both notices appear in supporting documentation.
57df8bae1dSRodney W. Grimes  *
58df8bae1dSRodney W. Grimes  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
59df8bae1dSRodney W. Grimes  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
60df8bae1dSRodney W. Grimes  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
61df8bae1dSRodney W. Grimes  *
62df8bae1dSRodney W. Grimes  * Carnegie Mellon requests users of this software to return to
63df8bae1dSRodney W. Grimes  *
64df8bae1dSRodney W. Grimes  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
65df8bae1dSRodney W. Grimes  *  School of Computer Science
66df8bae1dSRodney W. Grimes  *  Carnegie Mellon University
67df8bae1dSRodney W. Grimes  *  Pittsburgh PA 15213-3890
68df8bae1dSRodney W. Grimes  *
69df8bae1dSRodney W. Grimes  * any improvements or extensions that they make and grant Carnegie the
70df8bae1dSRodney W. Grimes  * rights to redistribute these changes.
71df8bae1dSRodney W. Grimes  */
72df8bae1dSRodney W. Grimes 
73df8bae1dSRodney W. Grimes /*
74df8bae1dSRodney W. Grimes  *	The proverbial page-out daemon.
75df8bae1dSRodney W. Grimes  */
76df8bae1dSRodney W. Grimes 
77874651b1SDavid E. O'Brien #include <sys/cdefs.h>
78874651b1SDavid E. O'Brien __FBSDID("$FreeBSD$");
79874651b1SDavid E. O'Brien 
80faa5f8d8SAndrzej Bialecki #include "opt_vm.h"
817672ca05SMark Johnston 
82df8bae1dSRodney W. Grimes #include <sys/param.h>
8326f9a767SRodney W. Grimes #include <sys/systm.h>
84b5e8ce9fSBruce Evans #include <sys/kernel.h>
85855a310fSJeff Roberson #include <sys/eventhandler.h>
86fb919e4dSMark Murray #include <sys/lock.h>
87fb919e4dSMark Murray #include <sys/mutex.h>
8826f9a767SRodney W. Grimes #include <sys/proc.h>
899c8b8baaSPeter Wemm #include <sys/kthread.h>
900384fff8SJason Evans #include <sys/ktr.h>
9197824da3SAlan Cox #include <sys/mount.h>
92099e7e95SEdward Tomasz Napierala #include <sys/racct.h>
9326f9a767SRodney W. Grimes #include <sys/resourcevar.h>
94b43179fbSJeff Roberson #include <sys/sched.h>
9514a0d74eSSteven Hartland #include <sys/sdt.h>
96d2fc5315SPoul-Henning Kamp #include <sys/signalvar.h>
97449c2e92SKonstantin Belousov #include <sys/smp.h>
98a6bf3a9eSRyan Stone #include <sys/time.h>
99f6b04d2bSDavid Greenman #include <sys/vnode.h>
100efeaf95aSDavid Greenman #include <sys/vmmeter.h>
10189f6b863SAttilio Rao #include <sys/rwlock.h>
1021005a129SJohn Baldwin #include <sys/sx.h>
10338efa82bSJohn Dyson #include <sys/sysctl.h>
104df8bae1dSRodney W. Grimes 
105df8bae1dSRodney W. Grimes #include <vm/vm.h>
106efeaf95aSDavid Greenman #include <vm/vm_param.h>
107efeaf95aSDavid Greenman #include <vm/vm_object.h>
108df8bae1dSRodney W. Grimes #include <vm/vm_page.h>
109efeaf95aSDavid Greenman #include <vm/vm_map.h>
110df8bae1dSRodney W. Grimes #include <vm/vm_pageout.h>
11124a1cce3SDavid Greenman #include <vm/vm_pager.h>
112449c2e92SKonstantin Belousov #include <vm/vm_phys.h>
11305f0fdd2SPoul-Henning Kamp #include <vm/swap_pager.h>
114efeaf95aSDavid Greenman #include <vm/vm_extern.h>
115670d17b5SJeff Roberson #include <vm/uma.h>
116df8bae1dSRodney W. Grimes 
1172b14f991SJulian Elischer /*
1182b14f991SJulian Elischer  * System initialization
1192b14f991SJulian Elischer  */
1202b14f991SJulian Elischer 
1212b14f991SJulian Elischer /* the kernel process "vm_pageout"*/
12211caded3SAlfred Perlstein static void vm_pageout(void);
1234d19f4adSSteven Hartland static void vm_pageout_init(void);
124ebcddc72SAlan Cox static int vm_pageout_clean(vm_page_t m, int *numpagedout);
12534d8b7eaSJeff Roberson static int vm_pageout_cluster(vm_page_t m);
126e57dd910SAlan Cox static bool vm_pageout_scan(struct vm_domain *vmd, int pass);
12776386c7eSKonstantin Belousov static void vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
12876386c7eSKonstantin Belousov     int starting_page_shortage);
12945ae1d91SAlan Cox 
1304d19f4adSSteven Hartland SYSINIT(pagedaemon_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, vm_pageout_init,
1314d19f4adSSteven Hartland     NULL);
1324d19f4adSSteven Hartland 
1332b14f991SJulian Elischer struct proc *pageproc;
1342b14f991SJulian Elischer 
1352b14f991SJulian Elischer static struct kproc_desc page_kp = {
1362b14f991SJulian Elischer 	"pagedaemon",
1372b14f991SJulian Elischer 	vm_pageout,
1382b14f991SJulian Elischer 	&pageproc
1392b14f991SJulian Elischer };
1404d19f4adSSteven Hartland SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_SECOND, kproc_start,
141237fdd78SRobert Watson     &page_kp);
1422b14f991SJulian Elischer 
14314a0d74eSSteven Hartland SDT_PROVIDER_DEFINE(vm);
14414a0d74eSSteven Hartland SDT_PROBE_DEFINE(vm, , , vm__lowmem_scan);
14514a0d74eSSteven Hartland 
146ebcddc72SAlan Cox /* Pagedaemon activity rates, in subdivisions of one second. */
147ebcddc72SAlan Cox #define	VM_LAUNDER_RATE		10
148ebcddc72SAlan Cox #define	VM_INACT_SCAN_RATE	2
1492b14f991SJulian Elischer 
1508b245767SAlan Cox int vm_pageout_deficit;		/* Estimated number of pages deficit */
15120c58db9SMark Johnston u_int vm_pageout_wakeup_thresh;
15276386c7eSKonstantin Belousov static int vm_pageout_oom_seq = 12;
15356ce0690SAlan Cox bool vm_pageout_wanted;		/* Event on which pageout daemon sleeps */
15456ce0690SAlan Cox bool vm_pages_needed;		/* Are threads waiting for free pages? */
15526f9a767SRodney W. Grimes 
156ebcddc72SAlan Cox /* Pending request for dirty page laundering. */
157ebcddc72SAlan Cox static enum {
158ebcddc72SAlan Cox 	VM_LAUNDRY_IDLE,
159ebcddc72SAlan Cox 	VM_LAUNDRY_BACKGROUND,
160ebcddc72SAlan Cox 	VM_LAUNDRY_SHORTFALL
161ebcddc72SAlan Cox } vm_laundry_request = VM_LAUNDRY_IDLE;
162ebcddc72SAlan Cox 
163d9e23210SJeff Roberson static int vm_pageout_update_period;
1644a365329SAndrey Zonov static int disable_swap_pageouts;
165c9612b2dSJeff Roberson static int lowmem_period = 10;
166a6bf3a9eSRyan Stone static time_t lowmem_uptime;
167b1fd102eSMark Johnston static int swapdev_enabled;
16870111b90SJohn Dyson 
1698311a2b8SWill Andrews static int vm_panic_on_oom = 0;
1708311a2b8SWill Andrews 
1718311a2b8SWill Andrews SYSCTL_INT(_vm, OID_AUTO, panic_on_oom,
1728311a2b8SWill Andrews 	CTLFLAG_RWTUN, &vm_panic_on_oom, 0,
1738311a2b8SWill Andrews 	"panic on out of memory instead of killing the largest process");
1748311a2b8SWill Andrews 
175d9e23210SJeff Roberson SYSCTL_INT(_vm, OID_AUTO, pageout_wakeup_thresh,
176e0b2fc3aSMark Johnston 	CTLFLAG_RWTUN, &vm_pageout_wakeup_thresh, 0,
177d9e23210SJeff Roberson 	"free page threshold for waking up the pageout daemon");
178d9e23210SJeff Roberson 
179d9e23210SJeff Roberson SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
180e0b2fc3aSMark Johnston 	CTLFLAG_RWTUN, &vm_pageout_update_period, 0,
181d9e23210SJeff Roberson 	"Maximum active LRU update period");
18253636869SAndrey Zonov 
183e0b2fc3aSMark Johnston SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RWTUN, &lowmem_period, 0,
184c9612b2dSJeff Roberson 	"Low memory callback period");
185c9612b2dSJeff Roberson 
186ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
187e0b2fc3aSMark Johnston 	CTLFLAG_RWTUN, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
18812ac6a1dSJohn Dyson 
18923b59018SMatthew Dillon static int pageout_lock_miss;
19023b59018SMatthew Dillon SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
19123b59018SMatthew Dillon 	CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
19223b59018SMatthew Dillon 
19376386c7eSKonstantin Belousov SYSCTL_INT(_vm, OID_AUTO, pageout_oom_seq,
194e0b2fc3aSMark Johnston 	CTLFLAG_RWTUN, &vm_pageout_oom_seq, 0,
19576386c7eSKonstantin Belousov 	"back-to-back calls to oom detector to start OOM");
19676386c7eSKonstantin Belousov 
197ebcddc72SAlan Cox static int act_scan_laundry_weight = 3;
198e0b2fc3aSMark Johnston SYSCTL_INT(_vm, OID_AUTO, act_scan_laundry_weight, CTLFLAG_RWTUN,
199ebcddc72SAlan Cox     &act_scan_laundry_weight, 0,
200ebcddc72SAlan Cox     "weight given to clean vs. dirty pages in active queue scans");
201ebcddc72SAlan Cox 
202ebcddc72SAlan Cox static u_int vm_background_launder_target;
203e0b2fc3aSMark Johnston SYSCTL_UINT(_vm, OID_AUTO, background_launder_target, CTLFLAG_RWTUN,
204ebcddc72SAlan Cox     &vm_background_launder_target, 0,
205ebcddc72SAlan Cox     "background laundering target, in pages");
206ebcddc72SAlan Cox 
207ebcddc72SAlan Cox static u_int vm_background_launder_rate = 4096;
208e0b2fc3aSMark Johnston SYSCTL_UINT(_vm, OID_AUTO, background_launder_rate, CTLFLAG_RWTUN,
209ebcddc72SAlan Cox     &vm_background_launder_rate, 0,
210ebcddc72SAlan Cox     "background laundering rate, in kilobytes per second");
211ebcddc72SAlan Cox 
212ebcddc72SAlan Cox static u_int vm_background_launder_max = 20 * 1024;
213e0b2fc3aSMark Johnston SYSCTL_UINT(_vm, OID_AUTO, background_launder_max, CTLFLAG_RWTUN,
214ebcddc72SAlan Cox     &vm_background_launder_max, 0, "background laundering cap, in kilobytes");
215ebcddc72SAlan Cox 
216e2241590SAlan Cox int vm_pageout_page_count = 32;
217df8bae1dSRodney W. Grimes 
218c3cb3e12SDavid Greenman int vm_page_max_wired;		/* XXX max # of wired pages system-wide */
2195dfc2870SAlan Cox SYSCTL_INT(_vm, OID_AUTO, max_wired,
2205dfc2870SAlan Cox 	CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
221df8bae1dSRodney W. Grimes 
222ebcddc72SAlan Cox static u_int isqrt(u_int num);
22385eeca35SAlan Cox static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
224ebcddc72SAlan Cox static int vm_pageout_launder(struct vm_domain *vmd, int launder,
225ebcddc72SAlan Cox     bool in_shortfall);
226ebcddc72SAlan Cox static void vm_pageout_laundry_worker(void *arg);
22785eeca35SAlan Cox static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
228cd41fc12SDavid Greenman 
229a8229fa3SAlan Cox /*
230a8229fa3SAlan Cox  * Initialize a dummy page for marking the caller's place in the specified
231a8229fa3SAlan Cox  * paging queue.  In principle, this function only needs to set the flag
232f0edf3f8SAlan Cox  * PG_MARKER.  Nonetheless, it write busies and initializes the hold count
233c7aebda8SAttilio Rao  * to one as safety precautions.
234a8229fa3SAlan Cox  */
2358c616246SKonstantin Belousov static void
2368c616246SKonstantin Belousov vm_pageout_init_marker(vm_page_t marker, u_short queue)
2378c616246SKonstantin Belousov {
2388c616246SKonstantin Belousov 
2398c616246SKonstantin Belousov 	bzero(marker, sizeof(*marker));
240a8229fa3SAlan Cox 	marker->flags = PG_MARKER;
241c7aebda8SAttilio Rao 	marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
2428c616246SKonstantin Belousov 	marker->queue = queue;
243a8229fa3SAlan Cox 	marker->hold_count = 1;
2448c616246SKonstantin Belousov }
2458c616246SKonstantin Belousov 
24626f9a767SRodney W. Grimes /*
2478dbca793STor Egge  * vm_pageout_fallback_object_lock:
2488dbca793STor Egge  *
24989f6b863SAttilio Rao  * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
2508dbca793STor Egge  * known to have failed and page queue must be either PQ_ACTIVE or
25144be0a8eSMark Johnston  * PQ_INACTIVE.  To avoid lock order violation, unlock the page queue
2528dbca793STor Egge  * while locking the vm object.  Use marker page to detect page queue
2538dbca793STor Egge  * changes and maintain notion of next page on page queue.  Return
2548dbca793STor Egge  * TRUE if no changes were detected, FALSE otherwise.  vm object is
2558dbca793STor Egge  * locked on return.
2568dbca793STor Egge  *
2578dbca793STor Egge  * This function depends on both the lock portion of struct vm_object
2588dbca793STor Egge  * and normal struct vm_page being type stable.
2598dbca793STor Egge  */
26085eeca35SAlan Cox static boolean_t
2618dbca793STor Egge vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
2628dbca793STor Egge {
2638dbca793STor Egge 	struct vm_page marker;
2648d220203SAlan Cox 	struct vm_pagequeue *pq;
2658dbca793STor Egge 	boolean_t unchanged;
2668dbca793STor Egge 	u_short queue;
2678dbca793STor Egge 	vm_object_t object;
2688dbca793STor Egge 
2698dbca793STor Egge 	queue = m->queue;
2708c616246SKonstantin Belousov 	vm_pageout_init_marker(&marker, queue);
271449c2e92SKonstantin Belousov 	pq = vm_page_pagequeue(m);
2728dbca793STor Egge 	object = m->object;
2738dbca793STor Egge 
274c325e866SKonstantin Belousov 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
2758d220203SAlan Cox 	vm_pagequeue_unlock(pq);
2762965a453SKip Macy 	vm_page_unlock(m);
27789f6b863SAttilio Rao 	VM_OBJECT_WLOCK(object);
2782965a453SKip Macy 	vm_page_lock(m);
2798d220203SAlan Cox 	vm_pagequeue_lock(pq);
2808dbca793STor Egge 
28169b8585eSKonstantin Belousov 	/*
28269b8585eSKonstantin Belousov 	 * The page's object might have changed, and/or the page might
28369b8585eSKonstantin Belousov 	 * have moved from its original position in the queue.  If the
28469b8585eSKonstantin Belousov 	 * page's object has changed, then the caller should abandon
28569b8585eSKonstantin Belousov 	 * processing the page because the wrong object lock was
28669b8585eSKonstantin Belousov 	 * acquired.  Use the marker's plinks.q, not the page's, to
28769b8585eSKonstantin Belousov 	 * determine if the page has been moved.  The state of the
28869b8585eSKonstantin Belousov 	 * page's plinks.q can be indeterminate; whereas, the marker's
28969b8585eSKonstantin Belousov 	 * plinks.q must be valid.
29069b8585eSKonstantin Belousov 	 */
291c325e866SKonstantin Belousov 	*next = TAILQ_NEXT(&marker, plinks.q);
29269b8585eSKonstantin Belousov 	unchanged = m->object == object &&
29369b8585eSKonstantin Belousov 	    m == TAILQ_PREV(&marker, pglist, plinks.q);
29469b8585eSKonstantin Belousov 	KASSERT(!unchanged || m->queue == queue,
29569b8585eSKonstantin Belousov 	    ("page %p queue %d %d", m, queue, m->queue));
296c325e866SKonstantin Belousov 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
2978dbca793STor Egge 	return (unchanged);
2988dbca793STor Egge }
2998dbca793STor Egge 
3008dbca793STor Egge /*
3018c616246SKonstantin Belousov  * Lock the page while holding the page queue lock.  Use marker page
3028c616246SKonstantin Belousov  * to detect page queue changes and maintain notion of next page on
3038c616246SKonstantin Belousov  * page queue.  Return TRUE if no changes were detected, FALSE
3048c616246SKonstantin Belousov  * otherwise.  The page is locked on return. The page queue lock might
3058c616246SKonstantin Belousov  * be dropped and reacquired.
3068c616246SKonstantin Belousov  *
3078c616246SKonstantin Belousov  * This function depends on normal struct vm_page being type stable.
3088c616246SKonstantin Belousov  */
30985eeca35SAlan Cox static boolean_t
3108c616246SKonstantin Belousov vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
3118c616246SKonstantin Belousov {
3128c616246SKonstantin Belousov 	struct vm_page marker;
3138d220203SAlan Cox 	struct vm_pagequeue *pq;
3148c616246SKonstantin Belousov 	boolean_t unchanged;
3158c616246SKonstantin Belousov 	u_short queue;
3168c616246SKonstantin Belousov 
3178c616246SKonstantin Belousov 	vm_page_lock_assert(m, MA_NOTOWNED);
3188c616246SKonstantin Belousov 	if (vm_page_trylock(m))
3198c616246SKonstantin Belousov 		return (TRUE);
3208c616246SKonstantin Belousov 
3218c616246SKonstantin Belousov 	queue = m->queue;
3228c616246SKonstantin Belousov 	vm_pageout_init_marker(&marker, queue);
323449c2e92SKonstantin Belousov 	pq = vm_page_pagequeue(m);
3248c616246SKonstantin Belousov 
325c325e866SKonstantin Belousov 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
3268d220203SAlan Cox 	vm_pagequeue_unlock(pq);
3278c616246SKonstantin Belousov 	vm_page_lock(m);
3288d220203SAlan Cox 	vm_pagequeue_lock(pq);
3298c616246SKonstantin Belousov 
3308c616246SKonstantin Belousov 	/* Page queue might have changed. */
331c325e866SKonstantin Belousov 	*next = TAILQ_NEXT(&marker, plinks.q);
33269b8585eSKonstantin Belousov 	unchanged = m == TAILQ_PREV(&marker, pglist, plinks.q);
33369b8585eSKonstantin Belousov 	KASSERT(!unchanged || m->queue == queue,
33469b8585eSKonstantin Belousov 	    ("page %p queue %d %d", m, queue, m->queue));
335c325e866SKonstantin Belousov 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
3368c616246SKonstantin Belousov 	return (unchanged);
3378c616246SKonstantin Belousov }
3388c616246SKonstantin Belousov 
3398c616246SKonstantin Belousov /*
340248fe642SAlan Cox  * Scan for pages at adjacent offsets within the given page's object that are
341248fe642SAlan Cox  * eligible for laundering, form a cluster of these pages and the given page,
342248fe642SAlan Cox  * and launder that cluster.
34326f9a767SRodney W. Grimes  */
3443af76890SPoul-Henning Kamp static int
34534d8b7eaSJeff Roberson vm_pageout_cluster(vm_page_t m)
34624a1cce3SDavid Greenman {
34754d92145SMatthew Dillon 	vm_object_t object;
348248fe642SAlan Cox 	vm_page_t mc[2 * vm_pageout_page_count], p, pb, ps;
349248fe642SAlan Cox 	vm_pindex_t pindex;
350248fe642SAlan Cox 	int ib, is, page_base, pageout_count;
35126f9a767SRodney W. Grimes 
352248fe642SAlan Cox 	vm_page_assert_locked(m);
35317f6a17bSAlan Cox 	object = m->object;
35489f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
355248fe642SAlan Cox 	pindex = m->pindex;
3560cddd8f0SMatthew Dillon 
35726f9a767SRodney W. Grimes 	/*
358248fe642SAlan Cox 	 * We can't clean the page if it is busy or held.
35924a1cce3SDavid Greenman 	 */
360c7aebda8SAttilio Rao 	vm_page_assert_unbusied(m);
361248fe642SAlan Cox 	KASSERT(m->hold_count == 0, ("page %p is held", m));
362aed9aaaaSMark Johnston 
363aed9aaaaSMark Johnston 	pmap_remove_write(m);
36417f6a17bSAlan Cox 	vm_page_unlock(m);
3650d94caffSDavid Greenman 
36691b4f427SAlan Cox 	mc[vm_pageout_page_count] = pb = ps = m;
36726f9a767SRodney W. Grimes 	pageout_count = 1;
368f35329acSJohn Dyson 	page_base = vm_pageout_page_count;
36990ecac61SMatthew Dillon 	ib = 1;
37090ecac61SMatthew Dillon 	is = 1;
37190ecac61SMatthew Dillon 
37224a1cce3SDavid Greenman 	/*
373248fe642SAlan Cox 	 * We can cluster only if the page is not clean, busy, or held, and
374ebcddc72SAlan Cox 	 * the page is in the laundry queue.
37590ecac61SMatthew Dillon 	 *
37690ecac61SMatthew Dillon 	 * During heavy mmap/modification loads the pageout
37790ecac61SMatthew Dillon 	 * daemon can really fragment the underlying file
378248fe642SAlan Cox 	 * due to flushing pages out of order and not trying to
379248fe642SAlan Cox 	 * align the clusters (which leaves sporadic out-of-order
38090ecac61SMatthew Dillon 	 * holes).  To solve this problem we do the reverse scan
38190ecac61SMatthew Dillon 	 * first and attempt to align our cluster, then do a
38290ecac61SMatthew Dillon 	 * forward scan if room remains.
38324a1cce3SDavid Greenman 	 */
38490ecac61SMatthew Dillon more:
385248fe642SAlan Cox 	while (ib != 0 && pageout_count < vm_pageout_page_count) {
38690ecac61SMatthew Dillon 		if (ib > pindex) {
38790ecac61SMatthew Dillon 			ib = 0;
38890ecac61SMatthew Dillon 			break;
389f6b04d2bSDavid Greenman 		}
390c7aebda8SAttilio Rao 		if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
39190ecac61SMatthew Dillon 			ib = 0;
39290ecac61SMatthew Dillon 			break;
393f6b04d2bSDavid Greenman 		}
39424a1cce3SDavid Greenman 		vm_page_test_dirty(p);
395eb5d3969SAlan Cox 		if (p->dirty == 0) {
396eb5d3969SAlan Cox 			ib = 0;
397eb5d3969SAlan Cox 			break;
398eb5d3969SAlan Cox 		}
399eb5d3969SAlan Cox 		vm_page_lock(p);
400ebcddc72SAlan Cox 		if (!vm_page_in_laundry(p) ||
40157601bcbSMatthew Dillon 		    p->hold_count != 0) {	/* may be undergoing I/O */
4022965a453SKip Macy 			vm_page_unlock(p);
40390ecac61SMatthew Dillon 			ib = 0;
40424a1cce3SDavid Greenman 			break;
405f6b04d2bSDavid Greenman 		}
406aed9aaaaSMark Johnston 		pmap_remove_write(p);
4072965a453SKip Macy 		vm_page_unlock(p);
40891b4f427SAlan Cox 		mc[--page_base] = pb = p;
40990ecac61SMatthew Dillon 		++pageout_count;
41090ecac61SMatthew Dillon 		++ib;
411248fe642SAlan Cox 
41224a1cce3SDavid Greenman 		/*
413248fe642SAlan Cox 		 * We are at an alignment boundary.  Stop here, and switch
414248fe642SAlan Cox 		 * directions.  Do not clear ib.
41524a1cce3SDavid Greenman 		 */
41690ecac61SMatthew Dillon 		if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
41790ecac61SMatthew Dillon 			break;
41824a1cce3SDavid Greenman 	}
41990ecac61SMatthew Dillon 	while (pageout_count < vm_pageout_page_count &&
42090ecac61SMatthew Dillon 	    pindex + is < object->size) {
421c7aebda8SAttilio Rao 		if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
42290ecac61SMatthew Dillon 			break;
42324a1cce3SDavid Greenman 		vm_page_test_dirty(p);
424eb5d3969SAlan Cox 		if (p->dirty == 0)
425eb5d3969SAlan Cox 			break;
426eb5d3969SAlan Cox 		vm_page_lock(p);
427ebcddc72SAlan Cox 		if (!vm_page_in_laundry(p) ||
42857601bcbSMatthew Dillon 		    p->hold_count != 0) {	/* may be undergoing I/O */
4292965a453SKip Macy 			vm_page_unlock(p);
43024a1cce3SDavid Greenman 			break;
43124a1cce3SDavid Greenman 		}
432aed9aaaaSMark Johnston 		pmap_remove_write(p);
4332965a453SKip Macy 		vm_page_unlock(p);
43491b4f427SAlan Cox 		mc[page_base + pageout_count] = ps = p;
43590ecac61SMatthew Dillon 		++pageout_count;
43690ecac61SMatthew Dillon 		++is;
43724a1cce3SDavid Greenman 	}
43890ecac61SMatthew Dillon 
43990ecac61SMatthew Dillon 	/*
44090ecac61SMatthew Dillon 	 * If we exhausted our forward scan, continue with the reverse scan
441248fe642SAlan Cox 	 * when possible, even past an alignment boundary.  This catches
442248fe642SAlan Cox 	 * boundary conditions.
44390ecac61SMatthew Dillon 	 */
444248fe642SAlan Cox 	if (ib != 0 && pageout_count < vm_pageout_page_count)
44590ecac61SMatthew Dillon 		goto more;
446f6b04d2bSDavid Greenman 
44799e6e193SMark Johnston 	return (vm_pageout_flush(&mc[page_base], pageout_count,
44899e6e193SMark Johnston 	    VM_PAGER_PUT_NOREUSE, 0, NULL, NULL));
449aef922f5SJohn Dyson }
450aef922f5SJohn Dyson 
4511c7c3c6aSMatthew Dillon /*
4521c7c3c6aSMatthew Dillon  * vm_pageout_flush() - launder the given pages
4531c7c3c6aSMatthew Dillon  *
4541c7c3c6aSMatthew Dillon  *	The given pages are laundered.  Note that we setup for the start of
4551c7c3c6aSMatthew Dillon  *	I/O ( i.e. busy the page ), mark it read-only, and bump the object
4561c7c3c6aSMatthew Dillon  *	reference count all in here rather then in the parent.  If we want
4571c7c3c6aSMatthew Dillon  *	the parent to do more sophisticated things we may have to change
4581c7c3c6aSMatthew Dillon  *	the ordering.
4591e8a675cSKonstantin Belousov  *
4601e8a675cSKonstantin Belousov  *	Returned runlen is the count of pages between mreq and first
4611e8a675cSKonstantin Belousov  *	page after mreq with status VM_PAGER_AGAIN.
462126d6082SKonstantin Belousov  *	*eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
463126d6082SKonstantin Belousov  *	for any page in runlen set.
4641c7c3c6aSMatthew Dillon  */
465aef922f5SJohn Dyson int
466126d6082SKonstantin Belousov vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
467126d6082SKonstantin Belousov     boolean_t *eio)
468aef922f5SJohn Dyson {
4692e3b314dSAlan Cox 	vm_object_t object = mc[0]->object;
470aef922f5SJohn Dyson 	int pageout_status[count];
47195461b45SJohn Dyson 	int numpagedout = 0;
4721e8a675cSKonstantin Belousov 	int i, runlen;
473aef922f5SJohn Dyson 
47489f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
4757bec141bSKip Macy 
4761c7c3c6aSMatthew Dillon 	/*
477aed9aaaaSMark Johnston 	 * Initiate I/O.  Mark the pages busy and verify that they're valid
478aed9aaaaSMark Johnston 	 * and read-only.
4791c7c3c6aSMatthew Dillon 	 *
4801c7c3c6aSMatthew Dillon 	 * We do not have to fixup the clean/dirty bits here... we can
4811c7c3c6aSMatthew Dillon 	 * allow the pager to do it after the I/O completes.
48202fa91d3SMatthew Dillon 	 *
48302fa91d3SMatthew Dillon 	 * NOTE! mc[i]->dirty may be partial or fragmented due to an
48402fa91d3SMatthew Dillon 	 * edge case with file fragments.
4851c7c3c6aSMatthew Dillon 	 */
4868f9110f6SJohn Dyson 	for (i = 0; i < count; i++) {
4877a935082SAlan Cox 		KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
4887a935082SAlan Cox 		    ("vm_pageout_flush: partially invalid page %p index %d/%d",
4897a935082SAlan Cox 			mc[i], i, count));
490aed9aaaaSMark Johnston 		KASSERT((mc[i]->aflags & PGA_WRITEABLE) == 0,
491aed9aaaaSMark Johnston 		    ("vm_pageout_flush: writeable page %p", mc[i]));
492c7aebda8SAttilio Rao 		vm_page_sbusy(mc[i]);
4932965a453SKip Macy 	}
494d474eaaaSDoug Rabson 	vm_object_pip_add(object, count);
495aef922f5SJohn Dyson 
496d076fbeaSAlan Cox 	vm_pager_put_pages(object, mc, count, flags, pageout_status);
49726f9a767SRodney W. Grimes 
4981e8a675cSKonstantin Belousov 	runlen = count - mreq;
499126d6082SKonstantin Belousov 	if (eio != NULL)
500126d6082SKonstantin Belousov 		*eio = FALSE;
501aef922f5SJohn Dyson 	for (i = 0; i < count; i++) {
502aef922f5SJohn Dyson 		vm_page_t mt = mc[i];
50324a1cce3SDavid Greenman 
5044cd45723SAlan Cox 		KASSERT(pageout_status[i] == VM_PAGER_PEND ||
5056031c68dSAlan Cox 		    !pmap_page_is_write_mapped(mt),
5069ea8d1a6SAlan Cox 		    ("vm_pageout_flush: page %p is not write protected", mt));
50726f9a767SRodney W. Grimes 		switch (pageout_status[i]) {
50826f9a767SRodney W. Grimes 		case VM_PAGER_OK:
509ebcddc72SAlan Cox 			vm_page_lock(mt);
510ebcddc72SAlan Cox 			if (vm_page_in_laundry(mt))
511ebcddc72SAlan Cox 				vm_page_deactivate_noreuse(mt);
512ebcddc72SAlan Cox 			vm_page_unlock(mt);
513ebcddc72SAlan Cox 			/* FALLTHROUGH */
51426f9a767SRodney W. Grimes 		case VM_PAGER_PEND:
51595461b45SJohn Dyson 			numpagedout++;
51626f9a767SRodney W. Grimes 			break;
51726f9a767SRodney W. Grimes 		case VM_PAGER_BAD:
51826f9a767SRodney W. Grimes 			/*
519ebcddc72SAlan Cox 			 * The page is outside the object's range.  We pretend
520ebcddc72SAlan Cox 			 * that the page out worked and clean the page, so the
521ebcddc72SAlan Cox 			 * changes will be lost if the page is reclaimed by
522ebcddc72SAlan Cox 			 * the page daemon.
52326f9a767SRodney W. Grimes 			 */
52490ecac61SMatthew Dillon 			vm_page_undirty(mt);
525ebcddc72SAlan Cox 			vm_page_lock(mt);
526ebcddc72SAlan Cox 			if (vm_page_in_laundry(mt))
527ebcddc72SAlan Cox 				vm_page_deactivate_noreuse(mt);
528ebcddc72SAlan Cox 			vm_page_unlock(mt);
52926f9a767SRodney W. Grimes 			break;
53026f9a767SRodney W. Grimes 		case VM_PAGER_ERROR:
53126f9a767SRodney W. Grimes 		case VM_PAGER_FAIL:
53226f9a767SRodney W. Grimes 			/*
533b1fd102eSMark Johnston 			 * If the page couldn't be paged out to swap because the
534b1fd102eSMark Johnston 			 * pager wasn't able to find space, place the page in
535b1fd102eSMark Johnston 			 * the PQ_UNSWAPPABLE holding queue.  This is an
536b1fd102eSMark Johnston 			 * optimization that prevents the page daemon from
537b1fd102eSMark Johnston 			 * wasting CPU cycles on pages that cannot be reclaimed
538b1fd102eSMark Johnston 			 * becase no swap device is configured.
539b1fd102eSMark Johnston 			 *
540b1fd102eSMark Johnston 			 * Otherwise, reactivate the page so that it doesn't
541b1fd102eSMark Johnston 			 * clog the laundry and inactive queues.  (We will try
542b1fd102eSMark Johnston 			 * paging it out again later.)
54326f9a767SRodney W. Grimes 			 */
5443c4a2440SAlan Cox 			vm_page_lock(mt);
545b1fd102eSMark Johnston 			if (object->type == OBJT_SWAP &&
546b1fd102eSMark Johnston 			    pageout_status[i] == VM_PAGER_FAIL) {
547b1fd102eSMark Johnston 				vm_page_unswappable(mt);
548b1fd102eSMark Johnston 				numpagedout++;
549b1fd102eSMark Johnston 			} else
55024a1cce3SDavid Greenman 				vm_page_activate(mt);
5513c4a2440SAlan Cox 			vm_page_unlock(mt);
552126d6082SKonstantin Belousov 			if (eio != NULL && i >= mreq && i - mreq < runlen)
553126d6082SKonstantin Belousov 				*eio = TRUE;
55426f9a767SRodney W. Grimes 			break;
55526f9a767SRodney W. Grimes 		case VM_PAGER_AGAIN:
5561e8a675cSKonstantin Belousov 			if (i >= mreq && i - mreq < runlen)
5571e8a675cSKonstantin Belousov 				runlen = i - mreq;
55826f9a767SRodney W. Grimes 			break;
55926f9a767SRodney W. Grimes 		}
56026f9a767SRodney W. Grimes 
56126f9a767SRodney W. Grimes 		/*
5620d94caffSDavid Greenman 		 * If the operation is still going, leave the page busy to
5630d94caffSDavid Greenman 		 * block all other accesses. Also, leave the paging in
5640d94caffSDavid Greenman 		 * progress indicator set so that we don't attempt an object
5650d94caffSDavid Greenman 		 * collapse.
56626f9a767SRodney W. Grimes 		 */
56726f9a767SRodney W. Grimes 		if (pageout_status[i] != VM_PAGER_PEND) {
568f919ebdeSDavid Greenman 			vm_object_pip_wakeup(object);
569c7aebda8SAttilio Rao 			vm_page_sunbusy(mt);
5703c4a2440SAlan Cox 		}
5713c4a2440SAlan Cox 	}
5721e8a675cSKonstantin Belousov 	if (prunlen != NULL)
5731e8a675cSKonstantin Belousov 		*prunlen = runlen;
5743c4a2440SAlan Cox 	return (numpagedout);
57526f9a767SRodney W. Grimes }
57626f9a767SRodney W. Grimes 
577b1fd102eSMark Johnston static void
578b1fd102eSMark Johnston vm_pageout_swapon(void *arg __unused, struct swdevt *sp __unused)
579b1fd102eSMark Johnston {
580b1fd102eSMark Johnston 
581b1fd102eSMark Johnston 	atomic_store_rel_int(&swapdev_enabled, 1);
582b1fd102eSMark Johnston }
583b1fd102eSMark Johnston 
584b1fd102eSMark Johnston static void
585b1fd102eSMark Johnston vm_pageout_swapoff(void *arg __unused, struct swdevt *sp __unused)
586b1fd102eSMark Johnston {
587b1fd102eSMark Johnston 
588b1fd102eSMark Johnston 	if (swap_pager_nswapdev() == 1)
589b1fd102eSMark Johnston 		atomic_store_rel_int(&swapdev_enabled, 0);
590b1fd102eSMark Johnston }
591b1fd102eSMark Johnston 
5921c7c3c6aSMatthew Dillon /*
59334d8b7eaSJeff Roberson  * Attempt to acquire all of the necessary locks to launder a page and
59434d8b7eaSJeff Roberson  * then call through the clustering layer to PUTPAGES.  Wait a short
59534d8b7eaSJeff Roberson  * time for a vnode lock.
59634d8b7eaSJeff Roberson  *
59734d8b7eaSJeff Roberson  * Requires the page and object lock on entry, releases both before return.
59834d8b7eaSJeff Roberson  * Returns 0 on success and an errno otherwise.
59934d8b7eaSJeff Roberson  */
60034d8b7eaSJeff Roberson static int
601ebcddc72SAlan Cox vm_pageout_clean(vm_page_t m, int *numpagedout)
60234d8b7eaSJeff Roberson {
60334d8b7eaSJeff Roberson 	struct vnode *vp;
60434d8b7eaSJeff Roberson 	struct mount *mp;
60534d8b7eaSJeff Roberson 	vm_object_t object;
60634d8b7eaSJeff Roberson 	vm_pindex_t pindex;
60734d8b7eaSJeff Roberson 	int error, lockmode;
60834d8b7eaSJeff Roberson 
60934d8b7eaSJeff Roberson 	vm_page_assert_locked(m);
61034d8b7eaSJeff Roberson 	object = m->object;
61134d8b7eaSJeff Roberson 	VM_OBJECT_ASSERT_WLOCKED(object);
61234d8b7eaSJeff Roberson 	error = 0;
61334d8b7eaSJeff Roberson 	vp = NULL;
61434d8b7eaSJeff Roberson 	mp = NULL;
61534d8b7eaSJeff Roberson 
61634d8b7eaSJeff Roberson 	/*
61734d8b7eaSJeff Roberson 	 * The object is already known NOT to be dead.   It
61834d8b7eaSJeff Roberson 	 * is possible for the vget() to block the whole
61934d8b7eaSJeff Roberson 	 * pageout daemon, but the new low-memory handling
62034d8b7eaSJeff Roberson 	 * code should prevent it.
62134d8b7eaSJeff Roberson 	 *
62234d8b7eaSJeff Roberson 	 * We can't wait forever for the vnode lock, we might
62334d8b7eaSJeff Roberson 	 * deadlock due to a vn_read() getting stuck in
62434d8b7eaSJeff Roberson 	 * vm_wait while holding this vnode.  We skip the
62534d8b7eaSJeff Roberson 	 * vnode if we can't get it in a reasonable amount
62634d8b7eaSJeff Roberson 	 * of time.
62734d8b7eaSJeff Roberson 	 */
62834d8b7eaSJeff Roberson 	if (object->type == OBJT_VNODE) {
62934d8b7eaSJeff Roberson 		vm_page_unlock(m);
63034d8b7eaSJeff Roberson 		vp = object->handle;
63134d8b7eaSJeff Roberson 		if (vp->v_type == VREG &&
63234d8b7eaSJeff Roberson 		    vn_start_write(vp, &mp, V_NOWAIT) != 0) {
63334d8b7eaSJeff Roberson 			mp = NULL;
63434d8b7eaSJeff Roberson 			error = EDEADLK;
63534d8b7eaSJeff Roberson 			goto unlock_all;
63634d8b7eaSJeff Roberson 		}
63734d8b7eaSJeff Roberson 		KASSERT(mp != NULL,
63834d8b7eaSJeff Roberson 		    ("vp %p with NULL v_mount", vp));
63934d8b7eaSJeff Roberson 		vm_object_reference_locked(object);
64034d8b7eaSJeff Roberson 		pindex = m->pindex;
64134d8b7eaSJeff Roberson 		VM_OBJECT_WUNLOCK(object);
64234d8b7eaSJeff Roberson 		lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
64334d8b7eaSJeff Roberson 		    LK_SHARED : LK_EXCLUSIVE;
64434d8b7eaSJeff Roberson 		if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
64534d8b7eaSJeff Roberson 			vp = NULL;
64634d8b7eaSJeff Roberson 			error = EDEADLK;
64734d8b7eaSJeff Roberson 			goto unlock_mp;
64834d8b7eaSJeff Roberson 		}
64934d8b7eaSJeff Roberson 		VM_OBJECT_WLOCK(object);
650*57cd81a3SMark Johnston 
651*57cd81a3SMark Johnston 		/*
652*57cd81a3SMark Johnston 		 * Ensure that the object and vnode were not disassociated
653*57cd81a3SMark Johnston 		 * while locks were dropped.
654*57cd81a3SMark Johnston 		 */
655*57cd81a3SMark Johnston 		if (vp->v_object != object) {
656*57cd81a3SMark Johnston 			error = ENOENT;
657*57cd81a3SMark Johnston 			goto unlock_all;
658*57cd81a3SMark Johnston 		}
65934d8b7eaSJeff Roberson 		vm_page_lock(m);
660*57cd81a3SMark Johnston 
66134d8b7eaSJeff Roberson 		/*
66234d8b7eaSJeff Roberson 		 * While the object and page were unlocked, the page
66334d8b7eaSJeff Roberson 		 * may have been:
66434d8b7eaSJeff Roberson 		 * (1) moved to a different queue,
66534d8b7eaSJeff Roberson 		 * (2) reallocated to a different object,
66634d8b7eaSJeff Roberson 		 * (3) reallocated to a different offset, or
66734d8b7eaSJeff Roberson 		 * (4) cleaned.
66834d8b7eaSJeff Roberson 		 */
669ebcddc72SAlan Cox 		if (!vm_page_in_laundry(m) || m->object != object ||
67034d8b7eaSJeff Roberson 		    m->pindex != pindex || m->dirty == 0) {
67134d8b7eaSJeff Roberson 			vm_page_unlock(m);
67234d8b7eaSJeff Roberson 			error = ENXIO;
67334d8b7eaSJeff Roberson 			goto unlock_all;
67434d8b7eaSJeff Roberson 		}
67534d8b7eaSJeff Roberson 
67634d8b7eaSJeff Roberson 		/*
67734d8b7eaSJeff Roberson 		 * The page may have been busied or held while the object
67834d8b7eaSJeff Roberson 		 * and page locks were released.
67934d8b7eaSJeff Roberson 		 */
68034d8b7eaSJeff Roberson 		if (vm_page_busied(m) || m->hold_count != 0) {
68134d8b7eaSJeff Roberson 			vm_page_unlock(m);
68234d8b7eaSJeff Roberson 			error = EBUSY;
68334d8b7eaSJeff Roberson 			goto unlock_all;
68434d8b7eaSJeff Roberson 		}
68534d8b7eaSJeff Roberson 	}
68634d8b7eaSJeff Roberson 
68734d8b7eaSJeff Roberson 	/*
68834d8b7eaSJeff Roberson 	 * If a page is dirty, then it is either being washed
68934d8b7eaSJeff Roberson 	 * (but not yet cleaned) or it is still in the
69034d8b7eaSJeff Roberson 	 * laundry.  If it is still in the laundry, then we
69134d8b7eaSJeff Roberson 	 * start the cleaning operation.
69234d8b7eaSJeff Roberson 	 */
693ebcddc72SAlan Cox 	if ((*numpagedout = vm_pageout_cluster(m)) == 0)
69434d8b7eaSJeff Roberson 		error = EIO;
69534d8b7eaSJeff Roberson 
69634d8b7eaSJeff Roberson unlock_all:
69734d8b7eaSJeff Roberson 	VM_OBJECT_WUNLOCK(object);
69834d8b7eaSJeff Roberson 
69934d8b7eaSJeff Roberson unlock_mp:
70034d8b7eaSJeff Roberson 	vm_page_lock_assert(m, MA_NOTOWNED);
70134d8b7eaSJeff Roberson 	if (mp != NULL) {
70234d8b7eaSJeff Roberson 		if (vp != NULL)
70334d8b7eaSJeff Roberson 			vput(vp);
70434d8b7eaSJeff Roberson 		vm_object_deallocate(object);
70534d8b7eaSJeff Roberson 		vn_finished_write(mp);
70634d8b7eaSJeff Roberson 	}
70734d8b7eaSJeff Roberson 
70834d8b7eaSJeff Roberson 	return (error);
70934d8b7eaSJeff Roberson }
71034d8b7eaSJeff Roberson 
71134d8b7eaSJeff Roberson /*
712ebcddc72SAlan Cox  * Attempt to launder the specified number of pages.
713ebcddc72SAlan Cox  *
714ebcddc72SAlan Cox  * Returns the number of pages successfully laundered.
715ebcddc72SAlan Cox  */
716ebcddc72SAlan Cox static int
717ebcddc72SAlan Cox vm_pageout_launder(struct vm_domain *vmd, int launder, bool in_shortfall)
718ebcddc72SAlan Cox {
719ebcddc72SAlan Cox 	struct vm_pagequeue *pq;
720ebcddc72SAlan Cox 	vm_object_t object;
721ebcddc72SAlan Cox 	vm_page_t m, next;
722ebcddc72SAlan Cox 	int act_delta, error, maxscan, numpagedout, starting_target;
723ebcddc72SAlan Cox 	int vnodes_skipped;
724ebcddc72SAlan Cox 	bool pageout_ok, queue_locked;
725ebcddc72SAlan Cox 
726ebcddc72SAlan Cox 	starting_target = launder;
727ebcddc72SAlan Cox 	vnodes_skipped = 0;
728ebcddc72SAlan Cox 
729ebcddc72SAlan Cox 	/*
730b1fd102eSMark Johnston 	 * Scan the laundry queues for pages eligible to be laundered.  We stop
731ebcddc72SAlan Cox 	 * once the target number of dirty pages have been laundered, or once
732ebcddc72SAlan Cox 	 * we've reached the end of the queue.  A single iteration of this loop
733ebcddc72SAlan Cox 	 * may cause more than one page to be laundered because of clustering.
734ebcddc72SAlan Cox 	 *
735ebcddc72SAlan Cox 	 * maxscan ensures that we don't re-examine requeued pages.  Any
736ebcddc72SAlan Cox 	 * additional pages written as part of a cluster are subtracted from
737ebcddc72SAlan Cox 	 * maxscan since they must be taken from the laundry queue.
738b1fd102eSMark Johnston 	 *
739b1fd102eSMark Johnston 	 * As an optimization, we avoid laundering from PQ_UNSWAPPABLE when no
740b1fd102eSMark Johnston 	 * swap devices are configured.
741ebcddc72SAlan Cox 	 */
742b1fd102eSMark Johnston 	if (atomic_load_acq_int(&swapdev_enabled))
743b1fd102eSMark Johnston 		pq = &vmd->vmd_pagequeues[PQ_UNSWAPPABLE];
744b1fd102eSMark Johnston 	else
745ebcddc72SAlan Cox 		pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
746ebcddc72SAlan Cox 
747b1fd102eSMark Johnston scan:
748ebcddc72SAlan Cox 	vm_pagequeue_lock(pq);
749b1fd102eSMark Johnston 	maxscan = pq->pq_cnt;
750ebcddc72SAlan Cox 	queue_locked = true;
751ebcddc72SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl);
752ebcddc72SAlan Cox 	    m != NULL && maxscan-- > 0 && launder > 0;
753ebcddc72SAlan Cox 	    m = next) {
754ebcddc72SAlan Cox 		vm_pagequeue_assert_locked(pq);
755ebcddc72SAlan Cox 		KASSERT(queue_locked, ("unlocked laundry queue"));
756ebcddc72SAlan Cox 		KASSERT(vm_page_in_laundry(m),
757ebcddc72SAlan Cox 		    ("page %p has an inconsistent queue", m));
758ebcddc72SAlan Cox 		next = TAILQ_NEXT(m, plinks.q);
759ebcddc72SAlan Cox 		if ((m->flags & PG_MARKER) != 0)
760ebcddc72SAlan Cox 			continue;
761ebcddc72SAlan Cox 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
762ebcddc72SAlan Cox 		    ("PG_FICTITIOUS page %p cannot be in laundry queue", m));
763ebcddc72SAlan Cox 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
764ebcddc72SAlan Cox 		    ("VPO_UNMANAGED page %p cannot be in laundry queue", m));
765ebcddc72SAlan Cox 		if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
766ebcddc72SAlan Cox 			vm_page_unlock(m);
767ebcddc72SAlan Cox 			continue;
768ebcddc72SAlan Cox 		}
769ebcddc72SAlan Cox 		object = m->object;
770ebcddc72SAlan Cox 		if ((!VM_OBJECT_TRYWLOCK(object) &&
771ebcddc72SAlan Cox 		    (!vm_pageout_fallback_object_lock(m, &next) ||
772ebcddc72SAlan Cox 		    m->hold_count != 0)) || vm_page_busied(m)) {
773ebcddc72SAlan Cox 			VM_OBJECT_WUNLOCK(object);
774ebcddc72SAlan Cox 			vm_page_unlock(m);
775ebcddc72SAlan Cox 			continue;
776ebcddc72SAlan Cox 		}
777ebcddc72SAlan Cox 
778ebcddc72SAlan Cox 		/*
779ebcddc72SAlan Cox 		 * Unlock the laundry queue, invalidating the 'next' pointer.
780ebcddc72SAlan Cox 		 * Use a marker to remember our place in the laundry queue.
781ebcddc72SAlan Cox 		 */
782ebcddc72SAlan Cox 		TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_laundry_marker,
783ebcddc72SAlan Cox 		    plinks.q);
784ebcddc72SAlan Cox 		vm_pagequeue_unlock(pq);
785ebcddc72SAlan Cox 		queue_locked = false;
786ebcddc72SAlan Cox 
787ebcddc72SAlan Cox 		/*
788ebcddc72SAlan Cox 		 * Invalid pages can be easily freed.  They cannot be
789ebcddc72SAlan Cox 		 * mapped; vm_page_free() asserts this.
790ebcddc72SAlan Cox 		 */
791ebcddc72SAlan Cox 		if (m->valid == 0)
792ebcddc72SAlan Cox 			goto free_page;
793ebcddc72SAlan Cox 
794ebcddc72SAlan Cox 		/*
795ebcddc72SAlan Cox 		 * If the page has been referenced and the object is not dead,
796ebcddc72SAlan Cox 		 * reactivate or requeue the page depending on whether the
797ebcddc72SAlan Cox 		 * object is mapped.
798ebcddc72SAlan Cox 		 */
799ebcddc72SAlan Cox 		if ((m->aflags & PGA_REFERENCED) != 0) {
800ebcddc72SAlan Cox 			vm_page_aflag_clear(m, PGA_REFERENCED);
801ebcddc72SAlan Cox 			act_delta = 1;
802ebcddc72SAlan Cox 		} else
803ebcddc72SAlan Cox 			act_delta = 0;
804ebcddc72SAlan Cox 		if (object->ref_count != 0)
805ebcddc72SAlan Cox 			act_delta += pmap_ts_referenced(m);
806ebcddc72SAlan Cox 		else {
807ebcddc72SAlan Cox 			KASSERT(!pmap_page_is_mapped(m),
808ebcddc72SAlan Cox 			    ("page %p is mapped", m));
809ebcddc72SAlan Cox 		}
810ebcddc72SAlan Cox 		if (act_delta != 0) {
811ebcddc72SAlan Cox 			if (object->ref_count != 0) {
81283c9dea1SGleb Smirnoff 				VM_CNT_INC(v_reactivated);
813ebcddc72SAlan Cox 				vm_page_activate(m);
814ebcddc72SAlan Cox 
815ebcddc72SAlan Cox 				/*
816ebcddc72SAlan Cox 				 * Increase the activation count if the page
817ebcddc72SAlan Cox 				 * was referenced while in the laundry queue.
818ebcddc72SAlan Cox 				 * This makes it less likely that the page will
819ebcddc72SAlan Cox 				 * be returned prematurely to the inactive
820ebcddc72SAlan Cox 				 * queue.
821ebcddc72SAlan Cox  				 */
822ebcddc72SAlan Cox 				m->act_count += act_delta + ACT_ADVANCE;
823ebcddc72SAlan Cox 
824ebcddc72SAlan Cox 				/*
825ebcddc72SAlan Cox 				 * If this was a background laundering, count
826ebcddc72SAlan Cox 				 * activated pages towards our target.  The
827ebcddc72SAlan Cox 				 * purpose of background laundering is to ensure
828ebcddc72SAlan Cox 				 * that pages are eventually cycled through the
829ebcddc72SAlan Cox 				 * laundry queue, and an activation is a valid
830ebcddc72SAlan Cox 				 * way out.
831ebcddc72SAlan Cox 				 */
832ebcddc72SAlan Cox 				if (!in_shortfall)
833ebcddc72SAlan Cox 					launder--;
834ebcddc72SAlan Cox 				goto drop_page;
835ebcddc72SAlan Cox 			} else if ((object->flags & OBJ_DEAD) == 0)
836ebcddc72SAlan Cox 				goto requeue_page;
837ebcddc72SAlan Cox 		}
838ebcddc72SAlan Cox 
839ebcddc72SAlan Cox 		/*
840ebcddc72SAlan Cox 		 * If the page appears to be clean at the machine-independent
841ebcddc72SAlan Cox 		 * layer, then remove all of its mappings from the pmap in
842ebcddc72SAlan Cox 		 * anticipation of freeing it.  If, however, any of the page's
843ebcddc72SAlan Cox 		 * mappings allow write access, then the page may still be
844ebcddc72SAlan Cox 		 * modified until the last of those mappings are removed.
845ebcddc72SAlan Cox 		 */
846ebcddc72SAlan Cox 		if (object->ref_count != 0) {
847ebcddc72SAlan Cox 			vm_page_test_dirty(m);
848ebcddc72SAlan Cox 			if (m->dirty == 0)
849ebcddc72SAlan Cox 				pmap_remove_all(m);
850ebcddc72SAlan Cox 		}
851ebcddc72SAlan Cox 
852ebcddc72SAlan Cox 		/*
853ebcddc72SAlan Cox 		 * Clean pages are freed, and dirty pages are paged out unless
854ebcddc72SAlan Cox 		 * they belong to a dead object.  Requeueing dirty pages from
855ebcddc72SAlan Cox 		 * dead objects is pointless, as they are being paged out and
856ebcddc72SAlan Cox 		 * freed by the thread that destroyed the object.
857ebcddc72SAlan Cox 		 */
858ebcddc72SAlan Cox 		if (m->dirty == 0) {
859ebcddc72SAlan Cox free_page:
860ebcddc72SAlan Cox 			vm_page_free(m);
86183c9dea1SGleb Smirnoff 			VM_CNT_INC(v_dfree);
862ebcddc72SAlan Cox 		} else if ((object->flags & OBJ_DEAD) == 0) {
863ebcddc72SAlan Cox 			if (object->type != OBJT_SWAP &&
864ebcddc72SAlan Cox 			    object->type != OBJT_DEFAULT)
865ebcddc72SAlan Cox 				pageout_ok = true;
866ebcddc72SAlan Cox 			else if (disable_swap_pageouts)
867ebcddc72SAlan Cox 				pageout_ok = false;
868ebcddc72SAlan Cox 			else
869ebcddc72SAlan Cox 				pageout_ok = true;
870ebcddc72SAlan Cox 			if (!pageout_ok) {
871ebcddc72SAlan Cox requeue_page:
872ebcddc72SAlan Cox 				vm_pagequeue_lock(pq);
873ebcddc72SAlan Cox 				queue_locked = true;
874ebcddc72SAlan Cox 				vm_page_requeue_locked(m);
875ebcddc72SAlan Cox 				goto drop_page;
876ebcddc72SAlan Cox 			}
877ebcddc72SAlan Cox 
878ebcddc72SAlan Cox 			/*
879ebcddc72SAlan Cox 			 * Form a cluster with adjacent, dirty pages from the
880ebcddc72SAlan Cox 			 * same object, and page out that entire cluster.
881ebcddc72SAlan Cox 			 *
882ebcddc72SAlan Cox 			 * The adjacent, dirty pages must also be in the
883ebcddc72SAlan Cox 			 * laundry.  However, their mappings are not checked
884ebcddc72SAlan Cox 			 * for new references.  Consequently, a recently
885ebcddc72SAlan Cox 			 * referenced page may be paged out.  However, that
886ebcddc72SAlan Cox 			 * page will not be prematurely reclaimed.  After page
887ebcddc72SAlan Cox 			 * out, the page will be placed in the inactive queue,
888ebcddc72SAlan Cox 			 * where any new references will be detected and the
889ebcddc72SAlan Cox 			 * page reactivated.
890ebcddc72SAlan Cox 			 */
891ebcddc72SAlan Cox 			error = vm_pageout_clean(m, &numpagedout);
892ebcddc72SAlan Cox 			if (error == 0) {
893ebcddc72SAlan Cox 				launder -= numpagedout;
894ebcddc72SAlan Cox 				maxscan -= numpagedout - 1;
895ebcddc72SAlan Cox 			} else if (error == EDEADLK) {
896ebcddc72SAlan Cox 				pageout_lock_miss++;
897ebcddc72SAlan Cox 				vnodes_skipped++;
898ebcddc72SAlan Cox 			}
899ebcddc72SAlan Cox 			goto relock_queue;
900ebcddc72SAlan Cox 		}
901ebcddc72SAlan Cox drop_page:
902ebcddc72SAlan Cox 		vm_page_unlock(m);
903ebcddc72SAlan Cox 		VM_OBJECT_WUNLOCK(object);
904ebcddc72SAlan Cox relock_queue:
905ebcddc72SAlan Cox 		if (!queue_locked) {
906ebcddc72SAlan Cox 			vm_pagequeue_lock(pq);
907ebcddc72SAlan Cox 			queue_locked = true;
908ebcddc72SAlan Cox 		}
909ebcddc72SAlan Cox 		next = TAILQ_NEXT(&vmd->vmd_laundry_marker, plinks.q);
910ebcddc72SAlan Cox 		TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_laundry_marker, plinks.q);
911ebcddc72SAlan Cox 	}
912ebcddc72SAlan Cox 	vm_pagequeue_unlock(pq);
913ebcddc72SAlan Cox 
914b1fd102eSMark Johnston 	if (launder > 0 && pq == &vmd->vmd_pagequeues[PQ_UNSWAPPABLE]) {
915b1fd102eSMark Johnston 		pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
916b1fd102eSMark Johnston 		goto scan;
917b1fd102eSMark Johnston 	}
918b1fd102eSMark Johnston 
919ebcddc72SAlan Cox 	/*
920ebcddc72SAlan Cox 	 * Wakeup the sync daemon if we skipped a vnode in a writeable object
921ebcddc72SAlan Cox 	 * and we didn't launder enough pages.
922ebcddc72SAlan Cox 	 */
923ebcddc72SAlan Cox 	if (vnodes_skipped > 0 && launder > 0)
924ebcddc72SAlan Cox 		(void)speedup_syncer();
925ebcddc72SAlan Cox 
926ebcddc72SAlan Cox 	return (starting_target - launder);
927ebcddc72SAlan Cox }
928ebcddc72SAlan Cox 
929ebcddc72SAlan Cox /*
930ebcddc72SAlan Cox  * Compute the integer square root.
931ebcddc72SAlan Cox  */
932ebcddc72SAlan Cox static u_int
933ebcddc72SAlan Cox isqrt(u_int num)
934ebcddc72SAlan Cox {
935ebcddc72SAlan Cox 	u_int bit, root, tmp;
936ebcddc72SAlan Cox 
937ebcddc72SAlan Cox 	bit = 1u << ((NBBY * sizeof(u_int)) - 2);
938ebcddc72SAlan Cox 	while (bit > num)
939ebcddc72SAlan Cox 		bit >>= 2;
940ebcddc72SAlan Cox 	root = 0;
941ebcddc72SAlan Cox 	while (bit != 0) {
942ebcddc72SAlan Cox 		tmp = root + bit;
943ebcddc72SAlan Cox 		root >>= 1;
944ebcddc72SAlan Cox 		if (num >= tmp) {
945ebcddc72SAlan Cox 			num -= tmp;
946ebcddc72SAlan Cox 			root += bit;
947ebcddc72SAlan Cox 		}
948ebcddc72SAlan Cox 		bit >>= 2;
949ebcddc72SAlan Cox 	}
950ebcddc72SAlan Cox 	return (root);
951ebcddc72SAlan Cox }
952ebcddc72SAlan Cox 
953ebcddc72SAlan Cox /*
954ebcddc72SAlan Cox  * Perform the work of the laundry thread: periodically wake up and determine
955ebcddc72SAlan Cox  * whether any pages need to be laundered.  If so, determine the number of pages
956ebcddc72SAlan Cox  * that need to be laundered, and launder them.
957ebcddc72SAlan Cox  */
958ebcddc72SAlan Cox static void
959ebcddc72SAlan Cox vm_pageout_laundry_worker(void *arg)
960ebcddc72SAlan Cox {
961ebcddc72SAlan Cox 	struct vm_domain *domain;
962ebcddc72SAlan Cox 	struct vm_pagequeue *pq;
963ebcddc72SAlan Cox 	uint64_t nclean, ndirty;
964ebcddc72SAlan Cox 	u_int last_launder, wakeups;
965ebcddc72SAlan Cox 	int domidx, last_target, launder, shortfall, shortfall_cycle, target;
966ebcddc72SAlan Cox 	bool in_shortfall;
967ebcddc72SAlan Cox 
968ebcddc72SAlan Cox 	domidx = (uintptr_t)arg;
969ebcddc72SAlan Cox 	domain = &vm_dom[domidx];
970ebcddc72SAlan Cox 	pq = &domain->vmd_pagequeues[PQ_LAUNDRY];
971ebcddc72SAlan Cox 	KASSERT(domain->vmd_segs != 0, ("domain without segments"));
972ebcddc72SAlan Cox 	vm_pageout_init_marker(&domain->vmd_laundry_marker, PQ_LAUNDRY);
973ebcddc72SAlan Cox 
974ebcddc72SAlan Cox 	shortfall = 0;
975ebcddc72SAlan Cox 	in_shortfall = false;
976ebcddc72SAlan Cox 	shortfall_cycle = 0;
977ebcddc72SAlan Cox 	target = 0;
978ebcddc72SAlan Cox 	last_launder = 0;
979ebcddc72SAlan Cox 
980ebcddc72SAlan Cox 	/*
981b1fd102eSMark Johnston 	 * Calls to these handlers are serialized by the swap syscall lock.
982b1fd102eSMark Johnston 	 */
983b1fd102eSMark Johnston 	(void)EVENTHANDLER_REGISTER(swapon, vm_pageout_swapon, domain,
984b1fd102eSMark Johnston 	    EVENTHANDLER_PRI_ANY);
985b1fd102eSMark Johnston 	(void)EVENTHANDLER_REGISTER(swapoff, vm_pageout_swapoff, domain,
986b1fd102eSMark Johnston 	    EVENTHANDLER_PRI_ANY);
987b1fd102eSMark Johnston 
988b1fd102eSMark Johnston 	/*
989ebcddc72SAlan Cox 	 * The pageout laundry worker is never done, so loop forever.
990ebcddc72SAlan Cox 	 */
991ebcddc72SAlan Cox 	for (;;) {
992ebcddc72SAlan Cox 		KASSERT(target >= 0, ("negative target %d", target));
993ebcddc72SAlan Cox 		KASSERT(shortfall_cycle >= 0,
994ebcddc72SAlan Cox 		    ("negative cycle %d", shortfall_cycle));
995ebcddc72SAlan Cox 		launder = 0;
99683c9dea1SGleb Smirnoff 		wakeups = VM_CNT_FETCH(v_pdwakeups);
997ebcddc72SAlan Cox 
998ebcddc72SAlan Cox 		/*
999ebcddc72SAlan Cox 		 * First determine whether we need to launder pages to meet a
1000ebcddc72SAlan Cox 		 * shortage of free pages.
1001ebcddc72SAlan Cox 		 */
1002ebcddc72SAlan Cox 		if (shortfall > 0) {
1003ebcddc72SAlan Cox 			in_shortfall = true;
1004ebcddc72SAlan Cox 			shortfall_cycle = VM_LAUNDER_RATE / VM_INACT_SCAN_RATE;
1005ebcddc72SAlan Cox 			target = shortfall;
1006ebcddc72SAlan Cox 		} else if (!in_shortfall)
1007ebcddc72SAlan Cox 			goto trybackground;
1008ebcddc72SAlan Cox 		else if (shortfall_cycle == 0 || vm_laundry_target() <= 0) {
1009ebcddc72SAlan Cox 			/*
1010ebcddc72SAlan Cox 			 * We recently entered shortfall and began laundering
1011ebcddc72SAlan Cox 			 * pages.  If we have completed that laundering run
1012ebcddc72SAlan Cox 			 * (and we are no longer in shortfall) or we have met
1013ebcddc72SAlan Cox 			 * our laundry target through other activity, then we
1014ebcddc72SAlan Cox 			 * can stop laundering pages.
1015ebcddc72SAlan Cox 			 */
1016ebcddc72SAlan Cox 			in_shortfall = false;
1017ebcddc72SAlan Cox 			target = 0;
1018ebcddc72SAlan Cox 			goto trybackground;
1019ebcddc72SAlan Cox 		}
1020ebcddc72SAlan Cox 		last_launder = wakeups;
1021ebcddc72SAlan Cox 		launder = target / shortfall_cycle--;
1022ebcddc72SAlan Cox 		goto dolaundry;
1023ebcddc72SAlan Cox 
1024ebcddc72SAlan Cox 		/*
1025ebcddc72SAlan Cox 		 * There's no immediate need to launder any pages; see if we
1026ebcddc72SAlan Cox 		 * meet the conditions to perform background laundering:
1027ebcddc72SAlan Cox 		 *
1028ebcddc72SAlan Cox 		 * 1. The ratio of dirty to clean inactive pages exceeds the
1029ebcddc72SAlan Cox 		 *    background laundering threshold and the pagedaemon has
1030ebcddc72SAlan Cox 		 *    been woken up to reclaim pages since our last
1031ebcddc72SAlan Cox 		 *    laundering, or
1032ebcddc72SAlan Cox 		 * 2. we haven't yet reached the target of the current
1033ebcddc72SAlan Cox 		 *    background laundering run.
1034ebcddc72SAlan Cox 		 *
1035ebcddc72SAlan Cox 		 * The background laundering threshold is not a constant.
1036ebcddc72SAlan Cox 		 * Instead, it is a slowly growing function of the number of
1037ebcddc72SAlan Cox 		 * page daemon wakeups since the last laundering.  Thus, as the
1038ebcddc72SAlan Cox 		 * ratio of dirty to clean inactive pages grows, the amount of
1039ebcddc72SAlan Cox 		 * memory pressure required to trigger laundering decreases.
1040ebcddc72SAlan Cox 		 */
1041ebcddc72SAlan Cox trybackground:
1042ebcddc72SAlan Cox 		nclean = vm_cnt.v_inactive_count + vm_cnt.v_free_count;
1043ebcddc72SAlan Cox 		ndirty = vm_cnt.v_laundry_count;
1044ebcddc72SAlan Cox 		if (target == 0 && wakeups != last_launder &&
1045ebcddc72SAlan Cox 		    ndirty * isqrt(wakeups - last_launder) >= nclean) {
1046ebcddc72SAlan Cox 			target = vm_background_launder_target;
1047ebcddc72SAlan Cox 		}
1048ebcddc72SAlan Cox 
1049ebcddc72SAlan Cox 		/*
1050ebcddc72SAlan Cox 		 * We have a non-zero background laundering target.  If we've
1051ebcddc72SAlan Cox 		 * laundered up to our maximum without observing a page daemon
1052ebcddc72SAlan Cox 		 * wakeup, just stop.  This is a safety belt that ensures we
1053ebcddc72SAlan Cox 		 * don't launder an excessive amount if memory pressure is low
1054ebcddc72SAlan Cox 		 * and the ratio of dirty to clean pages is large.  Otherwise,
1055ebcddc72SAlan Cox 		 * proceed at the background laundering rate.
1056ebcddc72SAlan Cox 		 */
1057ebcddc72SAlan Cox 		if (target > 0) {
1058ebcddc72SAlan Cox 			if (wakeups != last_launder) {
1059ebcddc72SAlan Cox 				last_launder = wakeups;
1060ebcddc72SAlan Cox 				last_target = target;
1061ebcddc72SAlan Cox 			} else if (last_target - target >=
1062ebcddc72SAlan Cox 			    vm_background_launder_max * PAGE_SIZE / 1024) {
1063ebcddc72SAlan Cox 				target = 0;
1064ebcddc72SAlan Cox 			}
1065ebcddc72SAlan Cox 			launder = vm_background_launder_rate * PAGE_SIZE / 1024;
1066ebcddc72SAlan Cox 			launder /= VM_LAUNDER_RATE;
1067ebcddc72SAlan Cox 			if (launder > target)
1068ebcddc72SAlan Cox 				launder = target;
1069ebcddc72SAlan Cox 		}
1070ebcddc72SAlan Cox 
1071ebcddc72SAlan Cox dolaundry:
1072ebcddc72SAlan Cox 		if (launder > 0) {
1073ebcddc72SAlan Cox 			/*
1074ebcddc72SAlan Cox 			 * Because of I/O clustering, the number of laundered
1075ebcddc72SAlan Cox 			 * pages could exceed "target" by the maximum size of
1076ebcddc72SAlan Cox 			 * a cluster minus one.
1077ebcddc72SAlan Cox 			 */
1078ebcddc72SAlan Cox 			target -= min(vm_pageout_launder(domain, launder,
1079ebcddc72SAlan Cox 			    in_shortfall), target);
1080ebcddc72SAlan Cox 			pause("laundp", hz / VM_LAUNDER_RATE);
1081ebcddc72SAlan Cox 		}
1082ebcddc72SAlan Cox 
1083ebcddc72SAlan Cox 		/*
1084ebcddc72SAlan Cox 		 * If we're not currently laundering pages and the page daemon
1085ebcddc72SAlan Cox 		 * hasn't posted a new request, sleep until the page daemon
1086ebcddc72SAlan Cox 		 * kicks us.
1087ebcddc72SAlan Cox 		 */
1088ebcddc72SAlan Cox 		vm_pagequeue_lock(pq);
1089ebcddc72SAlan Cox 		if (target == 0 && vm_laundry_request == VM_LAUNDRY_IDLE)
1090ebcddc72SAlan Cox 			(void)mtx_sleep(&vm_laundry_request,
1091ebcddc72SAlan Cox 			    vm_pagequeue_lockptr(pq), PVM, "launds", 0);
1092ebcddc72SAlan Cox 
1093ebcddc72SAlan Cox 		/*
1094ebcddc72SAlan Cox 		 * If the pagedaemon has indicated that it's in shortfall, start
1095ebcddc72SAlan Cox 		 * a shortfall laundering unless we're already in the middle of
1096ebcddc72SAlan Cox 		 * one.  This may preempt a background laundering.
1097ebcddc72SAlan Cox 		 */
1098ebcddc72SAlan Cox 		if (vm_laundry_request == VM_LAUNDRY_SHORTFALL &&
1099ebcddc72SAlan Cox 		    (!in_shortfall || shortfall_cycle == 0)) {
1100ebcddc72SAlan Cox 			shortfall = vm_laundry_target() + vm_pageout_deficit;
1101ebcddc72SAlan Cox 			target = 0;
1102ebcddc72SAlan Cox 		} else
1103ebcddc72SAlan Cox 			shortfall = 0;
1104ebcddc72SAlan Cox 
1105ebcddc72SAlan Cox 		if (target == 0)
1106ebcddc72SAlan Cox 			vm_laundry_request = VM_LAUNDRY_IDLE;
1107ebcddc72SAlan Cox 		vm_pagequeue_unlock(pq);
1108ebcddc72SAlan Cox 	}
1109ebcddc72SAlan Cox }
1110ebcddc72SAlan Cox 
1111ebcddc72SAlan Cox /*
1112df8bae1dSRodney W. Grimes  *	vm_pageout_scan does the dirty work for the pageout daemon.
1113d9e23210SJeff Roberson  *
1114ebcddc72SAlan Cox  *	pass == 0: Update active LRU/deactivate pages
1115ebcddc72SAlan Cox  *	pass >= 1: Free inactive pages
1116e57dd910SAlan Cox  *
1117e57dd910SAlan Cox  * Returns true if pass was zero or enough pages were freed by the inactive
1118e57dd910SAlan Cox  * queue scan to meet the target.
1119df8bae1dSRodney W. Grimes  */
1120e57dd910SAlan Cox static bool
1121449c2e92SKonstantin Belousov vm_pageout_scan(struct vm_domain *vmd, int pass)
1122df8bae1dSRodney W. Grimes {
1123502ba6e4SJohn Dyson 	vm_page_t m, next;
11248d220203SAlan Cox 	struct vm_pagequeue *pq;
1125df8bae1dSRodney W. Grimes 	vm_object_t object;
112622cf98d1SAlan Cox 	long min_scan;
1127ebcddc72SAlan Cox 	int act_delta, addl_page_shortage, deficit, inactq_shortage, maxscan;
1128ebcddc72SAlan Cox 	int page_shortage, scan_tick, scanned, starting_page_shortage;
1129ebcddc72SAlan Cox 	boolean_t queue_locked;
11300d94caffSDavid Greenman 
1131df8bae1dSRodney W. Grimes 	/*
1132d9e23210SJeff Roberson 	 * If we need to reclaim memory ask kernel caches to return
1133c9612b2dSJeff Roberson 	 * some.  We rate limit to avoid thrashing.
1134d9e23210SJeff Roberson 	 */
1135c9612b2dSJeff Roberson 	if (vmd == &vm_dom[0] && pass > 0 &&
1136a6bf3a9eSRyan Stone 	    (time_uptime - lowmem_uptime) >= lowmem_period) {
1137d9e23210SJeff Roberson 		/*
1138855a310fSJeff Roberson 		 * Decrease registered cache sizes.
1139855a310fSJeff Roberson 		 */
114014a0d74eSSteven Hartland 		SDT_PROBE0(vm, , , vm__lowmem_scan);
11419b43bc27SAndriy Gapon 		EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_PAGES);
1142855a310fSJeff Roberson 		/*
1143d9e23210SJeff Roberson 		 * We do this explicitly after the caches have been
1144d9e23210SJeff Roberson 		 * drained above.
1145855a310fSJeff Roberson 		 */
1146855a310fSJeff Roberson 		uma_reclaim();
1147a6bf3a9eSRyan Stone 		lowmem_uptime = time_uptime;
1148d9e23210SJeff Roberson 	}
11495985940eSJohn Dyson 
1150311e34e2SKonstantin Belousov 	/*
115196240c89SEitan Adler 	 * The addl_page_shortage is the number of temporarily
1152311e34e2SKonstantin Belousov 	 * stuck pages in the inactive queue.  In other words, the
1153449c2e92SKonstantin Belousov 	 * number of pages from the inactive count that should be
1154311e34e2SKonstantin Belousov 	 * discounted in setting the target for the active queue scan.
1155311e34e2SKonstantin Belousov 	 */
11569099545aSAlan Cox 	addl_page_shortage = 0;
11579099545aSAlan Cox 
11581c7c3c6aSMatthew Dillon 	/*
1159e57dd910SAlan Cox 	 * Calculate the number of pages that we want to free.  This number
1160e57dd910SAlan Cox 	 * can be negative if many pages are freed between the wakeup call to
1161e57dd910SAlan Cox 	 * the page daemon and this calculation.
11621c7c3c6aSMatthew Dillon 	 */
116360196cdaSAlan Cox 	if (pass > 0) {
116460196cdaSAlan Cox 		deficit = atomic_readandclear_int(&vm_pageout_deficit);
11659099545aSAlan Cox 		page_shortage = vm_paging_target() + deficit;
116660196cdaSAlan Cox 	} else
116760196cdaSAlan Cox 		page_shortage = deficit = 0;
116876386c7eSKonstantin Belousov 	starting_page_shortage = page_shortage;
11691c7c3c6aSMatthew Dillon 
1170936524aaSMatthew Dillon 	/*
1171f095d1bbSAlan Cox 	 * Start scanning the inactive queue for pages that we can free.  The
1172f095d1bbSAlan Cox 	 * scan will stop when we reach the target or we have scanned the
1173f095d1bbSAlan Cox 	 * entire queue.  (Note that m->act_count is not used to make
1174f095d1bbSAlan Cox 	 * decisions for the inactive queue, only for the active queue.)
11758d220203SAlan Cox 	 */
1176449c2e92SKonstantin Belousov 	pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
1177449c2e92SKonstantin Belousov 	maxscan = pq->pq_cnt;
11788d220203SAlan Cox 	vm_pagequeue_lock(pq);
11793ac8f842SMark Johnston 	queue_locked = TRUE;
11808d220203SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl);
11811c7c3c6aSMatthew Dillon 	     m != NULL && maxscan-- > 0 && page_shortage > 0;
1182e929c00dSKirk McKusick 	     m = next) {
11838d220203SAlan Cox 		vm_pagequeue_assert_locked(pq);
11843ac8f842SMark Johnston 		KASSERT(queue_locked, ("unlocked inactive queue"));
1185ebcddc72SAlan Cox 		KASSERT(vm_page_inactive(m), ("Inactive queue %p", m));
1186df8bae1dSRodney W. Grimes 
118783c9dea1SGleb Smirnoff 		VM_CNT_INC(v_pdpages);
1188c325e866SKonstantin Belousov 		next = TAILQ_NEXT(m, plinks.q);
1189df8bae1dSRodney W. Grimes 
1190936524aaSMatthew Dillon 		/*
1191936524aaSMatthew Dillon 		 * skip marker pages
1192936524aaSMatthew Dillon 		 */
1193936524aaSMatthew Dillon 		if (m->flags & PG_MARKER)
1194936524aaSMatthew Dillon 			continue;
1195936524aaSMatthew Dillon 
11967900f95dSKonstantin Belousov 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
11977900f95dSKonstantin Belousov 		    ("Fictitious page %p cannot be in inactive queue", m));
11987900f95dSKonstantin Belousov 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
11997900f95dSKonstantin Belousov 		    ("Unmanaged page %p cannot be in inactive queue", m));
12007900f95dSKonstantin Belousov 
12018c616246SKonstantin Belousov 		/*
1202311e34e2SKonstantin Belousov 		 * The page or object lock acquisitions fail if the
1203311e34e2SKonstantin Belousov 		 * page was removed from the queue or moved to a
1204311e34e2SKonstantin Belousov 		 * different position within the queue.  In either
1205311e34e2SKonstantin Belousov 		 * case, addl_page_shortage should not be incremented.
12068c616246SKonstantin Belousov 		 */
1207a3aeedabSAlan Cox 		if (!vm_pageout_page_lock(m, &next))
1208a3aeedabSAlan Cox 			goto unlock_page;
1209a3aeedabSAlan Cox 		else if (m->hold_count != 0) {
1210a3aeedabSAlan Cox 			/*
1211a3aeedabSAlan Cox 			 * Held pages are essentially stuck in the
1212a3aeedabSAlan Cox 			 * queue.  So, they ought to be discounted
1213a3aeedabSAlan Cox 			 * from the inactive count.  See the
1214e57dd910SAlan Cox 			 * calculation of inactq_shortage before the
1215a3aeedabSAlan Cox 			 * loop over the active queue below.
1216a3aeedabSAlan Cox 			 */
1217a3aeedabSAlan Cox 			addl_page_shortage++;
1218a3aeedabSAlan Cox 			goto unlock_page;
1219df8bae1dSRodney W. Grimes 		}
12209ee2165fSAlan Cox 		object = m->object;
1221a3aeedabSAlan Cox 		if (!VM_OBJECT_TRYWLOCK(object)) {
1222a3aeedabSAlan Cox 			if (!vm_pageout_fallback_object_lock(m, &next))
1223a3aeedabSAlan Cox 				goto unlock_object;
1224a3aeedabSAlan Cox 			else if (m->hold_count != 0) {
1225b182ec9eSJohn Dyson 				addl_page_shortage++;
1226a3aeedabSAlan Cox 				goto unlock_object;
1227a3aeedabSAlan Cox 			}
1228a3aeedabSAlan Cox 		}
1229a3aeedabSAlan Cox 		if (vm_page_busied(m)) {
1230a3aeedabSAlan Cox 			/*
1231a3aeedabSAlan Cox 			 * Don't mess with busy pages.  Leave them at
1232a3aeedabSAlan Cox 			 * the front of the queue.  Most likely, they
1233a3aeedabSAlan Cox 			 * are being paged out and will leave the
1234a3aeedabSAlan Cox 			 * queue shortly after the scan finishes.  So,
1235a3aeedabSAlan Cox 			 * they ought to be discounted from the
1236a3aeedabSAlan Cox 			 * inactive count.
1237a3aeedabSAlan Cox 			 */
1238a3aeedabSAlan Cox 			addl_page_shortage++;
1239a3aeedabSAlan Cox unlock_object:
1240a3aeedabSAlan Cox 			VM_OBJECT_WUNLOCK(object);
1241a3aeedabSAlan Cox unlock_page:
1242a3aeedabSAlan Cox 			vm_page_unlock(m);
124326f9a767SRodney W. Grimes 			continue;
124426f9a767SRodney W. Grimes 		}
1245a3aeedabSAlan Cox 		KASSERT(m->hold_count == 0, ("Held page %p", m));
1246bd7e5f99SJohn Dyson 
12477e006499SJohn Dyson 		/*
1248ebcddc72SAlan Cox 		 * Dequeue the inactive page and unlock the inactive page
1249ebcddc72SAlan Cox 		 * queue, invalidating the 'next' pointer.  Dequeueing the
1250ebcddc72SAlan Cox 		 * page here avoids a later reacquisition (and release) of
1251ebcddc72SAlan Cox 		 * the inactive page queue lock when vm_page_activate(),
1252ebcddc72SAlan Cox 		 * vm_page_free(), or vm_page_launder() is called.  Use a
1253ebcddc72SAlan Cox 		 * marker to remember our place in the inactive queue.
125448cc2fc7SKonstantin Belousov 		 */
1255c325e866SKonstantin Belousov 		TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
1256ebcddc72SAlan Cox 		vm_page_dequeue_locked(m);
12578d220203SAlan Cox 		vm_pagequeue_unlock(pq);
12583ac8f842SMark Johnston 		queue_locked = FALSE;
125948cc2fc7SKonstantin Belousov 
126048cc2fc7SKonstantin Belousov 		/*
12618748f58cSKonstantin Belousov 		 * Invalid pages can be easily freed. They cannot be
12628748f58cSKonstantin Belousov 		 * mapped, vm_page_free() asserts this.
1263776f729cSKonstantin Belousov 		 */
12648748f58cSKonstantin Belousov 		if (m->valid == 0)
12658748f58cSKonstantin Belousov 			goto free_page;
1266776f729cSKonstantin Belousov 
1267776f729cSKonstantin Belousov 		/*
1268960810ccSAlan Cox 		 * If the page has been referenced and the object is not dead,
1269960810ccSAlan Cox 		 * reactivate or requeue the page depending on whether the
1270960810ccSAlan Cox 		 * object is mapped.
12717e006499SJohn Dyson 		 */
1272bb7858eaSJeff Roberson 		if ((m->aflags & PGA_REFERENCED) != 0) {
1273bb7858eaSJeff Roberson 			vm_page_aflag_clear(m, PGA_REFERENCED);
1274bb7858eaSJeff Roberson 			act_delta = 1;
127586fa2471SAlan Cox 		} else
127686fa2471SAlan Cox 			act_delta = 0;
1277bb7858eaSJeff Roberson 		if (object->ref_count != 0) {
1278bb7858eaSJeff Roberson 			act_delta += pmap_ts_referenced(m);
1279bb7858eaSJeff Roberson 		} else {
1280bb7858eaSJeff Roberson 			KASSERT(!pmap_page_is_mapped(m),
1281bb7858eaSJeff Roberson 			    ("vm_pageout_scan: page %p is mapped", m));
12822fe6e4d7SDavid Greenman 		}
1283bb7858eaSJeff Roberson 		if (act_delta != 0) {
128486fa2471SAlan Cox 			if (object->ref_count != 0) {
128583c9dea1SGleb Smirnoff 				VM_CNT_INC(v_reactivated);
128626f9a767SRodney W. Grimes 				vm_page_activate(m);
1287960810ccSAlan Cox 
1288960810ccSAlan Cox 				/*
1289960810ccSAlan Cox 				 * Increase the activation count if the page
1290960810ccSAlan Cox 				 * was referenced while in the inactive queue.
1291960810ccSAlan Cox 				 * This makes it less likely that the page will
1292960810ccSAlan Cox 				 * be returned prematurely to the inactive
1293960810ccSAlan Cox 				 * queue.
1294960810ccSAlan Cox  				 */
1295bb7858eaSJeff Roberson 				m->act_count += act_delta + ACT_ADVANCE;
1296960810ccSAlan Cox 				goto drop_page;
1297ebcddc72SAlan Cox 			} else if ((object->flags & OBJ_DEAD) == 0) {
1298ebcddc72SAlan Cox 				vm_pagequeue_lock(pq);
1299ebcddc72SAlan Cox 				queue_locked = TRUE;
1300ebcddc72SAlan Cox 				m->queue = PQ_INACTIVE;
1301ebcddc72SAlan Cox 				TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
1302ebcddc72SAlan Cox 				vm_pagequeue_cnt_inc(pq);
1303ebcddc72SAlan Cox 				goto drop_page;
1304ebcddc72SAlan Cox 			}
1305960810ccSAlan Cox 		}
130667bf6868SJohn Dyson 
13077e006499SJohn Dyson 		/*
13089fc4739dSAlan Cox 		 * If the page appears to be clean at the machine-independent
13099fc4739dSAlan Cox 		 * layer, then remove all of its mappings from the pmap in
1310a766ffd0SAlan Cox 		 * anticipation of freeing it.  If, however, any of the page's
1311a766ffd0SAlan Cox 		 * mappings allow write access, then the page may still be
1312a766ffd0SAlan Cox 		 * modified until the last of those mappings are removed.
13137e006499SJohn Dyson 		 */
1314aa044135SAlan Cox 		if (object->ref_count != 0) {
13159fc4739dSAlan Cox 			vm_page_test_dirty(m);
1316aa044135SAlan Cox 			if (m->dirty == 0)
1317b78ddb0bSAlan Cox 				pmap_remove_all(m);
1318aa044135SAlan Cox 		}
1319dcbcd518SBruce Evans 
13206989c456SAlan Cox 		/*
1321ebcddc72SAlan Cox 		 * Clean pages can be freed, but dirty pages must be sent back
1322ebcddc72SAlan Cox 		 * to the laundry, unless they belong to a dead object.
1323ebcddc72SAlan Cox 		 * Requeueing dirty pages from dead objects is pointless, as
1324ebcddc72SAlan Cox 		 * they are being paged out and freed by the thread that
1325ebcddc72SAlan Cox 		 * destroyed the object.
13266989c456SAlan Cox 		 */
1327ebcddc72SAlan Cox 		if (m->dirty == 0) {
13288748f58cSKonstantin Belousov free_page:
132978afdce6SAlan Cox 			vm_page_free(m);
133083c9dea1SGleb Smirnoff 			VM_CNT_INC(v_dfree);
13311c7c3c6aSMatthew Dillon 			--page_shortage;
1332ebcddc72SAlan Cox 		} else if ((object->flags & OBJ_DEAD) == 0)
1333ebcddc72SAlan Cox 			vm_page_launder(m);
1334776f729cSKonstantin Belousov drop_page:
133548cc2fc7SKonstantin Belousov 		vm_page_unlock(m);
133689f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
13373ac8f842SMark Johnston 		if (!queue_locked) {
13388d220203SAlan Cox 			vm_pagequeue_lock(pq);
13393ac8f842SMark Johnston 			queue_locked = TRUE;
13406989c456SAlan Cox 		}
1341c325e866SKonstantin Belousov 		next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1342c325e866SKonstantin Belousov 		TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
13430d94caffSDavid Greenman 	}
13448d220203SAlan Cox 	vm_pagequeue_unlock(pq);
134526f9a767SRodney W. Grimes 
1346ebcddc72SAlan Cox 	/*
1347ebcddc72SAlan Cox 	 * Wake up the laundry thread so that it can perform any needed
1348ebcddc72SAlan Cox 	 * laundering.  If we didn't meet our target, we're in shortfall and
1349b1fd102eSMark Johnston 	 * need to launder more aggressively.  If PQ_LAUNDRY is empty and no
1350b1fd102eSMark Johnston 	 * swap devices are configured, the laundry thread has no work to do, so
1351b1fd102eSMark Johnston 	 * don't bother waking it up.
1352ebcddc72SAlan Cox 	 */
1353ebcddc72SAlan Cox 	if (vm_laundry_request == VM_LAUNDRY_IDLE &&
1354ebcddc72SAlan Cox 	    starting_page_shortage > 0) {
1355ebcddc72SAlan Cox 		pq = &vm_dom[0].vmd_pagequeues[PQ_LAUNDRY];
1356ebcddc72SAlan Cox 		vm_pagequeue_lock(pq);
1357b1fd102eSMark Johnston 		if (pq->pq_cnt > 0 || atomic_load_acq_int(&swapdev_enabled)) {
1358ebcddc72SAlan Cox 			if (page_shortage > 0) {
1359ebcddc72SAlan Cox 				vm_laundry_request = VM_LAUNDRY_SHORTFALL;
136083c9dea1SGleb Smirnoff 				VM_CNT_INC(v_pdshortfalls);
1361ebcddc72SAlan Cox 			} else if (vm_laundry_request != VM_LAUNDRY_SHORTFALL)
1362ebcddc72SAlan Cox 				vm_laundry_request = VM_LAUNDRY_BACKGROUND;
1363ebcddc72SAlan Cox 			wakeup(&vm_laundry_request);
1364b1fd102eSMark Johnston 		}
1365ebcddc72SAlan Cox 		vm_pagequeue_unlock(pq);
1366ebcddc72SAlan Cox 	}
1367ebcddc72SAlan Cox 
13689452b5edSAlan Cox 	/*
1369f095d1bbSAlan Cox 	 * Wakeup the swapout daemon if we didn't free the targeted number of
1370f095d1bbSAlan Cox 	 * pages.
13719452b5edSAlan Cox 	 */
1372ac04195bSKonstantin Belousov 	if (page_shortage > 0)
1373ac04195bSKonstantin Belousov 		vm_swapout_run();
13749452b5edSAlan Cox 
13759452b5edSAlan Cox 	/*
137676386c7eSKonstantin Belousov 	 * If the inactive queue scan fails repeatedly to meet its
137776386c7eSKonstantin Belousov 	 * target, kill the largest process.
137876386c7eSKonstantin Belousov 	 */
137976386c7eSKonstantin Belousov 	vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
138076386c7eSKonstantin Belousov 
138176386c7eSKonstantin Belousov 	/*
1382936524aaSMatthew Dillon 	 * Compute the number of pages we want to try to move from the
1383ebcddc72SAlan Cox 	 * active queue to either the inactive or laundry queue.
1384ebcddc72SAlan Cox 	 *
1385ebcddc72SAlan Cox 	 * When scanning active pages, we make clean pages count more heavily
1386ebcddc72SAlan Cox 	 * towards the page shortage than dirty pages.  This is because dirty
1387ebcddc72SAlan Cox 	 * pages must be laundered before they can be reused and thus have less
1388ebcddc72SAlan Cox 	 * utility when attempting to quickly alleviate a shortage.  However,
1389ebcddc72SAlan Cox 	 * this weighting also causes the scan to deactivate dirty pages more
1390ebcddc72SAlan Cox 	 * more aggressively, improving the effectiveness of clustering and
1391ebcddc72SAlan Cox 	 * ensuring that they can eventually be reused.
13921c7c3c6aSMatthew Dillon 	 */
1393ebcddc72SAlan Cox 	inactq_shortage = vm_cnt.v_inactive_target - (vm_cnt.v_inactive_count +
1394ebcddc72SAlan Cox 	    vm_cnt.v_laundry_count / act_scan_laundry_weight) +
13959099545aSAlan Cox 	    vm_paging_target() + deficit + addl_page_shortage;
1396ebcddc72SAlan Cox 	page_shortage *= act_scan_laundry_weight;
13979099545aSAlan Cox 
1398114f62c6SJeff Roberson 	pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1399114f62c6SJeff Roberson 	vm_pagequeue_lock(pq);
14009099545aSAlan Cox 	maxscan = pq->pq_cnt;
14019099545aSAlan Cox 
1402d9e23210SJeff Roberson 	/*
1403d9e23210SJeff Roberson 	 * If we're just idle polling attempt to visit every
1404d9e23210SJeff Roberson 	 * active page within 'update_period' seconds.
1405d9e23210SJeff Roberson 	 */
140622cf98d1SAlan Cox 	scan_tick = ticks;
140722cf98d1SAlan Cox 	if (vm_pageout_update_period != 0) {
140822cf98d1SAlan Cox 		min_scan = pq->pq_cnt;
140922cf98d1SAlan Cox 		min_scan *= scan_tick - vmd->vmd_last_active_scan;
141022cf98d1SAlan Cox 		min_scan /= hz * vm_pageout_update_period;
141122cf98d1SAlan Cox 	} else
141222cf98d1SAlan Cox 		min_scan = 0;
1413e57dd910SAlan Cox 	if (min_scan > 0 || (inactq_shortage > 0 && maxscan > 0))
141422cf98d1SAlan Cox 		vmd->vmd_last_active_scan = scan_tick;
14151c7c3c6aSMatthew Dillon 
14161c7c3c6aSMatthew Dillon 	/*
141722cf98d1SAlan Cox 	 * Scan the active queue for pages that can be deactivated.  Update
141822cf98d1SAlan Cox 	 * the per-page activity counter and use it to identify deactivation
141979144408SAlan Cox 	 * candidates.  Held pages may be deactivated.
14201c7c3c6aSMatthew Dillon 	 */
142122cf98d1SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
1422e57dd910SAlan Cox 	    min_scan || (inactq_shortage > 0 && scanned < maxscan)); m = next,
142322cf98d1SAlan Cox 	    scanned++) {
14249cf51988SAlan Cox 		KASSERT(m->queue == PQ_ACTIVE,
1425d3c09dd7SAlan Cox 		    ("vm_pageout_scan: page %p isn't active", m));
1426c325e866SKonstantin Belousov 		next = TAILQ_NEXT(m, plinks.q);
142722cf98d1SAlan Cox 		if ((m->flags & PG_MARKER) != 0)
14288dbca793STor Egge 			continue;
14297900f95dSKonstantin Belousov 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
14307900f95dSKonstantin Belousov 		    ("Fictitious page %p cannot be in active queue", m));
14317900f95dSKonstantin Belousov 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
14327900f95dSKonstantin Belousov 		    ("Unmanaged page %p cannot be in active queue", m));
14339ee2165fSAlan Cox 		if (!vm_pageout_page_lock(m, &next)) {
14348c616246SKonstantin Belousov 			vm_page_unlock(m);
14352965a453SKip Macy 			continue;
14362965a453SKip Macy 		}
1437b18bfc3dSJohn Dyson 
1438b18bfc3dSJohn Dyson 		/*
143979144408SAlan Cox 		 * The count for page daemon pages is updated after checking
144079144408SAlan Cox 		 * the page for eligibility.
1441b18bfc3dSJohn Dyson 		 */
144283c9dea1SGleb Smirnoff 		VM_CNT_INC(v_pdpages);
1443ef743ce6SJohn Dyson 
14447e006499SJohn Dyson 		/*
14457e006499SJohn Dyson 		 * Check to see "how much" the page has been used.
14467e006499SJohn Dyson 		 */
144786fa2471SAlan Cox 		if ((m->aflags & PGA_REFERENCED) != 0) {
1448bb7858eaSJeff Roberson 			vm_page_aflag_clear(m, PGA_REFERENCED);
144986fa2471SAlan Cox 			act_delta = 1;
145086fa2471SAlan Cox 		} else
145186fa2471SAlan Cox 			act_delta = 0;
145286fa2471SAlan Cox 
1453274132acSJeff Roberson 		/*
145479144408SAlan Cox 		 * Perform an unsynchronized object ref count check.  While
145579144408SAlan Cox 		 * the page lock ensures that the page is not reallocated to
145679144408SAlan Cox 		 * another object, in particular, one with unmanaged mappings
145779144408SAlan Cox 		 * that cannot support pmap_ts_referenced(), two races are,
145879144408SAlan Cox 		 * nonetheless, possible:
145979144408SAlan Cox 		 * 1) The count was transitioning to zero, but we saw a non-
146079144408SAlan Cox 		 *    zero value.  pmap_ts_referenced() will return zero
146179144408SAlan Cox 		 *    because the page is not mapped.
146279144408SAlan Cox 		 * 2) The count was transitioning to one, but we saw zero.
146379144408SAlan Cox 		 *    This race delays the detection of a new reference.  At
146479144408SAlan Cox 		 *    worst, we will deactivate and reactivate the page.
1465274132acSJeff Roberson 		 */
1466274132acSJeff Roberson 		if (m->object->ref_count != 0)
1467bb7858eaSJeff Roberson 			act_delta += pmap_ts_referenced(m);
1468bb7858eaSJeff Roberson 
1469bb7858eaSJeff Roberson 		/*
1470bb7858eaSJeff Roberson 		 * Advance or decay the act_count based on recent usage.
1471bb7858eaSJeff Roberson 		 */
147286fa2471SAlan Cox 		if (act_delta != 0) {
1473bb7858eaSJeff Roberson 			m->act_count += ACT_ADVANCE + act_delta;
147438efa82bSJohn Dyson 			if (m->act_count > ACT_MAX)
147538efa82bSJohn Dyson 				m->act_count = ACT_MAX;
147686fa2471SAlan Cox 		} else
147738efa82bSJohn Dyson 			m->act_count -= min(m->act_count, ACT_DECLINE);
1478bb7858eaSJeff Roberson 
1479bb7858eaSJeff Roberson 		/*
1480ebcddc72SAlan Cox 		 * Move this page to the tail of the active, inactive or laundry
1481bb7858eaSJeff Roberson 		 * queue depending on usage.
1482bb7858eaSJeff Roberson 		 */
148386fa2471SAlan Cox 		if (m->act_count == 0) {
14848d220203SAlan Cox 			/* Dequeue to avoid later lock recursion. */
14858d220203SAlan Cox 			vm_page_dequeue_locked(m);
1486ebcddc72SAlan Cox 
1487ebcddc72SAlan Cox 			/*
1488ebcddc72SAlan Cox 			 * When not short for inactive pages, let dirty pages go
1489ebcddc72SAlan Cox 			 * through the inactive queue before moving to the
1490ebcddc72SAlan Cox 			 * laundry queues.  This gives them some extra time to
1491ebcddc72SAlan Cox 			 * be reactivated, potentially avoiding an expensive
1492ebcddc72SAlan Cox 			 * pageout.  During a page shortage, the inactive queue
1493ebcddc72SAlan Cox 			 * is necessarily small, so we may move dirty pages
1494ebcddc72SAlan Cox 			 * directly to the laundry queue.
1495ebcddc72SAlan Cox 			 */
1496ebcddc72SAlan Cox 			if (inactq_shortage <= 0)
1497d4a272dbSJohn Dyson 				vm_page_deactivate(m);
1498ebcddc72SAlan Cox 			else {
1499ebcddc72SAlan Cox 				/*
1500ebcddc72SAlan Cox 				 * Calling vm_page_test_dirty() here would
1501ebcddc72SAlan Cox 				 * require acquisition of the object's write
1502ebcddc72SAlan Cox 				 * lock.  However, during a page shortage,
1503ebcddc72SAlan Cox 				 * directing dirty pages into the laundry
1504ebcddc72SAlan Cox 				 * queue is only an optimization and not a
1505ebcddc72SAlan Cox 				 * requirement.  Therefore, we simply rely on
1506ebcddc72SAlan Cox 				 * the opportunistic updates to the page's
1507ebcddc72SAlan Cox 				 * dirty field by the pmap.
1508ebcddc72SAlan Cox 				 */
1509ebcddc72SAlan Cox 				if (m->dirty == 0) {
1510ebcddc72SAlan Cox 					vm_page_deactivate(m);
1511ebcddc72SAlan Cox 					inactq_shortage -=
1512ebcddc72SAlan Cox 					    act_scan_laundry_weight;
1513ebcddc72SAlan Cox 				} else {
1514ebcddc72SAlan Cox 					vm_page_launder(m);
1515e57dd910SAlan Cox 					inactq_shortage--;
1516ebcddc72SAlan Cox 				}
1517ebcddc72SAlan Cox 			}
15188d220203SAlan Cox 		} else
15198d220203SAlan Cox 			vm_page_requeue_locked(m);
15202965a453SKip Macy 		vm_page_unlock(m);
152126f9a767SRodney W. Grimes 	}
15228d220203SAlan Cox 	vm_pagequeue_unlock(pq);
1523ac04195bSKonstantin Belousov 	if (pass > 0)
1524ac04195bSKonstantin Belousov 		vm_swapout_run_idle();
1525e57dd910SAlan Cox 	return (page_shortage <= 0);
15262025d69bSKonstantin Belousov }
15272025d69bSKonstantin Belousov 
1528449c2e92SKonstantin Belousov static int vm_pageout_oom_vote;
1529449c2e92SKonstantin Belousov 
1530449c2e92SKonstantin Belousov /*
1531449c2e92SKonstantin Belousov  * The pagedaemon threads randlomly select one to perform the
1532449c2e92SKonstantin Belousov  * OOM.  Trying to kill processes before all pagedaemons
1533449c2e92SKonstantin Belousov  * failed to reach free target is premature.
1534449c2e92SKonstantin Belousov  */
1535449c2e92SKonstantin Belousov static void
153676386c7eSKonstantin Belousov vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
153776386c7eSKonstantin Belousov     int starting_page_shortage)
1538449c2e92SKonstantin Belousov {
1539449c2e92SKonstantin Belousov 	int old_vote;
1540449c2e92SKonstantin Belousov 
154176386c7eSKonstantin Belousov 	if (starting_page_shortage <= 0 || starting_page_shortage !=
154276386c7eSKonstantin Belousov 	    page_shortage)
154376386c7eSKonstantin Belousov 		vmd->vmd_oom_seq = 0;
154476386c7eSKonstantin Belousov 	else
154576386c7eSKonstantin Belousov 		vmd->vmd_oom_seq++;
154676386c7eSKonstantin Belousov 	if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1547449c2e92SKonstantin Belousov 		if (vmd->vmd_oom) {
1548449c2e92SKonstantin Belousov 			vmd->vmd_oom = FALSE;
1549449c2e92SKonstantin Belousov 			atomic_subtract_int(&vm_pageout_oom_vote, 1);
1550449c2e92SKonstantin Belousov 		}
1551449c2e92SKonstantin Belousov 		return;
1552449c2e92SKonstantin Belousov 	}
1553449c2e92SKonstantin Belousov 
155476386c7eSKonstantin Belousov 	/*
155576386c7eSKonstantin Belousov 	 * Do not follow the call sequence until OOM condition is
155676386c7eSKonstantin Belousov 	 * cleared.
155776386c7eSKonstantin Belousov 	 */
155876386c7eSKonstantin Belousov 	vmd->vmd_oom_seq = 0;
155976386c7eSKonstantin Belousov 
1560449c2e92SKonstantin Belousov 	if (vmd->vmd_oom)
1561449c2e92SKonstantin Belousov 		return;
1562449c2e92SKonstantin Belousov 
1563449c2e92SKonstantin Belousov 	vmd->vmd_oom = TRUE;
1564449c2e92SKonstantin Belousov 	old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1565449c2e92SKonstantin Belousov 	if (old_vote != vm_ndomains - 1)
1566449c2e92SKonstantin Belousov 		return;
1567449c2e92SKonstantin Belousov 
1568449c2e92SKonstantin Belousov 	/*
1569449c2e92SKonstantin Belousov 	 * The current pagedaemon thread is the last in the quorum to
1570449c2e92SKonstantin Belousov 	 * start OOM.  Initiate the selection and signaling of the
1571449c2e92SKonstantin Belousov 	 * victim.
1572449c2e92SKonstantin Belousov 	 */
1573449c2e92SKonstantin Belousov 	vm_pageout_oom(VM_OOM_MEM);
1574449c2e92SKonstantin Belousov 
1575449c2e92SKonstantin Belousov 	/*
1576449c2e92SKonstantin Belousov 	 * After one round of OOM terror, recall our vote.  On the
1577449c2e92SKonstantin Belousov 	 * next pass, current pagedaemon would vote again if the low
1578449c2e92SKonstantin Belousov 	 * memory condition is still there, due to vmd_oom being
1579449c2e92SKonstantin Belousov 	 * false.
1580449c2e92SKonstantin Belousov 	 */
1581449c2e92SKonstantin Belousov 	vmd->vmd_oom = FALSE;
1582449c2e92SKonstantin Belousov 	atomic_subtract_int(&vm_pageout_oom_vote, 1);
1583449c2e92SKonstantin Belousov }
15842025d69bSKonstantin Belousov 
15853949873fSKonstantin Belousov /*
15863949873fSKonstantin Belousov  * The OOM killer is the page daemon's action of last resort when
15873949873fSKonstantin Belousov  * memory allocation requests have been stalled for a prolonged period
15883949873fSKonstantin Belousov  * of time because it cannot reclaim memory.  This function computes
15893949873fSKonstantin Belousov  * the approximate number of physical pages that could be reclaimed if
15903949873fSKonstantin Belousov  * the specified address space is destroyed.
15913949873fSKonstantin Belousov  *
15923949873fSKonstantin Belousov  * Private, anonymous memory owned by the address space is the
15933949873fSKonstantin Belousov  * principal resource that we expect to recover after an OOM kill.
15943949873fSKonstantin Belousov  * Since the physical pages mapped by the address space's COW entries
15953949873fSKonstantin Belousov  * are typically shared pages, they are unlikely to be released and so
15963949873fSKonstantin Belousov  * they are not counted.
15973949873fSKonstantin Belousov  *
15983949873fSKonstantin Belousov  * To get to the point where the page daemon runs the OOM killer, its
15993949873fSKonstantin Belousov  * efforts to write-back vnode-backed pages may have stalled.  This
16003949873fSKonstantin Belousov  * could be caused by a memory allocation deadlock in the write path
16013949873fSKonstantin Belousov  * that might be resolved by an OOM kill.  Therefore, physical pages
16023949873fSKonstantin Belousov  * belonging to vnode-backed objects are counted, because they might
16033949873fSKonstantin Belousov  * be freed without being written out first if the address space holds
16043949873fSKonstantin Belousov  * the last reference to an unlinked vnode.
16053949873fSKonstantin Belousov  *
16063949873fSKonstantin Belousov  * Similarly, physical pages belonging to OBJT_PHYS objects are
16073949873fSKonstantin Belousov  * counted because the address space might hold the last reference to
16083949873fSKonstantin Belousov  * the object.
16093949873fSKonstantin Belousov  */
16103949873fSKonstantin Belousov static long
16113949873fSKonstantin Belousov vm_pageout_oom_pagecount(struct vmspace *vmspace)
16123949873fSKonstantin Belousov {
16133949873fSKonstantin Belousov 	vm_map_t map;
16143949873fSKonstantin Belousov 	vm_map_entry_t entry;
16153949873fSKonstantin Belousov 	vm_object_t obj;
16163949873fSKonstantin Belousov 	long res;
16173949873fSKonstantin Belousov 
16183949873fSKonstantin Belousov 	map = &vmspace->vm_map;
16193949873fSKonstantin Belousov 	KASSERT(!map->system_map, ("system map"));
16203949873fSKonstantin Belousov 	sx_assert(&map->lock, SA_LOCKED);
16213949873fSKonstantin Belousov 	res = 0;
16223949873fSKonstantin Belousov 	for (entry = map->header.next; entry != &map->header;
16233949873fSKonstantin Belousov 	    entry = entry->next) {
16243949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
16253949873fSKonstantin Belousov 			continue;
16263949873fSKonstantin Belousov 		obj = entry->object.vm_object;
16273949873fSKonstantin Belousov 		if (obj == NULL)
16283949873fSKonstantin Belousov 			continue;
16293949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
16303949873fSKonstantin Belousov 		    obj->ref_count != 1)
16313949873fSKonstantin Belousov 			continue;
16323949873fSKonstantin Belousov 		switch (obj->type) {
16333949873fSKonstantin Belousov 		case OBJT_DEFAULT:
16343949873fSKonstantin Belousov 		case OBJT_SWAP:
16353949873fSKonstantin Belousov 		case OBJT_PHYS:
16363949873fSKonstantin Belousov 		case OBJT_VNODE:
16373949873fSKonstantin Belousov 			res += obj->resident_page_count;
16383949873fSKonstantin Belousov 			break;
16393949873fSKonstantin Belousov 		}
16403949873fSKonstantin Belousov 	}
16413949873fSKonstantin Belousov 	return (res);
16423949873fSKonstantin Belousov }
16433949873fSKonstantin Belousov 
16442025d69bSKonstantin Belousov void
16452025d69bSKonstantin Belousov vm_pageout_oom(int shortage)
16462025d69bSKonstantin Belousov {
16472025d69bSKonstantin Belousov 	struct proc *p, *bigproc;
16482025d69bSKonstantin Belousov 	vm_offset_t size, bigsize;
16492025d69bSKonstantin Belousov 	struct thread *td;
16506bed074cSKonstantin Belousov 	struct vmspace *vm;
16513e78e983SAlan Cox 	bool breakout;
16522025d69bSKonstantin Belousov 
16532025d69bSKonstantin Belousov 	/*
16541c58e4e5SJohn Baldwin 	 * We keep the process bigproc locked once we find it to keep anyone
16551c58e4e5SJohn Baldwin 	 * from messing with it; however, there is a possibility of
165628323addSBryan Drewery 	 * deadlock if process B is bigproc and one of its child processes
16571c58e4e5SJohn Baldwin 	 * attempts to propagate a signal to B while we are waiting for A's
16581c58e4e5SJohn Baldwin 	 * lock while walking this list.  To avoid this, we don't block on
16591c58e4e5SJohn Baldwin 	 * the process lock but just skip a process if it is already locked.
16605663e6deSDavid Greenman 	 */
16615663e6deSDavid Greenman 	bigproc = NULL;
16625663e6deSDavid Greenman 	bigsize = 0;
16631005a129SJohn Baldwin 	sx_slock(&allproc_lock);
1664e602ba25SJulian Elischer 	FOREACH_PROC_IN_SYSTEM(p) {
166571943c3dSKonstantin Belousov 		PROC_LOCK(p);
166671943c3dSKonstantin Belousov 
16671c58e4e5SJohn Baldwin 		/*
16683f1c4c4fSKonstantin Belousov 		 * If this is a system, protected or killed process, skip it.
16695663e6deSDavid Greenman 		 */
167071943c3dSKonstantin Belousov 		if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
167171943c3dSKonstantin Belousov 		    P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
167271943c3dSKonstantin Belousov 		    p->p_pid == 1 || P_KILLED(p) ||
167371943c3dSKonstantin Belousov 		    (p->p_pid < 48 && swap_pager_avail != 0)) {
16748606d880SJohn Baldwin 			PROC_UNLOCK(p);
16755663e6deSDavid Greenman 			continue;
16765663e6deSDavid Greenman 		}
16775663e6deSDavid Greenman 		/*
1678dcbcd518SBruce Evans 		 * If the process is in a non-running type state,
1679e602ba25SJulian Elischer 		 * don't touch it.  Check all the threads individually.
16805663e6deSDavid Greenman 		 */
16813e78e983SAlan Cox 		breakout = false;
1682e602ba25SJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td) {
1683982d11f8SJeff Roberson 			thread_lock(td);
168471fad9fdSJulian Elischer 			if (!TD_ON_RUNQ(td) &&
168571fad9fdSJulian Elischer 			    !TD_IS_RUNNING(td) &&
1686f497cda2SEdward Tomasz Napierala 			    !TD_IS_SLEEPING(td) &&
1687b98acc0aSKonstantin Belousov 			    !TD_IS_SUSPENDED(td) &&
1688b98acc0aSKonstantin Belousov 			    !TD_IS_SWAPPED(td)) {
1689982d11f8SJeff Roberson 				thread_unlock(td);
16903e78e983SAlan Cox 				breakout = true;
1691e602ba25SJulian Elischer 				break;
1692e602ba25SJulian Elischer 			}
1693982d11f8SJeff Roberson 			thread_unlock(td);
1694e602ba25SJulian Elischer 		}
1695e602ba25SJulian Elischer 		if (breakout) {
16961c58e4e5SJohn Baldwin 			PROC_UNLOCK(p);
16975663e6deSDavid Greenman 			continue;
16985663e6deSDavid Greenman 		}
16995663e6deSDavid Greenman 		/*
17005663e6deSDavid Greenman 		 * get the process size
17015663e6deSDavid Greenman 		 */
17026bed074cSKonstantin Belousov 		vm = vmspace_acquire_ref(p);
17036bed074cSKonstantin Belousov 		if (vm == NULL) {
17046bed074cSKonstantin Belousov 			PROC_UNLOCK(p);
17056bed074cSKonstantin Belousov 			continue;
17066bed074cSKonstantin Belousov 		}
170795e2409aSKonstantin Belousov 		_PHOLD_LITE(p);
170872d97679SDavid Schultz 		PROC_UNLOCK(p);
170995e2409aSKonstantin Belousov 		sx_sunlock(&allproc_lock);
171095e2409aSKonstantin Belousov 		if (!vm_map_trylock_read(&vm->vm_map)) {
171171943c3dSKonstantin Belousov 			vmspace_free(vm);
171295e2409aSKonstantin Belousov 			sx_slock(&allproc_lock);
171395e2409aSKonstantin Belousov 			PRELE(p);
171472d97679SDavid Schultz 			continue;
171572d97679SDavid Schultz 		}
17167981aa24SKonstantin Belousov 		size = vmspace_swap_count(vm);
17172025d69bSKonstantin Belousov 		if (shortage == VM_OOM_MEM)
17183949873fSKonstantin Belousov 			size += vm_pageout_oom_pagecount(vm);
17193949873fSKonstantin Belousov 		vm_map_unlock_read(&vm->vm_map);
17206bed074cSKonstantin Belousov 		vmspace_free(vm);
172195e2409aSKonstantin Belousov 		sx_slock(&allproc_lock);
17223949873fSKonstantin Belousov 
17235663e6deSDavid Greenman 		/*
17243949873fSKonstantin Belousov 		 * If this process is bigger than the biggest one,
17255663e6deSDavid Greenman 		 * remember it.
17265663e6deSDavid Greenman 		 */
17275663e6deSDavid Greenman 		if (size > bigsize) {
17281c58e4e5SJohn Baldwin 			if (bigproc != NULL)
172971943c3dSKonstantin Belousov 				PRELE(bigproc);
17305663e6deSDavid Greenman 			bigproc = p;
17315663e6deSDavid Greenman 			bigsize = size;
173271943c3dSKonstantin Belousov 		} else {
173371943c3dSKonstantin Belousov 			PRELE(p);
173471943c3dSKonstantin Belousov 		}
17355663e6deSDavid Greenman 	}
17361005a129SJohn Baldwin 	sx_sunlock(&allproc_lock);
17375663e6deSDavid Greenman 	if (bigproc != NULL) {
17388311a2b8SWill Andrews 		if (vm_panic_on_oom != 0)
17398311a2b8SWill Andrews 			panic("out of swap space");
174071943c3dSKonstantin Belousov 		PROC_LOCK(bigproc);
1741729b1e51SDavid Greenman 		killproc(bigproc, "out of swap space");
1742fa885116SJulian Elischer 		sched_nice(bigproc, PRIO_MIN);
174371943c3dSKonstantin Belousov 		_PRELE(bigproc);
17441c58e4e5SJohn Baldwin 		PROC_UNLOCK(bigproc);
174544f1c916SBryan Drewery 		wakeup(&vm_cnt.v_free_count);
17465663e6deSDavid Greenman 	}
17475663e6deSDavid Greenman }
174826f9a767SRodney W. Grimes 
1749449c2e92SKonstantin Belousov static void
1750449c2e92SKonstantin Belousov vm_pageout_worker(void *arg)
1751449c2e92SKonstantin Belousov {
1752449c2e92SKonstantin Belousov 	struct vm_domain *domain;
175370cf3cedSAlan Cox 	int domidx, pass;
1754e57dd910SAlan Cox 	bool target_met;
1755449c2e92SKonstantin Belousov 
1756449c2e92SKonstantin Belousov 	domidx = (uintptr_t)arg;
1757449c2e92SKonstantin Belousov 	domain = &vm_dom[domidx];
175870cf3cedSAlan Cox 	pass = 0;
1759e57dd910SAlan Cox 	target_met = true;
1760449c2e92SKonstantin Belousov 
1761449c2e92SKonstantin Belousov 	/*
1762949c9186SKonstantin Belousov 	 * XXXKIB It could be useful to bind pageout daemon threads to
1763949c9186SKonstantin Belousov 	 * the cores belonging to the domain, from which vm_page_array
1764949c9186SKonstantin Belousov 	 * is allocated.
1765449c2e92SKonstantin Belousov 	 */
1766449c2e92SKonstantin Belousov 
1767449c2e92SKonstantin Belousov 	KASSERT(domain->vmd_segs != 0, ("domain without segments"));
176822cf98d1SAlan Cox 	domain->vmd_last_active_scan = ticks;
1769449c2e92SKonstantin Belousov 	vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
17707e78597fSMark Johnston 	vm_pageout_init_marker(&domain->vmd_inacthead, PQ_INACTIVE);
17717e78597fSMark Johnston 	TAILQ_INSERT_HEAD(&domain->vmd_pagequeues[PQ_INACTIVE].pq_pl,
17727e78597fSMark Johnston 	    &domain->vmd_inacthead, plinks.q);
1773449c2e92SKonstantin Belousov 
1774449c2e92SKonstantin Belousov 	/*
1775449c2e92SKonstantin Belousov 	 * The pageout daemon worker is never done, so loop forever.
1776449c2e92SKonstantin Belousov 	 */
1777449c2e92SKonstantin Belousov 	while (TRUE) {
1778449c2e92SKonstantin Belousov 		mtx_lock(&vm_page_queue_free_mtx);
177956ce0690SAlan Cox 
178056ce0690SAlan Cox 		/*
178156ce0690SAlan Cox 		 * Generally, after a level >= 1 scan, if there are enough
178256ce0690SAlan Cox 		 * free pages to wakeup the waiters, then they are already
178356ce0690SAlan Cox 		 * awake.  A call to vm_page_free() during the scan awakened
178456ce0690SAlan Cox 		 * them.  However, in the following case, this wakeup serves
178556ce0690SAlan Cox 		 * to bound the amount of time that a thread might wait.
178656ce0690SAlan Cox 		 * Suppose a thread's call to vm_page_alloc() fails, but
178756ce0690SAlan Cox 		 * before that thread calls VM_WAIT, enough pages are freed by
178856ce0690SAlan Cox 		 * other threads to alleviate the free page shortage.  The
178956ce0690SAlan Cox 		 * thread will, nonetheless, wait until another page is freed
179056ce0690SAlan Cox 		 * or this wakeup is performed.
179156ce0690SAlan Cox 		 */
1792449c2e92SKonstantin Belousov 		if (vm_pages_needed && !vm_page_count_min()) {
179356ce0690SAlan Cox 			vm_pages_needed = false;
179444f1c916SBryan Drewery 			wakeup(&vm_cnt.v_free_count);
1795449c2e92SKonstantin Belousov 		}
179656ce0690SAlan Cox 
1797449c2e92SKonstantin Belousov 		/*
1798e57dd910SAlan Cox 		 * Do not clear vm_pageout_wanted until we reach our free page
1799e57dd910SAlan Cox 		 * target.  Otherwise, we may be awakened over and over again,
1800e57dd910SAlan Cox 		 * wasting CPU time.
1801449c2e92SKonstantin Belousov 		 */
1802e57dd910SAlan Cox 		if (vm_pageout_wanted && target_met)
180356ce0690SAlan Cox 			vm_pageout_wanted = false;
180456ce0690SAlan Cox 
180556ce0690SAlan Cox 		/*
180656ce0690SAlan Cox 		 * Might the page daemon receive a wakeup call?
180756ce0690SAlan Cox 		 */
180856ce0690SAlan Cox 		if (vm_pageout_wanted) {
180956ce0690SAlan Cox 			/*
181056ce0690SAlan Cox 			 * No.  Either vm_pageout_wanted was set by another
181156ce0690SAlan Cox 			 * thread during the previous scan, which must have
181256ce0690SAlan Cox 			 * been a level 0 scan, or vm_pageout_wanted was
181356ce0690SAlan Cox 			 * already set and the scan failed to free enough
1814ebcddc72SAlan Cox 			 * pages.  If we haven't yet performed a level >= 1
1815ebcddc72SAlan Cox 			 * (page reclamation) scan, then increase the level
1816ebcddc72SAlan Cox 			 * and scan again now.  Otherwise, sleep a bit and
1817ebcddc72SAlan Cox 			 * try again later.
181856ce0690SAlan Cox 			 */
181956ce0690SAlan Cox 			mtx_unlock(&vm_page_queue_free_mtx);
1820ebcddc72SAlan Cox 			if (pass >= 1)
1821ebcddc72SAlan Cox 				pause("psleep", hz / VM_INACT_SCAN_RATE);
182270cf3cedSAlan Cox 			pass++;
1823449c2e92SKonstantin Belousov 		} else {
1824449c2e92SKonstantin Belousov 			/*
182556ce0690SAlan Cox 			 * Yes.  Sleep until pages need to be reclaimed or
182656ce0690SAlan Cox 			 * have their reference stats updated.
1827449c2e92SKonstantin Belousov 			 */
182856ce0690SAlan Cox 			if (mtx_sleep(&vm_pageout_wanted,
182956ce0690SAlan Cox 			    &vm_page_queue_free_mtx, PDROP | PVM, "psleep",
183056ce0690SAlan Cox 			    hz) == 0) {
183183c9dea1SGleb Smirnoff 				VM_CNT_INC(v_pdwakeups);
183270cf3cedSAlan Cox 				pass = 1;
1833d9347bcaSAlan Cox 			} else
183470cf3cedSAlan Cox 				pass = 0;
183556ce0690SAlan Cox 		}
183656ce0690SAlan Cox 
183770cf3cedSAlan Cox 		target_met = vm_pageout_scan(domain, pass);
1838449c2e92SKonstantin Belousov 	}
1839449c2e92SKonstantin Belousov }
1840449c2e92SKonstantin Belousov 
1841df8bae1dSRodney W. Grimes /*
18424d19f4adSSteven Hartland  *	vm_pageout_init initialises basic pageout daemon settings.
1843df8bae1dSRodney W. Grimes  */
18442b14f991SJulian Elischer static void
18454d19f4adSSteven Hartland vm_pageout_init(void)
1846df8bae1dSRodney W. Grimes {
1847df8bae1dSRodney W. Grimes 	/*
1848df8bae1dSRodney W. Grimes 	 * Initialize some paging parameters.
1849df8bae1dSRodney W. Grimes 	 */
185044f1c916SBryan Drewery 	vm_cnt.v_interrupt_free_min = 2;
185144f1c916SBryan Drewery 	if (vm_cnt.v_page_count < 2000)
1852f35329acSJohn Dyson 		vm_pageout_page_count = 8;
1853f6b04d2bSDavid Greenman 
185445ae1d91SAlan Cox 	/*
185545ae1d91SAlan Cox 	 * v_free_reserved needs to include enough for the largest
185645ae1d91SAlan Cox 	 * swap pager structures plus enough for any pv_entry structs
185745ae1d91SAlan Cox 	 * when paging.
185845ae1d91SAlan Cox 	 */
185944f1c916SBryan Drewery 	if (vm_cnt.v_page_count > 1024)
186044f1c916SBryan Drewery 		vm_cnt.v_free_min = 4 + (vm_cnt.v_page_count - 1024) / 200;
18612feb50bfSAttilio Rao 	else
186244f1c916SBryan Drewery 		vm_cnt.v_free_min = 4;
186344f1c916SBryan Drewery 	vm_cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
186444f1c916SBryan Drewery 	    vm_cnt.v_interrupt_free_min;
186544f1c916SBryan Drewery 	vm_cnt.v_free_reserved = vm_pageout_page_count +
186644f1c916SBryan Drewery 	    vm_cnt.v_pageout_free_min + (vm_cnt.v_page_count / 768);
186744f1c916SBryan Drewery 	vm_cnt.v_free_severe = vm_cnt.v_free_min / 2;
186844f1c916SBryan Drewery 	vm_cnt.v_free_target = 4 * vm_cnt.v_free_min + vm_cnt.v_free_reserved;
186944f1c916SBryan Drewery 	vm_cnt.v_free_min += vm_cnt.v_free_reserved;
187044f1c916SBryan Drewery 	vm_cnt.v_free_severe += vm_cnt.v_free_reserved;
187144f1c916SBryan Drewery 	vm_cnt.v_inactive_target = (3 * vm_cnt.v_free_target) / 2;
187244f1c916SBryan Drewery 	if (vm_cnt.v_inactive_target > vm_cnt.v_free_count / 3)
187344f1c916SBryan Drewery 		vm_cnt.v_inactive_target = vm_cnt.v_free_count / 3;
1874df8bae1dSRodney W. Grimes 
1875d9e23210SJeff Roberson 	/*
1876d9e23210SJeff Roberson 	 * Set the default wakeup threshold to be 10% above the minimum
1877d9e23210SJeff Roberson 	 * page limit.  This keeps the steady state out of shortfall.
1878d9e23210SJeff Roberson 	 */
187944f1c916SBryan Drewery 	vm_pageout_wakeup_thresh = (vm_cnt.v_free_min / 10) * 11;
1880d9e23210SJeff Roberson 
1881d9e23210SJeff Roberson 	/*
1882d9e23210SJeff Roberson 	 * Set interval in seconds for active scan.  We want to visit each
1883c9612b2dSJeff Roberson 	 * page at least once every ten minutes.  This is to prevent worst
1884c9612b2dSJeff Roberson 	 * case paging behaviors with stale active LRU.
1885d9e23210SJeff Roberson 	 */
1886d9e23210SJeff Roberson 	if (vm_pageout_update_period == 0)
1887c9612b2dSJeff Roberson 		vm_pageout_update_period = 600;
1888d9e23210SJeff Roberson 
1889df8bae1dSRodney W. Grimes 	/* XXX does not really belong here */
1890df8bae1dSRodney W. Grimes 	if (vm_page_max_wired == 0)
189144f1c916SBryan Drewery 		vm_page_max_wired = vm_cnt.v_free_count / 3;
1892ebcddc72SAlan Cox 
1893ebcddc72SAlan Cox 	/*
1894ebcddc72SAlan Cox 	 * Target amount of memory to move out of the laundry queue during a
1895ebcddc72SAlan Cox 	 * background laundering.  This is proportional to the amount of system
1896ebcddc72SAlan Cox 	 * memory.
1897ebcddc72SAlan Cox 	 */
1898ebcddc72SAlan Cox 	vm_background_launder_target = (vm_cnt.v_free_target -
1899ebcddc72SAlan Cox 	    vm_cnt.v_free_min) / 10;
19004d19f4adSSteven Hartland }
19014d19f4adSSteven Hartland 
19024d19f4adSSteven Hartland /*
19034d19f4adSSteven Hartland  *     vm_pageout is the high level pageout daemon.
19044d19f4adSSteven Hartland  */
19054d19f4adSSteven Hartland static void
19064d19f4adSSteven Hartland vm_pageout(void)
19074d19f4adSSteven Hartland {
190844ec2b63SKonstantin Belousov 	int error;
190962d70a81SJohn Baldwin #ifdef VM_NUMA_ALLOC
191044ec2b63SKonstantin Belousov 	int i;
19114d19f4adSSteven Hartland #endif
1912df8bae1dSRodney W. Grimes 
191324a1cce3SDavid Greenman 	swap_pager_swap_init();
1914ebcddc72SAlan Cox 	error = kthread_add(vm_pageout_laundry_worker, NULL, curproc, NULL,
1915ebcddc72SAlan Cox 	    0, 0, "laundry: dom0");
1916ebcddc72SAlan Cox 	if (error != 0)
1917ebcddc72SAlan Cox 		panic("starting laundry for domain 0, error %d", error);
191862d70a81SJohn Baldwin #ifdef VM_NUMA_ALLOC
1919449c2e92SKonstantin Belousov 	for (i = 1; i < vm_ndomains; i++) {
1920449c2e92SKonstantin Belousov 		error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
1921449c2e92SKonstantin Belousov 		    curproc, NULL, 0, 0, "dom%d", i);
1922449c2e92SKonstantin Belousov 		if (error != 0) {
1923449c2e92SKonstantin Belousov 			panic("starting pageout for domain %d, error %d\n",
1924449c2e92SKonstantin Belousov 			    i, error);
1925dc2efb27SJohn Dyson 		}
1926f919ebdeSDavid Greenman 	}
1927449c2e92SKonstantin Belousov #endif
192844ec2b63SKonstantin Belousov 	error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
192944ec2b63SKonstantin Belousov 	    0, 0, "uma");
193044ec2b63SKonstantin Belousov 	if (error != 0)
193144ec2b63SKonstantin Belousov 		panic("starting uma_reclaim helper, error %d\n", error);
1932d395270dSDimitry Andric 	vm_pageout_worker((void *)(uintptr_t)0);
1933df8bae1dSRodney W. Grimes }
193426f9a767SRodney W. Grimes 
19356b4b77adSAlan Cox /*
1936e9f995d8SAlan Cox  * Unless the free page queue lock is held by the caller, this function
19376b4b77adSAlan Cox  * should be regarded as advisory.  Specifically, the caller should
193844f1c916SBryan Drewery  * not msleep() on &vm_cnt.v_free_count following this function unless
1939e9f995d8SAlan Cox  * the free page queue lock is held until the msleep() is performed.
19406b4b77adSAlan Cox  */
1941e0c5a895SJohn Dyson void
19424a365329SAndrey Zonov pagedaemon_wakeup(void)
1943e0c5a895SJohn Dyson {
1944a1c0a785SAlan Cox 
194556ce0690SAlan Cox 	if (!vm_pageout_wanted && curthread->td_proc != pageproc) {
194656ce0690SAlan Cox 		vm_pageout_wanted = true;
194756ce0690SAlan Cox 		wakeup(&vm_pageout_wanted);
1948e0c5a895SJohn Dyson 	}
1949e0c5a895SJohn Dyson }
1950