xref: /freebsd/sys/vm/vm_pageout.c (revision 95e2409a3340831355c176614690be1c6fcff654)
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);
12234d8b7eaSJeff Roberson static int vm_pageout_clean(vm_page_t m);
12334d8b7eaSJeff Roberson static int vm_pageout_cluster(vm_page_t m);
124449c2e92SKonstantin Belousov static void 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_cache);
14314a0d74eSSteven Hartland SDT_PROBE_DEFINE(vm, , , vm__lowmem_scan);
14414a0d74eSSteven Hartland 
14538efa82bSJohn Dyson #if !defined(NO_SWAPPING)
1462b14f991SJulian Elischer /* the kernel process "vm_daemon"*/
14711caded3SAlfred Perlstein static void vm_daemon(void);
148f708ef1bSPoul-Henning Kamp static struct	proc *vmproc;
1492b14f991SJulian Elischer 
1502b14f991SJulian Elischer static struct kproc_desc vm_kp = {
1512b14f991SJulian Elischer 	"vmdaemon",
1522b14f991SJulian Elischer 	vm_daemon,
1532b14f991SJulian Elischer 	&vmproc
1542b14f991SJulian Elischer };
155237fdd78SRobert Watson SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
15638efa82bSJohn Dyson #endif
1572b14f991SJulian Elischer 
1582b14f991SJulian Elischer 
1598b245767SAlan Cox int vm_pageout_deficit;		/* Estimated number of pages deficit */
160d9e23210SJeff Roberson int vm_pageout_wakeup_thresh;
16176386c7eSKonstantin Belousov static int vm_pageout_oom_seq = 12;
16256ce0690SAlan Cox bool vm_pageout_wanted;		/* Event on which pageout daemon sleeps */
16356ce0690SAlan Cox bool vm_pages_needed;		/* Are threads waiting for free pages? */
16426f9a767SRodney W. Grimes 
16538efa82bSJohn Dyson #if !defined(NO_SWAPPING)
166f708ef1bSPoul-Henning Kamp static int vm_pageout_req_swapout;	/* XXX */
167f708ef1bSPoul-Henning Kamp static int vm_daemon_needed;
16897824da3SAlan Cox static struct mtx vm_daemon_mtx;
16997824da3SAlan Cox /* Allow for use by vm_pageout before vm_daemon is initialized. */
17097824da3SAlan Cox MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
17138efa82bSJohn Dyson #endif
1722b6b0df7SMatthew Dillon static int vm_max_launder = 32;
173d9e23210SJeff Roberson static int vm_pageout_update_period;
1744a365329SAndrey Zonov static int defer_swap_pageouts;
1754a365329SAndrey Zonov static int disable_swap_pageouts;
176c9612b2dSJeff Roberson static int lowmem_period = 10;
177a6bf3a9eSRyan Stone static time_t lowmem_uptime;
17870111b90SJohn Dyson 
17938efa82bSJohn Dyson #if defined(NO_SWAPPING)
180303b270bSEivind Eklund static int vm_swap_enabled = 0;
181303b270bSEivind Eklund static int vm_swap_idle_enabled = 0;
18238efa82bSJohn Dyson #else
183303b270bSEivind Eklund static int vm_swap_enabled = 1;
184303b270bSEivind Eklund static int vm_swap_idle_enabled = 0;
18538efa82bSJohn Dyson #endif
18638efa82bSJohn Dyson 
1878311a2b8SWill Andrews static int vm_panic_on_oom = 0;
1888311a2b8SWill Andrews 
1898311a2b8SWill Andrews SYSCTL_INT(_vm, OID_AUTO, panic_on_oom,
1908311a2b8SWill Andrews 	CTLFLAG_RWTUN, &vm_panic_on_oom, 0,
1918311a2b8SWill Andrews 	"panic on out of memory instead of killing the largest process");
1928311a2b8SWill Andrews 
193d9e23210SJeff Roberson SYSCTL_INT(_vm, OID_AUTO, pageout_wakeup_thresh,
194d9e23210SJeff Roberson 	CTLFLAG_RW, &vm_pageout_wakeup_thresh, 0,
195d9e23210SJeff Roberson 	"free page threshold for waking up the pageout daemon");
196d9e23210SJeff Roberson 
1972b6b0df7SMatthew Dillon SYSCTL_INT(_vm, OID_AUTO, max_launder,
1982b6b0df7SMatthew Dillon 	CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
19938efa82bSJohn Dyson 
200d9e23210SJeff Roberson SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
201d9e23210SJeff Roberson 	CTLFLAG_RW, &vm_pageout_update_period, 0,
202d9e23210SJeff Roberson 	"Maximum active LRU update period");
20353636869SAndrey Zonov 
204c9612b2dSJeff Roberson SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RW, &lowmem_period, 0,
205c9612b2dSJeff Roberson 	"Low memory callback period");
206c9612b2dSJeff Roberson 
20738efa82bSJohn Dyson #if defined(NO_SWAPPING)
208ceb0cf87SJohn Dyson SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
2096bd9cb1cSTom Rhodes 	CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout");
210ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
2116bd9cb1cSTom Rhodes 	CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
21238efa82bSJohn Dyson #else
213ceb0cf87SJohn Dyson SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
214b0359e2cSPeter Wemm 	CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
215ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
216b0359e2cSPeter Wemm 	CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
21738efa82bSJohn Dyson #endif
21826f9a767SRodney W. Grimes 
219ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
220b0359e2cSPeter Wemm 	CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
22112ac6a1dSJohn Dyson 
222ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
223b0359e2cSPeter Wemm 	CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
22412ac6a1dSJohn Dyson 
22523b59018SMatthew Dillon static int pageout_lock_miss;
22623b59018SMatthew Dillon SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
22723b59018SMatthew Dillon 	CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
22823b59018SMatthew Dillon 
22976386c7eSKonstantin Belousov SYSCTL_INT(_vm, OID_AUTO, pageout_oom_seq,
23076386c7eSKonstantin Belousov 	CTLFLAG_RW, &vm_pageout_oom_seq, 0,
23176386c7eSKonstantin Belousov 	"back-to-back calls to oom detector to start OOM");
23276386c7eSKonstantin Belousov 
233ffc82b0aSJohn Dyson #define VM_PAGEOUT_PAGE_COUNT 16
234bbc0ec52SDavid Greenman int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
235df8bae1dSRodney W. Grimes 
236c3cb3e12SDavid Greenman int vm_page_max_wired;		/* XXX max # of wired pages system-wide */
2375dfc2870SAlan Cox SYSCTL_INT(_vm, OID_AUTO, max_wired,
2385dfc2870SAlan Cox 	CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
239df8bae1dSRodney W. Grimes 
24085eeca35SAlan Cox static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
24138efa82bSJohn Dyson #if !defined(NO_SWAPPING)
242ecf6279fSAlan Cox static void vm_pageout_map_deactivate_pages(vm_map_t, long);
243ecf6279fSAlan Cox static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
24497824da3SAlan Cox static void vm_req_vmdaemon(int req);
24538efa82bSJohn Dyson #endif
24685eeca35SAlan Cox static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
247cd41fc12SDavid Greenman 
248a8229fa3SAlan Cox /*
249a8229fa3SAlan Cox  * Initialize a dummy page for marking the caller's place in the specified
250a8229fa3SAlan Cox  * paging queue.  In principle, this function only needs to set the flag
251c7aebda8SAttilio Rao  * PG_MARKER.  Nonetheless, it wirte busies and initializes the hold count
252c7aebda8SAttilio Rao  * to one as safety precautions.
253a8229fa3SAlan Cox  */
2548c616246SKonstantin Belousov static void
2558c616246SKonstantin Belousov vm_pageout_init_marker(vm_page_t marker, u_short queue)
2568c616246SKonstantin Belousov {
2578c616246SKonstantin Belousov 
2588c616246SKonstantin Belousov 	bzero(marker, sizeof(*marker));
259a8229fa3SAlan Cox 	marker->flags = PG_MARKER;
260c7aebda8SAttilio Rao 	marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
2618c616246SKonstantin Belousov 	marker->queue = queue;
262a8229fa3SAlan Cox 	marker->hold_count = 1;
2638c616246SKonstantin Belousov }
2648c616246SKonstantin Belousov 
26526f9a767SRodney W. Grimes /*
2668dbca793STor Egge  * vm_pageout_fallback_object_lock:
2678dbca793STor Egge  *
26889f6b863SAttilio Rao  * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
2698dbca793STor Egge  * known to have failed and page queue must be either PQ_ACTIVE or
2708dbca793STor Egge  * PQ_INACTIVE.  To avoid lock order violation, unlock the page queues
2718dbca793STor Egge  * while locking the vm object.  Use marker page to detect page queue
2728dbca793STor Egge  * changes and maintain notion of next page on page queue.  Return
2738dbca793STor Egge  * TRUE if no changes were detected, FALSE otherwise.  vm object is
2748dbca793STor Egge  * locked on return.
2758dbca793STor Egge  *
2768dbca793STor Egge  * This function depends on both the lock portion of struct vm_object
2778dbca793STor Egge  * and normal struct vm_page being type stable.
2788dbca793STor Egge  */
27985eeca35SAlan Cox static boolean_t
2808dbca793STor Egge vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
2818dbca793STor Egge {
2828dbca793STor Egge 	struct vm_page marker;
2838d220203SAlan Cox 	struct vm_pagequeue *pq;
2848dbca793STor Egge 	boolean_t unchanged;
2858dbca793STor Egge 	u_short queue;
2868dbca793STor Egge 	vm_object_t object;
2878dbca793STor Egge 
2888dbca793STor Egge 	queue = m->queue;
2898c616246SKonstantin Belousov 	vm_pageout_init_marker(&marker, queue);
290449c2e92SKonstantin Belousov 	pq = vm_page_pagequeue(m);
2918dbca793STor Egge 	object = m->object;
2928dbca793STor Egge 
293c325e866SKonstantin Belousov 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
2948d220203SAlan Cox 	vm_pagequeue_unlock(pq);
2952965a453SKip Macy 	vm_page_unlock(m);
29689f6b863SAttilio Rao 	VM_OBJECT_WLOCK(object);
2972965a453SKip Macy 	vm_page_lock(m);
2988d220203SAlan Cox 	vm_pagequeue_lock(pq);
2998dbca793STor Egge 
30069b8585eSKonstantin Belousov 	/*
30169b8585eSKonstantin Belousov 	 * The page's object might have changed, and/or the page might
30269b8585eSKonstantin Belousov 	 * have moved from its original position in the queue.  If the
30369b8585eSKonstantin Belousov 	 * page's object has changed, then the caller should abandon
30469b8585eSKonstantin Belousov 	 * processing the page because the wrong object lock was
30569b8585eSKonstantin Belousov 	 * acquired.  Use the marker's plinks.q, not the page's, to
30669b8585eSKonstantin Belousov 	 * determine if the page has been moved.  The state of the
30769b8585eSKonstantin Belousov 	 * page's plinks.q can be indeterminate; whereas, the marker's
30869b8585eSKonstantin Belousov 	 * plinks.q must be valid.
30969b8585eSKonstantin Belousov 	 */
310c325e866SKonstantin Belousov 	*next = TAILQ_NEXT(&marker, plinks.q);
31169b8585eSKonstantin Belousov 	unchanged = m->object == object &&
31269b8585eSKonstantin Belousov 	    m == TAILQ_PREV(&marker, pglist, plinks.q);
31369b8585eSKonstantin Belousov 	KASSERT(!unchanged || m->queue == queue,
31469b8585eSKonstantin Belousov 	    ("page %p queue %d %d", m, queue, m->queue));
315c325e866SKonstantin Belousov 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
3168dbca793STor Egge 	return (unchanged);
3178dbca793STor Egge }
3188dbca793STor Egge 
3198dbca793STor Egge /*
3208c616246SKonstantin Belousov  * Lock the page while holding the page queue lock.  Use marker page
3218c616246SKonstantin Belousov  * to detect page queue changes and maintain notion of next page on
3228c616246SKonstantin Belousov  * page queue.  Return TRUE if no changes were detected, FALSE
3238c616246SKonstantin Belousov  * otherwise.  The page is locked on return. The page queue lock might
3248c616246SKonstantin Belousov  * be dropped and reacquired.
3258c616246SKonstantin Belousov  *
3268c616246SKonstantin Belousov  * This function depends on normal struct vm_page being type stable.
3278c616246SKonstantin Belousov  */
32885eeca35SAlan Cox static boolean_t
3298c616246SKonstantin Belousov vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
3308c616246SKonstantin Belousov {
3318c616246SKonstantin Belousov 	struct vm_page marker;
3328d220203SAlan Cox 	struct vm_pagequeue *pq;
3338c616246SKonstantin Belousov 	boolean_t unchanged;
3348c616246SKonstantin Belousov 	u_short queue;
3358c616246SKonstantin Belousov 
3368c616246SKonstantin Belousov 	vm_page_lock_assert(m, MA_NOTOWNED);
3378c616246SKonstantin Belousov 	if (vm_page_trylock(m))
3388c616246SKonstantin Belousov 		return (TRUE);
3398c616246SKonstantin Belousov 
3408c616246SKonstantin Belousov 	queue = m->queue;
3418c616246SKonstantin Belousov 	vm_pageout_init_marker(&marker, queue);
342449c2e92SKonstantin Belousov 	pq = vm_page_pagequeue(m);
3438c616246SKonstantin Belousov 
344c325e866SKonstantin Belousov 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
3458d220203SAlan Cox 	vm_pagequeue_unlock(pq);
3468c616246SKonstantin Belousov 	vm_page_lock(m);
3478d220203SAlan Cox 	vm_pagequeue_lock(pq);
3488c616246SKonstantin Belousov 
3498c616246SKonstantin Belousov 	/* Page queue might have changed. */
350c325e866SKonstantin Belousov 	*next = TAILQ_NEXT(&marker, plinks.q);
35169b8585eSKonstantin Belousov 	unchanged = m == TAILQ_PREV(&marker, pglist, plinks.q);
35269b8585eSKonstantin Belousov 	KASSERT(!unchanged || m->queue == queue,
35369b8585eSKonstantin Belousov 	    ("page %p queue %d %d", m, queue, m->queue));
354c325e866SKonstantin Belousov 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
3558c616246SKonstantin Belousov 	return (unchanged);
3568c616246SKonstantin Belousov }
3578c616246SKonstantin Belousov 
3588c616246SKonstantin Belousov /*
35926f9a767SRodney W. Grimes  * vm_pageout_clean:
36024a1cce3SDavid Greenman  *
3610d94caffSDavid Greenman  * Clean the page and remove it from the laundry.
36226f9a767SRodney W. Grimes  *
3630d94caffSDavid Greenman  * We set the busy bit to cause potential page faults on this page to
3641c7c3c6aSMatthew Dillon  * block.  Note the careful timing, however, the busy bit isn't set till
3651c7c3c6aSMatthew Dillon  * late and we cannot do anything that will mess with the page.
36626f9a767SRodney W. Grimes  */
3673af76890SPoul-Henning Kamp static int
36834d8b7eaSJeff Roberson vm_pageout_cluster(vm_page_t m)
36924a1cce3SDavid Greenman {
37054d92145SMatthew Dillon 	vm_object_t object;
37191b4f427SAlan Cox 	vm_page_t mc[2*vm_pageout_page_count], pb, ps;
3723562af12SAlan Cox 	int pageout_count;
37390ecac61SMatthew Dillon 	int ib, is, page_base;
374a316d390SJohn Dyson 	vm_pindex_t pindex = m->pindex;
37526f9a767SRodney W. Grimes 
37695976f3fSAlan Cox 	vm_page_lock_assert(m, MA_OWNED);
37717f6a17bSAlan Cox 	object = m->object;
37889f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
3790cddd8f0SMatthew Dillon 
38026f9a767SRodney W. Grimes 	/*
3811c7c3c6aSMatthew Dillon 	 * It doesn't cost us anything to pageout OBJT_DEFAULT or OBJT_SWAP
3821c7c3c6aSMatthew Dillon 	 * with the new swapper, but we could have serious problems paging
3831c7c3c6aSMatthew Dillon 	 * out other object types if there is insufficient memory.
3841c7c3c6aSMatthew Dillon 	 *
3851c7c3c6aSMatthew Dillon 	 * Unfortunately, checking free memory here is far too late, so the
3861c7c3c6aSMatthew Dillon 	 * check has been moved up a procedural level.
3871c7c3c6aSMatthew Dillon 	 */
3881c7c3c6aSMatthew Dillon 
38924a1cce3SDavid Greenman 	/*
3909e897b1bSAlan Cox 	 * Can't clean the page if it's busy or held.
39124a1cce3SDavid Greenman 	 */
392c7aebda8SAttilio Rao 	vm_page_assert_unbusied(m);
39395976f3fSAlan Cox 	KASSERT(m->hold_count == 0, ("vm_pageout_clean: page %p is held", m));
39417f6a17bSAlan Cox 	vm_page_unlock(m);
3950d94caffSDavid Greenman 
39691b4f427SAlan Cox 	mc[vm_pageout_page_count] = pb = ps = m;
39726f9a767SRodney W. Grimes 	pageout_count = 1;
398f35329acSJohn Dyson 	page_base = vm_pageout_page_count;
39990ecac61SMatthew Dillon 	ib = 1;
40090ecac61SMatthew Dillon 	is = 1;
40190ecac61SMatthew Dillon 
40224a1cce3SDavid Greenman 	/*
40324a1cce3SDavid Greenman 	 * Scan object for clusterable pages.
40424a1cce3SDavid Greenman 	 *
40524a1cce3SDavid Greenman 	 * We can cluster ONLY if: ->> the page is NOT
40624a1cce3SDavid Greenman 	 * clean, wired, busy, held, or mapped into a
40724a1cce3SDavid Greenman 	 * buffer, and one of the following:
40824a1cce3SDavid Greenman 	 * 1) The page is inactive, or a seldom used
40924a1cce3SDavid Greenman 	 *    active page.
41024a1cce3SDavid Greenman 	 * -or-
41124a1cce3SDavid Greenman 	 * 2) we force the issue.
41290ecac61SMatthew Dillon 	 *
41390ecac61SMatthew Dillon 	 * During heavy mmap/modification loads the pageout
41490ecac61SMatthew Dillon 	 * daemon can really fragment the underlying file
41590ecac61SMatthew Dillon 	 * due to flushing pages out of order and not trying
41690ecac61SMatthew Dillon 	 * align the clusters (which leave sporatic out-of-order
41790ecac61SMatthew Dillon 	 * holes).  To solve this problem we do the reverse scan
41890ecac61SMatthew Dillon 	 * first and attempt to align our cluster, then do a
41990ecac61SMatthew Dillon 	 * forward scan if room remains.
42024a1cce3SDavid Greenman 	 */
42190ecac61SMatthew Dillon more:
42290ecac61SMatthew Dillon 	while (ib && pageout_count < vm_pageout_page_count) {
42324a1cce3SDavid Greenman 		vm_page_t p;
424f6b04d2bSDavid Greenman 
42590ecac61SMatthew Dillon 		if (ib > pindex) {
42690ecac61SMatthew Dillon 			ib = 0;
42790ecac61SMatthew Dillon 			break;
428f6b04d2bSDavid Greenman 		}
42990ecac61SMatthew Dillon 
430c7aebda8SAttilio Rao 		if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
43190ecac61SMatthew Dillon 			ib = 0;
43290ecac61SMatthew Dillon 			break;
433f6b04d2bSDavid Greenman 		}
43424a1cce3SDavid Greenman 		vm_page_test_dirty(p);
435eb5d3969SAlan Cox 		if (p->dirty == 0) {
436eb5d3969SAlan Cox 			ib = 0;
437eb5d3969SAlan Cox 			break;
438eb5d3969SAlan Cox 		}
439eb5d3969SAlan Cox 		vm_page_lock(p);
440eb5d3969SAlan Cox 		if (p->queue != PQ_INACTIVE ||
44157601bcbSMatthew Dillon 		    p->hold_count != 0) {	/* may be undergoing I/O */
4422965a453SKip Macy 			vm_page_unlock(p);
44390ecac61SMatthew Dillon 			ib = 0;
44424a1cce3SDavid Greenman 			break;
445f6b04d2bSDavid Greenman 		}
4462965a453SKip Macy 		vm_page_unlock(p);
44791b4f427SAlan Cox 		mc[--page_base] = pb = p;
44890ecac61SMatthew Dillon 		++pageout_count;
44990ecac61SMatthew Dillon 		++ib;
45024a1cce3SDavid Greenman 		/*
451763df3ecSPedro F. Giffuni 		 * alignment boundary, stop here and switch directions.  Do
45290ecac61SMatthew Dillon 		 * not clear ib.
45324a1cce3SDavid Greenman 		 */
45490ecac61SMatthew Dillon 		if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
45590ecac61SMatthew Dillon 			break;
45624a1cce3SDavid Greenman 	}
45790ecac61SMatthew Dillon 
45890ecac61SMatthew Dillon 	while (pageout_count < vm_pageout_page_count &&
45990ecac61SMatthew Dillon 	    pindex + is < object->size) {
46090ecac61SMatthew Dillon 		vm_page_t p;
46190ecac61SMatthew Dillon 
462c7aebda8SAttilio Rao 		if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
46390ecac61SMatthew Dillon 			break;
46424a1cce3SDavid Greenman 		vm_page_test_dirty(p);
465eb5d3969SAlan Cox 		if (p->dirty == 0)
466eb5d3969SAlan Cox 			break;
467eb5d3969SAlan Cox 		vm_page_lock(p);
468eb5d3969SAlan Cox 		if (p->queue != PQ_INACTIVE ||
46957601bcbSMatthew Dillon 		    p->hold_count != 0) {	/* may be undergoing I/O */
4702965a453SKip Macy 			vm_page_unlock(p);
47124a1cce3SDavid Greenman 			break;
47224a1cce3SDavid Greenman 		}
4732965a453SKip Macy 		vm_page_unlock(p);
47491b4f427SAlan Cox 		mc[page_base + pageout_count] = ps = p;
47590ecac61SMatthew Dillon 		++pageout_count;
47690ecac61SMatthew Dillon 		++is;
47724a1cce3SDavid Greenman 	}
47890ecac61SMatthew Dillon 
47990ecac61SMatthew Dillon 	/*
48090ecac61SMatthew Dillon 	 * If we exhausted our forward scan, continue with the reverse scan
481763df3ecSPedro F. Giffuni 	 * when possible, even past a page boundary.  This catches boundary
48290ecac61SMatthew Dillon 	 * conditions.
48390ecac61SMatthew Dillon 	 */
48490ecac61SMatthew Dillon 	if (ib && pageout_count < vm_pageout_page_count)
48590ecac61SMatthew Dillon 		goto more;
486f6b04d2bSDavid Greenman 
48767bf6868SJohn Dyson 	/*
48867bf6868SJohn Dyson 	 * we allow reads during pageouts...
48967bf6868SJohn Dyson 	 */
490126d6082SKonstantin Belousov 	return (vm_pageout_flush(&mc[page_base], pageout_count, 0, 0, NULL,
491126d6082SKonstantin Belousov 	    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 	/*
5201c7c3c6aSMatthew Dillon 	 * Initiate I/O.  Bump the vm_page_t->busy counter and
5211c7c3c6aSMatthew Dillon 	 * mark the pages 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));
533c7aebda8SAttilio Rao 		vm_page_sbusy(mc[i]);
53478985e42SAlan Cox 		pmap_remove_write(mc[i]);
5352965a453SKip Macy 	}
536d474eaaaSDoug Rabson 	vm_object_pip_add(object, count);
537aef922f5SJohn Dyson 
538d076fbeaSAlan Cox 	vm_pager_put_pages(object, mc, count, flags, pageout_status);
53926f9a767SRodney W. Grimes 
5401e8a675cSKonstantin Belousov 	runlen = count - mreq;
541126d6082SKonstantin Belousov 	if (eio != NULL)
542126d6082SKonstantin Belousov 		*eio = FALSE;
543aef922f5SJohn Dyson 	for (i = 0; i < count; i++) {
544aef922f5SJohn Dyson 		vm_page_t mt = mc[i];
54524a1cce3SDavid Greenman 
5464cd45723SAlan Cox 		KASSERT(pageout_status[i] == VM_PAGER_PEND ||
5476031c68dSAlan Cox 		    !pmap_page_is_write_mapped(mt),
5489ea8d1a6SAlan Cox 		    ("vm_pageout_flush: page %p is not write protected", mt));
54926f9a767SRodney W. Grimes 		switch (pageout_status[i]) {
55026f9a767SRodney W. Grimes 		case VM_PAGER_OK:
55126f9a767SRodney W. Grimes 		case VM_PAGER_PEND:
55295461b45SJohn Dyson 			numpagedout++;
55326f9a767SRodney W. Grimes 			break;
55426f9a767SRodney W. Grimes 		case VM_PAGER_BAD:
55526f9a767SRodney W. Grimes 			/*
5560d94caffSDavid Greenman 			 * Page outside of range of object. Right now we
5570d94caffSDavid Greenman 			 * essentially lose the changes by pretending it
5580d94caffSDavid Greenman 			 * worked.
55926f9a767SRodney W. Grimes 			 */
56090ecac61SMatthew Dillon 			vm_page_undirty(mt);
56126f9a767SRodney W. Grimes 			break;
56226f9a767SRodney W. Grimes 		case VM_PAGER_ERROR:
56326f9a767SRodney W. Grimes 		case VM_PAGER_FAIL:
56426f9a767SRodney W. Grimes 			/*
5650d94caffSDavid Greenman 			 * If page couldn't be paged out, then reactivate the
5660d94caffSDavid Greenman 			 * page so it doesn't clog the inactive list.  (We
5670d94caffSDavid Greenman 			 * will try paging out it again later).
56826f9a767SRodney W. Grimes 			 */
5693c4a2440SAlan Cox 			vm_page_lock(mt);
57024a1cce3SDavid Greenman 			vm_page_activate(mt);
5713c4a2440SAlan Cox 			vm_page_unlock(mt);
572126d6082SKonstantin Belousov 			if (eio != NULL && i >= mreq && i - mreq < runlen)
573126d6082SKonstantin Belousov 				*eio = TRUE;
57426f9a767SRodney W. Grimes 			break;
57526f9a767SRodney W. Grimes 		case VM_PAGER_AGAIN:
5761e8a675cSKonstantin Belousov 			if (i >= mreq && i - mreq < runlen)
5771e8a675cSKonstantin Belousov 				runlen = i - mreq;
57826f9a767SRodney W. Grimes 			break;
57926f9a767SRodney W. Grimes 		}
58026f9a767SRodney W. Grimes 
58126f9a767SRodney W. Grimes 		/*
5820d94caffSDavid Greenman 		 * If the operation is still going, leave the page busy to
5830d94caffSDavid Greenman 		 * block all other accesses. Also, leave the paging in
5840d94caffSDavid Greenman 		 * progress indicator set so that we don't attempt an object
5850d94caffSDavid Greenman 		 * collapse.
58626f9a767SRodney W. Grimes 		 */
58726f9a767SRodney W. Grimes 		if (pageout_status[i] != VM_PAGER_PEND) {
588f919ebdeSDavid Greenman 			vm_object_pip_wakeup(object);
589c7aebda8SAttilio Rao 			vm_page_sunbusy(mt);
5903c4a2440SAlan Cox 		}
5913c4a2440SAlan Cox 	}
5921e8a675cSKonstantin Belousov 	if (prunlen != NULL)
5931e8a675cSKonstantin Belousov 		*prunlen = runlen;
5943c4a2440SAlan Cox 	return (numpagedout);
59526f9a767SRodney W. Grimes }
59626f9a767SRodney W. Grimes 
59738efa82bSJohn Dyson #if !defined(NO_SWAPPING)
59826f9a767SRodney W. Grimes /*
59926f9a767SRodney W. Grimes  *	vm_pageout_object_deactivate_pages
60026f9a767SRodney W. Grimes  *
601ce186587SAlan Cox  *	Deactivate enough pages to satisfy the inactive target
602ce186587SAlan Cox  *	requirements.
60326f9a767SRodney W. Grimes  *
60426f9a767SRodney W. Grimes  *	The object and map must be locked.
60526f9a767SRodney W. Grimes  */
60638efa82bSJohn Dyson static void
607ce186587SAlan Cox vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
608ce186587SAlan Cox     long desired)
60926f9a767SRodney W. Grimes {
610ecf6279fSAlan Cox 	vm_object_t backing_object, object;
611ce186587SAlan Cox 	vm_page_t p;
612bb7858eaSJeff Roberson 	int act_delta, remove_mode;
61326f9a767SRodney W. Grimes 
614e23b0a19SAlan Cox 	VM_OBJECT_ASSERT_LOCKED(first_object);
61528634820SAlan Cox 	if ((first_object->flags & OBJ_FICTITIOUS) != 0)
61638efa82bSJohn Dyson 		return;
617ecf6279fSAlan Cox 	for (object = first_object;; object = backing_object) {
618ecf6279fSAlan Cox 		if (pmap_resident_count(pmap) <= desired)
619ecf6279fSAlan Cox 			goto unlock_return;
620e23b0a19SAlan Cox 		VM_OBJECT_ASSERT_LOCKED(object);
62128634820SAlan Cox 		if ((object->flags & OBJ_UNMANAGED) != 0 ||
62228634820SAlan Cox 		    object->paging_in_progress != 0)
623ecf6279fSAlan Cox 			goto unlock_return;
62426f9a767SRodney W. Grimes 
62585b1dc89SAlan Cox 		remove_mode = 0;
62638efa82bSJohn Dyson 		if (object->shadow_count > 1)
62738efa82bSJohn Dyson 			remove_mode = 1;
62826f9a767SRodney W. Grimes 		/*
629ce186587SAlan Cox 		 * Scan the object's entire memory queue.
63026f9a767SRodney W. Grimes 		 */
631ce186587SAlan Cox 		TAILQ_FOREACH(p, &object->memq, listq) {
632447fe2a4SAlan Cox 			if (pmap_resident_count(pmap) <= desired)
633447fe2a4SAlan Cox 				goto unlock_return;
634c7aebda8SAttilio Rao 			if (vm_page_busied(p))
635447fe2a4SAlan Cox 				continue;
636ce186587SAlan Cox 			PCPU_INC(cnt.v_pdpages);
6372965a453SKip Macy 			vm_page_lock(p);
638ce186587SAlan Cox 			if (p->wire_count != 0 || p->hold_count != 0 ||
639ecf6279fSAlan Cox 			    !pmap_page_exists_quick(pmap, p)) {
6402965a453SKip Macy 				vm_page_unlock(p);
6410d94caffSDavid Greenman 				continue;
6420d94caffSDavid Greenman 			}
643bb7858eaSJeff Roberson 			act_delta = pmap_ts_referenced(p);
6443407fefeSKonstantin Belousov 			if ((p->aflags & PGA_REFERENCED) != 0) {
645bb7858eaSJeff Roberson 				if (act_delta == 0)
646bb7858eaSJeff Roberson 					act_delta = 1;
6473407fefeSKonstantin Belousov 				vm_page_aflag_clear(p, PGA_REFERENCED);
648ef743ce6SJohn Dyson 			}
649bb7858eaSJeff Roberson 			if (p->queue != PQ_ACTIVE && act_delta != 0) {
650ef743ce6SJohn Dyson 				vm_page_activate(p);
651bb7858eaSJeff Roberson 				p->act_count += act_delta;
652c8c4b40cSJohn Dyson 			} else if (p->queue == PQ_ACTIVE) {
653bb7858eaSJeff Roberson 				if (act_delta == 0) {
654ce186587SAlan Cox 					p->act_count -= min(p->act_count,
655ce186587SAlan Cox 					    ACT_DECLINE);
65690776bd7SJeff Roberson 					if (!remove_mode && p->act_count == 0) {
6574fec79beSAlan Cox 						pmap_remove_all(p);
65826f9a767SRodney W. Grimes 						vm_page_deactivate(p);
6598d220203SAlan Cox 					} else
6608d220203SAlan Cox 						vm_page_requeue(p);
661c8c4b40cSJohn Dyson 				} else {
662eaf13dd7SJohn Dyson 					vm_page_activate(p);
663ce186587SAlan Cox 					if (p->act_count < ACT_MAX -
664ce186587SAlan Cox 					    ACT_ADVANCE)
66538efa82bSJohn Dyson 						p->act_count += ACT_ADVANCE;
6668d220203SAlan Cox 					vm_page_requeue(p);
667ce186587SAlan Cox 				}
668ce186587SAlan Cox 			} else if (p->queue == PQ_INACTIVE)
669ce186587SAlan Cox 				pmap_remove_all(p);
6702965a453SKip Macy 			vm_page_unlock(p);
67126f9a767SRodney W. Grimes 		}
672ecf6279fSAlan Cox 		if ((backing_object = object->backing_object) == NULL)
673ecf6279fSAlan Cox 			goto unlock_return;
674e23b0a19SAlan Cox 		VM_OBJECT_RLOCK(backing_object);
675ecf6279fSAlan Cox 		if (object != first_object)
676e23b0a19SAlan Cox 			VM_OBJECT_RUNLOCK(object);
67738efa82bSJohn Dyson 	}
678ecf6279fSAlan Cox unlock_return:
679ecf6279fSAlan Cox 	if (object != first_object)
680e23b0a19SAlan Cox 		VM_OBJECT_RUNLOCK(object);
68126f9a767SRodney W. Grimes }
68226f9a767SRodney W. Grimes 
68326f9a767SRodney W. Grimes /*
68426f9a767SRodney W. Grimes  * deactivate some number of pages in a map, try to do it fairly, but
68526f9a767SRodney W. Grimes  * that is really hard to do.
68626f9a767SRodney W. Grimes  */
687cd41fc12SDavid Greenman static void
68838efa82bSJohn Dyson vm_pageout_map_deactivate_pages(map, desired)
68926f9a767SRodney W. Grimes 	vm_map_t map;
690ecf6279fSAlan Cox 	long desired;
69126f9a767SRodney W. Grimes {
69226f9a767SRodney W. Grimes 	vm_map_entry_t tmpe;
69338efa82bSJohn Dyson 	vm_object_t obj, bigobj;
69430105b9eSTor Egge 	int nothingwired;
6950d94caffSDavid Greenman 
696d974f03cSAlan Cox 	if (!vm_map_trylock(map))
69726f9a767SRodney W. Grimes 		return;
69838efa82bSJohn Dyson 
69938efa82bSJohn Dyson 	bigobj = NULL;
70030105b9eSTor Egge 	nothingwired = TRUE;
70138efa82bSJohn Dyson 
70238efa82bSJohn Dyson 	/*
70338efa82bSJohn Dyson 	 * first, search out the biggest object, and try to free pages from
70438efa82bSJohn Dyson 	 * that.
70538efa82bSJohn Dyson 	 */
70626f9a767SRodney W. Grimes 	tmpe = map->header.next;
70738efa82bSJohn Dyson 	while (tmpe != &map->header) {
7089fdfe602SMatthew Dillon 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
70938efa82bSJohn Dyson 			obj = tmpe->object.vm_object;
710e23b0a19SAlan Cox 			if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
7110774dfb3SAlan Cox 				if (obj->shadow_count <= 1 &&
7120774dfb3SAlan Cox 				    (bigobj == NULL ||
7130774dfb3SAlan Cox 				     bigobj->resident_page_count < obj->resident_page_count)) {
7140774dfb3SAlan Cox 					if (bigobj != NULL)
715e23b0a19SAlan Cox 						VM_OBJECT_RUNLOCK(bigobj);
71638efa82bSJohn Dyson 					bigobj = obj;
7170774dfb3SAlan Cox 				} else
718e23b0a19SAlan Cox 					VM_OBJECT_RUNLOCK(obj);
71938efa82bSJohn Dyson 			}
72038efa82bSJohn Dyson 		}
72130105b9eSTor Egge 		if (tmpe->wired_count > 0)
72230105b9eSTor Egge 			nothingwired = FALSE;
72338efa82bSJohn Dyson 		tmpe = tmpe->next;
72438efa82bSJohn Dyson 	}
72538efa82bSJohn Dyson 
7260774dfb3SAlan Cox 	if (bigobj != NULL) {
727ecf6279fSAlan Cox 		vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
728e23b0a19SAlan Cox 		VM_OBJECT_RUNLOCK(bigobj);
7290774dfb3SAlan Cox 	}
73038efa82bSJohn Dyson 	/*
73138efa82bSJohn Dyson 	 * Next, hunt around for other pages to deactivate.  We actually
73238efa82bSJohn Dyson 	 * do this search sort of wrong -- .text first is not the best idea.
73338efa82bSJohn Dyson 	 */
73438efa82bSJohn Dyson 	tmpe = map->header.next;
73538efa82bSJohn Dyson 	while (tmpe != &map->header) {
736b1028ad1SLuoqi Chen 		if (pmap_resident_count(vm_map_pmap(map)) <= desired)
73738efa82bSJohn Dyson 			break;
7389fdfe602SMatthew Dillon 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
73938efa82bSJohn Dyson 			obj = tmpe->object.vm_object;
7400774dfb3SAlan Cox 			if (obj != NULL) {
741e23b0a19SAlan Cox 				VM_OBJECT_RLOCK(obj);
742ecf6279fSAlan Cox 				vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
743e23b0a19SAlan Cox 				VM_OBJECT_RUNLOCK(obj);
7440774dfb3SAlan Cox 			}
74538efa82bSJohn Dyson 		}
74626f9a767SRodney W. Grimes 		tmpe = tmpe->next;
74738857e7fSAlan Cox 	}
74838efa82bSJohn Dyson 
74938efa82bSJohn Dyson 	/*
75038efa82bSJohn Dyson 	 * Remove all mappings if a process is swapped out, this will free page
75138efa82bSJohn Dyson 	 * table pages.
75238efa82bSJohn Dyson 	 */
75338857e7fSAlan Cox 	if (desired == 0 && nothingwired) {
7548d01a3b2SNathan Whitehorn 		pmap_remove(vm_map_pmap(map), vm_map_min(map),
7558d01a3b2SNathan Whitehorn 		    vm_map_max(map));
75638857e7fSAlan Cox 	}
757938b0f5bSMarcel Moolenaar 
75838efa82bSJohn Dyson 	vm_map_unlock(map);
75926f9a767SRodney W. Grimes }
760a1287949SEivind Eklund #endif		/* !defined(NO_SWAPPING) */
761df8bae1dSRodney W. Grimes 
7621c7c3c6aSMatthew Dillon /*
76334d8b7eaSJeff Roberson  * Attempt to acquire all of the necessary locks to launder a page and
76434d8b7eaSJeff Roberson  * then call through the clustering layer to PUTPAGES.  Wait a short
76534d8b7eaSJeff Roberson  * time for a vnode lock.
76634d8b7eaSJeff Roberson  *
76734d8b7eaSJeff Roberson  * Requires the page and object lock on entry, releases both before return.
76834d8b7eaSJeff Roberson  * Returns 0 on success and an errno otherwise.
76934d8b7eaSJeff Roberson  */
77034d8b7eaSJeff Roberson static int
77134d8b7eaSJeff Roberson vm_pageout_clean(vm_page_t m)
77234d8b7eaSJeff Roberson {
77334d8b7eaSJeff Roberson 	struct vnode *vp;
77434d8b7eaSJeff Roberson 	struct mount *mp;
77534d8b7eaSJeff Roberson 	vm_object_t object;
77634d8b7eaSJeff Roberson 	vm_pindex_t pindex;
77734d8b7eaSJeff Roberson 	int error, lockmode;
77834d8b7eaSJeff Roberson 
77934d8b7eaSJeff Roberson 	vm_page_assert_locked(m);
78034d8b7eaSJeff Roberson 	object = m->object;
78134d8b7eaSJeff Roberson 	VM_OBJECT_ASSERT_WLOCKED(object);
78234d8b7eaSJeff Roberson 	error = 0;
78334d8b7eaSJeff Roberson 	vp = NULL;
78434d8b7eaSJeff Roberson 	mp = NULL;
78534d8b7eaSJeff Roberson 
78634d8b7eaSJeff Roberson 	/*
78734d8b7eaSJeff Roberson 	 * The object is already known NOT to be dead.   It
78834d8b7eaSJeff Roberson 	 * is possible for the vget() to block the whole
78934d8b7eaSJeff Roberson 	 * pageout daemon, but the new low-memory handling
79034d8b7eaSJeff Roberson 	 * code should prevent it.
79134d8b7eaSJeff Roberson 	 *
79234d8b7eaSJeff Roberson 	 * We can't wait forever for the vnode lock, we might
79334d8b7eaSJeff Roberson 	 * deadlock due to a vn_read() getting stuck in
79434d8b7eaSJeff Roberson 	 * vm_wait while holding this vnode.  We skip the
79534d8b7eaSJeff Roberson 	 * vnode if we can't get it in a reasonable amount
79634d8b7eaSJeff Roberson 	 * of time.
79734d8b7eaSJeff Roberson 	 */
79834d8b7eaSJeff Roberson 	if (object->type == OBJT_VNODE) {
79934d8b7eaSJeff Roberson 		vm_page_unlock(m);
80034d8b7eaSJeff Roberson 		vp = object->handle;
80134d8b7eaSJeff Roberson 		if (vp->v_type == VREG &&
80234d8b7eaSJeff Roberson 		    vn_start_write(vp, &mp, V_NOWAIT) != 0) {
80334d8b7eaSJeff Roberson 			mp = NULL;
80434d8b7eaSJeff Roberson 			error = EDEADLK;
80534d8b7eaSJeff Roberson 			goto unlock_all;
80634d8b7eaSJeff Roberson 		}
80734d8b7eaSJeff Roberson 		KASSERT(mp != NULL,
80834d8b7eaSJeff Roberson 		    ("vp %p with NULL v_mount", vp));
80934d8b7eaSJeff Roberson 		vm_object_reference_locked(object);
81034d8b7eaSJeff Roberson 		pindex = m->pindex;
81134d8b7eaSJeff Roberson 		VM_OBJECT_WUNLOCK(object);
81234d8b7eaSJeff Roberson 		lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
81334d8b7eaSJeff Roberson 		    LK_SHARED : LK_EXCLUSIVE;
81434d8b7eaSJeff Roberson 		if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
81534d8b7eaSJeff Roberson 			vp = NULL;
81634d8b7eaSJeff Roberson 			error = EDEADLK;
81734d8b7eaSJeff Roberson 			goto unlock_mp;
81834d8b7eaSJeff Roberson 		}
81934d8b7eaSJeff Roberson 		VM_OBJECT_WLOCK(object);
82034d8b7eaSJeff Roberson 		vm_page_lock(m);
82134d8b7eaSJeff Roberson 		/*
82234d8b7eaSJeff Roberson 		 * While the object and page were unlocked, the page
82334d8b7eaSJeff Roberson 		 * may have been:
82434d8b7eaSJeff Roberson 		 * (1) moved to a different queue,
82534d8b7eaSJeff Roberson 		 * (2) reallocated to a different object,
82634d8b7eaSJeff Roberson 		 * (3) reallocated to a different offset, or
82734d8b7eaSJeff Roberson 		 * (4) cleaned.
82834d8b7eaSJeff Roberson 		 */
82934d8b7eaSJeff Roberson 		if (m->queue != PQ_INACTIVE || m->object != object ||
83034d8b7eaSJeff Roberson 		    m->pindex != pindex || m->dirty == 0) {
83134d8b7eaSJeff Roberson 			vm_page_unlock(m);
83234d8b7eaSJeff Roberson 			error = ENXIO;
83334d8b7eaSJeff Roberson 			goto unlock_all;
83434d8b7eaSJeff Roberson 		}
83534d8b7eaSJeff Roberson 
83634d8b7eaSJeff Roberson 		/*
83734d8b7eaSJeff Roberson 		 * The page may have been busied or held while the object
83834d8b7eaSJeff Roberson 		 * and page locks were released.
83934d8b7eaSJeff Roberson 		 */
84034d8b7eaSJeff Roberson 		if (vm_page_busied(m) || m->hold_count != 0) {
84134d8b7eaSJeff Roberson 			vm_page_unlock(m);
84234d8b7eaSJeff Roberson 			error = EBUSY;
84334d8b7eaSJeff Roberson 			goto unlock_all;
84434d8b7eaSJeff Roberson 		}
84534d8b7eaSJeff Roberson 	}
84634d8b7eaSJeff Roberson 
84734d8b7eaSJeff Roberson 	/*
84834d8b7eaSJeff Roberson 	 * If a page is dirty, then it is either being washed
84934d8b7eaSJeff Roberson 	 * (but not yet cleaned) or it is still in the
85034d8b7eaSJeff Roberson 	 * laundry.  If it is still in the laundry, then we
85134d8b7eaSJeff Roberson 	 * start the cleaning operation.
85234d8b7eaSJeff Roberson 	 */
85334d8b7eaSJeff Roberson 	if (vm_pageout_cluster(m) == 0)
85434d8b7eaSJeff Roberson 		error = EIO;
85534d8b7eaSJeff Roberson 
85634d8b7eaSJeff Roberson unlock_all:
85734d8b7eaSJeff Roberson 	VM_OBJECT_WUNLOCK(object);
85834d8b7eaSJeff Roberson 
85934d8b7eaSJeff Roberson unlock_mp:
86034d8b7eaSJeff Roberson 	vm_page_lock_assert(m, MA_NOTOWNED);
86134d8b7eaSJeff Roberson 	if (mp != NULL) {
86234d8b7eaSJeff Roberson 		if (vp != NULL)
86334d8b7eaSJeff Roberson 			vput(vp);
86434d8b7eaSJeff Roberson 		vm_object_deallocate(object);
86534d8b7eaSJeff Roberson 		vn_finished_write(mp);
86634d8b7eaSJeff Roberson 	}
86734d8b7eaSJeff Roberson 
86834d8b7eaSJeff Roberson 	return (error);
86934d8b7eaSJeff Roberson }
87034d8b7eaSJeff Roberson 
87134d8b7eaSJeff Roberson /*
872df8bae1dSRodney W. Grimes  *	vm_pageout_scan does the dirty work for the pageout daemon.
873d9e23210SJeff Roberson  *
874d9e23210SJeff Roberson  *	pass 0 - Update active LRU/deactivate pages
875d9e23210SJeff Roberson  *	pass 1 - Move inactive to cache or free
876d9e23210SJeff Roberson  *	pass 2 - Launder dirty pages
877df8bae1dSRodney W. Grimes  */
8782b6b0df7SMatthew Dillon static void
879449c2e92SKonstantin Belousov vm_pageout_scan(struct vm_domain *vmd, int pass)
880df8bae1dSRodney W. Grimes {
881502ba6e4SJohn Dyson 	vm_page_t m, next;
8828d220203SAlan Cox 	struct vm_pagequeue *pq;
883df8bae1dSRodney W. Grimes 	vm_object_t object;
88422cf98d1SAlan Cox 	long min_scan;
88540aa80a7SAlan Cox 	int act_delta, addl_page_shortage, deficit, error, maxlaunder, maxscan;
88676386c7eSKonstantin Belousov 	int page_shortage, scan_tick, scanned, starting_page_shortage;
88776386c7eSKonstantin Belousov 	int vnodes_skipped;
88840aa80a7SAlan Cox 	boolean_t pageout_ok, queues_locked;
8890d94caffSDavid Greenman 
890df8bae1dSRodney W. Grimes 	/*
891d9e23210SJeff Roberson 	 * If we need to reclaim memory ask kernel caches to return
892c9612b2dSJeff Roberson 	 * some.  We rate limit to avoid thrashing.
893d9e23210SJeff Roberson 	 */
894c9612b2dSJeff Roberson 	if (vmd == &vm_dom[0] && pass > 0 &&
895a6bf3a9eSRyan Stone 	    (time_uptime - lowmem_uptime) >= lowmem_period) {
896d9e23210SJeff Roberson 		/*
897855a310fSJeff Roberson 		 * Decrease registered cache sizes.
898855a310fSJeff Roberson 		 */
89914a0d74eSSteven Hartland 		SDT_PROBE0(vm, , , vm__lowmem_scan);
900855a310fSJeff Roberson 		EVENTHANDLER_INVOKE(vm_lowmem, 0);
901855a310fSJeff Roberson 		/*
902d9e23210SJeff Roberson 		 * We do this explicitly after the caches have been
903d9e23210SJeff Roberson 		 * drained above.
904855a310fSJeff Roberson 		 */
905855a310fSJeff Roberson 		uma_reclaim();
906a6bf3a9eSRyan Stone 		lowmem_uptime = time_uptime;
907d9e23210SJeff Roberson 	}
9085985940eSJohn Dyson 
909311e34e2SKonstantin Belousov 	/*
91096240c89SEitan Adler 	 * The addl_page_shortage is the number of temporarily
911311e34e2SKonstantin Belousov 	 * stuck pages in the inactive queue.  In other words, the
912449c2e92SKonstantin Belousov 	 * number of pages from the inactive count that should be
913311e34e2SKonstantin Belousov 	 * discounted in setting the target for the active queue scan.
914311e34e2SKonstantin Belousov 	 */
9159099545aSAlan Cox 	addl_page_shortage = 0;
9169099545aSAlan Cox 
9171c7c3c6aSMatthew Dillon 	/*
9181c7c3c6aSMatthew Dillon 	 * Calculate the number of pages we want to either free or move
9192b6b0df7SMatthew Dillon 	 * to the cache.
9201c7c3c6aSMatthew Dillon 	 */
92160196cdaSAlan Cox 	if (pass > 0) {
92260196cdaSAlan Cox 		deficit = atomic_readandclear_int(&vm_pageout_deficit);
9239099545aSAlan Cox 		page_shortage = vm_paging_target() + deficit;
92460196cdaSAlan Cox 	} else
92560196cdaSAlan Cox 		page_shortage = deficit = 0;
92676386c7eSKonstantin Belousov 	starting_page_shortage = page_shortage;
9271c7c3c6aSMatthew Dillon 
928936524aaSMatthew Dillon 	/*
9292b6b0df7SMatthew Dillon 	 * maxlaunder limits the number of dirty pages we flush per scan.
9302b6b0df7SMatthew Dillon 	 * For most systems a smaller value (16 or 32) is more robust under
9312b6b0df7SMatthew Dillon 	 * extreme memory and disk pressure because any unnecessary writes
9322b6b0df7SMatthew Dillon 	 * to disk can result in extreme performance degredation.  However,
9332b6b0df7SMatthew Dillon 	 * systems with excessive dirty pages (especially when MAP_NOSYNC is
9342b6b0df7SMatthew Dillon 	 * used) will die horribly with limited laundering.  If the pageout
9352b6b0df7SMatthew Dillon 	 * daemon cannot clean enough pages in the first pass, we let it go
9362b6b0df7SMatthew Dillon 	 * all out in succeeding passes.
9371c7c3c6aSMatthew Dillon 	 */
9382b6b0df7SMatthew Dillon 	if ((maxlaunder = vm_max_launder) <= 1)
9392b6b0df7SMatthew Dillon 		maxlaunder = 1;
940d9e23210SJeff Roberson 	if (pass > 1)
9412b6b0df7SMatthew Dillon 		maxlaunder = 10000;
9428d220203SAlan Cox 
94340aa80a7SAlan Cox 	vnodes_skipped = 0;
94440aa80a7SAlan Cox 
9458d220203SAlan Cox 	/*
9468d220203SAlan Cox 	 * Start scanning the inactive queue for pages we can move to the
9478d220203SAlan Cox 	 * cache or free.  The scan will stop when the target is reached or
9488d220203SAlan Cox 	 * we have scanned the entire inactive queue.  Note that m->act_count
9498d220203SAlan Cox 	 * is not used to form decisions for the inactive queue, only for the
9508d220203SAlan Cox 	 * active queue.
9518d220203SAlan Cox 	 */
952449c2e92SKonstantin Belousov 	pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
953449c2e92SKonstantin Belousov 	maxscan = pq->pq_cnt;
9548d220203SAlan Cox 	vm_pagequeue_lock(pq);
9558d220203SAlan Cox 	queues_locked = TRUE;
9568d220203SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl);
9571c7c3c6aSMatthew Dillon 	     m != NULL && maxscan-- > 0 && page_shortage > 0;
958e929c00dSKirk McKusick 	     m = next) {
9598d220203SAlan Cox 		vm_pagequeue_assert_locked(pq);
96048cc2fc7SKonstantin Belousov 		KASSERT(queues_locked, ("unlocked queues"));
961d4961bcbSKonstantin Belousov 		KASSERT(m->queue == PQ_INACTIVE, ("Inactive queue %p", m));
962df8bae1dSRodney W. Grimes 
9638d220203SAlan Cox 		PCPU_INC(cnt.v_pdpages);
964c325e866SKonstantin Belousov 		next = TAILQ_NEXT(m, plinks.q);
965df8bae1dSRodney W. Grimes 
966936524aaSMatthew Dillon 		/*
967936524aaSMatthew Dillon 		 * skip marker pages
968936524aaSMatthew Dillon 		 */
969936524aaSMatthew Dillon 		if (m->flags & PG_MARKER)
970936524aaSMatthew Dillon 			continue;
971936524aaSMatthew Dillon 
9727900f95dSKonstantin Belousov 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
9737900f95dSKonstantin Belousov 		    ("Fictitious page %p cannot be in inactive queue", m));
9747900f95dSKonstantin Belousov 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
9757900f95dSKonstantin Belousov 		    ("Unmanaged page %p cannot be in inactive queue", m));
9767900f95dSKonstantin Belousov 
9778c616246SKonstantin Belousov 		/*
978311e34e2SKonstantin Belousov 		 * The page or object lock acquisitions fail if the
979311e34e2SKonstantin Belousov 		 * page was removed from the queue or moved to a
980311e34e2SKonstantin Belousov 		 * different position within the queue.  In either
981311e34e2SKonstantin Belousov 		 * case, addl_page_shortage should not be incremented.
9828c616246SKonstantin Belousov 		 */
983a3aeedabSAlan Cox 		if (!vm_pageout_page_lock(m, &next))
984a3aeedabSAlan Cox 			goto unlock_page;
985a3aeedabSAlan Cox 		else if (m->hold_count != 0) {
986a3aeedabSAlan Cox 			/*
987a3aeedabSAlan Cox 			 * Held pages are essentially stuck in the
988a3aeedabSAlan Cox 			 * queue.  So, they ought to be discounted
989a3aeedabSAlan Cox 			 * from the inactive count.  See the
990a3aeedabSAlan Cox 			 * calculation of the page_shortage for the
991a3aeedabSAlan Cox 			 * loop over the active queue below.
992a3aeedabSAlan Cox 			 */
993a3aeedabSAlan Cox 			addl_page_shortage++;
994a3aeedabSAlan Cox 			goto unlock_page;
995df8bae1dSRodney W. Grimes 		}
9969ee2165fSAlan Cox 		object = m->object;
997a3aeedabSAlan Cox 		if (!VM_OBJECT_TRYWLOCK(object)) {
998a3aeedabSAlan Cox 			if (!vm_pageout_fallback_object_lock(m, &next))
999a3aeedabSAlan Cox 				goto unlock_object;
1000a3aeedabSAlan Cox 			else if (m->hold_count != 0) {
1001b182ec9eSJohn Dyson 				addl_page_shortage++;
1002a3aeedabSAlan Cox 				goto unlock_object;
1003a3aeedabSAlan Cox 			}
1004a3aeedabSAlan Cox 		}
1005a3aeedabSAlan Cox 		if (vm_page_busied(m)) {
1006a3aeedabSAlan Cox 			/*
1007a3aeedabSAlan Cox 			 * Don't mess with busy pages.  Leave them at
1008a3aeedabSAlan Cox 			 * the front of the queue.  Most likely, they
1009a3aeedabSAlan Cox 			 * are being paged out and will leave the
1010a3aeedabSAlan Cox 			 * queue shortly after the scan finishes.  So,
1011a3aeedabSAlan Cox 			 * they ought to be discounted from the
1012a3aeedabSAlan Cox 			 * inactive count.
1013a3aeedabSAlan Cox 			 */
1014a3aeedabSAlan Cox 			addl_page_shortage++;
1015a3aeedabSAlan Cox unlock_object:
1016a3aeedabSAlan Cox 			VM_OBJECT_WUNLOCK(object);
1017a3aeedabSAlan Cox unlock_page:
1018a3aeedabSAlan Cox 			vm_page_unlock(m);
101926f9a767SRodney W. Grimes 			continue;
102026f9a767SRodney W. Grimes 		}
1021a3aeedabSAlan Cox 		KASSERT(m->hold_count == 0, ("Held page %p", m));
1022bd7e5f99SJohn Dyson 
10237e006499SJohn Dyson 		/*
10248d220203SAlan Cox 		 * We unlock the inactive page queue, invalidating the
102548cc2fc7SKonstantin Belousov 		 * 'next' pointer.  Use our marker to remember our
102648cc2fc7SKonstantin Belousov 		 * place.
102748cc2fc7SKonstantin Belousov 		 */
1028c325e866SKonstantin Belousov 		TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
10298d220203SAlan Cox 		vm_pagequeue_unlock(pq);
103048cc2fc7SKonstantin Belousov 		queues_locked = FALSE;
103148cc2fc7SKonstantin Belousov 
103248cc2fc7SKonstantin Belousov 		/*
10338748f58cSKonstantin Belousov 		 * Invalid pages can be easily freed. They cannot be
10348748f58cSKonstantin Belousov 		 * mapped, vm_page_free() asserts this.
1035776f729cSKonstantin Belousov 		 */
10368748f58cSKonstantin Belousov 		if (m->valid == 0)
10378748f58cSKonstantin Belousov 			goto free_page;
1038776f729cSKonstantin Belousov 
1039776f729cSKonstantin Belousov 		/*
1040960810ccSAlan Cox 		 * If the page has been referenced and the object is not dead,
1041960810ccSAlan Cox 		 * reactivate or requeue the page depending on whether the
1042960810ccSAlan Cox 		 * object is mapped.
10437e006499SJohn Dyson 		 */
1044bb7858eaSJeff Roberson 		if ((m->aflags & PGA_REFERENCED) != 0) {
1045bb7858eaSJeff Roberson 			vm_page_aflag_clear(m, PGA_REFERENCED);
1046bb7858eaSJeff Roberson 			act_delta = 1;
104786fa2471SAlan Cox 		} else
104886fa2471SAlan Cox 			act_delta = 0;
1049bb7858eaSJeff Roberson 		if (object->ref_count != 0) {
1050bb7858eaSJeff Roberson 			act_delta += pmap_ts_referenced(m);
1051bb7858eaSJeff Roberson 		} else {
1052bb7858eaSJeff Roberson 			KASSERT(!pmap_page_is_mapped(m),
1053bb7858eaSJeff Roberson 			    ("vm_pageout_scan: page %p is mapped", m));
10542fe6e4d7SDavid Greenman 		}
1055bb7858eaSJeff Roberson 		if (act_delta != 0) {
105686fa2471SAlan Cox 			if (object->ref_count != 0) {
105726f9a767SRodney W. Grimes 				vm_page_activate(m);
1058960810ccSAlan Cox 
1059960810ccSAlan Cox 				/*
1060960810ccSAlan Cox 				 * Increase the activation count if the page
1061960810ccSAlan Cox 				 * was referenced while in the inactive queue.
1062960810ccSAlan Cox 				 * This makes it less likely that the page will
1063960810ccSAlan Cox 				 * be returned prematurely to the inactive
1064960810ccSAlan Cox 				 * queue.
1065960810ccSAlan Cox  				 */
1066bb7858eaSJeff Roberson 				m->act_count += act_delta + ACT_ADVANCE;
1067960810ccSAlan Cox 				goto drop_page;
106827a9fb2fSAlan Cox 			} else if ((object->flags & OBJ_DEAD) == 0)
106927a9fb2fSAlan Cox 				goto requeue_page;
1070960810ccSAlan Cox 		}
107167bf6868SJohn Dyson 
10727e006499SJohn Dyson 		/*
10739fc4739dSAlan Cox 		 * If the page appears to be clean at the machine-independent
10749fc4739dSAlan Cox 		 * layer, then remove all of its mappings from the pmap in
10759fc4739dSAlan Cox 		 * anticipation of placing it onto the cache queue.  If,
10769fc4739dSAlan Cox 		 * however, any of the page's mappings allow write access,
10779fc4739dSAlan Cox 		 * then the page may still be modified until the last of those
10789fc4739dSAlan Cox 		 * mappings are removed.
10797e006499SJohn Dyson 		 */
1080aa044135SAlan Cox 		if (object->ref_count != 0) {
10819fc4739dSAlan Cox 			vm_page_test_dirty(m);
1082aa044135SAlan Cox 			if (m->dirty == 0)
1083b78ddb0bSAlan Cox 				pmap_remove_all(m);
1084aa044135SAlan Cox 		}
1085dcbcd518SBruce Evans 
1086776f729cSKonstantin Belousov 		if (m->dirty == 0) {
10876989c456SAlan Cox 			/*
108878afdce6SAlan Cox 			 * Clean pages can be freed.
10896989c456SAlan Cox 			 */
10908748f58cSKonstantin Belousov free_page:
109178afdce6SAlan Cox 			vm_page_free(m);
109278afdce6SAlan Cox 			PCPU_INC(cnt.v_dfree);
10931c7c3c6aSMatthew Dillon 			--page_shortage;
1094960810ccSAlan Cox 		} else if ((object->flags & OBJ_DEAD) != 0) {
1095960810ccSAlan Cox 			/*
1096960810ccSAlan Cox 			 * Leave dirty pages from dead objects at the front of
1097960810ccSAlan Cox 			 * the queue.  They are being paged out and freed by
1098960810ccSAlan Cox 			 * the thread that destroyed the object.  They will
1099960810ccSAlan Cox 			 * leave the queue shortly after the scan finishes, so
1100960810ccSAlan Cox 			 * they should be discounted from the inactive count.
1101960810ccSAlan Cox 			 */
1102960810ccSAlan Cox 			addl_page_shortage++;
1103d9e23210SJeff Roberson 		} else if ((m->flags & PG_WINATCFLS) == 0 && pass < 2) {
11047e006499SJohn Dyson 			/*
11052b6b0df7SMatthew Dillon 			 * Dirty pages need to be paged out, but flushing
1106ab46f63eSJohn Baldwin 			 * a page is extremely expensive versus freeing
11072b6b0df7SMatthew Dillon 			 * a clean page.  Rather then artificially limiting
11082b6b0df7SMatthew Dillon 			 * the number of pages we can flush, we instead give
11092b6b0df7SMatthew Dillon 			 * dirty pages extra priority on the inactive queue
11102b6b0df7SMatthew Dillon 			 * by forcing them to be cycled through the queue
11112b6b0df7SMatthew Dillon 			 * twice before being flushed, after which the
11122b6b0df7SMatthew Dillon 			 * (now clean) page will cycle through once more
11132b6b0df7SMatthew Dillon 			 * before being freed.  This significantly extends
11142b6b0df7SMatthew Dillon 			 * the thrash point for a heavily loaded machine.
11157e006499SJohn Dyson 			 */
11163407fefeSKonstantin Belousov 			m->flags |= PG_WINATCFLS;
111727a9fb2fSAlan Cox requeue_page:
11188d220203SAlan Cox 			vm_pagequeue_lock(pq);
111948cc2fc7SKonstantin Belousov 			queues_locked = TRUE;
11208d220203SAlan Cox 			vm_page_requeue_locked(m);
11210d94caffSDavid Greenman 		} else if (maxlaunder > 0) {
11222b6b0df7SMatthew Dillon 			/*
11232b6b0df7SMatthew Dillon 			 * We always want to try to flush some dirty pages if
11242b6b0df7SMatthew Dillon 			 * we encounter them, to keep the system stable.
11252b6b0df7SMatthew Dillon 			 * Normally this number is small, but under extreme
11262b6b0df7SMatthew Dillon 			 * pressure where there are insufficient clean pages
11272b6b0df7SMatthew Dillon 			 * on the inactive queue, we may have to go all out.
11282b6b0df7SMatthew Dillon 			 */
11290d94caffSDavid Greenman 
113040aa80a7SAlan Cox 			if (object->type != OBJT_SWAP &&
113140aa80a7SAlan Cox 			    object->type != OBJT_DEFAULT)
113240aa80a7SAlan Cox 				pageout_ok = TRUE;
113340aa80a7SAlan Cox 			else if (disable_swap_pageouts)
113440aa80a7SAlan Cox 				pageout_ok = FALSE;
113540aa80a7SAlan Cox 			else if (defer_swap_pageouts)
113640aa80a7SAlan Cox 				pageout_ok = vm_page_count_min();
113740aa80a7SAlan Cox 			else
113840aa80a7SAlan Cox 				pageout_ok = TRUE;
113927a9fb2fSAlan Cox 			if (!pageout_ok)
114027a9fb2fSAlan Cox 				goto requeue_page;
114134d8b7eaSJeff Roberson 			error = vm_pageout_clean(m);
11421c7c3c6aSMatthew Dillon 			/*
114334d8b7eaSJeff Roberson 			 * Decrement page_shortage on success to account for
11442b6b0df7SMatthew Dillon 			 * the (future) cleaned page.  Otherwise we could wind
11452b6b0df7SMatthew Dillon 			 * up laundering or cleaning too many pages.
11460d94caffSDavid Greenman 			 */
114734d8b7eaSJeff Roberson 			if (error == 0) {
114834d8b7eaSJeff Roberson 				page_shortage--;
114934d8b7eaSJeff Roberson 				maxlaunder--;
115034d8b7eaSJeff Roberson 			} else if (error == EDEADLK) {
115134d8b7eaSJeff Roberson 				pageout_lock_miss++;
115234d8b7eaSJeff Roberson 				vnodes_skipped++;
115334d8b7eaSJeff Roberson 			} else if (error == EBUSY) {
115434d8b7eaSJeff Roberson 				addl_page_shortage++;
115548cc2fc7SKonstantin Belousov 			}
115648cc2fc7SKonstantin Belousov 			vm_page_lock_assert(m, MA_NOTOWNED);
115748cc2fc7SKonstantin Belousov 			goto relock_queues;
115848cc2fc7SKonstantin Belousov 		}
1159776f729cSKonstantin Belousov drop_page:
116048cc2fc7SKonstantin Belousov 		vm_page_unlock(m);
116189f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
116248cc2fc7SKonstantin Belousov relock_queues:
116348cc2fc7SKonstantin Belousov 		if (!queues_locked) {
11648d220203SAlan Cox 			vm_pagequeue_lock(pq);
116548cc2fc7SKonstantin Belousov 			queues_locked = TRUE;
11666989c456SAlan Cox 		}
1167c325e866SKonstantin Belousov 		next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1168c325e866SKonstantin Belousov 		TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
11690d94caffSDavid Greenman 	}
11708d220203SAlan Cox 	vm_pagequeue_unlock(pq);
117126f9a767SRodney W. Grimes 
11729452b5edSAlan Cox #if !defined(NO_SWAPPING)
11739452b5edSAlan Cox 	/*
11749452b5edSAlan Cox 	 * Wakeup the swapout daemon if we didn't cache or free the targeted
11759452b5edSAlan Cox 	 * number of pages.
11769452b5edSAlan Cox 	 */
11779452b5edSAlan Cox 	if (vm_swap_enabled && page_shortage > 0)
11789452b5edSAlan Cox 		vm_req_vmdaemon(VM_SWAP_NORMAL);
11799452b5edSAlan Cox #endif
11809452b5edSAlan Cox 
11819452b5edSAlan Cox 	/*
11829452b5edSAlan Cox 	 * Wakeup the sync daemon if we skipped a vnode in a writeable object
11839452b5edSAlan Cox 	 * and we didn't cache or free enough pages.
11849452b5edSAlan Cox 	 */
11859452b5edSAlan Cox 	if (vnodes_skipped > 0 && page_shortage > vm_cnt.v_free_target -
11869452b5edSAlan Cox 	    vm_cnt.v_free_min)
11879452b5edSAlan Cox 		(void)speedup_syncer();
11889452b5edSAlan Cox 
1189df8bae1dSRodney W. Grimes 	/*
119076386c7eSKonstantin Belousov 	 * If the inactive queue scan fails repeatedly to meet its
119176386c7eSKonstantin Belousov 	 * target, kill the largest process.
119276386c7eSKonstantin Belousov 	 */
119376386c7eSKonstantin Belousov 	vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
119476386c7eSKonstantin Belousov 
119576386c7eSKonstantin Belousov 	/*
1196936524aaSMatthew Dillon 	 * Compute the number of pages we want to try to move from the
1197936524aaSMatthew Dillon 	 * active queue to the inactive queue.
11981c7c3c6aSMatthew Dillon 	 */
119944f1c916SBryan Drewery 	page_shortage = vm_cnt.v_inactive_target - vm_cnt.v_inactive_count +
12009099545aSAlan Cox 	    vm_paging_target() + deficit + addl_page_shortage;
12019099545aSAlan Cox 
1202114f62c6SJeff Roberson 	pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1203114f62c6SJeff Roberson 	vm_pagequeue_lock(pq);
12049099545aSAlan Cox 	maxscan = pq->pq_cnt;
12059099545aSAlan Cox 
1206d9e23210SJeff Roberson 	/*
1207d9e23210SJeff Roberson 	 * If we're just idle polling attempt to visit every
1208d9e23210SJeff Roberson 	 * active page within 'update_period' seconds.
1209d9e23210SJeff Roberson 	 */
121022cf98d1SAlan Cox 	scan_tick = ticks;
121122cf98d1SAlan Cox 	if (vm_pageout_update_period != 0) {
121222cf98d1SAlan Cox 		min_scan = pq->pq_cnt;
121322cf98d1SAlan Cox 		min_scan *= scan_tick - vmd->vmd_last_active_scan;
121422cf98d1SAlan Cox 		min_scan /= hz * vm_pageout_update_period;
121522cf98d1SAlan Cox 	} else
121622cf98d1SAlan Cox 		min_scan = 0;
121722cf98d1SAlan Cox 	if (min_scan > 0 || (page_shortage > 0 && maxscan > 0))
121822cf98d1SAlan Cox 		vmd->vmd_last_active_scan = scan_tick;
12191c7c3c6aSMatthew Dillon 
12201c7c3c6aSMatthew Dillon 	/*
122122cf98d1SAlan Cox 	 * Scan the active queue for pages that can be deactivated.  Update
122222cf98d1SAlan Cox 	 * the per-page activity counter and use it to identify deactivation
122322cf98d1SAlan Cox 	 * candidates.
12241c7c3c6aSMatthew Dillon 	 */
122522cf98d1SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
122622cf98d1SAlan Cox 	    min_scan || (page_shortage > 0 && scanned < maxscan)); m = next,
122722cf98d1SAlan Cox 	    scanned++) {
1228f35329acSJohn Dyson 
12299cf51988SAlan Cox 		KASSERT(m->queue == PQ_ACTIVE,
1230d3c09dd7SAlan Cox 		    ("vm_pageout_scan: page %p isn't active", m));
1231f35329acSJohn Dyson 
1232c325e866SKonstantin Belousov 		next = TAILQ_NEXT(m, plinks.q);
123322cf98d1SAlan Cox 		if ((m->flags & PG_MARKER) != 0)
12348dbca793STor Egge 			continue;
12357900f95dSKonstantin Belousov 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
12367900f95dSKonstantin Belousov 		    ("Fictitious page %p cannot be in active queue", m));
12377900f95dSKonstantin Belousov 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
12387900f95dSKonstantin Belousov 		    ("Unmanaged page %p cannot be in active queue", m));
12399ee2165fSAlan Cox 		if (!vm_pageout_page_lock(m, &next)) {
12408c616246SKonstantin Belousov 			vm_page_unlock(m);
12412965a453SKip Macy 			continue;
12422965a453SKip Macy 		}
1243b18bfc3dSJohn Dyson 
1244b18bfc3dSJohn Dyson 		/*
1245b18bfc3dSJohn Dyson 		 * The count for pagedaemon pages is done after checking the
1246956f3135SPhilippe Charnier 		 * page for eligibility...
1247b18bfc3dSJohn Dyson 		 */
12488d220203SAlan Cox 		PCPU_INC(cnt.v_pdpages);
1249ef743ce6SJohn Dyson 
12507e006499SJohn Dyson 		/*
12517e006499SJohn Dyson 		 * Check to see "how much" the page has been used.
12527e006499SJohn Dyson 		 */
125386fa2471SAlan Cox 		if ((m->aflags & PGA_REFERENCED) != 0) {
1254bb7858eaSJeff Roberson 			vm_page_aflag_clear(m, PGA_REFERENCED);
125586fa2471SAlan Cox 			act_delta = 1;
125686fa2471SAlan Cox 		} else
125786fa2471SAlan Cox 			act_delta = 0;
125886fa2471SAlan Cox 
1259274132acSJeff Roberson 		/*
1260274132acSJeff Roberson 		 * Unlocked object ref count check.  Two races are possible.
1261274132acSJeff Roberson 		 * 1) The ref was transitioning to zero and we saw non-zero,
1262274132acSJeff Roberson 		 *    the pmap bits will be checked unnecessarily.
1263274132acSJeff Roberson 		 * 2) The ref was transitioning to one and we saw zero.
1264274132acSJeff Roberson 		 *    The page lock prevents a new reference to this page so
1265274132acSJeff Roberson 		 *    we need not check the reference bits.
1266274132acSJeff Roberson 		 */
1267274132acSJeff Roberson 		if (m->object->ref_count != 0)
1268bb7858eaSJeff Roberson 			act_delta += pmap_ts_referenced(m);
1269bb7858eaSJeff Roberson 
1270bb7858eaSJeff Roberson 		/*
1271bb7858eaSJeff Roberson 		 * Advance or decay the act_count based on recent usage.
1272bb7858eaSJeff Roberson 		 */
127386fa2471SAlan Cox 		if (act_delta != 0) {
1274bb7858eaSJeff Roberson 			m->act_count += ACT_ADVANCE + act_delta;
127538efa82bSJohn Dyson 			if (m->act_count > ACT_MAX)
127638efa82bSJohn Dyson 				m->act_count = ACT_MAX;
127786fa2471SAlan Cox 		} else
127838efa82bSJohn Dyson 			m->act_count -= min(m->act_count, ACT_DECLINE);
1279bb7858eaSJeff Roberson 
1280bb7858eaSJeff Roberson 		/*
1281bb7858eaSJeff Roberson 		 * Move this page to the tail of the active or inactive
1282bb7858eaSJeff Roberson 		 * queue depending on usage.
1283bb7858eaSJeff Roberson 		 */
128486fa2471SAlan Cox 		if (m->act_count == 0) {
12858d220203SAlan Cox 			/* Dequeue to avoid later lock recursion. */
12868d220203SAlan Cox 			vm_page_dequeue_locked(m);
1287d4a272dbSJohn Dyson 			vm_page_deactivate(m);
1288bb7858eaSJeff Roberson 			page_shortage--;
12898d220203SAlan Cox 		} else
12908d220203SAlan Cox 			vm_page_requeue_locked(m);
12912965a453SKip Macy 		vm_page_unlock(m);
129226f9a767SRodney W. Grimes 	}
12938d220203SAlan Cox 	vm_pagequeue_unlock(pq);
1294ceb0cf87SJohn Dyson #if !defined(NO_SWAPPING)
1295ceb0cf87SJohn Dyson 	/*
1296ceb0cf87SJohn Dyson 	 * Idle process swapout -- run once per second.
1297ceb0cf87SJohn Dyson 	 */
1298ceb0cf87SJohn Dyson 	if (vm_swap_idle_enabled) {
1299ceb0cf87SJohn Dyson 		static long lsec;
1300227ee8a1SPoul-Henning Kamp 		if (time_second != lsec) {
130197824da3SAlan Cox 			vm_req_vmdaemon(VM_SWAP_IDLE);
1302227ee8a1SPoul-Henning Kamp 			lsec = time_second;
1303ceb0cf87SJohn Dyson 		}
1304ceb0cf87SJohn Dyson 	}
1305ceb0cf87SJohn Dyson #endif
13062025d69bSKonstantin Belousov }
13072025d69bSKonstantin Belousov 
1308449c2e92SKonstantin Belousov static int vm_pageout_oom_vote;
1309449c2e92SKonstantin Belousov 
1310449c2e92SKonstantin Belousov /*
1311449c2e92SKonstantin Belousov  * The pagedaemon threads randlomly select one to perform the
1312449c2e92SKonstantin Belousov  * OOM.  Trying to kill processes before all pagedaemons
1313449c2e92SKonstantin Belousov  * failed to reach free target is premature.
1314449c2e92SKonstantin Belousov  */
1315449c2e92SKonstantin Belousov static void
131676386c7eSKonstantin Belousov vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
131776386c7eSKonstantin Belousov     int starting_page_shortage)
1318449c2e92SKonstantin Belousov {
1319449c2e92SKonstantin Belousov 	int old_vote;
1320449c2e92SKonstantin Belousov 
132176386c7eSKonstantin Belousov 	if (starting_page_shortage <= 0 || starting_page_shortage !=
132276386c7eSKonstantin Belousov 	    page_shortage)
132376386c7eSKonstantin Belousov 		vmd->vmd_oom_seq = 0;
132476386c7eSKonstantin Belousov 	else
132576386c7eSKonstantin Belousov 		vmd->vmd_oom_seq++;
132676386c7eSKonstantin Belousov 	if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1327449c2e92SKonstantin Belousov 		if (vmd->vmd_oom) {
1328449c2e92SKonstantin Belousov 			vmd->vmd_oom = FALSE;
1329449c2e92SKonstantin Belousov 			atomic_subtract_int(&vm_pageout_oom_vote, 1);
1330449c2e92SKonstantin Belousov 		}
1331449c2e92SKonstantin Belousov 		return;
1332449c2e92SKonstantin Belousov 	}
1333449c2e92SKonstantin Belousov 
133476386c7eSKonstantin Belousov 	/*
133576386c7eSKonstantin Belousov 	 * Do not follow the call sequence until OOM condition is
133676386c7eSKonstantin Belousov 	 * cleared.
133776386c7eSKonstantin Belousov 	 */
133876386c7eSKonstantin Belousov 	vmd->vmd_oom_seq = 0;
133976386c7eSKonstantin Belousov 
1340449c2e92SKonstantin Belousov 	if (vmd->vmd_oom)
1341449c2e92SKonstantin Belousov 		return;
1342449c2e92SKonstantin Belousov 
1343449c2e92SKonstantin Belousov 	vmd->vmd_oom = TRUE;
1344449c2e92SKonstantin Belousov 	old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1345449c2e92SKonstantin Belousov 	if (old_vote != vm_ndomains - 1)
1346449c2e92SKonstantin Belousov 		return;
1347449c2e92SKonstantin Belousov 
1348449c2e92SKonstantin Belousov 	/*
1349449c2e92SKonstantin Belousov 	 * The current pagedaemon thread is the last in the quorum to
1350449c2e92SKonstantin Belousov 	 * start OOM.  Initiate the selection and signaling of the
1351449c2e92SKonstantin Belousov 	 * victim.
1352449c2e92SKonstantin Belousov 	 */
1353449c2e92SKonstantin Belousov 	vm_pageout_oom(VM_OOM_MEM);
1354449c2e92SKonstantin Belousov 
1355449c2e92SKonstantin Belousov 	/*
1356449c2e92SKonstantin Belousov 	 * After one round of OOM terror, recall our vote.  On the
1357449c2e92SKonstantin Belousov 	 * next pass, current pagedaemon would vote again if the low
1358449c2e92SKonstantin Belousov 	 * memory condition is still there, due to vmd_oom being
1359449c2e92SKonstantin Belousov 	 * false.
1360449c2e92SKonstantin Belousov 	 */
1361449c2e92SKonstantin Belousov 	vmd->vmd_oom = FALSE;
1362449c2e92SKonstantin Belousov 	atomic_subtract_int(&vm_pageout_oom_vote, 1);
1363449c2e92SKonstantin Belousov }
13642025d69bSKonstantin Belousov 
13653949873fSKonstantin Belousov /*
13663949873fSKonstantin Belousov  * The OOM killer is the page daemon's action of last resort when
13673949873fSKonstantin Belousov  * memory allocation requests have been stalled for a prolonged period
13683949873fSKonstantin Belousov  * of time because it cannot reclaim memory.  This function computes
13693949873fSKonstantin Belousov  * the approximate number of physical pages that could be reclaimed if
13703949873fSKonstantin Belousov  * the specified address space is destroyed.
13713949873fSKonstantin Belousov  *
13723949873fSKonstantin Belousov  * Private, anonymous memory owned by the address space is the
13733949873fSKonstantin Belousov  * principal resource that we expect to recover after an OOM kill.
13743949873fSKonstantin Belousov  * Since the physical pages mapped by the address space's COW entries
13753949873fSKonstantin Belousov  * are typically shared pages, they are unlikely to be released and so
13763949873fSKonstantin Belousov  * they are not counted.
13773949873fSKonstantin Belousov  *
13783949873fSKonstantin Belousov  * To get to the point where the page daemon runs the OOM killer, its
13793949873fSKonstantin Belousov  * efforts to write-back vnode-backed pages may have stalled.  This
13803949873fSKonstantin Belousov  * could be caused by a memory allocation deadlock in the write path
13813949873fSKonstantin Belousov  * that might be resolved by an OOM kill.  Therefore, physical pages
13823949873fSKonstantin Belousov  * belonging to vnode-backed objects are counted, because they might
13833949873fSKonstantin Belousov  * be freed without being written out first if the address space holds
13843949873fSKonstantin Belousov  * the last reference to an unlinked vnode.
13853949873fSKonstantin Belousov  *
13863949873fSKonstantin Belousov  * Similarly, physical pages belonging to OBJT_PHYS objects are
13873949873fSKonstantin Belousov  * counted because the address space might hold the last reference to
13883949873fSKonstantin Belousov  * the object.
13893949873fSKonstantin Belousov  */
13903949873fSKonstantin Belousov static long
13913949873fSKonstantin Belousov vm_pageout_oom_pagecount(struct vmspace *vmspace)
13923949873fSKonstantin Belousov {
13933949873fSKonstantin Belousov 	vm_map_t map;
13943949873fSKonstantin Belousov 	vm_map_entry_t entry;
13953949873fSKonstantin Belousov 	vm_object_t obj;
13963949873fSKonstantin Belousov 	long res;
13973949873fSKonstantin Belousov 
13983949873fSKonstantin Belousov 	map = &vmspace->vm_map;
13993949873fSKonstantin Belousov 	KASSERT(!map->system_map, ("system map"));
14003949873fSKonstantin Belousov 	sx_assert(&map->lock, SA_LOCKED);
14013949873fSKonstantin Belousov 	res = 0;
14023949873fSKonstantin Belousov 	for (entry = map->header.next; entry != &map->header;
14033949873fSKonstantin Belousov 	    entry = entry->next) {
14043949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
14053949873fSKonstantin Belousov 			continue;
14063949873fSKonstantin Belousov 		obj = entry->object.vm_object;
14073949873fSKonstantin Belousov 		if (obj == NULL)
14083949873fSKonstantin Belousov 			continue;
14093949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
14103949873fSKonstantin Belousov 		    obj->ref_count != 1)
14113949873fSKonstantin Belousov 			continue;
14123949873fSKonstantin Belousov 		switch (obj->type) {
14133949873fSKonstantin Belousov 		case OBJT_DEFAULT:
14143949873fSKonstantin Belousov 		case OBJT_SWAP:
14153949873fSKonstantin Belousov 		case OBJT_PHYS:
14163949873fSKonstantin Belousov 		case OBJT_VNODE:
14173949873fSKonstantin Belousov 			res += obj->resident_page_count;
14183949873fSKonstantin Belousov 			break;
14193949873fSKonstantin Belousov 		}
14203949873fSKonstantin Belousov 	}
14213949873fSKonstantin Belousov 	return (res);
14223949873fSKonstantin Belousov }
14233949873fSKonstantin Belousov 
14242025d69bSKonstantin Belousov void
14252025d69bSKonstantin Belousov vm_pageout_oom(int shortage)
14262025d69bSKonstantin Belousov {
14272025d69bSKonstantin Belousov 	struct proc *p, *bigproc;
14282025d69bSKonstantin Belousov 	vm_offset_t size, bigsize;
14292025d69bSKonstantin Belousov 	struct thread *td;
14306bed074cSKonstantin Belousov 	struct vmspace *vm;
14312025d69bSKonstantin Belousov 
14322025d69bSKonstantin Belousov 	/*
14331c58e4e5SJohn Baldwin 	 * We keep the process bigproc locked once we find it to keep anyone
14341c58e4e5SJohn Baldwin 	 * from messing with it; however, there is a possibility of
14351c58e4e5SJohn Baldwin 	 * deadlock if process B is bigproc and one of it's child processes
14361c58e4e5SJohn Baldwin 	 * attempts to propagate a signal to B while we are waiting for A's
14371c58e4e5SJohn Baldwin 	 * lock while walking this list.  To avoid this, we don't block on
14381c58e4e5SJohn Baldwin 	 * the process lock but just skip a process if it is already locked.
14395663e6deSDavid Greenman 	 */
14405663e6deSDavid Greenman 	bigproc = NULL;
14415663e6deSDavid Greenman 	bigsize = 0;
14421005a129SJohn Baldwin 	sx_slock(&allproc_lock);
1443e602ba25SJulian Elischer 	FOREACH_PROC_IN_SYSTEM(p) {
1444e602ba25SJulian Elischer 		int breakout;
1445dcbcd518SBruce Evans 
144671943c3dSKonstantin Belousov 		PROC_LOCK(p);
144771943c3dSKonstantin Belousov 
14481c58e4e5SJohn Baldwin 		/*
14493f1c4c4fSKonstantin Belousov 		 * If this is a system, protected or killed process, skip it.
14505663e6deSDavid Greenman 		 */
145171943c3dSKonstantin Belousov 		if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
145271943c3dSKonstantin Belousov 		    P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
145371943c3dSKonstantin Belousov 		    p->p_pid == 1 || P_KILLED(p) ||
145471943c3dSKonstantin Belousov 		    (p->p_pid < 48 && swap_pager_avail != 0)) {
14558606d880SJohn Baldwin 			PROC_UNLOCK(p);
14565663e6deSDavid Greenman 			continue;
14575663e6deSDavid Greenman 		}
14585663e6deSDavid Greenman 		/*
1459dcbcd518SBruce Evans 		 * If the process is in a non-running type state,
1460e602ba25SJulian Elischer 		 * don't touch it.  Check all the threads individually.
14615663e6deSDavid Greenman 		 */
1462e602ba25SJulian Elischer 		breakout = 0;
1463e602ba25SJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td) {
1464982d11f8SJeff Roberson 			thread_lock(td);
146571fad9fdSJulian Elischer 			if (!TD_ON_RUNQ(td) &&
146671fad9fdSJulian Elischer 			    !TD_IS_RUNNING(td) &&
1467f497cda2SEdward Tomasz Napierala 			    !TD_IS_SLEEPING(td) &&
1468b98acc0aSKonstantin Belousov 			    !TD_IS_SUSPENDED(td) &&
1469b98acc0aSKonstantin Belousov 			    !TD_IS_SWAPPED(td)) {
1470982d11f8SJeff Roberson 				thread_unlock(td);
1471e602ba25SJulian Elischer 				breakout = 1;
1472e602ba25SJulian Elischer 				break;
1473e602ba25SJulian Elischer 			}
1474982d11f8SJeff Roberson 			thread_unlock(td);
1475e602ba25SJulian Elischer 		}
1476e602ba25SJulian Elischer 		if (breakout) {
14771c58e4e5SJohn Baldwin 			PROC_UNLOCK(p);
14785663e6deSDavid Greenman 			continue;
14795663e6deSDavid Greenman 		}
14805663e6deSDavid Greenman 		/*
14815663e6deSDavid Greenman 		 * get the process size
14825663e6deSDavid Greenman 		 */
14836bed074cSKonstantin Belousov 		vm = vmspace_acquire_ref(p);
14846bed074cSKonstantin Belousov 		if (vm == NULL) {
14856bed074cSKonstantin Belousov 			PROC_UNLOCK(p);
14866bed074cSKonstantin Belousov 			continue;
14876bed074cSKonstantin Belousov 		}
1488*95e2409aSKonstantin Belousov 		_PHOLD_LITE(p);
148972d97679SDavid Schultz 		PROC_UNLOCK(p);
1490*95e2409aSKonstantin Belousov 		sx_sunlock(&allproc_lock);
1491*95e2409aSKonstantin Belousov 		if (!vm_map_trylock_read(&vm->vm_map)) {
149271943c3dSKonstantin Belousov 			vmspace_free(vm);
1493*95e2409aSKonstantin Belousov 			sx_slock(&allproc_lock);
1494*95e2409aSKonstantin Belousov 			PRELE(p);
149572d97679SDavid Schultz 			continue;
149672d97679SDavid Schultz 		}
14977981aa24SKonstantin Belousov 		size = vmspace_swap_count(vm);
14982025d69bSKonstantin Belousov 		if (shortage == VM_OOM_MEM)
14993949873fSKonstantin Belousov 			size += vm_pageout_oom_pagecount(vm);
15003949873fSKonstantin Belousov 		vm_map_unlock_read(&vm->vm_map);
15016bed074cSKonstantin Belousov 		vmspace_free(vm);
1502*95e2409aSKonstantin Belousov 		sx_slock(&allproc_lock);
15033949873fSKonstantin Belousov 
15045663e6deSDavid Greenman 		/*
15053949873fSKonstantin Belousov 		 * If this process is bigger than the biggest one,
15065663e6deSDavid Greenman 		 * remember it.
15075663e6deSDavid Greenman 		 */
15085663e6deSDavid Greenman 		if (size > bigsize) {
15091c58e4e5SJohn Baldwin 			if (bigproc != NULL)
151071943c3dSKonstantin Belousov 				PRELE(bigproc);
15115663e6deSDavid Greenman 			bigproc = p;
15125663e6deSDavid Greenman 			bigsize = size;
151371943c3dSKonstantin Belousov 		} else {
151471943c3dSKonstantin Belousov 			PRELE(p);
151571943c3dSKonstantin Belousov 		}
15165663e6deSDavid Greenman 	}
15171005a129SJohn Baldwin 	sx_sunlock(&allproc_lock);
15185663e6deSDavid Greenman 	if (bigproc != NULL) {
15198311a2b8SWill Andrews 		if (vm_panic_on_oom != 0)
15208311a2b8SWill Andrews 			panic("out of swap space");
152171943c3dSKonstantin Belousov 		PROC_LOCK(bigproc);
1522729b1e51SDavid Greenman 		killproc(bigproc, "out of swap space");
1523fa885116SJulian Elischer 		sched_nice(bigproc, PRIO_MIN);
152471943c3dSKonstantin Belousov 		_PRELE(bigproc);
15251c58e4e5SJohn Baldwin 		PROC_UNLOCK(bigproc);
152644f1c916SBryan Drewery 		wakeup(&vm_cnt.v_free_count);
15275663e6deSDavid Greenman 	}
15285663e6deSDavid Greenman }
152926f9a767SRodney W. Grimes 
1530449c2e92SKonstantin Belousov static void
1531449c2e92SKonstantin Belousov vm_pageout_worker(void *arg)
1532449c2e92SKonstantin Belousov {
1533449c2e92SKonstantin Belousov 	struct vm_domain *domain;
1534949c9186SKonstantin Belousov 	int domidx;
1535449c2e92SKonstantin Belousov 
1536449c2e92SKonstantin Belousov 	domidx = (uintptr_t)arg;
1537449c2e92SKonstantin Belousov 	domain = &vm_dom[domidx];
1538449c2e92SKonstantin Belousov 
1539449c2e92SKonstantin Belousov 	/*
1540949c9186SKonstantin Belousov 	 * XXXKIB It could be useful to bind pageout daemon threads to
1541949c9186SKonstantin Belousov 	 * the cores belonging to the domain, from which vm_page_array
1542949c9186SKonstantin Belousov 	 * is allocated.
1543449c2e92SKonstantin Belousov 	 */
1544449c2e92SKonstantin Belousov 
1545449c2e92SKonstantin Belousov 	KASSERT(domain->vmd_segs != 0, ("domain without segments"));
154622cf98d1SAlan Cox 	domain->vmd_last_active_scan = ticks;
1547449c2e92SKonstantin Belousov 	vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
15487e78597fSMark Johnston 	vm_pageout_init_marker(&domain->vmd_inacthead, PQ_INACTIVE);
15497e78597fSMark Johnston 	TAILQ_INSERT_HEAD(&domain->vmd_pagequeues[PQ_INACTIVE].pq_pl,
15507e78597fSMark Johnston 	    &domain->vmd_inacthead, plinks.q);
1551449c2e92SKonstantin Belousov 
1552449c2e92SKonstantin Belousov 	/*
1553449c2e92SKonstantin Belousov 	 * The pageout daemon worker is never done, so loop forever.
1554449c2e92SKonstantin Belousov 	 */
1555449c2e92SKonstantin Belousov 	while (TRUE) {
1556449c2e92SKonstantin Belousov 		mtx_lock(&vm_page_queue_free_mtx);
155756ce0690SAlan Cox 
155856ce0690SAlan Cox 		/*
155956ce0690SAlan Cox 		 * Generally, after a level >= 1 scan, if there are enough
156056ce0690SAlan Cox 		 * free pages to wakeup the waiters, then they are already
156156ce0690SAlan Cox 		 * awake.  A call to vm_page_free() during the scan awakened
156256ce0690SAlan Cox 		 * them.  However, in the following case, this wakeup serves
156356ce0690SAlan Cox 		 * to bound the amount of time that a thread might wait.
156456ce0690SAlan Cox 		 * Suppose a thread's call to vm_page_alloc() fails, but
156556ce0690SAlan Cox 		 * before that thread calls VM_WAIT, enough pages are freed by
156656ce0690SAlan Cox 		 * other threads to alleviate the free page shortage.  The
156756ce0690SAlan Cox 		 * thread will, nonetheless, wait until another page is freed
156856ce0690SAlan Cox 		 * or this wakeup is performed.
156956ce0690SAlan Cox 		 */
1570449c2e92SKonstantin Belousov 		if (vm_pages_needed && !vm_page_count_min()) {
157156ce0690SAlan Cox 			vm_pages_needed = false;
157244f1c916SBryan Drewery 			wakeup(&vm_cnt.v_free_count);
1573449c2e92SKonstantin Belousov 		}
157456ce0690SAlan Cox 
1575449c2e92SKonstantin Belousov 		/*
157656ce0690SAlan Cox 		 * Do not clear vm_pageout_wanted until we reach our target.
157756ce0690SAlan Cox 		 * Otherwise, we may be awakened over and over again, wasting
157856ce0690SAlan Cox 		 * CPU time.
1579449c2e92SKonstantin Belousov 		 */
158056ce0690SAlan Cox 		if (vm_pageout_wanted && !vm_paging_needed())
158156ce0690SAlan Cox 			vm_pageout_wanted = false;
158256ce0690SAlan Cox 
158356ce0690SAlan Cox 		/*
158456ce0690SAlan Cox 		 * Might the page daemon receive a wakeup call?
158556ce0690SAlan Cox 		 */
158656ce0690SAlan Cox 		if (vm_pageout_wanted) {
158756ce0690SAlan Cox 			/*
158856ce0690SAlan Cox 			 * No.  Either vm_pageout_wanted was set by another
158956ce0690SAlan Cox 			 * thread during the previous scan, which must have
159056ce0690SAlan Cox 			 * been a level 0 scan, or vm_pageout_wanted was
159156ce0690SAlan Cox 			 * already set and the scan failed to free enough
159256ce0690SAlan Cox 			 * pages.  If we haven't yet performed a level >= 2
159356ce0690SAlan Cox 			 * scan (unlimited dirty cleaning), then upgrade the
159456ce0690SAlan Cox 			 * level and scan again now.  Otherwise, sleep a bit
159556ce0690SAlan Cox 			 * and try again later.
159656ce0690SAlan Cox 			 */
159756ce0690SAlan Cox 			mtx_unlock(&vm_page_queue_free_mtx);
1598449c2e92SKonstantin Belousov 			if (domain->vmd_pass > 1)
159956ce0690SAlan Cox 				pause("psleep", hz / 2);
160056ce0690SAlan Cox 			domain->vmd_pass++;
1601449c2e92SKonstantin Belousov 		} else {
1602449c2e92SKonstantin Belousov 			/*
160356ce0690SAlan Cox 			 * Yes.  Sleep until pages need to be reclaimed or
160456ce0690SAlan Cox 			 * have their reference stats updated.
1605449c2e92SKonstantin Belousov 			 */
160656ce0690SAlan Cox 			if (mtx_sleep(&vm_pageout_wanted,
160756ce0690SAlan Cox 			    &vm_page_queue_free_mtx, PDROP | PVM, "psleep",
160856ce0690SAlan Cox 			    hz) == 0) {
160956ce0690SAlan Cox 				PCPU_INC(cnt.v_pdwakeups);
161056ce0690SAlan Cox 				domain->vmd_pass = 1;
1611d9347bcaSAlan Cox 			} else
1612d9347bcaSAlan Cox 				domain->vmd_pass = 0;
161356ce0690SAlan Cox 		}
161456ce0690SAlan Cox 
1615449c2e92SKonstantin Belousov 		vm_pageout_scan(domain, domain->vmd_pass);
1616449c2e92SKonstantin Belousov 	}
1617449c2e92SKonstantin Belousov }
1618449c2e92SKonstantin Belousov 
1619df8bae1dSRodney W. Grimes /*
16204d19f4adSSteven Hartland  *	vm_pageout_init initialises basic pageout daemon settings.
1621df8bae1dSRodney W. Grimes  */
16222b14f991SJulian Elischer static void
16234d19f4adSSteven Hartland vm_pageout_init(void)
1624df8bae1dSRodney W. Grimes {
1625df8bae1dSRodney W. Grimes 	/*
1626df8bae1dSRodney W. Grimes 	 * Initialize some paging parameters.
1627df8bae1dSRodney W. Grimes 	 */
162844f1c916SBryan Drewery 	vm_cnt.v_interrupt_free_min = 2;
162944f1c916SBryan Drewery 	if (vm_cnt.v_page_count < 2000)
1630f35329acSJohn Dyson 		vm_pageout_page_count = 8;
1631f6b04d2bSDavid Greenman 
163245ae1d91SAlan Cox 	/*
163345ae1d91SAlan Cox 	 * v_free_reserved needs to include enough for the largest
163445ae1d91SAlan Cox 	 * swap pager structures plus enough for any pv_entry structs
163545ae1d91SAlan Cox 	 * when paging.
163645ae1d91SAlan Cox 	 */
163744f1c916SBryan Drewery 	if (vm_cnt.v_page_count > 1024)
163844f1c916SBryan Drewery 		vm_cnt.v_free_min = 4 + (vm_cnt.v_page_count - 1024) / 200;
16392feb50bfSAttilio Rao 	else
164044f1c916SBryan Drewery 		vm_cnt.v_free_min = 4;
164144f1c916SBryan Drewery 	vm_cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
164244f1c916SBryan Drewery 	    vm_cnt.v_interrupt_free_min;
164344f1c916SBryan Drewery 	vm_cnt.v_free_reserved = vm_pageout_page_count +
164444f1c916SBryan Drewery 	    vm_cnt.v_pageout_free_min + (vm_cnt.v_page_count / 768);
164544f1c916SBryan Drewery 	vm_cnt.v_free_severe = vm_cnt.v_free_min / 2;
164644f1c916SBryan Drewery 	vm_cnt.v_free_target = 4 * vm_cnt.v_free_min + vm_cnt.v_free_reserved;
164744f1c916SBryan Drewery 	vm_cnt.v_free_min += vm_cnt.v_free_reserved;
164844f1c916SBryan Drewery 	vm_cnt.v_free_severe += vm_cnt.v_free_reserved;
164944f1c916SBryan Drewery 	vm_cnt.v_inactive_target = (3 * vm_cnt.v_free_target) / 2;
165044f1c916SBryan Drewery 	if (vm_cnt.v_inactive_target > vm_cnt.v_free_count / 3)
165144f1c916SBryan Drewery 		vm_cnt.v_inactive_target = vm_cnt.v_free_count / 3;
1652df8bae1dSRodney W. Grimes 
1653d9e23210SJeff Roberson 	/*
1654d9e23210SJeff Roberson 	 * Set the default wakeup threshold to be 10% above the minimum
1655d9e23210SJeff Roberson 	 * page limit.  This keeps the steady state out of shortfall.
1656d9e23210SJeff Roberson 	 */
165744f1c916SBryan Drewery 	vm_pageout_wakeup_thresh = (vm_cnt.v_free_min / 10) * 11;
1658d9e23210SJeff Roberson 
1659d9e23210SJeff Roberson 	/*
1660d9e23210SJeff Roberson 	 * Set interval in seconds for active scan.  We want to visit each
1661c9612b2dSJeff Roberson 	 * page at least once every ten minutes.  This is to prevent worst
1662c9612b2dSJeff Roberson 	 * case paging behaviors with stale active LRU.
1663d9e23210SJeff Roberson 	 */
1664d9e23210SJeff Roberson 	if (vm_pageout_update_period == 0)
1665c9612b2dSJeff Roberson 		vm_pageout_update_period = 600;
1666d9e23210SJeff Roberson 
1667df8bae1dSRodney W. Grimes 	/* XXX does not really belong here */
1668df8bae1dSRodney W. Grimes 	if (vm_page_max_wired == 0)
166944f1c916SBryan Drewery 		vm_page_max_wired = vm_cnt.v_free_count / 3;
16704d19f4adSSteven Hartland }
16714d19f4adSSteven Hartland 
16724d19f4adSSteven Hartland /*
16734d19f4adSSteven Hartland  *     vm_pageout is the high level pageout daemon.
16744d19f4adSSteven Hartland  */
16754d19f4adSSteven Hartland static void
16764d19f4adSSteven Hartland vm_pageout(void)
16774d19f4adSSteven Hartland {
167844ec2b63SKonstantin Belousov 	int error;
167962d70a81SJohn Baldwin #ifdef VM_NUMA_ALLOC
168044ec2b63SKonstantin Belousov 	int i;
16814d19f4adSSteven Hartland #endif
1682df8bae1dSRodney W. Grimes 
168324a1cce3SDavid Greenman 	swap_pager_swap_init();
168462d70a81SJohn Baldwin #ifdef VM_NUMA_ALLOC
1685449c2e92SKonstantin Belousov 	for (i = 1; i < vm_ndomains; i++) {
1686449c2e92SKonstantin Belousov 		error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
1687449c2e92SKonstantin Belousov 		    curproc, NULL, 0, 0, "dom%d", i);
1688449c2e92SKonstantin Belousov 		if (error != 0) {
1689449c2e92SKonstantin Belousov 			panic("starting pageout for domain %d, error %d\n",
1690449c2e92SKonstantin Belousov 			    i, error);
1691dc2efb27SJohn Dyson 		}
1692f919ebdeSDavid Greenman 	}
1693449c2e92SKonstantin Belousov #endif
169444ec2b63SKonstantin Belousov 	error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
169544ec2b63SKonstantin Belousov 	    0, 0, "uma");
169644ec2b63SKonstantin Belousov 	if (error != 0)
169744ec2b63SKonstantin Belousov 		panic("starting uma_reclaim helper, error %d\n", error);
1698d395270dSDimitry Andric 	vm_pageout_worker((void *)(uintptr_t)0);
1699df8bae1dSRodney W. Grimes }
170026f9a767SRodney W. Grimes 
17016b4b77adSAlan Cox /*
1702e9f995d8SAlan Cox  * Unless the free page queue lock is held by the caller, this function
17036b4b77adSAlan Cox  * should be regarded as advisory.  Specifically, the caller should
170444f1c916SBryan Drewery  * not msleep() on &vm_cnt.v_free_count following this function unless
1705e9f995d8SAlan Cox  * the free page queue lock is held until the msleep() is performed.
17066b4b77adSAlan Cox  */
1707e0c5a895SJohn Dyson void
17084a365329SAndrey Zonov pagedaemon_wakeup(void)
1709e0c5a895SJohn Dyson {
1710a1c0a785SAlan Cox 
171156ce0690SAlan Cox 	if (!vm_pageout_wanted && curthread->td_proc != pageproc) {
171256ce0690SAlan Cox 		vm_pageout_wanted = true;
171356ce0690SAlan Cox 		wakeup(&vm_pageout_wanted);
1714e0c5a895SJohn Dyson 	}
1715e0c5a895SJohn Dyson }
1716e0c5a895SJohn Dyson 
171738efa82bSJohn Dyson #if !defined(NO_SWAPPING)
17185afce282SDavid Greenman static void
171997824da3SAlan Cox vm_req_vmdaemon(int req)
17205afce282SDavid Greenman {
17215afce282SDavid Greenman 	static int lastrun = 0;
17225afce282SDavid Greenman 
172397824da3SAlan Cox 	mtx_lock(&vm_daemon_mtx);
172497824da3SAlan Cox 	vm_pageout_req_swapout |= req;
1725b18bfc3dSJohn Dyson 	if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
17265afce282SDavid Greenman 		wakeup(&vm_daemon_needed);
17275afce282SDavid Greenman 		lastrun = ticks;
17285afce282SDavid Greenman 	}
172997824da3SAlan Cox 	mtx_unlock(&vm_daemon_mtx);
17305afce282SDavid Greenman }
17315afce282SDavid Greenman 
17322b14f991SJulian Elischer static void
17334a365329SAndrey Zonov vm_daemon(void)
17340d94caffSDavid Greenman {
173591d5354aSJohn Baldwin 	struct rlimit rsslim;
1736dcbcd518SBruce Evans 	struct proc *p;
1737dcbcd518SBruce Evans 	struct thread *td;
17386bed074cSKonstantin Belousov 	struct vmspace *vm;
1739099e7e95SEdward Tomasz Napierala 	int breakout, swapout_flags, tryagain, attempts;
1740afcc55f3SEdward Tomasz Napierala #ifdef RACCT
1741099e7e95SEdward Tomasz Napierala 	uint64_t rsize, ravailable;
1742afcc55f3SEdward Tomasz Napierala #endif
17430d94caffSDavid Greenman 
17442fe6e4d7SDavid Greenman 	while (TRUE) {
174597824da3SAlan Cox 		mtx_lock(&vm_daemon_mtx);
17464b5c9cf6SEdward Tomasz Napierala 		msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
1747099e7e95SEdward Tomasz Napierala #ifdef RACCT
17484b5c9cf6SEdward Tomasz Napierala 		    racct_enable ? hz : 0
1749099e7e95SEdward Tomasz Napierala #else
17504b5c9cf6SEdward Tomasz Napierala 		    0
1751099e7e95SEdward Tomasz Napierala #endif
17524b5c9cf6SEdward Tomasz Napierala 		);
175397824da3SAlan Cox 		swapout_flags = vm_pageout_req_swapout;
17544c1f8ee9SDavid Greenman 		vm_pageout_req_swapout = 0;
175597824da3SAlan Cox 		mtx_unlock(&vm_daemon_mtx);
175697824da3SAlan Cox 		if (swapout_flags)
175797824da3SAlan Cox 			swapout_procs(swapout_flags);
175897824da3SAlan Cox 
17592fe6e4d7SDavid Greenman 		/*
17600d94caffSDavid Greenman 		 * scan the processes for exceeding their rlimits or if
17610d94caffSDavid Greenman 		 * process is swapped out -- deactivate pages
17622fe6e4d7SDavid Greenman 		 */
1763099e7e95SEdward Tomasz Napierala 		tryagain = 0;
1764099e7e95SEdward Tomasz Napierala 		attempts = 0;
1765099e7e95SEdward Tomasz Napierala again:
1766099e7e95SEdward Tomasz Napierala 		attempts++;
17671005a129SJohn Baldwin 		sx_slock(&allproc_lock);
1768f67af5c9SXin LI 		FOREACH_PROC_IN_SYSTEM(p) {
1769fe2144fdSLuoqi Chen 			vm_pindex_t limit, size;
17702fe6e4d7SDavid Greenman 
17712fe6e4d7SDavid Greenman 			/*
17722fe6e4d7SDavid Greenman 			 * if this is a system process or if we have already
17732fe6e4d7SDavid Greenman 			 * looked at this process, skip it.
17742fe6e4d7SDavid Greenman 			 */
1775897ecacdSJohn Baldwin 			PROC_LOCK(p);
17768e6fa660SJohn Baldwin 			if (p->p_state != PRS_NORMAL ||
17778e6fa660SJohn Baldwin 			    p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
1778897ecacdSJohn Baldwin 				PROC_UNLOCK(p);
17792fe6e4d7SDavid Greenman 				continue;
17802fe6e4d7SDavid Greenman 			}
17812fe6e4d7SDavid Greenman 			/*
17822fe6e4d7SDavid Greenman 			 * if the process is in a non-running type state,
17832fe6e4d7SDavid Greenman 			 * don't touch it.
17842fe6e4d7SDavid Greenman 			 */
1785e602ba25SJulian Elischer 			breakout = 0;
1786e602ba25SJulian Elischer 			FOREACH_THREAD_IN_PROC(p, td) {
1787982d11f8SJeff Roberson 				thread_lock(td);
178871fad9fdSJulian Elischer 				if (!TD_ON_RUNQ(td) &&
178971fad9fdSJulian Elischer 				    !TD_IS_RUNNING(td) &&
1790f497cda2SEdward Tomasz Napierala 				    !TD_IS_SLEEPING(td) &&
1791f497cda2SEdward Tomasz Napierala 				    !TD_IS_SUSPENDED(td)) {
1792982d11f8SJeff Roberson 					thread_unlock(td);
1793e602ba25SJulian Elischer 					breakout = 1;
1794e602ba25SJulian Elischer 					break;
1795e602ba25SJulian Elischer 				}
1796982d11f8SJeff Roberson 				thread_unlock(td);
1797e602ba25SJulian Elischer 			}
1798897ecacdSJohn Baldwin 			if (breakout) {
1799897ecacdSJohn Baldwin 				PROC_UNLOCK(p);
18002fe6e4d7SDavid Greenman 				continue;
18012fe6e4d7SDavid Greenman 			}
18022fe6e4d7SDavid Greenman 			/*
18032fe6e4d7SDavid Greenman 			 * get a limit
18042fe6e4d7SDavid Greenman 			 */
1805f6f6d240SMateusz Guzik 			lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
1806fe2144fdSLuoqi Chen 			limit = OFF_TO_IDX(
180791d5354aSJohn Baldwin 			    qmin(rsslim.rlim_cur, rsslim.rlim_max));
18082fe6e4d7SDavid Greenman 
18092fe6e4d7SDavid Greenman 			/*
18100d94caffSDavid Greenman 			 * let processes that are swapped out really be
18110d94caffSDavid Greenman 			 * swapped out set the limit to nothing (will force a
18120d94caffSDavid Greenman 			 * swap-out.)
18132fe6e4d7SDavid Greenman 			 */
1814b61ce5b0SJeff Roberson 			if ((p->p_flag & P_INMEM) == 0)
18150d94caffSDavid Greenman 				limit = 0;	/* XXX */
18166bed074cSKonstantin Belousov 			vm = vmspace_acquire_ref(p);
1817*95e2409aSKonstantin Belousov 			_PHOLD_LITE(p);
1818897ecacdSJohn Baldwin 			PROC_UNLOCK(p);
1819*95e2409aSKonstantin Belousov 			if (vm == NULL) {
1820*95e2409aSKonstantin Belousov 				PRELE(p);
18216bed074cSKonstantin Belousov 				continue;
1822*95e2409aSKonstantin Belousov 			}
1823*95e2409aSKonstantin Belousov 			sx_sunlock(&allproc_lock);
18242fe6e4d7SDavid Greenman 
18256bed074cSKonstantin Belousov 			size = vmspace_resident_count(vm);
1826a406d8c3SEdward Tomasz Napierala 			if (size >= limit) {
1827fe2144fdSLuoqi Chen 				vm_pageout_map_deactivate_pages(
18286bed074cSKonstantin Belousov 				    &vm->vm_map, limit);
18292fe6e4d7SDavid Greenman 			}
1830afcc55f3SEdward Tomasz Napierala #ifdef RACCT
18314b5c9cf6SEdward Tomasz Napierala 			if (racct_enable) {
1832099e7e95SEdward Tomasz Napierala 				rsize = IDX_TO_OFF(size);
1833099e7e95SEdward Tomasz Napierala 				PROC_LOCK(p);
1834099e7e95SEdward Tomasz Napierala 				racct_set(p, RACCT_RSS, rsize);
1835099e7e95SEdward Tomasz Napierala 				ravailable = racct_get_available(p, RACCT_RSS);
1836099e7e95SEdward Tomasz Napierala 				PROC_UNLOCK(p);
1837099e7e95SEdward Tomasz Napierala 				if (rsize > ravailable) {
1838099e7e95SEdward Tomasz Napierala 					/*
18394b5c9cf6SEdward Tomasz Napierala 					 * Don't be overly aggressive; this
18404b5c9cf6SEdward Tomasz Napierala 					 * might be an innocent process,
18414b5c9cf6SEdward Tomasz Napierala 					 * and the limit could've been exceeded
18424b5c9cf6SEdward Tomasz Napierala 					 * by some memory hog.  Don't try
18434b5c9cf6SEdward Tomasz Napierala 					 * to deactivate more than 1/4th
18444b5c9cf6SEdward Tomasz Napierala 					 * of process' resident set size.
1845099e7e95SEdward Tomasz Napierala 					 */
1846099e7e95SEdward Tomasz Napierala 					if (attempts <= 8) {
18474b5c9cf6SEdward Tomasz Napierala 						if (ravailable < rsize -
18484b5c9cf6SEdward Tomasz Napierala 						    (rsize / 4)) {
18494b5c9cf6SEdward Tomasz Napierala 							ravailable = rsize -
18504b5c9cf6SEdward Tomasz Napierala 							    (rsize / 4);
18514b5c9cf6SEdward Tomasz Napierala 						}
1852099e7e95SEdward Tomasz Napierala 					}
1853099e7e95SEdward Tomasz Napierala 					vm_pageout_map_deactivate_pages(
18544b5c9cf6SEdward Tomasz Napierala 					    &vm->vm_map,
18554b5c9cf6SEdward Tomasz Napierala 					    OFF_TO_IDX(ravailable));
1856099e7e95SEdward Tomasz Napierala 					/* Update RSS usage after paging out. */
1857099e7e95SEdward Tomasz Napierala 					size = vmspace_resident_count(vm);
1858099e7e95SEdward Tomasz Napierala 					rsize = IDX_TO_OFF(size);
1859099e7e95SEdward Tomasz Napierala 					PROC_LOCK(p);
1860099e7e95SEdward Tomasz Napierala 					racct_set(p, RACCT_RSS, rsize);
1861099e7e95SEdward Tomasz Napierala 					PROC_UNLOCK(p);
1862099e7e95SEdward Tomasz Napierala 					if (rsize > ravailable)
1863099e7e95SEdward Tomasz Napierala 						tryagain = 1;
1864099e7e95SEdward Tomasz Napierala 				}
18654b5c9cf6SEdward Tomasz Napierala 			}
1866afcc55f3SEdward Tomasz Napierala #endif
18676bed074cSKonstantin Belousov 			vmspace_free(vm);
1868*95e2409aSKonstantin Belousov 			sx_slock(&allproc_lock);
1869*95e2409aSKonstantin Belousov 			PRELE(p);
18702fe6e4d7SDavid Greenman 		}
18711005a129SJohn Baldwin 		sx_sunlock(&allproc_lock);
1872099e7e95SEdward Tomasz Napierala 		if (tryagain != 0 && attempts <= 10)
1873099e7e95SEdward Tomasz Napierala 			goto again;
187424a1cce3SDavid Greenman 	}
18752fe6e4d7SDavid Greenman }
1876a1287949SEivind Eklund #endif			/* !defined(NO_SWAPPING) */
1877