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