xref: /freebsd/sys/vm/vm_pageout.c (revision 7672ca059a716f41cd64daef56493a75d661b166)
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"
79*7672ca05SMark 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_pages_needed;		/* Event on which pageout daemon sleeps */
1608b245767SAlan Cox int vm_pageout_deficit;		/* Estimated number of pages deficit */
161d9e23210SJeff Roberson int vm_pageout_wakeup_thresh;
16276386c7eSKonstantin Belousov static int vm_pageout_oom_seq = 12;
16326f9a767SRodney W. Grimes 
16438efa82bSJohn Dyson #if !defined(NO_SWAPPING)
165f708ef1bSPoul-Henning Kamp static int vm_pageout_req_swapout;	/* XXX */
166f708ef1bSPoul-Henning Kamp static int vm_daemon_needed;
16797824da3SAlan Cox static struct mtx vm_daemon_mtx;
16897824da3SAlan Cox /* Allow for use by vm_pageout before vm_daemon is initialized. */
16997824da3SAlan Cox MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
17038efa82bSJohn Dyson #endif
1712b6b0df7SMatthew Dillon static int vm_max_launder = 32;
172d9e23210SJeff Roberson static int vm_pageout_update_period;
1734a365329SAndrey Zonov static int defer_swap_pageouts;
1744a365329SAndrey Zonov static int disable_swap_pageouts;
175c9612b2dSJeff Roberson static int lowmem_period = 10;
176a6bf3a9eSRyan Stone static time_t lowmem_uptime;
17770111b90SJohn Dyson 
17838efa82bSJohn Dyson #if defined(NO_SWAPPING)
179303b270bSEivind Eklund static int vm_swap_enabled = 0;
180303b270bSEivind Eklund static int vm_swap_idle_enabled = 0;
18138efa82bSJohn Dyson #else
182303b270bSEivind Eklund static int vm_swap_enabled = 1;
183303b270bSEivind Eklund static int vm_swap_idle_enabled = 0;
18438efa82bSJohn Dyson #endif
18538efa82bSJohn Dyson 
1868311a2b8SWill Andrews static int vm_panic_on_oom = 0;
1878311a2b8SWill Andrews 
1888311a2b8SWill Andrews SYSCTL_INT(_vm, OID_AUTO, panic_on_oom,
1898311a2b8SWill Andrews 	CTLFLAG_RWTUN, &vm_panic_on_oom, 0,
1908311a2b8SWill Andrews 	"panic on out of memory instead of killing the largest process");
1918311a2b8SWill Andrews 
192d9e23210SJeff Roberson SYSCTL_INT(_vm, OID_AUTO, pageout_wakeup_thresh,
193d9e23210SJeff Roberson 	CTLFLAG_RW, &vm_pageout_wakeup_thresh, 0,
194d9e23210SJeff Roberson 	"free page threshold for waking up the pageout daemon");
195d9e23210SJeff Roberson 
1962b6b0df7SMatthew Dillon SYSCTL_INT(_vm, OID_AUTO, max_launder,
1972b6b0df7SMatthew Dillon 	CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
19838efa82bSJohn Dyson 
199d9e23210SJeff Roberson SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
200d9e23210SJeff Roberson 	CTLFLAG_RW, &vm_pageout_update_period, 0,
201d9e23210SJeff Roberson 	"Maximum active LRU update period");
20253636869SAndrey Zonov 
203c9612b2dSJeff Roberson SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RW, &lowmem_period, 0,
204c9612b2dSJeff Roberson 	"Low memory callback period");
205c9612b2dSJeff Roberson 
20638efa82bSJohn Dyson #if defined(NO_SWAPPING)
207ceb0cf87SJohn Dyson SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
2086bd9cb1cSTom Rhodes 	CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout");
209ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
2106bd9cb1cSTom Rhodes 	CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
21138efa82bSJohn Dyson #else
212ceb0cf87SJohn Dyson SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
213b0359e2cSPeter Wemm 	CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
214ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
215b0359e2cSPeter Wemm 	CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
21638efa82bSJohn Dyson #endif
21726f9a767SRodney W. Grimes 
218ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
219b0359e2cSPeter Wemm 	CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
22012ac6a1dSJohn Dyson 
221ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
222b0359e2cSPeter Wemm 	CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
22312ac6a1dSJohn Dyson 
22423b59018SMatthew Dillon static int pageout_lock_miss;
22523b59018SMatthew Dillon SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
22623b59018SMatthew Dillon 	CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
22723b59018SMatthew Dillon 
22876386c7eSKonstantin Belousov SYSCTL_INT(_vm, OID_AUTO, pageout_oom_seq,
22976386c7eSKonstantin Belousov 	CTLFLAG_RW, &vm_pageout_oom_seq, 0,
23076386c7eSKonstantin Belousov 	"back-to-back calls to oom detector to start OOM");
23176386c7eSKonstantin Belousov 
232ffc82b0aSJohn Dyson #define VM_PAGEOUT_PAGE_COUNT 16
233bbc0ec52SDavid Greenman int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
234df8bae1dSRodney W. Grimes 
235c3cb3e12SDavid Greenman int vm_page_max_wired;		/* XXX max # of wired pages system-wide */
2365dfc2870SAlan Cox SYSCTL_INT(_vm, OID_AUTO, max_wired,
2375dfc2870SAlan Cox 	CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
238df8bae1dSRodney W. Grimes 
23985eeca35SAlan Cox static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
240449c2e92SKonstantin Belousov static boolean_t vm_pageout_launder(struct vm_pagequeue *pq, int, vm_paddr_t,
241449c2e92SKonstantin Belousov     vm_paddr_t);
24238efa82bSJohn Dyson #if !defined(NO_SWAPPING)
243ecf6279fSAlan Cox static void vm_pageout_map_deactivate_pages(vm_map_t, long);
244ecf6279fSAlan Cox static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
24597824da3SAlan Cox static void vm_req_vmdaemon(int req);
24638efa82bSJohn Dyson #endif
24785eeca35SAlan Cox static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
248cd41fc12SDavid Greenman 
249a8229fa3SAlan Cox /*
250a8229fa3SAlan Cox  * Initialize a dummy page for marking the caller's place in the specified
251a8229fa3SAlan Cox  * paging queue.  In principle, this function only needs to set the flag
252c7aebda8SAttilio Rao  * PG_MARKER.  Nonetheless, it wirte busies and initializes the hold count
253c7aebda8SAttilio Rao  * to one as safety precautions.
254a8229fa3SAlan Cox  */
2558c616246SKonstantin Belousov static void
2568c616246SKonstantin Belousov vm_pageout_init_marker(vm_page_t marker, u_short queue)
2578c616246SKonstantin Belousov {
2588c616246SKonstantin Belousov 
2598c616246SKonstantin Belousov 	bzero(marker, sizeof(*marker));
260a8229fa3SAlan Cox 	marker->flags = PG_MARKER;
261c7aebda8SAttilio Rao 	marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
2628c616246SKonstantin Belousov 	marker->queue = queue;
263a8229fa3SAlan Cox 	marker->hold_count = 1;
2648c616246SKonstantin Belousov }
2658c616246SKonstantin Belousov 
26626f9a767SRodney W. Grimes /*
2678dbca793STor Egge  * vm_pageout_fallback_object_lock:
2688dbca793STor Egge  *
26989f6b863SAttilio Rao  * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
2708dbca793STor Egge  * known to have failed and page queue must be either PQ_ACTIVE or
2718dbca793STor Egge  * PQ_INACTIVE.  To avoid lock order violation, unlock the page queues
2728dbca793STor Egge  * while locking the vm object.  Use marker page to detect page queue
2738dbca793STor Egge  * changes and maintain notion of next page on page queue.  Return
2748dbca793STor Egge  * TRUE if no changes were detected, FALSE otherwise.  vm object is
2758dbca793STor Egge  * locked on return.
2768dbca793STor Egge  *
2778dbca793STor Egge  * This function depends on both the lock portion of struct vm_object
2788dbca793STor Egge  * and normal struct vm_page being type stable.
2798dbca793STor Egge  */
28085eeca35SAlan Cox static boolean_t
2818dbca793STor Egge vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
2828dbca793STor Egge {
2838dbca793STor Egge 	struct vm_page marker;
2848d220203SAlan Cox 	struct vm_pagequeue *pq;
2858dbca793STor Egge 	boolean_t unchanged;
2868dbca793STor Egge 	u_short queue;
2878dbca793STor Egge 	vm_object_t object;
2888dbca793STor Egge 
2898dbca793STor Egge 	queue = m->queue;
2908c616246SKonstantin Belousov 	vm_pageout_init_marker(&marker, queue);
291449c2e92SKonstantin Belousov 	pq = vm_page_pagequeue(m);
2928dbca793STor Egge 	object = m->object;
2938dbca793STor Egge 
294c325e866SKonstantin Belousov 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
2958d220203SAlan Cox 	vm_pagequeue_unlock(pq);
2962965a453SKip Macy 	vm_page_unlock(m);
29789f6b863SAttilio Rao 	VM_OBJECT_WLOCK(object);
2982965a453SKip Macy 	vm_page_lock(m);
2998d220203SAlan Cox 	vm_pagequeue_lock(pq);
3008dbca793STor Egge 
30169b8585eSKonstantin Belousov 	/*
30269b8585eSKonstantin Belousov 	 * The page's object might have changed, and/or the page might
30369b8585eSKonstantin Belousov 	 * have moved from its original position in the queue.  If the
30469b8585eSKonstantin Belousov 	 * page's object has changed, then the caller should abandon
30569b8585eSKonstantin Belousov 	 * processing the page because the wrong object lock was
30669b8585eSKonstantin Belousov 	 * acquired.  Use the marker's plinks.q, not the page's, to
30769b8585eSKonstantin Belousov 	 * determine if the page has been moved.  The state of the
30869b8585eSKonstantin Belousov 	 * page's plinks.q can be indeterminate; whereas, the marker's
30969b8585eSKonstantin Belousov 	 * plinks.q must be valid.
31069b8585eSKonstantin Belousov 	 */
311c325e866SKonstantin Belousov 	*next = TAILQ_NEXT(&marker, plinks.q);
31269b8585eSKonstantin Belousov 	unchanged = m->object == object &&
31369b8585eSKonstantin Belousov 	    m == TAILQ_PREV(&marker, pglist, plinks.q);
31469b8585eSKonstantin Belousov 	KASSERT(!unchanged || m->queue == queue,
31569b8585eSKonstantin Belousov 	    ("page %p queue %d %d", m, queue, m->queue));
316c325e866SKonstantin Belousov 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
3178dbca793STor Egge 	return (unchanged);
3188dbca793STor Egge }
3198dbca793STor Egge 
3208dbca793STor Egge /*
3218c616246SKonstantin Belousov  * Lock the page while holding the page queue lock.  Use marker page
3228c616246SKonstantin Belousov  * to detect page queue changes and maintain notion of next page on
3238c616246SKonstantin Belousov  * page queue.  Return TRUE if no changes were detected, FALSE
3248c616246SKonstantin Belousov  * otherwise.  The page is locked on return. The page queue lock might
3258c616246SKonstantin Belousov  * be dropped and reacquired.
3268c616246SKonstantin Belousov  *
3278c616246SKonstantin Belousov  * This function depends on normal struct vm_page being type stable.
3288c616246SKonstantin Belousov  */
32985eeca35SAlan Cox static boolean_t
3308c616246SKonstantin Belousov vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
3318c616246SKonstantin Belousov {
3328c616246SKonstantin Belousov 	struct vm_page marker;
3338d220203SAlan Cox 	struct vm_pagequeue *pq;
3348c616246SKonstantin Belousov 	boolean_t unchanged;
3358c616246SKonstantin Belousov 	u_short queue;
3368c616246SKonstantin Belousov 
3378c616246SKonstantin Belousov 	vm_page_lock_assert(m, MA_NOTOWNED);
3388c616246SKonstantin Belousov 	if (vm_page_trylock(m))
3398c616246SKonstantin Belousov 		return (TRUE);
3408c616246SKonstantin Belousov 
3418c616246SKonstantin Belousov 	queue = m->queue;
3428c616246SKonstantin Belousov 	vm_pageout_init_marker(&marker, queue);
343449c2e92SKonstantin Belousov 	pq = vm_page_pagequeue(m);
3448c616246SKonstantin Belousov 
345c325e866SKonstantin Belousov 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
3468d220203SAlan Cox 	vm_pagequeue_unlock(pq);
3478c616246SKonstantin Belousov 	vm_page_lock(m);
3488d220203SAlan Cox 	vm_pagequeue_lock(pq);
3498c616246SKonstantin Belousov 
3508c616246SKonstantin Belousov 	/* Page queue might have changed. */
351c325e866SKonstantin Belousov 	*next = TAILQ_NEXT(&marker, plinks.q);
35269b8585eSKonstantin Belousov 	unchanged = m == TAILQ_PREV(&marker, pglist, plinks.q);
35369b8585eSKonstantin Belousov 	KASSERT(!unchanged || m->queue == queue,
35469b8585eSKonstantin Belousov 	    ("page %p queue %d %d", m, queue, m->queue));
355c325e866SKonstantin Belousov 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
3568c616246SKonstantin Belousov 	return (unchanged);
3578c616246SKonstantin Belousov }
3588c616246SKonstantin Belousov 
3598c616246SKonstantin Belousov /*
36026f9a767SRodney W. Grimes  * vm_pageout_clean:
36124a1cce3SDavid Greenman  *
3620d94caffSDavid Greenman  * Clean the page and remove it from the laundry.
36326f9a767SRodney W. Grimes  *
3640d94caffSDavid Greenman  * We set the busy bit to cause potential page faults on this page to
3651c7c3c6aSMatthew Dillon  * block.  Note the careful timing, however, the busy bit isn't set till
3661c7c3c6aSMatthew Dillon  * late and we cannot do anything that will mess with the page.
36726f9a767SRodney W. Grimes  */
3683af76890SPoul-Henning Kamp static int
36934d8b7eaSJeff Roberson vm_pageout_cluster(vm_page_t m)
37024a1cce3SDavid Greenman {
37154d92145SMatthew Dillon 	vm_object_t object;
37291b4f427SAlan Cox 	vm_page_t mc[2*vm_pageout_page_count], pb, ps;
3733562af12SAlan Cox 	int pageout_count;
37490ecac61SMatthew Dillon 	int ib, is, page_base;
375a316d390SJohn Dyson 	vm_pindex_t pindex = m->pindex;
37626f9a767SRodney W. Grimes 
37795976f3fSAlan Cox 	vm_page_lock_assert(m, MA_OWNED);
37817f6a17bSAlan Cox 	object = m->object;
37989f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
3800cddd8f0SMatthew Dillon 
38126f9a767SRodney W. Grimes 	/*
3821c7c3c6aSMatthew Dillon 	 * It doesn't cost us anything to pageout OBJT_DEFAULT or OBJT_SWAP
3831c7c3c6aSMatthew Dillon 	 * with the new swapper, but we could have serious problems paging
3841c7c3c6aSMatthew Dillon 	 * out other object types if there is insufficient memory.
3851c7c3c6aSMatthew Dillon 	 *
3861c7c3c6aSMatthew Dillon 	 * Unfortunately, checking free memory here is far too late, so the
3871c7c3c6aSMatthew Dillon 	 * check has been moved up a procedural level.
3881c7c3c6aSMatthew Dillon 	 */
3891c7c3c6aSMatthew Dillon 
39024a1cce3SDavid Greenman 	/*
3919e897b1bSAlan Cox 	 * Can't clean the page if it's busy or held.
39224a1cce3SDavid Greenman 	 */
393c7aebda8SAttilio Rao 	vm_page_assert_unbusied(m);
39495976f3fSAlan Cox 	KASSERT(m->hold_count == 0, ("vm_pageout_clean: page %p is held", m));
39517f6a17bSAlan Cox 	vm_page_unlock(m);
3960d94caffSDavid Greenman 
39791b4f427SAlan Cox 	mc[vm_pageout_page_count] = pb = ps = m;
39826f9a767SRodney W. Grimes 	pageout_count = 1;
399f35329acSJohn Dyson 	page_base = vm_pageout_page_count;
40090ecac61SMatthew Dillon 	ib = 1;
40190ecac61SMatthew Dillon 	is = 1;
40290ecac61SMatthew Dillon 
40324a1cce3SDavid Greenman 	/*
40424a1cce3SDavid Greenman 	 * Scan object for clusterable pages.
40524a1cce3SDavid Greenman 	 *
40624a1cce3SDavid Greenman 	 * We can cluster ONLY if: ->> the page is NOT
40724a1cce3SDavid Greenman 	 * clean, wired, busy, held, or mapped into a
40824a1cce3SDavid Greenman 	 * buffer, and one of the following:
40924a1cce3SDavid Greenman 	 * 1) The page is inactive, or a seldom used
41024a1cce3SDavid Greenman 	 *    active page.
41124a1cce3SDavid Greenman 	 * -or-
41224a1cce3SDavid Greenman 	 * 2) we force the issue.
41390ecac61SMatthew Dillon 	 *
41490ecac61SMatthew Dillon 	 * During heavy mmap/modification loads the pageout
41590ecac61SMatthew Dillon 	 * daemon can really fragment the underlying file
41690ecac61SMatthew Dillon 	 * due to flushing pages out of order and not trying
41790ecac61SMatthew Dillon 	 * align the clusters (which leave sporatic out-of-order
41890ecac61SMatthew Dillon 	 * holes).  To solve this problem we do the reverse scan
41990ecac61SMatthew Dillon 	 * first and attempt to align our cluster, then do a
42090ecac61SMatthew Dillon 	 * forward scan if room remains.
42124a1cce3SDavid Greenman 	 */
42290ecac61SMatthew Dillon more:
42390ecac61SMatthew Dillon 	while (ib && pageout_count < vm_pageout_page_count) {
42424a1cce3SDavid Greenman 		vm_page_t p;
425f6b04d2bSDavid Greenman 
42690ecac61SMatthew Dillon 		if (ib > pindex) {
42790ecac61SMatthew Dillon 			ib = 0;
42890ecac61SMatthew Dillon 			break;
429f6b04d2bSDavid Greenman 		}
43090ecac61SMatthew Dillon 
431c7aebda8SAttilio Rao 		if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
43290ecac61SMatthew Dillon 			ib = 0;
43390ecac61SMatthew Dillon 			break;
434f6b04d2bSDavid Greenman 		}
43524a1cce3SDavid Greenman 		vm_page_test_dirty(p);
436eb5d3969SAlan Cox 		if (p->dirty == 0) {
437eb5d3969SAlan Cox 			ib = 0;
438eb5d3969SAlan Cox 			break;
439eb5d3969SAlan Cox 		}
440eb5d3969SAlan Cox 		vm_page_lock(p);
441eb5d3969SAlan Cox 		if (p->queue != PQ_INACTIVE ||
44257601bcbSMatthew Dillon 		    p->hold_count != 0) {	/* may be undergoing I/O */
4432965a453SKip Macy 			vm_page_unlock(p);
44490ecac61SMatthew Dillon 			ib = 0;
44524a1cce3SDavid Greenman 			break;
446f6b04d2bSDavid Greenman 		}
4472965a453SKip Macy 		vm_page_unlock(p);
44891b4f427SAlan Cox 		mc[--page_base] = pb = p;
44990ecac61SMatthew Dillon 		++pageout_count;
45090ecac61SMatthew Dillon 		++ib;
45124a1cce3SDavid Greenman 		/*
45290ecac61SMatthew Dillon 		 * alignment boundry, stop here and switch directions.  Do
45390ecac61SMatthew Dillon 		 * not clear ib.
45424a1cce3SDavid Greenman 		 */
45590ecac61SMatthew Dillon 		if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
45690ecac61SMatthew Dillon 			break;
45724a1cce3SDavid Greenman 	}
45890ecac61SMatthew Dillon 
45990ecac61SMatthew Dillon 	while (pageout_count < vm_pageout_page_count &&
46090ecac61SMatthew Dillon 	    pindex + is < object->size) {
46190ecac61SMatthew Dillon 		vm_page_t p;
46290ecac61SMatthew Dillon 
463c7aebda8SAttilio Rao 		if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
46490ecac61SMatthew Dillon 			break;
46524a1cce3SDavid Greenman 		vm_page_test_dirty(p);
466eb5d3969SAlan Cox 		if (p->dirty == 0)
467eb5d3969SAlan Cox 			break;
468eb5d3969SAlan Cox 		vm_page_lock(p);
469eb5d3969SAlan Cox 		if (p->queue != PQ_INACTIVE ||
47057601bcbSMatthew Dillon 		    p->hold_count != 0) {	/* may be undergoing I/O */
4712965a453SKip Macy 			vm_page_unlock(p);
47224a1cce3SDavid Greenman 			break;
47324a1cce3SDavid Greenman 		}
4742965a453SKip Macy 		vm_page_unlock(p);
47591b4f427SAlan Cox 		mc[page_base + pageout_count] = ps = p;
47690ecac61SMatthew Dillon 		++pageout_count;
47790ecac61SMatthew Dillon 		++is;
47824a1cce3SDavid Greenman 	}
47990ecac61SMatthew Dillon 
48090ecac61SMatthew Dillon 	/*
48190ecac61SMatthew Dillon 	 * If we exhausted our forward scan, continue with the reverse scan
48290ecac61SMatthew Dillon 	 * when possible, even past a page boundry.  This catches boundry
48390ecac61SMatthew Dillon 	 * conditions.
48490ecac61SMatthew Dillon 	 */
48590ecac61SMatthew Dillon 	if (ib && pageout_count < vm_pageout_page_count)
48690ecac61SMatthew Dillon 		goto more;
487f6b04d2bSDavid Greenman 
48867bf6868SJohn Dyson 	/*
48967bf6868SJohn Dyson 	 * we allow reads during pageouts...
49067bf6868SJohn Dyson 	 */
491126d6082SKonstantin Belousov 	return (vm_pageout_flush(&mc[page_base], pageout_count, 0, 0, NULL,
492126d6082SKonstantin Belousov 	    NULL));
493aef922f5SJohn Dyson }
494aef922f5SJohn Dyson 
4951c7c3c6aSMatthew Dillon /*
4961c7c3c6aSMatthew Dillon  * vm_pageout_flush() - launder the given pages
4971c7c3c6aSMatthew Dillon  *
4981c7c3c6aSMatthew Dillon  *	The given pages are laundered.  Note that we setup for the start of
4991c7c3c6aSMatthew Dillon  *	I/O ( i.e. busy the page ), mark it read-only, and bump the object
5001c7c3c6aSMatthew Dillon  *	reference count all in here rather then in the parent.  If we want
5011c7c3c6aSMatthew Dillon  *	the parent to do more sophisticated things we may have to change
5021c7c3c6aSMatthew Dillon  *	the ordering.
5031e8a675cSKonstantin Belousov  *
5041e8a675cSKonstantin Belousov  *	Returned runlen is the count of pages between mreq and first
5051e8a675cSKonstantin Belousov  *	page after mreq with status VM_PAGER_AGAIN.
506126d6082SKonstantin Belousov  *	*eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
507126d6082SKonstantin Belousov  *	for any page in runlen set.
5081c7c3c6aSMatthew Dillon  */
509aef922f5SJohn Dyson int
510126d6082SKonstantin Belousov vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
511126d6082SKonstantin Belousov     boolean_t *eio)
512aef922f5SJohn Dyson {
5132e3b314dSAlan Cox 	vm_object_t object = mc[0]->object;
514aef922f5SJohn Dyson 	int pageout_status[count];
51595461b45SJohn Dyson 	int numpagedout = 0;
5161e8a675cSKonstantin Belousov 	int i, runlen;
517aef922f5SJohn Dyson 
51889f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
5197bec141bSKip Macy 
5201c7c3c6aSMatthew Dillon 	/*
5211c7c3c6aSMatthew Dillon 	 * Initiate I/O.  Bump the vm_page_t->busy counter and
5221c7c3c6aSMatthew Dillon 	 * mark the pages read-only.
5231c7c3c6aSMatthew Dillon 	 *
5241c7c3c6aSMatthew Dillon 	 * We do not have to fixup the clean/dirty bits here... we can
5251c7c3c6aSMatthew Dillon 	 * allow the pager to do it after the I/O completes.
52602fa91d3SMatthew Dillon 	 *
52702fa91d3SMatthew Dillon 	 * NOTE! mc[i]->dirty may be partial or fragmented due to an
52802fa91d3SMatthew Dillon 	 * edge case with file fragments.
5291c7c3c6aSMatthew Dillon 	 */
5308f9110f6SJohn Dyson 	for (i = 0; i < count; i++) {
5317a935082SAlan Cox 		KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
5327a935082SAlan Cox 		    ("vm_pageout_flush: partially invalid page %p index %d/%d",
5337a935082SAlan Cox 			mc[i], i, count));
534c7aebda8SAttilio Rao 		vm_page_sbusy(mc[i]);
53578985e42SAlan Cox 		pmap_remove_write(mc[i]);
5362965a453SKip Macy 	}
537d474eaaaSDoug Rabson 	vm_object_pip_add(object, count);
538aef922f5SJohn Dyson 
539d076fbeaSAlan Cox 	vm_pager_put_pages(object, mc, count, flags, pageout_status);
54026f9a767SRodney W. Grimes 
5411e8a675cSKonstantin Belousov 	runlen = count - mreq;
542126d6082SKonstantin Belousov 	if (eio != NULL)
543126d6082SKonstantin Belousov 		*eio = FALSE;
544aef922f5SJohn Dyson 	for (i = 0; i < count; i++) {
545aef922f5SJohn Dyson 		vm_page_t mt = mc[i];
54624a1cce3SDavid Greenman 
5474cd45723SAlan Cox 		KASSERT(pageout_status[i] == VM_PAGER_PEND ||
5486031c68dSAlan Cox 		    !pmap_page_is_write_mapped(mt),
5499ea8d1a6SAlan Cox 		    ("vm_pageout_flush: page %p is not write protected", mt));
55026f9a767SRodney W. Grimes 		switch (pageout_status[i]) {
55126f9a767SRodney W. Grimes 		case VM_PAGER_OK:
55226f9a767SRodney W. Grimes 		case VM_PAGER_PEND:
55395461b45SJohn Dyson 			numpagedout++;
55426f9a767SRodney W. Grimes 			break;
55526f9a767SRodney W. Grimes 		case VM_PAGER_BAD:
55626f9a767SRodney W. Grimes 			/*
5570d94caffSDavid Greenman 			 * Page outside of range of object. Right now we
5580d94caffSDavid Greenman 			 * essentially lose the changes by pretending it
5590d94caffSDavid Greenman 			 * worked.
56026f9a767SRodney W. Grimes 			 */
56190ecac61SMatthew Dillon 			vm_page_undirty(mt);
56226f9a767SRodney W. Grimes 			break;
56326f9a767SRodney W. Grimes 		case VM_PAGER_ERROR:
56426f9a767SRodney W. Grimes 		case VM_PAGER_FAIL:
56526f9a767SRodney W. Grimes 			/*
5660d94caffSDavid Greenman 			 * If page couldn't be paged out, then reactivate the
5670d94caffSDavid Greenman 			 * page so it doesn't clog the inactive list.  (We
5680d94caffSDavid Greenman 			 * will try paging out it again later).
56926f9a767SRodney W. Grimes 			 */
5703c4a2440SAlan Cox 			vm_page_lock(mt);
57124a1cce3SDavid Greenman 			vm_page_activate(mt);
5723c4a2440SAlan Cox 			vm_page_unlock(mt);
573126d6082SKonstantin Belousov 			if (eio != NULL && i >= mreq && i - mreq < runlen)
574126d6082SKonstantin Belousov 				*eio = TRUE;
57526f9a767SRodney W. Grimes 			break;
57626f9a767SRodney W. Grimes 		case VM_PAGER_AGAIN:
5771e8a675cSKonstantin Belousov 			if (i >= mreq && i - mreq < runlen)
5781e8a675cSKonstantin Belousov 				runlen = i - mreq;
57926f9a767SRodney W. Grimes 			break;
58026f9a767SRodney W. Grimes 		}
58126f9a767SRodney W. Grimes 
58226f9a767SRodney W. Grimes 		/*
5830d94caffSDavid Greenman 		 * If the operation is still going, leave the page busy to
5840d94caffSDavid Greenman 		 * block all other accesses. Also, leave the paging in
5850d94caffSDavid Greenman 		 * progress indicator set so that we don't attempt an object
5860d94caffSDavid Greenman 		 * collapse.
58726f9a767SRodney W. Grimes 		 */
58826f9a767SRodney W. Grimes 		if (pageout_status[i] != VM_PAGER_PEND) {
589f919ebdeSDavid Greenman 			vm_object_pip_wakeup(object);
590c7aebda8SAttilio Rao 			vm_page_sunbusy(mt);
5913c4a2440SAlan Cox 		}
5923c4a2440SAlan Cox 	}
5931e8a675cSKonstantin Belousov 	if (prunlen != NULL)
5941e8a675cSKonstantin Belousov 		*prunlen = runlen;
5953c4a2440SAlan Cox 	return (numpagedout);
59626f9a767SRodney W. Grimes }
59726f9a767SRodney W. Grimes 
59885eeca35SAlan Cox static boolean_t
599449c2e92SKonstantin Belousov vm_pageout_launder(struct vm_pagequeue *pq, int tries, vm_paddr_t low,
600449c2e92SKonstantin Belousov     vm_paddr_t high)
60185eeca35SAlan Cox {
60285eeca35SAlan Cox 	struct mount *mp;
60385eeca35SAlan Cox 	struct vnode *vp;
60485eeca35SAlan Cox 	vm_object_t object;
60585eeca35SAlan Cox 	vm_paddr_t pa;
60685eeca35SAlan Cox 	vm_page_t m, m_tmp, next;
6071bd7d0b7SKonstantin Belousov 	int lockmode;
60885eeca35SAlan Cox 
6098d220203SAlan Cox 	vm_pagequeue_lock(pq);
610c325e866SKonstantin Belousov 	TAILQ_FOREACH_SAFE(m, &pq->pq_pl, plinks.q, next) {
61185eeca35SAlan Cox 		if ((m->flags & PG_MARKER) != 0)
61285eeca35SAlan Cox 			continue;
61385eeca35SAlan Cox 		pa = VM_PAGE_TO_PHYS(m);
61485eeca35SAlan Cox 		if (pa < low || pa + PAGE_SIZE > high)
61585eeca35SAlan Cox 			continue;
61685eeca35SAlan Cox 		if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
61785eeca35SAlan Cox 			vm_page_unlock(m);
61885eeca35SAlan Cox 			continue;
61985eeca35SAlan Cox 		}
62085eeca35SAlan Cox 		object = m->object;
62189f6b863SAttilio Rao 		if ((!VM_OBJECT_TRYWLOCK(object) &&
62285eeca35SAlan Cox 		    (!vm_pageout_fallback_object_lock(m, &next) ||
623c7aebda8SAttilio Rao 		    m->hold_count != 0)) || vm_page_busied(m)) {
62485eeca35SAlan Cox 			vm_page_unlock(m);
62589f6b863SAttilio Rao 			VM_OBJECT_WUNLOCK(object);
62685eeca35SAlan Cox 			continue;
62785eeca35SAlan Cox 		}
62885eeca35SAlan Cox 		vm_page_test_dirty(m);
6299fc4739dSAlan Cox 		if (m->dirty == 0 && object->ref_count != 0)
63085eeca35SAlan Cox 			pmap_remove_all(m);
63185eeca35SAlan Cox 		if (m->dirty != 0) {
63285eeca35SAlan Cox 			vm_page_unlock(m);
63385eeca35SAlan Cox 			if (tries == 0 || (object->flags & OBJ_DEAD) != 0) {
63489f6b863SAttilio Rao 				VM_OBJECT_WUNLOCK(object);
63585eeca35SAlan Cox 				continue;
63685eeca35SAlan Cox 			}
63785eeca35SAlan Cox 			if (object->type == OBJT_VNODE) {
6388d220203SAlan Cox 				vm_pagequeue_unlock(pq);
63985eeca35SAlan Cox 				vp = object->handle;
64085eeca35SAlan Cox 				vm_object_reference_locked(object);
64189f6b863SAttilio Rao 				VM_OBJECT_WUNLOCK(object);
64285eeca35SAlan Cox 				(void)vn_start_write(vp, &mp, V_WAIT);
6431bd7d0b7SKonstantin Belousov 				lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
6441bd7d0b7SKonstantin Belousov 				    LK_SHARED : LK_EXCLUSIVE;
6451bd7d0b7SKonstantin Belousov 				vn_lock(vp, lockmode | LK_RETRY);
64689f6b863SAttilio Rao 				VM_OBJECT_WLOCK(object);
64785eeca35SAlan Cox 				vm_object_page_clean(object, 0, 0, OBJPC_SYNC);
64889f6b863SAttilio Rao 				VM_OBJECT_WUNLOCK(object);
64985eeca35SAlan Cox 				VOP_UNLOCK(vp, 0);
65085eeca35SAlan Cox 				vm_object_deallocate(object);
65185eeca35SAlan Cox 				vn_finished_write(mp);
65285eeca35SAlan Cox 				return (TRUE);
65385eeca35SAlan Cox 			} else if (object->type == OBJT_SWAP ||
65485eeca35SAlan Cox 			    object->type == OBJT_DEFAULT) {
6558d220203SAlan Cox 				vm_pagequeue_unlock(pq);
65685eeca35SAlan Cox 				m_tmp = m;
65785eeca35SAlan Cox 				vm_pageout_flush(&m_tmp, 1, VM_PAGER_PUT_SYNC,
65885eeca35SAlan Cox 				    0, NULL, NULL);
65989f6b863SAttilio Rao 				VM_OBJECT_WUNLOCK(object);
66085eeca35SAlan Cox 				return (TRUE);
66185eeca35SAlan Cox 			}
66285eeca35SAlan Cox 		} else {
6638d220203SAlan Cox 			/*
6648d220203SAlan Cox 			 * Dequeue here to prevent lock recursion in
6658d220203SAlan Cox 			 * vm_page_cache().
6668d220203SAlan Cox 			 */
6678d220203SAlan Cox 			vm_page_dequeue_locked(m);
66885eeca35SAlan Cox 			vm_page_cache(m);
66985eeca35SAlan Cox 			vm_page_unlock(m);
67085eeca35SAlan Cox 		}
67189f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
67285eeca35SAlan Cox 	}
6738d220203SAlan Cox 	vm_pagequeue_unlock(pq);
67485eeca35SAlan Cox 	return (FALSE);
67585eeca35SAlan Cox }
67685eeca35SAlan Cox 
67785eeca35SAlan Cox /*
67885eeca35SAlan Cox  * Increase the number of cached pages.  The specified value, "tries",
67985eeca35SAlan Cox  * determines which categories of pages are cached:
68085eeca35SAlan Cox  *
68185eeca35SAlan Cox  *  0: All clean, inactive pages within the specified physical address range
68285eeca35SAlan Cox  *     are cached.  Will not sleep.
68385eeca35SAlan Cox  *  1: The vm_lowmem handlers are called.  All inactive pages within
68485eeca35SAlan Cox  *     the specified physical address range are cached.  May sleep.
68585eeca35SAlan Cox  *  2: The vm_lowmem handlers are called.  All inactive and active pages
68685eeca35SAlan Cox  *     within the specified physical address range are cached.  May sleep.
68785eeca35SAlan Cox  */
68885eeca35SAlan Cox void
68985eeca35SAlan Cox vm_pageout_grow_cache(int tries, vm_paddr_t low, vm_paddr_t high)
69085eeca35SAlan Cox {
691449c2e92SKonstantin Belousov 	int actl, actmax, inactl, inactmax, dom, initial_dom;
692449c2e92SKonstantin Belousov 	static int start_dom = 0;
69385eeca35SAlan Cox 
69485eeca35SAlan Cox 	if (tries > 0) {
69585eeca35SAlan Cox 		/*
69685eeca35SAlan Cox 		 * Decrease registered cache sizes.  The vm_lowmem handlers
69785eeca35SAlan Cox 		 * may acquire locks and/or sleep, so they can only be invoked
69885eeca35SAlan Cox 		 * when "tries" is greater than zero.
69985eeca35SAlan Cox 		 */
70014a0d74eSSteven Hartland 		SDT_PROBE0(vm, , , vm__lowmem_cache);
70185eeca35SAlan Cox 		EVENTHANDLER_INVOKE(vm_lowmem, 0);
70285eeca35SAlan Cox 
70385eeca35SAlan Cox 		/*
70485eeca35SAlan Cox 		 * We do this explicitly after the caches have been drained
70585eeca35SAlan Cox 		 * above.
70685eeca35SAlan Cox 		 */
70785eeca35SAlan Cox 		uma_reclaim();
70885eeca35SAlan Cox 	}
709449c2e92SKonstantin Belousov 
710449c2e92SKonstantin Belousov 	/*
711449c2e92SKonstantin Belousov 	 * Make the next scan start on the next domain.
712449c2e92SKonstantin Belousov 	 */
713449c2e92SKonstantin Belousov 	initial_dom = atomic_fetchadd_int(&start_dom, 1) % vm_ndomains;
714449c2e92SKonstantin Belousov 
71585eeca35SAlan Cox 	inactl = 0;
71644f1c916SBryan Drewery 	inactmax = vm_cnt.v_inactive_count;
71785eeca35SAlan Cox 	actl = 0;
71844f1c916SBryan Drewery 	actmax = tries < 2 ? 0 : vm_cnt.v_active_count;
719449c2e92SKonstantin Belousov 	dom = initial_dom;
720449c2e92SKonstantin Belousov 
721449c2e92SKonstantin Belousov 	/*
722449c2e92SKonstantin Belousov 	 * Scan domains in round-robin order, first inactive queues,
723449c2e92SKonstantin Belousov 	 * then active.  Since domain usually owns large physically
724449c2e92SKonstantin Belousov 	 * contiguous chunk of memory, it makes sense to completely
725449c2e92SKonstantin Belousov 	 * exhaust one domain before switching to next, while growing
726449c2e92SKonstantin Belousov 	 * the pool of contiguous physical pages.
727449c2e92SKonstantin Belousov 	 *
728449c2e92SKonstantin Belousov 	 * Do not even start launder a domain which cannot contain
729449c2e92SKonstantin Belousov 	 * the specified address range, as indicated by segments
730449c2e92SKonstantin Belousov 	 * constituting the domain.
731449c2e92SKonstantin Belousov 	 */
73285eeca35SAlan Cox again:
733449c2e92SKonstantin Belousov 	if (inactl < inactmax) {
734449c2e92SKonstantin Belousov 		if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
735449c2e92SKonstantin Belousov 		    low, high) &&
736449c2e92SKonstantin Belousov 		    vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_INACTIVE],
737449c2e92SKonstantin Belousov 		    tries, low, high)) {
73885eeca35SAlan Cox 			inactl++;
73985eeca35SAlan Cox 			goto again;
74085eeca35SAlan Cox 		}
741449c2e92SKonstantin Belousov 		if (++dom == vm_ndomains)
742449c2e92SKonstantin Belousov 			dom = 0;
743449c2e92SKonstantin Belousov 		if (dom != initial_dom)
744449c2e92SKonstantin Belousov 			goto again;
745449c2e92SKonstantin Belousov 	}
746449c2e92SKonstantin Belousov 	if (actl < actmax) {
747449c2e92SKonstantin Belousov 		if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
748449c2e92SKonstantin Belousov 		    low, high) &&
749449c2e92SKonstantin Belousov 		    vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_ACTIVE],
750449c2e92SKonstantin Belousov 		      tries, low, high)) {
75185eeca35SAlan Cox 			actl++;
75285eeca35SAlan Cox 			goto again;
75385eeca35SAlan Cox 		}
754449c2e92SKonstantin Belousov 		if (++dom == vm_ndomains)
755449c2e92SKonstantin Belousov 			dom = 0;
756449c2e92SKonstantin Belousov 		if (dom != initial_dom)
757449c2e92SKonstantin Belousov 			goto again;
758449c2e92SKonstantin Belousov 	}
75985eeca35SAlan Cox }
76085eeca35SAlan Cox 
76138efa82bSJohn Dyson #if !defined(NO_SWAPPING)
76226f9a767SRodney W. Grimes /*
76326f9a767SRodney W. Grimes  *	vm_pageout_object_deactivate_pages
76426f9a767SRodney W. Grimes  *
765ce186587SAlan Cox  *	Deactivate enough pages to satisfy the inactive target
766ce186587SAlan Cox  *	requirements.
76726f9a767SRodney W. Grimes  *
76826f9a767SRodney W. Grimes  *	The object and map must be locked.
76926f9a767SRodney W. Grimes  */
77038efa82bSJohn Dyson static void
771ce186587SAlan Cox vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
772ce186587SAlan Cox     long desired)
77326f9a767SRodney W. Grimes {
774ecf6279fSAlan Cox 	vm_object_t backing_object, object;
775ce186587SAlan Cox 	vm_page_t p;
776bb7858eaSJeff Roberson 	int act_delta, remove_mode;
77726f9a767SRodney W. Grimes 
778e23b0a19SAlan Cox 	VM_OBJECT_ASSERT_LOCKED(first_object);
77928634820SAlan Cox 	if ((first_object->flags & OBJ_FICTITIOUS) != 0)
78038efa82bSJohn Dyson 		return;
781ecf6279fSAlan Cox 	for (object = first_object;; object = backing_object) {
782ecf6279fSAlan Cox 		if (pmap_resident_count(pmap) <= desired)
783ecf6279fSAlan Cox 			goto unlock_return;
784e23b0a19SAlan Cox 		VM_OBJECT_ASSERT_LOCKED(object);
78528634820SAlan Cox 		if ((object->flags & OBJ_UNMANAGED) != 0 ||
78628634820SAlan Cox 		    object->paging_in_progress != 0)
787ecf6279fSAlan Cox 			goto unlock_return;
78826f9a767SRodney W. Grimes 
78985b1dc89SAlan Cox 		remove_mode = 0;
79038efa82bSJohn Dyson 		if (object->shadow_count > 1)
79138efa82bSJohn Dyson 			remove_mode = 1;
79226f9a767SRodney W. Grimes 		/*
793ce186587SAlan Cox 		 * Scan the object's entire memory queue.
79426f9a767SRodney W. Grimes 		 */
795ce186587SAlan Cox 		TAILQ_FOREACH(p, &object->memq, listq) {
796447fe2a4SAlan Cox 			if (pmap_resident_count(pmap) <= desired)
797447fe2a4SAlan Cox 				goto unlock_return;
798c7aebda8SAttilio Rao 			if (vm_page_busied(p))
799447fe2a4SAlan Cox 				continue;
800ce186587SAlan Cox 			PCPU_INC(cnt.v_pdpages);
8012965a453SKip Macy 			vm_page_lock(p);
802ce186587SAlan Cox 			if (p->wire_count != 0 || p->hold_count != 0 ||
803ecf6279fSAlan Cox 			    !pmap_page_exists_quick(pmap, p)) {
8042965a453SKip Macy 				vm_page_unlock(p);
8050d94caffSDavid Greenman 				continue;
8060d94caffSDavid Greenman 			}
807bb7858eaSJeff Roberson 			act_delta = pmap_ts_referenced(p);
8083407fefeSKonstantin Belousov 			if ((p->aflags & PGA_REFERENCED) != 0) {
809bb7858eaSJeff Roberson 				if (act_delta == 0)
810bb7858eaSJeff Roberson 					act_delta = 1;
8113407fefeSKonstantin Belousov 				vm_page_aflag_clear(p, PGA_REFERENCED);
812ef743ce6SJohn Dyson 			}
813bb7858eaSJeff Roberson 			if (p->queue != PQ_ACTIVE && act_delta != 0) {
814ef743ce6SJohn Dyson 				vm_page_activate(p);
815bb7858eaSJeff Roberson 				p->act_count += act_delta;
816c8c4b40cSJohn Dyson 			} else if (p->queue == PQ_ACTIVE) {
817bb7858eaSJeff Roberson 				if (act_delta == 0) {
818ce186587SAlan Cox 					p->act_count -= min(p->act_count,
819ce186587SAlan Cox 					    ACT_DECLINE);
82090776bd7SJeff Roberson 					if (!remove_mode && p->act_count == 0) {
8214fec79beSAlan Cox 						pmap_remove_all(p);
82226f9a767SRodney W. Grimes 						vm_page_deactivate(p);
8238d220203SAlan Cox 					} else
8248d220203SAlan Cox 						vm_page_requeue(p);
825c8c4b40cSJohn Dyson 				} else {
826eaf13dd7SJohn Dyson 					vm_page_activate(p);
827ce186587SAlan Cox 					if (p->act_count < ACT_MAX -
828ce186587SAlan Cox 					    ACT_ADVANCE)
82938efa82bSJohn Dyson 						p->act_count += ACT_ADVANCE;
8308d220203SAlan Cox 					vm_page_requeue(p);
831ce186587SAlan Cox 				}
832ce186587SAlan Cox 			} else if (p->queue == PQ_INACTIVE)
833ce186587SAlan Cox 				pmap_remove_all(p);
8342965a453SKip Macy 			vm_page_unlock(p);
83526f9a767SRodney W. Grimes 		}
836ecf6279fSAlan Cox 		if ((backing_object = object->backing_object) == NULL)
837ecf6279fSAlan Cox 			goto unlock_return;
838e23b0a19SAlan Cox 		VM_OBJECT_RLOCK(backing_object);
839ecf6279fSAlan Cox 		if (object != first_object)
840e23b0a19SAlan Cox 			VM_OBJECT_RUNLOCK(object);
84138efa82bSJohn Dyson 	}
842ecf6279fSAlan Cox unlock_return:
843ecf6279fSAlan Cox 	if (object != first_object)
844e23b0a19SAlan Cox 		VM_OBJECT_RUNLOCK(object);
84526f9a767SRodney W. Grimes }
84626f9a767SRodney W. Grimes 
84726f9a767SRodney W. Grimes /*
84826f9a767SRodney W. Grimes  * deactivate some number of pages in a map, try to do it fairly, but
84926f9a767SRodney W. Grimes  * that is really hard to do.
85026f9a767SRodney W. Grimes  */
851cd41fc12SDavid Greenman static void
85238efa82bSJohn Dyson vm_pageout_map_deactivate_pages(map, desired)
85326f9a767SRodney W. Grimes 	vm_map_t map;
854ecf6279fSAlan Cox 	long desired;
85526f9a767SRodney W. Grimes {
85626f9a767SRodney W. Grimes 	vm_map_entry_t tmpe;
85738efa82bSJohn Dyson 	vm_object_t obj, bigobj;
85830105b9eSTor Egge 	int nothingwired;
8590d94caffSDavid Greenman 
860d974f03cSAlan Cox 	if (!vm_map_trylock(map))
86126f9a767SRodney W. Grimes 		return;
86238efa82bSJohn Dyson 
86338efa82bSJohn Dyson 	bigobj = NULL;
86430105b9eSTor Egge 	nothingwired = TRUE;
86538efa82bSJohn Dyson 
86638efa82bSJohn Dyson 	/*
86738efa82bSJohn Dyson 	 * first, search out the biggest object, and try to free pages from
86838efa82bSJohn Dyson 	 * that.
86938efa82bSJohn Dyson 	 */
87026f9a767SRodney W. Grimes 	tmpe = map->header.next;
87138efa82bSJohn Dyson 	while (tmpe != &map->header) {
8729fdfe602SMatthew Dillon 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
87338efa82bSJohn Dyson 			obj = tmpe->object.vm_object;
874e23b0a19SAlan Cox 			if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
8750774dfb3SAlan Cox 				if (obj->shadow_count <= 1 &&
8760774dfb3SAlan Cox 				    (bigobj == NULL ||
8770774dfb3SAlan Cox 				     bigobj->resident_page_count < obj->resident_page_count)) {
8780774dfb3SAlan Cox 					if (bigobj != NULL)
879e23b0a19SAlan Cox 						VM_OBJECT_RUNLOCK(bigobj);
88038efa82bSJohn Dyson 					bigobj = obj;
8810774dfb3SAlan Cox 				} else
882e23b0a19SAlan Cox 					VM_OBJECT_RUNLOCK(obj);
88338efa82bSJohn Dyson 			}
88438efa82bSJohn Dyson 		}
88530105b9eSTor Egge 		if (tmpe->wired_count > 0)
88630105b9eSTor Egge 			nothingwired = FALSE;
88738efa82bSJohn Dyson 		tmpe = tmpe->next;
88838efa82bSJohn Dyson 	}
88938efa82bSJohn Dyson 
8900774dfb3SAlan Cox 	if (bigobj != NULL) {
891ecf6279fSAlan Cox 		vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
892e23b0a19SAlan Cox 		VM_OBJECT_RUNLOCK(bigobj);
8930774dfb3SAlan Cox 	}
89438efa82bSJohn Dyson 	/*
89538efa82bSJohn Dyson 	 * Next, hunt around for other pages to deactivate.  We actually
89638efa82bSJohn Dyson 	 * do this search sort of wrong -- .text first is not the best idea.
89738efa82bSJohn Dyson 	 */
89838efa82bSJohn Dyson 	tmpe = map->header.next;
89938efa82bSJohn Dyson 	while (tmpe != &map->header) {
900b1028ad1SLuoqi Chen 		if (pmap_resident_count(vm_map_pmap(map)) <= desired)
90138efa82bSJohn Dyson 			break;
9029fdfe602SMatthew Dillon 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
90338efa82bSJohn Dyson 			obj = tmpe->object.vm_object;
9040774dfb3SAlan Cox 			if (obj != NULL) {
905e23b0a19SAlan Cox 				VM_OBJECT_RLOCK(obj);
906ecf6279fSAlan Cox 				vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
907e23b0a19SAlan Cox 				VM_OBJECT_RUNLOCK(obj);
9080774dfb3SAlan Cox 			}
90938efa82bSJohn Dyson 		}
91026f9a767SRodney W. Grimes 		tmpe = tmpe->next;
91138857e7fSAlan Cox 	}
91238efa82bSJohn Dyson 
91338efa82bSJohn Dyson 	/*
91438efa82bSJohn Dyson 	 * Remove all mappings if a process is swapped out, this will free page
91538efa82bSJohn Dyson 	 * table pages.
91638efa82bSJohn Dyson 	 */
91738857e7fSAlan Cox 	if (desired == 0 && nothingwired) {
9188d01a3b2SNathan Whitehorn 		pmap_remove(vm_map_pmap(map), vm_map_min(map),
9198d01a3b2SNathan Whitehorn 		    vm_map_max(map));
92038857e7fSAlan Cox 	}
921938b0f5bSMarcel Moolenaar 
92238efa82bSJohn Dyson 	vm_map_unlock(map);
92326f9a767SRodney W. Grimes }
924a1287949SEivind Eklund #endif		/* !defined(NO_SWAPPING) */
925df8bae1dSRodney W. Grimes 
9261c7c3c6aSMatthew Dillon /*
92734d8b7eaSJeff Roberson  * Attempt to acquire all of the necessary locks to launder a page and
92834d8b7eaSJeff Roberson  * then call through the clustering layer to PUTPAGES.  Wait a short
92934d8b7eaSJeff Roberson  * time for a vnode lock.
93034d8b7eaSJeff Roberson  *
93134d8b7eaSJeff Roberson  * Requires the page and object lock on entry, releases both before return.
93234d8b7eaSJeff Roberson  * Returns 0 on success and an errno otherwise.
93334d8b7eaSJeff Roberson  */
93434d8b7eaSJeff Roberson static int
93534d8b7eaSJeff Roberson vm_pageout_clean(vm_page_t m)
93634d8b7eaSJeff Roberson {
93734d8b7eaSJeff Roberson 	struct vnode *vp;
93834d8b7eaSJeff Roberson 	struct mount *mp;
93934d8b7eaSJeff Roberson 	vm_object_t object;
94034d8b7eaSJeff Roberson 	vm_pindex_t pindex;
94134d8b7eaSJeff Roberson 	int error, lockmode;
94234d8b7eaSJeff Roberson 
94334d8b7eaSJeff Roberson 	vm_page_assert_locked(m);
94434d8b7eaSJeff Roberson 	object = m->object;
94534d8b7eaSJeff Roberson 	VM_OBJECT_ASSERT_WLOCKED(object);
94634d8b7eaSJeff Roberson 	error = 0;
94734d8b7eaSJeff Roberson 	vp = NULL;
94834d8b7eaSJeff Roberson 	mp = NULL;
94934d8b7eaSJeff Roberson 
95034d8b7eaSJeff Roberson 	/*
95134d8b7eaSJeff Roberson 	 * The object is already known NOT to be dead.   It
95234d8b7eaSJeff Roberson 	 * is possible for the vget() to block the whole
95334d8b7eaSJeff Roberson 	 * pageout daemon, but the new low-memory handling
95434d8b7eaSJeff Roberson 	 * code should prevent it.
95534d8b7eaSJeff Roberson 	 *
95634d8b7eaSJeff Roberson 	 * We can't wait forever for the vnode lock, we might
95734d8b7eaSJeff Roberson 	 * deadlock due to a vn_read() getting stuck in
95834d8b7eaSJeff Roberson 	 * vm_wait while holding this vnode.  We skip the
95934d8b7eaSJeff Roberson 	 * vnode if we can't get it in a reasonable amount
96034d8b7eaSJeff Roberson 	 * of time.
96134d8b7eaSJeff Roberson 	 */
96234d8b7eaSJeff Roberson 	if (object->type == OBJT_VNODE) {
96334d8b7eaSJeff Roberson 		vm_page_unlock(m);
96434d8b7eaSJeff Roberson 		vp = object->handle;
96534d8b7eaSJeff Roberson 		if (vp->v_type == VREG &&
96634d8b7eaSJeff Roberson 		    vn_start_write(vp, &mp, V_NOWAIT) != 0) {
96734d8b7eaSJeff Roberson 			mp = NULL;
96834d8b7eaSJeff Roberson 			error = EDEADLK;
96934d8b7eaSJeff Roberson 			goto unlock_all;
97034d8b7eaSJeff Roberson 		}
97134d8b7eaSJeff Roberson 		KASSERT(mp != NULL,
97234d8b7eaSJeff Roberson 		    ("vp %p with NULL v_mount", vp));
97334d8b7eaSJeff Roberson 		vm_object_reference_locked(object);
97434d8b7eaSJeff Roberson 		pindex = m->pindex;
97534d8b7eaSJeff Roberson 		VM_OBJECT_WUNLOCK(object);
97634d8b7eaSJeff Roberson 		lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
97734d8b7eaSJeff Roberson 		    LK_SHARED : LK_EXCLUSIVE;
97834d8b7eaSJeff Roberson 		if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
97934d8b7eaSJeff Roberson 			vp = NULL;
98034d8b7eaSJeff Roberson 			error = EDEADLK;
98134d8b7eaSJeff Roberson 			goto unlock_mp;
98234d8b7eaSJeff Roberson 		}
98334d8b7eaSJeff Roberson 		VM_OBJECT_WLOCK(object);
98434d8b7eaSJeff Roberson 		vm_page_lock(m);
98534d8b7eaSJeff Roberson 		/*
98634d8b7eaSJeff Roberson 		 * While the object and page were unlocked, the page
98734d8b7eaSJeff Roberson 		 * may have been:
98834d8b7eaSJeff Roberson 		 * (1) moved to a different queue,
98934d8b7eaSJeff Roberson 		 * (2) reallocated to a different object,
99034d8b7eaSJeff Roberson 		 * (3) reallocated to a different offset, or
99134d8b7eaSJeff Roberson 		 * (4) cleaned.
99234d8b7eaSJeff Roberson 		 */
99334d8b7eaSJeff Roberson 		if (m->queue != PQ_INACTIVE || m->object != object ||
99434d8b7eaSJeff Roberson 		    m->pindex != pindex || m->dirty == 0) {
99534d8b7eaSJeff Roberson 			vm_page_unlock(m);
99634d8b7eaSJeff Roberson 			error = ENXIO;
99734d8b7eaSJeff Roberson 			goto unlock_all;
99834d8b7eaSJeff Roberson 		}
99934d8b7eaSJeff Roberson 
100034d8b7eaSJeff Roberson 		/*
100134d8b7eaSJeff Roberson 		 * The page may have been busied or held while the object
100234d8b7eaSJeff Roberson 		 * and page locks were released.
100334d8b7eaSJeff Roberson 		 */
100434d8b7eaSJeff Roberson 		if (vm_page_busied(m) || m->hold_count != 0) {
100534d8b7eaSJeff Roberson 			vm_page_unlock(m);
100634d8b7eaSJeff Roberson 			error = EBUSY;
100734d8b7eaSJeff Roberson 			goto unlock_all;
100834d8b7eaSJeff Roberson 		}
100934d8b7eaSJeff Roberson 	}
101034d8b7eaSJeff Roberson 
101134d8b7eaSJeff Roberson 	/*
101234d8b7eaSJeff Roberson 	 * If a page is dirty, then it is either being washed
101334d8b7eaSJeff Roberson 	 * (but not yet cleaned) or it is still in the
101434d8b7eaSJeff Roberson 	 * laundry.  If it is still in the laundry, then we
101534d8b7eaSJeff Roberson 	 * start the cleaning operation.
101634d8b7eaSJeff Roberson 	 */
101734d8b7eaSJeff Roberson 	if (vm_pageout_cluster(m) == 0)
101834d8b7eaSJeff Roberson 		error = EIO;
101934d8b7eaSJeff Roberson 
102034d8b7eaSJeff Roberson unlock_all:
102134d8b7eaSJeff Roberson 	VM_OBJECT_WUNLOCK(object);
102234d8b7eaSJeff Roberson 
102334d8b7eaSJeff Roberson unlock_mp:
102434d8b7eaSJeff Roberson 	vm_page_lock_assert(m, MA_NOTOWNED);
102534d8b7eaSJeff Roberson 	if (mp != NULL) {
102634d8b7eaSJeff Roberson 		if (vp != NULL)
102734d8b7eaSJeff Roberson 			vput(vp);
102834d8b7eaSJeff Roberson 		vm_object_deallocate(object);
102934d8b7eaSJeff Roberson 		vn_finished_write(mp);
103034d8b7eaSJeff Roberson 	}
103134d8b7eaSJeff Roberson 
103234d8b7eaSJeff Roberson 	return (error);
103334d8b7eaSJeff Roberson }
103434d8b7eaSJeff Roberson 
103534d8b7eaSJeff Roberson /*
1036df8bae1dSRodney W. Grimes  *	vm_pageout_scan does the dirty work for the pageout daemon.
1037d9e23210SJeff Roberson  *
1038d9e23210SJeff Roberson  *	pass 0 - Update active LRU/deactivate pages
1039d9e23210SJeff Roberson  *	pass 1 - Move inactive to cache or free
1040d9e23210SJeff Roberson  *	pass 2 - Launder dirty pages
1041df8bae1dSRodney W. Grimes  */
10422b6b0df7SMatthew Dillon static void
1043449c2e92SKonstantin Belousov vm_pageout_scan(struct vm_domain *vmd, int pass)
1044df8bae1dSRodney W. Grimes {
1045502ba6e4SJohn Dyson 	vm_page_t m, next;
10468d220203SAlan Cox 	struct vm_pagequeue *pq;
1047df8bae1dSRodney W. Grimes 	vm_object_t object;
104822cf98d1SAlan Cox 	long min_scan;
104940aa80a7SAlan Cox 	int act_delta, addl_page_shortage, deficit, error, maxlaunder, maxscan;
105076386c7eSKonstantin Belousov 	int page_shortage, scan_tick, scanned, starting_page_shortage;
105176386c7eSKonstantin Belousov 	int vnodes_skipped;
105240aa80a7SAlan Cox 	boolean_t pageout_ok, queues_locked;
10530d94caffSDavid Greenman 
1054df8bae1dSRodney W. Grimes 	/*
1055d9e23210SJeff Roberson 	 * If we need to reclaim memory ask kernel caches to return
1056c9612b2dSJeff Roberson 	 * some.  We rate limit to avoid thrashing.
1057d9e23210SJeff Roberson 	 */
1058c9612b2dSJeff Roberson 	if (vmd == &vm_dom[0] && pass > 0 &&
1059a6bf3a9eSRyan Stone 	    (time_uptime - lowmem_uptime) >= lowmem_period) {
1060d9e23210SJeff Roberson 		/*
1061855a310fSJeff Roberson 		 * Decrease registered cache sizes.
1062855a310fSJeff Roberson 		 */
106314a0d74eSSteven Hartland 		SDT_PROBE0(vm, , , vm__lowmem_scan);
1064855a310fSJeff Roberson 		EVENTHANDLER_INVOKE(vm_lowmem, 0);
1065855a310fSJeff Roberson 		/*
1066d9e23210SJeff Roberson 		 * We do this explicitly after the caches have been
1067d9e23210SJeff Roberson 		 * drained above.
1068855a310fSJeff Roberson 		 */
1069855a310fSJeff Roberson 		uma_reclaim();
1070a6bf3a9eSRyan Stone 		lowmem_uptime = time_uptime;
1071d9e23210SJeff Roberson 	}
10725985940eSJohn Dyson 
1073311e34e2SKonstantin Belousov 	/*
107496240c89SEitan Adler 	 * The addl_page_shortage is the number of temporarily
1075311e34e2SKonstantin Belousov 	 * stuck pages in the inactive queue.  In other words, the
1076449c2e92SKonstantin Belousov 	 * number of pages from the inactive count that should be
1077311e34e2SKonstantin Belousov 	 * discounted in setting the target for the active queue scan.
1078311e34e2SKonstantin Belousov 	 */
10799099545aSAlan Cox 	addl_page_shortage = 0;
10809099545aSAlan Cox 
10811c7c3c6aSMatthew Dillon 	/*
10821c7c3c6aSMatthew Dillon 	 * Calculate the number of pages we want to either free or move
10832b6b0df7SMatthew Dillon 	 * to the cache.
10841c7c3c6aSMatthew Dillon 	 */
108560196cdaSAlan Cox 	if (pass > 0) {
108660196cdaSAlan Cox 		deficit = atomic_readandclear_int(&vm_pageout_deficit);
10879099545aSAlan Cox 		page_shortage = vm_paging_target() + deficit;
108860196cdaSAlan Cox 	} else
108960196cdaSAlan Cox 		page_shortage = deficit = 0;
109076386c7eSKonstantin Belousov 	starting_page_shortage = page_shortage;
10911c7c3c6aSMatthew Dillon 
1092936524aaSMatthew Dillon 	/*
10932b6b0df7SMatthew Dillon 	 * maxlaunder limits the number of dirty pages we flush per scan.
10942b6b0df7SMatthew Dillon 	 * For most systems a smaller value (16 or 32) is more robust under
10952b6b0df7SMatthew Dillon 	 * extreme memory and disk pressure because any unnecessary writes
10962b6b0df7SMatthew Dillon 	 * to disk can result in extreme performance degredation.  However,
10972b6b0df7SMatthew Dillon 	 * systems with excessive dirty pages (especially when MAP_NOSYNC is
10982b6b0df7SMatthew Dillon 	 * used) will die horribly with limited laundering.  If the pageout
10992b6b0df7SMatthew Dillon 	 * daemon cannot clean enough pages in the first pass, we let it go
11002b6b0df7SMatthew Dillon 	 * all out in succeeding passes.
11011c7c3c6aSMatthew Dillon 	 */
11022b6b0df7SMatthew Dillon 	if ((maxlaunder = vm_max_launder) <= 1)
11032b6b0df7SMatthew Dillon 		maxlaunder = 1;
1104d9e23210SJeff Roberson 	if (pass > 1)
11052b6b0df7SMatthew Dillon 		maxlaunder = 10000;
11068d220203SAlan Cox 
110740aa80a7SAlan Cox 	vnodes_skipped = 0;
110840aa80a7SAlan Cox 
11098d220203SAlan Cox 	/*
11108d220203SAlan Cox 	 * Start scanning the inactive queue for pages we can move to the
11118d220203SAlan Cox 	 * cache or free.  The scan will stop when the target is reached or
11128d220203SAlan Cox 	 * we have scanned the entire inactive queue.  Note that m->act_count
11138d220203SAlan Cox 	 * is not used to form decisions for the inactive queue, only for the
11148d220203SAlan Cox 	 * active queue.
11158d220203SAlan Cox 	 */
1116449c2e92SKonstantin Belousov 	pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
1117449c2e92SKonstantin Belousov 	maxscan = pq->pq_cnt;
11188d220203SAlan Cox 	vm_pagequeue_lock(pq);
11198d220203SAlan Cox 	queues_locked = TRUE;
11208d220203SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl);
11211c7c3c6aSMatthew Dillon 	     m != NULL && maxscan-- > 0 && page_shortage > 0;
1122e929c00dSKirk McKusick 	     m = next) {
11238d220203SAlan Cox 		vm_pagequeue_assert_locked(pq);
112448cc2fc7SKonstantin Belousov 		KASSERT(queues_locked, ("unlocked queues"));
1125d4961bcbSKonstantin Belousov 		KASSERT(m->queue == PQ_INACTIVE, ("Inactive queue %p", m));
1126df8bae1dSRodney W. Grimes 
11278d220203SAlan Cox 		PCPU_INC(cnt.v_pdpages);
1128c325e866SKonstantin Belousov 		next = TAILQ_NEXT(m, plinks.q);
1129df8bae1dSRodney W. Grimes 
1130936524aaSMatthew Dillon 		/*
1131936524aaSMatthew Dillon 		 * skip marker pages
1132936524aaSMatthew Dillon 		 */
1133936524aaSMatthew Dillon 		if (m->flags & PG_MARKER)
1134936524aaSMatthew Dillon 			continue;
1135936524aaSMatthew Dillon 
11367900f95dSKonstantin Belousov 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
11377900f95dSKonstantin Belousov 		    ("Fictitious page %p cannot be in inactive queue", m));
11387900f95dSKonstantin Belousov 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
11397900f95dSKonstantin Belousov 		    ("Unmanaged page %p cannot be in inactive queue", m));
11407900f95dSKonstantin Belousov 
11418c616246SKonstantin Belousov 		/*
1142311e34e2SKonstantin Belousov 		 * The page or object lock acquisitions fail if the
1143311e34e2SKonstantin Belousov 		 * page was removed from the queue or moved to a
1144311e34e2SKonstantin Belousov 		 * different position within the queue.  In either
1145311e34e2SKonstantin Belousov 		 * case, addl_page_shortage should not be incremented.
11468c616246SKonstantin Belousov 		 */
1147a3aeedabSAlan Cox 		if (!vm_pageout_page_lock(m, &next))
1148a3aeedabSAlan Cox 			goto unlock_page;
1149a3aeedabSAlan Cox 		else if (m->hold_count != 0) {
1150a3aeedabSAlan Cox 			/*
1151a3aeedabSAlan Cox 			 * Held pages are essentially stuck in the
1152a3aeedabSAlan Cox 			 * queue.  So, they ought to be discounted
1153a3aeedabSAlan Cox 			 * from the inactive count.  See the
1154a3aeedabSAlan Cox 			 * calculation of the page_shortage for the
1155a3aeedabSAlan Cox 			 * loop over the active queue below.
1156a3aeedabSAlan Cox 			 */
1157a3aeedabSAlan Cox 			addl_page_shortage++;
1158a3aeedabSAlan Cox 			goto unlock_page;
1159df8bae1dSRodney W. Grimes 		}
11609ee2165fSAlan Cox 		object = m->object;
1161a3aeedabSAlan Cox 		if (!VM_OBJECT_TRYWLOCK(object)) {
1162a3aeedabSAlan Cox 			if (!vm_pageout_fallback_object_lock(m, &next))
1163a3aeedabSAlan Cox 				goto unlock_object;
1164a3aeedabSAlan Cox 			else if (m->hold_count != 0) {
1165b182ec9eSJohn Dyson 				addl_page_shortage++;
1166a3aeedabSAlan Cox 				goto unlock_object;
1167a3aeedabSAlan Cox 			}
1168a3aeedabSAlan Cox 		}
1169a3aeedabSAlan Cox 		if (vm_page_busied(m)) {
1170a3aeedabSAlan Cox 			/*
1171a3aeedabSAlan Cox 			 * Don't mess with busy pages.  Leave them at
1172a3aeedabSAlan Cox 			 * the front of the queue.  Most likely, they
1173a3aeedabSAlan Cox 			 * are being paged out and will leave the
1174a3aeedabSAlan Cox 			 * queue shortly after the scan finishes.  So,
1175a3aeedabSAlan Cox 			 * they ought to be discounted from the
1176a3aeedabSAlan Cox 			 * inactive count.
1177a3aeedabSAlan Cox 			 */
1178a3aeedabSAlan Cox 			addl_page_shortage++;
1179a3aeedabSAlan Cox unlock_object:
1180a3aeedabSAlan Cox 			VM_OBJECT_WUNLOCK(object);
1181a3aeedabSAlan Cox unlock_page:
1182a3aeedabSAlan Cox 			vm_page_unlock(m);
118326f9a767SRodney W. Grimes 			continue;
118426f9a767SRodney W. Grimes 		}
1185a3aeedabSAlan Cox 		KASSERT(m->hold_count == 0, ("Held page %p", m));
1186bd7e5f99SJohn Dyson 
11877e006499SJohn Dyson 		/*
11888d220203SAlan Cox 		 * We unlock the inactive page queue, invalidating the
118948cc2fc7SKonstantin Belousov 		 * 'next' pointer.  Use our marker to remember our
119048cc2fc7SKonstantin Belousov 		 * place.
119148cc2fc7SKonstantin Belousov 		 */
1192c325e866SKonstantin Belousov 		TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
11938d220203SAlan Cox 		vm_pagequeue_unlock(pq);
119448cc2fc7SKonstantin Belousov 		queues_locked = FALSE;
119548cc2fc7SKonstantin Belousov 
119648cc2fc7SKonstantin Belousov 		/*
11978748f58cSKonstantin Belousov 		 * Invalid pages can be easily freed. They cannot be
11988748f58cSKonstantin Belousov 		 * mapped, vm_page_free() asserts this.
1199776f729cSKonstantin Belousov 		 */
12008748f58cSKonstantin Belousov 		if (m->valid == 0)
12018748f58cSKonstantin Belousov 			goto free_page;
1202776f729cSKonstantin Belousov 
1203776f729cSKonstantin Belousov 		/*
1204960810ccSAlan Cox 		 * If the page has been referenced and the object is not dead,
1205960810ccSAlan Cox 		 * reactivate or requeue the page depending on whether the
1206960810ccSAlan Cox 		 * object is mapped.
12077e006499SJohn Dyson 		 */
1208bb7858eaSJeff Roberson 		if ((m->aflags & PGA_REFERENCED) != 0) {
1209bb7858eaSJeff Roberson 			vm_page_aflag_clear(m, PGA_REFERENCED);
1210bb7858eaSJeff Roberson 			act_delta = 1;
121186fa2471SAlan Cox 		} else
121286fa2471SAlan Cox 			act_delta = 0;
1213bb7858eaSJeff Roberson 		if (object->ref_count != 0) {
1214bb7858eaSJeff Roberson 			act_delta += pmap_ts_referenced(m);
1215bb7858eaSJeff Roberson 		} else {
1216bb7858eaSJeff Roberson 			KASSERT(!pmap_page_is_mapped(m),
1217bb7858eaSJeff Roberson 			    ("vm_pageout_scan: page %p is mapped", m));
12182fe6e4d7SDavid Greenman 		}
1219bb7858eaSJeff Roberson 		if (act_delta != 0) {
122086fa2471SAlan Cox 			if (object->ref_count != 0) {
122126f9a767SRodney W. Grimes 				vm_page_activate(m);
1222960810ccSAlan Cox 
1223960810ccSAlan Cox 				/*
1224960810ccSAlan Cox 				 * Increase the activation count if the page
1225960810ccSAlan Cox 				 * was referenced while in the inactive queue.
1226960810ccSAlan Cox 				 * This makes it less likely that the page will
1227960810ccSAlan Cox 				 * be returned prematurely to the inactive
1228960810ccSAlan Cox 				 * queue.
1229960810ccSAlan Cox  				 */
1230bb7858eaSJeff Roberson 				m->act_count += act_delta + ACT_ADVANCE;
1231960810ccSAlan Cox 				goto drop_page;
123227a9fb2fSAlan Cox 			} else if ((object->flags & OBJ_DEAD) == 0)
123327a9fb2fSAlan Cox 				goto requeue_page;
1234960810ccSAlan Cox 		}
123567bf6868SJohn Dyson 
12367e006499SJohn Dyson 		/*
12379fc4739dSAlan Cox 		 * If the page appears to be clean at the machine-independent
12389fc4739dSAlan Cox 		 * layer, then remove all of its mappings from the pmap in
12399fc4739dSAlan Cox 		 * anticipation of placing it onto the cache queue.  If,
12409fc4739dSAlan Cox 		 * however, any of the page's mappings allow write access,
12419fc4739dSAlan Cox 		 * then the page may still be modified until the last of those
12429fc4739dSAlan Cox 		 * mappings are removed.
12437e006499SJohn Dyson 		 */
1244aa044135SAlan Cox 		if (object->ref_count != 0) {
12459fc4739dSAlan Cox 			vm_page_test_dirty(m);
1246aa044135SAlan Cox 			if (m->dirty == 0)
1247b78ddb0bSAlan Cox 				pmap_remove_all(m);
1248aa044135SAlan Cox 		}
1249dcbcd518SBruce Evans 
1250776f729cSKonstantin Belousov 		if (m->dirty == 0) {
12516989c456SAlan Cox 			/*
125278afdce6SAlan Cox 			 * Clean pages can be freed.
12536989c456SAlan Cox 			 */
12548748f58cSKonstantin Belousov free_page:
125578afdce6SAlan Cox 			vm_page_free(m);
125678afdce6SAlan Cox 			PCPU_INC(cnt.v_dfree);
12571c7c3c6aSMatthew Dillon 			--page_shortage;
1258960810ccSAlan Cox 		} else if ((object->flags & OBJ_DEAD) != 0) {
1259960810ccSAlan Cox 			/*
1260960810ccSAlan Cox 			 * Leave dirty pages from dead objects at the front of
1261960810ccSAlan Cox 			 * the queue.  They are being paged out and freed by
1262960810ccSAlan Cox 			 * the thread that destroyed the object.  They will
1263960810ccSAlan Cox 			 * leave the queue shortly after the scan finishes, so
1264960810ccSAlan Cox 			 * they should be discounted from the inactive count.
1265960810ccSAlan Cox 			 */
1266960810ccSAlan Cox 			addl_page_shortage++;
1267d9e23210SJeff Roberson 		} else if ((m->flags & PG_WINATCFLS) == 0 && pass < 2) {
12687e006499SJohn Dyson 			/*
12692b6b0df7SMatthew Dillon 			 * Dirty pages need to be paged out, but flushing
1270ab46f63eSJohn Baldwin 			 * a page is extremely expensive versus freeing
12712b6b0df7SMatthew Dillon 			 * a clean page.  Rather then artificially limiting
12722b6b0df7SMatthew Dillon 			 * the number of pages we can flush, we instead give
12732b6b0df7SMatthew Dillon 			 * dirty pages extra priority on the inactive queue
12742b6b0df7SMatthew Dillon 			 * by forcing them to be cycled through the queue
12752b6b0df7SMatthew Dillon 			 * twice before being flushed, after which the
12762b6b0df7SMatthew Dillon 			 * (now clean) page will cycle through once more
12772b6b0df7SMatthew Dillon 			 * before being freed.  This significantly extends
12782b6b0df7SMatthew Dillon 			 * the thrash point for a heavily loaded machine.
12797e006499SJohn Dyson 			 */
12803407fefeSKonstantin Belousov 			m->flags |= PG_WINATCFLS;
128127a9fb2fSAlan Cox requeue_page:
12828d220203SAlan Cox 			vm_pagequeue_lock(pq);
128348cc2fc7SKonstantin Belousov 			queues_locked = TRUE;
12848d220203SAlan Cox 			vm_page_requeue_locked(m);
12850d94caffSDavid Greenman 		} else if (maxlaunder > 0) {
12862b6b0df7SMatthew Dillon 			/*
12872b6b0df7SMatthew Dillon 			 * We always want to try to flush some dirty pages if
12882b6b0df7SMatthew Dillon 			 * we encounter them, to keep the system stable.
12892b6b0df7SMatthew Dillon 			 * Normally this number is small, but under extreme
12902b6b0df7SMatthew Dillon 			 * pressure where there are insufficient clean pages
12912b6b0df7SMatthew Dillon 			 * on the inactive queue, we may have to go all out.
12922b6b0df7SMatthew Dillon 			 */
12930d94caffSDavid Greenman 
129440aa80a7SAlan Cox 			if (object->type != OBJT_SWAP &&
129540aa80a7SAlan Cox 			    object->type != OBJT_DEFAULT)
129640aa80a7SAlan Cox 				pageout_ok = TRUE;
129740aa80a7SAlan Cox 			else if (disable_swap_pageouts)
129840aa80a7SAlan Cox 				pageout_ok = FALSE;
129940aa80a7SAlan Cox 			else if (defer_swap_pageouts)
130040aa80a7SAlan Cox 				pageout_ok = vm_page_count_min();
130140aa80a7SAlan Cox 			else
130240aa80a7SAlan Cox 				pageout_ok = TRUE;
130327a9fb2fSAlan Cox 			if (!pageout_ok)
130427a9fb2fSAlan Cox 				goto requeue_page;
130534d8b7eaSJeff Roberson 			error = vm_pageout_clean(m);
13061c7c3c6aSMatthew Dillon 			/*
130734d8b7eaSJeff Roberson 			 * Decrement page_shortage on success to account for
13082b6b0df7SMatthew Dillon 			 * the (future) cleaned page.  Otherwise we could wind
13092b6b0df7SMatthew Dillon 			 * up laundering or cleaning too many pages.
13100d94caffSDavid Greenman 			 */
131134d8b7eaSJeff Roberson 			if (error == 0) {
131234d8b7eaSJeff Roberson 				page_shortage--;
131334d8b7eaSJeff Roberson 				maxlaunder--;
131434d8b7eaSJeff Roberson 			} else if (error == EDEADLK) {
131534d8b7eaSJeff Roberson 				pageout_lock_miss++;
131634d8b7eaSJeff Roberson 				vnodes_skipped++;
131734d8b7eaSJeff Roberson 			} else if (error == EBUSY) {
131834d8b7eaSJeff Roberson 				addl_page_shortage++;
131948cc2fc7SKonstantin Belousov 			}
132048cc2fc7SKonstantin Belousov 			vm_page_lock_assert(m, MA_NOTOWNED);
132148cc2fc7SKonstantin Belousov 			goto relock_queues;
132248cc2fc7SKonstantin Belousov 		}
1323776f729cSKonstantin Belousov drop_page:
132448cc2fc7SKonstantin Belousov 		vm_page_unlock(m);
132589f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
132648cc2fc7SKonstantin Belousov relock_queues:
132748cc2fc7SKonstantin Belousov 		if (!queues_locked) {
13288d220203SAlan Cox 			vm_pagequeue_lock(pq);
132948cc2fc7SKonstantin Belousov 			queues_locked = TRUE;
13306989c456SAlan Cox 		}
1331c325e866SKonstantin Belousov 		next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1332c325e866SKonstantin Belousov 		TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
13330d94caffSDavid Greenman 	}
13348d220203SAlan Cox 	vm_pagequeue_unlock(pq);
133526f9a767SRodney W. Grimes 
13369452b5edSAlan Cox #if !defined(NO_SWAPPING)
13379452b5edSAlan Cox 	/*
13389452b5edSAlan Cox 	 * Wakeup the swapout daemon if we didn't cache or free the targeted
13399452b5edSAlan Cox 	 * number of pages.
13409452b5edSAlan Cox 	 */
13419452b5edSAlan Cox 	if (vm_swap_enabled && page_shortage > 0)
13429452b5edSAlan Cox 		vm_req_vmdaemon(VM_SWAP_NORMAL);
13439452b5edSAlan Cox #endif
13449452b5edSAlan Cox 
13459452b5edSAlan Cox 	/*
13469452b5edSAlan Cox 	 * Wakeup the sync daemon if we skipped a vnode in a writeable object
13479452b5edSAlan Cox 	 * and we didn't cache or free enough pages.
13489452b5edSAlan Cox 	 */
13499452b5edSAlan Cox 	if (vnodes_skipped > 0 && page_shortage > vm_cnt.v_free_target -
13509452b5edSAlan Cox 	    vm_cnt.v_free_min)
13519452b5edSAlan Cox 		(void)speedup_syncer();
13529452b5edSAlan Cox 
1353df8bae1dSRodney W. Grimes 	/*
135476386c7eSKonstantin Belousov 	 * If the inactive queue scan fails repeatedly to meet its
135576386c7eSKonstantin Belousov 	 * target, kill the largest process.
135676386c7eSKonstantin Belousov 	 */
135776386c7eSKonstantin Belousov 	vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
135876386c7eSKonstantin Belousov 
135976386c7eSKonstantin Belousov 	/*
1360936524aaSMatthew Dillon 	 * Compute the number of pages we want to try to move from the
1361936524aaSMatthew Dillon 	 * active queue to the inactive queue.
13621c7c3c6aSMatthew Dillon 	 */
136344f1c916SBryan Drewery 	page_shortage = vm_cnt.v_inactive_target - vm_cnt.v_inactive_count +
13649099545aSAlan Cox 	    vm_paging_target() + deficit + addl_page_shortage;
13659099545aSAlan Cox 
1366114f62c6SJeff Roberson 	pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1367114f62c6SJeff Roberson 	vm_pagequeue_lock(pq);
13689099545aSAlan Cox 	maxscan = pq->pq_cnt;
13699099545aSAlan Cox 
1370d9e23210SJeff Roberson 	/*
1371d9e23210SJeff Roberson 	 * If we're just idle polling attempt to visit every
1372d9e23210SJeff Roberson 	 * active page within 'update_period' seconds.
1373d9e23210SJeff Roberson 	 */
137422cf98d1SAlan Cox 	scan_tick = ticks;
137522cf98d1SAlan Cox 	if (vm_pageout_update_period != 0) {
137622cf98d1SAlan Cox 		min_scan = pq->pq_cnt;
137722cf98d1SAlan Cox 		min_scan *= scan_tick - vmd->vmd_last_active_scan;
137822cf98d1SAlan Cox 		min_scan /= hz * vm_pageout_update_period;
137922cf98d1SAlan Cox 	} else
138022cf98d1SAlan Cox 		min_scan = 0;
138122cf98d1SAlan Cox 	if (min_scan > 0 || (page_shortage > 0 && maxscan > 0))
138222cf98d1SAlan Cox 		vmd->vmd_last_active_scan = scan_tick;
13831c7c3c6aSMatthew Dillon 
13841c7c3c6aSMatthew Dillon 	/*
138522cf98d1SAlan Cox 	 * Scan the active queue for pages that can be deactivated.  Update
138622cf98d1SAlan Cox 	 * the per-page activity counter and use it to identify deactivation
138722cf98d1SAlan Cox 	 * candidates.
13881c7c3c6aSMatthew Dillon 	 */
138922cf98d1SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
139022cf98d1SAlan Cox 	    min_scan || (page_shortage > 0 && scanned < maxscan)); m = next,
139122cf98d1SAlan Cox 	    scanned++) {
1392f35329acSJohn Dyson 
13939cf51988SAlan Cox 		KASSERT(m->queue == PQ_ACTIVE,
1394d3c09dd7SAlan Cox 		    ("vm_pageout_scan: page %p isn't active", m));
1395f35329acSJohn Dyson 
1396c325e866SKonstantin Belousov 		next = TAILQ_NEXT(m, plinks.q);
139722cf98d1SAlan Cox 		if ((m->flags & PG_MARKER) != 0)
13988dbca793STor Egge 			continue;
13997900f95dSKonstantin Belousov 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
14007900f95dSKonstantin Belousov 		    ("Fictitious page %p cannot be in active queue", m));
14017900f95dSKonstantin Belousov 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
14027900f95dSKonstantin Belousov 		    ("Unmanaged page %p cannot be in active queue", m));
14039ee2165fSAlan Cox 		if (!vm_pageout_page_lock(m, &next)) {
14048c616246SKonstantin Belousov 			vm_page_unlock(m);
14052965a453SKip Macy 			continue;
14062965a453SKip Macy 		}
1407b18bfc3dSJohn Dyson 
1408b18bfc3dSJohn Dyson 		/*
1409b18bfc3dSJohn Dyson 		 * The count for pagedaemon pages is done after checking the
1410956f3135SPhilippe Charnier 		 * page for eligibility...
1411b18bfc3dSJohn Dyson 		 */
14128d220203SAlan Cox 		PCPU_INC(cnt.v_pdpages);
1413ef743ce6SJohn Dyson 
14147e006499SJohn Dyson 		/*
14157e006499SJohn Dyson 		 * Check to see "how much" the page has been used.
14167e006499SJohn Dyson 		 */
141786fa2471SAlan Cox 		if ((m->aflags & PGA_REFERENCED) != 0) {
1418bb7858eaSJeff Roberson 			vm_page_aflag_clear(m, PGA_REFERENCED);
141986fa2471SAlan Cox 			act_delta = 1;
142086fa2471SAlan Cox 		} else
142186fa2471SAlan Cox 			act_delta = 0;
142286fa2471SAlan Cox 
1423274132acSJeff Roberson 		/*
1424274132acSJeff Roberson 		 * Unlocked object ref count check.  Two races are possible.
1425274132acSJeff Roberson 		 * 1) The ref was transitioning to zero and we saw non-zero,
1426274132acSJeff Roberson 		 *    the pmap bits will be checked unnecessarily.
1427274132acSJeff Roberson 		 * 2) The ref was transitioning to one and we saw zero.
1428274132acSJeff Roberson 		 *    The page lock prevents a new reference to this page so
1429274132acSJeff Roberson 		 *    we need not check the reference bits.
1430274132acSJeff Roberson 		 */
1431274132acSJeff Roberson 		if (m->object->ref_count != 0)
1432bb7858eaSJeff Roberson 			act_delta += pmap_ts_referenced(m);
1433bb7858eaSJeff Roberson 
1434bb7858eaSJeff Roberson 		/*
1435bb7858eaSJeff Roberson 		 * Advance or decay the act_count based on recent usage.
1436bb7858eaSJeff Roberson 		 */
143786fa2471SAlan Cox 		if (act_delta != 0) {
1438bb7858eaSJeff Roberson 			m->act_count += ACT_ADVANCE + act_delta;
143938efa82bSJohn Dyson 			if (m->act_count > ACT_MAX)
144038efa82bSJohn Dyson 				m->act_count = ACT_MAX;
144186fa2471SAlan Cox 		} else
144238efa82bSJohn Dyson 			m->act_count -= min(m->act_count, ACT_DECLINE);
1443bb7858eaSJeff Roberson 
1444bb7858eaSJeff Roberson 		/*
1445bb7858eaSJeff Roberson 		 * Move this page to the tail of the active or inactive
1446bb7858eaSJeff Roberson 		 * queue depending on usage.
1447bb7858eaSJeff Roberson 		 */
144886fa2471SAlan Cox 		if (m->act_count == 0) {
14498d220203SAlan Cox 			/* Dequeue to avoid later lock recursion. */
14508d220203SAlan Cox 			vm_page_dequeue_locked(m);
1451d4a272dbSJohn Dyson 			vm_page_deactivate(m);
1452bb7858eaSJeff Roberson 			page_shortage--;
14538d220203SAlan Cox 		} else
14548d220203SAlan Cox 			vm_page_requeue_locked(m);
14552965a453SKip Macy 		vm_page_unlock(m);
145626f9a767SRodney W. Grimes 	}
14578d220203SAlan Cox 	vm_pagequeue_unlock(pq);
1458ceb0cf87SJohn Dyson #if !defined(NO_SWAPPING)
1459ceb0cf87SJohn Dyson 	/*
1460ceb0cf87SJohn Dyson 	 * Idle process swapout -- run once per second.
1461ceb0cf87SJohn Dyson 	 */
1462ceb0cf87SJohn Dyson 	if (vm_swap_idle_enabled) {
1463ceb0cf87SJohn Dyson 		static long lsec;
1464227ee8a1SPoul-Henning Kamp 		if (time_second != lsec) {
146597824da3SAlan Cox 			vm_req_vmdaemon(VM_SWAP_IDLE);
1466227ee8a1SPoul-Henning Kamp 			lsec = time_second;
1467ceb0cf87SJohn Dyson 		}
1468ceb0cf87SJohn Dyson 	}
1469ceb0cf87SJohn Dyson #endif
14702025d69bSKonstantin Belousov }
14712025d69bSKonstantin Belousov 
1472449c2e92SKonstantin Belousov static int vm_pageout_oom_vote;
1473449c2e92SKonstantin Belousov 
1474449c2e92SKonstantin Belousov /*
1475449c2e92SKonstantin Belousov  * The pagedaemon threads randlomly select one to perform the
1476449c2e92SKonstantin Belousov  * OOM.  Trying to kill processes before all pagedaemons
1477449c2e92SKonstantin Belousov  * failed to reach free target is premature.
1478449c2e92SKonstantin Belousov  */
1479449c2e92SKonstantin Belousov static void
148076386c7eSKonstantin Belousov vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
148176386c7eSKonstantin Belousov     int starting_page_shortage)
1482449c2e92SKonstantin Belousov {
1483449c2e92SKonstantin Belousov 	int old_vote;
1484449c2e92SKonstantin Belousov 
148576386c7eSKonstantin Belousov 	if (starting_page_shortage <= 0 || starting_page_shortage !=
148676386c7eSKonstantin Belousov 	    page_shortage)
148776386c7eSKonstantin Belousov 		vmd->vmd_oom_seq = 0;
148876386c7eSKonstantin Belousov 	else
148976386c7eSKonstantin Belousov 		vmd->vmd_oom_seq++;
149076386c7eSKonstantin Belousov 	if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1491449c2e92SKonstantin Belousov 		if (vmd->vmd_oom) {
1492449c2e92SKonstantin Belousov 			vmd->vmd_oom = FALSE;
1493449c2e92SKonstantin Belousov 			atomic_subtract_int(&vm_pageout_oom_vote, 1);
1494449c2e92SKonstantin Belousov 		}
1495449c2e92SKonstantin Belousov 		return;
1496449c2e92SKonstantin Belousov 	}
1497449c2e92SKonstantin Belousov 
149876386c7eSKonstantin Belousov 	/*
149976386c7eSKonstantin Belousov 	 * Do not follow the call sequence until OOM condition is
150076386c7eSKonstantin Belousov 	 * cleared.
150176386c7eSKonstantin Belousov 	 */
150276386c7eSKonstantin Belousov 	vmd->vmd_oom_seq = 0;
150376386c7eSKonstantin Belousov 
1504449c2e92SKonstantin Belousov 	if (vmd->vmd_oom)
1505449c2e92SKonstantin Belousov 		return;
1506449c2e92SKonstantin Belousov 
1507449c2e92SKonstantin Belousov 	vmd->vmd_oom = TRUE;
1508449c2e92SKonstantin Belousov 	old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1509449c2e92SKonstantin Belousov 	if (old_vote != vm_ndomains - 1)
1510449c2e92SKonstantin Belousov 		return;
1511449c2e92SKonstantin Belousov 
1512449c2e92SKonstantin Belousov 	/*
1513449c2e92SKonstantin Belousov 	 * The current pagedaemon thread is the last in the quorum to
1514449c2e92SKonstantin Belousov 	 * start OOM.  Initiate the selection and signaling of the
1515449c2e92SKonstantin Belousov 	 * victim.
1516449c2e92SKonstantin Belousov 	 */
1517449c2e92SKonstantin Belousov 	vm_pageout_oom(VM_OOM_MEM);
1518449c2e92SKonstantin Belousov 
1519449c2e92SKonstantin Belousov 	/*
1520449c2e92SKonstantin Belousov 	 * After one round of OOM terror, recall our vote.  On the
1521449c2e92SKonstantin Belousov 	 * next pass, current pagedaemon would vote again if the low
1522449c2e92SKonstantin Belousov 	 * memory condition is still there, due to vmd_oom being
1523449c2e92SKonstantin Belousov 	 * false.
1524449c2e92SKonstantin Belousov 	 */
1525449c2e92SKonstantin Belousov 	vmd->vmd_oom = FALSE;
1526449c2e92SKonstantin Belousov 	atomic_subtract_int(&vm_pageout_oom_vote, 1);
1527449c2e92SKonstantin Belousov }
15282025d69bSKonstantin Belousov 
15293949873fSKonstantin Belousov /*
15303949873fSKonstantin Belousov  * The OOM killer is the page daemon's action of last resort when
15313949873fSKonstantin Belousov  * memory allocation requests have been stalled for a prolonged period
15323949873fSKonstantin Belousov  * of time because it cannot reclaim memory.  This function computes
15333949873fSKonstantin Belousov  * the approximate number of physical pages that could be reclaimed if
15343949873fSKonstantin Belousov  * the specified address space is destroyed.
15353949873fSKonstantin Belousov  *
15363949873fSKonstantin Belousov  * Private, anonymous memory owned by the address space is the
15373949873fSKonstantin Belousov  * principal resource that we expect to recover after an OOM kill.
15383949873fSKonstantin Belousov  * Since the physical pages mapped by the address space's COW entries
15393949873fSKonstantin Belousov  * are typically shared pages, they are unlikely to be released and so
15403949873fSKonstantin Belousov  * they are not counted.
15413949873fSKonstantin Belousov  *
15423949873fSKonstantin Belousov  * To get to the point where the page daemon runs the OOM killer, its
15433949873fSKonstantin Belousov  * efforts to write-back vnode-backed pages may have stalled.  This
15443949873fSKonstantin Belousov  * could be caused by a memory allocation deadlock in the write path
15453949873fSKonstantin Belousov  * that might be resolved by an OOM kill.  Therefore, physical pages
15463949873fSKonstantin Belousov  * belonging to vnode-backed objects are counted, because they might
15473949873fSKonstantin Belousov  * be freed without being written out first if the address space holds
15483949873fSKonstantin Belousov  * the last reference to an unlinked vnode.
15493949873fSKonstantin Belousov  *
15503949873fSKonstantin Belousov  * Similarly, physical pages belonging to OBJT_PHYS objects are
15513949873fSKonstantin Belousov  * counted because the address space might hold the last reference to
15523949873fSKonstantin Belousov  * the object.
15533949873fSKonstantin Belousov  */
15543949873fSKonstantin Belousov static long
15553949873fSKonstantin Belousov vm_pageout_oom_pagecount(struct vmspace *vmspace)
15563949873fSKonstantin Belousov {
15573949873fSKonstantin Belousov 	vm_map_t map;
15583949873fSKonstantin Belousov 	vm_map_entry_t entry;
15593949873fSKonstantin Belousov 	vm_object_t obj;
15603949873fSKonstantin Belousov 	long res;
15613949873fSKonstantin Belousov 
15623949873fSKonstantin Belousov 	map = &vmspace->vm_map;
15633949873fSKonstantin Belousov 	KASSERT(!map->system_map, ("system map"));
15643949873fSKonstantin Belousov 	sx_assert(&map->lock, SA_LOCKED);
15653949873fSKonstantin Belousov 	res = 0;
15663949873fSKonstantin Belousov 	for (entry = map->header.next; entry != &map->header;
15673949873fSKonstantin Belousov 	    entry = entry->next) {
15683949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
15693949873fSKonstantin Belousov 			continue;
15703949873fSKonstantin Belousov 		obj = entry->object.vm_object;
15713949873fSKonstantin Belousov 		if (obj == NULL)
15723949873fSKonstantin Belousov 			continue;
15733949873fSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
15743949873fSKonstantin Belousov 		    obj->ref_count != 1)
15753949873fSKonstantin Belousov 			continue;
15763949873fSKonstantin Belousov 		switch (obj->type) {
15773949873fSKonstantin Belousov 		case OBJT_DEFAULT:
15783949873fSKonstantin Belousov 		case OBJT_SWAP:
15793949873fSKonstantin Belousov 		case OBJT_PHYS:
15803949873fSKonstantin Belousov 		case OBJT_VNODE:
15813949873fSKonstantin Belousov 			res += obj->resident_page_count;
15823949873fSKonstantin Belousov 			break;
15833949873fSKonstantin Belousov 		}
15843949873fSKonstantin Belousov 	}
15853949873fSKonstantin Belousov 	return (res);
15863949873fSKonstantin Belousov }
15873949873fSKonstantin Belousov 
15882025d69bSKonstantin Belousov void
15892025d69bSKonstantin Belousov vm_pageout_oom(int shortage)
15902025d69bSKonstantin Belousov {
15912025d69bSKonstantin Belousov 	struct proc *p, *bigproc;
15922025d69bSKonstantin Belousov 	vm_offset_t size, bigsize;
15932025d69bSKonstantin Belousov 	struct thread *td;
15946bed074cSKonstantin Belousov 	struct vmspace *vm;
15952025d69bSKonstantin Belousov 
15962025d69bSKonstantin Belousov 	/*
15971c58e4e5SJohn Baldwin 	 * We keep the process bigproc locked once we find it to keep anyone
15981c58e4e5SJohn Baldwin 	 * from messing with it; however, there is a possibility of
15991c58e4e5SJohn Baldwin 	 * deadlock if process B is bigproc and one of it's child processes
16001c58e4e5SJohn Baldwin 	 * attempts to propagate a signal to B while we are waiting for A's
16011c58e4e5SJohn Baldwin 	 * lock while walking this list.  To avoid this, we don't block on
16021c58e4e5SJohn Baldwin 	 * the process lock but just skip a process if it is already locked.
16035663e6deSDavid Greenman 	 */
16045663e6deSDavid Greenman 	bigproc = NULL;
16055663e6deSDavid Greenman 	bigsize = 0;
16061005a129SJohn Baldwin 	sx_slock(&allproc_lock);
1607e602ba25SJulian Elischer 	FOREACH_PROC_IN_SYSTEM(p) {
1608e602ba25SJulian Elischer 		int breakout;
1609dcbcd518SBruce Evans 
161071943c3dSKonstantin Belousov 		PROC_LOCK(p);
161171943c3dSKonstantin Belousov 
16121c58e4e5SJohn Baldwin 		/*
16133f1c4c4fSKonstantin Belousov 		 * If this is a system, protected or killed process, skip it.
16145663e6deSDavid Greenman 		 */
161571943c3dSKonstantin Belousov 		if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
161671943c3dSKonstantin Belousov 		    P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
161771943c3dSKonstantin Belousov 		    p->p_pid == 1 || P_KILLED(p) ||
161871943c3dSKonstantin Belousov 		    (p->p_pid < 48 && swap_pager_avail != 0)) {
16198606d880SJohn Baldwin 			PROC_UNLOCK(p);
16205663e6deSDavid Greenman 			continue;
16215663e6deSDavid Greenman 		}
16225663e6deSDavid Greenman 		/*
1623dcbcd518SBruce Evans 		 * If the process is in a non-running type state,
1624e602ba25SJulian Elischer 		 * don't touch it.  Check all the threads individually.
16255663e6deSDavid Greenman 		 */
1626e602ba25SJulian Elischer 		breakout = 0;
1627e602ba25SJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td) {
1628982d11f8SJeff Roberson 			thread_lock(td);
162971fad9fdSJulian Elischer 			if (!TD_ON_RUNQ(td) &&
163071fad9fdSJulian Elischer 			    !TD_IS_RUNNING(td) &&
1631f497cda2SEdward Tomasz Napierala 			    !TD_IS_SLEEPING(td) &&
1632b98acc0aSKonstantin Belousov 			    !TD_IS_SUSPENDED(td) &&
1633b98acc0aSKonstantin Belousov 			    !TD_IS_SWAPPED(td)) {
1634982d11f8SJeff Roberson 				thread_unlock(td);
1635e602ba25SJulian Elischer 				breakout = 1;
1636e602ba25SJulian Elischer 				break;
1637e602ba25SJulian Elischer 			}
1638982d11f8SJeff Roberson 			thread_unlock(td);
1639e602ba25SJulian Elischer 		}
1640e602ba25SJulian Elischer 		if (breakout) {
16411c58e4e5SJohn Baldwin 			PROC_UNLOCK(p);
16425663e6deSDavid Greenman 			continue;
16435663e6deSDavid Greenman 		}
16445663e6deSDavid Greenman 		/*
16455663e6deSDavid Greenman 		 * get the process size
16465663e6deSDavid Greenman 		 */
16476bed074cSKonstantin Belousov 		vm = vmspace_acquire_ref(p);
16486bed074cSKonstantin Belousov 		if (vm == NULL) {
16496bed074cSKonstantin Belousov 			PROC_UNLOCK(p);
16506bed074cSKonstantin Belousov 			continue;
16516bed074cSKonstantin Belousov 		}
165271943c3dSKonstantin Belousov 		_PHOLD(p);
16536bed074cSKonstantin Belousov 		if (!vm_map_trylock_read(&vm->vm_map)) {
165471943c3dSKonstantin Belousov 			_PRELE(p);
165572d97679SDavid Schultz 			PROC_UNLOCK(p);
165671943c3dSKonstantin Belousov 			vmspace_free(vm);
165772d97679SDavid Schultz 			continue;
165872d97679SDavid Schultz 		}
165971943c3dSKonstantin Belousov 		PROC_UNLOCK(p);
16607981aa24SKonstantin Belousov 		size = vmspace_swap_count(vm);
16612025d69bSKonstantin Belousov 		if (shortage == VM_OOM_MEM)
16623949873fSKonstantin Belousov 			size += vm_pageout_oom_pagecount(vm);
16633949873fSKonstantin Belousov 		vm_map_unlock_read(&vm->vm_map);
16646bed074cSKonstantin Belousov 		vmspace_free(vm);
16653949873fSKonstantin Belousov 
16665663e6deSDavid Greenman 		/*
16673949873fSKonstantin Belousov 		 * If this process is bigger than the biggest one,
16685663e6deSDavid Greenman 		 * remember it.
16695663e6deSDavid Greenman 		 */
16705663e6deSDavid Greenman 		if (size > bigsize) {
16711c58e4e5SJohn Baldwin 			if (bigproc != NULL)
167271943c3dSKonstantin Belousov 				PRELE(bigproc);
16735663e6deSDavid Greenman 			bigproc = p;
16745663e6deSDavid Greenman 			bigsize = size;
167571943c3dSKonstantin Belousov 		} else {
167671943c3dSKonstantin Belousov 			PRELE(p);
167771943c3dSKonstantin Belousov 		}
16785663e6deSDavid Greenman 	}
16791005a129SJohn Baldwin 	sx_sunlock(&allproc_lock);
16805663e6deSDavid Greenman 	if (bigproc != NULL) {
16818311a2b8SWill Andrews 		if (vm_panic_on_oom != 0)
16828311a2b8SWill Andrews 			panic("out of swap space");
168371943c3dSKonstantin Belousov 		PROC_LOCK(bigproc);
1684729b1e51SDavid Greenman 		killproc(bigproc, "out of swap space");
1685fa885116SJulian Elischer 		sched_nice(bigproc, PRIO_MIN);
168671943c3dSKonstantin Belousov 		_PRELE(bigproc);
16871c58e4e5SJohn Baldwin 		PROC_UNLOCK(bigproc);
168844f1c916SBryan Drewery 		wakeup(&vm_cnt.v_free_count);
16895663e6deSDavid Greenman 	}
16905663e6deSDavid Greenman }
169126f9a767SRodney W. Grimes 
1692449c2e92SKonstantin Belousov static void
1693449c2e92SKonstantin Belousov vm_pageout_worker(void *arg)
1694449c2e92SKonstantin Belousov {
1695449c2e92SKonstantin Belousov 	struct vm_domain *domain;
1696949c9186SKonstantin Belousov 	int domidx;
1697449c2e92SKonstantin Belousov 
1698449c2e92SKonstantin Belousov 	domidx = (uintptr_t)arg;
1699449c2e92SKonstantin Belousov 	domain = &vm_dom[domidx];
1700449c2e92SKonstantin Belousov 
1701449c2e92SKonstantin Belousov 	/*
1702949c9186SKonstantin Belousov 	 * XXXKIB It could be useful to bind pageout daemon threads to
1703949c9186SKonstantin Belousov 	 * the cores belonging to the domain, from which vm_page_array
1704949c9186SKonstantin Belousov 	 * is allocated.
1705449c2e92SKonstantin Belousov 	 */
1706449c2e92SKonstantin Belousov 
1707449c2e92SKonstantin Belousov 	KASSERT(domain->vmd_segs != 0, ("domain without segments"));
170822cf98d1SAlan Cox 	domain->vmd_last_active_scan = ticks;
1709449c2e92SKonstantin Belousov 	vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
17107e78597fSMark Johnston 	vm_pageout_init_marker(&domain->vmd_inacthead, PQ_INACTIVE);
17117e78597fSMark Johnston 	TAILQ_INSERT_HEAD(&domain->vmd_pagequeues[PQ_INACTIVE].pq_pl,
17127e78597fSMark Johnston 	    &domain->vmd_inacthead, plinks.q);
1713449c2e92SKonstantin Belousov 
1714449c2e92SKonstantin Belousov 	/*
1715449c2e92SKonstantin Belousov 	 * The pageout daemon worker is never done, so loop forever.
1716449c2e92SKonstantin Belousov 	 */
1717449c2e92SKonstantin Belousov 	while (TRUE) {
1718449c2e92SKonstantin Belousov 		/*
1719449c2e92SKonstantin Belousov 		 * If we have enough free memory, wakeup waiters.  Do
1720449c2e92SKonstantin Belousov 		 * not clear vm_pages_needed until we reach our target,
1721449c2e92SKonstantin Belousov 		 * otherwise we may be woken up over and over again and
1722449c2e92SKonstantin Belousov 		 * waste a lot of cpu.
1723449c2e92SKonstantin Belousov 		 */
1724449c2e92SKonstantin Belousov 		mtx_lock(&vm_page_queue_free_mtx);
1725449c2e92SKonstantin Belousov 		if (vm_pages_needed && !vm_page_count_min()) {
1726449c2e92SKonstantin Belousov 			if (!vm_paging_needed())
1727449c2e92SKonstantin Belousov 				vm_pages_needed = 0;
172844f1c916SBryan Drewery 			wakeup(&vm_cnt.v_free_count);
1729449c2e92SKonstantin Belousov 		}
1730449c2e92SKonstantin Belousov 		if (vm_pages_needed) {
1731449c2e92SKonstantin Belousov 			/*
1732d9347bcaSAlan Cox 			 * We're still not done.  Either vm_pages_needed was
1733d9347bcaSAlan Cox 			 * set by another thread during the previous scan
1734d9347bcaSAlan Cox 			 * (typically, this happens during a level 0 scan) or
1735d9347bcaSAlan Cox 			 * vm_pages_needed was already set and the scan failed
1736d9347bcaSAlan Cox 			 * to free enough pages.  If we haven't yet performed
1737d9347bcaSAlan Cox 			 * a level >= 2 scan (unlimited dirty cleaning), then
1738d9347bcaSAlan Cox 			 * upgrade the level and scan again now.  Otherwise,
1739d9347bcaSAlan Cox 			 * sleep a bit and try again later.  While sleeping,
1740d9347bcaSAlan Cox 			 * vm_pages_needed can be cleared.
1741449c2e92SKonstantin Belousov 			 */
1742449c2e92SKonstantin Belousov 			if (domain->vmd_pass > 1)
1743449c2e92SKonstantin Belousov 				msleep(&vm_pages_needed,
1744449c2e92SKonstantin Belousov 				    &vm_page_queue_free_mtx, PVM, "psleep",
1745449c2e92SKonstantin Belousov 				    hz / 2);
1746449c2e92SKonstantin Belousov 		} else {
1747449c2e92SKonstantin Belousov 			/*
1748d9e23210SJeff Roberson 			 * Good enough, sleep until required to refresh
1749d9e23210SJeff Roberson 			 * stats.
1750449c2e92SKonstantin Belousov 			 */
1751d9e23210SJeff Roberson 			msleep(&vm_pages_needed, &vm_page_queue_free_mtx,
1752d9e23210SJeff Roberson 			    PVM, "psleep", hz);
1753449c2e92SKonstantin Belousov 		}
1754d9e23210SJeff Roberson 		if (vm_pages_needed) {
175544f1c916SBryan Drewery 			vm_cnt.v_pdwakeups++;
1756d9e23210SJeff Roberson 			domain->vmd_pass++;
1757d9347bcaSAlan Cox 		} else
1758d9347bcaSAlan Cox 			domain->vmd_pass = 0;
1759449c2e92SKonstantin Belousov 		mtx_unlock(&vm_page_queue_free_mtx);
1760449c2e92SKonstantin Belousov 		vm_pageout_scan(domain, domain->vmd_pass);
1761449c2e92SKonstantin Belousov 	}
1762449c2e92SKonstantin Belousov }
1763449c2e92SKonstantin Belousov 
1764df8bae1dSRodney W. Grimes /*
17654d19f4adSSteven Hartland  *	vm_pageout_init initialises basic pageout daemon settings.
1766df8bae1dSRodney W. Grimes  */
17672b14f991SJulian Elischer static void
17684d19f4adSSteven Hartland vm_pageout_init(void)
1769df8bae1dSRodney W. Grimes {
1770df8bae1dSRodney W. Grimes 	/*
1771df8bae1dSRodney W. Grimes 	 * Initialize some paging parameters.
1772df8bae1dSRodney W. Grimes 	 */
177344f1c916SBryan Drewery 	vm_cnt.v_interrupt_free_min = 2;
177444f1c916SBryan Drewery 	if (vm_cnt.v_page_count < 2000)
1775f35329acSJohn Dyson 		vm_pageout_page_count = 8;
1776f6b04d2bSDavid Greenman 
177745ae1d91SAlan Cox 	/*
177845ae1d91SAlan Cox 	 * v_free_reserved needs to include enough for the largest
177945ae1d91SAlan Cox 	 * swap pager structures plus enough for any pv_entry structs
178045ae1d91SAlan Cox 	 * when paging.
178145ae1d91SAlan Cox 	 */
178244f1c916SBryan Drewery 	if (vm_cnt.v_page_count > 1024)
178344f1c916SBryan Drewery 		vm_cnt.v_free_min = 4 + (vm_cnt.v_page_count - 1024) / 200;
17842feb50bfSAttilio Rao 	else
178544f1c916SBryan Drewery 		vm_cnt.v_free_min = 4;
178644f1c916SBryan Drewery 	vm_cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
178744f1c916SBryan Drewery 	    vm_cnt.v_interrupt_free_min;
178844f1c916SBryan Drewery 	vm_cnt.v_free_reserved = vm_pageout_page_count +
178944f1c916SBryan Drewery 	    vm_cnt.v_pageout_free_min + (vm_cnt.v_page_count / 768);
179044f1c916SBryan Drewery 	vm_cnt.v_free_severe = vm_cnt.v_free_min / 2;
179144f1c916SBryan Drewery 	vm_cnt.v_free_target = 4 * vm_cnt.v_free_min + vm_cnt.v_free_reserved;
179244f1c916SBryan Drewery 	vm_cnt.v_free_min += vm_cnt.v_free_reserved;
179344f1c916SBryan Drewery 	vm_cnt.v_free_severe += vm_cnt.v_free_reserved;
179444f1c916SBryan Drewery 	vm_cnt.v_inactive_target = (3 * vm_cnt.v_free_target) / 2;
179544f1c916SBryan Drewery 	if (vm_cnt.v_inactive_target > vm_cnt.v_free_count / 3)
179644f1c916SBryan Drewery 		vm_cnt.v_inactive_target = vm_cnt.v_free_count / 3;
1797df8bae1dSRodney W. Grimes 
1798d9e23210SJeff Roberson 	/*
1799d9e23210SJeff Roberson 	 * Set the default wakeup threshold to be 10% above the minimum
1800d9e23210SJeff Roberson 	 * page limit.  This keeps the steady state out of shortfall.
1801d9e23210SJeff Roberson 	 */
180244f1c916SBryan Drewery 	vm_pageout_wakeup_thresh = (vm_cnt.v_free_min / 10) * 11;
1803d9e23210SJeff Roberson 
1804d9e23210SJeff Roberson 	/*
1805d9e23210SJeff Roberson 	 * Set interval in seconds for active scan.  We want to visit each
1806c9612b2dSJeff Roberson 	 * page at least once every ten minutes.  This is to prevent worst
1807c9612b2dSJeff Roberson 	 * case paging behaviors with stale active LRU.
1808d9e23210SJeff Roberson 	 */
1809d9e23210SJeff Roberson 	if (vm_pageout_update_period == 0)
1810c9612b2dSJeff Roberson 		vm_pageout_update_period = 600;
1811d9e23210SJeff Roberson 
1812df8bae1dSRodney W. Grimes 	/* XXX does not really belong here */
1813df8bae1dSRodney W. Grimes 	if (vm_page_max_wired == 0)
181444f1c916SBryan Drewery 		vm_page_max_wired = vm_cnt.v_free_count / 3;
18154d19f4adSSteven Hartland }
18164d19f4adSSteven Hartland 
18174d19f4adSSteven Hartland /*
18184d19f4adSSteven Hartland  *     vm_pageout is the high level pageout daemon.
18194d19f4adSSteven Hartland  */
18204d19f4adSSteven Hartland static void
18214d19f4adSSteven Hartland vm_pageout(void)
18224d19f4adSSteven Hartland {
182344ec2b63SKonstantin Belousov 	int error;
18244d19f4adSSteven Hartland #if MAXMEMDOM > 1
182544ec2b63SKonstantin Belousov 	int i;
18264d19f4adSSteven Hartland #endif
1827df8bae1dSRodney W. Grimes 
182824a1cce3SDavid Greenman 	swap_pager_swap_init();
1829449c2e92SKonstantin Belousov #if MAXMEMDOM > 1
1830449c2e92SKonstantin Belousov 	for (i = 1; i < vm_ndomains; i++) {
1831449c2e92SKonstantin Belousov 		error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
1832449c2e92SKonstantin Belousov 		    curproc, NULL, 0, 0, "dom%d", i);
1833449c2e92SKonstantin Belousov 		if (error != 0) {
1834449c2e92SKonstantin Belousov 			panic("starting pageout for domain %d, error %d\n",
1835449c2e92SKonstantin Belousov 			    i, error);
1836dc2efb27SJohn Dyson 		}
1837f919ebdeSDavid Greenman 	}
1838449c2e92SKonstantin Belousov #endif
183944ec2b63SKonstantin Belousov 	error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
184044ec2b63SKonstantin Belousov 	    0, 0, "uma");
184144ec2b63SKonstantin Belousov 	if (error != 0)
184244ec2b63SKonstantin Belousov 		panic("starting uma_reclaim helper, error %d\n", error);
1843d395270dSDimitry Andric 	vm_pageout_worker((void *)(uintptr_t)0);
1844df8bae1dSRodney W. Grimes }
184526f9a767SRodney W. Grimes 
18466b4b77adSAlan Cox /*
1847e9f995d8SAlan Cox  * Unless the free page queue lock is held by the caller, this function
18486b4b77adSAlan Cox  * should be regarded as advisory.  Specifically, the caller should
184944f1c916SBryan Drewery  * not msleep() on &vm_cnt.v_free_count following this function unless
1850e9f995d8SAlan Cox  * the free page queue lock is held until the msleep() is performed.
18516b4b77adSAlan Cox  */
1852e0c5a895SJohn Dyson void
18534a365329SAndrey Zonov pagedaemon_wakeup(void)
1854e0c5a895SJohn Dyson {
1855a1c0a785SAlan Cox 
1856b40ce416SJulian Elischer 	if (!vm_pages_needed && curthread->td_proc != pageproc) {
1857a1c0a785SAlan Cox 		vm_pages_needed = 1;
1858e0c5a895SJohn Dyson 		wakeup(&vm_pages_needed);
1859e0c5a895SJohn Dyson 	}
1860e0c5a895SJohn Dyson }
1861e0c5a895SJohn Dyson 
186238efa82bSJohn Dyson #if !defined(NO_SWAPPING)
18635afce282SDavid Greenman static void
186497824da3SAlan Cox vm_req_vmdaemon(int req)
18655afce282SDavid Greenman {
18665afce282SDavid Greenman 	static int lastrun = 0;
18675afce282SDavid Greenman 
186897824da3SAlan Cox 	mtx_lock(&vm_daemon_mtx);
186997824da3SAlan Cox 	vm_pageout_req_swapout |= req;
1870b18bfc3dSJohn Dyson 	if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
18715afce282SDavid Greenman 		wakeup(&vm_daemon_needed);
18725afce282SDavid Greenman 		lastrun = ticks;
18735afce282SDavid Greenman 	}
187497824da3SAlan Cox 	mtx_unlock(&vm_daemon_mtx);
18755afce282SDavid Greenman }
18765afce282SDavid Greenman 
18772b14f991SJulian Elischer static void
18784a365329SAndrey Zonov vm_daemon(void)
18790d94caffSDavid Greenman {
188091d5354aSJohn Baldwin 	struct rlimit rsslim;
1881dcbcd518SBruce Evans 	struct proc *p;
1882dcbcd518SBruce Evans 	struct thread *td;
18836bed074cSKonstantin Belousov 	struct vmspace *vm;
1884099e7e95SEdward Tomasz Napierala 	int breakout, swapout_flags, tryagain, attempts;
1885afcc55f3SEdward Tomasz Napierala #ifdef RACCT
1886099e7e95SEdward Tomasz Napierala 	uint64_t rsize, ravailable;
1887afcc55f3SEdward Tomasz Napierala #endif
18880d94caffSDavid Greenman 
18892fe6e4d7SDavid Greenman 	while (TRUE) {
189097824da3SAlan Cox 		mtx_lock(&vm_daemon_mtx);
18914b5c9cf6SEdward Tomasz Napierala 		msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
1892099e7e95SEdward Tomasz Napierala #ifdef RACCT
18934b5c9cf6SEdward Tomasz Napierala 		    racct_enable ? hz : 0
1894099e7e95SEdward Tomasz Napierala #else
18954b5c9cf6SEdward Tomasz Napierala 		    0
1896099e7e95SEdward Tomasz Napierala #endif
18974b5c9cf6SEdward Tomasz Napierala 		);
189897824da3SAlan Cox 		swapout_flags = vm_pageout_req_swapout;
18994c1f8ee9SDavid Greenman 		vm_pageout_req_swapout = 0;
190097824da3SAlan Cox 		mtx_unlock(&vm_daemon_mtx);
190197824da3SAlan Cox 		if (swapout_flags)
190297824da3SAlan Cox 			swapout_procs(swapout_flags);
190397824da3SAlan Cox 
19042fe6e4d7SDavid Greenman 		/*
19050d94caffSDavid Greenman 		 * scan the processes for exceeding their rlimits or if
19060d94caffSDavid Greenman 		 * process is swapped out -- deactivate pages
19072fe6e4d7SDavid Greenman 		 */
1908099e7e95SEdward Tomasz Napierala 		tryagain = 0;
1909099e7e95SEdward Tomasz Napierala 		attempts = 0;
1910099e7e95SEdward Tomasz Napierala again:
1911099e7e95SEdward Tomasz Napierala 		attempts++;
19121005a129SJohn Baldwin 		sx_slock(&allproc_lock);
1913f67af5c9SXin LI 		FOREACH_PROC_IN_SYSTEM(p) {
1914fe2144fdSLuoqi Chen 			vm_pindex_t limit, size;
19152fe6e4d7SDavid Greenman 
19162fe6e4d7SDavid Greenman 			/*
19172fe6e4d7SDavid Greenman 			 * if this is a system process or if we have already
19182fe6e4d7SDavid Greenman 			 * looked at this process, skip it.
19192fe6e4d7SDavid Greenman 			 */
1920897ecacdSJohn Baldwin 			PROC_LOCK(p);
19218e6fa660SJohn Baldwin 			if (p->p_state != PRS_NORMAL ||
19228e6fa660SJohn Baldwin 			    p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
1923897ecacdSJohn Baldwin 				PROC_UNLOCK(p);
19242fe6e4d7SDavid Greenman 				continue;
19252fe6e4d7SDavid Greenman 			}
19262fe6e4d7SDavid Greenman 			/*
19272fe6e4d7SDavid Greenman 			 * if the process is in a non-running type state,
19282fe6e4d7SDavid Greenman 			 * don't touch it.
19292fe6e4d7SDavid Greenman 			 */
1930e602ba25SJulian Elischer 			breakout = 0;
1931e602ba25SJulian Elischer 			FOREACH_THREAD_IN_PROC(p, td) {
1932982d11f8SJeff Roberson 				thread_lock(td);
193371fad9fdSJulian Elischer 				if (!TD_ON_RUNQ(td) &&
193471fad9fdSJulian Elischer 				    !TD_IS_RUNNING(td) &&
1935f497cda2SEdward Tomasz Napierala 				    !TD_IS_SLEEPING(td) &&
1936f497cda2SEdward Tomasz Napierala 				    !TD_IS_SUSPENDED(td)) {
1937982d11f8SJeff Roberson 					thread_unlock(td);
1938e602ba25SJulian Elischer 					breakout = 1;
1939e602ba25SJulian Elischer 					break;
1940e602ba25SJulian Elischer 				}
1941982d11f8SJeff Roberson 				thread_unlock(td);
1942e602ba25SJulian Elischer 			}
1943897ecacdSJohn Baldwin 			if (breakout) {
1944897ecacdSJohn Baldwin 				PROC_UNLOCK(p);
19452fe6e4d7SDavid Greenman 				continue;
19462fe6e4d7SDavid Greenman 			}
19472fe6e4d7SDavid Greenman 			/*
19482fe6e4d7SDavid Greenman 			 * get a limit
19492fe6e4d7SDavid Greenman 			 */
1950f6f6d240SMateusz Guzik 			lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
1951fe2144fdSLuoqi Chen 			limit = OFF_TO_IDX(
195291d5354aSJohn Baldwin 			    qmin(rsslim.rlim_cur, rsslim.rlim_max));
19532fe6e4d7SDavid Greenman 
19542fe6e4d7SDavid Greenman 			/*
19550d94caffSDavid Greenman 			 * let processes that are swapped out really be
19560d94caffSDavid Greenman 			 * swapped out set the limit to nothing (will force a
19570d94caffSDavid Greenman 			 * swap-out.)
19582fe6e4d7SDavid Greenman 			 */
1959b61ce5b0SJeff Roberson 			if ((p->p_flag & P_INMEM) == 0)
19600d94caffSDavid Greenman 				limit = 0;	/* XXX */
19616bed074cSKonstantin Belousov 			vm = vmspace_acquire_ref(p);
1962897ecacdSJohn Baldwin 			PROC_UNLOCK(p);
19636bed074cSKonstantin Belousov 			if (vm == NULL)
19646bed074cSKonstantin Belousov 				continue;
19652fe6e4d7SDavid Greenman 
19666bed074cSKonstantin Belousov 			size = vmspace_resident_count(vm);
1967a406d8c3SEdward Tomasz Napierala 			if (size >= limit) {
1968fe2144fdSLuoqi Chen 				vm_pageout_map_deactivate_pages(
19696bed074cSKonstantin Belousov 				    &vm->vm_map, limit);
19702fe6e4d7SDavid Greenman 			}
1971afcc55f3SEdward Tomasz Napierala #ifdef RACCT
19724b5c9cf6SEdward Tomasz Napierala 			if (racct_enable) {
1973099e7e95SEdward Tomasz Napierala 				rsize = IDX_TO_OFF(size);
1974099e7e95SEdward Tomasz Napierala 				PROC_LOCK(p);
1975099e7e95SEdward Tomasz Napierala 				racct_set(p, RACCT_RSS, rsize);
1976099e7e95SEdward Tomasz Napierala 				ravailable = racct_get_available(p, RACCT_RSS);
1977099e7e95SEdward Tomasz Napierala 				PROC_UNLOCK(p);
1978099e7e95SEdward Tomasz Napierala 				if (rsize > ravailable) {
1979099e7e95SEdward Tomasz Napierala 					/*
19804b5c9cf6SEdward Tomasz Napierala 					 * Don't be overly aggressive; this
19814b5c9cf6SEdward Tomasz Napierala 					 * might be an innocent process,
19824b5c9cf6SEdward Tomasz Napierala 					 * and the limit could've been exceeded
19834b5c9cf6SEdward Tomasz Napierala 					 * by some memory hog.  Don't try
19844b5c9cf6SEdward Tomasz Napierala 					 * to deactivate more than 1/4th
19854b5c9cf6SEdward Tomasz Napierala 					 * of process' resident set size.
1986099e7e95SEdward Tomasz Napierala 					 */
1987099e7e95SEdward Tomasz Napierala 					if (attempts <= 8) {
19884b5c9cf6SEdward Tomasz Napierala 						if (ravailable < rsize -
19894b5c9cf6SEdward Tomasz Napierala 						    (rsize / 4)) {
19904b5c9cf6SEdward Tomasz Napierala 							ravailable = rsize -
19914b5c9cf6SEdward Tomasz Napierala 							    (rsize / 4);
19924b5c9cf6SEdward Tomasz Napierala 						}
1993099e7e95SEdward Tomasz Napierala 					}
1994099e7e95SEdward Tomasz Napierala 					vm_pageout_map_deactivate_pages(
19954b5c9cf6SEdward Tomasz Napierala 					    &vm->vm_map,
19964b5c9cf6SEdward Tomasz Napierala 					    OFF_TO_IDX(ravailable));
1997099e7e95SEdward Tomasz Napierala 					/* Update RSS usage after paging out. */
1998099e7e95SEdward Tomasz Napierala 					size = vmspace_resident_count(vm);
1999099e7e95SEdward Tomasz Napierala 					rsize = IDX_TO_OFF(size);
2000099e7e95SEdward Tomasz Napierala 					PROC_LOCK(p);
2001099e7e95SEdward Tomasz Napierala 					racct_set(p, RACCT_RSS, rsize);
2002099e7e95SEdward Tomasz Napierala 					PROC_UNLOCK(p);
2003099e7e95SEdward Tomasz Napierala 					if (rsize > ravailable)
2004099e7e95SEdward Tomasz Napierala 						tryagain = 1;
2005099e7e95SEdward Tomasz Napierala 				}
20064b5c9cf6SEdward Tomasz Napierala 			}
2007afcc55f3SEdward Tomasz Napierala #endif
20086bed074cSKonstantin Belousov 			vmspace_free(vm);
20092fe6e4d7SDavid Greenman 		}
20101005a129SJohn Baldwin 		sx_sunlock(&allproc_lock);
2011099e7e95SEdward Tomasz Napierala 		if (tryagain != 0 && attempts <= 10)
2012099e7e95SEdward Tomasz Napierala 			goto again;
201324a1cce3SDavid Greenman 	}
20142fe6e4d7SDavid Greenman }
2015a1287949SEivind Eklund #endif			/* !defined(NO_SWAPPING) */
2016