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