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