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