xref: /freebsd/sys/vm/vm_pageout.c (revision e8bcf6966bbe60f44cae155e729608e50a802b32)
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);
221*e8bcf696SMark 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);
245*e8bcf696SMark 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 
274*e8bcf696SMark 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) {
283*e8bcf696SMark 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 
337c7aebda8SAttilio Rao 	vm_page_assert_unbusied(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 		}
363fee2a2faSMark Johnston 		if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p) ||
364fee2a2faSMark Johnston 		    vm_page_wired(p)) {
36590ecac61SMatthew Dillon 			ib = 0;
36690ecac61SMatthew Dillon 			break;
367f6b04d2bSDavid Greenman 		}
36824a1cce3SDavid Greenman 		vm_page_test_dirty(p);
3691b5c869dSMark Johnston 		if (p->dirty == 0) {
370eb5d3969SAlan Cox 			ib = 0;
371eb5d3969SAlan Cox 			break;
372eb5d3969SAlan Cox 		}
373*e8bcf696SMark Johnston 		vm_page_lock(p);
374fee2a2faSMark Johnston 		if (!vm_page_in_laundry(p) || !vm_page_try_remove_write(p)) {
375*e8bcf696SMark Johnston 			vm_page_unlock(p);
37690ecac61SMatthew Dillon 			ib = 0;
37724a1cce3SDavid Greenman 			break;
378f6b04d2bSDavid Greenman 		}
379*e8bcf696SMark Johnston 		vm_page_unlock(p);
38091b4f427SAlan Cox 		mc[--page_base] = pb = p;
38190ecac61SMatthew Dillon 		++pageout_count;
38290ecac61SMatthew Dillon 		++ib;
383248fe642SAlan Cox 
38424a1cce3SDavid Greenman 		/*
385248fe642SAlan Cox 		 * We are at an alignment boundary.  Stop here, and switch
386248fe642SAlan Cox 		 * directions.  Do not clear ib.
38724a1cce3SDavid Greenman 		 */
38890ecac61SMatthew Dillon 		if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
38990ecac61SMatthew Dillon 			break;
39024a1cce3SDavid Greenman 	}
39190ecac61SMatthew Dillon 	while (pageout_count < vm_pageout_page_count &&
39290ecac61SMatthew Dillon 	    pindex + is < object->size) {
393fee2a2faSMark Johnston 		if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p) ||
394fee2a2faSMark Johnston 		    vm_page_wired(p))
39590ecac61SMatthew Dillon 			break;
39624a1cce3SDavid Greenman 		vm_page_test_dirty(p);
3971b5c869dSMark Johnston 		if (p->dirty == 0)
398eb5d3969SAlan Cox 			break;
399*e8bcf696SMark Johnston 		vm_page_lock(p);
400*e8bcf696SMark Johnston 		if (!vm_page_in_laundry(p) || !vm_page_try_remove_write(p)) {
401*e8bcf696SMark Johnston 			vm_page_unlock(p);
40224a1cce3SDavid Greenman 			break;
403*e8bcf696SMark Johnston 		}
404*e8bcf696SMark Johnston 		vm_page_unlock(p);
40591b4f427SAlan Cox 		mc[page_base + pageout_count] = ps = p;
40690ecac61SMatthew Dillon 		++pageout_count;
40790ecac61SMatthew Dillon 		++is;
40824a1cce3SDavid Greenman 	}
40990ecac61SMatthew Dillon 
41090ecac61SMatthew Dillon 	/*
41190ecac61SMatthew Dillon 	 * If we exhausted our forward scan, continue with the reverse scan
412248fe642SAlan Cox 	 * when possible, even past an alignment boundary.  This catches
413248fe642SAlan Cox 	 * boundary conditions.
41490ecac61SMatthew Dillon 	 */
415248fe642SAlan Cox 	if (ib != 0 && pageout_count < vm_pageout_page_count)
41690ecac61SMatthew Dillon 		goto more;
417f6b04d2bSDavid Greenman 
41899e6e193SMark Johnston 	return (vm_pageout_flush(&mc[page_base], pageout_count,
41999e6e193SMark Johnston 	    VM_PAGER_PUT_NOREUSE, 0, NULL, NULL));
420aef922f5SJohn Dyson }
421aef922f5SJohn Dyson 
4221c7c3c6aSMatthew Dillon /*
4231c7c3c6aSMatthew Dillon  * vm_pageout_flush() - launder the given pages
4241c7c3c6aSMatthew Dillon  *
4251c7c3c6aSMatthew Dillon  *	The given pages are laundered.  Note that we setup for the start of
4261c7c3c6aSMatthew Dillon  *	I/O ( i.e. busy the page ), mark it read-only, and bump the object
4271c7c3c6aSMatthew Dillon  *	reference count all in here rather then in the parent.  If we want
4281c7c3c6aSMatthew Dillon  *	the parent to do more sophisticated things we may have to change
4291c7c3c6aSMatthew Dillon  *	the ordering.
4301e8a675cSKonstantin Belousov  *
4311e8a675cSKonstantin Belousov  *	Returned runlen is the count of pages between mreq and first
4321e8a675cSKonstantin Belousov  *	page after mreq with status VM_PAGER_AGAIN.
433126d6082SKonstantin Belousov  *	*eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
434126d6082SKonstantin Belousov  *	for any page in runlen set.
4351c7c3c6aSMatthew Dillon  */
436aef922f5SJohn Dyson int
437126d6082SKonstantin Belousov vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
438126d6082SKonstantin Belousov     boolean_t *eio)
439aef922f5SJohn Dyson {
4402e3b314dSAlan Cox 	vm_object_t object = mc[0]->object;
441aef922f5SJohn Dyson 	int pageout_status[count];
44295461b45SJohn Dyson 	int numpagedout = 0;
4431e8a675cSKonstantin Belousov 	int i, runlen;
444aef922f5SJohn Dyson 
44589f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
4467bec141bSKip Macy 
4471c7c3c6aSMatthew Dillon 	/*
448aed9aaaaSMark Johnston 	 * Initiate I/O.  Mark the pages busy and verify that they're valid
449aed9aaaaSMark Johnston 	 * and read-only.
4501c7c3c6aSMatthew Dillon 	 *
4511c7c3c6aSMatthew Dillon 	 * We do not have to fixup the clean/dirty bits here... we can
4521c7c3c6aSMatthew Dillon 	 * allow the pager to do it after the I/O completes.
45302fa91d3SMatthew Dillon 	 *
45402fa91d3SMatthew Dillon 	 * NOTE! mc[i]->dirty may be partial or fragmented due to an
45502fa91d3SMatthew Dillon 	 * edge case with file fragments.
4561c7c3c6aSMatthew Dillon 	 */
4578f9110f6SJohn Dyson 	for (i = 0; i < count; i++) {
4587a935082SAlan Cox 		KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
4597a935082SAlan Cox 		    ("vm_pageout_flush: partially invalid page %p index %d/%d",
4607a935082SAlan Cox 			mc[i], i, count));
461*e8bcf696SMark Johnston 		KASSERT((mc[i]->aflags & PGA_WRITEABLE) == 0,
462aed9aaaaSMark Johnston 		    ("vm_pageout_flush: writeable page %p", mc[i]));
463c7aebda8SAttilio Rao 		vm_page_sbusy(mc[i]);
4642965a453SKip Macy 	}
465d474eaaaSDoug Rabson 	vm_object_pip_add(object, count);
466aef922f5SJohn Dyson 
467d076fbeaSAlan Cox 	vm_pager_put_pages(object, mc, count, flags, pageout_status);
46826f9a767SRodney W. Grimes 
4691e8a675cSKonstantin Belousov 	runlen = count - mreq;
470126d6082SKonstantin Belousov 	if (eio != NULL)
471126d6082SKonstantin Belousov 		*eio = FALSE;
472aef922f5SJohn Dyson 	for (i = 0; i < count; i++) {
473aef922f5SJohn Dyson 		vm_page_t mt = mc[i];
47424a1cce3SDavid Greenman 
4754cd45723SAlan Cox 		KASSERT(pageout_status[i] == VM_PAGER_PEND ||
4766031c68dSAlan Cox 		    !pmap_page_is_write_mapped(mt),
4779ea8d1a6SAlan Cox 		    ("vm_pageout_flush: page %p is not write protected", mt));
47826f9a767SRodney W. Grimes 		switch (pageout_status[i]) {
47926f9a767SRodney W. Grimes 		case VM_PAGER_OK:
480ebcddc72SAlan Cox 			vm_page_lock(mt);
481ebcddc72SAlan Cox 			if (vm_page_in_laundry(mt))
482ebcddc72SAlan Cox 				vm_page_deactivate_noreuse(mt);
483ebcddc72SAlan Cox 			vm_page_unlock(mt);
484ebcddc72SAlan Cox 			/* FALLTHROUGH */
48526f9a767SRodney W. Grimes 		case VM_PAGER_PEND:
48695461b45SJohn Dyson 			numpagedout++;
48726f9a767SRodney W. Grimes 			break;
48826f9a767SRodney W. Grimes 		case VM_PAGER_BAD:
48926f9a767SRodney W. Grimes 			/*
490ebcddc72SAlan Cox 			 * The page is outside the object's range.  We pretend
491ebcddc72SAlan Cox 			 * that the page out worked and clean the page, so the
492ebcddc72SAlan Cox 			 * changes will be lost if the page is reclaimed by
493ebcddc72SAlan Cox 			 * the page daemon.
49426f9a767SRodney W. Grimes 			 */
49590ecac61SMatthew Dillon 			vm_page_undirty(mt);
496ebcddc72SAlan Cox 			vm_page_lock(mt);
497ebcddc72SAlan Cox 			if (vm_page_in_laundry(mt))
498ebcddc72SAlan Cox 				vm_page_deactivate_noreuse(mt);
499ebcddc72SAlan Cox 			vm_page_unlock(mt);
50026f9a767SRodney W. Grimes 			break;
50126f9a767SRodney W. Grimes 		case VM_PAGER_ERROR:
50226f9a767SRodney W. Grimes 		case VM_PAGER_FAIL:
50326f9a767SRodney W. Grimes 			/*
504b1fd102eSMark Johnston 			 * If the page couldn't be paged out to swap because the
505b1fd102eSMark Johnston 			 * pager wasn't able to find space, place the page in
506b1fd102eSMark Johnston 			 * the PQ_UNSWAPPABLE holding queue.  This is an
507b1fd102eSMark Johnston 			 * optimization that prevents the page daemon from
508b1fd102eSMark Johnston 			 * wasting CPU cycles on pages that cannot be reclaimed
509b1fd102eSMark Johnston 			 * becase no swap device is configured.
510b1fd102eSMark Johnston 			 *
511b1fd102eSMark Johnston 			 * Otherwise, reactivate the page so that it doesn't
512b1fd102eSMark Johnston 			 * clog the laundry and inactive queues.  (We will try
513b1fd102eSMark Johnston 			 * paging it out again later.)
51426f9a767SRodney W. Grimes 			 */
5153c4a2440SAlan Cox 			vm_page_lock(mt);
516b1fd102eSMark Johnston 			if (object->type == OBJT_SWAP &&
517b1fd102eSMark Johnston 			    pageout_status[i] == VM_PAGER_FAIL) {
518b1fd102eSMark Johnston 				vm_page_unswappable(mt);
519b1fd102eSMark Johnston 				numpagedout++;
520b1fd102eSMark Johnston 			} else
52124a1cce3SDavid Greenman 				vm_page_activate(mt);
5223c4a2440SAlan Cox 			vm_page_unlock(mt);
523126d6082SKonstantin Belousov 			if (eio != NULL && i >= mreq && i - mreq < runlen)
524126d6082SKonstantin Belousov 				*eio = TRUE;
52526f9a767SRodney W. Grimes 			break;
52626f9a767SRodney W. Grimes 		case VM_PAGER_AGAIN:
5271e8a675cSKonstantin Belousov 			if (i >= mreq && i - mreq < runlen)
5281e8a675cSKonstantin Belousov 				runlen = i - mreq;
52926f9a767SRodney W. Grimes 			break;
53026f9a767SRodney W. Grimes 		}
53126f9a767SRodney W. Grimes 
53226f9a767SRodney W. Grimes 		/*
5330d94caffSDavid Greenman 		 * If the operation is still going, leave the page busy to
5340d94caffSDavid Greenman 		 * block all other accesses. Also, leave the paging in
5350d94caffSDavid Greenman 		 * progress indicator set so that we don't attempt an object
5360d94caffSDavid Greenman 		 * collapse.
53726f9a767SRodney W. Grimes 		 */
53826f9a767SRodney W. Grimes 		if (pageout_status[i] != VM_PAGER_PEND) {
539f919ebdeSDavid Greenman 			vm_object_pip_wakeup(object);
540c7aebda8SAttilio Rao 			vm_page_sunbusy(mt);
5413c4a2440SAlan Cox 		}
5423c4a2440SAlan Cox 	}
5431e8a675cSKonstantin Belousov 	if (prunlen != NULL)
5441e8a675cSKonstantin Belousov 		*prunlen = runlen;
5453c4a2440SAlan Cox 	return (numpagedout);
54626f9a767SRodney W. Grimes }
54726f9a767SRodney W. Grimes 
548b1fd102eSMark Johnston static void
549b1fd102eSMark Johnston vm_pageout_swapon(void *arg __unused, struct swdevt *sp __unused)
550b1fd102eSMark Johnston {
551b1fd102eSMark Johnston 
552b1fd102eSMark Johnston 	atomic_store_rel_int(&swapdev_enabled, 1);
553b1fd102eSMark Johnston }
554b1fd102eSMark Johnston 
555b1fd102eSMark Johnston static void
556b1fd102eSMark Johnston vm_pageout_swapoff(void *arg __unused, struct swdevt *sp __unused)
557b1fd102eSMark Johnston {
558b1fd102eSMark Johnston 
559b1fd102eSMark Johnston 	if (swap_pager_nswapdev() == 1)
560b1fd102eSMark Johnston 		atomic_store_rel_int(&swapdev_enabled, 0);
561b1fd102eSMark Johnston }
562b1fd102eSMark Johnston 
5631c7c3c6aSMatthew Dillon /*
56434d8b7eaSJeff Roberson  * Attempt to acquire all of the necessary locks to launder a page and
56534d8b7eaSJeff Roberson  * then call through the clustering layer to PUTPAGES.  Wait a short
56634d8b7eaSJeff Roberson  * time for a vnode lock.
56734d8b7eaSJeff Roberson  *
56834d8b7eaSJeff Roberson  * Requires the page and object lock on entry, releases both before return.
56934d8b7eaSJeff Roberson  * Returns 0 on success and an errno otherwise.
57034d8b7eaSJeff Roberson  */
57134d8b7eaSJeff Roberson static int
572ebcddc72SAlan Cox vm_pageout_clean(vm_page_t m, int *numpagedout)
57334d8b7eaSJeff Roberson {
57434d8b7eaSJeff Roberson 	struct vnode *vp;
57534d8b7eaSJeff Roberson 	struct mount *mp;
57634d8b7eaSJeff Roberson 	vm_object_t object;
57734d8b7eaSJeff Roberson 	vm_pindex_t pindex;
57834d8b7eaSJeff Roberson 	int error, lockmode;
57934d8b7eaSJeff Roberson 
580*e8bcf696SMark Johnston 	vm_page_assert_locked(m);
58134d8b7eaSJeff Roberson 	object = m->object;
58234d8b7eaSJeff Roberson 	VM_OBJECT_ASSERT_WLOCKED(object);
58334d8b7eaSJeff Roberson 	error = 0;
58434d8b7eaSJeff Roberson 	vp = NULL;
58534d8b7eaSJeff Roberson 	mp = NULL;
58634d8b7eaSJeff Roberson 
58734d8b7eaSJeff Roberson 	/*
58834d8b7eaSJeff Roberson 	 * The object is already known NOT to be dead.   It
58934d8b7eaSJeff Roberson 	 * is possible for the vget() to block the whole
59034d8b7eaSJeff Roberson 	 * pageout daemon, but the new low-memory handling
59134d8b7eaSJeff Roberson 	 * code should prevent it.
59234d8b7eaSJeff Roberson 	 *
59334d8b7eaSJeff Roberson 	 * We can't wait forever for the vnode lock, we might
59434d8b7eaSJeff Roberson 	 * deadlock due to a vn_read() getting stuck in
59534d8b7eaSJeff Roberson 	 * vm_wait while holding this vnode.  We skip the
59634d8b7eaSJeff Roberson 	 * vnode if we can't get it in a reasonable amount
59734d8b7eaSJeff Roberson 	 * of time.
59834d8b7eaSJeff Roberson 	 */
59934d8b7eaSJeff Roberson 	if (object->type == OBJT_VNODE) {
600*e8bcf696SMark Johnston 		vm_page_unlock(m);
60134d8b7eaSJeff Roberson 		vp = object->handle;
60234d8b7eaSJeff Roberson 		if (vp->v_type == VREG &&
60334d8b7eaSJeff Roberson 		    vn_start_write(vp, &mp, V_NOWAIT) != 0) {
60434d8b7eaSJeff Roberson 			mp = NULL;
60534d8b7eaSJeff Roberson 			error = EDEADLK;
60634d8b7eaSJeff Roberson 			goto unlock_all;
60734d8b7eaSJeff Roberson 		}
60834d8b7eaSJeff Roberson 		KASSERT(mp != NULL,
60934d8b7eaSJeff Roberson 		    ("vp %p with NULL v_mount", vp));
61034d8b7eaSJeff Roberson 		vm_object_reference_locked(object);
61134d8b7eaSJeff Roberson 		pindex = m->pindex;
61234d8b7eaSJeff Roberson 		VM_OBJECT_WUNLOCK(object);
61334d8b7eaSJeff Roberson 		lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
61434d8b7eaSJeff Roberson 		    LK_SHARED : LK_EXCLUSIVE;
61534d8b7eaSJeff Roberson 		if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
61634d8b7eaSJeff Roberson 			vp = NULL;
61734d8b7eaSJeff Roberson 			error = EDEADLK;
61834d8b7eaSJeff Roberson 			goto unlock_mp;
61934d8b7eaSJeff Roberson 		}
62034d8b7eaSJeff Roberson 		VM_OBJECT_WLOCK(object);
62157cd81a3SMark Johnston 
62257cd81a3SMark Johnston 		/*
62357cd81a3SMark Johnston 		 * Ensure that the object and vnode were not disassociated
62457cd81a3SMark Johnston 		 * while locks were dropped.
62557cd81a3SMark Johnston 		 */
62657cd81a3SMark Johnston 		if (vp->v_object != object) {
62757cd81a3SMark Johnston 			error = ENOENT;
62857cd81a3SMark Johnston 			goto unlock_all;
62957cd81a3SMark Johnston 		}
630*e8bcf696SMark Johnston 		vm_page_lock(m);
63157cd81a3SMark Johnston 
63234d8b7eaSJeff Roberson 		/*
63334d8b7eaSJeff Roberson 		 * While the object and page were unlocked, the page
63434d8b7eaSJeff Roberson 		 * may have been:
63534d8b7eaSJeff Roberson 		 * (1) moved to a different queue,
63634d8b7eaSJeff Roberson 		 * (2) reallocated to a different object,
63734d8b7eaSJeff Roberson 		 * (3) reallocated to a different offset, or
63834d8b7eaSJeff Roberson 		 * (4) cleaned.
63934d8b7eaSJeff Roberson 		 */
640ebcddc72SAlan Cox 		if (!vm_page_in_laundry(m) || m->object != object ||
64134d8b7eaSJeff Roberson 		    m->pindex != pindex || m->dirty == 0) {
64234d8b7eaSJeff Roberson 			vm_page_unlock(m);
64334d8b7eaSJeff Roberson 			error = ENXIO;
64434d8b7eaSJeff Roberson 			goto unlock_all;
64534d8b7eaSJeff Roberson 		}
64634d8b7eaSJeff Roberson 
64734d8b7eaSJeff Roberson 		/*
648fee2a2faSMark Johnston 		 * The page may have been busied while the object and page
649fee2a2faSMark Johnston 		 * locks were released.
65034d8b7eaSJeff Roberson 		 */
651fee2a2faSMark Johnston 		if (vm_page_busied(m)) {
65234d8b7eaSJeff Roberson 			vm_page_unlock(m);
65334d8b7eaSJeff Roberson 			error = EBUSY;
65434d8b7eaSJeff Roberson 			goto unlock_all;
65534d8b7eaSJeff Roberson 		}
65634d8b7eaSJeff Roberson 	}
65734d8b7eaSJeff Roberson 
65834d8b7eaSJeff Roberson 	/*
659fee2a2faSMark Johnston 	 * Remove all writeable mappings, failing if the page is wired.
660fee2a2faSMark Johnston 	 */
661fee2a2faSMark Johnston 	if (!vm_page_try_remove_write(m)) {
662fee2a2faSMark Johnston 		vm_page_unlock(m);
663fee2a2faSMark Johnston 		error = EBUSY;
664fee2a2faSMark Johnston 		goto unlock_all;
665fee2a2faSMark Johnston 	}
666*e8bcf696SMark Johnston 	vm_page_unlock(m);
667fee2a2faSMark Johnston 
668fee2a2faSMark Johnston 	/*
66934d8b7eaSJeff Roberson 	 * If a page is dirty, then it is either being washed
67034d8b7eaSJeff Roberson 	 * (but not yet cleaned) or it is still in the
67134d8b7eaSJeff Roberson 	 * laundry.  If it is still in the laundry, then we
67234d8b7eaSJeff Roberson 	 * start the cleaning operation.
67334d8b7eaSJeff Roberson 	 */
674ebcddc72SAlan Cox 	if ((*numpagedout = vm_pageout_cluster(m)) == 0)
67534d8b7eaSJeff Roberson 		error = EIO;
67634d8b7eaSJeff Roberson 
67734d8b7eaSJeff Roberson unlock_all:
67834d8b7eaSJeff Roberson 	VM_OBJECT_WUNLOCK(object);
67934d8b7eaSJeff Roberson 
68034d8b7eaSJeff Roberson unlock_mp:
68134d8b7eaSJeff Roberson 	vm_page_lock_assert(m, MA_NOTOWNED);
68234d8b7eaSJeff Roberson 	if (mp != NULL) {
68334d8b7eaSJeff Roberson 		if (vp != NULL)
68434d8b7eaSJeff Roberson 			vput(vp);
68534d8b7eaSJeff Roberson 		vm_object_deallocate(object);
68634d8b7eaSJeff Roberson 		vn_finished_write(mp);
68734d8b7eaSJeff Roberson 	}
68834d8b7eaSJeff Roberson 
68934d8b7eaSJeff Roberson 	return (error);
69034d8b7eaSJeff Roberson }
69134d8b7eaSJeff Roberson 
69234d8b7eaSJeff Roberson /*
693ebcddc72SAlan Cox  * Attempt to launder the specified number of pages.
694ebcddc72SAlan Cox  *
695ebcddc72SAlan Cox  * Returns the number of pages successfully laundered.
696ebcddc72SAlan Cox  */
697ebcddc72SAlan Cox static int
698ebcddc72SAlan Cox vm_pageout_launder(struct vm_domain *vmd, int launder, bool in_shortfall)
699ebcddc72SAlan Cox {
7005cd29d0fSMark Johnston 	struct scan_state ss;
701ebcddc72SAlan Cox 	struct vm_pagequeue *pq;
702*e8bcf696SMark Johnston 	struct mtx *mtx;
703ebcddc72SAlan Cox 	vm_object_t object;
7045cd29d0fSMark Johnston 	vm_page_t m, marker;
705*e8bcf696SMark Johnston 	int act_delta, error, numpagedout, queue, starting_target;
706ebcddc72SAlan Cox 	int vnodes_skipped;
70760256604SMark Johnston 	bool pageout_ok;
708ebcddc72SAlan Cox 
709*e8bcf696SMark Johnston 	mtx = NULL;
7105cd29d0fSMark Johnston 	object = NULL;
711ebcddc72SAlan Cox 	starting_target = launder;
712ebcddc72SAlan Cox 	vnodes_skipped = 0;
713ebcddc72SAlan Cox 
714ebcddc72SAlan Cox 	/*
715b1fd102eSMark Johnston 	 * Scan the laundry queues for pages eligible to be laundered.  We stop
716ebcddc72SAlan Cox 	 * once the target number of dirty pages have been laundered, or once
717ebcddc72SAlan Cox 	 * we've reached the end of the queue.  A single iteration of this loop
718ebcddc72SAlan Cox 	 * may cause more than one page to be laundered because of clustering.
719ebcddc72SAlan Cox 	 *
720b1fd102eSMark Johnston 	 * As an optimization, we avoid laundering from PQ_UNSWAPPABLE when no
721b1fd102eSMark Johnston 	 * swap devices are configured.
722ebcddc72SAlan Cox 	 */
723b1fd102eSMark Johnston 	if (atomic_load_acq_int(&swapdev_enabled))
72464b38930SMark Johnston 		queue = PQ_UNSWAPPABLE;
725b1fd102eSMark Johnston 	else
72664b38930SMark Johnston 		queue = PQ_LAUNDRY;
727ebcddc72SAlan Cox 
728b1fd102eSMark Johnston scan:
72964b38930SMark Johnston 	marker = &vmd->vmd_markers[queue];
7305cd29d0fSMark Johnston 	pq = &vmd->vmd_pagequeues[queue];
731ebcddc72SAlan Cox 	vm_pagequeue_lock(pq);
7325cd29d0fSMark Johnston 	vm_pageout_init_scan(&ss, pq, marker, NULL, pq->pq_cnt);
7335cd29d0fSMark Johnston 	while (launder > 0 && (m = vm_pageout_next(&ss, false)) != NULL) {
7345cd29d0fSMark Johnston 		if (__predict_false((m->flags & PG_MARKER) != 0))
735ebcddc72SAlan Cox 			continue;
7365cd29d0fSMark Johnston 
737*e8bcf696SMark Johnston 		vm_page_change_lock(m, &mtx);
738*e8bcf696SMark Johnston 
739*e8bcf696SMark Johnston recheck:
7405cd29d0fSMark Johnston 		/*
741*e8bcf696SMark Johnston 		 * The page may have been disassociated from the queue
742*e8bcf696SMark Johnston 		 * or even freed while locks were dropped.  We thus must be
743*e8bcf696SMark Johnston 		 * careful whenever modifying page state.  Once the object lock
744*e8bcf696SMark Johnston 		 * has been acquired, we have a stable reference to the page.
7455cd29d0fSMark Johnston 		 */
746*e8bcf696SMark Johnston 		if (vm_page_queue(m) != queue)
747ebcddc72SAlan Cox 			continue;
748*e8bcf696SMark Johnston 
749*e8bcf696SMark Johnston 		/*
750*e8bcf696SMark Johnston 		 * A requeue was requested, so this page gets a second
751*e8bcf696SMark Johnston 		 * chance.
752*e8bcf696SMark Johnston 		 */
753*e8bcf696SMark Johnston 		if ((m->aflags & PGA_REQUEUE) != 0) {
7547cdeaf33SMark Johnston 			vm_page_pqbatch_submit(m, queue);
755ebcddc72SAlan Cox 			continue;
756ebcddc72SAlan Cox 		}
757ebcddc72SAlan Cox 
758*e8bcf696SMark Johnston 		/*
759*e8bcf696SMark Johnston 		 * Wired pages may not be freed.  Complete their removal
760*e8bcf696SMark Johnston 		 * from the queue now to avoid needless revisits during
761*e8bcf696SMark Johnston 		 * future scans.  This check is racy and must be reverified once
762*e8bcf696SMark Johnston 		 * we hold the object lock and have verified that the page
763*e8bcf696SMark Johnston 		 * is not busy.
764*e8bcf696SMark Johnston 		 */
765*e8bcf696SMark Johnston 		if (vm_page_wired(m)) {
766*e8bcf696SMark Johnston 			vm_page_dequeue_deferred(m);
767*e8bcf696SMark Johnston 			continue;
768*e8bcf696SMark Johnston 		}
769*e8bcf696SMark Johnston 
7705cd29d0fSMark Johnston 		if (object != m->object) {
77160256604SMark Johnston 			if (object != NULL)
7725cd29d0fSMark Johnston 				VM_OBJECT_WUNLOCK(object);
773*e8bcf696SMark Johnston 
774*e8bcf696SMark Johnston 			/*
775*e8bcf696SMark Johnston 			 * A page's object pointer may be set to NULL before
776*e8bcf696SMark Johnston 			 * the object lock is acquired.
777*e8bcf696SMark Johnston 			 */
778fee2a2faSMark Johnston 			object = (vm_object_t)atomic_load_ptr(&m->object);
779*e8bcf696SMark Johnston 			if (object != NULL && !VM_OBJECT_TRYWLOCK(object)) {
780*e8bcf696SMark Johnston 				mtx_unlock(mtx);
781*e8bcf696SMark Johnston 				/* Depends on type-stability. */
78241fd4b94SMark Johnston 				VM_OBJECT_WLOCK(object);
783*e8bcf696SMark Johnston 				mtx_lock(mtx);
784*e8bcf696SMark Johnston 				goto recheck;
785*e8bcf696SMark Johnston 			}
786*e8bcf696SMark Johnston 		}
787*e8bcf696SMark Johnston 		if (__predict_false(m->object == NULL))
788*e8bcf696SMark Johnston 			/*
789*e8bcf696SMark Johnston 			 * The page has been removed from its object.
790*e8bcf696SMark Johnston 			 */
79141fd4b94SMark Johnston 			continue;
792*e8bcf696SMark Johnston 		KASSERT(m->object == object, ("page %p does not belong to %p",
793*e8bcf696SMark Johnston 		    m, object));
7945cd29d0fSMark Johnston 
7955cd29d0fSMark Johnston 		if (vm_page_busied(m))
7965cd29d0fSMark Johnston 			continue;
797ebcddc72SAlan Cox 
798ebcddc72SAlan Cox 		/*
799*e8bcf696SMark Johnston 		 * Re-check for wirings now that we hold the object lock and
800*e8bcf696SMark Johnston 		 * have verified that the page is unbusied.  If the page is
801*e8bcf696SMark Johnston 		 * mapped, it may still be wired by pmap lookups.  The call to
802fee2a2faSMark Johnston 		 * vm_page_try_remove_all() below atomically checks for such
803fee2a2faSMark Johnston 		 * wirings and removes mappings.  If the page is unmapped, the
804fee2a2faSMark Johnston 		 * wire count is guaranteed not to increase.
805fee2a2faSMark Johnston 		 */
806fee2a2faSMark Johnston 		if (__predict_false(vm_page_wired(m))) {
807*e8bcf696SMark Johnston 			vm_page_dequeue_deferred(m);
808fee2a2faSMark Johnston 			continue;
809fee2a2faSMark Johnston 		}
810fee2a2faSMark Johnston 
811fee2a2faSMark Johnston 		/*
812ebcddc72SAlan Cox 		 * Invalid pages can be easily freed.  They cannot be
813ebcddc72SAlan Cox 		 * mapped; vm_page_free() asserts this.
814ebcddc72SAlan Cox 		 */
815ebcddc72SAlan Cox 		if (m->valid == 0)
816ebcddc72SAlan Cox 			goto free_page;
817ebcddc72SAlan Cox 
818ebcddc72SAlan Cox 		/*
819ebcddc72SAlan Cox 		 * If the page has been referenced and the object is not dead,
820ebcddc72SAlan Cox 		 * reactivate or requeue the page depending on whether the
821ebcddc72SAlan Cox 		 * object is mapped.
822d7aeb429SAlan Cox 		 *
823d7aeb429SAlan Cox 		 * Test PGA_REFERENCED after calling pmap_ts_referenced() so
824d7aeb429SAlan Cox 		 * that a reference from a concurrently destroyed mapping is
825d7aeb429SAlan Cox 		 * observed here and now.
826ebcddc72SAlan Cox 		 */
827*e8bcf696SMark Johnston 		if (object->ref_count != 0)
828*e8bcf696SMark Johnston 			act_delta = pmap_ts_referenced(m);
829*e8bcf696SMark Johnston 		else {
830*e8bcf696SMark Johnston 			KASSERT(!pmap_page_is_mapped(m),
831*e8bcf696SMark Johnston 			    ("page %p is mapped", m));
832*e8bcf696SMark Johnston 			act_delta = 0;
833d7aeb429SAlan Cox 		}
834*e8bcf696SMark Johnston 		if ((m->aflags & PGA_REFERENCED) != 0) {
835*e8bcf696SMark Johnston 			vm_page_aflag_clear(m, PGA_REFERENCED);
836d7aeb429SAlan Cox 			act_delta++;
837ebcddc72SAlan Cox 		}
838ebcddc72SAlan Cox 		if (act_delta != 0) {
839ebcddc72SAlan Cox 			if (object->ref_count != 0) {
84041fd4b94SMark Johnston 				VM_CNT_INC(v_reactivated);
841*e8bcf696SMark Johnston 				vm_page_activate(m);
842ebcddc72SAlan Cox 
843ebcddc72SAlan Cox 				/*
844*e8bcf696SMark Johnston 				 * Increase the activation count if the page
845*e8bcf696SMark Johnston 				 * was referenced while in the laundry queue.
846*e8bcf696SMark Johnston 				 * This makes it less likely that the page will
847*e8bcf696SMark Johnston 				 * be returned prematurely to the inactive
848*e8bcf696SMark Johnston 				 * queue.
849*e8bcf696SMark Johnston  				 */
850*e8bcf696SMark Johnston 				m->act_count += act_delta + ACT_ADVANCE;
851*e8bcf696SMark Johnston 
852*e8bcf696SMark Johnston 				/*
853*e8bcf696SMark Johnston 				 * If this was a background laundering, count
854*e8bcf696SMark Johnston 				 * activated pages towards our target.  The
855*e8bcf696SMark Johnston 				 * purpose of background laundering is to ensure
856*e8bcf696SMark Johnston 				 * that pages are eventually cycled through the
857*e8bcf696SMark Johnston 				 * laundry queue, and an activation is a valid
858*e8bcf696SMark Johnston 				 * way out.
859ebcddc72SAlan Cox 				 */
860ebcddc72SAlan Cox 				if (!in_shortfall)
861ebcddc72SAlan Cox 					launder--;
862*e8bcf696SMark Johnston 				continue;
8635cd29d0fSMark Johnston 			} else if ((object->flags & OBJ_DEAD) == 0) {
864*e8bcf696SMark Johnston 				vm_page_requeue(m);
865*e8bcf696SMark Johnston 				continue;
8665cd29d0fSMark Johnston 			}
867ebcddc72SAlan Cox 		}
868ebcddc72SAlan Cox 
869ebcddc72SAlan Cox 		/*
870ebcddc72SAlan Cox 		 * If the page appears to be clean at the machine-independent
871ebcddc72SAlan Cox 		 * layer, then remove all of its mappings from the pmap in
872ebcddc72SAlan Cox 		 * anticipation of freeing it.  If, however, any of the page's
873ebcddc72SAlan Cox 		 * mappings allow write access, then the page may still be
874ebcddc72SAlan Cox 		 * modified until the last of those mappings are removed.
875ebcddc72SAlan Cox 		 */
876ebcddc72SAlan Cox 		if (object->ref_count != 0) {
877ebcddc72SAlan Cox 			vm_page_test_dirty(m);
878fee2a2faSMark Johnston 			if (m->dirty == 0 && !vm_page_try_remove_all(m)) {
879*e8bcf696SMark Johnston 				vm_page_dequeue_deferred(m);
880fee2a2faSMark Johnston 				continue;
881fee2a2faSMark Johnston 			}
882ebcddc72SAlan Cox 		}
883ebcddc72SAlan Cox 
884ebcddc72SAlan Cox 		/*
885ebcddc72SAlan Cox 		 * Clean pages are freed, and dirty pages are paged out unless
886ebcddc72SAlan Cox 		 * they belong to a dead object.  Requeueing dirty pages from
887ebcddc72SAlan Cox 		 * dead objects is pointless, as they are being paged out and
888ebcddc72SAlan Cox 		 * freed by the thread that destroyed the object.
889ebcddc72SAlan Cox 		 */
890ebcddc72SAlan Cox 		if (m->dirty == 0) {
891ebcddc72SAlan Cox free_page:
892ebcddc72SAlan Cox 			vm_page_free(m);
89383c9dea1SGleb Smirnoff 			VM_CNT_INC(v_dfree);
894ebcddc72SAlan Cox 		} else if ((object->flags & OBJ_DEAD) == 0) {
895ebcddc72SAlan Cox 			if (object->type != OBJT_SWAP &&
896ebcddc72SAlan Cox 			    object->type != OBJT_DEFAULT)
897ebcddc72SAlan Cox 				pageout_ok = true;
898ebcddc72SAlan Cox 			else if (disable_swap_pageouts)
899ebcddc72SAlan Cox 				pageout_ok = false;
900ebcddc72SAlan Cox 			else
901ebcddc72SAlan Cox 				pageout_ok = true;
902ebcddc72SAlan Cox 			if (!pageout_ok) {
903*e8bcf696SMark Johnston 				vm_page_requeue(m);
9045cd29d0fSMark Johnston 				continue;
905ebcddc72SAlan Cox 			}
906ebcddc72SAlan Cox 
907ebcddc72SAlan Cox 			/*
908ebcddc72SAlan Cox 			 * Form a cluster with adjacent, dirty pages from the
909ebcddc72SAlan Cox 			 * same object, and page out that entire cluster.
910ebcddc72SAlan Cox 			 *
911ebcddc72SAlan Cox 			 * The adjacent, dirty pages must also be in the
912ebcddc72SAlan Cox 			 * laundry.  However, their mappings are not checked
913ebcddc72SAlan Cox 			 * for new references.  Consequently, a recently
914ebcddc72SAlan Cox 			 * referenced page may be paged out.  However, that
915ebcddc72SAlan Cox 			 * page will not be prematurely reclaimed.  After page
916ebcddc72SAlan Cox 			 * out, the page will be placed in the inactive queue,
917ebcddc72SAlan Cox 			 * where any new references will be detected and the
918ebcddc72SAlan Cox 			 * page reactivated.
919ebcddc72SAlan Cox 			 */
920ebcddc72SAlan Cox 			error = vm_pageout_clean(m, &numpagedout);
921ebcddc72SAlan Cox 			if (error == 0) {
922ebcddc72SAlan Cox 				launder -= numpagedout;
9235cd29d0fSMark Johnston 				ss.scanned += numpagedout;
924ebcddc72SAlan Cox 			} else if (error == EDEADLK) {
925ebcddc72SAlan Cox 				pageout_lock_miss++;
926ebcddc72SAlan Cox 				vnodes_skipped++;
927ebcddc72SAlan Cox 			}
928*e8bcf696SMark Johnston 			mtx = NULL;
92960256604SMark Johnston 			object = NULL;
930ebcddc72SAlan Cox 		}
931*e8bcf696SMark Johnston 	}
932*e8bcf696SMark Johnston 	if (mtx != NULL) {
933*e8bcf696SMark Johnston 		mtx_unlock(mtx);
934*e8bcf696SMark Johnston 		mtx = NULL;
93546e39081SMark Johnston 	}
93646e39081SMark Johnston 	if (object != NULL) {
937ebcddc72SAlan Cox 		VM_OBJECT_WUNLOCK(object);
93846e39081SMark Johnston 		object = NULL;
93946e39081SMark Johnston 	}
940ebcddc72SAlan Cox 	vm_pagequeue_lock(pq);
9415cd29d0fSMark Johnston 	vm_pageout_end_scan(&ss);
942ebcddc72SAlan Cox 	vm_pagequeue_unlock(pq);
943ebcddc72SAlan Cox 
94464b38930SMark Johnston 	if (launder > 0 && queue == PQ_UNSWAPPABLE) {
94564b38930SMark Johnston 		queue = PQ_LAUNDRY;
946b1fd102eSMark Johnston 		goto scan;
947b1fd102eSMark Johnston 	}
948b1fd102eSMark Johnston 
949ebcddc72SAlan Cox 	/*
950ebcddc72SAlan Cox 	 * Wakeup the sync daemon if we skipped a vnode in a writeable object
951ebcddc72SAlan Cox 	 * and we didn't launder enough pages.
952ebcddc72SAlan Cox 	 */
953ebcddc72SAlan Cox 	if (vnodes_skipped > 0 && launder > 0)
954ebcddc72SAlan Cox 		(void)speedup_syncer();
955ebcddc72SAlan Cox 
956ebcddc72SAlan Cox 	return (starting_target - launder);
957ebcddc72SAlan Cox }
958ebcddc72SAlan Cox 
959ebcddc72SAlan Cox /*
960ebcddc72SAlan Cox  * Compute the integer square root.
961ebcddc72SAlan Cox  */
962ebcddc72SAlan Cox static u_int
963ebcddc72SAlan Cox isqrt(u_int num)
964ebcddc72SAlan Cox {
965ebcddc72SAlan Cox 	u_int bit, root, tmp;
966ebcddc72SAlan Cox 
96764f8d257SDoug Moore 	bit = num != 0 ? (1u << ((fls(num) - 1) & ~1)) : 0;
968ebcddc72SAlan Cox 	root = 0;
969ebcddc72SAlan Cox 	while (bit != 0) {
970ebcddc72SAlan Cox 		tmp = root + bit;
971ebcddc72SAlan Cox 		root >>= 1;
972ebcddc72SAlan Cox 		if (num >= tmp) {
973ebcddc72SAlan Cox 			num -= tmp;
974ebcddc72SAlan Cox 			root += bit;
975ebcddc72SAlan Cox 		}
976ebcddc72SAlan Cox 		bit >>= 2;
977ebcddc72SAlan Cox 	}
978ebcddc72SAlan Cox 	return (root);
979ebcddc72SAlan Cox }
980ebcddc72SAlan Cox 
981ebcddc72SAlan Cox /*
982ebcddc72SAlan Cox  * Perform the work of the laundry thread: periodically wake up and determine
983ebcddc72SAlan Cox  * whether any pages need to be laundered.  If so, determine the number of pages
984ebcddc72SAlan Cox  * that need to be laundered, and launder them.
985ebcddc72SAlan Cox  */
986ebcddc72SAlan Cox static void
987ebcddc72SAlan Cox vm_pageout_laundry_worker(void *arg)
988ebcddc72SAlan Cox {
989e2068d0bSJeff Roberson 	struct vm_domain *vmd;
990ebcddc72SAlan Cox 	struct vm_pagequeue *pq;
99160684862SMark Johnston 	uint64_t nclean, ndirty, nfreed;
992e2068d0bSJeff Roberson 	int domain, last_target, launder, shortfall, shortfall_cycle, target;
993ebcddc72SAlan Cox 	bool in_shortfall;
994ebcddc72SAlan Cox 
995e2068d0bSJeff Roberson 	domain = (uintptr_t)arg;
996e2068d0bSJeff Roberson 	vmd = VM_DOMAIN(domain);
997e2068d0bSJeff Roberson 	pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
998e2068d0bSJeff Roberson 	KASSERT(vmd->vmd_segs != 0, ("domain without segments"));
999ebcddc72SAlan Cox 
1000ebcddc72SAlan Cox 	shortfall = 0;
1001ebcddc72SAlan Cox 	in_shortfall = false;
1002ebcddc72SAlan Cox 	shortfall_cycle = 0;
10038002c3a4SMark Johnston 	last_target = target = 0;
100460684862SMark Johnston 	nfreed = 0;
1005ebcddc72SAlan Cox 
1006ebcddc72SAlan Cox 	/*
1007b1fd102eSMark Johnston 	 * Calls to these handlers are serialized by the swap syscall lock.
1008b1fd102eSMark Johnston 	 */
1009e2068d0bSJeff Roberson 	(void)EVENTHANDLER_REGISTER(swapon, vm_pageout_swapon, vmd,
1010b1fd102eSMark Johnston 	    EVENTHANDLER_PRI_ANY);
1011e2068d0bSJeff Roberson 	(void)EVENTHANDLER_REGISTER(swapoff, vm_pageout_swapoff, vmd,
1012b1fd102eSMark Johnston 	    EVENTHANDLER_PRI_ANY);
1013b1fd102eSMark Johnston 
1014b1fd102eSMark Johnston 	/*
1015ebcddc72SAlan Cox 	 * The pageout laundry worker is never done, so loop forever.
1016ebcddc72SAlan Cox 	 */
1017ebcddc72SAlan Cox 	for (;;) {
1018ebcddc72SAlan Cox 		KASSERT(target >= 0, ("negative target %d", target));
1019ebcddc72SAlan Cox 		KASSERT(shortfall_cycle >= 0,
1020ebcddc72SAlan Cox 		    ("negative cycle %d", shortfall_cycle));
1021ebcddc72SAlan Cox 		launder = 0;
1022ebcddc72SAlan Cox 
1023ebcddc72SAlan Cox 		/*
1024ebcddc72SAlan Cox 		 * First determine whether we need to launder pages to meet a
1025ebcddc72SAlan Cox 		 * shortage of free pages.
1026ebcddc72SAlan Cox 		 */
1027ebcddc72SAlan Cox 		if (shortfall > 0) {
1028ebcddc72SAlan Cox 			in_shortfall = true;
1029ebcddc72SAlan Cox 			shortfall_cycle = VM_LAUNDER_RATE / VM_INACT_SCAN_RATE;
1030ebcddc72SAlan Cox 			target = shortfall;
1031ebcddc72SAlan Cox 		} else if (!in_shortfall)
1032ebcddc72SAlan Cox 			goto trybackground;
1033e2068d0bSJeff Roberson 		else if (shortfall_cycle == 0 || vm_laundry_target(vmd) <= 0) {
1034ebcddc72SAlan Cox 			/*
1035ebcddc72SAlan Cox 			 * We recently entered shortfall and began laundering
1036ebcddc72SAlan Cox 			 * pages.  If we have completed that laundering run
1037ebcddc72SAlan Cox 			 * (and we are no longer in shortfall) or we have met
1038ebcddc72SAlan Cox 			 * our laundry target through other activity, then we
1039ebcddc72SAlan Cox 			 * can stop laundering pages.
1040ebcddc72SAlan Cox 			 */
1041ebcddc72SAlan Cox 			in_shortfall = false;
1042ebcddc72SAlan Cox 			target = 0;
1043ebcddc72SAlan Cox 			goto trybackground;
1044ebcddc72SAlan Cox 		}
1045ebcddc72SAlan Cox 		launder = target / shortfall_cycle--;
1046ebcddc72SAlan Cox 		goto dolaundry;
1047ebcddc72SAlan Cox 
1048ebcddc72SAlan Cox 		/*
1049ebcddc72SAlan Cox 		 * There's no immediate need to launder any pages; see if we
1050ebcddc72SAlan Cox 		 * meet the conditions to perform background laundering:
1051ebcddc72SAlan Cox 		 *
1052ebcddc72SAlan Cox 		 * 1. The ratio of dirty to clean inactive pages exceeds the
105360684862SMark Johnston 		 *    background laundering threshold, or
1054ebcddc72SAlan Cox 		 * 2. we haven't yet reached the target of the current
1055ebcddc72SAlan Cox 		 *    background laundering run.
1056ebcddc72SAlan Cox 		 *
1057ebcddc72SAlan Cox 		 * The background laundering threshold is not a constant.
1058ebcddc72SAlan Cox 		 * Instead, it is a slowly growing function of the number of
105960684862SMark Johnston 		 * clean pages freed by the page daemon since the last
106060684862SMark Johnston 		 * background laundering.  Thus, as the ratio of dirty to
106160684862SMark Johnston 		 * clean inactive pages grows, the amount of memory pressure
1062c098768eSMark Johnston 		 * required to trigger laundering decreases.  We ensure
1063c098768eSMark Johnston 		 * that the threshold is non-zero after an inactive queue
1064c098768eSMark Johnston 		 * scan, even if that scan failed to free a single clean page.
1065ebcddc72SAlan Cox 		 */
1066ebcddc72SAlan Cox trybackground:
1067e2068d0bSJeff Roberson 		nclean = vmd->vmd_free_count +
1068e2068d0bSJeff Roberson 		    vmd->vmd_pagequeues[PQ_INACTIVE].pq_cnt;
1069e2068d0bSJeff Roberson 		ndirty = vmd->vmd_pagequeues[PQ_LAUNDRY].pq_cnt;
1070c098768eSMark Johnston 		if (target == 0 && ndirty * isqrt(howmany(nfreed + 1,
1071c098768eSMark Johnston 		    vmd->vmd_free_target - vmd->vmd_free_min)) >= nclean) {
1072e2068d0bSJeff Roberson 			target = vmd->vmd_background_launder_target;
1073ebcddc72SAlan Cox 		}
1074ebcddc72SAlan Cox 
1075ebcddc72SAlan Cox 		/*
1076ebcddc72SAlan Cox 		 * We have a non-zero background laundering target.  If we've
1077ebcddc72SAlan Cox 		 * laundered up to our maximum without observing a page daemon
1078cb35676eSMark Johnston 		 * request, just stop.  This is a safety belt that ensures we
1079ebcddc72SAlan Cox 		 * don't launder an excessive amount if memory pressure is low
1080ebcddc72SAlan Cox 		 * and the ratio of dirty to clean pages is large.  Otherwise,
1081ebcddc72SAlan Cox 		 * proceed at the background laundering rate.
1082ebcddc72SAlan Cox 		 */
1083ebcddc72SAlan Cox 		if (target > 0) {
108460684862SMark Johnston 			if (nfreed > 0) {
108560684862SMark Johnston 				nfreed = 0;
1086ebcddc72SAlan Cox 				last_target = target;
1087ebcddc72SAlan Cox 			} else if (last_target - target >=
1088ebcddc72SAlan Cox 			    vm_background_launder_max * PAGE_SIZE / 1024) {
1089ebcddc72SAlan Cox 				target = 0;
1090ebcddc72SAlan Cox 			}
1091ebcddc72SAlan Cox 			launder = vm_background_launder_rate * PAGE_SIZE / 1024;
1092ebcddc72SAlan Cox 			launder /= VM_LAUNDER_RATE;
1093ebcddc72SAlan Cox 			if (launder > target)
1094ebcddc72SAlan Cox 				launder = target;
1095ebcddc72SAlan Cox 		}
1096ebcddc72SAlan Cox 
1097ebcddc72SAlan Cox dolaundry:
1098ebcddc72SAlan Cox 		if (launder > 0) {
1099ebcddc72SAlan Cox 			/*
1100ebcddc72SAlan Cox 			 * Because of I/O clustering, the number of laundered
1101ebcddc72SAlan Cox 			 * pages could exceed "target" by the maximum size of
1102ebcddc72SAlan Cox 			 * a cluster minus one.
1103ebcddc72SAlan Cox 			 */
1104e2068d0bSJeff Roberson 			target -= min(vm_pageout_launder(vmd, launder,
1105ebcddc72SAlan Cox 			    in_shortfall), target);
1106ebcddc72SAlan Cox 			pause("laundp", hz / VM_LAUNDER_RATE);
1107ebcddc72SAlan Cox 		}
1108ebcddc72SAlan Cox 
1109ebcddc72SAlan Cox 		/*
1110ebcddc72SAlan Cox 		 * If we're not currently laundering pages and the page daemon
1111ebcddc72SAlan Cox 		 * hasn't posted a new request, sleep until the page daemon
1112ebcddc72SAlan Cox 		 * kicks us.
1113ebcddc72SAlan Cox 		 */
1114ebcddc72SAlan Cox 		vm_pagequeue_lock(pq);
1115e2068d0bSJeff Roberson 		if (target == 0 && vmd->vmd_laundry_request == VM_LAUNDRY_IDLE)
1116e2068d0bSJeff Roberson 			(void)mtx_sleep(&vmd->vmd_laundry_request,
1117ebcddc72SAlan Cox 			    vm_pagequeue_lockptr(pq), PVM, "launds", 0);
1118ebcddc72SAlan Cox 
1119ebcddc72SAlan Cox 		/*
1120ebcddc72SAlan Cox 		 * If the pagedaemon has indicated that it's in shortfall, start
1121ebcddc72SAlan Cox 		 * a shortfall laundering unless we're already in the middle of
1122ebcddc72SAlan Cox 		 * one.  This may preempt a background laundering.
1123ebcddc72SAlan Cox 		 */
1124e2068d0bSJeff Roberson 		if (vmd->vmd_laundry_request == VM_LAUNDRY_SHORTFALL &&
1125ebcddc72SAlan Cox 		    (!in_shortfall || shortfall_cycle == 0)) {
1126e2068d0bSJeff Roberson 			shortfall = vm_laundry_target(vmd) +
1127e2068d0bSJeff Roberson 			    vmd->vmd_pageout_deficit;
1128ebcddc72SAlan Cox 			target = 0;
1129ebcddc72SAlan Cox 		} else
1130ebcddc72SAlan Cox 			shortfall = 0;
1131ebcddc72SAlan Cox 
1132ebcddc72SAlan Cox 		if (target == 0)
1133e2068d0bSJeff Roberson 			vmd->vmd_laundry_request = VM_LAUNDRY_IDLE;
113460684862SMark Johnston 		nfreed += vmd->vmd_clean_pages_freed;
113560684862SMark Johnston 		vmd->vmd_clean_pages_freed = 0;
1136ebcddc72SAlan Cox 		vm_pagequeue_unlock(pq);
1137ebcddc72SAlan Cox 	}
1138ebcddc72SAlan Cox }
1139ebcddc72SAlan Cox 
1140be37ee79SMark Johnston /*
1141be37ee79SMark Johnston  * Compute the number of pages we want to try to move from the
1142be37ee79SMark Johnston  * active queue to either the inactive or laundry queue.
1143be37ee79SMark Johnston  *
11447bb4634eSMark Johnston  * When scanning active pages during a shortage, we make clean pages
11457bb4634eSMark Johnston  * count more heavily towards the page shortage than dirty pages.
11467bb4634eSMark Johnston  * This is because dirty pages must be laundered before they can be
11477bb4634eSMark Johnston  * reused and thus have less utility when attempting to quickly
11487bb4634eSMark Johnston  * alleviate a free page shortage.  However, this weighting also
11497bb4634eSMark Johnston  * causes the scan to deactivate dirty pages more aggressively,
11507bb4634eSMark Johnston  * improving the effectiveness of clustering.
1151be37ee79SMark Johnston  */
1152be37ee79SMark Johnston static int
11537bb4634eSMark Johnston vm_pageout_active_target(struct vm_domain *vmd)
1154be37ee79SMark Johnston {
1155be37ee79SMark Johnston 	int shortage;
1156be37ee79SMark Johnston 
1157be37ee79SMark Johnston 	shortage = vmd->vmd_inactive_target + vm_paging_target(vmd) -
1158be37ee79SMark Johnston 	    (vmd->vmd_pagequeues[PQ_INACTIVE].pq_cnt +
1159be37ee79SMark Johnston 	    vmd->vmd_pagequeues[PQ_LAUNDRY].pq_cnt / act_scan_laundry_weight);
1160be37ee79SMark Johnston 	shortage *= act_scan_laundry_weight;
1161be37ee79SMark Johnston 	return (shortage);
1162be37ee79SMark Johnston }
1163be37ee79SMark Johnston 
1164be37ee79SMark Johnston /*
1165be37ee79SMark Johnston  * Scan the active queue.  If there is no shortage of inactive pages, scan a
1166be37ee79SMark Johnston  * small portion of the queue in order to maintain quasi-LRU.
1167be37ee79SMark Johnston  */
1168be37ee79SMark Johnston static void
1169be37ee79SMark Johnston vm_pageout_scan_active(struct vm_domain *vmd, int page_shortage)
1170be37ee79SMark Johnston {
1171be37ee79SMark Johnston 	struct scan_state ss;
1172*e8bcf696SMark Johnston 	struct mtx *mtx;
1173fee2a2faSMark Johnston 	vm_object_t object;
1174be37ee79SMark Johnston 	vm_page_t m, marker;
1175be37ee79SMark Johnston 	struct vm_pagequeue *pq;
1176be37ee79SMark Johnston 	long min_scan;
1177*e8bcf696SMark Johnston 	int act_delta, max_scan, scan_tick;
1178be37ee79SMark Johnston 
1179be37ee79SMark Johnston 	marker = &vmd->vmd_markers[PQ_ACTIVE];
1180be37ee79SMark Johnston 	pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1181be37ee79SMark Johnston 	vm_pagequeue_lock(pq);
1182be37ee79SMark Johnston 
1183be37ee79SMark Johnston 	/*
1184be37ee79SMark Johnston 	 * If we're just idle polling attempt to visit every
1185be37ee79SMark Johnston 	 * active page within 'update_period' seconds.
1186be37ee79SMark Johnston 	 */
1187be37ee79SMark Johnston 	scan_tick = ticks;
1188be37ee79SMark Johnston 	if (vm_pageout_update_period != 0) {
1189be37ee79SMark Johnston 		min_scan = pq->pq_cnt;
1190be37ee79SMark Johnston 		min_scan *= scan_tick - vmd->vmd_last_active_scan;
1191be37ee79SMark Johnston 		min_scan /= hz * vm_pageout_update_period;
1192be37ee79SMark Johnston 	} else
1193be37ee79SMark Johnston 		min_scan = 0;
1194be37ee79SMark Johnston 	if (min_scan > 0 || (page_shortage > 0 && pq->pq_cnt > 0))
1195be37ee79SMark Johnston 		vmd->vmd_last_active_scan = scan_tick;
1196be37ee79SMark Johnston 
1197be37ee79SMark Johnston 	/*
1198be37ee79SMark Johnston 	 * Scan the active queue for pages that can be deactivated.  Update
1199be37ee79SMark Johnston 	 * the per-page activity counter and use it to identify deactivation
1200be37ee79SMark Johnston 	 * candidates.  Held pages may be deactivated.
1201be37ee79SMark Johnston 	 *
1202be37ee79SMark Johnston 	 * To avoid requeuing each page that remains in the active queue, we
12037bb4634eSMark Johnston 	 * implement the CLOCK algorithm.  To keep the implementation of the
12047bb4634eSMark Johnston 	 * enqueue operation consistent for all page queues, we use two hands,
12057bb4634eSMark Johnston 	 * represented by marker pages. Scans begin at the first hand, which
12067bb4634eSMark Johnston 	 * precedes the second hand in the queue.  When the two hands meet,
12077bb4634eSMark Johnston 	 * they are moved back to the head and tail of the queue, respectively,
12087bb4634eSMark Johnston 	 * and scanning resumes.
1209be37ee79SMark Johnston 	 */
1210be37ee79SMark Johnston 	max_scan = page_shortage > 0 ? pq->pq_cnt : min_scan;
1211*e8bcf696SMark Johnston 	mtx = NULL;
1212be37ee79SMark Johnston act_scan:
1213be37ee79SMark Johnston 	vm_pageout_init_scan(&ss, pq, marker, &vmd->vmd_clock[0], max_scan);
1214be37ee79SMark Johnston 	while ((m = vm_pageout_next(&ss, false)) != NULL) {
1215be37ee79SMark Johnston 		if (__predict_false(m == &vmd->vmd_clock[1])) {
1216be37ee79SMark Johnston 			vm_pagequeue_lock(pq);
1217be37ee79SMark Johnston 			TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_clock[0], plinks.q);
1218be37ee79SMark Johnston 			TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_clock[1], plinks.q);
1219be37ee79SMark Johnston 			TAILQ_INSERT_HEAD(&pq->pq_pl, &vmd->vmd_clock[0],
1220be37ee79SMark Johnston 			    plinks.q);
1221be37ee79SMark Johnston 			TAILQ_INSERT_TAIL(&pq->pq_pl, &vmd->vmd_clock[1],
1222be37ee79SMark Johnston 			    plinks.q);
1223be37ee79SMark Johnston 			max_scan -= ss.scanned;
1224be37ee79SMark Johnston 			vm_pageout_end_scan(&ss);
1225be37ee79SMark Johnston 			goto act_scan;
1226be37ee79SMark Johnston 		}
1227be37ee79SMark Johnston 		if (__predict_false((m->flags & PG_MARKER) != 0))
1228be37ee79SMark Johnston 			continue;
1229be37ee79SMark Johnston 
1230*e8bcf696SMark Johnston 		vm_page_change_lock(m, &mtx);
1231*e8bcf696SMark Johnston 
1232*e8bcf696SMark Johnston 		/*
1233*e8bcf696SMark Johnston 		 * The page may have been disassociated from the queue
1234*e8bcf696SMark Johnston 		 * or even freed while locks were dropped.  We thus must be
1235*e8bcf696SMark Johnston 		 * careful whenever modifying page state.  Once the object lock
1236*e8bcf696SMark Johnston 		 * has been acquired, we have a stable reference to the page.
1237*e8bcf696SMark Johnston 		 */
1238*e8bcf696SMark Johnston 		if (vm_page_queue(m) != PQ_ACTIVE)
1239*e8bcf696SMark Johnston 			continue;
1240*e8bcf696SMark Johnston 
1241*e8bcf696SMark Johnston 		/*
1242*e8bcf696SMark Johnston 		 * Wired pages are dequeued lazily.
1243*e8bcf696SMark Johnston 		 */
1244*e8bcf696SMark Johnston 		if (vm_page_wired(m)) {
1245*e8bcf696SMark Johnston 			vm_page_dequeue_deferred(m);
1246*e8bcf696SMark Johnston 			continue;
1247*e8bcf696SMark Johnston 		}
1248*e8bcf696SMark Johnston 
1249*e8bcf696SMark Johnston 		/*
1250*e8bcf696SMark Johnston 		 * A page's object pointer may be set to NULL before
1251*e8bcf696SMark Johnston 		 * the object lock is acquired.
1252*e8bcf696SMark Johnston 		 */
1253fee2a2faSMark Johnston 		object = (vm_object_t)atomic_load_ptr(&m->object);
1254fee2a2faSMark Johnston 		if (__predict_false(object == NULL))
1255fee2a2faSMark Johnston 			/*
1256fee2a2faSMark Johnston 			 * The page has been removed from its object.
1257fee2a2faSMark Johnston 			 */
1258fee2a2faSMark Johnston 			continue;
1259fee2a2faSMark Johnston 
1260fee2a2faSMark Johnston 		/*
1261be37ee79SMark Johnston 		 * Check to see "how much" the page has been used.
1262d7aeb429SAlan Cox 		 *
1263d7aeb429SAlan Cox 		 * Test PGA_REFERENCED after calling pmap_ts_referenced() so
1264d7aeb429SAlan Cox 		 * that a reference from a concurrently destroyed mapping is
1265d7aeb429SAlan Cox 		 * observed here and now.
1266d7aeb429SAlan Cox 		 *
1267*e8bcf696SMark Johnston 		 * Perform an unsynchronized object ref count check.  While
1268*e8bcf696SMark Johnston 		 * the page lock ensures that the page is not reallocated to
1269*e8bcf696SMark Johnston 		 * another object, in particular, one with unmanaged mappings
1270*e8bcf696SMark Johnston 		 * that cannot support pmap_ts_referenced(), two races are,
1271be37ee79SMark Johnston 		 * nonetheless, possible:
1272be37ee79SMark Johnston 		 * 1) The count was transitioning to zero, but we saw a non-
1273*e8bcf696SMark Johnston 		 *    zero value.  pmap_ts_referenced() will return zero
1274*e8bcf696SMark Johnston 		 *    because the page is not mapped.
1275*e8bcf696SMark Johnston 		 * 2) The count was transitioning to one, but we saw zero.
1276*e8bcf696SMark Johnston 		 *    This race delays the detection of a new reference.  At
1277*e8bcf696SMark Johnston 		 *    worst, we will deactivate and reactivate the page.
1278be37ee79SMark Johnston 		 */
1279*e8bcf696SMark Johnston 		if (object->ref_count != 0)
1280*e8bcf696SMark Johnston 			act_delta = pmap_ts_referenced(m);
1281*e8bcf696SMark Johnston 		else
1282*e8bcf696SMark Johnston 			act_delta = 0;
1283*e8bcf696SMark Johnston 		if ((m->aflags & PGA_REFERENCED) != 0) {
1284*e8bcf696SMark Johnston 			vm_page_aflag_clear(m, PGA_REFERENCED);
1285d7aeb429SAlan Cox 			act_delta++;
1286d7aeb429SAlan Cox 		}
1287be37ee79SMark Johnston 
1288be37ee79SMark Johnston 		/*
1289be37ee79SMark Johnston 		 * Advance or decay the act_count based on recent usage.
1290be37ee79SMark Johnston 		 */
1291be37ee79SMark Johnston 		if (act_delta != 0) {
1292*e8bcf696SMark Johnston 			m->act_count += ACT_ADVANCE + act_delta;
1293*e8bcf696SMark Johnston 			if (m->act_count > ACT_MAX)
1294*e8bcf696SMark Johnston 				m->act_count = ACT_MAX;
1295*e8bcf696SMark Johnston 		} else
1296*e8bcf696SMark Johnston 			m->act_count -= min(m->act_count, ACT_DECLINE);
1297be37ee79SMark Johnston 
1298*e8bcf696SMark Johnston 		if (m->act_count == 0) {
1299be37ee79SMark Johnston 			/*
1300*e8bcf696SMark Johnston 			 * When not short for inactive pages, let dirty pages go
1301*e8bcf696SMark Johnston 			 * through the inactive queue before moving to the
1302*e8bcf696SMark Johnston 			 * laundry queues.  This gives them some extra time to
1303*e8bcf696SMark Johnston 			 * be reactivated, potentially avoiding an expensive
1304*e8bcf696SMark Johnston 			 * pageout.  However, during a page shortage, the
1305*e8bcf696SMark Johnston 			 * inactive queue is necessarily small, and so dirty
1306*e8bcf696SMark Johnston 			 * pages would only spend a trivial amount of time in
1307*e8bcf696SMark Johnston 			 * the inactive queue.  Therefore, we might as well
1308*e8bcf696SMark Johnston 			 * place them directly in the laundry queue to reduce
1309*e8bcf696SMark Johnston 			 * queuing overhead.
1310be37ee79SMark Johnston 			 */
1311*e8bcf696SMark Johnston 			if (page_shortage <= 0) {
1312*e8bcf696SMark Johnston 				vm_page_swapqueue(m, PQ_ACTIVE, PQ_INACTIVE);
13137cdeaf33SMark Johnston 			} else {
1314be37ee79SMark Johnston 				/*
1315be37ee79SMark Johnston 				 * Calling vm_page_test_dirty() here would
1316be37ee79SMark Johnston 				 * require acquisition of the object's write
1317be37ee79SMark Johnston 				 * lock.  However, during a page shortage,
1318*e8bcf696SMark Johnston 				 * directing dirty pages into the laundry
1319*e8bcf696SMark Johnston 				 * queue is only an optimization and not a
1320be37ee79SMark Johnston 				 * requirement.  Therefore, we simply rely on
1321*e8bcf696SMark Johnston 				 * the opportunistic updates to the page's
1322*e8bcf696SMark Johnston 				 * dirty field by the pmap.
1323be37ee79SMark Johnston 				 */
1324*e8bcf696SMark Johnston 				if (m->dirty == 0) {
1325*e8bcf696SMark Johnston 					vm_page_swapqueue(m, PQ_ACTIVE,
1326*e8bcf696SMark Johnston 					    PQ_INACTIVE);
1327*e8bcf696SMark Johnston 					page_shortage -=
1328*e8bcf696SMark Johnston 					    act_scan_laundry_weight;
1329be37ee79SMark Johnston 				} else {
1330*e8bcf696SMark Johnston 					vm_page_swapqueue(m, PQ_ACTIVE,
1331*e8bcf696SMark Johnston 					    PQ_LAUNDRY);
1332*e8bcf696SMark Johnston 					page_shortage--;
1333be37ee79SMark Johnston 				}
1334be37ee79SMark Johnston 			}
1335be37ee79SMark Johnston 		}
1336be37ee79SMark Johnston 	}
1337*e8bcf696SMark Johnston 	if (mtx != NULL) {
1338*e8bcf696SMark Johnston 		mtx_unlock(mtx);
1339*e8bcf696SMark Johnston 		mtx = NULL;
1340*e8bcf696SMark Johnston 	}
1341be37ee79SMark Johnston 	vm_pagequeue_lock(pq);
1342be37ee79SMark Johnston 	TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_clock[0], plinks.q);
1343be37ee79SMark Johnston 	TAILQ_INSERT_AFTER(&pq->pq_pl, marker, &vmd->vmd_clock[0], plinks.q);
1344be37ee79SMark Johnston 	vm_pageout_end_scan(&ss);
1345be37ee79SMark Johnston 	vm_pagequeue_unlock(pq);
1346be37ee79SMark Johnston }
1347be37ee79SMark Johnston 
13485cd29d0fSMark Johnston static int
13495cd29d0fSMark Johnston vm_pageout_reinsert_inactive_page(struct scan_state *ss, vm_page_t m)
13505cd29d0fSMark Johnston {
13515cd29d0fSMark Johnston 	struct vm_domain *vmd;
13525cd29d0fSMark Johnston 
1353*e8bcf696SMark Johnston 	if (m->queue != PQ_INACTIVE || (m->aflags & PGA_ENQUEUED) != 0)
1354*e8bcf696SMark Johnston 		return (0);
1355*e8bcf696SMark Johnston 	vm_page_aflag_set(m, PGA_ENQUEUED);
1356*e8bcf696SMark Johnston 	if ((m->aflags & PGA_REQUEUE_HEAD) != 0) {
13575cd29d0fSMark Johnston 		vmd = vm_pagequeue_domain(m);
13585cd29d0fSMark Johnston 		TAILQ_INSERT_BEFORE(&vmd->vmd_inacthead, m, plinks.q);
1359*e8bcf696SMark Johnston 		vm_page_aflag_clear(m, PGA_REQUEUE | PGA_REQUEUE_HEAD);
1360*e8bcf696SMark Johnston 	} else if ((m->aflags & PGA_REQUEUE) != 0) {
13615cd29d0fSMark Johnston 		TAILQ_INSERT_TAIL(&ss->pq->pq_pl, m, plinks.q);
1362*e8bcf696SMark Johnston 		vm_page_aflag_clear(m, PGA_REQUEUE | PGA_REQUEUE_HEAD);
1363*e8bcf696SMark Johnston 	} else
13645cd29d0fSMark Johnston 		TAILQ_INSERT_BEFORE(ss->marker, m, plinks.q);
13655cd29d0fSMark Johnston 	return (1);
13665cd29d0fSMark Johnston }
13675cd29d0fSMark Johnston 
13685cd29d0fSMark Johnston /*
13695cd29d0fSMark Johnston  * Re-add stuck pages to the inactive queue.  We will examine them again
13705cd29d0fSMark Johnston  * during the next scan.  If the queue state of a page has changed since
13715cd29d0fSMark Johnston  * it was physically removed from the page queue in
13725cd29d0fSMark Johnston  * vm_pageout_collect_batch(), don't do anything with that page.
13735cd29d0fSMark Johnston  */
13745cd29d0fSMark Johnston static void
13755cd29d0fSMark Johnston vm_pageout_reinsert_inactive(struct scan_state *ss, struct vm_batchqueue *bq,
13765cd29d0fSMark Johnston     vm_page_t m)
13775cd29d0fSMark Johnston {
13785cd29d0fSMark Johnston 	struct vm_pagequeue *pq;
13795cd29d0fSMark Johnston 	int delta;
13805cd29d0fSMark Johnston 
13815cd29d0fSMark Johnston 	delta = 0;
13825cd29d0fSMark Johnston 	pq = ss->pq;
13835cd29d0fSMark Johnston 
13845cd29d0fSMark Johnston 	if (m != NULL) {
13855cd29d0fSMark Johnston 		if (vm_batchqueue_insert(bq, m))
13865cd29d0fSMark Johnston 			return;
13875cd29d0fSMark Johnston 		vm_pagequeue_lock(pq);
13885cd29d0fSMark Johnston 		delta += vm_pageout_reinsert_inactive_page(ss, m);
13895cd29d0fSMark Johnston 	} else
13905cd29d0fSMark Johnston 		vm_pagequeue_lock(pq);
13915cd29d0fSMark Johnston 	while ((m = vm_batchqueue_pop(bq)) != NULL)
13925cd29d0fSMark Johnston 		delta += vm_pageout_reinsert_inactive_page(ss, m);
13935cd29d0fSMark Johnston 	vm_pagequeue_cnt_add(pq, delta);
13945cd29d0fSMark Johnston 	vm_pagequeue_unlock(pq);
13955cd29d0fSMark Johnston 	vm_batchqueue_init(bq);
13965cd29d0fSMark Johnston }
13975cd29d0fSMark Johnston 
1398ebcddc72SAlan Cox /*
139927e29d10SMark Johnston  * Attempt to reclaim the requested number of pages from the inactive queue.
140027e29d10SMark Johnston  * Returns true if the shortage was addressed.
1401df8bae1dSRodney W. Grimes  */
1402be37ee79SMark Johnston static int
140349a3710cSMark Johnston vm_pageout_scan_inactive(struct vm_domain *vmd, int shortage,
1404be37ee79SMark Johnston     int *addl_shortage)
1405df8bae1dSRodney W. Grimes {
14065cd29d0fSMark Johnston 	struct scan_state ss;
14075cd29d0fSMark Johnston 	struct vm_batchqueue rq;
1408*e8bcf696SMark Johnston 	struct mtx *mtx;
14095cd29d0fSMark Johnston 	vm_page_t m, marker;
14108d220203SAlan Cox 	struct vm_pagequeue *pq;
1411df8bae1dSRodney W. Grimes 	vm_object_t object;
1412*e8bcf696SMark Johnston 	int act_delta, addl_page_shortage, deficit, page_shortage;
1413be37ee79SMark Johnston 	int starting_page_shortage;
14140d94caffSDavid Greenman 
1415df8bae1dSRodney W. Grimes 	/*
141601f04471SMark Johnston 	 * The addl_page_shortage is an estimate of the number of temporarily
1417311e34e2SKonstantin Belousov 	 * stuck pages in the inactive queue.  In other words, the
1418449c2e92SKonstantin Belousov 	 * number of pages from the inactive count that should be
1419311e34e2SKonstantin Belousov 	 * discounted in setting the target for the active queue scan.
1420311e34e2SKonstantin Belousov 	 */
14219099545aSAlan Cox 	addl_page_shortage = 0;
14229099545aSAlan Cox 
14231c7c3c6aSMatthew Dillon 	/*
142449a3710cSMark Johnston 	 * vmd_pageout_deficit counts the number of pages requested in
142549a3710cSMark Johnston 	 * allocations that failed because of a free page shortage.  We assume
142649a3710cSMark Johnston 	 * that the allocations will be reattempted and thus include the deficit
142749a3710cSMark Johnston 	 * in our scan target.
14281c7c3c6aSMatthew Dillon 	 */
1429e2068d0bSJeff Roberson 	deficit = atomic_readandclear_int(&vmd->vmd_pageout_deficit);
143049a3710cSMark Johnston 	starting_page_shortage = page_shortage = shortage + deficit;
14311c7c3c6aSMatthew Dillon 
1432*e8bcf696SMark Johnston 	mtx = NULL;
14335cd29d0fSMark Johnston 	object = NULL;
14345cd29d0fSMark Johnston 	vm_batchqueue_init(&rq);
14355cd29d0fSMark Johnston 
1436936524aaSMatthew Dillon 	/*
1437f095d1bbSAlan Cox 	 * Start scanning the inactive queue for pages that we can free.  The
1438f095d1bbSAlan Cox 	 * scan will stop when we reach the target or we have scanned the
1439f095d1bbSAlan Cox 	 * entire queue.  (Note that m->act_count is not used to make
1440f095d1bbSAlan Cox 	 * decisions for the inactive queue, only for the active queue.)
14418d220203SAlan Cox 	 */
144264b38930SMark Johnston 	marker = &vmd->vmd_markers[PQ_INACTIVE];
14435cd29d0fSMark Johnston 	pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
14448d220203SAlan Cox 	vm_pagequeue_lock(pq);
14455cd29d0fSMark Johnston 	vm_pageout_init_scan(&ss, pq, marker, NULL, pq->pq_cnt);
14465cd29d0fSMark Johnston 	while (page_shortage > 0 && (m = vm_pageout_next(&ss, true)) != NULL) {
14475cd29d0fSMark Johnston 		KASSERT((m->flags & PG_MARKER) == 0,
14485cd29d0fSMark Johnston 		    ("marker page %p was dequeued", m));
1449df8bae1dSRodney W. Grimes 
1450*e8bcf696SMark Johnston 		vm_page_change_lock(m, &mtx);
1451*e8bcf696SMark Johnston 
1452*e8bcf696SMark Johnston recheck:
1453936524aaSMatthew Dillon 		/*
1454*e8bcf696SMark Johnston 		 * The page may have been disassociated from the queue
1455*e8bcf696SMark Johnston 		 * or even freed while locks were dropped.  We thus must be
1456*e8bcf696SMark Johnston 		 * careful whenever modifying page state.  Once the object lock
1457*e8bcf696SMark Johnston 		 * has been acquired, we have a stable reference to the page.
1458936524aaSMatthew Dillon 		 */
1459*e8bcf696SMark Johnston 		if (vm_page_queue(m) != PQ_INACTIVE) {
1460*e8bcf696SMark Johnston 			addl_page_shortage++;
1461936524aaSMatthew Dillon 			continue;
1462*e8bcf696SMark Johnston 		}
1463*e8bcf696SMark Johnston 
1464*e8bcf696SMark Johnston 		/*
1465*e8bcf696SMark Johnston 		 * The page was re-enqueued after the page queue lock was
1466*e8bcf696SMark Johnston 		 * dropped, or a requeue was requested.  This page gets a second
1467*e8bcf696SMark Johnston 		 * chance.
1468*e8bcf696SMark Johnston 		 */
1469*e8bcf696SMark Johnston 		if ((m->aflags & (PGA_ENQUEUED | PGA_REQUEUE |
1470*e8bcf696SMark Johnston 		    PGA_REQUEUE_HEAD)) != 0)
1471*e8bcf696SMark Johnston 			goto reinsert;
1472*e8bcf696SMark Johnston 
1473*e8bcf696SMark Johnston 		/*
1474*e8bcf696SMark Johnston 		 * Wired pages may not be freed.  Complete their removal
1475*e8bcf696SMark Johnston 		 * from the queue now to avoid needless revisits during
1476*e8bcf696SMark Johnston 		 * future scans.  This check is racy and must be reverified once
1477*e8bcf696SMark Johnston 		 * we hold the object lock and have verified that the page
1478*e8bcf696SMark Johnston 		 * is not busy.
1479*e8bcf696SMark Johnston 		 */
1480*e8bcf696SMark Johnston 		if (vm_page_wired(m)) {
1481*e8bcf696SMark Johnston 			vm_page_dequeue_deferred(m);
14825cd29d0fSMark Johnston 			continue;
14835cd29d0fSMark Johnston 		}
14845cd29d0fSMark Johnston 
14855cd29d0fSMark Johnston 		if (object != m->object) {
148660256604SMark Johnston 			if (object != NULL)
14875cd29d0fSMark Johnston 				VM_OBJECT_WUNLOCK(object);
1488*e8bcf696SMark Johnston 
1489*e8bcf696SMark Johnston 			/*
1490*e8bcf696SMark Johnston 			 * A page's object pointer may be set to NULL before
1491*e8bcf696SMark Johnston 			 * the object lock is acquired.
1492*e8bcf696SMark Johnston 			 */
1493fee2a2faSMark Johnston 			object = (vm_object_t)atomic_load_ptr(&m->object);
1494*e8bcf696SMark Johnston 			if (object != NULL && !VM_OBJECT_TRYWLOCK(object)) {
1495*e8bcf696SMark Johnston 				mtx_unlock(mtx);
1496*e8bcf696SMark Johnston 				/* Depends on type-stability. */
149741fd4b94SMark Johnston 				VM_OBJECT_WLOCK(object);
1498*e8bcf696SMark Johnston 				mtx_lock(mtx);
1499*e8bcf696SMark Johnston 				goto recheck;
150041fd4b94SMark Johnston 			}
150141fd4b94SMark Johnston 		}
1502*e8bcf696SMark Johnston 		if (__predict_false(m->object == NULL))
1503*e8bcf696SMark Johnston 			/*
1504*e8bcf696SMark Johnston 			 * The page has been removed from its object.
1505*e8bcf696SMark Johnston 			 */
1506*e8bcf696SMark Johnston 			continue;
1507*e8bcf696SMark Johnston 		KASSERT(m->object == object, ("page %p does not belong to %p",
1508*e8bcf696SMark Johnston 		    m, object));
15095cd29d0fSMark Johnston 
1510a3aeedabSAlan Cox 		if (vm_page_busied(m)) {
1511a3aeedabSAlan Cox 			/*
1512a3aeedabSAlan Cox 			 * Don't mess with busy pages.  Leave them at
1513a3aeedabSAlan Cox 			 * the front of the queue.  Most likely, they
1514a3aeedabSAlan Cox 			 * are being paged out and will leave the
1515a3aeedabSAlan Cox 			 * queue shortly after the scan finishes.  So,
1516a3aeedabSAlan Cox 			 * they ought to be discounted from the
1517a3aeedabSAlan Cox 			 * inactive count.
1518a3aeedabSAlan Cox 			 */
1519a3aeedabSAlan Cox 			addl_page_shortage++;
15205cd29d0fSMark Johnston 			goto reinsert;
152126f9a767SRodney W. Grimes 		}
152248cc2fc7SKonstantin Belousov 
152348cc2fc7SKonstantin Belousov 		/*
1524*e8bcf696SMark Johnston 		 * Re-check for wirings now that we hold the object lock and
1525*e8bcf696SMark Johnston 		 * have verified that the page is unbusied.  If the page is
1526*e8bcf696SMark Johnston 		 * mapped, it may still be wired by pmap lookups.  The call to
1527fee2a2faSMark Johnston 		 * vm_page_try_remove_all() below atomically checks for such
1528fee2a2faSMark Johnston 		 * wirings and removes mappings.  If the page is unmapped, the
1529fee2a2faSMark Johnston 		 * wire count is guaranteed not to increase.
1530fee2a2faSMark Johnston 		 */
1531fee2a2faSMark Johnston 		if (__predict_false(vm_page_wired(m))) {
1532*e8bcf696SMark Johnston 			vm_page_dequeue_deferred(m);
1533fee2a2faSMark Johnston 			continue;
1534fee2a2faSMark Johnston 		}
1535fee2a2faSMark Johnston 
1536fee2a2faSMark Johnston 		/*
15378748f58cSKonstantin Belousov 		 * Invalid pages can be easily freed. They cannot be
15388748f58cSKonstantin Belousov 		 * mapped, vm_page_free() asserts this.
1539776f729cSKonstantin Belousov 		 */
15408748f58cSKonstantin Belousov 		if (m->valid == 0)
15418748f58cSKonstantin Belousov 			goto free_page;
1542776f729cSKonstantin Belousov 
1543776f729cSKonstantin Belousov 		/*
1544960810ccSAlan Cox 		 * If the page has been referenced and the object is not dead,
1545960810ccSAlan Cox 		 * reactivate or requeue the page depending on whether the
1546960810ccSAlan Cox 		 * object is mapped.
1547d7aeb429SAlan Cox 		 *
1548d7aeb429SAlan Cox 		 * Test PGA_REFERENCED after calling pmap_ts_referenced() so
1549d7aeb429SAlan Cox 		 * that a reference from a concurrently destroyed mapping is
1550d7aeb429SAlan Cox 		 * observed here and now.
15517e006499SJohn Dyson 		 */
1552*e8bcf696SMark Johnston 		if (object->ref_count != 0)
1553*e8bcf696SMark Johnston 			act_delta = pmap_ts_referenced(m);
1554*e8bcf696SMark Johnston 		else {
1555*e8bcf696SMark Johnston 			KASSERT(!pmap_page_is_mapped(m),
1556*e8bcf696SMark Johnston 			    ("page %p is mapped", m));
1557*e8bcf696SMark Johnston 			act_delta = 0;
1558d7aeb429SAlan Cox 		}
1559*e8bcf696SMark Johnston 		if ((m->aflags & PGA_REFERENCED) != 0) {
1560*e8bcf696SMark Johnston 			vm_page_aflag_clear(m, PGA_REFERENCED);
1561d7aeb429SAlan Cox 			act_delta++;
15622fe6e4d7SDavid Greenman 		}
1563bb7858eaSJeff Roberson 		if (act_delta != 0) {
156486fa2471SAlan Cox 			if (object->ref_count != 0) {
156541fd4b94SMark Johnston 				VM_CNT_INC(v_reactivated);
1566*e8bcf696SMark Johnston 				vm_page_activate(m);
1567*e8bcf696SMark Johnston 
1568*e8bcf696SMark Johnston 				/*
1569*e8bcf696SMark Johnston 				 * Increase the activation count if the page
1570*e8bcf696SMark Johnston 				 * was referenced while in the inactive queue.
1571*e8bcf696SMark Johnston 				 * This makes it less likely that the page will
1572*e8bcf696SMark Johnston 				 * be returned prematurely to the inactive
1573*e8bcf696SMark Johnston 				 * queue.
1574*e8bcf696SMark Johnston  				 */
1575*e8bcf696SMark Johnston 				m->act_count += act_delta + ACT_ADVANCE;
1576*e8bcf696SMark Johnston 				continue;
1577ebcddc72SAlan Cox 			} else if ((object->flags & OBJ_DEAD) == 0) {
15785cd29d0fSMark Johnston 				vm_page_aflag_set(m, PGA_REQUEUE);
15795cd29d0fSMark Johnston 				goto reinsert;
1580ebcddc72SAlan Cox 			}
1581960810ccSAlan Cox 		}
158267bf6868SJohn Dyson 
15837e006499SJohn Dyson 		/*
15849fc4739dSAlan Cox 		 * If the page appears to be clean at the machine-independent
15859fc4739dSAlan Cox 		 * layer, then remove all of its mappings from the pmap in
1586a766ffd0SAlan Cox 		 * anticipation of freeing it.  If, however, any of the page's
1587a766ffd0SAlan Cox 		 * mappings allow write access, then the page may still be
1588a766ffd0SAlan Cox 		 * modified until the last of those mappings are removed.
15897e006499SJohn Dyson 		 */
1590aa044135SAlan Cox 		if (object->ref_count != 0) {
15919fc4739dSAlan Cox 			vm_page_test_dirty(m);
1592fee2a2faSMark Johnston 			if (m->dirty == 0 && !vm_page_try_remove_all(m)) {
1593*e8bcf696SMark Johnston 				vm_page_dequeue_deferred(m);
1594fee2a2faSMark Johnston 				continue;
1595fee2a2faSMark Johnston 			}
1596aa044135SAlan Cox 		}
1597dcbcd518SBruce Evans 
15986989c456SAlan Cox 		/*
1599ebcddc72SAlan Cox 		 * Clean pages can be freed, but dirty pages must be sent back
1600ebcddc72SAlan Cox 		 * to the laundry, unless they belong to a dead object.
1601ebcddc72SAlan Cox 		 * Requeueing dirty pages from dead objects is pointless, as
1602ebcddc72SAlan Cox 		 * they are being paged out and freed by the thread that
1603ebcddc72SAlan Cox 		 * destroyed the object.
16046989c456SAlan Cox 		 */
1605ebcddc72SAlan Cox 		if (m->dirty == 0) {
16068748f58cSKonstantin Belousov free_page:
16075cd29d0fSMark Johnston 			/*
16085cd29d0fSMark Johnston 			 * Because we dequeued the page and have already
16095cd29d0fSMark Johnston 			 * checked for concurrent dequeue and enqueue
16105cd29d0fSMark Johnston 			 * requests, we can safely disassociate the page
16115cd29d0fSMark Johnston 			 * from the inactive queue.
16125cd29d0fSMark Johnston 			 */
1613*e8bcf696SMark Johnston 			KASSERT((m->aflags & PGA_QUEUE_STATE_MASK) == 0,
1614*e8bcf696SMark Johnston 			    ("page %p has queue state", m));
1615*e8bcf696SMark Johnston 			m->queue = PQ_NONE;
161678afdce6SAlan Cox 			vm_page_free(m);
16175cd29d0fSMark Johnston 			page_shortage--;
1618ebcddc72SAlan Cox 		} else if ((object->flags & OBJ_DEAD) == 0)
1619ebcddc72SAlan Cox 			vm_page_launder(m);
16205cd29d0fSMark Johnston 		continue;
16215cd29d0fSMark Johnston reinsert:
16225cd29d0fSMark Johnston 		vm_pageout_reinsert_inactive(&ss, &rq, m);
16235cd29d0fSMark Johnston 	}
1624*e8bcf696SMark Johnston 	if (mtx != NULL)
1625*e8bcf696SMark Johnston 		mtx_unlock(mtx);
162660256604SMark Johnston 	if (object != NULL)
162789f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
16285cd29d0fSMark Johnston 	vm_pageout_reinsert_inactive(&ss, &rq, NULL);
16295cd29d0fSMark Johnston 	vm_pageout_reinsert_inactive(&ss, &ss.bq, NULL);
16308d220203SAlan Cox 	vm_pagequeue_lock(pq);
16315cd29d0fSMark Johnston 	vm_pageout_end_scan(&ss);
16328d220203SAlan Cox 	vm_pagequeue_unlock(pq);
163326f9a767SRodney W. Grimes 
16345cd29d0fSMark Johnston 	VM_CNT_ADD(v_dfree, starting_page_shortage - page_shortage);
16355cd29d0fSMark Johnston 
1636ebcddc72SAlan Cox 	/*
1637ebcddc72SAlan Cox 	 * Wake up the laundry thread so that it can perform any needed
1638ebcddc72SAlan Cox 	 * laundering.  If we didn't meet our target, we're in shortfall and
1639b1fd102eSMark Johnston 	 * need to launder more aggressively.  If PQ_LAUNDRY is empty and no
1640b1fd102eSMark Johnston 	 * swap devices are configured, the laundry thread has no work to do, so
1641b1fd102eSMark Johnston 	 * don't bother waking it up.
1642cb35676eSMark Johnston 	 *
1643cb35676eSMark Johnston 	 * The laundry thread uses the number of inactive queue scans elapsed
1644cb35676eSMark Johnston 	 * since the last laundering to determine whether to launder again, so
1645cb35676eSMark Johnston 	 * keep count.
1646ebcddc72SAlan Cox 	 */
1647cb35676eSMark Johnston 	if (starting_page_shortage > 0) {
1648e2068d0bSJeff Roberson 		pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
1649ebcddc72SAlan Cox 		vm_pagequeue_lock(pq);
1650e2068d0bSJeff Roberson 		if (vmd->vmd_laundry_request == VM_LAUNDRY_IDLE &&
1651cb35676eSMark Johnston 		    (pq->pq_cnt > 0 || atomic_load_acq_int(&swapdev_enabled))) {
1652ebcddc72SAlan Cox 			if (page_shortage > 0) {
1653e2068d0bSJeff Roberson 				vmd->vmd_laundry_request = VM_LAUNDRY_SHORTFALL;
165483c9dea1SGleb Smirnoff 				VM_CNT_INC(v_pdshortfalls);
1655e2068d0bSJeff Roberson 			} else if (vmd->vmd_laundry_request !=
1656e2068d0bSJeff Roberson 			    VM_LAUNDRY_SHORTFALL)
1657e2068d0bSJeff Roberson 				vmd->vmd_laundry_request =
1658e2068d0bSJeff Roberson 				    VM_LAUNDRY_BACKGROUND;
1659e2068d0bSJeff Roberson 			wakeup(&vmd->vmd_laundry_request);
1660b1fd102eSMark Johnston 		}
166160684862SMark Johnston 		vmd->vmd_clean_pages_freed +=
166260684862SMark Johnston 		    starting_page_shortage - page_shortage;
1663ebcddc72SAlan Cox 		vm_pagequeue_unlock(pq);
1664ebcddc72SAlan Cox 	}
1665ebcddc72SAlan Cox 
16669452b5edSAlan Cox 	/*
1667f095d1bbSAlan Cox 	 * Wakeup the swapout daemon if we didn't free the targeted number of
1668f095d1bbSAlan Cox 	 * pages.
16699452b5edSAlan Cox 	 */
1670ac04195bSKonstantin Belousov 	if (page_shortage > 0)
1671ac04195bSKonstantin Belousov 		vm_swapout_run();
16729452b5edSAlan Cox 
16739452b5edSAlan Cox 	/*
167476386c7eSKonstantin Belousov 	 * If the inactive queue scan fails repeatedly to meet its
167576386c7eSKonstantin Belousov 	 * target, kill the largest process.
167676386c7eSKonstantin Belousov 	 */
167776386c7eSKonstantin Belousov 	vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
167876386c7eSKonstantin Belousov 
167976386c7eSKonstantin Belousov 	/*
1680be37ee79SMark Johnston 	 * Reclaim pages by swapping out idle processes, if configured to do so.
16811c7c3c6aSMatthew Dillon 	 */
1682ac04195bSKonstantin Belousov 	vm_swapout_run_idle();
1683be37ee79SMark Johnston 
1684be37ee79SMark Johnston 	/*
1685be37ee79SMark Johnston 	 * See the description of addl_page_shortage above.
1686be37ee79SMark Johnston 	 */
1687be37ee79SMark Johnston 	*addl_shortage = addl_page_shortage + deficit;
1688be37ee79SMark Johnston 
1689e57dd910SAlan Cox 	return (page_shortage <= 0);
16902025d69bSKonstantin Belousov }
16912025d69bSKonstantin Belousov 
1692449c2e92SKonstantin Belousov static int vm_pageout_oom_vote;
1693449c2e92SKonstantin Belousov 
1694449c2e92SKonstantin Belousov /*
1695449c2e92SKonstantin Belousov  * The pagedaemon threads randlomly select one to perform the
1696449c2e92SKonstantin Belousov  * OOM.  Trying to kill processes before all pagedaemons
1697449c2e92SKonstantin Belousov  * failed to reach free target is premature.
1698449c2e92SKonstantin Belousov  */
1699449c2e92SKonstantin Belousov static void
170076386c7eSKonstantin Belousov vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
170176386c7eSKonstantin Belousov     int starting_page_shortage)
1702449c2e92SKonstantin Belousov {
1703449c2e92SKonstantin Belousov 	int old_vote;
1704449c2e92SKonstantin Belousov 
170576386c7eSKonstantin Belousov 	if (starting_page_shortage <= 0 || starting_page_shortage !=
170676386c7eSKonstantin Belousov 	    page_shortage)
170776386c7eSKonstantin Belousov 		vmd->vmd_oom_seq = 0;
170876386c7eSKonstantin Belousov 	else
170976386c7eSKonstantin Belousov 		vmd->vmd_oom_seq++;
171076386c7eSKonstantin Belousov 	if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1711449c2e92SKonstantin Belousov 		if (vmd->vmd_oom) {
1712449c2e92SKonstantin Belousov 			vmd->vmd_oom = FALSE;
1713449c2e92SKonstantin Belousov 			atomic_subtract_int(&vm_pageout_oom_vote, 1);
1714449c2e92SKonstantin Belousov 		}
1715449c2e92SKonstantin Belousov 		return;
1716449c2e92SKonstantin Belousov 	}
1717449c2e92SKonstantin Belousov 
171876386c7eSKonstantin Belousov 	/*
171976386c7eSKonstantin Belousov 	 * Do not follow the call sequence until OOM condition is
172076386c7eSKonstantin Belousov 	 * cleared.
172176386c7eSKonstantin Belousov 	 */
172276386c7eSKonstantin Belousov 	vmd->vmd_oom_seq = 0;
172376386c7eSKonstantin Belousov 
1724449c2e92SKonstantin Belousov 	if (vmd->vmd_oom)
1725449c2e92SKonstantin Belousov 		return;
1726449c2e92SKonstantin Belousov 
1727449c2e92SKonstantin Belousov 	vmd->vmd_oom = TRUE;
1728449c2e92SKonstantin Belousov 	old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1729449c2e92SKonstantin Belousov 	if (old_vote != vm_ndomains - 1)
1730449c2e92SKonstantin Belousov 		return;
1731449c2e92SKonstantin Belousov 
1732449c2e92SKonstantin Belousov 	/*
1733449c2e92SKonstantin Belousov 	 * The current pagedaemon thread is the last in the quorum to
1734449c2e92SKonstantin Belousov 	 * start OOM.  Initiate the selection and signaling of the
1735449c2e92SKonstantin Belousov 	 * victim.
1736449c2e92SKonstantin Belousov 	 */
1737449c2e92SKonstantin Belousov 	vm_pageout_oom(VM_OOM_MEM);
1738449c2e92SKonstantin Belousov 
1739449c2e92SKonstantin Belousov 	/*
1740449c2e92SKonstantin Belousov 	 * After one round of OOM terror, recall our vote.  On the
1741449c2e92SKonstantin Belousov 	 * next pass, current pagedaemon would vote again if the low
1742449c2e92SKonstantin Belousov 	 * memory condition is still there, due to vmd_oom being
1743449c2e92SKonstantin Belousov 	 * false.
1744449c2e92SKonstantin Belousov 	 */
1745449c2e92SKonstantin Belousov 	vmd->vmd_oom = FALSE;
1746449c2e92SKonstantin Belousov 	atomic_subtract_int(&vm_pageout_oom_vote, 1);
1747449c2e92SKonstantin Belousov }
17482025d69bSKonstantin Belousov 
17493949873fSKonstantin Belousov /*
17503949873fSKonstantin Belousov  * The OOM killer is the page daemon's action of last resort when
17513949873fSKonstantin Belousov  * memory allocation requests have been stalled for a prolonged period
17523949873fSKonstantin Belousov  * of time because it cannot reclaim memory.  This function computes
17533949873fSKonstantin Belousov  * the approximate number of physical pages that could be reclaimed if
17543949873fSKonstantin Belousov  * the specified address space is destroyed.
17553949873fSKonstantin Belousov  *
17563949873fSKonstantin Belousov  * Private, anonymous memory owned by the address space is the
17573949873fSKonstantin Belousov  * principal resource that we expect to recover after an OOM kill.
17583949873fSKonstantin Belousov  * Since the physical pages mapped by the address space's COW entries
17593949873fSKonstantin Belousov  * are typically shared pages, they are unlikely to be released and so
17603949873fSKonstantin Belousov  * they are not counted.
17613949873fSKonstantin Belousov  *
17623949873fSKonstantin Belousov  * To get to the point where the page daemon runs the OOM killer, its
17633949873fSKonstantin Belousov  * efforts to write-back vnode-backed pages may have stalled.  This
17643949873fSKonstantin Belousov  * could be caused by a memory allocation deadlock in the write path
17653949873fSKonstantin Belousov  * that might be resolved by an OOM kill.  Therefore, physical pages
17663949873fSKonstantin Belousov  * belonging to vnode-backed objects are counted, because they might
17673949873fSKonstantin Belousov  * be freed without being written out first if the address space holds
17683949873fSKonstantin Belousov  * the last reference to an unlinked vnode.
17693949873fSKonstantin Belousov  *
17703949873fSKonstantin Belousov  * Similarly, physical pages belonging to OBJT_PHYS objects are
17713949873fSKonstantin Belousov  * counted because the address space might hold the last reference to
17723949873fSKonstantin Belousov  * the object.
17733949873fSKonstantin Belousov  */
17743949873fSKonstantin Belousov static long
17753949873fSKonstantin Belousov vm_pageout_oom_pagecount(struct vmspace *vmspace)
17763949873fSKonstantin Belousov {
17773949873fSKonstantin Belousov 	vm_map_t map;
17783949873fSKonstantin Belousov 	vm_map_entry_t entry;
17793949873fSKonstantin Belousov 	vm_object_t obj;
17803949873fSKonstantin Belousov 	long res;
17813949873fSKonstantin Belousov 
17823949873fSKonstantin Belousov 	map = &vmspace->vm_map;
17833949873fSKonstantin Belousov 	KASSERT(!map->system_map, ("system map"));
17843949873fSKonstantin Belousov 	sx_assert(&map->lock, SA_LOCKED);
17853949873fSKonstantin Belousov 	res = 0;
17863949873fSKonstantin Belousov 	for (entry = map->header.next; entry != &map->header;
17873949873fSKonstantin Belousov 	    entry = entry->next) {
17883949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
17893949873fSKonstantin Belousov 			continue;
17903949873fSKonstantin Belousov 		obj = entry->object.vm_object;
17913949873fSKonstantin Belousov 		if (obj == NULL)
17923949873fSKonstantin Belousov 			continue;
17933949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
17943949873fSKonstantin Belousov 		    obj->ref_count != 1)
17953949873fSKonstantin Belousov 			continue;
17963949873fSKonstantin Belousov 		switch (obj->type) {
17973949873fSKonstantin Belousov 		case OBJT_DEFAULT:
17983949873fSKonstantin Belousov 		case OBJT_SWAP:
17993949873fSKonstantin Belousov 		case OBJT_PHYS:
18003949873fSKonstantin Belousov 		case OBJT_VNODE:
18013949873fSKonstantin Belousov 			res += obj->resident_page_count;
18023949873fSKonstantin Belousov 			break;
18033949873fSKonstantin Belousov 		}
18043949873fSKonstantin Belousov 	}
18053949873fSKonstantin Belousov 	return (res);
18063949873fSKonstantin Belousov }
18073949873fSKonstantin Belousov 
1808245139c6SKonstantin Belousov static int vm_oom_ratelim_last;
1809245139c6SKonstantin Belousov static int vm_oom_pf_secs = 10;
1810245139c6SKonstantin Belousov SYSCTL_INT(_vm, OID_AUTO, oom_pf_secs, CTLFLAG_RWTUN, &vm_oom_pf_secs, 0,
1811245139c6SKonstantin Belousov     "");
1812245139c6SKonstantin Belousov static struct mtx vm_oom_ratelim_mtx;
1813245139c6SKonstantin Belousov 
18142025d69bSKonstantin Belousov void
18152025d69bSKonstantin Belousov vm_pageout_oom(int shortage)
18162025d69bSKonstantin Belousov {
18172025d69bSKonstantin Belousov 	struct proc *p, *bigproc;
18182025d69bSKonstantin Belousov 	vm_offset_t size, bigsize;
18192025d69bSKonstantin Belousov 	struct thread *td;
18206bed074cSKonstantin Belousov 	struct vmspace *vm;
1821245139c6SKonstantin Belousov 	int now;
18223e78e983SAlan Cox 	bool breakout;
18232025d69bSKonstantin Belousov 
18242025d69bSKonstantin Belousov 	/*
1825245139c6SKonstantin Belousov 	 * For OOM requests originating from vm_fault(), there is a high
1826245139c6SKonstantin Belousov 	 * chance that a single large process faults simultaneously in
1827245139c6SKonstantin Belousov 	 * several threads.  Also, on an active system running many
1828245139c6SKonstantin Belousov 	 * processes of middle-size, like buildworld, all of them
1829245139c6SKonstantin Belousov 	 * could fault almost simultaneously as well.
1830245139c6SKonstantin Belousov 	 *
1831245139c6SKonstantin Belousov 	 * To avoid killing too many processes, rate-limit OOMs
1832245139c6SKonstantin Belousov 	 * initiated by vm_fault() time-outs on the waits for free
1833245139c6SKonstantin Belousov 	 * pages.
1834245139c6SKonstantin Belousov 	 */
1835245139c6SKonstantin Belousov 	mtx_lock(&vm_oom_ratelim_mtx);
1836245139c6SKonstantin Belousov 	now = ticks;
1837245139c6SKonstantin Belousov 	if (shortage == VM_OOM_MEM_PF &&
1838245139c6SKonstantin Belousov 	    (u_int)(now - vm_oom_ratelim_last) < hz * vm_oom_pf_secs) {
1839245139c6SKonstantin Belousov 		mtx_unlock(&vm_oom_ratelim_mtx);
1840245139c6SKonstantin Belousov 		return;
1841245139c6SKonstantin Belousov 	}
1842245139c6SKonstantin Belousov 	vm_oom_ratelim_last = now;
1843245139c6SKonstantin Belousov 	mtx_unlock(&vm_oom_ratelim_mtx);
1844245139c6SKonstantin Belousov 
1845245139c6SKonstantin Belousov 	/*
18461c58e4e5SJohn Baldwin 	 * We keep the process bigproc locked once we find it to keep anyone
18471c58e4e5SJohn Baldwin 	 * from messing with it; however, there is a possibility of
184828323addSBryan Drewery 	 * deadlock if process B is bigproc and one of its child processes
18491c58e4e5SJohn Baldwin 	 * attempts to propagate a signal to B while we are waiting for A's
18501c58e4e5SJohn Baldwin 	 * lock while walking this list.  To avoid this, we don't block on
18511c58e4e5SJohn Baldwin 	 * the process lock but just skip a process if it is already locked.
18525663e6deSDavid Greenman 	 */
18535663e6deSDavid Greenman 	bigproc = NULL;
18545663e6deSDavid Greenman 	bigsize = 0;
18551005a129SJohn Baldwin 	sx_slock(&allproc_lock);
1856e602ba25SJulian Elischer 	FOREACH_PROC_IN_SYSTEM(p) {
185771943c3dSKonstantin Belousov 		PROC_LOCK(p);
185871943c3dSKonstantin Belousov 
18591c58e4e5SJohn Baldwin 		/*
18603f1c4c4fSKonstantin Belousov 		 * If this is a system, protected or killed process, skip it.
18615663e6deSDavid Greenman 		 */
186271943c3dSKonstantin Belousov 		if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
186371943c3dSKonstantin Belousov 		    P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
186471943c3dSKonstantin Belousov 		    p->p_pid == 1 || P_KILLED(p) ||
186571943c3dSKonstantin Belousov 		    (p->p_pid < 48 && swap_pager_avail != 0)) {
18668606d880SJohn Baldwin 			PROC_UNLOCK(p);
18675663e6deSDavid Greenman 			continue;
18685663e6deSDavid Greenman 		}
18695663e6deSDavid Greenman 		/*
1870dcbcd518SBruce Evans 		 * If the process is in a non-running type state,
1871e602ba25SJulian Elischer 		 * don't touch it.  Check all the threads individually.
18725663e6deSDavid Greenman 		 */
18733e78e983SAlan Cox 		breakout = false;
1874e602ba25SJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td) {
1875982d11f8SJeff Roberson 			thread_lock(td);
187671fad9fdSJulian Elischer 			if (!TD_ON_RUNQ(td) &&
187771fad9fdSJulian Elischer 			    !TD_IS_RUNNING(td) &&
1878f497cda2SEdward Tomasz Napierala 			    !TD_IS_SLEEPING(td) &&
1879b98acc0aSKonstantin Belousov 			    !TD_IS_SUSPENDED(td) &&
1880b98acc0aSKonstantin Belousov 			    !TD_IS_SWAPPED(td)) {
1881982d11f8SJeff Roberson 				thread_unlock(td);
18823e78e983SAlan Cox 				breakout = true;
1883e602ba25SJulian Elischer 				break;
1884e602ba25SJulian Elischer 			}
1885982d11f8SJeff Roberson 			thread_unlock(td);
1886e602ba25SJulian Elischer 		}
1887e602ba25SJulian Elischer 		if (breakout) {
18881c58e4e5SJohn Baldwin 			PROC_UNLOCK(p);
18895663e6deSDavid Greenman 			continue;
18905663e6deSDavid Greenman 		}
18915663e6deSDavid Greenman 		/*
18925663e6deSDavid Greenman 		 * get the process size
18935663e6deSDavid Greenman 		 */
18946bed074cSKonstantin Belousov 		vm = vmspace_acquire_ref(p);
18956bed074cSKonstantin Belousov 		if (vm == NULL) {
18966bed074cSKonstantin Belousov 			PROC_UNLOCK(p);
18976bed074cSKonstantin Belousov 			continue;
18986bed074cSKonstantin Belousov 		}
189995e2409aSKonstantin Belousov 		_PHOLD_LITE(p);
190072d97679SDavid Schultz 		PROC_UNLOCK(p);
190195e2409aSKonstantin Belousov 		sx_sunlock(&allproc_lock);
190295e2409aSKonstantin Belousov 		if (!vm_map_trylock_read(&vm->vm_map)) {
190371943c3dSKonstantin Belousov 			vmspace_free(vm);
190495e2409aSKonstantin Belousov 			sx_slock(&allproc_lock);
190595e2409aSKonstantin Belousov 			PRELE(p);
190672d97679SDavid Schultz 			continue;
190772d97679SDavid Schultz 		}
19087981aa24SKonstantin Belousov 		size = vmspace_swap_count(vm);
1909245139c6SKonstantin Belousov 		if (shortage == VM_OOM_MEM || shortage == VM_OOM_MEM_PF)
19103949873fSKonstantin Belousov 			size += vm_pageout_oom_pagecount(vm);
19113949873fSKonstantin Belousov 		vm_map_unlock_read(&vm->vm_map);
19126bed074cSKonstantin Belousov 		vmspace_free(vm);
191395e2409aSKonstantin Belousov 		sx_slock(&allproc_lock);
19143949873fSKonstantin Belousov 
19155663e6deSDavid Greenman 		/*
19163949873fSKonstantin Belousov 		 * If this process is bigger than the biggest one,
19175663e6deSDavid Greenman 		 * remember it.
19185663e6deSDavid Greenman 		 */
19195663e6deSDavid Greenman 		if (size > bigsize) {
19201c58e4e5SJohn Baldwin 			if (bigproc != NULL)
192171943c3dSKonstantin Belousov 				PRELE(bigproc);
19225663e6deSDavid Greenman 			bigproc = p;
19235663e6deSDavid Greenman 			bigsize = size;
192471943c3dSKonstantin Belousov 		} else {
192571943c3dSKonstantin Belousov 			PRELE(p);
192671943c3dSKonstantin Belousov 		}
19275663e6deSDavid Greenman 	}
19281005a129SJohn Baldwin 	sx_sunlock(&allproc_lock);
19295663e6deSDavid Greenman 	if (bigproc != NULL) {
19308311a2b8SWill Andrews 		if (vm_panic_on_oom != 0)
19318311a2b8SWill Andrews 			panic("out of swap space");
193271943c3dSKonstantin Belousov 		PROC_LOCK(bigproc);
1933729b1e51SDavid Greenman 		killproc(bigproc, "out of swap space");
1934fa885116SJulian Elischer 		sched_nice(bigproc, PRIO_MIN);
193571943c3dSKonstantin Belousov 		_PRELE(bigproc);
19361c58e4e5SJohn Baldwin 		PROC_UNLOCK(bigproc);
19375663e6deSDavid Greenman 	}
19385663e6deSDavid Greenman }
193926f9a767SRodney W. Grimes 
1940b50a4ea6SMark Johnston static bool
1941b50a4ea6SMark Johnston vm_pageout_lowmem(void)
194249a3710cSMark Johnston {
1943b50a4ea6SMark Johnston 	static int lowmem_ticks = 0;
1944b50a4ea6SMark Johnston 	int last;
194549a3710cSMark Johnston 
1946b50a4ea6SMark Johnston 	last = atomic_load_int(&lowmem_ticks);
1947b50a4ea6SMark Johnston 	while ((u_int)(ticks - last) / hz >= lowmem_period) {
1948b50a4ea6SMark Johnston 		if (atomic_fcmpset_int(&lowmem_ticks, &last, ticks) == 0)
1949b50a4ea6SMark Johnston 			continue;
1950b50a4ea6SMark Johnston 
195149a3710cSMark Johnston 		/*
195249a3710cSMark Johnston 		 * Decrease registered cache sizes.
195349a3710cSMark Johnston 		 */
195449a3710cSMark Johnston 		SDT_PROBE0(vm, , , vm__lowmem_scan);
195549a3710cSMark Johnston 		EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_PAGES);
195649a3710cSMark Johnston 
195749a3710cSMark Johnston 		/*
195849a3710cSMark Johnston 		 * We do this explicitly after the caches have been
195908cfa56eSMark Johnston 		 * drained above.  If we have a severe page shortage on
196008cfa56eSMark Johnston 		 * our hands, completely drain all UMA zones.  Otherwise,
196108cfa56eSMark Johnston 		 * just prune the caches.
196249a3710cSMark Johnston 		 */
196308cfa56eSMark Johnston 		uma_reclaim(vm_page_count_min() ? UMA_RECLAIM_DRAIN_CPU :
196408cfa56eSMark Johnston 		    UMA_RECLAIM_TRIM);
1965b50a4ea6SMark Johnston 		return (true);
196649a3710cSMark Johnston 	}
1967b50a4ea6SMark Johnston 	return (false);
196849a3710cSMark Johnston }
196949a3710cSMark Johnston 
197049a3710cSMark Johnston static void
1971449c2e92SKonstantin Belousov vm_pageout_worker(void *arg)
1972449c2e92SKonstantin Belousov {
1973e2068d0bSJeff Roberson 	struct vm_domain *vmd;
1974b50a4ea6SMark Johnston 	u_int ofree;
197549a3710cSMark Johnston 	int addl_shortage, domain, shortage;
1976e57dd910SAlan Cox 	bool target_met;
1977449c2e92SKonstantin Belousov 
1978e2068d0bSJeff Roberson 	domain = (uintptr_t)arg;
1979e2068d0bSJeff Roberson 	vmd = VM_DOMAIN(domain);
19805f8cd1c0SJeff Roberson 	shortage = 0;
1981e57dd910SAlan Cox 	target_met = true;
1982449c2e92SKonstantin Belousov 
1983449c2e92SKonstantin Belousov 	/*
1984949c9186SKonstantin Belousov 	 * XXXKIB It could be useful to bind pageout daemon threads to
1985949c9186SKonstantin Belousov 	 * the cores belonging to the domain, from which vm_page_array
1986949c9186SKonstantin Belousov 	 * is allocated.
1987449c2e92SKonstantin Belousov 	 */
1988449c2e92SKonstantin Belousov 
1989e2068d0bSJeff Roberson 	KASSERT(vmd->vmd_segs != 0, ("domain without segments"));
1990e2068d0bSJeff Roberson 	vmd->vmd_last_active_scan = ticks;
1991449c2e92SKonstantin Belousov 
1992449c2e92SKonstantin Belousov 	/*
1993449c2e92SKonstantin Belousov 	 * The pageout daemon worker is never done, so loop forever.
1994449c2e92SKonstantin Belousov 	 */
1995449c2e92SKonstantin Belousov 	while (TRUE) {
199630fbfddaSJeff Roberson 		vm_domain_pageout_lock(vmd);
199749a3710cSMark Johnston 
199830fbfddaSJeff Roberson 		/*
199930fbfddaSJeff Roberson 		 * We need to clear wanted before we check the limits.  This
200030fbfddaSJeff Roberson 		 * prevents races with wakers who will check wanted after they
200130fbfddaSJeff Roberson 		 * reach the limit.
200230fbfddaSJeff Roberson 		 */
200330fbfddaSJeff Roberson 		atomic_store_int(&vmd->vmd_pageout_wanted, 0);
200456ce0690SAlan Cox 
200556ce0690SAlan Cox 		/*
20065f8cd1c0SJeff Roberson 		 * Might the page daemon need to run again?
2007449c2e92SKonstantin Belousov 		 */
20085f8cd1c0SJeff Roberson 		if (vm_paging_needed(vmd, vmd->vmd_free_count)) {
200956ce0690SAlan Cox 			/*
201049a3710cSMark Johnston 			 * Yes.  If the scan failed to produce enough free
201149a3710cSMark Johnston 			 * pages, sleep uninterruptibly for some time in the
201249a3710cSMark Johnston 			 * hope that the laundry thread will clean some pages.
201356ce0690SAlan Cox 			 */
201430fbfddaSJeff Roberson 			vm_domain_pageout_unlock(vmd);
201549a3710cSMark Johnston 			if (!target_met)
20166eebec83SMark Johnston 				pause("pwait", hz / VM_INACT_SCAN_RATE);
2017449c2e92SKonstantin Belousov 		} else {
2018449c2e92SKonstantin Belousov 			/*
20195f8cd1c0SJeff Roberson 			 * No, sleep until the next wakeup or until pages
20205f8cd1c0SJeff Roberson 			 * need to have their reference stats updated.
2021449c2e92SKonstantin Belousov 			 */
20222c0f13aaSKonstantin Belousov 			if (mtx_sleep(&vmd->vmd_pageout_wanted,
202330fbfddaSJeff Roberson 			    vm_domain_pageout_lockptr(vmd), PDROP | PVM,
20245f8cd1c0SJeff Roberson 			    "psleep", hz / VM_INACT_SCAN_RATE) == 0)
202583c9dea1SGleb Smirnoff 				VM_CNT_INC(v_pdwakeups);
202656ce0690SAlan Cox 		}
2027be37ee79SMark Johnston 
202830fbfddaSJeff Roberson 		/* Prevent spurious wakeups by ensuring that wanted is set. */
202930fbfddaSJeff Roberson 		atomic_store_int(&vmd->vmd_pageout_wanted, 1);
203030fbfddaSJeff Roberson 
203130fbfddaSJeff Roberson 		/*
203230fbfddaSJeff Roberson 		 * Use the controller to calculate how many pages to free in
2033b50a4ea6SMark Johnston 		 * this interval, and scan the inactive queue.  If the lowmem
2034b50a4ea6SMark Johnston 		 * handlers appear to have freed up some pages, subtract the
2035b50a4ea6SMark Johnston 		 * difference from the inactive queue scan target.
203630fbfddaSJeff Roberson 		 */
20375f8cd1c0SJeff Roberson 		shortage = pidctrl_daemon(&vmd->vmd_pid, vmd->vmd_free_count);
203849a3710cSMark Johnston 		if (shortage > 0) {
2039b50a4ea6SMark Johnston 			ofree = vmd->vmd_free_count;
2040b50a4ea6SMark Johnston 			if (vm_pageout_lowmem() && vmd->vmd_free_count > ofree)
2041b50a4ea6SMark Johnston 				shortage -= min(vmd->vmd_free_count - ofree,
2042b50a4ea6SMark Johnston 				    (u_int)shortage);
204349a3710cSMark Johnston 			target_met = vm_pageout_scan_inactive(vmd, shortage,
2044be37ee79SMark Johnston 			    &addl_shortage);
204549a3710cSMark Johnston 		} else
204649a3710cSMark Johnston 			addl_shortage = 0;
204756ce0690SAlan Cox 
2048be37ee79SMark Johnston 		/*
2049be37ee79SMark Johnston 		 * Scan the active queue.  A positive value for shortage
2050be37ee79SMark Johnston 		 * indicates that we must aggressively deactivate pages to avoid
2051be37ee79SMark Johnston 		 * a shortfall.
2052be37ee79SMark Johnston 		 */
20537bb4634eSMark Johnston 		shortage = vm_pageout_active_target(vmd) + addl_shortage;
2054be37ee79SMark Johnston 		vm_pageout_scan_active(vmd, shortage);
2055449c2e92SKonstantin Belousov 	}
2056449c2e92SKonstantin Belousov }
2057449c2e92SKonstantin Belousov 
2058df8bae1dSRodney W. Grimes /*
20594d19f4adSSteven Hartland  *	vm_pageout_init initialises basic pageout daemon settings.
2060df8bae1dSRodney W. Grimes  */
20612b14f991SJulian Elischer static void
2062e2068d0bSJeff Roberson vm_pageout_init_domain(int domain)
2063df8bae1dSRodney W. Grimes {
2064e2068d0bSJeff Roberson 	struct vm_domain *vmd;
20655f8cd1c0SJeff Roberson 	struct sysctl_oid *oid;
2066e2068d0bSJeff Roberson 
2067e2068d0bSJeff Roberson 	vmd = VM_DOMAIN(domain);
2068e2068d0bSJeff Roberson 	vmd->vmd_interrupt_free_min = 2;
2069f6b04d2bSDavid Greenman 
207045ae1d91SAlan Cox 	/*
207145ae1d91SAlan Cox 	 * v_free_reserved needs to include enough for the largest
207245ae1d91SAlan Cox 	 * swap pager structures plus enough for any pv_entry structs
207345ae1d91SAlan Cox 	 * when paging.
207445ae1d91SAlan Cox 	 */
2075e2068d0bSJeff Roberson 	if (vmd->vmd_page_count > 1024)
2076e2068d0bSJeff Roberson 		vmd->vmd_free_min = 4 + (vmd->vmd_page_count - 1024) / 200;
20772feb50bfSAttilio Rao 	else
2078e2068d0bSJeff Roberson 		vmd->vmd_free_min = 4;
20790cab71bcSDoug Moore 	vmd->vmd_pageout_free_min = 2 * MAXBSIZE / PAGE_SIZE +
2080e2068d0bSJeff Roberson 	    vmd->vmd_interrupt_free_min;
2081e2068d0bSJeff Roberson 	vmd->vmd_free_reserved = vm_pageout_page_count +
2082e2068d0bSJeff Roberson 	    vmd->vmd_pageout_free_min + (vmd->vmd_page_count / 768);
2083e2068d0bSJeff Roberson 	vmd->vmd_free_severe = vmd->vmd_free_min / 2;
2084e2068d0bSJeff Roberson 	vmd->vmd_free_target = 4 * vmd->vmd_free_min + vmd->vmd_free_reserved;
2085e2068d0bSJeff Roberson 	vmd->vmd_free_min += vmd->vmd_free_reserved;
2086e2068d0bSJeff Roberson 	vmd->vmd_free_severe += vmd->vmd_free_reserved;
2087e2068d0bSJeff Roberson 	vmd->vmd_inactive_target = (3 * vmd->vmd_free_target) / 2;
2088e2068d0bSJeff Roberson 	if (vmd->vmd_inactive_target > vmd->vmd_free_count / 3)
2089e2068d0bSJeff Roberson 		vmd->vmd_inactive_target = vmd->vmd_free_count / 3;
2090df8bae1dSRodney W. Grimes 
2091d9e23210SJeff Roberson 	/*
20925f8cd1c0SJeff Roberson 	 * Set the default wakeup threshold to be 10% below the paging
20935f8cd1c0SJeff Roberson 	 * target.  This keeps the steady state out of shortfall.
2094d9e23210SJeff Roberson 	 */
20955f8cd1c0SJeff Roberson 	vmd->vmd_pageout_wakeup_thresh = (vmd->vmd_free_target / 10) * 9;
2096e2068d0bSJeff Roberson 
2097e2068d0bSJeff Roberson 	/*
2098e2068d0bSJeff Roberson 	 * Target amount of memory to move out of the laundry queue during a
2099e2068d0bSJeff Roberson 	 * background laundering.  This is proportional to the amount of system
2100e2068d0bSJeff Roberson 	 * memory.
2101e2068d0bSJeff Roberson 	 */
2102e2068d0bSJeff Roberson 	vmd->vmd_background_launder_target = (vmd->vmd_free_target -
2103e2068d0bSJeff Roberson 	    vmd->vmd_free_min) / 10;
21045f8cd1c0SJeff Roberson 
21055f8cd1c0SJeff Roberson 	/* Initialize the pageout daemon pid controller. */
21065f8cd1c0SJeff Roberson 	pidctrl_init(&vmd->vmd_pid, hz / VM_INACT_SCAN_RATE,
21075f8cd1c0SJeff Roberson 	    vmd->vmd_free_target, PIDCTRL_BOUND,
21085f8cd1c0SJeff Roberson 	    PIDCTRL_KPD, PIDCTRL_KID, PIDCTRL_KDD);
21095f8cd1c0SJeff Roberson 	oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(vmd->vmd_oid), OID_AUTO,
21105f8cd1c0SJeff Roberson 	    "pidctrl", CTLFLAG_RD, NULL, "");
21115f8cd1c0SJeff Roberson 	pidctrl_init_sysctl(&vmd->vmd_pid, SYSCTL_CHILDREN(oid));
2112e2068d0bSJeff Roberson }
2113e2068d0bSJeff Roberson 
2114e2068d0bSJeff Roberson static void
2115e2068d0bSJeff Roberson vm_pageout_init(void)
2116e2068d0bSJeff Roberson {
2117e2068d0bSJeff Roberson 	u_int freecount;
2118e2068d0bSJeff Roberson 	int i;
2119e2068d0bSJeff Roberson 
2120e2068d0bSJeff Roberson 	/*
2121e2068d0bSJeff Roberson 	 * Initialize some paging parameters.
2122e2068d0bSJeff Roberson 	 */
2123e2068d0bSJeff Roberson 	if (vm_cnt.v_page_count < 2000)
2124e2068d0bSJeff Roberson 		vm_pageout_page_count = 8;
2125e2068d0bSJeff Roberson 
2126e2068d0bSJeff Roberson 	freecount = 0;
2127e2068d0bSJeff Roberson 	for (i = 0; i < vm_ndomains; i++) {
2128e2068d0bSJeff Roberson 		struct vm_domain *vmd;
2129e2068d0bSJeff Roberson 
2130e2068d0bSJeff Roberson 		vm_pageout_init_domain(i);
2131e2068d0bSJeff Roberson 		vmd = VM_DOMAIN(i);
2132e2068d0bSJeff Roberson 		vm_cnt.v_free_reserved += vmd->vmd_free_reserved;
2133e2068d0bSJeff Roberson 		vm_cnt.v_free_target += vmd->vmd_free_target;
2134e2068d0bSJeff Roberson 		vm_cnt.v_free_min += vmd->vmd_free_min;
2135e2068d0bSJeff Roberson 		vm_cnt.v_inactive_target += vmd->vmd_inactive_target;
2136e2068d0bSJeff Roberson 		vm_cnt.v_pageout_free_min += vmd->vmd_pageout_free_min;
2137e2068d0bSJeff Roberson 		vm_cnt.v_interrupt_free_min += vmd->vmd_interrupt_free_min;
2138e2068d0bSJeff Roberson 		vm_cnt.v_free_severe += vmd->vmd_free_severe;
2139e2068d0bSJeff Roberson 		freecount += vmd->vmd_free_count;
2140e2068d0bSJeff Roberson 	}
2141d9e23210SJeff Roberson 
2142d9e23210SJeff Roberson 	/*
2143d9e23210SJeff Roberson 	 * Set interval in seconds for active scan.  We want to visit each
2144c9612b2dSJeff Roberson 	 * page at least once every ten minutes.  This is to prevent worst
2145c9612b2dSJeff Roberson 	 * case paging behaviors with stale active LRU.
2146d9e23210SJeff Roberson 	 */
2147d9e23210SJeff Roberson 	if (vm_pageout_update_period == 0)
2148c9612b2dSJeff Roberson 		vm_pageout_update_period = 600;
2149d9e23210SJeff Roberson 
215054a3a114SMark Johnston 	if (vm_page_max_user_wired == 0)
215154a3a114SMark Johnston 		vm_page_max_user_wired = freecount / 3;
21524d19f4adSSteven Hartland }
21534d19f4adSSteven Hartland 
21544d19f4adSSteven Hartland /*
21554d19f4adSSteven Hartland  *     vm_pageout is the high level pageout daemon.
21564d19f4adSSteven Hartland  */
21574d19f4adSSteven Hartland static void
21584d19f4adSSteven Hartland vm_pageout(void)
21594d19f4adSSteven Hartland {
2160920239efSMark Johnston 	struct proc *p;
2161920239efSMark Johnston 	struct thread *td;
2162920239efSMark Johnston 	int error, first, i;
2163920239efSMark Johnston 
2164920239efSMark Johnston 	p = curproc;
2165920239efSMark Johnston 	td = curthread;
2166df8bae1dSRodney W. Grimes 
2167245139c6SKonstantin Belousov 	mtx_init(&vm_oom_ratelim_mtx, "vmoomr", NULL, MTX_DEF);
216824a1cce3SDavid Greenman 	swap_pager_swap_init();
2169920239efSMark Johnston 	for (first = -1, i = 0; i < vm_ndomains; i++) {
217030c5525bSAndrew Gallatin 		if (VM_DOMAIN_EMPTY(i)) {
217130c5525bSAndrew Gallatin 			if (bootverbose)
217230c5525bSAndrew Gallatin 				printf("domain %d empty; skipping pageout\n",
217330c5525bSAndrew Gallatin 				    i);
217430c5525bSAndrew Gallatin 			continue;
217530c5525bSAndrew Gallatin 		}
2176920239efSMark Johnston 		if (first == -1)
2177920239efSMark Johnston 			first = i;
2178920239efSMark Johnston 		else {
2179920239efSMark Johnston 			error = kthread_add(vm_pageout_worker,
2180920239efSMark Johnston 			    (void *)(uintptr_t)i, p, NULL, 0, 0, "dom%d", i);
2181920239efSMark Johnston 			if (error != 0)
2182920239efSMark Johnston 				panic("starting pageout for domain %d: %d\n",
2183449c2e92SKonstantin Belousov 				    i, error);
2184dc2efb27SJohn Dyson 		}
2185e2068d0bSJeff Roberson 		error = kthread_add(vm_pageout_laundry_worker,
2186920239efSMark Johnston 		    (void *)(uintptr_t)i, p, NULL, 0, 0, "laundry: dom%d", i);
2187e2068d0bSJeff Roberson 		if (error != 0)
2188920239efSMark Johnston 			panic("starting laundry for domain %d: %d", i, error);
2189f919ebdeSDavid Greenman 	}
2190920239efSMark Johnston 	error = kthread_add(uma_reclaim_worker, NULL, p, NULL, 0, 0, "uma");
219144ec2b63SKonstantin Belousov 	if (error != 0)
219244ec2b63SKonstantin Belousov 		panic("starting uma_reclaim helper, error %d\n", error);
2193920239efSMark Johnston 
2194920239efSMark Johnston 	snprintf(td->td_name, sizeof(td->td_name), "dom%d", first);
2195920239efSMark Johnston 	vm_pageout_worker((void *)(uintptr_t)first);
2196df8bae1dSRodney W. Grimes }
219726f9a767SRodney W. Grimes 
21986b4b77adSAlan Cox /*
2199280d15cdSMark Johnston  * Perform an advisory wakeup of the page daemon.
22006b4b77adSAlan Cox  */
2201e0c5a895SJohn Dyson void
2202e2068d0bSJeff Roberson pagedaemon_wakeup(int domain)
2203e0c5a895SJohn Dyson {
2204e2068d0bSJeff Roberson 	struct vm_domain *vmd;
2205a1c0a785SAlan Cox 
2206e2068d0bSJeff Roberson 	vmd = VM_DOMAIN(domain);
220730fbfddaSJeff Roberson 	vm_domain_pageout_assert_unlocked(vmd);
220830fbfddaSJeff Roberson 	if (curproc == pageproc)
220930fbfddaSJeff Roberson 		return;
2210280d15cdSMark Johnston 
221130fbfddaSJeff Roberson 	if (atomic_fetchadd_int(&vmd->vmd_pageout_wanted, 1) == 0) {
221230fbfddaSJeff Roberson 		vm_domain_pageout_lock(vmd);
221330fbfddaSJeff Roberson 		atomic_store_int(&vmd->vmd_pageout_wanted, 1);
2214e2068d0bSJeff Roberson 		wakeup(&vmd->vmd_pageout_wanted);
221530fbfddaSJeff Roberson 		vm_domain_pageout_unlock(vmd);
2216e0c5a895SJohn Dyson 	}
2217e0c5a895SJohn Dyson }
2218