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