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