xref: /freebsd/sys/vm/vm_pageout.c (revision efec381dd1d9e0e449bcc4cb1f189434f9c7d55c)
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,
1613c200db9SJonathan T. Looney 	"Panic on the given number of out-of-memory errors 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);
2215cff1f4dSMark Johnston 	KASSERT((marker->a.flags & 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);
2455cff1f4dSMark Johnston 	KASSERT((ss->marker->a.flags & 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  *
260*efec381dSMark Johnston  * When processing the batch queue, vm_pageout_defer() must be used to
261*efec381dSMark Johnston  * determine whether the page has been logically dequeued since the batch was
262*efec381dSMark Johnston  * collected.
2635cd29d0fSMark Johnston  */
2645cd29d0fSMark Johnston static __always_inline void
2655cd29d0fSMark Johnston vm_pageout_collect_batch(struct scan_state *ss, const bool dequeue)
2665cd29d0fSMark Johnston {
2678d220203SAlan Cox 	struct vm_pagequeue *pq;
268d70f0ab3SMark Johnston 	vm_page_t m, marker, n;
2698c616246SKonstantin Belousov 
2705cd29d0fSMark Johnston 	marker = ss->marker;
2715cd29d0fSMark Johnston 	pq = ss->pq;
2728c616246SKonstantin Belousov 
2735cff1f4dSMark Johnston 	KASSERT((marker->a.flags & PGA_ENQUEUED) != 0,
2745cd29d0fSMark Johnston 	    ("marker %p not enqueued", ss->marker));
2758c616246SKonstantin Belousov 
2768d220203SAlan Cox 	vm_pagequeue_lock(pq);
2775cd29d0fSMark Johnston 	for (m = TAILQ_NEXT(marker, plinks.q); m != NULL &&
2785cd29d0fSMark Johnston 	    ss->scanned < ss->maxscan && ss->bq.bq_cnt < VM_BATCHQUEUE_SIZE;
279d70f0ab3SMark Johnston 	    m = n, ss->scanned++) {
280d70f0ab3SMark Johnston 		n = TAILQ_NEXT(m, plinks.q);
2815cd29d0fSMark Johnston 		if ((m->flags & PG_MARKER) == 0) {
2825cff1f4dSMark Johnston 			KASSERT((m->a.flags & PGA_ENQUEUED) != 0,
2835cd29d0fSMark Johnston 			    ("page %p not enqueued", m));
2845cd29d0fSMark Johnston 			KASSERT((m->flags & PG_FICTITIOUS) == 0,
2855cd29d0fSMark Johnston 			    ("Fictitious page %p cannot be in page queue", m));
2865cd29d0fSMark Johnston 			KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2875cd29d0fSMark Johnston 			    ("Unmanaged page %p cannot be in page queue", m));
2885cd29d0fSMark Johnston 		} else if (dequeue)
2895cd29d0fSMark Johnston 			continue;
2908c616246SKonstantin Belousov 
2915cd29d0fSMark Johnston 		(void)vm_batchqueue_insert(&ss->bq, m);
2925cd29d0fSMark Johnston 		if (dequeue) {
2935cd29d0fSMark Johnston 			TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2945cd29d0fSMark Johnston 			vm_page_aflag_clear(m, PGA_ENQUEUED);
2955cd29d0fSMark Johnston 		}
2965cd29d0fSMark Johnston 	}
2975cd29d0fSMark Johnston 	TAILQ_REMOVE(&pq->pq_pl, marker, plinks.q);
2985cd29d0fSMark Johnston 	if (__predict_true(m != NULL))
2995cd29d0fSMark Johnston 		TAILQ_INSERT_BEFORE(m, marker, plinks.q);
3005cd29d0fSMark Johnston 	else
3015cd29d0fSMark Johnston 		TAILQ_INSERT_TAIL(&pq->pq_pl, marker, plinks.q);
3025cd29d0fSMark Johnston 	if (dequeue)
3035cd29d0fSMark Johnston 		vm_pagequeue_cnt_add(pq, -ss->bq.bq_cnt);
3045cd29d0fSMark Johnston 	vm_pagequeue_unlock(pq);
3055cd29d0fSMark Johnston }
3065cd29d0fSMark Johnston 
307fee2a2faSMark Johnston /*
308fee2a2faSMark Johnston  * Return the next page to be scanned, or NULL if the scan is complete.
309fee2a2faSMark Johnston  */
3105cd29d0fSMark Johnston static __always_inline vm_page_t
3115cd29d0fSMark Johnston vm_pageout_next(struct scan_state *ss, const bool dequeue)
3125cd29d0fSMark Johnston {
3135cd29d0fSMark Johnston 
3145cd29d0fSMark Johnston 	if (ss->bq.bq_cnt == 0)
3155cd29d0fSMark Johnston 		vm_pageout_collect_batch(ss, dequeue);
3165cd29d0fSMark Johnston 	return (vm_batchqueue_pop(&ss->bq));
3178c616246SKonstantin Belousov }
3188c616246SKonstantin Belousov 
3198c616246SKonstantin Belousov /*
320b7f30bffSMark Johnston  * Determine whether processing of a page should be deferred and ensure that any
321b7f30bffSMark Johnston  * outstanding queue operations are processed.
322b7f30bffSMark Johnston  */
323b7f30bffSMark Johnston static __always_inline bool
324b7f30bffSMark Johnston vm_pageout_defer(vm_page_t m, const uint8_t queue, const bool enqueued)
325b7f30bffSMark Johnston {
326b7f30bffSMark Johnston 	vm_page_astate_t as;
327b7f30bffSMark Johnston 
328b7f30bffSMark Johnston 	as = vm_page_astate_load(m);
329b7f30bffSMark Johnston 	if (__predict_false(as.queue != queue ||
330b7f30bffSMark Johnston 	    ((as.flags & PGA_ENQUEUED) != 0) != enqueued))
331b7f30bffSMark Johnston 		return (true);
332b7f30bffSMark Johnston 	if ((as.flags & PGA_QUEUE_OP_MASK) != 0) {
333b7f30bffSMark Johnston 		vm_page_pqbatch_submit(m, queue);
334b7f30bffSMark Johnston 		return (true);
335b7f30bffSMark Johnston 	}
336b7f30bffSMark Johnston 	return (false);
337b7f30bffSMark Johnston }
338b7f30bffSMark Johnston 
339b7f30bffSMark Johnston /*
340248fe642SAlan Cox  * Scan for pages at adjacent offsets within the given page's object that are
341248fe642SAlan Cox  * eligible for laundering, form a cluster of these pages and the given page,
342248fe642SAlan Cox  * and launder that cluster.
34326f9a767SRodney W. Grimes  */
3443af76890SPoul-Henning Kamp static int
34534d8b7eaSJeff Roberson vm_pageout_cluster(vm_page_t m)
34624a1cce3SDavid Greenman {
34754d92145SMatthew Dillon 	vm_object_t object;
348248fe642SAlan Cox 	vm_page_t mc[2 * vm_pageout_page_count], p, pb, ps;
349248fe642SAlan Cox 	vm_pindex_t pindex;
350248fe642SAlan Cox 	int ib, is, page_base, pageout_count;
35126f9a767SRodney W. Grimes 
35217f6a17bSAlan Cox 	object = m->object;
35389f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
354248fe642SAlan Cox 	pindex = m->pindex;
3550cddd8f0SMatthew Dillon 
35663e97555SJeff Roberson 	vm_page_assert_xbusied(m);
3570d94caffSDavid Greenman 
35891b4f427SAlan Cox 	mc[vm_pageout_page_count] = pb = ps = m;
35926f9a767SRodney W. Grimes 	pageout_count = 1;
360f35329acSJohn Dyson 	page_base = vm_pageout_page_count;
36190ecac61SMatthew Dillon 	ib = 1;
36290ecac61SMatthew Dillon 	is = 1;
36390ecac61SMatthew Dillon 
36424a1cce3SDavid Greenman 	/*
365248fe642SAlan Cox 	 * We can cluster only if the page is not clean, busy, or held, and
366ebcddc72SAlan Cox 	 * the page is in the laundry queue.
36790ecac61SMatthew Dillon 	 *
36890ecac61SMatthew Dillon 	 * During heavy mmap/modification loads the pageout
36990ecac61SMatthew Dillon 	 * daemon can really fragment the underlying file
370248fe642SAlan Cox 	 * due to flushing pages out of order and not trying to
371248fe642SAlan Cox 	 * align the clusters (which leaves sporadic out-of-order
37290ecac61SMatthew Dillon 	 * holes).  To solve this problem we do the reverse scan
37390ecac61SMatthew Dillon 	 * first and attempt to align our cluster, then do a
37490ecac61SMatthew Dillon 	 * forward scan if room remains.
37524a1cce3SDavid Greenman 	 */
37690ecac61SMatthew Dillon more:
377248fe642SAlan Cox 	while (ib != 0 && pageout_count < vm_pageout_page_count) {
37890ecac61SMatthew Dillon 		if (ib > pindex) {
37990ecac61SMatthew Dillon 			ib = 0;
38090ecac61SMatthew Dillon 			break;
381f6b04d2bSDavid Greenman 		}
38263e97555SJeff Roberson 		if ((p = vm_page_prev(pb)) == NULL ||
38363e97555SJeff Roberson 		    vm_page_tryxbusy(p) == 0) {
38490ecac61SMatthew Dillon 			ib = 0;
38590ecac61SMatthew Dillon 			break;
386f6b04d2bSDavid Greenman 		}
38763e97555SJeff Roberson 		if (vm_page_wired(p)) {
38863e97555SJeff Roberson 			ib = 0;
38963e97555SJeff Roberson 			vm_page_xunbusy(p);
39063e97555SJeff Roberson 			break;
39163e97555SJeff Roberson 		}
39224a1cce3SDavid Greenman 		vm_page_test_dirty(p);
3931b5c869dSMark Johnston 		if (p->dirty == 0) {
394eb5d3969SAlan Cox 			ib = 0;
39563e97555SJeff Roberson 			vm_page_xunbusy(p);
396eb5d3969SAlan Cox 			break;
397eb5d3969SAlan Cox 		}
398fee2a2faSMark Johnston 		if (!vm_page_in_laundry(p) || !vm_page_try_remove_write(p)) {
39963e97555SJeff Roberson 			vm_page_xunbusy(p);
40090ecac61SMatthew Dillon 			ib = 0;
40124a1cce3SDavid Greenman 			break;
402f6b04d2bSDavid Greenman 		}
40391b4f427SAlan Cox 		mc[--page_base] = pb = p;
40490ecac61SMatthew Dillon 		++pageout_count;
40590ecac61SMatthew Dillon 		++ib;
406248fe642SAlan Cox 
40724a1cce3SDavid Greenman 		/*
408248fe642SAlan Cox 		 * We are at an alignment boundary.  Stop here, and switch
409248fe642SAlan Cox 		 * directions.  Do not clear ib.
41024a1cce3SDavid Greenman 		 */
41190ecac61SMatthew Dillon 		if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
41290ecac61SMatthew Dillon 			break;
41324a1cce3SDavid Greenman 	}
41490ecac61SMatthew Dillon 	while (pageout_count < vm_pageout_page_count &&
41590ecac61SMatthew Dillon 	    pindex + is < object->size) {
41663e97555SJeff Roberson 		if ((p = vm_page_next(ps)) == NULL ||
41763e97555SJeff Roberson 		    vm_page_tryxbusy(p) == 0)
41890ecac61SMatthew Dillon 			break;
41963e97555SJeff Roberson 		if (vm_page_wired(p)) {
42063e97555SJeff Roberson 			vm_page_xunbusy(p);
42163e97555SJeff Roberson 			break;
42263e97555SJeff Roberson 		}
42324a1cce3SDavid Greenman 		vm_page_test_dirty(p);
42463e97555SJeff Roberson 		if (p->dirty == 0) {
42563e97555SJeff Roberson 			vm_page_xunbusy(p);
426eb5d3969SAlan Cox 			break;
42763e97555SJeff Roberson 		}
428e8bcf696SMark Johnston 		if (!vm_page_in_laundry(p) || !vm_page_try_remove_write(p)) {
42963e97555SJeff Roberson 			vm_page_xunbusy(p);
43024a1cce3SDavid Greenman 			break;
431e8bcf696SMark Johnston 		}
43291b4f427SAlan Cox 		mc[page_base + pageout_count] = ps = p;
43390ecac61SMatthew Dillon 		++pageout_count;
43490ecac61SMatthew Dillon 		++is;
43524a1cce3SDavid Greenman 	}
43690ecac61SMatthew Dillon 
43790ecac61SMatthew Dillon 	/*
43890ecac61SMatthew Dillon 	 * If we exhausted our forward scan, continue with the reverse scan
439248fe642SAlan Cox 	 * when possible, even past an alignment boundary.  This catches
440248fe642SAlan Cox 	 * boundary conditions.
44190ecac61SMatthew Dillon 	 */
442248fe642SAlan Cox 	if (ib != 0 && pageout_count < vm_pageout_page_count)
44390ecac61SMatthew Dillon 		goto more;
444f6b04d2bSDavid Greenman 
44599e6e193SMark Johnston 	return (vm_pageout_flush(&mc[page_base], pageout_count,
44699e6e193SMark Johnston 	    VM_PAGER_PUT_NOREUSE, 0, NULL, NULL));
447aef922f5SJohn Dyson }
448aef922f5SJohn Dyson 
4491c7c3c6aSMatthew Dillon /*
4501c7c3c6aSMatthew Dillon  * vm_pageout_flush() - launder the given pages
4511c7c3c6aSMatthew Dillon  *
4521c7c3c6aSMatthew Dillon  *	The given pages are laundered.  Note that we setup for the start of
4531c7c3c6aSMatthew Dillon  *	I/O ( i.e. busy the page ), mark it read-only, and bump the object
4541c7c3c6aSMatthew Dillon  *	reference count all in here rather then in the parent.  If we want
4551c7c3c6aSMatthew Dillon  *	the parent to do more sophisticated things we may have to change
4561c7c3c6aSMatthew Dillon  *	the ordering.
4571e8a675cSKonstantin Belousov  *
4581e8a675cSKonstantin Belousov  *	Returned runlen is the count of pages between mreq and first
4591e8a675cSKonstantin Belousov  *	page after mreq with status VM_PAGER_AGAIN.
460126d6082SKonstantin Belousov  *	*eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
461126d6082SKonstantin Belousov  *	for any page in runlen set.
4621c7c3c6aSMatthew Dillon  */
463aef922f5SJohn Dyson int
464126d6082SKonstantin Belousov vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
465126d6082SKonstantin Belousov     boolean_t *eio)
466aef922f5SJohn Dyson {
4672e3b314dSAlan Cox 	vm_object_t object = mc[0]->object;
468aef922f5SJohn Dyson 	int pageout_status[count];
46995461b45SJohn Dyson 	int numpagedout = 0;
4701e8a675cSKonstantin Belousov 	int i, runlen;
471aef922f5SJohn Dyson 
47289f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
4737bec141bSKip Macy 
4741c7c3c6aSMatthew Dillon 	/*
47563e97555SJeff Roberson 	 * Initiate I/O.  Mark the pages shared busy and verify that they're
47663e97555SJeff Roberson 	 * valid and read-only.
4771c7c3c6aSMatthew Dillon 	 *
4781c7c3c6aSMatthew Dillon 	 * We do not have to fixup the clean/dirty bits here... we can
4791c7c3c6aSMatthew Dillon 	 * allow the pager to do it after the I/O completes.
48002fa91d3SMatthew Dillon 	 *
48102fa91d3SMatthew Dillon 	 * NOTE! mc[i]->dirty may be partial or fragmented due to an
48202fa91d3SMatthew Dillon 	 * edge case with file fragments.
4831c7c3c6aSMatthew Dillon 	 */
4848f9110f6SJohn Dyson 	for (i = 0; i < count; i++) {
4850012f373SJeff Roberson 		KASSERT(vm_page_all_valid(mc[i]),
4867a935082SAlan Cox 		    ("vm_pageout_flush: partially invalid page %p index %d/%d",
4877a935082SAlan Cox 			mc[i], i, count));
4885cff1f4dSMark Johnston 		KASSERT((mc[i]->a.flags & PGA_WRITEABLE) == 0,
489aed9aaaaSMark Johnston 		    ("vm_pageout_flush: writeable page %p", mc[i]));
49063e97555SJeff Roberson 		vm_page_busy_downgrade(mc[i]);
4912965a453SKip Macy 	}
492d474eaaaSDoug Rabson 	vm_object_pip_add(object, count);
493aef922f5SJohn Dyson 
494d076fbeaSAlan Cox 	vm_pager_put_pages(object, mc, count, flags, pageout_status);
49526f9a767SRodney W. Grimes 
4961e8a675cSKonstantin Belousov 	runlen = count - mreq;
497126d6082SKonstantin Belousov 	if (eio != NULL)
498126d6082SKonstantin Belousov 		*eio = FALSE;
499aef922f5SJohn Dyson 	for (i = 0; i < count; i++) {
500aef922f5SJohn Dyson 		vm_page_t mt = mc[i];
50124a1cce3SDavid Greenman 
5024cd45723SAlan Cox 		KASSERT(pageout_status[i] == VM_PAGER_PEND ||
5036031c68dSAlan Cox 		    !pmap_page_is_write_mapped(mt),
5049ea8d1a6SAlan Cox 		    ("vm_pageout_flush: page %p is not write protected", mt));
50526f9a767SRodney W. Grimes 		switch (pageout_status[i]) {
50626f9a767SRodney W. Grimes 		case VM_PAGER_OK:
5079f5632e6SMark Johnston 			/*
5089f5632e6SMark Johnston 			 * The page may have moved since laundering started, in
5099f5632e6SMark Johnston 			 * which case it should be left alone.
5109f5632e6SMark Johnston 			 */
511ebcddc72SAlan Cox 			if (vm_page_in_laundry(mt))
512ebcddc72SAlan Cox 				vm_page_deactivate_noreuse(mt);
513ebcddc72SAlan Cox 			/* FALLTHROUGH */
51426f9a767SRodney W. Grimes 		case VM_PAGER_PEND:
51595461b45SJohn Dyson 			numpagedout++;
51626f9a767SRodney W. Grimes 			break;
51726f9a767SRodney W. Grimes 		case VM_PAGER_BAD:
51826f9a767SRodney W. Grimes 			/*
519ebcddc72SAlan Cox 			 * The page is outside the object's range.  We pretend
520ebcddc72SAlan Cox 			 * that the page out worked and clean the page, so the
521ebcddc72SAlan Cox 			 * changes will be lost if the page is reclaimed by
522ebcddc72SAlan Cox 			 * the page daemon.
52326f9a767SRodney W. Grimes 			 */
52490ecac61SMatthew Dillon 			vm_page_undirty(mt);
525ebcddc72SAlan Cox 			if (vm_page_in_laundry(mt))
526ebcddc72SAlan Cox 				vm_page_deactivate_noreuse(mt);
52726f9a767SRodney W. Grimes 			break;
52826f9a767SRodney W. Grimes 		case VM_PAGER_ERROR:
52926f9a767SRodney W. Grimes 		case VM_PAGER_FAIL:
53026f9a767SRodney W. Grimes 			/*
531b1fd102eSMark Johnston 			 * If the page couldn't be paged out to swap because the
532b1fd102eSMark Johnston 			 * pager wasn't able to find space, place the page in
533b1fd102eSMark Johnston 			 * the PQ_UNSWAPPABLE holding queue.  This is an
534b1fd102eSMark Johnston 			 * optimization that prevents the page daemon from
535b1fd102eSMark Johnston 			 * wasting CPU cycles on pages that cannot be reclaimed
536b1fd102eSMark Johnston 			 * becase no swap device is configured.
537b1fd102eSMark Johnston 			 *
538b1fd102eSMark Johnston 			 * Otherwise, reactivate the page so that it doesn't
539b1fd102eSMark Johnston 			 * clog the laundry and inactive queues.  (We will try
540b1fd102eSMark Johnston 			 * paging it out again later.)
54126f9a767SRodney W. Grimes 			 */
542b1fd102eSMark Johnston 			if (object->type == OBJT_SWAP &&
543b1fd102eSMark Johnston 			    pageout_status[i] == VM_PAGER_FAIL) {
544b1fd102eSMark Johnston 				vm_page_unswappable(mt);
545b1fd102eSMark Johnston 				numpagedout++;
546b1fd102eSMark Johnston 			} else
54724a1cce3SDavid Greenman 				vm_page_activate(mt);
548126d6082SKonstantin Belousov 			if (eio != NULL && i >= mreq && i - mreq < runlen)
549126d6082SKonstantin Belousov 				*eio = TRUE;
55026f9a767SRodney W. Grimes 			break;
55126f9a767SRodney W. Grimes 		case VM_PAGER_AGAIN:
5521e8a675cSKonstantin Belousov 			if (i >= mreq && i - mreq < runlen)
5531e8a675cSKonstantin Belousov 				runlen = i - mreq;
55426f9a767SRodney W. Grimes 			break;
55526f9a767SRodney W. Grimes 		}
55626f9a767SRodney W. Grimes 
55726f9a767SRodney W. Grimes 		/*
5580d94caffSDavid Greenman 		 * If the operation is still going, leave the page busy to
5590d94caffSDavid Greenman 		 * block all other accesses. Also, leave the paging in
5600d94caffSDavid Greenman 		 * progress indicator set so that we don't attempt an object
5610d94caffSDavid Greenman 		 * collapse.
56226f9a767SRodney W. Grimes 		 */
56326f9a767SRodney W. Grimes 		if (pageout_status[i] != VM_PAGER_PEND) {
564f919ebdeSDavid Greenman 			vm_object_pip_wakeup(object);
565c7aebda8SAttilio Rao 			vm_page_sunbusy(mt);
5663c4a2440SAlan Cox 		}
5673c4a2440SAlan Cox 	}
5681e8a675cSKonstantin Belousov 	if (prunlen != NULL)
5691e8a675cSKonstantin Belousov 		*prunlen = runlen;
5703c4a2440SAlan Cox 	return (numpagedout);
57126f9a767SRodney W. Grimes }
57226f9a767SRodney W. Grimes 
573b1fd102eSMark Johnston static void
574b1fd102eSMark Johnston vm_pageout_swapon(void *arg __unused, struct swdevt *sp __unused)
575b1fd102eSMark Johnston {
576b1fd102eSMark Johnston 
577b1fd102eSMark Johnston 	atomic_store_rel_int(&swapdev_enabled, 1);
578b1fd102eSMark Johnston }
579b1fd102eSMark Johnston 
580b1fd102eSMark Johnston static void
581b1fd102eSMark Johnston vm_pageout_swapoff(void *arg __unused, struct swdevt *sp __unused)
582b1fd102eSMark Johnston {
583b1fd102eSMark Johnston 
584b1fd102eSMark Johnston 	if (swap_pager_nswapdev() == 1)
585b1fd102eSMark Johnston 		atomic_store_rel_int(&swapdev_enabled, 0);
586b1fd102eSMark Johnston }
587b1fd102eSMark Johnston 
5881c7c3c6aSMatthew Dillon /*
58934d8b7eaSJeff Roberson  * Attempt to acquire all of the necessary locks to launder a page and
59034d8b7eaSJeff Roberson  * then call through the clustering layer to PUTPAGES.  Wait a short
59134d8b7eaSJeff Roberson  * time for a vnode lock.
59234d8b7eaSJeff Roberson  *
59334d8b7eaSJeff Roberson  * Requires the page and object lock on entry, releases both before return.
59434d8b7eaSJeff Roberson  * Returns 0 on success and an errno otherwise.
59534d8b7eaSJeff Roberson  */
59634d8b7eaSJeff Roberson static int
597ebcddc72SAlan Cox vm_pageout_clean(vm_page_t m, int *numpagedout)
59834d8b7eaSJeff Roberson {
59934d8b7eaSJeff Roberson 	struct vnode *vp;
60034d8b7eaSJeff Roberson 	struct mount *mp;
60134d8b7eaSJeff Roberson 	vm_object_t object;
60234d8b7eaSJeff Roberson 	vm_pindex_t pindex;
60334d8b7eaSJeff Roberson 	int error, lockmode;
60434d8b7eaSJeff Roberson 
60534d8b7eaSJeff Roberson 	object = m->object;
60634d8b7eaSJeff Roberson 	VM_OBJECT_ASSERT_WLOCKED(object);
60734d8b7eaSJeff Roberson 	error = 0;
60834d8b7eaSJeff Roberson 	vp = NULL;
60934d8b7eaSJeff Roberson 	mp = NULL;
61034d8b7eaSJeff Roberson 
61134d8b7eaSJeff Roberson 	/*
61234d8b7eaSJeff Roberson 	 * The object is already known NOT to be dead.   It
61334d8b7eaSJeff Roberson 	 * is possible for the vget() to block the whole
61434d8b7eaSJeff Roberson 	 * pageout daemon, but the new low-memory handling
61534d8b7eaSJeff Roberson 	 * code should prevent it.
61634d8b7eaSJeff Roberson 	 *
61734d8b7eaSJeff Roberson 	 * We can't wait forever for the vnode lock, we might
61834d8b7eaSJeff Roberson 	 * deadlock due to a vn_read() getting stuck in
61934d8b7eaSJeff Roberson 	 * vm_wait while holding this vnode.  We skip the
62034d8b7eaSJeff Roberson 	 * vnode if we can't get it in a reasonable amount
62134d8b7eaSJeff Roberson 	 * of time.
62234d8b7eaSJeff Roberson 	 */
62334d8b7eaSJeff Roberson 	if (object->type == OBJT_VNODE) {
62463e97555SJeff Roberson 		vm_page_xunbusy(m);
62534d8b7eaSJeff Roberson 		vp = object->handle;
62634d8b7eaSJeff Roberson 		if (vp->v_type == VREG &&
62734d8b7eaSJeff Roberson 		    vn_start_write(vp, &mp, V_NOWAIT) != 0) {
62834d8b7eaSJeff Roberson 			mp = NULL;
62934d8b7eaSJeff Roberson 			error = EDEADLK;
63034d8b7eaSJeff Roberson 			goto unlock_all;
63134d8b7eaSJeff Roberson 		}
63234d8b7eaSJeff Roberson 		KASSERT(mp != NULL,
63334d8b7eaSJeff Roberson 		    ("vp %p with NULL v_mount", vp));
63434d8b7eaSJeff Roberson 		vm_object_reference_locked(object);
63534d8b7eaSJeff Roberson 		pindex = m->pindex;
63634d8b7eaSJeff Roberson 		VM_OBJECT_WUNLOCK(object);
63734d8b7eaSJeff Roberson 		lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
63834d8b7eaSJeff Roberson 		    LK_SHARED : LK_EXCLUSIVE;
63934d8b7eaSJeff Roberson 		if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
64034d8b7eaSJeff Roberson 			vp = NULL;
64134d8b7eaSJeff Roberson 			error = EDEADLK;
64234d8b7eaSJeff Roberson 			goto unlock_mp;
64334d8b7eaSJeff Roberson 		}
64434d8b7eaSJeff Roberson 		VM_OBJECT_WLOCK(object);
64557cd81a3SMark Johnston 
64657cd81a3SMark Johnston 		/*
64757cd81a3SMark Johnston 		 * Ensure that the object and vnode were not disassociated
64857cd81a3SMark Johnston 		 * while locks were dropped.
64957cd81a3SMark Johnston 		 */
65057cd81a3SMark Johnston 		if (vp->v_object != object) {
65157cd81a3SMark Johnston 			error = ENOENT;
65257cd81a3SMark Johnston 			goto unlock_all;
65357cd81a3SMark Johnston 		}
65457cd81a3SMark Johnston 
65534d8b7eaSJeff Roberson 		/*
6569f5632e6SMark Johnston 		 * While the object was unlocked, the page may have been:
65734d8b7eaSJeff Roberson 		 * (1) moved to a different queue,
65834d8b7eaSJeff Roberson 		 * (2) reallocated to a different object,
65934d8b7eaSJeff Roberson 		 * (3) reallocated to a different offset, or
66034d8b7eaSJeff Roberson 		 * (4) cleaned.
66134d8b7eaSJeff Roberson 		 */
662ebcddc72SAlan Cox 		if (!vm_page_in_laundry(m) || m->object != object ||
66334d8b7eaSJeff Roberson 		    m->pindex != pindex || m->dirty == 0) {
66434d8b7eaSJeff Roberson 			error = ENXIO;
66534d8b7eaSJeff Roberson 			goto unlock_all;
66634d8b7eaSJeff Roberson 		}
66734d8b7eaSJeff Roberson 
66834d8b7eaSJeff Roberson 		/*
6699f5632e6SMark Johnston 		 * The page may have been busied while the object lock was
6709f5632e6SMark Johnston 		 * released.
67134d8b7eaSJeff Roberson 		 */
67263e97555SJeff Roberson 		if (vm_page_tryxbusy(m) == 0) {
67334d8b7eaSJeff Roberson 			error = EBUSY;
67434d8b7eaSJeff Roberson 			goto unlock_all;
67534d8b7eaSJeff Roberson 		}
67634d8b7eaSJeff Roberson 	}
67734d8b7eaSJeff Roberson 
67834d8b7eaSJeff Roberson 	/*
679fee2a2faSMark Johnston 	 * Remove all writeable mappings, failing if the page is wired.
680fee2a2faSMark Johnston 	 */
681fee2a2faSMark Johnston 	if (!vm_page_try_remove_write(m)) {
68263e97555SJeff Roberson 		vm_page_xunbusy(m);
683fee2a2faSMark Johnston 		error = EBUSY;
684fee2a2faSMark Johnston 		goto unlock_all;
685fee2a2faSMark Johnston 	}
686fee2a2faSMark Johnston 
687fee2a2faSMark Johnston 	/*
68834d8b7eaSJeff Roberson 	 * If a page is dirty, then it is either being washed
68934d8b7eaSJeff Roberson 	 * (but not yet cleaned) or it is still in the
69034d8b7eaSJeff Roberson 	 * laundry.  If it is still in the laundry, then we
69134d8b7eaSJeff Roberson 	 * start the cleaning operation.
69234d8b7eaSJeff Roberson 	 */
693ebcddc72SAlan Cox 	if ((*numpagedout = vm_pageout_cluster(m)) == 0)
69434d8b7eaSJeff Roberson 		error = EIO;
69534d8b7eaSJeff Roberson 
69634d8b7eaSJeff Roberson unlock_all:
69734d8b7eaSJeff Roberson 	VM_OBJECT_WUNLOCK(object);
69834d8b7eaSJeff Roberson 
69934d8b7eaSJeff Roberson unlock_mp:
70034d8b7eaSJeff Roberson 	if (mp != NULL) {
70134d8b7eaSJeff Roberson 		if (vp != NULL)
70234d8b7eaSJeff Roberson 			vput(vp);
70334d8b7eaSJeff Roberson 		vm_object_deallocate(object);
70434d8b7eaSJeff Roberson 		vn_finished_write(mp);
70534d8b7eaSJeff Roberson 	}
70634d8b7eaSJeff Roberson 
70734d8b7eaSJeff Roberson 	return (error);
70834d8b7eaSJeff Roberson }
70934d8b7eaSJeff Roberson 
71034d8b7eaSJeff Roberson /*
711ebcddc72SAlan Cox  * Attempt to launder the specified number of pages.
712ebcddc72SAlan Cox  *
713ebcddc72SAlan Cox  * Returns the number of pages successfully laundered.
714ebcddc72SAlan Cox  */
715ebcddc72SAlan Cox static int
716ebcddc72SAlan Cox vm_pageout_launder(struct vm_domain *vmd, int launder, bool in_shortfall)
717ebcddc72SAlan Cox {
7185cd29d0fSMark Johnston 	struct scan_state ss;
719ebcddc72SAlan Cox 	struct vm_pagequeue *pq;
720ebcddc72SAlan Cox 	vm_object_t object;
7215cd29d0fSMark Johnston 	vm_page_t m, marker;
722f3f38e25SMark Johnston 	vm_page_astate_t new, old;
723f3f38e25SMark Johnston 	int act_delta, error, numpagedout, queue, refs, starting_target;
724ebcddc72SAlan Cox 	int vnodes_skipped;
72560256604SMark Johnston 	bool pageout_ok;
726ebcddc72SAlan Cox 
7275cd29d0fSMark Johnston 	object = NULL;
728ebcddc72SAlan Cox 	starting_target = launder;
729ebcddc72SAlan Cox 	vnodes_skipped = 0;
730ebcddc72SAlan Cox 
731ebcddc72SAlan Cox 	/*
732b1fd102eSMark Johnston 	 * Scan the laundry queues for pages eligible to be laundered.  We stop
733ebcddc72SAlan Cox 	 * once the target number of dirty pages have been laundered, or once
734ebcddc72SAlan Cox 	 * we've reached the end of the queue.  A single iteration of this loop
735ebcddc72SAlan Cox 	 * may cause more than one page to be laundered because of clustering.
736ebcddc72SAlan Cox 	 *
737b1fd102eSMark Johnston 	 * As an optimization, we avoid laundering from PQ_UNSWAPPABLE when no
738b1fd102eSMark Johnston 	 * swap devices are configured.
739ebcddc72SAlan Cox 	 */
740b1fd102eSMark Johnston 	if (atomic_load_acq_int(&swapdev_enabled))
74164b38930SMark Johnston 		queue = PQ_UNSWAPPABLE;
742b1fd102eSMark Johnston 	else
74364b38930SMark Johnston 		queue = PQ_LAUNDRY;
744ebcddc72SAlan Cox 
745b1fd102eSMark Johnston scan:
74664b38930SMark Johnston 	marker = &vmd->vmd_markers[queue];
7475cd29d0fSMark Johnston 	pq = &vmd->vmd_pagequeues[queue];
748ebcddc72SAlan Cox 	vm_pagequeue_lock(pq);
7495cd29d0fSMark Johnston 	vm_pageout_init_scan(&ss, pq, marker, NULL, pq->pq_cnt);
7505cd29d0fSMark Johnston 	while (launder > 0 && (m = vm_pageout_next(&ss, false)) != NULL) {
7515cd29d0fSMark Johnston 		if (__predict_false((m->flags & PG_MARKER) != 0))
752ebcddc72SAlan Cox 			continue;
7535cd29d0fSMark Johnston 
7545cd29d0fSMark Johnston 		/*
755b7f30bffSMark Johnston 		 * Don't touch a page that was removed from the queue after the
756b7f30bffSMark Johnston 		 * page queue lock was released.  Otherwise, ensure that any
757b7f30bffSMark Johnston 		 * pending queue operations, such as dequeues for wired pages,
758b7f30bffSMark Johnston 		 * are handled.
7595cd29d0fSMark Johnston 		 */
760b7f30bffSMark Johnston 		if (vm_pageout_defer(m, queue, true))
761ebcddc72SAlan Cox 			continue;
762e8bcf696SMark Johnston 
7639f5632e6SMark Johnston 		/*
7649f5632e6SMark Johnston 		 * Lock the page's object.
7659f5632e6SMark Johnston 		 */
7669f5632e6SMark Johnston 		if (object == NULL || object != m->object) {
76760256604SMark Johnston 			if (object != NULL)
7685cd29d0fSMark Johnston 				VM_OBJECT_WUNLOCK(object);
76923ed568cSMateusz Guzik 			object = atomic_load_ptr(&m->object);
7709f5632e6SMark Johnston 			if (__predict_false(object == NULL))
7719f5632e6SMark Johnston 				/* The page is being freed by another thread. */
7729f5632e6SMark Johnston 				continue;
7739f5632e6SMark Johnston 
774e8bcf696SMark Johnston 			/* Depends on type-stability. */
77541fd4b94SMark Johnston 			VM_OBJECT_WLOCK(object);
7769f5632e6SMark Johnston 			if (__predict_false(m->object != object)) {
7779f5632e6SMark Johnston 				VM_OBJECT_WUNLOCK(object);
7789f5632e6SMark Johnston 				object = NULL;
77941fd4b94SMark Johnston 				continue;
7809f5632e6SMark Johnston 			}
7819f5632e6SMark Johnston 		}
7825cd29d0fSMark Johnston 
78363e97555SJeff Roberson 		if (vm_page_tryxbusy(m) == 0)
7845cd29d0fSMark Johnston 			continue;
785ebcddc72SAlan Cox 
786ebcddc72SAlan Cox 		/*
787b7f30bffSMark Johnston 		 * Check for wirings now that we hold the object lock and have
7889f5632e6SMark Johnston 		 * exclusively busied the page.  If the page is mapped, it may
7899f5632e6SMark Johnston 		 * still be wired by pmap lookups.  The call to
790fee2a2faSMark Johnston 		 * vm_page_try_remove_all() below atomically checks for such
791fee2a2faSMark Johnston 		 * wirings and removes mappings.  If the page is unmapped, the
7929f5632e6SMark Johnston 		 * wire count is guaranteed not to increase after this check.
793fee2a2faSMark Johnston 		 */
7949f5632e6SMark Johnston 		if (__predict_false(vm_page_wired(m)))
795f3f38e25SMark Johnston 			goto skip_page;
796fee2a2faSMark Johnston 
797fee2a2faSMark Johnston 		/*
798ebcddc72SAlan Cox 		 * Invalid pages can be easily freed.  They cannot be
799ebcddc72SAlan Cox 		 * mapped; vm_page_free() asserts this.
800ebcddc72SAlan Cox 		 */
8010012f373SJeff Roberson 		if (vm_page_none_valid(m))
802ebcddc72SAlan Cox 			goto free_page;
803ebcddc72SAlan Cox 
804f3f38e25SMark Johnston 		refs = object->ref_count != 0 ? pmap_ts_referenced(m) : 0;
805f3f38e25SMark Johnston 
806f3f38e25SMark Johnston 		for (old = vm_page_astate_load(m);;) {
807ebcddc72SAlan Cox 			/*
808f3f38e25SMark Johnston 			 * Check to see if the page has been removed from the
809f3f38e25SMark Johnston 			 * queue since the first such check.  Leave it alone if
810f3f38e25SMark Johnston 			 * so, discarding any references collected by
811f3f38e25SMark Johnston 			 * pmap_ts_referenced().
812ebcddc72SAlan Cox 			 */
813f3f38e25SMark Johnston 			if (__predict_false(_vm_page_queue(old) == PQ_NONE))
814f3f38e25SMark Johnston 				goto skip_page;
815f3f38e25SMark Johnston 
816f3f38e25SMark Johnston 			new = old;
817f3f38e25SMark Johnston 			act_delta = refs;
818f3f38e25SMark Johnston 			if ((old.flags & PGA_REFERENCED) != 0) {
819f3f38e25SMark Johnston 				new.flags &= ~PGA_REFERENCED;
820d7aeb429SAlan Cox 				act_delta++;
821ebcddc72SAlan Cox 			}
822f3f38e25SMark Johnston 			if (act_delta == 0) {
823f3f38e25SMark Johnston 				;
824f3f38e25SMark Johnston 			} else if (object->ref_count != 0) {
825ebcddc72SAlan Cox 				/*
826f3f38e25SMark Johnston 				 * Increase the activation count if the page was
827f3f38e25SMark Johnston 				 * referenced while in the laundry queue.  This
828f3f38e25SMark Johnston 				 * makes it less likely that the page will be
829f3f38e25SMark Johnston 				 * returned prematurely to the laundry queue.
830e8bcf696SMark Johnston 				 */
831f3f38e25SMark Johnston 				new.act_count += ACT_ADVANCE +
832f3f38e25SMark Johnston 				    act_delta;
833f3f38e25SMark Johnston 				if (new.act_count > ACT_MAX)
834f3f38e25SMark Johnston 					new.act_count = ACT_MAX;
835f3f38e25SMark Johnston 
836f7607c30SMark Johnston 				new.flags &= ~PGA_QUEUE_OP_MASK;
837f3f38e25SMark Johnston 				new.flags |= PGA_REQUEUE;
838f3f38e25SMark Johnston 				new.queue = PQ_ACTIVE;
839f3f38e25SMark Johnston 				if (!vm_page_pqstate_commit(m, &old, new))
840f3f38e25SMark Johnston 					continue;
841e8bcf696SMark Johnston 
842e8bcf696SMark Johnston 				/*
843e8bcf696SMark Johnston 				 * If this was a background laundering, count
844e8bcf696SMark Johnston 				 * activated pages towards our target.  The
845e8bcf696SMark Johnston 				 * purpose of background laundering is to ensure
846e8bcf696SMark Johnston 				 * that pages are eventually cycled through the
847e8bcf696SMark Johnston 				 * laundry queue, and an activation is a valid
848e8bcf696SMark Johnston 				 * way out.
849ebcddc72SAlan Cox 				 */
850ebcddc72SAlan Cox 				if (!in_shortfall)
851ebcddc72SAlan Cox 					launder--;
852f3f38e25SMark Johnston 				VM_CNT_INC(v_reactivated);
853f3f38e25SMark Johnston 				goto skip_page;
8545cd29d0fSMark Johnston 			} else if ((object->flags & OBJ_DEAD) == 0) {
855f3f38e25SMark Johnston 				new.flags |= PGA_REQUEUE;
856f3f38e25SMark Johnston 				if (!vm_page_pqstate_commit(m, &old, new))
857e8bcf696SMark Johnston 					continue;
858f3f38e25SMark Johnston 				goto skip_page;
8595cd29d0fSMark Johnston 			}
860f3f38e25SMark Johnston 			break;
861ebcddc72SAlan Cox 		}
862ebcddc72SAlan Cox 
863ebcddc72SAlan Cox 		/*
864ebcddc72SAlan Cox 		 * If the page appears to be clean at the machine-independent
865ebcddc72SAlan Cox 		 * layer, then remove all of its mappings from the pmap in
866ebcddc72SAlan Cox 		 * anticipation of freeing it.  If, however, any of the page's
867ebcddc72SAlan Cox 		 * mappings allow write access, then the page may still be
868ebcddc72SAlan Cox 		 * modified until the last of those mappings are removed.
869ebcddc72SAlan Cox 		 */
870ebcddc72SAlan Cox 		if (object->ref_count != 0) {
871ebcddc72SAlan Cox 			vm_page_test_dirty(m);
8729f5632e6SMark Johnston 			if (m->dirty == 0 && !vm_page_try_remove_all(m))
873f3f38e25SMark Johnston 				goto skip_page;
874fee2a2faSMark Johnston 		}
875ebcddc72SAlan Cox 
876ebcddc72SAlan Cox 		/*
877ebcddc72SAlan Cox 		 * Clean pages are freed, and dirty pages are paged out unless
878ebcddc72SAlan Cox 		 * they belong to a dead object.  Requeueing dirty pages from
879ebcddc72SAlan Cox 		 * dead objects is pointless, as they are being paged out and
880ebcddc72SAlan Cox 		 * freed by the thread that destroyed the object.
881ebcddc72SAlan Cox 		 */
882ebcddc72SAlan Cox 		if (m->dirty == 0) {
883ebcddc72SAlan Cox free_page:
8849f5632e6SMark Johnston 			/*
8859f5632e6SMark Johnston 			 * Now we are guaranteed that no other threads are
8869f5632e6SMark Johnston 			 * manipulating the page, check for a last-second
8879f5632e6SMark Johnston 			 * reference.
8889f5632e6SMark Johnston 			 */
8899f5632e6SMark Johnston 			if (vm_pageout_defer(m, queue, true))
8909f5632e6SMark Johnston 				goto skip_page;
891ebcddc72SAlan Cox 			vm_page_free(m);
89283c9dea1SGleb Smirnoff 			VM_CNT_INC(v_dfree);
893ebcddc72SAlan Cox 		} else if ((object->flags & OBJ_DEAD) == 0) {
894ebcddc72SAlan Cox 			if (object->type != OBJT_SWAP &&
895ebcddc72SAlan Cox 			    object->type != OBJT_DEFAULT)
896ebcddc72SAlan Cox 				pageout_ok = true;
897ebcddc72SAlan Cox 			else if (disable_swap_pageouts)
898ebcddc72SAlan Cox 				pageout_ok = false;
899ebcddc72SAlan Cox 			else
900ebcddc72SAlan Cox 				pageout_ok = true;
901ebcddc72SAlan Cox 			if (!pageout_ok) {
902f3f38e25SMark Johnston 				vm_page_launder(m);
903f3f38e25SMark Johnston 				goto skip_page;
904ebcddc72SAlan Cox 			}
905ebcddc72SAlan Cox 
906ebcddc72SAlan Cox 			/*
907ebcddc72SAlan Cox 			 * Form a cluster with adjacent, dirty pages from the
908ebcddc72SAlan Cox 			 * same object, and page out that entire cluster.
909ebcddc72SAlan Cox 			 *
910ebcddc72SAlan Cox 			 * The adjacent, dirty pages must also be in the
911ebcddc72SAlan Cox 			 * laundry.  However, their mappings are not checked
912ebcddc72SAlan Cox 			 * for new references.  Consequently, a recently
913ebcddc72SAlan Cox 			 * referenced page may be paged out.  However, that
914ebcddc72SAlan Cox 			 * page will not be prematurely reclaimed.  After page
915ebcddc72SAlan Cox 			 * out, the page will be placed in the inactive queue,
916ebcddc72SAlan Cox 			 * where any new references will be detected and the
917ebcddc72SAlan Cox 			 * page reactivated.
918ebcddc72SAlan Cox 			 */
919ebcddc72SAlan Cox 			error = vm_pageout_clean(m, &numpagedout);
920ebcddc72SAlan Cox 			if (error == 0) {
921ebcddc72SAlan Cox 				launder -= numpagedout;
9225cd29d0fSMark Johnston 				ss.scanned += numpagedout;
923ebcddc72SAlan Cox 			} else if (error == EDEADLK) {
924ebcddc72SAlan Cox 				pageout_lock_miss++;
925ebcddc72SAlan Cox 				vnodes_skipped++;
926ebcddc72SAlan Cox 			}
92760256604SMark Johnston 			object = NULL;
928f3f38e25SMark Johnston 		} else {
929f3f38e25SMark Johnston skip_page:
93063e97555SJeff Roberson 			vm_page_xunbusy(m);
931e8bcf696SMark Johnston 		}
932f3f38e25SMark Johnston 	}
93346e39081SMark Johnston 	if (object != NULL) {
934ebcddc72SAlan Cox 		VM_OBJECT_WUNLOCK(object);
93546e39081SMark Johnston 		object = NULL;
93646e39081SMark Johnston 	}
937ebcddc72SAlan Cox 	vm_pagequeue_lock(pq);
9385cd29d0fSMark Johnston 	vm_pageout_end_scan(&ss);
939ebcddc72SAlan Cox 	vm_pagequeue_unlock(pq);
940ebcddc72SAlan Cox 
94164b38930SMark Johnston 	if (launder > 0 && queue == PQ_UNSWAPPABLE) {
94264b38930SMark Johnston 		queue = PQ_LAUNDRY;
943b1fd102eSMark Johnston 		goto scan;
944b1fd102eSMark Johnston 	}
945b1fd102eSMark Johnston 
946ebcddc72SAlan Cox 	/*
947ebcddc72SAlan Cox 	 * Wakeup the sync daemon if we skipped a vnode in a writeable object
948ebcddc72SAlan Cox 	 * and we didn't launder enough pages.
949ebcddc72SAlan Cox 	 */
950ebcddc72SAlan Cox 	if (vnodes_skipped > 0 && launder > 0)
951ebcddc72SAlan Cox 		(void)speedup_syncer();
952ebcddc72SAlan Cox 
953ebcddc72SAlan Cox 	return (starting_target - launder);
954ebcddc72SAlan Cox }
955ebcddc72SAlan Cox 
956ebcddc72SAlan Cox /*
957ebcddc72SAlan Cox  * Compute the integer square root.
958ebcddc72SAlan Cox  */
959ebcddc72SAlan Cox static u_int
960ebcddc72SAlan Cox isqrt(u_int num)
961ebcddc72SAlan Cox {
962ebcddc72SAlan Cox 	u_int bit, root, tmp;
963ebcddc72SAlan Cox 
96464f8d257SDoug Moore 	bit = num != 0 ? (1u << ((fls(num) - 1) & ~1)) : 0;
965ebcddc72SAlan Cox 	root = 0;
966ebcddc72SAlan Cox 	while (bit != 0) {
967ebcddc72SAlan Cox 		tmp = root + bit;
968ebcddc72SAlan Cox 		root >>= 1;
969ebcddc72SAlan Cox 		if (num >= tmp) {
970ebcddc72SAlan Cox 			num -= tmp;
971ebcddc72SAlan Cox 			root += bit;
972ebcddc72SAlan Cox 		}
973ebcddc72SAlan Cox 		bit >>= 2;
974ebcddc72SAlan Cox 	}
975ebcddc72SAlan Cox 	return (root);
976ebcddc72SAlan Cox }
977ebcddc72SAlan Cox 
978ebcddc72SAlan Cox /*
979ebcddc72SAlan Cox  * Perform the work of the laundry thread: periodically wake up and determine
980ebcddc72SAlan Cox  * whether any pages need to be laundered.  If so, determine the number of pages
981ebcddc72SAlan Cox  * that need to be laundered, and launder them.
982ebcddc72SAlan Cox  */
983ebcddc72SAlan Cox static void
984ebcddc72SAlan Cox vm_pageout_laundry_worker(void *arg)
985ebcddc72SAlan Cox {
986e2068d0bSJeff Roberson 	struct vm_domain *vmd;
987ebcddc72SAlan Cox 	struct vm_pagequeue *pq;
98860684862SMark Johnston 	uint64_t nclean, ndirty, nfreed;
989e2068d0bSJeff Roberson 	int domain, last_target, launder, shortfall, shortfall_cycle, target;
990ebcddc72SAlan Cox 	bool in_shortfall;
991ebcddc72SAlan Cox 
992e2068d0bSJeff Roberson 	domain = (uintptr_t)arg;
993e2068d0bSJeff Roberson 	vmd = VM_DOMAIN(domain);
994e2068d0bSJeff Roberson 	pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
995e2068d0bSJeff Roberson 	KASSERT(vmd->vmd_segs != 0, ("domain without segments"));
996ebcddc72SAlan Cox 
997ebcddc72SAlan Cox 	shortfall = 0;
998ebcddc72SAlan Cox 	in_shortfall = false;
999ebcddc72SAlan Cox 	shortfall_cycle = 0;
10008002c3a4SMark Johnston 	last_target = target = 0;
100160684862SMark Johnston 	nfreed = 0;
1002ebcddc72SAlan Cox 
1003ebcddc72SAlan Cox 	/*
1004b1fd102eSMark Johnston 	 * Calls to these handlers are serialized by the swap syscall lock.
1005b1fd102eSMark Johnston 	 */
1006e2068d0bSJeff Roberson 	(void)EVENTHANDLER_REGISTER(swapon, vm_pageout_swapon, vmd,
1007b1fd102eSMark Johnston 	    EVENTHANDLER_PRI_ANY);
1008e2068d0bSJeff Roberson 	(void)EVENTHANDLER_REGISTER(swapoff, vm_pageout_swapoff, vmd,
1009b1fd102eSMark Johnston 	    EVENTHANDLER_PRI_ANY);
1010b1fd102eSMark Johnston 
1011b1fd102eSMark Johnston 	/*
1012ebcddc72SAlan Cox 	 * The pageout laundry worker is never done, so loop forever.
1013ebcddc72SAlan Cox 	 */
1014ebcddc72SAlan Cox 	for (;;) {
1015ebcddc72SAlan Cox 		KASSERT(target >= 0, ("negative target %d", target));
1016ebcddc72SAlan Cox 		KASSERT(shortfall_cycle >= 0,
1017ebcddc72SAlan Cox 		    ("negative cycle %d", shortfall_cycle));
1018ebcddc72SAlan Cox 		launder = 0;
1019ebcddc72SAlan Cox 
1020ebcddc72SAlan Cox 		/*
1021ebcddc72SAlan Cox 		 * First determine whether we need to launder pages to meet a
1022ebcddc72SAlan Cox 		 * shortage of free pages.
1023ebcddc72SAlan Cox 		 */
1024ebcddc72SAlan Cox 		if (shortfall > 0) {
1025ebcddc72SAlan Cox 			in_shortfall = true;
1026ebcddc72SAlan Cox 			shortfall_cycle = VM_LAUNDER_RATE / VM_INACT_SCAN_RATE;
1027ebcddc72SAlan Cox 			target = shortfall;
1028ebcddc72SAlan Cox 		} else if (!in_shortfall)
1029ebcddc72SAlan Cox 			goto trybackground;
1030e2068d0bSJeff Roberson 		else if (shortfall_cycle == 0 || vm_laundry_target(vmd) <= 0) {
1031ebcddc72SAlan Cox 			/*
1032ebcddc72SAlan Cox 			 * We recently entered shortfall and began laundering
1033ebcddc72SAlan Cox 			 * pages.  If we have completed that laundering run
1034ebcddc72SAlan Cox 			 * (and we are no longer in shortfall) or we have met
1035ebcddc72SAlan Cox 			 * our laundry target through other activity, then we
1036ebcddc72SAlan Cox 			 * can stop laundering pages.
1037ebcddc72SAlan Cox 			 */
1038ebcddc72SAlan Cox 			in_shortfall = false;
1039ebcddc72SAlan Cox 			target = 0;
1040ebcddc72SAlan Cox 			goto trybackground;
1041ebcddc72SAlan Cox 		}
1042ebcddc72SAlan Cox 		launder = target / shortfall_cycle--;
1043ebcddc72SAlan Cox 		goto dolaundry;
1044ebcddc72SAlan Cox 
1045ebcddc72SAlan Cox 		/*
1046ebcddc72SAlan Cox 		 * There's no immediate need to launder any pages; see if we
1047ebcddc72SAlan Cox 		 * meet the conditions to perform background laundering:
1048ebcddc72SAlan Cox 		 *
1049ebcddc72SAlan Cox 		 * 1. The ratio of dirty to clean inactive pages exceeds the
105060684862SMark Johnston 		 *    background laundering threshold, or
1051ebcddc72SAlan Cox 		 * 2. we haven't yet reached the target of the current
1052ebcddc72SAlan Cox 		 *    background laundering run.
1053ebcddc72SAlan Cox 		 *
1054ebcddc72SAlan Cox 		 * The background laundering threshold is not a constant.
1055ebcddc72SAlan Cox 		 * Instead, it is a slowly growing function of the number of
105660684862SMark Johnston 		 * clean pages freed by the page daemon since the last
105760684862SMark Johnston 		 * background laundering.  Thus, as the ratio of dirty to
105860684862SMark Johnston 		 * clean inactive pages grows, the amount of memory pressure
1059c098768eSMark Johnston 		 * required to trigger laundering decreases.  We ensure
1060c098768eSMark Johnston 		 * that the threshold is non-zero after an inactive queue
1061c098768eSMark Johnston 		 * scan, even if that scan failed to free a single clean page.
1062ebcddc72SAlan Cox 		 */
1063ebcddc72SAlan Cox trybackground:
1064e2068d0bSJeff Roberson 		nclean = vmd->vmd_free_count +
1065e2068d0bSJeff Roberson 		    vmd->vmd_pagequeues[PQ_INACTIVE].pq_cnt;
1066e2068d0bSJeff Roberson 		ndirty = vmd->vmd_pagequeues[PQ_LAUNDRY].pq_cnt;
1067c098768eSMark Johnston 		if (target == 0 && ndirty * isqrt(howmany(nfreed + 1,
1068c098768eSMark Johnston 		    vmd->vmd_free_target - vmd->vmd_free_min)) >= nclean) {
1069e2068d0bSJeff Roberson 			target = vmd->vmd_background_launder_target;
1070ebcddc72SAlan Cox 		}
1071ebcddc72SAlan Cox 
1072ebcddc72SAlan Cox 		/*
1073ebcddc72SAlan Cox 		 * We have a non-zero background laundering target.  If we've
1074ebcddc72SAlan Cox 		 * laundered up to our maximum without observing a page daemon
1075cb35676eSMark Johnston 		 * request, just stop.  This is a safety belt that ensures we
1076ebcddc72SAlan Cox 		 * don't launder an excessive amount if memory pressure is low
1077ebcddc72SAlan Cox 		 * and the ratio of dirty to clean pages is large.  Otherwise,
1078ebcddc72SAlan Cox 		 * proceed at the background laundering rate.
1079ebcddc72SAlan Cox 		 */
1080ebcddc72SAlan Cox 		if (target > 0) {
108160684862SMark Johnston 			if (nfreed > 0) {
108260684862SMark Johnston 				nfreed = 0;
1083ebcddc72SAlan Cox 				last_target = target;
1084ebcddc72SAlan Cox 			} else if (last_target - target >=
1085ebcddc72SAlan Cox 			    vm_background_launder_max * PAGE_SIZE / 1024) {
1086ebcddc72SAlan Cox 				target = 0;
1087ebcddc72SAlan Cox 			}
1088ebcddc72SAlan Cox 			launder = vm_background_launder_rate * PAGE_SIZE / 1024;
1089ebcddc72SAlan Cox 			launder /= VM_LAUNDER_RATE;
1090ebcddc72SAlan Cox 			if (launder > target)
1091ebcddc72SAlan Cox 				launder = target;
1092ebcddc72SAlan Cox 		}
1093ebcddc72SAlan Cox 
1094ebcddc72SAlan Cox dolaundry:
1095ebcddc72SAlan Cox 		if (launder > 0) {
1096ebcddc72SAlan Cox 			/*
1097ebcddc72SAlan Cox 			 * Because of I/O clustering, the number of laundered
1098ebcddc72SAlan Cox 			 * pages could exceed "target" by the maximum size of
1099ebcddc72SAlan Cox 			 * a cluster minus one.
1100ebcddc72SAlan Cox 			 */
1101e2068d0bSJeff Roberson 			target -= min(vm_pageout_launder(vmd, launder,
1102ebcddc72SAlan Cox 			    in_shortfall), target);
1103ebcddc72SAlan Cox 			pause("laundp", hz / VM_LAUNDER_RATE);
1104ebcddc72SAlan Cox 		}
1105ebcddc72SAlan Cox 
1106ebcddc72SAlan Cox 		/*
1107ebcddc72SAlan Cox 		 * If we're not currently laundering pages and the page daemon
1108ebcddc72SAlan Cox 		 * hasn't posted a new request, sleep until the page daemon
1109ebcddc72SAlan Cox 		 * kicks us.
1110ebcddc72SAlan Cox 		 */
1111ebcddc72SAlan Cox 		vm_pagequeue_lock(pq);
1112e2068d0bSJeff Roberson 		if (target == 0 && vmd->vmd_laundry_request == VM_LAUNDRY_IDLE)
1113e2068d0bSJeff Roberson 			(void)mtx_sleep(&vmd->vmd_laundry_request,
1114ebcddc72SAlan Cox 			    vm_pagequeue_lockptr(pq), PVM, "launds", 0);
1115ebcddc72SAlan Cox 
1116ebcddc72SAlan Cox 		/*
1117ebcddc72SAlan Cox 		 * If the pagedaemon has indicated that it's in shortfall, start
1118ebcddc72SAlan Cox 		 * a shortfall laundering unless we're already in the middle of
1119ebcddc72SAlan Cox 		 * one.  This may preempt a background laundering.
1120ebcddc72SAlan Cox 		 */
1121e2068d0bSJeff Roberson 		if (vmd->vmd_laundry_request == VM_LAUNDRY_SHORTFALL &&
1122ebcddc72SAlan Cox 		    (!in_shortfall || shortfall_cycle == 0)) {
1123e2068d0bSJeff Roberson 			shortfall = vm_laundry_target(vmd) +
1124e2068d0bSJeff Roberson 			    vmd->vmd_pageout_deficit;
1125ebcddc72SAlan Cox 			target = 0;
1126ebcddc72SAlan Cox 		} else
1127ebcddc72SAlan Cox 			shortfall = 0;
1128ebcddc72SAlan Cox 
1129ebcddc72SAlan Cox 		if (target == 0)
1130e2068d0bSJeff Roberson 			vmd->vmd_laundry_request = VM_LAUNDRY_IDLE;
113160684862SMark Johnston 		nfreed += vmd->vmd_clean_pages_freed;
113260684862SMark Johnston 		vmd->vmd_clean_pages_freed = 0;
1133ebcddc72SAlan Cox 		vm_pagequeue_unlock(pq);
1134ebcddc72SAlan Cox 	}
1135ebcddc72SAlan Cox }
1136ebcddc72SAlan Cox 
1137be37ee79SMark Johnston /*
1138be37ee79SMark Johnston  * Compute the number of pages we want to try to move from the
1139be37ee79SMark Johnston  * active queue to either the inactive or laundry queue.
1140be37ee79SMark Johnston  *
11417bb4634eSMark Johnston  * When scanning active pages during a shortage, we make clean pages
11427bb4634eSMark Johnston  * count more heavily towards the page shortage than dirty pages.
11437bb4634eSMark Johnston  * This is because dirty pages must be laundered before they can be
11447bb4634eSMark Johnston  * reused and thus have less utility when attempting to quickly
11457bb4634eSMark Johnston  * alleviate a free page shortage.  However, this weighting also
11467bb4634eSMark Johnston  * causes the scan to deactivate dirty pages more aggressively,
11477bb4634eSMark Johnston  * improving the effectiveness of clustering.
1148be37ee79SMark Johnston  */
1149be37ee79SMark Johnston static int
11507bb4634eSMark Johnston vm_pageout_active_target(struct vm_domain *vmd)
1151be37ee79SMark Johnston {
1152be37ee79SMark Johnston 	int shortage;
1153be37ee79SMark Johnston 
1154be37ee79SMark Johnston 	shortage = vmd->vmd_inactive_target + vm_paging_target(vmd) -
1155be37ee79SMark Johnston 	    (vmd->vmd_pagequeues[PQ_INACTIVE].pq_cnt +
1156be37ee79SMark Johnston 	    vmd->vmd_pagequeues[PQ_LAUNDRY].pq_cnt / act_scan_laundry_weight);
1157be37ee79SMark Johnston 	shortage *= act_scan_laundry_weight;
1158be37ee79SMark Johnston 	return (shortage);
1159be37ee79SMark Johnston }
1160be37ee79SMark Johnston 
1161be37ee79SMark Johnston /*
1162be37ee79SMark Johnston  * Scan the active queue.  If there is no shortage of inactive pages, scan a
1163be37ee79SMark Johnston  * small portion of the queue in order to maintain quasi-LRU.
1164be37ee79SMark Johnston  */
1165be37ee79SMark Johnston static void
1166be37ee79SMark Johnston vm_pageout_scan_active(struct vm_domain *vmd, int page_shortage)
1167be37ee79SMark Johnston {
1168be37ee79SMark Johnston 	struct scan_state ss;
1169fee2a2faSMark Johnston 	vm_object_t object;
1170be37ee79SMark Johnston 	vm_page_t m, marker;
1171be37ee79SMark Johnston 	struct vm_pagequeue *pq;
1172f3f38e25SMark Johnston 	vm_page_astate_t old, new;
1173be37ee79SMark Johnston 	long min_scan;
1174f3f38e25SMark Johnston 	int act_delta, max_scan, ps_delta, refs, scan_tick;
1175f3f38e25SMark Johnston 	uint8_t nqueue;
1176be37ee79SMark Johnston 
1177be37ee79SMark Johnston 	marker = &vmd->vmd_markers[PQ_ACTIVE];
1178be37ee79SMark Johnston 	pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1179be37ee79SMark Johnston 	vm_pagequeue_lock(pq);
1180be37ee79SMark Johnston 
1181be37ee79SMark Johnston 	/*
1182be37ee79SMark Johnston 	 * If we're just idle polling attempt to visit every
1183be37ee79SMark Johnston 	 * active page within 'update_period' seconds.
1184be37ee79SMark Johnston 	 */
1185be37ee79SMark Johnston 	scan_tick = ticks;
1186be37ee79SMark Johnston 	if (vm_pageout_update_period != 0) {
1187be37ee79SMark Johnston 		min_scan = pq->pq_cnt;
1188be37ee79SMark Johnston 		min_scan *= scan_tick - vmd->vmd_last_active_scan;
1189be37ee79SMark Johnston 		min_scan /= hz * vm_pageout_update_period;
1190be37ee79SMark Johnston 	} else
1191be37ee79SMark Johnston 		min_scan = 0;
1192be37ee79SMark Johnston 	if (min_scan > 0 || (page_shortage > 0 && pq->pq_cnt > 0))
1193be37ee79SMark Johnston 		vmd->vmd_last_active_scan = scan_tick;
1194be37ee79SMark Johnston 
1195be37ee79SMark Johnston 	/*
1196be37ee79SMark Johnston 	 * Scan the active queue for pages that can be deactivated.  Update
1197be37ee79SMark Johnston 	 * the per-page activity counter and use it to identify deactivation
1198be37ee79SMark Johnston 	 * candidates.  Held pages may be deactivated.
1199be37ee79SMark Johnston 	 *
1200be37ee79SMark Johnston 	 * To avoid requeuing each page that remains in the active queue, we
12017bb4634eSMark Johnston 	 * implement the CLOCK algorithm.  To keep the implementation of the
12027bb4634eSMark Johnston 	 * enqueue operation consistent for all page queues, we use two hands,
12037bb4634eSMark Johnston 	 * represented by marker pages. Scans begin at the first hand, which
12047bb4634eSMark Johnston 	 * precedes the second hand in the queue.  When the two hands meet,
12057bb4634eSMark Johnston 	 * they are moved back to the head and tail of the queue, respectively,
12067bb4634eSMark Johnston 	 * and scanning resumes.
1207be37ee79SMark Johnston 	 */
1208be37ee79SMark Johnston 	max_scan = page_shortage > 0 ? pq->pq_cnt : min_scan;
1209be37ee79SMark Johnston act_scan:
1210be37ee79SMark Johnston 	vm_pageout_init_scan(&ss, pq, marker, &vmd->vmd_clock[0], max_scan);
1211be37ee79SMark Johnston 	while ((m = vm_pageout_next(&ss, false)) != NULL) {
1212be37ee79SMark Johnston 		if (__predict_false(m == &vmd->vmd_clock[1])) {
1213be37ee79SMark Johnston 			vm_pagequeue_lock(pq);
1214be37ee79SMark Johnston 			TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_clock[0], plinks.q);
1215be37ee79SMark Johnston 			TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_clock[1], plinks.q);
1216be37ee79SMark Johnston 			TAILQ_INSERT_HEAD(&pq->pq_pl, &vmd->vmd_clock[0],
1217be37ee79SMark Johnston 			    plinks.q);
1218be37ee79SMark Johnston 			TAILQ_INSERT_TAIL(&pq->pq_pl, &vmd->vmd_clock[1],
1219be37ee79SMark Johnston 			    plinks.q);
1220be37ee79SMark Johnston 			max_scan -= ss.scanned;
1221be37ee79SMark Johnston 			vm_pageout_end_scan(&ss);
1222be37ee79SMark Johnston 			goto act_scan;
1223be37ee79SMark Johnston 		}
1224be37ee79SMark Johnston 		if (__predict_false((m->flags & PG_MARKER) != 0))
1225be37ee79SMark Johnston 			continue;
1226be37ee79SMark Johnston 
1227e8bcf696SMark Johnston 		/*
1228b7f30bffSMark Johnston 		 * Don't touch a page that was removed from the queue after the
1229b7f30bffSMark Johnston 		 * page queue lock was released.  Otherwise, ensure that any
1230b7f30bffSMark Johnston 		 * pending queue operations, such as dequeues for wired pages,
1231b7f30bffSMark Johnston 		 * are handled.
1232e8bcf696SMark Johnston 		 */
1233b7f30bffSMark Johnston 		if (vm_pageout_defer(m, PQ_ACTIVE, true))
1234e8bcf696SMark Johnston 			continue;
1235e8bcf696SMark Johnston 
1236e8bcf696SMark Johnston 		/*
1237e8bcf696SMark Johnston 		 * A page's object pointer may be set to NULL before
1238e8bcf696SMark Johnston 		 * the object lock is acquired.
1239e8bcf696SMark Johnston 		 */
124023ed568cSMateusz Guzik 		object = atomic_load_ptr(&m->object);
1241fee2a2faSMark Johnston 		if (__predict_false(object == NULL))
1242fee2a2faSMark Johnston 			/*
1243fee2a2faSMark Johnston 			 * The page has been removed from its object.
1244fee2a2faSMark Johnston 			 */
1245fee2a2faSMark Johnston 			continue;
1246fee2a2faSMark Johnston 
1247f3f38e25SMark Johnston 		/* Deferred free of swap space. */
1248f3f38e25SMark Johnston 		if ((m->a.flags & PGA_SWAP_FREE) != 0 &&
1249f3f38e25SMark Johnston 		    VM_OBJECT_TRYWLOCK(object)) {
1250f3f38e25SMark Johnston 			if (m->object == object)
1251f3f38e25SMark Johnston 				vm_pager_page_unswapped(m);
1252f3f38e25SMark Johnston 			VM_OBJECT_WUNLOCK(object);
1253f3f38e25SMark Johnston 		}
1254f3f38e25SMark Johnston 
1255fee2a2faSMark Johnston 		/*
1256be37ee79SMark Johnston 		 * Check to see "how much" the page has been used.
1257d7aeb429SAlan Cox 		 *
1258d7aeb429SAlan Cox 		 * Test PGA_REFERENCED after calling pmap_ts_referenced() so
1259d7aeb429SAlan Cox 		 * that a reference from a concurrently destroyed mapping is
1260d7aeb429SAlan Cox 		 * observed here and now.
1261d7aeb429SAlan Cox 		 *
1262e8bcf696SMark Johnston 		 * Perform an unsynchronized object ref count check.  While
1263e8bcf696SMark Johnston 		 * the page lock ensures that the page is not reallocated to
1264e8bcf696SMark Johnston 		 * another object, in particular, one with unmanaged mappings
1265e8bcf696SMark Johnston 		 * that cannot support pmap_ts_referenced(), two races are,
1266be37ee79SMark Johnston 		 * nonetheless, possible:
1267be37ee79SMark Johnston 		 * 1) The count was transitioning to zero, but we saw a non-
1268e8bcf696SMark Johnston 		 *    zero value.  pmap_ts_referenced() will return zero
1269e8bcf696SMark Johnston 		 *    because the page is not mapped.
1270e8bcf696SMark Johnston 		 * 2) The count was transitioning to one, but we saw zero.
1271e8bcf696SMark Johnston 		 *    This race delays the detection of a new reference.  At
1272e8bcf696SMark Johnston 		 *    worst, we will deactivate and reactivate the page.
1273be37ee79SMark Johnston 		 */
1274f3f38e25SMark Johnston 		refs = object->ref_count != 0 ? pmap_ts_referenced(m) : 0;
1275be37ee79SMark Johnston 
1276f3f38e25SMark Johnston 		old = vm_page_astate_load(m);
1277f3f38e25SMark Johnston 		do {
1278f3f38e25SMark Johnston 			/*
1279f3f38e25SMark Johnston 			 * Check to see if the page has been removed from the
1280f3f38e25SMark Johnston 			 * queue since the first such check.  Leave it alone if
1281f3f38e25SMark Johnston 			 * so, discarding any references collected by
1282f3f38e25SMark Johnston 			 * pmap_ts_referenced().
1283f3f38e25SMark Johnston 			 */
1284f3f38e25SMark Johnston 			if (__predict_false(_vm_page_queue(old) == PQ_NONE))
1285f3f38e25SMark Johnston 				break;
1286a8081778SJeff Roberson 
1287be37ee79SMark Johnston 			/*
1288be37ee79SMark Johnston 			 * Advance or decay the act_count based on recent usage.
1289be37ee79SMark Johnston 			 */
1290f3f38e25SMark Johnston 			new = old;
1291f3f38e25SMark Johnston 			act_delta = refs;
1292f3f38e25SMark Johnston 			if ((old.flags & PGA_REFERENCED) != 0) {
1293f3f38e25SMark Johnston 				new.flags &= ~PGA_REFERENCED;
1294f3f38e25SMark Johnston 				act_delta++;
1295f3f38e25SMark Johnston 			}
1296be37ee79SMark Johnston 			if (act_delta != 0) {
1297f3f38e25SMark Johnston 				new.act_count += ACT_ADVANCE + act_delta;
1298f3f38e25SMark Johnston 				if (new.act_count > ACT_MAX)
1299f3f38e25SMark Johnston 					new.act_count = ACT_MAX;
1300f3f38e25SMark Johnston 			} else {
1301f3f38e25SMark Johnston 				new.act_count -= min(new.act_count,
1302f3f38e25SMark Johnston 				    ACT_DECLINE);
1303f3f38e25SMark Johnston 			}
1304be37ee79SMark Johnston 
1305f3f38e25SMark Johnston 			if (new.act_count > 0) {
1306be37ee79SMark Johnston 				/*
1307f3f38e25SMark Johnston 				 * Adjust the activation count and keep the page
1308f3f38e25SMark Johnston 				 * in the active queue.  The count might be left
1309f3f38e25SMark Johnston 				 * unchanged if it is saturated.  The page may
1310f3f38e25SMark Johnston 				 * have been moved to a different queue since we
1311f3f38e25SMark Johnston 				 * started the scan, in which case we move it
1312f3f38e25SMark Johnston 				 * back.
1313be37ee79SMark Johnston 				 */
1314f3f38e25SMark Johnston 				ps_delta = 0;
1315f3f38e25SMark Johnston 				if (old.queue != PQ_ACTIVE) {
1316f7607c30SMark Johnston 					new.flags &= ~PGA_QUEUE_OP_MASK;
1317f7607c30SMark Johnston 					new.flags |= PGA_REQUEUE;
1318f7607c30SMark Johnston 					new.queue = PQ_ACTIVE;
1319f3f38e25SMark Johnston 				}
13207cdeaf33SMark Johnston 			} else {
1321be37ee79SMark Johnston 				/*
1322f3f38e25SMark Johnston 				 * When not short for inactive pages, let dirty
1323f3f38e25SMark Johnston 				 * pages go through the inactive queue before
1324f3f38e25SMark Johnston 				 * moving to the laundry queue.  This gives them
1325f3f38e25SMark Johnston 				 * some extra time to be reactivated,
1326f3f38e25SMark Johnston 				 * potentially avoiding an expensive pageout.
1327f3f38e25SMark Johnston 				 * However, during a page shortage, the inactive
1328f3f38e25SMark Johnston 				 * queue is necessarily small, and so dirty
1329f3f38e25SMark Johnston 				 * pages would only spend a trivial amount of
1330f3f38e25SMark Johnston 				 * time in the inactive queue.  Therefore, we
1331f3f38e25SMark Johnston 				 * might as well place them directly in the
1332f3f38e25SMark Johnston 				 * laundry queue to reduce queuing overhead.
1333f3f38e25SMark Johnston 				 *
1334be37ee79SMark Johnston 				 * Calling vm_page_test_dirty() here would
1335be37ee79SMark Johnston 				 * require acquisition of the object's write
1336be37ee79SMark Johnston 				 * lock.  However, during a page shortage,
1337f3f38e25SMark Johnston 				 * directing dirty pages into the laundry queue
1338f3f38e25SMark Johnston 				 * is only an optimization and not a
1339be37ee79SMark Johnston 				 * requirement.  Therefore, we simply rely on
1340f3f38e25SMark Johnston 				 * the opportunistic updates to the page's dirty
1341f3f38e25SMark Johnston 				 * field by the pmap.
1342be37ee79SMark Johnston 				 */
1343f3f38e25SMark Johnston 				if (page_shortage <= 0) {
1344f3f38e25SMark Johnston 					nqueue = PQ_INACTIVE;
1345f3f38e25SMark Johnston 					ps_delta = 0;
1346f3f38e25SMark Johnston 				} else if (m->dirty == 0) {
1347f3f38e25SMark Johnston 					nqueue = PQ_INACTIVE;
1348f3f38e25SMark Johnston 					ps_delta = act_scan_laundry_weight;
1349be37ee79SMark Johnston 				} else {
1350f3f38e25SMark Johnston 					nqueue = PQ_LAUNDRY;
1351f3f38e25SMark Johnston 					ps_delta = 1;
1352be37ee79SMark Johnston 				}
1353f3f38e25SMark Johnston 
1354f7607c30SMark Johnston 				new.flags &= ~PGA_QUEUE_OP_MASK;
1355f3f38e25SMark Johnston 				new.flags |= PGA_REQUEUE;
1356f3f38e25SMark Johnston 				new.queue = nqueue;
1357be37ee79SMark Johnston 			}
1358f3f38e25SMark Johnston 		} while (!vm_page_pqstate_commit(m, &old, new));
1359f3f38e25SMark Johnston 
1360f3f38e25SMark Johnston 		page_shortage -= ps_delta;
1361be37ee79SMark Johnston 	}
1362be37ee79SMark Johnston 	vm_pagequeue_lock(pq);
1363be37ee79SMark Johnston 	TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_clock[0], plinks.q);
1364be37ee79SMark Johnston 	TAILQ_INSERT_AFTER(&pq->pq_pl, marker, &vmd->vmd_clock[0], plinks.q);
1365be37ee79SMark Johnston 	vm_pageout_end_scan(&ss);
1366be37ee79SMark Johnston 	vm_pagequeue_unlock(pq);
1367be37ee79SMark Johnston }
1368be37ee79SMark Johnston 
13695cd29d0fSMark Johnston static int
1370f3f38e25SMark Johnston vm_pageout_reinsert_inactive_page(struct vm_pagequeue *pq, vm_page_t marker,
1371f3f38e25SMark Johnston     vm_page_t m)
13725cd29d0fSMark Johnston {
1373f3f38e25SMark Johnston 	vm_page_astate_t as;
13745cd29d0fSMark Johnston 
1375f3f38e25SMark Johnston 	vm_pagequeue_assert_locked(pq);
1376f3f38e25SMark Johnston 
1377f3f38e25SMark Johnston 	as = vm_page_astate_load(m);
1378f3f38e25SMark Johnston 	if (as.queue != PQ_INACTIVE || (as.flags & PGA_ENQUEUED) != 0)
1379e8bcf696SMark Johnston 		return (0);
1380e8bcf696SMark Johnston 	vm_page_aflag_set(m, PGA_ENQUEUED);
1381f3f38e25SMark Johnston 	TAILQ_INSERT_BEFORE(marker, m, plinks.q);
13825cd29d0fSMark Johnston 	return (1);
13835cd29d0fSMark Johnston }
13845cd29d0fSMark Johnston 
13855cd29d0fSMark Johnston /*
13865cd29d0fSMark Johnston  * Re-add stuck pages to the inactive queue.  We will examine them again
13875cd29d0fSMark Johnston  * during the next scan.  If the queue state of a page has changed since
13885cd29d0fSMark Johnston  * it was physically removed from the page queue in
13895cd29d0fSMark Johnston  * vm_pageout_collect_batch(), don't do anything with that page.
13905cd29d0fSMark Johnston  */
13915cd29d0fSMark Johnston static void
13925cd29d0fSMark Johnston vm_pageout_reinsert_inactive(struct scan_state *ss, struct vm_batchqueue *bq,
13935cd29d0fSMark Johnston     vm_page_t m)
13945cd29d0fSMark Johnston {
13955cd29d0fSMark Johnston 	struct vm_pagequeue *pq;
1396f3f38e25SMark Johnston 	vm_page_t marker;
13975cd29d0fSMark Johnston 	int delta;
13985cd29d0fSMark Johnston 
13995cd29d0fSMark Johnston 	delta = 0;
1400f3f38e25SMark Johnston 	marker = ss->marker;
14015cd29d0fSMark Johnston 	pq = ss->pq;
14025cd29d0fSMark Johnston 
14035cd29d0fSMark Johnston 	if (m != NULL) {
14045cd29d0fSMark Johnston 		if (vm_batchqueue_insert(bq, m))
14055cd29d0fSMark Johnston 			return;
14065cd29d0fSMark Johnston 		vm_pagequeue_lock(pq);
1407f3f38e25SMark Johnston 		delta += vm_pageout_reinsert_inactive_page(pq, marker, m);
14085cd29d0fSMark Johnston 	} else
14095cd29d0fSMark Johnston 		vm_pagequeue_lock(pq);
14105cd29d0fSMark Johnston 	while ((m = vm_batchqueue_pop(bq)) != NULL)
1411f3f38e25SMark Johnston 		delta += vm_pageout_reinsert_inactive_page(pq, marker, m);
14125cd29d0fSMark Johnston 	vm_pagequeue_cnt_add(pq, delta);
14135cd29d0fSMark Johnston 	vm_pagequeue_unlock(pq);
14145cd29d0fSMark Johnston 	vm_batchqueue_init(bq);
14155cd29d0fSMark Johnston }
14165cd29d0fSMark Johnston 
1417ebcddc72SAlan Cox /*
141827e29d10SMark Johnston  * Attempt to reclaim the requested number of pages from the inactive queue.
141927e29d10SMark Johnston  * Returns true if the shortage was addressed.
1420df8bae1dSRodney W. Grimes  */
1421be37ee79SMark Johnston static int
142249a3710cSMark Johnston vm_pageout_scan_inactive(struct vm_domain *vmd, int shortage,
1423be37ee79SMark Johnston     int *addl_shortage)
1424df8bae1dSRodney W. Grimes {
14255cd29d0fSMark Johnston 	struct scan_state ss;
14265cd29d0fSMark Johnston 	struct vm_batchqueue rq;
14275cd29d0fSMark Johnston 	vm_page_t m, marker;
14288d220203SAlan Cox 	struct vm_pagequeue *pq;
1429df8bae1dSRodney W. Grimes 	vm_object_t object;
1430f3f38e25SMark Johnston 	vm_page_astate_t old, new;
1431f3f38e25SMark Johnston 	int act_delta, addl_page_shortage, deficit, page_shortage, refs;
1432be37ee79SMark Johnston 	int starting_page_shortage;
14330d94caffSDavid Greenman 
1434df8bae1dSRodney W. Grimes 	/*
143501f04471SMark Johnston 	 * The addl_page_shortage is an estimate of the number of temporarily
1436311e34e2SKonstantin Belousov 	 * stuck pages in the inactive queue.  In other words, the
1437449c2e92SKonstantin Belousov 	 * number of pages from the inactive count that should be
1438311e34e2SKonstantin Belousov 	 * discounted in setting the target for the active queue scan.
1439311e34e2SKonstantin Belousov 	 */
14409099545aSAlan Cox 	addl_page_shortage = 0;
14419099545aSAlan Cox 
14421c7c3c6aSMatthew Dillon 	/*
144349a3710cSMark Johnston 	 * vmd_pageout_deficit counts the number of pages requested in
144449a3710cSMark Johnston 	 * allocations that failed because of a free page shortage.  We assume
144549a3710cSMark Johnston 	 * that the allocations will be reattempted and thus include the deficit
144649a3710cSMark Johnston 	 * in our scan target.
14471c7c3c6aSMatthew Dillon 	 */
1448e2068d0bSJeff Roberson 	deficit = atomic_readandclear_int(&vmd->vmd_pageout_deficit);
144949a3710cSMark Johnston 	starting_page_shortage = page_shortage = shortage + deficit;
14501c7c3c6aSMatthew Dillon 
14515cd29d0fSMark Johnston 	object = NULL;
14525cd29d0fSMark Johnston 	vm_batchqueue_init(&rq);
14535cd29d0fSMark Johnston 
1454936524aaSMatthew Dillon 	/*
1455f095d1bbSAlan Cox 	 * Start scanning the inactive queue for pages that we can free.  The
1456f095d1bbSAlan Cox 	 * scan will stop when we reach the target or we have scanned the
14575cff1f4dSMark Johnston 	 * entire queue.  (Note that m->a.act_count is not used to make
1458f095d1bbSAlan Cox 	 * decisions for the inactive queue, only for the active queue.)
14598d220203SAlan Cox 	 */
146064b38930SMark Johnston 	marker = &vmd->vmd_markers[PQ_INACTIVE];
14615cd29d0fSMark Johnston 	pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
14628d220203SAlan Cox 	vm_pagequeue_lock(pq);
14635cd29d0fSMark Johnston 	vm_pageout_init_scan(&ss, pq, marker, NULL, pq->pq_cnt);
14645cd29d0fSMark Johnston 	while (page_shortage > 0 && (m = vm_pageout_next(&ss, true)) != NULL) {
14655cd29d0fSMark Johnston 		KASSERT((m->flags & PG_MARKER) == 0,
14665cd29d0fSMark Johnston 		    ("marker page %p was dequeued", m));
1467df8bae1dSRodney W. Grimes 
1468936524aaSMatthew Dillon 		/*
1469b7f30bffSMark Johnston 		 * Don't touch a page that was removed from the queue after the
1470b7f30bffSMark Johnston 		 * page queue lock was released.  Otherwise, ensure that any
1471b7f30bffSMark Johnston 		 * pending queue operations, such as dequeues for wired pages,
1472b7f30bffSMark Johnston 		 * are handled.
1473936524aaSMatthew Dillon 		 */
1474b7f30bffSMark Johnston 		if (vm_pageout_defer(m, PQ_INACTIVE, false))
1475936524aaSMatthew Dillon 			continue;
1476e8bcf696SMark Johnston 
14779f5632e6SMark Johnston 		/*
14789f5632e6SMark Johnston 		 * Lock the page's object.
14799f5632e6SMark Johnston 		 */
14809f5632e6SMark Johnston 		if (object == NULL || object != m->object) {
148160256604SMark Johnston 			if (object != NULL)
14825cd29d0fSMark Johnston 				VM_OBJECT_WUNLOCK(object);
148323ed568cSMateusz Guzik 			object = atomic_load_ptr(&m->object);
14849f5632e6SMark Johnston 			if (__predict_false(object == NULL))
14859f5632e6SMark Johnston 				/* The page is being freed by another thread. */
14869f5632e6SMark Johnston 				continue;
14879f5632e6SMark Johnston 
1488e8bcf696SMark Johnston 			/* Depends on type-stability. */
148941fd4b94SMark Johnston 			VM_OBJECT_WLOCK(object);
14909f5632e6SMark Johnston 			if (__predict_false(m->object != object)) {
14919f5632e6SMark Johnston 				VM_OBJECT_WUNLOCK(object);
14929f5632e6SMark Johnston 				object = NULL;
14939f5632e6SMark Johnston 				goto reinsert;
149441fd4b94SMark Johnston 			}
149541fd4b94SMark Johnston 		}
14965cd29d0fSMark Johnston 
149763e97555SJeff Roberson 		if (vm_page_tryxbusy(m) == 0) {
1498a3aeedabSAlan Cox 			/*
1499a3aeedabSAlan Cox 			 * Don't mess with busy pages.  Leave them at
1500a3aeedabSAlan Cox 			 * the front of the queue.  Most likely, they
1501a3aeedabSAlan Cox 			 * are being paged out and will leave the
1502a3aeedabSAlan Cox 			 * queue shortly after the scan finishes.  So,
1503a3aeedabSAlan Cox 			 * they ought to be discounted from the
1504a3aeedabSAlan Cox 			 * inactive count.
1505a3aeedabSAlan Cox 			 */
1506a3aeedabSAlan Cox 			addl_page_shortage++;
15075cd29d0fSMark Johnston 			goto reinsert;
150826f9a767SRodney W. Grimes 		}
150948cc2fc7SKonstantin Belousov 
1510a8081778SJeff Roberson 		/* Deferred free of swap space. */
1511a8081778SJeff Roberson 		if ((m->a.flags & PGA_SWAP_FREE) != 0)
1512a8081778SJeff Roberson 			vm_pager_page_unswapped(m);
1513a8081778SJeff Roberson 
151448cc2fc7SKonstantin Belousov 		/*
15159f5632e6SMark Johnston 		 * Check for wirings now that we hold the object lock and have
15169f5632e6SMark Johnston 		 * exclusively busied the page.  If the page is mapped, it may
15179f5632e6SMark Johnston 		 * still be wired by pmap lookups.  The call to
1518fee2a2faSMark Johnston 		 * vm_page_try_remove_all() below atomically checks for such
1519fee2a2faSMark Johnston 		 * wirings and removes mappings.  If the page is unmapped, the
15209f5632e6SMark Johnston 		 * wire count is guaranteed not to increase after this check.
1521fee2a2faSMark Johnston 		 */
15229f5632e6SMark Johnston 		if (__predict_false(vm_page_wired(m)))
1523f3f38e25SMark Johnston 			goto skip_page;
1524fee2a2faSMark Johnston 
1525fee2a2faSMark Johnston 		/*
15268748f58cSKonstantin Belousov 		 * Invalid pages can be easily freed. They cannot be
15278748f58cSKonstantin Belousov 		 * mapped, vm_page_free() asserts this.
1528776f729cSKonstantin Belousov 		 */
15290012f373SJeff Roberson 		if (vm_page_none_valid(m))
15308748f58cSKonstantin Belousov 			goto free_page;
1531776f729cSKonstantin Belousov 
1532f3f38e25SMark Johnston 		refs = object->ref_count != 0 ? pmap_ts_referenced(m) : 0;
1533f3f38e25SMark Johnston 
1534f3f38e25SMark Johnston 		for (old = vm_page_astate_load(m);;) {
1535776f729cSKonstantin Belousov 			/*
1536f3f38e25SMark Johnston 			 * Check to see if the page has been removed from the
1537f3f38e25SMark Johnston 			 * queue since the first such check.  Leave it alone if
1538f3f38e25SMark Johnston 			 * so, discarding any references collected by
1539f3f38e25SMark Johnston 			 * pmap_ts_referenced().
15407e006499SJohn Dyson 			 */
1541f3f38e25SMark Johnston 			if (__predict_false(_vm_page_queue(old) == PQ_NONE))
1542f3f38e25SMark Johnston 				goto skip_page;
1543f3f38e25SMark Johnston 
1544f3f38e25SMark Johnston 			new = old;
1545f3f38e25SMark Johnston 			act_delta = refs;
1546f3f38e25SMark Johnston 			if ((old.flags & PGA_REFERENCED) != 0) {
1547f3f38e25SMark Johnston 				new.flags &= ~PGA_REFERENCED;
1548d7aeb429SAlan Cox 				act_delta++;
15492fe6e4d7SDavid Greenman 			}
1550f3f38e25SMark Johnston 			if (act_delta == 0) {
1551f3f38e25SMark Johnston 				;
1552f3f38e25SMark Johnston 			} else if (object->ref_count != 0) {
1553e8bcf696SMark Johnston 				/*
1554f3f38e25SMark Johnston 				 * Increase the activation count if the
1555f3f38e25SMark Johnston 				 * page was referenced while in the
1556f3f38e25SMark Johnston 				 * inactive queue.  This makes it less
1557f3f38e25SMark Johnston 				 * likely that the page will be returned
1558f3f38e25SMark Johnston 				 * prematurely to the inactive queue.
1559e8bcf696SMark Johnston 				 */
1560f3f38e25SMark Johnston 				new.act_count += ACT_ADVANCE +
1561f3f38e25SMark Johnston 				    act_delta;
1562f3f38e25SMark Johnston 				if (new.act_count > ACT_MAX)
1563f3f38e25SMark Johnston 					new.act_count = ACT_MAX;
1564f3f38e25SMark Johnston 
1565f7607c30SMark Johnston 				new.flags &= ~PGA_QUEUE_OP_MASK;
1566f3f38e25SMark Johnston 				new.flags |= PGA_REQUEUE;
1567f3f38e25SMark Johnston 				new.queue = PQ_ACTIVE;
1568f3f38e25SMark Johnston 				if (!vm_page_pqstate_commit(m, &old, new))
1569e8bcf696SMark Johnston 					continue;
1570f3f38e25SMark Johnston 
1571f3f38e25SMark Johnston 				VM_CNT_INC(v_reactivated);
1572f3f38e25SMark Johnston 				goto skip_page;
1573ebcddc72SAlan Cox 			} else if ((object->flags & OBJ_DEAD) == 0) {
1574f3f38e25SMark Johnston 				new.queue = PQ_INACTIVE;
1575f3f38e25SMark Johnston 				new.flags |= PGA_REQUEUE;
1576f3f38e25SMark Johnston 				if (!vm_page_pqstate_commit(m, &old, new))
1577f3f38e25SMark Johnston 					continue;
1578f3f38e25SMark Johnston 				goto skip_page;
1579ebcddc72SAlan Cox 			}
1580f3f38e25SMark Johnston 			break;
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);
15929f5632e6SMark Johnston 			if (m->dirty == 0 && !vm_page_try_remove_all(m))
1593f3f38e25SMark Johnston 				goto skip_page;
1594fee2a2faSMark Johnston 		}
1595dcbcd518SBruce Evans 
15966989c456SAlan Cox 		/*
1597ebcddc72SAlan Cox 		 * Clean pages can be freed, but dirty pages must be sent back
1598ebcddc72SAlan Cox 		 * to the laundry, unless they belong to a dead object.
1599ebcddc72SAlan Cox 		 * Requeueing dirty pages from dead objects is pointless, as
1600ebcddc72SAlan Cox 		 * they are being paged out and freed by the thread that
1601ebcddc72SAlan Cox 		 * destroyed the object.
16026989c456SAlan Cox 		 */
1603ebcddc72SAlan Cox 		if (m->dirty == 0) {
16048748f58cSKonstantin Belousov free_page:
16055cd29d0fSMark Johnston 			/*
16069f5632e6SMark Johnston 			 * Now we are guaranteed that no other threads are
16079f5632e6SMark Johnston 			 * manipulating the page, check for a last-second
16089f5632e6SMark Johnston 			 * reference that would save it from doom.
16095cd29d0fSMark Johnston 			 */
16109f5632e6SMark Johnston 			if (vm_pageout_defer(m, PQ_INACTIVE, false))
16119f5632e6SMark Johnston 				goto skip_page;
16129f5632e6SMark Johnston 
16139f5632e6SMark Johnston 			/*
16149f5632e6SMark Johnston 			 * Because we dequeued the page and have already checked
16159f5632e6SMark Johnston 			 * for pending dequeue and enqueue requests, we can
16169f5632e6SMark Johnston 			 * safely disassociate the page from the inactive queue
16179f5632e6SMark Johnston 			 * without holding the queue lock.
16189f5632e6SMark Johnston 			 */
16195cff1f4dSMark Johnston 			m->a.queue = PQ_NONE;
162078afdce6SAlan Cox 			vm_page_free(m);
16215cd29d0fSMark Johnston 			page_shortage--;
162263e97555SJeff Roberson 			continue;
162363e97555SJeff Roberson 		}
162463e97555SJeff Roberson 		if ((object->flags & OBJ_DEAD) == 0)
1625ebcddc72SAlan Cox 			vm_page_launder(m);
1626f3f38e25SMark Johnston skip_page:
1627f3f38e25SMark Johnston 		vm_page_xunbusy(m);
16285cd29d0fSMark Johnston 		continue;
16295cd29d0fSMark Johnston reinsert:
16305cd29d0fSMark Johnston 		vm_pageout_reinsert_inactive(&ss, &rq, m);
16315cd29d0fSMark Johnston 	}
163260256604SMark Johnston 	if (object != NULL)
163389f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
16345cd29d0fSMark Johnston 	vm_pageout_reinsert_inactive(&ss, &rq, NULL);
16355cd29d0fSMark Johnston 	vm_pageout_reinsert_inactive(&ss, &ss.bq, NULL);
16368d220203SAlan Cox 	vm_pagequeue_lock(pq);
16375cd29d0fSMark Johnston 	vm_pageout_end_scan(&ss);
16388d220203SAlan Cox 	vm_pagequeue_unlock(pq);
163926f9a767SRodney W. Grimes 
16405cd29d0fSMark Johnston 	VM_CNT_ADD(v_dfree, starting_page_shortage - page_shortage);
16415cd29d0fSMark Johnston 
1642ebcddc72SAlan Cox 	/*
1643ebcddc72SAlan Cox 	 * Wake up the laundry thread so that it can perform any needed
1644ebcddc72SAlan Cox 	 * laundering.  If we didn't meet our target, we're in shortfall and
1645b1fd102eSMark Johnston 	 * need to launder more aggressively.  If PQ_LAUNDRY is empty and no
1646b1fd102eSMark Johnston 	 * swap devices are configured, the laundry thread has no work to do, so
1647b1fd102eSMark Johnston 	 * don't bother waking it up.
1648cb35676eSMark Johnston 	 *
1649cb35676eSMark Johnston 	 * The laundry thread uses the number of inactive queue scans elapsed
1650cb35676eSMark Johnston 	 * since the last laundering to determine whether to launder again, so
1651cb35676eSMark Johnston 	 * keep count.
1652ebcddc72SAlan Cox 	 */
1653cb35676eSMark Johnston 	if (starting_page_shortage > 0) {
1654e2068d0bSJeff Roberson 		pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
1655ebcddc72SAlan Cox 		vm_pagequeue_lock(pq);
1656e2068d0bSJeff Roberson 		if (vmd->vmd_laundry_request == VM_LAUNDRY_IDLE &&
1657cb35676eSMark Johnston 		    (pq->pq_cnt > 0 || atomic_load_acq_int(&swapdev_enabled))) {
1658ebcddc72SAlan Cox 			if (page_shortage > 0) {
1659e2068d0bSJeff Roberson 				vmd->vmd_laundry_request = VM_LAUNDRY_SHORTFALL;
166083c9dea1SGleb Smirnoff 				VM_CNT_INC(v_pdshortfalls);
1661e2068d0bSJeff Roberson 			} else if (vmd->vmd_laundry_request !=
1662e2068d0bSJeff Roberson 			    VM_LAUNDRY_SHORTFALL)
1663e2068d0bSJeff Roberson 				vmd->vmd_laundry_request =
1664e2068d0bSJeff Roberson 				    VM_LAUNDRY_BACKGROUND;
1665e2068d0bSJeff Roberson 			wakeup(&vmd->vmd_laundry_request);
1666b1fd102eSMark Johnston 		}
166760684862SMark Johnston 		vmd->vmd_clean_pages_freed +=
166860684862SMark Johnston 		    starting_page_shortage - page_shortage;
1669ebcddc72SAlan Cox 		vm_pagequeue_unlock(pq);
1670ebcddc72SAlan Cox 	}
1671ebcddc72SAlan Cox 
16729452b5edSAlan Cox 	/*
1673f095d1bbSAlan Cox 	 * Wakeup the swapout daemon if we didn't free the targeted number of
1674f095d1bbSAlan Cox 	 * pages.
16759452b5edSAlan Cox 	 */
1676ac04195bSKonstantin Belousov 	if (page_shortage > 0)
1677ac04195bSKonstantin Belousov 		vm_swapout_run();
16789452b5edSAlan Cox 
16799452b5edSAlan Cox 	/*
168076386c7eSKonstantin Belousov 	 * If the inactive queue scan fails repeatedly to meet its
168176386c7eSKonstantin Belousov 	 * target, kill the largest process.
168276386c7eSKonstantin Belousov 	 */
168376386c7eSKonstantin Belousov 	vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
168476386c7eSKonstantin Belousov 
168576386c7eSKonstantin Belousov 	/*
1686be37ee79SMark Johnston 	 * Reclaim pages by swapping out idle processes, if configured to do so.
16871c7c3c6aSMatthew Dillon 	 */
1688ac04195bSKonstantin Belousov 	vm_swapout_run_idle();
1689be37ee79SMark Johnston 
1690be37ee79SMark Johnston 	/*
1691be37ee79SMark Johnston 	 * See the description of addl_page_shortage above.
1692be37ee79SMark Johnston 	 */
1693be37ee79SMark Johnston 	*addl_shortage = addl_page_shortage + deficit;
1694be37ee79SMark Johnston 
1695e57dd910SAlan Cox 	return (page_shortage <= 0);
16962025d69bSKonstantin Belousov }
16972025d69bSKonstantin Belousov 
1698449c2e92SKonstantin Belousov static int vm_pageout_oom_vote;
1699449c2e92SKonstantin Belousov 
1700449c2e92SKonstantin Belousov /*
1701449c2e92SKonstantin Belousov  * The pagedaemon threads randlomly select one to perform the
1702449c2e92SKonstantin Belousov  * OOM.  Trying to kill processes before all pagedaemons
1703449c2e92SKonstantin Belousov  * failed to reach free target is premature.
1704449c2e92SKonstantin Belousov  */
1705449c2e92SKonstantin Belousov static void
170676386c7eSKonstantin Belousov vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
170776386c7eSKonstantin Belousov     int starting_page_shortage)
1708449c2e92SKonstantin Belousov {
1709449c2e92SKonstantin Belousov 	int old_vote;
1710449c2e92SKonstantin Belousov 
171176386c7eSKonstantin Belousov 	if (starting_page_shortage <= 0 || starting_page_shortage !=
171276386c7eSKonstantin Belousov 	    page_shortage)
171376386c7eSKonstantin Belousov 		vmd->vmd_oom_seq = 0;
171476386c7eSKonstantin Belousov 	else
171576386c7eSKonstantin Belousov 		vmd->vmd_oom_seq++;
171676386c7eSKonstantin Belousov 	if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1717449c2e92SKonstantin Belousov 		if (vmd->vmd_oom) {
1718449c2e92SKonstantin Belousov 			vmd->vmd_oom = FALSE;
1719449c2e92SKonstantin Belousov 			atomic_subtract_int(&vm_pageout_oom_vote, 1);
1720449c2e92SKonstantin Belousov 		}
1721449c2e92SKonstantin Belousov 		return;
1722449c2e92SKonstantin Belousov 	}
1723449c2e92SKonstantin Belousov 
172476386c7eSKonstantin Belousov 	/*
172576386c7eSKonstantin Belousov 	 * Do not follow the call sequence until OOM condition is
172676386c7eSKonstantin Belousov 	 * cleared.
172776386c7eSKonstantin Belousov 	 */
172876386c7eSKonstantin Belousov 	vmd->vmd_oom_seq = 0;
172976386c7eSKonstantin Belousov 
1730449c2e92SKonstantin Belousov 	if (vmd->vmd_oom)
1731449c2e92SKonstantin Belousov 		return;
1732449c2e92SKonstantin Belousov 
1733449c2e92SKonstantin Belousov 	vmd->vmd_oom = TRUE;
1734449c2e92SKonstantin Belousov 	old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1735449c2e92SKonstantin Belousov 	if (old_vote != vm_ndomains - 1)
1736449c2e92SKonstantin Belousov 		return;
1737449c2e92SKonstantin Belousov 
1738449c2e92SKonstantin Belousov 	/*
1739449c2e92SKonstantin Belousov 	 * The current pagedaemon thread is the last in the quorum to
1740449c2e92SKonstantin Belousov 	 * start OOM.  Initiate the selection and signaling of the
1741449c2e92SKonstantin Belousov 	 * victim.
1742449c2e92SKonstantin Belousov 	 */
1743449c2e92SKonstantin Belousov 	vm_pageout_oom(VM_OOM_MEM);
1744449c2e92SKonstantin Belousov 
1745449c2e92SKonstantin Belousov 	/*
1746449c2e92SKonstantin Belousov 	 * After one round of OOM terror, recall our vote.  On the
1747449c2e92SKonstantin Belousov 	 * next pass, current pagedaemon would vote again if the low
1748449c2e92SKonstantin Belousov 	 * memory condition is still there, due to vmd_oom being
1749449c2e92SKonstantin Belousov 	 * false.
1750449c2e92SKonstantin Belousov 	 */
1751449c2e92SKonstantin Belousov 	vmd->vmd_oom = FALSE;
1752449c2e92SKonstantin Belousov 	atomic_subtract_int(&vm_pageout_oom_vote, 1);
1753449c2e92SKonstantin Belousov }
17542025d69bSKonstantin Belousov 
17553949873fSKonstantin Belousov /*
17563949873fSKonstantin Belousov  * The OOM killer is the page daemon's action of last resort when
17573949873fSKonstantin Belousov  * memory allocation requests have been stalled for a prolonged period
17583949873fSKonstantin Belousov  * of time because it cannot reclaim memory.  This function computes
17593949873fSKonstantin Belousov  * the approximate number of physical pages that could be reclaimed if
17603949873fSKonstantin Belousov  * the specified address space is destroyed.
17613949873fSKonstantin Belousov  *
17623949873fSKonstantin Belousov  * Private, anonymous memory owned by the address space is the
17633949873fSKonstantin Belousov  * principal resource that we expect to recover after an OOM kill.
17643949873fSKonstantin Belousov  * Since the physical pages mapped by the address space's COW entries
17653949873fSKonstantin Belousov  * are typically shared pages, they are unlikely to be released and so
17663949873fSKonstantin Belousov  * they are not counted.
17673949873fSKonstantin Belousov  *
17683949873fSKonstantin Belousov  * To get to the point where the page daemon runs the OOM killer, its
17693949873fSKonstantin Belousov  * efforts to write-back vnode-backed pages may have stalled.  This
17703949873fSKonstantin Belousov  * could be caused by a memory allocation deadlock in the write path
17713949873fSKonstantin Belousov  * that might be resolved by an OOM kill.  Therefore, physical pages
17723949873fSKonstantin Belousov  * belonging to vnode-backed objects are counted, because they might
17733949873fSKonstantin Belousov  * be freed without being written out first if the address space holds
17743949873fSKonstantin Belousov  * the last reference to an unlinked vnode.
17753949873fSKonstantin Belousov  *
17763949873fSKonstantin Belousov  * Similarly, physical pages belonging to OBJT_PHYS objects are
17773949873fSKonstantin Belousov  * counted because the address space might hold the last reference to
17783949873fSKonstantin Belousov  * the object.
17793949873fSKonstantin Belousov  */
17803949873fSKonstantin Belousov static long
17813949873fSKonstantin Belousov vm_pageout_oom_pagecount(struct vmspace *vmspace)
17823949873fSKonstantin Belousov {
17833949873fSKonstantin Belousov 	vm_map_t map;
17843949873fSKonstantin Belousov 	vm_map_entry_t entry;
17853949873fSKonstantin Belousov 	vm_object_t obj;
17863949873fSKonstantin Belousov 	long res;
17873949873fSKonstantin Belousov 
17883949873fSKonstantin Belousov 	map = &vmspace->vm_map;
17893949873fSKonstantin Belousov 	KASSERT(!map->system_map, ("system map"));
17903949873fSKonstantin Belousov 	sx_assert(&map->lock, SA_LOCKED);
17913949873fSKonstantin Belousov 	res = 0;
17922288078cSDoug Moore 	VM_MAP_ENTRY_FOREACH(entry, map) {
17933949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
17943949873fSKonstantin Belousov 			continue;
17953949873fSKonstantin Belousov 		obj = entry->object.vm_object;
17963949873fSKonstantin Belousov 		if (obj == NULL)
17973949873fSKonstantin Belousov 			continue;
17983949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
17993949873fSKonstantin Belousov 		    obj->ref_count != 1)
18003949873fSKonstantin Belousov 			continue;
18013949873fSKonstantin Belousov 		switch (obj->type) {
18023949873fSKonstantin Belousov 		case OBJT_DEFAULT:
18033949873fSKonstantin Belousov 		case OBJT_SWAP:
18043949873fSKonstantin Belousov 		case OBJT_PHYS:
18053949873fSKonstantin Belousov 		case OBJT_VNODE:
18063949873fSKonstantin Belousov 			res += obj->resident_page_count;
18073949873fSKonstantin Belousov 			break;
18083949873fSKonstantin Belousov 		}
18093949873fSKonstantin Belousov 	}
18103949873fSKonstantin Belousov 	return (res);
18113949873fSKonstantin Belousov }
18123949873fSKonstantin Belousov 
1813245139c6SKonstantin Belousov static int vm_oom_ratelim_last;
1814245139c6SKonstantin Belousov static int vm_oom_pf_secs = 10;
1815245139c6SKonstantin Belousov SYSCTL_INT(_vm, OID_AUTO, oom_pf_secs, CTLFLAG_RWTUN, &vm_oom_pf_secs, 0,
1816245139c6SKonstantin Belousov     "");
1817245139c6SKonstantin Belousov static struct mtx vm_oom_ratelim_mtx;
1818245139c6SKonstantin Belousov 
18192025d69bSKonstantin Belousov void
18202025d69bSKonstantin Belousov vm_pageout_oom(int shortage)
18212025d69bSKonstantin Belousov {
18222025d69bSKonstantin Belousov 	struct proc *p, *bigproc;
18232025d69bSKonstantin Belousov 	vm_offset_t size, bigsize;
18242025d69bSKonstantin Belousov 	struct thread *td;
18256bed074cSKonstantin Belousov 	struct vmspace *vm;
1826245139c6SKonstantin Belousov 	int now;
18273e78e983SAlan Cox 	bool breakout;
18282025d69bSKonstantin Belousov 
18292025d69bSKonstantin Belousov 	/*
1830245139c6SKonstantin Belousov 	 * For OOM requests originating from vm_fault(), there is a high
1831245139c6SKonstantin Belousov 	 * chance that a single large process faults simultaneously in
1832245139c6SKonstantin Belousov 	 * several threads.  Also, on an active system running many
1833245139c6SKonstantin Belousov 	 * processes of middle-size, like buildworld, all of them
1834245139c6SKonstantin Belousov 	 * could fault almost simultaneously as well.
1835245139c6SKonstantin Belousov 	 *
1836245139c6SKonstantin Belousov 	 * To avoid killing too many processes, rate-limit OOMs
1837245139c6SKonstantin Belousov 	 * initiated by vm_fault() time-outs on the waits for free
1838245139c6SKonstantin Belousov 	 * pages.
1839245139c6SKonstantin Belousov 	 */
1840245139c6SKonstantin Belousov 	mtx_lock(&vm_oom_ratelim_mtx);
1841245139c6SKonstantin Belousov 	now = ticks;
1842245139c6SKonstantin Belousov 	if (shortage == VM_OOM_MEM_PF &&
1843245139c6SKonstantin Belousov 	    (u_int)(now - vm_oom_ratelim_last) < hz * vm_oom_pf_secs) {
1844245139c6SKonstantin Belousov 		mtx_unlock(&vm_oom_ratelim_mtx);
1845245139c6SKonstantin Belousov 		return;
1846245139c6SKonstantin Belousov 	}
1847245139c6SKonstantin Belousov 	vm_oom_ratelim_last = now;
1848245139c6SKonstantin Belousov 	mtx_unlock(&vm_oom_ratelim_mtx);
1849245139c6SKonstantin Belousov 
1850245139c6SKonstantin Belousov 	/*
18511c58e4e5SJohn Baldwin 	 * We keep the process bigproc locked once we find it to keep anyone
18521c58e4e5SJohn Baldwin 	 * from messing with it; however, there is a possibility of
185328323addSBryan Drewery 	 * deadlock if process B is bigproc and one of its child processes
18541c58e4e5SJohn Baldwin 	 * attempts to propagate a signal to B while we are waiting for A's
18551c58e4e5SJohn Baldwin 	 * lock while walking this list.  To avoid this, we don't block on
18561c58e4e5SJohn Baldwin 	 * the process lock but just skip a process if it is already locked.
18575663e6deSDavid Greenman 	 */
18585663e6deSDavid Greenman 	bigproc = NULL;
18595663e6deSDavid Greenman 	bigsize = 0;
18601005a129SJohn Baldwin 	sx_slock(&allproc_lock);
1861e602ba25SJulian Elischer 	FOREACH_PROC_IN_SYSTEM(p) {
186271943c3dSKonstantin Belousov 		PROC_LOCK(p);
186371943c3dSKonstantin Belousov 
18641c58e4e5SJohn Baldwin 		/*
18653f1c4c4fSKonstantin Belousov 		 * If this is a system, protected or killed process, skip it.
18665663e6deSDavid Greenman 		 */
186771943c3dSKonstantin Belousov 		if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
186871943c3dSKonstantin Belousov 		    P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
186971943c3dSKonstantin Belousov 		    p->p_pid == 1 || P_KILLED(p) ||
187071943c3dSKonstantin Belousov 		    (p->p_pid < 48 && swap_pager_avail != 0)) {
18718606d880SJohn Baldwin 			PROC_UNLOCK(p);
18725663e6deSDavid Greenman 			continue;
18735663e6deSDavid Greenman 		}
18745663e6deSDavid Greenman 		/*
1875dcbcd518SBruce Evans 		 * If the process is in a non-running type state,
1876e602ba25SJulian Elischer 		 * don't touch it.  Check all the threads individually.
18775663e6deSDavid Greenman 		 */
18783e78e983SAlan Cox 		breakout = false;
1879e602ba25SJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td) {
1880982d11f8SJeff Roberson 			thread_lock(td);
188171fad9fdSJulian Elischer 			if (!TD_ON_RUNQ(td) &&
188271fad9fdSJulian Elischer 			    !TD_IS_RUNNING(td) &&
1883f497cda2SEdward Tomasz Napierala 			    !TD_IS_SLEEPING(td) &&
1884b98acc0aSKonstantin Belousov 			    !TD_IS_SUSPENDED(td) &&
1885b98acc0aSKonstantin Belousov 			    !TD_IS_SWAPPED(td)) {
1886982d11f8SJeff Roberson 				thread_unlock(td);
18873e78e983SAlan Cox 				breakout = true;
1888e602ba25SJulian Elischer 				break;
1889e602ba25SJulian Elischer 			}
1890982d11f8SJeff Roberson 			thread_unlock(td);
1891e602ba25SJulian Elischer 		}
1892e602ba25SJulian Elischer 		if (breakout) {
18931c58e4e5SJohn Baldwin 			PROC_UNLOCK(p);
18945663e6deSDavid Greenman 			continue;
18955663e6deSDavid Greenman 		}
18965663e6deSDavid Greenman 		/*
18975663e6deSDavid Greenman 		 * get the process size
18985663e6deSDavid Greenman 		 */
18996bed074cSKonstantin Belousov 		vm = vmspace_acquire_ref(p);
19006bed074cSKonstantin Belousov 		if (vm == NULL) {
19016bed074cSKonstantin Belousov 			PROC_UNLOCK(p);
19026bed074cSKonstantin Belousov 			continue;
19036bed074cSKonstantin Belousov 		}
190495e2409aSKonstantin Belousov 		_PHOLD_LITE(p);
190572d97679SDavid Schultz 		PROC_UNLOCK(p);
190695e2409aSKonstantin Belousov 		sx_sunlock(&allproc_lock);
190795e2409aSKonstantin Belousov 		if (!vm_map_trylock_read(&vm->vm_map)) {
190871943c3dSKonstantin Belousov 			vmspace_free(vm);
190995e2409aSKonstantin Belousov 			sx_slock(&allproc_lock);
191095e2409aSKonstantin Belousov 			PRELE(p);
191172d97679SDavid Schultz 			continue;
191272d97679SDavid Schultz 		}
19137981aa24SKonstantin Belousov 		size = vmspace_swap_count(vm);
1914245139c6SKonstantin Belousov 		if (shortage == VM_OOM_MEM || shortage == VM_OOM_MEM_PF)
19153949873fSKonstantin Belousov 			size += vm_pageout_oom_pagecount(vm);
19163949873fSKonstantin Belousov 		vm_map_unlock_read(&vm->vm_map);
19176bed074cSKonstantin Belousov 		vmspace_free(vm);
191895e2409aSKonstantin Belousov 		sx_slock(&allproc_lock);
19193949873fSKonstantin Belousov 
19205663e6deSDavid Greenman 		/*
19213949873fSKonstantin Belousov 		 * If this process is bigger than the biggest one,
19225663e6deSDavid Greenman 		 * remember it.
19235663e6deSDavid Greenman 		 */
19245663e6deSDavid Greenman 		if (size > bigsize) {
19251c58e4e5SJohn Baldwin 			if (bigproc != NULL)
192671943c3dSKonstantin Belousov 				PRELE(bigproc);
19275663e6deSDavid Greenman 			bigproc = p;
19285663e6deSDavid Greenman 			bigsize = size;
192971943c3dSKonstantin Belousov 		} else {
193071943c3dSKonstantin Belousov 			PRELE(p);
193171943c3dSKonstantin Belousov 		}
19325663e6deSDavid Greenman 	}
19331005a129SJohn Baldwin 	sx_sunlock(&allproc_lock);
19345663e6deSDavid Greenman 	if (bigproc != NULL) {
19353c200db9SJonathan T. Looney 		if (vm_panic_on_oom != 0 && --vm_panic_on_oom == 0)
19368311a2b8SWill Andrews 			panic("out of swap space");
193771943c3dSKonstantin Belousov 		PROC_LOCK(bigproc);
1938729b1e51SDavid Greenman 		killproc(bigproc, "out of swap space");
1939fa885116SJulian Elischer 		sched_nice(bigproc, PRIO_MIN);
194071943c3dSKonstantin Belousov 		_PRELE(bigproc);
19411c58e4e5SJohn Baldwin 		PROC_UNLOCK(bigproc);
19425663e6deSDavid Greenman 	}
19435663e6deSDavid Greenman }
194426f9a767SRodney W. Grimes 
19458fc25508SMark Johnston /*
19468fc25508SMark Johnston  * Signal a free page shortage to subsystems that have registered an event
19478fc25508SMark Johnston  * handler.  Reclaim memory from UMA in the event of a severe shortage.
19488fc25508SMark Johnston  * Return true if the free page count should be re-evaluated.
19498fc25508SMark Johnston  */
1950b50a4ea6SMark Johnston static bool
1951b50a4ea6SMark Johnston vm_pageout_lowmem(void)
195249a3710cSMark Johnston {
1953b50a4ea6SMark Johnston 	static int lowmem_ticks = 0;
1954b50a4ea6SMark Johnston 	int last;
19558fc25508SMark Johnston 	bool ret;
19568fc25508SMark Johnston 
19578fc25508SMark Johnston 	ret = false;
195849a3710cSMark Johnston 
1959b50a4ea6SMark Johnston 	last = atomic_load_int(&lowmem_ticks);
1960b50a4ea6SMark Johnston 	while ((u_int)(ticks - last) / hz >= lowmem_period) {
1961b50a4ea6SMark Johnston 		if (atomic_fcmpset_int(&lowmem_ticks, &last, ticks) == 0)
1962b50a4ea6SMark Johnston 			continue;
1963b50a4ea6SMark Johnston 
196449a3710cSMark Johnston 		/*
196549a3710cSMark Johnston 		 * Decrease registered cache sizes.
196649a3710cSMark Johnston 		 */
196749a3710cSMark Johnston 		SDT_PROBE0(vm, , , vm__lowmem_scan);
196849a3710cSMark Johnston 		EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_PAGES);
196949a3710cSMark Johnston 
197049a3710cSMark Johnston 		/*
197149a3710cSMark Johnston 		 * We do this explicitly after the caches have been
19728fc25508SMark Johnston 		 * drained above.
197349a3710cSMark Johnston 		 */
19748fc25508SMark Johnston 		uma_reclaim(UMA_RECLAIM_TRIM);
19758fc25508SMark Johnston 		ret = true;
1976ace409ceSAlexander Motin 		break;
197749a3710cSMark Johnston 	}
19788fc25508SMark Johnston 
19798fc25508SMark Johnston 	/*
19808fc25508SMark Johnston 	 * Kick off an asynchronous reclaim of cached memory if one of the
19818fc25508SMark Johnston 	 * page daemons is failing to keep up with demand.  Use the "severe"
19828fc25508SMark Johnston 	 * threshold instead of "min" to ensure that we do not blow away the
19838fc25508SMark Johnston 	 * caches if a subset of the NUMA domains are depleted by kernel memory
19848fc25508SMark Johnston 	 * allocations; the domainset iterators automatically skip domains
19858fc25508SMark Johnston 	 * below the "min" threshold on the first pass.
19868fc25508SMark Johnston 	 *
19878fc25508SMark Johnston 	 * UMA reclaim worker has its own rate-limiting mechanism, so don't
19888fc25508SMark Johnston 	 * worry about kicking it too often.
19898fc25508SMark Johnston 	 */
19908fc25508SMark Johnston 	if (vm_page_count_severe())
19918fc25508SMark Johnston 		uma_reclaim_wakeup();
19928fc25508SMark Johnston 
19938fc25508SMark Johnston 	return (ret);
199449a3710cSMark Johnston }
199549a3710cSMark Johnston 
199649a3710cSMark Johnston static void
1997449c2e92SKonstantin Belousov vm_pageout_worker(void *arg)
1998449c2e92SKonstantin Belousov {
1999e2068d0bSJeff Roberson 	struct vm_domain *vmd;
2000b50a4ea6SMark Johnston 	u_int ofree;
200149a3710cSMark Johnston 	int addl_shortage, domain, shortage;
2002e57dd910SAlan Cox 	bool target_met;
2003449c2e92SKonstantin Belousov 
2004e2068d0bSJeff Roberson 	domain = (uintptr_t)arg;
2005e2068d0bSJeff Roberson 	vmd = VM_DOMAIN(domain);
20065f8cd1c0SJeff Roberson 	shortage = 0;
2007e57dd910SAlan Cox 	target_met = true;
2008449c2e92SKonstantin Belousov 
2009449c2e92SKonstantin Belousov 	/*
2010949c9186SKonstantin Belousov 	 * XXXKIB It could be useful to bind pageout daemon threads to
2011949c9186SKonstantin Belousov 	 * the cores belonging to the domain, from which vm_page_array
2012949c9186SKonstantin Belousov 	 * is allocated.
2013449c2e92SKonstantin Belousov 	 */
2014449c2e92SKonstantin Belousov 
2015e2068d0bSJeff Roberson 	KASSERT(vmd->vmd_segs != 0, ("domain without segments"));
2016e2068d0bSJeff Roberson 	vmd->vmd_last_active_scan = ticks;
2017449c2e92SKonstantin Belousov 
2018449c2e92SKonstantin Belousov 	/*
2019449c2e92SKonstantin Belousov 	 * The pageout daemon worker is never done, so loop forever.
2020449c2e92SKonstantin Belousov 	 */
2021449c2e92SKonstantin Belousov 	while (TRUE) {
202230fbfddaSJeff Roberson 		vm_domain_pageout_lock(vmd);
202349a3710cSMark Johnston 
202430fbfddaSJeff Roberson 		/*
202530fbfddaSJeff Roberson 		 * We need to clear wanted before we check the limits.  This
202630fbfddaSJeff Roberson 		 * prevents races with wakers who will check wanted after they
202730fbfddaSJeff Roberson 		 * reach the limit.
202830fbfddaSJeff Roberson 		 */
202930fbfddaSJeff Roberson 		atomic_store_int(&vmd->vmd_pageout_wanted, 0);
203056ce0690SAlan Cox 
203156ce0690SAlan Cox 		/*
20325f8cd1c0SJeff Roberson 		 * Might the page daemon need to run again?
2033449c2e92SKonstantin Belousov 		 */
20345f8cd1c0SJeff Roberson 		if (vm_paging_needed(vmd, vmd->vmd_free_count)) {
203556ce0690SAlan Cox 			/*
203649a3710cSMark Johnston 			 * Yes.  If the scan failed to produce enough free
203749a3710cSMark Johnston 			 * pages, sleep uninterruptibly for some time in the
203849a3710cSMark Johnston 			 * hope that the laundry thread will clean some pages.
203956ce0690SAlan Cox 			 */
204030fbfddaSJeff Roberson 			vm_domain_pageout_unlock(vmd);
204149a3710cSMark Johnston 			if (!target_met)
20426eebec83SMark Johnston 				pause("pwait", hz / VM_INACT_SCAN_RATE);
2043449c2e92SKonstantin Belousov 		} else {
2044449c2e92SKonstantin Belousov 			/*
20455f8cd1c0SJeff Roberson 			 * No, sleep until the next wakeup or until pages
20465f8cd1c0SJeff Roberson 			 * need to have their reference stats updated.
2047449c2e92SKonstantin Belousov 			 */
20482c0f13aaSKonstantin Belousov 			if (mtx_sleep(&vmd->vmd_pageout_wanted,
204930fbfddaSJeff Roberson 			    vm_domain_pageout_lockptr(vmd), PDROP | PVM,
20505f8cd1c0SJeff Roberson 			    "psleep", hz / VM_INACT_SCAN_RATE) == 0)
205183c9dea1SGleb Smirnoff 				VM_CNT_INC(v_pdwakeups);
205256ce0690SAlan Cox 		}
2053be37ee79SMark Johnston 
205430fbfddaSJeff Roberson 		/* Prevent spurious wakeups by ensuring that wanted is set. */
205530fbfddaSJeff Roberson 		atomic_store_int(&vmd->vmd_pageout_wanted, 1);
205630fbfddaSJeff Roberson 
205730fbfddaSJeff Roberson 		/*
205830fbfddaSJeff Roberson 		 * Use the controller to calculate how many pages to free in
2059b50a4ea6SMark Johnston 		 * this interval, and scan the inactive queue.  If the lowmem
2060b50a4ea6SMark Johnston 		 * handlers appear to have freed up some pages, subtract the
2061b50a4ea6SMark Johnston 		 * difference from the inactive queue scan target.
206230fbfddaSJeff Roberson 		 */
20635f8cd1c0SJeff Roberson 		shortage = pidctrl_daemon(&vmd->vmd_pid, vmd->vmd_free_count);
206449a3710cSMark Johnston 		if (shortage > 0) {
2065b50a4ea6SMark Johnston 			ofree = vmd->vmd_free_count;
2066b50a4ea6SMark Johnston 			if (vm_pageout_lowmem() && vmd->vmd_free_count > ofree)
2067b50a4ea6SMark Johnston 				shortage -= min(vmd->vmd_free_count - ofree,
2068b50a4ea6SMark Johnston 				    (u_int)shortage);
206949a3710cSMark Johnston 			target_met = vm_pageout_scan_inactive(vmd, shortage,
2070be37ee79SMark Johnston 			    &addl_shortage);
207149a3710cSMark Johnston 		} else
207249a3710cSMark Johnston 			addl_shortage = 0;
207356ce0690SAlan Cox 
2074be37ee79SMark Johnston 		/*
2075be37ee79SMark Johnston 		 * Scan the active queue.  A positive value for shortage
2076be37ee79SMark Johnston 		 * indicates that we must aggressively deactivate pages to avoid
2077be37ee79SMark Johnston 		 * a shortfall.
2078be37ee79SMark Johnston 		 */
20797bb4634eSMark Johnston 		shortage = vm_pageout_active_target(vmd) + addl_shortage;
2080be37ee79SMark Johnston 		vm_pageout_scan_active(vmd, shortage);
2081449c2e92SKonstantin Belousov 	}
2082449c2e92SKonstantin Belousov }
2083449c2e92SKonstantin Belousov 
2084df8bae1dSRodney W. Grimes /*
20859c770a27SMark Johnston  * Initialize basic pageout daemon settings.  See the comment above the
20869c770a27SMark Johnston  * definition of vm_domain for some explanation of how these thresholds are
20879c770a27SMark Johnston  * used.
2088df8bae1dSRodney W. Grimes  */
20892b14f991SJulian Elischer static void
2090e2068d0bSJeff Roberson vm_pageout_init_domain(int domain)
2091df8bae1dSRodney W. Grimes {
2092e2068d0bSJeff Roberson 	struct vm_domain *vmd;
20935f8cd1c0SJeff Roberson 	struct sysctl_oid *oid;
2094e2068d0bSJeff Roberson 
2095e2068d0bSJeff Roberson 	vmd = VM_DOMAIN(domain);
2096e2068d0bSJeff Roberson 	vmd->vmd_interrupt_free_min = 2;
2097f6b04d2bSDavid Greenman 
209845ae1d91SAlan Cox 	/*
209945ae1d91SAlan Cox 	 * v_free_reserved needs to include enough for the largest
210045ae1d91SAlan Cox 	 * swap pager structures plus enough for any pv_entry structs
210145ae1d91SAlan Cox 	 * when paging.
210245ae1d91SAlan Cox 	 */
21030cab71bcSDoug Moore 	vmd->vmd_pageout_free_min = 2 * MAXBSIZE / PAGE_SIZE +
2104e2068d0bSJeff Roberson 	    vmd->vmd_interrupt_free_min;
2105e2068d0bSJeff Roberson 	vmd->vmd_free_reserved = vm_pageout_page_count +
21069c770a27SMark Johnston 	    vmd->vmd_pageout_free_min + vmd->vmd_page_count / 768;
21079c770a27SMark Johnston 	vmd->vmd_free_min = vmd->vmd_page_count / 200;
2108e2068d0bSJeff Roberson 	vmd->vmd_free_severe = vmd->vmd_free_min / 2;
2109e2068d0bSJeff Roberson 	vmd->vmd_free_target = 4 * vmd->vmd_free_min + vmd->vmd_free_reserved;
2110e2068d0bSJeff Roberson 	vmd->vmd_free_min += vmd->vmd_free_reserved;
2111e2068d0bSJeff Roberson 	vmd->vmd_free_severe += vmd->vmd_free_reserved;
2112e2068d0bSJeff Roberson 	vmd->vmd_inactive_target = (3 * vmd->vmd_free_target) / 2;
2113e2068d0bSJeff Roberson 	if (vmd->vmd_inactive_target > vmd->vmd_free_count / 3)
2114e2068d0bSJeff Roberson 		vmd->vmd_inactive_target = vmd->vmd_free_count / 3;
2115df8bae1dSRodney W. Grimes 
2116d9e23210SJeff Roberson 	/*
21175f8cd1c0SJeff Roberson 	 * Set the default wakeup threshold to be 10% below the paging
21185f8cd1c0SJeff Roberson 	 * target.  This keeps the steady state out of shortfall.
2119d9e23210SJeff Roberson 	 */
21205f8cd1c0SJeff Roberson 	vmd->vmd_pageout_wakeup_thresh = (vmd->vmd_free_target / 10) * 9;
2121e2068d0bSJeff Roberson 
2122e2068d0bSJeff Roberson 	/*
2123e2068d0bSJeff Roberson 	 * Target amount of memory to move out of the laundry queue during a
2124e2068d0bSJeff Roberson 	 * background laundering.  This is proportional to the amount of system
2125e2068d0bSJeff Roberson 	 * memory.
2126e2068d0bSJeff Roberson 	 */
2127e2068d0bSJeff Roberson 	vmd->vmd_background_launder_target = (vmd->vmd_free_target -
2128e2068d0bSJeff Roberson 	    vmd->vmd_free_min) / 10;
21295f8cd1c0SJeff Roberson 
21305f8cd1c0SJeff Roberson 	/* Initialize the pageout daemon pid controller. */
21315f8cd1c0SJeff Roberson 	pidctrl_init(&vmd->vmd_pid, hz / VM_INACT_SCAN_RATE,
21325f8cd1c0SJeff Roberson 	    vmd->vmd_free_target, PIDCTRL_BOUND,
21335f8cd1c0SJeff Roberson 	    PIDCTRL_KPD, PIDCTRL_KID, PIDCTRL_KDD);
21345f8cd1c0SJeff Roberson 	oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(vmd->vmd_oid), OID_AUTO,
21357029da5cSPawel Biernacki 	    "pidctrl", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
21365f8cd1c0SJeff Roberson 	pidctrl_init_sysctl(&vmd->vmd_pid, SYSCTL_CHILDREN(oid));
2137e2068d0bSJeff Roberson }
2138e2068d0bSJeff Roberson 
2139e2068d0bSJeff Roberson static void
2140e2068d0bSJeff Roberson vm_pageout_init(void)
2141e2068d0bSJeff Roberson {
2142e2068d0bSJeff Roberson 	u_int freecount;
2143e2068d0bSJeff Roberson 	int i;
2144e2068d0bSJeff Roberson 
2145e2068d0bSJeff Roberson 	/*
2146e2068d0bSJeff Roberson 	 * Initialize some paging parameters.
2147e2068d0bSJeff Roberson 	 */
2148e2068d0bSJeff Roberson 	if (vm_cnt.v_page_count < 2000)
2149e2068d0bSJeff Roberson 		vm_pageout_page_count = 8;
2150e2068d0bSJeff Roberson 
2151e2068d0bSJeff Roberson 	freecount = 0;
2152e2068d0bSJeff Roberson 	for (i = 0; i < vm_ndomains; i++) {
2153e2068d0bSJeff Roberson 		struct vm_domain *vmd;
2154e2068d0bSJeff Roberson 
2155e2068d0bSJeff Roberson 		vm_pageout_init_domain(i);
2156e2068d0bSJeff Roberson 		vmd = VM_DOMAIN(i);
2157e2068d0bSJeff Roberson 		vm_cnt.v_free_reserved += vmd->vmd_free_reserved;
2158e2068d0bSJeff Roberson 		vm_cnt.v_free_target += vmd->vmd_free_target;
2159e2068d0bSJeff Roberson 		vm_cnt.v_free_min += vmd->vmd_free_min;
2160e2068d0bSJeff Roberson 		vm_cnt.v_inactive_target += vmd->vmd_inactive_target;
2161e2068d0bSJeff Roberson 		vm_cnt.v_pageout_free_min += vmd->vmd_pageout_free_min;
2162e2068d0bSJeff Roberson 		vm_cnt.v_interrupt_free_min += vmd->vmd_interrupt_free_min;
2163e2068d0bSJeff Roberson 		vm_cnt.v_free_severe += vmd->vmd_free_severe;
2164e2068d0bSJeff Roberson 		freecount += vmd->vmd_free_count;
2165e2068d0bSJeff Roberson 	}
2166d9e23210SJeff Roberson 
2167d9e23210SJeff Roberson 	/*
2168d9e23210SJeff Roberson 	 * Set interval in seconds for active scan.  We want to visit each
2169c9612b2dSJeff Roberson 	 * page at least once every ten minutes.  This is to prevent worst
2170c9612b2dSJeff Roberson 	 * case paging behaviors with stale active LRU.
2171d9e23210SJeff Roberson 	 */
2172d9e23210SJeff Roberson 	if (vm_pageout_update_period == 0)
2173c9612b2dSJeff Roberson 		vm_pageout_update_period = 600;
2174d9e23210SJeff Roberson 
217554a3a114SMark Johnston 	if (vm_page_max_user_wired == 0)
217654a3a114SMark Johnston 		vm_page_max_user_wired = freecount / 3;
21774d19f4adSSteven Hartland }
21784d19f4adSSteven Hartland 
21794d19f4adSSteven Hartland /*
21804d19f4adSSteven Hartland  *     vm_pageout is the high level pageout daemon.
21814d19f4adSSteven Hartland  */
21824d19f4adSSteven Hartland static void
21834d19f4adSSteven Hartland vm_pageout(void)
21844d19f4adSSteven Hartland {
2185920239efSMark Johnston 	struct proc *p;
2186920239efSMark Johnston 	struct thread *td;
2187920239efSMark Johnston 	int error, first, i;
2188920239efSMark Johnston 
2189920239efSMark Johnston 	p = curproc;
2190920239efSMark Johnston 	td = curthread;
2191df8bae1dSRodney W. Grimes 
2192245139c6SKonstantin Belousov 	mtx_init(&vm_oom_ratelim_mtx, "vmoomr", NULL, MTX_DEF);
219324a1cce3SDavid Greenman 	swap_pager_swap_init();
2194920239efSMark Johnston 	for (first = -1, i = 0; i < vm_ndomains; i++) {
219530c5525bSAndrew Gallatin 		if (VM_DOMAIN_EMPTY(i)) {
219630c5525bSAndrew Gallatin 			if (bootverbose)
219730c5525bSAndrew Gallatin 				printf("domain %d empty; skipping pageout\n",
219830c5525bSAndrew Gallatin 				    i);
219930c5525bSAndrew Gallatin 			continue;
220030c5525bSAndrew Gallatin 		}
2201920239efSMark Johnston 		if (first == -1)
2202920239efSMark Johnston 			first = i;
2203920239efSMark Johnston 		else {
2204920239efSMark Johnston 			error = kthread_add(vm_pageout_worker,
2205920239efSMark Johnston 			    (void *)(uintptr_t)i, p, NULL, 0, 0, "dom%d", i);
2206920239efSMark Johnston 			if (error != 0)
2207920239efSMark Johnston 				panic("starting pageout for domain %d: %d\n",
2208449c2e92SKonstantin Belousov 				    i, error);
2209dc2efb27SJohn Dyson 		}
2210e2068d0bSJeff Roberson 		error = kthread_add(vm_pageout_laundry_worker,
2211920239efSMark Johnston 		    (void *)(uintptr_t)i, p, NULL, 0, 0, "laundry: dom%d", i);
2212e2068d0bSJeff Roberson 		if (error != 0)
2213920239efSMark Johnston 			panic("starting laundry for domain %d: %d", i, error);
2214f919ebdeSDavid Greenman 	}
2215920239efSMark Johnston 	error = kthread_add(uma_reclaim_worker, NULL, p, NULL, 0, 0, "uma");
221644ec2b63SKonstantin Belousov 	if (error != 0)
221744ec2b63SKonstantin Belousov 		panic("starting uma_reclaim helper, error %d\n", error);
2218920239efSMark Johnston 
2219920239efSMark Johnston 	snprintf(td->td_name, sizeof(td->td_name), "dom%d", first);
2220920239efSMark Johnston 	vm_pageout_worker((void *)(uintptr_t)first);
2221df8bae1dSRodney W. Grimes }
222226f9a767SRodney W. Grimes 
22236b4b77adSAlan Cox /*
2224280d15cdSMark Johnston  * Perform an advisory wakeup of the page daemon.
22256b4b77adSAlan Cox  */
2226e0c5a895SJohn Dyson void
2227e2068d0bSJeff Roberson pagedaemon_wakeup(int domain)
2228e0c5a895SJohn Dyson {
2229e2068d0bSJeff Roberson 	struct vm_domain *vmd;
2230a1c0a785SAlan Cox 
2231e2068d0bSJeff Roberson 	vmd = VM_DOMAIN(domain);
223230fbfddaSJeff Roberson 	vm_domain_pageout_assert_unlocked(vmd);
223330fbfddaSJeff Roberson 	if (curproc == pageproc)
223430fbfddaSJeff Roberson 		return;
2235280d15cdSMark Johnston 
223630fbfddaSJeff Roberson 	if (atomic_fetchadd_int(&vmd->vmd_pageout_wanted, 1) == 0) {
223730fbfddaSJeff Roberson 		vm_domain_pageout_lock(vmd);
223830fbfddaSJeff Roberson 		atomic_store_int(&vmd->vmd_pageout_wanted, 1);
2239e2068d0bSJeff Roberson 		wakeup(&vmd->vmd_pageout_wanted);
224030fbfddaSJeff Roberson 		vm_domain_pageout_unlock(vmd);
2241e0c5a895SJohn Dyson 	}
2242e0c5a895SJohn Dyson }
2243