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