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