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