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