vm_pageout.c revision 209407
1/*-
2 * Copyright (c) 1991 Regents of the University of California.
3 * All rights reserved.
4 * Copyright (c) 1994 John S. Dyson
5 * All rights reserved.
6 * Copyright (c) 1994 David Greenman
7 * All rights reserved.
8 * Copyright (c) 2005 Yahoo! Technologies Norway AS
9 * All rights reserved.
10 *
11 * This code is derived from software contributed to Berkeley by
12 * The Mach Operating System project at Carnegie-Mellon University.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
16 * are met:
17 * 1. Redistributions of source code must retain the above copyright
18 *    notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 *    notice, this list of conditions and the following disclaimer in the
21 *    documentation and/or other materials provided with the distribution.
22 * 3. All advertising materials mentioning features or use of this software
23 *    must display the following acknowledgement:
24 *	This product includes software developed by the University of
25 *	California, Berkeley and its contributors.
26 * 4. Neither the name of the University nor the names of its contributors
27 *    may be used to endorse or promote products derived from this software
28 *    without specific prior written permission.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 * SUCH DAMAGE.
41 *
42 *	from: @(#)vm_pageout.c	7.4 (Berkeley) 5/7/91
43 *
44 *
45 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
46 * All rights reserved.
47 *
48 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
49 *
50 * Permission to use, copy, modify and distribute this software and
51 * its documentation is hereby granted, provided that both the copyright
52 * notice and this permission notice appear in all copies of the
53 * software, derivative works or modified versions, and any portions
54 * thereof, and that both notices appear in supporting documentation.
55 *
56 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
57 * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
58 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
59 *
60 * Carnegie Mellon requests users of this software to return to
61 *
62 *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
63 *  School of Computer Science
64 *  Carnegie Mellon University
65 *  Pittsburgh PA 15213-3890
66 *
67 * any improvements or extensions that they make and grant Carnegie the
68 * rights to redistribute these changes.
69 */
70
71/*
72 *	The proverbial page-out daemon.
73 */
74
75#include <sys/cdefs.h>
76__FBSDID("$FreeBSD: head/sys/vm/vm_pageout.c 209407 2010-06-21 23:27:24Z alc $");
77
78#include "opt_vm.h"
79#include <sys/param.h>
80#include <sys/systm.h>
81#include <sys/kernel.h>
82#include <sys/eventhandler.h>
83#include <sys/lock.h>
84#include <sys/mutex.h>
85#include <sys/proc.h>
86#include <sys/kthread.h>
87#include <sys/ktr.h>
88#include <sys/mount.h>
89#include <sys/resourcevar.h>
90#include <sys/sched.h>
91#include <sys/signalvar.h>
92#include <sys/vnode.h>
93#include <sys/vmmeter.h>
94#include <sys/sx.h>
95#include <sys/sysctl.h>
96
97#include <vm/vm.h>
98#include <vm/vm_param.h>
99#include <vm/vm_object.h>
100#include <vm/vm_page.h>
101#include <vm/vm_map.h>
102#include <vm/vm_pageout.h>
103#include <vm/vm_pager.h>
104#include <vm/swap_pager.h>
105#include <vm/vm_extern.h>
106#include <vm/uma.h>
107
108/*
109 * System initialization
110 */
111
112/* the kernel process "vm_pageout"*/
113static void vm_pageout(void);
114static int vm_pageout_clean(vm_page_t);
115static void vm_pageout_scan(int pass);
116
117struct proc *pageproc;
118
119static struct kproc_desc page_kp = {
120	"pagedaemon",
121	vm_pageout,
122	&pageproc
123};
124SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, kproc_start,
125    &page_kp);
126
127#if !defined(NO_SWAPPING)
128/* the kernel process "vm_daemon"*/
129static void vm_daemon(void);
130static struct	proc *vmproc;
131
132static struct kproc_desc vm_kp = {
133	"vmdaemon",
134	vm_daemon,
135	&vmproc
136};
137SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
138#endif
139
140
141int vm_pages_needed;		/* Event on which pageout daemon sleeps */
142int vm_pageout_deficit;		/* Estimated number of pages deficit */
143int vm_pageout_pages_needed;	/* flag saying that the pageout daemon needs pages */
144
145#if !defined(NO_SWAPPING)
146static int vm_pageout_req_swapout;	/* XXX */
147static int vm_daemon_needed;
148static struct mtx vm_daemon_mtx;
149/* Allow for use by vm_pageout before vm_daemon is initialized. */
150MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
151#endif
152static int vm_max_launder = 32;
153static int vm_pageout_stats_max=0, vm_pageout_stats_interval = 0;
154static int vm_pageout_full_stats_interval = 0;
155static int vm_pageout_algorithm=0;
156static int defer_swap_pageouts=0;
157static int disable_swap_pageouts=0;
158
159#if defined(NO_SWAPPING)
160static int vm_swap_enabled=0;
161static int vm_swap_idle_enabled=0;
162#else
163static int vm_swap_enabled=1;
164static int vm_swap_idle_enabled=0;
165#endif
166
167SYSCTL_INT(_vm, VM_PAGEOUT_ALGORITHM, pageout_algorithm,
168	CTLFLAG_RW, &vm_pageout_algorithm, 0, "LRU page mgmt");
169
170SYSCTL_INT(_vm, OID_AUTO, max_launder,
171	CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
172
173SYSCTL_INT(_vm, OID_AUTO, pageout_stats_max,
174	CTLFLAG_RW, &vm_pageout_stats_max, 0, "Max pageout stats scan length");
175
176SYSCTL_INT(_vm, OID_AUTO, pageout_full_stats_interval,
177	CTLFLAG_RW, &vm_pageout_full_stats_interval, 0, "Interval for full stats scan");
178
179SYSCTL_INT(_vm, OID_AUTO, pageout_stats_interval,
180	CTLFLAG_RW, &vm_pageout_stats_interval, 0, "Interval for partial stats scan");
181
182#if defined(NO_SWAPPING)
183SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
184	CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout");
185SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
186	CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
187#else
188SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
189	CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
190SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
191	CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
192#endif
193
194SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
195	CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
196
197SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
198	CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
199
200static int pageout_lock_miss;
201SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
202	CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
203
204#define VM_PAGEOUT_PAGE_COUNT 16
205int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
206
207int vm_page_max_wired;		/* XXX max # of wired pages system-wide */
208SYSCTL_INT(_vm, OID_AUTO, max_wired,
209	CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
210
211#if !defined(NO_SWAPPING)
212static void vm_pageout_map_deactivate_pages(vm_map_t, long);
213static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
214static void vm_req_vmdaemon(int req);
215#endif
216static void vm_pageout_page_stats(void);
217
218static void
219vm_pageout_init_marker(vm_page_t marker, u_short queue)
220{
221
222	bzero(marker, sizeof(*marker));
223	marker->flags = PG_FICTITIOUS | PG_MARKER;
224	marker->oflags = VPO_BUSY;
225	marker->queue = queue;
226	marker->wire_count = 1;
227}
228
229/*
230 * vm_pageout_fallback_object_lock:
231 *
232 * Lock vm object currently associated with `m'. VM_OBJECT_TRYLOCK is
233 * known to have failed and page queue must be either PQ_ACTIVE or
234 * PQ_INACTIVE.  To avoid lock order violation, unlock the page queues
235 * while locking the vm object.  Use marker page to detect page queue
236 * changes and maintain notion of next page on page queue.  Return
237 * TRUE if no changes were detected, FALSE otherwise.  vm object is
238 * locked on return.
239 *
240 * This function depends on both the lock portion of struct vm_object
241 * and normal struct vm_page being type stable.
242 */
243boolean_t
244vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
245{
246	struct vm_page marker;
247	boolean_t unchanged;
248	u_short queue;
249	vm_object_t object;
250
251	queue = m->queue;
252	vm_pageout_init_marker(&marker, queue);
253	object = m->object;
254
255	TAILQ_INSERT_AFTER(&vm_page_queues[queue].pl,
256			   m, &marker, pageq);
257	vm_page_unlock_queues();
258	vm_page_unlock(m);
259	VM_OBJECT_LOCK(object);
260	vm_page_lock(m);
261	vm_page_lock_queues();
262
263	/* Page queue might have changed. */
264	*next = TAILQ_NEXT(&marker, pageq);
265	unchanged = (m->queue == queue &&
266		     m->object == object &&
267		     &marker == TAILQ_NEXT(m, pageq));
268	TAILQ_REMOVE(&vm_page_queues[queue].pl,
269		     &marker, pageq);
270	return (unchanged);
271}
272
273/*
274 * Lock the page while holding the page queue lock.  Use marker page
275 * to detect page queue changes and maintain notion of next page on
276 * page queue.  Return TRUE if no changes were detected, FALSE
277 * otherwise.  The page is locked on return. The page queue lock might
278 * be dropped and reacquired.
279 *
280 * This function depends on normal struct vm_page being type stable.
281 */
282boolean_t
283vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
284{
285	struct vm_page marker;
286	boolean_t unchanged;
287	u_short queue;
288
289	vm_page_lock_assert(m, MA_NOTOWNED);
290	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
291
292	if (vm_page_trylock(m))
293		return (TRUE);
294
295	queue = m->queue;
296	vm_pageout_init_marker(&marker, queue);
297
298	TAILQ_INSERT_AFTER(&vm_page_queues[queue].pl, m, &marker, pageq);
299	vm_page_unlock_queues();
300	vm_page_lock(m);
301	vm_page_lock_queues();
302
303	/* Page queue might have changed. */
304	*next = TAILQ_NEXT(&marker, pageq);
305	unchanged = (m->queue == queue && &marker == TAILQ_NEXT(m, pageq));
306	TAILQ_REMOVE(&vm_page_queues[queue].pl, &marker, pageq);
307	return (unchanged);
308}
309
310/*
311 * vm_pageout_clean:
312 *
313 * Clean the page and remove it from the laundry.
314 *
315 * We set the busy bit to cause potential page faults on this page to
316 * block.  Note the careful timing, however, the busy bit isn't set till
317 * late and we cannot do anything that will mess with the page.
318 */
319static int
320vm_pageout_clean(vm_page_t m)
321{
322	vm_object_t object;
323	vm_page_t mc[2*vm_pageout_page_count], pb, ps;
324	int pageout_count;
325	int ib, is, page_base;
326	vm_pindex_t pindex = m->pindex;
327
328	vm_page_lock_assert(m, MA_NOTOWNED);
329	vm_page_lock(m);
330	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
331
332	/*
333	 * It doesn't cost us anything to pageout OBJT_DEFAULT or OBJT_SWAP
334	 * with the new swapper, but we could have serious problems paging
335	 * out other object types if there is insufficient memory.
336	 *
337	 * Unfortunately, checking free memory here is far too late, so the
338	 * check has been moved up a procedural level.
339	 */
340
341	/*
342	 * Can't clean the page if it's busy or held.
343	 */
344	if ((m->hold_count != 0) ||
345	    ((m->busy != 0) || (m->oflags & VPO_BUSY))) {
346		vm_page_unlock(m);
347		return 0;
348	}
349
350	mc[vm_pageout_page_count] = pb = ps = m;
351	pageout_count = 1;
352	page_base = vm_pageout_page_count;
353	ib = 1;
354	is = 1;
355
356	/*
357	 * Scan object for clusterable pages.
358	 *
359	 * We can cluster ONLY if: ->> the page is NOT
360	 * clean, wired, busy, held, or mapped into a
361	 * buffer, and one of the following:
362	 * 1) The page is inactive, or a seldom used
363	 *    active page.
364	 * -or-
365	 * 2) we force the issue.
366	 *
367	 * During heavy mmap/modification loads the pageout
368	 * daemon can really fragment the underlying file
369	 * due to flushing pages out of order and not trying
370	 * align the clusters (which leave sporatic out-of-order
371	 * holes).  To solve this problem we do the reverse scan
372	 * first and attempt to align our cluster, then do a
373	 * forward scan if room remains.
374	 */
375	object = m->object;
376more:
377	while (ib && pageout_count < vm_pageout_page_count) {
378		vm_page_t p;
379
380		if (ib > pindex) {
381			ib = 0;
382			break;
383		}
384
385		if ((p = vm_page_prev(pb)) == NULL ||
386		    (p->oflags & VPO_BUSY) != 0 || p->busy != 0) {
387			ib = 0;
388			break;
389		}
390		vm_page_lock(p);
391		vm_page_test_dirty(p);
392		if (p->dirty == 0 ||
393		    p->queue != PQ_INACTIVE ||
394		    p->hold_count != 0) {	/* may be undergoing I/O */
395			vm_page_unlock(p);
396			ib = 0;
397			break;
398		}
399		vm_page_unlock(p);
400		mc[--page_base] = pb = p;
401		++pageout_count;
402		++ib;
403		/*
404		 * alignment boundry, stop here and switch directions.  Do
405		 * not clear ib.
406		 */
407		if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
408			break;
409	}
410
411	while (pageout_count < vm_pageout_page_count &&
412	    pindex + is < object->size) {
413		vm_page_t p;
414
415		if ((p = vm_page_next(ps)) == NULL ||
416		    (p->oflags & VPO_BUSY) != 0 || p->busy != 0)
417			break;
418		vm_page_lock(p);
419		vm_page_test_dirty(p);
420		if (p->dirty == 0 ||
421		    p->queue != PQ_INACTIVE ||
422		    p->hold_count != 0) {	/* may be undergoing I/O */
423			vm_page_unlock(p);
424			break;
425		}
426		vm_page_unlock(p);
427		mc[page_base + pageout_count] = ps = p;
428		++pageout_count;
429		++is;
430	}
431
432	/*
433	 * If we exhausted our forward scan, continue with the reverse scan
434	 * when possible, even past a page boundry.  This catches boundry
435	 * conditions.
436	 */
437	if (ib && pageout_count < vm_pageout_page_count)
438		goto more;
439
440	vm_page_unlock(m);
441	/*
442	 * we allow reads during pageouts...
443	 */
444	return (vm_pageout_flush(&mc[page_base], pageout_count, 0));
445}
446
447/*
448 * vm_pageout_flush() - launder the given pages
449 *
450 *	The given pages are laundered.  Note that we setup for the start of
451 *	I/O ( i.e. busy the page ), mark it read-only, and bump the object
452 *	reference count all in here rather then in the parent.  If we want
453 *	the parent to do more sophisticated things we may have to change
454 *	the ordering.
455 */
456int
457vm_pageout_flush(vm_page_t *mc, int count, int flags)
458{
459	vm_object_t object = mc[0]->object;
460	int pageout_status[count];
461	int numpagedout = 0;
462	int i;
463
464	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
465	mtx_assert(&vm_page_queue_mtx, MA_NOTOWNED);
466
467	/*
468	 * Initiate I/O.  Bump the vm_page_t->busy counter and
469	 * mark the pages read-only.
470	 *
471	 * We do not have to fixup the clean/dirty bits here... we can
472	 * allow the pager to do it after the I/O completes.
473	 *
474	 * NOTE! mc[i]->dirty may be partial or fragmented due to an
475	 * edge case with file fragments.
476	 */
477	for (i = 0; i < count; i++) {
478		KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
479		    ("vm_pageout_flush: partially invalid page %p index %d/%d",
480			mc[i], i, count));
481		vm_page_io_start(mc[i]);
482		pmap_remove_write(mc[i]);
483	}
484	vm_object_pip_add(object, count);
485
486	vm_pager_put_pages(object, mc, count, flags, pageout_status);
487
488	for (i = 0; i < count; i++) {
489		vm_page_t mt = mc[i];
490
491		KASSERT(pageout_status[i] == VM_PAGER_PEND ||
492		    (mt->flags & PG_WRITEABLE) == 0,
493		    ("vm_pageout_flush: page %p is not write protected", mt));
494		switch (pageout_status[i]) {
495		case VM_PAGER_OK:
496		case VM_PAGER_PEND:
497			numpagedout++;
498			break;
499		case VM_PAGER_BAD:
500			/*
501			 * Page outside of range of object. Right now we
502			 * essentially lose the changes by pretending it
503			 * worked.
504			 */
505			vm_page_undirty(mt);
506			break;
507		case VM_PAGER_ERROR:
508		case VM_PAGER_FAIL:
509			/*
510			 * If page couldn't be paged out, then reactivate the
511			 * page so it doesn't clog the inactive list.  (We
512			 * will try paging out it again later).
513			 */
514			vm_page_lock(mt);
515			vm_page_activate(mt);
516			vm_page_unlock(mt);
517			break;
518		case VM_PAGER_AGAIN:
519			break;
520		}
521
522		/*
523		 * If the operation is still going, leave the page busy to
524		 * block all other accesses. Also, leave the paging in
525		 * progress indicator set so that we don't attempt an object
526		 * collapse.
527		 */
528		if (pageout_status[i] != VM_PAGER_PEND) {
529			vm_object_pip_wakeup(object);
530			vm_page_io_finish(mt);
531			if (vm_page_count_severe()) {
532				vm_page_lock(mt);
533				vm_page_try_to_cache(mt);
534				vm_page_unlock(mt);
535			}
536		}
537	}
538	return (numpagedout);
539}
540
541#if !defined(NO_SWAPPING)
542/*
543 *	vm_pageout_object_deactivate_pages
544 *
545 *	Deactivate enough pages to satisfy the inactive target
546 *	requirements.
547 *
548 *	The object and map must be locked.
549 */
550static void
551vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
552    long desired)
553{
554	vm_object_t backing_object, object;
555	vm_page_t p;
556	int actcount, remove_mode;
557
558	VM_OBJECT_LOCK_ASSERT(first_object, MA_OWNED);
559	if (first_object->type == OBJT_DEVICE ||
560	    first_object->type == OBJT_SG)
561		return;
562	for (object = first_object;; object = backing_object) {
563		if (pmap_resident_count(pmap) <= desired)
564			goto unlock_return;
565		VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
566		if (object->type == OBJT_PHYS || object->paging_in_progress)
567			goto unlock_return;
568
569		remove_mode = 0;
570		if (object->shadow_count > 1)
571			remove_mode = 1;
572		/*
573		 * Scan the object's entire memory queue.
574		 */
575		TAILQ_FOREACH(p, &object->memq, listq) {
576			if (pmap_resident_count(pmap) <= desired)
577				goto unlock_return;
578			if ((p->oflags & VPO_BUSY) != 0 || p->busy != 0)
579				continue;
580			PCPU_INC(cnt.v_pdpages);
581			vm_page_lock(p);
582			if (p->wire_count != 0 || p->hold_count != 0 ||
583			    !pmap_page_exists_quick(pmap, p)) {
584				vm_page_unlock(p);
585				continue;
586			}
587			actcount = pmap_ts_referenced(p);
588			if ((p->flags & PG_REFERENCED) != 0) {
589				if (actcount == 0)
590					actcount = 1;
591				vm_page_lock_queues();
592				vm_page_flag_clear(p, PG_REFERENCED);
593				vm_page_unlock_queues();
594			}
595			if (p->queue != PQ_ACTIVE && actcount != 0) {
596				vm_page_activate(p);
597				p->act_count += actcount;
598			} else if (p->queue == PQ_ACTIVE) {
599				if (actcount == 0) {
600					p->act_count -= min(p->act_count,
601					    ACT_DECLINE);
602					if (!remove_mode &&
603					    (vm_pageout_algorithm ||
604					    p->act_count == 0)) {
605						pmap_remove_all(p);
606						vm_page_deactivate(p);
607					} else {
608						vm_page_lock_queues();
609						vm_page_requeue(p);
610						vm_page_unlock_queues();
611					}
612				} else {
613					vm_page_activate(p);
614					if (p->act_count < ACT_MAX -
615					    ACT_ADVANCE)
616						p->act_count += ACT_ADVANCE;
617					vm_page_lock_queues();
618					vm_page_requeue(p);
619					vm_page_unlock_queues();
620				}
621			} else if (p->queue == PQ_INACTIVE)
622				pmap_remove_all(p);
623			vm_page_unlock(p);
624		}
625		if ((backing_object = object->backing_object) == NULL)
626			goto unlock_return;
627		VM_OBJECT_LOCK(backing_object);
628		if (object != first_object)
629			VM_OBJECT_UNLOCK(object);
630	}
631unlock_return:
632	if (object != first_object)
633		VM_OBJECT_UNLOCK(object);
634}
635
636/*
637 * deactivate some number of pages in a map, try to do it fairly, but
638 * that is really hard to do.
639 */
640static void
641vm_pageout_map_deactivate_pages(map, desired)
642	vm_map_t map;
643	long desired;
644{
645	vm_map_entry_t tmpe;
646	vm_object_t obj, bigobj;
647	int nothingwired;
648
649	if (!vm_map_trylock(map))
650		return;
651
652	bigobj = NULL;
653	nothingwired = TRUE;
654
655	/*
656	 * first, search out the biggest object, and try to free pages from
657	 * that.
658	 */
659	tmpe = map->header.next;
660	while (tmpe != &map->header) {
661		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
662			obj = tmpe->object.vm_object;
663			if (obj != NULL && VM_OBJECT_TRYLOCK(obj)) {
664				if (obj->shadow_count <= 1 &&
665				    (bigobj == NULL ||
666				     bigobj->resident_page_count < obj->resident_page_count)) {
667					if (bigobj != NULL)
668						VM_OBJECT_UNLOCK(bigobj);
669					bigobj = obj;
670				} else
671					VM_OBJECT_UNLOCK(obj);
672			}
673		}
674		if (tmpe->wired_count > 0)
675			nothingwired = FALSE;
676		tmpe = tmpe->next;
677	}
678
679	if (bigobj != NULL) {
680		vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
681		VM_OBJECT_UNLOCK(bigobj);
682	}
683	/*
684	 * Next, hunt around for other pages to deactivate.  We actually
685	 * do this search sort of wrong -- .text first is not the best idea.
686	 */
687	tmpe = map->header.next;
688	while (tmpe != &map->header) {
689		if (pmap_resident_count(vm_map_pmap(map)) <= desired)
690			break;
691		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
692			obj = tmpe->object.vm_object;
693			if (obj != NULL) {
694				VM_OBJECT_LOCK(obj);
695				vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
696				VM_OBJECT_UNLOCK(obj);
697			}
698		}
699		tmpe = tmpe->next;
700	}
701
702	/*
703	 * Remove all mappings if a process is swapped out, this will free page
704	 * table pages.
705	 */
706	if (desired == 0 && nothingwired) {
707		pmap_remove(vm_map_pmap(map), vm_map_min(map),
708		    vm_map_max(map));
709	}
710	vm_map_unlock(map);
711}
712#endif		/* !defined(NO_SWAPPING) */
713
714/*
715 *	vm_pageout_scan does the dirty work for the pageout daemon.
716 */
717static void
718vm_pageout_scan(int pass)
719{
720	vm_page_t m, next;
721	struct vm_page marker;
722	int page_shortage, maxscan, pcount;
723	int addl_page_shortage, addl_page_shortage_init;
724	vm_object_t object;
725	int actcount;
726	int vnodes_skipped = 0;
727	int maxlaunder;
728
729	/*
730	 * Decrease registered cache sizes.
731	 */
732	EVENTHANDLER_INVOKE(vm_lowmem, 0);
733	/*
734	 * We do this explicitly after the caches have been drained above.
735	 */
736	uma_reclaim();
737
738	addl_page_shortage_init = atomic_readandclear_int(&vm_pageout_deficit);
739
740	/*
741	 * Calculate the number of pages we want to either free or move
742	 * to the cache.
743	 */
744	page_shortage = vm_paging_target() + addl_page_shortage_init;
745
746	vm_pageout_init_marker(&marker, PQ_INACTIVE);
747
748	/*
749	 * Start scanning the inactive queue for pages we can move to the
750	 * cache or free.  The scan will stop when the target is reached or
751	 * we have scanned the entire inactive queue.  Note that m->act_count
752	 * is not used to form decisions for the inactive queue, only for the
753	 * active queue.
754	 *
755	 * maxlaunder limits the number of dirty pages we flush per scan.
756	 * For most systems a smaller value (16 or 32) is more robust under
757	 * extreme memory and disk pressure because any unnecessary writes
758	 * to disk can result in extreme performance degredation.  However,
759	 * systems with excessive dirty pages (especially when MAP_NOSYNC is
760	 * used) will die horribly with limited laundering.  If the pageout
761	 * daemon cannot clean enough pages in the first pass, we let it go
762	 * all out in succeeding passes.
763	 */
764	if ((maxlaunder = vm_max_launder) <= 1)
765		maxlaunder = 1;
766	if (pass)
767		maxlaunder = 10000;
768	vm_page_lock_queues();
769rescan0:
770	addl_page_shortage = addl_page_shortage_init;
771	maxscan = cnt.v_inactive_count;
772
773	for (m = TAILQ_FIRST(&vm_page_queues[PQ_INACTIVE].pl);
774	     m != NULL && maxscan-- > 0 && page_shortage > 0;
775	     m = next) {
776
777		cnt.v_pdpages++;
778
779		if (VM_PAGE_GETQUEUE(m) != PQ_INACTIVE) {
780			goto rescan0;
781		}
782
783		next = TAILQ_NEXT(m, pageq);
784
785		/*
786		 * skip marker pages
787		 */
788		if (m->flags & PG_MARKER)
789			continue;
790
791		/*
792		 * Lock the page.
793		 */
794		if (!vm_pageout_page_lock(m, &next)) {
795			vm_page_unlock(m);
796			addl_page_shortage++;
797			continue;
798		}
799
800		/*
801		 * A held page may be undergoing I/O, so skip it.
802		 */
803		if (m->hold_count) {
804			vm_page_unlock(m);
805			vm_page_requeue(m);
806			addl_page_shortage++;
807			continue;
808		}
809
810		/*
811		 * Don't mess with busy pages, keep in the front of the
812		 * queue, most likely are being paged out.
813		 */
814		object = m->object;
815		if (!VM_OBJECT_TRYLOCK(object) &&
816		    (!vm_pageout_fallback_object_lock(m, &next) ||
817			m->hold_count != 0)) {
818			VM_OBJECT_UNLOCK(object);
819			vm_page_unlock(m);
820			addl_page_shortage++;
821			continue;
822		}
823		if (m->busy || (m->oflags & VPO_BUSY)) {
824			vm_page_unlock(m);
825			VM_OBJECT_UNLOCK(object);
826			addl_page_shortage++;
827			continue;
828		}
829
830		/*
831		 * If the object is not being used, we ignore previous
832		 * references.
833		 */
834		if (object->ref_count == 0) {
835			vm_page_flag_clear(m, PG_REFERENCED);
836			KASSERT(!pmap_page_is_mapped(m),
837			    ("vm_pageout_scan: page %p is mapped", m));
838
839		/*
840		 * Otherwise, if the page has been referenced while in the
841		 * inactive queue, we bump the "activation count" upwards,
842		 * making it less likely that the page will be added back to
843		 * the inactive queue prematurely again.  Here we check the
844		 * page tables (or emulated bits, if any), given the upper
845		 * level VM system not knowing anything about existing
846		 * references.
847		 */
848		} else if (((m->flags & PG_REFERENCED) == 0) &&
849			(actcount = pmap_ts_referenced(m))) {
850			vm_page_activate(m);
851			VM_OBJECT_UNLOCK(object);
852			m->act_count += (actcount + ACT_ADVANCE);
853			vm_page_unlock(m);
854			continue;
855		}
856
857		/*
858		 * If the upper level VM system knows about any page
859		 * references, we activate the page.  We also set the
860		 * "activation count" higher than normal so that we will less
861		 * likely place pages back onto the inactive queue again.
862		 */
863		if ((m->flags & PG_REFERENCED) != 0) {
864			vm_page_flag_clear(m, PG_REFERENCED);
865			actcount = pmap_ts_referenced(m);
866			vm_page_activate(m);
867			VM_OBJECT_UNLOCK(object);
868			m->act_count += (actcount + ACT_ADVANCE + 1);
869			vm_page_unlock(m);
870			continue;
871		}
872
873		/*
874		 * If the upper level VM system does not believe that the page
875		 * is fully dirty, but it is mapped for write access, then we
876		 * consult the pmap to see if the page's dirty status should
877		 * be updated.
878		 */
879		if (m->dirty != VM_PAGE_BITS_ALL &&
880		    (m->flags & PG_WRITEABLE) != 0) {
881			/*
882			 * Avoid a race condition: Unless write access is
883			 * removed from the page, another processor could
884			 * modify it before all access is removed by the call
885			 * to vm_page_cache() below.  If vm_page_cache() finds
886			 * that the page has been modified when it removes all
887			 * access, it panics because it cannot cache dirty
888			 * pages.  In principle, we could eliminate just write
889			 * access here rather than all access.  In the expected
890			 * case, when there are no last instant modifications
891			 * to the page, removing all access will be cheaper
892			 * overall.
893			 */
894			if (pmap_is_modified(m))
895				vm_page_dirty(m);
896			else if (m->dirty == 0)
897				pmap_remove_all(m);
898		}
899
900		if (m->valid == 0) {
901			/*
902			 * Invalid pages can be easily freed
903			 */
904			vm_page_free(m);
905			cnt.v_dfree++;
906			--page_shortage;
907		} else if (m->dirty == 0) {
908			/*
909			 * Clean pages can be placed onto the cache queue.
910			 * This effectively frees them.
911			 */
912			vm_page_cache(m);
913			--page_shortage;
914		} else if ((m->flags & PG_WINATCFLS) == 0 && pass == 0) {
915			/*
916			 * Dirty pages need to be paged out, but flushing
917			 * a page is extremely expensive verses freeing
918			 * a clean page.  Rather then artificially limiting
919			 * the number of pages we can flush, we instead give
920			 * dirty pages extra priority on the inactive queue
921			 * by forcing them to be cycled through the queue
922			 * twice before being flushed, after which the
923			 * (now clean) page will cycle through once more
924			 * before being freed.  This significantly extends
925			 * the thrash point for a heavily loaded machine.
926			 */
927			vm_page_flag_set(m, PG_WINATCFLS);
928			vm_page_requeue(m);
929		} else if (maxlaunder > 0) {
930			/*
931			 * We always want to try to flush some dirty pages if
932			 * we encounter them, to keep the system stable.
933			 * Normally this number is small, but under extreme
934			 * pressure where there are insufficient clean pages
935			 * on the inactive queue, we may have to go all out.
936			 */
937			int swap_pageouts_ok, vfslocked = 0;
938			struct vnode *vp = NULL;
939			struct mount *mp = NULL;
940
941			if ((object->type != OBJT_SWAP) && (object->type != OBJT_DEFAULT)) {
942				swap_pageouts_ok = 1;
943			} else {
944				swap_pageouts_ok = !(defer_swap_pageouts || disable_swap_pageouts);
945				swap_pageouts_ok |= (!disable_swap_pageouts && defer_swap_pageouts &&
946				vm_page_count_min());
947
948			}
949
950			/*
951			 * We don't bother paging objects that are "dead".
952			 * Those objects are in a "rundown" state.
953			 */
954			if (!swap_pageouts_ok || (object->flags & OBJ_DEAD)) {
955				vm_page_unlock(m);
956				VM_OBJECT_UNLOCK(object);
957				vm_page_requeue(m);
958				continue;
959			}
960
961			/*
962			 * Following operations may unlock
963			 * vm_page_queue_mtx, invalidating the 'next'
964			 * pointer.  To prevent an inordinate number
965			 * of restarts we use our marker to remember
966			 * our place.
967			 *
968			 */
969			TAILQ_INSERT_AFTER(&vm_page_queues[PQ_INACTIVE].pl,
970					   m, &marker, pageq);
971			/*
972			 * The object is already known NOT to be dead.   It
973			 * is possible for the vget() to block the whole
974			 * pageout daemon, but the new low-memory handling
975			 * code should prevent it.
976			 *
977			 * The previous code skipped locked vnodes and, worse,
978			 * reordered pages in the queue.  This results in
979			 * completely non-deterministic operation and, on a
980			 * busy system, can lead to extremely non-optimal
981			 * pageouts.  For example, it can cause clean pages
982			 * to be freed and dirty pages to be moved to the end
983			 * of the queue.  Since dirty pages are also moved to
984			 * the end of the queue once-cleaned, this gives
985			 * way too large a weighting to defering the freeing
986			 * of dirty pages.
987			 *
988			 * We can't wait forever for the vnode lock, we might
989			 * deadlock due to a vn_read() getting stuck in
990			 * vm_wait while holding this vnode.  We skip the
991			 * vnode if we can't get it in a reasonable amount
992			 * of time.
993			 */
994			if (object->type == OBJT_VNODE) {
995				vm_page_unlock_queues();
996				vm_page_unlock(m);
997				vp = object->handle;
998				if (vp->v_type == VREG &&
999				    vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1000					mp = NULL;
1001					++pageout_lock_miss;
1002					if (object->flags & OBJ_MIGHTBEDIRTY)
1003						vnodes_skipped++;
1004					vm_page_lock_queues();
1005					goto unlock_and_continue;
1006				}
1007				KASSERT(mp != NULL,
1008				    ("vp %p with NULL v_mount", vp));
1009				vm_object_reference_locked(object);
1010				VM_OBJECT_UNLOCK(object);
1011				vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1012				if (vget(vp, LK_EXCLUSIVE | LK_TIMELOCK,
1013				    curthread)) {
1014					VM_OBJECT_LOCK(object);
1015					vm_page_lock_queues();
1016					++pageout_lock_miss;
1017					if (object->flags & OBJ_MIGHTBEDIRTY)
1018						vnodes_skipped++;
1019					vp = NULL;
1020					goto unlock_and_continue;
1021				}
1022				VM_OBJECT_LOCK(object);
1023				vm_page_lock(m);
1024				vm_page_lock_queues();
1025				/*
1026				 * The page might have been moved to another
1027				 * queue during potential blocking in vget()
1028				 * above.  The page might have been freed and
1029				 * reused for another vnode.
1030				 */
1031				if (VM_PAGE_GETQUEUE(m) != PQ_INACTIVE ||
1032				    m->object != object ||
1033				    TAILQ_NEXT(m, pageq) != &marker) {
1034					vm_page_unlock(m);
1035					if (object->flags & OBJ_MIGHTBEDIRTY)
1036						vnodes_skipped++;
1037					goto unlock_and_continue;
1038				}
1039
1040				/*
1041				 * The page may have been busied during the
1042				 * blocking in vget().  We don't move the
1043				 * page back onto the end of the queue so that
1044				 * statistics are more correct if we don't.
1045				 */
1046				if (m->busy || (m->oflags & VPO_BUSY)) {
1047					vm_page_unlock(m);
1048					goto unlock_and_continue;
1049				}
1050
1051				/*
1052				 * If the page has become held it might
1053				 * be undergoing I/O, so skip it
1054				 */
1055				if (m->hold_count) {
1056					vm_page_unlock(m);
1057					vm_page_requeue(m);
1058					if (object->flags & OBJ_MIGHTBEDIRTY)
1059						vnodes_skipped++;
1060					goto unlock_and_continue;
1061				}
1062			}
1063			vm_page_unlock(m);
1064
1065			/*
1066			 * If a page is dirty, then it is either being washed
1067			 * (but not yet cleaned) or it is still in the
1068			 * laundry.  If it is still in the laundry, then we
1069			 * start the cleaning operation.
1070			 *
1071			 * decrement page_shortage on success to account for
1072			 * the (future) cleaned page.  Otherwise we could wind
1073			 * up laundering or cleaning too many pages.
1074			 */
1075			vm_page_unlock_queues();
1076			if (vm_pageout_clean(m) != 0) {
1077				--page_shortage;
1078				--maxlaunder;
1079			}
1080			vm_page_lock_queues();
1081unlock_and_continue:
1082			vm_page_lock_assert(m, MA_NOTOWNED);
1083			VM_OBJECT_UNLOCK(object);
1084			if (mp != NULL) {
1085				vm_page_unlock_queues();
1086				if (vp != NULL)
1087					vput(vp);
1088				VFS_UNLOCK_GIANT(vfslocked);
1089				vm_object_deallocate(object);
1090				vn_finished_write(mp);
1091				vm_page_lock_queues();
1092			}
1093			next = TAILQ_NEXT(&marker, pageq);
1094			TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE].pl,
1095				     &marker, pageq);
1096			vm_page_lock_assert(m, MA_NOTOWNED);
1097			continue;
1098		}
1099		vm_page_unlock(m);
1100		VM_OBJECT_UNLOCK(object);
1101	}
1102
1103	/*
1104	 * Compute the number of pages we want to try to move from the
1105	 * active queue to the inactive queue.
1106	 */
1107	page_shortage = vm_paging_target() +
1108		cnt.v_inactive_target - cnt.v_inactive_count;
1109	page_shortage += addl_page_shortage;
1110
1111	/*
1112	 * Scan the active queue for things we can deactivate. We nominally
1113	 * track the per-page activity counter and use it to locate
1114	 * deactivation candidates.
1115	 */
1116	pcount = cnt.v_active_count;
1117	m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1118	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1119
1120	while ((m != NULL) && (pcount-- > 0) && (page_shortage > 0)) {
1121
1122		KASSERT(VM_PAGE_INQUEUE2(m, PQ_ACTIVE),
1123		    ("vm_pageout_scan: page %p isn't active", m));
1124
1125		next = TAILQ_NEXT(m, pageq);
1126		if ((m->flags & PG_MARKER) != 0) {
1127			m = next;
1128			continue;
1129		}
1130		if (!vm_pageout_page_lock(m, &next)) {
1131			vm_page_unlock(m);
1132			m = next;
1133			continue;
1134		}
1135		object = m->object;
1136		if (!VM_OBJECT_TRYLOCK(object) &&
1137		    !vm_pageout_fallback_object_lock(m, &next)) {
1138			VM_OBJECT_UNLOCK(object);
1139			vm_page_unlock(m);
1140			m = next;
1141			continue;
1142		}
1143
1144		/*
1145		 * Don't deactivate pages that are busy.
1146		 */
1147		if ((m->busy != 0) ||
1148		    (m->oflags & VPO_BUSY) ||
1149		    (m->hold_count != 0)) {
1150			vm_page_unlock(m);
1151			VM_OBJECT_UNLOCK(object);
1152			vm_page_requeue(m);
1153			m = next;
1154			continue;
1155		}
1156
1157		/*
1158		 * The count for pagedaemon pages is done after checking the
1159		 * page for eligibility...
1160		 */
1161		cnt.v_pdpages++;
1162
1163		/*
1164		 * Check to see "how much" the page has been used.
1165		 */
1166		actcount = 0;
1167		if (object->ref_count != 0) {
1168			if (m->flags & PG_REFERENCED) {
1169				actcount += 1;
1170			}
1171			actcount += pmap_ts_referenced(m);
1172			if (actcount) {
1173				m->act_count += ACT_ADVANCE + actcount;
1174				if (m->act_count > ACT_MAX)
1175					m->act_count = ACT_MAX;
1176			}
1177		}
1178
1179		/*
1180		 * Since we have "tested" this bit, we need to clear it now.
1181		 */
1182		vm_page_flag_clear(m, PG_REFERENCED);
1183
1184		/*
1185		 * Only if an object is currently being used, do we use the
1186		 * page activation count stats.
1187		 */
1188		if (actcount && (object->ref_count != 0)) {
1189			vm_page_requeue(m);
1190		} else {
1191			m->act_count -= min(m->act_count, ACT_DECLINE);
1192			if (vm_pageout_algorithm ||
1193			    object->ref_count == 0 ||
1194			    m->act_count == 0) {
1195				page_shortage--;
1196				if (object->ref_count == 0) {
1197					KASSERT(!pmap_page_is_mapped(m),
1198				    ("vm_pageout_scan: page %p is mapped", m));
1199					if (m->dirty == 0)
1200						vm_page_cache(m);
1201					else
1202						vm_page_deactivate(m);
1203				} else {
1204					vm_page_deactivate(m);
1205				}
1206			} else {
1207				vm_page_requeue(m);
1208			}
1209		}
1210		vm_page_unlock(m);
1211		VM_OBJECT_UNLOCK(object);
1212		m = next;
1213	}
1214	vm_page_unlock_queues();
1215#if !defined(NO_SWAPPING)
1216	/*
1217	 * Idle process swapout -- run once per second.
1218	 */
1219	if (vm_swap_idle_enabled) {
1220		static long lsec;
1221		if (time_second != lsec) {
1222			vm_req_vmdaemon(VM_SWAP_IDLE);
1223			lsec = time_second;
1224		}
1225	}
1226#endif
1227
1228	/*
1229	 * If we didn't get enough free pages, and we have skipped a vnode
1230	 * in a writeable object, wakeup the sync daemon.  And kick swapout
1231	 * if we did not get enough free pages.
1232	 */
1233	if (vm_paging_target() > 0) {
1234		if (vnodes_skipped && vm_page_count_min())
1235			(void) speedup_syncer();
1236#if !defined(NO_SWAPPING)
1237		if (vm_swap_enabled && vm_page_count_target())
1238			vm_req_vmdaemon(VM_SWAP_NORMAL);
1239#endif
1240	}
1241
1242	/*
1243	 * If we are critically low on one of RAM or swap and low on
1244	 * the other, kill the largest process.  However, we avoid
1245	 * doing this on the first pass in order to give ourselves a
1246	 * chance to flush out dirty vnode-backed pages and to allow
1247	 * active pages to be moved to the inactive queue and reclaimed.
1248	 */
1249	if (pass != 0 &&
1250	    ((swap_pager_avail < 64 && vm_page_count_min()) ||
1251	     (swap_pager_full && vm_paging_target() > 0)))
1252		vm_pageout_oom(VM_OOM_MEM);
1253}
1254
1255
1256void
1257vm_pageout_oom(int shortage)
1258{
1259	struct proc *p, *bigproc;
1260	vm_offset_t size, bigsize;
1261	struct thread *td;
1262	struct vmspace *vm;
1263
1264	/*
1265	 * We keep the process bigproc locked once we find it to keep anyone
1266	 * from messing with it; however, there is a possibility of
1267	 * deadlock if process B is bigproc and one of it's child processes
1268	 * attempts to propagate a signal to B while we are waiting for A's
1269	 * lock while walking this list.  To avoid this, we don't block on
1270	 * the process lock but just skip a process if it is already locked.
1271	 */
1272	bigproc = NULL;
1273	bigsize = 0;
1274	sx_slock(&allproc_lock);
1275	FOREACH_PROC_IN_SYSTEM(p) {
1276		int breakout;
1277
1278		if (PROC_TRYLOCK(p) == 0)
1279			continue;
1280		/*
1281		 * If this is a system, protected or killed process, skip it.
1282		 */
1283		if ((p->p_flag & (P_INEXEC | P_PROTECTED | P_SYSTEM)) ||
1284		    (p->p_pid == 1) || P_KILLED(p) ||
1285		    ((p->p_pid < 48) && (swap_pager_avail != 0))) {
1286			PROC_UNLOCK(p);
1287			continue;
1288		}
1289		/*
1290		 * If the process is in a non-running type state,
1291		 * don't touch it.  Check all the threads individually.
1292		 */
1293		breakout = 0;
1294		FOREACH_THREAD_IN_PROC(p, td) {
1295			thread_lock(td);
1296			if (!TD_ON_RUNQ(td) &&
1297			    !TD_IS_RUNNING(td) &&
1298			    !TD_IS_SLEEPING(td)) {
1299				thread_unlock(td);
1300				breakout = 1;
1301				break;
1302			}
1303			thread_unlock(td);
1304		}
1305		if (breakout) {
1306			PROC_UNLOCK(p);
1307			continue;
1308		}
1309		/*
1310		 * get the process size
1311		 */
1312		vm = vmspace_acquire_ref(p);
1313		if (vm == NULL) {
1314			PROC_UNLOCK(p);
1315			continue;
1316		}
1317		if (!vm_map_trylock_read(&vm->vm_map)) {
1318			vmspace_free(vm);
1319			PROC_UNLOCK(p);
1320			continue;
1321		}
1322		size = vmspace_swap_count(vm);
1323		vm_map_unlock_read(&vm->vm_map);
1324		if (shortage == VM_OOM_MEM)
1325			size += vmspace_resident_count(vm);
1326		vmspace_free(vm);
1327		/*
1328		 * if the this process is bigger than the biggest one
1329		 * remember it.
1330		 */
1331		if (size > bigsize) {
1332			if (bigproc != NULL)
1333				PROC_UNLOCK(bigproc);
1334			bigproc = p;
1335			bigsize = size;
1336		} else
1337			PROC_UNLOCK(p);
1338	}
1339	sx_sunlock(&allproc_lock);
1340	if (bigproc != NULL) {
1341		killproc(bigproc, "out of swap space");
1342		sched_nice(bigproc, PRIO_MIN);
1343		PROC_UNLOCK(bigproc);
1344		wakeup(&cnt.v_free_count);
1345	}
1346}
1347
1348/*
1349 * This routine tries to maintain the pseudo LRU active queue,
1350 * so that during long periods of time where there is no paging,
1351 * that some statistic accumulation still occurs.  This code
1352 * helps the situation where paging just starts to occur.
1353 */
1354static void
1355vm_pageout_page_stats()
1356{
1357	vm_object_t object;
1358	vm_page_t m,next;
1359	int pcount,tpcount;		/* Number of pages to check */
1360	static int fullintervalcount = 0;
1361	int page_shortage;
1362
1363	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1364	page_shortage =
1365	    (cnt.v_inactive_target + cnt.v_cache_max + cnt.v_free_min) -
1366	    (cnt.v_free_count + cnt.v_inactive_count + cnt.v_cache_count);
1367
1368	if (page_shortage <= 0)
1369		return;
1370
1371	pcount = cnt.v_active_count;
1372	fullintervalcount += vm_pageout_stats_interval;
1373	if (fullintervalcount < vm_pageout_full_stats_interval) {
1374		tpcount = (int64_t)vm_pageout_stats_max * cnt.v_active_count /
1375		    cnt.v_page_count;
1376		if (pcount > tpcount)
1377			pcount = tpcount;
1378	} else {
1379		fullintervalcount = 0;
1380	}
1381
1382	m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1383	while ((m != NULL) && (pcount-- > 0)) {
1384		int actcount;
1385
1386		KASSERT(VM_PAGE_INQUEUE2(m, PQ_ACTIVE),
1387		    ("vm_pageout_page_stats: page %p isn't active", m));
1388
1389		next = TAILQ_NEXT(m, pageq);
1390		if ((m->flags & PG_MARKER) != 0) {
1391			m = next;
1392			continue;
1393		}
1394		vm_page_lock_assert(m, MA_NOTOWNED);
1395		if (!vm_pageout_page_lock(m, &next)) {
1396			vm_page_unlock(m);
1397			m = next;
1398			continue;
1399		}
1400		object = m->object;
1401		if (!VM_OBJECT_TRYLOCK(object) &&
1402		    !vm_pageout_fallback_object_lock(m, &next)) {
1403			VM_OBJECT_UNLOCK(object);
1404			vm_page_unlock(m);
1405			m = next;
1406			continue;
1407		}
1408
1409		/*
1410		 * Don't deactivate pages that are busy.
1411		 */
1412		if ((m->busy != 0) ||
1413		    (m->oflags & VPO_BUSY) ||
1414		    (m->hold_count != 0)) {
1415			vm_page_unlock(m);
1416			VM_OBJECT_UNLOCK(object);
1417			vm_page_requeue(m);
1418			m = next;
1419			continue;
1420		}
1421
1422		actcount = 0;
1423		if (m->flags & PG_REFERENCED) {
1424			vm_page_flag_clear(m, PG_REFERENCED);
1425			actcount += 1;
1426		}
1427
1428		actcount += pmap_ts_referenced(m);
1429		if (actcount) {
1430			m->act_count += ACT_ADVANCE + actcount;
1431			if (m->act_count > ACT_MAX)
1432				m->act_count = ACT_MAX;
1433			vm_page_requeue(m);
1434		} else {
1435			if (m->act_count == 0) {
1436				/*
1437				 * We turn off page access, so that we have
1438				 * more accurate RSS stats.  We don't do this
1439				 * in the normal page deactivation when the
1440				 * system is loaded VM wise, because the
1441				 * cost of the large number of page protect
1442				 * operations would be higher than the value
1443				 * of doing the operation.
1444				 */
1445				pmap_remove_all(m);
1446				vm_page_deactivate(m);
1447			} else {
1448				m->act_count -= min(m->act_count, ACT_DECLINE);
1449				vm_page_requeue(m);
1450			}
1451		}
1452		vm_page_unlock(m);
1453		VM_OBJECT_UNLOCK(object);
1454		m = next;
1455	}
1456}
1457
1458/*
1459 *	vm_pageout is the high level pageout daemon.
1460 */
1461static void
1462vm_pageout()
1463{
1464	int error, pass;
1465
1466	/*
1467	 * Initialize some paging parameters.
1468	 */
1469	cnt.v_interrupt_free_min = 2;
1470	if (cnt.v_page_count < 2000)
1471		vm_pageout_page_count = 8;
1472
1473	/*
1474	 * v_free_reserved needs to include enough for the largest
1475	 * swap pager structures plus enough for any pv_entry structs
1476	 * when paging.
1477	 */
1478	if (cnt.v_page_count > 1024)
1479		cnt.v_free_min = 4 + (cnt.v_page_count - 1024) / 200;
1480	else
1481		cnt.v_free_min = 4;
1482	cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1483	    cnt.v_interrupt_free_min;
1484	cnt.v_free_reserved = vm_pageout_page_count +
1485	    cnt.v_pageout_free_min + (cnt.v_page_count / 768);
1486	cnt.v_free_severe = cnt.v_free_min / 2;
1487	cnt.v_free_min += cnt.v_free_reserved;
1488	cnt.v_free_severe += cnt.v_free_reserved;
1489
1490	/*
1491	 * v_free_target and v_cache_min control pageout hysteresis.  Note
1492	 * that these are more a measure of the VM cache queue hysteresis
1493	 * then the VM free queue.  Specifically, v_free_target is the
1494	 * high water mark (free+cache pages).
1495	 *
1496	 * v_free_reserved + v_cache_min (mostly means v_cache_min) is the
1497	 * low water mark, while v_free_min is the stop.  v_cache_min must
1498	 * be big enough to handle memory needs while the pageout daemon
1499	 * is signalled and run to free more pages.
1500	 */
1501	if (cnt.v_free_count > 6144)
1502		cnt.v_free_target = 4 * cnt.v_free_min + cnt.v_free_reserved;
1503	else
1504		cnt.v_free_target = 2 * cnt.v_free_min + cnt.v_free_reserved;
1505
1506	if (cnt.v_free_count > 2048) {
1507		cnt.v_cache_min = cnt.v_free_target;
1508		cnt.v_cache_max = 2 * cnt.v_cache_min;
1509		cnt.v_inactive_target = (3 * cnt.v_free_target) / 2;
1510	} else {
1511		cnt.v_cache_min = 0;
1512		cnt.v_cache_max = 0;
1513		cnt.v_inactive_target = cnt.v_free_count / 4;
1514	}
1515	if (cnt.v_inactive_target > cnt.v_free_count / 3)
1516		cnt.v_inactive_target = cnt.v_free_count / 3;
1517
1518	/* XXX does not really belong here */
1519	if (vm_page_max_wired == 0)
1520		vm_page_max_wired = cnt.v_free_count / 3;
1521
1522	if (vm_pageout_stats_max == 0)
1523		vm_pageout_stats_max = cnt.v_free_target;
1524
1525	/*
1526	 * Set interval in seconds for stats scan.
1527	 */
1528	if (vm_pageout_stats_interval == 0)
1529		vm_pageout_stats_interval = 5;
1530	if (vm_pageout_full_stats_interval == 0)
1531		vm_pageout_full_stats_interval = vm_pageout_stats_interval * 4;
1532
1533	swap_pager_swap_init();
1534	pass = 0;
1535	/*
1536	 * The pageout daemon is never done, so loop forever.
1537	 */
1538	while (TRUE) {
1539		/*
1540		 * If we have enough free memory, wakeup waiters.  Do
1541		 * not clear vm_pages_needed until we reach our target,
1542		 * otherwise we may be woken up over and over again and
1543		 * waste a lot of cpu.
1544		 */
1545		mtx_lock(&vm_page_queue_free_mtx);
1546		if (vm_pages_needed && !vm_page_count_min()) {
1547			if (!vm_paging_needed())
1548				vm_pages_needed = 0;
1549			wakeup(&cnt.v_free_count);
1550		}
1551		if (vm_pages_needed) {
1552			/*
1553			 * Still not done, take a second pass without waiting
1554			 * (unlimited dirty cleaning), otherwise sleep a bit
1555			 * and try again.
1556			 */
1557			++pass;
1558			if (pass > 1)
1559				msleep(&vm_pages_needed,
1560				    &vm_page_queue_free_mtx, PVM, "psleep",
1561				    hz / 2);
1562		} else {
1563			/*
1564			 * Good enough, sleep & handle stats.  Prime the pass
1565			 * for the next run.
1566			 */
1567			if (pass > 1)
1568				pass = 1;
1569			else
1570				pass = 0;
1571			error = msleep(&vm_pages_needed,
1572			    &vm_page_queue_free_mtx, PVM, "psleep",
1573			    vm_pageout_stats_interval * hz);
1574			if (error && !vm_pages_needed) {
1575				mtx_unlock(&vm_page_queue_free_mtx);
1576				pass = 0;
1577				vm_page_lock_queues();
1578				vm_pageout_page_stats();
1579				vm_page_unlock_queues();
1580				continue;
1581			}
1582		}
1583		if (vm_pages_needed)
1584			cnt.v_pdwakeups++;
1585		mtx_unlock(&vm_page_queue_free_mtx);
1586		vm_pageout_scan(pass);
1587	}
1588}
1589
1590/*
1591 * Unless the free page queue lock is held by the caller, this function
1592 * should be regarded as advisory.  Specifically, the caller should
1593 * not msleep() on &cnt.v_free_count following this function unless
1594 * the free page queue lock is held until the msleep() is performed.
1595 */
1596void
1597pagedaemon_wakeup()
1598{
1599
1600	if (!vm_pages_needed && curthread->td_proc != pageproc) {
1601		vm_pages_needed = 1;
1602		wakeup(&vm_pages_needed);
1603	}
1604}
1605
1606#if !defined(NO_SWAPPING)
1607static void
1608vm_req_vmdaemon(int req)
1609{
1610	static int lastrun = 0;
1611
1612	mtx_lock(&vm_daemon_mtx);
1613	vm_pageout_req_swapout |= req;
1614	if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
1615		wakeup(&vm_daemon_needed);
1616		lastrun = ticks;
1617	}
1618	mtx_unlock(&vm_daemon_mtx);
1619}
1620
1621static void
1622vm_daemon()
1623{
1624	struct rlimit rsslim;
1625	struct proc *p;
1626	struct thread *td;
1627	struct vmspace *vm;
1628	int breakout, swapout_flags;
1629
1630	while (TRUE) {
1631		mtx_lock(&vm_daemon_mtx);
1632		msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep", 0);
1633		swapout_flags = vm_pageout_req_swapout;
1634		vm_pageout_req_swapout = 0;
1635		mtx_unlock(&vm_daemon_mtx);
1636		if (swapout_flags)
1637			swapout_procs(swapout_flags);
1638
1639		/*
1640		 * scan the processes for exceeding their rlimits or if
1641		 * process is swapped out -- deactivate pages
1642		 */
1643		sx_slock(&allproc_lock);
1644		FOREACH_PROC_IN_SYSTEM(p) {
1645			vm_pindex_t limit, size;
1646
1647			/*
1648			 * if this is a system process or if we have already
1649			 * looked at this process, skip it.
1650			 */
1651			PROC_LOCK(p);
1652			if (p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
1653				PROC_UNLOCK(p);
1654				continue;
1655			}
1656			/*
1657			 * if the process is in a non-running type state,
1658			 * don't touch it.
1659			 */
1660			breakout = 0;
1661			FOREACH_THREAD_IN_PROC(p, td) {
1662				thread_lock(td);
1663				if (!TD_ON_RUNQ(td) &&
1664				    !TD_IS_RUNNING(td) &&
1665				    !TD_IS_SLEEPING(td)) {
1666					thread_unlock(td);
1667					breakout = 1;
1668					break;
1669				}
1670				thread_unlock(td);
1671			}
1672			if (breakout) {
1673				PROC_UNLOCK(p);
1674				continue;
1675			}
1676			/*
1677			 * get a limit
1678			 */
1679			lim_rlimit(p, RLIMIT_RSS, &rsslim);
1680			limit = OFF_TO_IDX(
1681			    qmin(rsslim.rlim_cur, rsslim.rlim_max));
1682
1683			/*
1684			 * let processes that are swapped out really be
1685			 * swapped out set the limit to nothing (will force a
1686			 * swap-out.)
1687			 */
1688			if ((p->p_flag & P_INMEM) == 0)
1689				limit = 0;	/* XXX */
1690			vm = vmspace_acquire_ref(p);
1691			PROC_UNLOCK(p);
1692			if (vm == NULL)
1693				continue;
1694
1695			size = vmspace_resident_count(vm);
1696			if (limit >= 0 && size >= limit) {
1697				vm_pageout_map_deactivate_pages(
1698				    &vm->vm_map, limit);
1699			}
1700			vmspace_free(vm);
1701		}
1702		sx_sunlock(&allproc_lock);
1703	}
1704}
1705#endif			/* !defined(NO_SWAPPING) */
1706