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