xref: /freebsd/sys/vm/vm_pageout.c (revision 83c9dea1bac40c7c7cbde4ccb3d747134311ab5a)
160727d8bSWarner Losh /*-
226f9a767SRodney W. Grimes  * Copyright (c) 1991 Regents of the University of California.
326f9a767SRodney W. Grimes  * All rights reserved.
426f9a767SRodney W. Grimes  * Copyright (c) 1994 John S. Dyson
526f9a767SRodney W. Grimes  * All rights reserved.
626f9a767SRodney W. Grimes  * Copyright (c) 1994 David Greenman
726f9a767SRodney W. Grimes  * All rights reserved.
88dbca793STor Egge  * Copyright (c) 2005 Yahoo! Technologies Norway AS
98dbca793STor Egge  * All rights reserved.
10df8bae1dSRodney W. Grimes  *
11df8bae1dSRodney W. Grimes  * This code is derived from software contributed to Berkeley by
12df8bae1dSRodney W. Grimes  * The Mach Operating System project at Carnegie-Mellon University.
13df8bae1dSRodney W. Grimes  *
14df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
15df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
16df8bae1dSRodney W. Grimes  * are met:
17df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
18df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
19df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
20df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
21df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
22df8bae1dSRodney W. Grimes  * 3. All advertising materials mentioning features or use of this software
235929bcfaSPhilippe Charnier  *    must display the following acknowledgement:
24df8bae1dSRodney W. Grimes  *	This product includes software developed by the University of
25df8bae1dSRodney W. Grimes  *	California, Berkeley and its contributors.
26df8bae1dSRodney W. Grimes  * 4. Neither the name of the University nor the names of its contributors
27df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
28df8bae1dSRodney W. Grimes  *    without specific prior written permission.
29df8bae1dSRodney W. Grimes  *
30df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
41df8bae1dSRodney W. Grimes  *
423c4dd356SDavid Greenman  *	from: @(#)vm_pageout.c	7.4 (Berkeley) 5/7/91
43df8bae1dSRodney W. Grimes  *
44df8bae1dSRodney W. Grimes  *
45df8bae1dSRodney W. Grimes  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
46df8bae1dSRodney W. Grimes  * All rights reserved.
47df8bae1dSRodney W. Grimes  *
48df8bae1dSRodney W. Grimes  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
49df8bae1dSRodney W. Grimes  *
50df8bae1dSRodney W. Grimes  * Permission to use, copy, modify and distribute this software and
51df8bae1dSRodney W. Grimes  * its documentation is hereby granted, provided that both the copyright
52df8bae1dSRodney W. Grimes  * notice and this permission notice appear in all copies of the
53df8bae1dSRodney W. Grimes  * software, derivative works or modified versions, and any portions
54df8bae1dSRodney W. Grimes  * thereof, and that both notices appear in supporting documentation.
55df8bae1dSRodney W. Grimes  *
56df8bae1dSRodney W. Grimes  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
57df8bae1dSRodney W. Grimes  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
58df8bae1dSRodney W. Grimes  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
59df8bae1dSRodney W. Grimes  *
60df8bae1dSRodney W. Grimes  * Carnegie Mellon requests users of this software to return to
61df8bae1dSRodney W. Grimes  *
62df8bae1dSRodney W. Grimes  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
63df8bae1dSRodney W. Grimes  *  School of Computer Science
64df8bae1dSRodney W. Grimes  *  Carnegie Mellon University
65df8bae1dSRodney W. Grimes  *  Pittsburgh PA 15213-3890
66df8bae1dSRodney W. Grimes  *
67df8bae1dSRodney W. Grimes  * any improvements or extensions that they make and grant Carnegie the
68df8bae1dSRodney W. Grimes  * rights to redistribute these changes.
69df8bae1dSRodney W. Grimes  */
70df8bae1dSRodney W. Grimes 
71df8bae1dSRodney W. Grimes /*
72df8bae1dSRodney W. Grimes  *	The proverbial page-out daemon.
73df8bae1dSRodney W. Grimes  */
74df8bae1dSRodney W. Grimes 
75874651b1SDavid E. O'Brien #include <sys/cdefs.h>
76874651b1SDavid E. O'Brien __FBSDID("$FreeBSD$");
77874651b1SDavid E. O'Brien 
78faa5f8d8SAndrzej Bialecki #include "opt_vm.h"
797672ca05SMark Johnston 
80df8bae1dSRodney W. Grimes #include <sys/param.h>
8126f9a767SRodney W. Grimes #include <sys/systm.h>
82b5e8ce9fSBruce Evans #include <sys/kernel.h>
83855a310fSJeff Roberson #include <sys/eventhandler.h>
84fb919e4dSMark Murray #include <sys/lock.h>
85fb919e4dSMark Murray #include <sys/mutex.h>
8626f9a767SRodney W. Grimes #include <sys/proc.h>
879c8b8baaSPeter Wemm #include <sys/kthread.h>
880384fff8SJason Evans #include <sys/ktr.h>
8997824da3SAlan Cox #include <sys/mount.h>
90099e7e95SEdward Tomasz Napierala #include <sys/racct.h>
9126f9a767SRodney W. Grimes #include <sys/resourcevar.h>
92b43179fbSJeff Roberson #include <sys/sched.h>
9314a0d74eSSteven Hartland #include <sys/sdt.h>
94d2fc5315SPoul-Henning Kamp #include <sys/signalvar.h>
95449c2e92SKonstantin Belousov #include <sys/smp.h>
96a6bf3a9eSRyan Stone #include <sys/time.h>
97f6b04d2bSDavid Greenman #include <sys/vnode.h>
98efeaf95aSDavid Greenman #include <sys/vmmeter.h>
9989f6b863SAttilio Rao #include <sys/rwlock.h>
1001005a129SJohn Baldwin #include <sys/sx.h>
10138efa82bSJohn Dyson #include <sys/sysctl.h>
102df8bae1dSRodney W. Grimes 
103df8bae1dSRodney W. Grimes #include <vm/vm.h>
104efeaf95aSDavid Greenman #include <vm/vm_param.h>
105efeaf95aSDavid Greenman #include <vm/vm_object.h>
106df8bae1dSRodney W. Grimes #include <vm/vm_page.h>
107efeaf95aSDavid Greenman #include <vm/vm_map.h>
108df8bae1dSRodney W. Grimes #include <vm/vm_pageout.h>
10924a1cce3SDavid Greenman #include <vm/vm_pager.h>
110449c2e92SKonstantin Belousov #include <vm/vm_phys.h>
11105f0fdd2SPoul-Henning Kamp #include <vm/swap_pager.h>
112efeaf95aSDavid Greenman #include <vm/vm_extern.h>
113670d17b5SJeff Roberson #include <vm/uma.h>
114df8bae1dSRodney W. Grimes 
1152b14f991SJulian Elischer /*
1162b14f991SJulian Elischer  * System initialization
1172b14f991SJulian Elischer  */
1182b14f991SJulian Elischer 
1192b14f991SJulian Elischer /* the kernel process "vm_pageout"*/
12011caded3SAlfred Perlstein static void vm_pageout(void);
1214d19f4adSSteven Hartland static void vm_pageout_init(void);
122ebcddc72SAlan Cox static int vm_pageout_clean(vm_page_t m, int *numpagedout);
12334d8b7eaSJeff Roberson static int vm_pageout_cluster(vm_page_t m);
124e57dd910SAlan Cox static bool vm_pageout_scan(struct vm_domain *vmd, int pass);
12576386c7eSKonstantin Belousov static void vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
12676386c7eSKonstantin Belousov     int starting_page_shortage);
12745ae1d91SAlan Cox 
1284d19f4adSSteven Hartland SYSINIT(pagedaemon_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, vm_pageout_init,
1294d19f4adSSteven Hartland     NULL);
1304d19f4adSSteven Hartland 
1312b14f991SJulian Elischer struct proc *pageproc;
1322b14f991SJulian Elischer 
1332b14f991SJulian Elischer static struct kproc_desc page_kp = {
1342b14f991SJulian Elischer 	"pagedaemon",
1352b14f991SJulian Elischer 	vm_pageout,
1362b14f991SJulian Elischer 	&pageproc
1372b14f991SJulian Elischer };
1384d19f4adSSteven Hartland SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_SECOND, kproc_start,
139237fdd78SRobert Watson     &page_kp);
1402b14f991SJulian Elischer 
14114a0d74eSSteven Hartland SDT_PROVIDER_DEFINE(vm);
14214a0d74eSSteven Hartland SDT_PROBE_DEFINE(vm, , , vm__lowmem_scan);
14314a0d74eSSteven Hartland 
14438efa82bSJohn Dyson #if !defined(NO_SWAPPING)
1452b14f991SJulian Elischer /* the kernel process "vm_daemon"*/
14611caded3SAlfred Perlstein static void vm_daemon(void);
147f708ef1bSPoul-Henning Kamp static struct	proc *vmproc;
1482b14f991SJulian Elischer 
1492b14f991SJulian Elischer static struct kproc_desc vm_kp = {
1502b14f991SJulian Elischer 	"vmdaemon",
1512b14f991SJulian Elischer 	vm_daemon,
1522b14f991SJulian Elischer 	&vmproc
1532b14f991SJulian Elischer };
154237fdd78SRobert Watson SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
15538efa82bSJohn Dyson #endif
1562b14f991SJulian Elischer 
157ebcddc72SAlan Cox /* Pagedaemon activity rates, in subdivisions of one second. */
158ebcddc72SAlan Cox #define	VM_LAUNDER_RATE		10
159ebcddc72SAlan Cox #define	VM_INACT_SCAN_RATE	2
1602b14f991SJulian Elischer 
1618b245767SAlan Cox int vm_pageout_deficit;		/* Estimated number of pages deficit */
16220c58db9SMark Johnston u_int vm_pageout_wakeup_thresh;
16376386c7eSKonstantin Belousov static int vm_pageout_oom_seq = 12;
16456ce0690SAlan Cox bool vm_pageout_wanted;		/* Event on which pageout daemon sleeps */
16556ce0690SAlan Cox bool vm_pages_needed;		/* Are threads waiting for free pages? */
16626f9a767SRodney W. Grimes 
167ebcddc72SAlan Cox /* Pending request for dirty page laundering. */
168ebcddc72SAlan Cox static enum {
169ebcddc72SAlan Cox 	VM_LAUNDRY_IDLE,
170ebcddc72SAlan Cox 	VM_LAUNDRY_BACKGROUND,
171ebcddc72SAlan Cox 	VM_LAUNDRY_SHORTFALL
172ebcddc72SAlan Cox } vm_laundry_request = VM_LAUNDRY_IDLE;
173ebcddc72SAlan Cox 
17438efa82bSJohn Dyson #if !defined(NO_SWAPPING)
175f708ef1bSPoul-Henning Kamp static int vm_pageout_req_swapout;	/* XXX */
176f708ef1bSPoul-Henning Kamp static int vm_daemon_needed;
17797824da3SAlan Cox static struct mtx vm_daemon_mtx;
17897824da3SAlan Cox /* Allow for use by vm_pageout before vm_daemon is initialized. */
17997824da3SAlan Cox MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
18038efa82bSJohn Dyson #endif
181d9e23210SJeff Roberson static int vm_pageout_update_period;
1824a365329SAndrey Zonov static int disable_swap_pageouts;
183c9612b2dSJeff Roberson static int lowmem_period = 10;
184a6bf3a9eSRyan Stone static time_t lowmem_uptime;
185b1fd102eSMark Johnston static int swapdev_enabled;
18670111b90SJohn Dyson 
18738efa82bSJohn Dyson #if defined(NO_SWAPPING)
188303b270bSEivind Eklund static int vm_swap_enabled = 0;
189303b270bSEivind Eklund static int vm_swap_idle_enabled = 0;
19038efa82bSJohn Dyson #else
191303b270bSEivind Eklund static int vm_swap_enabled = 1;
192303b270bSEivind Eklund static int vm_swap_idle_enabled = 0;
19338efa82bSJohn Dyson #endif
19438efa82bSJohn Dyson 
1958311a2b8SWill Andrews static int vm_panic_on_oom = 0;
1968311a2b8SWill Andrews 
1978311a2b8SWill Andrews SYSCTL_INT(_vm, OID_AUTO, panic_on_oom,
1988311a2b8SWill Andrews 	CTLFLAG_RWTUN, &vm_panic_on_oom, 0,
1998311a2b8SWill Andrews 	"panic on out of memory instead of killing the largest process");
2008311a2b8SWill Andrews 
201d9e23210SJeff Roberson SYSCTL_INT(_vm, OID_AUTO, pageout_wakeup_thresh,
202d9e23210SJeff Roberson 	CTLFLAG_RW, &vm_pageout_wakeup_thresh, 0,
203d9e23210SJeff Roberson 	"free page threshold for waking up the pageout daemon");
204d9e23210SJeff Roberson 
205d9e23210SJeff Roberson SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
206d9e23210SJeff Roberson 	CTLFLAG_RW, &vm_pageout_update_period, 0,
207d9e23210SJeff Roberson 	"Maximum active LRU update period");
20853636869SAndrey Zonov 
209c9612b2dSJeff Roberson SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RW, &lowmem_period, 0,
210c9612b2dSJeff Roberson 	"Low memory callback period");
211c9612b2dSJeff Roberson 
21238efa82bSJohn Dyson #if defined(NO_SWAPPING)
213ceb0cf87SJohn Dyson SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
2146bd9cb1cSTom Rhodes 	CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout");
215ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
2166bd9cb1cSTom Rhodes 	CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
21738efa82bSJohn Dyson #else
218ceb0cf87SJohn Dyson SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
219b0359e2cSPeter Wemm 	CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
220ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
221b0359e2cSPeter Wemm 	CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
22238efa82bSJohn Dyson #endif
22326f9a767SRodney W. Grimes 
224ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
225b0359e2cSPeter Wemm 	CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
22612ac6a1dSJohn Dyson 
22723b59018SMatthew Dillon static int pageout_lock_miss;
22823b59018SMatthew Dillon SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
22923b59018SMatthew Dillon 	CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
23023b59018SMatthew Dillon 
23176386c7eSKonstantin Belousov SYSCTL_INT(_vm, OID_AUTO, pageout_oom_seq,
23276386c7eSKonstantin Belousov 	CTLFLAG_RW, &vm_pageout_oom_seq, 0,
23376386c7eSKonstantin Belousov 	"back-to-back calls to oom detector to start OOM");
23476386c7eSKonstantin Belousov 
235ebcddc72SAlan Cox static int act_scan_laundry_weight = 3;
236ebcddc72SAlan Cox SYSCTL_INT(_vm, OID_AUTO, act_scan_laundry_weight, CTLFLAG_RW,
237ebcddc72SAlan Cox     &act_scan_laundry_weight, 0,
238ebcddc72SAlan Cox     "weight given to clean vs. dirty pages in active queue scans");
239ebcddc72SAlan Cox 
240ebcddc72SAlan Cox static u_int vm_background_launder_target;
241ebcddc72SAlan Cox SYSCTL_UINT(_vm, OID_AUTO, background_launder_target, CTLFLAG_RW,
242ebcddc72SAlan Cox     &vm_background_launder_target, 0,
243ebcddc72SAlan Cox     "background laundering target, in pages");
244ebcddc72SAlan Cox 
245ebcddc72SAlan Cox static u_int vm_background_launder_rate = 4096;
246ebcddc72SAlan Cox SYSCTL_UINT(_vm, OID_AUTO, background_launder_rate, CTLFLAG_RW,
247ebcddc72SAlan Cox     &vm_background_launder_rate, 0,
248ebcddc72SAlan Cox     "background laundering rate, in kilobytes per second");
249ebcddc72SAlan Cox 
250ebcddc72SAlan Cox static u_int vm_background_launder_max = 20 * 1024;
251ebcddc72SAlan Cox SYSCTL_UINT(_vm, OID_AUTO, background_launder_max, CTLFLAG_RW,
252ebcddc72SAlan Cox     &vm_background_launder_max, 0, "background laundering cap, in kilobytes");
253ebcddc72SAlan Cox 
254ffc82b0aSJohn Dyson #define VM_PAGEOUT_PAGE_COUNT 16
255bbc0ec52SDavid Greenman int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
256df8bae1dSRodney W. Grimes 
257c3cb3e12SDavid Greenman int vm_page_max_wired;		/* XXX max # of wired pages system-wide */
2585dfc2870SAlan Cox SYSCTL_INT(_vm, OID_AUTO, max_wired,
2595dfc2870SAlan Cox 	CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
260df8bae1dSRodney W. Grimes 
261ebcddc72SAlan Cox static u_int isqrt(u_int num);
26285eeca35SAlan Cox static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
263ebcddc72SAlan Cox static int vm_pageout_launder(struct vm_domain *vmd, int launder,
264ebcddc72SAlan Cox     bool in_shortfall);
265ebcddc72SAlan Cox static void vm_pageout_laundry_worker(void *arg);
26638efa82bSJohn Dyson #if !defined(NO_SWAPPING)
267ecf6279fSAlan Cox static void vm_pageout_map_deactivate_pages(vm_map_t, long);
268ecf6279fSAlan Cox static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
26997824da3SAlan Cox static void vm_req_vmdaemon(int req);
27038efa82bSJohn Dyson #endif
27185eeca35SAlan Cox static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
272cd41fc12SDavid Greenman 
273a8229fa3SAlan Cox /*
274a8229fa3SAlan Cox  * Initialize a dummy page for marking the caller's place in the specified
275a8229fa3SAlan Cox  * paging queue.  In principle, this function only needs to set the flag
276f0edf3f8SAlan Cox  * PG_MARKER.  Nonetheless, it write busies and initializes the hold count
277c7aebda8SAttilio Rao  * to one as safety precautions.
278a8229fa3SAlan Cox  */
2798c616246SKonstantin Belousov static void
2808c616246SKonstantin Belousov vm_pageout_init_marker(vm_page_t marker, u_short queue)
2818c616246SKonstantin Belousov {
2828c616246SKonstantin Belousov 
2838c616246SKonstantin Belousov 	bzero(marker, sizeof(*marker));
284a8229fa3SAlan Cox 	marker->flags = PG_MARKER;
285c7aebda8SAttilio Rao 	marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
2868c616246SKonstantin Belousov 	marker->queue = queue;
287a8229fa3SAlan Cox 	marker->hold_count = 1;
2888c616246SKonstantin Belousov }
2898c616246SKonstantin Belousov 
29026f9a767SRodney W. Grimes /*
2918dbca793STor Egge  * vm_pageout_fallback_object_lock:
2928dbca793STor Egge  *
29389f6b863SAttilio Rao  * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
2948dbca793STor Egge  * known to have failed and page queue must be either PQ_ACTIVE or
29544be0a8eSMark Johnston  * PQ_INACTIVE.  To avoid lock order violation, unlock the page queue
2968dbca793STor Egge  * while locking the vm object.  Use marker page to detect page queue
2978dbca793STor Egge  * changes and maintain notion of next page on page queue.  Return
2988dbca793STor Egge  * TRUE if no changes were detected, FALSE otherwise.  vm object is
2998dbca793STor Egge  * locked on return.
3008dbca793STor Egge  *
3018dbca793STor Egge  * This function depends on both the lock portion of struct vm_object
3028dbca793STor Egge  * and normal struct vm_page being type stable.
3038dbca793STor Egge  */
30485eeca35SAlan Cox static boolean_t
3058dbca793STor Egge vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
3068dbca793STor Egge {
3078dbca793STor Egge 	struct vm_page marker;
3088d220203SAlan Cox 	struct vm_pagequeue *pq;
3098dbca793STor Egge 	boolean_t unchanged;
3108dbca793STor Egge 	u_short queue;
3118dbca793STor Egge 	vm_object_t object;
3128dbca793STor Egge 
3138dbca793STor Egge 	queue = m->queue;
3148c616246SKonstantin Belousov 	vm_pageout_init_marker(&marker, queue);
315449c2e92SKonstantin Belousov 	pq = vm_page_pagequeue(m);
3168dbca793STor Egge 	object = m->object;
3178dbca793STor Egge 
318c325e866SKonstantin Belousov 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
3198d220203SAlan Cox 	vm_pagequeue_unlock(pq);
3202965a453SKip Macy 	vm_page_unlock(m);
32189f6b863SAttilio Rao 	VM_OBJECT_WLOCK(object);
3222965a453SKip Macy 	vm_page_lock(m);
3238d220203SAlan Cox 	vm_pagequeue_lock(pq);
3248dbca793STor Egge 
32569b8585eSKonstantin Belousov 	/*
32669b8585eSKonstantin Belousov 	 * The page's object might have changed, and/or the page might
32769b8585eSKonstantin Belousov 	 * have moved from its original position in the queue.  If the
32869b8585eSKonstantin Belousov 	 * page's object has changed, then the caller should abandon
32969b8585eSKonstantin Belousov 	 * processing the page because the wrong object lock was
33069b8585eSKonstantin Belousov 	 * acquired.  Use the marker's plinks.q, not the page's, to
33169b8585eSKonstantin Belousov 	 * determine if the page has been moved.  The state of the
33269b8585eSKonstantin Belousov 	 * page's plinks.q can be indeterminate; whereas, the marker's
33369b8585eSKonstantin Belousov 	 * plinks.q must be valid.
33469b8585eSKonstantin Belousov 	 */
335c325e866SKonstantin Belousov 	*next = TAILQ_NEXT(&marker, plinks.q);
33669b8585eSKonstantin Belousov 	unchanged = m->object == object &&
33769b8585eSKonstantin Belousov 	    m == TAILQ_PREV(&marker, pglist, plinks.q);
33869b8585eSKonstantin Belousov 	KASSERT(!unchanged || m->queue == queue,
33969b8585eSKonstantin Belousov 	    ("page %p queue %d %d", m, queue, m->queue));
340c325e866SKonstantin Belousov 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
3418dbca793STor Egge 	return (unchanged);
3428dbca793STor Egge }
3438dbca793STor Egge 
3448dbca793STor Egge /*
3458c616246SKonstantin Belousov  * Lock the page while holding the page queue lock.  Use marker page
3468c616246SKonstantin Belousov  * to detect page queue changes and maintain notion of next page on
3478c616246SKonstantin Belousov  * page queue.  Return TRUE if no changes were detected, FALSE
3488c616246SKonstantin Belousov  * otherwise.  The page is locked on return. The page queue lock might
3498c616246SKonstantin Belousov  * be dropped and reacquired.
3508c616246SKonstantin Belousov  *
3518c616246SKonstantin Belousov  * This function depends on normal struct vm_page being type stable.
3528c616246SKonstantin Belousov  */
35385eeca35SAlan Cox static boolean_t
3548c616246SKonstantin Belousov vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
3558c616246SKonstantin Belousov {
3568c616246SKonstantin Belousov 	struct vm_page marker;
3578d220203SAlan Cox 	struct vm_pagequeue *pq;
3588c616246SKonstantin Belousov 	boolean_t unchanged;
3598c616246SKonstantin Belousov 	u_short queue;
3608c616246SKonstantin Belousov 
3618c616246SKonstantin Belousov 	vm_page_lock_assert(m, MA_NOTOWNED);
3628c616246SKonstantin Belousov 	if (vm_page_trylock(m))
3638c616246SKonstantin Belousov 		return (TRUE);
3648c616246SKonstantin Belousov 
3658c616246SKonstantin Belousov 	queue = m->queue;
3668c616246SKonstantin Belousov 	vm_pageout_init_marker(&marker, queue);
367449c2e92SKonstantin Belousov 	pq = vm_page_pagequeue(m);
3688c616246SKonstantin Belousov 
369c325e866SKonstantin Belousov 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
3708d220203SAlan Cox 	vm_pagequeue_unlock(pq);
3718c616246SKonstantin Belousov 	vm_page_lock(m);
3728d220203SAlan Cox 	vm_pagequeue_lock(pq);
3738c616246SKonstantin Belousov 
3748c616246SKonstantin Belousov 	/* Page queue might have changed. */
375c325e866SKonstantin Belousov 	*next = TAILQ_NEXT(&marker, plinks.q);
37669b8585eSKonstantin Belousov 	unchanged = m == TAILQ_PREV(&marker, pglist, plinks.q);
37769b8585eSKonstantin Belousov 	KASSERT(!unchanged || m->queue == queue,
37869b8585eSKonstantin Belousov 	    ("page %p queue %d %d", m, queue, m->queue));
379c325e866SKonstantin Belousov 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
3808c616246SKonstantin Belousov 	return (unchanged);
3818c616246SKonstantin Belousov }
3828c616246SKonstantin Belousov 
3838c616246SKonstantin Belousov /*
384248fe642SAlan Cox  * Scan for pages at adjacent offsets within the given page's object that are
385248fe642SAlan Cox  * eligible for laundering, form a cluster of these pages and the given page,
386248fe642SAlan Cox  * and launder that cluster.
38726f9a767SRodney W. Grimes  */
3883af76890SPoul-Henning Kamp static int
38934d8b7eaSJeff Roberson vm_pageout_cluster(vm_page_t m)
39024a1cce3SDavid Greenman {
39154d92145SMatthew Dillon 	vm_object_t object;
392248fe642SAlan Cox 	vm_page_t mc[2 * vm_pageout_page_count], p, pb, ps;
393248fe642SAlan Cox 	vm_pindex_t pindex;
394248fe642SAlan Cox 	int ib, is, page_base, pageout_count;
39526f9a767SRodney W. Grimes 
396248fe642SAlan Cox 	vm_page_assert_locked(m);
39717f6a17bSAlan Cox 	object = m->object;
39889f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
399248fe642SAlan Cox 	pindex = m->pindex;
4000cddd8f0SMatthew Dillon 
40126f9a767SRodney W. Grimes 	/*
402248fe642SAlan Cox 	 * We can't clean the page if it is busy or held.
40324a1cce3SDavid Greenman 	 */
404c7aebda8SAttilio Rao 	vm_page_assert_unbusied(m);
405248fe642SAlan Cox 	KASSERT(m->hold_count == 0, ("page %p is held", m));
40617f6a17bSAlan Cox 	vm_page_unlock(m);
4070d94caffSDavid Greenman 
40891b4f427SAlan Cox 	mc[vm_pageout_page_count] = pb = ps = m;
40926f9a767SRodney W. Grimes 	pageout_count = 1;
410f35329acSJohn Dyson 	page_base = vm_pageout_page_count;
41190ecac61SMatthew Dillon 	ib = 1;
41290ecac61SMatthew Dillon 	is = 1;
41390ecac61SMatthew Dillon 
41424a1cce3SDavid Greenman 	/*
415248fe642SAlan Cox 	 * We can cluster only if the page is not clean, busy, or held, and
416ebcddc72SAlan Cox 	 * the page is in the laundry queue.
41790ecac61SMatthew Dillon 	 *
41890ecac61SMatthew Dillon 	 * During heavy mmap/modification loads the pageout
41990ecac61SMatthew Dillon 	 * daemon can really fragment the underlying file
420248fe642SAlan Cox 	 * due to flushing pages out of order and not trying to
421248fe642SAlan Cox 	 * align the clusters (which leaves sporadic out-of-order
42290ecac61SMatthew Dillon 	 * holes).  To solve this problem we do the reverse scan
42390ecac61SMatthew Dillon 	 * first and attempt to align our cluster, then do a
42490ecac61SMatthew Dillon 	 * forward scan if room remains.
42524a1cce3SDavid Greenman 	 */
42690ecac61SMatthew Dillon more:
427248fe642SAlan Cox 	while (ib != 0 && pageout_count < vm_pageout_page_count) {
42890ecac61SMatthew Dillon 		if (ib > pindex) {
42990ecac61SMatthew Dillon 			ib = 0;
43090ecac61SMatthew Dillon 			break;
431f6b04d2bSDavid Greenman 		}
432c7aebda8SAttilio Rao 		if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
43390ecac61SMatthew Dillon 			ib = 0;
43490ecac61SMatthew Dillon 			break;
435f6b04d2bSDavid Greenman 		}
43624a1cce3SDavid Greenman 		vm_page_test_dirty(p);
437eb5d3969SAlan Cox 		if (p->dirty == 0) {
438eb5d3969SAlan Cox 			ib = 0;
439eb5d3969SAlan Cox 			break;
440eb5d3969SAlan Cox 		}
441eb5d3969SAlan Cox 		vm_page_lock(p);
442ebcddc72SAlan Cox 		if (!vm_page_in_laundry(p) ||
44357601bcbSMatthew Dillon 		    p->hold_count != 0) {	/* may be undergoing I/O */
4442965a453SKip Macy 			vm_page_unlock(p);
44590ecac61SMatthew Dillon 			ib = 0;
44624a1cce3SDavid Greenman 			break;
447f6b04d2bSDavid Greenman 		}
4482965a453SKip Macy 		vm_page_unlock(p);
44991b4f427SAlan Cox 		mc[--page_base] = pb = p;
45090ecac61SMatthew Dillon 		++pageout_count;
45190ecac61SMatthew Dillon 		++ib;
452248fe642SAlan Cox 
45324a1cce3SDavid Greenman 		/*
454248fe642SAlan Cox 		 * We are at an alignment boundary.  Stop here, and switch
455248fe642SAlan Cox 		 * directions.  Do not clear ib.
45624a1cce3SDavid Greenman 		 */
45790ecac61SMatthew Dillon 		if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
45890ecac61SMatthew Dillon 			break;
45924a1cce3SDavid Greenman 	}
46090ecac61SMatthew Dillon 	while (pageout_count < vm_pageout_page_count &&
46190ecac61SMatthew Dillon 	    pindex + is < object->size) {
462c7aebda8SAttilio Rao 		if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
46390ecac61SMatthew Dillon 			break;
46424a1cce3SDavid Greenman 		vm_page_test_dirty(p);
465eb5d3969SAlan Cox 		if (p->dirty == 0)
466eb5d3969SAlan Cox 			break;
467eb5d3969SAlan Cox 		vm_page_lock(p);
468ebcddc72SAlan Cox 		if (!vm_page_in_laundry(p) ||
46957601bcbSMatthew Dillon 		    p->hold_count != 0) {	/* may be undergoing I/O */
4702965a453SKip Macy 			vm_page_unlock(p);
47124a1cce3SDavid Greenman 			break;
47224a1cce3SDavid Greenman 		}
4732965a453SKip Macy 		vm_page_unlock(p);
47491b4f427SAlan Cox 		mc[page_base + pageout_count] = ps = p;
47590ecac61SMatthew Dillon 		++pageout_count;
47690ecac61SMatthew Dillon 		++is;
47724a1cce3SDavid Greenman 	}
47890ecac61SMatthew Dillon 
47990ecac61SMatthew Dillon 	/*
48090ecac61SMatthew Dillon 	 * If we exhausted our forward scan, continue with the reverse scan
481248fe642SAlan Cox 	 * when possible, even past an alignment boundary.  This catches
482248fe642SAlan Cox 	 * boundary conditions.
48390ecac61SMatthew Dillon 	 */
484248fe642SAlan Cox 	if (ib != 0 && pageout_count < vm_pageout_page_count)
48590ecac61SMatthew Dillon 		goto more;
486f6b04d2bSDavid Greenman 
48799e6e193SMark Johnston 	return (vm_pageout_flush(&mc[page_base], pageout_count,
48899e6e193SMark Johnston 	    VM_PAGER_PUT_NOREUSE, 0, NULL, NULL));
489aef922f5SJohn Dyson }
490aef922f5SJohn Dyson 
4911c7c3c6aSMatthew Dillon /*
4921c7c3c6aSMatthew Dillon  * vm_pageout_flush() - launder the given pages
4931c7c3c6aSMatthew Dillon  *
4941c7c3c6aSMatthew Dillon  *	The given pages are laundered.  Note that we setup for the start of
4951c7c3c6aSMatthew Dillon  *	I/O ( i.e. busy the page ), mark it read-only, and bump the object
4961c7c3c6aSMatthew Dillon  *	reference count all in here rather then in the parent.  If we want
4971c7c3c6aSMatthew Dillon  *	the parent to do more sophisticated things we may have to change
4981c7c3c6aSMatthew Dillon  *	the ordering.
4991e8a675cSKonstantin Belousov  *
5001e8a675cSKonstantin Belousov  *	Returned runlen is the count of pages between mreq and first
5011e8a675cSKonstantin Belousov  *	page after mreq with status VM_PAGER_AGAIN.
502126d6082SKonstantin Belousov  *	*eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
503126d6082SKonstantin Belousov  *	for any page in runlen set.
5041c7c3c6aSMatthew Dillon  */
505aef922f5SJohn Dyson int
506126d6082SKonstantin Belousov vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
507126d6082SKonstantin Belousov     boolean_t *eio)
508aef922f5SJohn Dyson {
5092e3b314dSAlan Cox 	vm_object_t object = mc[0]->object;
510aef922f5SJohn Dyson 	int pageout_status[count];
51195461b45SJohn Dyson 	int numpagedout = 0;
5121e8a675cSKonstantin Belousov 	int i, runlen;
513aef922f5SJohn Dyson 
51489f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
5157bec141bSKip Macy 
5161c7c3c6aSMatthew Dillon 	/*
5171c7c3c6aSMatthew Dillon 	 * Initiate I/O.  Bump the vm_page_t->busy counter and
5181c7c3c6aSMatthew Dillon 	 * mark the pages read-only.
5191c7c3c6aSMatthew Dillon 	 *
5201c7c3c6aSMatthew Dillon 	 * We do not have to fixup the clean/dirty bits here... we can
5211c7c3c6aSMatthew Dillon 	 * allow the pager to do it after the I/O completes.
52202fa91d3SMatthew Dillon 	 *
52302fa91d3SMatthew Dillon 	 * NOTE! mc[i]->dirty may be partial or fragmented due to an
52402fa91d3SMatthew Dillon 	 * edge case with file fragments.
5251c7c3c6aSMatthew Dillon 	 */
5268f9110f6SJohn Dyson 	for (i = 0; i < count; i++) {
5277a935082SAlan Cox 		KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
5287a935082SAlan Cox 		    ("vm_pageout_flush: partially invalid page %p index %d/%d",
5297a935082SAlan Cox 			mc[i], i, count));
530c7aebda8SAttilio Rao 		vm_page_sbusy(mc[i]);
53178985e42SAlan Cox 		pmap_remove_write(mc[i]);
5322965a453SKip Macy 	}
533d474eaaaSDoug Rabson 	vm_object_pip_add(object, count);
534aef922f5SJohn Dyson 
535d076fbeaSAlan Cox 	vm_pager_put_pages(object, mc, count, flags, pageout_status);
53626f9a767SRodney W. Grimes 
5371e8a675cSKonstantin Belousov 	runlen = count - mreq;
538126d6082SKonstantin Belousov 	if (eio != NULL)
539126d6082SKonstantin Belousov 		*eio = FALSE;
540aef922f5SJohn Dyson 	for (i = 0; i < count; i++) {
541aef922f5SJohn Dyson 		vm_page_t mt = mc[i];
54224a1cce3SDavid Greenman 
5434cd45723SAlan Cox 		KASSERT(pageout_status[i] == VM_PAGER_PEND ||
5446031c68dSAlan Cox 		    !pmap_page_is_write_mapped(mt),
5459ea8d1a6SAlan Cox 		    ("vm_pageout_flush: page %p is not write protected", mt));
54626f9a767SRodney W. Grimes 		switch (pageout_status[i]) {
54726f9a767SRodney W. Grimes 		case VM_PAGER_OK:
548ebcddc72SAlan Cox 			vm_page_lock(mt);
549ebcddc72SAlan Cox 			if (vm_page_in_laundry(mt))
550ebcddc72SAlan Cox 				vm_page_deactivate_noreuse(mt);
551ebcddc72SAlan Cox 			vm_page_unlock(mt);
552ebcddc72SAlan Cox 			/* FALLTHROUGH */
55326f9a767SRodney W. Grimes 		case VM_PAGER_PEND:
55495461b45SJohn Dyson 			numpagedout++;
55526f9a767SRodney W. Grimes 			break;
55626f9a767SRodney W. Grimes 		case VM_PAGER_BAD:
55726f9a767SRodney W. Grimes 			/*
558ebcddc72SAlan Cox 			 * The page is outside the object's range.  We pretend
559ebcddc72SAlan Cox 			 * that the page out worked and clean the page, so the
560ebcddc72SAlan Cox 			 * changes will be lost if the page is reclaimed by
561ebcddc72SAlan Cox 			 * the page daemon.
56226f9a767SRodney W. Grimes 			 */
56390ecac61SMatthew Dillon 			vm_page_undirty(mt);
564ebcddc72SAlan Cox 			vm_page_lock(mt);
565ebcddc72SAlan Cox 			if (vm_page_in_laundry(mt))
566ebcddc72SAlan Cox 				vm_page_deactivate_noreuse(mt);
567ebcddc72SAlan Cox 			vm_page_unlock(mt);
56826f9a767SRodney W. Grimes 			break;
56926f9a767SRodney W. Grimes 		case VM_PAGER_ERROR:
57026f9a767SRodney W. Grimes 		case VM_PAGER_FAIL:
57126f9a767SRodney W. Grimes 			/*
572b1fd102eSMark Johnston 			 * If the page couldn't be paged out to swap because the
573b1fd102eSMark Johnston 			 * pager wasn't able to find space, place the page in
574b1fd102eSMark Johnston 			 * the PQ_UNSWAPPABLE holding queue.  This is an
575b1fd102eSMark Johnston 			 * optimization that prevents the page daemon from
576b1fd102eSMark Johnston 			 * wasting CPU cycles on pages that cannot be reclaimed
577b1fd102eSMark Johnston 			 * becase no swap device is configured.
578b1fd102eSMark Johnston 			 *
579b1fd102eSMark Johnston 			 * Otherwise, reactivate the page so that it doesn't
580b1fd102eSMark Johnston 			 * clog the laundry and inactive queues.  (We will try
581b1fd102eSMark Johnston 			 * paging it out again later.)
58226f9a767SRodney W. Grimes 			 */
5833c4a2440SAlan Cox 			vm_page_lock(mt);
584b1fd102eSMark Johnston 			if (object->type == OBJT_SWAP &&
585b1fd102eSMark Johnston 			    pageout_status[i] == VM_PAGER_FAIL) {
586b1fd102eSMark Johnston 				vm_page_unswappable(mt);
587b1fd102eSMark Johnston 				numpagedout++;
588b1fd102eSMark Johnston 			} else
58924a1cce3SDavid Greenman 				vm_page_activate(mt);
5903c4a2440SAlan Cox 			vm_page_unlock(mt);
591126d6082SKonstantin Belousov 			if (eio != NULL && i >= mreq && i - mreq < runlen)
592126d6082SKonstantin Belousov 				*eio = TRUE;
59326f9a767SRodney W. Grimes 			break;
59426f9a767SRodney W. Grimes 		case VM_PAGER_AGAIN:
5951e8a675cSKonstantin Belousov 			if (i >= mreq && i - mreq < runlen)
5961e8a675cSKonstantin Belousov 				runlen = i - mreq;
59726f9a767SRodney W. Grimes 			break;
59826f9a767SRodney W. Grimes 		}
59926f9a767SRodney W. Grimes 
60026f9a767SRodney W. Grimes 		/*
6010d94caffSDavid Greenman 		 * If the operation is still going, leave the page busy to
6020d94caffSDavid Greenman 		 * block all other accesses. Also, leave the paging in
6030d94caffSDavid Greenman 		 * progress indicator set so that we don't attempt an object
6040d94caffSDavid Greenman 		 * collapse.
60526f9a767SRodney W. Grimes 		 */
60626f9a767SRodney W. Grimes 		if (pageout_status[i] != VM_PAGER_PEND) {
607f919ebdeSDavid Greenman 			vm_object_pip_wakeup(object);
608c7aebda8SAttilio Rao 			vm_page_sunbusy(mt);
6093c4a2440SAlan Cox 		}
6103c4a2440SAlan Cox 	}
6111e8a675cSKonstantin Belousov 	if (prunlen != NULL)
6121e8a675cSKonstantin Belousov 		*prunlen = runlen;
6133c4a2440SAlan Cox 	return (numpagedout);
61426f9a767SRodney W. Grimes }
61526f9a767SRodney W. Grimes 
616b1fd102eSMark Johnston static void
617b1fd102eSMark Johnston vm_pageout_swapon(void *arg __unused, struct swdevt *sp __unused)
618b1fd102eSMark Johnston {
619b1fd102eSMark Johnston 
620b1fd102eSMark Johnston 	atomic_store_rel_int(&swapdev_enabled, 1);
621b1fd102eSMark Johnston }
622b1fd102eSMark Johnston 
623b1fd102eSMark Johnston static void
624b1fd102eSMark Johnston vm_pageout_swapoff(void *arg __unused, struct swdevt *sp __unused)
625b1fd102eSMark Johnston {
626b1fd102eSMark Johnston 
627b1fd102eSMark Johnston 	if (swap_pager_nswapdev() == 1)
628b1fd102eSMark Johnston 		atomic_store_rel_int(&swapdev_enabled, 0);
629b1fd102eSMark Johnston }
630b1fd102eSMark Johnston 
63138efa82bSJohn Dyson #if !defined(NO_SWAPPING)
63226f9a767SRodney W. Grimes /*
63326f9a767SRodney W. Grimes  *	vm_pageout_object_deactivate_pages
63426f9a767SRodney W. Grimes  *
635ce186587SAlan Cox  *	Deactivate enough pages to satisfy the inactive target
636ce186587SAlan Cox  *	requirements.
63726f9a767SRodney W. Grimes  *
63826f9a767SRodney W. Grimes  *	The object and map must be locked.
63926f9a767SRodney W. Grimes  */
64038efa82bSJohn Dyson static void
641ce186587SAlan Cox vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
642ce186587SAlan Cox     long desired)
64326f9a767SRodney W. Grimes {
644ecf6279fSAlan Cox 	vm_object_t backing_object, object;
645ce186587SAlan Cox 	vm_page_t p;
646bb7858eaSJeff Roberson 	int act_delta, remove_mode;
64726f9a767SRodney W. Grimes 
648e23b0a19SAlan Cox 	VM_OBJECT_ASSERT_LOCKED(first_object);
64928634820SAlan Cox 	if ((first_object->flags & OBJ_FICTITIOUS) != 0)
65038efa82bSJohn Dyson 		return;
651ecf6279fSAlan Cox 	for (object = first_object;; object = backing_object) {
652ecf6279fSAlan Cox 		if (pmap_resident_count(pmap) <= desired)
653ecf6279fSAlan Cox 			goto unlock_return;
654e23b0a19SAlan Cox 		VM_OBJECT_ASSERT_LOCKED(object);
65528634820SAlan Cox 		if ((object->flags & OBJ_UNMANAGED) != 0 ||
65628634820SAlan Cox 		    object->paging_in_progress != 0)
657ecf6279fSAlan Cox 			goto unlock_return;
65826f9a767SRodney W. Grimes 
65985b1dc89SAlan Cox 		remove_mode = 0;
66038efa82bSJohn Dyson 		if (object->shadow_count > 1)
66138efa82bSJohn Dyson 			remove_mode = 1;
66226f9a767SRodney W. Grimes 		/*
663ce186587SAlan Cox 		 * Scan the object's entire memory queue.
66426f9a767SRodney W. Grimes 		 */
665ce186587SAlan Cox 		TAILQ_FOREACH(p, &object->memq, listq) {
666447fe2a4SAlan Cox 			if (pmap_resident_count(pmap) <= desired)
667447fe2a4SAlan Cox 				goto unlock_return;
668c7aebda8SAttilio Rao 			if (vm_page_busied(p))
669447fe2a4SAlan Cox 				continue;
670*83c9dea1SGleb Smirnoff 			VM_CNT_INC(v_pdpages);
6712965a453SKip Macy 			vm_page_lock(p);
672ce186587SAlan Cox 			if (p->wire_count != 0 || p->hold_count != 0 ||
673ecf6279fSAlan Cox 			    !pmap_page_exists_quick(pmap, p)) {
6742965a453SKip Macy 				vm_page_unlock(p);
6750d94caffSDavid Greenman 				continue;
6760d94caffSDavid Greenman 			}
677bb7858eaSJeff Roberson 			act_delta = pmap_ts_referenced(p);
6783407fefeSKonstantin Belousov 			if ((p->aflags & PGA_REFERENCED) != 0) {
679bb7858eaSJeff Roberson 				if (act_delta == 0)
680bb7858eaSJeff Roberson 					act_delta = 1;
6813407fefeSKonstantin Belousov 				vm_page_aflag_clear(p, PGA_REFERENCED);
682ef743ce6SJohn Dyson 			}
683ebcddc72SAlan Cox 			if (!vm_page_active(p) && act_delta != 0) {
684ef743ce6SJohn Dyson 				vm_page_activate(p);
685bb7858eaSJeff Roberson 				p->act_count += act_delta;
686ebcddc72SAlan Cox 			} else if (vm_page_active(p)) {
687bb7858eaSJeff Roberson 				if (act_delta == 0) {
688ce186587SAlan Cox 					p->act_count -= min(p->act_count,
689ce186587SAlan Cox 					    ACT_DECLINE);
69090776bd7SJeff Roberson 					if (!remove_mode && p->act_count == 0) {
6914fec79beSAlan Cox 						pmap_remove_all(p);
69226f9a767SRodney W. Grimes 						vm_page_deactivate(p);
6938d220203SAlan Cox 					} else
6948d220203SAlan Cox 						vm_page_requeue(p);
695c8c4b40cSJohn Dyson 				} else {
696eaf13dd7SJohn Dyson 					vm_page_activate(p);
697ce186587SAlan Cox 					if (p->act_count < ACT_MAX -
698ce186587SAlan Cox 					    ACT_ADVANCE)
69938efa82bSJohn Dyson 						p->act_count += ACT_ADVANCE;
7008d220203SAlan Cox 					vm_page_requeue(p);
701ce186587SAlan Cox 				}
702ebcddc72SAlan Cox 			} else if (vm_page_inactive(p))
703ce186587SAlan Cox 				pmap_remove_all(p);
7042965a453SKip Macy 			vm_page_unlock(p);
70526f9a767SRodney W. Grimes 		}
706ecf6279fSAlan Cox 		if ((backing_object = object->backing_object) == NULL)
707ecf6279fSAlan Cox 			goto unlock_return;
708e23b0a19SAlan Cox 		VM_OBJECT_RLOCK(backing_object);
709ecf6279fSAlan Cox 		if (object != first_object)
710e23b0a19SAlan Cox 			VM_OBJECT_RUNLOCK(object);
71138efa82bSJohn Dyson 	}
712ecf6279fSAlan Cox unlock_return:
713ecf6279fSAlan Cox 	if (object != first_object)
714e23b0a19SAlan Cox 		VM_OBJECT_RUNLOCK(object);
71526f9a767SRodney W. Grimes }
71626f9a767SRodney W. Grimes 
71726f9a767SRodney W. Grimes /*
71826f9a767SRodney W. Grimes  * deactivate some number of pages in a map, try to do it fairly, but
71926f9a767SRodney W. Grimes  * that is really hard to do.
72026f9a767SRodney W. Grimes  */
721cd41fc12SDavid Greenman static void
72238efa82bSJohn Dyson vm_pageout_map_deactivate_pages(map, desired)
72326f9a767SRodney W. Grimes 	vm_map_t map;
724ecf6279fSAlan Cox 	long desired;
72526f9a767SRodney W. Grimes {
72626f9a767SRodney W. Grimes 	vm_map_entry_t tmpe;
72738efa82bSJohn Dyson 	vm_object_t obj, bigobj;
72830105b9eSTor Egge 	int nothingwired;
7290d94caffSDavid Greenman 
730d974f03cSAlan Cox 	if (!vm_map_trylock(map))
73126f9a767SRodney W. Grimes 		return;
73238efa82bSJohn Dyson 
73338efa82bSJohn Dyson 	bigobj = NULL;
73430105b9eSTor Egge 	nothingwired = TRUE;
73538efa82bSJohn Dyson 
73638efa82bSJohn Dyson 	/*
73738efa82bSJohn Dyson 	 * first, search out the biggest object, and try to free pages from
73838efa82bSJohn Dyson 	 * that.
73938efa82bSJohn Dyson 	 */
74026f9a767SRodney W. Grimes 	tmpe = map->header.next;
74138efa82bSJohn Dyson 	while (tmpe != &map->header) {
7429fdfe602SMatthew Dillon 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
74338efa82bSJohn Dyson 			obj = tmpe->object.vm_object;
744e23b0a19SAlan Cox 			if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
7450774dfb3SAlan Cox 				if (obj->shadow_count <= 1 &&
7460774dfb3SAlan Cox 				    (bigobj == NULL ||
7470774dfb3SAlan Cox 				     bigobj->resident_page_count < obj->resident_page_count)) {
7480774dfb3SAlan Cox 					if (bigobj != NULL)
749e23b0a19SAlan Cox 						VM_OBJECT_RUNLOCK(bigobj);
75038efa82bSJohn Dyson 					bigobj = obj;
7510774dfb3SAlan Cox 				} else
752e23b0a19SAlan Cox 					VM_OBJECT_RUNLOCK(obj);
75338efa82bSJohn Dyson 			}
75438efa82bSJohn Dyson 		}
75530105b9eSTor Egge 		if (tmpe->wired_count > 0)
75630105b9eSTor Egge 			nothingwired = FALSE;
75738efa82bSJohn Dyson 		tmpe = tmpe->next;
75838efa82bSJohn Dyson 	}
75938efa82bSJohn Dyson 
7600774dfb3SAlan Cox 	if (bigobj != NULL) {
761ecf6279fSAlan Cox 		vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
762e23b0a19SAlan Cox 		VM_OBJECT_RUNLOCK(bigobj);
7630774dfb3SAlan Cox 	}
76438efa82bSJohn Dyson 	/*
76538efa82bSJohn Dyson 	 * Next, hunt around for other pages to deactivate.  We actually
76638efa82bSJohn Dyson 	 * do this search sort of wrong -- .text first is not the best idea.
76738efa82bSJohn Dyson 	 */
76838efa82bSJohn Dyson 	tmpe = map->header.next;
76938efa82bSJohn Dyson 	while (tmpe != &map->header) {
770b1028ad1SLuoqi Chen 		if (pmap_resident_count(vm_map_pmap(map)) <= desired)
77138efa82bSJohn Dyson 			break;
7729fdfe602SMatthew Dillon 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
77338efa82bSJohn Dyson 			obj = tmpe->object.vm_object;
7740774dfb3SAlan Cox 			if (obj != NULL) {
775e23b0a19SAlan Cox 				VM_OBJECT_RLOCK(obj);
776ecf6279fSAlan Cox 				vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
777e23b0a19SAlan Cox 				VM_OBJECT_RUNLOCK(obj);
7780774dfb3SAlan Cox 			}
77938efa82bSJohn Dyson 		}
78026f9a767SRodney W. Grimes 		tmpe = tmpe->next;
78138857e7fSAlan Cox 	}
78238efa82bSJohn Dyson 
78338efa82bSJohn Dyson 	/*
78438efa82bSJohn Dyson 	 * Remove all mappings if a process is swapped out, this will free page
78538efa82bSJohn Dyson 	 * table pages.
78638efa82bSJohn Dyson 	 */
78738857e7fSAlan Cox 	if (desired == 0 && nothingwired) {
7888d01a3b2SNathan Whitehorn 		pmap_remove(vm_map_pmap(map), vm_map_min(map),
7898d01a3b2SNathan Whitehorn 		    vm_map_max(map));
79038857e7fSAlan Cox 	}
791938b0f5bSMarcel Moolenaar 
79238efa82bSJohn Dyson 	vm_map_unlock(map);
79326f9a767SRodney W. Grimes }
794a1287949SEivind Eklund #endif		/* !defined(NO_SWAPPING) */
795df8bae1dSRodney W. Grimes 
7961c7c3c6aSMatthew Dillon /*
79734d8b7eaSJeff Roberson  * Attempt to acquire all of the necessary locks to launder a page and
79834d8b7eaSJeff Roberson  * then call through the clustering layer to PUTPAGES.  Wait a short
79934d8b7eaSJeff Roberson  * time for a vnode lock.
80034d8b7eaSJeff Roberson  *
80134d8b7eaSJeff Roberson  * Requires the page and object lock on entry, releases both before return.
80234d8b7eaSJeff Roberson  * Returns 0 on success and an errno otherwise.
80334d8b7eaSJeff Roberson  */
80434d8b7eaSJeff Roberson static int
805ebcddc72SAlan Cox vm_pageout_clean(vm_page_t m, int *numpagedout)
80634d8b7eaSJeff Roberson {
80734d8b7eaSJeff Roberson 	struct vnode *vp;
80834d8b7eaSJeff Roberson 	struct mount *mp;
80934d8b7eaSJeff Roberson 	vm_object_t object;
81034d8b7eaSJeff Roberson 	vm_pindex_t pindex;
81134d8b7eaSJeff Roberson 	int error, lockmode;
81234d8b7eaSJeff Roberson 
81334d8b7eaSJeff Roberson 	vm_page_assert_locked(m);
81434d8b7eaSJeff Roberson 	object = m->object;
81534d8b7eaSJeff Roberson 	VM_OBJECT_ASSERT_WLOCKED(object);
81634d8b7eaSJeff Roberson 	error = 0;
81734d8b7eaSJeff Roberson 	vp = NULL;
81834d8b7eaSJeff Roberson 	mp = NULL;
81934d8b7eaSJeff Roberson 
82034d8b7eaSJeff Roberson 	/*
82134d8b7eaSJeff Roberson 	 * The object is already known NOT to be dead.   It
82234d8b7eaSJeff Roberson 	 * is possible for the vget() to block the whole
82334d8b7eaSJeff Roberson 	 * pageout daemon, but the new low-memory handling
82434d8b7eaSJeff Roberson 	 * code should prevent it.
82534d8b7eaSJeff Roberson 	 *
82634d8b7eaSJeff Roberson 	 * We can't wait forever for the vnode lock, we might
82734d8b7eaSJeff Roberson 	 * deadlock due to a vn_read() getting stuck in
82834d8b7eaSJeff Roberson 	 * vm_wait while holding this vnode.  We skip the
82934d8b7eaSJeff Roberson 	 * vnode if we can't get it in a reasonable amount
83034d8b7eaSJeff Roberson 	 * of time.
83134d8b7eaSJeff Roberson 	 */
83234d8b7eaSJeff Roberson 	if (object->type == OBJT_VNODE) {
83334d8b7eaSJeff Roberson 		vm_page_unlock(m);
83434d8b7eaSJeff Roberson 		vp = object->handle;
83534d8b7eaSJeff Roberson 		if (vp->v_type == VREG &&
83634d8b7eaSJeff Roberson 		    vn_start_write(vp, &mp, V_NOWAIT) != 0) {
83734d8b7eaSJeff Roberson 			mp = NULL;
83834d8b7eaSJeff Roberson 			error = EDEADLK;
83934d8b7eaSJeff Roberson 			goto unlock_all;
84034d8b7eaSJeff Roberson 		}
84134d8b7eaSJeff Roberson 		KASSERT(mp != NULL,
84234d8b7eaSJeff Roberson 		    ("vp %p with NULL v_mount", vp));
84334d8b7eaSJeff Roberson 		vm_object_reference_locked(object);
84434d8b7eaSJeff Roberson 		pindex = m->pindex;
84534d8b7eaSJeff Roberson 		VM_OBJECT_WUNLOCK(object);
84634d8b7eaSJeff Roberson 		lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
84734d8b7eaSJeff Roberson 		    LK_SHARED : LK_EXCLUSIVE;
84834d8b7eaSJeff Roberson 		if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
84934d8b7eaSJeff Roberson 			vp = NULL;
85034d8b7eaSJeff Roberson 			error = EDEADLK;
85134d8b7eaSJeff Roberson 			goto unlock_mp;
85234d8b7eaSJeff Roberson 		}
85334d8b7eaSJeff Roberson 		VM_OBJECT_WLOCK(object);
85434d8b7eaSJeff Roberson 		vm_page_lock(m);
85534d8b7eaSJeff Roberson 		/*
85634d8b7eaSJeff Roberson 		 * While the object and page were unlocked, the page
85734d8b7eaSJeff Roberson 		 * may have been:
85834d8b7eaSJeff Roberson 		 * (1) moved to a different queue,
85934d8b7eaSJeff Roberson 		 * (2) reallocated to a different object,
86034d8b7eaSJeff Roberson 		 * (3) reallocated to a different offset, or
86134d8b7eaSJeff Roberson 		 * (4) cleaned.
86234d8b7eaSJeff Roberson 		 */
863ebcddc72SAlan Cox 		if (!vm_page_in_laundry(m) || m->object != object ||
86434d8b7eaSJeff Roberson 		    m->pindex != pindex || m->dirty == 0) {
86534d8b7eaSJeff Roberson 			vm_page_unlock(m);
86634d8b7eaSJeff Roberson 			error = ENXIO;
86734d8b7eaSJeff Roberson 			goto unlock_all;
86834d8b7eaSJeff Roberson 		}
86934d8b7eaSJeff Roberson 
87034d8b7eaSJeff Roberson 		/*
87134d8b7eaSJeff Roberson 		 * The page may have been busied or held while the object
87234d8b7eaSJeff Roberson 		 * and page locks were released.
87334d8b7eaSJeff Roberson 		 */
87434d8b7eaSJeff Roberson 		if (vm_page_busied(m) || m->hold_count != 0) {
87534d8b7eaSJeff Roberson 			vm_page_unlock(m);
87634d8b7eaSJeff Roberson 			error = EBUSY;
87734d8b7eaSJeff Roberson 			goto unlock_all;
87834d8b7eaSJeff Roberson 		}
87934d8b7eaSJeff Roberson 	}
88034d8b7eaSJeff Roberson 
88134d8b7eaSJeff Roberson 	/*
88234d8b7eaSJeff Roberson 	 * If a page is dirty, then it is either being washed
88334d8b7eaSJeff Roberson 	 * (but not yet cleaned) or it is still in the
88434d8b7eaSJeff Roberson 	 * laundry.  If it is still in the laundry, then we
88534d8b7eaSJeff Roberson 	 * start the cleaning operation.
88634d8b7eaSJeff Roberson 	 */
887ebcddc72SAlan Cox 	if ((*numpagedout = vm_pageout_cluster(m)) == 0)
88834d8b7eaSJeff Roberson 		error = EIO;
88934d8b7eaSJeff Roberson 
89034d8b7eaSJeff Roberson unlock_all:
89134d8b7eaSJeff Roberson 	VM_OBJECT_WUNLOCK(object);
89234d8b7eaSJeff Roberson 
89334d8b7eaSJeff Roberson unlock_mp:
89434d8b7eaSJeff Roberson 	vm_page_lock_assert(m, MA_NOTOWNED);
89534d8b7eaSJeff Roberson 	if (mp != NULL) {
89634d8b7eaSJeff Roberson 		if (vp != NULL)
89734d8b7eaSJeff Roberson 			vput(vp);
89834d8b7eaSJeff Roberson 		vm_object_deallocate(object);
89934d8b7eaSJeff Roberson 		vn_finished_write(mp);
90034d8b7eaSJeff Roberson 	}
90134d8b7eaSJeff Roberson 
90234d8b7eaSJeff Roberson 	return (error);
90334d8b7eaSJeff Roberson }
90434d8b7eaSJeff Roberson 
90534d8b7eaSJeff Roberson /*
906ebcddc72SAlan Cox  * Attempt to launder the specified number of pages.
907ebcddc72SAlan Cox  *
908ebcddc72SAlan Cox  * Returns the number of pages successfully laundered.
909ebcddc72SAlan Cox  */
910ebcddc72SAlan Cox static int
911ebcddc72SAlan Cox vm_pageout_launder(struct vm_domain *vmd, int launder, bool in_shortfall)
912ebcddc72SAlan Cox {
913ebcddc72SAlan Cox 	struct vm_pagequeue *pq;
914ebcddc72SAlan Cox 	vm_object_t object;
915ebcddc72SAlan Cox 	vm_page_t m, next;
916ebcddc72SAlan Cox 	int act_delta, error, maxscan, numpagedout, starting_target;
917ebcddc72SAlan Cox 	int vnodes_skipped;
918ebcddc72SAlan Cox 	bool pageout_ok, queue_locked;
919ebcddc72SAlan Cox 
920ebcddc72SAlan Cox 	starting_target = launder;
921ebcddc72SAlan Cox 	vnodes_skipped = 0;
922ebcddc72SAlan Cox 
923ebcddc72SAlan Cox 	/*
924b1fd102eSMark Johnston 	 * Scan the laundry queues for pages eligible to be laundered.  We stop
925ebcddc72SAlan Cox 	 * once the target number of dirty pages have been laundered, or once
926ebcddc72SAlan Cox 	 * we've reached the end of the queue.  A single iteration of this loop
927ebcddc72SAlan Cox 	 * may cause more than one page to be laundered because of clustering.
928ebcddc72SAlan Cox 	 *
929ebcddc72SAlan Cox 	 * maxscan ensures that we don't re-examine requeued pages.  Any
930ebcddc72SAlan Cox 	 * additional pages written as part of a cluster are subtracted from
931ebcddc72SAlan Cox 	 * maxscan since they must be taken from the laundry queue.
932b1fd102eSMark Johnston 	 *
933b1fd102eSMark Johnston 	 * As an optimization, we avoid laundering from PQ_UNSWAPPABLE when no
934b1fd102eSMark Johnston 	 * swap devices are configured.
935ebcddc72SAlan Cox 	 */
936b1fd102eSMark Johnston 	if (atomic_load_acq_int(&swapdev_enabled))
937b1fd102eSMark Johnston 		pq = &vmd->vmd_pagequeues[PQ_UNSWAPPABLE];
938b1fd102eSMark Johnston 	else
939ebcddc72SAlan Cox 		pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
940ebcddc72SAlan Cox 
941b1fd102eSMark Johnston scan:
942ebcddc72SAlan Cox 	vm_pagequeue_lock(pq);
943b1fd102eSMark Johnston 	maxscan = pq->pq_cnt;
944ebcddc72SAlan Cox 	queue_locked = true;
945ebcddc72SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl);
946ebcddc72SAlan Cox 	    m != NULL && maxscan-- > 0 && launder > 0;
947ebcddc72SAlan Cox 	    m = next) {
948ebcddc72SAlan Cox 		vm_pagequeue_assert_locked(pq);
949ebcddc72SAlan Cox 		KASSERT(queue_locked, ("unlocked laundry queue"));
950ebcddc72SAlan Cox 		KASSERT(vm_page_in_laundry(m),
951ebcddc72SAlan Cox 		    ("page %p has an inconsistent queue", m));
952ebcddc72SAlan Cox 		next = TAILQ_NEXT(m, plinks.q);
953ebcddc72SAlan Cox 		if ((m->flags & PG_MARKER) != 0)
954ebcddc72SAlan Cox 			continue;
955ebcddc72SAlan Cox 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
956ebcddc72SAlan Cox 		    ("PG_FICTITIOUS page %p cannot be in laundry queue", m));
957ebcddc72SAlan Cox 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
958ebcddc72SAlan Cox 		    ("VPO_UNMANAGED page %p cannot be in laundry queue", m));
959ebcddc72SAlan Cox 		if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
960ebcddc72SAlan Cox 			vm_page_unlock(m);
961ebcddc72SAlan Cox 			continue;
962ebcddc72SAlan Cox 		}
963ebcddc72SAlan Cox 		object = m->object;
964ebcddc72SAlan Cox 		if ((!VM_OBJECT_TRYWLOCK(object) &&
965ebcddc72SAlan Cox 		    (!vm_pageout_fallback_object_lock(m, &next) ||
966ebcddc72SAlan Cox 		    m->hold_count != 0)) || vm_page_busied(m)) {
967ebcddc72SAlan Cox 			VM_OBJECT_WUNLOCK(object);
968ebcddc72SAlan Cox 			vm_page_unlock(m);
969ebcddc72SAlan Cox 			continue;
970ebcddc72SAlan Cox 		}
971ebcddc72SAlan Cox 
972ebcddc72SAlan Cox 		/*
973ebcddc72SAlan Cox 		 * Unlock the laundry queue, invalidating the 'next' pointer.
974ebcddc72SAlan Cox 		 * Use a marker to remember our place in the laundry queue.
975ebcddc72SAlan Cox 		 */
976ebcddc72SAlan Cox 		TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_laundry_marker,
977ebcddc72SAlan Cox 		    plinks.q);
978ebcddc72SAlan Cox 		vm_pagequeue_unlock(pq);
979ebcddc72SAlan Cox 		queue_locked = false;
980ebcddc72SAlan Cox 
981ebcddc72SAlan Cox 		/*
982ebcddc72SAlan Cox 		 * Invalid pages can be easily freed.  They cannot be
983ebcddc72SAlan Cox 		 * mapped; vm_page_free() asserts this.
984ebcddc72SAlan Cox 		 */
985ebcddc72SAlan Cox 		if (m->valid == 0)
986ebcddc72SAlan Cox 			goto free_page;
987ebcddc72SAlan Cox 
988ebcddc72SAlan Cox 		/*
989ebcddc72SAlan Cox 		 * If the page has been referenced and the object is not dead,
990ebcddc72SAlan Cox 		 * reactivate or requeue the page depending on whether the
991ebcddc72SAlan Cox 		 * object is mapped.
992ebcddc72SAlan Cox 		 */
993ebcddc72SAlan Cox 		if ((m->aflags & PGA_REFERENCED) != 0) {
994ebcddc72SAlan Cox 			vm_page_aflag_clear(m, PGA_REFERENCED);
995ebcddc72SAlan Cox 			act_delta = 1;
996ebcddc72SAlan Cox 		} else
997ebcddc72SAlan Cox 			act_delta = 0;
998ebcddc72SAlan Cox 		if (object->ref_count != 0)
999ebcddc72SAlan Cox 			act_delta += pmap_ts_referenced(m);
1000ebcddc72SAlan Cox 		else {
1001ebcddc72SAlan Cox 			KASSERT(!pmap_page_is_mapped(m),
1002ebcddc72SAlan Cox 			    ("page %p is mapped", m));
1003ebcddc72SAlan Cox 		}
1004ebcddc72SAlan Cox 		if (act_delta != 0) {
1005ebcddc72SAlan Cox 			if (object->ref_count != 0) {
1006*83c9dea1SGleb Smirnoff 				VM_CNT_INC(v_reactivated);
1007ebcddc72SAlan Cox 				vm_page_activate(m);
1008ebcddc72SAlan Cox 
1009ebcddc72SAlan Cox 				/*
1010ebcddc72SAlan Cox 				 * Increase the activation count if the page
1011ebcddc72SAlan Cox 				 * was referenced while in the laundry queue.
1012ebcddc72SAlan Cox 				 * This makes it less likely that the page will
1013ebcddc72SAlan Cox 				 * be returned prematurely to the inactive
1014ebcddc72SAlan Cox 				 * queue.
1015ebcddc72SAlan Cox  				 */
1016ebcddc72SAlan Cox 				m->act_count += act_delta + ACT_ADVANCE;
1017ebcddc72SAlan Cox 
1018ebcddc72SAlan Cox 				/*
1019ebcddc72SAlan Cox 				 * If this was a background laundering, count
1020ebcddc72SAlan Cox 				 * activated pages towards our target.  The
1021ebcddc72SAlan Cox 				 * purpose of background laundering is to ensure
1022ebcddc72SAlan Cox 				 * that pages are eventually cycled through the
1023ebcddc72SAlan Cox 				 * laundry queue, and an activation is a valid
1024ebcddc72SAlan Cox 				 * way out.
1025ebcddc72SAlan Cox 				 */
1026ebcddc72SAlan Cox 				if (!in_shortfall)
1027ebcddc72SAlan Cox 					launder--;
1028ebcddc72SAlan Cox 				goto drop_page;
1029ebcddc72SAlan Cox 			} else if ((object->flags & OBJ_DEAD) == 0)
1030ebcddc72SAlan Cox 				goto requeue_page;
1031ebcddc72SAlan Cox 		}
1032ebcddc72SAlan Cox 
1033ebcddc72SAlan Cox 		/*
1034ebcddc72SAlan Cox 		 * If the page appears to be clean at the machine-independent
1035ebcddc72SAlan Cox 		 * layer, then remove all of its mappings from the pmap in
1036ebcddc72SAlan Cox 		 * anticipation of freeing it.  If, however, any of the page's
1037ebcddc72SAlan Cox 		 * mappings allow write access, then the page may still be
1038ebcddc72SAlan Cox 		 * modified until the last of those mappings are removed.
1039ebcddc72SAlan Cox 		 */
1040ebcddc72SAlan Cox 		if (object->ref_count != 0) {
1041ebcddc72SAlan Cox 			vm_page_test_dirty(m);
1042ebcddc72SAlan Cox 			if (m->dirty == 0)
1043ebcddc72SAlan Cox 				pmap_remove_all(m);
1044ebcddc72SAlan Cox 		}
1045ebcddc72SAlan Cox 
1046ebcddc72SAlan Cox 		/*
1047ebcddc72SAlan Cox 		 * Clean pages are freed, and dirty pages are paged out unless
1048ebcddc72SAlan Cox 		 * they belong to a dead object.  Requeueing dirty pages from
1049ebcddc72SAlan Cox 		 * dead objects is pointless, as they are being paged out and
1050ebcddc72SAlan Cox 		 * freed by the thread that destroyed the object.
1051ebcddc72SAlan Cox 		 */
1052ebcddc72SAlan Cox 		if (m->dirty == 0) {
1053ebcddc72SAlan Cox free_page:
1054ebcddc72SAlan Cox 			vm_page_free(m);
1055*83c9dea1SGleb Smirnoff 			VM_CNT_INC(v_dfree);
1056ebcddc72SAlan Cox 		} else if ((object->flags & OBJ_DEAD) == 0) {
1057ebcddc72SAlan Cox 			if (object->type != OBJT_SWAP &&
1058ebcddc72SAlan Cox 			    object->type != OBJT_DEFAULT)
1059ebcddc72SAlan Cox 				pageout_ok = true;
1060ebcddc72SAlan Cox 			else if (disable_swap_pageouts)
1061ebcddc72SAlan Cox 				pageout_ok = false;
1062ebcddc72SAlan Cox 			else
1063ebcddc72SAlan Cox 				pageout_ok = true;
1064ebcddc72SAlan Cox 			if (!pageout_ok) {
1065ebcddc72SAlan Cox requeue_page:
1066ebcddc72SAlan Cox 				vm_pagequeue_lock(pq);
1067ebcddc72SAlan Cox 				queue_locked = true;
1068ebcddc72SAlan Cox 				vm_page_requeue_locked(m);
1069ebcddc72SAlan Cox 				goto drop_page;
1070ebcddc72SAlan Cox 			}
1071ebcddc72SAlan Cox 
1072ebcddc72SAlan Cox 			/*
1073ebcddc72SAlan Cox 			 * Form a cluster with adjacent, dirty pages from the
1074ebcddc72SAlan Cox 			 * same object, and page out that entire cluster.
1075ebcddc72SAlan Cox 			 *
1076ebcddc72SAlan Cox 			 * The adjacent, dirty pages must also be in the
1077ebcddc72SAlan Cox 			 * laundry.  However, their mappings are not checked
1078ebcddc72SAlan Cox 			 * for new references.  Consequently, a recently
1079ebcddc72SAlan Cox 			 * referenced page may be paged out.  However, that
1080ebcddc72SAlan Cox 			 * page will not be prematurely reclaimed.  After page
1081ebcddc72SAlan Cox 			 * out, the page will be placed in the inactive queue,
1082ebcddc72SAlan Cox 			 * where any new references will be detected and the
1083ebcddc72SAlan Cox 			 * page reactivated.
1084ebcddc72SAlan Cox 			 */
1085ebcddc72SAlan Cox 			error = vm_pageout_clean(m, &numpagedout);
1086ebcddc72SAlan Cox 			if (error == 0) {
1087ebcddc72SAlan Cox 				launder -= numpagedout;
1088ebcddc72SAlan Cox 				maxscan -= numpagedout - 1;
1089ebcddc72SAlan Cox 			} else if (error == EDEADLK) {
1090ebcddc72SAlan Cox 				pageout_lock_miss++;
1091ebcddc72SAlan Cox 				vnodes_skipped++;
1092ebcddc72SAlan Cox 			}
1093ebcddc72SAlan Cox 			goto relock_queue;
1094ebcddc72SAlan Cox 		}
1095ebcddc72SAlan Cox drop_page:
1096ebcddc72SAlan Cox 		vm_page_unlock(m);
1097ebcddc72SAlan Cox 		VM_OBJECT_WUNLOCK(object);
1098ebcddc72SAlan Cox relock_queue:
1099ebcddc72SAlan Cox 		if (!queue_locked) {
1100ebcddc72SAlan Cox 			vm_pagequeue_lock(pq);
1101ebcddc72SAlan Cox 			queue_locked = true;
1102ebcddc72SAlan Cox 		}
1103ebcddc72SAlan Cox 		next = TAILQ_NEXT(&vmd->vmd_laundry_marker, plinks.q);
1104ebcddc72SAlan Cox 		TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_laundry_marker, plinks.q);
1105ebcddc72SAlan Cox 	}
1106ebcddc72SAlan Cox 	vm_pagequeue_unlock(pq);
1107ebcddc72SAlan Cox 
1108b1fd102eSMark Johnston 	if (launder > 0 && pq == &vmd->vmd_pagequeues[PQ_UNSWAPPABLE]) {
1109b1fd102eSMark Johnston 		pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
1110b1fd102eSMark Johnston 		goto scan;
1111b1fd102eSMark Johnston 	}
1112b1fd102eSMark Johnston 
1113ebcddc72SAlan Cox 	/*
1114ebcddc72SAlan Cox 	 * Wakeup the sync daemon if we skipped a vnode in a writeable object
1115ebcddc72SAlan Cox 	 * and we didn't launder enough pages.
1116ebcddc72SAlan Cox 	 */
1117ebcddc72SAlan Cox 	if (vnodes_skipped > 0 && launder > 0)
1118ebcddc72SAlan Cox 		(void)speedup_syncer();
1119ebcddc72SAlan Cox 
1120ebcddc72SAlan Cox 	return (starting_target - launder);
1121ebcddc72SAlan Cox }
1122ebcddc72SAlan Cox 
1123ebcddc72SAlan Cox /*
1124ebcddc72SAlan Cox  * Compute the integer square root.
1125ebcddc72SAlan Cox  */
1126ebcddc72SAlan Cox static u_int
1127ebcddc72SAlan Cox isqrt(u_int num)
1128ebcddc72SAlan Cox {
1129ebcddc72SAlan Cox 	u_int bit, root, tmp;
1130ebcddc72SAlan Cox 
1131ebcddc72SAlan Cox 	bit = 1u << ((NBBY * sizeof(u_int)) - 2);
1132ebcddc72SAlan Cox 	while (bit > num)
1133ebcddc72SAlan Cox 		bit >>= 2;
1134ebcddc72SAlan Cox 	root = 0;
1135ebcddc72SAlan Cox 	while (bit != 0) {
1136ebcddc72SAlan Cox 		tmp = root + bit;
1137ebcddc72SAlan Cox 		root >>= 1;
1138ebcddc72SAlan Cox 		if (num >= tmp) {
1139ebcddc72SAlan Cox 			num -= tmp;
1140ebcddc72SAlan Cox 			root += bit;
1141ebcddc72SAlan Cox 		}
1142ebcddc72SAlan Cox 		bit >>= 2;
1143ebcddc72SAlan Cox 	}
1144ebcddc72SAlan Cox 	return (root);
1145ebcddc72SAlan Cox }
1146ebcddc72SAlan Cox 
1147ebcddc72SAlan Cox /*
1148ebcddc72SAlan Cox  * Perform the work of the laundry thread: periodically wake up and determine
1149ebcddc72SAlan Cox  * whether any pages need to be laundered.  If so, determine the number of pages
1150ebcddc72SAlan Cox  * that need to be laundered, and launder them.
1151ebcddc72SAlan Cox  */
1152ebcddc72SAlan Cox static void
1153ebcddc72SAlan Cox vm_pageout_laundry_worker(void *arg)
1154ebcddc72SAlan Cox {
1155ebcddc72SAlan Cox 	struct vm_domain *domain;
1156ebcddc72SAlan Cox 	struct vm_pagequeue *pq;
1157ebcddc72SAlan Cox 	uint64_t nclean, ndirty;
1158ebcddc72SAlan Cox 	u_int last_launder, wakeups;
1159ebcddc72SAlan Cox 	int domidx, last_target, launder, shortfall, shortfall_cycle, target;
1160ebcddc72SAlan Cox 	bool in_shortfall;
1161ebcddc72SAlan Cox 
1162ebcddc72SAlan Cox 	domidx = (uintptr_t)arg;
1163ebcddc72SAlan Cox 	domain = &vm_dom[domidx];
1164ebcddc72SAlan Cox 	pq = &domain->vmd_pagequeues[PQ_LAUNDRY];
1165ebcddc72SAlan Cox 	KASSERT(domain->vmd_segs != 0, ("domain without segments"));
1166ebcddc72SAlan Cox 	vm_pageout_init_marker(&domain->vmd_laundry_marker, PQ_LAUNDRY);
1167ebcddc72SAlan Cox 
1168ebcddc72SAlan Cox 	shortfall = 0;
1169ebcddc72SAlan Cox 	in_shortfall = false;
1170ebcddc72SAlan Cox 	shortfall_cycle = 0;
1171ebcddc72SAlan Cox 	target = 0;
1172ebcddc72SAlan Cox 	last_launder = 0;
1173ebcddc72SAlan Cox 
1174ebcddc72SAlan Cox 	/*
1175b1fd102eSMark Johnston 	 * Calls to these handlers are serialized by the swap syscall lock.
1176b1fd102eSMark Johnston 	 */
1177b1fd102eSMark Johnston 	(void)EVENTHANDLER_REGISTER(swapon, vm_pageout_swapon, domain,
1178b1fd102eSMark Johnston 	    EVENTHANDLER_PRI_ANY);
1179b1fd102eSMark Johnston 	(void)EVENTHANDLER_REGISTER(swapoff, vm_pageout_swapoff, domain,
1180b1fd102eSMark Johnston 	    EVENTHANDLER_PRI_ANY);
1181b1fd102eSMark Johnston 
1182b1fd102eSMark Johnston 	/*
1183ebcddc72SAlan Cox 	 * The pageout laundry worker is never done, so loop forever.
1184ebcddc72SAlan Cox 	 */
1185ebcddc72SAlan Cox 	for (;;) {
1186ebcddc72SAlan Cox 		KASSERT(target >= 0, ("negative target %d", target));
1187ebcddc72SAlan Cox 		KASSERT(shortfall_cycle >= 0,
1188ebcddc72SAlan Cox 		    ("negative cycle %d", shortfall_cycle));
1189ebcddc72SAlan Cox 		launder = 0;
1190*83c9dea1SGleb Smirnoff 		wakeups = VM_CNT_FETCH(v_pdwakeups);
1191ebcddc72SAlan Cox 
1192ebcddc72SAlan Cox 		/*
1193ebcddc72SAlan Cox 		 * First determine whether we need to launder pages to meet a
1194ebcddc72SAlan Cox 		 * shortage of free pages.
1195ebcddc72SAlan Cox 		 */
1196ebcddc72SAlan Cox 		if (shortfall > 0) {
1197ebcddc72SAlan Cox 			in_shortfall = true;
1198ebcddc72SAlan Cox 			shortfall_cycle = VM_LAUNDER_RATE / VM_INACT_SCAN_RATE;
1199ebcddc72SAlan Cox 			target = shortfall;
1200ebcddc72SAlan Cox 		} else if (!in_shortfall)
1201ebcddc72SAlan Cox 			goto trybackground;
1202ebcddc72SAlan Cox 		else if (shortfall_cycle == 0 || vm_laundry_target() <= 0) {
1203ebcddc72SAlan Cox 			/*
1204ebcddc72SAlan Cox 			 * We recently entered shortfall and began laundering
1205ebcddc72SAlan Cox 			 * pages.  If we have completed that laundering run
1206ebcddc72SAlan Cox 			 * (and we are no longer in shortfall) or we have met
1207ebcddc72SAlan Cox 			 * our laundry target through other activity, then we
1208ebcddc72SAlan Cox 			 * can stop laundering pages.
1209ebcddc72SAlan Cox 			 */
1210ebcddc72SAlan Cox 			in_shortfall = false;
1211ebcddc72SAlan Cox 			target = 0;
1212ebcddc72SAlan Cox 			goto trybackground;
1213ebcddc72SAlan Cox 		}
1214ebcddc72SAlan Cox 		last_launder = wakeups;
1215ebcddc72SAlan Cox 		launder = target / shortfall_cycle--;
1216ebcddc72SAlan Cox 		goto dolaundry;
1217ebcddc72SAlan Cox 
1218ebcddc72SAlan Cox 		/*
1219ebcddc72SAlan Cox 		 * There's no immediate need to launder any pages; see if we
1220ebcddc72SAlan Cox 		 * meet the conditions to perform background laundering:
1221ebcddc72SAlan Cox 		 *
1222ebcddc72SAlan Cox 		 * 1. The ratio of dirty to clean inactive pages exceeds the
1223ebcddc72SAlan Cox 		 *    background laundering threshold and the pagedaemon has
1224ebcddc72SAlan Cox 		 *    been woken up to reclaim pages since our last
1225ebcddc72SAlan Cox 		 *    laundering, or
1226ebcddc72SAlan Cox 		 * 2. we haven't yet reached the target of the current
1227ebcddc72SAlan Cox 		 *    background laundering run.
1228ebcddc72SAlan Cox 		 *
1229ebcddc72SAlan Cox 		 * The background laundering threshold is not a constant.
1230ebcddc72SAlan Cox 		 * Instead, it is a slowly growing function of the number of
1231ebcddc72SAlan Cox 		 * page daemon wakeups since the last laundering.  Thus, as the
1232ebcddc72SAlan Cox 		 * ratio of dirty to clean inactive pages grows, the amount of
1233ebcddc72SAlan Cox 		 * memory pressure required to trigger laundering decreases.
1234ebcddc72SAlan Cox 		 */
1235ebcddc72SAlan Cox trybackground:
1236ebcddc72SAlan Cox 		nclean = vm_cnt.v_inactive_count + vm_cnt.v_free_count;
1237ebcddc72SAlan Cox 		ndirty = vm_cnt.v_laundry_count;
1238ebcddc72SAlan Cox 		if (target == 0 && wakeups != last_launder &&
1239ebcddc72SAlan Cox 		    ndirty * isqrt(wakeups - last_launder) >= nclean) {
1240ebcddc72SAlan Cox 			target = vm_background_launder_target;
1241ebcddc72SAlan Cox 		}
1242ebcddc72SAlan Cox 
1243ebcddc72SAlan Cox 		/*
1244ebcddc72SAlan Cox 		 * We have a non-zero background laundering target.  If we've
1245ebcddc72SAlan Cox 		 * laundered up to our maximum without observing a page daemon
1246ebcddc72SAlan Cox 		 * wakeup, just stop.  This is a safety belt that ensures we
1247ebcddc72SAlan Cox 		 * don't launder an excessive amount if memory pressure is low
1248ebcddc72SAlan Cox 		 * and the ratio of dirty to clean pages is large.  Otherwise,
1249ebcddc72SAlan Cox 		 * proceed at the background laundering rate.
1250ebcddc72SAlan Cox 		 */
1251ebcddc72SAlan Cox 		if (target > 0) {
1252ebcddc72SAlan Cox 			if (wakeups != last_launder) {
1253ebcddc72SAlan Cox 				last_launder = wakeups;
1254ebcddc72SAlan Cox 				last_target = target;
1255ebcddc72SAlan Cox 			} else if (last_target - target >=
1256ebcddc72SAlan Cox 			    vm_background_launder_max * PAGE_SIZE / 1024) {
1257ebcddc72SAlan Cox 				target = 0;
1258ebcddc72SAlan Cox 			}
1259ebcddc72SAlan Cox 			launder = vm_background_launder_rate * PAGE_SIZE / 1024;
1260ebcddc72SAlan Cox 			launder /= VM_LAUNDER_RATE;
1261ebcddc72SAlan Cox 			if (launder > target)
1262ebcddc72SAlan Cox 				launder = target;
1263ebcddc72SAlan Cox 		}
1264ebcddc72SAlan Cox 
1265ebcddc72SAlan Cox dolaundry:
1266ebcddc72SAlan Cox 		if (launder > 0) {
1267ebcddc72SAlan Cox 			/*
1268ebcddc72SAlan Cox 			 * Because of I/O clustering, the number of laundered
1269ebcddc72SAlan Cox 			 * pages could exceed "target" by the maximum size of
1270ebcddc72SAlan Cox 			 * a cluster minus one.
1271ebcddc72SAlan Cox 			 */
1272ebcddc72SAlan Cox 			target -= min(vm_pageout_launder(domain, launder,
1273ebcddc72SAlan Cox 			    in_shortfall), target);
1274ebcddc72SAlan Cox 			pause("laundp", hz / VM_LAUNDER_RATE);
1275ebcddc72SAlan Cox 		}
1276ebcddc72SAlan Cox 
1277ebcddc72SAlan Cox 		/*
1278ebcddc72SAlan Cox 		 * If we're not currently laundering pages and the page daemon
1279ebcddc72SAlan Cox 		 * hasn't posted a new request, sleep until the page daemon
1280ebcddc72SAlan Cox 		 * kicks us.
1281ebcddc72SAlan Cox 		 */
1282ebcddc72SAlan Cox 		vm_pagequeue_lock(pq);
1283ebcddc72SAlan Cox 		if (target == 0 && vm_laundry_request == VM_LAUNDRY_IDLE)
1284ebcddc72SAlan Cox 			(void)mtx_sleep(&vm_laundry_request,
1285ebcddc72SAlan Cox 			    vm_pagequeue_lockptr(pq), PVM, "launds", 0);
1286ebcddc72SAlan Cox 
1287ebcddc72SAlan Cox 		/*
1288ebcddc72SAlan Cox 		 * If the pagedaemon has indicated that it's in shortfall, start
1289ebcddc72SAlan Cox 		 * a shortfall laundering unless we're already in the middle of
1290ebcddc72SAlan Cox 		 * one.  This may preempt a background laundering.
1291ebcddc72SAlan Cox 		 */
1292ebcddc72SAlan Cox 		if (vm_laundry_request == VM_LAUNDRY_SHORTFALL &&
1293ebcddc72SAlan Cox 		    (!in_shortfall || shortfall_cycle == 0)) {
1294ebcddc72SAlan Cox 			shortfall = vm_laundry_target() + vm_pageout_deficit;
1295ebcddc72SAlan Cox 			target = 0;
1296ebcddc72SAlan Cox 		} else
1297ebcddc72SAlan Cox 			shortfall = 0;
1298ebcddc72SAlan Cox 
1299ebcddc72SAlan Cox 		if (target == 0)
1300ebcddc72SAlan Cox 			vm_laundry_request = VM_LAUNDRY_IDLE;
1301ebcddc72SAlan Cox 		vm_pagequeue_unlock(pq);
1302ebcddc72SAlan Cox 	}
1303ebcddc72SAlan Cox }
1304ebcddc72SAlan Cox 
1305ebcddc72SAlan Cox /*
1306df8bae1dSRodney W. Grimes  *	vm_pageout_scan does the dirty work for the pageout daemon.
1307d9e23210SJeff Roberson  *
1308ebcddc72SAlan Cox  *	pass == 0: Update active LRU/deactivate pages
1309ebcddc72SAlan Cox  *	pass >= 1: Free inactive pages
1310e57dd910SAlan Cox  *
1311e57dd910SAlan Cox  * Returns true if pass was zero or enough pages were freed by the inactive
1312e57dd910SAlan Cox  * queue scan to meet the target.
1313df8bae1dSRodney W. Grimes  */
1314e57dd910SAlan Cox static bool
1315449c2e92SKonstantin Belousov vm_pageout_scan(struct vm_domain *vmd, int pass)
1316df8bae1dSRodney W. Grimes {
1317502ba6e4SJohn Dyson 	vm_page_t m, next;
13188d220203SAlan Cox 	struct vm_pagequeue *pq;
1319df8bae1dSRodney W. Grimes 	vm_object_t object;
132022cf98d1SAlan Cox 	long min_scan;
1321ebcddc72SAlan Cox 	int act_delta, addl_page_shortage, deficit, inactq_shortage, maxscan;
1322ebcddc72SAlan Cox 	int page_shortage, scan_tick, scanned, starting_page_shortage;
1323ebcddc72SAlan Cox 	boolean_t queue_locked;
13240d94caffSDavid Greenman 
1325df8bae1dSRodney W. Grimes 	/*
1326d9e23210SJeff Roberson 	 * If we need to reclaim memory ask kernel caches to return
1327c9612b2dSJeff Roberson 	 * some.  We rate limit to avoid thrashing.
1328d9e23210SJeff Roberson 	 */
1329c9612b2dSJeff Roberson 	if (vmd == &vm_dom[0] && pass > 0 &&
1330a6bf3a9eSRyan Stone 	    (time_uptime - lowmem_uptime) >= lowmem_period) {
1331d9e23210SJeff Roberson 		/*
1332855a310fSJeff Roberson 		 * Decrease registered cache sizes.
1333855a310fSJeff Roberson 		 */
133414a0d74eSSteven Hartland 		SDT_PROBE0(vm, , , vm__lowmem_scan);
13359b43bc27SAndriy Gapon 		EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_PAGES);
1336855a310fSJeff Roberson 		/*
1337d9e23210SJeff Roberson 		 * We do this explicitly after the caches have been
1338d9e23210SJeff Roberson 		 * drained above.
1339855a310fSJeff Roberson 		 */
1340855a310fSJeff Roberson 		uma_reclaim();
1341a6bf3a9eSRyan Stone 		lowmem_uptime = time_uptime;
1342d9e23210SJeff Roberson 	}
13435985940eSJohn Dyson 
1344311e34e2SKonstantin Belousov 	/*
134596240c89SEitan Adler 	 * The addl_page_shortage is the number of temporarily
1346311e34e2SKonstantin Belousov 	 * stuck pages in the inactive queue.  In other words, the
1347449c2e92SKonstantin Belousov 	 * number of pages from the inactive count that should be
1348311e34e2SKonstantin Belousov 	 * discounted in setting the target for the active queue scan.
1349311e34e2SKonstantin Belousov 	 */
13509099545aSAlan Cox 	addl_page_shortage = 0;
13519099545aSAlan Cox 
13521c7c3c6aSMatthew Dillon 	/*
1353e57dd910SAlan Cox 	 * Calculate the number of pages that we want to free.  This number
1354e57dd910SAlan Cox 	 * can be negative if many pages are freed between the wakeup call to
1355e57dd910SAlan Cox 	 * the page daemon and this calculation.
13561c7c3c6aSMatthew Dillon 	 */
135760196cdaSAlan Cox 	if (pass > 0) {
135860196cdaSAlan Cox 		deficit = atomic_readandclear_int(&vm_pageout_deficit);
13599099545aSAlan Cox 		page_shortage = vm_paging_target() + deficit;
136060196cdaSAlan Cox 	} else
136160196cdaSAlan Cox 		page_shortage = deficit = 0;
136276386c7eSKonstantin Belousov 	starting_page_shortage = page_shortage;
13631c7c3c6aSMatthew Dillon 
1364936524aaSMatthew Dillon 	/*
1365f095d1bbSAlan Cox 	 * Start scanning the inactive queue for pages that we can free.  The
1366f095d1bbSAlan Cox 	 * scan will stop when we reach the target or we have scanned the
1367f095d1bbSAlan Cox 	 * entire queue.  (Note that m->act_count is not used to make
1368f095d1bbSAlan Cox 	 * decisions for the inactive queue, only for the active queue.)
13698d220203SAlan Cox 	 */
1370449c2e92SKonstantin Belousov 	pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
1371449c2e92SKonstantin Belousov 	maxscan = pq->pq_cnt;
13728d220203SAlan Cox 	vm_pagequeue_lock(pq);
13733ac8f842SMark Johnston 	queue_locked = TRUE;
13748d220203SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl);
13751c7c3c6aSMatthew Dillon 	     m != NULL && maxscan-- > 0 && page_shortage > 0;
1376e929c00dSKirk McKusick 	     m = next) {
13778d220203SAlan Cox 		vm_pagequeue_assert_locked(pq);
13783ac8f842SMark Johnston 		KASSERT(queue_locked, ("unlocked inactive queue"));
1379ebcddc72SAlan Cox 		KASSERT(vm_page_inactive(m), ("Inactive queue %p", m));
1380df8bae1dSRodney W. Grimes 
1381*83c9dea1SGleb Smirnoff 		VM_CNT_INC(v_pdpages);
1382c325e866SKonstantin Belousov 		next = TAILQ_NEXT(m, plinks.q);
1383df8bae1dSRodney W. Grimes 
1384936524aaSMatthew Dillon 		/*
1385936524aaSMatthew Dillon 		 * skip marker pages
1386936524aaSMatthew Dillon 		 */
1387936524aaSMatthew Dillon 		if (m->flags & PG_MARKER)
1388936524aaSMatthew Dillon 			continue;
1389936524aaSMatthew Dillon 
13907900f95dSKonstantin Belousov 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
13917900f95dSKonstantin Belousov 		    ("Fictitious page %p cannot be in inactive queue", m));
13927900f95dSKonstantin Belousov 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
13937900f95dSKonstantin Belousov 		    ("Unmanaged page %p cannot be in inactive queue", m));
13947900f95dSKonstantin Belousov 
13958c616246SKonstantin Belousov 		/*
1396311e34e2SKonstantin Belousov 		 * The page or object lock acquisitions fail if the
1397311e34e2SKonstantin Belousov 		 * page was removed from the queue or moved to a
1398311e34e2SKonstantin Belousov 		 * different position within the queue.  In either
1399311e34e2SKonstantin Belousov 		 * case, addl_page_shortage should not be incremented.
14008c616246SKonstantin Belousov 		 */
1401a3aeedabSAlan Cox 		if (!vm_pageout_page_lock(m, &next))
1402a3aeedabSAlan Cox 			goto unlock_page;
1403a3aeedabSAlan Cox 		else if (m->hold_count != 0) {
1404a3aeedabSAlan Cox 			/*
1405a3aeedabSAlan Cox 			 * Held pages are essentially stuck in the
1406a3aeedabSAlan Cox 			 * queue.  So, they ought to be discounted
1407a3aeedabSAlan Cox 			 * from the inactive count.  See the
1408e57dd910SAlan Cox 			 * calculation of inactq_shortage before the
1409a3aeedabSAlan Cox 			 * loop over the active queue below.
1410a3aeedabSAlan Cox 			 */
1411a3aeedabSAlan Cox 			addl_page_shortage++;
1412a3aeedabSAlan Cox 			goto unlock_page;
1413df8bae1dSRodney W. Grimes 		}
14149ee2165fSAlan Cox 		object = m->object;
1415a3aeedabSAlan Cox 		if (!VM_OBJECT_TRYWLOCK(object)) {
1416a3aeedabSAlan Cox 			if (!vm_pageout_fallback_object_lock(m, &next))
1417a3aeedabSAlan Cox 				goto unlock_object;
1418a3aeedabSAlan Cox 			else if (m->hold_count != 0) {
1419b182ec9eSJohn Dyson 				addl_page_shortage++;
1420a3aeedabSAlan Cox 				goto unlock_object;
1421a3aeedabSAlan Cox 			}
1422a3aeedabSAlan Cox 		}
1423a3aeedabSAlan Cox 		if (vm_page_busied(m)) {
1424a3aeedabSAlan Cox 			/*
1425a3aeedabSAlan Cox 			 * Don't mess with busy pages.  Leave them at
1426a3aeedabSAlan Cox 			 * the front of the queue.  Most likely, they
1427a3aeedabSAlan Cox 			 * are being paged out and will leave the
1428a3aeedabSAlan Cox 			 * queue shortly after the scan finishes.  So,
1429a3aeedabSAlan Cox 			 * they ought to be discounted from the
1430a3aeedabSAlan Cox 			 * inactive count.
1431a3aeedabSAlan Cox 			 */
1432a3aeedabSAlan Cox 			addl_page_shortage++;
1433a3aeedabSAlan Cox unlock_object:
1434a3aeedabSAlan Cox 			VM_OBJECT_WUNLOCK(object);
1435a3aeedabSAlan Cox unlock_page:
1436a3aeedabSAlan Cox 			vm_page_unlock(m);
143726f9a767SRodney W. Grimes 			continue;
143826f9a767SRodney W. Grimes 		}
1439a3aeedabSAlan Cox 		KASSERT(m->hold_count == 0, ("Held page %p", m));
1440bd7e5f99SJohn Dyson 
14417e006499SJohn Dyson 		/*
1442ebcddc72SAlan Cox 		 * Dequeue the inactive page and unlock the inactive page
1443ebcddc72SAlan Cox 		 * queue, invalidating the 'next' pointer.  Dequeueing the
1444ebcddc72SAlan Cox 		 * page here avoids a later reacquisition (and release) of
1445ebcddc72SAlan Cox 		 * the inactive page queue lock when vm_page_activate(),
1446ebcddc72SAlan Cox 		 * vm_page_free(), or vm_page_launder() is called.  Use a
1447ebcddc72SAlan Cox 		 * marker to remember our place in the inactive queue.
144848cc2fc7SKonstantin Belousov 		 */
1449c325e866SKonstantin Belousov 		TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
1450ebcddc72SAlan Cox 		vm_page_dequeue_locked(m);
14518d220203SAlan Cox 		vm_pagequeue_unlock(pq);
14523ac8f842SMark Johnston 		queue_locked = FALSE;
145348cc2fc7SKonstantin Belousov 
145448cc2fc7SKonstantin Belousov 		/*
14558748f58cSKonstantin Belousov 		 * Invalid pages can be easily freed. They cannot be
14568748f58cSKonstantin Belousov 		 * mapped, vm_page_free() asserts this.
1457776f729cSKonstantin Belousov 		 */
14588748f58cSKonstantin Belousov 		if (m->valid == 0)
14598748f58cSKonstantin Belousov 			goto free_page;
1460776f729cSKonstantin Belousov 
1461776f729cSKonstantin Belousov 		/*
1462960810ccSAlan Cox 		 * If the page has been referenced and the object is not dead,
1463960810ccSAlan Cox 		 * reactivate or requeue the page depending on whether the
1464960810ccSAlan Cox 		 * object is mapped.
14657e006499SJohn Dyson 		 */
1466bb7858eaSJeff Roberson 		if ((m->aflags & PGA_REFERENCED) != 0) {
1467bb7858eaSJeff Roberson 			vm_page_aflag_clear(m, PGA_REFERENCED);
1468bb7858eaSJeff Roberson 			act_delta = 1;
146986fa2471SAlan Cox 		} else
147086fa2471SAlan Cox 			act_delta = 0;
1471bb7858eaSJeff Roberson 		if (object->ref_count != 0) {
1472bb7858eaSJeff Roberson 			act_delta += pmap_ts_referenced(m);
1473bb7858eaSJeff Roberson 		} else {
1474bb7858eaSJeff Roberson 			KASSERT(!pmap_page_is_mapped(m),
1475bb7858eaSJeff Roberson 			    ("vm_pageout_scan: page %p is mapped", m));
14762fe6e4d7SDavid Greenman 		}
1477bb7858eaSJeff Roberson 		if (act_delta != 0) {
147886fa2471SAlan Cox 			if (object->ref_count != 0) {
1479*83c9dea1SGleb Smirnoff 				VM_CNT_INC(v_reactivated);
148026f9a767SRodney W. Grimes 				vm_page_activate(m);
1481960810ccSAlan Cox 
1482960810ccSAlan Cox 				/*
1483960810ccSAlan Cox 				 * Increase the activation count if the page
1484960810ccSAlan Cox 				 * was referenced while in the inactive queue.
1485960810ccSAlan Cox 				 * This makes it less likely that the page will
1486960810ccSAlan Cox 				 * be returned prematurely to the inactive
1487960810ccSAlan Cox 				 * queue.
1488960810ccSAlan Cox  				 */
1489bb7858eaSJeff Roberson 				m->act_count += act_delta + ACT_ADVANCE;
1490960810ccSAlan Cox 				goto drop_page;
1491ebcddc72SAlan Cox 			} else if ((object->flags & OBJ_DEAD) == 0) {
1492ebcddc72SAlan Cox 				vm_pagequeue_lock(pq);
1493ebcddc72SAlan Cox 				queue_locked = TRUE;
1494ebcddc72SAlan Cox 				m->queue = PQ_INACTIVE;
1495ebcddc72SAlan Cox 				TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
1496ebcddc72SAlan Cox 				vm_pagequeue_cnt_inc(pq);
1497ebcddc72SAlan Cox 				goto drop_page;
1498ebcddc72SAlan Cox 			}
1499960810ccSAlan Cox 		}
150067bf6868SJohn Dyson 
15017e006499SJohn Dyson 		/*
15029fc4739dSAlan Cox 		 * If the page appears to be clean at the machine-independent
15039fc4739dSAlan Cox 		 * layer, then remove all of its mappings from the pmap in
1504a766ffd0SAlan Cox 		 * anticipation of freeing it.  If, however, any of the page's
1505a766ffd0SAlan Cox 		 * mappings allow write access, then the page may still be
1506a766ffd0SAlan Cox 		 * modified until the last of those mappings are removed.
15077e006499SJohn Dyson 		 */
1508aa044135SAlan Cox 		if (object->ref_count != 0) {
15099fc4739dSAlan Cox 			vm_page_test_dirty(m);
1510aa044135SAlan Cox 			if (m->dirty == 0)
1511b78ddb0bSAlan Cox 				pmap_remove_all(m);
1512aa044135SAlan Cox 		}
1513dcbcd518SBruce Evans 
15146989c456SAlan Cox 		/*
1515ebcddc72SAlan Cox 		 * Clean pages can be freed, but dirty pages must be sent back
1516ebcddc72SAlan Cox 		 * to the laundry, unless they belong to a dead object.
1517ebcddc72SAlan Cox 		 * Requeueing dirty pages from dead objects is pointless, as
1518ebcddc72SAlan Cox 		 * they are being paged out and freed by the thread that
1519ebcddc72SAlan Cox 		 * destroyed the object.
15206989c456SAlan Cox 		 */
1521ebcddc72SAlan Cox 		if (m->dirty == 0) {
15228748f58cSKonstantin Belousov free_page:
152378afdce6SAlan Cox 			vm_page_free(m);
1524*83c9dea1SGleb Smirnoff 			VM_CNT_INC(v_dfree);
15251c7c3c6aSMatthew Dillon 			--page_shortage;
1526ebcddc72SAlan Cox 		} else if ((object->flags & OBJ_DEAD) == 0)
1527ebcddc72SAlan Cox 			vm_page_launder(m);
1528776f729cSKonstantin Belousov drop_page:
152948cc2fc7SKonstantin Belousov 		vm_page_unlock(m);
153089f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
15313ac8f842SMark Johnston 		if (!queue_locked) {
15328d220203SAlan Cox 			vm_pagequeue_lock(pq);
15333ac8f842SMark Johnston 			queue_locked = TRUE;
15346989c456SAlan Cox 		}
1535c325e866SKonstantin Belousov 		next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1536c325e866SKonstantin Belousov 		TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
15370d94caffSDavid Greenman 	}
15388d220203SAlan Cox 	vm_pagequeue_unlock(pq);
153926f9a767SRodney W. Grimes 
1540ebcddc72SAlan Cox 	/*
1541ebcddc72SAlan Cox 	 * Wake up the laundry thread so that it can perform any needed
1542ebcddc72SAlan Cox 	 * laundering.  If we didn't meet our target, we're in shortfall and
1543b1fd102eSMark Johnston 	 * need to launder more aggressively.  If PQ_LAUNDRY is empty and no
1544b1fd102eSMark Johnston 	 * swap devices are configured, the laundry thread has no work to do, so
1545b1fd102eSMark Johnston 	 * don't bother waking it up.
1546ebcddc72SAlan Cox 	 */
1547ebcddc72SAlan Cox 	if (vm_laundry_request == VM_LAUNDRY_IDLE &&
1548ebcddc72SAlan Cox 	    starting_page_shortage > 0) {
1549ebcddc72SAlan Cox 		pq = &vm_dom[0].vmd_pagequeues[PQ_LAUNDRY];
1550ebcddc72SAlan Cox 		vm_pagequeue_lock(pq);
1551b1fd102eSMark Johnston 		if (pq->pq_cnt > 0 || atomic_load_acq_int(&swapdev_enabled)) {
1552ebcddc72SAlan Cox 			if (page_shortage > 0) {
1553ebcddc72SAlan Cox 				vm_laundry_request = VM_LAUNDRY_SHORTFALL;
1554*83c9dea1SGleb Smirnoff 				VM_CNT_INC(v_pdshortfalls);
1555ebcddc72SAlan Cox 			} else if (vm_laundry_request != VM_LAUNDRY_SHORTFALL)
1556ebcddc72SAlan Cox 				vm_laundry_request = VM_LAUNDRY_BACKGROUND;
1557ebcddc72SAlan Cox 			wakeup(&vm_laundry_request);
1558b1fd102eSMark Johnston 		}
1559ebcddc72SAlan Cox 		vm_pagequeue_unlock(pq);
1560ebcddc72SAlan Cox 	}
1561ebcddc72SAlan Cox 
15629452b5edSAlan Cox #if !defined(NO_SWAPPING)
15639452b5edSAlan Cox 	/*
1564f095d1bbSAlan Cox 	 * Wakeup the swapout daemon if we didn't free the targeted number of
1565f095d1bbSAlan Cox 	 * pages.
15669452b5edSAlan Cox 	 */
15679452b5edSAlan Cox 	if (vm_swap_enabled && page_shortage > 0)
15689452b5edSAlan Cox 		vm_req_vmdaemon(VM_SWAP_NORMAL);
15699452b5edSAlan Cox #endif
15709452b5edSAlan Cox 
15719452b5edSAlan Cox 	/*
157276386c7eSKonstantin Belousov 	 * If the inactive queue scan fails repeatedly to meet its
157376386c7eSKonstantin Belousov 	 * target, kill the largest process.
157476386c7eSKonstantin Belousov 	 */
157576386c7eSKonstantin Belousov 	vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
157676386c7eSKonstantin Belousov 
157776386c7eSKonstantin Belousov 	/*
1578936524aaSMatthew Dillon 	 * Compute the number of pages we want to try to move from the
1579ebcddc72SAlan Cox 	 * active queue to either the inactive or laundry queue.
1580ebcddc72SAlan Cox 	 *
1581ebcddc72SAlan Cox 	 * When scanning active pages, we make clean pages count more heavily
1582ebcddc72SAlan Cox 	 * towards the page shortage than dirty pages.  This is because dirty
1583ebcddc72SAlan Cox 	 * pages must be laundered before they can be reused and thus have less
1584ebcddc72SAlan Cox 	 * utility when attempting to quickly alleviate a shortage.  However,
1585ebcddc72SAlan Cox 	 * this weighting also causes the scan to deactivate dirty pages more
1586ebcddc72SAlan Cox 	 * more aggressively, improving the effectiveness of clustering and
1587ebcddc72SAlan Cox 	 * ensuring that they can eventually be reused.
15881c7c3c6aSMatthew Dillon 	 */
1589ebcddc72SAlan Cox 	inactq_shortage = vm_cnt.v_inactive_target - (vm_cnt.v_inactive_count +
1590ebcddc72SAlan Cox 	    vm_cnt.v_laundry_count / act_scan_laundry_weight) +
15919099545aSAlan Cox 	    vm_paging_target() + deficit + addl_page_shortage;
1592ebcddc72SAlan Cox 	page_shortage *= act_scan_laundry_weight;
15939099545aSAlan Cox 
1594114f62c6SJeff Roberson 	pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1595114f62c6SJeff Roberson 	vm_pagequeue_lock(pq);
15969099545aSAlan Cox 	maxscan = pq->pq_cnt;
15979099545aSAlan Cox 
1598d9e23210SJeff Roberson 	/*
1599d9e23210SJeff Roberson 	 * If we're just idle polling attempt to visit every
1600d9e23210SJeff Roberson 	 * active page within 'update_period' seconds.
1601d9e23210SJeff Roberson 	 */
160222cf98d1SAlan Cox 	scan_tick = ticks;
160322cf98d1SAlan Cox 	if (vm_pageout_update_period != 0) {
160422cf98d1SAlan Cox 		min_scan = pq->pq_cnt;
160522cf98d1SAlan Cox 		min_scan *= scan_tick - vmd->vmd_last_active_scan;
160622cf98d1SAlan Cox 		min_scan /= hz * vm_pageout_update_period;
160722cf98d1SAlan Cox 	} else
160822cf98d1SAlan Cox 		min_scan = 0;
1609e57dd910SAlan Cox 	if (min_scan > 0 || (inactq_shortage > 0 && maxscan > 0))
161022cf98d1SAlan Cox 		vmd->vmd_last_active_scan = scan_tick;
16111c7c3c6aSMatthew Dillon 
16121c7c3c6aSMatthew Dillon 	/*
161322cf98d1SAlan Cox 	 * Scan the active queue for pages that can be deactivated.  Update
161422cf98d1SAlan Cox 	 * the per-page activity counter and use it to identify deactivation
161579144408SAlan Cox 	 * candidates.  Held pages may be deactivated.
16161c7c3c6aSMatthew Dillon 	 */
161722cf98d1SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
1618e57dd910SAlan Cox 	    min_scan || (inactq_shortage > 0 && scanned < maxscan)); m = next,
161922cf98d1SAlan Cox 	    scanned++) {
16209cf51988SAlan Cox 		KASSERT(m->queue == PQ_ACTIVE,
1621d3c09dd7SAlan Cox 		    ("vm_pageout_scan: page %p isn't active", m));
1622c325e866SKonstantin Belousov 		next = TAILQ_NEXT(m, plinks.q);
162322cf98d1SAlan Cox 		if ((m->flags & PG_MARKER) != 0)
16248dbca793STor Egge 			continue;
16257900f95dSKonstantin Belousov 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
16267900f95dSKonstantin Belousov 		    ("Fictitious page %p cannot be in active queue", m));
16277900f95dSKonstantin Belousov 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
16287900f95dSKonstantin Belousov 		    ("Unmanaged page %p cannot be in active queue", m));
16299ee2165fSAlan Cox 		if (!vm_pageout_page_lock(m, &next)) {
16308c616246SKonstantin Belousov 			vm_page_unlock(m);
16312965a453SKip Macy 			continue;
16322965a453SKip Macy 		}
1633b18bfc3dSJohn Dyson 
1634b18bfc3dSJohn Dyson 		/*
163579144408SAlan Cox 		 * The count for page daemon pages is updated after checking
163679144408SAlan Cox 		 * the page for eligibility.
1637b18bfc3dSJohn Dyson 		 */
1638*83c9dea1SGleb Smirnoff 		VM_CNT_INC(v_pdpages);
1639ef743ce6SJohn Dyson 
16407e006499SJohn Dyson 		/*
16417e006499SJohn Dyson 		 * Check to see "how much" the page has been used.
16427e006499SJohn Dyson 		 */
164386fa2471SAlan Cox 		if ((m->aflags & PGA_REFERENCED) != 0) {
1644bb7858eaSJeff Roberson 			vm_page_aflag_clear(m, PGA_REFERENCED);
164586fa2471SAlan Cox 			act_delta = 1;
164686fa2471SAlan Cox 		} else
164786fa2471SAlan Cox 			act_delta = 0;
164886fa2471SAlan Cox 
1649274132acSJeff Roberson 		/*
165079144408SAlan Cox 		 * Perform an unsynchronized object ref count check.  While
165179144408SAlan Cox 		 * the page lock ensures that the page is not reallocated to
165279144408SAlan Cox 		 * another object, in particular, one with unmanaged mappings
165379144408SAlan Cox 		 * that cannot support pmap_ts_referenced(), two races are,
165479144408SAlan Cox 		 * nonetheless, possible:
165579144408SAlan Cox 		 * 1) The count was transitioning to zero, but we saw a non-
165679144408SAlan Cox 		 *    zero value.  pmap_ts_referenced() will return zero
165779144408SAlan Cox 		 *    because the page is not mapped.
165879144408SAlan Cox 		 * 2) The count was transitioning to one, but we saw zero.
165979144408SAlan Cox 		 *    This race delays the detection of a new reference.  At
166079144408SAlan Cox 		 *    worst, we will deactivate and reactivate the page.
1661274132acSJeff Roberson 		 */
1662274132acSJeff Roberson 		if (m->object->ref_count != 0)
1663bb7858eaSJeff Roberson 			act_delta += pmap_ts_referenced(m);
1664bb7858eaSJeff Roberson 
1665bb7858eaSJeff Roberson 		/*
1666bb7858eaSJeff Roberson 		 * Advance or decay the act_count based on recent usage.
1667bb7858eaSJeff Roberson 		 */
166886fa2471SAlan Cox 		if (act_delta != 0) {
1669bb7858eaSJeff Roberson 			m->act_count += ACT_ADVANCE + act_delta;
167038efa82bSJohn Dyson 			if (m->act_count > ACT_MAX)
167138efa82bSJohn Dyson 				m->act_count = ACT_MAX;
167286fa2471SAlan Cox 		} else
167338efa82bSJohn Dyson 			m->act_count -= min(m->act_count, ACT_DECLINE);
1674bb7858eaSJeff Roberson 
1675bb7858eaSJeff Roberson 		/*
1676ebcddc72SAlan Cox 		 * Move this page to the tail of the active, inactive or laundry
1677bb7858eaSJeff Roberson 		 * queue depending on usage.
1678bb7858eaSJeff Roberson 		 */
167986fa2471SAlan Cox 		if (m->act_count == 0) {
16808d220203SAlan Cox 			/* Dequeue to avoid later lock recursion. */
16818d220203SAlan Cox 			vm_page_dequeue_locked(m);
1682ebcddc72SAlan Cox 
1683ebcddc72SAlan Cox 			/*
1684ebcddc72SAlan Cox 			 * When not short for inactive pages, let dirty pages go
1685ebcddc72SAlan Cox 			 * through the inactive queue before moving to the
1686ebcddc72SAlan Cox 			 * laundry queues.  This gives them some extra time to
1687ebcddc72SAlan Cox 			 * be reactivated, potentially avoiding an expensive
1688ebcddc72SAlan Cox 			 * pageout.  During a page shortage, the inactive queue
1689ebcddc72SAlan Cox 			 * is necessarily small, so we may move dirty pages
1690ebcddc72SAlan Cox 			 * directly to the laundry queue.
1691ebcddc72SAlan Cox 			 */
1692ebcddc72SAlan Cox 			if (inactq_shortage <= 0)
1693d4a272dbSJohn Dyson 				vm_page_deactivate(m);
1694ebcddc72SAlan Cox 			else {
1695ebcddc72SAlan Cox 				/*
1696ebcddc72SAlan Cox 				 * Calling vm_page_test_dirty() here would
1697ebcddc72SAlan Cox 				 * require acquisition of the object's write
1698ebcddc72SAlan Cox 				 * lock.  However, during a page shortage,
1699ebcddc72SAlan Cox 				 * directing dirty pages into the laundry
1700ebcddc72SAlan Cox 				 * queue is only an optimization and not a
1701ebcddc72SAlan Cox 				 * requirement.  Therefore, we simply rely on
1702ebcddc72SAlan Cox 				 * the opportunistic updates to the page's
1703ebcddc72SAlan Cox 				 * dirty field by the pmap.
1704ebcddc72SAlan Cox 				 */
1705ebcddc72SAlan Cox 				if (m->dirty == 0) {
1706ebcddc72SAlan Cox 					vm_page_deactivate(m);
1707ebcddc72SAlan Cox 					inactq_shortage -=
1708ebcddc72SAlan Cox 					    act_scan_laundry_weight;
1709ebcddc72SAlan Cox 				} else {
1710ebcddc72SAlan Cox 					vm_page_launder(m);
1711e57dd910SAlan Cox 					inactq_shortage--;
1712ebcddc72SAlan Cox 				}
1713ebcddc72SAlan Cox 			}
17148d220203SAlan Cox 		} else
17158d220203SAlan Cox 			vm_page_requeue_locked(m);
17162965a453SKip Macy 		vm_page_unlock(m);
171726f9a767SRodney W. Grimes 	}
17188d220203SAlan Cox 	vm_pagequeue_unlock(pq);
1719ceb0cf87SJohn Dyson #if !defined(NO_SWAPPING)
1720ceb0cf87SJohn Dyson 	/*
172187ff568cSAlan Cox 	 * Idle process swapout -- run once per second when we are reclaiming
172287ff568cSAlan Cox 	 * pages.
1723ceb0cf87SJohn Dyson 	 */
172487ff568cSAlan Cox 	if (vm_swap_idle_enabled && pass > 0) {
1725ceb0cf87SJohn Dyson 		static long lsec;
1726227ee8a1SPoul-Henning Kamp 		if (time_second != lsec) {
172797824da3SAlan Cox 			vm_req_vmdaemon(VM_SWAP_IDLE);
1728227ee8a1SPoul-Henning Kamp 			lsec = time_second;
1729ceb0cf87SJohn Dyson 		}
1730ceb0cf87SJohn Dyson 	}
1731ceb0cf87SJohn Dyson #endif
1732e57dd910SAlan Cox 	return (page_shortage <= 0);
17332025d69bSKonstantin Belousov }
17342025d69bSKonstantin Belousov 
1735449c2e92SKonstantin Belousov static int vm_pageout_oom_vote;
1736449c2e92SKonstantin Belousov 
1737449c2e92SKonstantin Belousov /*
1738449c2e92SKonstantin Belousov  * The pagedaemon threads randlomly select one to perform the
1739449c2e92SKonstantin Belousov  * OOM.  Trying to kill processes before all pagedaemons
1740449c2e92SKonstantin Belousov  * failed to reach free target is premature.
1741449c2e92SKonstantin Belousov  */
1742449c2e92SKonstantin Belousov static void
174376386c7eSKonstantin Belousov vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
174476386c7eSKonstantin Belousov     int starting_page_shortage)
1745449c2e92SKonstantin Belousov {
1746449c2e92SKonstantin Belousov 	int old_vote;
1747449c2e92SKonstantin Belousov 
174876386c7eSKonstantin Belousov 	if (starting_page_shortage <= 0 || starting_page_shortage !=
174976386c7eSKonstantin Belousov 	    page_shortage)
175076386c7eSKonstantin Belousov 		vmd->vmd_oom_seq = 0;
175176386c7eSKonstantin Belousov 	else
175276386c7eSKonstantin Belousov 		vmd->vmd_oom_seq++;
175376386c7eSKonstantin Belousov 	if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1754449c2e92SKonstantin Belousov 		if (vmd->vmd_oom) {
1755449c2e92SKonstantin Belousov 			vmd->vmd_oom = FALSE;
1756449c2e92SKonstantin Belousov 			atomic_subtract_int(&vm_pageout_oom_vote, 1);
1757449c2e92SKonstantin Belousov 		}
1758449c2e92SKonstantin Belousov 		return;
1759449c2e92SKonstantin Belousov 	}
1760449c2e92SKonstantin Belousov 
176176386c7eSKonstantin Belousov 	/*
176276386c7eSKonstantin Belousov 	 * Do not follow the call sequence until OOM condition is
176376386c7eSKonstantin Belousov 	 * cleared.
176476386c7eSKonstantin Belousov 	 */
176576386c7eSKonstantin Belousov 	vmd->vmd_oom_seq = 0;
176676386c7eSKonstantin Belousov 
1767449c2e92SKonstantin Belousov 	if (vmd->vmd_oom)
1768449c2e92SKonstantin Belousov 		return;
1769449c2e92SKonstantin Belousov 
1770449c2e92SKonstantin Belousov 	vmd->vmd_oom = TRUE;
1771449c2e92SKonstantin Belousov 	old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1772449c2e92SKonstantin Belousov 	if (old_vote != vm_ndomains - 1)
1773449c2e92SKonstantin Belousov 		return;
1774449c2e92SKonstantin Belousov 
1775449c2e92SKonstantin Belousov 	/*
1776449c2e92SKonstantin Belousov 	 * The current pagedaemon thread is the last in the quorum to
1777449c2e92SKonstantin Belousov 	 * start OOM.  Initiate the selection and signaling of the
1778449c2e92SKonstantin Belousov 	 * victim.
1779449c2e92SKonstantin Belousov 	 */
1780449c2e92SKonstantin Belousov 	vm_pageout_oom(VM_OOM_MEM);
1781449c2e92SKonstantin Belousov 
1782449c2e92SKonstantin Belousov 	/*
1783449c2e92SKonstantin Belousov 	 * After one round of OOM terror, recall our vote.  On the
1784449c2e92SKonstantin Belousov 	 * next pass, current pagedaemon would vote again if the low
1785449c2e92SKonstantin Belousov 	 * memory condition is still there, due to vmd_oom being
1786449c2e92SKonstantin Belousov 	 * false.
1787449c2e92SKonstantin Belousov 	 */
1788449c2e92SKonstantin Belousov 	vmd->vmd_oom = FALSE;
1789449c2e92SKonstantin Belousov 	atomic_subtract_int(&vm_pageout_oom_vote, 1);
1790449c2e92SKonstantin Belousov }
17912025d69bSKonstantin Belousov 
17923949873fSKonstantin Belousov /*
17933949873fSKonstantin Belousov  * The OOM killer is the page daemon's action of last resort when
17943949873fSKonstantin Belousov  * memory allocation requests have been stalled for a prolonged period
17953949873fSKonstantin Belousov  * of time because it cannot reclaim memory.  This function computes
17963949873fSKonstantin Belousov  * the approximate number of physical pages that could be reclaimed if
17973949873fSKonstantin Belousov  * the specified address space is destroyed.
17983949873fSKonstantin Belousov  *
17993949873fSKonstantin Belousov  * Private, anonymous memory owned by the address space is the
18003949873fSKonstantin Belousov  * principal resource that we expect to recover after an OOM kill.
18013949873fSKonstantin Belousov  * Since the physical pages mapped by the address space's COW entries
18023949873fSKonstantin Belousov  * are typically shared pages, they are unlikely to be released and so
18033949873fSKonstantin Belousov  * they are not counted.
18043949873fSKonstantin Belousov  *
18053949873fSKonstantin Belousov  * To get to the point where the page daemon runs the OOM killer, its
18063949873fSKonstantin Belousov  * efforts to write-back vnode-backed pages may have stalled.  This
18073949873fSKonstantin Belousov  * could be caused by a memory allocation deadlock in the write path
18083949873fSKonstantin Belousov  * that might be resolved by an OOM kill.  Therefore, physical pages
18093949873fSKonstantin Belousov  * belonging to vnode-backed objects are counted, because they might
18103949873fSKonstantin Belousov  * be freed without being written out first if the address space holds
18113949873fSKonstantin Belousov  * the last reference to an unlinked vnode.
18123949873fSKonstantin Belousov  *
18133949873fSKonstantin Belousov  * Similarly, physical pages belonging to OBJT_PHYS objects are
18143949873fSKonstantin Belousov  * counted because the address space might hold the last reference to
18153949873fSKonstantin Belousov  * the object.
18163949873fSKonstantin Belousov  */
18173949873fSKonstantin Belousov static long
18183949873fSKonstantin Belousov vm_pageout_oom_pagecount(struct vmspace *vmspace)
18193949873fSKonstantin Belousov {
18203949873fSKonstantin Belousov 	vm_map_t map;
18213949873fSKonstantin Belousov 	vm_map_entry_t entry;
18223949873fSKonstantin Belousov 	vm_object_t obj;
18233949873fSKonstantin Belousov 	long res;
18243949873fSKonstantin Belousov 
18253949873fSKonstantin Belousov 	map = &vmspace->vm_map;
18263949873fSKonstantin Belousov 	KASSERT(!map->system_map, ("system map"));
18273949873fSKonstantin Belousov 	sx_assert(&map->lock, SA_LOCKED);
18283949873fSKonstantin Belousov 	res = 0;
18293949873fSKonstantin Belousov 	for (entry = map->header.next; entry != &map->header;
18303949873fSKonstantin Belousov 	    entry = entry->next) {
18313949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
18323949873fSKonstantin Belousov 			continue;
18333949873fSKonstantin Belousov 		obj = entry->object.vm_object;
18343949873fSKonstantin Belousov 		if (obj == NULL)
18353949873fSKonstantin Belousov 			continue;
18363949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
18373949873fSKonstantin Belousov 		    obj->ref_count != 1)
18383949873fSKonstantin Belousov 			continue;
18393949873fSKonstantin Belousov 		switch (obj->type) {
18403949873fSKonstantin Belousov 		case OBJT_DEFAULT:
18413949873fSKonstantin Belousov 		case OBJT_SWAP:
18423949873fSKonstantin Belousov 		case OBJT_PHYS:
18433949873fSKonstantin Belousov 		case OBJT_VNODE:
18443949873fSKonstantin Belousov 			res += obj->resident_page_count;
18453949873fSKonstantin Belousov 			break;
18463949873fSKonstantin Belousov 		}
18473949873fSKonstantin Belousov 	}
18483949873fSKonstantin Belousov 	return (res);
18493949873fSKonstantin Belousov }
18503949873fSKonstantin Belousov 
18512025d69bSKonstantin Belousov void
18522025d69bSKonstantin Belousov vm_pageout_oom(int shortage)
18532025d69bSKonstantin Belousov {
18542025d69bSKonstantin Belousov 	struct proc *p, *bigproc;
18552025d69bSKonstantin Belousov 	vm_offset_t size, bigsize;
18562025d69bSKonstantin Belousov 	struct thread *td;
18576bed074cSKonstantin Belousov 	struct vmspace *vm;
18582025d69bSKonstantin Belousov 
18592025d69bSKonstantin Belousov 	/*
18601c58e4e5SJohn Baldwin 	 * We keep the process bigproc locked once we find it to keep anyone
18611c58e4e5SJohn Baldwin 	 * from messing with it; however, there is a possibility of
186228323addSBryan Drewery 	 * deadlock if process B is bigproc and one of its child processes
18631c58e4e5SJohn Baldwin 	 * attempts to propagate a signal to B while we are waiting for A's
18641c58e4e5SJohn Baldwin 	 * lock while walking this list.  To avoid this, we don't block on
18651c58e4e5SJohn Baldwin 	 * the process lock but just skip a process if it is already locked.
18665663e6deSDavid Greenman 	 */
18675663e6deSDavid Greenman 	bigproc = NULL;
18685663e6deSDavid Greenman 	bigsize = 0;
18691005a129SJohn Baldwin 	sx_slock(&allproc_lock);
1870e602ba25SJulian Elischer 	FOREACH_PROC_IN_SYSTEM(p) {
1871e602ba25SJulian Elischer 		int breakout;
1872dcbcd518SBruce Evans 
187371943c3dSKonstantin Belousov 		PROC_LOCK(p);
187471943c3dSKonstantin Belousov 
18751c58e4e5SJohn Baldwin 		/*
18763f1c4c4fSKonstantin Belousov 		 * If this is a system, protected or killed process, skip it.
18775663e6deSDavid Greenman 		 */
187871943c3dSKonstantin Belousov 		if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
187971943c3dSKonstantin Belousov 		    P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
188071943c3dSKonstantin Belousov 		    p->p_pid == 1 || P_KILLED(p) ||
188171943c3dSKonstantin Belousov 		    (p->p_pid < 48 && swap_pager_avail != 0)) {
18828606d880SJohn Baldwin 			PROC_UNLOCK(p);
18835663e6deSDavid Greenman 			continue;
18845663e6deSDavid Greenman 		}
18855663e6deSDavid Greenman 		/*
1886dcbcd518SBruce Evans 		 * If the process is in a non-running type state,
1887e602ba25SJulian Elischer 		 * don't touch it.  Check all the threads individually.
18885663e6deSDavid Greenman 		 */
1889e602ba25SJulian Elischer 		breakout = 0;
1890e602ba25SJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td) {
1891982d11f8SJeff Roberson 			thread_lock(td);
189271fad9fdSJulian Elischer 			if (!TD_ON_RUNQ(td) &&
189371fad9fdSJulian Elischer 			    !TD_IS_RUNNING(td) &&
1894f497cda2SEdward Tomasz Napierala 			    !TD_IS_SLEEPING(td) &&
1895b98acc0aSKonstantin Belousov 			    !TD_IS_SUSPENDED(td) &&
1896b98acc0aSKonstantin Belousov 			    !TD_IS_SWAPPED(td)) {
1897982d11f8SJeff Roberson 				thread_unlock(td);
1898e602ba25SJulian Elischer 				breakout = 1;
1899e602ba25SJulian Elischer 				break;
1900e602ba25SJulian Elischer 			}
1901982d11f8SJeff Roberson 			thread_unlock(td);
1902e602ba25SJulian Elischer 		}
1903e602ba25SJulian Elischer 		if (breakout) {
19041c58e4e5SJohn Baldwin 			PROC_UNLOCK(p);
19055663e6deSDavid Greenman 			continue;
19065663e6deSDavid Greenman 		}
19075663e6deSDavid Greenman 		/*
19085663e6deSDavid Greenman 		 * get the process size
19095663e6deSDavid Greenman 		 */
19106bed074cSKonstantin Belousov 		vm = vmspace_acquire_ref(p);
19116bed074cSKonstantin Belousov 		if (vm == NULL) {
19126bed074cSKonstantin Belousov 			PROC_UNLOCK(p);
19136bed074cSKonstantin Belousov 			continue;
19146bed074cSKonstantin Belousov 		}
191595e2409aSKonstantin Belousov 		_PHOLD_LITE(p);
191672d97679SDavid Schultz 		PROC_UNLOCK(p);
191795e2409aSKonstantin Belousov 		sx_sunlock(&allproc_lock);
191895e2409aSKonstantin Belousov 		if (!vm_map_trylock_read(&vm->vm_map)) {
191971943c3dSKonstantin Belousov 			vmspace_free(vm);
192095e2409aSKonstantin Belousov 			sx_slock(&allproc_lock);
192195e2409aSKonstantin Belousov 			PRELE(p);
192272d97679SDavid Schultz 			continue;
192372d97679SDavid Schultz 		}
19247981aa24SKonstantin Belousov 		size = vmspace_swap_count(vm);
19252025d69bSKonstantin Belousov 		if (shortage == VM_OOM_MEM)
19263949873fSKonstantin Belousov 			size += vm_pageout_oom_pagecount(vm);
19273949873fSKonstantin Belousov 		vm_map_unlock_read(&vm->vm_map);
19286bed074cSKonstantin Belousov 		vmspace_free(vm);
192995e2409aSKonstantin Belousov 		sx_slock(&allproc_lock);
19303949873fSKonstantin Belousov 
19315663e6deSDavid Greenman 		/*
19323949873fSKonstantin Belousov 		 * If this process is bigger than the biggest one,
19335663e6deSDavid Greenman 		 * remember it.
19345663e6deSDavid Greenman 		 */
19355663e6deSDavid Greenman 		if (size > bigsize) {
19361c58e4e5SJohn Baldwin 			if (bigproc != NULL)
193771943c3dSKonstantin Belousov 				PRELE(bigproc);
19385663e6deSDavid Greenman 			bigproc = p;
19395663e6deSDavid Greenman 			bigsize = size;
194071943c3dSKonstantin Belousov 		} else {
194171943c3dSKonstantin Belousov 			PRELE(p);
194271943c3dSKonstantin Belousov 		}
19435663e6deSDavid Greenman 	}
19441005a129SJohn Baldwin 	sx_sunlock(&allproc_lock);
19455663e6deSDavid Greenman 	if (bigproc != NULL) {
19468311a2b8SWill Andrews 		if (vm_panic_on_oom != 0)
19478311a2b8SWill Andrews 			panic("out of swap space");
194871943c3dSKonstantin Belousov 		PROC_LOCK(bigproc);
1949729b1e51SDavid Greenman 		killproc(bigproc, "out of swap space");
1950fa885116SJulian Elischer 		sched_nice(bigproc, PRIO_MIN);
195171943c3dSKonstantin Belousov 		_PRELE(bigproc);
19521c58e4e5SJohn Baldwin 		PROC_UNLOCK(bigproc);
195344f1c916SBryan Drewery 		wakeup(&vm_cnt.v_free_count);
19545663e6deSDavid Greenman 	}
19555663e6deSDavid Greenman }
195626f9a767SRodney W. Grimes 
1957449c2e92SKonstantin Belousov static void
1958449c2e92SKonstantin Belousov vm_pageout_worker(void *arg)
1959449c2e92SKonstantin Belousov {
1960449c2e92SKonstantin Belousov 	struct vm_domain *domain;
196170cf3cedSAlan Cox 	int domidx, pass;
1962e57dd910SAlan Cox 	bool target_met;
1963449c2e92SKonstantin Belousov 
1964449c2e92SKonstantin Belousov 	domidx = (uintptr_t)arg;
1965449c2e92SKonstantin Belousov 	domain = &vm_dom[domidx];
196670cf3cedSAlan Cox 	pass = 0;
1967e57dd910SAlan Cox 	target_met = true;
1968449c2e92SKonstantin Belousov 
1969449c2e92SKonstantin Belousov 	/*
1970949c9186SKonstantin Belousov 	 * XXXKIB It could be useful to bind pageout daemon threads to
1971949c9186SKonstantin Belousov 	 * the cores belonging to the domain, from which vm_page_array
1972949c9186SKonstantin Belousov 	 * is allocated.
1973449c2e92SKonstantin Belousov 	 */
1974449c2e92SKonstantin Belousov 
1975449c2e92SKonstantin Belousov 	KASSERT(domain->vmd_segs != 0, ("domain without segments"));
197622cf98d1SAlan Cox 	domain->vmd_last_active_scan = ticks;
1977449c2e92SKonstantin Belousov 	vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
19787e78597fSMark Johnston 	vm_pageout_init_marker(&domain->vmd_inacthead, PQ_INACTIVE);
19797e78597fSMark Johnston 	TAILQ_INSERT_HEAD(&domain->vmd_pagequeues[PQ_INACTIVE].pq_pl,
19807e78597fSMark Johnston 	    &domain->vmd_inacthead, plinks.q);
1981449c2e92SKonstantin Belousov 
1982449c2e92SKonstantin Belousov 	/*
1983449c2e92SKonstantin Belousov 	 * The pageout daemon worker is never done, so loop forever.
1984449c2e92SKonstantin Belousov 	 */
1985449c2e92SKonstantin Belousov 	while (TRUE) {
1986449c2e92SKonstantin Belousov 		mtx_lock(&vm_page_queue_free_mtx);
198756ce0690SAlan Cox 
198856ce0690SAlan Cox 		/*
198956ce0690SAlan Cox 		 * Generally, after a level >= 1 scan, if there are enough
199056ce0690SAlan Cox 		 * free pages to wakeup the waiters, then they are already
199156ce0690SAlan Cox 		 * awake.  A call to vm_page_free() during the scan awakened
199256ce0690SAlan Cox 		 * them.  However, in the following case, this wakeup serves
199356ce0690SAlan Cox 		 * to bound the amount of time that a thread might wait.
199456ce0690SAlan Cox 		 * Suppose a thread's call to vm_page_alloc() fails, but
199556ce0690SAlan Cox 		 * before that thread calls VM_WAIT, enough pages are freed by
199656ce0690SAlan Cox 		 * other threads to alleviate the free page shortage.  The
199756ce0690SAlan Cox 		 * thread will, nonetheless, wait until another page is freed
199856ce0690SAlan Cox 		 * or this wakeup is performed.
199956ce0690SAlan Cox 		 */
2000449c2e92SKonstantin Belousov 		if (vm_pages_needed && !vm_page_count_min()) {
200156ce0690SAlan Cox 			vm_pages_needed = false;
200244f1c916SBryan Drewery 			wakeup(&vm_cnt.v_free_count);
2003449c2e92SKonstantin Belousov 		}
200456ce0690SAlan Cox 
2005449c2e92SKonstantin Belousov 		/*
2006e57dd910SAlan Cox 		 * Do not clear vm_pageout_wanted until we reach our free page
2007e57dd910SAlan Cox 		 * target.  Otherwise, we may be awakened over and over again,
2008e57dd910SAlan Cox 		 * wasting CPU time.
2009449c2e92SKonstantin Belousov 		 */
2010e57dd910SAlan Cox 		if (vm_pageout_wanted && target_met)
201156ce0690SAlan Cox 			vm_pageout_wanted = false;
201256ce0690SAlan Cox 
201356ce0690SAlan Cox 		/*
201456ce0690SAlan Cox 		 * Might the page daemon receive a wakeup call?
201556ce0690SAlan Cox 		 */
201656ce0690SAlan Cox 		if (vm_pageout_wanted) {
201756ce0690SAlan Cox 			/*
201856ce0690SAlan Cox 			 * No.  Either vm_pageout_wanted was set by another
201956ce0690SAlan Cox 			 * thread during the previous scan, which must have
202056ce0690SAlan Cox 			 * been a level 0 scan, or vm_pageout_wanted was
202156ce0690SAlan Cox 			 * already set and the scan failed to free enough
2022ebcddc72SAlan Cox 			 * pages.  If we haven't yet performed a level >= 1
2023ebcddc72SAlan Cox 			 * (page reclamation) scan, then increase the level
2024ebcddc72SAlan Cox 			 * and scan again now.  Otherwise, sleep a bit and
2025ebcddc72SAlan Cox 			 * try again later.
202656ce0690SAlan Cox 			 */
202756ce0690SAlan Cox 			mtx_unlock(&vm_page_queue_free_mtx);
2028ebcddc72SAlan Cox 			if (pass >= 1)
2029ebcddc72SAlan Cox 				pause("psleep", hz / VM_INACT_SCAN_RATE);
203070cf3cedSAlan Cox 			pass++;
2031449c2e92SKonstantin Belousov 		} else {
2032449c2e92SKonstantin Belousov 			/*
203356ce0690SAlan Cox 			 * Yes.  Sleep until pages need to be reclaimed or
203456ce0690SAlan Cox 			 * have their reference stats updated.
2035449c2e92SKonstantin Belousov 			 */
203656ce0690SAlan Cox 			if (mtx_sleep(&vm_pageout_wanted,
203756ce0690SAlan Cox 			    &vm_page_queue_free_mtx, PDROP | PVM, "psleep",
203856ce0690SAlan Cox 			    hz) == 0) {
2039*83c9dea1SGleb Smirnoff 				VM_CNT_INC(v_pdwakeups);
204070cf3cedSAlan Cox 				pass = 1;
2041d9347bcaSAlan Cox 			} else
204270cf3cedSAlan Cox 				pass = 0;
204356ce0690SAlan Cox 		}
204456ce0690SAlan Cox 
204570cf3cedSAlan Cox 		target_met = vm_pageout_scan(domain, pass);
2046449c2e92SKonstantin Belousov 	}
2047449c2e92SKonstantin Belousov }
2048449c2e92SKonstantin Belousov 
2049df8bae1dSRodney W. Grimes /*
20504d19f4adSSteven Hartland  *	vm_pageout_init initialises basic pageout daemon settings.
2051df8bae1dSRodney W. Grimes  */
20522b14f991SJulian Elischer static void
20534d19f4adSSteven Hartland vm_pageout_init(void)
2054df8bae1dSRodney W. Grimes {
2055df8bae1dSRodney W. Grimes 	/*
2056df8bae1dSRodney W. Grimes 	 * Initialize some paging parameters.
2057df8bae1dSRodney W. Grimes 	 */
205844f1c916SBryan Drewery 	vm_cnt.v_interrupt_free_min = 2;
205944f1c916SBryan Drewery 	if (vm_cnt.v_page_count < 2000)
2060f35329acSJohn Dyson 		vm_pageout_page_count = 8;
2061f6b04d2bSDavid Greenman 
206245ae1d91SAlan Cox 	/*
206345ae1d91SAlan Cox 	 * v_free_reserved needs to include enough for the largest
206445ae1d91SAlan Cox 	 * swap pager structures plus enough for any pv_entry structs
206545ae1d91SAlan Cox 	 * when paging.
206645ae1d91SAlan Cox 	 */
206744f1c916SBryan Drewery 	if (vm_cnt.v_page_count > 1024)
206844f1c916SBryan Drewery 		vm_cnt.v_free_min = 4 + (vm_cnt.v_page_count - 1024) / 200;
20692feb50bfSAttilio Rao 	else
207044f1c916SBryan Drewery 		vm_cnt.v_free_min = 4;
207144f1c916SBryan Drewery 	vm_cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
207244f1c916SBryan Drewery 	    vm_cnt.v_interrupt_free_min;
207344f1c916SBryan Drewery 	vm_cnt.v_free_reserved = vm_pageout_page_count +
207444f1c916SBryan Drewery 	    vm_cnt.v_pageout_free_min + (vm_cnt.v_page_count / 768);
207544f1c916SBryan Drewery 	vm_cnt.v_free_severe = vm_cnt.v_free_min / 2;
207644f1c916SBryan Drewery 	vm_cnt.v_free_target = 4 * vm_cnt.v_free_min + vm_cnt.v_free_reserved;
207744f1c916SBryan Drewery 	vm_cnt.v_free_min += vm_cnt.v_free_reserved;
207844f1c916SBryan Drewery 	vm_cnt.v_free_severe += vm_cnt.v_free_reserved;
207944f1c916SBryan Drewery 	vm_cnt.v_inactive_target = (3 * vm_cnt.v_free_target) / 2;
208044f1c916SBryan Drewery 	if (vm_cnt.v_inactive_target > vm_cnt.v_free_count / 3)
208144f1c916SBryan Drewery 		vm_cnt.v_inactive_target = vm_cnt.v_free_count / 3;
2082df8bae1dSRodney W. Grimes 
2083d9e23210SJeff Roberson 	/*
2084d9e23210SJeff Roberson 	 * Set the default wakeup threshold to be 10% above the minimum
2085d9e23210SJeff Roberson 	 * page limit.  This keeps the steady state out of shortfall.
2086d9e23210SJeff Roberson 	 */
208744f1c916SBryan Drewery 	vm_pageout_wakeup_thresh = (vm_cnt.v_free_min / 10) * 11;
2088d9e23210SJeff Roberson 
2089d9e23210SJeff Roberson 	/*
2090d9e23210SJeff Roberson 	 * Set interval in seconds for active scan.  We want to visit each
2091c9612b2dSJeff Roberson 	 * page at least once every ten minutes.  This is to prevent worst
2092c9612b2dSJeff Roberson 	 * case paging behaviors with stale active LRU.
2093d9e23210SJeff Roberson 	 */
2094d9e23210SJeff Roberson 	if (vm_pageout_update_period == 0)
2095c9612b2dSJeff Roberson 		vm_pageout_update_period = 600;
2096d9e23210SJeff Roberson 
2097df8bae1dSRodney W. Grimes 	/* XXX does not really belong here */
2098df8bae1dSRodney W. Grimes 	if (vm_page_max_wired == 0)
209944f1c916SBryan Drewery 		vm_page_max_wired = vm_cnt.v_free_count / 3;
2100ebcddc72SAlan Cox 
2101ebcddc72SAlan Cox 	/*
2102ebcddc72SAlan Cox 	 * Target amount of memory to move out of the laundry queue during a
2103ebcddc72SAlan Cox 	 * background laundering.  This is proportional to the amount of system
2104ebcddc72SAlan Cox 	 * memory.
2105ebcddc72SAlan Cox 	 */
2106ebcddc72SAlan Cox 	vm_background_launder_target = (vm_cnt.v_free_target -
2107ebcddc72SAlan Cox 	    vm_cnt.v_free_min) / 10;
21084d19f4adSSteven Hartland }
21094d19f4adSSteven Hartland 
21104d19f4adSSteven Hartland /*
21114d19f4adSSteven Hartland  *     vm_pageout is the high level pageout daemon.
21124d19f4adSSteven Hartland  */
21134d19f4adSSteven Hartland static void
21144d19f4adSSteven Hartland vm_pageout(void)
21154d19f4adSSteven Hartland {
211644ec2b63SKonstantin Belousov 	int error;
211762d70a81SJohn Baldwin #ifdef VM_NUMA_ALLOC
211844ec2b63SKonstantin Belousov 	int i;
21194d19f4adSSteven Hartland #endif
2120df8bae1dSRodney W. Grimes 
212124a1cce3SDavid Greenman 	swap_pager_swap_init();
2122ebcddc72SAlan Cox 	error = kthread_add(vm_pageout_laundry_worker, NULL, curproc, NULL,
2123ebcddc72SAlan Cox 	    0, 0, "laundry: dom0");
2124ebcddc72SAlan Cox 	if (error != 0)
2125ebcddc72SAlan Cox 		panic("starting laundry for domain 0, error %d", error);
212662d70a81SJohn Baldwin #ifdef VM_NUMA_ALLOC
2127449c2e92SKonstantin Belousov 	for (i = 1; i < vm_ndomains; i++) {
2128449c2e92SKonstantin Belousov 		error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
2129449c2e92SKonstantin Belousov 		    curproc, NULL, 0, 0, "dom%d", i);
2130449c2e92SKonstantin Belousov 		if (error != 0) {
2131449c2e92SKonstantin Belousov 			panic("starting pageout for domain %d, error %d\n",
2132449c2e92SKonstantin Belousov 			    i, error);
2133dc2efb27SJohn Dyson 		}
2134f919ebdeSDavid Greenman 	}
2135449c2e92SKonstantin Belousov #endif
213644ec2b63SKonstantin Belousov 	error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
213744ec2b63SKonstantin Belousov 	    0, 0, "uma");
213844ec2b63SKonstantin Belousov 	if (error != 0)
213944ec2b63SKonstantin Belousov 		panic("starting uma_reclaim helper, error %d\n", error);
2140d395270dSDimitry Andric 	vm_pageout_worker((void *)(uintptr_t)0);
2141df8bae1dSRodney W. Grimes }
214226f9a767SRodney W. Grimes 
21436b4b77adSAlan Cox /*
2144e9f995d8SAlan Cox  * Unless the free page queue lock is held by the caller, this function
21456b4b77adSAlan Cox  * should be regarded as advisory.  Specifically, the caller should
214644f1c916SBryan Drewery  * not msleep() on &vm_cnt.v_free_count following this function unless
2147e9f995d8SAlan Cox  * the free page queue lock is held until the msleep() is performed.
21486b4b77adSAlan Cox  */
2149e0c5a895SJohn Dyson void
21504a365329SAndrey Zonov pagedaemon_wakeup(void)
2151e0c5a895SJohn Dyson {
2152a1c0a785SAlan Cox 
215356ce0690SAlan Cox 	if (!vm_pageout_wanted && curthread->td_proc != pageproc) {
215456ce0690SAlan Cox 		vm_pageout_wanted = true;
215556ce0690SAlan Cox 		wakeup(&vm_pageout_wanted);
2156e0c5a895SJohn Dyson 	}
2157e0c5a895SJohn Dyson }
2158e0c5a895SJohn Dyson 
215938efa82bSJohn Dyson #if !defined(NO_SWAPPING)
21605afce282SDavid Greenman static void
216197824da3SAlan Cox vm_req_vmdaemon(int req)
21625afce282SDavid Greenman {
21635afce282SDavid Greenman 	static int lastrun = 0;
21645afce282SDavid Greenman 
216597824da3SAlan Cox 	mtx_lock(&vm_daemon_mtx);
216697824da3SAlan Cox 	vm_pageout_req_swapout |= req;
2167b18bfc3dSJohn Dyson 	if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
21685afce282SDavid Greenman 		wakeup(&vm_daemon_needed);
21695afce282SDavid Greenman 		lastrun = ticks;
21705afce282SDavid Greenman 	}
217197824da3SAlan Cox 	mtx_unlock(&vm_daemon_mtx);
21725afce282SDavid Greenman }
21735afce282SDavid Greenman 
21742b14f991SJulian Elischer static void
21754a365329SAndrey Zonov vm_daemon(void)
21760d94caffSDavid Greenman {
217791d5354aSJohn Baldwin 	struct rlimit rsslim;
2178dcbcd518SBruce Evans 	struct proc *p;
2179dcbcd518SBruce Evans 	struct thread *td;
21806bed074cSKonstantin Belousov 	struct vmspace *vm;
2181099e7e95SEdward Tomasz Napierala 	int breakout, swapout_flags, tryagain, attempts;
2182afcc55f3SEdward Tomasz Napierala #ifdef RACCT
2183099e7e95SEdward Tomasz Napierala 	uint64_t rsize, ravailable;
2184afcc55f3SEdward Tomasz Napierala #endif
21850d94caffSDavid Greenman 
21862fe6e4d7SDavid Greenman 	while (TRUE) {
218797824da3SAlan Cox 		mtx_lock(&vm_daemon_mtx);
21884b5c9cf6SEdward Tomasz Napierala 		msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
2189099e7e95SEdward Tomasz Napierala #ifdef RACCT
21904b5c9cf6SEdward Tomasz Napierala 		    racct_enable ? hz : 0
2191099e7e95SEdward Tomasz Napierala #else
21924b5c9cf6SEdward Tomasz Napierala 		    0
2193099e7e95SEdward Tomasz Napierala #endif
21944b5c9cf6SEdward Tomasz Napierala 		);
219597824da3SAlan Cox 		swapout_flags = vm_pageout_req_swapout;
21964c1f8ee9SDavid Greenman 		vm_pageout_req_swapout = 0;
219797824da3SAlan Cox 		mtx_unlock(&vm_daemon_mtx);
219897824da3SAlan Cox 		if (swapout_flags)
219997824da3SAlan Cox 			swapout_procs(swapout_flags);
220097824da3SAlan Cox 
22012fe6e4d7SDavid Greenman 		/*
22020d94caffSDavid Greenman 		 * scan the processes for exceeding their rlimits or if
22030d94caffSDavid Greenman 		 * process is swapped out -- deactivate pages
22042fe6e4d7SDavid Greenman 		 */
2205099e7e95SEdward Tomasz Napierala 		tryagain = 0;
2206099e7e95SEdward Tomasz Napierala 		attempts = 0;
2207099e7e95SEdward Tomasz Napierala again:
2208099e7e95SEdward Tomasz Napierala 		attempts++;
22091005a129SJohn Baldwin 		sx_slock(&allproc_lock);
2210f67af5c9SXin LI 		FOREACH_PROC_IN_SYSTEM(p) {
2211fe2144fdSLuoqi Chen 			vm_pindex_t limit, size;
22122fe6e4d7SDavid Greenman 
22132fe6e4d7SDavid Greenman 			/*
22142fe6e4d7SDavid Greenman 			 * if this is a system process or if we have already
22152fe6e4d7SDavid Greenman 			 * looked at this process, skip it.
22162fe6e4d7SDavid Greenman 			 */
2217897ecacdSJohn Baldwin 			PROC_LOCK(p);
22188e6fa660SJohn Baldwin 			if (p->p_state != PRS_NORMAL ||
22198e6fa660SJohn Baldwin 			    p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
2220897ecacdSJohn Baldwin 				PROC_UNLOCK(p);
22212fe6e4d7SDavid Greenman 				continue;
22222fe6e4d7SDavid Greenman 			}
22232fe6e4d7SDavid Greenman 			/*
22242fe6e4d7SDavid Greenman 			 * if the process is in a non-running type state,
22252fe6e4d7SDavid Greenman 			 * don't touch it.
22262fe6e4d7SDavid Greenman 			 */
2227e602ba25SJulian Elischer 			breakout = 0;
2228e602ba25SJulian Elischer 			FOREACH_THREAD_IN_PROC(p, td) {
2229982d11f8SJeff Roberson 				thread_lock(td);
223071fad9fdSJulian Elischer 				if (!TD_ON_RUNQ(td) &&
223171fad9fdSJulian Elischer 				    !TD_IS_RUNNING(td) &&
2232f497cda2SEdward Tomasz Napierala 				    !TD_IS_SLEEPING(td) &&
2233f497cda2SEdward Tomasz Napierala 				    !TD_IS_SUSPENDED(td)) {
2234982d11f8SJeff Roberson 					thread_unlock(td);
2235e602ba25SJulian Elischer 					breakout = 1;
2236e602ba25SJulian Elischer 					break;
2237e602ba25SJulian Elischer 				}
2238982d11f8SJeff Roberson 				thread_unlock(td);
2239e602ba25SJulian Elischer 			}
2240897ecacdSJohn Baldwin 			if (breakout) {
2241897ecacdSJohn Baldwin 				PROC_UNLOCK(p);
22422fe6e4d7SDavid Greenman 				continue;
22432fe6e4d7SDavid Greenman 			}
22442fe6e4d7SDavid Greenman 			/*
22452fe6e4d7SDavid Greenman 			 * get a limit
22462fe6e4d7SDavid Greenman 			 */
2247f6f6d240SMateusz Guzik 			lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
2248fe2144fdSLuoqi Chen 			limit = OFF_TO_IDX(
224991d5354aSJohn Baldwin 			    qmin(rsslim.rlim_cur, rsslim.rlim_max));
22502fe6e4d7SDavid Greenman 
22512fe6e4d7SDavid Greenman 			/*
22520d94caffSDavid Greenman 			 * let processes that are swapped out really be
22530d94caffSDavid Greenman 			 * swapped out set the limit to nothing (will force a
22540d94caffSDavid Greenman 			 * swap-out.)
22552fe6e4d7SDavid Greenman 			 */
2256b61ce5b0SJeff Roberson 			if ((p->p_flag & P_INMEM) == 0)
22570d94caffSDavid Greenman 				limit = 0;	/* XXX */
22586bed074cSKonstantin Belousov 			vm = vmspace_acquire_ref(p);
225995e2409aSKonstantin Belousov 			_PHOLD_LITE(p);
2260897ecacdSJohn Baldwin 			PROC_UNLOCK(p);
226195e2409aSKonstantin Belousov 			if (vm == NULL) {
226295e2409aSKonstantin Belousov 				PRELE(p);
22636bed074cSKonstantin Belousov 				continue;
226495e2409aSKonstantin Belousov 			}
226595e2409aSKonstantin Belousov 			sx_sunlock(&allproc_lock);
22662fe6e4d7SDavid Greenman 
22676bed074cSKonstantin Belousov 			size = vmspace_resident_count(vm);
2268a406d8c3SEdward Tomasz Napierala 			if (size >= limit) {
2269fe2144fdSLuoqi Chen 				vm_pageout_map_deactivate_pages(
22706bed074cSKonstantin Belousov 				    &vm->vm_map, limit);
2271937c1b07SAndriy Gapon 				size = vmspace_resident_count(vm);
22722fe6e4d7SDavid Greenman 			}
2273afcc55f3SEdward Tomasz Napierala #ifdef RACCT
22744b5c9cf6SEdward Tomasz Napierala 			if (racct_enable) {
2275099e7e95SEdward Tomasz Napierala 				rsize = IDX_TO_OFF(size);
2276099e7e95SEdward Tomasz Napierala 				PROC_LOCK(p);
2277937c1b07SAndriy Gapon 				if (p->p_state == PRS_NORMAL)
2278099e7e95SEdward Tomasz Napierala 					racct_set(p, RACCT_RSS, rsize);
2279099e7e95SEdward Tomasz Napierala 				ravailable = racct_get_available(p, RACCT_RSS);
2280099e7e95SEdward Tomasz Napierala 				PROC_UNLOCK(p);
2281099e7e95SEdward Tomasz Napierala 				if (rsize > ravailable) {
2282099e7e95SEdward Tomasz Napierala 					/*
22834b5c9cf6SEdward Tomasz Napierala 					 * Don't be overly aggressive; this
22844b5c9cf6SEdward Tomasz Napierala 					 * might be an innocent process,
22854b5c9cf6SEdward Tomasz Napierala 					 * and the limit could've been exceeded
22864b5c9cf6SEdward Tomasz Napierala 					 * by some memory hog.  Don't try
22874b5c9cf6SEdward Tomasz Napierala 					 * to deactivate more than 1/4th
22884b5c9cf6SEdward Tomasz Napierala 					 * of process' resident set size.
2289099e7e95SEdward Tomasz Napierala 					 */
2290099e7e95SEdward Tomasz Napierala 					if (attempts <= 8) {
22914b5c9cf6SEdward Tomasz Napierala 						if (ravailable < rsize -
22924b5c9cf6SEdward Tomasz Napierala 						    (rsize / 4)) {
22934b5c9cf6SEdward Tomasz Napierala 							ravailable = rsize -
22944b5c9cf6SEdward Tomasz Napierala 							    (rsize / 4);
22954b5c9cf6SEdward Tomasz Napierala 						}
2296099e7e95SEdward Tomasz Napierala 					}
2297099e7e95SEdward Tomasz Napierala 					vm_pageout_map_deactivate_pages(
22984b5c9cf6SEdward Tomasz Napierala 					    &vm->vm_map,
22994b5c9cf6SEdward Tomasz Napierala 					    OFF_TO_IDX(ravailable));
2300099e7e95SEdward Tomasz Napierala 					/* Update RSS usage after paging out. */
2301099e7e95SEdward Tomasz Napierala 					size = vmspace_resident_count(vm);
2302099e7e95SEdward Tomasz Napierala 					rsize = IDX_TO_OFF(size);
2303099e7e95SEdward Tomasz Napierala 					PROC_LOCK(p);
2304937c1b07SAndriy Gapon 					if (p->p_state == PRS_NORMAL)
2305099e7e95SEdward Tomasz Napierala 						racct_set(p, RACCT_RSS, rsize);
2306099e7e95SEdward Tomasz Napierala 					PROC_UNLOCK(p);
2307099e7e95SEdward Tomasz Napierala 					if (rsize > ravailable)
2308099e7e95SEdward Tomasz Napierala 						tryagain = 1;
2309099e7e95SEdward Tomasz Napierala 				}
23104b5c9cf6SEdward Tomasz Napierala 			}
2311afcc55f3SEdward Tomasz Napierala #endif
23126bed074cSKonstantin Belousov 			vmspace_free(vm);
231395e2409aSKonstantin Belousov 			sx_slock(&allproc_lock);
231495e2409aSKonstantin Belousov 			PRELE(p);
23152fe6e4d7SDavid Greenman 		}
23161005a129SJohn Baldwin 		sx_sunlock(&allproc_lock);
2317099e7e95SEdward Tomasz Napierala 		if (tryagain != 0 && attempts <= 10)
2318099e7e95SEdward Tomasz Napierala 			goto again;
231924a1cce3SDavid Greenman 	}
23202fe6e4d7SDavid Greenman }
2321a1287949SEivind Eklund #endif			/* !defined(NO_SWAPPING) */
2322