xref: /freebsd/sys/vm/vm_pageout.c (revision aed9aaaa76eb7cb3c686a2ba529293e768a58fa0)
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 
254e2241590SAlan Cox int vm_pageout_page_count = 32;
255df8bae1dSRodney W. Grimes 
256c3cb3e12SDavid Greenman int vm_page_max_wired;		/* XXX max # of wired pages system-wide */
2575dfc2870SAlan Cox SYSCTL_INT(_vm, OID_AUTO, max_wired,
2585dfc2870SAlan Cox 	CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
259df8bae1dSRodney W. Grimes 
260ebcddc72SAlan Cox static u_int isqrt(u_int num);
26185eeca35SAlan Cox static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
262ebcddc72SAlan Cox static int vm_pageout_launder(struct vm_domain *vmd, int launder,
263ebcddc72SAlan Cox     bool in_shortfall);
264ebcddc72SAlan Cox static void vm_pageout_laundry_worker(void *arg);
26538efa82bSJohn Dyson #if !defined(NO_SWAPPING)
266ecf6279fSAlan Cox static void vm_pageout_map_deactivate_pages(vm_map_t, long);
267ecf6279fSAlan Cox static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
26897824da3SAlan Cox static void vm_req_vmdaemon(int req);
26938efa82bSJohn Dyson #endif
27085eeca35SAlan Cox static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
271cd41fc12SDavid Greenman 
272a8229fa3SAlan Cox /*
273a8229fa3SAlan Cox  * Initialize a dummy page for marking the caller's place in the specified
274a8229fa3SAlan Cox  * paging queue.  In principle, this function only needs to set the flag
275f0edf3f8SAlan Cox  * PG_MARKER.  Nonetheless, it write busies and initializes the hold count
276c7aebda8SAttilio Rao  * to one as safety precautions.
277a8229fa3SAlan Cox  */
2788c616246SKonstantin Belousov static void
2798c616246SKonstantin Belousov vm_pageout_init_marker(vm_page_t marker, u_short queue)
2808c616246SKonstantin Belousov {
2818c616246SKonstantin Belousov 
2828c616246SKonstantin Belousov 	bzero(marker, sizeof(*marker));
283a8229fa3SAlan Cox 	marker->flags = PG_MARKER;
284c7aebda8SAttilio Rao 	marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
2858c616246SKonstantin Belousov 	marker->queue = queue;
286a8229fa3SAlan Cox 	marker->hold_count = 1;
2878c616246SKonstantin Belousov }
2888c616246SKonstantin Belousov 
28926f9a767SRodney W. Grimes /*
2908dbca793STor Egge  * vm_pageout_fallback_object_lock:
2918dbca793STor Egge  *
29289f6b863SAttilio Rao  * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
2938dbca793STor Egge  * known to have failed and page queue must be either PQ_ACTIVE or
29444be0a8eSMark Johnston  * PQ_INACTIVE.  To avoid lock order violation, unlock the page queue
2958dbca793STor Egge  * while locking the vm object.  Use marker page to detect page queue
2968dbca793STor Egge  * changes and maintain notion of next page on page queue.  Return
2978dbca793STor Egge  * TRUE if no changes were detected, FALSE otherwise.  vm object is
2988dbca793STor Egge  * locked on return.
2998dbca793STor Egge  *
3008dbca793STor Egge  * This function depends on both the lock portion of struct vm_object
3018dbca793STor Egge  * and normal struct vm_page being type stable.
3028dbca793STor Egge  */
30385eeca35SAlan Cox static boolean_t
3048dbca793STor Egge vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
3058dbca793STor Egge {
3068dbca793STor Egge 	struct vm_page marker;
3078d220203SAlan Cox 	struct vm_pagequeue *pq;
3088dbca793STor Egge 	boolean_t unchanged;
3098dbca793STor Egge 	u_short queue;
3108dbca793STor Egge 	vm_object_t object;
3118dbca793STor Egge 
3128dbca793STor Egge 	queue = m->queue;
3138c616246SKonstantin Belousov 	vm_pageout_init_marker(&marker, queue);
314449c2e92SKonstantin Belousov 	pq = vm_page_pagequeue(m);
3158dbca793STor Egge 	object = m->object;
3168dbca793STor Egge 
317c325e866SKonstantin Belousov 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
3188d220203SAlan Cox 	vm_pagequeue_unlock(pq);
3192965a453SKip Macy 	vm_page_unlock(m);
32089f6b863SAttilio Rao 	VM_OBJECT_WLOCK(object);
3212965a453SKip Macy 	vm_page_lock(m);
3228d220203SAlan Cox 	vm_pagequeue_lock(pq);
3238dbca793STor Egge 
32469b8585eSKonstantin Belousov 	/*
32569b8585eSKonstantin Belousov 	 * The page's object might have changed, and/or the page might
32669b8585eSKonstantin Belousov 	 * have moved from its original position in the queue.  If the
32769b8585eSKonstantin Belousov 	 * page's object has changed, then the caller should abandon
32869b8585eSKonstantin Belousov 	 * processing the page because the wrong object lock was
32969b8585eSKonstantin Belousov 	 * acquired.  Use the marker's plinks.q, not the page's, to
33069b8585eSKonstantin Belousov 	 * determine if the page has been moved.  The state of the
33169b8585eSKonstantin Belousov 	 * page's plinks.q can be indeterminate; whereas, the marker's
33269b8585eSKonstantin Belousov 	 * plinks.q must be valid.
33369b8585eSKonstantin Belousov 	 */
334c325e866SKonstantin Belousov 	*next = TAILQ_NEXT(&marker, plinks.q);
33569b8585eSKonstantin Belousov 	unchanged = m->object == object &&
33669b8585eSKonstantin Belousov 	    m == TAILQ_PREV(&marker, pglist, plinks.q);
33769b8585eSKonstantin Belousov 	KASSERT(!unchanged || m->queue == queue,
33869b8585eSKonstantin Belousov 	    ("page %p queue %d %d", m, queue, m->queue));
339c325e866SKonstantin Belousov 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
3408dbca793STor Egge 	return (unchanged);
3418dbca793STor Egge }
3428dbca793STor Egge 
3438dbca793STor Egge /*
3448c616246SKonstantin Belousov  * Lock the page while holding the page queue lock.  Use marker page
3458c616246SKonstantin Belousov  * to detect page queue changes and maintain notion of next page on
3468c616246SKonstantin Belousov  * page queue.  Return TRUE if no changes were detected, FALSE
3478c616246SKonstantin Belousov  * otherwise.  The page is locked on return. The page queue lock might
3488c616246SKonstantin Belousov  * be dropped and reacquired.
3498c616246SKonstantin Belousov  *
3508c616246SKonstantin Belousov  * This function depends on normal struct vm_page being type stable.
3518c616246SKonstantin Belousov  */
35285eeca35SAlan Cox static boolean_t
3538c616246SKonstantin Belousov vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
3548c616246SKonstantin Belousov {
3558c616246SKonstantin Belousov 	struct vm_page marker;
3568d220203SAlan Cox 	struct vm_pagequeue *pq;
3578c616246SKonstantin Belousov 	boolean_t unchanged;
3588c616246SKonstantin Belousov 	u_short queue;
3598c616246SKonstantin Belousov 
3608c616246SKonstantin Belousov 	vm_page_lock_assert(m, MA_NOTOWNED);
3618c616246SKonstantin Belousov 	if (vm_page_trylock(m))
3628c616246SKonstantin Belousov 		return (TRUE);
3638c616246SKonstantin Belousov 
3648c616246SKonstantin Belousov 	queue = m->queue;
3658c616246SKonstantin Belousov 	vm_pageout_init_marker(&marker, queue);
366449c2e92SKonstantin Belousov 	pq = vm_page_pagequeue(m);
3678c616246SKonstantin Belousov 
368c325e866SKonstantin Belousov 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
3698d220203SAlan Cox 	vm_pagequeue_unlock(pq);
3708c616246SKonstantin Belousov 	vm_page_lock(m);
3718d220203SAlan Cox 	vm_pagequeue_lock(pq);
3728c616246SKonstantin Belousov 
3738c616246SKonstantin Belousov 	/* Page queue might have changed. */
374c325e866SKonstantin Belousov 	*next = TAILQ_NEXT(&marker, plinks.q);
37569b8585eSKonstantin Belousov 	unchanged = m == TAILQ_PREV(&marker, pglist, plinks.q);
37669b8585eSKonstantin Belousov 	KASSERT(!unchanged || m->queue == queue,
37769b8585eSKonstantin Belousov 	    ("page %p queue %d %d", m, queue, m->queue));
378c325e866SKonstantin Belousov 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
3798c616246SKonstantin Belousov 	return (unchanged);
3808c616246SKonstantin Belousov }
3818c616246SKonstantin Belousov 
3828c616246SKonstantin Belousov /*
383248fe642SAlan Cox  * Scan for pages at adjacent offsets within the given page's object that are
384248fe642SAlan Cox  * eligible for laundering, form a cluster of these pages and the given page,
385248fe642SAlan Cox  * and launder that cluster.
38626f9a767SRodney W. Grimes  */
3873af76890SPoul-Henning Kamp static int
38834d8b7eaSJeff Roberson vm_pageout_cluster(vm_page_t m)
38924a1cce3SDavid Greenman {
39054d92145SMatthew Dillon 	vm_object_t object;
391248fe642SAlan Cox 	vm_page_t mc[2 * vm_pageout_page_count], p, pb, ps;
392248fe642SAlan Cox 	vm_pindex_t pindex;
393248fe642SAlan Cox 	int ib, is, page_base, pageout_count;
39426f9a767SRodney W. Grimes 
395248fe642SAlan Cox 	vm_page_assert_locked(m);
39617f6a17bSAlan Cox 	object = m->object;
39789f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
398248fe642SAlan Cox 	pindex = m->pindex;
3990cddd8f0SMatthew Dillon 
40026f9a767SRodney W. Grimes 	/*
401248fe642SAlan Cox 	 * We can't clean the page if it is busy or held.
40224a1cce3SDavid Greenman 	 */
403c7aebda8SAttilio Rao 	vm_page_assert_unbusied(m);
404248fe642SAlan Cox 	KASSERT(m->hold_count == 0, ("page %p is held", m));
405*aed9aaaaSMark Johnston 
406*aed9aaaaSMark Johnston 	pmap_remove_write(m);
40717f6a17bSAlan Cox 	vm_page_unlock(m);
4080d94caffSDavid Greenman 
40991b4f427SAlan Cox 	mc[vm_pageout_page_count] = pb = ps = m;
41026f9a767SRodney W. Grimes 	pageout_count = 1;
411f35329acSJohn Dyson 	page_base = vm_pageout_page_count;
41290ecac61SMatthew Dillon 	ib = 1;
41390ecac61SMatthew Dillon 	is = 1;
41490ecac61SMatthew Dillon 
41524a1cce3SDavid Greenman 	/*
416248fe642SAlan Cox 	 * We can cluster only if the page is not clean, busy, or held, and
417ebcddc72SAlan Cox 	 * the page is in the laundry queue.
41890ecac61SMatthew Dillon 	 *
41990ecac61SMatthew Dillon 	 * During heavy mmap/modification loads the pageout
42090ecac61SMatthew Dillon 	 * daemon can really fragment the underlying file
421248fe642SAlan Cox 	 * due to flushing pages out of order and not trying to
422248fe642SAlan Cox 	 * align the clusters (which leaves sporadic out-of-order
42390ecac61SMatthew Dillon 	 * holes).  To solve this problem we do the reverse scan
42490ecac61SMatthew Dillon 	 * first and attempt to align our cluster, then do a
42590ecac61SMatthew Dillon 	 * forward scan if room remains.
42624a1cce3SDavid Greenman 	 */
42790ecac61SMatthew Dillon more:
428248fe642SAlan Cox 	while (ib != 0 && pageout_count < vm_pageout_page_count) {
42990ecac61SMatthew Dillon 		if (ib > pindex) {
43090ecac61SMatthew Dillon 			ib = 0;
43190ecac61SMatthew Dillon 			break;
432f6b04d2bSDavid Greenman 		}
433c7aebda8SAttilio Rao 		if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
43490ecac61SMatthew Dillon 			ib = 0;
43590ecac61SMatthew Dillon 			break;
436f6b04d2bSDavid Greenman 		}
43724a1cce3SDavid Greenman 		vm_page_test_dirty(p);
438eb5d3969SAlan Cox 		if (p->dirty == 0) {
439eb5d3969SAlan Cox 			ib = 0;
440eb5d3969SAlan Cox 			break;
441eb5d3969SAlan Cox 		}
442eb5d3969SAlan Cox 		vm_page_lock(p);
443ebcddc72SAlan Cox 		if (!vm_page_in_laundry(p) ||
44457601bcbSMatthew Dillon 		    p->hold_count != 0) {	/* may be undergoing I/O */
4452965a453SKip Macy 			vm_page_unlock(p);
44690ecac61SMatthew Dillon 			ib = 0;
44724a1cce3SDavid Greenman 			break;
448f6b04d2bSDavid Greenman 		}
449*aed9aaaaSMark Johnston 		pmap_remove_write(p);
4502965a453SKip Macy 		vm_page_unlock(p);
45191b4f427SAlan Cox 		mc[--page_base] = pb = p;
45290ecac61SMatthew Dillon 		++pageout_count;
45390ecac61SMatthew Dillon 		++ib;
454248fe642SAlan Cox 
45524a1cce3SDavid Greenman 		/*
456248fe642SAlan Cox 		 * We are at an alignment boundary.  Stop here, and switch
457248fe642SAlan Cox 		 * directions.  Do not clear ib.
45824a1cce3SDavid Greenman 		 */
45990ecac61SMatthew Dillon 		if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
46090ecac61SMatthew Dillon 			break;
46124a1cce3SDavid Greenman 	}
46290ecac61SMatthew Dillon 	while (pageout_count < vm_pageout_page_count &&
46390ecac61SMatthew Dillon 	    pindex + is < object->size) {
464c7aebda8SAttilio Rao 		if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
46590ecac61SMatthew Dillon 			break;
46624a1cce3SDavid Greenman 		vm_page_test_dirty(p);
467eb5d3969SAlan Cox 		if (p->dirty == 0)
468eb5d3969SAlan Cox 			break;
469eb5d3969SAlan Cox 		vm_page_lock(p);
470ebcddc72SAlan Cox 		if (!vm_page_in_laundry(p) ||
47157601bcbSMatthew Dillon 		    p->hold_count != 0) {	/* may be undergoing I/O */
4722965a453SKip Macy 			vm_page_unlock(p);
47324a1cce3SDavid Greenman 			break;
47424a1cce3SDavid Greenman 		}
475*aed9aaaaSMark Johnston 		pmap_remove_write(p);
4762965a453SKip Macy 		vm_page_unlock(p);
47791b4f427SAlan Cox 		mc[page_base + pageout_count] = ps = p;
47890ecac61SMatthew Dillon 		++pageout_count;
47990ecac61SMatthew Dillon 		++is;
48024a1cce3SDavid Greenman 	}
48190ecac61SMatthew Dillon 
48290ecac61SMatthew Dillon 	/*
48390ecac61SMatthew Dillon 	 * If we exhausted our forward scan, continue with the reverse scan
484248fe642SAlan Cox 	 * when possible, even past an alignment boundary.  This catches
485248fe642SAlan Cox 	 * boundary conditions.
48690ecac61SMatthew Dillon 	 */
487248fe642SAlan Cox 	if (ib != 0 && pageout_count < vm_pageout_page_count)
48890ecac61SMatthew Dillon 		goto more;
489f6b04d2bSDavid Greenman 
49099e6e193SMark Johnston 	return (vm_pageout_flush(&mc[page_base], pageout_count,
49199e6e193SMark Johnston 	    VM_PAGER_PUT_NOREUSE, 0, NULL, NULL));
492aef922f5SJohn Dyson }
493aef922f5SJohn Dyson 
4941c7c3c6aSMatthew Dillon /*
4951c7c3c6aSMatthew Dillon  * vm_pageout_flush() - launder the given pages
4961c7c3c6aSMatthew Dillon  *
4971c7c3c6aSMatthew Dillon  *	The given pages are laundered.  Note that we setup for the start of
4981c7c3c6aSMatthew Dillon  *	I/O ( i.e. busy the page ), mark it read-only, and bump the object
4991c7c3c6aSMatthew Dillon  *	reference count all in here rather then in the parent.  If we want
5001c7c3c6aSMatthew Dillon  *	the parent to do more sophisticated things we may have to change
5011c7c3c6aSMatthew Dillon  *	the ordering.
5021e8a675cSKonstantin Belousov  *
5031e8a675cSKonstantin Belousov  *	Returned runlen is the count of pages between mreq and first
5041e8a675cSKonstantin Belousov  *	page after mreq with status VM_PAGER_AGAIN.
505126d6082SKonstantin Belousov  *	*eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
506126d6082SKonstantin Belousov  *	for any page in runlen set.
5071c7c3c6aSMatthew Dillon  */
508aef922f5SJohn Dyson int
509126d6082SKonstantin Belousov vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
510126d6082SKonstantin Belousov     boolean_t *eio)
511aef922f5SJohn Dyson {
5122e3b314dSAlan Cox 	vm_object_t object = mc[0]->object;
513aef922f5SJohn Dyson 	int pageout_status[count];
51495461b45SJohn Dyson 	int numpagedout = 0;
5151e8a675cSKonstantin Belousov 	int i, runlen;
516aef922f5SJohn Dyson 
51789f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
5187bec141bSKip Macy 
5191c7c3c6aSMatthew Dillon 	/*
520*aed9aaaaSMark Johnston 	 * Initiate I/O.  Mark the pages busy and verify that they're valid
521*aed9aaaaSMark Johnston 	 * and read-only.
5221c7c3c6aSMatthew Dillon 	 *
5231c7c3c6aSMatthew Dillon 	 * We do not have to fixup the clean/dirty bits here... we can
5241c7c3c6aSMatthew Dillon 	 * allow the pager to do it after the I/O completes.
52502fa91d3SMatthew Dillon 	 *
52602fa91d3SMatthew Dillon 	 * NOTE! mc[i]->dirty may be partial or fragmented due to an
52702fa91d3SMatthew Dillon 	 * edge case with file fragments.
5281c7c3c6aSMatthew Dillon 	 */
5298f9110f6SJohn Dyson 	for (i = 0; i < count; i++) {
5307a935082SAlan Cox 		KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
5317a935082SAlan Cox 		    ("vm_pageout_flush: partially invalid page %p index %d/%d",
5327a935082SAlan Cox 			mc[i], i, count));
533*aed9aaaaSMark Johnston 		KASSERT((mc[i]->aflags & PGA_WRITEABLE) == 0,
534*aed9aaaaSMark Johnston 		    ("vm_pageout_flush: writeable page %p", mc[i]));
535c7aebda8SAttilio Rao 		vm_page_sbusy(mc[i]);
5362965a453SKip Macy 	}
537d474eaaaSDoug Rabson 	vm_object_pip_add(object, count);
538aef922f5SJohn Dyson 
539d076fbeaSAlan Cox 	vm_pager_put_pages(object, mc, count, flags, pageout_status);
54026f9a767SRodney W. Grimes 
5411e8a675cSKonstantin Belousov 	runlen = count - mreq;
542126d6082SKonstantin Belousov 	if (eio != NULL)
543126d6082SKonstantin Belousov 		*eio = FALSE;
544aef922f5SJohn Dyson 	for (i = 0; i < count; i++) {
545aef922f5SJohn Dyson 		vm_page_t mt = mc[i];
54624a1cce3SDavid Greenman 
5474cd45723SAlan Cox 		KASSERT(pageout_status[i] == VM_PAGER_PEND ||
5486031c68dSAlan Cox 		    !pmap_page_is_write_mapped(mt),
5499ea8d1a6SAlan Cox 		    ("vm_pageout_flush: page %p is not write protected", mt));
55026f9a767SRodney W. Grimes 		switch (pageout_status[i]) {
55126f9a767SRodney W. Grimes 		case VM_PAGER_OK:
552ebcddc72SAlan Cox 			vm_page_lock(mt);
553ebcddc72SAlan Cox 			if (vm_page_in_laundry(mt))
554ebcddc72SAlan Cox 				vm_page_deactivate_noreuse(mt);
555ebcddc72SAlan Cox 			vm_page_unlock(mt);
556ebcddc72SAlan Cox 			/* FALLTHROUGH */
55726f9a767SRodney W. Grimes 		case VM_PAGER_PEND:
55895461b45SJohn Dyson 			numpagedout++;
55926f9a767SRodney W. Grimes 			break;
56026f9a767SRodney W. Grimes 		case VM_PAGER_BAD:
56126f9a767SRodney W. Grimes 			/*
562ebcddc72SAlan Cox 			 * The page is outside the object's range.  We pretend
563ebcddc72SAlan Cox 			 * that the page out worked and clean the page, so the
564ebcddc72SAlan Cox 			 * changes will be lost if the page is reclaimed by
565ebcddc72SAlan Cox 			 * the page daemon.
56626f9a767SRodney W. Grimes 			 */
56790ecac61SMatthew Dillon 			vm_page_undirty(mt);
568ebcddc72SAlan Cox 			vm_page_lock(mt);
569ebcddc72SAlan Cox 			if (vm_page_in_laundry(mt))
570ebcddc72SAlan Cox 				vm_page_deactivate_noreuse(mt);
571ebcddc72SAlan Cox 			vm_page_unlock(mt);
57226f9a767SRodney W. Grimes 			break;
57326f9a767SRodney W. Grimes 		case VM_PAGER_ERROR:
57426f9a767SRodney W. Grimes 		case VM_PAGER_FAIL:
57526f9a767SRodney W. Grimes 			/*
576b1fd102eSMark Johnston 			 * If the page couldn't be paged out to swap because the
577b1fd102eSMark Johnston 			 * pager wasn't able to find space, place the page in
578b1fd102eSMark Johnston 			 * the PQ_UNSWAPPABLE holding queue.  This is an
579b1fd102eSMark Johnston 			 * optimization that prevents the page daemon from
580b1fd102eSMark Johnston 			 * wasting CPU cycles on pages that cannot be reclaimed
581b1fd102eSMark Johnston 			 * becase no swap device is configured.
582b1fd102eSMark Johnston 			 *
583b1fd102eSMark Johnston 			 * Otherwise, reactivate the page so that it doesn't
584b1fd102eSMark Johnston 			 * clog the laundry and inactive queues.  (We will try
585b1fd102eSMark Johnston 			 * paging it out again later.)
58626f9a767SRodney W. Grimes 			 */
5873c4a2440SAlan Cox 			vm_page_lock(mt);
588b1fd102eSMark Johnston 			if (object->type == OBJT_SWAP &&
589b1fd102eSMark Johnston 			    pageout_status[i] == VM_PAGER_FAIL) {
590b1fd102eSMark Johnston 				vm_page_unswappable(mt);
591b1fd102eSMark Johnston 				numpagedout++;
592b1fd102eSMark Johnston 			} else
59324a1cce3SDavid Greenman 				vm_page_activate(mt);
5943c4a2440SAlan Cox 			vm_page_unlock(mt);
595126d6082SKonstantin Belousov 			if (eio != NULL && i >= mreq && i - mreq < runlen)
596126d6082SKonstantin Belousov 				*eio = TRUE;
59726f9a767SRodney W. Grimes 			break;
59826f9a767SRodney W. Grimes 		case VM_PAGER_AGAIN:
5991e8a675cSKonstantin Belousov 			if (i >= mreq && i - mreq < runlen)
6001e8a675cSKonstantin Belousov 				runlen = i - mreq;
60126f9a767SRodney W. Grimes 			break;
60226f9a767SRodney W. Grimes 		}
60326f9a767SRodney W. Grimes 
60426f9a767SRodney W. Grimes 		/*
6050d94caffSDavid Greenman 		 * If the operation is still going, leave the page busy to
6060d94caffSDavid Greenman 		 * block all other accesses. Also, leave the paging in
6070d94caffSDavid Greenman 		 * progress indicator set so that we don't attempt an object
6080d94caffSDavid Greenman 		 * collapse.
60926f9a767SRodney W. Grimes 		 */
61026f9a767SRodney W. Grimes 		if (pageout_status[i] != VM_PAGER_PEND) {
611f919ebdeSDavid Greenman 			vm_object_pip_wakeup(object);
612c7aebda8SAttilio Rao 			vm_page_sunbusy(mt);
6133c4a2440SAlan Cox 		}
6143c4a2440SAlan Cox 	}
6151e8a675cSKonstantin Belousov 	if (prunlen != NULL)
6161e8a675cSKonstantin Belousov 		*prunlen = runlen;
6173c4a2440SAlan Cox 	return (numpagedout);
61826f9a767SRodney W. Grimes }
61926f9a767SRodney W. Grimes 
620b1fd102eSMark Johnston static void
621b1fd102eSMark Johnston vm_pageout_swapon(void *arg __unused, struct swdevt *sp __unused)
622b1fd102eSMark Johnston {
623b1fd102eSMark Johnston 
624b1fd102eSMark Johnston 	atomic_store_rel_int(&swapdev_enabled, 1);
625b1fd102eSMark Johnston }
626b1fd102eSMark Johnston 
627b1fd102eSMark Johnston static void
628b1fd102eSMark Johnston vm_pageout_swapoff(void *arg __unused, struct swdevt *sp __unused)
629b1fd102eSMark Johnston {
630b1fd102eSMark Johnston 
631b1fd102eSMark Johnston 	if (swap_pager_nswapdev() == 1)
632b1fd102eSMark Johnston 		atomic_store_rel_int(&swapdev_enabled, 0);
633b1fd102eSMark Johnston }
634b1fd102eSMark Johnston 
63538efa82bSJohn Dyson #if !defined(NO_SWAPPING)
63626f9a767SRodney W. Grimes /*
63726f9a767SRodney W. Grimes  *	vm_pageout_object_deactivate_pages
63826f9a767SRodney W. Grimes  *
639ce186587SAlan Cox  *	Deactivate enough pages to satisfy the inactive target
640ce186587SAlan Cox  *	requirements.
64126f9a767SRodney W. Grimes  *
64226f9a767SRodney W. Grimes  *	The object and map must be locked.
64326f9a767SRodney W. Grimes  */
64438efa82bSJohn Dyson static void
645ce186587SAlan Cox vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
646ce186587SAlan Cox     long desired)
64726f9a767SRodney W. Grimes {
648ecf6279fSAlan Cox 	vm_object_t backing_object, object;
649ce186587SAlan Cox 	vm_page_t p;
650bb7858eaSJeff Roberson 	int act_delta, remove_mode;
65126f9a767SRodney W. Grimes 
652e23b0a19SAlan Cox 	VM_OBJECT_ASSERT_LOCKED(first_object);
65328634820SAlan Cox 	if ((first_object->flags & OBJ_FICTITIOUS) != 0)
65438efa82bSJohn Dyson 		return;
655ecf6279fSAlan Cox 	for (object = first_object;; object = backing_object) {
656ecf6279fSAlan Cox 		if (pmap_resident_count(pmap) <= desired)
657ecf6279fSAlan Cox 			goto unlock_return;
658e23b0a19SAlan Cox 		VM_OBJECT_ASSERT_LOCKED(object);
65928634820SAlan Cox 		if ((object->flags & OBJ_UNMANAGED) != 0 ||
66028634820SAlan Cox 		    object->paging_in_progress != 0)
661ecf6279fSAlan Cox 			goto unlock_return;
66226f9a767SRodney W. Grimes 
66385b1dc89SAlan Cox 		remove_mode = 0;
66438efa82bSJohn Dyson 		if (object->shadow_count > 1)
66538efa82bSJohn Dyson 			remove_mode = 1;
66626f9a767SRodney W. Grimes 		/*
667ce186587SAlan Cox 		 * Scan the object's entire memory queue.
66826f9a767SRodney W. Grimes 		 */
669ce186587SAlan Cox 		TAILQ_FOREACH(p, &object->memq, listq) {
670447fe2a4SAlan Cox 			if (pmap_resident_count(pmap) <= desired)
671447fe2a4SAlan Cox 				goto unlock_return;
672c7aebda8SAttilio Rao 			if (vm_page_busied(p))
673447fe2a4SAlan Cox 				continue;
67483c9dea1SGleb Smirnoff 			VM_CNT_INC(v_pdpages);
6752965a453SKip Macy 			vm_page_lock(p);
676ce186587SAlan Cox 			if (p->wire_count != 0 || p->hold_count != 0 ||
677ecf6279fSAlan Cox 			    !pmap_page_exists_quick(pmap, p)) {
6782965a453SKip Macy 				vm_page_unlock(p);
6790d94caffSDavid Greenman 				continue;
6800d94caffSDavid Greenman 			}
681bb7858eaSJeff Roberson 			act_delta = pmap_ts_referenced(p);
6823407fefeSKonstantin Belousov 			if ((p->aflags & PGA_REFERENCED) != 0) {
683bb7858eaSJeff Roberson 				if (act_delta == 0)
684bb7858eaSJeff Roberson 					act_delta = 1;
6853407fefeSKonstantin Belousov 				vm_page_aflag_clear(p, PGA_REFERENCED);
686ef743ce6SJohn Dyson 			}
687ebcddc72SAlan Cox 			if (!vm_page_active(p) && act_delta != 0) {
688ef743ce6SJohn Dyson 				vm_page_activate(p);
689bb7858eaSJeff Roberson 				p->act_count += act_delta;
690ebcddc72SAlan Cox 			} else if (vm_page_active(p)) {
691bb7858eaSJeff Roberson 				if (act_delta == 0) {
692ce186587SAlan Cox 					p->act_count -= min(p->act_count,
693ce186587SAlan Cox 					    ACT_DECLINE);
69490776bd7SJeff Roberson 					if (!remove_mode && p->act_count == 0) {
6954fec79beSAlan Cox 						pmap_remove_all(p);
69626f9a767SRodney W. Grimes 						vm_page_deactivate(p);
6978d220203SAlan Cox 					} else
6988d220203SAlan Cox 						vm_page_requeue(p);
699c8c4b40cSJohn Dyson 				} else {
700eaf13dd7SJohn Dyson 					vm_page_activate(p);
701ce186587SAlan Cox 					if (p->act_count < ACT_MAX -
702ce186587SAlan Cox 					    ACT_ADVANCE)
70338efa82bSJohn Dyson 						p->act_count += ACT_ADVANCE;
7048d220203SAlan Cox 					vm_page_requeue(p);
705ce186587SAlan Cox 				}
706ebcddc72SAlan Cox 			} else if (vm_page_inactive(p))
707ce186587SAlan Cox 				pmap_remove_all(p);
7082965a453SKip Macy 			vm_page_unlock(p);
70926f9a767SRodney W. Grimes 		}
710ecf6279fSAlan Cox 		if ((backing_object = object->backing_object) == NULL)
711ecf6279fSAlan Cox 			goto unlock_return;
712e23b0a19SAlan Cox 		VM_OBJECT_RLOCK(backing_object);
713ecf6279fSAlan Cox 		if (object != first_object)
714e23b0a19SAlan Cox 			VM_OBJECT_RUNLOCK(object);
71538efa82bSJohn Dyson 	}
716ecf6279fSAlan Cox unlock_return:
717ecf6279fSAlan Cox 	if (object != first_object)
718e23b0a19SAlan Cox 		VM_OBJECT_RUNLOCK(object);
71926f9a767SRodney W. Grimes }
72026f9a767SRodney W. Grimes 
72126f9a767SRodney W. Grimes /*
72226f9a767SRodney W. Grimes  * deactivate some number of pages in a map, try to do it fairly, but
72326f9a767SRodney W. Grimes  * that is really hard to do.
72426f9a767SRodney W. Grimes  */
725cd41fc12SDavid Greenman static void
72638efa82bSJohn Dyson vm_pageout_map_deactivate_pages(map, desired)
72726f9a767SRodney W. Grimes 	vm_map_t map;
728ecf6279fSAlan Cox 	long desired;
72926f9a767SRodney W. Grimes {
73026f9a767SRodney W. Grimes 	vm_map_entry_t tmpe;
73138efa82bSJohn Dyson 	vm_object_t obj, bigobj;
73230105b9eSTor Egge 	int nothingwired;
7330d94caffSDavid Greenman 
734d974f03cSAlan Cox 	if (!vm_map_trylock(map))
73526f9a767SRodney W. Grimes 		return;
73638efa82bSJohn Dyson 
73738efa82bSJohn Dyson 	bigobj = NULL;
73830105b9eSTor Egge 	nothingwired = TRUE;
73938efa82bSJohn Dyson 
74038efa82bSJohn Dyson 	/*
74138efa82bSJohn Dyson 	 * first, search out the biggest object, and try to free pages from
74238efa82bSJohn Dyson 	 * that.
74338efa82bSJohn Dyson 	 */
74426f9a767SRodney W. Grimes 	tmpe = map->header.next;
74538efa82bSJohn Dyson 	while (tmpe != &map->header) {
7469fdfe602SMatthew Dillon 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
74738efa82bSJohn Dyson 			obj = tmpe->object.vm_object;
748e23b0a19SAlan Cox 			if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
7490774dfb3SAlan Cox 				if (obj->shadow_count <= 1 &&
7500774dfb3SAlan Cox 				    (bigobj == NULL ||
7510774dfb3SAlan Cox 				     bigobj->resident_page_count < obj->resident_page_count)) {
7520774dfb3SAlan Cox 					if (bigobj != NULL)
753e23b0a19SAlan Cox 						VM_OBJECT_RUNLOCK(bigobj);
75438efa82bSJohn Dyson 					bigobj = obj;
7550774dfb3SAlan Cox 				} else
756e23b0a19SAlan Cox 					VM_OBJECT_RUNLOCK(obj);
75738efa82bSJohn Dyson 			}
75838efa82bSJohn Dyson 		}
75930105b9eSTor Egge 		if (tmpe->wired_count > 0)
76030105b9eSTor Egge 			nothingwired = FALSE;
76138efa82bSJohn Dyson 		tmpe = tmpe->next;
76238efa82bSJohn Dyson 	}
76338efa82bSJohn Dyson 
7640774dfb3SAlan Cox 	if (bigobj != NULL) {
765ecf6279fSAlan Cox 		vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
766e23b0a19SAlan Cox 		VM_OBJECT_RUNLOCK(bigobj);
7670774dfb3SAlan Cox 	}
76838efa82bSJohn Dyson 	/*
76938efa82bSJohn Dyson 	 * Next, hunt around for other pages to deactivate.  We actually
77038efa82bSJohn Dyson 	 * do this search sort of wrong -- .text first is not the best idea.
77138efa82bSJohn Dyson 	 */
77238efa82bSJohn Dyson 	tmpe = map->header.next;
77338efa82bSJohn Dyson 	while (tmpe != &map->header) {
774b1028ad1SLuoqi Chen 		if (pmap_resident_count(vm_map_pmap(map)) <= desired)
77538efa82bSJohn Dyson 			break;
7769fdfe602SMatthew Dillon 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
77738efa82bSJohn Dyson 			obj = tmpe->object.vm_object;
7780774dfb3SAlan Cox 			if (obj != NULL) {
779e23b0a19SAlan Cox 				VM_OBJECT_RLOCK(obj);
780ecf6279fSAlan Cox 				vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
781e23b0a19SAlan Cox 				VM_OBJECT_RUNLOCK(obj);
7820774dfb3SAlan Cox 			}
78338efa82bSJohn Dyson 		}
78426f9a767SRodney W. Grimes 		tmpe = tmpe->next;
78538857e7fSAlan Cox 	}
78638efa82bSJohn Dyson 
78738efa82bSJohn Dyson 	/*
78838efa82bSJohn Dyson 	 * Remove all mappings if a process is swapped out, this will free page
78938efa82bSJohn Dyson 	 * table pages.
79038efa82bSJohn Dyson 	 */
79138857e7fSAlan Cox 	if (desired == 0 && nothingwired) {
7928d01a3b2SNathan Whitehorn 		pmap_remove(vm_map_pmap(map), vm_map_min(map),
7938d01a3b2SNathan Whitehorn 		    vm_map_max(map));
79438857e7fSAlan Cox 	}
795938b0f5bSMarcel Moolenaar 
79638efa82bSJohn Dyson 	vm_map_unlock(map);
79726f9a767SRodney W. Grimes }
798a1287949SEivind Eklund #endif		/* !defined(NO_SWAPPING) */
799df8bae1dSRodney W. Grimes 
8001c7c3c6aSMatthew Dillon /*
80134d8b7eaSJeff Roberson  * Attempt to acquire all of the necessary locks to launder a page and
80234d8b7eaSJeff Roberson  * then call through the clustering layer to PUTPAGES.  Wait a short
80334d8b7eaSJeff Roberson  * time for a vnode lock.
80434d8b7eaSJeff Roberson  *
80534d8b7eaSJeff Roberson  * Requires the page and object lock on entry, releases both before return.
80634d8b7eaSJeff Roberson  * Returns 0 on success and an errno otherwise.
80734d8b7eaSJeff Roberson  */
80834d8b7eaSJeff Roberson static int
809ebcddc72SAlan Cox vm_pageout_clean(vm_page_t m, int *numpagedout)
81034d8b7eaSJeff Roberson {
81134d8b7eaSJeff Roberson 	struct vnode *vp;
81234d8b7eaSJeff Roberson 	struct mount *mp;
81334d8b7eaSJeff Roberson 	vm_object_t object;
81434d8b7eaSJeff Roberson 	vm_pindex_t pindex;
81534d8b7eaSJeff Roberson 	int error, lockmode;
81634d8b7eaSJeff Roberson 
81734d8b7eaSJeff Roberson 	vm_page_assert_locked(m);
81834d8b7eaSJeff Roberson 	object = m->object;
81934d8b7eaSJeff Roberson 	VM_OBJECT_ASSERT_WLOCKED(object);
82034d8b7eaSJeff Roberson 	error = 0;
82134d8b7eaSJeff Roberson 	vp = NULL;
82234d8b7eaSJeff Roberson 	mp = NULL;
82334d8b7eaSJeff Roberson 
82434d8b7eaSJeff Roberson 	/*
82534d8b7eaSJeff Roberson 	 * The object is already known NOT to be dead.   It
82634d8b7eaSJeff Roberson 	 * is possible for the vget() to block the whole
82734d8b7eaSJeff Roberson 	 * pageout daemon, but the new low-memory handling
82834d8b7eaSJeff Roberson 	 * code should prevent it.
82934d8b7eaSJeff Roberson 	 *
83034d8b7eaSJeff Roberson 	 * We can't wait forever for the vnode lock, we might
83134d8b7eaSJeff Roberson 	 * deadlock due to a vn_read() getting stuck in
83234d8b7eaSJeff Roberson 	 * vm_wait while holding this vnode.  We skip the
83334d8b7eaSJeff Roberson 	 * vnode if we can't get it in a reasonable amount
83434d8b7eaSJeff Roberson 	 * of time.
83534d8b7eaSJeff Roberson 	 */
83634d8b7eaSJeff Roberson 	if (object->type == OBJT_VNODE) {
83734d8b7eaSJeff Roberson 		vm_page_unlock(m);
83834d8b7eaSJeff Roberson 		vp = object->handle;
83934d8b7eaSJeff Roberson 		if (vp->v_type == VREG &&
84034d8b7eaSJeff Roberson 		    vn_start_write(vp, &mp, V_NOWAIT) != 0) {
84134d8b7eaSJeff Roberson 			mp = NULL;
84234d8b7eaSJeff Roberson 			error = EDEADLK;
84334d8b7eaSJeff Roberson 			goto unlock_all;
84434d8b7eaSJeff Roberson 		}
84534d8b7eaSJeff Roberson 		KASSERT(mp != NULL,
84634d8b7eaSJeff Roberson 		    ("vp %p with NULL v_mount", vp));
84734d8b7eaSJeff Roberson 		vm_object_reference_locked(object);
84834d8b7eaSJeff Roberson 		pindex = m->pindex;
84934d8b7eaSJeff Roberson 		VM_OBJECT_WUNLOCK(object);
85034d8b7eaSJeff Roberson 		lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
85134d8b7eaSJeff Roberson 		    LK_SHARED : LK_EXCLUSIVE;
85234d8b7eaSJeff Roberson 		if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
85334d8b7eaSJeff Roberson 			vp = NULL;
85434d8b7eaSJeff Roberson 			error = EDEADLK;
85534d8b7eaSJeff Roberson 			goto unlock_mp;
85634d8b7eaSJeff Roberson 		}
85734d8b7eaSJeff Roberson 		VM_OBJECT_WLOCK(object);
85834d8b7eaSJeff Roberson 		vm_page_lock(m);
85934d8b7eaSJeff Roberson 		/*
86034d8b7eaSJeff Roberson 		 * While the object and page were unlocked, the page
86134d8b7eaSJeff Roberson 		 * may have been:
86234d8b7eaSJeff Roberson 		 * (1) moved to a different queue,
86334d8b7eaSJeff Roberson 		 * (2) reallocated to a different object,
86434d8b7eaSJeff Roberson 		 * (3) reallocated to a different offset, or
86534d8b7eaSJeff Roberson 		 * (4) cleaned.
86634d8b7eaSJeff Roberson 		 */
867ebcddc72SAlan Cox 		if (!vm_page_in_laundry(m) || m->object != object ||
86834d8b7eaSJeff Roberson 		    m->pindex != pindex || m->dirty == 0) {
86934d8b7eaSJeff Roberson 			vm_page_unlock(m);
87034d8b7eaSJeff Roberson 			error = ENXIO;
87134d8b7eaSJeff Roberson 			goto unlock_all;
87234d8b7eaSJeff Roberson 		}
87334d8b7eaSJeff Roberson 
87434d8b7eaSJeff Roberson 		/*
87534d8b7eaSJeff Roberson 		 * The page may have been busied or held while the object
87634d8b7eaSJeff Roberson 		 * and page locks were released.
87734d8b7eaSJeff Roberson 		 */
87834d8b7eaSJeff Roberson 		if (vm_page_busied(m) || m->hold_count != 0) {
87934d8b7eaSJeff Roberson 			vm_page_unlock(m);
88034d8b7eaSJeff Roberson 			error = EBUSY;
88134d8b7eaSJeff Roberson 			goto unlock_all;
88234d8b7eaSJeff Roberson 		}
88334d8b7eaSJeff Roberson 	}
88434d8b7eaSJeff Roberson 
88534d8b7eaSJeff Roberson 	/*
88634d8b7eaSJeff Roberson 	 * If a page is dirty, then it is either being washed
88734d8b7eaSJeff Roberson 	 * (but not yet cleaned) or it is still in the
88834d8b7eaSJeff Roberson 	 * laundry.  If it is still in the laundry, then we
88934d8b7eaSJeff Roberson 	 * start the cleaning operation.
89034d8b7eaSJeff Roberson 	 */
891ebcddc72SAlan Cox 	if ((*numpagedout = vm_pageout_cluster(m)) == 0)
89234d8b7eaSJeff Roberson 		error = EIO;
89334d8b7eaSJeff Roberson 
89434d8b7eaSJeff Roberson unlock_all:
89534d8b7eaSJeff Roberson 	VM_OBJECT_WUNLOCK(object);
89634d8b7eaSJeff Roberson 
89734d8b7eaSJeff Roberson unlock_mp:
89834d8b7eaSJeff Roberson 	vm_page_lock_assert(m, MA_NOTOWNED);
89934d8b7eaSJeff Roberson 	if (mp != NULL) {
90034d8b7eaSJeff Roberson 		if (vp != NULL)
90134d8b7eaSJeff Roberson 			vput(vp);
90234d8b7eaSJeff Roberson 		vm_object_deallocate(object);
90334d8b7eaSJeff Roberson 		vn_finished_write(mp);
90434d8b7eaSJeff Roberson 	}
90534d8b7eaSJeff Roberson 
90634d8b7eaSJeff Roberson 	return (error);
90734d8b7eaSJeff Roberson }
90834d8b7eaSJeff Roberson 
90934d8b7eaSJeff Roberson /*
910ebcddc72SAlan Cox  * Attempt to launder the specified number of pages.
911ebcddc72SAlan Cox  *
912ebcddc72SAlan Cox  * Returns the number of pages successfully laundered.
913ebcddc72SAlan Cox  */
914ebcddc72SAlan Cox static int
915ebcddc72SAlan Cox vm_pageout_launder(struct vm_domain *vmd, int launder, bool in_shortfall)
916ebcddc72SAlan Cox {
917ebcddc72SAlan Cox 	struct vm_pagequeue *pq;
918ebcddc72SAlan Cox 	vm_object_t object;
919ebcddc72SAlan Cox 	vm_page_t m, next;
920ebcddc72SAlan Cox 	int act_delta, error, maxscan, numpagedout, starting_target;
921ebcddc72SAlan Cox 	int vnodes_skipped;
922ebcddc72SAlan Cox 	bool pageout_ok, queue_locked;
923ebcddc72SAlan Cox 
924ebcddc72SAlan Cox 	starting_target = launder;
925ebcddc72SAlan Cox 	vnodes_skipped = 0;
926ebcddc72SAlan Cox 
927ebcddc72SAlan Cox 	/*
928b1fd102eSMark Johnston 	 * Scan the laundry queues for pages eligible to be laundered.  We stop
929ebcddc72SAlan Cox 	 * once the target number of dirty pages have been laundered, or once
930ebcddc72SAlan Cox 	 * we've reached the end of the queue.  A single iteration of this loop
931ebcddc72SAlan Cox 	 * may cause more than one page to be laundered because of clustering.
932ebcddc72SAlan Cox 	 *
933ebcddc72SAlan Cox 	 * maxscan ensures that we don't re-examine requeued pages.  Any
934ebcddc72SAlan Cox 	 * additional pages written as part of a cluster are subtracted from
935ebcddc72SAlan Cox 	 * maxscan since they must be taken from the laundry queue.
936b1fd102eSMark Johnston 	 *
937b1fd102eSMark Johnston 	 * As an optimization, we avoid laundering from PQ_UNSWAPPABLE when no
938b1fd102eSMark Johnston 	 * swap devices are configured.
939ebcddc72SAlan Cox 	 */
940b1fd102eSMark Johnston 	if (atomic_load_acq_int(&swapdev_enabled))
941b1fd102eSMark Johnston 		pq = &vmd->vmd_pagequeues[PQ_UNSWAPPABLE];
942b1fd102eSMark Johnston 	else
943ebcddc72SAlan Cox 		pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
944ebcddc72SAlan Cox 
945b1fd102eSMark Johnston scan:
946ebcddc72SAlan Cox 	vm_pagequeue_lock(pq);
947b1fd102eSMark Johnston 	maxscan = pq->pq_cnt;
948ebcddc72SAlan Cox 	queue_locked = true;
949ebcddc72SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl);
950ebcddc72SAlan Cox 	    m != NULL && maxscan-- > 0 && launder > 0;
951ebcddc72SAlan Cox 	    m = next) {
952ebcddc72SAlan Cox 		vm_pagequeue_assert_locked(pq);
953ebcddc72SAlan Cox 		KASSERT(queue_locked, ("unlocked laundry queue"));
954ebcddc72SAlan Cox 		KASSERT(vm_page_in_laundry(m),
955ebcddc72SAlan Cox 		    ("page %p has an inconsistent queue", m));
956ebcddc72SAlan Cox 		next = TAILQ_NEXT(m, plinks.q);
957ebcddc72SAlan Cox 		if ((m->flags & PG_MARKER) != 0)
958ebcddc72SAlan Cox 			continue;
959ebcddc72SAlan Cox 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
960ebcddc72SAlan Cox 		    ("PG_FICTITIOUS page %p cannot be in laundry queue", m));
961ebcddc72SAlan Cox 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
962ebcddc72SAlan Cox 		    ("VPO_UNMANAGED page %p cannot be in laundry queue", m));
963ebcddc72SAlan Cox 		if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
964ebcddc72SAlan Cox 			vm_page_unlock(m);
965ebcddc72SAlan Cox 			continue;
966ebcddc72SAlan Cox 		}
967ebcddc72SAlan Cox 		object = m->object;
968ebcddc72SAlan Cox 		if ((!VM_OBJECT_TRYWLOCK(object) &&
969ebcddc72SAlan Cox 		    (!vm_pageout_fallback_object_lock(m, &next) ||
970ebcddc72SAlan Cox 		    m->hold_count != 0)) || vm_page_busied(m)) {
971ebcddc72SAlan Cox 			VM_OBJECT_WUNLOCK(object);
972ebcddc72SAlan Cox 			vm_page_unlock(m);
973ebcddc72SAlan Cox 			continue;
974ebcddc72SAlan Cox 		}
975ebcddc72SAlan Cox 
976ebcddc72SAlan Cox 		/*
977ebcddc72SAlan Cox 		 * Unlock the laundry queue, invalidating the 'next' pointer.
978ebcddc72SAlan Cox 		 * Use a marker to remember our place in the laundry queue.
979ebcddc72SAlan Cox 		 */
980ebcddc72SAlan Cox 		TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_laundry_marker,
981ebcddc72SAlan Cox 		    plinks.q);
982ebcddc72SAlan Cox 		vm_pagequeue_unlock(pq);
983ebcddc72SAlan Cox 		queue_locked = false;
984ebcddc72SAlan Cox 
985ebcddc72SAlan Cox 		/*
986ebcddc72SAlan Cox 		 * Invalid pages can be easily freed.  They cannot be
987ebcddc72SAlan Cox 		 * mapped; vm_page_free() asserts this.
988ebcddc72SAlan Cox 		 */
989ebcddc72SAlan Cox 		if (m->valid == 0)
990ebcddc72SAlan Cox 			goto free_page;
991ebcddc72SAlan Cox 
992ebcddc72SAlan Cox 		/*
993ebcddc72SAlan Cox 		 * If the page has been referenced and the object is not dead,
994ebcddc72SAlan Cox 		 * reactivate or requeue the page depending on whether the
995ebcddc72SAlan Cox 		 * object is mapped.
996ebcddc72SAlan Cox 		 */
997ebcddc72SAlan Cox 		if ((m->aflags & PGA_REFERENCED) != 0) {
998ebcddc72SAlan Cox 			vm_page_aflag_clear(m, PGA_REFERENCED);
999ebcddc72SAlan Cox 			act_delta = 1;
1000ebcddc72SAlan Cox 		} else
1001ebcddc72SAlan Cox 			act_delta = 0;
1002ebcddc72SAlan Cox 		if (object->ref_count != 0)
1003ebcddc72SAlan Cox 			act_delta += pmap_ts_referenced(m);
1004ebcddc72SAlan Cox 		else {
1005ebcddc72SAlan Cox 			KASSERT(!pmap_page_is_mapped(m),
1006ebcddc72SAlan Cox 			    ("page %p is mapped", m));
1007ebcddc72SAlan Cox 		}
1008ebcddc72SAlan Cox 		if (act_delta != 0) {
1009ebcddc72SAlan Cox 			if (object->ref_count != 0) {
101083c9dea1SGleb Smirnoff 				VM_CNT_INC(v_reactivated);
1011ebcddc72SAlan Cox 				vm_page_activate(m);
1012ebcddc72SAlan Cox 
1013ebcddc72SAlan Cox 				/*
1014ebcddc72SAlan Cox 				 * Increase the activation count if the page
1015ebcddc72SAlan Cox 				 * was referenced while in the laundry queue.
1016ebcddc72SAlan Cox 				 * This makes it less likely that the page will
1017ebcddc72SAlan Cox 				 * be returned prematurely to the inactive
1018ebcddc72SAlan Cox 				 * queue.
1019ebcddc72SAlan Cox  				 */
1020ebcddc72SAlan Cox 				m->act_count += act_delta + ACT_ADVANCE;
1021ebcddc72SAlan Cox 
1022ebcddc72SAlan Cox 				/*
1023ebcddc72SAlan Cox 				 * If this was a background laundering, count
1024ebcddc72SAlan Cox 				 * activated pages towards our target.  The
1025ebcddc72SAlan Cox 				 * purpose of background laundering is to ensure
1026ebcddc72SAlan Cox 				 * that pages are eventually cycled through the
1027ebcddc72SAlan Cox 				 * laundry queue, and an activation is a valid
1028ebcddc72SAlan Cox 				 * way out.
1029ebcddc72SAlan Cox 				 */
1030ebcddc72SAlan Cox 				if (!in_shortfall)
1031ebcddc72SAlan Cox 					launder--;
1032ebcddc72SAlan Cox 				goto drop_page;
1033ebcddc72SAlan Cox 			} else if ((object->flags & OBJ_DEAD) == 0)
1034ebcddc72SAlan Cox 				goto requeue_page;
1035ebcddc72SAlan Cox 		}
1036ebcddc72SAlan Cox 
1037ebcddc72SAlan Cox 		/*
1038ebcddc72SAlan Cox 		 * If the page appears to be clean at the machine-independent
1039ebcddc72SAlan Cox 		 * layer, then remove all of its mappings from the pmap in
1040ebcddc72SAlan Cox 		 * anticipation of freeing it.  If, however, any of the page's
1041ebcddc72SAlan Cox 		 * mappings allow write access, then the page may still be
1042ebcddc72SAlan Cox 		 * modified until the last of those mappings are removed.
1043ebcddc72SAlan Cox 		 */
1044ebcddc72SAlan Cox 		if (object->ref_count != 0) {
1045ebcddc72SAlan Cox 			vm_page_test_dirty(m);
1046ebcddc72SAlan Cox 			if (m->dirty == 0)
1047ebcddc72SAlan Cox 				pmap_remove_all(m);
1048ebcddc72SAlan Cox 		}
1049ebcddc72SAlan Cox 
1050ebcddc72SAlan Cox 		/*
1051ebcddc72SAlan Cox 		 * Clean pages are freed, and dirty pages are paged out unless
1052ebcddc72SAlan Cox 		 * they belong to a dead object.  Requeueing dirty pages from
1053ebcddc72SAlan Cox 		 * dead objects is pointless, as they are being paged out and
1054ebcddc72SAlan Cox 		 * freed by the thread that destroyed the object.
1055ebcddc72SAlan Cox 		 */
1056ebcddc72SAlan Cox 		if (m->dirty == 0) {
1057ebcddc72SAlan Cox free_page:
1058ebcddc72SAlan Cox 			vm_page_free(m);
105983c9dea1SGleb Smirnoff 			VM_CNT_INC(v_dfree);
1060ebcddc72SAlan Cox 		} else if ((object->flags & OBJ_DEAD) == 0) {
1061ebcddc72SAlan Cox 			if (object->type != OBJT_SWAP &&
1062ebcddc72SAlan Cox 			    object->type != OBJT_DEFAULT)
1063ebcddc72SAlan Cox 				pageout_ok = true;
1064ebcddc72SAlan Cox 			else if (disable_swap_pageouts)
1065ebcddc72SAlan Cox 				pageout_ok = false;
1066ebcddc72SAlan Cox 			else
1067ebcddc72SAlan Cox 				pageout_ok = true;
1068ebcddc72SAlan Cox 			if (!pageout_ok) {
1069ebcddc72SAlan Cox requeue_page:
1070ebcddc72SAlan Cox 				vm_pagequeue_lock(pq);
1071ebcddc72SAlan Cox 				queue_locked = true;
1072ebcddc72SAlan Cox 				vm_page_requeue_locked(m);
1073ebcddc72SAlan Cox 				goto drop_page;
1074ebcddc72SAlan Cox 			}
1075ebcddc72SAlan Cox 
1076ebcddc72SAlan Cox 			/*
1077ebcddc72SAlan Cox 			 * Form a cluster with adjacent, dirty pages from the
1078ebcddc72SAlan Cox 			 * same object, and page out that entire cluster.
1079ebcddc72SAlan Cox 			 *
1080ebcddc72SAlan Cox 			 * The adjacent, dirty pages must also be in the
1081ebcddc72SAlan Cox 			 * laundry.  However, their mappings are not checked
1082ebcddc72SAlan Cox 			 * for new references.  Consequently, a recently
1083ebcddc72SAlan Cox 			 * referenced page may be paged out.  However, that
1084ebcddc72SAlan Cox 			 * page will not be prematurely reclaimed.  After page
1085ebcddc72SAlan Cox 			 * out, the page will be placed in the inactive queue,
1086ebcddc72SAlan Cox 			 * where any new references will be detected and the
1087ebcddc72SAlan Cox 			 * page reactivated.
1088ebcddc72SAlan Cox 			 */
1089ebcddc72SAlan Cox 			error = vm_pageout_clean(m, &numpagedout);
1090ebcddc72SAlan Cox 			if (error == 0) {
1091ebcddc72SAlan Cox 				launder -= numpagedout;
1092ebcddc72SAlan Cox 				maxscan -= numpagedout - 1;
1093ebcddc72SAlan Cox 			} else if (error == EDEADLK) {
1094ebcddc72SAlan Cox 				pageout_lock_miss++;
1095ebcddc72SAlan Cox 				vnodes_skipped++;
1096ebcddc72SAlan Cox 			}
1097ebcddc72SAlan Cox 			goto relock_queue;
1098ebcddc72SAlan Cox 		}
1099ebcddc72SAlan Cox drop_page:
1100ebcddc72SAlan Cox 		vm_page_unlock(m);
1101ebcddc72SAlan Cox 		VM_OBJECT_WUNLOCK(object);
1102ebcddc72SAlan Cox relock_queue:
1103ebcddc72SAlan Cox 		if (!queue_locked) {
1104ebcddc72SAlan Cox 			vm_pagequeue_lock(pq);
1105ebcddc72SAlan Cox 			queue_locked = true;
1106ebcddc72SAlan Cox 		}
1107ebcddc72SAlan Cox 		next = TAILQ_NEXT(&vmd->vmd_laundry_marker, plinks.q);
1108ebcddc72SAlan Cox 		TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_laundry_marker, plinks.q);
1109ebcddc72SAlan Cox 	}
1110ebcddc72SAlan Cox 	vm_pagequeue_unlock(pq);
1111ebcddc72SAlan Cox 
1112b1fd102eSMark Johnston 	if (launder > 0 && pq == &vmd->vmd_pagequeues[PQ_UNSWAPPABLE]) {
1113b1fd102eSMark Johnston 		pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
1114b1fd102eSMark Johnston 		goto scan;
1115b1fd102eSMark Johnston 	}
1116b1fd102eSMark Johnston 
1117ebcddc72SAlan Cox 	/*
1118ebcddc72SAlan Cox 	 * Wakeup the sync daemon if we skipped a vnode in a writeable object
1119ebcddc72SAlan Cox 	 * and we didn't launder enough pages.
1120ebcddc72SAlan Cox 	 */
1121ebcddc72SAlan Cox 	if (vnodes_skipped > 0 && launder > 0)
1122ebcddc72SAlan Cox 		(void)speedup_syncer();
1123ebcddc72SAlan Cox 
1124ebcddc72SAlan Cox 	return (starting_target - launder);
1125ebcddc72SAlan Cox }
1126ebcddc72SAlan Cox 
1127ebcddc72SAlan Cox /*
1128ebcddc72SAlan Cox  * Compute the integer square root.
1129ebcddc72SAlan Cox  */
1130ebcddc72SAlan Cox static u_int
1131ebcddc72SAlan Cox isqrt(u_int num)
1132ebcddc72SAlan Cox {
1133ebcddc72SAlan Cox 	u_int bit, root, tmp;
1134ebcddc72SAlan Cox 
1135ebcddc72SAlan Cox 	bit = 1u << ((NBBY * sizeof(u_int)) - 2);
1136ebcddc72SAlan Cox 	while (bit > num)
1137ebcddc72SAlan Cox 		bit >>= 2;
1138ebcddc72SAlan Cox 	root = 0;
1139ebcddc72SAlan Cox 	while (bit != 0) {
1140ebcddc72SAlan Cox 		tmp = root + bit;
1141ebcddc72SAlan Cox 		root >>= 1;
1142ebcddc72SAlan Cox 		if (num >= tmp) {
1143ebcddc72SAlan Cox 			num -= tmp;
1144ebcddc72SAlan Cox 			root += bit;
1145ebcddc72SAlan Cox 		}
1146ebcddc72SAlan Cox 		bit >>= 2;
1147ebcddc72SAlan Cox 	}
1148ebcddc72SAlan Cox 	return (root);
1149ebcddc72SAlan Cox }
1150ebcddc72SAlan Cox 
1151ebcddc72SAlan Cox /*
1152ebcddc72SAlan Cox  * Perform the work of the laundry thread: periodically wake up and determine
1153ebcddc72SAlan Cox  * whether any pages need to be laundered.  If so, determine the number of pages
1154ebcddc72SAlan Cox  * that need to be laundered, and launder them.
1155ebcddc72SAlan Cox  */
1156ebcddc72SAlan Cox static void
1157ebcddc72SAlan Cox vm_pageout_laundry_worker(void *arg)
1158ebcddc72SAlan Cox {
1159ebcddc72SAlan Cox 	struct vm_domain *domain;
1160ebcddc72SAlan Cox 	struct vm_pagequeue *pq;
1161ebcddc72SAlan Cox 	uint64_t nclean, ndirty;
1162ebcddc72SAlan Cox 	u_int last_launder, wakeups;
1163ebcddc72SAlan Cox 	int domidx, last_target, launder, shortfall, shortfall_cycle, target;
1164ebcddc72SAlan Cox 	bool in_shortfall;
1165ebcddc72SAlan Cox 
1166ebcddc72SAlan Cox 	domidx = (uintptr_t)arg;
1167ebcddc72SAlan Cox 	domain = &vm_dom[domidx];
1168ebcddc72SAlan Cox 	pq = &domain->vmd_pagequeues[PQ_LAUNDRY];
1169ebcddc72SAlan Cox 	KASSERT(domain->vmd_segs != 0, ("domain without segments"));
1170ebcddc72SAlan Cox 	vm_pageout_init_marker(&domain->vmd_laundry_marker, PQ_LAUNDRY);
1171ebcddc72SAlan Cox 
1172ebcddc72SAlan Cox 	shortfall = 0;
1173ebcddc72SAlan Cox 	in_shortfall = false;
1174ebcddc72SAlan Cox 	shortfall_cycle = 0;
1175ebcddc72SAlan Cox 	target = 0;
1176ebcddc72SAlan Cox 	last_launder = 0;
1177ebcddc72SAlan Cox 
1178ebcddc72SAlan Cox 	/*
1179b1fd102eSMark Johnston 	 * Calls to these handlers are serialized by the swap syscall lock.
1180b1fd102eSMark Johnston 	 */
1181b1fd102eSMark Johnston 	(void)EVENTHANDLER_REGISTER(swapon, vm_pageout_swapon, domain,
1182b1fd102eSMark Johnston 	    EVENTHANDLER_PRI_ANY);
1183b1fd102eSMark Johnston 	(void)EVENTHANDLER_REGISTER(swapoff, vm_pageout_swapoff, domain,
1184b1fd102eSMark Johnston 	    EVENTHANDLER_PRI_ANY);
1185b1fd102eSMark Johnston 
1186b1fd102eSMark Johnston 	/*
1187ebcddc72SAlan Cox 	 * The pageout laundry worker is never done, so loop forever.
1188ebcddc72SAlan Cox 	 */
1189ebcddc72SAlan Cox 	for (;;) {
1190ebcddc72SAlan Cox 		KASSERT(target >= 0, ("negative target %d", target));
1191ebcddc72SAlan Cox 		KASSERT(shortfall_cycle >= 0,
1192ebcddc72SAlan Cox 		    ("negative cycle %d", shortfall_cycle));
1193ebcddc72SAlan Cox 		launder = 0;
119483c9dea1SGleb Smirnoff 		wakeups = VM_CNT_FETCH(v_pdwakeups);
1195ebcddc72SAlan Cox 
1196ebcddc72SAlan Cox 		/*
1197ebcddc72SAlan Cox 		 * First determine whether we need to launder pages to meet a
1198ebcddc72SAlan Cox 		 * shortage of free pages.
1199ebcddc72SAlan Cox 		 */
1200ebcddc72SAlan Cox 		if (shortfall > 0) {
1201ebcddc72SAlan Cox 			in_shortfall = true;
1202ebcddc72SAlan Cox 			shortfall_cycle = VM_LAUNDER_RATE / VM_INACT_SCAN_RATE;
1203ebcddc72SAlan Cox 			target = shortfall;
1204ebcddc72SAlan Cox 		} else if (!in_shortfall)
1205ebcddc72SAlan Cox 			goto trybackground;
1206ebcddc72SAlan Cox 		else if (shortfall_cycle == 0 || vm_laundry_target() <= 0) {
1207ebcddc72SAlan Cox 			/*
1208ebcddc72SAlan Cox 			 * We recently entered shortfall and began laundering
1209ebcddc72SAlan Cox 			 * pages.  If we have completed that laundering run
1210ebcddc72SAlan Cox 			 * (and we are no longer in shortfall) or we have met
1211ebcddc72SAlan Cox 			 * our laundry target through other activity, then we
1212ebcddc72SAlan Cox 			 * can stop laundering pages.
1213ebcddc72SAlan Cox 			 */
1214ebcddc72SAlan Cox 			in_shortfall = false;
1215ebcddc72SAlan Cox 			target = 0;
1216ebcddc72SAlan Cox 			goto trybackground;
1217ebcddc72SAlan Cox 		}
1218ebcddc72SAlan Cox 		last_launder = wakeups;
1219ebcddc72SAlan Cox 		launder = target / shortfall_cycle--;
1220ebcddc72SAlan Cox 		goto dolaundry;
1221ebcddc72SAlan Cox 
1222ebcddc72SAlan Cox 		/*
1223ebcddc72SAlan Cox 		 * There's no immediate need to launder any pages; see if we
1224ebcddc72SAlan Cox 		 * meet the conditions to perform background laundering:
1225ebcddc72SAlan Cox 		 *
1226ebcddc72SAlan Cox 		 * 1. The ratio of dirty to clean inactive pages exceeds the
1227ebcddc72SAlan Cox 		 *    background laundering threshold and the pagedaemon has
1228ebcddc72SAlan Cox 		 *    been woken up to reclaim pages since our last
1229ebcddc72SAlan Cox 		 *    laundering, or
1230ebcddc72SAlan Cox 		 * 2. we haven't yet reached the target of the current
1231ebcddc72SAlan Cox 		 *    background laundering run.
1232ebcddc72SAlan Cox 		 *
1233ebcddc72SAlan Cox 		 * The background laundering threshold is not a constant.
1234ebcddc72SAlan Cox 		 * Instead, it is a slowly growing function of the number of
1235ebcddc72SAlan Cox 		 * page daemon wakeups since the last laundering.  Thus, as the
1236ebcddc72SAlan Cox 		 * ratio of dirty to clean inactive pages grows, the amount of
1237ebcddc72SAlan Cox 		 * memory pressure required to trigger laundering decreases.
1238ebcddc72SAlan Cox 		 */
1239ebcddc72SAlan Cox trybackground:
1240ebcddc72SAlan Cox 		nclean = vm_cnt.v_inactive_count + vm_cnt.v_free_count;
1241ebcddc72SAlan Cox 		ndirty = vm_cnt.v_laundry_count;
1242ebcddc72SAlan Cox 		if (target == 0 && wakeups != last_launder &&
1243ebcddc72SAlan Cox 		    ndirty * isqrt(wakeups - last_launder) >= nclean) {
1244ebcddc72SAlan Cox 			target = vm_background_launder_target;
1245ebcddc72SAlan Cox 		}
1246ebcddc72SAlan Cox 
1247ebcddc72SAlan Cox 		/*
1248ebcddc72SAlan Cox 		 * We have a non-zero background laundering target.  If we've
1249ebcddc72SAlan Cox 		 * laundered up to our maximum without observing a page daemon
1250ebcddc72SAlan Cox 		 * wakeup, just stop.  This is a safety belt that ensures we
1251ebcddc72SAlan Cox 		 * don't launder an excessive amount if memory pressure is low
1252ebcddc72SAlan Cox 		 * and the ratio of dirty to clean pages is large.  Otherwise,
1253ebcddc72SAlan Cox 		 * proceed at the background laundering rate.
1254ebcddc72SAlan Cox 		 */
1255ebcddc72SAlan Cox 		if (target > 0) {
1256ebcddc72SAlan Cox 			if (wakeups != last_launder) {
1257ebcddc72SAlan Cox 				last_launder = wakeups;
1258ebcddc72SAlan Cox 				last_target = target;
1259ebcddc72SAlan Cox 			} else if (last_target - target >=
1260ebcddc72SAlan Cox 			    vm_background_launder_max * PAGE_SIZE / 1024) {
1261ebcddc72SAlan Cox 				target = 0;
1262ebcddc72SAlan Cox 			}
1263ebcddc72SAlan Cox 			launder = vm_background_launder_rate * PAGE_SIZE / 1024;
1264ebcddc72SAlan Cox 			launder /= VM_LAUNDER_RATE;
1265ebcddc72SAlan Cox 			if (launder > target)
1266ebcddc72SAlan Cox 				launder = target;
1267ebcddc72SAlan Cox 		}
1268ebcddc72SAlan Cox 
1269ebcddc72SAlan Cox dolaundry:
1270ebcddc72SAlan Cox 		if (launder > 0) {
1271ebcddc72SAlan Cox 			/*
1272ebcddc72SAlan Cox 			 * Because of I/O clustering, the number of laundered
1273ebcddc72SAlan Cox 			 * pages could exceed "target" by the maximum size of
1274ebcddc72SAlan Cox 			 * a cluster minus one.
1275ebcddc72SAlan Cox 			 */
1276ebcddc72SAlan Cox 			target -= min(vm_pageout_launder(domain, launder,
1277ebcddc72SAlan Cox 			    in_shortfall), target);
1278ebcddc72SAlan Cox 			pause("laundp", hz / VM_LAUNDER_RATE);
1279ebcddc72SAlan Cox 		}
1280ebcddc72SAlan Cox 
1281ebcddc72SAlan Cox 		/*
1282ebcddc72SAlan Cox 		 * If we're not currently laundering pages and the page daemon
1283ebcddc72SAlan Cox 		 * hasn't posted a new request, sleep until the page daemon
1284ebcddc72SAlan Cox 		 * kicks us.
1285ebcddc72SAlan Cox 		 */
1286ebcddc72SAlan Cox 		vm_pagequeue_lock(pq);
1287ebcddc72SAlan Cox 		if (target == 0 && vm_laundry_request == VM_LAUNDRY_IDLE)
1288ebcddc72SAlan Cox 			(void)mtx_sleep(&vm_laundry_request,
1289ebcddc72SAlan Cox 			    vm_pagequeue_lockptr(pq), PVM, "launds", 0);
1290ebcddc72SAlan Cox 
1291ebcddc72SAlan Cox 		/*
1292ebcddc72SAlan Cox 		 * If the pagedaemon has indicated that it's in shortfall, start
1293ebcddc72SAlan Cox 		 * a shortfall laundering unless we're already in the middle of
1294ebcddc72SAlan Cox 		 * one.  This may preempt a background laundering.
1295ebcddc72SAlan Cox 		 */
1296ebcddc72SAlan Cox 		if (vm_laundry_request == VM_LAUNDRY_SHORTFALL &&
1297ebcddc72SAlan Cox 		    (!in_shortfall || shortfall_cycle == 0)) {
1298ebcddc72SAlan Cox 			shortfall = vm_laundry_target() + vm_pageout_deficit;
1299ebcddc72SAlan Cox 			target = 0;
1300ebcddc72SAlan Cox 		} else
1301ebcddc72SAlan Cox 			shortfall = 0;
1302ebcddc72SAlan Cox 
1303ebcddc72SAlan Cox 		if (target == 0)
1304ebcddc72SAlan Cox 			vm_laundry_request = VM_LAUNDRY_IDLE;
1305ebcddc72SAlan Cox 		vm_pagequeue_unlock(pq);
1306ebcddc72SAlan Cox 	}
1307ebcddc72SAlan Cox }
1308ebcddc72SAlan Cox 
1309ebcddc72SAlan Cox /*
1310df8bae1dSRodney W. Grimes  *	vm_pageout_scan does the dirty work for the pageout daemon.
1311d9e23210SJeff Roberson  *
1312ebcddc72SAlan Cox  *	pass == 0: Update active LRU/deactivate pages
1313ebcddc72SAlan Cox  *	pass >= 1: Free inactive pages
1314e57dd910SAlan Cox  *
1315e57dd910SAlan Cox  * Returns true if pass was zero or enough pages were freed by the inactive
1316e57dd910SAlan Cox  * queue scan to meet the target.
1317df8bae1dSRodney W. Grimes  */
1318e57dd910SAlan Cox static bool
1319449c2e92SKonstantin Belousov vm_pageout_scan(struct vm_domain *vmd, int pass)
1320df8bae1dSRodney W. Grimes {
1321502ba6e4SJohn Dyson 	vm_page_t m, next;
13228d220203SAlan Cox 	struct vm_pagequeue *pq;
1323df8bae1dSRodney W. Grimes 	vm_object_t object;
132422cf98d1SAlan Cox 	long min_scan;
1325ebcddc72SAlan Cox 	int act_delta, addl_page_shortage, deficit, inactq_shortage, maxscan;
1326ebcddc72SAlan Cox 	int page_shortage, scan_tick, scanned, starting_page_shortage;
1327ebcddc72SAlan Cox 	boolean_t queue_locked;
13280d94caffSDavid Greenman 
1329df8bae1dSRodney W. Grimes 	/*
1330d9e23210SJeff Roberson 	 * If we need to reclaim memory ask kernel caches to return
1331c9612b2dSJeff Roberson 	 * some.  We rate limit to avoid thrashing.
1332d9e23210SJeff Roberson 	 */
1333c9612b2dSJeff Roberson 	if (vmd == &vm_dom[0] && pass > 0 &&
1334a6bf3a9eSRyan Stone 	    (time_uptime - lowmem_uptime) >= lowmem_period) {
1335d9e23210SJeff Roberson 		/*
1336855a310fSJeff Roberson 		 * Decrease registered cache sizes.
1337855a310fSJeff Roberson 		 */
133814a0d74eSSteven Hartland 		SDT_PROBE0(vm, , , vm__lowmem_scan);
13399b43bc27SAndriy Gapon 		EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_PAGES);
1340855a310fSJeff Roberson 		/*
1341d9e23210SJeff Roberson 		 * We do this explicitly after the caches have been
1342d9e23210SJeff Roberson 		 * drained above.
1343855a310fSJeff Roberson 		 */
1344855a310fSJeff Roberson 		uma_reclaim();
1345a6bf3a9eSRyan Stone 		lowmem_uptime = time_uptime;
1346d9e23210SJeff Roberson 	}
13475985940eSJohn Dyson 
1348311e34e2SKonstantin Belousov 	/*
134996240c89SEitan Adler 	 * The addl_page_shortage is the number of temporarily
1350311e34e2SKonstantin Belousov 	 * stuck pages in the inactive queue.  In other words, the
1351449c2e92SKonstantin Belousov 	 * number of pages from the inactive count that should be
1352311e34e2SKonstantin Belousov 	 * discounted in setting the target for the active queue scan.
1353311e34e2SKonstantin Belousov 	 */
13549099545aSAlan Cox 	addl_page_shortage = 0;
13559099545aSAlan Cox 
13561c7c3c6aSMatthew Dillon 	/*
1357e57dd910SAlan Cox 	 * Calculate the number of pages that we want to free.  This number
1358e57dd910SAlan Cox 	 * can be negative if many pages are freed between the wakeup call to
1359e57dd910SAlan Cox 	 * the page daemon and this calculation.
13601c7c3c6aSMatthew Dillon 	 */
136160196cdaSAlan Cox 	if (pass > 0) {
136260196cdaSAlan Cox 		deficit = atomic_readandclear_int(&vm_pageout_deficit);
13639099545aSAlan Cox 		page_shortage = vm_paging_target() + deficit;
136460196cdaSAlan Cox 	} else
136560196cdaSAlan Cox 		page_shortage = deficit = 0;
136676386c7eSKonstantin Belousov 	starting_page_shortage = page_shortage;
13671c7c3c6aSMatthew Dillon 
1368936524aaSMatthew Dillon 	/*
1369f095d1bbSAlan Cox 	 * Start scanning the inactive queue for pages that we can free.  The
1370f095d1bbSAlan Cox 	 * scan will stop when we reach the target or we have scanned the
1371f095d1bbSAlan Cox 	 * entire queue.  (Note that m->act_count is not used to make
1372f095d1bbSAlan Cox 	 * decisions for the inactive queue, only for the active queue.)
13738d220203SAlan Cox 	 */
1374449c2e92SKonstantin Belousov 	pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
1375449c2e92SKonstantin Belousov 	maxscan = pq->pq_cnt;
13768d220203SAlan Cox 	vm_pagequeue_lock(pq);
13773ac8f842SMark Johnston 	queue_locked = TRUE;
13788d220203SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl);
13791c7c3c6aSMatthew Dillon 	     m != NULL && maxscan-- > 0 && page_shortage > 0;
1380e929c00dSKirk McKusick 	     m = next) {
13818d220203SAlan Cox 		vm_pagequeue_assert_locked(pq);
13823ac8f842SMark Johnston 		KASSERT(queue_locked, ("unlocked inactive queue"));
1383ebcddc72SAlan Cox 		KASSERT(vm_page_inactive(m), ("Inactive queue %p", m));
1384df8bae1dSRodney W. Grimes 
138583c9dea1SGleb Smirnoff 		VM_CNT_INC(v_pdpages);
1386c325e866SKonstantin Belousov 		next = TAILQ_NEXT(m, plinks.q);
1387df8bae1dSRodney W. Grimes 
1388936524aaSMatthew Dillon 		/*
1389936524aaSMatthew Dillon 		 * skip marker pages
1390936524aaSMatthew Dillon 		 */
1391936524aaSMatthew Dillon 		if (m->flags & PG_MARKER)
1392936524aaSMatthew Dillon 			continue;
1393936524aaSMatthew Dillon 
13947900f95dSKonstantin Belousov 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
13957900f95dSKonstantin Belousov 		    ("Fictitious page %p cannot be in inactive queue", m));
13967900f95dSKonstantin Belousov 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
13977900f95dSKonstantin Belousov 		    ("Unmanaged page %p cannot be in inactive queue", m));
13987900f95dSKonstantin Belousov 
13998c616246SKonstantin Belousov 		/*
1400311e34e2SKonstantin Belousov 		 * The page or object lock acquisitions fail if the
1401311e34e2SKonstantin Belousov 		 * page was removed from the queue or moved to a
1402311e34e2SKonstantin Belousov 		 * different position within the queue.  In either
1403311e34e2SKonstantin Belousov 		 * case, addl_page_shortage should not be incremented.
14048c616246SKonstantin Belousov 		 */
1405a3aeedabSAlan Cox 		if (!vm_pageout_page_lock(m, &next))
1406a3aeedabSAlan Cox 			goto unlock_page;
1407a3aeedabSAlan Cox 		else if (m->hold_count != 0) {
1408a3aeedabSAlan Cox 			/*
1409a3aeedabSAlan Cox 			 * Held pages are essentially stuck in the
1410a3aeedabSAlan Cox 			 * queue.  So, they ought to be discounted
1411a3aeedabSAlan Cox 			 * from the inactive count.  See the
1412e57dd910SAlan Cox 			 * calculation of inactq_shortage before the
1413a3aeedabSAlan Cox 			 * loop over the active queue below.
1414a3aeedabSAlan Cox 			 */
1415a3aeedabSAlan Cox 			addl_page_shortage++;
1416a3aeedabSAlan Cox 			goto unlock_page;
1417df8bae1dSRodney W. Grimes 		}
14189ee2165fSAlan Cox 		object = m->object;
1419a3aeedabSAlan Cox 		if (!VM_OBJECT_TRYWLOCK(object)) {
1420a3aeedabSAlan Cox 			if (!vm_pageout_fallback_object_lock(m, &next))
1421a3aeedabSAlan Cox 				goto unlock_object;
1422a3aeedabSAlan Cox 			else if (m->hold_count != 0) {
1423b182ec9eSJohn Dyson 				addl_page_shortage++;
1424a3aeedabSAlan Cox 				goto unlock_object;
1425a3aeedabSAlan Cox 			}
1426a3aeedabSAlan Cox 		}
1427a3aeedabSAlan Cox 		if (vm_page_busied(m)) {
1428a3aeedabSAlan Cox 			/*
1429a3aeedabSAlan Cox 			 * Don't mess with busy pages.  Leave them at
1430a3aeedabSAlan Cox 			 * the front of the queue.  Most likely, they
1431a3aeedabSAlan Cox 			 * are being paged out and will leave the
1432a3aeedabSAlan Cox 			 * queue shortly after the scan finishes.  So,
1433a3aeedabSAlan Cox 			 * they ought to be discounted from the
1434a3aeedabSAlan Cox 			 * inactive count.
1435a3aeedabSAlan Cox 			 */
1436a3aeedabSAlan Cox 			addl_page_shortage++;
1437a3aeedabSAlan Cox unlock_object:
1438a3aeedabSAlan Cox 			VM_OBJECT_WUNLOCK(object);
1439a3aeedabSAlan Cox unlock_page:
1440a3aeedabSAlan Cox 			vm_page_unlock(m);
144126f9a767SRodney W. Grimes 			continue;
144226f9a767SRodney W. Grimes 		}
1443a3aeedabSAlan Cox 		KASSERT(m->hold_count == 0, ("Held page %p", m));
1444bd7e5f99SJohn Dyson 
14457e006499SJohn Dyson 		/*
1446ebcddc72SAlan Cox 		 * Dequeue the inactive page and unlock the inactive page
1447ebcddc72SAlan Cox 		 * queue, invalidating the 'next' pointer.  Dequeueing the
1448ebcddc72SAlan Cox 		 * page here avoids a later reacquisition (and release) of
1449ebcddc72SAlan Cox 		 * the inactive page queue lock when vm_page_activate(),
1450ebcddc72SAlan Cox 		 * vm_page_free(), or vm_page_launder() is called.  Use a
1451ebcddc72SAlan Cox 		 * marker to remember our place in the inactive queue.
145248cc2fc7SKonstantin Belousov 		 */
1453c325e866SKonstantin Belousov 		TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
1454ebcddc72SAlan Cox 		vm_page_dequeue_locked(m);
14558d220203SAlan Cox 		vm_pagequeue_unlock(pq);
14563ac8f842SMark Johnston 		queue_locked = FALSE;
145748cc2fc7SKonstantin Belousov 
145848cc2fc7SKonstantin Belousov 		/*
14598748f58cSKonstantin Belousov 		 * Invalid pages can be easily freed. They cannot be
14608748f58cSKonstantin Belousov 		 * mapped, vm_page_free() asserts this.
1461776f729cSKonstantin Belousov 		 */
14628748f58cSKonstantin Belousov 		if (m->valid == 0)
14638748f58cSKonstantin Belousov 			goto free_page;
1464776f729cSKonstantin Belousov 
1465776f729cSKonstantin Belousov 		/*
1466960810ccSAlan Cox 		 * If the page has been referenced and the object is not dead,
1467960810ccSAlan Cox 		 * reactivate or requeue the page depending on whether the
1468960810ccSAlan Cox 		 * object is mapped.
14697e006499SJohn Dyson 		 */
1470bb7858eaSJeff Roberson 		if ((m->aflags & PGA_REFERENCED) != 0) {
1471bb7858eaSJeff Roberson 			vm_page_aflag_clear(m, PGA_REFERENCED);
1472bb7858eaSJeff Roberson 			act_delta = 1;
147386fa2471SAlan Cox 		} else
147486fa2471SAlan Cox 			act_delta = 0;
1475bb7858eaSJeff Roberson 		if (object->ref_count != 0) {
1476bb7858eaSJeff Roberson 			act_delta += pmap_ts_referenced(m);
1477bb7858eaSJeff Roberson 		} else {
1478bb7858eaSJeff Roberson 			KASSERT(!pmap_page_is_mapped(m),
1479bb7858eaSJeff Roberson 			    ("vm_pageout_scan: page %p is mapped", m));
14802fe6e4d7SDavid Greenman 		}
1481bb7858eaSJeff Roberson 		if (act_delta != 0) {
148286fa2471SAlan Cox 			if (object->ref_count != 0) {
148383c9dea1SGleb Smirnoff 				VM_CNT_INC(v_reactivated);
148426f9a767SRodney W. Grimes 				vm_page_activate(m);
1485960810ccSAlan Cox 
1486960810ccSAlan Cox 				/*
1487960810ccSAlan Cox 				 * Increase the activation count if the page
1488960810ccSAlan Cox 				 * was referenced while in the inactive queue.
1489960810ccSAlan Cox 				 * This makes it less likely that the page will
1490960810ccSAlan Cox 				 * be returned prematurely to the inactive
1491960810ccSAlan Cox 				 * queue.
1492960810ccSAlan Cox  				 */
1493bb7858eaSJeff Roberson 				m->act_count += act_delta + ACT_ADVANCE;
1494960810ccSAlan Cox 				goto drop_page;
1495ebcddc72SAlan Cox 			} else if ((object->flags & OBJ_DEAD) == 0) {
1496ebcddc72SAlan Cox 				vm_pagequeue_lock(pq);
1497ebcddc72SAlan Cox 				queue_locked = TRUE;
1498ebcddc72SAlan Cox 				m->queue = PQ_INACTIVE;
1499ebcddc72SAlan Cox 				TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
1500ebcddc72SAlan Cox 				vm_pagequeue_cnt_inc(pq);
1501ebcddc72SAlan Cox 				goto drop_page;
1502ebcddc72SAlan Cox 			}
1503960810ccSAlan Cox 		}
150467bf6868SJohn Dyson 
15057e006499SJohn Dyson 		/*
15069fc4739dSAlan Cox 		 * If the page appears to be clean at the machine-independent
15079fc4739dSAlan Cox 		 * layer, then remove all of its mappings from the pmap in
1508a766ffd0SAlan Cox 		 * anticipation of freeing it.  If, however, any of the page's
1509a766ffd0SAlan Cox 		 * mappings allow write access, then the page may still be
1510a766ffd0SAlan Cox 		 * modified until the last of those mappings are removed.
15117e006499SJohn Dyson 		 */
1512aa044135SAlan Cox 		if (object->ref_count != 0) {
15139fc4739dSAlan Cox 			vm_page_test_dirty(m);
1514aa044135SAlan Cox 			if (m->dirty == 0)
1515b78ddb0bSAlan Cox 				pmap_remove_all(m);
1516aa044135SAlan Cox 		}
1517dcbcd518SBruce Evans 
15186989c456SAlan Cox 		/*
1519ebcddc72SAlan Cox 		 * Clean pages can be freed, but dirty pages must be sent back
1520ebcddc72SAlan Cox 		 * to the laundry, unless they belong to a dead object.
1521ebcddc72SAlan Cox 		 * Requeueing dirty pages from dead objects is pointless, as
1522ebcddc72SAlan Cox 		 * they are being paged out and freed by the thread that
1523ebcddc72SAlan Cox 		 * destroyed the object.
15246989c456SAlan Cox 		 */
1525ebcddc72SAlan Cox 		if (m->dirty == 0) {
15268748f58cSKonstantin Belousov free_page:
152778afdce6SAlan Cox 			vm_page_free(m);
152883c9dea1SGleb Smirnoff 			VM_CNT_INC(v_dfree);
15291c7c3c6aSMatthew Dillon 			--page_shortage;
1530ebcddc72SAlan Cox 		} else if ((object->flags & OBJ_DEAD) == 0)
1531ebcddc72SAlan Cox 			vm_page_launder(m);
1532776f729cSKonstantin Belousov drop_page:
153348cc2fc7SKonstantin Belousov 		vm_page_unlock(m);
153489f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
15353ac8f842SMark Johnston 		if (!queue_locked) {
15368d220203SAlan Cox 			vm_pagequeue_lock(pq);
15373ac8f842SMark Johnston 			queue_locked = TRUE;
15386989c456SAlan Cox 		}
1539c325e866SKonstantin Belousov 		next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1540c325e866SKonstantin Belousov 		TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
15410d94caffSDavid Greenman 	}
15428d220203SAlan Cox 	vm_pagequeue_unlock(pq);
154326f9a767SRodney W. Grimes 
1544ebcddc72SAlan Cox 	/*
1545ebcddc72SAlan Cox 	 * Wake up the laundry thread so that it can perform any needed
1546ebcddc72SAlan Cox 	 * laundering.  If we didn't meet our target, we're in shortfall and
1547b1fd102eSMark Johnston 	 * need to launder more aggressively.  If PQ_LAUNDRY is empty and no
1548b1fd102eSMark Johnston 	 * swap devices are configured, the laundry thread has no work to do, so
1549b1fd102eSMark Johnston 	 * don't bother waking it up.
1550ebcddc72SAlan Cox 	 */
1551ebcddc72SAlan Cox 	if (vm_laundry_request == VM_LAUNDRY_IDLE &&
1552ebcddc72SAlan Cox 	    starting_page_shortage > 0) {
1553ebcddc72SAlan Cox 		pq = &vm_dom[0].vmd_pagequeues[PQ_LAUNDRY];
1554ebcddc72SAlan Cox 		vm_pagequeue_lock(pq);
1555b1fd102eSMark Johnston 		if (pq->pq_cnt > 0 || atomic_load_acq_int(&swapdev_enabled)) {
1556ebcddc72SAlan Cox 			if (page_shortage > 0) {
1557ebcddc72SAlan Cox 				vm_laundry_request = VM_LAUNDRY_SHORTFALL;
155883c9dea1SGleb Smirnoff 				VM_CNT_INC(v_pdshortfalls);
1559ebcddc72SAlan Cox 			} else if (vm_laundry_request != VM_LAUNDRY_SHORTFALL)
1560ebcddc72SAlan Cox 				vm_laundry_request = VM_LAUNDRY_BACKGROUND;
1561ebcddc72SAlan Cox 			wakeup(&vm_laundry_request);
1562b1fd102eSMark Johnston 		}
1563ebcddc72SAlan Cox 		vm_pagequeue_unlock(pq);
1564ebcddc72SAlan Cox 	}
1565ebcddc72SAlan Cox 
15669452b5edSAlan Cox #if !defined(NO_SWAPPING)
15679452b5edSAlan Cox 	/*
1568f095d1bbSAlan Cox 	 * Wakeup the swapout daemon if we didn't free the targeted number of
1569f095d1bbSAlan Cox 	 * pages.
15709452b5edSAlan Cox 	 */
15719452b5edSAlan Cox 	if (vm_swap_enabled && page_shortage > 0)
15729452b5edSAlan Cox 		vm_req_vmdaemon(VM_SWAP_NORMAL);
15739452b5edSAlan Cox #endif
15749452b5edSAlan Cox 
15759452b5edSAlan Cox 	/*
157676386c7eSKonstantin Belousov 	 * If the inactive queue scan fails repeatedly to meet its
157776386c7eSKonstantin Belousov 	 * target, kill the largest process.
157876386c7eSKonstantin Belousov 	 */
157976386c7eSKonstantin Belousov 	vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
158076386c7eSKonstantin Belousov 
158176386c7eSKonstantin Belousov 	/*
1582936524aaSMatthew Dillon 	 * Compute the number of pages we want to try to move from the
1583ebcddc72SAlan Cox 	 * active queue to either the inactive or laundry queue.
1584ebcddc72SAlan Cox 	 *
1585ebcddc72SAlan Cox 	 * When scanning active pages, we make clean pages count more heavily
1586ebcddc72SAlan Cox 	 * towards the page shortage than dirty pages.  This is because dirty
1587ebcddc72SAlan Cox 	 * pages must be laundered before they can be reused and thus have less
1588ebcddc72SAlan Cox 	 * utility when attempting to quickly alleviate a shortage.  However,
1589ebcddc72SAlan Cox 	 * this weighting also causes the scan to deactivate dirty pages more
1590ebcddc72SAlan Cox 	 * more aggressively, improving the effectiveness of clustering and
1591ebcddc72SAlan Cox 	 * ensuring that they can eventually be reused.
15921c7c3c6aSMatthew Dillon 	 */
1593ebcddc72SAlan Cox 	inactq_shortage = vm_cnt.v_inactive_target - (vm_cnt.v_inactive_count +
1594ebcddc72SAlan Cox 	    vm_cnt.v_laundry_count / act_scan_laundry_weight) +
15959099545aSAlan Cox 	    vm_paging_target() + deficit + addl_page_shortage;
1596ebcddc72SAlan Cox 	page_shortage *= act_scan_laundry_weight;
15979099545aSAlan Cox 
1598114f62c6SJeff Roberson 	pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1599114f62c6SJeff Roberson 	vm_pagequeue_lock(pq);
16009099545aSAlan Cox 	maxscan = pq->pq_cnt;
16019099545aSAlan Cox 
1602d9e23210SJeff Roberson 	/*
1603d9e23210SJeff Roberson 	 * If we're just idle polling attempt to visit every
1604d9e23210SJeff Roberson 	 * active page within 'update_period' seconds.
1605d9e23210SJeff Roberson 	 */
160622cf98d1SAlan Cox 	scan_tick = ticks;
160722cf98d1SAlan Cox 	if (vm_pageout_update_period != 0) {
160822cf98d1SAlan Cox 		min_scan = pq->pq_cnt;
160922cf98d1SAlan Cox 		min_scan *= scan_tick - vmd->vmd_last_active_scan;
161022cf98d1SAlan Cox 		min_scan /= hz * vm_pageout_update_period;
161122cf98d1SAlan Cox 	} else
161222cf98d1SAlan Cox 		min_scan = 0;
1613e57dd910SAlan Cox 	if (min_scan > 0 || (inactq_shortage > 0 && maxscan > 0))
161422cf98d1SAlan Cox 		vmd->vmd_last_active_scan = scan_tick;
16151c7c3c6aSMatthew Dillon 
16161c7c3c6aSMatthew Dillon 	/*
161722cf98d1SAlan Cox 	 * Scan the active queue for pages that can be deactivated.  Update
161822cf98d1SAlan Cox 	 * the per-page activity counter and use it to identify deactivation
161979144408SAlan Cox 	 * candidates.  Held pages may be deactivated.
16201c7c3c6aSMatthew Dillon 	 */
162122cf98d1SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
1622e57dd910SAlan Cox 	    min_scan || (inactq_shortage > 0 && scanned < maxscan)); m = next,
162322cf98d1SAlan Cox 	    scanned++) {
16249cf51988SAlan Cox 		KASSERT(m->queue == PQ_ACTIVE,
1625d3c09dd7SAlan Cox 		    ("vm_pageout_scan: page %p isn't active", m));
1626c325e866SKonstantin Belousov 		next = TAILQ_NEXT(m, plinks.q);
162722cf98d1SAlan Cox 		if ((m->flags & PG_MARKER) != 0)
16288dbca793STor Egge 			continue;
16297900f95dSKonstantin Belousov 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
16307900f95dSKonstantin Belousov 		    ("Fictitious page %p cannot be in active queue", m));
16317900f95dSKonstantin Belousov 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
16327900f95dSKonstantin Belousov 		    ("Unmanaged page %p cannot be in active queue", m));
16339ee2165fSAlan Cox 		if (!vm_pageout_page_lock(m, &next)) {
16348c616246SKonstantin Belousov 			vm_page_unlock(m);
16352965a453SKip Macy 			continue;
16362965a453SKip Macy 		}
1637b18bfc3dSJohn Dyson 
1638b18bfc3dSJohn Dyson 		/*
163979144408SAlan Cox 		 * The count for page daemon pages is updated after checking
164079144408SAlan Cox 		 * the page for eligibility.
1641b18bfc3dSJohn Dyson 		 */
164283c9dea1SGleb Smirnoff 		VM_CNT_INC(v_pdpages);
1643ef743ce6SJohn Dyson 
16447e006499SJohn Dyson 		/*
16457e006499SJohn Dyson 		 * Check to see "how much" the page has been used.
16467e006499SJohn Dyson 		 */
164786fa2471SAlan Cox 		if ((m->aflags & PGA_REFERENCED) != 0) {
1648bb7858eaSJeff Roberson 			vm_page_aflag_clear(m, PGA_REFERENCED);
164986fa2471SAlan Cox 			act_delta = 1;
165086fa2471SAlan Cox 		} else
165186fa2471SAlan Cox 			act_delta = 0;
165286fa2471SAlan Cox 
1653274132acSJeff Roberson 		/*
165479144408SAlan Cox 		 * Perform an unsynchronized object ref count check.  While
165579144408SAlan Cox 		 * the page lock ensures that the page is not reallocated to
165679144408SAlan Cox 		 * another object, in particular, one with unmanaged mappings
165779144408SAlan Cox 		 * that cannot support pmap_ts_referenced(), two races are,
165879144408SAlan Cox 		 * nonetheless, possible:
165979144408SAlan Cox 		 * 1) The count was transitioning to zero, but we saw a non-
166079144408SAlan Cox 		 *    zero value.  pmap_ts_referenced() will return zero
166179144408SAlan Cox 		 *    because the page is not mapped.
166279144408SAlan Cox 		 * 2) The count was transitioning to one, but we saw zero.
166379144408SAlan Cox 		 *    This race delays the detection of a new reference.  At
166479144408SAlan Cox 		 *    worst, we will deactivate and reactivate the page.
1665274132acSJeff Roberson 		 */
1666274132acSJeff Roberson 		if (m->object->ref_count != 0)
1667bb7858eaSJeff Roberson 			act_delta += pmap_ts_referenced(m);
1668bb7858eaSJeff Roberson 
1669bb7858eaSJeff Roberson 		/*
1670bb7858eaSJeff Roberson 		 * Advance or decay the act_count based on recent usage.
1671bb7858eaSJeff Roberson 		 */
167286fa2471SAlan Cox 		if (act_delta != 0) {
1673bb7858eaSJeff Roberson 			m->act_count += ACT_ADVANCE + act_delta;
167438efa82bSJohn Dyson 			if (m->act_count > ACT_MAX)
167538efa82bSJohn Dyson 				m->act_count = ACT_MAX;
167686fa2471SAlan Cox 		} else
167738efa82bSJohn Dyson 			m->act_count -= min(m->act_count, ACT_DECLINE);
1678bb7858eaSJeff Roberson 
1679bb7858eaSJeff Roberson 		/*
1680ebcddc72SAlan Cox 		 * Move this page to the tail of the active, inactive or laundry
1681bb7858eaSJeff Roberson 		 * queue depending on usage.
1682bb7858eaSJeff Roberson 		 */
168386fa2471SAlan Cox 		if (m->act_count == 0) {
16848d220203SAlan Cox 			/* Dequeue to avoid later lock recursion. */
16858d220203SAlan Cox 			vm_page_dequeue_locked(m);
1686ebcddc72SAlan Cox 
1687ebcddc72SAlan Cox 			/*
1688ebcddc72SAlan Cox 			 * When not short for inactive pages, let dirty pages go
1689ebcddc72SAlan Cox 			 * through the inactive queue before moving to the
1690ebcddc72SAlan Cox 			 * laundry queues.  This gives them some extra time to
1691ebcddc72SAlan Cox 			 * be reactivated, potentially avoiding an expensive
1692ebcddc72SAlan Cox 			 * pageout.  During a page shortage, the inactive queue
1693ebcddc72SAlan Cox 			 * is necessarily small, so we may move dirty pages
1694ebcddc72SAlan Cox 			 * directly to the laundry queue.
1695ebcddc72SAlan Cox 			 */
1696ebcddc72SAlan Cox 			if (inactq_shortage <= 0)
1697d4a272dbSJohn Dyson 				vm_page_deactivate(m);
1698ebcddc72SAlan Cox 			else {
1699ebcddc72SAlan Cox 				/*
1700ebcddc72SAlan Cox 				 * Calling vm_page_test_dirty() here would
1701ebcddc72SAlan Cox 				 * require acquisition of the object's write
1702ebcddc72SAlan Cox 				 * lock.  However, during a page shortage,
1703ebcddc72SAlan Cox 				 * directing dirty pages into the laundry
1704ebcddc72SAlan Cox 				 * queue is only an optimization and not a
1705ebcddc72SAlan Cox 				 * requirement.  Therefore, we simply rely on
1706ebcddc72SAlan Cox 				 * the opportunistic updates to the page's
1707ebcddc72SAlan Cox 				 * dirty field by the pmap.
1708ebcddc72SAlan Cox 				 */
1709ebcddc72SAlan Cox 				if (m->dirty == 0) {
1710ebcddc72SAlan Cox 					vm_page_deactivate(m);
1711ebcddc72SAlan Cox 					inactq_shortage -=
1712ebcddc72SAlan Cox 					    act_scan_laundry_weight;
1713ebcddc72SAlan Cox 				} else {
1714ebcddc72SAlan Cox 					vm_page_launder(m);
1715e57dd910SAlan Cox 					inactq_shortage--;
1716ebcddc72SAlan Cox 				}
1717ebcddc72SAlan Cox 			}
17188d220203SAlan Cox 		} else
17198d220203SAlan Cox 			vm_page_requeue_locked(m);
17202965a453SKip Macy 		vm_page_unlock(m);
172126f9a767SRodney W. Grimes 	}
17228d220203SAlan Cox 	vm_pagequeue_unlock(pq);
1723ceb0cf87SJohn Dyson #if !defined(NO_SWAPPING)
1724ceb0cf87SJohn Dyson 	/*
172587ff568cSAlan Cox 	 * Idle process swapout -- run once per second when we are reclaiming
172687ff568cSAlan Cox 	 * pages.
1727ceb0cf87SJohn Dyson 	 */
172887ff568cSAlan Cox 	if (vm_swap_idle_enabled && pass > 0) {
1729ceb0cf87SJohn Dyson 		static long lsec;
1730227ee8a1SPoul-Henning Kamp 		if (time_second != lsec) {
173197824da3SAlan Cox 			vm_req_vmdaemon(VM_SWAP_IDLE);
1732227ee8a1SPoul-Henning Kamp 			lsec = time_second;
1733ceb0cf87SJohn Dyson 		}
1734ceb0cf87SJohn Dyson 	}
1735ceb0cf87SJohn Dyson #endif
1736e57dd910SAlan Cox 	return (page_shortage <= 0);
17372025d69bSKonstantin Belousov }
17382025d69bSKonstantin Belousov 
1739449c2e92SKonstantin Belousov static int vm_pageout_oom_vote;
1740449c2e92SKonstantin Belousov 
1741449c2e92SKonstantin Belousov /*
1742449c2e92SKonstantin Belousov  * The pagedaemon threads randlomly select one to perform the
1743449c2e92SKonstantin Belousov  * OOM.  Trying to kill processes before all pagedaemons
1744449c2e92SKonstantin Belousov  * failed to reach free target is premature.
1745449c2e92SKonstantin Belousov  */
1746449c2e92SKonstantin Belousov static void
174776386c7eSKonstantin Belousov vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
174876386c7eSKonstantin Belousov     int starting_page_shortage)
1749449c2e92SKonstantin Belousov {
1750449c2e92SKonstantin Belousov 	int old_vote;
1751449c2e92SKonstantin Belousov 
175276386c7eSKonstantin Belousov 	if (starting_page_shortage <= 0 || starting_page_shortage !=
175376386c7eSKonstantin Belousov 	    page_shortage)
175476386c7eSKonstantin Belousov 		vmd->vmd_oom_seq = 0;
175576386c7eSKonstantin Belousov 	else
175676386c7eSKonstantin Belousov 		vmd->vmd_oom_seq++;
175776386c7eSKonstantin Belousov 	if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1758449c2e92SKonstantin Belousov 		if (vmd->vmd_oom) {
1759449c2e92SKonstantin Belousov 			vmd->vmd_oom = FALSE;
1760449c2e92SKonstantin Belousov 			atomic_subtract_int(&vm_pageout_oom_vote, 1);
1761449c2e92SKonstantin Belousov 		}
1762449c2e92SKonstantin Belousov 		return;
1763449c2e92SKonstantin Belousov 	}
1764449c2e92SKonstantin Belousov 
176576386c7eSKonstantin Belousov 	/*
176676386c7eSKonstantin Belousov 	 * Do not follow the call sequence until OOM condition is
176776386c7eSKonstantin Belousov 	 * cleared.
176876386c7eSKonstantin Belousov 	 */
176976386c7eSKonstantin Belousov 	vmd->vmd_oom_seq = 0;
177076386c7eSKonstantin Belousov 
1771449c2e92SKonstantin Belousov 	if (vmd->vmd_oom)
1772449c2e92SKonstantin Belousov 		return;
1773449c2e92SKonstantin Belousov 
1774449c2e92SKonstantin Belousov 	vmd->vmd_oom = TRUE;
1775449c2e92SKonstantin Belousov 	old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1776449c2e92SKonstantin Belousov 	if (old_vote != vm_ndomains - 1)
1777449c2e92SKonstantin Belousov 		return;
1778449c2e92SKonstantin Belousov 
1779449c2e92SKonstantin Belousov 	/*
1780449c2e92SKonstantin Belousov 	 * The current pagedaemon thread is the last in the quorum to
1781449c2e92SKonstantin Belousov 	 * start OOM.  Initiate the selection and signaling of the
1782449c2e92SKonstantin Belousov 	 * victim.
1783449c2e92SKonstantin Belousov 	 */
1784449c2e92SKonstantin Belousov 	vm_pageout_oom(VM_OOM_MEM);
1785449c2e92SKonstantin Belousov 
1786449c2e92SKonstantin Belousov 	/*
1787449c2e92SKonstantin Belousov 	 * After one round of OOM terror, recall our vote.  On the
1788449c2e92SKonstantin Belousov 	 * next pass, current pagedaemon would vote again if the low
1789449c2e92SKonstantin Belousov 	 * memory condition is still there, due to vmd_oom being
1790449c2e92SKonstantin Belousov 	 * false.
1791449c2e92SKonstantin Belousov 	 */
1792449c2e92SKonstantin Belousov 	vmd->vmd_oom = FALSE;
1793449c2e92SKonstantin Belousov 	atomic_subtract_int(&vm_pageout_oom_vote, 1);
1794449c2e92SKonstantin Belousov }
17952025d69bSKonstantin Belousov 
17963949873fSKonstantin Belousov /*
17973949873fSKonstantin Belousov  * The OOM killer is the page daemon's action of last resort when
17983949873fSKonstantin Belousov  * memory allocation requests have been stalled for a prolonged period
17993949873fSKonstantin Belousov  * of time because it cannot reclaim memory.  This function computes
18003949873fSKonstantin Belousov  * the approximate number of physical pages that could be reclaimed if
18013949873fSKonstantin Belousov  * the specified address space is destroyed.
18023949873fSKonstantin Belousov  *
18033949873fSKonstantin Belousov  * Private, anonymous memory owned by the address space is the
18043949873fSKonstantin Belousov  * principal resource that we expect to recover after an OOM kill.
18053949873fSKonstantin Belousov  * Since the physical pages mapped by the address space's COW entries
18063949873fSKonstantin Belousov  * are typically shared pages, they are unlikely to be released and so
18073949873fSKonstantin Belousov  * they are not counted.
18083949873fSKonstantin Belousov  *
18093949873fSKonstantin Belousov  * To get to the point where the page daemon runs the OOM killer, its
18103949873fSKonstantin Belousov  * efforts to write-back vnode-backed pages may have stalled.  This
18113949873fSKonstantin Belousov  * could be caused by a memory allocation deadlock in the write path
18123949873fSKonstantin Belousov  * that might be resolved by an OOM kill.  Therefore, physical pages
18133949873fSKonstantin Belousov  * belonging to vnode-backed objects are counted, because they might
18143949873fSKonstantin Belousov  * be freed without being written out first if the address space holds
18153949873fSKonstantin Belousov  * the last reference to an unlinked vnode.
18163949873fSKonstantin Belousov  *
18173949873fSKonstantin Belousov  * Similarly, physical pages belonging to OBJT_PHYS objects are
18183949873fSKonstantin Belousov  * counted because the address space might hold the last reference to
18193949873fSKonstantin Belousov  * the object.
18203949873fSKonstantin Belousov  */
18213949873fSKonstantin Belousov static long
18223949873fSKonstantin Belousov vm_pageout_oom_pagecount(struct vmspace *vmspace)
18233949873fSKonstantin Belousov {
18243949873fSKonstantin Belousov 	vm_map_t map;
18253949873fSKonstantin Belousov 	vm_map_entry_t entry;
18263949873fSKonstantin Belousov 	vm_object_t obj;
18273949873fSKonstantin Belousov 	long res;
18283949873fSKonstantin Belousov 
18293949873fSKonstantin Belousov 	map = &vmspace->vm_map;
18303949873fSKonstantin Belousov 	KASSERT(!map->system_map, ("system map"));
18313949873fSKonstantin Belousov 	sx_assert(&map->lock, SA_LOCKED);
18323949873fSKonstantin Belousov 	res = 0;
18333949873fSKonstantin Belousov 	for (entry = map->header.next; entry != &map->header;
18343949873fSKonstantin Belousov 	    entry = entry->next) {
18353949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
18363949873fSKonstantin Belousov 			continue;
18373949873fSKonstantin Belousov 		obj = entry->object.vm_object;
18383949873fSKonstantin Belousov 		if (obj == NULL)
18393949873fSKonstantin Belousov 			continue;
18403949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
18413949873fSKonstantin Belousov 		    obj->ref_count != 1)
18423949873fSKonstantin Belousov 			continue;
18433949873fSKonstantin Belousov 		switch (obj->type) {
18443949873fSKonstantin Belousov 		case OBJT_DEFAULT:
18453949873fSKonstantin Belousov 		case OBJT_SWAP:
18463949873fSKonstantin Belousov 		case OBJT_PHYS:
18473949873fSKonstantin Belousov 		case OBJT_VNODE:
18483949873fSKonstantin Belousov 			res += obj->resident_page_count;
18493949873fSKonstantin Belousov 			break;
18503949873fSKonstantin Belousov 		}
18513949873fSKonstantin Belousov 	}
18523949873fSKonstantin Belousov 	return (res);
18533949873fSKonstantin Belousov }
18543949873fSKonstantin Belousov 
18552025d69bSKonstantin Belousov void
18562025d69bSKonstantin Belousov vm_pageout_oom(int shortage)
18572025d69bSKonstantin Belousov {
18582025d69bSKonstantin Belousov 	struct proc *p, *bigproc;
18592025d69bSKonstantin Belousov 	vm_offset_t size, bigsize;
18602025d69bSKonstantin Belousov 	struct thread *td;
18616bed074cSKonstantin Belousov 	struct vmspace *vm;
18623e78e983SAlan Cox 	bool breakout;
18632025d69bSKonstantin Belousov 
18642025d69bSKonstantin Belousov 	/*
18651c58e4e5SJohn Baldwin 	 * We keep the process bigproc locked once we find it to keep anyone
18661c58e4e5SJohn Baldwin 	 * from messing with it; however, there is a possibility of
186728323addSBryan Drewery 	 * deadlock if process B is bigproc and one of its child processes
18681c58e4e5SJohn Baldwin 	 * attempts to propagate a signal to B while we are waiting for A's
18691c58e4e5SJohn Baldwin 	 * lock while walking this list.  To avoid this, we don't block on
18701c58e4e5SJohn Baldwin 	 * the process lock but just skip a process if it is already locked.
18715663e6deSDavid Greenman 	 */
18725663e6deSDavid Greenman 	bigproc = NULL;
18735663e6deSDavid Greenman 	bigsize = 0;
18741005a129SJohn Baldwin 	sx_slock(&allproc_lock);
1875e602ba25SJulian Elischer 	FOREACH_PROC_IN_SYSTEM(p) {
187671943c3dSKonstantin Belousov 		PROC_LOCK(p);
187771943c3dSKonstantin Belousov 
18781c58e4e5SJohn Baldwin 		/*
18793f1c4c4fSKonstantin Belousov 		 * If this is a system, protected or killed process, skip it.
18805663e6deSDavid Greenman 		 */
188171943c3dSKonstantin Belousov 		if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
188271943c3dSKonstantin Belousov 		    P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
188371943c3dSKonstantin Belousov 		    p->p_pid == 1 || P_KILLED(p) ||
188471943c3dSKonstantin Belousov 		    (p->p_pid < 48 && swap_pager_avail != 0)) {
18858606d880SJohn Baldwin 			PROC_UNLOCK(p);
18865663e6deSDavid Greenman 			continue;
18875663e6deSDavid Greenman 		}
18885663e6deSDavid Greenman 		/*
1889dcbcd518SBruce Evans 		 * If the process is in a non-running type state,
1890e602ba25SJulian Elischer 		 * don't touch it.  Check all the threads individually.
18915663e6deSDavid Greenman 		 */
18923e78e983SAlan Cox 		breakout = false;
1893e602ba25SJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td) {
1894982d11f8SJeff Roberson 			thread_lock(td);
189571fad9fdSJulian Elischer 			if (!TD_ON_RUNQ(td) &&
189671fad9fdSJulian Elischer 			    !TD_IS_RUNNING(td) &&
1897f497cda2SEdward Tomasz Napierala 			    !TD_IS_SLEEPING(td) &&
1898b98acc0aSKonstantin Belousov 			    !TD_IS_SUSPENDED(td) &&
1899b98acc0aSKonstantin Belousov 			    !TD_IS_SWAPPED(td)) {
1900982d11f8SJeff Roberson 				thread_unlock(td);
19013e78e983SAlan Cox 				breakout = true;
1902e602ba25SJulian Elischer 				break;
1903e602ba25SJulian Elischer 			}
1904982d11f8SJeff Roberson 			thread_unlock(td);
1905e602ba25SJulian Elischer 		}
1906e602ba25SJulian Elischer 		if (breakout) {
19071c58e4e5SJohn Baldwin 			PROC_UNLOCK(p);
19085663e6deSDavid Greenman 			continue;
19095663e6deSDavid Greenman 		}
19105663e6deSDavid Greenman 		/*
19115663e6deSDavid Greenman 		 * get the process size
19125663e6deSDavid Greenman 		 */
19136bed074cSKonstantin Belousov 		vm = vmspace_acquire_ref(p);
19146bed074cSKonstantin Belousov 		if (vm == NULL) {
19156bed074cSKonstantin Belousov 			PROC_UNLOCK(p);
19166bed074cSKonstantin Belousov 			continue;
19176bed074cSKonstantin Belousov 		}
191895e2409aSKonstantin Belousov 		_PHOLD_LITE(p);
191972d97679SDavid Schultz 		PROC_UNLOCK(p);
192095e2409aSKonstantin Belousov 		sx_sunlock(&allproc_lock);
192195e2409aSKonstantin Belousov 		if (!vm_map_trylock_read(&vm->vm_map)) {
192271943c3dSKonstantin Belousov 			vmspace_free(vm);
192395e2409aSKonstantin Belousov 			sx_slock(&allproc_lock);
192495e2409aSKonstantin Belousov 			PRELE(p);
192572d97679SDavid Schultz 			continue;
192672d97679SDavid Schultz 		}
19277981aa24SKonstantin Belousov 		size = vmspace_swap_count(vm);
19282025d69bSKonstantin Belousov 		if (shortage == VM_OOM_MEM)
19293949873fSKonstantin Belousov 			size += vm_pageout_oom_pagecount(vm);
19303949873fSKonstantin Belousov 		vm_map_unlock_read(&vm->vm_map);
19316bed074cSKonstantin Belousov 		vmspace_free(vm);
193295e2409aSKonstantin Belousov 		sx_slock(&allproc_lock);
19333949873fSKonstantin Belousov 
19345663e6deSDavid Greenman 		/*
19353949873fSKonstantin Belousov 		 * If this process is bigger than the biggest one,
19365663e6deSDavid Greenman 		 * remember it.
19375663e6deSDavid Greenman 		 */
19385663e6deSDavid Greenman 		if (size > bigsize) {
19391c58e4e5SJohn Baldwin 			if (bigproc != NULL)
194071943c3dSKonstantin Belousov 				PRELE(bigproc);
19415663e6deSDavid Greenman 			bigproc = p;
19425663e6deSDavid Greenman 			bigsize = size;
194371943c3dSKonstantin Belousov 		} else {
194471943c3dSKonstantin Belousov 			PRELE(p);
194571943c3dSKonstantin Belousov 		}
19465663e6deSDavid Greenman 	}
19471005a129SJohn Baldwin 	sx_sunlock(&allproc_lock);
19485663e6deSDavid Greenman 	if (bigproc != NULL) {
19498311a2b8SWill Andrews 		if (vm_panic_on_oom != 0)
19508311a2b8SWill Andrews 			panic("out of swap space");
195171943c3dSKonstantin Belousov 		PROC_LOCK(bigproc);
1952729b1e51SDavid Greenman 		killproc(bigproc, "out of swap space");
1953fa885116SJulian Elischer 		sched_nice(bigproc, PRIO_MIN);
195471943c3dSKonstantin Belousov 		_PRELE(bigproc);
19551c58e4e5SJohn Baldwin 		PROC_UNLOCK(bigproc);
195644f1c916SBryan Drewery 		wakeup(&vm_cnt.v_free_count);
19575663e6deSDavid Greenman 	}
19585663e6deSDavid Greenman }
195926f9a767SRodney W. Grimes 
1960449c2e92SKonstantin Belousov static void
1961449c2e92SKonstantin Belousov vm_pageout_worker(void *arg)
1962449c2e92SKonstantin Belousov {
1963449c2e92SKonstantin Belousov 	struct vm_domain *domain;
196470cf3cedSAlan Cox 	int domidx, pass;
1965e57dd910SAlan Cox 	bool target_met;
1966449c2e92SKonstantin Belousov 
1967449c2e92SKonstantin Belousov 	domidx = (uintptr_t)arg;
1968449c2e92SKonstantin Belousov 	domain = &vm_dom[domidx];
196970cf3cedSAlan Cox 	pass = 0;
1970e57dd910SAlan Cox 	target_met = true;
1971449c2e92SKonstantin Belousov 
1972449c2e92SKonstantin Belousov 	/*
1973949c9186SKonstantin Belousov 	 * XXXKIB It could be useful to bind pageout daemon threads to
1974949c9186SKonstantin Belousov 	 * the cores belonging to the domain, from which vm_page_array
1975949c9186SKonstantin Belousov 	 * is allocated.
1976449c2e92SKonstantin Belousov 	 */
1977449c2e92SKonstantin Belousov 
1978449c2e92SKonstantin Belousov 	KASSERT(domain->vmd_segs != 0, ("domain without segments"));
197922cf98d1SAlan Cox 	domain->vmd_last_active_scan = ticks;
1980449c2e92SKonstantin Belousov 	vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
19817e78597fSMark Johnston 	vm_pageout_init_marker(&domain->vmd_inacthead, PQ_INACTIVE);
19827e78597fSMark Johnston 	TAILQ_INSERT_HEAD(&domain->vmd_pagequeues[PQ_INACTIVE].pq_pl,
19837e78597fSMark Johnston 	    &domain->vmd_inacthead, plinks.q);
1984449c2e92SKonstantin Belousov 
1985449c2e92SKonstantin Belousov 	/*
1986449c2e92SKonstantin Belousov 	 * The pageout daemon worker is never done, so loop forever.
1987449c2e92SKonstantin Belousov 	 */
1988449c2e92SKonstantin Belousov 	while (TRUE) {
1989449c2e92SKonstantin Belousov 		mtx_lock(&vm_page_queue_free_mtx);
199056ce0690SAlan Cox 
199156ce0690SAlan Cox 		/*
199256ce0690SAlan Cox 		 * Generally, after a level >= 1 scan, if there are enough
199356ce0690SAlan Cox 		 * free pages to wakeup the waiters, then they are already
199456ce0690SAlan Cox 		 * awake.  A call to vm_page_free() during the scan awakened
199556ce0690SAlan Cox 		 * them.  However, in the following case, this wakeup serves
199656ce0690SAlan Cox 		 * to bound the amount of time that a thread might wait.
199756ce0690SAlan Cox 		 * Suppose a thread's call to vm_page_alloc() fails, but
199856ce0690SAlan Cox 		 * before that thread calls VM_WAIT, enough pages are freed by
199956ce0690SAlan Cox 		 * other threads to alleviate the free page shortage.  The
200056ce0690SAlan Cox 		 * thread will, nonetheless, wait until another page is freed
200156ce0690SAlan Cox 		 * or this wakeup is performed.
200256ce0690SAlan Cox 		 */
2003449c2e92SKonstantin Belousov 		if (vm_pages_needed && !vm_page_count_min()) {
200456ce0690SAlan Cox 			vm_pages_needed = false;
200544f1c916SBryan Drewery 			wakeup(&vm_cnt.v_free_count);
2006449c2e92SKonstantin Belousov 		}
200756ce0690SAlan Cox 
2008449c2e92SKonstantin Belousov 		/*
2009e57dd910SAlan Cox 		 * Do not clear vm_pageout_wanted until we reach our free page
2010e57dd910SAlan Cox 		 * target.  Otherwise, we may be awakened over and over again,
2011e57dd910SAlan Cox 		 * wasting CPU time.
2012449c2e92SKonstantin Belousov 		 */
2013e57dd910SAlan Cox 		if (vm_pageout_wanted && target_met)
201456ce0690SAlan Cox 			vm_pageout_wanted = false;
201556ce0690SAlan Cox 
201656ce0690SAlan Cox 		/*
201756ce0690SAlan Cox 		 * Might the page daemon receive a wakeup call?
201856ce0690SAlan Cox 		 */
201956ce0690SAlan Cox 		if (vm_pageout_wanted) {
202056ce0690SAlan Cox 			/*
202156ce0690SAlan Cox 			 * No.  Either vm_pageout_wanted was set by another
202256ce0690SAlan Cox 			 * thread during the previous scan, which must have
202356ce0690SAlan Cox 			 * been a level 0 scan, or vm_pageout_wanted was
202456ce0690SAlan Cox 			 * already set and the scan failed to free enough
2025ebcddc72SAlan Cox 			 * pages.  If we haven't yet performed a level >= 1
2026ebcddc72SAlan Cox 			 * (page reclamation) scan, then increase the level
2027ebcddc72SAlan Cox 			 * and scan again now.  Otherwise, sleep a bit and
2028ebcddc72SAlan Cox 			 * try again later.
202956ce0690SAlan Cox 			 */
203056ce0690SAlan Cox 			mtx_unlock(&vm_page_queue_free_mtx);
2031ebcddc72SAlan Cox 			if (pass >= 1)
2032ebcddc72SAlan Cox 				pause("psleep", hz / VM_INACT_SCAN_RATE);
203370cf3cedSAlan Cox 			pass++;
2034449c2e92SKonstantin Belousov 		} else {
2035449c2e92SKonstantin Belousov 			/*
203656ce0690SAlan Cox 			 * Yes.  Sleep until pages need to be reclaimed or
203756ce0690SAlan Cox 			 * have their reference stats updated.
2038449c2e92SKonstantin Belousov 			 */
203956ce0690SAlan Cox 			if (mtx_sleep(&vm_pageout_wanted,
204056ce0690SAlan Cox 			    &vm_page_queue_free_mtx, PDROP | PVM, "psleep",
204156ce0690SAlan Cox 			    hz) == 0) {
204283c9dea1SGleb Smirnoff 				VM_CNT_INC(v_pdwakeups);
204370cf3cedSAlan Cox 				pass = 1;
2044d9347bcaSAlan Cox 			} else
204570cf3cedSAlan Cox 				pass = 0;
204656ce0690SAlan Cox 		}
204756ce0690SAlan Cox 
204870cf3cedSAlan Cox 		target_met = vm_pageout_scan(domain, pass);
2049449c2e92SKonstantin Belousov 	}
2050449c2e92SKonstantin Belousov }
2051449c2e92SKonstantin Belousov 
2052df8bae1dSRodney W. Grimes /*
20534d19f4adSSteven Hartland  *	vm_pageout_init initialises basic pageout daemon settings.
2054df8bae1dSRodney W. Grimes  */
20552b14f991SJulian Elischer static void
20564d19f4adSSteven Hartland vm_pageout_init(void)
2057df8bae1dSRodney W. Grimes {
2058df8bae1dSRodney W. Grimes 	/*
2059df8bae1dSRodney W. Grimes 	 * Initialize some paging parameters.
2060df8bae1dSRodney W. Grimes 	 */
206144f1c916SBryan Drewery 	vm_cnt.v_interrupt_free_min = 2;
206244f1c916SBryan Drewery 	if (vm_cnt.v_page_count < 2000)
2063f35329acSJohn Dyson 		vm_pageout_page_count = 8;
2064f6b04d2bSDavid Greenman 
206545ae1d91SAlan Cox 	/*
206645ae1d91SAlan Cox 	 * v_free_reserved needs to include enough for the largest
206745ae1d91SAlan Cox 	 * swap pager structures plus enough for any pv_entry structs
206845ae1d91SAlan Cox 	 * when paging.
206945ae1d91SAlan Cox 	 */
207044f1c916SBryan Drewery 	if (vm_cnt.v_page_count > 1024)
207144f1c916SBryan Drewery 		vm_cnt.v_free_min = 4 + (vm_cnt.v_page_count - 1024) / 200;
20722feb50bfSAttilio Rao 	else
207344f1c916SBryan Drewery 		vm_cnt.v_free_min = 4;
207444f1c916SBryan Drewery 	vm_cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
207544f1c916SBryan Drewery 	    vm_cnt.v_interrupt_free_min;
207644f1c916SBryan Drewery 	vm_cnt.v_free_reserved = vm_pageout_page_count +
207744f1c916SBryan Drewery 	    vm_cnt.v_pageout_free_min + (vm_cnt.v_page_count / 768);
207844f1c916SBryan Drewery 	vm_cnt.v_free_severe = vm_cnt.v_free_min / 2;
207944f1c916SBryan Drewery 	vm_cnt.v_free_target = 4 * vm_cnt.v_free_min + vm_cnt.v_free_reserved;
208044f1c916SBryan Drewery 	vm_cnt.v_free_min += vm_cnt.v_free_reserved;
208144f1c916SBryan Drewery 	vm_cnt.v_free_severe += vm_cnt.v_free_reserved;
208244f1c916SBryan Drewery 	vm_cnt.v_inactive_target = (3 * vm_cnt.v_free_target) / 2;
208344f1c916SBryan Drewery 	if (vm_cnt.v_inactive_target > vm_cnt.v_free_count / 3)
208444f1c916SBryan Drewery 		vm_cnt.v_inactive_target = vm_cnt.v_free_count / 3;
2085df8bae1dSRodney W. Grimes 
2086d9e23210SJeff Roberson 	/*
2087d9e23210SJeff Roberson 	 * Set the default wakeup threshold to be 10% above the minimum
2088d9e23210SJeff Roberson 	 * page limit.  This keeps the steady state out of shortfall.
2089d9e23210SJeff Roberson 	 */
209044f1c916SBryan Drewery 	vm_pageout_wakeup_thresh = (vm_cnt.v_free_min / 10) * 11;
2091d9e23210SJeff Roberson 
2092d9e23210SJeff Roberson 	/*
2093d9e23210SJeff Roberson 	 * Set interval in seconds for active scan.  We want to visit each
2094c9612b2dSJeff Roberson 	 * page at least once every ten minutes.  This is to prevent worst
2095c9612b2dSJeff Roberson 	 * case paging behaviors with stale active LRU.
2096d9e23210SJeff Roberson 	 */
2097d9e23210SJeff Roberson 	if (vm_pageout_update_period == 0)
2098c9612b2dSJeff Roberson 		vm_pageout_update_period = 600;
2099d9e23210SJeff Roberson 
2100df8bae1dSRodney W. Grimes 	/* XXX does not really belong here */
2101df8bae1dSRodney W. Grimes 	if (vm_page_max_wired == 0)
210244f1c916SBryan Drewery 		vm_page_max_wired = vm_cnt.v_free_count / 3;
2103ebcddc72SAlan Cox 
2104ebcddc72SAlan Cox 	/*
2105ebcddc72SAlan Cox 	 * Target amount of memory to move out of the laundry queue during a
2106ebcddc72SAlan Cox 	 * background laundering.  This is proportional to the amount of system
2107ebcddc72SAlan Cox 	 * memory.
2108ebcddc72SAlan Cox 	 */
2109ebcddc72SAlan Cox 	vm_background_launder_target = (vm_cnt.v_free_target -
2110ebcddc72SAlan Cox 	    vm_cnt.v_free_min) / 10;
21114d19f4adSSteven Hartland }
21124d19f4adSSteven Hartland 
21134d19f4adSSteven Hartland /*
21144d19f4adSSteven Hartland  *     vm_pageout is the high level pageout daemon.
21154d19f4adSSteven Hartland  */
21164d19f4adSSteven Hartland static void
21174d19f4adSSteven Hartland vm_pageout(void)
21184d19f4adSSteven Hartland {
211944ec2b63SKonstantin Belousov 	int error;
212062d70a81SJohn Baldwin #ifdef VM_NUMA_ALLOC
212144ec2b63SKonstantin Belousov 	int i;
21224d19f4adSSteven Hartland #endif
2123df8bae1dSRodney W. Grimes 
212424a1cce3SDavid Greenman 	swap_pager_swap_init();
2125ebcddc72SAlan Cox 	error = kthread_add(vm_pageout_laundry_worker, NULL, curproc, NULL,
2126ebcddc72SAlan Cox 	    0, 0, "laundry: dom0");
2127ebcddc72SAlan Cox 	if (error != 0)
2128ebcddc72SAlan Cox 		panic("starting laundry for domain 0, error %d", error);
212962d70a81SJohn Baldwin #ifdef VM_NUMA_ALLOC
2130449c2e92SKonstantin Belousov 	for (i = 1; i < vm_ndomains; i++) {
2131449c2e92SKonstantin Belousov 		error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
2132449c2e92SKonstantin Belousov 		    curproc, NULL, 0, 0, "dom%d", i);
2133449c2e92SKonstantin Belousov 		if (error != 0) {
2134449c2e92SKonstantin Belousov 			panic("starting pageout for domain %d, error %d\n",
2135449c2e92SKonstantin Belousov 			    i, error);
2136dc2efb27SJohn Dyson 		}
2137f919ebdeSDavid Greenman 	}
2138449c2e92SKonstantin Belousov #endif
213944ec2b63SKonstantin Belousov 	error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
214044ec2b63SKonstantin Belousov 	    0, 0, "uma");
214144ec2b63SKonstantin Belousov 	if (error != 0)
214244ec2b63SKonstantin Belousov 		panic("starting uma_reclaim helper, error %d\n", error);
2143d395270dSDimitry Andric 	vm_pageout_worker((void *)(uintptr_t)0);
2144df8bae1dSRodney W. Grimes }
214526f9a767SRodney W. Grimes 
21466b4b77adSAlan Cox /*
2147e9f995d8SAlan Cox  * Unless the free page queue lock is held by the caller, this function
21486b4b77adSAlan Cox  * should be regarded as advisory.  Specifically, the caller should
214944f1c916SBryan Drewery  * not msleep() on &vm_cnt.v_free_count following this function unless
2150e9f995d8SAlan Cox  * the free page queue lock is held until the msleep() is performed.
21516b4b77adSAlan Cox  */
2152e0c5a895SJohn Dyson void
21534a365329SAndrey Zonov pagedaemon_wakeup(void)
2154e0c5a895SJohn Dyson {
2155a1c0a785SAlan Cox 
215656ce0690SAlan Cox 	if (!vm_pageout_wanted && curthread->td_proc != pageproc) {
215756ce0690SAlan Cox 		vm_pageout_wanted = true;
215856ce0690SAlan Cox 		wakeup(&vm_pageout_wanted);
2159e0c5a895SJohn Dyson 	}
2160e0c5a895SJohn Dyson }
2161e0c5a895SJohn Dyson 
216238efa82bSJohn Dyson #if !defined(NO_SWAPPING)
21635afce282SDavid Greenman static void
216497824da3SAlan Cox vm_req_vmdaemon(int req)
21655afce282SDavid Greenman {
21665afce282SDavid Greenman 	static int lastrun = 0;
21675afce282SDavid Greenman 
216897824da3SAlan Cox 	mtx_lock(&vm_daemon_mtx);
216997824da3SAlan Cox 	vm_pageout_req_swapout |= req;
2170b18bfc3dSJohn Dyson 	if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
21715afce282SDavid Greenman 		wakeup(&vm_daemon_needed);
21725afce282SDavid Greenman 		lastrun = ticks;
21735afce282SDavid Greenman 	}
217497824da3SAlan Cox 	mtx_unlock(&vm_daemon_mtx);
21755afce282SDavid Greenman }
21765afce282SDavid Greenman 
21772b14f991SJulian Elischer static void
21784a365329SAndrey Zonov vm_daemon(void)
21790d94caffSDavid Greenman {
218091d5354aSJohn Baldwin 	struct rlimit rsslim;
2181dcbcd518SBruce Evans 	struct proc *p;
2182dcbcd518SBruce Evans 	struct thread *td;
21836bed074cSKonstantin Belousov 	struct vmspace *vm;
2184099e7e95SEdward Tomasz Napierala 	int breakout, swapout_flags, tryagain, attempts;
2185afcc55f3SEdward Tomasz Napierala #ifdef RACCT
2186099e7e95SEdward Tomasz Napierala 	uint64_t rsize, ravailable;
2187afcc55f3SEdward Tomasz Napierala #endif
21880d94caffSDavid Greenman 
21892fe6e4d7SDavid Greenman 	while (TRUE) {
219097824da3SAlan Cox 		mtx_lock(&vm_daemon_mtx);
21914b5c9cf6SEdward Tomasz Napierala 		msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
2192099e7e95SEdward Tomasz Napierala #ifdef RACCT
21934b5c9cf6SEdward Tomasz Napierala 		    racct_enable ? hz : 0
2194099e7e95SEdward Tomasz Napierala #else
21954b5c9cf6SEdward Tomasz Napierala 		    0
2196099e7e95SEdward Tomasz Napierala #endif
21974b5c9cf6SEdward Tomasz Napierala 		);
219897824da3SAlan Cox 		swapout_flags = vm_pageout_req_swapout;
21994c1f8ee9SDavid Greenman 		vm_pageout_req_swapout = 0;
220097824da3SAlan Cox 		mtx_unlock(&vm_daemon_mtx);
220197824da3SAlan Cox 		if (swapout_flags)
220297824da3SAlan Cox 			swapout_procs(swapout_flags);
220397824da3SAlan Cox 
22042fe6e4d7SDavid Greenman 		/*
22050d94caffSDavid Greenman 		 * scan the processes for exceeding their rlimits or if
22060d94caffSDavid Greenman 		 * process is swapped out -- deactivate pages
22072fe6e4d7SDavid Greenman 		 */
2208099e7e95SEdward Tomasz Napierala 		tryagain = 0;
2209099e7e95SEdward Tomasz Napierala 		attempts = 0;
2210099e7e95SEdward Tomasz Napierala again:
2211099e7e95SEdward Tomasz Napierala 		attempts++;
22121005a129SJohn Baldwin 		sx_slock(&allproc_lock);
2213f67af5c9SXin LI 		FOREACH_PROC_IN_SYSTEM(p) {
2214fe2144fdSLuoqi Chen 			vm_pindex_t limit, size;
22152fe6e4d7SDavid Greenman 
22162fe6e4d7SDavid Greenman 			/*
22172fe6e4d7SDavid Greenman 			 * if this is a system process or if we have already
22182fe6e4d7SDavid Greenman 			 * looked at this process, skip it.
22192fe6e4d7SDavid Greenman 			 */
2220897ecacdSJohn Baldwin 			PROC_LOCK(p);
22218e6fa660SJohn Baldwin 			if (p->p_state != PRS_NORMAL ||
22228e6fa660SJohn Baldwin 			    p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
2223897ecacdSJohn Baldwin 				PROC_UNLOCK(p);
22242fe6e4d7SDavid Greenman 				continue;
22252fe6e4d7SDavid Greenman 			}
22262fe6e4d7SDavid Greenman 			/*
22272fe6e4d7SDavid Greenman 			 * if the process is in a non-running type state,
22282fe6e4d7SDavid Greenman 			 * don't touch it.
22292fe6e4d7SDavid Greenman 			 */
2230e602ba25SJulian Elischer 			breakout = 0;
2231e602ba25SJulian Elischer 			FOREACH_THREAD_IN_PROC(p, td) {
2232982d11f8SJeff Roberson 				thread_lock(td);
223371fad9fdSJulian Elischer 				if (!TD_ON_RUNQ(td) &&
223471fad9fdSJulian Elischer 				    !TD_IS_RUNNING(td) &&
2235f497cda2SEdward Tomasz Napierala 				    !TD_IS_SLEEPING(td) &&
2236f497cda2SEdward Tomasz Napierala 				    !TD_IS_SUSPENDED(td)) {
2237982d11f8SJeff Roberson 					thread_unlock(td);
2238e602ba25SJulian Elischer 					breakout = 1;
2239e602ba25SJulian Elischer 					break;
2240e602ba25SJulian Elischer 				}
2241982d11f8SJeff Roberson 				thread_unlock(td);
2242e602ba25SJulian Elischer 			}
2243897ecacdSJohn Baldwin 			if (breakout) {
2244897ecacdSJohn Baldwin 				PROC_UNLOCK(p);
22452fe6e4d7SDavid Greenman 				continue;
22462fe6e4d7SDavid Greenman 			}
22472fe6e4d7SDavid Greenman 			/*
22482fe6e4d7SDavid Greenman 			 * get a limit
22492fe6e4d7SDavid Greenman 			 */
2250f6f6d240SMateusz Guzik 			lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
2251fe2144fdSLuoqi Chen 			limit = OFF_TO_IDX(
225291d5354aSJohn Baldwin 			    qmin(rsslim.rlim_cur, rsslim.rlim_max));
22532fe6e4d7SDavid Greenman 
22542fe6e4d7SDavid Greenman 			/*
22550d94caffSDavid Greenman 			 * let processes that are swapped out really be
22560d94caffSDavid Greenman 			 * swapped out set the limit to nothing (will force a
22570d94caffSDavid Greenman 			 * swap-out.)
22582fe6e4d7SDavid Greenman 			 */
2259b61ce5b0SJeff Roberson 			if ((p->p_flag & P_INMEM) == 0)
22600d94caffSDavid Greenman 				limit = 0;	/* XXX */
22616bed074cSKonstantin Belousov 			vm = vmspace_acquire_ref(p);
226295e2409aSKonstantin Belousov 			_PHOLD_LITE(p);
2263897ecacdSJohn Baldwin 			PROC_UNLOCK(p);
226495e2409aSKonstantin Belousov 			if (vm == NULL) {
226595e2409aSKonstantin Belousov 				PRELE(p);
22666bed074cSKonstantin Belousov 				continue;
226795e2409aSKonstantin Belousov 			}
226895e2409aSKonstantin Belousov 			sx_sunlock(&allproc_lock);
22692fe6e4d7SDavid Greenman 
22706bed074cSKonstantin Belousov 			size = vmspace_resident_count(vm);
2271a406d8c3SEdward Tomasz Napierala 			if (size >= limit) {
2272fe2144fdSLuoqi Chen 				vm_pageout_map_deactivate_pages(
22736bed074cSKonstantin Belousov 				    &vm->vm_map, limit);
2274937c1b07SAndriy Gapon 				size = vmspace_resident_count(vm);
22752fe6e4d7SDavid Greenman 			}
2276afcc55f3SEdward Tomasz Napierala #ifdef RACCT
22774b5c9cf6SEdward Tomasz Napierala 			if (racct_enable) {
2278099e7e95SEdward Tomasz Napierala 				rsize = IDX_TO_OFF(size);
2279099e7e95SEdward Tomasz Napierala 				PROC_LOCK(p);
2280937c1b07SAndriy Gapon 				if (p->p_state == PRS_NORMAL)
2281099e7e95SEdward Tomasz Napierala 					racct_set(p, RACCT_RSS, rsize);
2282099e7e95SEdward Tomasz Napierala 				ravailable = racct_get_available(p, RACCT_RSS);
2283099e7e95SEdward Tomasz Napierala 				PROC_UNLOCK(p);
2284099e7e95SEdward Tomasz Napierala 				if (rsize > ravailable) {
2285099e7e95SEdward Tomasz Napierala 					/*
22864b5c9cf6SEdward Tomasz Napierala 					 * Don't be overly aggressive; this
22874b5c9cf6SEdward Tomasz Napierala 					 * might be an innocent process,
22884b5c9cf6SEdward Tomasz Napierala 					 * and the limit could've been exceeded
22894b5c9cf6SEdward Tomasz Napierala 					 * by some memory hog.  Don't try
22904b5c9cf6SEdward Tomasz Napierala 					 * to deactivate more than 1/4th
22914b5c9cf6SEdward Tomasz Napierala 					 * of process' resident set size.
2292099e7e95SEdward Tomasz Napierala 					 */
2293099e7e95SEdward Tomasz Napierala 					if (attempts <= 8) {
22944b5c9cf6SEdward Tomasz Napierala 						if (ravailable < rsize -
22954b5c9cf6SEdward Tomasz Napierala 						    (rsize / 4)) {
22964b5c9cf6SEdward Tomasz Napierala 							ravailable = rsize -
22974b5c9cf6SEdward Tomasz Napierala 							    (rsize / 4);
22984b5c9cf6SEdward Tomasz Napierala 						}
2299099e7e95SEdward Tomasz Napierala 					}
2300099e7e95SEdward Tomasz Napierala 					vm_pageout_map_deactivate_pages(
23014b5c9cf6SEdward Tomasz Napierala 					    &vm->vm_map,
23024b5c9cf6SEdward Tomasz Napierala 					    OFF_TO_IDX(ravailable));
2303099e7e95SEdward Tomasz Napierala 					/* Update RSS usage after paging out. */
2304099e7e95SEdward Tomasz Napierala 					size = vmspace_resident_count(vm);
2305099e7e95SEdward Tomasz Napierala 					rsize = IDX_TO_OFF(size);
2306099e7e95SEdward Tomasz Napierala 					PROC_LOCK(p);
2307937c1b07SAndriy Gapon 					if (p->p_state == PRS_NORMAL)
2308099e7e95SEdward Tomasz Napierala 						racct_set(p, RACCT_RSS, rsize);
2309099e7e95SEdward Tomasz Napierala 					PROC_UNLOCK(p);
2310099e7e95SEdward Tomasz Napierala 					if (rsize > ravailable)
2311099e7e95SEdward Tomasz Napierala 						tryagain = 1;
2312099e7e95SEdward Tomasz Napierala 				}
23134b5c9cf6SEdward Tomasz Napierala 			}
2314afcc55f3SEdward Tomasz Napierala #endif
23156bed074cSKonstantin Belousov 			vmspace_free(vm);
231695e2409aSKonstantin Belousov 			sx_slock(&allproc_lock);
231795e2409aSKonstantin Belousov 			PRELE(p);
23182fe6e4d7SDavid Greenman 		}
23191005a129SJohn Baldwin 		sx_sunlock(&allproc_lock);
2320099e7e95SEdward Tomasz Napierala 		if (tryagain != 0 && attempts <= 10)
2321099e7e95SEdward Tomasz Napierala 			goto again;
232224a1cce3SDavid Greenman 	}
23232fe6e4d7SDavid Greenman }
2324a1287949SEivind Eklund #endif			/* !defined(NO_SWAPPING) */
2325