]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vm_pageout.c
MFC revisions 1.375-1.377
[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_pmap_collect(void);
118 static void vm_pageout_scan(int pass);
119
120 struct proc *pageproc;
121
122 static struct kproc_desc page_kp = {
123         "pagedaemon",
124         vm_pageout,
125         &pageproc
126 };
127 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, kproc_start, &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
211 #if !defined(NO_SWAPPING)
212 static void vm_pageout_map_deactivate_pages(vm_map_t, long);
213 static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
214 static void vm_req_vmdaemon(int req);
215 #endif
216 static void vm_pageout_page_stats(void);
217
218 /*
219  * vm_pageout_fallback_object_lock:
220  * 
221  * Lock vm object currently associated with `m'. VM_OBJECT_TRYLOCK is
222  * known to have failed and page queue must be either PQ_ACTIVE or
223  * PQ_INACTIVE.  To avoid lock order violation, unlock the page queues
224  * while locking the vm object.  Use marker page to detect page queue
225  * changes and maintain notion of next page on page queue.  Return
226  * TRUE if no changes were detected, FALSE otherwise.  vm object is
227  * locked on return.
228  * 
229  * This function depends on both the lock portion of struct vm_object
230  * and normal struct vm_page being type stable.
231  */
232 static boolean_t
233 vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
234 {
235         struct vm_page marker;
236         boolean_t unchanged;
237         u_short queue;
238         vm_object_t object;
239
240         /*
241          * Initialize our marker
242          */
243         bzero(&marker, sizeof(marker));
244         marker.flags = PG_BUSY | PG_FICTITIOUS | PG_MARKER;
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          * Don't mess with the page if it's busy, held, or special
300          */
301         if ((m->hold_count != 0) ||
302             ((m->busy != 0) || (m->flags & (PG_BUSY|PG_UNMANAGED)))) {
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->queue - p->pc) == PQ_CACHE) ||
346                     (p->flags & (PG_BUSY|PG_UNMANAGED)) || p->busy) {
347                         ib = 0;
348                         break;
349                 }
350                 vm_page_test_dirty(p);
351                 if ((p->dirty & p->valid) == 0 ||
352                     p->queue != PQ_INACTIVE ||
353                     p->wire_count != 0 ||       /* may be held by buf cache */
354                     p->hold_count != 0) {       /* may be undergoing I/O */
355                         ib = 0;
356                         break;
357                 }
358                 mc[--page_base] = p;
359                 ++pageout_count;
360                 ++ib;
361                 /*
362                  * alignment boundry, stop here and switch directions.  Do
363                  * not clear ib.
364                  */
365                 if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
366                         break;
367         }
368
369         while (pageout_count < vm_pageout_page_count && 
370             pindex + is < object->size) {
371                 vm_page_t p;
372
373                 if ((p = vm_page_lookup(object, pindex + is)) == NULL)
374                         break;
375                 if (((p->queue - p->pc) == PQ_CACHE) ||
376                     (p->flags & (PG_BUSY|PG_UNMANAGED)) || p->busy) {
377                         break;
378                 }
379                 vm_page_test_dirty(p);
380                 if ((p->dirty & p->valid) == 0 ||
381                     p->queue != PQ_INACTIVE ||
382                     p->wire_count != 0 ||       /* may be held by buf cache */
383                     p->hold_count != 0) {       /* may be undergoing I/O */
384                         break;
385                 }
386                 mc[page_base + pageout_count] = p;
387                 ++pageout_count;
388                 ++is;
389         }
390
391         /*
392          * If we exhausted our forward scan, continue with the reverse scan
393          * when possible, even past a page boundry.  This catches boundry
394          * conditions.
395          */
396         if (ib && pageout_count < vm_pageout_page_count)
397                 goto more;
398
399         /*
400          * we allow reads during pageouts...
401          */
402         return (vm_pageout_flush(&mc[page_base], pageout_count, 0));
403 }
404
405 /*
406  * vm_pageout_flush() - launder the given pages
407  *
408  *      The given pages are laundered.  Note that we setup for the start of
409  *      I/O ( i.e. busy the page ), mark it read-only, and bump the object
410  *      reference count all in here rather then in the parent.  If we want
411  *      the parent to do more sophisticated things we may have to change
412  *      the ordering.
413  */
414 int
415 vm_pageout_flush(vm_page_t *mc, int count, int flags)
416 {
417         vm_object_t object = mc[0]->object;
418         int pageout_status[count];
419         int numpagedout = 0;
420         int i;
421
422         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
423         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
424         /*
425          * Initiate I/O.  Bump the vm_page_t->busy counter and
426          * mark the pages read-only.
427          *
428          * We do not have to fixup the clean/dirty bits here... we can
429          * allow the pager to do it after the I/O completes.
430          *
431          * NOTE! mc[i]->dirty may be partial or fragmented due to an
432          * edge case with file fragments.
433          */
434         for (i = 0; i < count; i++) {
435                 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
436                     ("vm_pageout_flush: partially invalid page %p index %d/%d",
437                         mc[i], i, count));
438                 vm_page_io_start(mc[i]);
439                 pmap_page_protect(mc[i], VM_PROT_READ);
440         }
441         vm_page_unlock_queues();
442         vm_object_pip_add(object, count);
443
444         vm_pager_put_pages(object, mc, count,
445             (flags | ((object == kernel_object) ? VM_PAGER_PUT_SYNC : 0)),
446             pageout_status);
447
448         vm_page_lock_queues();
449         for (i = 0; i < count; i++) {
450                 vm_page_t mt = mc[i];
451
452                 KASSERT((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->flags & (PG_BUSY|PG_UNMANAGED)) ||
547                             !pmap_page_exists_quick(pmap, p)) {
548                                 p = next;
549                                 continue;
550                         }
551                         actcount = pmap_ts_referenced(p);
552                         if (actcount) {
553                                 vm_page_flag_set(p, PG_REFERENCED);
554                         } else if (p->flags & PG_REFERENCED) {
555                                 actcount = 1;
556                         }
557                         if ((p->queue != PQ_ACTIVE) &&
558                                 (p->flags & PG_REFERENCED)) {
559                                 vm_page_activate(p);
560                                 p->act_count += actcount;
561                                 vm_page_flag_clear(p, PG_REFERENCED);
562                         } else if (p->queue == PQ_ACTIVE) {
563                                 if ((p->flags & PG_REFERENCED) == 0) {
564                                         p->act_count -= min(p->act_count, ACT_DECLINE);
565                                         if (!remove_mode && (vm_pageout_algorithm || (p->act_count == 0))) {
566                                                 pmap_remove_all(p);
567                                                 vm_page_deactivate(p);
568                                         } else {
569                                                 vm_pageq_requeue(p);
570                                         }
571                                 } else {
572                                         vm_page_activate(p);
573                                         vm_page_flag_clear(p, PG_REFERENCED);
574                                         if (p->act_count < (ACT_MAX - ACT_ADVANCE))
575                                                 p->act_count += ACT_ADVANCE;
576                                         vm_pageq_requeue(p);
577                                 }
578                         } else if (p->queue == PQ_INACTIVE) {
579                                 pmap_remove_all(p);
580                         }
581                         p = next;
582                 }
583                 vm_page_unlock_queues();
584                 if ((backing_object = object->backing_object) == NULL)
585                         goto unlock_return;
586                 VM_OBJECT_LOCK(backing_object);
587                 if (object != first_object)
588                         VM_OBJECT_UNLOCK(object);
589         }
590 unlock_return:
591         if (object != first_object)
592                 VM_OBJECT_UNLOCK(object);
593 }
594
595 /*
596  * deactivate some number of pages in a map, try to do it fairly, but
597  * that is really hard to do.
598  */
599 static void
600 vm_pageout_map_deactivate_pages(map, desired)
601         vm_map_t map;
602         long desired;
603 {
604         vm_map_entry_t tmpe;
605         vm_object_t obj, bigobj;
606         int nothingwired;
607
608         if (!vm_map_trylock(map))
609                 return;
610
611         bigobj = NULL;
612         nothingwired = TRUE;
613
614         /*
615          * first, search out the biggest object, and try to free pages from
616          * that.
617          */
618         tmpe = map->header.next;
619         while (tmpe != &map->header) {
620                 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
621                         obj = tmpe->object.vm_object;
622                         if (obj != NULL && VM_OBJECT_TRYLOCK(obj)) {
623                                 if (obj->shadow_count <= 1 &&
624                                     (bigobj == NULL ||
625                                      bigobj->resident_page_count < obj->resident_page_count)) {
626                                         if (bigobj != NULL)
627                                                 VM_OBJECT_UNLOCK(bigobj);
628                                         bigobj = obj;
629                                 } else
630                                         VM_OBJECT_UNLOCK(obj);
631                         }
632                 }
633                 if (tmpe->wired_count > 0)
634                         nothingwired = FALSE;
635                 tmpe = tmpe->next;
636         }
637
638         if (bigobj != NULL) {
639                 vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
640                 VM_OBJECT_UNLOCK(bigobj);
641         }
642         /*
643          * Next, hunt around for other pages to deactivate.  We actually
644          * do this search sort of wrong -- .text first is not the best idea.
645          */
646         tmpe = map->header.next;
647         while (tmpe != &map->header) {
648                 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
649                         break;
650                 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
651                         obj = tmpe->object.vm_object;
652                         if (obj != NULL) {
653                                 VM_OBJECT_LOCK(obj);
654                                 vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
655                                 VM_OBJECT_UNLOCK(obj);
656                         }
657                 }
658                 tmpe = tmpe->next;
659         }
660
661         /*
662          * Remove all mappings if a process is swapped out, this will free page
663          * table pages.
664          */
665         if (desired == 0 && nothingwired) {
666                 pmap_remove(vm_map_pmap(map), vm_map_min(map),
667                     vm_map_max(map));
668         }
669         vm_map_unlock(map);
670 }
671 #endif          /* !defined(NO_SWAPPING) */
672
673 /*
674  * This routine is very drastic, but can save the system
675  * in a pinch.
676  */
677 static void
678 vm_pageout_pmap_collect(void)
679 {
680         int i;
681         vm_page_t m;
682         static int warningdone;
683
684         if (pmap_pagedaemon_waken == 0)
685                 return;
686         if (warningdone < 5) {
687                 printf("collecting pv entries -- suggest increasing PMAP_SHPGPERPROC\n");
688                 warningdone++;
689         }
690         vm_page_lock_queues();
691         for (i = 0; i < vm_page_array_size; i++) {
692                 m = &vm_page_array[i];
693                 if (m->wire_count || m->hold_count || m->busy ||
694                     (m->flags & (PG_BUSY | PG_UNMANAGED)))
695                         continue;
696                 pmap_remove_all(m);
697         }
698         vm_page_unlock_queues();
699         pmap_pagedaemon_waken = 0;
700 }
701         
702 /*
703  *      vm_pageout_scan does the dirty work for the pageout daemon.
704  */
705 static void
706 vm_pageout_scan(int pass)
707 {
708         vm_page_t m, next;
709         struct vm_page marker;
710         int page_shortage, maxscan, pcount;
711         int addl_page_shortage, addl_page_shortage_init;
712         struct proc *p, *bigproc;
713         struct thread *td;
714         vm_offset_t size, bigsize;
715         vm_object_t object;
716         int actcount, cache_cur, cache_first_failure;
717         static int cache_last_free;
718         int vnodes_skipped = 0;
719         int maxlaunder;
720
721         /*
722          * Decrease registered cache sizes.
723          */
724         EVENTHANDLER_INVOKE(vm_lowmem, 0);
725         /*
726          * We do this explicitly after the caches have been drained above.
727          */
728         uma_reclaim();
729         /*
730          * Do whatever cleanup that the pmap code can.
731          */
732         vm_pageout_pmap_collect();
733
734         addl_page_shortage_init = atomic_readandclear_int(&vm_pageout_deficit);
735
736         /*
737          * Calculate the number of pages we want to either free or move
738          * to the cache.
739          */
740         page_shortage = vm_paging_target() + addl_page_shortage_init;
741
742         /*
743          * Initialize our marker
744          */
745         bzero(&marker, sizeof(marker));
746         marker.flags = PG_BUSY | PG_FICTITIOUS | PG_MARKER;
747         marker.queue = PQ_INACTIVE;
748         marker.wire_count = 1;
749
750         /*
751          * Start scanning the inactive queue for pages we can move to the
752          * cache or free.  The scan will stop when the target is reached or
753          * we have scanned the entire inactive queue.  Note that m->act_count
754          * is not used to form decisions for the inactive queue, only for the
755          * active queue.
756          *
757          * maxlaunder limits the number of dirty pages we flush per scan.
758          * For most systems a smaller value (16 or 32) is more robust under
759          * extreme memory and disk pressure because any unnecessary writes
760          * to disk can result in extreme performance degredation.  However,
761          * systems with excessive dirty pages (especially when MAP_NOSYNC is
762          * used) will die horribly with limited laundering.  If the pageout
763          * daemon cannot clean enough pages in the first pass, we let it go
764          * all out in succeeding passes.
765          */
766         if ((maxlaunder = vm_max_launder) <= 1)
767                 maxlaunder = 1;
768         if (pass)
769                 maxlaunder = 10000;
770         vm_page_lock_queues();
771 rescan0:
772         addl_page_shortage = addl_page_shortage_init;
773         maxscan = cnt.v_inactive_count;
774
775         for (m = TAILQ_FIRST(&vm_page_queues[PQ_INACTIVE].pl);
776              m != NULL && maxscan-- > 0 && page_shortage > 0;
777              m = next) {
778
779                 cnt.v_pdpages++;
780
781                 if (m->queue != PQ_INACTIVE) {
782                         goto rescan0;
783                 }
784
785                 next = TAILQ_NEXT(m, pageq);
786                 object = m->object;
787
788                 /*
789                  * skip marker pages
790                  */
791                 if (m->flags & PG_MARKER)
792                         continue;
793
794                 /*
795                  * A held page may be undergoing I/O, so skip it.
796                  */
797                 if (m->hold_count) {
798                         vm_pageq_requeue(m);
799                         addl_page_shortage++;
800                         continue;
801                 }
802                 /*
803                  * Don't mess with busy pages, keep in the front of the
804                  * queue, most likely are being paged out.
805                  */
806                 if (!VM_OBJECT_TRYLOCK(object) &&
807                     (!vm_pageout_fallback_object_lock(m, &next) ||
808                      m->hold_count != 0)) {
809                         VM_OBJECT_UNLOCK(object);
810                         addl_page_shortage++;
811                         continue;
812                 }
813                 if (m->busy || (m->flags & PG_BUSY)) {
814                         VM_OBJECT_UNLOCK(object);
815                         addl_page_shortage++;
816                         continue;
817                 }
818
819                 /*
820                  * If the object is not being used, we ignore previous 
821                  * references.
822                  */
823                 if (object->ref_count == 0) {
824                         vm_page_flag_clear(m, PG_REFERENCED);
825                         pmap_clear_reference(m);
826
827                 /*
828                  * Otherwise, if the page has been referenced while in the 
829                  * inactive queue, we bump the "activation count" upwards, 
830                  * making it less likely that the page will be added back to 
831                  * the inactive queue prematurely again.  Here we check the 
832                  * page tables (or emulated bits, if any), given the upper 
833                  * level VM system not knowing anything about existing 
834                  * references.
835                  */
836                 } else if (((m->flags & PG_REFERENCED) == 0) &&
837                         (actcount = pmap_ts_referenced(m))) {
838                         vm_page_activate(m);
839                         VM_OBJECT_UNLOCK(object);
840                         m->act_count += (actcount + ACT_ADVANCE);
841                         continue;
842                 }
843
844                 /*
845                  * If the upper level VM system knows about any page 
846                  * references, we activate the page.  We also set the 
847                  * "activation count" higher than normal so that we will less 
848                  * likely place pages back onto the inactive queue again.
849                  */
850                 if ((m->flags & PG_REFERENCED) != 0) {
851                         vm_page_flag_clear(m, PG_REFERENCED);
852                         actcount = pmap_ts_referenced(m);
853                         vm_page_activate(m);
854                         VM_OBJECT_UNLOCK(object);
855                         m->act_count += (actcount + ACT_ADVANCE + 1);
856                         continue;
857                 }
858
859                 /*
860                  * If the upper level VM system doesn't know anything about 
861                  * the page being dirty, we have to check for it again.  As 
862                  * far as the VM code knows, any partially dirty pages are 
863                  * fully dirty.
864                  */
865                 if (m->dirty == 0 && !pmap_is_modified(m)) {
866                         /*
867                          * Avoid a race condition: Unless write access is
868                          * removed from the page, another processor could
869                          * modify it before all access is removed by the call
870                          * to vm_page_cache() below.  If vm_page_cache() finds
871                          * that the page has been modified when it removes all
872                          * access, it panics because it cannot cache dirty
873                          * pages.  In principle, we could eliminate just write
874                          * access here rather than all access.  In the expected
875                          * case, when there are no last instant modifications
876                          * to the page, removing all access will be cheaper
877                          * overall.
878                          */
879                         if ((m->flags & PG_WRITEABLE) != 0)
880                                 pmap_remove_all(m);
881                 } else {
882                         vm_page_dirty(m);
883                 }
884
885                 if (m->valid == 0) {
886                         /*
887                          * Invalid pages can be easily freed
888                          */
889                         pmap_remove_all(m);
890                         vm_page_free(m);
891                         cnt.v_dfree++;
892                         --page_shortage;
893                 } else if (m->dirty == 0) {
894                         /*
895                          * Clean pages can be placed onto the cache queue.
896                          * This effectively frees them.
897                          */
898                         vm_page_cache(m);
899                         --page_shortage;
900                 } else if ((m->flags & PG_WINATCFLS) == 0 && pass == 0) {
901                         /*
902                          * Dirty pages need to be paged out, but flushing
903                          * a page is extremely expensive verses freeing
904                          * a clean page.  Rather then artificially limiting
905                          * the number of pages we can flush, we instead give
906                          * dirty pages extra priority on the inactive queue
907                          * by forcing them to be cycled through the queue
908                          * twice before being flushed, after which the
909                          * (now clean) page will cycle through once more
910                          * before being freed.  This significantly extends
911                          * the thrash point for a heavily loaded machine.
912                          */
913                         vm_page_flag_set(m, PG_WINATCFLS);
914                         vm_pageq_requeue(m);
915                 } else if (maxlaunder > 0) {
916                         /*
917                          * We always want to try to flush some dirty pages if
918                          * we encounter them, to keep the system stable.
919                          * Normally this number is small, but under extreme
920                          * pressure where there are insufficient clean pages
921                          * on the inactive queue, we may have to go all out.
922                          */
923                         int swap_pageouts_ok, vfslocked = 0;
924                         struct vnode *vp = NULL;
925                         struct mount *mp = NULL;
926
927                         if ((object->type != OBJT_SWAP) && (object->type != OBJT_DEFAULT)) {
928                                 swap_pageouts_ok = 1;
929                         } else {
930                                 swap_pageouts_ok = !(defer_swap_pageouts || disable_swap_pageouts);
931                                 swap_pageouts_ok |= (!disable_swap_pageouts && defer_swap_pageouts &&
932                                 vm_page_count_min());
933                                                                                 
934                         }
935
936                         /*
937                          * We don't bother paging objects that are "dead".  
938                          * Those objects are in a "rundown" state.
939                          */
940                         if (!swap_pageouts_ok || (object->flags & OBJ_DEAD)) {
941                                 VM_OBJECT_UNLOCK(object);
942                                 vm_pageq_requeue(m);
943                                 continue;
944                         }
945
946                         /*
947                          * Following operations may unlock
948                          * vm_page_queue_mtx, invalidating the 'next'
949                          * pointer.  To prevent an inordinate number
950                          * of restarts we use our marker to remember
951                          * our place.
952                          *
953                          */
954                         TAILQ_INSERT_AFTER(&vm_page_queues[PQ_INACTIVE].pl,
955                                            m, &marker, pageq);
956                         /*
957                          * The object is already known NOT to be dead.   It
958                          * is possible for the vget() to block the whole
959                          * pageout daemon, but the new low-memory handling
960                          * code should prevent it.
961                          *
962                          * The previous code skipped locked vnodes and, worse,
963                          * reordered pages in the queue.  This results in
964                          * completely non-deterministic operation and, on a
965                          * busy system, can lead to extremely non-optimal
966                          * pageouts.  For example, it can cause clean pages
967                          * to be freed and dirty pages to be moved to the end
968                          * of the queue.  Since dirty pages are also moved to
969                          * the end of the queue once-cleaned, this gives
970                          * way too large a weighting to defering the freeing
971                          * of dirty pages.
972                          *
973                          * We can't wait forever for the vnode lock, we might
974                          * deadlock due to a vn_read() getting stuck in
975                          * vm_wait while holding this vnode.  We skip the 
976                          * vnode if we can't get it in a reasonable amount
977                          * of time.
978                          */
979                         if (object->type == OBJT_VNODE) {
980                                 vp = object->handle;
981                                 if (vp->v_type == VREG &&
982                                     vn_start_write(vp, &mp, V_NOWAIT) != 0) {
983                                         KASSERT(mp == NULL,
984                                             ("vm_pageout_scan: mp != NULL"));
985                                         ++pageout_lock_miss;
986                                         if (object->flags & OBJ_MIGHTBEDIRTY)
987                                                 vnodes_skipped++;
988                                         goto unlock_and_continue;
989                                 }
990                                 vm_page_unlock_queues();
991                                 vm_object_reference_locked(object);
992                                 VM_OBJECT_UNLOCK(object);
993                                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
994                                 if (vget(vp, LK_EXCLUSIVE | LK_TIMELOCK,
995                                     curthread)) {
996                                         VM_OBJECT_LOCK(object);
997                                         vm_page_lock_queues();
998                                         ++pageout_lock_miss;
999                                         if (object->flags & OBJ_MIGHTBEDIRTY)
1000                                                 vnodes_skipped++;
1001                                         vp = NULL;
1002                                         goto unlock_and_continue;
1003                                 }
1004                                 VM_OBJECT_LOCK(object);
1005                                 vm_page_lock_queues();
1006                                 /*
1007                                  * The page might have been moved to another
1008                                  * queue during potential blocking in vget()
1009                                  * above.  The page might have been freed and
1010                                  * reused for another vnode.
1011                                  */
1012                                 if (m->queue != PQ_INACTIVE ||
1013                                     m->object != object ||
1014                                     TAILQ_NEXT(m, pageq) != &marker) {
1015                                         if (object->flags & OBJ_MIGHTBEDIRTY)
1016                                                 vnodes_skipped++;
1017                                         goto unlock_and_continue;
1018                                 }
1019         
1020                                 /*
1021                                  * The page may have been busied during the
1022                                  * blocking in vget().  We don't move the
1023                                  * page back onto the end of the queue so that
1024                                  * statistics are more correct if we don't.
1025                                  */
1026                                 if (m->busy || (m->flags & PG_BUSY)) {
1027                                         goto unlock_and_continue;
1028                                 }
1029
1030                                 /*
1031                                  * If the page has become held it might
1032                                  * be undergoing I/O, so skip it
1033                                  */
1034                                 if (m->hold_count) {
1035                                         vm_pageq_requeue(m);
1036                                         if (object->flags & OBJ_MIGHTBEDIRTY)
1037                                                 vnodes_skipped++;
1038                                         goto unlock_and_continue;
1039                                 }
1040                         }
1041
1042                         /*
1043                          * If a page is dirty, then it is either being washed
1044                          * (but not yet cleaned) or it is still in the
1045                          * laundry.  If it is still in the laundry, then we
1046                          * start the cleaning operation. 
1047                          *
1048                          * decrement page_shortage on success to account for
1049                          * the (future) cleaned page.  Otherwise we could wind
1050                          * up laundering or cleaning too many pages.
1051                          */
1052                         if (vm_pageout_clean(m) != 0) {
1053                                 --page_shortage;
1054                                 --maxlaunder;
1055                         }
1056 unlock_and_continue:
1057                         VM_OBJECT_UNLOCK(object);
1058                         if (mp != NULL) {
1059                                 vm_page_unlock_queues();
1060                                 if (vp != NULL)
1061                                         vput(vp);
1062                                 VFS_UNLOCK_GIANT(vfslocked);
1063                                 vm_object_deallocate(object);
1064                                 vn_finished_write(mp);
1065                                 vm_page_lock_queues();
1066                         }
1067                         next = TAILQ_NEXT(&marker, pageq);
1068                         TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE].pl,
1069                                      &marker, pageq);
1070                         continue;
1071                 }
1072                 VM_OBJECT_UNLOCK(object);
1073         }
1074
1075         /*
1076          * Compute the number of pages we want to try to move from the
1077          * active queue to the inactive queue.
1078          */
1079         page_shortage = vm_paging_target() +
1080                 cnt.v_inactive_target - cnt.v_inactive_count;
1081         page_shortage += addl_page_shortage;
1082
1083         /*
1084          * Scan the active queue for things we can deactivate. We nominally
1085          * track the per-page activity counter and use it to locate
1086          * deactivation candidates.
1087          */
1088         pcount = cnt.v_active_count;
1089         m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1090
1091         while ((m != NULL) && (pcount-- > 0) && (page_shortage > 0)) {
1092
1093                 KASSERT(m->queue == PQ_ACTIVE,
1094                     ("vm_pageout_scan: page %p isn't active", m));
1095
1096                 next = TAILQ_NEXT(m, pageq);
1097                 object = m->object;
1098                 if ((m->flags & PG_MARKER) != 0) {
1099                         m = next;
1100                         continue;
1101                 }
1102                 if (!VM_OBJECT_TRYLOCK(object) &&
1103                     !vm_pageout_fallback_object_lock(m, &next)) {
1104                         VM_OBJECT_UNLOCK(object);
1105                         m = next;
1106                         continue;
1107                 }
1108
1109                 /*
1110                  * Don't deactivate pages that are busy.
1111                  */
1112                 if ((m->busy != 0) ||
1113                     (m->flags & PG_BUSY) ||
1114                     (m->hold_count != 0)) {
1115                         VM_OBJECT_UNLOCK(object);
1116                         vm_pageq_requeue(m);
1117                         m = next;
1118                         continue;
1119                 }
1120
1121                 /*
1122                  * The count for pagedaemon pages is done after checking the
1123                  * page for eligibility...
1124                  */
1125                 cnt.v_pdpages++;
1126
1127                 /*
1128                  * Check to see "how much" the page has been used.
1129                  */
1130                 actcount = 0;
1131                 if (object->ref_count != 0) {
1132                         if (m->flags & PG_REFERENCED) {
1133                                 actcount += 1;
1134                         }
1135                         actcount += pmap_ts_referenced(m);
1136                         if (actcount) {
1137                                 m->act_count += ACT_ADVANCE + actcount;
1138                                 if (m->act_count > ACT_MAX)
1139                                         m->act_count = ACT_MAX;
1140                         }
1141                 }
1142
1143                 /*
1144                  * Since we have "tested" this bit, we need to clear it now.
1145                  */
1146                 vm_page_flag_clear(m, PG_REFERENCED);
1147
1148                 /*
1149                  * Only if an object is currently being used, do we use the
1150                  * page activation count stats.
1151                  */
1152                 if (actcount && (object->ref_count != 0)) {
1153                         vm_pageq_requeue(m);
1154                 } else {
1155                         m->act_count -= min(m->act_count, ACT_DECLINE);
1156                         if (vm_pageout_algorithm ||
1157                             object->ref_count == 0 ||
1158                             m->act_count == 0) {
1159                                 page_shortage--;
1160                                 if (object->ref_count == 0) {
1161                                         pmap_remove_all(m);
1162                                         if (m->dirty == 0)
1163                                                 vm_page_cache(m);
1164                                         else
1165                                                 vm_page_deactivate(m);
1166                                 } else {
1167                                         vm_page_deactivate(m);
1168                                 }
1169                         } else {
1170                                 vm_pageq_requeue(m);
1171                         }
1172                 }
1173                 VM_OBJECT_UNLOCK(object);
1174                 m = next;
1175         }
1176
1177         /*
1178          * We try to maintain some *really* free pages, this allows interrupt
1179          * code to be guaranteed space.  Since both cache and free queues 
1180          * are considered basically 'free', moving pages from cache to free
1181          * does not effect other calculations.
1182          */
1183         cache_cur = cache_last_free;
1184         cache_first_failure = -1;
1185         while (cnt.v_free_count < cnt.v_free_reserved && (cache_cur =
1186             (cache_cur + PQ_PRIME2) & PQ_L2_MASK) != cache_first_failure) {
1187                 TAILQ_FOREACH(m, &vm_page_queues[PQ_CACHE + cache_cur].pl,
1188                     pageq) {
1189                         KASSERT(m->dirty == 0,
1190                             ("Found dirty cache page %p", m));
1191                         KASSERT(!pmap_page_is_mapped(m),
1192                             ("Found mapped cache page %p", m));
1193                         KASSERT((m->flags & PG_UNMANAGED) == 0,
1194                             ("Found unmanaged cache page %p", m));
1195                         KASSERT(m->wire_count == 0,
1196                             ("Found wired cache page %p", m));
1197                         if (m->hold_count == 0 && VM_OBJECT_TRYLOCK(object =
1198                             m->object)) {
1199                                 KASSERT((m->flags & PG_BUSY) == 0 &&
1200                                     m->busy == 0, ("Found busy cache page %p",
1201                                     m));
1202                                 vm_page_free(m);
1203                                 VM_OBJECT_UNLOCK(object);
1204                                 cnt.v_dfree++;
1205                                 cache_last_free = cache_cur;
1206                                 cache_first_failure = -1;
1207                                 break;
1208                         }
1209                 }
1210                 if (m == NULL && cache_first_failure == -1)
1211                         cache_first_failure = cache_cur;
1212         }
1213         vm_page_unlock_queues();
1214 #if !defined(NO_SWAPPING)
1215         /*
1216          * Idle process swapout -- run once per second.
1217          */
1218         if (vm_swap_idle_enabled) {
1219                 static long lsec;
1220                 if (time_second != lsec) {
1221                         vm_req_vmdaemon(VM_SWAP_IDLE);
1222                         lsec = time_second;
1223                 }
1224         }
1225 #endif
1226                 
1227         /*
1228          * If we didn't get enough free pages, and we have skipped a vnode
1229          * in a writeable object, wakeup the sync daemon.  And kick swapout
1230          * if we did not get enough free pages.
1231          */
1232         if (vm_paging_target() > 0) {
1233                 if (vnodes_skipped && vm_page_count_min())
1234                         (void) speedup_syncer();
1235 #if !defined(NO_SWAPPING)
1236                 if (vm_swap_enabled && vm_page_count_target())
1237                         vm_req_vmdaemon(VM_SWAP_NORMAL);
1238 #endif
1239         }
1240
1241         /*
1242          * If we are critically low on one of RAM or swap and low on
1243          * the other, kill the largest process.  However, we avoid
1244          * doing this on the first pass in order to give ourselves a
1245          * chance to flush out dirty vnode-backed pages and to allow
1246          * active pages to be moved to the inactive queue and reclaimed.
1247          *
1248          * We keep the process bigproc locked once we find it to keep anyone
1249          * from messing with it; however, there is a possibility of
1250          * deadlock if process B is bigproc and one of it's child processes
1251          * attempts to propagate a signal to B while we are waiting for A's
1252          * lock while walking this list.  To avoid this, we don't block on
1253          * the process lock but just skip a process if it is already locked.
1254          */
1255         if (pass != 0 &&
1256             ((swap_pager_avail < 64 && vm_page_count_min()) ||
1257              (swap_pager_full && vm_paging_target() > 0))) {
1258                 bigproc = NULL;
1259                 bigsize = 0;
1260                 sx_slock(&allproc_lock);
1261                 FOREACH_PROC_IN_SYSTEM(p) {
1262                         int breakout;
1263
1264                         if (PROC_TRYLOCK(p) == 0)
1265                                 continue;
1266                         /*
1267                          * If this is a system or protected process, skip it.
1268                          */
1269                         if ((p->p_flag & P_SYSTEM) || (p->p_pid == 1) ||
1270                             (p->p_flag & P_PROTECTED) ||
1271                             ((p->p_pid < 48) && (swap_pager_avail != 0))) {
1272                                 PROC_UNLOCK(p);
1273                                 continue;
1274                         }
1275                         /*
1276                          * If the process is in a non-running type state,
1277                          * don't touch it.  Check all the threads individually.
1278                          */
1279                         mtx_lock_spin(&sched_lock);
1280                         breakout = 0;
1281                         FOREACH_THREAD_IN_PROC(p, td) {
1282                                 if (!TD_ON_RUNQ(td) &&
1283                                     !TD_IS_RUNNING(td) &&
1284                                     !TD_IS_SLEEPING(td)) {
1285                                         breakout = 1;
1286                                         break;
1287                                 }
1288                         }
1289                         if (breakout) {
1290                                 mtx_unlock_spin(&sched_lock);
1291                                 PROC_UNLOCK(p);
1292                                 continue;
1293                         }
1294                         mtx_unlock_spin(&sched_lock);
1295                         /*
1296                          * get the process size
1297                          */
1298                         if (!vm_map_trylock_read(&p->p_vmspace->vm_map)) {
1299                                 PROC_UNLOCK(p);
1300                                 continue;
1301                         }
1302                         size = vmspace_swap_count(p->p_vmspace);
1303                         vm_map_unlock_read(&p->p_vmspace->vm_map);
1304                         size += vmspace_resident_count(p->p_vmspace);
1305                         /*
1306                          * if the this process is bigger than the biggest one
1307                          * remember it.
1308                          */
1309                         if (size > bigsize) {
1310                                 if (bigproc != NULL)
1311                                         PROC_UNLOCK(bigproc);
1312                                 bigproc = p;
1313                                 bigsize = size;
1314                         } else
1315                                 PROC_UNLOCK(p);
1316                 }
1317                 sx_sunlock(&allproc_lock);
1318                 if (bigproc != NULL) {
1319                         killproc(bigproc, "out of swap space");
1320                         mtx_lock_spin(&sched_lock);
1321                         sched_nice(bigproc, PRIO_MIN);
1322                         mtx_unlock_spin(&sched_lock);
1323                         PROC_UNLOCK(bigproc);
1324                         wakeup(&cnt.v_free_count);
1325                 }
1326         }
1327 }
1328
1329 /*
1330  * This routine tries to maintain the pseudo LRU active queue,
1331  * so that during long periods of time where there is no paging,
1332  * that some statistic accumulation still occurs.  This code
1333  * helps the situation where paging just starts to occur.
1334  */
1335 static void
1336 vm_pageout_page_stats()
1337 {
1338         vm_object_t object;
1339         vm_page_t m,next;
1340         int pcount,tpcount;             /* Number of pages to check */
1341         static int fullintervalcount = 0;
1342         int page_shortage;
1343
1344         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1345         page_shortage = 
1346             (cnt.v_inactive_target + cnt.v_cache_max + cnt.v_free_min) -
1347             (cnt.v_free_count + cnt.v_inactive_count + cnt.v_cache_count);
1348
1349         if (page_shortage <= 0)
1350                 return;
1351
1352         pcount = cnt.v_active_count;
1353         fullintervalcount += vm_pageout_stats_interval;
1354         if (fullintervalcount < vm_pageout_full_stats_interval) {
1355                 tpcount = (vm_pageout_stats_max * cnt.v_active_count) / cnt.v_page_count;
1356                 if (pcount > tpcount)
1357                         pcount = tpcount;
1358         } else {
1359                 fullintervalcount = 0;
1360         }
1361
1362         m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1363         while ((m != NULL) && (pcount-- > 0)) {
1364                 int actcount;
1365
1366                 KASSERT(m->queue == PQ_ACTIVE,
1367                     ("vm_pageout_page_stats: page %p isn't active", m));
1368
1369                 next = TAILQ_NEXT(m, pageq);
1370                 object = m->object;
1371
1372                 if ((m->flags & PG_MARKER) != 0) {
1373                         m = next;
1374                         continue;
1375                 }
1376                 if (!VM_OBJECT_TRYLOCK(object) &&
1377                     !vm_pageout_fallback_object_lock(m, &next)) {
1378                         VM_OBJECT_UNLOCK(object);
1379                         m = next;
1380                         continue;
1381                 }
1382
1383                 /*
1384                  * Don't deactivate pages that are busy.
1385                  */
1386                 if ((m->busy != 0) ||
1387                     (m->flags & PG_BUSY) ||
1388                     (m->hold_count != 0)) {
1389                         VM_OBJECT_UNLOCK(object);
1390                         vm_pageq_requeue(m);
1391                         m = next;
1392                         continue;
1393                 }
1394
1395                 actcount = 0;
1396                 if (m->flags & PG_REFERENCED) {
1397                         vm_page_flag_clear(m, PG_REFERENCED);
1398                         actcount += 1;
1399                 }
1400
1401                 actcount += pmap_ts_referenced(m);
1402                 if (actcount) {
1403                         m->act_count += ACT_ADVANCE + actcount;
1404                         if (m->act_count > ACT_MAX)
1405                                 m->act_count = ACT_MAX;
1406                         vm_pageq_requeue(m);
1407                 } else {
1408                         if (m->act_count == 0) {
1409                                 /*
1410                                  * We turn off page access, so that we have
1411                                  * more accurate RSS stats.  We don't do this
1412                                  * in the normal page deactivation when the
1413                                  * system is loaded VM wise, because the
1414                                  * cost of the large number of page protect
1415                                  * operations would be higher than the value
1416                                  * of doing the operation.
1417                                  */
1418                                 pmap_remove_all(m);
1419                                 vm_page_deactivate(m);
1420                         } else {
1421                                 m->act_count -= min(m->act_count, ACT_DECLINE);
1422                                 vm_pageq_requeue(m);
1423                         }
1424                 }
1425                 VM_OBJECT_UNLOCK(object);
1426                 m = next;
1427         }
1428 }
1429
1430 /*
1431  *      vm_pageout is the high level pageout daemon.
1432  */
1433 static void
1434 vm_pageout()
1435 {
1436         int error, pass;
1437
1438         /*
1439          * Initialize some paging parameters.
1440          */
1441         cnt.v_interrupt_free_min = 2;
1442         if (cnt.v_page_count < 2000)
1443                 vm_pageout_page_count = 8;
1444
1445         /*
1446          * v_free_reserved needs to include enough for the largest
1447          * swap pager structures plus enough for any pv_entry structs
1448          * when paging. 
1449          */
1450         if (cnt.v_page_count > 1024)
1451                 cnt.v_free_min = 4 + (cnt.v_page_count - 1024) / 200;
1452         else
1453                 cnt.v_free_min = 4;
1454         cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1455             cnt.v_interrupt_free_min;
1456         cnt.v_free_reserved = vm_pageout_page_count +
1457             cnt.v_pageout_free_min + (cnt.v_page_count / 768) + PQ_L2_SIZE;
1458         cnt.v_free_severe = cnt.v_free_min / 2;
1459         cnt.v_free_min += cnt.v_free_reserved;
1460         cnt.v_free_severe += cnt.v_free_reserved;
1461
1462         /*
1463          * v_free_target and v_cache_min control pageout hysteresis.  Note
1464          * that these are more a measure of the VM cache queue hysteresis
1465          * then the VM free queue.  Specifically, v_free_target is the
1466          * high water mark (free+cache pages).
1467          *
1468          * v_free_reserved + v_cache_min (mostly means v_cache_min) is the
1469          * low water mark, while v_free_min is the stop.  v_cache_min must
1470          * be big enough to handle memory needs while the pageout daemon
1471          * is signalled and run to free more pages.
1472          */
1473         if (cnt.v_free_count > 6144)
1474                 cnt.v_free_target = 4 * cnt.v_free_min + cnt.v_free_reserved;
1475         else
1476                 cnt.v_free_target = 2 * cnt.v_free_min + cnt.v_free_reserved;
1477
1478         if (cnt.v_free_count > 2048) {
1479                 cnt.v_cache_min = cnt.v_free_target;
1480                 cnt.v_cache_max = 2 * cnt.v_cache_min;
1481                 cnt.v_inactive_target = (3 * cnt.v_free_target) / 2;
1482         } else {
1483                 cnt.v_cache_min = 0;
1484                 cnt.v_cache_max = 0;
1485                 cnt.v_inactive_target = cnt.v_free_count / 4;
1486         }
1487         if (cnt.v_inactive_target > cnt.v_free_count / 3)
1488                 cnt.v_inactive_target = cnt.v_free_count / 3;
1489
1490         /* XXX does not really belong here */
1491         if (vm_page_max_wired == 0)
1492                 vm_page_max_wired = cnt.v_free_count / 3;
1493
1494         if (vm_pageout_stats_max == 0)
1495                 vm_pageout_stats_max = cnt.v_free_target;
1496
1497         /*
1498          * Set interval in seconds for stats scan.
1499          */
1500         if (vm_pageout_stats_interval == 0)
1501                 vm_pageout_stats_interval = 5;
1502         if (vm_pageout_full_stats_interval == 0)
1503                 vm_pageout_full_stats_interval = vm_pageout_stats_interval * 4;
1504
1505         swap_pager_swap_init();
1506         pass = 0;
1507         /*
1508          * The pageout daemon is never done, so loop forever.
1509          */
1510         while (TRUE) {
1511                 vm_page_lock_queues();
1512                 /*
1513                  * If we have enough free memory, wakeup waiters.  Do
1514                  * not clear vm_pages_needed until we reach our target,
1515                  * otherwise we may be woken up over and over again and
1516                  * waste a lot of cpu.
1517                  */
1518                 if (vm_pages_needed && !vm_page_count_min()) {
1519                         if (!vm_paging_needed())
1520                                 vm_pages_needed = 0;
1521                         wakeup(&cnt.v_free_count);
1522                 }
1523                 if (vm_pages_needed) {
1524                         /*
1525                          * Still not done, take a second pass without waiting
1526                          * (unlimited dirty cleaning), otherwise sleep a bit
1527                          * and try again.
1528                          */
1529                         ++pass;
1530                         if (pass > 1)
1531                                 msleep(&vm_pages_needed, &vm_page_queue_mtx, PVM,
1532                                        "psleep", hz/2);
1533                 } else {
1534                         /*
1535                          * Good enough, sleep & handle stats.  Prime the pass
1536                          * for the next run.
1537                          */
1538                         if (pass > 1)
1539                                 pass = 1;
1540                         else
1541                                 pass = 0;
1542                         error = msleep(&vm_pages_needed, &vm_page_queue_mtx, PVM,
1543                                     "psleep", vm_pageout_stats_interval * hz);
1544                         if (error && !vm_pages_needed) {
1545                                 pass = 0;
1546                                 vm_pageout_page_stats();
1547                                 vm_page_unlock_queues();
1548                                 continue;
1549                         }
1550                 }
1551                 if (vm_pages_needed)
1552                         cnt.v_pdwakeups++;
1553                 vm_page_unlock_queues();
1554                 vm_pageout_scan(pass);
1555         }
1556 }
1557
1558 /*
1559  * Unless the page queue lock is held by the caller, this function
1560  * should be regarded as advisory.  Specifically, the caller should
1561  * not msleep() on &cnt.v_free_count following this function unless
1562  * the page queue lock is held until the msleep() is performed.
1563  */
1564 void
1565 pagedaemon_wakeup()
1566 {
1567
1568         if (!vm_pages_needed && curthread->td_proc != pageproc) {
1569                 vm_pages_needed = 1;
1570                 wakeup(&vm_pages_needed);
1571         }
1572 }
1573
1574 #if !defined(NO_SWAPPING)
1575 static void
1576 vm_req_vmdaemon(int req)
1577 {
1578         static int lastrun = 0;
1579
1580         mtx_lock(&vm_daemon_mtx);
1581         vm_pageout_req_swapout |= req;
1582         if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
1583                 wakeup(&vm_daemon_needed);
1584                 lastrun = ticks;
1585         }
1586         mtx_unlock(&vm_daemon_mtx);
1587 }
1588
1589 static void
1590 vm_daemon()
1591 {
1592         struct rlimit rsslim;
1593         struct proc *p;
1594         struct thread *td;
1595         int breakout, swapout_flags;
1596
1597         while (TRUE) {
1598                 mtx_lock(&vm_daemon_mtx);
1599                 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep", 0);
1600                 swapout_flags = vm_pageout_req_swapout;
1601                 vm_pageout_req_swapout = 0;
1602                 mtx_unlock(&vm_daemon_mtx);
1603                 if (swapout_flags)
1604                         swapout_procs(swapout_flags);
1605
1606                 /*
1607                  * scan the processes for exceeding their rlimits or if
1608                  * process is swapped out -- deactivate pages
1609                  */
1610                 sx_slock(&allproc_lock);
1611                 LIST_FOREACH(p, &allproc, p_list) {
1612                         vm_pindex_t limit, size;
1613
1614                         /*
1615                          * if this is a system process or if we have already
1616                          * looked at this process, skip it.
1617                          */
1618                         PROC_LOCK(p);
1619                         if (p->p_flag & (P_SYSTEM | P_WEXIT)) {
1620                                 PROC_UNLOCK(p);
1621                                 continue;
1622                         }
1623                         /*
1624                          * if the process is in a non-running type state,
1625                          * don't touch it.
1626                          */
1627                         mtx_lock_spin(&sched_lock);
1628                         breakout = 0;
1629                         FOREACH_THREAD_IN_PROC(p, td) {
1630                                 if (!TD_ON_RUNQ(td) &&
1631                                     !TD_IS_RUNNING(td) &&
1632                                     !TD_IS_SLEEPING(td)) {
1633                                         breakout = 1;
1634                                         break;
1635                                 }
1636                         }
1637                         mtx_unlock_spin(&sched_lock);
1638                         if (breakout) {
1639                                 PROC_UNLOCK(p);
1640                                 continue;
1641                         }
1642                         /*
1643                          * get a limit
1644                          */
1645                         lim_rlimit(p, RLIMIT_RSS, &rsslim);
1646                         limit = OFF_TO_IDX(
1647                             qmin(rsslim.rlim_cur, rsslim.rlim_max));
1648
1649                         /*
1650                          * let processes that are swapped out really be
1651                          * swapped out set the limit to nothing (will force a
1652                          * swap-out.)
1653                          */
1654                         if ((p->p_sflag & PS_INMEM) == 0)
1655                                 limit = 0;      /* XXX */
1656                         PROC_UNLOCK(p);
1657
1658                         size = vmspace_resident_count(p->p_vmspace);
1659                         if (limit >= 0 && size >= limit) {
1660                                 vm_pageout_map_deactivate_pages(
1661                                     &p->p_vmspace->vm_map, limit);
1662                         }
1663                 }
1664                 sx_sunlock(&allproc_lock);
1665         }
1666 }
1667 #endif                  /* !defined(NO_SWAPPING) */