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