xref: /freebsd/sys/vm/vm_pageout.c (revision f095d1bbc7ecc81f63c280cb7f11a8ae2a20a7c7)
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 */
16020c58db9SMark Johnston u_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
27044be0a8eSMark Johnston  * PQ_INACTIVE.  To avoid lock order violation, unlock the page queue
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
875*f095d1bbSAlan Cox  *	pass 1 - Free inactive pages
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;
8883ac8f842SMark Johnston 	boolean_t pageout_ok, queue_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 	/*
918*f095d1bbSAlan Cox 	 * Calculate the number of pages that we want to free.
9191c7c3c6aSMatthew Dillon 	 */
92060196cdaSAlan Cox 	if (pass > 0) {
92160196cdaSAlan Cox 		deficit = atomic_readandclear_int(&vm_pageout_deficit);
9229099545aSAlan Cox 		page_shortage = vm_paging_target() + deficit;
92360196cdaSAlan Cox 	} else
92460196cdaSAlan Cox 		page_shortage = deficit = 0;
92576386c7eSKonstantin Belousov 	starting_page_shortage = page_shortage;
9261c7c3c6aSMatthew Dillon 
927936524aaSMatthew Dillon 	/*
9282b6b0df7SMatthew Dillon 	 * maxlaunder limits the number of dirty pages we flush per scan.
9292b6b0df7SMatthew Dillon 	 * For most systems a smaller value (16 or 32) is more robust under
9302b6b0df7SMatthew Dillon 	 * extreme memory and disk pressure because any unnecessary writes
9312b6b0df7SMatthew Dillon 	 * to disk can result in extreme performance degredation.  However,
9322b6b0df7SMatthew Dillon 	 * systems with excessive dirty pages (especially when MAP_NOSYNC is
9332b6b0df7SMatthew Dillon 	 * used) will die horribly with limited laundering.  If the pageout
9342b6b0df7SMatthew Dillon 	 * daemon cannot clean enough pages in the first pass, we let it go
9352b6b0df7SMatthew Dillon 	 * all out in succeeding passes.
9361c7c3c6aSMatthew Dillon 	 */
9372b6b0df7SMatthew Dillon 	if ((maxlaunder = vm_max_launder) <= 1)
9382b6b0df7SMatthew Dillon 		maxlaunder = 1;
939d9e23210SJeff Roberson 	if (pass > 1)
9402b6b0df7SMatthew Dillon 		maxlaunder = 10000;
9418d220203SAlan Cox 
94240aa80a7SAlan Cox 	vnodes_skipped = 0;
94340aa80a7SAlan Cox 
9448d220203SAlan Cox 	/*
945*f095d1bbSAlan Cox 	 * Start scanning the inactive queue for pages that we can free.  The
946*f095d1bbSAlan Cox 	 * scan will stop when we reach the target or we have scanned the
947*f095d1bbSAlan Cox 	 * entire queue.  (Note that m->act_count is not used to make
948*f095d1bbSAlan Cox 	 * decisions for the inactive queue, only for the active queue.)
9498d220203SAlan Cox 	 */
950449c2e92SKonstantin Belousov 	pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
951449c2e92SKonstantin Belousov 	maxscan = pq->pq_cnt;
9528d220203SAlan Cox 	vm_pagequeue_lock(pq);
9533ac8f842SMark Johnston 	queue_locked = TRUE;
9548d220203SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl);
9551c7c3c6aSMatthew Dillon 	     m != NULL && maxscan-- > 0 && page_shortage > 0;
956e929c00dSKirk McKusick 	     m = next) {
9578d220203SAlan Cox 		vm_pagequeue_assert_locked(pq);
9583ac8f842SMark Johnston 		KASSERT(queue_locked, ("unlocked inactive queue"));
959d4961bcbSKonstantin Belousov 		KASSERT(m->queue == PQ_INACTIVE, ("Inactive queue %p", m));
960df8bae1dSRodney W. Grimes 
9618d220203SAlan Cox 		PCPU_INC(cnt.v_pdpages);
962c325e866SKonstantin Belousov 		next = TAILQ_NEXT(m, plinks.q);
963df8bae1dSRodney W. Grimes 
964936524aaSMatthew Dillon 		/*
965936524aaSMatthew Dillon 		 * skip marker pages
966936524aaSMatthew Dillon 		 */
967936524aaSMatthew Dillon 		if (m->flags & PG_MARKER)
968936524aaSMatthew Dillon 			continue;
969936524aaSMatthew Dillon 
9707900f95dSKonstantin Belousov 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
9717900f95dSKonstantin Belousov 		    ("Fictitious page %p cannot be in inactive queue", m));
9727900f95dSKonstantin Belousov 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
9737900f95dSKonstantin Belousov 		    ("Unmanaged page %p cannot be in inactive queue", m));
9747900f95dSKonstantin Belousov 
9758c616246SKonstantin Belousov 		/*
976311e34e2SKonstantin Belousov 		 * The page or object lock acquisitions fail if the
977311e34e2SKonstantin Belousov 		 * page was removed from the queue or moved to a
978311e34e2SKonstantin Belousov 		 * different position within the queue.  In either
979311e34e2SKonstantin Belousov 		 * case, addl_page_shortage should not be incremented.
9808c616246SKonstantin Belousov 		 */
981a3aeedabSAlan Cox 		if (!vm_pageout_page_lock(m, &next))
982a3aeedabSAlan Cox 			goto unlock_page;
983a3aeedabSAlan Cox 		else if (m->hold_count != 0) {
984a3aeedabSAlan Cox 			/*
985a3aeedabSAlan Cox 			 * Held pages are essentially stuck in the
986a3aeedabSAlan Cox 			 * queue.  So, they ought to be discounted
987a3aeedabSAlan Cox 			 * from the inactive count.  See the
988a3aeedabSAlan Cox 			 * calculation of the page_shortage for the
989a3aeedabSAlan Cox 			 * loop over the active queue below.
990a3aeedabSAlan Cox 			 */
991a3aeedabSAlan Cox 			addl_page_shortage++;
992a3aeedabSAlan Cox 			goto unlock_page;
993df8bae1dSRodney W. Grimes 		}
9949ee2165fSAlan Cox 		object = m->object;
995a3aeedabSAlan Cox 		if (!VM_OBJECT_TRYWLOCK(object)) {
996a3aeedabSAlan Cox 			if (!vm_pageout_fallback_object_lock(m, &next))
997a3aeedabSAlan Cox 				goto unlock_object;
998a3aeedabSAlan Cox 			else if (m->hold_count != 0) {
999b182ec9eSJohn Dyson 				addl_page_shortage++;
1000a3aeedabSAlan Cox 				goto unlock_object;
1001a3aeedabSAlan Cox 			}
1002a3aeedabSAlan Cox 		}
1003a3aeedabSAlan Cox 		if (vm_page_busied(m)) {
1004a3aeedabSAlan Cox 			/*
1005a3aeedabSAlan Cox 			 * Don't mess with busy pages.  Leave them at
1006a3aeedabSAlan Cox 			 * the front of the queue.  Most likely, they
1007a3aeedabSAlan Cox 			 * are being paged out and will leave the
1008a3aeedabSAlan Cox 			 * queue shortly after the scan finishes.  So,
1009a3aeedabSAlan Cox 			 * they ought to be discounted from the
1010a3aeedabSAlan Cox 			 * inactive count.
1011a3aeedabSAlan Cox 			 */
1012a3aeedabSAlan Cox 			addl_page_shortage++;
1013a3aeedabSAlan Cox unlock_object:
1014a3aeedabSAlan Cox 			VM_OBJECT_WUNLOCK(object);
1015a3aeedabSAlan Cox unlock_page:
1016a3aeedabSAlan Cox 			vm_page_unlock(m);
101726f9a767SRodney W. Grimes 			continue;
101826f9a767SRodney W. Grimes 		}
1019a3aeedabSAlan Cox 		KASSERT(m->hold_count == 0, ("Held page %p", m));
1020bd7e5f99SJohn Dyson 
10217e006499SJohn Dyson 		/*
10228d220203SAlan Cox 		 * We unlock the inactive page queue, invalidating the
102348cc2fc7SKonstantin Belousov 		 * 'next' pointer.  Use our marker to remember our
102448cc2fc7SKonstantin Belousov 		 * place.
102548cc2fc7SKonstantin Belousov 		 */
1026c325e866SKonstantin Belousov 		TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
10278d220203SAlan Cox 		vm_pagequeue_unlock(pq);
10283ac8f842SMark Johnston 		queue_locked = FALSE;
102948cc2fc7SKonstantin Belousov 
103048cc2fc7SKonstantin Belousov 		/*
10318748f58cSKonstantin Belousov 		 * Invalid pages can be easily freed. They cannot be
10328748f58cSKonstantin Belousov 		 * mapped, vm_page_free() asserts this.
1033776f729cSKonstantin Belousov 		 */
10348748f58cSKonstantin Belousov 		if (m->valid == 0)
10358748f58cSKonstantin Belousov 			goto free_page;
1036776f729cSKonstantin Belousov 
1037776f729cSKonstantin Belousov 		/*
1038960810ccSAlan Cox 		 * If the page has been referenced and the object is not dead,
1039960810ccSAlan Cox 		 * reactivate or requeue the page depending on whether the
1040960810ccSAlan Cox 		 * object is mapped.
10417e006499SJohn Dyson 		 */
1042bb7858eaSJeff Roberson 		if ((m->aflags & PGA_REFERENCED) != 0) {
1043bb7858eaSJeff Roberson 			vm_page_aflag_clear(m, PGA_REFERENCED);
1044bb7858eaSJeff Roberson 			act_delta = 1;
104586fa2471SAlan Cox 		} else
104686fa2471SAlan Cox 			act_delta = 0;
1047bb7858eaSJeff Roberson 		if (object->ref_count != 0) {
1048bb7858eaSJeff Roberson 			act_delta += pmap_ts_referenced(m);
1049bb7858eaSJeff Roberson 		} else {
1050bb7858eaSJeff Roberson 			KASSERT(!pmap_page_is_mapped(m),
1051bb7858eaSJeff Roberson 			    ("vm_pageout_scan: page %p is mapped", m));
10522fe6e4d7SDavid Greenman 		}
1053bb7858eaSJeff Roberson 		if (act_delta != 0) {
105486fa2471SAlan Cox 			if (object->ref_count != 0) {
105526f9a767SRodney W. Grimes 				vm_page_activate(m);
1056960810ccSAlan Cox 
1057960810ccSAlan Cox 				/*
1058960810ccSAlan Cox 				 * Increase the activation count if the page
1059960810ccSAlan Cox 				 * was referenced while in the inactive queue.
1060960810ccSAlan Cox 				 * This makes it less likely that the page will
1061960810ccSAlan Cox 				 * be returned prematurely to the inactive
1062960810ccSAlan Cox 				 * queue.
1063960810ccSAlan Cox  				 */
1064bb7858eaSJeff Roberson 				m->act_count += act_delta + ACT_ADVANCE;
1065960810ccSAlan Cox 				goto drop_page;
106627a9fb2fSAlan Cox 			} else if ((object->flags & OBJ_DEAD) == 0)
106727a9fb2fSAlan Cox 				goto requeue_page;
1068960810ccSAlan Cox 		}
106967bf6868SJohn Dyson 
10707e006499SJohn Dyson 		/*
10719fc4739dSAlan Cox 		 * If the page appears to be clean at the machine-independent
10729fc4739dSAlan Cox 		 * layer, then remove all of its mappings from the pmap in
1073a766ffd0SAlan Cox 		 * anticipation of freeing it.  If, however, any of the page's
1074a766ffd0SAlan Cox 		 * mappings allow write access, then the page may still be
1075a766ffd0SAlan Cox 		 * modified until the last of those mappings are removed.
10767e006499SJohn Dyson 		 */
1077aa044135SAlan Cox 		if (object->ref_count != 0) {
10789fc4739dSAlan Cox 			vm_page_test_dirty(m);
1079aa044135SAlan Cox 			if (m->dirty == 0)
1080b78ddb0bSAlan Cox 				pmap_remove_all(m);
1081aa044135SAlan Cox 		}
1082dcbcd518SBruce Evans 
1083776f729cSKonstantin Belousov 		if (m->dirty == 0) {
10846989c456SAlan Cox 			/*
108578afdce6SAlan Cox 			 * Clean pages can be freed.
10866989c456SAlan Cox 			 */
10878748f58cSKonstantin Belousov free_page:
108878afdce6SAlan Cox 			vm_page_free(m);
108978afdce6SAlan Cox 			PCPU_INC(cnt.v_dfree);
10901c7c3c6aSMatthew Dillon 			--page_shortage;
1091960810ccSAlan Cox 		} else if ((object->flags & OBJ_DEAD) != 0) {
1092960810ccSAlan Cox 			/*
1093960810ccSAlan Cox 			 * Leave dirty pages from dead objects at the front of
1094960810ccSAlan Cox 			 * the queue.  They are being paged out and freed by
1095960810ccSAlan Cox 			 * the thread that destroyed the object.  They will
1096960810ccSAlan Cox 			 * leave the queue shortly after the scan finishes, so
1097960810ccSAlan Cox 			 * they should be discounted from the inactive count.
1098960810ccSAlan Cox 			 */
1099960810ccSAlan Cox 			addl_page_shortage++;
1100d9e23210SJeff Roberson 		} else if ((m->flags & PG_WINATCFLS) == 0 && pass < 2) {
11017e006499SJohn Dyson 			/*
11022b6b0df7SMatthew Dillon 			 * Dirty pages need to be paged out, but flushing
1103ab46f63eSJohn Baldwin 			 * a page is extremely expensive versus freeing
11042b6b0df7SMatthew Dillon 			 * a clean page.  Rather then artificially limiting
11052b6b0df7SMatthew Dillon 			 * the number of pages we can flush, we instead give
11062b6b0df7SMatthew Dillon 			 * dirty pages extra priority on the inactive queue
11072b6b0df7SMatthew Dillon 			 * by forcing them to be cycled through the queue
11082b6b0df7SMatthew Dillon 			 * twice before being flushed, after which the
11092b6b0df7SMatthew Dillon 			 * (now clean) page will cycle through once more
11102b6b0df7SMatthew Dillon 			 * before being freed.  This significantly extends
11112b6b0df7SMatthew Dillon 			 * the thrash point for a heavily loaded machine.
11127e006499SJohn Dyson 			 */
11133407fefeSKonstantin Belousov 			m->flags |= PG_WINATCFLS;
111427a9fb2fSAlan Cox requeue_page:
11158d220203SAlan Cox 			vm_pagequeue_lock(pq);
11163ac8f842SMark Johnston 			queue_locked = TRUE;
11178d220203SAlan Cox 			vm_page_requeue_locked(m);
11180d94caffSDavid Greenman 		} else if (maxlaunder > 0) {
11192b6b0df7SMatthew Dillon 			/*
11202b6b0df7SMatthew Dillon 			 * We always want to try to flush some dirty pages if
11212b6b0df7SMatthew Dillon 			 * we encounter them, to keep the system stable.
11222b6b0df7SMatthew Dillon 			 * Normally this number is small, but under extreme
11232b6b0df7SMatthew Dillon 			 * pressure where there are insufficient clean pages
11242b6b0df7SMatthew Dillon 			 * on the inactive queue, we may have to go all out.
11252b6b0df7SMatthew Dillon 			 */
11260d94caffSDavid Greenman 
112740aa80a7SAlan Cox 			if (object->type != OBJT_SWAP &&
112840aa80a7SAlan Cox 			    object->type != OBJT_DEFAULT)
112940aa80a7SAlan Cox 				pageout_ok = TRUE;
113040aa80a7SAlan Cox 			else if (disable_swap_pageouts)
113140aa80a7SAlan Cox 				pageout_ok = FALSE;
113240aa80a7SAlan Cox 			else if (defer_swap_pageouts)
113340aa80a7SAlan Cox 				pageout_ok = vm_page_count_min();
113440aa80a7SAlan Cox 			else
113540aa80a7SAlan Cox 				pageout_ok = TRUE;
113627a9fb2fSAlan Cox 			if (!pageout_ok)
113727a9fb2fSAlan Cox 				goto requeue_page;
113834d8b7eaSJeff Roberson 			error = vm_pageout_clean(m);
11391c7c3c6aSMatthew Dillon 			/*
114034d8b7eaSJeff Roberson 			 * Decrement page_shortage on success to account for
11412b6b0df7SMatthew Dillon 			 * the (future) cleaned page.  Otherwise we could wind
11422b6b0df7SMatthew Dillon 			 * up laundering or cleaning too many pages.
11430d94caffSDavid Greenman 			 */
114434d8b7eaSJeff Roberson 			if (error == 0) {
114534d8b7eaSJeff Roberson 				page_shortage--;
114634d8b7eaSJeff Roberson 				maxlaunder--;
114734d8b7eaSJeff Roberson 			} else if (error == EDEADLK) {
114834d8b7eaSJeff Roberson 				pageout_lock_miss++;
114934d8b7eaSJeff Roberson 				vnodes_skipped++;
115034d8b7eaSJeff Roberson 			} else if (error == EBUSY) {
115134d8b7eaSJeff Roberson 				addl_page_shortage++;
115248cc2fc7SKonstantin Belousov 			}
115348cc2fc7SKonstantin Belousov 			vm_page_lock_assert(m, MA_NOTOWNED);
11543ac8f842SMark Johnston 			goto relock_queue;
115548cc2fc7SKonstantin Belousov 		}
1156776f729cSKonstantin Belousov drop_page:
115748cc2fc7SKonstantin Belousov 		vm_page_unlock(m);
115889f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
11593ac8f842SMark Johnston relock_queue:
11603ac8f842SMark Johnston 		if (!queue_locked) {
11618d220203SAlan Cox 			vm_pagequeue_lock(pq);
11623ac8f842SMark Johnston 			queue_locked = TRUE;
11636989c456SAlan Cox 		}
1164c325e866SKonstantin Belousov 		next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1165c325e866SKonstantin Belousov 		TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
11660d94caffSDavid Greenman 	}
11678d220203SAlan Cox 	vm_pagequeue_unlock(pq);
116826f9a767SRodney W. Grimes 
11699452b5edSAlan Cox #if !defined(NO_SWAPPING)
11709452b5edSAlan Cox 	/*
1171*f095d1bbSAlan Cox 	 * Wakeup the swapout daemon if we didn't free the targeted number of
1172*f095d1bbSAlan Cox 	 * pages.
11739452b5edSAlan Cox 	 */
11749452b5edSAlan Cox 	if (vm_swap_enabled && page_shortage > 0)
11759452b5edSAlan Cox 		vm_req_vmdaemon(VM_SWAP_NORMAL);
11769452b5edSAlan Cox #endif
11779452b5edSAlan Cox 
11789452b5edSAlan Cox 	/*
11799452b5edSAlan Cox 	 * Wakeup the sync daemon if we skipped a vnode in a writeable object
1180*f095d1bbSAlan Cox 	 * and we didn't free enough pages.
11819452b5edSAlan Cox 	 */
11829452b5edSAlan Cox 	if (vnodes_skipped > 0 && page_shortage > vm_cnt.v_free_target -
11839452b5edSAlan Cox 	    vm_cnt.v_free_min)
11849452b5edSAlan Cox 		(void)speedup_syncer();
11859452b5edSAlan Cox 
1186df8bae1dSRodney W. Grimes 	/*
118776386c7eSKonstantin Belousov 	 * If the inactive queue scan fails repeatedly to meet its
118876386c7eSKonstantin Belousov 	 * target, kill the largest process.
118976386c7eSKonstantin Belousov 	 */
119076386c7eSKonstantin Belousov 	vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
119176386c7eSKonstantin Belousov 
119276386c7eSKonstantin Belousov 	/*
1193936524aaSMatthew Dillon 	 * Compute the number of pages we want to try to move from the
1194936524aaSMatthew Dillon 	 * active queue to the inactive queue.
11951c7c3c6aSMatthew Dillon 	 */
119644f1c916SBryan Drewery 	page_shortage = vm_cnt.v_inactive_target - vm_cnt.v_inactive_count +
11979099545aSAlan Cox 	    vm_paging_target() + deficit + addl_page_shortage;
11989099545aSAlan Cox 
1199114f62c6SJeff Roberson 	pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1200114f62c6SJeff Roberson 	vm_pagequeue_lock(pq);
12019099545aSAlan Cox 	maxscan = pq->pq_cnt;
12029099545aSAlan Cox 
1203d9e23210SJeff Roberson 	/*
1204d9e23210SJeff Roberson 	 * If we're just idle polling attempt to visit every
1205d9e23210SJeff Roberson 	 * active page within 'update_period' seconds.
1206d9e23210SJeff Roberson 	 */
120722cf98d1SAlan Cox 	scan_tick = ticks;
120822cf98d1SAlan Cox 	if (vm_pageout_update_period != 0) {
120922cf98d1SAlan Cox 		min_scan = pq->pq_cnt;
121022cf98d1SAlan Cox 		min_scan *= scan_tick - vmd->vmd_last_active_scan;
121122cf98d1SAlan Cox 		min_scan /= hz * vm_pageout_update_period;
121222cf98d1SAlan Cox 	} else
121322cf98d1SAlan Cox 		min_scan = 0;
121422cf98d1SAlan Cox 	if (min_scan > 0 || (page_shortage > 0 && maxscan > 0))
121522cf98d1SAlan Cox 		vmd->vmd_last_active_scan = scan_tick;
12161c7c3c6aSMatthew Dillon 
12171c7c3c6aSMatthew Dillon 	/*
121822cf98d1SAlan Cox 	 * Scan the active queue for pages that can be deactivated.  Update
121922cf98d1SAlan Cox 	 * the per-page activity counter and use it to identify deactivation
122022cf98d1SAlan Cox 	 * candidates.
12211c7c3c6aSMatthew Dillon 	 */
122222cf98d1SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
122322cf98d1SAlan Cox 	    min_scan || (page_shortage > 0 && scanned < maxscan)); m = next,
122422cf98d1SAlan Cox 	    scanned++) {
1225f35329acSJohn Dyson 
12269cf51988SAlan Cox 		KASSERT(m->queue == PQ_ACTIVE,
1227d3c09dd7SAlan Cox 		    ("vm_pageout_scan: page %p isn't active", m));
1228f35329acSJohn Dyson 
1229c325e866SKonstantin Belousov 		next = TAILQ_NEXT(m, plinks.q);
123022cf98d1SAlan Cox 		if ((m->flags & PG_MARKER) != 0)
12318dbca793STor Egge 			continue;
12327900f95dSKonstantin Belousov 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
12337900f95dSKonstantin Belousov 		    ("Fictitious page %p cannot be in active queue", m));
12347900f95dSKonstantin Belousov 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
12357900f95dSKonstantin Belousov 		    ("Unmanaged page %p cannot be in active queue", m));
12369ee2165fSAlan Cox 		if (!vm_pageout_page_lock(m, &next)) {
12378c616246SKonstantin Belousov 			vm_page_unlock(m);
12382965a453SKip Macy 			continue;
12392965a453SKip Macy 		}
1240b18bfc3dSJohn Dyson 
1241b18bfc3dSJohn Dyson 		/*
1242b18bfc3dSJohn Dyson 		 * The count for pagedaemon pages is done after checking the
1243956f3135SPhilippe Charnier 		 * page for eligibility...
1244b18bfc3dSJohn Dyson 		 */
12458d220203SAlan Cox 		PCPU_INC(cnt.v_pdpages);
1246ef743ce6SJohn Dyson 
12477e006499SJohn Dyson 		/*
12487e006499SJohn Dyson 		 * Check to see "how much" the page has been used.
12497e006499SJohn Dyson 		 */
125086fa2471SAlan Cox 		if ((m->aflags & PGA_REFERENCED) != 0) {
1251bb7858eaSJeff Roberson 			vm_page_aflag_clear(m, PGA_REFERENCED);
125286fa2471SAlan Cox 			act_delta = 1;
125386fa2471SAlan Cox 		} else
125486fa2471SAlan Cox 			act_delta = 0;
125586fa2471SAlan Cox 
1256274132acSJeff Roberson 		/*
1257274132acSJeff Roberson 		 * Unlocked object ref count check.  Two races are possible.
1258274132acSJeff Roberson 		 * 1) The ref was transitioning to zero and we saw non-zero,
1259274132acSJeff Roberson 		 *    the pmap bits will be checked unnecessarily.
1260274132acSJeff Roberson 		 * 2) The ref was transitioning to one and we saw zero.
1261274132acSJeff Roberson 		 *    The page lock prevents a new reference to this page so
1262274132acSJeff Roberson 		 *    we need not check the reference bits.
1263274132acSJeff Roberson 		 */
1264274132acSJeff Roberson 		if (m->object->ref_count != 0)
1265bb7858eaSJeff Roberson 			act_delta += pmap_ts_referenced(m);
1266bb7858eaSJeff Roberson 
1267bb7858eaSJeff Roberson 		/*
1268bb7858eaSJeff Roberson 		 * Advance or decay the act_count based on recent usage.
1269bb7858eaSJeff Roberson 		 */
127086fa2471SAlan Cox 		if (act_delta != 0) {
1271bb7858eaSJeff Roberson 			m->act_count += ACT_ADVANCE + act_delta;
127238efa82bSJohn Dyson 			if (m->act_count > ACT_MAX)
127338efa82bSJohn Dyson 				m->act_count = ACT_MAX;
127486fa2471SAlan Cox 		} else
127538efa82bSJohn Dyson 			m->act_count -= min(m->act_count, ACT_DECLINE);
1276bb7858eaSJeff Roberson 
1277bb7858eaSJeff Roberson 		/*
1278bb7858eaSJeff Roberson 		 * Move this page to the tail of the active or inactive
1279bb7858eaSJeff Roberson 		 * queue depending on usage.
1280bb7858eaSJeff Roberson 		 */
128186fa2471SAlan Cox 		if (m->act_count == 0) {
12828d220203SAlan Cox 			/* Dequeue to avoid later lock recursion. */
12838d220203SAlan Cox 			vm_page_dequeue_locked(m);
1284d4a272dbSJohn Dyson 			vm_page_deactivate(m);
1285bb7858eaSJeff Roberson 			page_shortage--;
12868d220203SAlan Cox 		} else
12878d220203SAlan Cox 			vm_page_requeue_locked(m);
12882965a453SKip Macy 		vm_page_unlock(m);
128926f9a767SRodney W. Grimes 	}
12908d220203SAlan Cox 	vm_pagequeue_unlock(pq);
1291ceb0cf87SJohn Dyson #if !defined(NO_SWAPPING)
1292ceb0cf87SJohn Dyson 	/*
1293ceb0cf87SJohn Dyson 	 * Idle process swapout -- run once per second.
1294ceb0cf87SJohn Dyson 	 */
1295ceb0cf87SJohn Dyson 	if (vm_swap_idle_enabled) {
1296ceb0cf87SJohn Dyson 		static long lsec;
1297227ee8a1SPoul-Henning Kamp 		if (time_second != lsec) {
129897824da3SAlan Cox 			vm_req_vmdaemon(VM_SWAP_IDLE);
1299227ee8a1SPoul-Henning Kamp 			lsec = time_second;
1300ceb0cf87SJohn Dyson 		}
1301ceb0cf87SJohn Dyson 	}
1302ceb0cf87SJohn Dyson #endif
13032025d69bSKonstantin Belousov }
13042025d69bSKonstantin Belousov 
1305449c2e92SKonstantin Belousov static int vm_pageout_oom_vote;
1306449c2e92SKonstantin Belousov 
1307449c2e92SKonstantin Belousov /*
1308449c2e92SKonstantin Belousov  * The pagedaemon threads randlomly select one to perform the
1309449c2e92SKonstantin Belousov  * OOM.  Trying to kill processes before all pagedaemons
1310449c2e92SKonstantin Belousov  * failed to reach free target is premature.
1311449c2e92SKonstantin Belousov  */
1312449c2e92SKonstantin Belousov static void
131376386c7eSKonstantin Belousov vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
131476386c7eSKonstantin Belousov     int starting_page_shortage)
1315449c2e92SKonstantin Belousov {
1316449c2e92SKonstantin Belousov 	int old_vote;
1317449c2e92SKonstantin Belousov 
131876386c7eSKonstantin Belousov 	if (starting_page_shortage <= 0 || starting_page_shortage !=
131976386c7eSKonstantin Belousov 	    page_shortage)
132076386c7eSKonstantin Belousov 		vmd->vmd_oom_seq = 0;
132176386c7eSKonstantin Belousov 	else
132276386c7eSKonstantin Belousov 		vmd->vmd_oom_seq++;
132376386c7eSKonstantin Belousov 	if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1324449c2e92SKonstantin Belousov 		if (vmd->vmd_oom) {
1325449c2e92SKonstantin Belousov 			vmd->vmd_oom = FALSE;
1326449c2e92SKonstantin Belousov 			atomic_subtract_int(&vm_pageout_oom_vote, 1);
1327449c2e92SKonstantin Belousov 		}
1328449c2e92SKonstantin Belousov 		return;
1329449c2e92SKonstantin Belousov 	}
1330449c2e92SKonstantin Belousov 
133176386c7eSKonstantin Belousov 	/*
133276386c7eSKonstantin Belousov 	 * Do not follow the call sequence until OOM condition is
133376386c7eSKonstantin Belousov 	 * cleared.
133476386c7eSKonstantin Belousov 	 */
133576386c7eSKonstantin Belousov 	vmd->vmd_oom_seq = 0;
133676386c7eSKonstantin Belousov 
1337449c2e92SKonstantin Belousov 	if (vmd->vmd_oom)
1338449c2e92SKonstantin Belousov 		return;
1339449c2e92SKonstantin Belousov 
1340449c2e92SKonstantin Belousov 	vmd->vmd_oom = TRUE;
1341449c2e92SKonstantin Belousov 	old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1342449c2e92SKonstantin Belousov 	if (old_vote != vm_ndomains - 1)
1343449c2e92SKonstantin Belousov 		return;
1344449c2e92SKonstantin Belousov 
1345449c2e92SKonstantin Belousov 	/*
1346449c2e92SKonstantin Belousov 	 * The current pagedaemon thread is the last in the quorum to
1347449c2e92SKonstantin Belousov 	 * start OOM.  Initiate the selection and signaling of the
1348449c2e92SKonstantin Belousov 	 * victim.
1349449c2e92SKonstantin Belousov 	 */
1350449c2e92SKonstantin Belousov 	vm_pageout_oom(VM_OOM_MEM);
1351449c2e92SKonstantin Belousov 
1352449c2e92SKonstantin Belousov 	/*
1353449c2e92SKonstantin Belousov 	 * After one round of OOM terror, recall our vote.  On the
1354449c2e92SKonstantin Belousov 	 * next pass, current pagedaemon would vote again if the low
1355449c2e92SKonstantin Belousov 	 * memory condition is still there, due to vmd_oom being
1356449c2e92SKonstantin Belousov 	 * false.
1357449c2e92SKonstantin Belousov 	 */
1358449c2e92SKonstantin Belousov 	vmd->vmd_oom = FALSE;
1359449c2e92SKonstantin Belousov 	atomic_subtract_int(&vm_pageout_oom_vote, 1);
1360449c2e92SKonstantin Belousov }
13612025d69bSKonstantin Belousov 
13623949873fSKonstantin Belousov /*
13633949873fSKonstantin Belousov  * The OOM killer is the page daemon's action of last resort when
13643949873fSKonstantin Belousov  * memory allocation requests have been stalled for a prolonged period
13653949873fSKonstantin Belousov  * of time because it cannot reclaim memory.  This function computes
13663949873fSKonstantin Belousov  * the approximate number of physical pages that could be reclaimed if
13673949873fSKonstantin Belousov  * the specified address space is destroyed.
13683949873fSKonstantin Belousov  *
13693949873fSKonstantin Belousov  * Private, anonymous memory owned by the address space is the
13703949873fSKonstantin Belousov  * principal resource that we expect to recover after an OOM kill.
13713949873fSKonstantin Belousov  * Since the physical pages mapped by the address space's COW entries
13723949873fSKonstantin Belousov  * are typically shared pages, they are unlikely to be released and so
13733949873fSKonstantin Belousov  * they are not counted.
13743949873fSKonstantin Belousov  *
13753949873fSKonstantin Belousov  * To get to the point where the page daemon runs the OOM killer, its
13763949873fSKonstantin Belousov  * efforts to write-back vnode-backed pages may have stalled.  This
13773949873fSKonstantin Belousov  * could be caused by a memory allocation deadlock in the write path
13783949873fSKonstantin Belousov  * that might be resolved by an OOM kill.  Therefore, physical pages
13793949873fSKonstantin Belousov  * belonging to vnode-backed objects are counted, because they might
13803949873fSKonstantin Belousov  * be freed without being written out first if the address space holds
13813949873fSKonstantin Belousov  * the last reference to an unlinked vnode.
13823949873fSKonstantin Belousov  *
13833949873fSKonstantin Belousov  * Similarly, physical pages belonging to OBJT_PHYS objects are
13843949873fSKonstantin Belousov  * counted because the address space might hold the last reference to
13853949873fSKonstantin Belousov  * the object.
13863949873fSKonstantin Belousov  */
13873949873fSKonstantin Belousov static long
13883949873fSKonstantin Belousov vm_pageout_oom_pagecount(struct vmspace *vmspace)
13893949873fSKonstantin Belousov {
13903949873fSKonstantin Belousov 	vm_map_t map;
13913949873fSKonstantin Belousov 	vm_map_entry_t entry;
13923949873fSKonstantin Belousov 	vm_object_t obj;
13933949873fSKonstantin Belousov 	long res;
13943949873fSKonstantin Belousov 
13953949873fSKonstantin Belousov 	map = &vmspace->vm_map;
13963949873fSKonstantin Belousov 	KASSERT(!map->system_map, ("system map"));
13973949873fSKonstantin Belousov 	sx_assert(&map->lock, SA_LOCKED);
13983949873fSKonstantin Belousov 	res = 0;
13993949873fSKonstantin Belousov 	for (entry = map->header.next; entry != &map->header;
14003949873fSKonstantin Belousov 	    entry = entry->next) {
14013949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
14023949873fSKonstantin Belousov 			continue;
14033949873fSKonstantin Belousov 		obj = entry->object.vm_object;
14043949873fSKonstantin Belousov 		if (obj == NULL)
14053949873fSKonstantin Belousov 			continue;
14063949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
14073949873fSKonstantin Belousov 		    obj->ref_count != 1)
14083949873fSKonstantin Belousov 			continue;
14093949873fSKonstantin Belousov 		switch (obj->type) {
14103949873fSKonstantin Belousov 		case OBJT_DEFAULT:
14113949873fSKonstantin Belousov 		case OBJT_SWAP:
14123949873fSKonstantin Belousov 		case OBJT_PHYS:
14133949873fSKonstantin Belousov 		case OBJT_VNODE:
14143949873fSKonstantin Belousov 			res += obj->resident_page_count;
14153949873fSKonstantin Belousov 			break;
14163949873fSKonstantin Belousov 		}
14173949873fSKonstantin Belousov 	}
14183949873fSKonstantin Belousov 	return (res);
14193949873fSKonstantin Belousov }
14203949873fSKonstantin Belousov 
14212025d69bSKonstantin Belousov void
14222025d69bSKonstantin Belousov vm_pageout_oom(int shortage)
14232025d69bSKonstantin Belousov {
14242025d69bSKonstantin Belousov 	struct proc *p, *bigproc;
14252025d69bSKonstantin Belousov 	vm_offset_t size, bigsize;
14262025d69bSKonstantin Belousov 	struct thread *td;
14276bed074cSKonstantin Belousov 	struct vmspace *vm;
14282025d69bSKonstantin Belousov 
14292025d69bSKonstantin Belousov 	/*
14301c58e4e5SJohn Baldwin 	 * We keep the process bigproc locked once we find it to keep anyone
14311c58e4e5SJohn Baldwin 	 * from messing with it; however, there is a possibility of
14321c58e4e5SJohn Baldwin 	 * deadlock if process B is bigproc and one of it's child processes
14331c58e4e5SJohn Baldwin 	 * attempts to propagate a signal to B while we are waiting for A's
14341c58e4e5SJohn Baldwin 	 * lock while walking this list.  To avoid this, we don't block on
14351c58e4e5SJohn Baldwin 	 * the process lock but just skip a process if it is already locked.
14365663e6deSDavid Greenman 	 */
14375663e6deSDavid Greenman 	bigproc = NULL;
14385663e6deSDavid Greenman 	bigsize = 0;
14391005a129SJohn Baldwin 	sx_slock(&allproc_lock);
1440e602ba25SJulian Elischer 	FOREACH_PROC_IN_SYSTEM(p) {
1441e602ba25SJulian Elischer 		int breakout;
1442dcbcd518SBruce Evans 
144371943c3dSKonstantin Belousov 		PROC_LOCK(p);
144471943c3dSKonstantin Belousov 
14451c58e4e5SJohn Baldwin 		/*
14463f1c4c4fSKonstantin Belousov 		 * If this is a system, protected or killed process, skip it.
14475663e6deSDavid Greenman 		 */
144871943c3dSKonstantin Belousov 		if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
144971943c3dSKonstantin Belousov 		    P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
145071943c3dSKonstantin Belousov 		    p->p_pid == 1 || P_KILLED(p) ||
145171943c3dSKonstantin Belousov 		    (p->p_pid < 48 && swap_pager_avail != 0)) {
14528606d880SJohn Baldwin 			PROC_UNLOCK(p);
14535663e6deSDavid Greenman 			continue;
14545663e6deSDavid Greenman 		}
14555663e6deSDavid Greenman 		/*
1456dcbcd518SBruce Evans 		 * If the process is in a non-running type state,
1457e602ba25SJulian Elischer 		 * don't touch it.  Check all the threads individually.
14585663e6deSDavid Greenman 		 */
1459e602ba25SJulian Elischer 		breakout = 0;
1460e602ba25SJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td) {
1461982d11f8SJeff Roberson 			thread_lock(td);
146271fad9fdSJulian Elischer 			if (!TD_ON_RUNQ(td) &&
146371fad9fdSJulian Elischer 			    !TD_IS_RUNNING(td) &&
1464f497cda2SEdward Tomasz Napierala 			    !TD_IS_SLEEPING(td) &&
1465b98acc0aSKonstantin Belousov 			    !TD_IS_SUSPENDED(td) &&
1466b98acc0aSKonstantin Belousov 			    !TD_IS_SWAPPED(td)) {
1467982d11f8SJeff Roberson 				thread_unlock(td);
1468e602ba25SJulian Elischer 				breakout = 1;
1469e602ba25SJulian Elischer 				break;
1470e602ba25SJulian Elischer 			}
1471982d11f8SJeff Roberson 			thread_unlock(td);
1472e602ba25SJulian Elischer 		}
1473e602ba25SJulian Elischer 		if (breakout) {
14741c58e4e5SJohn Baldwin 			PROC_UNLOCK(p);
14755663e6deSDavid Greenman 			continue;
14765663e6deSDavid Greenman 		}
14775663e6deSDavid Greenman 		/*
14785663e6deSDavid Greenman 		 * get the process size
14795663e6deSDavid Greenman 		 */
14806bed074cSKonstantin Belousov 		vm = vmspace_acquire_ref(p);
14816bed074cSKonstantin Belousov 		if (vm == NULL) {
14826bed074cSKonstantin Belousov 			PROC_UNLOCK(p);
14836bed074cSKonstantin Belousov 			continue;
14846bed074cSKonstantin Belousov 		}
148595e2409aSKonstantin Belousov 		_PHOLD_LITE(p);
148672d97679SDavid Schultz 		PROC_UNLOCK(p);
148795e2409aSKonstantin Belousov 		sx_sunlock(&allproc_lock);
148895e2409aSKonstantin Belousov 		if (!vm_map_trylock_read(&vm->vm_map)) {
148971943c3dSKonstantin Belousov 			vmspace_free(vm);
149095e2409aSKonstantin Belousov 			sx_slock(&allproc_lock);
149195e2409aSKonstantin Belousov 			PRELE(p);
149272d97679SDavid Schultz 			continue;
149372d97679SDavid Schultz 		}
14947981aa24SKonstantin Belousov 		size = vmspace_swap_count(vm);
14952025d69bSKonstantin Belousov 		if (shortage == VM_OOM_MEM)
14963949873fSKonstantin Belousov 			size += vm_pageout_oom_pagecount(vm);
14973949873fSKonstantin Belousov 		vm_map_unlock_read(&vm->vm_map);
14986bed074cSKonstantin Belousov 		vmspace_free(vm);
149995e2409aSKonstantin Belousov 		sx_slock(&allproc_lock);
15003949873fSKonstantin Belousov 
15015663e6deSDavid Greenman 		/*
15023949873fSKonstantin Belousov 		 * If this process is bigger than the biggest one,
15035663e6deSDavid Greenman 		 * remember it.
15045663e6deSDavid Greenman 		 */
15055663e6deSDavid Greenman 		if (size > bigsize) {
15061c58e4e5SJohn Baldwin 			if (bigproc != NULL)
150771943c3dSKonstantin Belousov 				PRELE(bigproc);
15085663e6deSDavid Greenman 			bigproc = p;
15095663e6deSDavid Greenman 			bigsize = size;
151071943c3dSKonstantin Belousov 		} else {
151171943c3dSKonstantin Belousov 			PRELE(p);
151271943c3dSKonstantin Belousov 		}
15135663e6deSDavid Greenman 	}
15141005a129SJohn Baldwin 	sx_sunlock(&allproc_lock);
15155663e6deSDavid Greenman 	if (bigproc != NULL) {
15168311a2b8SWill Andrews 		if (vm_panic_on_oom != 0)
15178311a2b8SWill Andrews 			panic("out of swap space");
151871943c3dSKonstantin Belousov 		PROC_LOCK(bigproc);
1519729b1e51SDavid Greenman 		killproc(bigproc, "out of swap space");
1520fa885116SJulian Elischer 		sched_nice(bigproc, PRIO_MIN);
152171943c3dSKonstantin Belousov 		_PRELE(bigproc);
15221c58e4e5SJohn Baldwin 		PROC_UNLOCK(bigproc);
152344f1c916SBryan Drewery 		wakeup(&vm_cnt.v_free_count);
15245663e6deSDavid Greenman 	}
15255663e6deSDavid Greenman }
152626f9a767SRodney W. Grimes 
1527449c2e92SKonstantin Belousov static void
1528449c2e92SKonstantin Belousov vm_pageout_worker(void *arg)
1529449c2e92SKonstantin Belousov {
1530449c2e92SKonstantin Belousov 	struct vm_domain *domain;
1531949c9186SKonstantin Belousov 	int domidx;
1532449c2e92SKonstantin Belousov 
1533449c2e92SKonstantin Belousov 	domidx = (uintptr_t)arg;
1534449c2e92SKonstantin Belousov 	domain = &vm_dom[domidx];
1535449c2e92SKonstantin Belousov 
1536449c2e92SKonstantin Belousov 	/*
1537949c9186SKonstantin Belousov 	 * XXXKIB It could be useful to bind pageout daemon threads to
1538949c9186SKonstantin Belousov 	 * the cores belonging to the domain, from which vm_page_array
1539949c9186SKonstantin Belousov 	 * is allocated.
1540449c2e92SKonstantin Belousov 	 */
1541449c2e92SKonstantin Belousov 
1542449c2e92SKonstantin Belousov 	KASSERT(domain->vmd_segs != 0, ("domain without segments"));
154322cf98d1SAlan Cox 	domain->vmd_last_active_scan = ticks;
1544449c2e92SKonstantin Belousov 	vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
15457e78597fSMark Johnston 	vm_pageout_init_marker(&domain->vmd_inacthead, PQ_INACTIVE);
15467e78597fSMark Johnston 	TAILQ_INSERT_HEAD(&domain->vmd_pagequeues[PQ_INACTIVE].pq_pl,
15477e78597fSMark Johnston 	    &domain->vmd_inacthead, plinks.q);
1548449c2e92SKonstantin Belousov 
1549449c2e92SKonstantin Belousov 	/*
1550449c2e92SKonstantin Belousov 	 * The pageout daemon worker is never done, so loop forever.
1551449c2e92SKonstantin Belousov 	 */
1552449c2e92SKonstantin Belousov 	while (TRUE) {
1553449c2e92SKonstantin Belousov 		mtx_lock(&vm_page_queue_free_mtx);
155456ce0690SAlan Cox 
155556ce0690SAlan Cox 		/*
155656ce0690SAlan Cox 		 * Generally, after a level >= 1 scan, if there are enough
155756ce0690SAlan Cox 		 * free pages to wakeup the waiters, then they are already
155856ce0690SAlan Cox 		 * awake.  A call to vm_page_free() during the scan awakened
155956ce0690SAlan Cox 		 * them.  However, in the following case, this wakeup serves
156056ce0690SAlan Cox 		 * to bound the amount of time that a thread might wait.
156156ce0690SAlan Cox 		 * Suppose a thread's call to vm_page_alloc() fails, but
156256ce0690SAlan Cox 		 * before that thread calls VM_WAIT, enough pages are freed by
156356ce0690SAlan Cox 		 * other threads to alleviate the free page shortage.  The
156456ce0690SAlan Cox 		 * thread will, nonetheless, wait until another page is freed
156556ce0690SAlan Cox 		 * or this wakeup is performed.
156656ce0690SAlan Cox 		 */
1567449c2e92SKonstantin Belousov 		if (vm_pages_needed && !vm_page_count_min()) {
156856ce0690SAlan Cox 			vm_pages_needed = false;
156944f1c916SBryan Drewery 			wakeup(&vm_cnt.v_free_count);
1570449c2e92SKonstantin Belousov 		}
157156ce0690SAlan Cox 
1572449c2e92SKonstantin Belousov 		/*
157356ce0690SAlan Cox 		 * Do not clear vm_pageout_wanted until we reach our target.
157456ce0690SAlan Cox 		 * Otherwise, we may be awakened over and over again, wasting
157556ce0690SAlan Cox 		 * CPU time.
1576449c2e92SKonstantin Belousov 		 */
157756ce0690SAlan Cox 		if (vm_pageout_wanted && !vm_paging_needed())
157856ce0690SAlan Cox 			vm_pageout_wanted = false;
157956ce0690SAlan Cox 
158056ce0690SAlan Cox 		/*
158156ce0690SAlan Cox 		 * Might the page daemon receive a wakeup call?
158256ce0690SAlan Cox 		 */
158356ce0690SAlan Cox 		if (vm_pageout_wanted) {
158456ce0690SAlan Cox 			/*
158556ce0690SAlan Cox 			 * No.  Either vm_pageout_wanted was set by another
158656ce0690SAlan Cox 			 * thread during the previous scan, which must have
158756ce0690SAlan Cox 			 * been a level 0 scan, or vm_pageout_wanted was
158856ce0690SAlan Cox 			 * already set and the scan failed to free enough
158956ce0690SAlan Cox 			 * pages.  If we haven't yet performed a level >= 2
159056ce0690SAlan Cox 			 * scan (unlimited dirty cleaning), then upgrade the
159156ce0690SAlan Cox 			 * level and scan again now.  Otherwise, sleep a bit
159256ce0690SAlan Cox 			 * and try again later.
159356ce0690SAlan Cox 			 */
159456ce0690SAlan Cox 			mtx_unlock(&vm_page_queue_free_mtx);
1595449c2e92SKonstantin Belousov 			if (domain->vmd_pass > 1)
159656ce0690SAlan Cox 				pause("psleep", hz / 2);
159756ce0690SAlan Cox 			domain->vmd_pass++;
1598449c2e92SKonstantin Belousov 		} else {
1599449c2e92SKonstantin Belousov 			/*
160056ce0690SAlan Cox 			 * Yes.  Sleep until pages need to be reclaimed or
160156ce0690SAlan Cox 			 * have their reference stats updated.
1602449c2e92SKonstantin Belousov 			 */
160356ce0690SAlan Cox 			if (mtx_sleep(&vm_pageout_wanted,
160456ce0690SAlan Cox 			    &vm_page_queue_free_mtx, PDROP | PVM, "psleep",
160556ce0690SAlan Cox 			    hz) == 0) {
160656ce0690SAlan Cox 				PCPU_INC(cnt.v_pdwakeups);
160756ce0690SAlan Cox 				domain->vmd_pass = 1;
1608d9347bcaSAlan Cox 			} else
1609d9347bcaSAlan Cox 				domain->vmd_pass = 0;
161056ce0690SAlan Cox 		}
161156ce0690SAlan Cox 
1612449c2e92SKonstantin Belousov 		vm_pageout_scan(domain, domain->vmd_pass);
1613449c2e92SKonstantin Belousov 	}
1614449c2e92SKonstantin Belousov }
1615449c2e92SKonstantin Belousov 
1616df8bae1dSRodney W. Grimes /*
16174d19f4adSSteven Hartland  *	vm_pageout_init initialises basic pageout daemon settings.
1618df8bae1dSRodney W. Grimes  */
16192b14f991SJulian Elischer static void
16204d19f4adSSteven Hartland vm_pageout_init(void)
1621df8bae1dSRodney W. Grimes {
1622df8bae1dSRodney W. Grimes 	/*
1623df8bae1dSRodney W. Grimes 	 * Initialize some paging parameters.
1624df8bae1dSRodney W. Grimes 	 */
162544f1c916SBryan Drewery 	vm_cnt.v_interrupt_free_min = 2;
162644f1c916SBryan Drewery 	if (vm_cnt.v_page_count < 2000)
1627f35329acSJohn Dyson 		vm_pageout_page_count = 8;
1628f6b04d2bSDavid Greenman 
162945ae1d91SAlan Cox 	/*
163045ae1d91SAlan Cox 	 * v_free_reserved needs to include enough for the largest
163145ae1d91SAlan Cox 	 * swap pager structures plus enough for any pv_entry structs
163245ae1d91SAlan Cox 	 * when paging.
163345ae1d91SAlan Cox 	 */
163444f1c916SBryan Drewery 	if (vm_cnt.v_page_count > 1024)
163544f1c916SBryan Drewery 		vm_cnt.v_free_min = 4 + (vm_cnt.v_page_count - 1024) / 200;
16362feb50bfSAttilio Rao 	else
163744f1c916SBryan Drewery 		vm_cnt.v_free_min = 4;
163844f1c916SBryan Drewery 	vm_cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
163944f1c916SBryan Drewery 	    vm_cnt.v_interrupt_free_min;
164044f1c916SBryan Drewery 	vm_cnt.v_free_reserved = vm_pageout_page_count +
164144f1c916SBryan Drewery 	    vm_cnt.v_pageout_free_min + (vm_cnt.v_page_count / 768);
164244f1c916SBryan Drewery 	vm_cnt.v_free_severe = vm_cnt.v_free_min / 2;
164344f1c916SBryan Drewery 	vm_cnt.v_free_target = 4 * vm_cnt.v_free_min + vm_cnt.v_free_reserved;
164444f1c916SBryan Drewery 	vm_cnt.v_free_min += vm_cnt.v_free_reserved;
164544f1c916SBryan Drewery 	vm_cnt.v_free_severe += vm_cnt.v_free_reserved;
164644f1c916SBryan Drewery 	vm_cnt.v_inactive_target = (3 * vm_cnt.v_free_target) / 2;
164744f1c916SBryan Drewery 	if (vm_cnt.v_inactive_target > vm_cnt.v_free_count / 3)
164844f1c916SBryan Drewery 		vm_cnt.v_inactive_target = vm_cnt.v_free_count / 3;
1649df8bae1dSRodney W. Grimes 
1650d9e23210SJeff Roberson 	/*
1651d9e23210SJeff Roberson 	 * Set the default wakeup threshold to be 10% above the minimum
1652d9e23210SJeff Roberson 	 * page limit.  This keeps the steady state out of shortfall.
1653d9e23210SJeff Roberson 	 */
165444f1c916SBryan Drewery 	vm_pageout_wakeup_thresh = (vm_cnt.v_free_min / 10) * 11;
1655d9e23210SJeff Roberson 
1656d9e23210SJeff Roberson 	/*
1657d9e23210SJeff Roberson 	 * Set interval in seconds for active scan.  We want to visit each
1658c9612b2dSJeff Roberson 	 * page at least once every ten minutes.  This is to prevent worst
1659c9612b2dSJeff Roberson 	 * case paging behaviors with stale active LRU.
1660d9e23210SJeff Roberson 	 */
1661d9e23210SJeff Roberson 	if (vm_pageout_update_period == 0)
1662c9612b2dSJeff Roberson 		vm_pageout_update_period = 600;
1663d9e23210SJeff Roberson 
1664df8bae1dSRodney W. Grimes 	/* XXX does not really belong here */
1665df8bae1dSRodney W. Grimes 	if (vm_page_max_wired == 0)
166644f1c916SBryan Drewery 		vm_page_max_wired = vm_cnt.v_free_count / 3;
16674d19f4adSSteven Hartland }
16684d19f4adSSteven Hartland 
16694d19f4adSSteven Hartland /*
16704d19f4adSSteven Hartland  *     vm_pageout is the high level pageout daemon.
16714d19f4adSSteven Hartland  */
16724d19f4adSSteven Hartland static void
16734d19f4adSSteven Hartland vm_pageout(void)
16744d19f4adSSteven Hartland {
167544ec2b63SKonstantin Belousov 	int error;
167662d70a81SJohn Baldwin #ifdef VM_NUMA_ALLOC
167744ec2b63SKonstantin Belousov 	int i;
16784d19f4adSSteven Hartland #endif
1679df8bae1dSRodney W. Grimes 
168024a1cce3SDavid Greenman 	swap_pager_swap_init();
168162d70a81SJohn Baldwin #ifdef VM_NUMA_ALLOC
1682449c2e92SKonstantin Belousov 	for (i = 1; i < vm_ndomains; i++) {
1683449c2e92SKonstantin Belousov 		error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
1684449c2e92SKonstantin Belousov 		    curproc, NULL, 0, 0, "dom%d", i);
1685449c2e92SKonstantin Belousov 		if (error != 0) {
1686449c2e92SKonstantin Belousov 			panic("starting pageout for domain %d, error %d\n",
1687449c2e92SKonstantin Belousov 			    i, error);
1688dc2efb27SJohn Dyson 		}
1689f919ebdeSDavid Greenman 	}
1690449c2e92SKonstantin Belousov #endif
169144ec2b63SKonstantin Belousov 	error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
169244ec2b63SKonstantin Belousov 	    0, 0, "uma");
169344ec2b63SKonstantin Belousov 	if (error != 0)
169444ec2b63SKonstantin Belousov 		panic("starting uma_reclaim helper, error %d\n", error);
1695d395270dSDimitry Andric 	vm_pageout_worker((void *)(uintptr_t)0);
1696df8bae1dSRodney W. Grimes }
169726f9a767SRodney W. Grimes 
16986b4b77adSAlan Cox /*
1699e9f995d8SAlan Cox  * Unless the free page queue lock is held by the caller, this function
17006b4b77adSAlan Cox  * should be regarded as advisory.  Specifically, the caller should
170144f1c916SBryan Drewery  * not msleep() on &vm_cnt.v_free_count following this function unless
1702e9f995d8SAlan Cox  * the free page queue lock is held until the msleep() is performed.
17036b4b77adSAlan Cox  */
1704e0c5a895SJohn Dyson void
17054a365329SAndrey Zonov pagedaemon_wakeup(void)
1706e0c5a895SJohn Dyson {
1707a1c0a785SAlan Cox 
170856ce0690SAlan Cox 	if (!vm_pageout_wanted && curthread->td_proc != pageproc) {
170956ce0690SAlan Cox 		vm_pageout_wanted = true;
171056ce0690SAlan Cox 		wakeup(&vm_pageout_wanted);
1711e0c5a895SJohn Dyson 	}
1712e0c5a895SJohn Dyson }
1713e0c5a895SJohn Dyson 
171438efa82bSJohn Dyson #if !defined(NO_SWAPPING)
17155afce282SDavid Greenman static void
171697824da3SAlan Cox vm_req_vmdaemon(int req)
17175afce282SDavid Greenman {
17185afce282SDavid Greenman 	static int lastrun = 0;
17195afce282SDavid Greenman 
172097824da3SAlan Cox 	mtx_lock(&vm_daemon_mtx);
172197824da3SAlan Cox 	vm_pageout_req_swapout |= req;
1722b18bfc3dSJohn Dyson 	if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
17235afce282SDavid Greenman 		wakeup(&vm_daemon_needed);
17245afce282SDavid Greenman 		lastrun = ticks;
17255afce282SDavid Greenman 	}
172697824da3SAlan Cox 	mtx_unlock(&vm_daemon_mtx);
17275afce282SDavid Greenman }
17285afce282SDavid Greenman 
17292b14f991SJulian Elischer static void
17304a365329SAndrey Zonov vm_daemon(void)
17310d94caffSDavid Greenman {
173291d5354aSJohn Baldwin 	struct rlimit rsslim;
1733dcbcd518SBruce Evans 	struct proc *p;
1734dcbcd518SBruce Evans 	struct thread *td;
17356bed074cSKonstantin Belousov 	struct vmspace *vm;
1736099e7e95SEdward Tomasz Napierala 	int breakout, swapout_flags, tryagain, attempts;
1737afcc55f3SEdward Tomasz Napierala #ifdef RACCT
1738099e7e95SEdward Tomasz Napierala 	uint64_t rsize, ravailable;
1739afcc55f3SEdward Tomasz Napierala #endif
17400d94caffSDavid Greenman 
17412fe6e4d7SDavid Greenman 	while (TRUE) {
174297824da3SAlan Cox 		mtx_lock(&vm_daemon_mtx);
17434b5c9cf6SEdward Tomasz Napierala 		msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
1744099e7e95SEdward Tomasz Napierala #ifdef RACCT
17454b5c9cf6SEdward Tomasz Napierala 		    racct_enable ? hz : 0
1746099e7e95SEdward Tomasz Napierala #else
17474b5c9cf6SEdward Tomasz Napierala 		    0
1748099e7e95SEdward Tomasz Napierala #endif
17494b5c9cf6SEdward Tomasz Napierala 		);
175097824da3SAlan Cox 		swapout_flags = vm_pageout_req_swapout;
17514c1f8ee9SDavid Greenman 		vm_pageout_req_swapout = 0;
175297824da3SAlan Cox 		mtx_unlock(&vm_daemon_mtx);
175397824da3SAlan Cox 		if (swapout_flags)
175497824da3SAlan Cox 			swapout_procs(swapout_flags);
175597824da3SAlan Cox 
17562fe6e4d7SDavid Greenman 		/*
17570d94caffSDavid Greenman 		 * scan the processes for exceeding their rlimits or if
17580d94caffSDavid Greenman 		 * process is swapped out -- deactivate pages
17592fe6e4d7SDavid Greenman 		 */
1760099e7e95SEdward Tomasz Napierala 		tryagain = 0;
1761099e7e95SEdward Tomasz Napierala 		attempts = 0;
1762099e7e95SEdward Tomasz Napierala again:
1763099e7e95SEdward Tomasz Napierala 		attempts++;
17641005a129SJohn Baldwin 		sx_slock(&allproc_lock);
1765f67af5c9SXin LI 		FOREACH_PROC_IN_SYSTEM(p) {
1766fe2144fdSLuoqi Chen 			vm_pindex_t limit, size;
17672fe6e4d7SDavid Greenman 
17682fe6e4d7SDavid Greenman 			/*
17692fe6e4d7SDavid Greenman 			 * if this is a system process or if we have already
17702fe6e4d7SDavid Greenman 			 * looked at this process, skip it.
17712fe6e4d7SDavid Greenman 			 */
1772897ecacdSJohn Baldwin 			PROC_LOCK(p);
17738e6fa660SJohn Baldwin 			if (p->p_state != PRS_NORMAL ||
17748e6fa660SJohn Baldwin 			    p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
1775897ecacdSJohn Baldwin 				PROC_UNLOCK(p);
17762fe6e4d7SDavid Greenman 				continue;
17772fe6e4d7SDavid Greenman 			}
17782fe6e4d7SDavid Greenman 			/*
17792fe6e4d7SDavid Greenman 			 * if the process is in a non-running type state,
17802fe6e4d7SDavid Greenman 			 * don't touch it.
17812fe6e4d7SDavid Greenman 			 */
1782e602ba25SJulian Elischer 			breakout = 0;
1783e602ba25SJulian Elischer 			FOREACH_THREAD_IN_PROC(p, td) {
1784982d11f8SJeff Roberson 				thread_lock(td);
178571fad9fdSJulian Elischer 				if (!TD_ON_RUNQ(td) &&
178671fad9fdSJulian Elischer 				    !TD_IS_RUNNING(td) &&
1787f497cda2SEdward Tomasz Napierala 				    !TD_IS_SLEEPING(td) &&
1788f497cda2SEdward Tomasz Napierala 				    !TD_IS_SUSPENDED(td)) {
1789982d11f8SJeff Roberson 					thread_unlock(td);
1790e602ba25SJulian Elischer 					breakout = 1;
1791e602ba25SJulian Elischer 					break;
1792e602ba25SJulian Elischer 				}
1793982d11f8SJeff Roberson 				thread_unlock(td);
1794e602ba25SJulian Elischer 			}
1795897ecacdSJohn Baldwin 			if (breakout) {
1796897ecacdSJohn Baldwin 				PROC_UNLOCK(p);
17972fe6e4d7SDavid Greenman 				continue;
17982fe6e4d7SDavid Greenman 			}
17992fe6e4d7SDavid Greenman 			/*
18002fe6e4d7SDavid Greenman 			 * get a limit
18012fe6e4d7SDavid Greenman 			 */
1802f6f6d240SMateusz Guzik 			lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
1803fe2144fdSLuoqi Chen 			limit = OFF_TO_IDX(
180491d5354aSJohn Baldwin 			    qmin(rsslim.rlim_cur, rsslim.rlim_max));
18052fe6e4d7SDavid Greenman 
18062fe6e4d7SDavid Greenman 			/*
18070d94caffSDavid Greenman 			 * let processes that are swapped out really be
18080d94caffSDavid Greenman 			 * swapped out set the limit to nothing (will force a
18090d94caffSDavid Greenman 			 * swap-out.)
18102fe6e4d7SDavid Greenman 			 */
1811b61ce5b0SJeff Roberson 			if ((p->p_flag & P_INMEM) == 0)
18120d94caffSDavid Greenman 				limit = 0;	/* XXX */
18136bed074cSKonstantin Belousov 			vm = vmspace_acquire_ref(p);
181495e2409aSKonstantin Belousov 			_PHOLD_LITE(p);
1815897ecacdSJohn Baldwin 			PROC_UNLOCK(p);
181695e2409aSKonstantin Belousov 			if (vm == NULL) {
181795e2409aSKonstantin Belousov 				PRELE(p);
18186bed074cSKonstantin Belousov 				continue;
181995e2409aSKonstantin Belousov 			}
182095e2409aSKonstantin Belousov 			sx_sunlock(&allproc_lock);
18212fe6e4d7SDavid Greenman 
18226bed074cSKonstantin Belousov 			size = vmspace_resident_count(vm);
1823a406d8c3SEdward Tomasz Napierala 			if (size >= limit) {
1824fe2144fdSLuoqi Chen 				vm_pageout_map_deactivate_pages(
18256bed074cSKonstantin Belousov 				    &vm->vm_map, limit);
18262fe6e4d7SDavid Greenman 			}
1827afcc55f3SEdward Tomasz Napierala #ifdef RACCT
18284b5c9cf6SEdward Tomasz Napierala 			if (racct_enable) {
1829099e7e95SEdward Tomasz Napierala 				rsize = IDX_TO_OFF(size);
1830099e7e95SEdward Tomasz Napierala 				PROC_LOCK(p);
1831099e7e95SEdward Tomasz Napierala 				racct_set(p, RACCT_RSS, rsize);
1832099e7e95SEdward Tomasz Napierala 				ravailable = racct_get_available(p, RACCT_RSS);
1833099e7e95SEdward Tomasz Napierala 				PROC_UNLOCK(p);
1834099e7e95SEdward Tomasz Napierala 				if (rsize > ravailable) {
1835099e7e95SEdward Tomasz Napierala 					/*
18364b5c9cf6SEdward Tomasz Napierala 					 * Don't be overly aggressive; this
18374b5c9cf6SEdward Tomasz Napierala 					 * might be an innocent process,
18384b5c9cf6SEdward Tomasz Napierala 					 * and the limit could've been exceeded
18394b5c9cf6SEdward Tomasz Napierala 					 * by some memory hog.  Don't try
18404b5c9cf6SEdward Tomasz Napierala 					 * to deactivate more than 1/4th
18414b5c9cf6SEdward Tomasz Napierala 					 * of process' resident set size.
1842099e7e95SEdward Tomasz Napierala 					 */
1843099e7e95SEdward Tomasz Napierala 					if (attempts <= 8) {
18444b5c9cf6SEdward Tomasz Napierala 						if (ravailable < rsize -
18454b5c9cf6SEdward Tomasz Napierala 						    (rsize / 4)) {
18464b5c9cf6SEdward Tomasz Napierala 							ravailable = rsize -
18474b5c9cf6SEdward Tomasz Napierala 							    (rsize / 4);
18484b5c9cf6SEdward Tomasz Napierala 						}
1849099e7e95SEdward Tomasz Napierala 					}
1850099e7e95SEdward Tomasz Napierala 					vm_pageout_map_deactivate_pages(
18514b5c9cf6SEdward Tomasz Napierala 					    &vm->vm_map,
18524b5c9cf6SEdward Tomasz Napierala 					    OFF_TO_IDX(ravailable));
1853099e7e95SEdward Tomasz Napierala 					/* Update RSS usage after paging out. */
1854099e7e95SEdward Tomasz Napierala 					size = vmspace_resident_count(vm);
1855099e7e95SEdward Tomasz Napierala 					rsize = IDX_TO_OFF(size);
1856099e7e95SEdward Tomasz Napierala 					PROC_LOCK(p);
1857099e7e95SEdward Tomasz Napierala 					racct_set(p, RACCT_RSS, rsize);
1858099e7e95SEdward Tomasz Napierala 					PROC_UNLOCK(p);
1859099e7e95SEdward Tomasz Napierala 					if (rsize > ravailable)
1860099e7e95SEdward Tomasz Napierala 						tryagain = 1;
1861099e7e95SEdward Tomasz Napierala 				}
18624b5c9cf6SEdward Tomasz Napierala 			}
1863afcc55f3SEdward Tomasz Napierala #endif
18646bed074cSKonstantin Belousov 			vmspace_free(vm);
186595e2409aSKonstantin Belousov 			sx_slock(&allproc_lock);
186695e2409aSKonstantin Belousov 			PRELE(p);
18672fe6e4d7SDavid Greenman 		}
18681005a129SJohn Baldwin 		sx_sunlock(&allproc_lock);
1869099e7e95SEdward Tomasz Napierala 		if (tryagain != 0 && attempts <= 10)
1870099e7e95SEdward Tomasz Napierala 			goto again;
187124a1cce3SDavid Greenman 	}
18722fe6e4d7SDavid Greenman }
1873a1287949SEivind Eklund #endif			/* !defined(NO_SWAPPING) */
1874