vm_pageout.c revision 33108
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 * $Id: vm_pageout.c,v 1.110 1998/01/31 11:56:49 dyson Exp $
69 */
70
71/*
72 *	The proverbial page-out daemon.
73 */
74
75#include "opt_diagnostic.h"
76
77#include <sys/param.h>
78#include <sys/systm.h>
79#include <sys/kernel.h>
80#include <sys/proc.h>
81#include <sys/resourcevar.h>
82#include <sys/signalvar.h>
83#include <sys/vnode.h>
84#include <sys/vmmeter.h>
85#include <sys/sysctl.h>
86
87#include <vm/vm.h>
88#include <vm/vm_param.h>
89#include <vm/vm_prot.h>
90#include <sys/lock.h>
91#include <vm/vm_object.h>
92#include <vm/vm_page.h>
93#include <vm/vm_map.h>
94#include <vm/vm_pageout.h>
95#include <vm/vm_pager.h>
96#include <vm/swap_pager.h>
97#include <vm/vm_extern.h>
98
99/*
100 * System initialization
101 */
102
103/* the kernel process "vm_pageout"*/
104static void vm_pageout __P((void));
105static int vm_pageout_clean __P((vm_page_t, int));
106static int vm_pageout_scan __P((void));
107static int vm_pageout_free_page_calc __P((vm_size_t count));
108struct proc *pageproc;
109
110static struct kproc_desc page_kp = {
111	"pagedaemon",
112	vm_pageout,
113	&pageproc
114};
115SYSINIT_KT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, kproc_start, &page_kp)
116
117#if !defined(NO_SWAPPING)
118/* the kernel process "vm_daemon"*/
119static void vm_daemon __P((void));
120static struct	proc *vmproc;
121
122static struct kproc_desc vm_kp = {
123	"vmdaemon",
124	vm_daemon,
125	&vmproc
126};
127SYSINIT_KT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp)
128#endif
129
130
131int vm_pages_needed=0;		/* Event on which pageout daemon sleeps */
132int vm_pageout_deficit=0;	/* Estimated number of pages deficit */
133int vm_pageout_pages_needed=0;	/* flag saying that the pageout daemon needs pages */
134
135extern int npendingio;
136#if !defined(NO_SWAPPING)
137static int vm_pageout_req_swapout;	/* XXX */
138static int vm_daemon_needed;
139#endif
140extern int nswiodone;
141extern int vm_swap_size;
142extern int vfs_update_wakeup;
143int vm_pageout_stats_max=0, vm_pageout_stats_interval = 0;
144int vm_pageout_full_stats_interval = 0;
145int vm_pageout_stats_free_max=0, vm_pageout_algorithm_lru=0;
146int defer_swap_pageouts=0;
147int disable_swap_pageouts=0;
148
149int max_page_launder=100;
150#if defined(NO_SWAPPING)
151int vm_swap_enabled=0;
152int vm_swap_idle_enabled=0;
153#else
154int vm_swap_enabled=1;
155int vm_swap_idle_enabled=0;
156#endif
157
158SYSCTL_INT(_vm, VM_PAGEOUT_ALGORITHM, pageout_algorithm,
159	CTLFLAG_RW, &vm_pageout_algorithm_lru, 0, "");
160
161SYSCTL_INT(_vm, OID_AUTO, pageout_stats_max,
162	CTLFLAG_RW, &vm_pageout_stats_max, 0, "");
163
164SYSCTL_INT(_vm, OID_AUTO, pageout_full_stats_interval,
165	CTLFLAG_RW, &vm_pageout_full_stats_interval, 0, "");
166
167SYSCTL_INT(_vm, OID_AUTO, pageout_stats_interval,
168	CTLFLAG_RW, &vm_pageout_stats_interval, 0, "");
169
170SYSCTL_INT(_vm, OID_AUTO, pageout_stats_free_max,
171	CTLFLAG_RW, &vm_pageout_stats_free_max, 0, "");
172
173#if defined(NO_SWAPPING)
174SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
175	CTLFLAG_RD, &vm_swap_enabled, 0, "");
176SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
177	CTLFLAG_RD, &vm_swap_idle_enabled, 0, "");
178#else
179SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
180	CTLFLAG_RW, &vm_swap_enabled, 0, "");
181SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
182	CTLFLAG_RW, &vm_swap_idle_enabled, 0, "");
183#endif
184
185SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
186	CTLFLAG_RW, &defer_swap_pageouts, 0, "");
187
188SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
189	CTLFLAG_RW, &disable_swap_pageouts, 0, "");
190
191SYSCTL_INT(_vm, OID_AUTO, max_page_launder,
192	CTLFLAG_RW, &max_page_launder, 0, "");
193
194
195#define VM_PAGEOUT_PAGE_COUNT 8
196int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
197
198int vm_page_max_wired;		/* XXX max # of wired pages system-wide */
199
200#if !defined(NO_SWAPPING)
201typedef void freeer_fcn_t __P((vm_map_t, vm_object_t, vm_pindex_t, int));
202static void vm_pageout_map_deactivate_pages __P((vm_map_t, vm_pindex_t));
203static freeer_fcn_t vm_pageout_object_deactivate_pages;
204static void vm_req_vmdaemon __P((void));
205#endif
206static void vm_pageout_page_stats(void);
207void pmap_collect(void);
208
209/*
210 * vm_pageout_clean:
211 *
212 * Clean the page and remove it from the laundry.
213 *
214 * We set the busy bit to cause potential page faults on this page to
215 * block.
216 *
217 * And we set pageout-in-progress to keep the object from disappearing
218 * during pageout.  This guarantees that the page won't move from the
219 * inactive queue.  (However, any other page on the inactive queue may
220 * move!)
221 */
222static int
223vm_pageout_clean(m, sync)
224	vm_page_t m;
225	int sync;
226{
227	register vm_object_t object;
228	vm_page_t mc[2*vm_pageout_page_count];
229	int pageout_count;
230	int i, forward_okay, backward_okay, page_base;
231	vm_pindex_t pindex = m->pindex;
232
233	object = m->object;
234
235	/*
236	 * If not OBJT_SWAP, additional memory may be needed to do the pageout.
237	 * Try to avoid the deadlock.
238	 */
239	if ((sync != VM_PAGEOUT_FORCE) &&
240	    (object->type == OBJT_DEFAULT) &&
241	    ((cnt.v_free_count + cnt.v_cache_count) < cnt.v_pageout_free_min))
242		return 0;
243
244	/*
245	 * Don't mess with the page if it's busy.
246	 */
247	if ((!sync && m->hold_count != 0) ||
248	    ((m->busy != 0) || (m->flags & PG_BUSY)))
249		return 0;
250
251	/*
252	 * Try collapsing before it's too late.
253	 */
254	if (!sync && object->backing_object) {
255		vm_object_collapse(object);
256	}
257
258	mc[vm_pageout_page_count] = m;
259	pageout_count = 1;
260	page_base = vm_pageout_page_count;
261	forward_okay = TRUE;
262	if (pindex != 0)
263		backward_okay = TRUE;
264	else
265		backward_okay = FALSE;
266	/*
267	 * Scan object for clusterable pages.
268	 *
269	 * We can cluster ONLY if: ->> the page is NOT
270	 * clean, wired, busy, held, or mapped into a
271	 * buffer, and one of the following:
272	 * 1) The page is inactive, or a seldom used
273	 *    active page.
274	 * -or-
275	 * 2) we force the issue.
276	 */
277	for (i = 1; (i < vm_pageout_page_count) && (forward_okay || backward_okay); i++) {
278		vm_page_t p;
279
280		/*
281		 * See if forward page is clusterable.
282		 */
283		if (forward_okay) {
284			/*
285			 * Stop forward scan at end of object.
286			 */
287			if ((pindex + i) > object->size) {
288				forward_okay = FALSE;
289				goto do_backward;
290			}
291			p = vm_page_lookup(object, pindex + i);
292			if (p) {
293				if (((p->queue - p->pc) == PQ_CACHE) ||
294					(p->flags & PG_BUSY) || p->busy) {
295					forward_okay = FALSE;
296					goto do_backward;
297				}
298				vm_page_test_dirty(p);
299				if ((p->dirty & p->valid) != 0 &&
300				    ((p->queue == PQ_INACTIVE) ||
301				     (sync == VM_PAGEOUT_FORCE)) &&
302				    (p->wire_count == 0) &&
303				    (p->hold_count == 0)) {
304					mc[vm_pageout_page_count + i] = p;
305					pageout_count++;
306					if (pageout_count == vm_pageout_page_count)
307						break;
308				} else {
309					forward_okay = FALSE;
310				}
311			} else {
312				forward_okay = FALSE;
313			}
314		}
315do_backward:
316		/*
317		 * See if backward page is clusterable.
318		 */
319		if (backward_okay) {
320			/*
321			 * Stop backward scan at beginning of object.
322			 */
323			if ((pindex - i) == 0) {
324				backward_okay = FALSE;
325			}
326			p = vm_page_lookup(object, pindex - i);
327			if (p) {
328				if (((p->queue - p->pc) == PQ_CACHE) ||
329					(p->flags & PG_BUSY) || p->busy) {
330					backward_okay = FALSE;
331					continue;
332				}
333				vm_page_test_dirty(p);
334				if ((p->dirty & p->valid) != 0 &&
335				    ((p->queue == PQ_INACTIVE) ||
336				     (sync == VM_PAGEOUT_FORCE)) &&
337				    (p->wire_count == 0) &&
338				    (p->hold_count == 0)) {
339					mc[vm_pageout_page_count - i] = p;
340					pageout_count++;
341					page_base--;
342					if (pageout_count == vm_pageout_page_count)
343						break;
344				} else {
345					backward_okay = FALSE;
346				}
347			} else {
348				backward_okay = FALSE;
349			}
350		}
351	}
352
353	/*
354	 * we allow reads during pageouts...
355	 */
356	for (i = page_base; i < (page_base + pageout_count); i++) {
357		mc[i]->flags |= PG_BUSY;
358		vm_page_protect(mc[i], VM_PROT_READ);
359	}
360
361	return vm_pageout_flush(&mc[page_base], pageout_count, sync);
362}
363
364int
365vm_pageout_flush(mc, count, sync)
366	vm_page_t *mc;
367	int count;
368	int sync;
369{
370	register vm_object_t object;
371	int pageout_status[count];
372	int anyok = 0;
373	int i;
374
375	object = mc[0]->object;
376	object->paging_in_progress += count;
377
378	vm_pager_put_pages(object, mc, count,
379	    ((sync || (object == kernel_object)) ? TRUE : FALSE),
380	    pageout_status);
381
382	for (i = 0; i < count; i++) {
383		vm_page_t mt = mc[i];
384
385		switch (pageout_status[i]) {
386		case VM_PAGER_OK:
387			anyok++;
388			break;
389		case VM_PAGER_PEND:
390			anyok++;
391			break;
392		case VM_PAGER_BAD:
393			/*
394			 * Page outside of range of object. Right now we
395			 * essentially lose the changes by pretending it
396			 * worked.
397			 */
398			pmap_clear_modify(VM_PAGE_TO_PHYS(mt));
399			mt->dirty = 0;
400			break;
401		case VM_PAGER_ERROR:
402		case VM_PAGER_FAIL:
403			/*
404			 * If page couldn't be paged out, then reactivate the
405			 * page so it doesn't clog the inactive list.  (We
406			 * will try paging out it again later).
407			 */
408			vm_page_activate(mt);
409			break;
410		case VM_PAGER_AGAIN:
411			break;
412		}
413
414
415		/*
416		 * If the operation is still going, leave the page busy to
417		 * block all other accesses. Also, leave the paging in
418		 * progress indicator set so that we don't attempt an object
419		 * collapse.
420		 */
421		if (pageout_status[i] != VM_PAGER_PEND) {
422			vm_object_pip_wakeup(object);
423			PAGE_WAKEUP(mt);
424		}
425	}
426	return anyok;
427}
428
429#if !defined(NO_SWAPPING)
430/*
431 *	vm_pageout_object_deactivate_pages
432 *
433 *	deactivate enough pages to satisfy the inactive target
434 *	requirements or if vm_page_proc_limit is set, then
435 *	deactivate all of the pages in the object and its
436 *	backing_objects.
437 *
438 *	The object and map must be locked.
439 */
440static void
441vm_pageout_object_deactivate_pages(map, object, desired, map_remove_only)
442	vm_map_t map;
443	vm_object_t object;
444	vm_pindex_t desired;
445	int map_remove_only;
446{
447	register vm_page_t p, next;
448	int rcount;
449	int remove_mode;
450	int s;
451
452	if (object->type == OBJT_DEVICE)
453		return;
454
455	while (object) {
456		if (vm_map_pmap(map)->pm_stats.resident_count <= desired)
457			return;
458		if (object->paging_in_progress)
459			return;
460
461		remove_mode = map_remove_only;
462		if (object->shadow_count > 1)
463			remove_mode = 1;
464	/*
465	 * scan the objects entire memory queue
466	 */
467		rcount = object->resident_page_count;
468		p = TAILQ_FIRST(&object->memq);
469		while (p && (rcount-- > 0)) {
470			int actcount;
471			if (vm_map_pmap(map)->pm_stats.resident_count <= desired)
472				return;
473			next = TAILQ_NEXT(p, listq);
474			cnt.v_pdpages++;
475			if (p->wire_count != 0 ||
476			    p->hold_count != 0 ||
477			    p->busy != 0 ||
478			    (p->flags & PG_BUSY) ||
479			    !pmap_page_exists(vm_map_pmap(map), VM_PAGE_TO_PHYS(p))) {
480				p = next;
481				continue;
482			}
483
484			actcount = pmap_ts_referenced(VM_PAGE_TO_PHYS(p));
485			if (actcount) {
486				p->flags |= PG_REFERENCED;
487			} else if (p->flags & PG_REFERENCED) {
488				actcount = 1;
489			}
490
491			if ((p->queue != PQ_ACTIVE) &&
492				(p->flags & PG_REFERENCED)) {
493				vm_page_activate(p);
494				p->act_count += actcount;
495				p->flags &= ~PG_REFERENCED;
496			} else if (p->queue == PQ_ACTIVE) {
497				if ((p->flags & PG_REFERENCED) == 0) {
498					p->act_count -= min(p->act_count, ACT_DECLINE);
499					if (!remove_mode && (vm_pageout_algorithm_lru || (p->act_count == 0))) {
500						vm_page_protect(p, VM_PROT_NONE);
501						vm_page_deactivate(p);
502					} else {
503						s = splvm();
504						TAILQ_REMOVE(&vm_page_queue_active, p, pageq);
505						TAILQ_INSERT_TAIL(&vm_page_queue_active, p, pageq);
506						splx(s);
507					}
508				} else {
509					vm_page_activate(p);
510					p->flags &= ~PG_REFERENCED;
511					if (p->act_count < (ACT_MAX - ACT_ADVANCE))
512						p->act_count += ACT_ADVANCE;
513					s = splvm();
514					TAILQ_REMOVE(&vm_page_queue_active, p, pageq);
515					TAILQ_INSERT_TAIL(&vm_page_queue_active, p, pageq);
516					splx(s);
517				}
518			} else if (p->queue == PQ_INACTIVE) {
519				vm_page_protect(p, VM_PROT_NONE);
520			}
521			p = next;
522		}
523		object = object->backing_object;
524	}
525	return;
526}
527
528/*
529 * deactivate some number of pages in a map, try to do it fairly, but
530 * that is really hard to do.
531 */
532static void
533vm_pageout_map_deactivate_pages(map, desired)
534	vm_map_t map;
535	vm_pindex_t desired;
536{
537	vm_map_entry_t tmpe;
538	vm_object_t obj, bigobj;
539
540	if (lockmgr(&map->lock, LK_EXCLUSIVE | LK_NOWAIT, (void *)0, curproc)) {
541		return;
542	}
543
544	bigobj = NULL;
545
546	/*
547	 * first, search out the biggest object, and try to free pages from
548	 * that.
549	 */
550	tmpe = map->header.next;
551	while (tmpe != &map->header) {
552		if ((tmpe->eflags & (MAP_ENTRY_IS_A_MAP|MAP_ENTRY_IS_SUB_MAP)) == 0) {
553			obj = tmpe->object.vm_object;
554			if ((obj != NULL) && (obj->shadow_count <= 1) &&
555				((bigobj == NULL) ||
556				 (bigobj->resident_page_count < obj->resident_page_count))) {
557				bigobj = obj;
558			}
559		}
560		tmpe = tmpe->next;
561	}
562
563	if (bigobj)
564		vm_pageout_object_deactivate_pages(map, bigobj, desired, 0);
565
566	/*
567	 * Next, hunt around for other pages to deactivate.  We actually
568	 * do this search sort of wrong -- .text first is not the best idea.
569	 */
570	tmpe = map->header.next;
571	while (tmpe != &map->header) {
572		if (vm_map_pmap(map)->pm_stats.resident_count <= desired)
573			break;
574		if ((tmpe->eflags & (MAP_ENTRY_IS_A_MAP|MAP_ENTRY_IS_SUB_MAP)) == 0) {
575			obj = tmpe->object.vm_object;
576			if (obj)
577				vm_pageout_object_deactivate_pages(map, obj, desired, 0);
578		}
579		tmpe = tmpe->next;
580	};
581
582	/*
583	 * Remove all mappings if a process is swapped out, this will free page
584	 * table pages.
585	 */
586	if (desired == 0)
587		pmap_remove(vm_map_pmap(map),
588			VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS);
589	vm_map_unlock(map);
590	return;
591}
592#endif
593
594void
595vm_pageout_page_free(vm_page_t m) {
596	struct vnode *vp;
597	vm_object_t object;
598
599	object = m->object;
600	object->ref_count++;
601
602	if (object->type == OBJT_VNODE) {
603		vp = object->handle;
604		vp->v_usecount++;
605		if (VSHOULDBUSY(vp))
606			vbusy(vp);
607	}
608
609	m->flags |= PG_BUSY;
610	vm_page_protect(m, VM_PROT_NONE);
611	vm_page_free(m);
612	vm_object_deallocate(object);
613}
614
615/*
616 *	vm_pageout_scan does the dirty work for the pageout daemon.
617 */
618static int
619vm_pageout_scan()
620{
621	vm_page_t m, next;
622	int page_shortage, addl_page_shortage, maxscan, pcount;
623	int maxlaunder;
624	int pages_freed;
625	struct proc *p, *bigproc;
626	vm_offset_t size, bigsize;
627	vm_object_t object;
628	int force_wakeup = 0;
629	int actcount;
630	int vnodes_skipped = 0;
631	int s;
632
633	/*
634	 * Do whatever cleanup that the pmap code can.
635	 */
636	pmap_collect();
637
638	/*
639	 * Start scanning the inactive queue for pages we can free. We keep
640	 * scanning until we have enough free pages or we have scanned through
641	 * the entire queue.  If we encounter dirty pages, we start cleaning
642	 * them.
643	 */
644
645	pages_freed = 0;
646	addl_page_shortage = vm_pageout_deficit;
647
648	if (max_page_launder == 0)
649		max_page_launder = 1;
650	maxlaunder = (cnt.v_inactive_target > max_page_launder) ?
651	    max_page_launder : cnt.v_inactive_target;
652
653rescan0:
654	maxscan = cnt.v_inactive_count;
655	for( m = TAILQ_FIRST(&vm_page_queue_inactive);
656
657		(m != NULL) && (maxscan-- > 0) &&
658			((cnt.v_cache_count + cnt.v_free_count) <
659			(cnt.v_cache_min + cnt.v_free_target));
660
661		m = next) {
662
663		cnt.v_pdpages++;
664
665		if (m->queue != PQ_INACTIVE) {
666			goto rescan0;
667		}
668
669		next = TAILQ_NEXT(m, pageq);
670
671		if (m->hold_count) {
672			s = splvm();
673			TAILQ_REMOVE(&vm_page_queue_inactive, m, pageq);
674			TAILQ_INSERT_TAIL(&vm_page_queue_inactive, m, pageq);
675			splx(s);
676			addl_page_shortage++;
677			continue;
678		}
679		/*
680		 * Dont mess with busy pages, keep in the front of the
681		 * queue, most likely are being paged out.
682		 */
683		if (m->busy || (m->flags & PG_BUSY)) {
684			addl_page_shortage++;
685			continue;
686		}
687
688		/*
689		 * If the object is not being used, we ignore previous references.
690		 */
691		if (m->object->ref_count == 0) {
692			m->flags &= ~PG_REFERENCED;
693			pmap_clear_reference(VM_PAGE_TO_PHYS(m));
694
695		/*
696		 * Otherwise, if the page has been referenced while in the inactive
697		 * queue, we bump the "activation count" upwards, making it less
698		 * likely that the page will be added back to the inactive queue
699		 * prematurely again.  Here we check the page tables (or emulated
700		 * bits, if any), given the upper level VM system not knowing anything
701		 * about existing references.
702		 */
703		} else if (((m->flags & PG_REFERENCED) == 0) &&
704			(actcount = pmap_ts_referenced(VM_PAGE_TO_PHYS(m)))) {
705			vm_page_activate(m);
706			m->act_count += (actcount + ACT_ADVANCE);
707			continue;
708		}
709
710		/*
711		 * If the upper level VM system knows about any page references,
712		 * we activate the page.  We also set the "activation count" higher
713		 * than normal so that we will less likely place pages back onto the
714		 * inactive queue again.
715		 */
716		if ((m->flags & PG_REFERENCED) != 0) {
717			m->flags &= ~PG_REFERENCED;
718			actcount = pmap_ts_referenced(VM_PAGE_TO_PHYS(m));
719			vm_page_activate(m);
720			m->act_count += (actcount + ACT_ADVANCE + 1);
721			continue;
722		}
723
724		/*
725		 * If the upper level VM system doesn't know anything about the
726		 * page being dirty, we have to check for it again.  As far as the
727		 * VM code knows, any partially dirty pages are fully dirty.
728		 */
729		if (m->dirty == 0) {
730			vm_page_test_dirty(m);
731		} else if (m->dirty != 0) {
732			m->dirty = VM_PAGE_BITS_ALL;
733		}
734
735		/*
736		 * Invalid pages can be easily freed
737		 */
738		if (m->valid == 0) {
739			vm_pageout_page_free(m);
740			cnt.v_dfree++;
741			pages_freed++;
742
743		/*
744		 * Clean pages can be placed onto the cache queue.
745		 */
746		} else if (m->dirty == 0) {
747			vm_page_cache(m);
748			pages_freed++;
749
750		/*
751		 * Dirty pages need to be paged out.  Note that we clean
752		 * only a limited number of pages per pagedaemon pass.
753		 */
754		} else if (maxlaunder > 0) {
755			int written;
756			int swap_pageouts_ok;
757			struct vnode *vp = NULL;
758
759			object = m->object;
760
761			if ((object->type != OBJT_SWAP) && (object->type != OBJT_DEFAULT)) {
762				swap_pageouts_ok = 1;
763			} else {
764				swap_pageouts_ok = !(defer_swap_pageouts || disable_swap_pageouts);
765				swap_pageouts_ok |= (!disable_swap_pageouts && defer_swap_pageouts &&
766					(cnt.v_free_count + cnt.v_cache_count) < cnt.v_free_min);
767
768			}
769
770			/*
771			 * We don't bother paging objects that are "dead".  Those
772			 * objects are in a "rundown" state.
773			 */
774			if (!swap_pageouts_ok || (object->flags & OBJ_DEAD)) {
775				s = splvm();
776				TAILQ_REMOVE(&vm_page_queue_inactive, m, pageq);
777				TAILQ_INSERT_TAIL(&vm_page_queue_inactive, m, pageq);
778				splx(s);
779				continue;
780			}
781
782			if ((object->type == OBJT_VNODE) &&
783				(object->flags & OBJ_DEAD) == 0) {
784				vp = object->handle;
785				if (VOP_ISLOCKED(vp) ||
786				    vget(vp, LK_EXCLUSIVE|LK_NOOBJ, curproc)) {
787					if ((m->queue == PQ_INACTIVE) &&
788						(m->hold_count == 0) &&
789						(m->busy == 0) &&
790						(m->flags & PG_BUSY) == 0) {
791						s = splvm();
792						TAILQ_REMOVE(&vm_page_queue_inactive, m, pageq);
793						TAILQ_INSERT_TAIL(&vm_page_queue_inactive, m, pageq);
794						splx(s);
795					}
796					if (object->flags & OBJ_MIGHTBEDIRTY)
797						vnodes_skipped++;
798					continue;
799				}
800
801				/*
802				 * The page might have been moved to another queue
803				 * during potential blocking in vget() above.
804				 */
805				if (m->queue != PQ_INACTIVE) {
806					if (object->flags & OBJ_MIGHTBEDIRTY)
807						vnodes_skipped++;
808					vput(vp);
809					continue;
810				}
811
812				/*
813				 * The page may have been busied during the blocking in
814				 * vput();  We don't move the page back onto the end of
815				 * the queue so that statistics are more correct if we don't.
816				 */
817				if (m->busy || (m->flags & PG_BUSY)) {
818					vput(vp);
819					continue;
820				}
821
822				/*
823				 * If the page has become held, then skip it
824				 */
825				if (m->hold_count) {
826					s = splvm();
827					TAILQ_REMOVE(&vm_page_queue_inactive, m, pageq);
828					TAILQ_INSERT_TAIL(&vm_page_queue_inactive, m, pageq);
829					splx(s);
830					if (object->flags & OBJ_MIGHTBEDIRTY)
831						vnodes_skipped++;
832					vput(vp);
833					continue;
834				}
835			}
836
837			/*
838			 * If a page is dirty, then it is either being washed
839			 * (but not yet cleaned) or it is still in the
840			 * laundry.  If it is still in the laundry, then we
841			 * start the cleaning operation.
842			 */
843			written = vm_pageout_clean(m, 0);
844			if (vp)
845				vput(vp);
846
847			maxlaunder -= written;
848		}
849	}
850
851	/*
852	 * Compute the page shortage.  If we are still very low on memory be
853	 * sure that we will move a minimal amount of pages from active to
854	 * inactive.
855	 */
856	page_shortage = (cnt.v_inactive_target + cnt.v_cache_min) -
857	    (cnt.v_free_count + cnt.v_inactive_count + cnt.v_cache_count);
858	if (page_shortage <= 0) {
859		if (pages_freed == 0) {
860			page_shortage = cnt.v_free_min - cnt.v_free_count;
861		} else {
862			page_shortage = 1;
863		}
864	}
865
866	/*
867	 * If the "inactive" loop finds that there is a shortage over and
868	 * above the page statistics variables, then we need to accomodate
869	 * that.  This avoids potential deadlocks due to pages being temporarily
870	 * busy for I/O or other types of temporary wiring.
871	 */
872	if (addl_page_shortage) {
873		if (page_shortage < 0)
874			page_shortage = 0;
875		page_shortage += addl_page_shortage;
876	}
877
878	pcount = cnt.v_active_count;
879	m = TAILQ_FIRST(&vm_page_queue_active);
880	while ((m != NULL) && (pcount-- > 0) && (page_shortage > 0)) {
881
882		/*
883		 * This is a consistancy check, and should likely be a panic
884		 * or warning.
885		 */
886		if (m->queue != PQ_ACTIVE) {
887			break;
888		}
889
890		next = TAILQ_NEXT(m, pageq);
891		/*
892		 * Don't deactivate pages that are busy.
893		 */
894		if ((m->busy != 0) ||
895		    (m->flags & PG_BUSY) ||
896		    (m->hold_count != 0)) {
897			s = splvm();
898			TAILQ_REMOVE(&vm_page_queue_active, m, pageq);
899			TAILQ_INSERT_TAIL(&vm_page_queue_active, m, pageq);
900			splx(s);
901			m = next;
902			continue;
903		}
904
905		/*
906		 * The count for pagedaemon pages is done after checking the
907		 * page for eligbility...
908		 */
909		cnt.v_pdpages++;
910
911		/*
912		 * Check to see "how much" the page has been used.
913		 */
914		actcount = 0;
915		if (m->object->ref_count != 0) {
916			if (m->flags & PG_REFERENCED) {
917				actcount += 1;
918			}
919			actcount += pmap_ts_referenced(VM_PAGE_TO_PHYS(m));
920			if (actcount) {
921				m->act_count += ACT_ADVANCE + actcount;
922				if (m->act_count > ACT_MAX)
923					m->act_count = ACT_MAX;
924			}
925		}
926
927		/*
928		 * Since we have "tested" this bit, we need to clear it now.
929		 */
930		m->flags &= ~PG_REFERENCED;
931
932		/*
933		 * Only if an object is currently being used, do we use the
934		 * page activation count stats.
935		 */
936		if (actcount && (m->object->ref_count != 0)) {
937			s = splvm();
938			TAILQ_REMOVE(&vm_page_queue_active, m, pageq);
939			TAILQ_INSERT_TAIL(&vm_page_queue_active, m, pageq);
940			splx(s);
941		} else {
942			m->act_count -= min(m->act_count, ACT_DECLINE);
943			if (vm_pageout_algorithm_lru ||
944				(m->object->ref_count == 0) || (m->act_count == 0)) {
945				page_shortage--;
946				if (m->object->ref_count == 0) {
947					vm_page_protect(m, VM_PROT_NONE);
948					if (m->dirty == 0)
949						vm_page_cache(m);
950					else
951						vm_page_deactivate(m);
952				} else {
953					vm_page_deactivate(m);
954				}
955			} else {
956				s = splvm();
957				TAILQ_REMOVE(&vm_page_queue_active, m, pageq);
958				TAILQ_INSERT_TAIL(&vm_page_queue_active, m, pageq);
959				splx(s);
960			}
961		}
962		m = next;
963	}
964
965	s = splvm();
966	/*
967	 * We try to maintain some *really* free pages, this allows interrupt
968	 * code to be guaranteed space.
969	 */
970	while (cnt.v_free_count < cnt.v_free_reserved) {
971		static int cache_rover = 0;
972		m = vm_page_list_find(PQ_CACHE, cache_rover);
973		if (!m)
974			break;
975		cache_rover = (cache_rover + PQ_PRIME2) & PQ_L2_MASK;
976		vm_pageout_page_free(m);
977		cnt.v_dfree++;
978	}
979	splx(s);
980
981#if !defined(NO_SWAPPING)
982	/*
983	 * Idle process swapout -- run once per second.
984	 */
985	if (vm_swap_idle_enabled) {
986		static long lsec;
987		if (time.tv_sec != lsec) {
988			vm_pageout_req_swapout |= VM_SWAP_IDLE;
989			vm_req_vmdaemon();
990			lsec = time.tv_sec;
991		}
992	}
993#endif
994
995	/*
996	 * If we didn't get enough free pages, and we have skipped a vnode
997	 * in a writeable object, wakeup the sync daemon.  And kick swapout
998	 * if we did not get enough free pages.
999	 */
1000	if ((cnt.v_cache_count + cnt.v_free_count) <
1001		(cnt.v_free_target + cnt.v_cache_min) ) {
1002		if (vnodes_skipped &&
1003		    (cnt.v_cache_count + cnt.v_free_count) < cnt.v_free_min) {
1004			if (!vfs_update_wakeup) {
1005				vfs_update_wakeup = 1;
1006				wakeup(&vfs_update_wakeup);
1007			}
1008		}
1009#if !defined(NO_SWAPPING)
1010		if (vm_swap_enabled &&
1011			(cnt.v_free_count + cnt.v_cache_count < cnt.v_free_target)) {
1012			vm_req_vmdaemon();
1013			vm_pageout_req_swapout |= VM_SWAP_NORMAL;
1014		}
1015#endif
1016	}
1017
1018
1019	/*
1020	 * make sure that we have swap space -- if we are low on memory and
1021	 * swap -- then kill the biggest process.
1022	 */
1023	if ((vm_swap_size == 0 || swap_pager_full) &&
1024	    ((cnt.v_free_count + cnt.v_cache_count) < cnt.v_free_min)) {
1025		bigproc = NULL;
1026		bigsize = 0;
1027		for (p = allproc.lh_first; p != 0; p = p->p_list.le_next) {
1028			/*
1029			 * if this is a system process, skip it
1030			 */
1031			if ((p->p_flag & P_SYSTEM) || (p->p_pid == 1) ||
1032			    ((p->p_pid < 48) && (vm_swap_size != 0))) {
1033				continue;
1034			}
1035			/*
1036			 * if the process is in a non-running type state,
1037			 * don't touch it.
1038			 */
1039			if (p->p_stat != SRUN && p->p_stat != SSLEEP) {
1040				continue;
1041			}
1042			/*
1043			 * get the process size
1044			 */
1045			size = p->p_vmspace->vm_pmap.pm_stats.resident_count;
1046			/*
1047			 * if the this process is bigger than the biggest one
1048			 * remember it.
1049			 */
1050			if (size > bigsize) {
1051				bigproc = p;
1052				bigsize = size;
1053			}
1054		}
1055		if (bigproc != NULL) {
1056			killproc(bigproc, "out of swap space");
1057			bigproc->p_estcpu = 0;
1058			bigproc->p_nice = PRIO_MIN;
1059			resetpriority(bigproc);
1060			wakeup(&cnt.v_free_count);
1061		}
1062	}
1063	return force_wakeup;
1064}
1065
1066/*
1067 * This routine tries to maintain the pseudo LRU active queue,
1068 * so that during long periods of time where there is no paging,
1069 * that some statistic accumlation still occurs.  This code
1070 * helps the situation where paging just starts to occur.
1071 */
1072static void
1073vm_pageout_page_stats()
1074{
1075	int s;
1076	vm_page_t m,next;
1077	int pcount,tpcount;		/* Number of pages to check */
1078	static int fullintervalcount = 0;
1079
1080	pcount = cnt.v_active_count;
1081	fullintervalcount += vm_pageout_stats_interval;
1082	if (fullintervalcount < vm_pageout_full_stats_interval) {
1083		tpcount = (vm_pageout_stats_max * cnt.v_active_count) / cnt.v_page_count;
1084		if (pcount > tpcount)
1085			pcount = tpcount;
1086	}
1087
1088	m = TAILQ_FIRST(&vm_page_queue_active);
1089	while ((m != NULL) && (pcount-- > 0)) {
1090		int actcount;
1091
1092		if (m->queue != PQ_ACTIVE) {
1093			break;
1094		}
1095
1096		next = TAILQ_NEXT(m, pageq);
1097		/*
1098		 * Don't deactivate pages that are busy.
1099		 */
1100		if ((m->busy != 0) ||
1101		    (m->flags & PG_BUSY) ||
1102		    (m->hold_count != 0)) {
1103			s = splvm();
1104			TAILQ_REMOVE(&vm_page_queue_active, m, pageq);
1105			TAILQ_INSERT_TAIL(&vm_page_queue_active, m, pageq);
1106			splx(s);
1107			m = next;
1108			continue;
1109		}
1110
1111		actcount = 0;
1112		if (m->flags & PG_REFERENCED) {
1113			m->flags &= ~PG_REFERENCED;
1114			actcount += 1;
1115		}
1116
1117		actcount += pmap_ts_referenced(VM_PAGE_TO_PHYS(m));
1118		if (actcount) {
1119			m->act_count += ACT_ADVANCE + actcount;
1120			if (m->act_count > ACT_MAX)
1121				m->act_count = ACT_MAX;
1122			s = splvm();
1123			TAILQ_REMOVE(&vm_page_queue_active, m, pageq);
1124			TAILQ_INSERT_TAIL(&vm_page_queue_active, m, pageq);
1125			splx(s);
1126		} else {
1127			if (m->act_count == 0) {
1128				/*
1129				 * We turn off page access, so that we have more accurate
1130				 * RSS stats.  We don't do this in the normal page deactivation
1131				 * when the system is loaded VM wise, because the cost of
1132				 * the large number of page protect operations would be higher
1133				 * than the value of doing the operation.
1134				 */
1135				vm_page_protect(m, VM_PROT_NONE);
1136				vm_page_deactivate(m);
1137			} else {
1138				m->act_count -= min(m->act_count, ACT_DECLINE);
1139				s = splvm();
1140				TAILQ_REMOVE(&vm_page_queue_active, m, pageq);
1141				TAILQ_INSERT_TAIL(&vm_page_queue_active, m, pageq);
1142				splx(s);
1143			}
1144		}
1145
1146		m = next;
1147	}
1148}
1149
1150
1151static int
1152vm_pageout_free_page_calc(count)
1153vm_size_t count;
1154{
1155	if (count < cnt.v_page_count)
1156		 return 0;
1157	/*
1158	 * free_reserved needs to include enough for the largest swap pager
1159	 * structures plus enough for any pv_entry structs when paging.
1160	 */
1161	if (cnt.v_page_count > 1024)
1162		cnt.v_free_min = 4 + (cnt.v_page_count - 1024) / 200;
1163	else
1164		cnt.v_free_min = 4;
1165	cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1166		cnt.v_interrupt_free_min;
1167	cnt.v_free_reserved = vm_pageout_page_count +
1168		cnt.v_pageout_free_min + (count / 2048) + PQ_L2_SIZE;
1169	cnt.v_free_min += cnt.v_free_reserved;
1170	return 1;
1171}
1172
1173
1174/*
1175 *	vm_pageout is the high level pageout daemon.
1176 */
1177static void
1178vm_pageout()
1179{
1180	/*
1181	 * Initialize some paging parameters.
1182	 */
1183
1184	cnt.v_interrupt_free_min = 2;
1185	if (cnt.v_page_count < 2000)
1186		vm_pageout_page_count = 8;
1187
1188	vm_pageout_free_page_calc(cnt.v_page_count);
1189	/*
1190	 * free_reserved needs to include enough for the largest swap pager
1191	 * structures plus enough for any pv_entry structs when paging.
1192	 */
1193	cnt.v_free_target = 3 * cnt.v_free_min + cnt.v_free_reserved;
1194
1195	if (cnt.v_free_count > 1024) {
1196		cnt.v_cache_max = (cnt.v_free_count - 1024) / 2;
1197		cnt.v_cache_min = (cnt.v_free_count - 1024) / 8;
1198		cnt.v_inactive_target = 2*cnt.v_cache_min + 192;
1199	} else {
1200		cnt.v_cache_min = 0;
1201		cnt.v_cache_max = 0;
1202		cnt.v_inactive_target = cnt.v_free_count / 4;
1203	}
1204
1205	/* XXX does not really belong here */
1206	if (vm_page_max_wired == 0)
1207		vm_page_max_wired = cnt.v_free_count / 3;
1208
1209	if (vm_pageout_stats_max == 0)
1210		vm_pageout_stats_max = cnt.v_free_target;
1211
1212	/*
1213	 * Set interval in seconds for stats scan.
1214	 */
1215	if (vm_pageout_stats_interval == 0)
1216		vm_pageout_stats_interval = 4;
1217	if (vm_pageout_full_stats_interval == 0)
1218		vm_pageout_full_stats_interval = vm_pageout_stats_interval * 4;
1219
1220
1221	/*
1222	 * Set maximum free per pass
1223	 */
1224	if (vm_pageout_stats_free_max == 0)
1225		vm_pageout_stats_free_max = 25;
1226
1227	max_page_launder = (cnt.v_page_count > 1800 ? 32 : 16);
1228
1229	swap_pager_swap_init();
1230	/*
1231	 * The pageout daemon is never done, so loop forever.
1232	 */
1233	while (TRUE) {
1234		int inactive_target;
1235		int error;
1236		int s = splvm();
1237		if (!vm_pages_needed ||
1238			((cnt.v_free_count + cnt.v_cache_count) > cnt.v_free_min)) {
1239			vm_pages_needed = 0;
1240			error = tsleep(&vm_pages_needed,
1241				PVM, "psleep", vm_pageout_stats_interval * hz);
1242			if (error && !vm_pages_needed) {
1243				splx(s);
1244				vm_pageout_page_stats();
1245				continue;
1246			}
1247		} else if (vm_pages_needed) {
1248			tsleep(&vm_pages_needed, PVM, "psleep", hz/10);
1249		}
1250		inactive_target =
1251			(cnt.v_page_count - cnt.v_wire_count) / 4;
1252		if (inactive_target < 2*cnt.v_free_min)
1253			inactive_target = 2*cnt.v_free_min;
1254		cnt.v_inactive_target = inactive_target;
1255		if (vm_pages_needed)
1256			cnt.v_pdwakeups++;
1257		vm_pages_needed = 0;
1258		splx(s);
1259		vm_pager_sync();
1260		vm_pageout_scan();
1261		vm_pageout_deficit = 0;
1262		vm_pager_sync();
1263		wakeup(&cnt.v_free_count);
1264	}
1265}
1266
1267void
1268pagedaemon_wakeup()
1269{
1270	if (!vm_pages_needed && curproc != pageproc) {
1271		vm_pages_needed++;
1272		wakeup(&vm_pages_needed);
1273	}
1274}
1275
1276#if !defined(NO_SWAPPING)
1277static void
1278vm_req_vmdaemon()
1279{
1280	static int lastrun = 0;
1281
1282	if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
1283		wakeup(&vm_daemon_needed);
1284		lastrun = ticks;
1285	}
1286}
1287
1288static void
1289vm_daemon()
1290{
1291	vm_object_t object;
1292	struct proc *p;
1293
1294	while (TRUE) {
1295		tsleep(&vm_daemon_needed, PUSER, "psleep", 0);
1296		if (vm_pageout_req_swapout) {
1297			swapout_procs(vm_pageout_req_swapout);
1298			vm_pageout_req_swapout = 0;
1299		}
1300		/*
1301		 * scan the processes for exceeding their rlimits or if
1302		 * process is swapped out -- deactivate pages
1303		 */
1304
1305		for (p = allproc.lh_first; p != 0; p = p->p_list.le_next) {
1306			quad_t limit;
1307			vm_offset_t size;
1308
1309			/*
1310			 * if this is a system process or if we have already
1311			 * looked at this process, skip it.
1312			 */
1313			if (p->p_flag & (P_SYSTEM | P_WEXIT)) {
1314				continue;
1315			}
1316			/*
1317			 * if the process is in a non-running type state,
1318			 * don't touch it.
1319			 */
1320			if (p->p_stat != SRUN && p->p_stat != SSLEEP) {
1321				continue;
1322			}
1323			/*
1324			 * get a limit
1325			 */
1326			limit = qmin(p->p_rlimit[RLIMIT_RSS].rlim_cur,
1327			    p->p_rlimit[RLIMIT_RSS].rlim_max);
1328
1329			/*
1330			 * let processes that are swapped out really be
1331			 * swapped out set the limit to nothing (will force a
1332			 * swap-out.)
1333			 */
1334			if ((p->p_flag & P_INMEM) == 0)
1335				limit = 0;	/* XXX */
1336
1337			size = p->p_vmspace->vm_pmap.pm_stats.resident_count * PAGE_SIZE;
1338			if (limit >= 0 && size >= limit) {
1339				vm_pageout_map_deactivate_pages(&p->p_vmspace->vm_map,
1340				    (vm_pindex_t)(limit >> PAGE_SHIFT) );
1341			}
1342		}
1343	}
1344}
1345#endif
1346