vm_pageout.c revision 170292
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 170292 2007-06-04 21:45:18Z attilio $");
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,
444	    (flags | ((object == kernel_object) ? VM_PAGER_PUT_SYNC : 0)),
445	    pageout_status);
446
447	vm_page_lock_queues();
448	for (i = 0; i < count; i++) {
449		vm_page_t mt = mc[i];
450
451		KASSERT((mt->flags & PG_WRITEABLE) == 0,
452		    ("vm_pageout_flush: page %p is not write protected", mt));
453		switch (pageout_status[i]) {
454		case VM_PAGER_OK:
455		case VM_PAGER_PEND:
456			numpagedout++;
457			break;
458		case VM_PAGER_BAD:
459			/*
460			 * Page outside of range of object. Right now we
461			 * essentially lose the changes by pretending it
462			 * worked.
463			 */
464			pmap_clear_modify(mt);
465			vm_page_undirty(mt);
466			break;
467		case VM_PAGER_ERROR:
468		case VM_PAGER_FAIL:
469			/*
470			 * If page couldn't be paged out, then reactivate the
471			 * page so it doesn't clog the inactive list.  (We
472			 * will try paging out it again later).
473			 */
474			vm_page_activate(mt);
475			break;
476		case VM_PAGER_AGAIN:
477			break;
478		}
479
480		/*
481		 * If the operation is still going, leave the page busy to
482		 * block all other accesses. Also, leave the paging in
483		 * progress indicator set so that we don't attempt an object
484		 * collapse.
485		 */
486		if (pageout_status[i] != VM_PAGER_PEND) {
487			vm_object_pip_wakeup(object);
488			vm_page_io_finish(mt);
489			if (vm_page_count_severe())
490				vm_page_try_to_cache(mt);
491		}
492	}
493	return numpagedout;
494}
495
496#if !defined(NO_SWAPPING)
497/*
498 *	vm_pageout_object_deactivate_pages
499 *
500 *	deactivate enough pages to satisfy the inactive target
501 *	requirements or if vm_page_proc_limit is set, then
502 *	deactivate all of the pages in the object and its
503 *	backing_objects.
504 *
505 *	The object and map must be locked.
506 */
507static void
508vm_pageout_object_deactivate_pages(pmap, first_object, desired)
509	pmap_t pmap;
510	vm_object_t first_object;
511	long desired;
512{
513	vm_object_t backing_object, object;
514	vm_page_t p, next;
515	int actcount, rcount, remove_mode;
516
517	VM_OBJECT_LOCK_ASSERT(first_object, MA_OWNED);
518	if (first_object->type == OBJT_DEVICE || first_object->type == OBJT_PHYS)
519		return;
520	for (object = first_object;; object = backing_object) {
521		if (pmap_resident_count(pmap) <= desired)
522			goto unlock_return;
523		if (object->paging_in_progress)
524			goto unlock_return;
525
526		remove_mode = 0;
527		if (object->shadow_count > 1)
528			remove_mode = 1;
529		/*
530		 * scan the objects entire memory queue
531		 */
532		rcount = object->resident_page_count;
533		p = TAILQ_FIRST(&object->memq);
534		vm_page_lock_queues();
535		while (p && (rcount-- > 0)) {
536			if (pmap_resident_count(pmap) <= desired) {
537				vm_page_unlock_queues();
538				goto unlock_return;
539			}
540			next = TAILQ_NEXT(p, listq);
541			PCPU_INC(cnt.v_pdpages);
542			if (p->wire_count != 0 ||
543			    p->hold_count != 0 ||
544			    p->busy != 0 ||
545			    (p->oflags & VPO_BUSY) ||
546			    (p->flags & PG_UNMANAGED) ||
547			    !pmap_page_exists_quick(pmap, p)) {
548				p = next;
549				continue;
550			}
551			actcount = pmap_ts_referenced(p);
552			if (actcount) {
553				vm_page_flag_set(p, PG_REFERENCED);
554			} else if (p->flags & PG_REFERENCED) {
555				actcount = 1;
556			}
557			if ((p->queue != PQ_ACTIVE) &&
558				(p->flags & PG_REFERENCED)) {
559				vm_page_activate(p);
560				p->act_count += actcount;
561				vm_page_flag_clear(p, PG_REFERENCED);
562			} else if (p->queue == PQ_ACTIVE) {
563				if ((p->flags & PG_REFERENCED) == 0) {
564					p->act_count -= min(p->act_count, ACT_DECLINE);
565					if (!remove_mode && (vm_pageout_algorithm || (p->act_count == 0))) {
566						pmap_remove_all(p);
567						vm_page_deactivate(p);
568					} else {
569						vm_pageq_requeue(p);
570					}
571				} else {
572					vm_page_activate(p);
573					vm_page_flag_clear(p, PG_REFERENCED);
574					if (p->act_count < (ACT_MAX - ACT_ADVANCE))
575						p->act_count += ACT_ADVANCE;
576					vm_pageq_requeue(p);
577				}
578			} else if (p->queue == PQ_INACTIVE) {
579				pmap_remove_all(p);
580			}
581			p = next;
582		}
583		vm_page_unlock_queues();
584		if ((backing_object = object->backing_object) == NULL)
585			goto unlock_return;
586		VM_OBJECT_LOCK(backing_object);
587		if (object != first_object)
588			VM_OBJECT_UNLOCK(object);
589	}
590unlock_return:
591	if (object != first_object)
592		VM_OBJECT_UNLOCK(object);
593}
594
595/*
596 * deactivate some number of pages in a map, try to do it fairly, but
597 * that is really hard to do.
598 */
599static void
600vm_pageout_map_deactivate_pages(map, desired)
601	vm_map_t map;
602	long desired;
603{
604	vm_map_entry_t tmpe;
605	vm_object_t obj, bigobj;
606	int nothingwired;
607
608	if (!vm_map_trylock(map))
609		return;
610
611	bigobj = NULL;
612	nothingwired = TRUE;
613
614	/*
615	 * first, search out the biggest object, and try to free pages from
616	 * that.
617	 */
618	tmpe = map->header.next;
619	while (tmpe != &map->header) {
620		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
621			obj = tmpe->object.vm_object;
622			if (obj != NULL && VM_OBJECT_TRYLOCK(obj)) {
623				if (obj->shadow_count <= 1 &&
624				    (bigobj == NULL ||
625				     bigobj->resident_page_count < obj->resident_page_count)) {
626					if (bigobj != NULL)
627						VM_OBJECT_UNLOCK(bigobj);
628					bigobj = obj;
629				} else
630					VM_OBJECT_UNLOCK(obj);
631			}
632		}
633		if (tmpe->wired_count > 0)
634			nothingwired = FALSE;
635		tmpe = tmpe->next;
636	}
637
638	if (bigobj != NULL) {
639		vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
640		VM_OBJECT_UNLOCK(bigobj);
641	}
642	/*
643	 * Next, hunt around for other pages to deactivate.  We actually
644	 * do this search sort of wrong -- .text first is not the best idea.
645	 */
646	tmpe = map->header.next;
647	while (tmpe != &map->header) {
648		if (pmap_resident_count(vm_map_pmap(map)) <= desired)
649			break;
650		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
651			obj = tmpe->object.vm_object;
652			if (obj != NULL) {
653				VM_OBJECT_LOCK(obj);
654				vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
655				VM_OBJECT_UNLOCK(obj);
656			}
657		}
658		tmpe = tmpe->next;
659	}
660
661	/*
662	 * Remove all mappings if a process is swapped out, this will free page
663	 * table pages.
664	 */
665	if (desired == 0 && nothingwired) {
666		pmap_remove(vm_map_pmap(map), vm_map_min(map),
667		    vm_map_max(map));
668	}
669	vm_map_unlock(map);
670}
671#endif		/* !defined(NO_SWAPPING) */
672
673/*
674 *	vm_pageout_scan does the dirty work for the pageout daemon.
675 */
676static void
677vm_pageout_scan(int pass)
678{
679	vm_page_t m, next;
680	struct vm_page marker;
681	int page_shortage, maxscan, pcount;
682	int addl_page_shortage, addl_page_shortage_init;
683	struct proc *p, *bigproc;
684	struct thread *td;
685	vm_offset_t size, bigsize;
686	vm_object_t object;
687	int actcount, cache_cur, cache_first_failure;
688	static int cache_last_free;
689	int vnodes_skipped = 0;
690	int maxlaunder;
691
692	mtx_lock(&Giant);
693	/*
694	 * Decrease registered cache sizes.
695	 */
696	EVENTHANDLER_INVOKE(vm_lowmem, 0);
697	/*
698	 * We do this explicitly after the caches have been drained above.
699	 */
700	uma_reclaim();
701
702	addl_page_shortage_init = atomic_readandclear_int(&vm_pageout_deficit);
703
704	/*
705	 * Calculate the number of pages we want to either free or move
706	 * to the cache.
707	 */
708	page_shortage = vm_paging_target() + addl_page_shortage_init;
709
710	/*
711	 * Initialize our marker
712	 */
713	bzero(&marker, sizeof(marker));
714	marker.flags = PG_FICTITIOUS | PG_MARKER;
715	marker.oflags = VPO_BUSY;
716	marker.queue = PQ_INACTIVE;
717	marker.wire_count = 1;
718
719	/*
720	 * Start scanning the inactive queue for pages we can move to the
721	 * cache or free.  The scan will stop when the target is reached or
722	 * we have scanned the entire inactive queue.  Note that m->act_count
723	 * is not used to form decisions for the inactive queue, only for the
724	 * active queue.
725	 *
726	 * maxlaunder limits the number of dirty pages we flush per scan.
727	 * For most systems a smaller value (16 or 32) is more robust under
728	 * extreme memory and disk pressure because any unnecessary writes
729	 * to disk can result in extreme performance degredation.  However,
730	 * systems with excessive dirty pages (especially when MAP_NOSYNC is
731	 * used) will die horribly with limited laundering.  If the pageout
732	 * daemon cannot clean enough pages in the first pass, we let it go
733	 * all out in succeeding passes.
734	 */
735	if ((maxlaunder = vm_max_launder) <= 1)
736		maxlaunder = 1;
737	if (pass)
738		maxlaunder = 10000;
739	vm_page_lock_queues();
740rescan0:
741	addl_page_shortage = addl_page_shortage_init;
742	maxscan = cnt.v_inactive_count;
743
744	for (m = TAILQ_FIRST(&vm_page_queues[PQ_INACTIVE].pl);
745	     m != NULL && maxscan-- > 0 && page_shortage > 0;
746	     m = next) {
747
748		PCPU_INC(cnt.v_pdpages);
749
750		if (VM_PAGE_GETQUEUE(m) != PQ_INACTIVE) {
751			goto rescan0;
752		}
753
754		next = TAILQ_NEXT(m, pageq);
755		object = m->object;
756
757		/*
758		 * skip marker pages
759		 */
760		if (m->flags & PG_MARKER)
761			continue;
762
763		/*
764		 * A held page may be undergoing I/O, so skip it.
765		 */
766		if (m->hold_count) {
767			vm_pageq_requeue(m);
768			addl_page_shortage++;
769			continue;
770		}
771		/*
772		 * Don't mess with busy pages, keep in the front of the
773		 * queue, most likely are being paged out.
774		 */
775		if (!VM_OBJECT_TRYLOCK(object) &&
776		    (!vm_pageout_fallback_object_lock(m, &next) ||
777		     m->hold_count != 0)) {
778			VM_OBJECT_UNLOCK(object);
779			addl_page_shortage++;
780			continue;
781		}
782		if (m->busy || (m->oflags & VPO_BUSY)) {
783			VM_OBJECT_UNLOCK(object);
784			addl_page_shortage++;
785			continue;
786		}
787
788		/*
789		 * If the object is not being used, we ignore previous
790		 * references.
791		 */
792		if (object->ref_count == 0) {
793			vm_page_flag_clear(m, PG_REFERENCED);
794			pmap_clear_reference(m);
795
796		/*
797		 * Otherwise, if the page has been referenced while in the
798		 * inactive queue, we bump the "activation count" upwards,
799		 * making it less likely that the page will be added back to
800		 * the inactive queue prematurely again.  Here we check the
801		 * page tables (or emulated bits, if any), given the upper
802		 * level VM system not knowing anything about existing
803		 * references.
804		 */
805		} else if (((m->flags & PG_REFERENCED) == 0) &&
806			(actcount = pmap_ts_referenced(m))) {
807			vm_page_activate(m);
808			VM_OBJECT_UNLOCK(object);
809			m->act_count += (actcount + ACT_ADVANCE);
810			continue;
811		}
812
813		/*
814		 * If the upper level VM system knows about any page
815		 * references, we activate the page.  We also set the
816		 * "activation count" higher than normal so that we will less
817		 * likely place pages back onto the inactive queue again.
818		 */
819		if ((m->flags & PG_REFERENCED) != 0) {
820			vm_page_flag_clear(m, PG_REFERENCED);
821			actcount = pmap_ts_referenced(m);
822			vm_page_activate(m);
823			VM_OBJECT_UNLOCK(object);
824			m->act_count += (actcount + ACT_ADVANCE + 1);
825			continue;
826		}
827
828		/*
829		 * If the upper level VM system doesn't know anything about
830		 * the page being dirty, we have to check for it again.  As
831		 * far as the VM code knows, any partially dirty pages are
832		 * fully dirty.
833		 */
834		if (m->dirty == 0 && !pmap_is_modified(m)) {
835			/*
836			 * Avoid a race condition: Unless write access is
837			 * removed from the page, another processor could
838			 * modify it before all access is removed by the call
839			 * to vm_page_cache() below.  If vm_page_cache() finds
840			 * that the page has been modified when it removes all
841			 * access, it panics because it cannot cache dirty
842			 * pages.  In principle, we could eliminate just write
843			 * access here rather than all access.  In the expected
844			 * case, when there are no last instant modifications
845			 * to the page, removing all access will be cheaper
846			 * overall.
847			 */
848			if ((m->flags & PG_WRITEABLE) != 0)
849				pmap_remove_all(m);
850		} else {
851			vm_page_dirty(m);
852		}
853
854		if (m->valid == 0) {
855			/*
856			 * Invalid pages can be easily freed
857			 */
858			vm_page_free(m);
859			PCPU_INC(cnt.v_dfree);
860			--page_shortage;
861		} else if (m->dirty == 0) {
862			/*
863			 * Clean pages can be placed onto the cache queue.
864			 * This effectively frees them.
865			 */
866			vm_page_cache(m);
867			--page_shortage;
868		} else if ((m->flags & PG_WINATCFLS) == 0 && pass == 0) {
869			/*
870			 * Dirty pages need to be paged out, but flushing
871			 * a page is extremely expensive verses freeing
872			 * a clean page.  Rather then artificially limiting
873			 * the number of pages we can flush, we instead give
874			 * dirty pages extra priority on the inactive queue
875			 * by forcing them to be cycled through the queue
876			 * twice before being flushed, after which the
877			 * (now clean) page will cycle through once more
878			 * before being freed.  This significantly extends
879			 * the thrash point for a heavily loaded machine.
880			 */
881			vm_page_flag_set(m, PG_WINATCFLS);
882			vm_pageq_requeue(m);
883		} else if (maxlaunder > 0) {
884			/*
885			 * We always want to try to flush some dirty pages if
886			 * we encounter them, to keep the system stable.
887			 * Normally this number is small, but under extreme
888			 * pressure where there are insufficient clean pages
889			 * on the inactive queue, we may have to go all out.
890			 */
891			int swap_pageouts_ok;
892			struct vnode *vp = NULL;
893			struct mount *mp;
894
895			if ((object->type != OBJT_SWAP) && (object->type != OBJT_DEFAULT)) {
896				swap_pageouts_ok = 1;
897			} else {
898				swap_pageouts_ok = !(defer_swap_pageouts || disable_swap_pageouts);
899				swap_pageouts_ok |= (!disable_swap_pageouts && defer_swap_pageouts &&
900				vm_page_count_min());
901
902			}
903
904			/*
905			 * We don't bother paging objects that are "dead".
906			 * Those objects are in a "rundown" state.
907			 */
908			if (!swap_pageouts_ok || (object->flags & OBJ_DEAD)) {
909				VM_OBJECT_UNLOCK(object);
910				vm_pageq_requeue(m);
911				continue;
912			}
913
914			/*
915			 * Following operations may unlock
916			 * vm_page_queue_mtx, invalidating the 'next'
917			 * pointer.  To prevent an inordinate number
918			 * of restarts we use our marker to remember
919			 * our place.
920			 *
921			 */
922			TAILQ_INSERT_AFTER(&vm_page_queues[PQ_INACTIVE].pl,
923					   m, &marker, pageq);
924			/*
925			 * The object is already known NOT to be dead.   It
926			 * is possible for the vget() to block the whole
927			 * pageout daemon, but the new low-memory handling
928			 * code should prevent it.
929			 *
930			 * The previous code skipped locked vnodes and, worse,
931			 * reordered pages in the queue.  This results in
932			 * completely non-deterministic operation and, on a
933			 * busy system, can lead to extremely non-optimal
934			 * pageouts.  For example, it can cause clean pages
935			 * to be freed and dirty pages to be moved to the end
936			 * of the queue.  Since dirty pages are also moved to
937			 * the end of the queue once-cleaned, this gives
938			 * way too large a weighting to defering the freeing
939			 * of dirty pages.
940			 *
941			 * We can't wait forever for the vnode lock, we might
942			 * deadlock due to a vn_read() getting stuck in
943			 * vm_wait while holding this vnode.  We skip the
944			 * vnode if we can't get it in a reasonable amount
945			 * of time.
946			 */
947			if (object->type == OBJT_VNODE) {
948				vp = object->handle;
949				mp = NULL;
950				if (vp->v_type == VREG &&
951				    vn_start_write(vp, &mp, V_NOWAIT) != 0) {
952					++pageout_lock_miss;
953					if (object->flags & OBJ_MIGHTBEDIRTY)
954						vnodes_skipped++;
955					vp = NULL;
956					goto unlock_and_continue;
957				}
958				vm_page_unlock_queues();
959				VI_LOCK(vp);
960				VM_OBJECT_UNLOCK(object);
961				if (vget(vp, LK_EXCLUSIVE | LK_INTERLOCK |
962				    LK_TIMELOCK, curthread)) {
963					VM_OBJECT_LOCK(object);
964					vm_page_lock_queues();
965					++pageout_lock_miss;
966					vn_finished_write(mp);
967					if (object->flags & OBJ_MIGHTBEDIRTY)
968						vnodes_skipped++;
969					vp = NULL;
970					goto unlock_and_continue;
971				}
972				VM_OBJECT_LOCK(object);
973				vm_page_lock_queues();
974				/*
975				 * The page might have been moved to another
976				 * queue during potential blocking in vget()
977				 * above.  The page might have been freed and
978				 * reused for another vnode.  The object might
979				 * have been reused for another vnode.
980				 */
981				if (VM_PAGE_GETQUEUE(m) != PQ_INACTIVE ||
982				    m->object != object ||
983				    object->handle != vp ||
984				    TAILQ_NEXT(m, pageq) != &marker) {
985					if (object->flags & OBJ_MIGHTBEDIRTY)
986						vnodes_skipped++;
987					goto unlock_and_continue;
988				}
989
990				/*
991				 * The page may have been busied during the
992				 * blocking in vput();  We don't move the
993				 * page back onto the end of the queue so that
994				 * statistics are more correct if we don't.
995				 */
996				if (m->busy || (m->oflags & VPO_BUSY)) {
997					goto unlock_and_continue;
998				}
999
1000				/*
1001				 * If the page has become held it might
1002				 * be undergoing I/O, so skip it
1003				 */
1004				if (m->hold_count) {
1005					vm_pageq_requeue(m);
1006					if (object->flags & OBJ_MIGHTBEDIRTY)
1007						vnodes_skipped++;
1008					goto unlock_and_continue;
1009				}
1010			}
1011
1012			/*
1013			 * If a page is dirty, then it is either being washed
1014			 * (but not yet cleaned) or it is still in the
1015			 * laundry.  If it is still in the laundry, then we
1016			 * start the cleaning operation.
1017			 *
1018			 * decrement page_shortage on success to account for
1019			 * the (future) cleaned page.  Otherwise we could wind
1020			 * up laundering or cleaning too many pages.
1021			 */
1022			if (vm_pageout_clean(m) != 0) {
1023				--page_shortage;
1024				--maxlaunder;
1025			}
1026unlock_and_continue:
1027			VM_OBJECT_UNLOCK(object);
1028			if (vp) {
1029				vm_page_unlock_queues();
1030				vput(vp);
1031				vn_finished_write(mp);
1032				vm_page_lock_queues();
1033			}
1034			next = TAILQ_NEXT(&marker, pageq);
1035			TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE].pl,
1036				     &marker, pageq);
1037			continue;
1038		}
1039		VM_OBJECT_UNLOCK(object);
1040	}
1041
1042	/*
1043	 * Compute the number of pages we want to try to move from the
1044	 * active queue to the inactive queue.
1045	 */
1046	page_shortage = vm_paging_target() +
1047		cnt.v_inactive_target - cnt.v_inactive_count;
1048	page_shortage += addl_page_shortage;
1049
1050	/*
1051	 * Scan the active queue for things we can deactivate. We nominally
1052	 * track the per-page activity counter and use it to locate
1053	 * deactivation candidates.
1054	 */
1055	pcount = cnt.v_active_count;
1056	m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1057
1058	while ((m != NULL) && (pcount-- > 0) && (page_shortage > 0)) {
1059
1060		KASSERT(VM_PAGE_INQUEUE2(m, PQ_ACTIVE),
1061		    ("vm_pageout_scan: page %p isn't active", m));
1062
1063		next = TAILQ_NEXT(m, pageq);
1064		object = m->object;
1065		if ((m->flags & PG_MARKER) != 0) {
1066			m = next;
1067			continue;
1068		}
1069		if (!VM_OBJECT_TRYLOCK(object) &&
1070		    !vm_pageout_fallback_object_lock(m, &next)) {
1071			VM_OBJECT_UNLOCK(object);
1072			m = next;
1073			continue;
1074		}
1075
1076		/*
1077		 * Don't deactivate pages that are busy.
1078		 */
1079		if ((m->busy != 0) ||
1080		    (m->oflags & VPO_BUSY) ||
1081		    (m->hold_count != 0)) {
1082			VM_OBJECT_UNLOCK(object);
1083			vm_pageq_requeue(m);
1084			m = next;
1085			continue;
1086		}
1087
1088		/*
1089		 * The count for pagedaemon pages is done after checking the
1090		 * page for eligibility...
1091		 */
1092		PCPU_INC(cnt.v_pdpages);
1093
1094		/*
1095		 * Check to see "how much" the page has been used.
1096		 */
1097		actcount = 0;
1098		if (object->ref_count != 0) {
1099			if (m->flags & PG_REFERENCED) {
1100				actcount += 1;
1101			}
1102			actcount += pmap_ts_referenced(m);
1103			if (actcount) {
1104				m->act_count += ACT_ADVANCE + actcount;
1105				if (m->act_count > ACT_MAX)
1106					m->act_count = ACT_MAX;
1107			}
1108		}
1109
1110		/*
1111		 * Since we have "tested" this bit, we need to clear it now.
1112		 */
1113		vm_page_flag_clear(m, PG_REFERENCED);
1114
1115		/*
1116		 * Only if an object is currently being used, do we use the
1117		 * page activation count stats.
1118		 */
1119		if (actcount && (object->ref_count != 0)) {
1120			vm_pageq_requeue(m);
1121		} else {
1122			m->act_count -= min(m->act_count, ACT_DECLINE);
1123			if (vm_pageout_algorithm ||
1124			    object->ref_count == 0 ||
1125			    m->act_count == 0) {
1126				page_shortage--;
1127				if (object->ref_count == 0) {
1128					pmap_remove_all(m);
1129					if (m->dirty == 0)
1130						vm_page_cache(m);
1131					else
1132						vm_page_deactivate(m);
1133				} else {
1134					vm_page_deactivate(m);
1135				}
1136			} else {
1137				vm_pageq_requeue(m);
1138			}
1139		}
1140		VM_OBJECT_UNLOCK(object);
1141		m = next;
1142	}
1143
1144	/*
1145	 * We try to maintain some *really* free pages, this allows interrupt
1146	 * code to be guaranteed space.  Since both cache and free queues
1147	 * are considered basically 'free', moving pages from cache to free
1148	 * does not effect other calculations.
1149	 */
1150	cache_cur = cache_last_free;
1151	cache_first_failure = -1;
1152	while (cnt.v_free_count < cnt.v_free_reserved && (cache_cur =
1153	    (cache_cur + PQ_PRIME2) & PQ_COLORMASK) != cache_first_failure) {
1154		TAILQ_FOREACH(m, &vm_page_queues[PQ_CACHE + cache_cur].pl,
1155		    pageq) {
1156			KASSERT(m->dirty == 0,
1157			    ("Found dirty cache page %p", m));
1158			KASSERT(!pmap_page_is_mapped(m),
1159			    ("Found mapped cache page %p", m));
1160			KASSERT((m->flags & PG_UNMANAGED) == 0,
1161			    ("Found unmanaged cache page %p", m));
1162			KASSERT(m->wire_count == 0,
1163			    ("Found wired cache page %p", m));
1164			if (m->hold_count == 0 && VM_OBJECT_TRYLOCK(object =
1165			    m->object)) {
1166				KASSERT((m->oflags & VPO_BUSY) == 0 &&
1167				    m->busy == 0, ("Found busy cache page %p",
1168				    m));
1169				vm_page_free(m);
1170				VM_OBJECT_UNLOCK(object);
1171				PCPU_INC(cnt.v_dfree);
1172				cache_last_free = cache_cur;
1173				cache_first_failure = -1;
1174				break;
1175			}
1176		}
1177		if (m == NULL && cache_first_failure == -1)
1178			cache_first_failure = cache_cur;
1179	}
1180	vm_page_unlock_queues();
1181#if !defined(NO_SWAPPING)
1182	/*
1183	 * Idle process swapout -- run once per second.
1184	 */
1185	if (vm_swap_idle_enabled) {
1186		static long lsec;
1187		if (time_second != lsec) {
1188			vm_pageout_req_swapout |= VM_SWAP_IDLE;
1189			vm_req_vmdaemon();
1190			lsec = time_second;
1191		}
1192	}
1193#endif
1194
1195	/*
1196	 * If we didn't get enough free pages, and we have skipped a vnode
1197	 * in a writeable object, wakeup the sync daemon.  And kick swapout
1198	 * if we did not get enough free pages.
1199	 */
1200	if (vm_paging_target() > 0) {
1201		if (vnodes_skipped && vm_page_count_min())
1202			(void) speedup_syncer();
1203#if !defined(NO_SWAPPING)
1204		if (vm_swap_enabled && vm_page_count_target()) {
1205			vm_req_vmdaemon();
1206			vm_pageout_req_swapout |= VM_SWAP_NORMAL;
1207		}
1208#endif
1209	}
1210
1211	/*
1212	 * If we are critically low on one of RAM or swap and low on
1213	 * the other, kill the largest process.  However, we avoid
1214	 * doing this on the first pass in order to give ourselves a
1215	 * chance to flush out dirty vnode-backed pages and to allow
1216	 * active pages to be moved to the inactive queue and reclaimed.
1217	 *
1218	 * We keep the process bigproc locked once we find it to keep anyone
1219	 * from messing with it; however, there is a possibility of
1220	 * deadlock if process B is bigproc and one of it's child processes
1221	 * attempts to propagate a signal to B while we are waiting for A's
1222	 * lock while walking this list.  To avoid this, we don't block on
1223	 * the process lock but just skip a process if it is already locked.
1224	 */
1225	if (pass != 0 &&
1226	    ((swap_pager_avail < 64 && vm_page_count_min()) ||
1227	     (swap_pager_full && vm_paging_target() > 0))) {
1228		bigproc = NULL;
1229		bigsize = 0;
1230		sx_slock(&allproc_lock);
1231		FOREACH_PROC_IN_SYSTEM(p) {
1232			int breakout;
1233
1234			if (PROC_TRYLOCK(p) == 0)
1235				continue;
1236			/*
1237			 * If this is a system or protected process, skip it.
1238			 */
1239			if ((p->p_flag & P_SYSTEM) || (p->p_pid == 1) ||
1240			    (p->p_flag & P_PROTECTED) ||
1241			    ((p->p_pid < 48) && (swap_pager_avail != 0))) {
1242				PROC_UNLOCK(p);
1243				continue;
1244			}
1245			/*
1246			 * If the process is in a non-running type state,
1247			 * don't touch it.  Check all the threads individually.
1248			 */
1249			mtx_lock_spin(&sched_lock);
1250			breakout = 0;
1251			FOREACH_THREAD_IN_PROC(p, td) {
1252				if (!TD_ON_RUNQ(td) &&
1253				    !TD_IS_RUNNING(td) &&
1254				    !TD_IS_SLEEPING(td)) {
1255					breakout = 1;
1256					break;
1257				}
1258			}
1259			if (breakout) {
1260				mtx_unlock_spin(&sched_lock);
1261				PROC_UNLOCK(p);
1262				continue;
1263			}
1264			mtx_unlock_spin(&sched_lock);
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			mtx_lock_spin(&sched_lock);
1291			sched_nice(bigproc, PRIO_MIN);
1292			mtx_unlock_spin(&sched_lock);
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
1431	/*
1432	 * Here adds don't need to be atomic since we are only initializing
1433	 * v_free_min and v_free_severe.
1434	 */
1435	cnt.v_free_min += cnt.v_free_reserved;
1436	cnt.v_free_severe += cnt.v_free_reserved;
1437
1438	/*
1439	 * v_free_target and v_cache_min control pageout hysteresis.  Note
1440	 * that these are more a measure of the VM cache queue hysteresis
1441	 * then the VM free queue.  Specifically, v_free_target is the
1442	 * high water mark (free+cache pages).
1443	 *
1444	 * v_free_reserved + v_cache_min (mostly means v_cache_min) is the
1445	 * low water mark, while v_free_min is the stop.  v_cache_min must
1446	 * be big enough to handle memory needs while the pageout daemon
1447	 * is signalled and run to free more pages.
1448	 */
1449	if (cnt.v_free_count > 6144)
1450		cnt.v_free_target = 4 * cnt.v_free_min + cnt.v_free_reserved;
1451	else
1452		cnt.v_free_target = 2 * cnt.v_free_min + cnt.v_free_reserved;
1453
1454	if (cnt.v_free_count > 2048) {
1455		cnt.v_cache_min = cnt.v_free_target;
1456		cnt.v_cache_max = 2 * cnt.v_cache_min;
1457		cnt.v_inactive_target = (3 * cnt.v_free_target) / 2;
1458	} else {
1459		cnt.v_cache_min = 0;
1460		cnt.v_cache_max = 0;
1461		cnt.v_inactive_target = cnt.v_free_count / 4;
1462	}
1463	if (cnt.v_inactive_target > cnt.v_free_count / 3)
1464		cnt.v_inactive_target = cnt.v_free_count / 3;
1465
1466	/* XXX does not really belong here */
1467	if (vm_page_max_wired == 0)
1468		vm_page_max_wired = cnt.v_free_count / 3;
1469
1470	if (vm_pageout_stats_max == 0)
1471		vm_pageout_stats_max = cnt.v_free_target;
1472
1473	/*
1474	 * Set interval in seconds for stats scan.
1475	 */
1476	if (vm_pageout_stats_interval == 0)
1477		vm_pageout_stats_interval = 5;
1478	if (vm_pageout_full_stats_interval == 0)
1479		vm_pageout_full_stats_interval = vm_pageout_stats_interval * 4;
1480
1481	swap_pager_swap_init();
1482	pass = 0;
1483	/*
1484	 * The pageout daemon is never done, so loop forever.
1485	 */
1486	while (TRUE) {
1487		/*
1488		 * If we have enough free memory, wakeup waiters.  Do
1489		 * not clear vm_pages_needed until we reach our target,
1490		 * otherwise we may be woken up over and over again and
1491		 * waste a lot of cpu.
1492		 */
1493		mtx_lock(&vm_page_queue_free_mtx);
1494		if (vm_pages_needed && !vm_page_count_min()) {
1495			if (!vm_paging_needed())
1496				vm_pages_needed = 0;
1497			wakeup(&cnt.v_free_count);
1498		}
1499		if (vm_pages_needed) {
1500			/*
1501			 * Still not done, take a second pass without waiting
1502			 * (unlimited dirty cleaning), otherwise sleep a bit
1503			 * and try again.
1504			 */
1505			++pass;
1506			if (pass > 1)
1507				msleep(&vm_pages_needed,
1508				    &vm_page_queue_free_mtx, PVM, "psleep",
1509				    hz / 2);
1510		} else {
1511			/*
1512			 * Good enough, sleep & handle stats.  Prime the pass
1513			 * for the next run.
1514			 */
1515			if (pass > 1)
1516				pass = 1;
1517			else
1518				pass = 0;
1519			error = msleep(&vm_pages_needed,
1520			    &vm_page_queue_free_mtx, PVM, "psleep",
1521			    vm_pageout_stats_interval * hz);
1522			if (error && !vm_pages_needed) {
1523				mtx_unlock(&vm_page_queue_free_mtx);
1524				pass = 0;
1525				vm_page_lock_queues();
1526				vm_pageout_page_stats();
1527				vm_page_unlock_queues();
1528				continue;
1529			}
1530		}
1531		if (vm_pages_needed)
1532			PCPU_INC(cnt.v_pdwakeups);
1533		mtx_unlock(&vm_page_queue_free_mtx);
1534		vm_pageout_scan(pass);
1535	}
1536}
1537
1538/*
1539 * Unless the free page queue lock is held by the caller, this function
1540 * should be regarded as advisory.  Specifically, the caller should
1541 * not msleep() on &cnt.v_free_count following this function unless
1542 * the free page queue lock is held until the msleep() is performed.
1543 */
1544void
1545pagedaemon_wakeup()
1546{
1547
1548	if (!vm_pages_needed && curthread->td_proc != pageproc) {
1549		vm_pages_needed = 1;
1550		wakeup(&vm_pages_needed);
1551	}
1552}
1553
1554#if !defined(NO_SWAPPING)
1555static void
1556vm_req_vmdaemon()
1557{
1558	static int lastrun = 0;
1559
1560	if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
1561		wakeup(&vm_daemon_needed);
1562		lastrun = ticks;
1563	}
1564}
1565
1566static void
1567vm_daemon()
1568{
1569	struct rlimit rsslim;
1570	struct proc *p;
1571	struct thread *td;
1572	int breakout;
1573
1574	mtx_lock(&Giant);
1575	while (TRUE) {
1576		tsleep(&vm_daemon_needed, PPAUSE, "psleep", 0);
1577		if (vm_pageout_req_swapout) {
1578			swapout_procs(vm_pageout_req_swapout);
1579			vm_pageout_req_swapout = 0;
1580		}
1581		/*
1582		 * scan the processes for exceeding their rlimits or if
1583		 * process is swapped out -- deactivate pages
1584		 */
1585		sx_slock(&allproc_lock);
1586		FOREACH_PROC_IN_SYSTEM(p) {
1587			vm_pindex_t limit, size;
1588
1589			/*
1590			 * if this is a system process or if we have already
1591			 * looked at this process, skip it.
1592			 */
1593			PROC_LOCK(p);
1594			if (p->p_flag & (P_SYSTEM | P_WEXIT)) {
1595				PROC_UNLOCK(p);
1596				continue;
1597			}
1598			/*
1599			 * if the process is in a non-running type state,
1600			 * don't touch it.
1601			 */
1602			mtx_lock_spin(&sched_lock);
1603			breakout = 0;
1604			FOREACH_THREAD_IN_PROC(p, td) {
1605				if (!TD_ON_RUNQ(td) &&
1606				    !TD_IS_RUNNING(td) &&
1607				    !TD_IS_SLEEPING(td)) {
1608					breakout = 1;
1609					break;
1610				}
1611			}
1612			mtx_unlock_spin(&sched_lock);
1613			if (breakout) {
1614				PROC_UNLOCK(p);
1615				continue;
1616			}
1617			/*
1618			 * get a limit
1619			 */
1620			lim_rlimit(p, RLIMIT_RSS, &rsslim);
1621			limit = OFF_TO_IDX(
1622			    qmin(rsslim.rlim_cur, rsslim.rlim_max));
1623
1624			/*
1625			 * let processes that are swapped out really be
1626			 * swapped out set the limit to nothing (will force a
1627			 * swap-out.)
1628			 */
1629			if ((p->p_sflag & PS_INMEM) == 0)
1630				limit = 0;	/* XXX */
1631			PROC_UNLOCK(p);
1632
1633			size = vmspace_resident_count(p->p_vmspace);
1634			if (limit >= 0 && size >= limit) {
1635				vm_pageout_map_deactivate_pages(
1636				    &p->p_vmspace->vm_map, limit);
1637			}
1638		}
1639		sx_sunlock(&allproc_lock);
1640	}
1641}
1642#endif			/* !defined(NO_SWAPPING) */
1643