xref: /freebsd/sys/vm/vm_pageout.c (revision 8748f58cdeea8fa71bb11de47eadc217383f0091)
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"
7914a0d74eSSteven Hartland #include "opt_kdtrace.h"
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);
125449c2e92SKonstantin Belousov static void vm_pageout_mightbe_oom(struct vm_domain *vmd, int pass);
12645ae1d91SAlan Cox 
1274d19f4adSSteven Hartland SYSINIT(pagedaemon_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, vm_pageout_init,
1284d19f4adSSteven Hartland     NULL);
1294d19f4adSSteven Hartland 
1302b14f991SJulian Elischer struct proc *pageproc;
1312b14f991SJulian Elischer 
1322b14f991SJulian Elischer static struct kproc_desc page_kp = {
1332b14f991SJulian Elischer 	"pagedaemon",
1342b14f991SJulian Elischer 	vm_pageout,
1352b14f991SJulian Elischer 	&pageproc
1362b14f991SJulian Elischer };
1374d19f4adSSteven Hartland SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_SECOND, kproc_start,
138237fdd78SRobert Watson     &page_kp);
1392b14f991SJulian Elischer 
14014a0d74eSSteven Hartland SDT_PROVIDER_DEFINE(vm);
14114a0d74eSSteven Hartland SDT_PROBE_DEFINE(vm, , , vm__lowmem_cache);
14214a0d74eSSteven Hartland SDT_PROBE_DEFINE(vm, , , vm__lowmem_scan);
14314a0d74eSSteven Hartland 
14438efa82bSJohn Dyson #if !defined(NO_SWAPPING)
1452b14f991SJulian Elischer /* the kernel process "vm_daemon"*/
14611caded3SAlfred Perlstein static void vm_daemon(void);
147f708ef1bSPoul-Henning Kamp static struct	proc *vmproc;
1482b14f991SJulian Elischer 
1492b14f991SJulian Elischer static struct kproc_desc vm_kp = {
1502b14f991SJulian Elischer 	"vmdaemon",
1512b14f991SJulian Elischer 	vm_daemon,
1522b14f991SJulian Elischer 	&vmproc
1532b14f991SJulian Elischer };
154237fdd78SRobert Watson SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
15538efa82bSJohn Dyson #endif
1562b14f991SJulian Elischer 
1572b14f991SJulian Elischer 
1588b245767SAlan Cox int vm_pages_needed;		/* Event on which pageout daemon sleeps */
1598b245767SAlan Cox int vm_pageout_deficit;		/* Estimated number of pages deficit */
160d9e23210SJeff Roberson int vm_pageout_wakeup_thresh;
16126f9a767SRodney W. Grimes 
16238efa82bSJohn Dyson #if !defined(NO_SWAPPING)
163f708ef1bSPoul-Henning Kamp static int vm_pageout_req_swapout;	/* XXX */
164f708ef1bSPoul-Henning Kamp static int vm_daemon_needed;
16597824da3SAlan Cox static struct mtx vm_daemon_mtx;
16697824da3SAlan Cox /* Allow for use by vm_pageout before vm_daemon is initialized. */
16797824da3SAlan Cox MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
16838efa82bSJohn Dyson #endif
1692b6b0df7SMatthew Dillon static int vm_max_launder = 32;
170d9e23210SJeff Roberson static int vm_pageout_update_period;
1714a365329SAndrey Zonov static int defer_swap_pageouts;
1724a365329SAndrey Zonov static int disable_swap_pageouts;
173c9612b2dSJeff Roberson static int lowmem_period = 10;
174a6bf3a9eSRyan Stone static time_t lowmem_uptime;
17570111b90SJohn Dyson 
17638efa82bSJohn Dyson #if defined(NO_SWAPPING)
177303b270bSEivind Eklund static int vm_swap_enabled = 0;
178303b270bSEivind Eklund static int vm_swap_idle_enabled = 0;
17938efa82bSJohn Dyson #else
180303b270bSEivind Eklund static int vm_swap_enabled = 1;
181303b270bSEivind Eklund static int vm_swap_idle_enabled = 0;
18238efa82bSJohn Dyson #endif
18338efa82bSJohn Dyson 
1848311a2b8SWill Andrews static int vm_panic_on_oom = 0;
1858311a2b8SWill Andrews 
1868311a2b8SWill Andrews SYSCTL_INT(_vm, OID_AUTO, panic_on_oom,
1878311a2b8SWill Andrews 	CTLFLAG_RWTUN, &vm_panic_on_oom, 0,
1888311a2b8SWill Andrews 	"panic on out of memory instead of killing the largest process");
1898311a2b8SWill Andrews 
190d9e23210SJeff Roberson SYSCTL_INT(_vm, OID_AUTO, pageout_wakeup_thresh,
191d9e23210SJeff Roberson 	CTLFLAG_RW, &vm_pageout_wakeup_thresh, 0,
192d9e23210SJeff Roberson 	"free page threshold for waking up the pageout daemon");
193d9e23210SJeff Roberson 
1942b6b0df7SMatthew Dillon SYSCTL_INT(_vm, OID_AUTO, max_launder,
1952b6b0df7SMatthew Dillon 	CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
19638efa82bSJohn Dyson 
197d9e23210SJeff Roberson SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
198d9e23210SJeff Roberson 	CTLFLAG_RW, &vm_pageout_update_period, 0,
199d9e23210SJeff Roberson 	"Maximum active LRU update period");
20053636869SAndrey Zonov 
201c9612b2dSJeff Roberson SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RW, &lowmem_period, 0,
202c9612b2dSJeff Roberson 	"Low memory callback period");
203c9612b2dSJeff Roberson 
20438efa82bSJohn Dyson #if defined(NO_SWAPPING)
205ceb0cf87SJohn Dyson SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
2066bd9cb1cSTom Rhodes 	CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout");
207ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
2086bd9cb1cSTom Rhodes 	CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
20938efa82bSJohn Dyson #else
210ceb0cf87SJohn Dyson SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
211b0359e2cSPeter Wemm 	CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
212ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
213b0359e2cSPeter Wemm 	CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
21438efa82bSJohn Dyson #endif
21526f9a767SRodney W. Grimes 
216ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
217b0359e2cSPeter Wemm 	CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
21812ac6a1dSJohn Dyson 
219ceb0cf87SJohn Dyson SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
220b0359e2cSPeter Wemm 	CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
22112ac6a1dSJohn Dyson 
22223b59018SMatthew Dillon static int pageout_lock_miss;
22323b59018SMatthew Dillon SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
22423b59018SMatthew Dillon 	CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
22523b59018SMatthew Dillon 
226ffc82b0aSJohn Dyson #define VM_PAGEOUT_PAGE_COUNT 16
227bbc0ec52SDavid Greenman int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
228df8bae1dSRodney W. Grimes 
229c3cb3e12SDavid Greenman int vm_page_max_wired;		/* XXX max # of wired pages system-wide */
2305dfc2870SAlan Cox SYSCTL_INT(_vm, OID_AUTO, max_wired,
2315dfc2870SAlan Cox 	CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
232df8bae1dSRodney W. Grimes 
23385eeca35SAlan Cox static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
234449c2e92SKonstantin Belousov static boolean_t vm_pageout_launder(struct vm_pagequeue *pq, int, vm_paddr_t,
235449c2e92SKonstantin Belousov     vm_paddr_t);
23638efa82bSJohn Dyson #if !defined(NO_SWAPPING)
237ecf6279fSAlan Cox static void vm_pageout_map_deactivate_pages(vm_map_t, long);
238ecf6279fSAlan Cox static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
23997824da3SAlan Cox static void vm_req_vmdaemon(int req);
24038efa82bSJohn Dyson #endif
24185eeca35SAlan Cox static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
242cd41fc12SDavid Greenman 
243a8229fa3SAlan Cox /*
244a8229fa3SAlan Cox  * Initialize a dummy page for marking the caller's place in the specified
245a8229fa3SAlan Cox  * paging queue.  In principle, this function only needs to set the flag
246c7aebda8SAttilio Rao  * PG_MARKER.  Nonetheless, it wirte busies and initializes the hold count
247c7aebda8SAttilio Rao  * to one as safety precautions.
248a8229fa3SAlan Cox  */
2498c616246SKonstantin Belousov static void
2508c616246SKonstantin Belousov vm_pageout_init_marker(vm_page_t marker, u_short queue)
2518c616246SKonstantin Belousov {
2528c616246SKonstantin Belousov 
2538c616246SKonstantin Belousov 	bzero(marker, sizeof(*marker));
254a8229fa3SAlan Cox 	marker->flags = PG_MARKER;
255c7aebda8SAttilio Rao 	marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
2568c616246SKonstantin Belousov 	marker->queue = queue;
257a8229fa3SAlan Cox 	marker->hold_count = 1;
2588c616246SKonstantin Belousov }
2598c616246SKonstantin Belousov 
26026f9a767SRodney W. Grimes /*
2618dbca793STor Egge  * vm_pageout_fallback_object_lock:
2628dbca793STor Egge  *
26389f6b863SAttilio Rao  * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
2648dbca793STor Egge  * known to have failed and page queue must be either PQ_ACTIVE or
2658dbca793STor Egge  * PQ_INACTIVE.  To avoid lock order violation, unlock the page queues
2668dbca793STor Egge  * while locking the vm object.  Use marker page to detect page queue
2678dbca793STor Egge  * changes and maintain notion of next page on page queue.  Return
2688dbca793STor Egge  * TRUE if no changes were detected, FALSE otherwise.  vm object is
2698dbca793STor Egge  * locked on return.
2708dbca793STor Egge  *
2718dbca793STor Egge  * This function depends on both the lock portion of struct vm_object
2728dbca793STor Egge  * and normal struct vm_page being type stable.
2738dbca793STor Egge  */
27485eeca35SAlan Cox static boolean_t
2758dbca793STor Egge vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
2768dbca793STor Egge {
2778dbca793STor Egge 	struct vm_page marker;
2788d220203SAlan Cox 	struct vm_pagequeue *pq;
2798dbca793STor Egge 	boolean_t unchanged;
2808dbca793STor Egge 	u_short queue;
2818dbca793STor Egge 	vm_object_t object;
2828dbca793STor Egge 
2838dbca793STor Egge 	queue = m->queue;
2848c616246SKonstantin Belousov 	vm_pageout_init_marker(&marker, queue);
285449c2e92SKonstantin Belousov 	pq = vm_page_pagequeue(m);
2868dbca793STor Egge 	object = m->object;
2878dbca793STor Egge 
288c325e866SKonstantin Belousov 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
2898d220203SAlan Cox 	vm_pagequeue_unlock(pq);
2902965a453SKip Macy 	vm_page_unlock(m);
29189f6b863SAttilio Rao 	VM_OBJECT_WLOCK(object);
2922965a453SKip Macy 	vm_page_lock(m);
2938d220203SAlan Cox 	vm_pagequeue_lock(pq);
2948dbca793STor Egge 
2958dbca793STor Egge 	/* Page queue might have changed. */
296c325e866SKonstantin Belousov 	*next = TAILQ_NEXT(&marker, plinks.q);
2978dbca793STor Egge 	unchanged = (m->queue == queue &&
2988dbca793STor Egge 		     m->object == object &&
299c325e866SKonstantin Belousov 		     &marker == TAILQ_NEXT(m, plinks.q));
300c325e866SKonstantin Belousov 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
3018dbca793STor Egge 	return (unchanged);
3028dbca793STor Egge }
3038dbca793STor Egge 
3048dbca793STor Egge /*
3058c616246SKonstantin Belousov  * Lock the page while holding the page queue lock.  Use marker page
3068c616246SKonstantin Belousov  * to detect page queue changes and maintain notion of next page on
3078c616246SKonstantin Belousov  * page queue.  Return TRUE if no changes were detected, FALSE
3088c616246SKonstantin Belousov  * otherwise.  The page is locked on return. The page queue lock might
3098c616246SKonstantin Belousov  * be dropped and reacquired.
3108c616246SKonstantin Belousov  *
3118c616246SKonstantin Belousov  * This function depends on normal struct vm_page being type stable.
3128c616246SKonstantin Belousov  */
31385eeca35SAlan Cox static boolean_t
3148c616246SKonstantin Belousov vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
3158c616246SKonstantin Belousov {
3168c616246SKonstantin Belousov 	struct vm_page marker;
3178d220203SAlan Cox 	struct vm_pagequeue *pq;
3188c616246SKonstantin Belousov 	boolean_t unchanged;
3198c616246SKonstantin Belousov 	u_short queue;
3208c616246SKonstantin Belousov 
3218c616246SKonstantin Belousov 	vm_page_lock_assert(m, MA_NOTOWNED);
3228c616246SKonstantin Belousov 	if (vm_page_trylock(m))
3238c616246SKonstantin Belousov 		return (TRUE);
3248c616246SKonstantin Belousov 
3258c616246SKonstantin Belousov 	queue = m->queue;
3268c616246SKonstantin Belousov 	vm_pageout_init_marker(&marker, queue);
327449c2e92SKonstantin Belousov 	pq = vm_page_pagequeue(m);
3288c616246SKonstantin Belousov 
329c325e866SKonstantin Belousov 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
3308d220203SAlan Cox 	vm_pagequeue_unlock(pq);
3318c616246SKonstantin Belousov 	vm_page_lock(m);
3328d220203SAlan Cox 	vm_pagequeue_lock(pq);
3338c616246SKonstantin Belousov 
3348c616246SKonstantin Belousov 	/* Page queue might have changed. */
335c325e866SKonstantin Belousov 	*next = TAILQ_NEXT(&marker, plinks.q);
336c325e866SKonstantin Belousov 	unchanged = (m->queue == queue && &marker == TAILQ_NEXT(m, plinks.q));
337c325e866SKonstantin Belousov 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
3388c616246SKonstantin Belousov 	return (unchanged);
3398c616246SKonstantin Belousov }
3408c616246SKonstantin Belousov 
3418c616246SKonstantin Belousov /*
34226f9a767SRodney W. Grimes  * vm_pageout_clean:
34324a1cce3SDavid Greenman  *
3440d94caffSDavid Greenman  * Clean the page and remove it from the laundry.
34526f9a767SRodney W. Grimes  *
3460d94caffSDavid Greenman  * We set the busy bit to cause potential page faults on this page to
3471c7c3c6aSMatthew Dillon  * block.  Note the careful timing, however, the busy bit isn't set till
3481c7c3c6aSMatthew Dillon  * late and we cannot do anything that will mess with the page.
34926f9a767SRodney W. Grimes  */
3503af76890SPoul-Henning Kamp static int
35134d8b7eaSJeff Roberson vm_pageout_cluster(vm_page_t m)
35224a1cce3SDavid Greenman {
35354d92145SMatthew Dillon 	vm_object_t object;
35491b4f427SAlan Cox 	vm_page_t mc[2*vm_pageout_page_count], pb, ps;
3553562af12SAlan Cox 	int pageout_count;
35690ecac61SMatthew Dillon 	int ib, is, page_base;
357a316d390SJohn Dyson 	vm_pindex_t pindex = m->pindex;
35826f9a767SRodney W. Grimes 
35995976f3fSAlan Cox 	vm_page_lock_assert(m, MA_OWNED);
36017f6a17bSAlan Cox 	object = m->object;
36189f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
3620cddd8f0SMatthew Dillon 
36326f9a767SRodney W. Grimes 	/*
3641c7c3c6aSMatthew Dillon 	 * It doesn't cost us anything to pageout OBJT_DEFAULT or OBJT_SWAP
3651c7c3c6aSMatthew Dillon 	 * with the new swapper, but we could have serious problems paging
3661c7c3c6aSMatthew Dillon 	 * out other object types if there is insufficient memory.
3671c7c3c6aSMatthew Dillon 	 *
3681c7c3c6aSMatthew Dillon 	 * Unfortunately, checking free memory here is far too late, so the
3691c7c3c6aSMatthew Dillon 	 * check has been moved up a procedural level.
3701c7c3c6aSMatthew Dillon 	 */
3711c7c3c6aSMatthew Dillon 
37224a1cce3SDavid Greenman 	/*
3739e897b1bSAlan Cox 	 * Can't clean the page if it's busy or held.
37424a1cce3SDavid Greenman 	 */
375c7aebda8SAttilio Rao 	vm_page_assert_unbusied(m);
37695976f3fSAlan Cox 	KASSERT(m->hold_count == 0, ("vm_pageout_clean: page %p is held", m));
37717f6a17bSAlan Cox 	vm_page_unlock(m);
3780d94caffSDavid Greenman 
37991b4f427SAlan Cox 	mc[vm_pageout_page_count] = pb = ps = m;
38026f9a767SRodney W. Grimes 	pageout_count = 1;
381f35329acSJohn Dyson 	page_base = vm_pageout_page_count;
38290ecac61SMatthew Dillon 	ib = 1;
38390ecac61SMatthew Dillon 	is = 1;
38490ecac61SMatthew Dillon 
38524a1cce3SDavid Greenman 	/*
38624a1cce3SDavid Greenman 	 * Scan object for clusterable pages.
38724a1cce3SDavid Greenman 	 *
38824a1cce3SDavid Greenman 	 * We can cluster ONLY if: ->> the page is NOT
38924a1cce3SDavid Greenman 	 * clean, wired, busy, held, or mapped into a
39024a1cce3SDavid Greenman 	 * buffer, and one of the following:
39124a1cce3SDavid Greenman 	 * 1) The page is inactive, or a seldom used
39224a1cce3SDavid Greenman 	 *    active page.
39324a1cce3SDavid Greenman 	 * -or-
39424a1cce3SDavid Greenman 	 * 2) we force the issue.
39590ecac61SMatthew Dillon 	 *
39690ecac61SMatthew Dillon 	 * During heavy mmap/modification loads the pageout
39790ecac61SMatthew Dillon 	 * daemon can really fragment the underlying file
39890ecac61SMatthew Dillon 	 * due to flushing pages out of order and not trying
39990ecac61SMatthew Dillon 	 * align the clusters (which leave sporatic out-of-order
40090ecac61SMatthew Dillon 	 * holes).  To solve this problem we do the reverse scan
40190ecac61SMatthew Dillon 	 * first and attempt to align our cluster, then do a
40290ecac61SMatthew Dillon 	 * forward scan if room remains.
40324a1cce3SDavid Greenman 	 */
40490ecac61SMatthew Dillon more:
40590ecac61SMatthew Dillon 	while (ib && pageout_count < vm_pageout_page_count) {
40624a1cce3SDavid Greenman 		vm_page_t p;
407f6b04d2bSDavid Greenman 
40890ecac61SMatthew Dillon 		if (ib > pindex) {
40990ecac61SMatthew Dillon 			ib = 0;
41090ecac61SMatthew Dillon 			break;
411f6b04d2bSDavid Greenman 		}
41290ecac61SMatthew Dillon 
413c7aebda8SAttilio Rao 		if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
41490ecac61SMatthew Dillon 			ib = 0;
41590ecac61SMatthew Dillon 			break;
416f6b04d2bSDavid Greenman 		}
41724a1cce3SDavid Greenman 		vm_page_test_dirty(p);
418eb5d3969SAlan Cox 		if (p->dirty == 0) {
419eb5d3969SAlan Cox 			ib = 0;
420eb5d3969SAlan Cox 			break;
421eb5d3969SAlan Cox 		}
422eb5d3969SAlan Cox 		vm_page_lock(p);
423eb5d3969SAlan Cox 		if (p->queue != PQ_INACTIVE ||
42457601bcbSMatthew Dillon 		    p->hold_count != 0) {	/* may be undergoing I/O */
4252965a453SKip Macy 			vm_page_unlock(p);
42690ecac61SMatthew Dillon 			ib = 0;
42724a1cce3SDavid Greenman 			break;
428f6b04d2bSDavid Greenman 		}
4292965a453SKip Macy 		vm_page_unlock(p);
43091b4f427SAlan Cox 		mc[--page_base] = pb = p;
43190ecac61SMatthew Dillon 		++pageout_count;
43290ecac61SMatthew Dillon 		++ib;
43324a1cce3SDavid Greenman 		/*
43490ecac61SMatthew Dillon 		 * alignment boundry, stop here and switch directions.  Do
43590ecac61SMatthew Dillon 		 * not clear ib.
43624a1cce3SDavid Greenman 		 */
43790ecac61SMatthew Dillon 		if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
43890ecac61SMatthew Dillon 			break;
43924a1cce3SDavid Greenman 	}
44090ecac61SMatthew Dillon 
44190ecac61SMatthew Dillon 	while (pageout_count < vm_pageout_page_count &&
44290ecac61SMatthew Dillon 	    pindex + is < object->size) {
44390ecac61SMatthew Dillon 		vm_page_t p;
44490ecac61SMatthew Dillon 
445c7aebda8SAttilio Rao 		if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
44690ecac61SMatthew Dillon 			break;
44724a1cce3SDavid Greenman 		vm_page_test_dirty(p);
448eb5d3969SAlan Cox 		if (p->dirty == 0)
449eb5d3969SAlan Cox 			break;
450eb5d3969SAlan Cox 		vm_page_lock(p);
451eb5d3969SAlan Cox 		if (p->queue != PQ_INACTIVE ||
45257601bcbSMatthew Dillon 		    p->hold_count != 0) {	/* may be undergoing I/O */
4532965a453SKip Macy 			vm_page_unlock(p);
45424a1cce3SDavid Greenman 			break;
45524a1cce3SDavid Greenman 		}
4562965a453SKip Macy 		vm_page_unlock(p);
45791b4f427SAlan Cox 		mc[page_base + pageout_count] = ps = p;
45890ecac61SMatthew Dillon 		++pageout_count;
45990ecac61SMatthew Dillon 		++is;
46024a1cce3SDavid Greenman 	}
46190ecac61SMatthew Dillon 
46290ecac61SMatthew Dillon 	/*
46390ecac61SMatthew Dillon 	 * If we exhausted our forward scan, continue with the reverse scan
46490ecac61SMatthew Dillon 	 * when possible, even past a page boundry.  This catches boundry
46590ecac61SMatthew Dillon 	 * conditions.
46690ecac61SMatthew Dillon 	 */
46790ecac61SMatthew Dillon 	if (ib && pageout_count < vm_pageout_page_count)
46890ecac61SMatthew Dillon 		goto more;
469f6b04d2bSDavid Greenman 
47067bf6868SJohn Dyson 	/*
47167bf6868SJohn Dyson 	 * we allow reads during pageouts...
47267bf6868SJohn Dyson 	 */
473126d6082SKonstantin Belousov 	return (vm_pageout_flush(&mc[page_base], pageout_count, 0, 0, NULL,
474126d6082SKonstantin Belousov 	    NULL));
475aef922f5SJohn Dyson }
476aef922f5SJohn Dyson 
4771c7c3c6aSMatthew Dillon /*
4781c7c3c6aSMatthew Dillon  * vm_pageout_flush() - launder the given pages
4791c7c3c6aSMatthew Dillon  *
4801c7c3c6aSMatthew Dillon  *	The given pages are laundered.  Note that we setup for the start of
4811c7c3c6aSMatthew Dillon  *	I/O ( i.e. busy the page ), mark it read-only, and bump the object
4821c7c3c6aSMatthew Dillon  *	reference count all in here rather then in the parent.  If we want
4831c7c3c6aSMatthew Dillon  *	the parent to do more sophisticated things we may have to change
4841c7c3c6aSMatthew Dillon  *	the ordering.
4851e8a675cSKonstantin Belousov  *
4861e8a675cSKonstantin Belousov  *	Returned runlen is the count of pages between mreq and first
4871e8a675cSKonstantin Belousov  *	page after mreq with status VM_PAGER_AGAIN.
488126d6082SKonstantin Belousov  *	*eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
489126d6082SKonstantin Belousov  *	for any page in runlen set.
4901c7c3c6aSMatthew Dillon  */
491aef922f5SJohn Dyson int
492126d6082SKonstantin Belousov vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
493126d6082SKonstantin Belousov     boolean_t *eio)
494aef922f5SJohn Dyson {
4952e3b314dSAlan Cox 	vm_object_t object = mc[0]->object;
496aef922f5SJohn Dyson 	int pageout_status[count];
49795461b45SJohn Dyson 	int numpagedout = 0;
4981e8a675cSKonstantin Belousov 	int i, runlen;
499aef922f5SJohn Dyson 
50089f6b863SAttilio Rao 	VM_OBJECT_ASSERT_WLOCKED(object);
5017bec141bSKip Macy 
5021c7c3c6aSMatthew Dillon 	/*
5031c7c3c6aSMatthew Dillon 	 * Initiate I/O.  Bump the vm_page_t->busy counter and
5041c7c3c6aSMatthew Dillon 	 * mark the pages read-only.
5051c7c3c6aSMatthew Dillon 	 *
5061c7c3c6aSMatthew Dillon 	 * We do not have to fixup the clean/dirty bits here... we can
5071c7c3c6aSMatthew Dillon 	 * allow the pager to do it after the I/O completes.
50802fa91d3SMatthew Dillon 	 *
50902fa91d3SMatthew Dillon 	 * NOTE! mc[i]->dirty may be partial or fragmented due to an
51002fa91d3SMatthew Dillon 	 * edge case with file fragments.
5111c7c3c6aSMatthew Dillon 	 */
5128f9110f6SJohn Dyson 	for (i = 0; i < count; i++) {
5137a935082SAlan Cox 		KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
5147a935082SAlan Cox 		    ("vm_pageout_flush: partially invalid page %p index %d/%d",
5157a935082SAlan Cox 			mc[i], i, count));
516c7aebda8SAttilio Rao 		vm_page_sbusy(mc[i]);
51778985e42SAlan Cox 		pmap_remove_write(mc[i]);
5182965a453SKip Macy 	}
519d474eaaaSDoug Rabson 	vm_object_pip_add(object, count);
520aef922f5SJohn Dyson 
521d076fbeaSAlan Cox 	vm_pager_put_pages(object, mc, count, flags, pageout_status);
52226f9a767SRodney W. Grimes 
5231e8a675cSKonstantin Belousov 	runlen = count - mreq;
524126d6082SKonstantin Belousov 	if (eio != NULL)
525126d6082SKonstantin Belousov 		*eio = FALSE;
526aef922f5SJohn Dyson 	for (i = 0; i < count; i++) {
527aef922f5SJohn Dyson 		vm_page_t mt = mc[i];
52824a1cce3SDavid Greenman 
5294cd45723SAlan Cox 		KASSERT(pageout_status[i] == VM_PAGER_PEND ||
5306031c68dSAlan Cox 		    !pmap_page_is_write_mapped(mt),
5319ea8d1a6SAlan Cox 		    ("vm_pageout_flush: page %p is not write protected", mt));
53226f9a767SRodney W. Grimes 		switch (pageout_status[i]) {
53326f9a767SRodney W. Grimes 		case VM_PAGER_OK:
53426f9a767SRodney W. Grimes 		case VM_PAGER_PEND:
53595461b45SJohn Dyson 			numpagedout++;
53626f9a767SRodney W. Grimes 			break;
53726f9a767SRodney W. Grimes 		case VM_PAGER_BAD:
53826f9a767SRodney W. Grimes 			/*
5390d94caffSDavid Greenman 			 * Page outside of range of object. Right now we
5400d94caffSDavid Greenman 			 * essentially lose the changes by pretending it
5410d94caffSDavid Greenman 			 * worked.
54226f9a767SRodney W. Grimes 			 */
54390ecac61SMatthew Dillon 			vm_page_undirty(mt);
54426f9a767SRodney W. Grimes 			break;
54526f9a767SRodney W. Grimes 		case VM_PAGER_ERROR:
54626f9a767SRodney W. Grimes 		case VM_PAGER_FAIL:
54726f9a767SRodney W. Grimes 			/*
5480d94caffSDavid Greenman 			 * If page couldn't be paged out, then reactivate the
5490d94caffSDavid Greenman 			 * page so it doesn't clog the inactive list.  (We
5500d94caffSDavid Greenman 			 * will try paging out it again later).
55126f9a767SRodney W. Grimes 			 */
5523c4a2440SAlan Cox 			vm_page_lock(mt);
55324a1cce3SDavid Greenman 			vm_page_activate(mt);
5543c4a2440SAlan Cox 			vm_page_unlock(mt);
555126d6082SKonstantin Belousov 			if (eio != NULL && i >= mreq && i - mreq < runlen)
556126d6082SKonstantin Belousov 				*eio = TRUE;
55726f9a767SRodney W. Grimes 			break;
55826f9a767SRodney W. Grimes 		case VM_PAGER_AGAIN:
5591e8a675cSKonstantin Belousov 			if (i >= mreq && i - mreq < runlen)
5601e8a675cSKonstantin Belousov 				runlen = i - mreq;
56126f9a767SRodney W. Grimes 			break;
56226f9a767SRodney W. Grimes 		}
56326f9a767SRodney W. Grimes 
56426f9a767SRodney W. Grimes 		/*
5650d94caffSDavid Greenman 		 * If the operation is still going, leave the page busy to
5660d94caffSDavid Greenman 		 * block all other accesses. Also, leave the paging in
5670d94caffSDavid Greenman 		 * progress indicator set so that we don't attempt an object
5680d94caffSDavid Greenman 		 * collapse.
56926f9a767SRodney W. Grimes 		 */
57026f9a767SRodney W. Grimes 		if (pageout_status[i] != VM_PAGER_PEND) {
571f919ebdeSDavid Greenman 			vm_object_pip_wakeup(object);
572c7aebda8SAttilio Rao 			vm_page_sunbusy(mt);
5733c4a2440SAlan Cox 		}
5743c4a2440SAlan Cox 	}
5751e8a675cSKonstantin Belousov 	if (prunlen != NULL)
5761e8a675cSKonstantin Belousov 		*prunlen = runlen;
5773c4a2440SAlan Cox 	return (numpagedout);
57826f9a767SRodney W. Grimes }
57926f9a767SRodney W. Grimes 
58085eeca35SAlan Cox static boolean_t
581449c2e92SKonstantin Belousov vm_pageout_launder(struct vm_pagequeue *pq, int tries, vm_paddr_t low,
582449c2e92SKonstantin Belousov     vm_paddr_t high)
58385eeca35SAlan Cox {
58485eeca35SAlan Cox 	struct mount *mp;
58585eeca35SAlan Cox 	struct vnode *vp;
58685eeca35SAlan Cox 	vm_object_t object;
58785eeca35SAlan Cox 	vm_paddr_t pa;
58885eeca35SAlan Cox 	vm_page_t m, m_tmp, next;
5891bd7d0b7SKonstantin Belousov 	int lockmode;
59085eeca35SAlan Cox 
5918d220203SAlan Cox 	vm_pagequeue_lock(pq);
592c325e866SKonstantin Belousov 	TAILQ_FOREACH_SAFE(m, &pq->pq_pl, plinks.q, next) {
59385eeca35SAlan Cox 		if ((m->flags & PG_MARKER) != 0)
59485eeca35SAlan Cox 			continue;
59585eeca35SAlan Cox 		pa = VM_PAGE_TO_PHYS(m);
59685eeca35SAlan Cox 		if (pa < low || pa + PAGE_SIZE > high)
59785eeca35SAlan Cox 			continue;
59885eeca35SAlan Cox 		if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
59985eeca35SAlan Cox 			vm_page_unlock(m);
60085eeca35SAlan Cox 			continue;
60185eeca35SAlan Cox 		}
60285eeca35SAlan Cox 		object = m->object;
60389f6b863SAttilio Rao 		if ((!VM_OBJECT_TRYWLOCK(object) &&
60485eeca35SAlan Cox 		    (!vm_pageout_fallback_object_lock(m, &next) ||
605c7aebda8SAttilio Rao 		    m->hold_count != 0)) || vm_page_busied(m)) {
60685eeca35SAlan Cox 			vm_page_unlock(m);
60789f6b863SAttilio Rao 			VM_OBJECT_WUNLOCK(object);
60885eeca35SAlan Cox 			continue;
60985eeca35SAlan Cox 		}
61085eeca35SAlan Cox 		vm_page_test_dirty(m);
6119fc4739dSAlan Cox 		if (m->dirty == 0 && object->ref_count != 0)
61285eeca35SAlan Cox 			pmap_remove_all(m);
61385eeca35SAlan Cox 		if (m->dirty != 0) {
61485eeca35SAlan Cox 			vm_page_unlock(m);
61585eeca35SAlan Cox 			if (tries == 0 || (object->flags & OBJ_DEAD) != 0) {
61689f6b863SAttilio Rao 				VM_OBJECT_WUNLOCK(object);
61785eeca35SAlan Cox 				continue;
61885eeca35SAlan Cox 			}
61985eeca35SAlan Cox 			if (object->type == OBJT_VNODE) {
6208d220203SAlan Cox 				vm_pagequeue_unlock(pq);
62185eeca35SAlan Cox 				vp = object->handle;
62285eeca35SAlan Cox 				vm_object_reference_locked(object);
62389f6b863SAttilio Rao 				VM_OBJECT_WUNLOCK(object);
62485eeca35SAlan Cox 				(void)vn_start_write(vp, &mp, V_WAIT);
6251bd7d0b7SKonstantin Belousov 				lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
6261bd7d0b7SKonstantin Belousov 				    LK_SHARED : LK_EXCLUSIVE;
6271bd7d0b7SKonstantin Belousov 				vn_lock(vp, lockmode | LK_RETRY);
62889f6b863SAttilio Rao 				VM_OBJECT_WLOCK(object);
62985eeca35SAlan Cox 				vm_object_page_clean(object, 0, 0, OBJPC_SYNC);
63089f6b863SAttilio Rao 				VM_OBJECT_WUNLOCK(object);
63185eeca35SAlan Cox 				VOP_UNLOCK(vp, 0);
63285eeca35SAlan Cox 				vm_object_deallocate(object);
63385eeca35SAlan Cox 				vn_finished_write(mp);
63485eeca35SAlan Cox 				return (TRUE);
63585eeca35SAlan Cox 			} else if (object->type == OBJT_SWAP ||
63685eeca35SAlan Cox 			    object->type == OBJT_DEFAULT) {
6378d220203SAlan Cox 				vm_pagequeue_unlock(pq);
63885eeca35SAlan Cox 				m_tmp = m;
63985eeca35SAlan Cox 				vm_pageout_flush(&m_tmp, 1, VM_PAGER_PUT_SYNC,
64085eeca35SAlan Cox 				    0, NULL, NULL);
64189f6b863SAttilio Rao 				VM_OBJECT_WUNLOCK(object);
64285eeca35SAlan Cox 				return (TRUE);
64385eeca35SAlan Cox 			}
64485eeca35SAlan Cox 		} else {
6458d220203SAlan Cox 			/*
6468d220203SAlan Cox 			 * Dequeue here to prevent lock recursion in
6478d220203SAlan Cox 			 * vm_page_cache().
6488d220203SAlan Cox 			 */
6498d220203SAlan Cox 			vm_page_dequeue_locked(m);
65085eeca35SAlan Cox 			vm_page_cache(m);
65185eeca35SAlan Cox 			vm_page_unlock(m);
65285eeca35SAlan Cox 		}
65389f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
65485eeca35SAlan Cox 	}
6558d220203SAlan Cox 	vm_pagequeue_unlock(pq);
65685eeca35SAlan Cox 	return (FALSE);
65785eeca35SAlan Cox }
65885eeca35SAlan Cox 
65985eeca35SAlan Cox /*
66085eeca35SAlan Cox  * Increase the number of cached pages.  The specified value, "tries",
66185eeca35SAlan Cox  * determines which categories of pages are cached:
66285eeca35SAlan Cox  *
66385eeca35SAlan Cox  *  0: All clean, inactive pages within the specified physical address range
66485eeca35SAlan Cox  *     are cached.  Will not sleep.
66585eeca35SAlan Cox  *  1: The vm_lowmem handlers are called.  All inactive pages within
66685eeca35SAlan Cox  *     the specified physical address range are cached.  May sleep.
66785eeca35SAlan Cox  *  2: The vm_lowmem handlers are called.  All inactive and active pages
66885eeca35SAlan Cox  *     within the specified physical address range are cached.  May sleep.
66985eeca35SAlan Cox  */
67085eeca35SAlan Cox void
67185eeca35SAlan Cox vm_pageout_grow_cache(int tries, vm_paddr_t low, vm_paddr_t high)
67285eeca35SAlan Cox {
673449c2e92SKonstantin Belousov 	int actl, actmax, inactl, inactmax, dom, initial_dom;
674449c2e92SKonstantin Belousov 	static int start_dom = 0;
67585eeca35SAlan Cox 
67685eeca35SAlan Cox 	if (tries > 0) {
67785eeca35SAlan Cox 		/*
67885eeca35SAlan Cox 		 * Decrease registered cache sizes.  The vm_lowmem handlers
67985eeca35SAlan Cox 		 * may acquire locks and/or sleep, so they can only be invoked
68085eeca35SAlan Cox 		 * when "tries" is greater than zero.
68185eeca35SAlan Cox 		 */
68214a0d74eSSteven Hartland 		SDT_PROBE0(vm, , , vm__lowmem_cache);
68385eeca35SAlan Cox 		EVENTHANDLER_INVOKE(vm_lowmem, 0);
68485eeca35SAlan Cox 
68585eeca35SAlan Cox 		/*
68685eeca35SAlan Cox 		 * We do this explicitly after the caches have been drained
68785eeca35SAlan Cox 		 * above.
68885eeca35SAlan Cox 		 */
68985eeca35SAlan Cox 		uma_reclaim();
69085eeca35SAlan Cox 	}
691449c2e92SKonstantin Belousov 
692449c2e92SKonstantin Belousov 	/*
693449c2e92SKonstantin Belousov 	 * Make the next scan start on the next domain.
694449c2e92SKonstantin Belousov 	 */
695449c2e92SKonstantin Belousov 	initial_dom = atomic_fetchadd_int(&start_dom, 1) % vm_ndomains;
696449c2e92SKonstantin Belousov 
69785eeca35SAlan Cox 	inactl = 0;
69844f1c916SBryan Drewery 	inactmax = vm_cnt.v_inactive_count;
69985eeca35SAlan Cox 	actl = 0;
70044f1c916SBryan Drewery 	actmax = tries < 2 ? 0 : vm_cnt.v_active_count;
701449c2e92SKonstantin Belousov 	dom = initial_dom;
702449c2e92SKonstantin Belousov 
703449c2e92SKonstantin Belousov 	/*
704449c2e92SKonstantin Belousov 	 * Scan domains in round-robin order, first inactive queues,
705449c2e92SKonstantin Belousov 	 * then active.  Since domain usually owns large physically
706449c2e92SKonstantin Belousov 	 * contiguous chunk of memory, it makes sense to completely
707449c2e92SKonstantin Belousov 	 * exhaust one domain before switching to next, while growing
708449c2e92SKonstantin Belousov 	 * the pool of contiguous physical pages.
709449c2e92SKonstantin Belousov 	 *
710449c2e92SKonstantin Belousov 	 * Do not even start launder a domain which cannot contain
711449c2e92SKonstantin Belousov 	 * the specified address range, as indicated by segments
712449c2e92SKonstantin Belousov 	 * constituting the domain.
713449c2e92SKonstantin Belousov 	 */
71485eeca35SAlan Cox again:
715449c2e92SKonstantin Belousov 	if (inactl < inactmax) {
716449c2e92SKonstantin Belousov 		if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
717449c2e92SKonstantin Belousov 		    low, high) &&
718449c2e92SKonstantin Belousov 		    vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_INACTIVE],
719449c2e92SKonstantin Belousov 		    tries, low, high)) {
72085eeca35SAlan Cox 			inactl++;
72185eeca35SAlan Cox 			goto again;
72285eeca35SAlan Cox 		}
723449c2e92SKonstantin Belousov 		if (++dom == vm_ndomains)
724449c2e92SKonstantin Belousov 			dom = 0;
725449c2e92SKonstantin Belousov 		if (dom != initial_dom)
726449c2e92SKonstantin Belousov 			goto again;
727449c2e92SKonstantin Belousov 	}
728449c2e92SKonstantin Belousov 	if (actl < actmax) {
729449c2e92SKonstantin Belousov 		if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
730449c2e92SKonstantin Belousov 		    low, high) &&
731449c2e92SKonstantin Belousov 		    vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_ACTIVE],
732449c2e92SKonstantin Belousov 		      tries, low, high)) {
73385eeca35SAlan Cox 			actl++;
73485eeca35SAlan Cox 			goto again;
73585eeca35SAlan Cox 		}
736449c2e92SKonstantin Belousov 		if (++dom == vm_ndomains)
737449c2e92SKonstantin Belousov 			dom = 0;
738449c2e92SKonstantin Belousov 		if (dom != initial_dom)
739449c2e92SKonstantin Belousov 			goto again;
740449c2e92SKonstantin Belousov 	}
74185eeca35SAlan Cox }
74285eeca35SAlan Cox 
74338efa82bSJohn Dyson #if !defined(NO_SWAPPING)
74426f9a767SRodney W. Grimes /*
74526f9a767SRodney W. Grimes  *	vm_pageout_object_deactivate_pages
74626f9a767SRodney W. Grimes  *
747ce186587SAlan Cox  *	Deactivate enough pages to satisfy the inactive target
748ce186587SAlan Cox  *	requirements.
74926f9a767SRodney W. Grimes  *
75026f9a767SRodney W. Grimes  *	The object and map must be locked.
75126f9a767SRodney W. Grimes  */
75238efa82bSJohn Dyson static void
753ce186587SAlan Cox vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
754ce186587SAlan Cox     long desired)
75526f9a767SRodney W. Grimes {
756ecf6279fSAlan Cox 	vm_object_t backing_object, object;
757ce186587SAlan Cox 	vm_page_t p;
758bb7858eaSJeff Roberson 	int act_delta, remove_mode;
75926f9a767SRodney W. Grimes 
760e23b0a19SAlan Cox 	VM_OBJECT_ASSERT_LOCKED(first_object);
76128634820SAlan Cox 	if ((first_object->flags & OBJ_FICTITIOUS) != 0)
76238efa82bSJohn Dyson 		return;
763ecf6279fSAlan Cox 	for (object = first_object;; object = backing_object) {
764ecf6279fSAlan Cox 		if (pmap_resident_count(pmap) <= desired)
765ecf6279fSAlan Cox 			goto unlock_return;
766e23b0a19SAlan Cox 		VM_OBJECT_ASSERT_LOCKED(object);
76728634820SAlan Cox 		if ((object->flags & OBJ_UNMANAGED) != 0 ||
76828634820SAlan Cox 		    object->paging_in_progress != 0)
769ecf6279fSAlan Cox 			goto unlock_return;
77026f9a767SRodney W. Grimes 
77185b1dc89SAlan Cox 		remove_mode = 0;
77238efa82bSJohn Dyson 		if (object->shadow_count > 1)
77338efa82bSJohn Dyson 			remove_mode = 1;
77426f9a767SRodney W. Grimes 		/*
775ce186587SAlan Cox 		 * Scan the object's entire memory queue.
77626f9a767SRodney W. Grimes 		 */
777ce186587SAlan Cox 		TAILQ_FOREACH(p, &object->memq, listq) {
778447fe2a4SAlan Cox 			if (pmap_resident_count(pmap) <= desired)
779447fe2a4SAlan Cox 				goto unlock_return;
780c7aebda8SAttilio Rao 			if (vm_page_busied(p))
781447fe2a4SAlan Cox 				continue;
782ce186587SAlan Cox 			PCPU_INC(cnt.v_pdpages);
7832965a453SKip Macy 			vm_page_lock(p);
784ce186587SAlan Cox 			if (p->wire_count != 0 || p->hold_count != 0 ||
785ecf6279fSAlan Cox 			    !pmap_page_exists_quick(pmap, p)) {
7862965a453SKip Macy 				vm_page_unlock(p);
7870d94caffSDavid Greenman 				continue;
7880d94caffSDavid Greenman 			}
789bb7858eaSJeff Roberson 			act_delta = pmap_ts_referenced(p);
7903407fefeSKonstantin Belousov 			if ((p->aflags & PGA_REFERENCED) != 0) {
791bb7858eaSJeff Roberson 				if (act_delta == 0)
792bb7858eaSJeff Roberson 					act_delta = 1;
7933407fefeSKonstantin Belousov 				vm_page_aflag_clear(p, PGA_REFERENCED);
794ef743ce6SJohn Dyson 			}
795bb7858eaSJeff Roberson 			if (p->queue != PQ_ACTIVE && act_delta != 0) {
796ef743ce6SJohn Dyson 				vm_page_activate(p);
797bb7858eaSJeff Roberson 				p->act_count += act_delta;
798c8c4b40cSJohn Dyson 			} else if (p->queue == PQ_ACTIVE) {
799bb7858eaSJeff Roberson 				if (act_delta == 0) {
800ce186587SAlan Cox 					p->act_count -= min(p->act_count,
801ce186587SAlan Cox 					    ACT_DECLINE);
80290776bd7SJeff Roberson 					if (!remove_mode && p->act_count == 0) {
8034fec79beSAlan Cox 						pmap_remove_all(p);
80426f9a767SRodney W. Grimes 						vm_page_deactivate(p);
8058d220203SAlan Cox 					} else
8068d220203SAlan Cox 						vm_page_requeue(p);
807c8c4b40cSJohn Dyson 				} else {
808eaf13dd7SJohn Dyson 					vm_page_activate(p);
809ce186587SAlan Cox 					if (p->act_count < ACT_MAX -
810ce186587SAlan Cox 					    ACT_ADVANCE)
81138efa82bSJohn Dyson 						p->act_count += ACT_ADVANCE;
8128d220203SAlan Cox 					vm_page_requeue(p);
813ce186587SAlan Cox 				}
814ce186587SAlan Cox 			} else if (p->queue == PQ_INACTIVE)
815ce186587SAlan Cox 				pmap_remove_all(p);
8162965a453SKip Macy 			vm_page_unlock(p);
81726f9a767SRodney W. Grimes 		}
818ecf6279fSAlan Cox 		if ((backing_object = object->backing_object) == NULL)
819ecf6279fSAlan Cox 			goto unlock_return;
820e23b0a19SAlan Cox 		VM_OBJECT_RLOCK(backing_object);
821ecf6279fSAlan Cox 		if (object != first_object)
822e23b0a19SAlan Cox 			VM_OBJECT_RUNLOCK(object);
82338efa82bSJohn Dyson 	}
824ecf6279fSAlan Cox unlock_return:
825ecf6279fSAlan Cox 	if (object != first_object)
826e23b0a19SAlan Cox 		VM_OBJECT_RUNLOCK(object);
82726f9a767SRodney W. Grimes }
82826f9a767SRodney W. Grimes 
82926f9a767SRodney W. Grimes /*
83026f9a767SRodney W. Grimes  * deactivate some number of pages in a map, try to do it fairly, but
83126f9a767SRodney W. Grimes  * that is really hard to do.
83226f9a767SRodney W. Grimes  */
833cd41fc12SDavid Greenman static void
83438efa82bSJohn Dyson vm_pageout_map_deactivate_pages(map, desired)
83526f9a767SRodney W. Grimes 	vm_map_t map;
836ecf6279fSAlan Cox 	long desired;
83726f9a767SRodney W. Grimes {
83826f9a767SRodney W. Grimes 	vm_map_entry_t tmpe;
83938efa82bSJohn Dyson 	vm_object_t obj, bigobj;
84030105b9eSTor Egge 	int nothingwired;
8410d94caffSDavid Greenman 
842d974f03cSAlan Cox 	if (!vm_map_trylock(map))
84326f9a767SRodney W. Grimes 		return;
84438efa82bSJohn Dyson 
84538efa82bSJohn Dyson 	bigobj = NULL;
84630105b9eSTor Egge 	nothingwired = TRUE;
84738efa82bSJohn Dyson 
84838efa82bSJohn Dyson 	/*
84938efa82bSJohn Dyson 	 * first, search out the biggest object, and try to free pages from
85038efa82bSJohn Dyson 	 * that.
85138efa82bSJohn Dyson 	 */
85226f9a767SRodney W. Grimes 	tmpe = map->header.next;
85338efa82bSJohn Dyson 	while (tmpe != &map->header) {
8549fdfe602SMatthew Dillon 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
85538efa82bSJohn Dyson 			obj = tmpe->object.vm_object;
856e23b0a19SAlan Cox 			if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
8570774dfb3SAlan Cox 				if (obj->shadow_count <= 1 &&
8580774dfb3SAlan Cox 				    (bigobj == NULL ||
8590774dfb3SAlan Cox 				     bigobj->resident_page_count < obj->resident_page_count)) {
8600774dfb3SAlan Cox 					if (bigobj != NULL)
861e23b0a19SAlan Cox 						VM_OBJECT_RUNLOCK(bigobj);
86238efa82bSJohn Dyson 					bigobj = obj;
8630774dfb3SAlan Cox 				} else
864e23b0a19SAlan Cox 					VM_OBJECT_RUNLOCK(obj);
86538efa82bSJohn Dyson 			}
86638efa82bSJohn Dyson 		}
86730105b9eSTor Egge 		if (tmpe->wired_count > 0)
86830105b9eSTor Egge 			nothingwired = FALSE;
86938efa82bSJohn Dyson 		tmpe = tmpe->next;
87038efa82bSJohn Dyson 	}
87138efa82bSJohn Dyson 
8720774dfb3SAlan Cox 	if (bigobj != NULL) {
873ecf6279fSAlan Cox 		vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
874e23b0a19SAlan Cox 		VM_OBJECT_RUNLOCK(bigobj);
8750774dfb3SAlan Cox 	}
87638efa82bSJohn Dyson 	/*
87738efa82bSJohn Dyson 	 * Next, hunt around for other pages to deactivate.  We actually
87838efa82bSJohn Dyson 	 * do this search sort of wrong -- .text first is not the best idea.
87938efa82bSJohn Dyson 	 */
88038efa82bSJohn Dyson 	tmpe = map->header.next;
88138efa82bSJohn Dyson 	while (tmpe != &map->header) {
882b1028ad1SLuoqi Chen 		if (pmap_resident_count(vm_map_pmap(map)) <= desired)
88338efa82bSJohn Dyson 			break;
8849fdfe602SMatthew Dillon 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
88538efa82bSJohn Dyson 			obj = tmpe->object.vm_object;
8860774dfb3SAlan Cox 			if (obj != NULL) {
887e23b0a19SAlan Cox 				VM_OBJECT_RLOCK(obj);
888ecf6279fSAlan Cox 				vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
889e23b0a19SAlan Cox 				VM_OBJECT_RUNLOCK(obj);
8900774dfb3SAlan Cox 			}
89138efa82bSJohn Dyson 		}
89226f9a767SRodney W. Grimes 		tmpe = tmpe->next;
89338857e7fSAlan Cox 	}
89438efa82bSJohn Dyson 
89538efa82bSJohn Dyson 	/*
89638efa82bSJohn Dyson 	 * Remove all mappings if a process is swapped out, this will free page
89738efa82bSJohn Dyson 	 * table pages.
89838efa82bSJohn Dyson 	 */
89938857e7fSAlan Cox 	if (desired == 0 && nothingwired) {
9008d01a3b2SNathan Whitehorn 		pmap_remove(vm_map_pmap(map), vm_map_min(map),
9018d01a3b2SNathan Whitehorn 		    vm_map_max(map));
90238857e7fSAlan Cox 	}
903938b0f5bSMarcel Moolenaar 
90438efa82bSJohn Dyson 	vm_map_unlock(map);
90526f9a767SRodney W. Grimes }
906a1287949SEivind Eklund #endif		/* !defined(NO_SWAPPING) */
907df8bae1dSRodney W. Grimes 
9081c7c3c6aSMatthew Dillon /*
90934d8b7eaSJeff Roberson  * Attempt to acquire all of the necessary locks to launder a page and
91034d8b7eaSJeff Roberson  * then call through the clustering layer to PUTPAGES.  Wait a short
91134d8b7eaSJeff Roberson  * time for a vnode lock.
91234d8b7eaSJeff Roberson  *
91334d8b7eaSJeff Roberson  * Requires the page and object lock on entry, releases both before return.
91434d8b7eaSJeff Roberson  * Returns 0 on success and an errno otherwise.
91534d8b7eaSJeff Roberson  */
91634d8b7eaSJeff Roberson static int
91734d8b7eaSJeff Roberson vm_pageout_clean(vm_page_t m)
91834d8b7eaSJeff Roberson {
91934d8b7eaSJeff Roberson 	struct vnode *vp;
92034d8b7eaSJeff Roberson 	struct mount *mp;
92134d8b7eaSJeff Roberson 	vm_object_t object;
92234d8b7eaSJeff Roberson 	vm_pindex_t pindex;
92334d8b7eaSJeff Roberson 	int error, lockmode;
92434d8b7eaSJeff Roberson 
92534d8b7eaSJeff Roberson 	vm_page_assert_locked(m);
92634d8b7eaSJeff Roberson 	object = m->object;
92734d8b7eaSJeff Roberson 	VM_OBJECT_ASSERT_WLOCKED(object);
92834d8b7eaSJeff Roberson 	error = 0;
92934d8b7eaSJeff Roberson 	vp = NULL;
93034d8b7eaSJeff Roberson 	mp = NULL;
93134d8b7eaSJeff Roberson 
93234d8b7eaSJeff Roberson 	/*
93334d8b7eaSJeff Roberson 	 * The object is already known NOT to be dead.   It
93434d8b7eaSJeff Roberson 	 * is possible for the vget() to block the whole
93534d8b7eaSJeff Roberson 	 * pageout daemon, but the new low-memory handling
93634d8b7eaSJeff Roberson 	 * code should prevent it.
93734d8b7eaSJeff Roberson 	 *
93834d8b7eaSJeff Roberson 	 * We can't wait forever for the vnode lock, we might
93934d8b7eaSJeff Roberson 	 * deadlock due to a vn_read() getting stuck in
94034d8b7eaSJeff Roberson 	 * vm_wait while holding this vnode.  We skip the
94134d8b7eaSJeff Roberson 	 * vnode if we can't get it in a reasonable amount
94234d8b7eaSJeff Roberson 	 * of time.
94334d8b7eaSJeff Roberson 	 */
94434d8b7eaSJeff Roberson 	if (object->type == OBJT_VNODE) {
94534d8b7eaSJeff Roberson 		vm_page_unlock(m);
94634d8b7eaSJeff Roberson 		vp = object->handle;
94734d8b7eaSJeff Roberson 		if (vp->v_type == VREG &&
94834d8b7eaSJeff Roberson 		    vn_start_write(vp, &mp, V_NOWAIT) != 0) {
94934d8b7eaSJeff Roberson 			mp = NULL;
95034d8b7eaSJeff Roberson 			error = EDEADLK;
95134d8b7eaSJeff Roberson 			goto unlock_all;
95234d8b7eaSJeff Roberson 		}
95334d8b7eaSJeff Roberson 		KASSERT(mp != NULL,
95434d8b7eaSJeff Roberson 		    ("vp %p with NULL v_mount", vp));
95534d8b7eaSJeff Roberson 		vm_object_reference_locked(object);
95634d8b7eaSJeff Roberson 		pindex = m->pindex;
95734d8b7eaSJeff Roberson 		VM_OBJECT_WUNLOCK(object);
95834d8b7eaSJeff Roberson 		lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
95934d8b7eaSJeff Roberson 		    LK_SHARED : LK_EXCLUSIVE;
96034d8b7eaSJeff Roberson 		if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
96134d8b7eaSJeff Roberson 			vp = NULL;
96234d8b7eaSJeff Roberson 			error = EDEADLK;
96334d8b7eaSJeff Roberson 			goto unlock_mp;
96434d8b7eaSJeff Roberson 		}
96534d8b7eaSJeff Roberson 		VM_OBJECT_WLOCK(object);
96634d8b7eaSJeff Roberson 		vm_page_lock(m);
96734d8b7eaSJeff Roberson 		/*
96834d8b7eaSJeff Roberson 		 * While the object and page were unlocked, the page
96934d8b7eaSJeff Roberson 		 * may have been:
97034d8b7eaSJeff Roberson 		 * (1) moved to a different queue,
97134d8b7eaSJeff Roberson 		 * (2) reallocated to a different object,
97234d8b7eaSJeff Roberson 		 * (3) reallocated to a different offset, or
97334d8b7eaSJeff Roberson 		 * (4) cleaned.
97434d8b7eaSJeff Roberson 		 */
97534d8b7eaSJeff Roberson 		if (m->queue != PQ_INACTIVE || m->object != object ||
97634d8b7eaSJeff Roberson 		    m->pindex != pindex || m->dirty == 0) {
97734d8b7eaSJeff Roberson 			vm_page_unlock(m);
97834d8b7eaSJeff Roberson 			error = ENXIO;
97934d8b7eaSJeff Roberson 			goto unlock_all;
98034d8b7eaSJeff Roberson 		}
98134d8b7eaSJeff Roberson 
98234d8b7eaSJeff Roberson 		/*
98334d8b7eaSJeff Roberson 		 * The page may have been busied or held while the object
98434d8b7eaSJeff Roberson 		 * and page locks were released.
98534d8b7eaSJeff Roberson 		 */
98634d8b7eaSJeff Roberson 		if (vm_page_busied(m) || m->hold_count != 0) {
98734d8b7eaSJeff Roberson 			vm_page_unlock(m);
98834d8b7eaSJeff Roberson 			error = EBUSY;
98934d8b7eaSJeff Roberson 			goto unlock_all;
99034d8b7eaSJeff Roberson 		}
99134d8b7eaSJeff Roberson 	}
99234d8b7eaSJeff Roberson 
99334d8b7eaSJeff Roberson 	/*
99434d8b7eaSJeff Roberson 	 * If a page is dirty, then it is either being washed
99534d8b7eaSJeff Roberson 	 * (but not yet cleaned) or it is still in the
99634d8b7eaSJeff Roberson 	 * laundry.  If it is still in the laundry, then we
99734d8b7eaSJeff Roberson 	 * start the cleaning operation.
99834d8b7eaSJeff Roberson 	 */
99934d8b7eaSJeff Roberson 	if (vm_pageout_cluster(m) == 0)
100034d8b7eaSJeff Roberson 		error = EIO;
100134d8b7eaSJeff Roberson 
100234d8b7eaSJeff Roberson unlock_all:
100334d8b7eaSJeff Roberson 	VM_OBJECT_WUNLOCK(object);
100434d8b7eaSJeff Roberson 
100534d8b7eaSJeff Roberson unlock_mp:
100634d8b7eaSJeff Roberson 	vm_page_lock_assert(m, MA_NOTOWNED);
100734d8b7eaSJeff Roberson 	if (mp != NULL) {
100834d8b7eaSJeff Roberson 		if (vp != NULL)
100934d8b7eaSJeff Roberson 			vput(vp);
101034d8b7eaSJeff Roberson 		vm_object_deallocate(object);
101134d8b7eaSJeff Roberson 		vn_finished_write(mp);
101234d8b7eaSJeff Roberson 	}
101334d8b7eaSJeff Roberson 
101434d8b7eaSJeff Roberson 	return (error);
101534d8b7eaSJeff Roberson }
101634d8b7eaSJeff Roberson 
101734d8b7eaSJeff Roberson /*
1018df8bae1dSRodney W. Grimes  *	vm_pageout_scan does the dirty work for the pageout daemon.
1019d9e23210SJeff Roberson  *
1020d9e23210SJeff Roberson  *	pass 0 - Update active LRU/deactivate pages
1021d9e23210SJeff Roberson  *	pass 1 - Move inactive to cache or free
1022d9e23210SJeff Roberson  *	pass 2 - Launder dirty pages
1023df8bae1dSRodney W. Grimes  */
10242b6b0df7SMatthew Dillon static void
1025449c2e92SKonstantin Belousov vm_pageout_scan(struct vm_domain *vmd, int pass)
1026df8bae1dSRodney W. Grimes {
1027502ba6e4SJohn Dyson 	vm_page_t m, next;
10288d220203SAlan Cox 	struct vm_pagequeue *pq;
1029df8bae1dSRodney W. Grimes 	vm_object_t object;
103022cf98d1SAlan Cox 	long min_scan;
103140aa80a7SAlan Cox 	int act_delta, addl_page_shortage, deficit, error, maxlaunder, maxscan;
103240aa80a7SAlan Cox 	int page_shortage, scan_tick, scanned, vnodes_skipped;
103340aa80a7SAlan Cox 	boolean_t pageout_ok, queues_locked;
10340d94caffSDavid Greenman 
1035df8bae1dSRodney W. Grimes 	/*
1036d9e23210SJeff Roberson 	 * If we need to reclaim memory ask kernel caches to return
1037c9612b2dSJeff Roberson 	 * some.  We rate limit to avoid thrashing.
1038d9e23210SJeff Roberson 	 */
1039c9612b2dSJeff Roberson 	if (vmd == &vm_dom[0] && pass > 0 &&
1040a6bf3a9eSRyan Stone 	    (time_uptime - lowmem_uptime) >= lowmem_period) {
1041d9e23210SJeff Roberson 		/*
1042855a310fSJeff Roberson 		 * Decrease registered cache sizes.
1043855a310fSJeff Roberson 		 */
104414a0d74eSSteven Hartland 		SDT_PROBE0(vm, , , vm__lowmem_scan);
1045855a310fSJeff Roberson 		EVENTHANDLER_INVOKE(vm_lowmem, 0);
1046855a310fSJeff Roberson 		/*
1047d9e23210SJeff Roberson 		 * We do this explicitly after the caches have been
1048d9e23210SJeff Roberson 		 * drained above.
1049855a310fSJeff Roberson 		 */
1050855a310fSJeff Roberson 		uma_reclaim();
1051a6bf3a9eSRyan Stone 		lowmem_uptime = time_uptime;
1052d9e23210SJeff Roberson 	}
10535985940eSJohn Dyson 
1054311e34e2SKonstantin Belousov 	/*
105596240c89SEitan Adler 	 * The addl_page_shortage is the number of temporarily
1056311e34e2SKonstantin Belousov 	 * stuck pages in the inactive queue.  In other words, the
1057449c2e92SKonstantin Belousov 	 * number of pages from the inactive count that should be
1058311e34e2SKonstantin Belousov 	 * discounted in setting the target for the active queue scan.
1059311e34e2SKonstantin Belousov 	 */
10609099545aSAlan Cox 	addl_page_shortage = 0;
10619099545aSAlan Cox 
10621c7c3c6aSMatthew Dillon 	/*
10631c7c3c6aSMatthew Dillon 	 * Calculate the number of pages we want to either free or move
10642b6b0df7SMatthew Dillon 	 * to the cache.
10651c7c3c6aSMatthew Dillon 	 */
106660196cdaSAlan Cox 	if (pass > 0) {
106760196cdaSAlan Cox 		deficit = atomic_readandclear_int(&vm_pageout_deficit);
10689099545aSAlan Cox 		page_shortage = vm_paging_target() + deficit;
106960196cdaSAlan Cox 	} else
107060196cdaSAlan Cox 		page_shortage = deficit = 0;
10711c7c3c6aSMatthew Dillon 
1072936524aaSMatthew Dillon 	/*
10732b6b0df7SMatthew Dillon 	 * maxlaunder limits the number of dirty pages we flush per scan.
10742b6b0df7SMatthew Dillon 	 * For most systems a smaller value (16 or 32) is more robust under
10752b6b0df7SMatthew Dillon 	 * extreme memory and disk pressure because any unnecessary writes
10762b6b0df7SMatthew Dillon 	 * to disk can result in extreme performance degredation.  However,
10772b6b0df7SMatthew Dillon 	 * systems with excessive dirty pages (especially when MAP_NOSYNC is
10782b6b0df7SMatthew Dillon 	 * used) will die horribly with limited laundering.  If the pageout
10792b6b0df7SMatthew Dillon 	 * daemon cannot clean enough pages in the first pass, we let it go
10802b6b0df7SMatthew Dillon 	 * all out in succeeding passes.
10811c7c3c6aSMatthew Dillon 	 */
10822b6b0df7SMatthew Dillon 	if ((maxlaunder = vm_max_launder) <= 1)
10832b6b0df7SMatthew Dillon 		maxlaunder = 1;
1084d9e23210SJeff Roberson 	if (pass > 1)
10852b6b0df7SMatthew Dillon 		maxlaunder = 10000;
10868d220203SAlan Cox 
108740aa80a7SAlan Cox 	vnodes_skipped = 0;
108840aa80a7SAlan Cox 
10898d220203SAlan Cox 	/*
10908d220203SAlan Cox 	 * Start scanning the inactive queue for pages we can move to the
10918d220203SAlan Cox 	 * cache or free.  The scan will stop when the target is reached or
10928d220203SAlan Cox 	 * we have scanned the entire inactive queue.  Note that m->act_count
10938d220203SAlan Cox 	 * is not used to form decisions for the inactive queue, only for the
10948d220203SAlan Cox 	 * active queue.
10958d220203SAlan Cox 	 */
1096449c2e92SKonstantin Belousov 	pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
1097449c2e92SKonstantin Belousov 	maxscan = pq->pq_cnt;
10988d220203SAlan Cox 	vm_pagequeue_lock(pq);
10998d220203SAlan Cox 	queues_locked = TRUE;
11008d220203SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl);
11011c7c3c6aSMatthew Dillon 	     m != NULL && maxscan-- > 0 && page_shortage > 0;
1102e929c00dSKirk McKusick 	     m = next) {
11038d220203SAlan Cox 		vm_pagequeue_assert_locked(pq);
110448cc2fc7SKonstantin Belousov 		KASSERT(queues_locked, ("unlocked queues"));
1105d4961bcbSKonstantin Belousov 		KASSERT(m->queue == PQ_INACTIVE, ("Inactive queue %p", m));
1106df8bae1dSRodney W. Grimes 
11078d220203SAlan Cox 		PCPU_INC(cnt.v_pdpages);
1108c325e866SKonstantin Belousov 		next = TAILQ_NEXT(m, plinks.q);
1109df8bae1dSRodney W. Grimes 
1110936524aaSMatthew Dillon 		/*
1111936524aaSMatthew Dillon 		 * skip marker pages
1112936524aaSMatthew Dillon 		 */
1113936524aaSMatthew Dillon 		if (m->flags & PG_MARKER)
1114936524aaSMatthew Dillon 			continue;
1115936524aaSMatthew Dillon 
11167900f95dSKonstantin Belousov 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
11177900f95dSKonstantin Belousov 		    ("Fictitious page %p cannot be in inactive queue", m));
11187900f95dSKonstantin Belousov 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
11197900f95dSKonstantin Belousov 		    ("Unmanaged page %p cannot be in inactive queue", m));
11207900f95dSKonstantin Belousov 
11218c616246SKonstantin Belousov 		/*
1122311e34e2SKonstantin Belousov 		 * The page or object lock acquisitions fail if the
1123311e34e2SKonstantin Belousov 		 * page was removed from the queue or moved to a
1124311e34e2SKonstantin Belousov 		 * different position within the queue.  In either
1125311e34e2SKonstantin Belousov 		 * case, addl_page_shortage should not be incremented.
11268c616246SKonstantin Belousov 		 */
1127a3aeedabSAlan Cox 		if (!vm_pageout_page_lock(m, &next))
1128a3aeedabSAlan Cox 			goto unlock_page;
1129a3aeedabSAlan Cox 		else if (m->hold_count != 0) {
1130a3aeedabSAlan Cox 			/*
1131a3aeedabSAlan Cox 			 * Held pages are essentially stuck in the
1132a3aeedabSAlan Cox 			 * queue.  So, they ought to be discounted
1133a3aeedabSAlan Cox 			 * from the inactive count.  See the
1134a3aeedabSAlan Cox 			 * calculation of the page_shortage for the
1135a3aeedabSAlan Cox 			 * loop over the active queue below.
1136a3aeedabSAlan Cox 			 */
1137a3aeedabSAlan Cox 			addl_page_shortage++;
1138a3aeedabSAlan Cox 			goto unlock_page;
1139df8bae1dSRodney W. Grimes 		}
11409ee2165fSAlan Cox 		object = m->object;
1141a3aeedabSAlan Cox 		if (!VM_OBJECT_TRYWLOCK(object)) {
1142a3aeedabSAlan Cox 			if (!vm_pageout_fallback_object_lock(m, &next))
1143a3aeedabSAlan Cox 				goto unlock_object;
1144a3aeedabSAlan Cox 			else if (m->hold_count != 0) {
1145b182ec9eSJohn Dyson 				addl_page_shortage++;
1146a3aeedabSAlan Cox 				goto unlock_object;
1147a3aeedabSAlan Cox 			}
1148a3aeedabSAlan Cox 		}
1149a3aeedabSAlan Cox 		if (vm_page_busied(m)) {
1150a3aeedabSAlan Cox 			/*
1151a3aeedabSAlan Cox 			 * Don't mess with busy pages.  Leave them at
1152a3aeedabSAlan Cox 			 * the front of the queue.  Most likely, they
1153a3aeedabSAlan Cox 			 * are being paged out and will leave the
1154a3aeedabSAlan Cox 			 * queue shortly after the scan finishes.  So,
1155a3aeedabSAlan Cox 			 * they ought to be discounted from the
1156a3aeedabSAlan Cox 			 * inactive count.
1157a3aeedabSAlan Cox 			 */
1158a3aeedabSAlan Cox 			addl_page_shortage++;
1159a3aeedabSAlan Cox unlock_object:
1160a3aeedabSAlan Cox 			VM_OBJECT_WUNLOCK(object);
1161a3aeedabSAlan Cox unlock_page:
1162a3aeedabSAlan Cox 			vm_page_unlock(m);
116326f9a767SRodney W. Grimes 			continue;
116426f9a767SRodney W. Grimes 		}
1165a3aeedabSAlan Cox 		KASSERT(m->hold_count == 0, ("Held page %p", m));
1166bd7e5f99SJohn Dyson 
11677e006499SJohn Dyson 		/*
11688d220203SAlan Cox 		 * We unlock the inactive page queue, invalidating the
116948cc2fc7SKonstantin Belousov 		 * 'next' pointer.  Use our marker to remember our
117048cc2fc7SKonstantin Belousov 		 * place.
117148cc2fc7SKonstantin Belousov 		 */
1172c325e866SKonstantin Belousov 		TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
11738d220203SAlan Cox 		vm_pagequeue_unlock(pq);
117448cc2fc7SKonstantin Belousov 		queues_locked = FALSE;
117548cc2fc7SKonstantin Belousov 
117648cc2fc7SKonstantin Belousov 		/*
1177*8748f58cSKonstantin Belousov 		 * Invalid pages can be easily freed. They cannot be
1178*8748f58cSKonstantin Belousov 		 * mapped, vm_page_free() asserts this.
1179776f729cSKonstantin Belousov 		 */
1180*8748f58cSKonstantin Belousov 		if (m->valid == 0)
1181*8748f58cSKonstantin Belousov 			goto free_page;
1182776f729cSKonstantin Belousov 
1183776f729cSKonstantin Belousov 		/*
1184960810ccSAlan Cox 		 * If the page has been referenced and the object is not dead,
1185960810ccSAlan Cox 		 * reactivate or requeue the page depending on whether the
1186960810ccSAlan Cox 		 * object is mapped.
11877e006499SJohn Dyson 		 */
1188bb7858eaSJeff Roberson 		if ((m->aflags & PGA_REFERENCED) != 0) {
1189bb7858eaSJeff Roberson 			vm_page_aflag_clear(m, PGA_REFERENCED);
1190bb7858eaSJeff Roberson 			act_delta = 1;
119186fa2471SAlan Cox 		} else
119286fa2471SAlan Cox 			act_delta = 0;
1193bb7858eaSJeff Roberson 		if (object->ref_count != 0) {
1194bb7858eaSJeff Roberson 			act_delta += pmap_ts_referenced(m);
1195bb7858eaSJeff Roberson 		} else {
1196bb7858eaSJeff Roberson 			KASSERT(!pmap_page_is_mapped(m),
1197bb7858eaSJeff Roberson 			    ("vm_pageout_scan: page %p is mapped", m));
11982fe6e4d7SDavid Greenman 		}
1199bb7858eaSJeff Roberson 		if (act_delta != 0) {
120086fa2471SAlan Cox 			if (object->ref_count != 0) {
120126f9a767SRodney W. Grimes 				vm_page_activate(m);
1202960810ccSAlan Cox 
1203960810ccSAlan Cox 				/*
1204960810ccSAlan Cox 				 * Increase the activation count if the page
1205960810ccSAlan Cox 				 * was referenced while in the inactive queue.
1206960810ccSAlan Cox 				 * This makes it less likely that the page will
1207960810ccSAlan Cox 				 * be returned prematurely to the inactive
1208960810ccSAlan Cox 				 * queue.
1209960810ccSAlan Cox  				 */
1210bb7858eaSJeff Roberson 				m->act_count += act_delta + ACT_ADVANCE;
1211960810ccSAlan Cox 				goto drop_page;
121227a9fb2fSAlan Cox 			} else if ((object->flags & OBJ_DEAD) == 0)
121327a9fb2fSAlan Cox 				goto requeue_page;
1214960810ccSAlan Cox 		}
121567bf6868SJohn Dyson 
12167e006499SJohn Dyson 		/*
12179fc4739dSAlan Cox 		 * If the page appears to be clean at the machine-independent
12189fc4739dSAlan Cox 		 * layer, then remove all of its mappings from the pmap in
12199fc4739dSAlan Cox 		 * anticipation of placing it onto the cache queue.  If,
12209fc4739dSAlan Cox 		 * however, any of the page's mappings allow write access,
12219fc4739dSAlan Cox 		 * then the page may still be modified until the last of those
12229fc4739dSAlan Cox 		 * mappings are removed.
12237e006499SJohn Dyson 		 */
1224aa044135SAlan Cox 		if (object->ref_count != 0) {
12259fc4739dSAlan Cox 			vm_page_test_dirty(m);
1226aa044135SAlan Cox 			if (m->dirty == 0)
1227b78ddb0bSAlan Cox 				pmap_remove_all(m);
1228aa044135SAlan Cox 		}
1229dcbcd518SBruce Evans 
1230776f729cSKonstantin Belousov 		if (m->dirty == 0) {
12316989c456SAlan Cox 			/*
123278afdce6SAlan Cox 			 * Clean pages can be freed.
12336989c456SAlan Cox 			 */
1234*8748f58cSKonstantin Belousov free_page:
123578afdce6SAlan Cox 			vm_page_free(m);
123678afdce6SAlan Cox 			PCPU_INC(cnt.v_dfree);
12371c7c3c6aSMatthew Dillon 			--page_shortage;
1238960810ccSAlan Cox 		} else if ((object->flags & OBJ_DEAD) != 0) {
1239960810ccSAlan Cox 			/*
1240960810ccSAlan Cox 			 * Leave dirty pages from dead objects at the front of
1241960810ccSAlan Cox 			 * the queue.  They are being paged out and freed by
1242960810ccSAlan Cox 			 * the thread that destroyed the object.  They will
1243960810ccSAlan Cox 			 * leave the queue shortly after the scan finishes, so
1244960810ccSAlan Cox 			 * they should be discounted from the inactive count.
1245960810ccSAlan Cox 			 */
1246960810ccSAlan Cox 			addl_page_shortage++;
1247d9e23210SJeff Roberson 		} else if ((m->flags & PG_WINATCFLS) == 0 && pass < 2) {
12487e006499SJohn Dyson 			/*
12492b6b0df7SMatthew Dillon 			 * Dirty pages need to be paged out, but flushing
1250ab46f63eSJohn Baldwin 			 * a page is extremely expensive versus freeing
12512b6b0df7SMatthew Dillon 			 * a clean page.  Rather then artificially limiting
12522b6b0df7SMatthew Dillon 			 * the number of pages we can flush, we instead give
12532b6b0df7SMatthew Dillon 			 * dirty pages extra priority on the inactive queue
12542b6b0df7SMatthew Dillon 			 * by forcing them to be cycled through the queue
12552b6b0df7SMatthew Dillon 			 * twice before being flushed, after which the
12562b6b0df7SMatthew Dillon 			 * (now clean) page will cycle through once more
12572b6b0df7SMatthew Dillon 			 * before being freed.  This significantly extends
12582b6b0df7SMatthew Dillon 			 * the thrash point for a heavily loaded machine.
12597e006499SJohn Dyson 			 */
12603407fefeSKonstantin Belousov 			m->flags |= PG_WINATCFLS;
126127a9fb2fSAlan Cox requeue_page:
12628d220203SAlan Cox 			vm_pagequeue_lock(pq);
126348cc2fc7SKonstantin Belousov 			queues_locked = TRUE;
12648d220203SAlan Cox 			vm_page_requeue_locked(m);
12650d94caffSDavid Greenman 		} else if (maxlaunder > 0) {
12662b6b0df7SMatthew Dillon 			/*
12672b6b0df7SMatthew Dillon 			 * We always want to try to flush some dirty pages if
12682b6b0df7SMatthew Dillon 			 * we encounter them, to keep the system stable.
12692b6b0df7SMatthew Dillon 			 * Normally this number is small, but under extreme
12702b6b0df7SMatthew Dillon 			 * pressure where there are insufficient clean pages
12712b6b0df7SMatthew Dillon 			 * on the inactive queue, we may have to go all out.
12722b6b0df7SMatthew Dillon 			 */
12730d94caffSDavid Greenman 
127440aa80a7SAlan Cox 			if (object->type != OBJT_SWAP &&
127540aa80a7SAlan Cox 			    object->type != OBJT_DEFAULT)
127640aa80a7SAlan Cox 				pageout_ok = TRUE;
127740aa80a7SAlan Cox 			else if (disable_swap_pageouts)
127840aa80a7SAlan Cox 				pageout_ok = FALSE;
127940aa80a7SAlan Cox 			else if (defer_swap_pageouts)
128040aa80a7SAlan Cox 				pageout_ok = vm_page_count_min();
128140aa80a7SAlan Cox 			else
128240aa80a7SAlan Cox 				pageout_ok = TRUE;
128327a9fb2fSAlan Cox 			if (!pageout_ok)
128427a9fb2fSAlan Cox 				goto requeue_page;
128534d8b7eaSJeff Roberson 			error = vm_pageout_clean(m);
12861c7c3c6aSMatthew Dillon 			/*
128734d8b7eaSJeff Roberson 			 * Decrement page_shortage on success to account for
12882b6b0df7SMatthew Dillon 			 * the (future) cleaned page.  Otherwise we could wind
12892b6b0df7SMatthew Dillon 			 * up laundering or cleaning too many pages.
12900d94caffSDavid Greenman 			 */
129134d8b7eaSJeff Roberson 			if (error == 0) {
129234d8b7eaSJeff Roberson 				page_shortage--;
129334d8b7eaSJeff Roberson 				maxlaunder--;
129434d8b7eaSJeff Roberson 			} else if (error == EDEADLK) {
129534d8b7eaSJeff Roberson 				pageout_lock_miss++;
129634d8b7eaSJeff Roberson 				vnodes_skipped++;
129734d8b7eaSJeff Roberson 			} else if (error == EBUSY) {
129834d8b7eaSJeff Roberson 				addl_page_shortage++;
129948cc2fc7SKonstantin Belousov 			}
130048cc2fc7SKonstantin Belousov 			vm_page_lock_assert(m, MA_NOTOWNED);
130148cc2fc7SKonstantin Belousov 			goto relock_queues;
130248cc2fc7SKonstantin Belousov 		}
1303776f729cSKonstantin Belousov drop_page:
130448cc2fc7SKonstantin Belousov 		vm_page_unlock(m);
130589f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
130648cc2fc7SKonstantin Belousov relock_queues:
130748cc2fc7SKonstantin Belousov 		if (!queues_locked) {
13088d220203SAlan Cox 			vm_pagequeue_lock(pq);
130948cc2fc7SKonstantin Belousov 			queues_locked = TRUE;
13106989c456SAlan Cox 		}
1311c325e866SKonstantin Belousov 		next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1312c325e866SKonstantin Belousov 		TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
13130d94caffSDavid Greenman 	}
13148d220203SAlan Cox 	vm_pagequeue_unlock(pq);
131526f9a767SRodney W. Grimes 
13169452b5edSAlan Cox #if !defined(NO_SWAPPING)
13179452b5edSAlan Cox 	/*
13189452b5edSAlan Cox 	 * Wakeup the swapout daemon if we didn't cache or free the targeted
13199452b5edSAlan Cox 	 * number of pages.
13209452b5edSAlan Cox 	 */
13219452b5edSAlan Cox 	if (vm_swap_enabled && page_shortage > 0)
13229452b5edSAlan Cox 		vm_req_vmdaemon(VM_SWAP_NORMAL);
13239452b5edSAlan Cox #endif
13249452b5edSAlan Cox 
13259452b5edSAlan Cox 	/*
13269452b5edSAlan Cox 	 * Wakeup the sync daemon if we skipped a vnode in a writeable object
13279452b5edSAlan Cox 	 * and we didn't cache or free enough pages.
13289452b5edSAlan Cox 	 */
13299452b5edSAlan Cox 	if (vnodes_skipped > 0 && page_shortage > vm_cnt.v_free_target -
13309452b5edSAlan Cox 	    vm_cnt.v_free_min)
13319452b5edSAlan Cox 		(void)speedup_syncer();
13329452b5edSAlan Cox 
1333df8bae1dSRodney W. Grimes 	/*
1334936524aaSMatthew Dillon 	 * Compute the number of pages we want to try to move from the
1335936524aaSMatthew Dillon 	 * active queue to the inactive queue.
13361c7c3c6aSMatthew Dillon 	 */
133744f1c916SBryan Drewery 	page_shortage = vm_cnt.v_inactive_target - vm_cnt.v_inactive_count +
13389099545aSAlan Cox 	    vm_paging_target() + deficit + addl_page_shortage;
13399099545aSAlan Cox 
1340114f62c6SJeff Roberson 	pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1341114f62c6SJeff Roberson 	vm_pagequeue_lock(pq);
13429099545aSAlan Cox 	maxscan = pq->pq_cnt;
13439099545aSAlan Cox 
1344d9e23210SJeff Roberson 	/*
1345d9e23210SJeff Roberson 	 * If we're just idle polling attempt to visit every
1346d9e23210SJeff Roberson 	 * active page within 'update_period' seconds.
1347d9e23210SJeff Roberson 	 */
134822cf98d1SAlan Cox 	scan_tick = ticks;
134922cf98d1SAlan Cox 	if (vm_pageout_update_period != 0) {
135022cf98d1SAlan Cox 		min_scan = pq->pq_cnt;
135122cf98d1SAlan Cox 		min_scan *= scan_tick - vmd->vmd_last_active_scan;
135222cf98d1SAlan Cox 		min_scan /= hz * vm_pageout_update_period;
135322cf98d1SAlan Cox 	} else
135422cf98d1SAlan Cox 		min_scan = 0;
135522cf98d1SAlan Cox 	if (min_scan > 0 || (page_shortage > 0 && maxscan > 0))
135622cf98d1SAlan Cox 		vmd->vmd_last_active_scan = scan_tick;
13571c7c3c6aSMatthew Dillon 
13581c7c3c6aSMatthew Dillon 	/*
135922cf98d1SAlan Cox 	 * Scan the active queue for pages that can be deactivated.  Update
136022cf98d1SAlan Cox 	 * the per-page activity counter and use it to identify deactivation
136122cf98d1SAlan Cox 	 * candidates.
13621c7c3c6aSMatthew Dillon 	 */
136322cf98d1SAlan Cox 	for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
136422cf98d1SAlan Cox 	    min_scan || (page_shortage > 0 && scanned < maxscan)); m = next,
136522cf98d1SAlan Cox 	    scanned++) {
1366f35329acSJohn Dyson 
13679cf51988SAlan Cox 		KASSERT(m->queue == PQ_ACTIVE,
1368d3c09dd7SAlan Cox 		    ("vm_pageout_scan: page %p isn't active", m));
1369f35329acSJohn Dyson 
1370c325e866SKonstantin Belousov 		next = TAILQ_NEXT(m, plinks.q);
137122cf98d1SAlan Cox 		if ((m->flags & PG_MARKER) != 0)
13728dbca793STor Egge 			continue;
13737900f95dSKonstantin Belousov 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
13747900f95dSKonstantin Belousov 		    ("Fictitious page %p cannot be in active queue", m));
13757900f95dSKonstantin Belousov 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
13767900f95dSKonstantin Belousov 		    ("Unmanaged page %p cannot be in active queue", m));
13779ee2165fSAlan Cox 		if (!vm_pageout_page_lock(m, &next)) {
13788c616246SKonstantin Belousov 			vm_page_unlock(m);
13792965a453SKip Macy 			continue;
13802965a453SKip Macy 		}
1381b18bfc3dSJohn Dyson 
1382b18bfc3dSJohn Dyson 		/*
1383b18bfc3dSJohn Dyson 		 * The count for pagedaemon pages is done after checking the
1384956f3135SPhilippe Charnier 		 * page for eligibility...
1385b18bfc3dSJohn Dyson 		 */
13868d220203SAlan Cox 		PCPU_INC(cnt.v_pdpages);
1387ef743ce6SJohn Dyson 
13887e006499SJohn Dyson 		/*
13897e006499SJohn Dyson 		 * Check to see "how much" the page has been used.
13907e006499SJohn Dyson 		 */
139186fa2471SAlan Cox 		if ((m->aflags & PGA_REFERENCED) != 0) {
1392bb7858eaSJeff Roberson 			vm_page_aflag_clear(m, PGA_REFERENCED);
139386fa2471SAlan Cox 			act_delta = 1;
139486fa2471SAlan Cox 		} else
139586fa2471SAlan Cox 			act_delta = 0;
139686fa2471SAlan Cox 
1397274132acSJeff Roberson 		/*
1398274132acSJeff Roberson 		 * Unlocked object ref count check.  Two races are possible.
1399274132acSJeff Roberson 		 * 1) The ref was transitioning to zero and we saw non-zero,
1400274132acSJeff Roberson 		 *    the pmap bits will be checked unnecessarily.
1401274132acSJeff Roberson 		 * 2) The ref was transitioning to one and we saw zero.
1402274132acSJeff Roberson 		 *    The page lock prevents a new reference to this page so
1403274132acSJeff Roberson 		 *    we need not check the reference bits.
1404274132acSJeff Roberson 		 */
1405274132acSJeff Roberson 		if (m->object->ref_count != 0)
1406bb7858eaSJeff Roberson 			act_delta += pmap_ts_referenced(m);
1407bb7858eaSJeff Roberson 
1408bb7858eaSJeff Roberson 		/*
1409bb7858eaSJeff Roberson 		 * Advance or decay the act_count based on recent usage.
1410bb7858eaSJeff Roberson 		 */
141186fa2471SAlan Cox 		if (act_delta != 0) {
1412bb7858eaSJeff Roberson 			m->act_count += ACT_ADVANCE + act_delta;
141338efa82bSJohn Dyson 			if (m->act_count > ACT_MAX)
141438efa82bSJohn Dyson 				m->act_count = ACT_MAX;
141586fa2471SAlan Cox 		} else
141638efa82bSJohn Dyson 			m->act_count -= min(m->act_count, ACT_DECLINE);
1417bb7858eaSJeff Roberson 
1418bb7858eaSJeff Roberson 		/*
1419bb7858eaSJeff Roberson 		 * Move this page to the tail of the active or inactive
1420bb7858eaSJeff Roberson 		 * queue depending on usage.
1421bb7858eaSJeff Roberson 		 */
142286fa2471SAlan Cox 		if (m->act_count == 0) {
14238d220203SAlan Cox 			/* Dequeue to avoid later lock recursion. */
14248d220203SAlan Cox 			vm_page_dequeue_locked(m);
1425d4a272dbSJohn Dyson 			vm_page_deactivate(m);
1426bb7858eaSJeff Roberson 			page_shortage--;
14278d220203SAlan Cox 		} else
14288d220203SAlan Cox 			vm_page_requeue_locked(m);
14292965a453SKip Macy 		vm_page_unlock(m);
143026f9a767SRodney W. Grimes 	}
14318d220203SAlan Cox 	vm_pagequeue_unlock(pq);
1432ceb0cf87SJohn Dyson #if !defined(NO_SWAPPING)
1433ceb0cf87SJohn Dyson 	/*
1434ceb0cf87SJohn Dyson 	 * Idle process swapout -- run once per second.
1435ceb0cf87SJohn Dyson 	 */
1436ceb0cf87SJohn Dyson 	if (vm_swap_idle_enabled) {
1437ceb0cf87SJohn Dyson 		static long lsec;
1438227ee8a1SPoul-Henning Kamp 		if (time_second != lsec) {
143997824da3SAlan Cox 			vm_req_vmdaemon(VM_SWAP_IDLE);
1440227ee8a1SPoul-Henning Kamp 			lsec = time_second;
1441ceb0cf87SJohn Dyson 		}
1442ceb0cf87SJohn Dyson 	}
1443ceb0cf87SJohn Dyson #endif
1444ceb0cf87SJohn Dyson 
14455663e6deSDavid Greenman 	/*
1446e92686d0SDavid Schultz 	 * If we are critically low on one of RAM or swap and low on
1447e92686d0SDavid Schultz 	 * the other, kill the largest process.  However, we avoid
1448e92686d0SDavid Schultz 	 * doing this on the first pass in order to give ourselves a
1449e92686d0SDavid Schultz 	 * chance to flush out dirty vnode-backed pages and to allow
1450e92686d0SDavid Schultz 	 * active pages to be moved to the inactive queue and reclaimed.
14512025d69bSKonstantin Belousov 	 */
1452449c2e92SKonstantin Belousov 	vm_pageout_mightbe_oom(vmd, pass);
14532025d69bSKonstantin Belousov }
14542025d69bSKonstantin Belousov 
1455449c2e92SKonstantin Belousov static int vm_pageout_oom_vote;
1456449c2e92SKonstantin Belousov 
1457449c2e92SKonstantin Belousov /*
1458449c2e92SKonstantin Belousov  * The pagedaemon threads randlomly select one to perform the
1459449c2e92SKonstantin Belousov  * OOM.  Trying to kill processes before all pagedaemons
1460449c2e92SKonstantin Belousov  * failed to reach free target is premature.
1461449c2e92SKonstantin Belousov  */
1462449c2e92SKonstantin Belousov static void
1463449c2e92SKonstantin Belousov vm_pageout_mightbe_oom(struct vm_domain *vmd, int pass)
1464449c2e92SKonstantin Belousov {
1465449c2e92SKonstantin Belousov 	int old_vote;
1466449c2e92SKonstantin Belousov 
1467d9e23210SJeff Roberson 	if (pass <= 1 || !((swap_pager_avail < 64 && vm_page_count_min()) ||
1468449c2e92SKonstantin Belousov 	    (swap_pager_full && vm_paging_target() > 0))) {
1469449c2e92SKonstantin Belousov 		if (vmd->vmd_oom) {
1470449c2e92SKonstantin Belousov 			vmd->vmd_oom = FALSE;
1471449c2e92SKonstantin Belousov 			atomic_subtract_int(&vm_pageout_oom_vote, 1);
1472449c2e92SKonstantin Belousov 		}
1473449c2e92SKonstantin Belousov 		return;
1474449c2e92SKonstantin Belousov 	}
1475449c2e92SKonstantin Belousov 
1476449c2e92SKonstantin Belousov 	if (vmd->vmd_oom)
1477449c2e92SKonstantin Belousov 		return;
1478449c2e92SKonstantin Belousov 
1479449c2e92SKonstantin Belousov 	vmd->vmd_oom = TRUE;
1480449c2e92SKonstantin Belousov 	old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1481449c2e92SKonstantin Belousov 	if (old_vote != vm_ndomains - 1)
1482449c2e92SKonstantin Belousov 		return;
1483449c2e92SKonstantin Belousov 
1484449c2e92SKonstantin Belousov 	/*
1485449c2e92SKonstantin Belousov 	 * The current pagedaemon thread is the last in the quorum to
1486449c2e92SKonstantin Belousov 	 * start OOM.  Initiate the selection and signaling of the
1487449c2e92SKonstantin Belousov 	 * victim.
1488449c2e92SKonstantin Belousov 	 */
1489449c2e92SKonstantin Belousov 	vm_pageout_oom(VM_OOM_MEM);
1490449c2e92SKonstantin Belousov 
1491449c2e92SKonstantin Belousov 	/*
1492449c2e92SKonstantin Belousov 	 * After one round of OOM terror, recall our vote.  On the
1493449c2e92SKonstantin Belousov 	 * next pass, current pagedaemon would vote again if the low
1494449c2e92SKonstantin Belousov 	 * memory condition is still there, due to vmd_oom being
1495449c2e92SKonstantin Belousov 	 * false.
1496449c2e92SKonstantin Belousov 	 */
1497449c2e92SKonstantin Belousov 	vmd->vmd_oom = FALSE;
1498449c2e92SKonstantin Belousov 	atomic_subtract_int(&vm_pageout_oom_vote, 1);
1499449c2e92SKonstantin Belousov }
15002025d69bSKonstantin Belousov 
15012025d69bSKonstantin Belousov void
15022025d69bSKonstantin Belousov vm_pageout_oom(int shortage)
15032025d69bSKonstantin Belousov {
15042025d69bSKonstantin Belousov 	struct proc *p, *bigproc;
15052025d69bSKonstantin Belousov 	vm_offset_t size, bigsize;
15062025d69bSKonstantin Belousov 	struct thread *td;
15076bed074cSKonstantin Belousov 	struct vmspace *vm;
15082025d69bSKonstantin Belousov 
15092025d69bSKonstantin Belousov 	/*
15101c58e4e5SJohn Baldwin 	 * We keep the process bigproc locked once we find it to keep anyone
15111c58e4e5SJohn Baldwin 	 * from messing with it; however, there is a possibility of
15121c58e4e5SJohn Baldwin 	 * deadlock if process B is bigproc and one of it's child processes
15131c58e4e5SJohn Baldwin 	 * attempts to propagate a signal to B while we are waiting for A's
15141c58e4e5SJohn Baldwin 	 * lock while walking this list.  To avoid this, we don't block on
15151c58e4e5SJohn Baldwin 	 * the process lock but just skip a process if it is already locked.
15165663e6deSDavid Greenman 	 */
15175663e6deSDavid Greenman 	bigproc = NULL;
15185663e6deSDavid Greenman 	bigsize = 0;
15191005a129SJohn Baldwin 	sx_slock(&allproc_lock);
1520e602ba25SJulian Elischer 	FOREACH_PROC_IN_SYSTEM(p) {
1521e602ba25SJulian Elischer 		int breakout;
1522dcbcd518SBruce Evans 
152371943c3dSKonstantin Belousov 		PROC_LOCK(p);
152471943c3dSKonstantin Belousov 
15251c58e4e5SJohn Baldwin 		/*
15263f1c4c4fSKonstantin Belousov 		 * If this is a system, protected or killed process, skip it.
15275663e6deSDavid Greenman 		 */
152871943c3dSKonstantin Belousov 		if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
152971943c3dSKonstantin Belousov 		    P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
153071943c3dSKonstantin Belousov 		    p->p_pid == 1 || P_KILLED(p) ||
153171943c3dSKonstantin Belousov 		    (p->p_pid < 48 && swap_pager_avail != 0)) {
15328606d880SJohn Baldwin 			PROC_UNLOCK(p);
15335663e6deSDavid Greenman 			continue;
15345663e6deSDavid Greenman 		}
15355663e6deSDavid Greenman 		/*
1536dcbcd518SBruce Evans 		 * If the process is in a non-running type state,
1537e602ba25SJulian Elischer 		 * don't touch it.  Check all the threads individually.
15385663e6deSDavid Greenman 		 */
1539e602ba25SJulian Elischer 		breakout = 0;
1540e602ba25SJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td) {
1541982d11f8SJeff Roberson 			thread_lock(td);
154271fad9fdSJulian Elischer 			if (!TD_ON_RUNQ(td) &&
154371fad9fdSJulian Elischer 			    !TD_IS_RUNNING(td) &&
1544f497cda2SEdward Tomasz Napierala 			    !TD_IS_SLEEPING(td) &&
1545f497cda2SEdward Tomasz Napierala 			    !TD_IS_SUSPENDED(td)) {
1546982d11f8SJeff Roberson 				thread_unlock(td);
1547e602ba25SJulian Elischer 				breakout = 1;
1548e602ba25SJulian Elischer 				break;
1549e602ba25SJulian Elischer 			}
1550982d11f8SJeff Roberson 			thread_unlock(td);
1551e602ba25SJulian Elischer 		}
1552e602ba25SJulian Elischer 		if (breakout) {
15531c58e4e5SJohn Baldwin 			PROC_UNLOCK(p);
15545663e6deSDavid Greenman 			continue;
15555663e6deSDavid Greenman 		}
15565663e6deSDavid Greenman 		/*
15575663e6deSDavid Greenman 		 * get the process size
15585663e6deSDavid Greenman 		 */
15596bed074cSKonstantin Belousov 		vm = vmspace_acquire_ref(p);
15606bed074cSKonstantin Belousov 		if (vm == NULL) {
15616bed074cSKonstantin Belousov 			PROC_UNLOCK(p);
15626bed074cSKonstantin Belousov 			continue;
15636bed074cSKonstantin Belousov 		}
156471943c3dSKonstantin Belousov 		_PHOLD(p);
15656bed074cSKonstantin Belousov 		if (!vm_map_trylock_read(&vm->vm_map)) {
156671943c3dSKonstantin Belousov 			_PRELE(p);
156772d97679SDavid Schultz 			PROC_UNLOCK(p);
156871943c3dSKonstantin Belousov 			vmspace_free(vm);
156972d97679SDavid Schultz 			continue;
157072d97679SDavid Schultz 		}
157171943c3dSKonstantin Belousov 		PROC_UNLOCK(p);
15727981aa24SKonstantin Belousov 		size = vmspace_swap_count(vm);
15736bed074cSKonstantin Belousov 		vm_map_unlock_read(&vm->vm_map);
15742025d69bSKonstantin Belousov 		if (shortage == VM_OOM_MEM)
15756bed074cSKonstantin Belousov 			size += vmspace_resident_count(vm);
15766bed074cSKonstantin Belousov 		vmspace_free(vm);
15775663e6deSDavid Greenman 		/*
15785663e6deSDavid Greenman 		 * if the this process is bigger than the biggest one
15795663e6deSDavid Greenman 		 * remember it.
15805663e6deSDavid Greenman 		 */
15815663e6deSDavid Greenman 		if (size > bigsize) {
15821c58e4e5SJohn Baldwin 			if (bigproc != NULL)
158371943c3dSKonstantin Belousov 				PRELE(bigproc);
15845663e6deSDavid Greenman 			bigproc = p;
15855663e6deSDavid Greenman 			bigsize = size;
158671943c3dSKonstantin Belousov 		} else {
158771943c3dSKonstantin Belousov 			PRELE(p);
158871943c3dSKonstantin Belousov 		}
15895663e6deSDavid Greenman 	}
15901005a129SJohn Baldwin 	sx_sunlock(&allproc_lock);
15915663e6deSDavid Greenman 	if (bigproc != NULL) {
15928311a2b8SWill Andrews 		if (vm_panic_on_oom != 0)
15938311a2b8SWill Andrews 			panic("out of swap space");
159471943c3dSKonstantin Belousov 		PROC_LOCK(bigproc);
1595729b1e51SDavid Greenman 		killproc(bigproc, "out of swap space");
1596fa885116SJulian Elischer 		sched_nice(bigproc, PRIO_MIN);
159771943c3dSKonstantin Belousov 		_PRELE(bigproc);
15981c58e4e5SJohn Baldwin 		PROC_UNLOCK(bigproc);
159944f1c916SBryan Drewery 		wakeup(&vm_cnt.v_free_count);
16005663e6deSDavid Greenman 	}
16015663e6deSDavid Greenman }
160226f9a767SRodney W. Grimes 
1603449c2e92SKonstantin Belousov static void
1604449c2e92SKonstantin Belousov vm_pageout_worker(void *arg)
1605449c2e92SKonstantin Belousov {
1606449c2e92SKonstantin Belousov 	struct vm_domain *domain;
1607949c9186SKonstantin Belousov 	int domidx;
1608449c2e92SKonstantin Belousov 
1609449c2e92SKonstantin Belousov 	domidx = (uintptr_t)arg;
1610449c2e92SKonstantin Belousov 	domain = &vm_dom[domidx];
1611449c2e92SKonstantin Belousov 
1612449c2e92SKonstantin Belousov 	/*
1613949c9186SKonstantin Belousov 	 * XXXKIB It could be useful to bind pageout daemon threads to
1614949c9186SKonstantin Belousov 	 * the cores belonging to the domain, from which vm_page_array
1615949c9186SKonstantin Belousov 	 * is allocated.
1616449c2e92SKonstantin Belousov 	 */
1617449c2e92SKonstantin Belousov 
1618449c2e92SKonstantin Belousov 	KASSERT(domain->vmd_segs != 0, ("domain without segments"));
161922cf98d1SAlan Cox 	domain->vmd_last_active_scan = ticks;
1620449c2e92SKonstantin Belousov 	vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
1621449c2e92SKonstantin Belousov 
1622449c2e92SKonstantin Belousov 	/*
1623449c2e92SKonstantin Belousov 	 * The pageout daemon worker is never done, so loop forever.
1624449c2e92SKonstantin Belousov 	 */
1625449c2e92SKonstantin Belousov 	while (TRUE) {
1626449c2e92SKonstantin Belousov 		/*
1627449c2e92SKonstantin Belousov 		 * If we have enough free memory, wakeup waiters.  Do
1628449c2e92SKonstantin Belousov 		 * not clear vm_pages_needed until we reach our target,
1629449c2e92SKonstantin Belousov 		 * otherwise we may be woken up over and over again and
1630449c2e92SKonstantin Belousov 		 * waste a lot of cpu.
1631449c2e92SKonstantin Belousov 		 */
1632449c2e92SKonstantin Belousov 		mtx_lock(&vm_page_queue_free_mtx);
1633449c2e92SKonstantin Belousov 		if (vm_pages_needed && !vm_page_count_min()) {
1634449c2e92SKonstantin Belousov 			if (!vm_paging_needed())
1635449c2e92SKonstantin Belousov 				vm_pages_needed = 0;
163644f1c916SBryan Drewery 			wakeup(&vm_cnt.v_free_count);
1637449c2e92SKonstantin Belousov 		}
1638449c2e92SKonstantin Belousov 		if (vm_pages_needed) {
1639449c2e92SKonstantin Belousov 			/*
1640d9347bcaSAlan Cox 			 * We're still not done.  Either vm_pages_needed was
1641d9347bcaSAlan Cox 			 * set by another thread during the previous scan
1642d9347bcaSAlan Cox 			 * (typically, this happens during a level 0 scan) or
1643d9347bcaSAlan Cox 			 * vm_pages_needed was already set and the scan failed
1644d9347bcaSAlan Cox 			 * to free enough pages.  If we haven't yet performed
1645d9347bcaSAlan Cox 			 * a level >= 2 scan (unlimited dirty cleaning), then
1646d9347bcaSAlan Cox 			 * upgrade the level and scan again now.  Otherwise,
1647d9347bcaSAlan Cox 			 * sleep a bit and try again later.  While sleeping,
1648d9347bcaSAlan Cox 			 * vm_pages_needed can be cleared.
1649449c2e92SKonstantin Belousov 			 */
1650449c2e92SKonstantin Belousov 			if (domain->vmd_pass > 1)
1651449c2e92SKonstantin Belousov 				msleep(&vm_pages_needed,
1652449c2e92SKonstantin Belousov 				    &vm_page_queue_free_mtx, PVM, "psleep",
1653449c2e92SKonstantin Belousov 				    hz / 2);
1654449c2e92SKonstantin Belousov 		} else {
1655449c2e92SKonstantin Belousov 			/*
1656d9e23210SJeff Roberson 			 * Good enough, sleep until required to refresh
1657d9e23210SJeff Roberson 			 * stats.
1658449c2e92SKonstantin Belousov 			 */
1659d9e23210SJeff Roberson 			msleep(&vm_pages_needed, &vm_page_queue_free_mtx,
1660d9e23210SJeff Roberson 			    PVM, "psleep", hz);
1661449c2e92SKonstantin Belousov 		}
1662d9e23210SJeff Roberson 		if (vm_pages_needed) {
166344f1c916SBryan Drewery 			vm_cnt.v_pdwakeups++;
1664d9e23210SJeff Roberson 			domain->vmd_pass++;
1665d9347bcaSAlan Cox 		} else
1666d9347bcaSAlan Cox 			domain->vmd_pass = 0;
1667449c2e92SKonstantin Belousov 		mtx_unlock(&vm_page_queue_free_mtx);
1668449c2e92SKonstantin Belousov 		vm_pageout_scan(domain, domain->vmd_pass);
1669449c2e92SKonstantin Belousov 	}
1670449c2e92SKonstantin Belousov }
1671449c2e92SKonstantin Belousov 
1672df8bae1dSRodney W. Grimes /*
16734d19f4adSSteven Hartland  *	vm_pageout_init initialises basic pageout daemon settings.
1674df8bae1dSRodney W. Grimes  */
16752b14f991SJulian Elischer static void
16764d19f4adSSteven Hartland vm_pageout_init(void)
1677df8bae1dSRodney W. Grimes {
1678df8bae1dSRodney W. Grimes 	/*
1679df8bae1dSRodney W. Grimes 	 * Initialize some paging parameters.
1680df8bae1dSRodney W. Grimes 	 */
168144f1c916SBryan Drewery 	vm_cnt.v_interrupt_free_min = 2;
168244f1c916SBryan Drewery 	if (vm_cnt.v_page_count < 2000)
1683f35329acSJohn Dyson 		vm_pageout_page_count = 8;
1684f6b04d2bSDavid Greenman 
168545ae1d91SAlan Cox 	/*
168645ae1d91SAlan Cox 	 * v_free_reserved needs to include enough for the largest
168745ae1d91SAlan Cox 	 * swap pager structures plus enough for any pv_entry structs
168845ae1d91SAlan Cox 	 * when paging.
168945ae1d91SAlan Cox 	 */
169044f1c916SBryan Drewery 	if (vm_cnt.v_page_count > 1024)
169144f1c916SBryan Drewery 		vm_cnt.v_free_min = 4 + (vm_cnt.v_page_count - 1024) / 200;
16922feb50bfSAttilio Rao 	else
169344f1c916SBryan Drewery 		vm_cnt.v_free_min = 4;
169444f1c916SBryan Drewery 	vm_cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
169544f1c916SBryan Drewery 	    vm_cnt.v_interrupt_free_min;
169644f1c916SBryan Drewery 	vm_cnt.v_free_reserved = vm_pageout_page_count +
169744f1c916SBryan Drewery 	    vm_cnt.v_pageout_free_min + (vm_cnt.v_page_count / 768);
169844f1c916SBryan Drewery 	vm_cnt.v_free_severe = vm_cnt.v_free_min / 2;
169944f1c916SBryan Drewery 	vm_cnt.v_free_target = 4 * vm_cnt.v_free_min + vm_cnt.v_free_reserved;
170044f1c916SBryan Drewery 	vm_cnt.v_free_min += vm_cnt.v_free_reserved;
170144f1c916SBryan Drewery 	vm_cnt.v_free_severe += vm_cnt.v_free_reserved;
170244f1c916SBryan Drewery 	vm_cnt.v_inactive_target = (3 * vm_cnt.v_free_target) / 2;
170344f1c916SBryan Drewery 	if (vm_cnt.v_inactive_target > vm_cnt.v_free_count / 3)
170444f1c916SBryan Drewery 		vm_cnt.v_inactive_target = vm_cnt.v_free_count / 3;
1705df8bae1dSRodney W. Grimes 
1706d9e23210SJeff Roberson 	/*
1707d9e23210SJeff Roberson 	 * Set the default wakeup threshold to be 10% above the minimum
1708d9e23210SJeff Roberson 	 * page limit.  This keeps the steady state out of shortfall.
1709d9e23210SJeff Roberson 	 */
171044f1c916SBryan Drewery 	vm_pageout_wakeup_thresh = (vm_cnt.v_free_min / 10) * 11;
1711d9e23210SJeff Roberson 
1712d9e23210SJeff Roberson 	/*
1713d9e23210SJeff Roberson 	 * Set interval in seconds for active scan.  We want to visit each
1714c9612b2dSJeff Roberson 	 * page at least once every ten minutes.  This is to prevent worst
1715c9612b2dSJeff Roberson 	 * case paging behaviors with stale active LRU.
1716d9e23210SJeff Roberson 	 */
1717d9e23210SJeff Roberson 	if (vm_pageout_update_period == 0)
1718c9612b2dSJeff Roberson 		vm_pageout_update_period = 600;
1719d9e23210SJeff Roberson 
1720df8bae1dSRodney W. Grimes 	/* XXX does not really belong here */
1721df8bae1dSRodney W. Grimes 	if (vm_page_max_wired == 0)
172244f1c916SBryan Drewery 		vm_page_max_wired = vm_cnt.v_free_count / 3;
17234d19f4adSSteven Hartland }
17244d19f4adSSteven Hartland 
17254d19f4adSSteven Hartland /*
17264d19f4adSSteven Hartland  *     vm_pageout is the high level pageout daemon.
17274d19f4adSSteven Hartland  */
17284d19f4adSSteven Hartland static void
17294d19f4adSSteven Hartland vm_pageout(void)
17304d19f4adSSteven Hartland {
173144ec2b63SKonstantin Belousov 	int error;
17324d19f4adSSteven Hartland #if MAXMEMDOM > 1
173344ec2b63SKonstantin Belousov 	int i;
17344d19f4adSSteven Hartland #endif
1735df8bae1dSRodney W. Grimes 
173624a1cce3SDavid Greenman 	swap_pager_swap_init();
1737449c2e92SKonstantin Belousov #if MAXMEMDOM > 1
1738449c2e92SKonstantin Belousov 	for (i = 1; i < vm_ndomains; i++) {
1739449c2e92SKonstantin Belousov 		error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
1740449c2e92SKonstantin Belousov 		    curproc, NULL, 0, 0, "dom%d", i);
1741449c2e92SKonstantin Belousov 		if (error != 0) {
1742449c2e92SKonstantin Belousov 			panic("starting pageout for domain %d, error %d\n",
1743449c2e92SKonstantin Belousov 			    i, error);
1744dc2efb27SJohn Dyson 		}
1745f919ebdeSDavid Greenman 	}
1746449c2e92SKonstantin Belousov #endif
174744ec2b63SKonstantin Belousov 	error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
174844ec2b63SKonstantin Belousov 	    0, 0, "uma");
174944ec2b63SKonstantin Belousov 	if (error != 0)
175044ec2b63SKonstantin Belousov 		panic("starting uma_reclaim helper, error %d\n", error);
1751d395270dSDimitry Andric 	vm_pageout_worker((void *)(uintptr_t)0);
1752df8bae1dSRodney W. Grimes }
175326f9a767SRodney W. Grimes 
17546b4b77adSAlan Cox /*
1755e9f995d8SAlan Cox  * Unless the free page queue lock is held by the caller, this function
17566b4b77adSAlan Cox  * should be regarded as advisory.  Specifically, the caller should
175744f1c916SBryan Drewery  * not msleep() on &vm_cnt.v_free_count following this function unless
1758e9f995d8SAlan Cox  * the free page queue lock is held until the msleep() is performed.
17596b4b77adSAlan Cox  */
1760e0c5a895SJohn Dyson void
17614a365329SAndrey Zonov pagedaemon_wakeup(void)
1762e0c5a895SJohn Dyson {
1763a1c0a785SAlan Cox 
1764b40ce416SJulian Elischer 	if (!vm_pages_needed && curthread->td_proc != pageproc) {
1765a1c0a785SAlan Cox 		vm_pages_needed = 1;
1766e0c5a895SJohn Dyson 		wakeup(&vm_pages_needed);
1767e0c5a895SJohn Dyson 	}
1768e0c5a895SJohn Dyson }
1769e0c5a895SJohn Dyson 
177038efa82bSJohn Dyson #if !defined(NO_SWAPPING)
17715afce282SDavid Greenman static void
177297824da3SAlan Cox vm_req_vmdaemon(int req)
17735afce282SDavid Greenman {
17745afce282SDavid Greenman 	static int lastrun = 0;
17755afce282SDavid Greenman 
177697824da3SAlan Cox 	mtx_lock(&vm_daemon_mtx);
177797824da3SAlan Cox 	vm_pageout_req_swapout |= req;
1778b18bfc3dSJohn Dyson 	if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
17795afce282SDavid Greenman 		wakeup(&vm_daemon_needed);
17805afce282SDavid Greenman 		lastrun = ticks;
17815afce282SDavid Greenman 	}
178297824da3SAlan Cox 	mtx_unlock(&vm_daemon_mtx);
17835afce282SDavid Greenman }
17845afce282SDavid Greenman 
17852b14f991SJulian Elischer static void
17864a365329SAndrey Zonov vm_daemon(void)
17870d94caffSDavid Greenman {
178891d5354aSJohn Baldwin 	struct rlimit rsslim;
1789dcbcd518SBruce Evans 	struct proc *p;
1790dcbcd518SBruce Evans 	struct thread *td;
17916bed074cSKonstantin Belousov 	struct vmspace *vm;
1792099e7e95SEdward Tomasz Napierala 	int breakout, swapout_flags, tryagain, attempts;
1793afcc55f3SEdward Tomasz Napierala #ifdef RACCT
1794099e7e95SEdward Tomasz Napierala 	uint64_t rsize, ravailable;
1795afcc55f3SEdward Tomasz Napierala #endif
17960d94caffSDavid Greenman 
17972fe6e4d7SDavid Greenman 	while (TRUE) {
179897824da3SAlan Cox 		mtx_lock(&vm_daemon_mtx);
17994b5c9cf6SEdward Tomasz Napierala 		msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
1800099e7e95SEdward Tomasz Napierala #ifdef RACCT
18014b5c9cf6SEdward Tomasz Napierala 		    racct_enable ? hz : 0
1802099e7e95SEdward Tomasz Napierala #else
18034b5c9cf6SEdward Tomasz Napierala 		    0
1804099e7e95SEdward Tomasz Napierala #endif
18054b5c9cf6SEdward Tomasz Napierala 		);
180697824da3SAlan Cox 		swapout_flags = vm_pageout_req_swapout;
18074c1f8ee9SDavid Greenman 		vm_pageout_req_swapout = 0;
180897824da3SAlan Cox 		mtx_unlock(&vm_daemon_mtx);
180997824da3SAlan Cox 		if (swapout_flags)
181097824da3SAlan Cox 			swapout_procs(swapout_flags);
181197824da3SAlan Cox 
18122fe6e4d7SDavid Greenman 		/*
18130d94caffSDavid Greenman 		 * scan the processes for exceeding their rlimits or if
18140d94caffSDavid Greenman 		 * process is swapped out -- deactivate pages
18152fe6e4d7SDavid Greenman 		 */
1816099e7e95SEdward Tomasz Napierala 		tryagain = 0;
1817099e7e95SEdward Tomasz Napierala 		attempts = 0;
1818099e7e95SEdward Tomasz Napierala again:
1819099e7e95SEdward Tomasz Napierala 		attempts++;
18201005a129SJohn Baldwin 		sx_slock(&allproc_lock);
1821f67af5c9SXin LI 		FOREACH_PROC_IN_SYSTEM(p) {
1822fe2144fdSLuoqi Chen 			vm_pindex_t limit, size;
18232fe6e4d7SDavid Greenman 
18242fe6e4d7SDavid Greenman 			/*
18252fe6e4d7SDavid Greenman 			 * if this is a system process or if we have already
18262fe6e4d7SDavid Greenman 			 * looked at this process, skip it.
18272fe6e4d7SDavid Greenman 			 */
1828897ecacdSJohn Baldwin 			PROC_LOCK(p);
18298e6fa660SJohn Baldwin 			if (p->p_state != PRS_NORMAL ||
18308e6fa660SJohn Baldwin 			    p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
1831897ecacdSJohn Baldwin 				PROC_UNLOCK(p);
18322fe6e4d7SDavid Greenman 				continue;
18332fe6e4d7SDavid Greenman 			}
18342fe6e4d7SDavid Greenman 			/*
18352fe6e4d7SDavid Greenman 			 * if the process is in a non-running type state,
18362fe6e4d7SDavid Greenman 			 * don't touch it.
18372fe6e4d7SDavid Greenman 			 */
1838e602ba25SJulian Elischer 			breakout = 0;
1839e602ba25SJulian Elischer 			FOREACH_THREAD_IN_PROC(p, td) {
1840982d11f8SJeff Roberson 				thread_lock(td);
184171fad9fdSJulian Elischer 				if (!TD_ON_RUNQ(td) &&
184271fad9fdSJulian Elischer 				    !TD_IS_RUNNING(td) &&
1843f497cda2SEdward Tomasz Napierala 				    !TD_IS_SLEEPING(td) &&
1844f497cda2SEdward Tomasz Napierala 				    !TD_IS_SUSPENDED(td)) {
1845982d11f8SJeff Roberson 					thread_unlock(td);
1846e602ba25SJulian Elischer 					breakout = 1;
1847e602ba25SJulian Elischer 					break;
1848e602ba25SJulian Elischer 				}
1849982d11f8SJeff Roberson 				thread_unlock(td);
1850e602ba25SJulian Elischer 			}
1851897ecacdSJohn Baldwin 			if (breakout) {
1852897ecacdSJohn Baldwin 				PROC_UNLOCK(p);
18532fe6e4d7SDavid Greenman 				continue;
18542fe6e4d7SDavid Greenman 			}
18552fe6e4d7SDavid Greenman 			/*
18562fe6e4d7SDavid Greenman 			 * get a limit
18572fe6e4d7SDavid Greenman 			 */
1858f6f6d240SMateusz Guzik 			lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
1859fe2144fdSLuoqi Chen 			limit = OFF_TO_IDX(
186091d5354aSJohn Baldwin 			    qmin(rsslim.rlim_cur, rsslim.rlim_max));
18612fe6e4d7SDavid Greenman 
18622fe6e4d7SDavid Greenman 			/*
18630d94caffSDavid Greenman 			 * let processes that are swapped out really be
18640d94caffSDavid Greenman 			 * swapped out set the limit to nothing (will force a
18650d94caffSDavid Greenman 			 * swap-out.)
18662fe6e4d7SDavid Greenman 			 */
1867b61ce5b0SJeff Roberson 			if ((p->p_flag & P_INMEM) == 0)
18680d94caffSDavid Greenman 				limit = 0;	/* XXX */
18696bed074cSKonstantin Belousov 			vm = vmspace_acquire_ref(p);
1870897ecacdSJohn Baldwin 			PROC_UNLOCK(p);
18716bed074cSKonstantin Belousov 			if (vm == NULL)
18726bed074cSKonstantin Belousov 				continue;
18732fe6e4d7SDavid Greenman 
18746bed074cSKonstantin Belousov 			size = vmspace_resident_count(vm);
1875a406d8c3SEdward Tomasz Napierala 			if (size >= limit) {
1876fe2144fdSLuoqi Chen 				vm_pageout_map_deactivate_pages(
18776bed074cSKonstantin Belousov 				    &vm->vm_map, limit);
18782fe6e4d7SDavid Greenman 			}
1879afcc55f3SEdward Tomasz Napierala #ifdef RACCT
18804b5c9cf6SEdward Tomasz Napierala 			if (racct_enable) {
1881099e7e95SEdward Tomasz Napierala 				rsize = IDX_TO_OFF(size);
1882099e7e95SEdward Tomasz Napierala 				PROC_LOCK(p);
1883099e7e95SEdward Tomasz Napierala 				racct_set(p, RACCT_RSS, rsize);
1884099e7e95SEdward Tomasz Napierala 				ravailable = racct_get_available(p, RACCT_RSS);
1885099e7e95SEdward Tomasz Napierala 				PROC_UNLOCK(p);
1886099e7e95SEdward Tomasz Napierala 				if (rsize > ravailable) {
1887099e7e95SEdward Tomasz Napierala 					/*
18884b5c9cf6SEdward Tomasz Napierala 					 * Don't be overly aggressive; this
18894b5c9cf6SEdward Tomasz Napierala 					 * might be an innocent process,
18904b5c9cf6SEdward Tomasz Napierala 					 * and the limit could've been exceeded
18914b5c9cf6SEdward Tomasz Napierala 					 * by some memory hog.  Don't try
18924b5c9cf6SEdward Tomasz Napierala 					 * to deactivate more than 1/4th
18934b5c9cf6SEdward Tomasz Napierala 					 * of process' resident set size.
1894099e7e95SEdward Tomasz Napierala 					 */
1895099e7e95SEdward Tomasz Napierala 					if (attempts <= 8) {
18964b5c9cf6SEdward Tomasz Napierala 						if (ravailable < rsize -
18974b5c9cf6SEdward Tomasz Napierala 						    (rsize / 4)) {
18984b5c9cf6SEdward Tomasz Napierala 							ravailable = rsize -
18994b5c9cf6SEdward Tomasz Napierala 							    (rsize / 4);
19004b5c9cf6SEdward Tomasz Napierala 						}
1901099e7e95SEdward Tomasz Napierala 					}
1902099e7e95SEdward Tomasz Napierala 					vm_pageout_map_deactivate_pages(
19034b5c9cf6SEdward Tomasz Napierala 					    &vm->vm_map,
19044b5c9cf6SEdward Tomasz Napierala 					    OFF_TO_IDX(ravailable));
1905099e7e95SEdward Tomasz Napierala 					/* Update RSS usage after paging out. */
1906099e7e95SEdward Tomasz Napierala 					size = vmspace_resident_count(vm);
1907099e7e95SEdward Tomasz Napierala 					rsize = IDX_TO_OFF(size);
1908099e7e95SEdward Tomasz Napierala 					PROC_LOCK(p);
1909099e7e95SEdward Tomasz Napierala 					racct_set(p, RACCT_RSS, rsize);
1910099e7e95SEdward Tomasz Napierala 					PROC_UNLOCK(p);
1911099e7e95SEdward Tomasz Napierala 					if (rsize > ravailable)
1912099e7e95SEdward Tomasz Napierala 						tryagain = 1;
1913099e7e95SEdward Tomasz Napierala 				}
19144b5c9cf6SEdward Tomasz Napierala 			}
1915afcc55f3SEdward Tomasz Napierala #endif
19166bed074cSKonstantin Belousov 			vmspace_free(vm);
19172fe6e4d7SDavid Greenman 		}
19181005a129SJohn Baldwin 		sx_sunlock(&allproc_lock);
1919099e7e95SEdward Tomasz Napierala 		if (tryagain != 0 && attempts <= 10)
1920099e7e95SEdward Tomasz Napierala 			goto again;
192124a1cce3SDavid Greenman 	}
19222fe6e4d7SDavid Greenman }
1923a1287949SEivind Eklund #endif			/* !defined(NO_SWAPPING) */
1924