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