xref: /freebsd/sys/vm/vm_pageout.c (revision 8fc2550837bfde16dbd65d489c00dedd018d82ae)
160727d8bSWarner Losh /*-
2796df753SPedro F. Giffuni  * SPDX-License-Identifier: (BSD-4-Clause AND MIT-CMU)
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>
113e2068d0bSJeff Roberson #include <vm/vm_pagequeue.h>
11405f0fdd2SPoul-Henning Kamp #include <vm/swap_pager.h>
115efeaf95aSDavid Greenman #include <vm/vm_extern.h>
116670d17b5SJeff Roberson #include <vm/uma.h>
117df8bae1dSRodney W. Grimes 
1182b14f991SJulian Elischer /*
1192b14f991SJulian Elischer  * System initialization
1202b14f991SJulian Elischer  */
1212b14f991SJulian Elischer 
1222b14f991SJulian Elischer /* the kernel process "vm_pageout"*/
12311caded3SAlfred Perlstein static void vm_pageout(void);
1244d19f4adSSteven Hartland static void vm_pageout_init(void);
125ebcddc72SAlan Cox static int vm_pageout_clean(vm_page_t m, int *numpagedout);
12634d8b7eaSJeff Roberson static int vm_pageout_cluster(vm_page_t m);
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
1485f8cd1c0SJeff Roberson #define	VM_INACT_SCAN_RATE	10
1492b14f991SJulian Elischer 
15076386c7eSKonstantin Belousov static int vm_pageout_oom_seq = 12;
151ebcddc72SAlan Cox 
152d9e23210SJeff Roberson static int vm_pageout_update_period;
1534a365329SAndrey Zonov static int disable_swap_pageouts;
154c9612b2dSJeff Roberson static int lowmem_period = 10;
155b1fd102eSMark Johnston static int swapdev_enabled;
15670111b90SJohn Dyson 
1578311a2b8SWill Andrews static int vm_panic_on_oom = 0;
1588311a2b8SWill Andrews 
1598311a2b8SWill Andrews SYSCTL_INT(_vm, OID_AUTO, panic_on_oom,
1608311a2b8SWill Andrews 	CTLFLAG_RWTUN, &vm_panic_on_oom, 0,
1618311a2b8SWill Andrews 	"panic on out of memory instead of killing the largest process");
1628311a2b8SWill Andrews 
163d9e23210SJeff Roberson SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
164e0b2fc3aSMark Johnston 	CTLFLAG_RWTUN, &vm_pageout_update_period, 0,
165d9e23210SJeff Roberson 	"Maximum active LRU update period");
16653636869SAndrey Zonov 
167e0b2fc3aSMark Johnston SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RWTUN, &lowmem_period, 0,
168c9612b2dSJeff Roberson 	"Low memory callback period");
169c9612b2dSJeff Roberson 
170ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
171e0b2fc3aSMark Johnston 	CTLFLAG_RWTUN, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
17212ac6a1dSJohn Dyson 
17323b59018SMatthew Dillon static int pageout_lock_miss;
17423b59018SMatthew Dillon SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
17523b59018SMatthew Dillon 	CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
17623b59018SMatthew Dillon 
17776386c7eSKonstantin Belousov SYSCTL_INT(_vm, OID_AUTO, pageout_oom_seq,
178e0b2fc3aSMark Johnston 	CTLFLAG_RWTUN, &vm_pageout_oom_seq, 0,
17976386c7eSKonstantin Belousov 	"back-to-back calls to oom detector to start OOM");
18076386c7eSKonstantin Belousov 
181ebcddc72SAlan Cox static int act_scan_laundry_weight = 3;
182e0b2fc3aSMark Johnston SYSCTL_INT(_vm, OID_AUTO, act_scan_laundry_weight, CTLFLAG_RWTUN,
183ebcddc72SAlan Cox     &act_scan_laundry_weight, 0,
184ebcddc72SAlan Cox     "weight given to clean vs. dirty pages in active queue scans");
185ebcddc72SAlan Cox 
186ebcddc72SAlan Cox static u_int vm_background_launder_rate = 4096;
187e0b2fc3aSMark Johnston SYSCTL_UINT(_vm, OID_AUTO, background_launder_rate, CTLFLAG_RWTUN,
188ebcddc72SAlan Cox     &vm_background_launder_rate, 0,
189ebcddc72SAlan Cox     "background laundering rate, in kilobytes per second");
190ebcddc72SAlan Cox 
191ebcddc72SAlan Cox static u_int vm_background_launder_max = 20 * 1024;
192e0b2fc3aSMark Johnston SYSCTL_UINT(_vm, OID_AUTO, background_launder_max, CTLFLAG_RWTUN,
193ebcddc72SAlan Cox     &vm_background_launder_max, 0, "background laundering cap, in kilobytes");
194ebcddc72SAlan Cox 
195e2241590SAlan Cox int vm_pageout_page_count = 32;
196df8bae1dSRodney W. Grimes 
19754a3a114SMark Johnston u_long vm_page_max_user_wired;
19854a3a114SMark Johnston SYSCTL_ULONG(_vm, OID_AUTO, max_user_wired, CTLFLAG_RW,
19954a3a114SMark Johnston     &vm_page_max_user_wired, 0,
20054a3a114SMark Johnston     "system-wide limit to user-wired page count");
201df8bae1dSRodney W. Grimes 
202ebcddc72SAlan Cox static u_int isqrt(u_int num);
203ebcddc72SAlan Cox static int vm_pageout_launder(struct vm_domain *vmd, int launder,
204ebcddc72SAlan Cox     bool in_shortfall);
205ebcddc72SAlan Cox static void vm_pageout_laundry_worker(void *arg);
206cd41fc12SDavid Greenman 
2075cd29d0fSMark Johnston struct scan_state {
2085cd29d0fSMark Johnston 	struct vm_batchqueue bq;
2098d220203SAlan Cox 	struct vm_pagequeue *pq;
2105cd29d0fSMark Johnston 	vm_page_t	marker;
2115cd29d0fSMark Johnston 	int		maxscan;
2125cd29d0fSMark Johnston 	int		scanned;
2135cd29d0fSMark Johnston };
2148dbca793STor Egge 
2155cd29d0fSMark Johnston static void
2165cd29d0fSMark Johnston vm_pageout_init_scan(struct scan_state *ss, struct vm_pagequeue *pq,
2175cd29d0fSMark Johnston     vm_page_t marker, vm_page_t after, int maxscan)
2185cd29d0fSMark Johnston {
2198dbca793STor Egge 
2205cd29d0fSMark Johnston 	vm_pagequeue_assert_locked(pq);
221e8bcf696SMark Johnston 	KASSERT((marker->aflags & PGA_ENQUEUED) == 0,
2225cd29d0fSMark Johnston 	    ("marker %p already enqueued", marker));
2235cd29d0fSMark Johnston 
2245cd29d0fSMark Johnston 	if (after == NULL)
2255cd29d0fSMark Johnston 		TAILQ_INSERT_HEAD(&pq->pq_pl, marker, plinks.q);
2265cd29d0fSMark Johnston 	else
2275cd29d0fSMark Johnston 		TAILQ_INSERT_AFTER(&pq->pq_pl, after, marker, plinks.q);
2285cd29d0fSMark Johnston 	vm_page_aflag_set(marker, PGA_ENQUEUED);
2295cd29d0fSMark Johnston 
2305cd29d0fSMark Johnston 	vm_batchqueue_init(&ss->bq);
2315cd29d0fSMark Johnston 	ss->pq = pq;
2325cd29d0fSMark Johnston 	ss->marker = marker;
2335cd29d0fSMark Johnston 	ss->maxscan = maxscan;
2345cd29d0fSMark Johnston 	ss->scanned = 0;
2358d220203SAlan Cox 	vm_pagequeue_unlock(pq);
2365cd29d0fSMark Johnston }
2378dbca793STor Egge 
2385cd29d0fSMark Johnston static void
2395cd29d0fSMark Johnston vm_pageout_end_scan(struct scan_state *ss)
2405cd29d0fSMark Johnston {
2415cd29d0fSMark Johnston 	struct vm_pagequeue *pq;
2425cd29d0fSMark Johnston 
2435cd29d0fSMark Johnston 	pq = ss->pq;
2445cd29d0fSMark Johnston 	vm_pagequeue_assert_locked(pq);
245e8bcf696SMark Johnston 	KASSERT((ss->marker->aflags & PGA_ENQUEUED) != 0,
2465cd29d0fSMark Johnston 	    ("marker %p not enqueued", ss->marker));
2475cd29d0fSMark Johnston 
2485cd29d0fSMark Johnston 	TAILQ_REMOVE(&pq->pq_pl, ss->marker, plinks.q);
2495cd29d0fSMark Johnston 	vm_page_aflag_clear(ss->marker, PGA_ENQUEUED);
250899fe184SMark Johnston 	pq->pq_pdpages += ss->scanned;
2518dbca793STor Egge }
2528dbca793STor Egge 
2538dbca793STor Egge /*
2545cd29d0fSMark Johnston  * Add a small number of queued pages to a batch queue for later processing
2555cd29d0fSMark Johnston  * without the corresponding queue lock held.  The caller must have enqueued a
2565cd29d0fSMark Johnston  * marker page at the desired start point for the scan.  Pages will be
2575cd29d0fSMark Johnston  * physically dequeued if the caller so requests.  Otherwise, the returned
2585cd29d0fSMark Johnston  * batch may contain marker pages, and it is up to the caller to handle them.
2595cd29d0fSMark Johnston  *
26036f8fe9bSMark Johnston  * When processing the batch queue, vm_page_queue() must be used to
26136f8fe9bSMark Johnston  * determine whether the page has been logically dequeued by another thread.
26236f8fe9bSMark Johnston  * Once this check is performed, the page lock guarantees that the page will
26336f8fe9bSMark Johnston  * not be disassociated from the queue.
2645cd29d0fSMark Johnston  */
2655cd29d0fSMark Johnston static __always_inline void
2665cd29d0fSMark Johnston vm_pageout_collect_batch(struct scan_state *ss, const bool dequeue)
2675cd29d0fSMark Johnston {
2688d220203SAlan Cox 	struct vm_pagequeue *pq;
269d70f0ab3SMark Johnston 	vm_page_t m, marker, n;
2708c616246SKonstantin Belousov 
2715cd29d0fSMark Johnston 	marker = ss->marker;
2725cd29d0fSMark Johnston 	pq = ss->pq;
2738c616246SKonstantin Belousov 
274e8bcf696SMark Johnston 	KASSERT((marker->aflags & PGA_ENQUEUED) != 0,
2755cd29d0fSMark Johnston 	    ("marker %p not enqueued", ss->marker));
2768c616246SKonstantin Belousov 
2778d220203SAlan Cox 	vm_pagequeue_lock(pq);
2785cd29d0fSMark Johnston 	for (m = TAILQ_NEXT(marker, plinks.q); m != NULL &&
2795cd29d0fSMark Johnston 	    ss->scanned < ss->maxscan && ss->bq.bq_cnt < VM_BATCHQUEUE_SIZE;
280d70f0ab3SMark Johnston 	    m = n, ss->scanned++) {
281d70f0ab3SMark Johnston 		n = TAILQ_NEXT(m, plinks.q);
2825cd29d0fSMark Johnston 		if ((m->flags & PG_MARKER) == 0) {
283e8bcf696SMark Johnston 			KASSERT((m->aflags & PGA_ENQUEUED) != 0,
2845cd29d0fSMark Johnston 			    ("page %p not enqueued", m));
2855cd29d0fSMark Johnston 			KASSERT((m->flags & PG_FICTITIOUS) == 0,
2865cd29d0fSMark Johnston 			    ("Fictitious page %p cannot be in page queue", m));
2875cd29d0fSMark Johnston 			KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2885cd29d0fSMark Johnston 			    ("Unmanaged page %p cannot be in page queue", m));
2895cd29d0fSMark Johnston 		} else if (dequeue)
2905cd29d0fSMark Johnston 			continue;
2918c616246SKonstantin Belousov 
2925cd29d0fSMark Johnston 		(void)vm_batchqueue_insert(&ss->bq, m);
2935cd29d0fSMark Johnston 		if (dequeue) {
2945cd29d0fSMark Johnston 			TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2955cd29d0fSMark Johnston 			vm_page_aflag_clear(m, PGA_ENQUEUED);
2965cd29d0fSMark Johnston 		}
2975cd29d0fSMark Johnston 	}
2985cd29d0fSMark Johnston 	TAILQ_REMOVE(&pq->pq_pl, marker, plinks.q);
2995cd29d0fSMark Johnston 	if (__predict_true(m != NULL))
3005cd29d0fSMark Johnston 		TAILQ_INSERT_BEFORE(m, marker, plinks.q);
3015cd29d0fSMark Johnston 	else
3025cd29d0fSMark Johnston 		TAILQ_INSERT_TAIL(&pq->pq_pl, marker, plinks.q);
3035cd29d0fSMark Johnston 	if (dequeue)
3045cd29d0fSMark Johnston 		vm_pagequeue_cnt_add(pq, -ss->bq.bq_cnt);
3055cd29d0fSMark Johnston 	vm_pagequeue_unlock(pq);
3065cd29d0fSMark Johnston }
3075cd29d0fSMark Johnston 
308fee2a2faSMark Johnston /*
309fee2a2faSMark Johnston  * Return the next page to be scanned, or NULL if the scan is complete.
310fee2a2faSMark Johnston  */
3115cd29d0fSMark Johnston static __always_inline vm_page_t
3125cd29d0fSMark Johnston vm_pageout_next(struct scan_state *ss, const bool dequeue)
3135cd29d0fSMark Johnston {
3145cd29d0fSMark Johnston 
3155cd29d0fSMark Johnston 	if (ss->bq.bq_cnt == 0)
3165cd29d0fSMark Johnston 		vm_pageout_collect_batch(ss, dequeue);
3175cd29d0fSMark Johnston 	return (vm_batchqueue_pop(&ss->bq));
3188c616246SKonstantin Belousov }
3198c616246SKonstantin Belousov 
3208c616246SKonstantin Belousov /*
321248fe642SAlan Cox  * Scan for pages at adjacent offsets within the given page's object that are
322248fe642SAlan Cox  * eligible for laundering, form a cluster of these pages and the given page,
323248fe642SAlan Cox  * and launder that cluster.
32426f9a767SRodney W. Grimes  */
3253af76890SPoul-Henning Kamp static int
32634d8b7eaSJeff Roberson vm_pageout_cluster(vm_page_t m)
32724a1cce3SDavid Greenman {
32854d92145SMatthew Dillon 	vm_object_t object;
329248fe642SAlan Cox 	vm_page_t mc[2 * vm_pageout_page_count], p, pb, ps;
330248fe642SAlan Cox 	vm_pindex_t pindex;
331248fe642SAlan Cox 	int ib, is, page_base, pageout_count;
33226f9a767SRodney W. Grimes 
33317f6a17bSAlan Cox 	object = m->object;
33489f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
335248fe642SAlan Cox 	pindex = m->pindex;
3360cddd8f0SMatthew Dillon 
33763e97555SJeff Roberson 	vm_page_assert_xbusied(m);
3380d94caffSDavid Greenman 
33991b4f427SAlan Cox 	mc[vm_pageout_page_count] = pb = ps = m;
34026f9a767SRodney W. Grimes 	pageout_count = 1;
341f35329acSJohn Dyson 	page_base = vm_pageout_page_count;
34290ecac61SMatthew Dillon 	ib = 1;
34390ecac61SMatthew Dillon 	is = 1;
34490ecac61SMatthew Dillon 
34524a1cce3SDavid Greenman 	/*
346248fe642SAlan Cox 	 * We can cluster only if the page is not clean, busy, or held, and
347ebcddc72SAlan Cox 	 * the page is in the laundry queue.
34890ecac61SMatthew Dillon 	 *
34990ecac61SMatthew Dillon 	 * During heavy mmap/modification loads the pageout
35090ecac61SMatthew Dillon 	 * daemon can really fragment the underlying file
351248fe642SAlan Cox 	 * due to flushing pages out of order and not trying to
352248fe642SAlan Cox 	 * align the clusters (which leaves sporadic out-of-order
35390ecac61SMatthew Dillon 	 * holes).  To solve this problem we do the reverse scan
35490ecac61SMatthew Dillon 	 * first and attempt to align our cluster, then do a
35590ecac61SMatthew Dillon 	 * forward scan if room remains.
35624a1cce3SDavid Greenman 	 */
35790ecac61SMatthew Dillon more:
358248fe642SAlan Cox 	while (ib != 0 && pageout_count < vm_pageout_page_count) {
35990ecac61SMatthew Dillon 		if (ib > pindex) {
36090ecac61SMatthew Dillon 			ib = 0;
36190ecac61SMatthew Dillon 			break;
362f6b04d2bSDavid Greenman 		}
36363e97555SJeff Roberson 		if ((p = vm_page_prev(pb)) == NULL ||
36463e97555SJeff Roberson 		    vm_page_tryxbusy(p) == 0) {
36590ecac61SMatthew Dillon 			ib = 0;
36690ecac61SMatthew Dillon 			break;
367f6b04d2bSDavid Greenman 		}
36863e97555SJeff Roberson 		if (vm_page_wired(p)) {
36963e97555SJeff Roberson 			ib = 0;
37063e97555SJeff Roberson 			vm_page_xunbusy(p);
37163e97555SJeff Roberson 			break;
37263e97555SJeff Roberson 		}
37324a1cce3SDavid Greenman 		vm_page_test_dirty(p);
3741b5c869dSMark Johnston 		if (p->dirty == 0) {
375eb5d3969SAlan Cox 			ib = 0;
37663e97555SJeff Roberson 			vm_page_xunbusy(p);
377eb5d3969SAlan Cox 			break;
378eb5d3969SAlan Cox 		}
379e8bcf696SMark Johnston 		vm_page_lock(p);
380fee2a2faSMark Johnston 		if (!vm_page_in_laundry(p) || !vm_page_try_remove_write(p)) {
381e8bcf696SMark Johnston 			vm_page_unlock(p);
38263e97555SJeff Roberson 			vm_page_xunbusy(p);
38390ecac61SMatthew Dillon 			ib = 0;
38424a1cce3SDavid Greenman 			break;
385f6b04d2bSDavid Greenman 		}
386e8bcf696SMark Johnston 		vm_page_unlock(p);
38791b4f427SAlan Cox 		mc[--page_base] = pb = p;
38890ecac61SMatthew Dillon 		++pageout_count;
38990ecac61SMatthew Dillon 		++ib;
390248fe642SAlan Cox 
39124a1cce3SDavid Greenman 		/*
392248fe642SAlan Cox 		 * We are at an alignment boundary.  Stop here, and switch
393248fe642SAlan Cox 		 * directions.  Do not clear ib.
39424a1cce3SDavid Greenman 		 */
39590ecac61SMatthew Dillon 		if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
39690ecac61SMatthew Dillon 			break;
39724a1cce3SDavid Greenman 	}
39890ecac61SMatthew Dillon 	while (pageout_count < vm_pageout_page_count &&
39990ecac61SMatthew Dillon 	    pindex + is < object->size) {
40063e97555SJeff Roberson 		if ((p = vm_page_next(ps)) == NULL ||
40163e97555SJeff Roberson 		    vm_page_tryxbusy(p) == 0)
40290ecac61SMatthew Dillon 			break;
40363e97555SJeff Roberson 		if (vm_page_wired(p)) {
40463e97555SJeff Roberson 			vm_page_xunbusy(p);
40563e97555SJeff Roberson 			break;
40663e97555SJeff Roberson 		}
40724a1cce3SDavid Greenman 		vm_page_test_dirty(p);
40863e97555SJeff Roberson 		if (p->dirty == 0) {
40963e97555SJeff Roberson 			vm_page_xunbusy(p);
410eb5d3969SAlan Cox 			break;
41163e97555SJeff Roberson 		}
412e8bcf696SMark Johnston 		vm_page_lock(p);
413e8bcf696SMark Johnston 		if (!vm_page_in_laundry(p) || !vm_page_try_remove_write(p)) {
414e8bcf696SMark Johnston 			vm_page_unlock(p);
41563e97555SJeff Roberson 			vm_page_xunbusy(p);
41624a1cce3SDavid Greenman 			break;
417e8bcf696SMark Johnston 		}
418e8bcf696SMark Johnston 		vm_page_unlock(p);
41991b4f427SAlan Cox 		mc[page_base + pageout_count] = ps = p;
42090ecac61SMatthew Dillon 		++pageout_count;
42190ecac61SMatthew Dillon 		++is;
42224a1cce3SDavid Greenman 	}
42390ecac61SMatthew Dillon 
42490ecac61SMatthew Dillon 	/*
42590ecac61SMatthew Dillon 	 * If we exhausted our forward scan, continue with the reverse scan
426248fe642SAlan Cox 	 * when possible, even past an alignment boundary.  This catches
427248fe642SAlan Cox 	 * boundary conditions.
42890ecac61SMatthew Dillon 	 */
429248fe642SAlan Cox 	if (ib != 0 && pageout_count < vm_pageout_page_count)
43090ecac61SMatthew Dillon 		goto more;
431f6b04d2bSDavid Greenman 
43299e6e193SMark Johnston 	return (vm_pageout_flush(&mc[page_base], pageout_count,
43399e6e193SMark Johnston 	    VM_PAGER_PUT_NOREUSE, 0, NULL, NULL));
434aef922f5SJohn Dyson }
435aef922f5SJohn Dyson 
4361c7c3c6aSMatthew Dillon /*
4371c7c3c6aSMatthew Dillon  * vm_pageout_flush() - launder the given pages
4381c7c3c6aSMatthew Dillon  *
4391c7c3c6aSMatthew Dillon  *	The given pages are laundered.  Note that we setup for the start of
4401c7c3c6aSMatthew Dillon  *	I/O ( i.e. busy the page ), mark it read-only, and bump the object
4411c7c3c6aSMatthew Dillon  *	reference count all in here rather then in the parent.  If we want
4421c7c3c6aSMatthew Dillon  *	the parent to do more sophisticated things we may have to change
4431c7c3c6aSMatthew Dillon  *	the ordering.
4441e8a675cSKonstantin Belousov  *
4451e8a675cSKonstantin Belousov  *	Returned runlen is the count of pages between mreq and first
4461e8a675cSKonstantin Belousov  *	page after mreq with status VM_PAGER_AGAIN.
447126d6082SKonstantin Belousov  *	*eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
448126d6082SKonstantin Belousov  *	for any page in runlen set.
4491c7c3c6aSMatthew Dillon  */
450aef922f5SJohn Dyson int
451126d6082SKonstantin Belousov vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
452126d6082SKonstantin Belousov     boolean_t *eio)
453aef922f5SJohn Dyson {
4542e3b314dSAlan Cox 	vm_object_t object = mc[0]->object;
455aef922f5SJohn Dyson 	int pageout_status[count];
45695461b45SJohn Dyson 	int numpagedout = 0;
4571e8a675cSKonstantin Belousov 	int i, runlen;
458aef922f5SJohn Dyson 
45989f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
4607bec141bSKip Macy 
4611c7c3c6aSMatthew Dillon 	/*
46263e97555SJeff Roberson 	 * Initiate I/O.  Mark the pages shared busy and verify that they're
46363e97555SJeff Roberson 	 * valid and read-only.
4641c7c3c6aSMatthew Dillon 	 *
4651c7c3c6aSMatthew Dillon 	 * We do not have to fixup the clean/dirty bits here... we can
4661c7c3c6aSMatthew Dillon 	 * allow the pager to do it after the I/O completes.
46702fa91d3SMatthew Dillon 	 *
46802fa91d3SMatthew Dillon 	 * NOTE! mc[i]->dirty may be partial or fragmented due to an
46902fa91d3SMatthew Dillon 	 * edge case with file fragments.
4701c7c3c6aSMatthew Dillon 	 */
4718f9110f6SJohn Dyson 	for (i = 0; i < count; i++) {
4720012f373SJeff Roberson 		KASSERT(vm_page_all_valid(mc[i]),
4737a935082SAlan Cox 		    ("vm_pageout_flush: partially invalid page %p index %d/%d",
4747a935082SAlan Cox 			mc[i], i, count));
475e8bcf696SMark Johnston 		KASSERT((mc[i]->aflags & PGA_WRITEABLE) == 0,
476aed9aaaaSMark Johnston 		    ("vm_pageout_flush: writeable page %p", mc[i]));
47763e97555SJeff Roberson 		vm_page_busy_downgrade(mc[i]);
4782965a453SKip Macy 	}
479d474eaaaSDoug Rabson 	vm_object_pip_add(object, count);
480aef922f5SJohn Dyson 
481d076fbeaSAlan Cox 	vm_pager_put_pages(object, mc, count, flags, pageout_status);
48226f9a767SRodney W. Grimes 
4831e8a675cSKonstantin Belousov 	runlen = count - mreq;
484126d6082SKonstantin Belousov 	if (eio != NULL)
485126d6082SKonstantin Belousov 		*eio = FALSE;
486aef922f5SJohn Dyson 	for (i = 0; i < count; i++) {
487aef922f5SJohn Dyson 		vm_page_t mt = mc[i];
48824a1cce3SDavid Greenman 
4894cd45723SAlan Cox 		KASSERT(pageout_status[i] == VM_PAGER_PEND ||
4906031c68dSAlan Cox 		    !pmap_page_is_write_mapped(mt),
4919ea8d1a6SAlan Cox 		    ("vm_pageout_flush: page %p is not write protected", mt));
49226f9a767SRodney W. Grimes 		switch (pageout_status[i]) {
49326f9a767SRodney W. Grimes 		case VM_PAGER_OK:
494ebcddc72SAlan Cox 			vm_page_lock(mt);
495ebcddc72SAlan Cox 			if (vm_page_in_laundry(mt))
496ebcddc72SAlan Cox 				vm_page_deactivate_noreuse(mt);
497ebcddc72SAlan Cox 			vm_page_unlock(mt);
498ebcddc72SAlan Cox 			/* FALLTHROUGH */
49926f9a767SRodney W. Grimes 		case VM_PAGER_PEND:
50095461b45SJohn Dyson 			numpagedout++;
50126f9a767SRodney W. Grimes 			break;
50226f9a767SRodney W. Grimes 		case VM_PAGER_BAD:
50326f9a767SRodney W. Grimes 			/*
504ebcddc72SAlan Cox 			 * The page is outside the object's range.  We pretend
505ebcddc72SAlan Cox 			 * that the page out worked and clean the page, so the
506ebcddc72SAlan Cox 			 * changes will be lost if the page is reclaimed by
507ebcddc72SAlan Cox 			 * the page daemon.
50826f9a767SRodney W. Grimes 			 */
50990ecac61SMatthew Dillon 			vm_page_undirty(mt);
510ebcddc72SAlan Cox 			vm_page_lock(mt);
511ebcddc72SAlan Cox 			if (vm_page_in_laundry(mt))
512ebcddc72SAlan Cox 				vm_page_deactivate_noreuse(mt);
513ebcddc72SAlan Cox 			vm_page_unlock(mt);
51426f9a767SRodney W. Grimes 			break;
51526f9a767SRodney W. Grimes 		case VM_PAGER_ERROR:
51626f9a767SRodney W. Grimes 		case VM_PAGER_FAIL:
51726f9a767SRodney W. Grimes 			/*
518b1fd102eSMark Johnston 			 * If the page couldn't be paged out to swap because the
519b1fd102eSMark Johnston 			 * pager wasn't able to find space, place the page in
520b1fd102eSMark Johnston 			 * the PQ_UNSWAPPABLE holding queue.  This is an
521b1fd102eSMark Johnston 			 * optimization that prevents the page daemon from
522b1fd102eSMark Johnston 			 * wasting CPU cycles on pages that cannot be reclaimed
523b1fd102eSMark Johnston 			 * becase no swap device is configured.
524b1fd102eSMark Johnston 			 *
525b1fd102eSMark Johnston 			 * Otherwise, reactivate the page so that it doesn't
526b1fd102eSMark Johnston 			 * clog the laundry and inactive queues.  (We will try
527b1fd102eSMark Johnston 			 * paging it out again later.)
52826f9a767SRodney W. Grimes 			 */
5293c4a2440SAlan Cox 			vm_page_lock(mt);
530b1fd102eSMark Johnston 			if (object->type == OBJT_SWAP &&
531b1fd102eSMark Johnston 			    pageout_status[i] == VM_PAGER_FAIL) {
532b1fd102eSMark Johnston 				vm_page_unswappable(mt);
533b1fd102eSMark Johnston 				numpagedout++;
534b1fd102eSMark Johnston 			} else
53524a1cce3SDavid Greenman 				vm_page_activate(mt);
5363c4a2440SAlan Cox 			vm_page_unlock(mt);
537126d6082SKonstantin Belousov 			if (eio != NULL && i >= mreq && i - mreq < runlen)
538126d6082SKonstantin Belousov 				*eio = TRUE;
53926f9a767SRodney W. Grimes 			break;
54026f9a767SRodney W. Grimes 		case VM_PAGER_AGAIN:
5411e8a675cSKonstantin Belousov 			if (i >= mreq && i - mreq < runlen)
5421e8a675cSKonstantin Belousov 				runlen = i - mreq;
54326f9a767SRodney W. Grimes 			break;
54426f9a767SRodney W. Grimes 		}
54526f9a767SRodney W. Grimes 
54626f9a767SRodney W. Grimes 		/*
5470d94caffSDavid Greenman 		 * If the operation is still going, leave the page busy to
5480d94caffSDavid Greenman 		 * block all other accesses. Also, leave the paging in
5490d94caffSDavid Greenman 		 * progress indicator set so that we don't attempt an object
5500d94caffSDavid Greenman 		 * collapse.
55126f9a767SRodney W. Grimes 		 */
55226f9a767SRodney W. Grimes 		if (pageout_status[i] != VM_PAGER_PEND) {
553f919ebdeSDavid Greenman 			vm_object_pip_wakeup(object);
554c7aebda8SAttilio Rao 			vm_page_sunbusy(mt);
5553c4a2440SAlan Cox 		}
5563c4a2440SAlan Cox 	}
5571e8a675cSKonstantin Belousov 	if (prunlen != NULL)
5581e8a675cSKonstantin Belousov 		*prunlen = runlen;
5593c4a2440SAlan Cox 	return (numpagedout);
56026f9a767SRodney W. Grimes }
56126f9a767SRodney W. Grimes 
562b1fd102eSMark Johnston static void
563b1fd102eSMark Johnston vm_pageout_swapon(void *arg __unused, struct swdevt *sp __unused)
564b1fd102eSMark Johnston {
565b1fd102eSMark Johnston 
566b1fd102eSMark Johnston 	atomic_store_rel_int(&swapdev_enabled, 1);
567b1fd102eSMark Johnston }
568b1fd102eSMark Johnston 
569b1fd102eSMark Johnston static void
570b1fd102eSMark Johnston vm_pageout_swapoff(void *arg __unused, struct swdevt *sp __unused)
571b1fd102eSMark Johnston {
572b1fd102eSMark Johnston 
573b1fd102eSMark Johnston 	if (swap_pager_nswapdev() == 1)
574b1fd102eSMark Johnston 		atomic_store_rel_int(&swapdev_enabled, 0);
575b1fd102eSMark Johnston }
576b1fd102eSMark Johnston 
5771c7c3c6aSMatthew Dillon /*
57834d8b7eaSJeff Roberson  * Attempt to acquire all of the necessary locks to launder a page and
57934d8b7eaSJeff Roberson  * then call through the clustering layer to PUTPAGES.  Wait a short
58034d8b7eaSJeff Roberson  * time for a vnode lock.
58134d8b7eaSJeff Roberson  *
58234d8b7eaSJeff Roberson  * Requires the page and object lock on entry, releases both before return.
58334d8b7eaSJeff Roberson  * Returns 0 on success and an errno otherwise.
58434d8b7eaSJeff Roberson  */
58534d8b7eaSJeff Roberson static int
586ebcddc72SAlan Cox vm_pageout_clean(vm_page_t m, int *numpagedout)
58734d8b7eaSJeff Roberson {
58834d8b7eaSJeff Roberson 	struct vnode *vp;
58934d8b7eaSJeff Roberson 	struct mount *mp;
59034d8b7eaSJeff Roberson 	vm_object_t object;
59134d8b7eaSJeff Roberson 	vm_pindex_t pindex;
59234d8b7eaSJeff Roberson 	int error, lockmode;
59334d8b7eaSJeff Roberson 
594e8bcf696SMark Johnston 	vm_page_assert_locked(m);
59534d8b7eaSJeff Roberson 	object = m->object;
59634d8b7eaSJeff Roberson 	VM_OBJECT_ASSERT_WLOCKED(object);
59734d8b7eaSJeff Roberson 	error = 0;
59834d8b7eaSJeff Roberson 	vp = NULL;
59934d8b7eaSJeff Roberson 	mp = NULL;
60034d8b7eaSJeff Roberson 
60134d8b7eaSJeff Roberson 	/*
60234d8b7eaSJeff Roberson 	 * The object is already known NOT to be dead.   It
60334d8b7eaSJeff Roberson 	 * is possible for the vget() to block the whole
60434d8b7eaSJeff Roberson 	 * pageout daemon, but the new low-memory handling
60534d8b7eaSJeff Roberson 	 * code should prevent it.
60634d8b7eaSJeff Roberson 	 *
60734d8b7eaSJeff Roberson 	 * We can't wait forever for the vnode lock, we might
60834d8b7eaSJeff Roberson 	 * deadlock due to a vn_read() getting stuck in
60934d8b7eaSJeff Roberson 	 * vm_wait while holding this vnode.  We skip the
61034d8b7eaSJeff Roberson 	 * vnode if we can't get it in a reasonable amount
61134d8b7eaSJeff Roberson 	 * of time.
61234d8b7eaSJeff Roberson 	 */
61334d8b7eaSJeff Roberson 	if (object->type == OBJT_VNODE) {
614e8bcf696SMark Johnston 		vm_page_unlock(m);
61563e97555SJeff Roberson 		vm_page_xunbusy(m);
61634d8b7eaSJeff Roberson 		vp = object->handle;
61734d8b7eaSJeff Roberson 		if (vp->v_type == VREG &&
61834d8b7eaSJeff Roberson 		    vn_start_write(vp, &mp, V_NOWAIT) != 0) {
61934d8b7eaSJeff Roberson 			mp = NULL;
62034d8b7eaSJeff Roberson 			error = EDEADLK;
62134d8b7eaSJeff Roberson 			goto unlock_all;
62234d8b7eaSJeff Roberson 		}
62334d8b7eaSJeff Roberson 		KASSERT(mp != NULL,
62434d8b7eaSJeff Roberson 		    ("vp %p with NULL v_mount", vp));
62534d8b7eaSJeff Roberson 		vm_object_reference_locked(object);
62634d8b7eaSJeff Roberson 		pindex = m->pindex;
62734d8b7eaSJeff Roberson 		VM_OBJECT_WUNLOCK(object);
62834d8b7eaSJeff Roberson 		lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
62934d8b7eaSJeff Roberson 		    LK_SHARED : LK_EXCLUSIVE;
63034d8b7eaSJeff Roberson 		if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
63134d8b7eaSJeff Roberson 			vp = NULL;
63234d8b7eaSJeff Roberson 			error = EDEADLK;
63334d8b7eaSJeff Roberson 			goto unlock_mp;
63434d8b7eaSJeff Roberson 		}
63534d8b7eaSJeff Roberson 		VM_OBJECT_WLOCK(object);
63657cd81a3SMark Johnston 
63757cd81a3SMark Johnston 		/*
63857cd81a3SMark Johnston 		 * Ensure that the object and vnode were not disassociated
63957cd81a3SMark Johnston 		 * while locks were dropped.
64057cd81a3SMark Johnston 		 */
64157cd81a3SMark Johnston 		if (vp->v_object != object) {
64257cd81a3SMark Johnston 			error = ENOENT;
64357cd81a3SMark Johnston 			goto unlock_all;
64457cd81a3SMark Johnston 		}
645e8bcf696SMark Johnston 		vm_page_lock(m);
64657cd81a3SMark Johnston 
64734d8b7eaSJeff Roberson 		/*
64834d8b7eaSJeff Roberson 		 * While the object and page were unlocked, the page
64934d8b7eaSJeff Roberson 		 * may have been:
65034d8b7eaSJeff Roberson 		 * (1) moved to a different queue,
65134d8b7eaSJeff Roberson 		 * (2) reallocated to a different object,
65234d8b7eaSJeff Roberson 		 * (3) reallocated to a different offset, or
65334d8b7eaSJeff Roberson 		 * (4) cleaned.
65434d8b7eaSJeff Roberson 		 */
655ebcddc72SAlan Cox 		if (!vm_page_in_laundry(m) || m->object != object ||
65634d8b7eaSJeff Roberson 		    m->pindex != pindex || m->dirty == 0) {
65734d8b7eaSJeff Roberson 			vm_page_unlock(m);
65834d8b7eaSJeff Roberson 			error = ENXIO;
65934d8b7eaSJeff Roberson 			goto unlock_all;
66034d8b7eaSJeff Roberson 		}
66134d8b7eaSJeff Roberson 
66234d8b7eaSJeff Roberson 		/*
663fee2a2faSMark Johnston 		 * The page may have been busied while the object and page
664fee2a2faSMark Johnston 		 * locks were released.
66534d8b7eaSJeff Roberson 		 */
66663e97555SJeff Roberson 		if (vm_page_tryxbusy(m) == 0) {
66734d8b7eaSJeff Roberson 			vm_page_unlock(m);
66834d8b7eaSJeff Roberson 			error = EBUSY;
66934d8b7eaSJeff Roberson 			goto unlock_all;
67034d8b7eaSJeff Roberson 		}
67134d8b7eaSJeff Roberson 	}
67234d8b7eaSJeff Roberson 
67334d8b7eaSJeff Roberson 	/*
674fee2a2faSMark Johnston 	 * Remove all writeable mappings, failing if the page is wired.
675fee2a2faSMark Johnston 	 */
676fee2a2faSMark Johnston 	if (!vm_page_try_remove_write(m)) {
67763e97555SJeff Roberson 		vm_page_xunbusy(m);
678fee2a2faSMark Johnston 		vm_page_unlock(m);
679fee2a2faSMark Johnston 		error = EBUSY;
680fee2a2faSMark Johnston 		goto unlock_all;
681fee2a2faSMark Johnston 	}
682e8bcf696SMark Johnston 	vm_page_unlock(m);
683fee2a2faSMark Johnston 
684fee2a2faSMark Johnston 	/*
68534d8b7eaSJeff Roberson 	 * If a page is dirty, then it is either being washed
68634d8b7eaSJeff Roberson 	 * (but not yet cleaned) or it is still in the
68734d8b7eaSJeff Roberson 	 * laundry.  If it is still in the laundry, then we
68834d8b7eaSJeff Roberson 	 * start the cleaning operation.
68934d8b7eaSJeff Roberson 	 */
690ebcddc72SAlan Cox 	if ((*numpagedout = vm_pageout_cluster(m)) == 0)
69134d8b7eaSJeff Roberson 		error = EIO;
69234d8b7eaSJeff Roberson 
69334d8b7eaSJeff Roberson unlock_all:
69434d8b7eaSJeff Roberson 	VM_OBJECT_WUNLOCK(object);
69534d8b7eaSJeff Roberson 
69634d8b7eaSJeff Roberson unlock_mp:
69734d8b7eaSJeff Roberson 	vm_page_lock_assert(m, MA_NOTOWNED);
69834d8b7eaSJeff Roberson 	if (mp != NULL) {
69934d8b7eaSJeff Roberson 		if (vp != NULL)
70034d8b7eaSJeff Roberson 			vput(vp);
70134d8b7eaSJeff Roberson 		vm_object_deallocate(object);
70234d8b7eaSJeff Roberson 		vn_finished_write(mp);
70334d8b7eaSJeff Roberson 	}
70434d8b7eaSJeff Roberson 
70534d8b7eaSJeff Roberson 	return (error);
70634d8b7eaSJeff Roberson }
70734d8b7eaSJeff Roberson 
70834d8b7eaSJeff Roberson /*
709ebcddc72SAlan Cox  * Attempt to launder the specified number of pages.
710ebcddc72SAlan Cox  *
711ebcddc72SAlan Cox  * Returns the number of pages successfully laundered.
712ebcddc72SAlan Cox  */
713ebcddc72SAlan Cox static int
714ebcddc72SAlan Cox vm_pageout_launder(struct vm_domain *vmd, int launder, bool in_shortfall)
715ebcddc72SAlan Cox {
7165cd29d0fSMark Johnston 	struct scan_state ss;
717ebcddc72SAlan Cox 	struct vm_pagequeue *pq;
718e8bcf696SMark Johnston 	struct mtx *mtx;
719ebcddc72SAlan Cox 	vm_object_t object;
7205cd29d0fSMark Johnston 	vm_page_t m, marker;
721e8bcf696SMark Johnston 	int act_delta, error, numpagedout, queue, starting_target;
722ebcddc72SAlan Cox 	int vnodes_skipped;
72360256604SMark Johnston 	bool pageout_ok;
724ebcddc72SAlan Cox 
725e8bcf696SMark Johnston 	mtx = NULL;
7265cd29d0fSMark Johnston 	object = NULL;
727ebcddc72SAlan Cox 	starting_target = launder;
728ebcddc72SAlan Cox 	vnodes_skipped = 0;
729ebcddc72SAlan Cox 
730ebcddc72SAlan Cox 	/*
731b1fd102eSMark Johnston 	 * Scan the laundry queues for pages eligible to be laundered.  We stop
732ebcddc72SAlan Cox 	 * once the target number of dirty pages have been laundered, or once
733ebcddc72SAlan Cox 	 * we've reached the end of the queue.  A single iteration of this loop
734ebcddc72SAlan Cox 	 * may cause more than one page to be laundered because of clustering.
735ebcddc72SAlan Cox 	 *
736b1fd102eSMark Johnston 	 * As an optimization, we avoid laundering from PQ_UNSWAPPABLE when no
737b1fd102eSMark Johnston 	 * swap devices are configured.
738ebcddc72SAlan Cox 	 */
739b1fd102eSMark Johnston 	if (atomic_load_acq_int(&swapdev_enabled))
74064b38930SMark Johnston 		queue = PQ_UNSWAPPABLE;
741b1fd102eSMark Johnston 	else
74264b38930SMark Johnston 		queue = PQ_LAUNDRY;
743ebcddc72SAlan Cox 
744b1fd102eSMark Johnston scan:
74564b38930SMark Johnston 	marker = &vmd->vmd_markers[queue];
7465cd29d0fSMark Johnston 	pq = &vmd->vmd_pagequeues[queue];
747ebcddc72SAlan Cox 	vm_pagequeue_lock(pq);
7485cd29d0fSMark Johnston 	vm_pageout_init_scan(&ss, pq, marker, NULL, pq->pq_cnt);
7495cd29d0fSMark Johnston 	while (launder > 0 && (m = vm_pageout_next(&ss, false)) != NULL) {
7505cd29d0fSMark Johnston 		if (__predict_false((m->flags & PG_MARKER) != 0))
751ebcddc72SAlan Cox 			continue;
7525cd29d0fSMark Johnston 
753e8bcf696SMark Johnston 		vm_page_change_lock(m, &mtx);
754e8bcf696SMark Johnston 
755e8bcf696SMark Johnston recheck:
7565cd29d0fSMark Johnston 		/*
757e8bcf696SMark Johnston 		 * The page may have been disassociated from the queue
758e8bcf696SMark Johnston 		 * or even freed while locks were dropped.  We thus must be
759e8bcf696SMark Johnston 		 * careful whenever modifying page state.  Once the object lock
760e8bcf696SMark Johnston 		 * has been acquired, we have a stable reference to the page.
7615cd29d0fSMark Johnston 		 */
762e8bcf696SMark Johnston 		if (vm_page_queue(m) != queue)
763ebcddc72SAlan Cox 			continue;
764e8bcf696SMark Johnston 
765e8bcf696SMark Johnston 		/*
766e8bcf696SMark Johnston 		 * A requeue was requested, so this page gets a second
767e8bcf696SMark Johnston 		 * chance.
768e8bcf696SMark Johnston 		 */
769e8bcf696SMark Johnston 		if ((m->aflags & PGA_REQUEUE) != 0) {
7707cdeaf33SMark Johnston 			vm_page_pqbatch_submit(m, queue);
771ebcddc72SAlan Cox 			continue;
772ebcddc72SAlan Cox 		}
773ebcddc72SAlan Cox 
774e8bcf696SMark Johnston 		/*
775e8bcf696SMark Johnston 		 * Wired pages may not be freed.  Complete their removal
776e8bcf696SMark Johnston 		 * from the queue now to avoid needless revisits during
777e8bcf696SMark Johnston 		 * future scans.  This check is racy and must be reverified once
778e8bcf696SMark Johnston 		 * we hold the object lock and have verified that the page
779e8bcf696SMark Johnston 		 * is not busy.
780e8bcf696SMark Johnston 		 */
781e8bcf696SMark Johnston 		if (vm_page_wired(m)) {
782e8bcf696SMark Johnston 			vm_page_dequeue_deferred(m);
783e8bcf696SMark Johnston 			continue;
784e8bcf696SMark Johnston 		}
785e8bcf696SMark Johnston 
7865cd29d0fSMark Johnston 		if (object != m->object) {
78760256604SMark Johnston 			if (object != NULL)
7885cd29d0fSMark Johnston 				VM_OBJECT_WUNLOCK(object);
789e8bcf696SMark Johnston 
790e8bcf696SMark Johnston 			/*
791e8bcf696SMark Johnston 			 * A page's object pointer may be set to NULL before
792e8bcf696SMark Johnston 			 * the object lock is acquired.
793e8bcf696SMark Johnston 			 */
794fee2a2faSMark Johnston 			object = (vm_object_t)atomic_load_ptr(&m->object);
795e8bcf696SMark Johnston 			if (object != NULL && !VM_OBJECT_TRYWLOCK(object)) {
796e8bcf696SMark Johnston 				mtx_unlock(mtx);
797e8bcf696SMark Johnston 				/* Depends on type-stability. */
79841fd4b94SMark Johnston 				VM_OBJECT_WLOCK(object);
799e8bcf696SMark Johnston 				mtx_lock(mtx);
800e8bcf696SMark Johnston 				goto recheck;
801e8bcf696SMark Johnston 			}
802e8bcf696SMark Johnston 		}
803e8bcf696SMark Johnston 		if (__predict_false(m->object == NULL))
804e8bcf696SMark Johnston 			/*
805e8bcf696SMark Johnston 			 * The page has been removed from its object.
806e8bcf696SMark Johnston 			 */
80741fd4b94SMark Johnston 			continue;
808e8bcf696SMark Johnston 		KASSERT(m->object == object, ("page %p does not belong to %p",
809e8bcf696SMark Johnston 		    m, object));
8105cd29d0fSMark Johnston 
81163e97555SJeff Roberson 		if (vm_page_tryxbusy(m) == 0)
8125cd29d0fSMark Johnston 			continue;
813ebcddc72SAlan Cox 
814ebcddc72SAlan Cox 		/*
815e8bcf696SMark Johnston 		 * Re-check for wirings now that we hold the object lock and
816e8bcf696SMark Johnston 		 * have verified that the page is unbusied.  If the page is
817e8bcf696SMark Johnston 		 * mapped, it may still be wired by pmap lookups.  The call to
818fee2a2faSMark Johnston 		 * vm_page_try_remove_all() below atomically checks for such
819fee2a2faSMark Johnston 		 * wirings and removes mappings.  If the page is unmapped, the
820fee2a2faSMark Johnston 		 * wire count is guaranteed not to increase.
821fee2a2faSMark Johnston 		 */
822fee2a2faSMark Johnston 		if (__predict_false(vm_page_wired(m))) {
82363e97555SJeff Roberson 			vm_page_xunbusy(m);
824e8bcf696SMark Johnston 			vm_page_dequeue_deferred(m);
825fee2a2faSMark Johnston 			continue;
826fee2a2faSMark Johnston 		}
827fee2a2faSMark Johnston 
828fee2a2faSMark Johnston 		/*
829ebcddc72SAlan Cox 		 * Invalid pages can be easily freed.  They cannot be
830ebcddc72SAlan Cox 		 * mapped; vm_page_free() asserts this.
831ebcddc72SAlan Cox 		 */
8320012f373SJeff Roberson 		if (vm_page_none_valid(m))
833ebcddc72SAlan Cox 			goto free_page;
834ebcddc72SAlan Cox 
835ebcddc72SAlan Cox 		/*
836ebcddc72SAlan Cox 		 * If the page has been referenced and the object is not dead,
837ebcddc72SAlan Cox 		 * reactivate or requeue the page depending on whether the
838ebcddc72SAlan Cox 		 * object is mapped.
839d7aeb429SAlan Cox 		 *
840d7aeb429SAlan Cox 		 * Test PGA_REFERENCED after calling pmap_ts_referenced() so
841d7aeb429SAlan Cox 		 * that a reference from a concurrently destroyed mapping is
842d7aeb429SAlan Cox 		 * observed here and now.
843ebcddc72SAlan Cox 		 */
844e8bcf696SMark Johnston 		if (object->ref_count != 0)
845e8bcf696SMark Johnston 			act_delta = pmap_ts_referenced(m);
846e8bcf696SMark Johnston 		else {
847e8bcf696SMark Johnston 			KASSERT(!pmap_page_is_mapped(m),
848e8bcf696SMark Johnston 			    ("page %p is mapped", m));
849e8bcf696SMark Johnston 			act_delta = 0;
850d7aeb429SAlan Cox 		}
851e8bcf696SMark Johnston 		if ((m->aflags & PGA_REFERENCED) != 0) {
852e8bcf696SMark Johnston 			vm_page_aflag_clear(m, PGA_REFERENCED);
853d7aeb429SAlan Cox 			act_delta++;
854ebcddc72SAlan Cox 		}
855ebcddc72SAlan Cox 		if (act_delta != 0) {
856ebcddc72SAlan Cox 			if (object->ref_count != 0) {
85763e97555SJeff Roberson 				vm_page_xunbusy(m);
85841fd4b94SMark Johnston 				VM_CNT_INC(v_reactivated);
859e8bcf696SMark Johnston 				vm_page_activate(m);
860ebcddc72SAlan Cox 
861ebcddc72SAlan Cox 				/*
862e8bcf696SMark Johnston 				 * Increase the activation count if the page
863e8bcf696SMark Johnston 				 * was referenced while in the laundry queue.
864e8bcf696SMark Johnston 				 * This makes it less likely that the page will
865e8bcf696SMark Johnston 				 * be returned prematurely to the inactive
866e8bcf696SMark Johnston 				 * queue.
867e8bcf696SMark Johnston  				 */
868e8bcf696SMark Johnston 				m->act_count += act_delta + ACT_ADVANCE;
869e8bcf696SMark Johnston 
870e8bcf696SMark Johnston 				/*
871e8bcf696SMark Johnston 				 * If this was a background laundering, count
872e8bcf696SMark Johnston 				 * activated pages towards our target.  The
873e8bcf696SMark Johnston 				 * purpose of background laundering is to ensure
874e8bcf696SMark Johnston 				 * that pages are eventually cycled through the
875e8bcf696SMark Johnston 				 * laundry queue, and an activation is a valid
876e8bcf696SMark Johnston 				 * way out.
877ebcddc72SAlan Cox 				 */
878ebcddc72SAlan Cox 				if (!in_shortfall)
879ebcddc72SAlan Cox 					launder--;
880e8bcf696SMark Johnston 				continue;
8815cd29d0fSMark Johnston 			} else if ((object->flags & OBJ_DEAD) == 0) {
88263e97555SJeff Roberson 				vm_page_xunbusy(m);
883e8bcf696SMark Johnston 				vm_page_requeue(m);
884e8bcf696SMark Johnston 				continue;
8855cd29d0fSMark Johnston 			}
886ebcddc72SAlan Cox 		}
887ebcddc72SAlan Cox 
888ebcddc72SAlan Cox 		/*
889ebcddc72SAlan Cox 		 * If the page appears to be clean at the machine-independent
890ebcddc72SAlan Cox 		 * layer, then remove all of its mappings from the pmap in
891ebcddc72SAlan Cox 		 * anticipation of freeing it.  If, however, any of the page's
892ebcddc72SAlan Cox 		 * mappings allow write access, then the page may still be
893ebcddc72SAlan Cox 		 * modified until the last of those mappings are removed.
894ebcddc72SAlan Cox 		 */
895ebcddc72SAlan Cox 		if (object->ref_count != 0) {
896ebcddc72SAlan Cox 			vm_page_test_dirty(m);
897fee2a2faSMark Johnston 			if (m->dirty == 0 && !vm_page_try_remove_all(m)) {
89863e97555SJeff Roberson 				vm_page_xunbusy(m);
899e8bcf696SMark Johnston 				vm_page_dequeue_deferred(m);
900fee2a2faSMark Johnston 				continue;
901fee2a2faSMark Johnston 			}
902ebcddc72SAlan Cox 		}
903ebcddc72SAlan Cox 
904ebcddc72SAlan Cox 		/*
905ebcddc72SAlan Cox 		 * Clean pages are freed, and dirty pages are paged out unless
906ebcddc72SAlan Cox 		 * they belong to a dead object.  Requeueing dirty pages from
907ebcddc72SAlan Cox 		 * dead objects is pointless, as they are being paged out and
908ebcddc72SAlan Cox 		 * freed by the thread that destroyed the object.
909ebcddc72SAlan Cox 		 */
910ebcddc72SAlan Cox 		if (m->dirty == 0) {
911ebcddc72SAlan Cox free_page:
912ebcddc72SAlan Cox 			vm_page_free(m);
91383c9dea1SGleb Smirnoff 			VM_CNT_INC(v_dfree);
914ebcddc72SAlan Cox 		} else if ((object->flags & OBJ_DEAD) == 0) {
915ebcddc72SAlan Cox 			if (object->type != OBJT_SWAP &&
916ebcddc72SAlan Cox 			    object->type != OBJT_DEFAULT)
917ebcddc72SAlan Cox 				pageout_ok = true;
918ebcddc72SAlan Cox 			else if (disable_swap_pageouts)
919ebcddc72SAlan Cox 				pageout_ok = false;
920ebcddc72SAlan Cox 			else
921ebcddc72SAlan Cox 				pageout_ok = true;
922ebcddc72SAlan Cox 			if (!pageout_ok) {
92363e97555SJeff Roberson 				vm_page_xunbusy(m);
924e8bcf696SMark Johnston 				vm_page_requeue(m);
9255cd29d0fSMark Johnston 				continue;
926ebcddc72SAlan Cox 			}
927ebcddc72SAlan Cox 
928ebcddc72SAlan Cox 			/*
929ebcddc72SAlan Cox 			 * Form a cluster with adjacent, dirty pages from the
930ebcddc72SAlan Cox 			 * same object, and page out that entire cluster.
931ebcddc72SAlan Cox 			 *
932ebcddc72SAlan Cox 			 * The adjacent, dirty pages must also be in the
933ebcddc72SAlan Cox 			 * laundry.  However, their mappings are not checked
934ebcddc72SAlan Cox 			 * for new references.  Consequently, a recently
935ebcddc72SAlan Cox 			 * referenced page may be paged out.  However, that
936ebcddc72SAlan Cox 			 * page will not be prematurely reclaimed.  After page
937ebcddc72SAlan Cox 			 * out, the page will be placed in the inactive queue,
938ebcddc72SAlan Cox 			 * where any new references will be detected and the
939ebcddc72SAlan Cox 			 * page reactivated.
940ebcddc72SAlan Cox 			 */
941ebcddc72SAlan Cox 			error = vm_pageout_clean(m, &numpagedout);
942ebcddc72SAlan Cox 			if (error == 0) {
943ebcddc72SAlan Cox 				launder -= numpagedout;
9445cd29d0fSMark Johnston 				ss.scanned += numpagedout;
945ebcddc72SAlan Cox 			} else if (error == EDEADLK) {
946ebcddc72SAlan Cox 				pageout_lock_miss++;
947ebcddc72SAlan Cox 				vnodes_skipped++;
948ebcddc72SAlan Cox 			}
949e8bcf696SMark Johnston 			mtx = NULL;
95060256604SMark Johnston 			object = NULL;
95163e97555SJeff Roberson 		} else
95263e97555SJeff Roberson 			vm_page_xunbusy(m);
953e8bcf696SMark Johnston 	}
954e8bcf696SMark Johnston 	if (mtx != NULL) {
955e8bcf696SMark Johnston 		mtx_unlock(mtx);
956e8bcf696SMark Johnston 		mtx = NULL;
95746e39081SMark Johnston 	}
95846e39081SMark Johnston 	if (object != NULL) {
959ebcddc72SAlan Cox 		VM_OBJECT_WUNLOCK(object);
96046e39081SMark Johnston 		object = NULL;
96146e39081SMark Johnston 	}
962ebcddc72SAlan Cox 	vm_pagequeue_lock(pq);
9635cd29d0fSMark Johnston 	vm_pageout_end_scan(&ss);
964ebcddc72SAlan Cox 	vm_pagequeue_unlock(pq);
965ebcddc72SAlan Cox 
96664b38930SMark Johnston 	if (launder > 0 && queue == PQ_UNSWAPPABLE) {
96764b38930SMark Johnston 		queue = PQ_LAUNDRY;
968b1fd102eSMark Johnston 		goto scan;
969b1fd102eSMark Johnston 	}
970b1fd102eSMark Johnston 
971ebcddc72SAlan Cox 	/*
972ebcddc72SAlan Cox 	 * Wakeup the sync daemon if we skipped a vnode in a writeable object
973ebcddc72SAlan Cox 	 * and we didn't launder enough pages.
974ebcddc72SAlan Cox 	 */
975ebcddc72SAlan Cox 	if (vnodes_skipped > 0 && launder > 0)
976ebcddc72SAlan Cox 		(void)speedup_syncer();
977ebcddc72SAlan Cox 
978ebcddc72SAlan Cox 	return (starting_target - launder);
979ebcddc72SAlan Cox }
980ebcddc72SAlan Cox 
981ebcddc72SAlan Cox /*
982ebcddc72SAlan Cox  * Compute the integer square root.
983ebcddc72SAlan Cox  */
984ebcddc72SAlan Cox static u_int
985ebcddc72SAlan Cox isqrt(u_int num)
986ebcddc72SAlan Cox {
987ebcddc72SAlan Cox 	u_int bit, root, tmp;
988ebcddc72SAlan Cox 
98964f8d257SDoug Moore 	bit = num != 0 ? (1u << ((fls(num) - 1) & ~1)) : 0;
990ebcddc72SAlan Cox 	root = 0;
991ebcddc72SAlan Cox 	while (bit != 0) {
992ebcddc72SAlan Cox 		tmp = root + bit;
993ebcddc72SAlan Cox 		root >>= 1;
994ebcddc72SAlan Cox 		if (num >= tmp) {
995ebcddc72SAlan Cox 			num -= tmp;
996ebcddc72SAlan Cox 			root += bit;
997ebcddc72SAlan Cox 		}
998ebcddc72SAlan Cox 		bit >>= 2;
999ebcddc72SAlan Cox 	}
1000ebcddc72SAlan Cox 	return (root);
1001ebcddc72SAlan Cox }
1002ebcddc72SAlan Cox 
1003ebcddc72SAlan Cox /*
1004ebcddc72SAlan Cox  * Perform the work of the laundry thread: periodically wake up and determine
1005ebcddc72SAlan Cox  * whether any pages need to be laundered.  If so, determine the number of pages
1006ebcddc72SAlan Cox  * that need to be laundered, and launder them.
1007ebcddc72SAlan Cox  */
1008ebcddc72SAlan Cox static void
1009ebcddc72SAlan Cox vm_pageout_laundry_worker(void *arg)
1010ebcddc72SAlan Cox {
1011e2068d0bSJeff Roberson 	struct vm_domain *vmd;
1012ebcddc72SAlan Cox 	struct vm_pagequeue *pq;
101360684862SMark Johnston 	uint64_t nclean, ndirty, nfreed;
1014e2068d0bSJeff Roberson 	int domain, last_target, launder, shortfall, shortfall_cycle, target;
1015ebcddc72SAlan Cox 	bool in_shortfall;
1016ebcddc72SAlan Cox 
1017e2068d0bSJeff Roberson 	domain = (uintptr_t)arg;
1018e2068d0bSJeff Roberson 	vmd = VM_DOMAIN(domain);
1019e2068d0bSJeff Roberson 	pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
1020e2068d0bSJeff Roberson 	KASSERT(vmd->vmd_segs != 0, ("domain without segments"));
1021ebcddc72SAlan Cox 
1022ebcddc72SAlan Cox 	shortfall = 0;
1023ebcddc72SAlan Cox 	in_shortfall = false;
1024ebcddc72SAlan Cox 	shortfall_cycle = 0;
10258002c3a4SMark Johnston 	last_target = target = 0;
102660684862SMark Johnston 	nfreed = 0;
1027ebcddc72SAlan Cox 
1028ebcddc72SAlan Cox 	/*
1029b1fd102eSMark Johnston 	 * Calls to these handlers are serialized by the swap syscall lock.
1030b1fd102eSMark Johnston 	 */
1031e2068d0bSJeff Roberson 	(void)EVENTHANDLER_REGISTER(swapon, vm_pageout_swapon, vmd,
1032b1fd102eSMark Johnston 	    EVENTHANDLER_PRI_ANY);
1033e2068d0bSJeff Roberson 	(void)EVENTHANDLER_REGISTER(swapoff, vm_pageout_swapoff, vmd,
1034b1fd102eSMark Johnston 	    EVENTHANDLER_PRI_ANY);
1035b1fd102eSMark Johnston 
1036b1fd102eSMark Johnston 	/*
1037ebcddc72SAlan Cox 	 * The pageout laundry worker is never done, so loop forever.
1038ebcddc72SAlan Cox 	 */
1039ebcddc72SAlan Cox 	for (;;) {
1040ebcddc72SAlan Cox 		KASSERT(target >= 0, ("negative target %d", target));
1041ebcddc72SAlan Cox 		KASSERT(shortfall_cycle >= 0,
1042ebcddc72SAlan Cox 		    ("negative cycle %d", shortfall_cycle));
1043ebcddc72SAlan Cox 		launder = 0;
1044ebcddc72SAlan Cox 
1045ebcddc72SAlan Cox 		/*
1046ebcddc72SAlan Cox 		 * First determine whether we need to launder pages to meet a
1047ebcddc72SAlan Cox 		 * shortage of free pages.
1048ebcddc72SAlan Cox 		 */
1049ebcddc72SAlan Cox 		if (shortfall > 0) {
1050ebcddc72SAlan Cox 			in_shortfall = true;
1051ebcddc72SAlan Cox 			shortfall_cycle = VM_LAUNDER_RATE / VM_INACT_SCAN_RATE;
1052ebcddc72SAlan Cox 			target = shortfall;
1053ebcddc72SAlan Cox 		} else if (!in_shortfall)
1054ebcddc72SAlan Cox 			goto trybackground;
1055e2068d0bSJeff Roberson 		else if (shortfall_cycle == 0 || vm_laundry_target(vmd) <= 0) {
1056ebcddc72SAlan Cox 			/*
1057ebcddc72SAlan Cox 			 * We recently entered shortfall and began laundering
1058ebcddc72SAlan Cox 			 * pages.  If we have completed that laundering run
1059ebcddc72SAlan Cox 			 * (and we are no longer in shortfall) or we have met
1060ebcddc72SAlan Cox 			 * our laundry target through other activity, then we
1061ebcddc72SAlan Cox 			 * can stop laundering pages.
1062ebcddc72SAlan Cox 			 */
1063ebcddc72SAlan Cox 			in_shortfall = false;
1064ebcddc72SAlan Cox 			target = 0;
1065ebcddc72SAlan Cox 			goto trybackground;
1066ebcddc72SAlan Cox 		}
1067ebcddc72SAlan Cox 		launder = target / shortfall_cycle--;
1068ebcddc72SAlan Cox 		goto dolaundry;
1069ebcddc72SAlan Cox 
1070ebcddc72SAlan Cox 		/*
1071ebcddc72SAlan Cox 		 * There's no immediate need to launder any pages; see if we
1072ebcddc72SAlan Cox 		 * meet the conditions to perform background laundering:
1073ebcddc72SAlan Cox 		 *
1074ebcddc72SAlan Cox 		 * 1. The ratio of dirty to clean inactive pages exceeds the
107560684862SMark Johnston 		 *    background laundering threshold, or
1076ebcddc72SAlan Cox 		 * 2. we haven't yet reached the target of the current
1077ebcddc72SAlan Cox 		 *    background laundering run.
1078ebcddc72SAlan Cox 		 *
1079ebcddc72SAlan Cox 		 * The background laundering threshold is not a constant.
1080ebcddc72SAlan Cox 		 * Instead, it is a slowly growing function of the number of
108160684862SMark Johnston 		 * clean pages freed by the page daemon since the last
108260684862SMark Johnston 		 * background laundering.  Thus, as the ratio of dirty to
108360684862SMark Johnston 		 * clean inactive pages grows, the amount of memory pressure
1084c098768eSMark Johnston 		 * required to trigger laundering decreases.  We ensure
1085c098768eSMark Johnston 		 * that the threshold is non-zero after an inactive queue
1086c098768eSMark Johnston 		 * scan, even if that scan failed to free a single clean page.
1087ebcddc72SAlan Cox 		 */
1088ebcddc72SAlan Cox trybackground:
1089e2068d0bSJeff Roberson 		nclean = vmd->vmd_free_count +
1090e2068d0bSJeff Roberson 		    vmd->vmd_pagequeues[PQ_INACTIVE].pq_cnt;
1091e2068d0bSJeff Roberson 		ndirty = vmd->vmd_pagequeues[PQ_LAUNDRY].pq_cnt;
1092c098768eSMark Johnston 		if (target == 0 && ndirty * isqrt(howmany(nfreed + 1,
1093c098768eSMark Johnston 		    vmd->vmd_free_target - vmd->vmd_free_min)) >= nclean) {
1094e2068d0bSJeff Roberson 			target = vmd->vmd_background_launder_target;
1095ebcddc72SAlan Cox 		}
1096ebcddc72SAlan Cox 
1097ebcddc72SAlan Cox 		/*
1098ebcddc72SAlan Cox 		 * We have a non-zero background laundering target.  If we've
1099ebcddc72SAlan Cox 		 * laundered up to our maximum without observing a page daemon
1100cb35676eSMark Johnston 		 * request, just stop.  This is a safety belt that ensures we
1101ebcddc72SAlan Cox 		 * don't launder an excessive amount if memory pressure is low
1102ebcddc72SAlan Cox 		 * and the ratio of dirty to clean pages is large.  Otherwise,
1103ebcddc72SAlan Cox 		 * proceed at the background laundering rate.
1104ebcddc72SAlan Cox 		 */
1105ebcddc72SAlan Cox 		if (target > 0) {
110660684862SMark Johnston 			if (nfreed > 0) {
110760684862SMark Johnston 				nfreed = 0;
1108ebcddc72SAlan Cox 				last_target = target;
1109ebcddc72SAlan Cox 			} else if (last_target - target >=
1110ebcddc72SAlan Cox 			    vm_background_launder_max * PAGE_SIZE / 1024) {
1111ebcddc72SAlan Cox 				target = 0;
1112ebcddc72SAlan Cox 			}
1113ebcddc72SAlan Cox 			launder = vm_background_launder_rate * PAGE_SIZE / 1024;
1114ebcddc72SAlan Cox 			launder /= VM_LAUNDER_RATE;
1115ebcddc72SAlan Cox 			if (launder > target)
1116ebcddc72SAlan Cox 				launder = target;
1117ebcddc72SAlan Cox 		}
1118ebcddc72SAlan Cox 
1119ebcddc72SAlan Cox dolaundry:
1120ebcddc72SAlan Cox 		if (launder > 0) {
1121ebcddc72SAlan Cox 			/*
1122ebcddc72SAlan Cox 			 * Because of I/O clustering, the number of laundered
1123ebcddc72SAlan Cox 			 * pages could exceed "target" by the maximum size of
1124ebcddc72SAlan Cox 			 * a cluster minus one.
1125ebcddc72SAlan Cox 			 */
1126e2068d0bSJeff Roberson 			target -= min(vm_pageout_launder(vmd, launder,
1127ebcddc72SAlan Cox 			    in_shortfall), target);
1128ebcddc72SAlan Cox 			pause("laundp", hz / VM_LAUNDER_RATE);
1129ebcddc72SAlan Cox 		}
1130ebcddc72SAlan Cox 
1131ebcddc72SAlan Cox 		/*
1132ebcddc72SAlan Cox 		 * If we're not currently laundering pages and the page daemon
1133ebcddc72SAlan Cox 		 * hasn't posted a new request, sleep until the page daemon
1134ebcddc72SAlan Cox 		 * kicks us.
1135ebcddc72SAlan Cox 		 */
1136ebcddc72SAlan Cox 		vm_pagequeue_lock(pq);
1137e2068d0bSJeff Roberson 		if (target == 0 && vmd->vmd_laundry_request == VM_LAUNDRY_IDLE)
1138e2068d0bSJeff Roberson 			(void)mtx_sleep(&vmd->vmd_laundry_request,
1139ebcddc72SAlan Cox 			    vm_pagequeue_lockptr(pq), PVM, "launds", 0);
1140ebcddc72SAlan Cox 
1141ebcddc72SAlan Cox 		/*
1142ebcddc72SAlan Cox 		 * If the pagedaemon has indicated that it's in shortfall, start
1143ebcddc72SAlan Cox 		 * a shortfall laundering unless we're already in the middle of
1144ebcddc72SAlan Cox 		 * one.  This may preempt a background laundering.
1145ebcddc72SAlan Cox 		 */
1146e2068d0bSJeff Roberson 		if (vmd->vmd_laundry_request == VM_LAUNDRY_SHORTFALL &&
1147ebcddc72SAlan Cox 		    (!in_shortfall || shortfall_cycle == 0)) {
1148e2068d0bSJeff Roberson 			shortfall = vm_laundry_target(vmd) +
1149e2068d0bSJeff Roberson 			    vmd->vmd_pageout_deficit;
1150ebcddc72SAlan Cox 			target = 0;
1151ebcddc72SAlan Cox 		} else
1152ebcddc72SAlan Cox 			shortfall = 0;
1153ebcddc72SAlan Cox 
1154ebcddc72SAlan Cox 		if (target == 0)
1155e2068d0bSJeff Roberson 			vmd->vmd_laundry_request = VM_LAUNDRY_IDLE;
115660684862SMark Johnston 		nfreed += vmd->vmd_clean_pages_freed;
115760684862SMark Johnston 		vmd->vmd_clean_pages_freed = 0;
1158ebcddc72SAlan Cox 		vm_pagequeue_unlock(pq);
1159ebcddc72SAlan Cox 	}
1160ebcddc72SAlan Cox }
1161ebcddc72SAlan Cox 
1162be37ee79SMark Johnston /*
1163be37ee79SMark Johnston  * Compute the number of pages we want to try to move from the
1164be37ee79SMark Johnston  * active queue to either the inactive or laundry queue.
1165be37ee79SMark Johnston  *
11667bb4634eSMark Johnston  * When scanning active pages during a shortage, we make clean pages
11677bb4634eSMark Johnston  * count more heavily towards the page shortage than dirty pages.
11687bb4634eSMark Johnston  * This is because dirty pages must be laundered before they can be
11697bb4634eSMark Johnston  * reused and thus have less utility when attempting to quickly
11707bb4634eSMark Johnston  * alleviate a free page shortage.  However, this weighting also
11717bb4634eSMark Johnston  * causes the scan to deactivate dirty pages more aggressively,
11727bb4634eSMark Johnston  * improving the effectiveness of clustering.
1173be37ee79SMark Johnston  */
1174be37ee79SMark Johnston static int
11757bb4634eSMark Johnston vm_pageout_active_target(struct vm_domain *vmd)
1176be37ee79SMark Johnston {
1177be37ee79SMark Johnston 	int shortage;
1178be37ee79SMark Johnston 
1179be37ee79SMark Johnston 	shortage = vmd->vmd_inactive_target + vm_paging_target(vmd) -
1180be37ee79SMark Johnston 	    (vmd->vmd_pagequeues[PQ_INACTIVE].pq_cnt +
1181be37ee79SMark Johnston 	    vmd->vmd_pagequeues[PQ_LAUNDRY].pq_cnt / act_scan_laundry_weight);
1182be37ee79SMark Johnston 	shortage *= act_scan_laundry_weight;
1183be37ee79SMark Johnston 	return (shortage);
1184be37ee79SMark Johnston }
1185be37ee79SMark Johnston 
1186be37ee79SMark Johnston /*
1187be37ee79SMark Johnston  * Scan the active queue.  If there is no shortage of inactive pages, scan a
1188be37ee79SMark Johnston  * small portion of the queue in order to maintain quasi-LRU.
1189be37ee79SMark Johnston  */
1190be37ee79SMark Johnston static void
1191be37ee79SMark Johnston vm_pageout_scan_active(struct vm_domain *vmd, int page_shortage)
1192be37ee79SMark Johnston {
1193be37ee79SMark Johnston 	struct scan_state ss;
1194e8bcf696SMark Johnston 	struct mtx *mtx;
1195fee2a2faSMark Johnston 	vm_object_t object;
1196be37ee79SMark Johnston 	vm_page_t m, marker;
1197be37ee79SMark Johnston 	struct vm_pagequeue *pq;
1198be37ee79SMark Johnston 	long min_scan;
1199e8bcf696SMark Johnston 	int act_delta, max_scan, scan_tick;
1200be37ee79SMark Johnston 
1201be37ee79SMark Johnston 	marker = &vmd->vmd_markers[PQ_ACTIVE];
1202be37ee79SMark Johnston 	pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1203be37ee79SMark Johnston 	vm_pagequeue_lock(pq);
1204be37ee79SMark Johnston 
1205be37ee79SMark Johnston 	/*
1206be37ee79SMark Johnston 	 * If we're just idle polling attempt to visit every
1207be37ee79SMark Johnston 	 * active page within 'update_period' seconds.
1208be37ee79SMark Johnston 	 */
1209be37ee79SMark Johnston 	scan_tick = ticks;
1210be37ee79SMark Johnston 	if (vm_pageout_update_period != 0) {
1211be37ee79SMark Johnston 		min_scan = pq->pq_cnt;
1212be37ee79SMark Johnston 		min_scan *= scan_tick - vmd->vmd_last_active_scan;
1213be37ee79SMark Johnston 		min_scan /= hz * vm_pageout_update_period;
1214be37ee79SMark Johnston 	} else
1215be37ee79SMark Johnston 		min_scan = 0;
1216be37ee79SMark Johnston 	if (min_scan > 0 || (page_shortage > 0 && pq->pq_cnt > 0))
1217be37ee79SMark Johnston 		vmd->vmd_last_active_scan = scan_tick;
1218be37ee79SMark Johnston 
1219be37ee79SMark Johnston 	/*
1220be37ee79SMark Johnston 	 * Scan the active queue for pages that can be deactivated.  Update
1221be37ee79SMark Johnston 	 * the per-page activity counter and use it to identify deactivation
1222be37ee79SMark Johnston 	 * candidates.  Held pages may be deactivated.
1223be37ee79SMark Johnston 	 *
1224be37ee79SMark Johnston 	 * To avoid requeuing each page that remains in the active queue, we
12257bb4634eSMark Johnston 	 * implement the CLOCK algorithm.  To keep the implementation of the
12267bb4634eSMark Johnston 	 * enqueue operation consistent for all page queues, we use two hands,
12277bb4634eSMark Johnston 	 * represented by marker pages. Scans begin at the first hand, which
12287bb4634eSMark Johnston 	 * precedes the second hand in the queue.  When the two hands meet,
12297bb4634eSMark Johnston 	 * they are moved back to the head and tail of the queue, respectively,
12307bb4634eSMark Johnston 	 * and scanning resumes.
1231be37ee79SMark Johnston 	 */
1232be37ee79SMark Johnston 	max_scan = page_shortage > 0 ? pq->pq_cnt : min_scan;
1233e8bcf696SMark Johnston 	mtx = NULL;
1234be37ee79SMark Johnston act_scan:
1235be37ee79SMark Johnston 	vm_pageout_init_scan(&ss, pq, marker, &vmd->vmd_clock[0], max_scan);
1236be37ee79SMark Johnston 	while ((m = vm_pageout_next(&ss, false)) != NULL) {
1237be37ee79SMark Johnston 		if (__predict_false(m == &vmd->vmd_clock[1])) {
1238be37ee79SMark Johnston 			vm_pagequeue_lock(pq);
1239be37ee79SMark Johnston 			TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_clock[0], plinks.q);
1240be37ee79SMark Johnston 			TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_clock[1], plinks.q);
1241be37ee79SMark Johnston 			TAILQ_INSERT_HEAD(&pq->pq_pl, &vmd->vmd_clock[0],
1242be37ee79SMark Johnston 			    plinks.q);
1243be37ee79SMark Johnston 			TAILQ_INSERT_TAIL(&pq->pq_pl, &vmd->vmd_clock[1],
1244be37ee79SMark Johnston 			    plinks.q);
1245be37ee79SMark Johnston 			max_scan -= ss.scanned;
1246be37ee79SMark Johnston 			vm_pageout_end_scan(&ss);
1247be37ee79SMark Johnston 			goto act_scan;
1248be37ee79SMark Johnston 		}
1249be37ee79SMark Johnston 		if (__predict_false((m->flags & PG_MARKER) != 0))
1250be37ee79SMark Johnston 			continue;
1251be37ee79SMark Johnston 
1252e8bcf696SMark Johnston 		vm_page_change_lock(m, &mtx);
1253e8bcf696SMark Johnston 
1254e8bcf696SMark Johnston 		/*
1255e8bcf696SMark Johnston 		 * The page may have been disassociated from the queue
1256e8bcf696SMark Johnston 		 * or even freed while locks were dropped.  We thus must be
1257e8bcf696SMark Johnston 		 * careful whenever modifying page state.  Once the object lock
1258e8bcf696SMark Johnston 		 * has been acquired, we have a stable reference to the page.
1259e8bcf696SMark Johnston 		 */
1260e8bcf696SMark Johnston 		if (vm_page_queue(m) != PQ_ACTIVE)
1261e8bcf696SMark Johnston 			continue;
1262e8bcf696SMark Johnston 
1263e8bcf696SMark Johnston 		/*
1264e8bcf696SMark Johnston 		 * Wired pages are dequeued lazily.
1265e8bcf696SMark Johnston 		 */
1266e8bcf696SMark Johnston 		if (vm_page_wired(m)) {
1267e8bcf696SMark Johnston 			vm_page_dequeue_deferred(m);
1268e8bcf696SMark Johnston 			continue;
1269e8bcf696SMark Johnston 		}
1270e8bcf696SMark Johnston 
1271e8bcf696SMark Johnston 		/*
1272e8bcf696SMark Johnston 		 * A page's object pointer may be set to NULL before
1273e8bcf696SMark Johnston 		 * the object lock is acquired.
1274e8bcf696SMark Johnston 		 */
1275fee2a2faSMark Johnston 		object = (vm_object_t)atomic_load_ptr(&m->object);
1276fee2a2faSMark Johnston 		if (__predict_false(object == NULL))
1277fee2a2faSMark Johnston 			/*
1278fee2a2faSMark Johnston 			 * The page has been removed from its object.
1279fee2a2faSMark Johnston 			 */
1280fee2a2faSMark Johnston 			continue;
1281fee2a2faSMark Johnston 
1282fee2a2faSMark Johnston 		/*
1283be37ee79SMark Johnston 		 * Check to see "how much" the page has been used.
1284d7aeb429SAlan Cox 		 *
1285d7aeb429SAlan Cox 		 * Test PGA_REFERENCED after calling pmap_ts_referenced() so
1286d7aeb429SAlan Cox 		 * that a reference from a concurrently destroyed mapping is
1287d7aeb429SAlan Cox 		 * observed here and now.
1288d7aeb429SAlan Cox 		 *
1289e8bcf696SMark Johnston 		 * Perform an unsynchronized object ref count check.  While
1290e8bcf696SMark Johnston 		 * the page lock ensures that the page is not reallocated to
1291e8bcf696SMark Johnston 		 * another object, in particular, one with unmanaged mappings
1292e8bcf696SMark Johnston 		 * that cannot support pmap_ts_referenced(), two races are,
1293be37ee79SMark Johnston 		 * nonetheless, possible:
1294be37ee79SMark Johnston 		 * 1) The count was transitioning to zero, but we saw a non-
1295e8bcf696SMark Johnston 		 *    zero value.  pmap_ts_referenced() will return zero
1296e8bcf696SMark Johnston 		 *    because the page is not mapped.
1297e8bcf696SMark Johnston 		 * 2) The count was transitioning to one, but we saw zero.
1298e8bcf696SMark Johnston 		 *    This race delays the detection of a new reference.  At
1299e8bcf696SMark Johnston 		 *    worst, we will deactivate and reactivate the page.
1300be37ee79SMark Johnston 		 */
1301e8bcf696SMark Johnston 		if (object->ref_count != 0)
1302e8bcf696SMark Johnston 			act_delta = pmap_ts_referenced(m);
1303e8bcf696SMark Johnston 		else
1304e8bcf696SMark Johnston 			act_delta = 0;
1305e8bcf696SMark Johnston 		if ((m->aflags & PGA_REFERENCED) != 0) {
1306e8bcf696SMark Johnston 			vm_page_aflag_clear(m, PGA_REFERENCED);
1307d7aeb429SAlan Cox 			act_delta++;
1308d7aeb429SAlan Cox 		}
1309be37ee79SMark Johnston 
1310be37ee79SMark Johnston 		/*
1311be37ee79SMark Johnston 		 * Advance or decay the act_count based on recent usage.
1312be37ee79SMark Johnston 		 */
1313be37ee79SMark Johnston 		if (act_delta != 0) {
1314e8bcf696SMark Johnston 			m->act_count += ACT_ADVANCE + act_delta;
1315e8bcf696SMark Johnston 			if (m->act_count > ACT_MAX)
1316e8bcf696SMark Johnston 				m->act_count = ACT_MAX;
1317e8bcf696SMark Johnston 		} else
1318e8bcf696SMark Johnston 			m->act_count -= min(m->act_count, ACT_DECLINE);
1319be37ee79SMark Johnston 
1320e8bcf696SMark Johnston 		if (m->act_count == 0) {
1321be37ee79SMark Johnston 			/*
1322e8bcf696SMark Johnston 			 * When not short for inactive pages, let dirty pages go
1323e8bcf696SMark Johnston 			 * through the inactive queue before moving to the
1324e8bcf696SMark Johnston 			 * laundry queues.  This gives them some extra time to
1325e8bcf696SMark Johnston 			 * be reactivated, potentially avoiding an expensive
1326e8bcf696SMark Johnston 			 * pageout.  However, during a page shortage, the
1327e8bcf696SMark Johnston 			 * inactive queue is necessarily small, and so dirty
1328e8bcf696SMark Johnston 			 * pages would only spend a trivial amount of time in
1329e8bcf696SMark Johnston 			 * the inactive queue.  Therefore, we might as well
1330e8bcf696SMark Johnston 			 * place them directly in the laundry queue to reduce
1331e8bcf696SMark Johnston 			 * queuing overhead.
1332be37ee79SMark Johnston 			 */
1333e8bcf696SMark Johnston 			if (page_shortage <= 0) {
1334e8bcf696SMark Johnston 				vm_page_swapqueue(m, PQ_ACTIVE, PQ_INACTIVE);
13357cdeaf33SMark Johnston 			} else {
1336be37ee79SMark Johnston 				/*
1337be37ee79SMark Johnston 				 * Calling vm_page_test_dirty() here would
1338be37ee79SMark Johnston 				 * require acquisition of the object's write
1339be37ee79SMark Johnston 				 * lock.  However, during a page shortage,
1340e8bcf696SMark Johnston 				 * directing dirty pages into the laundry
1341e8bcf696SMark Johnston 				 * queue is only an optimization and not a
1342be37ee79SMark Johnston 				 * requirement.  Therefore, we simply rely on
1343e8bcf696SMark Johnston 				 * the opportunistic updates to the page's
1344e8bcf696SMark Johnston 				 * dirty field by the pmap.
1345be37ee79SMark Johnston 				 */
1346e8bcf696SMark Johnston 				if (m->dirty == 0) {
1347e8bcf696SMark Johnston 					vm_page_swapqueue(m, PQ_ACTIVE,
1348e8bcf696SMark Johnston 					    PQ_INACTIVE);
1349e8bcf696SMark Johnston 					page_shortage -=
1350e8bcf696SMark Johnston 					    act_scan_laundry_weight;
1351be37ee79SMark Johnston 				} else {
1352e8bcf696SMark Johnston 					vm_page_swapqueue(m, PQ_ACTIVE,
1353e8bcf696SMark Johnston 					    PQ_LAUNDRY);
1354e8bcf696SMark Johnston 					page_shortage--;
1355be37ee79SMark Johnston 				}
1356be37ee79SMark Johnston 			}
1357be37ee79SMark Johnston 		}
1358be37ee79SMark Johnston 	}
1359e8bcf696SMark Johnston 	if (mtx != NULL) {
1360e8bcf696SMark Johnston 		mtx_unlock(mtx);
1361e8bcf696SMark Johnston 		mtx = NULL;
1362e8bcf696SMark Johnston 	}
1363be37ee79SMark Johnston 	vm_pagequeue_lock(pq);
1364be37ee79SMark Johnston 	TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_clock[0], plinks.q);
1365be37ee79SMark Johnston 	TAILQ_INSERT_AFTER(&pq->pq_pl, marker, &vmd->vmd_clock[0], plinks.q);
1366be37ee79SMark Johnston 	vm_pageout_end_scan(&ss);
1367be37ee79SMark Johnston 	vm_pagequeue_unlock(pq);
1368be37ee79SMark Johnston }
1369be37ee79SMark Johnston 
13705cd29d0fSMark Johnston static int
13715cd29d0fSMark Johnston vm_pageout_reinsert_inactive_page(struct scan_state *ss, vm_page_t m)
13725cd29d0fSMark Johnston {
13735cd29d0fSMark Johnston 	struct vm_domain *vmd;
13745cd29d0fSMark Johnston 
1375e8bcf696SMark Johnston 	if (m->queue != PQ_INACTIVE || (m->aflags & PGA_ENQUEUED) != 0)
1376e8bcf696SMark Johnston 		return (0);
1377e8bcf696SMark Johnston 	vm_page_aflag_set(m, PGA_ENQUEUED);
1378e8bcf696SMark Johnston 	if ((m->aflags & PGA_REQUEUE_HEAD) != 0) {
13795cd29d0fSMark Johnston 		vmd = vm_pagequeue_domain(m);
13805cd29d0fSMark Johnston 		TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
1381e8bcf696SMark Johnston 		vm_page_aflag_clear(m, PGA_REQUEUE | PGA_REQUEUE_HEAD);
1382e8bcf696SMark Johnston 	} else if ((m->aflags & PGA_REQUEUE) != 0) {
13835cd29d0fSMark Johnston 		TAILQ_INSERT_TAIL(&ss->pq->pq_pl, m, plinks.q);
1384e8bcf696SMark Johnston 		vm_page_aflag_clear(m, PGA_REQUEUE | PGA_REQUEUE_HEAD);
1385e8bcf696SMark Johnston 	} else
13865cd29d0fSMark Johnston 		TAILQ_INSERT_BEFORE(ss->marker, m, plinks.q);
13875cd29d0fSMark Johnston 	return (1);
13885cd29d0fSMark Johnston }
13895cd29d0fSMark Johnston 
13905cd29d0fSMark Johnston /*
13915cd29d0fSMark Johnston  * Re-add stuck pages to the inactive queue.  We will examine them again
13925cd29d0fSMark Johnston  * during the next scan.  If the queue state of a page has changed since
13935cd29d0fSMark Johnston  * it was physically removed from the page queue in
13945cd29d0fSMark Johnston  * vm_pageout_collect_batch(), don't do anything with that page.
13955cd29d0fSMark Johnston  */
13965cd29d0fSMark Johnston static void
13975cd29d0fSMark Johnston vm_pageout_reinsert_inactive(struct scan_state *ss, struct vm_batchqueue *bq,
13985cd29d0fSMark Johnston     vm_page_t m)
13995cd29d0fSMark Johnston {
14005cd29d0fSMark Johnston 	struct vm_pagequeue *pq;
14015cd29d0fSMark Johnston 	int delta;
14025cd29d0fSMark Johnston 
14035cd29d0fSMark Johnston 	delta = 0;
14045cd29d0fSMark Johnston 	pq = ss->pq;
14055cd29d0fSMark Johnston 
14065cd29d0fSMark Johnston 	if (m != NULL) {
14075cd29d0fSMark Johnston 		if (vm_batchqueue_insert(bq, m))
14085cd29d0fSMark Johnston 			return;
14095cd29d0fSMark Johnston 		vm_pagequeue_lock(pq);
14105cd29d0fSMark Johnston 		delta += vm_pageout_reinsert_inactive_page(ss, m);
14115cd29d0fSMark Johnston 	} else
14125cd29d0fSMark Johnston 		vm_pagequeue_lock(pq);
14135cd29d0fSMark Johnston 	while ((m = vm_batchqueue_pop(bq)) != NULL)
14145cd29d0fSMark Johnston 		delta += vm_pageout_reinsert_inactive_page(ss, m);
14155cd29d0fSMark Johnston 	vm_pagequeue_cnt_add(pq, delta);
14165cd29d0fSMark Johnston 	vm_pagequeue_unlock(pq);
14175cd29d0fSMark Johnston 	vm_batchqueue_init(bq);
14185cd29d0fSMark Johnston }
14195cd29d0fSMark Johnston 
1420ebcddc72SAlan Cox /*
142127e29d10SMark Johnston  * Attempt to reclaim the requested number of pages from the inactive queue.
142227e29d10SMark Johnston  * Returns true if the shortage was addressed.
1423df8bae1dSRodney W. Grimes  */
1424be37ee79SMark Johnston static int
142549a3710cSMark Johnston vm_pageout_scan_inactive(struct vm_domain *vmd, int shortage,
1426be37ee79SMark Johnston     int *addl_shortage)
1427df8bae1dSRodney W. Grimes {
14285cd29d0fSMark Johnston 	struct scan_state ss;
14295cd29d0fSMark Johnston 	struct vm_batchqueue rq;
1430e8bcf696SMark Johnston 	struct mtx *mtx;
14315cd29d0fSMark Johnston 	vm_page_t m, marker;
14328d220203SAlan Cox 	struct vm_pagequeue *pq;
1433df8bae1dSRodney W. Grimes 	vm_object_t object;
1434e8bcf696SMark Johnston 	int act_delta, addl_page_shortage, deficit, page_shortage;
1435be37ee79SMark Johnston 	int starting_page_shortage;
14360d94caffSDavid Greenman 
1437df8bae1dSRodney W. Grimes 	/*
143801f04471SMark Johnston 	 * The addl_page_shortage is an estimate of the number of temporarily
1439311e34e2SKonstantin Belousov 	 * stuck pages in the inactive queue.  In other words, the
1440449c2e92SKonstantin Belousov 	 * number of pages from the inactive count that should be
1441311e34e2SKonstantin Belousov 	 * discounted in setting the target for the active queue scan.
1442311e34e2SKonstantin Belousov 	 */
14439099545aSAlan Cox 	addl_page_shortage = 0;
14449099545aSAlan Cox 
14451c7c3c6aSMatthew Dillon 	/*
144649a3710cSMark Johnston 	 * vmd_pageout_deficit counts the number of pages requested in
144749a3710cSMark Johnston 	 * allocations that failed because of a free page shortage.  We assume
144849a3710cSMark Johnston 	 * that the allocations will be reattempted and thus include the deficit
144949a3710cSMark Johnston 	 * in our scan target.
14501c7c3c6aSMatthew Dillon 	 */
1451e2068d0bSJeff Roberson 	deficit = atomic_readandclear_int(&vmd->vmd_pageout_deficit);
145249a3710cSMark Johnston 	starting_page_shortage = page_shortage = shortage + deficit;
14531c7c3c6aSMatthew Dillon 
1454e8bcf696SMark Johnston 	mtx = NULL;
14555cd29d0fSMark Johnston 	object = NULL;
14565cd29d0fSMark Johnston 	vm_batchqueue_init(&rq);
14575cd29d0fSMark Johnston 
1458936524aaSMatthew Dillon 	/*
1459f095d1bbSAlan Cox 	 * Start scanning the inactive queue for pages that we can free.  The
1460f095d1bbSAlan Cox 	 * scan will stop when we reach the target or we have scanned the
1461f095d1bbSAlan Cox 	 * entire queue.  (Note that m->act_count is not used to make
1462f095d1bbSAlan Cox 	 * decisions for the inactive queue, only for the active queue.)
14638d220203SAlan Cox 	 */
146464b38930SMark Johnston 	marker = &vmd->vmd_markers[PQ_INACTIVE];
14655cd29d0fSMark Johnston 	pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
14668d220203SAlan Cox 	vm_pagequeue_lock(pq);
14675cd29d0fSMark Johnston 	vm_pageout_init_scan(&ss, pq, marker, NULL, pq->pq_cnt);
14685cd29d0fSMark Johnston 	while (page_shortage > 0 && (m = vm_pageout_next(&ss, true)) != NULL) {
14695cd29d0fSMark Johnston 		KASSERT((m->flags & PG_MARKER) == 0,
14705cd29d0fSMark Johnston 		    ("marker page %p was dequeued", m));
1471df8bae1dSRodney W. Grimes 
1472e8bcf696SMark Johnston 		vm_page_change_lock(m, &mtx);
1473e8bcf696SMark Johnston 
1474e8bcf696SMark Johnston recheck:
1475936524aaSMatthew Dillon 		/*
1476e8bcf696SMark Johnston 		 * The page may have been disassociated from the queue
1477e8bcf696SMark Johnston 		 * or even freed while locks were dropped.  We thus must be
1478e8bcf696SMark Johnston 		 * careful whenever modifying page state.  Once the object lock
1479e8bcf696SMark Johnston 		 * has been acquired, we have a stable reference to the page.
1480936524aaSMatthew Dillon 		 */
1481e8bcf696SMark Johnston 		if (vm_page_queue(m) != PQ_INACTIVE) {
1482e8bcf696SMark Johnston 			addl_page_shortage++;
1483936524aaSMatthew Dillon 			continue;
1484e8bcf696SMark Johnston 		}
1485e8bcf696SMark Johnston 
1486e8bcf696SMark Johnston 		/*
1487e8bcf696SMark Johnston 		 * The page was re-enqueued after the page queue lock was
1488e8bcf696SMark Johnston 		 * dropped, or a requeue was requested.  This page gets a second
1489e8bcf696SMark Johnston 		 * chance.
1490e8bcf696SMark Johnston 		 */
1491e8bcf696SMark Johnston 		if ((m->aflags & (PGA_ENQUEUED | PGA_REQUEUE |
1492e8bcf696SMark Johnston 		    PGA_REQUEUE_HEAD)) != 0)
1493e8bcf696SMark Johnston 			goto reinsert;
1494e8bcf696SMark Johnston 
1495e8bcf696SMark Johnston 		/*
1496e8bcf696SMark Johnston 		 * Wired pages may not be freed.  Complete their removal
1497e8bcf696SMark Johnston 		 * from the queue now to avoid needless revisits during
1498e8bcf696SMark Johnston 		 * future scans.  This check is racy and must be reverified once
1499e8bcf696SMark Johnston 		 * we hold the object lock and have verified that the page
1500e8bcf696SMark Johnston 		 * is not busy.
1501e8bcf696SMark Johnston 		 */
1502e8bcf696SMark Johnston 		if (vm_page_wired(m)) {
1503e8bcf696SMark Johnston 			vm_page_dequeue_deferred(m);
15045cd29d0fSMark Johnston 			continue;
15055cd29d0fSMark Johnston 		}
15065cd29d0fSMark Johnston 
15075cd29d0fSMark Johnston 		if (object != m->object) {
150860256604SMark Johnston 			if (object != NULL)
15095cd29d0fSMark Johnston 				VM_OBJECT_WUNLOCK(object);
1510e8bcf696SMark Johnston 
1511e8bcf696SMark Johnston 			/*
1512e8bcf696SMark Johnston 			 * A page's object pointer may be set to NULL before
1513e8bcf696SMark Johnston 			 * the object lock is acquired.
1514e8bcf696SMark Johnston 			 */
1515fee2a2faSMark Johnston 			object = (vm_object_t)atomic_load_ptr(&m->object);
1516e8bcf696SMark Johnston 			if (object != NULL && !VM_OBJECT_TRYWLOCK(object)) {
1517e8bcf696SMark Johnston 				mtx_unlock(mtx);
1518e8bcf696SMark Johnston 				/* Depends on type-stability. */
151941fd4b94SMark Johnston 				VM_OBJECT_WLOCK(object);
1520e8bcf696SMark Johnston 				mtx_lock(mtx);
1521e8bcf696SMark Johnston 				goto recheck;
152241fd4b94SMark Johnston 			}
152341fd4b94SMark Johnston 		}
1524e8bcf696SMark Johnston 		if (__predict_false(m->object == NULL))
1525e8bcf696SMark Johnston 			/*
1526e8bcf696SMark Johnston 			 * The page has been removed from its object.
1527e8bcf696SMark Johnston 			 */
1528e8bcf696SMark Johnston 			continue;
1529e8bcf696SMark Johnston 		KASSERT(m->object == object, ("page %p does not belong to %p",
1530e8bcf696SMark Johnston 		    m, object));
15315cd29d0fSMark Johnston 
153263e97555SJeff Roberson 		if (vm_page_tryxbusy(m) == 0) {
1533a3aeedabSAlan Cox 			/*
1534a3aeedabSAlan Cox 			 * Don't mess with busy pages.  Leave them at
1535a3aeedabSAlan Cox 			 * the front of the queue.  Most likely, they
1536a3aeedabSAlan Cox 			 * are being paged out and will leave the
1537a3aeedabSAlan Cox 			 * queue shortly after the scan finishes.  So,
1538a3aeedabSAlan Cox 			 * they ought to be discounted from the
1539a3aeedabSAlan Cox 			 * inactive count.
1540a3aeedabSAlan Cox 			 */
1541a3aeedabSAlan Cox 			addl_page_shortage++;
15425cd29d0fSMark Johnston 			goto reinsert;
154326f9a767SRodney W. Grimes 		}
154448cc2fc7SKonstantin Belousov 
154548cc2fc7SKonstantin Belousov 		/*
1546e8bcf696SMark Johnston 		 * Re-check for wirings now that we hold the object lock and
1547e8bcf696SMark Johnston 		 * have verified that the page is unbusied.  If the page is
1548e8bcf696SMark Johnston 		 * mapped, it may still be wired by pmap lookups.  The call to
1549fee2a2faSMark Johnston 		 * vm_page_try_remove_all() below atomically checks for such
1550fee2a2faSMark Johnston 		 * wirings and removes mappings.  If the page is unmapped, the
1551fee2a2faSMark Johnston 		 * wire count is guaranteed not to increase.
1552fee2a2faSMark Johnston 		 */
1553fee2a2faSMark Johnston 		if (__predict_false(vm_page_wired(m))) {
155463e97555SJeff Roberson 			vm_page_xunbusy(m);
1555e8bcf696SMark Johnston 			vm_page_dequeue_deferred(m);
1556fee2a2faSMark Johnston 			continue;
1557fee2a2faSMark Johnston 		}
1558fee2a2faSMark Johnston 
1559fee2a2faSMark Johnston 		/*
15608748f58cSKonstantin Belousov 		 * Invalid pages can be easily freed. They cannot be
15618748f58cSKonstantin Belousov 		 * mapped, vm_page_free() asserts this.
1562776f729cSKonstantin Belousov 		 */
15630012f373SJeff Roberson 		if (vm_page_none_valid(m))
15648748f58cSKonstantin Belousov 			goto free_page;
1565776f729cSKonstantin Belousov 
1566776f729cSKonstantin Belousov 		/*
1567960810ccSAlan Cox 		 * If the page has been referenced and the object is not dead,
1568960810ccSAlan Cox 		 * reactivate or requeue the page depending on whether the
1569960810ccSAlan Cox 		 * object is mapped.
1570d7aeb429SAlan Cox 		 *
1571d7aeb429SAlan Cox 		 * Test PGA_REFERENCED after calling pmap_ts_referenced() so
1572d7aeb429SAlan Cox 		 * that a reference from a concurrently destroyed mapping is
1573d7aeb429SAlan Cox 		 * observed here and now.
15747e006499SJohn Dyson 		 */
1575e8bcf696SMark Johnston 		if (object->ref_count != 0)
1576e8bcf696SMark Johnston 			act_delta = pmap_ts_referenced(m);
1577e8bcf696SMark Johnston 		else {
1578e8bcf696SMark Johnston 			KASSERT(!pmap_page_is_mapped(m),
1579e8bcf696SMark Johnston 			    ("page %p is mapped", m));
1580e8bcf696SMark Johnston 			act_delta = 0;
1581d7aeb429SAlan Cox 		}
1582e8bcf696SMark Johnston 		if ((m->aflags & PGA_REFERENCED) != 0) {
1583e8bcf696SMark Johnston 			vm_page_aflag_clear(m, PGA_REFERENCED);
1584d7aeb429SAlan Cox 			act_delta++;
15852fe6e4d7SDavid Greenman 		}
1586bb7858eaSJeff Roberson 		if (act_delta != 0) {
158786fa2471SAlan Cox 			if (object->ref_count != 0) {
158863e97555SJeff Roberson 				vm_page_xunbusy(m);
158941fd4b94SMark Johnston 				VM_CNT_INC(v_reactivated);
1590e8bcf696SMark Johnston 				vm_page_activate(m);
1591e8bcf696SMark Johnston 
1592e8bcf696SMark Johnston 				/*
1593e8bcf696SMark Johnston 				 * Increase the activation count if the page
1594e8bcf696SMark Johnston 				 * was referenced while in the inactive queue.
1595e8bcf696SMark Johnston 				 * This makes it less likely that the page will
1596e8bcf696SMark Johnston 				 * be returned prematurely to the inactive
1597e8bcf696SMark Johnston 				 * queue.
1598e8bcf696SMark Johnston  				 */
1599e8bcf696SMark Johnston 				m->act_count += act_delta + ACT_ADVANCE;
1600e8bcf696SMark Johnston 				continue;
1601ebcddc72SAlan Cox 			} else if ((object->flags & OBJ_DEAD) == 0) {
160263e97555SJeff Roberson 				vm_page_xunbusy(m);
16035cd29d0fSMark Johnston 				vm_page_aflag_set(m, PGA_REQUEUE);
16045cd29d0fSMark Johnston 				goto reinsert;
1605ebcddc72SAlan Cox 			}
1606960810ccSAlan Cox 		}
160767bf6868SJohn Dyson 
16087e006499SJohn Dyson 		/*
16099fc4739dSAlan Cox 		 * If the page appears to be clean at the machine-independent
16109fc4739dSAlan Cox 		 * layer, then remove all of its mappings from the pmap in
1611a766ffd0SAlan Cox 		 * anticipation of freeing it.  If, however, any of the page's
1612a766ffd0SAlan Cox 		 * mappings allow write access, then the page may still be
1613a766ffd0SAlan Cox 		 * modified until the last of those mappings are removed.
16147e006499SJohn Dyson 		 */
1615aa044135SAlan Cox 		if (object->ref_count != 0) {
16169fc4739dSAlan Cox 			vm_page_test_dirty(m);
1617fee2a2faSMark Johnston 			if (m->dirty == 0 && !vm_page_try_remove_all(m)) {
161863e97555SJeff Roberson 				vm_page_xunbusy(m);
1619e8bcf696SMark Johnston 				vm_page_dequeue_deferred(m);
1620fee2a2faSMark Johnston 				continue;
1621fee2a2faSMark Johnston 			}
1622aa044135SAlan Cox 		}
1623dcbcd518SBruce Evans 
16246989c456SAlan Cox 		/*
1625ebcddc72SAlan Cox 		 * Clean pages can be freed, but dirty pages must be sent back
1626ebcddc72SAlan Cox 		 * to the laundry, unless they belong to a dead object.
1627ebcddc72SAlan Cox 		 * Requeueing dirty pages from dead objects is pointless, as
1628ebcddc72SAlan Cox 		 * they are being paged out and freed by the thread that
1629ebcddc72SAlan Cox 		 * destroyed the object.
16306989c456SAlan Cox 		 */
1631ebcddc72SAlan Cox 		if (m->dirty == 0) {
16328748f58cSKonstantin Belousov free_page:
16335cd29d0fSMark Johnston 			/*
16345cd29d0fSMark Johnston 			 * Because we dequeued the page and have already
16355cd29d0fSMark Johnston 			 * checked for concurrent dequeue and enqueue
16365cd29d0fSMark Johnston 			 * requests, we can safely disassociate the page
16375cd29d0fSMark Johnston 			 * from the inactive queue.
16385cd29d0fSMark Johnston 			 */
1639e8bcf696SMark Johnston 			KASSERT((m->aflags & PGA_QUEUE_STATE_MASK) == 0,
1640e8bcf696SMark Johnston 			    ("page %p has queue state", m));
1641e8bcf696SMark Johnston 			m->queue = PQ_NONE;
164278afdce6SAlan Cox 			vm_page_free(m);
16435cd29d0fSMark Johnston 			page_shortage--;
164463e97555SJeff Roberson 			continue;
164563e97555SJeff Roberson 		}
164663e97555SJeff Roberson 		vm_page_xunbusy(m);
164763e97555SJeff Roberson 		if ((object->flags & OBJ_DEAD) == 0)
1648ebcddc72SAlan Cox 			vm_page_launder(m);
16495cd29d0fSMark Johnston 		continue;
16505cd29d0fSMark Johnston reinsert:
16515cd29d0fSMark Johnston 		vm_pageout_reinsert_inactive(&ss, &rq, m);
16525cd29d0fSMark Johnston 	}
1653e8bcf696SMark Johnston 	if (mtx != NULL)
1654e8bcf696SMark Johnston 		mtx_unlock(mtx);
165560256604SMark Johnston 	if (object != NULL)
165689f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
16575cd29d0fSMark Johnston 	vm_pageout_reinsert_inactive(&ss, &rq, NULL);
16585cd29d0fSMark Johnston 	vm_pageout_reinsert_inactive(&ss, &ss.bq, NULL);
16598d220203SAlan Cox 	vm_pagequeue_lock(pq);
16605cd29d0fSMark Johnston 	vm_pageout_end_scan(&ss);
16618d220203SAlan Cox 	vm_pagequeue_unlock(pq);
166226f9a767SRodney W. Grimes 
16635cd29d0fSMark Johnston 	VM_CNT_ADD(v_dfree, starting_page_shortage - page_shortage);
16645cd29d0fSMark Johnston 
1665ebcddc72SAlan Cox 	/*
1666ebcddc72SAlan Cox 	 * Wake up the laundry thread so that it can perform any needed
1667ebcddc72SAlan Cox 	 * laundering.  If we didn't meet our target, we're in shortfall and
1668b1fd102eSMark Johnston 	 * need to launder more aggressively.  If PQ_LAUNDRY is empty and no
1669b1fd102eSMark Johnston 	 * swap devices are configured, the laundry thread has no work to do, so
1670b1fd102eSMark Johnston 	 * don't bother waking it up.
1671cb35676eSMark Johnston 	 *
1672cb35676eSMark Johnston 	 * The laundry thread uses the number of inactive queue scans elapsed
1673cb35676eSMark Johnston 	 * since the last laundering to determine whether to launder again, so
1674cb35676eSMark Johnston 	 * keep count.
1675ebcddc72SAlan Cox 	 */
1676cb35676eSMark Johnston 	if (starting_page_shortage > 0) {
1677e2068d0bSJeff Roberson 		pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
1678ebcddc72SAlan Cox 		vm_pagequeue_lock(pq);
1679e2068d0bSJeff Roberson 		if (vmd->vmd_laundry_request == VM_LAUNDRY_IDLE &&
1680cb35676eSMark Johnston 		    (pq->pq_cnt > 0 || atomic_load_acq_int(&swapdev_enabled))) {
1681ebcddc72SAlan Cox 			if (page_shortage > 0) {
1682e2068d0bSJeff Roberson 				vmd->vmd_laundry_request = VM_LAUNDRY_SHORTFALL;
168383c9dea1SGleb Smirnoff 				VM_CNT_INC(v_pdshortfalls);
1684e2068d0bSJeff Roberson 			} else if (vmd->vmd_laundry_request !=
1685e2068d0bSJeff Roberson 			    VM_LAUNDRY_SHORTFALL)
1686e2068d0bSJeff Roberson 				vmd->vmd_laundry_request =
1687e2068d0bSJeff Roberson 				    VM_LAUNDRY_BACKGROUND;
1688e2068d0bSJeff Roberson 			wakeup(&vmd->vmd_laundry_request);
1689b1fd102eSMark Johnston 		}
169060684862SMark Johnston 		vmd->vmd_clean_pages_freed +=
169160684862SMark Johnston 		    starting_page_shortage - page_shortage;
1692ebcddc72SAlan Cox 		vm_pagequeue_unlock(pq);
1693ebcddc72SAlan Cox 	}
1694ebcddc72SAlan Cox 
16959452b5edSAlan Cox 	/*
1696f095d1bbSAlan Cox 	 * Wakeup the swapout daemon if we didn't free the targeted number of
1697f095d1bbSAlan Cox 	 * pages.
16989452b5edSAlan Cox 	 */
1699ac04195bSKonstantin Belousov 	if (page_shortage > 0)
1700ac04195bSKonstantin Belousov 		vm_swapout_run();
17019452b5edSAlan Cox 
17029452b5edSAlan Cox 	/*
170376386c7eSKonstantin Belousov 	 * If the inactive queue scan fails repeatedly to meet its
170476386c7eSKonstantin Belousov 	 * target, kill the largest process.
170576386c7eSKonstantin Belousov 	 */
170676386c7eSKonstantin Belousov 	vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
170776386c7eSKonstantin Belousov 
170876386c7eSKonstantin Belousov 	/*
1709be37ee79SMark Johnston 	 * Reclaim pages by swapping out idle processes, if configured to do so.
17101c7c3c6aSMatthew Dillon 	 */
1711ac04195bSKonstantin Belousov 	vm_swapout_run_idle();
1712be37ee79SMark Johnston 
1713be37ee79SMark Johnston 	/*
1714be37ee79SMark Johnston 	 * See the description of addl_page_shortage above.
1715be37ee79SMark Johnston 	 */
1716be37ee79SMark Johnston 	*addl_shortage = addl_page_shortage + deficit;
1717be37ee79SMark Johnston 
1718e57dd910SAlan Cox 	return (page_shortage <= 0);
17192025d69bSKonstantin Belousov }
17202025d69bSKonstantin Belousov 
1721449c2e92SKonstantin Belousov static int vm_pageout_oom_vote;
1722449c2e92SKonstantin Belousov 
1723449c2e92SKonstantin Belousov /*
1724449c2e92SKonstantin Belousov  * The pagedaemon threads randlomly select one to perform the
1725449c2e92SKonstantin Belousov  * OOM.  Trying to kill processes before all pagedaemons
1726449c2e92SKonstantin Belousov  * failed to reach free target is premature.
1727449c2e92SKonstantin Belousov  */
1728449c2e92SKonstantin Belousov static void
172976386c7eSKonstantin Belousov vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
173076386c7eSKonstantin Belousov     int starting_page_shortage)
1731449c2e92SKonstantin Belousov {
1732449c2e92SKonstantin Belousov 	int old_vote;
1733449c2e92SKonstantin Belousov 
173476386c7eSKonstantin Belousov 	if (starting_page_shortage <= 0 || starting_page_shortage !=
173576386c7eSKonstantin Belousov 	    page_shortage)
173676386c7eSKonstantin Belousov 		vmd->vmd_oom_seq = 0;
173776386c7eSKonstantin Belousov 	else
173876386c7eSKonstantin Belousov 		vmd->vmd_oom_seq++;
173976386c7eSKonstantin Belousov 	if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1740449c2e92SKonstantin Belousov 		if (vmd->vmd_oom) {
1741449c2e92SKonstantin Belousov 			vmd->vmd_oom = FALSE;
1742449c2e92SKonstantin Belousov 			atomic_subtract_int(&vm_pageout_oom_vote, 1);
1743449c2e92SKonstantin Belousov 		}
1744449c2e92SKonstantin Belousov 		return;
1745449c2e92SKonstantin Belousov 	}
1746449c2e92SKonstantin Belousov 
174776386c7eSKonstantin Belousov 	/*
174876386c7eSKonstantin Belousov 	 * Do not follow the call sequence until OOM condition is
174976386c7eSKonstantin Belousov 	 * cleared.
175076386c7eSKonstantin Belousov 	 */
175176386c7eSKonstantin Belousov 	vmd->vmd_oom_seq = 0;
175276386c7eSKonstantin Belousov 
1753449c2e92SKonstantin Belousov 	if (vmd->vmd_oom)
1754449c2e92SKonstantin Belousov 		return;
1755449c2e92SKonstantin Belousov 
1756449c2e92SKonstantin Belousov 	vmd->vmd_oom = TRUE;
1757449c2e92SKonstantin Belousov 	old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1758449c2e92SKonstantin Belousov 	if (old_vote != vm_ndomains - 1)
1759449c2e92SKonstantin Belousov 		return;
1760449c2e92SKonstantin Belousov 
1761449c2e92SKonstantin Belousov 	/*
1762449c2e92SKonstantin Belousov 	 * The current pagedaemon thread is the last in the quorum to
1763449c2e92SKonstantin Belousov 	 * start OOM.  Initiate the selection and signaling of the
1764449c2e92SKonstantin Belousov 	 * victim.
1765449c2e92SKonstantin Belousov 	 */
1766449c2e92SKonstantin Belousov 	vm_pageout_oom(VM_OOM_MEM);
1767449c2e92SKonstantin Belousov 
1768449c2e92SKonstantin Belousov 	/*
1769449c2e92SKonstantin Belousov 	 * After one round of OOM terror, recall our vote.  On the
1770449c2e92SKonstantin Belousov 	 * next pass, current pagedaemon would vote again if the low
1771449c2e92SKonstantin Belousov 	 * memory condition is still there, due to vmd_oom being
1772449c2e92SKonstantin Belousov 	 * false.
1773449c2e92SKonstantin Belousov 	 */
1774449c2e92SKonstantin Belousov 	vmd->vmd_oom = FALSE;
1775449c2e92SKonstantin Belousov 	atomic_subtract_int(&vm_pageout_oom_vote, 1);
1776449c2e92SKonstantin Belousov }
17772025d69bSKonstantin Belousov 
17783949873fSKonstantin Belousov /*
17793949873fSKonstantin Belousov  * The OOM killer is the page daemon's action of last resort when
17803949873fSKonstantin Belousov  * memory allocation requests have been stalled for a prolonged period
17813949873fSKonstantin Belousov  * of time because it cannot reclaim memory.  This function computes
17823949873fSKonstantin Belousov  * the approximate number of physical pages that could be reclaimed if
17833949873fSKonstantin Belousov  * the specified address space is destroyed.
17843949873fSKonstantin Belousov  *
17853949873fSKonstantin Belousov  * Private, anonymous memory owned by the address space is the
17863949873fSKonstantin Belousov  * principal resource that we expect to recover after an OOM kill.
17873949873fSKonstantin Belousov  * Since the physical pages mapped by the address space's COW entries
17883949873fSKonstantin Belousov  * are typically shared pages, they are unlikely to be released and so
17893949873fSKonstantin Belousov  * they are not counted.
17903949873fSKonstantin Belousov  *
17913949873fSKonstantin Belousov  * To get to the point where the page daemon runs the OOM killer, its
17923949873fSKonstantin Belousov  * efforts to write-back vnode-backed pages may have stalled.  This
17933949873fSKonstantin Belousov  * could be caused by a memory allocation deadlock in the write path
17943949873fSKonstantin Belousov  * that might be resolved by an OOM kill.  Therefore, physical pages
17953949873fSKonstantin Belousov  * belonging to vnode-backed objects are counted, because they might
17963949873fSKonstantin Belousov  * be freed without being written out first if the address space holds
17973949873fSKonstantin Belousov  * the last reference to an unlinked vnode.
17983949873fSKonstantin Belousov  *
17993949873fSKonstantin Belousov  * Similarly, physical pages belonging to OBJT_PHYS objects are
18003949873fSKonstantin Belousov  * counted because the address space might hold the last reference to
18013949873fSKonstantin Belousov  * the object.
18023949873fSKonstantin Belousov  */
18033949873fSKonstantin Belousov static long
18043949873fSKonstantin Belousov vm_pageout_oom_pagecount(struct vmspace *vmspace)
18053949873fSKonstantin Belousov {
18063949873fSKonstantin Belousov 	vm_map_t map;
18073949873fSKonstantin Belousov 	vm_map_entry_t entry;
18083949873fSKonstantin Belousov 	vm_object_t obj;
18093949873fSKonstantin Belousov 	long res;
18103949873fSKonstantin Belousov 
18113949873fSKonstantin Belousov 	map = &vmspace->vm_map;
18123949873fSKonstantin Belousov 	KASSERT(!map->system_map, ("system map"));
18133949873fSKonstantin Belousov 	sx_assert(&map->lock, SA_LOCKED);
18143949873fSKonstantin Belousov 	res = 0;
18152288078cSDoug Moore 	VM_MAP_ENTRY_FOREACH(entry, map) {
18163949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
18173949873fSKonstantin Belousov 			continue;
18183949873fSKonstantin Belousov 		obj = entry->object.vm_object;
18193949873fSKonstantin Belousov 		if (obj == NULL)
18203949873fSKonstantin Belousov 			continue;
18213949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
18223949873fSKonstantin Belousov 		    obj->ref_count != 1)
18233949873fSKonstantin Belousov 			continue;
18243949873fSKonstantin Belousov 		switch (obj->type) {
18253949873fSKonstantin Belousov 		case OBJT_DEFAULT:
18263949873fSKonstantin Belousov 		case OBJT_SWAP:
18273949873fSKonstantin Belousov 		case OBJT_PHYS:
18283949873fSKonstantin Belousov 		case OBJT_VNODE:
18293949873fSKonstantin Belousov 			res += obj->resident_page_count;
18303949873fSKonstantin Belousov 			break;
18313949873fSKonstantin Belousov 		}
18323949873fSKonstantin Belousov 	}
18333949873fSKonstantin Belousov 	return (res);
18343949873fSKonstantin Belousov }
18353949873fSKonstantin Belousov 
1836245139c6SKonstantin Belousov static int vm_oom_ratelim_last;
1837245139c6SKonstantin Belousov static int vm_oom_pf_secs = 10;
1838245139c6SKonstantin Belousov SYSCTL_INT(_vm, OID_AUTO, oom_pf_secs, CTLFLAG_RWTUN, &vm_oom_pf_secs, 0,
1839245139c6SKonstantin Belousov     "");
1840245139c6SKonstantin Belousov static struct mtx vm_oom_ratelim_mtx;
1841245139c6SKonstantin Belousov 
18422025d69bSKonstantin Belousov void
18432025d69bSKonstantin Belousov vm_pageout_oom(int shortage)
18442025d69bSKonstantin Belousov {
18452025d69bSKonstantin Belousov 	struct proc *p, *bigproc;
18462025d69bSKonstantin Belousov 	vm_offset_t size, bigsize;
18472025d69bSKonstantin Belousov 	struct thread *td;
18486bed074cSKonstantin Belousov 	struct vmspace *vm;
1849245139c6SKonstantin Belousov 	int now;
18503e78e983SAlan Cox 	bool breakout;
18512025d69bSKonstantin Belousov 
18522025d69bSKonstantin Belousov 	/*
1853245139c6SKonstantin Belousov 	 * For OOM requests originating from vm_fault(), there is a high
1854245139c6SKonstantin Belousov 	 * chance that a single large process faults simultaneously in
1855245139c6SKonstantin Belousov 	 * several threads.  Also, on an active system running many
1856245139c6SKonstantin Belousov 	 * processes of middle-size, like buildworld, all of them
1857245139c6SKonstantin Belousov 	 * could fault almost simultaneously as well.
1858245139c6SKonstantin Belousov 	 *
1859245139c6SKonstantin Belousov 	 * To avoid killing too many processes, rate-limit OOMs
1860245139c6SKonstantin Belousov 	 * initiated by vm_fault() time-outs on the waits for free
1861245139c6SKonstantin Belousov 	 * pages.
1862245139c6SKonstantin Belousov 	 */
1863245139c6SKonstantin Belousov 	mtx_lock(&vm_oom_ratelim_mtx);
1864245139c6SKonstantin Belousov 	now = ticks;
1865245139c6SKonstantin Belousov 	if (shortage == VM_OOM_MEM_PF &&
1866245139c6SKonstantin Belousov 	    (u_int)(now - vm_oom_ratelim_last) < hz * vm_oom_pf_secs) {
1867245139c6SKonstantin Belousov 		mtx_unlock(&vm_oom_ratelim_mtx);
1868245139c6SKonstantin Belousov 		return;
1869245139c6SKonstantin Belousov 	}
1870245139c6SKonstantin Belousov 	vm_oom_ratelim_last = now;
1871245139c6SKonstantin Belousov 	mtx_unlock(&vm_oom_ratelim_mtx);
1872245139c6SKonstantin Belousov 
1873245139c6SKonstantin Belousov 	/*
18741c58e4e5SJohn Baldwin 	 * We keep the process bigproc locked once we find it to keep anyone
18751c58e4e5SJohn Baldwin 	 * from messing with it; however, there is a possibility of
187628323addSBryan Drewery 	 * deadlock if process B is bigproc and one of its child processes
18771c58e4e5SJohn Baldwin 	 * attempts to propagate a signal to B while we are waiting for A's
18781c58e4e5SJohn Baldwin 	 * lock while walking this list.  To avoid this, we don't block on
18791c58e4e5SJohn Baldwin 	 * the process lock but just skip a process if it is already locked.
18805663e6deSDavid Greenman 	 */
18815663e6deSDavid Greenman 	bigproc = NULL;
18825663e6deSDavid Greenman 	bigsize = 0;
18831005a129SJohn Baldwin 	sx_slock(&allproc_lock);
1884e602ba25SJulian Elischer 	FOREACH_PROC_IN_SYSTEM(p) {
188571943c3dSKonstantin Belousov 		PROC_LOCK(p);
188671943c3dSKonstantin Belousov 
18871c58e4e5SJohn Baldwin 		/*
18883f1c4c4fSKonstantin Belousov 		 * If this is a system, protected or killed process, skip it.
18895663e6deSDavid Greenman 		 */
189071943c3dSKonstantin Belousov 		if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
189171943c3dSKonstantin Belousov 		    P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
189271943c3dSKonstantin Belousov 		    p->p_pid == 1 || P_KILLED(p) ||
189371943c3dSKonstantin Belousov 		    (p->p_pid < 48 && swap_pager_avail != 0)) {
18948606d880SJohn Baldwin 			PROC_UNLOCK(p);
18955663e6deSDavid Greenman 			continue;
18965663e6deSDavid Greenman 		}
18975663e6deSDavid Greenman 		/*
1898dcbcd518SBruce Evans 		 * If the process is in a non-running type state,
1899e602ba25SJulian Elischer 		 * don't touch it.  Check all the threads individually.
19005663e6deSDavid Greenman 		 */
19013e78e983SAlan Cox 		breakout = false;
1902e602ba25SJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td) {
1903982d11f8SJeff Roberson 			thread_lock(td);
190471fad9fdSJulian Elischer 			if (!TD_ON_RUNQ(td) &&
190571fad9fdSJulian Elischer 			    !TD_IS_RUNNING(td) &&
1906f497cda2SEdward Tomasz Napierala 			    !TD_IS_SLEEPING(td) &&
1907b98acc0aSKonstantin Belousov 			    !TD_IS_SUSPENDED(td) &&
1908b98acc0aSKonstantin Belousov 			    !TD_IS_SWAPPED(td)) {
1909982d11f8SJeff Roberson 				thread_unlock(td);
19103e78e983SAlan Cox 				breakout = true;
1911e602ba25SJulian Elischer 				break;
1912e602ba25SJulian Elischer 			}
1913982d11f8SJeff Roberson 			thread_unlock(td);
1914e602ba25SJulian Elischer 		}
1915e602ba25SJulian Elischer 		if (breakout) {
19161c58e4e5SJohn Baldwin 			PROC_UNLOCK(p);
19175663e6deSDavid Greenman 			continue;
19185663e6deSDavid Greenman 		}
19195663e6deSDavid Greenman 		/*
19205663e6deSDavid Greenman 		 * get the process size
19215663e6deSDavid Greenman 		 */
19226bed074cSKonstantin Belousov 		vm = vmspace_acquire_ref(p);
19236bed074cSKonstantin Belousov 		if (vm == NULL) {
19246bed074cSKonstantin Belousov 			PROC_UNLOCK(p);
19256bed074cSKonstantin Belousov 			continue;
19266bed074cSKonstantin Belousov 		}
192795e2409aSKonstantin Belousov 		_PHOLD_LITE(p);
192872d97679SDavid Schultz 		PROC_UNLOCK(p);
192995e2409aSKonstantin Belousov 		sx_sunlock(&allproc_lock);
193095e2409aSKonstantin Belousov 		if (!vm_map_trylock_read(&vm->vm_map)) {
193171943c3dSKonstantin Belousov 			vmspace_free(vm);
193295e2409aSKonstantin Belousov 			sx_slock(&allproc_lock);
193395e2409aSKonstantin Belousov 			PRELE(p);
193472d97679SDavid Schultz 			continue;
193572d97679SDavid Schultz 		}
19367981aa24SKonstantin Belousov 		size = vmspace_swap_count(vm);
1937245139c6SKonstantin Belousov 		if (shortage == VM_OOM_MEM || shortage == VM_OOM_MEM_PF)
19383949873fSKonstantin Belousov 			size += vm_pageout_oom_pagecount(vm);
19393949873fSKonstantin Belousov 		vm_map_unlock_read(&vm->vm_map);
19406bed074cSKonstantin Belousov 		vmspace_free(vm);
194195e2409aSKonstantin Belousov 		sx_slock(&allproc_lock);
19423949873fSKonstantin Belousov 
19435663e6deSDavid Greenman 		/*
19443949873fSKonstantin Belousov 		 * If this process is bigger than the biggest one,
19455663e6deSDavid Greenman 		 * remember it.
19465663e6deSDavid Greenman 		 */
19475663e6deSDavid Greenman 		if (size > bigsize) {
19481c58e4e5SJohn Baldwin 			if (bigproc != NULL)
194971943c3dSKonstantin Belousov 				PRELE(bigproc);
19505663e6deSDavid Greenman 			bigproc = p;
19515663e6deSDavid Greenman 			bigsize = size;
195271943c3dSKonstantin Belousov 		} else {
195371943c3dSKonstantin Belousov 			PRELE(p);
195471943c3dSKonstantin Belousov 		}
19555663e6deSDavid Greenman 	}
19561005a129SJohn Baldwin 	sx_sunlock(&allproc_lock);
19575663e6deSDavid Greenman 	if (bigproc != NULL) {
19588311a2b8SWill Andrews 		if (vm_panic_on_oom != 0)
19598311a2b8SWill Andrews 			panic("out of swap space");
196071943c3dSKonstantin Belousov 		PROC_LOCK(bigproc);
1961729b1e51SDavid Greenman 		killproc(bigproc, "out of swap space");
1962fa885116SJulian Elischer 		sched_nice(bigproc, PRIO_MIN);
196371943c3dSKonstantin Belousov 		_PRELE(bigproc);
19641c58e4e5SJohn Baldwin 		PROC_UNLOCK(bigproc);
19655663e6deSDavid Greenman 	}
19665663e6deSDavid Greenman }
196726f9a767SRodney W. Grimes 
1968*8fc25508SMark Johnston /*
1969*8fc25508SMark Johnston  * Signal a free page shortage to subsystems that have registered an event
1970*8fc25508SMark Johnston  * handler.  Reclaim memory from UMA in the event of a severe shortage.
1971*8fc25508SMark Johnston  * Return true if the free page count should be re-evaluated.
1972*8fc25508SMark Johnston  */
1973b50a4ea6SMark Johnston static bool
1974b50a4ea6SMark Johnston vm_pageout_lowmem(void)
197549a3710cSMark Johnston {
1976b50a4ea6SMark Johnston 	static int lowmem_ticks = 0;
1977b50a4ea6SMark Johnston 	int last;
1978*8fc25508SMark Johnston 	bool ret;
1979*8fc25508SMark Johnston 
1980*8fc25508SMark Johnston 	ret = false;
198149a3710cSMark Johnston 
1982b50a4ea6SMark Johnston 	last = atomic_load_int(&lowmem_ticks);
1983b50a4ea6SMark Johnston 	while ((u_int)(ticks - last) / hz >= lowmem_period) {
1984b50a4ea6SMark Johnston 		if (atomic_fcmpset_int(&lowmem_ticks, &last, ticks) == 0)
1985b50a4ea6SMark Johnston 			continue;
1986b50a4ea6SMark Johnston 
198749a3710cSMark Johnston 		/*
198849a3710cSMark Johnston 		 * Decrease registered cache sizes.
198949a3710cSMark Johnston 		 */
199049a3710cSMark Johnston 		SDT_PROBE0(vm, , , vm__lowmem_scan);
199149a3710cSMark Johnston 		EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_PAGES);
199249a3710cSMark Johnston 
199349a3710cSMark Johnston 		/*
199449a3710cSMark Johnston 		 * We do this explicitly after the caches have been
1995*8fc25508SMark Johnston 		 * drained above.
199649a3710cSMark Johnston 		 */
1997*8fc25508SMark Johnston 		uma_reclaim(UMA_RECLAIM_TRIM);
1998*8fc25508SMark Johnston 		ret = true;
199949a3710cSMark Johnston 	}
2000*8fc25508SMark Johnston 
2001*8fc25508SMark Johnston 	/*
2002*8fc25508SMark Johnston 	 * Kick off an asynchronous reclaim of cached memory if one of the
2003*8fc25508SMark Johnston 	 * page daemons is failing to keep up with demand.  Use the "severe"
2004*8fc25508SMark Johnston 	 * threshold instead of "min" to ensure that we do not blow away the
2005*8fc25508SMark Johnston 	 * caches if a subset of the NUMA domains are depleted by kernel memory
2006*8fc25508SMark Johnston 	 * allocations; the domainset iterators automatically skip domains
2007*8fc25508SMark Johnston 	 * below the "min" threshold on the first pass.
2008*8fc25508SMark Johnston 	 *
2009*8fc25508SMark Johnston 	 * UMA reclaim worker has its own rate-limiting mechanism, so don't
2010*8fc25508SMark Johnston 	 * worry about kicking it too often.
2011*8fc25508SMark Johnston 	 */
2012*8fc25508SMark Johnston 	if (vm_page_count_severe())
2013*8fc25508SMark Johnston 		uma_reclaim_wakeup();
2014*8fc25508SMark Johnston 
2015*8fc25508SMark Johnston 	return (ret);
201649a3710cSMark Johnston }
201749a3710cSMark Johnston 
201849a3710cSMark Johnston static void
2019449c2e92SKonstantin Belousov vm_pageout_worker(void *arg)
2020449c2e92SKonstantin Belousov {
2021e2068d0bSJeff Roberson 	struct vm_domain *vmd;
2022b50a4ea6SMark Johnston 	u_int ofree;
202349a3710cSMark Johnston 	int addl_shortage, domain, shortage;
2024e57dd910SAlan Cox 	bool target_met;
2025449c2e92SKonstantin Belousov 
2026e2068d0bSJeff Roberson 	domain = (uintptr_t)arg;
2027e2068d0bSJeff Roberson 	vmd = VM_DOMAIN(domain);
20285f8cd1c0SJeff Roberson 	shortage = 0;
2029e57dd910SAlan Cox 	target_met = true;
2030449c2e92SKonstantin Belousov 
2031449c2e92SKonstantin Belousov 	/*
2032949c9186SKonstantin Belousov 	 * XXXKIB It could be useful to bind pageout daemon threads to
2033949c9186SKonstantin Belousov 	 * the cores belonging to the domain, from which vm_page_array
2034949c9186SKonstantin Belousov 	 * is allocated.
2035449c2e92SKonstantin Belousov 	 */
2036449c2e92SKonstantin Belousov 
2037e2068d0bSJeff Roberson 	KASSERT(vmd->vmd_segs != 0, ("domain without segments"));
2038e2068d0bSJeff Roberson 	vmd->vmd_last_active_scan = ticks;
2039449c2e92SKonstantin Belousov 
2040449c2e92SKonstantin Belousov 	/*
2041449c2e92SKonstantin Belousov 	 * The pageout daemon worker is never done, so loop forever.
2042449c2e92SKonstantin Belousov 	 */
2043449c2e92SKonstantin Belousov 	while (TRUE) {
204430fbfddaSJeff Roberson 		vm_domain_pageout_lock(vmd);
204549a3710cSMark Johnston 
204630fbfddaSJeff Roberson 		/*
204730fbfddaSJeff Roberson 		 * We need to clear wanted before we check the limits.  This
204830fbfddaSJeff Roberson 		 * prevents races with wakers who will check wanted after they
204930fbfddaSJeff Roberson 		 * reach the limit.
205030fbfddaSJeff Roberson 		 */
205130fbfddaSJeff Roberson 		atomic_store_int(&vmd->vmd_pageout_wanted, 0);
205256ce0690SAlan Cox 
205356ce0690SAlan Cox 		/*
20545f8cd1c0SJeff Roberson 		 * Might the page daemon need to run again?
2055449c2e92SKonstantin Belousov 		 */
20565f8cd1c0SJeff Roberson 		if (vm_paging_needed(vmd, vmd->vmd_free_count)) {
205756ce0690SAlan Cox 			/*
205849a3710cSMark Johnston 			 * Yes.  If the scan failed to produce enough free
205949a3710cSMark Johnston 			 * pages, sleep uninterruptibly for some time in the
206049a3710cSMark Johnston 			 * hope that the laundry thread will clean some pages.
206156ce0690SAlan Cox 			 */
206230fbfddaSJeff Roberson 			vm_domain_pageout_unlock(vmd);
206349a3710cSMark Johnston 			if (!target_met)
20646eebec83SMark Johnston 				pause("pwait", hz / VM_INACT_SCAN_RATE);
2065449c2e92SKonstantin Belousov 		} else {
2066449c2e92SKonstantin Belousov 			/*
20675f8cd1c0SJeff Roberson 			 * No, sleep until the next wakeup or until pages
20685f8cd1c0SJeff Roberson 			 * need to have their reference stats updated.
2069449c2e92SKonstantin Belousov 			 */
20702c0f13aaSKonstantin Belousov 			if (mtx_sleep(&vmd->vmd_pageout_wanted,
207130fbfddaSJeff Roberson 			    vm_domain_pageout_lockptr(vmd), PDROP | PVM,
20725f8cd1c0SJeff Roberson 			    "psleep", hz / VM_INACT_SCAN_RATE) == 0)
207383c9dea1SGleb Smirnoff 				VM_CNT_INC(v_pdwakeups);
207456ce0690SAlan Cox 		}
2075be37ee79SMark Johnston 
207630fbfddaSJeff Roberson 		/* Prevent spurious wakeups by ensuring that wanted is set. */
207730fbfddaSJeff Roberson 		atomic_store_int(&vmd->vmd_pageout_wanted, 1);
207830fbfddaSJeff Roberson 
207930fbfddaSJeff Roberson 		/*
208030fbfddaSJeff Roberson 		 * Use the controller to calculate how many pages to free in
2081b50a4ea6SMark Johnston 		 * this interval, and scan the inactive queue.  If the lowmem
2082b50a4ea6SMark Johnston 		 * handlers appear to have freed up some pages, subtract the
2083b50a4ea6SMark Johnston 		 * difference from the inactive queue scan target.
208430fbfddaSJeff Roberson 		 */
20855f8cd1c0SJeff Roberson 		shortage = pidctrl_daemon(&vmd->vmd_pid, vmd->vmd_free_count);
208649a3710cSMark Johnston 		if (shortage > 0) {
2087b50a4ea6SMark Johnston 			ofree = vmd->vmd_free_count;
2088b50a4ea6SMark Johnston 			if (vm_pageout_lowmem() && vmd->vmd_free_count > ofree)
2089b50a4ea6SMark Johnston 				shortage -= min(vmd->vmd_free_count - ofree,
2090b50a4ea6SMark Johnston 				    (u_int)shortage);
209149a3710cSMark Johnston 			target_met = vm_pageout_scan_inactive(vmd, shortage,
2092be37ee79SMark Johnston 			    &addl_shortage);
209349a3710cSMark Johnston 		} else
209449a3710cSMark Johnston 			addl_shortage = 0;
209556ce0690SAlan Cox 
2096be37ee79SMark Johnston 		/*
2097be37ee79SMark Johnston 		 * Scan the active queue.  A positive value for shortage
2098be37ee79SMark Johnston 		 * indicates that we must aggressively deactivate pages to avoid
2099be37ee79SMark Johnston 		 * a shortfall.
2100be37ee79SMark Johnston 		 */
21017bb4634eSMark Johnston 		shortage = vm_pageout_active_target(vmd) + addl_shortage;
2102be37ee79SMark Johnston 		vm_pageout_scan_active(vmd, shortage);
2103449c2e92SKonstantin Belousov 	}
2104449c2e92SKonstantin Belousov }
2105449c2e92SKonstantin Belousov 
2106df8bae1dSRodney W. Grimes /*
21074d19f4adSSteven Hartland  *	vm_pageout_init initialises basic pageout daemon settings.
2108df8bae1dSRodney W. Grimes  */
21092b14f991SJulian Elischer static void
2110e2068d0bSJeff Roberson vm_pageout_init_domain(int domain)
2111df8bae1dSRodney W. Grimes {
2112e2068d0bSJeff Roberson 	struct vm_domain *vmd;
21135f8cd1c0SJeff Roberson 	struct sysctl_oid *oid;
2114e2068d0bSJeff Roberson 
2115e2068d0bSJeff Roberson 	vmd = VM_DOMAIN(domain);
2116e2068d0bSJeff Roberson 	vmd->vmd_interrupt_free_min = 2;
2117f6b04d2bSDavid Greenman 
211845ae1d91SAlan Cox 	/*
211945ae1d91SAlan Cox 	 * v_free_reserved needs to include enough for the largest
212045ae1d91SAlan Cox 	 * swap pager structures plus enough for any pv_entry structs
212145ae1d91SAlan Cox 	 * when paging.
212245ae1d91SAlan Cox 	 */
2123e2068d0bSJeff Roberson 	if (vmd->vmd_page_count > 1024)
2124e2068d0bSJeff Roberson 		vmd->vmd_free_min = 4 + (vmd->vmd_page_count - 1024) / 200;
21252feb50bfSAttilio Rao 	else
2126e2068d0bSJeff Roberson 		vmd->vmd_free_min = 4;
21270cab71bcSDoug Moore 	vmd->vmd_pageout_free_min = 2 * MAXBSIZE / PAGE_SIZE +
2128e2068d0bSJeff Roberson 	    vmd->vmd_interrupt_free_min;
2129e2068d0bSJeff Roberson 	vmd->vmd_free_reserved = vm_pageout_page_count +
2130e2068d0bSJeff Roberson 	    vmd->vmd_pageout_free_min + (vmd->vmd_page_count / 768);
2131e2068d0bSJeff Roberson 	vmd->vmd_free_severe = vmd->vmd_free_min / 2;
2132e2068d0bSJeff Roberson 	vmd->vmd_free_target = 4 * vmd->vmd_free_min + vmd->vmd_free_reserved;
2133e2068d0bSJeff Roberson 	vmd->vmd_free_min += vmd->vmd_free_reserved;
2134e2068d0bSJeff Roberson 	vmd->vmd_free_severe += vmd->vmd_free_reserved;
2135e2068d0bSJeff Roberson 	vmd->vmd_inactive_target = (3 * vmd->vmd_free_target) / 2;
2136e2068d0bSJeff Roberson 	if (vmd->vmd_inactive_target > vmd->vmd_free_count / 3)
2137e2068d0bSJeff Roberson 		vmd->vmd_inactive_target = vmd->vmd_free_count / 3;
2138df8bae1dSRodney W. Grimes 
2139d9e23210SJeff Roberson 	/*
21405f8cd1c0SJeff Roberson 	 * Set the default wakeup threshold to be 10% below the paging
21415f8cd1c0SJeff Roberson 	 * target.  This keeps the steady state out of shortfall.
2142d9e23210SJeff Roberson 	 */
21435f8cd1c0SJeff Roberson 	vmd->vmd_pageout_wakeup_thresh = (vmd->vmd_free_target / 10) * 9;
2144e2068d0bSJeff Roberson 
2145e2068d0bSJeff Roberson 	/*
2146e2068d0bSJeff Roberson 	 * Target amount of memory to move out of the laundry queue during a
2147e2068d0bSJeff Roberson 	 * background laundering.  This is proportional to the amount of system
2148e2068d0bSJeff Roberson 	 * memory.
2149e2068d0bSJeff Roberson 	 */
2150e2068d0bSJeff Roberson 	vmd->vmd_background_launder_target = (vmd->vmd_free_target -
2151e2068d0bSJeff Roberson 	    vmd->vmd_free_min) / 10;
21525f8cd1c0SJeff Roberson 
21535f8cd1c0SJeff Roberson 	/* Initialize the pageout daemon pid controller. */
21545f8cd1c0SJeff Roberson 	pidctrl_init(&vmd->vmd_pid, hz / VM_INACT_SCAN_RATE,
21555f8cd1c0SJeff Roberson 	    vmd->vmd_free_target, PIDCTRL_BOUND,
21565f8cd1c0SJeff Roberson 	    PIDCTRL_KPD, PIDCTRL_KID, PIDCTRL_KDD);
21575f8cd1c0SJeff Roberson 	oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(vmd->vmd_oid), OID_AUTO,
21585f8cd1c0SJeff Roberson 	    "pidctrl", CTLFLAG_RD, NULL, "");
21595f8cd1c0SJeff Roberson 	pidctrl_init_sysctl(&vmd->vmd_pid, SYSCTL_CHILDREN(oid));
2160e2068d0bSJeff Roberson }
2161e2068d0bSJeff Roberson 
2162e2068d0bSJeff Roberson static void
2163e2068d0bSJeff Roberson vm_pageout_init(void)
2164e2068d0bSJeff Roberson {
2165e2068d0bSJeff Roberson 	u_int freecount;
2166e2068d0bSJeff Roberson 	int i;
2167e2068d0bSJeff Roberson 
2168e2068d0bSJeff Roberson 	/*
2169e2068d0bSJeff Roberson 	 * Initialize some paging parameters.
2170e2068d0bSJeff Roberson 	 */
2171e2068d0bSJeff Roberson 	if (vm_cnt.v_page_count < 2000)
2172e2068d0bSJeff Roberson 		vm_pageout_page_count = 8;
2173e2068d0bSJeff Roberson 
2174e2068d0bSJeff Roberson 	freecount = 0;
2175e2068d0bSJeff Roberson 	for (i = 0; i < vm_ndomains; i++) {
2176e2068d0bSJeff Roberson 		struct vm_domain *vmd;
2177e2068d0bSJeff Roberson 
2178e2068d0bSJeff Roberson 		vm_pageout_init_domain(i);
2179e2068d0bSJeff Roberson 		vmd = VM_DOMAIN(i);
2180e2068d0bSJeff Roberson 		vm_cnt.v_free_reserved += vmd->vmd_free_reserved;
2181e2068d0bSJeff Roberson 		vm_cnt.v_free_target += vmd->vmd_free_target;
2182e2068d0bSJeff Roberson 		vm_cnt.v_free_min += vmd->vmd_free_min;
2183e2068d0bSJeff Roberson 		vm_cnt.v_inactive_target += vmd->vmd_inactive_target;
2184e2068d0bSJeff Roberson 		vm_cnt.v_pageout_free_min += vmd->vmd_pageout_free_min;
2185e2068d0bSJeff Roberson 		vm_cnt.v_interrupt_free_min += vmd->vmd_interrupt_free_min;
2186e2068d0bSJeff Roberson 		vm_cnt.v_free_severe += vmd->vmd_free_severe;
2187e2068d0bSJeff Roberson 		freecount += vmd->vmd_free_count;
2188e2068d0bSJeff Roberson 	}
2189d9e23210SJeff Roberson 
2190d9e23210SJeff Roberson 	/*
2191d9e23210SJeff Roberson 	 * Set interval in seconds for active scan.  We want to visit each
2192c9612b2dSJeff Roberson 	 * page at least once every ten minutes.  This is to prevent worst
2193c9612b2dSJeff Roberson 	 * case paging behaviors with stale active LRU.
2194d9e23210SJeff Roberson 	 */
2195d9e23210SJeff Roberson 	if (vm_pageout_update_period == 0)
2196c9612b2dSJeff Roberson 		vm_pageout_update_period = 600;
2197d9e23210SJeff Roberson 
219854a3a114SMark Johnston 	if (vm_page_max_user_wired == 0)
219954a3a114SMark Johnston 		vm_page_max_user_wired = freecount / 3;
22004d19f4adSSteven Hartland }
22014d19f4adSSteven Hartland 
22024d19f4adSSteven Hartland /*
22034d19f4adSSteven Hartland  *     vm_pageout is the high level pageout daemon.
22044d19f4adSSteven Hartland  */
22054d19f4adSSteven Hartland static void
22064d19f4adSSteven Hartland vm_pageout(void)
22074d19f4adSSteven Hartland {
2208920239efSMark Johnston 	struct proc *p;
2209920239efSMark Johnston 	struct thread *td;
2210920239efSMark Johnston 	int error, first, i;
2211920239efSMark Johnston 
2212920239efSMark Johnston 	p = curproc;
2213920239efSMark Johnston 	td = curthread;
2214df8bae1dSRodney W. Grimes 
2215245139c6SKonstantin Belousov 	mtx_init(&vm_oom_ratelim_mtx, "vmoomr", NULL, MTX_DEF);
221624a1cce3SDavid Greenman 	swap_pager_swap_init();
2217920239efSMark Johnston 	for (first = -1, i = 0; i < vm_ndomains; i++) {
221830c5525bSAndrew Gallatin 		if (VM_DOMAIN_EMPTY(i)) {
221930c5525bSAndrew Gallatin 			if (bootverbose)
222030c5525bSAndrew Gallatin 				printf("domain %d empty; skipping pageout\n",
222130c5525bSAndrew Gallatin 				    i);
222230c5525bSAndrew Gallatin 			continue;
222330c5525bSAndrew Gallatin 		}
2224920239efSMark Johnston 		if (first == -1)
2225920239efSMark Johnston 			first = i;
2226920239efSMark Johnston 		else {
2227920239efSMark Johnston 			error = kthread_add(vm_pageout_worker,
2228920239efSMark Johnston 			    (void *)(uintptr_t)i, p, NULL, 0, 0, "dom%d", i);
2229920239efSMark Johnston 			if (error != 0)
2230920239efSMark Johnston 				panic("starting pageout for domain %d: %d\n",
2231449c2e92SKonstantin Belousov 				    i, error);
2232dc2efb27SJohn Dyson 		}
2233e2068d0bSJeff Roberson 		error = kthread_add(vm_pageout_laundry_worker,
2234920239efSMark Johnston 		    (void *)(uintptr_t)i, p, NULL, 0, 0, "laundry: dom%d", i);
2235e2068d0bSJeff Roberson 		if (error != 0)
2236920239efSMark Johnston 			panic("starting laundry for domain %d: %d", i, error);
2237f919ebdeSDavid Greenman 	}
2238920239efSMark Johnston 	error = kthread_add(uma_reclaim_worker, NULL, p, NULL, 0, 0, "uma");
223944ec2b63SKonstantin Belousov 	if (error != 0)
224044ec2b63SKonstantin Belousov 		panic("starting uma_reclaim helper, error %d\n", error);
2241920239efSMark Johnston 
2242920239efSMark Johnston 	snprintf(td->td_name, sizeof(td->td_name), "dom%d", first);
2243920239efSMark Johnston 	vm_pageout_worker((void *)(uintptr_t)first);
2244df8bae1dSRodney W. Grimes }
224526f9a767SRodney W. Grimes 
22466b4b77adSAlan Cox /*
2247280d15cdSMark Johnston  * Perform an advisory wakeup of the page daemon.
22486b4b77adSAlan Cox  */
2249e0c5a895SJohn Dyson void
2250e2068d0bSJeff Roberson pagedaemon_wakeup(int domain)
2251e0c5a895SJohn Dyson {
2252e2068d0bSJeff Roberson 	struct vm_domain *vmd;
2253a1c0a785SAlan Cox 
2254e2068d0bSJeff Roberson 	vmd = VM_DOMAIN(domain);
225530fbfddaSJeff Roberson 	vm_domain_pageout_assert_unlocked(vmd);
225630fbfddaSJeff Roberson 	if (curproc == pageproc)
225730fbfddaSJeff Roberson 		return;
2258280d15cdSMark Johnston 
225930fbfddaSJeff Roberson 	if (atomic_fetchadd_int(&vmd->vmd_pageout_wanted, 1) == 0) {
226030fbfddaSJeff Roberson 		vm_domain_pageout_lock(vmd);
226130fbfddaSJeff Roberson 		atomic_store_int(&vmd->vmd_pageout_wanted, 1);
2262e2068d0bSJeff Roberson 		wakeup(&vmd->vmd_pageout_wanted);
226330fbfddaSJeff Roberson 		vm_domain_pageout_unlock(vmd);
2264e0c5a895SJohn Dyson 	}
2265e0c5a895SJohn Dyson }
2266