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