]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - sys/vm/vm_pageout.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / sys / vm / vm_pageout.c
1 /*-
2  * Copyright (c) 1991 Regents of the University of California.
3  * All rights reserved.
4  * Copyright (c) 1994 John S. Dyson
5  * All rights reserved.
6  * Copyright (c) 1994 David Greenman
7  * All rights reserved.
8  * Copyright (c) 2005 Yahoo! Technologies Norway AS
9  * All rights reserved.
10  *
11  * This code is derived from software contributed to Berkeley by
12  * The Mach Operating System project at Carnegie-Mellon University.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. All advertising materials mentioning features or use of this software
23  *    must display the following acknowledgement:
24  *      This product includes software developed by the University of
25  *      California, Berkeley and its contributors.
26  * 4. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  *
42  *      from: @(#)vm_pageout.c  7.4 (Berkeley) 5/7/91
43  *
44  *
45  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
46  * All rights reserved.
47  *
48  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
49  *
50  * Permission to use, copy, modify and distribute this software and
51  * its documentation is hereby granted, provided that both the copyright
52  * notice and this permission notice appear in all copies of the
53  * software, derivative works or modified versions, and any portions
54  * thereof, and that both notices appear in supporting documentation.
55  *
56  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
57  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
58  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
59  *
60  * Carnegie Mellon requests users of this software to return to
61  *
62  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
63  *  School of Computer Science
64  *  Carnegie Mellon University
65  *  Pittsburgh PA 15213-3890
66  *
67  * any improvements or extensions that they make and grant Carnegie the
68  * rights to redistribute these changes.
69  */
70
71 /*
72  *      The proverbial page-out daemon.
73  */
74
75 #include <sys/cdefs.h>
76 __FBSDID("$FreeBSD$");
77
78 #include "opt_vm.h"
79 #include <sys/param.h>
80 #include <sys/systm.h>
81 #include <sys/kernel.h>
82 #include <sys/eventhandler.h>
83 #include <sys/lock.h>
84 #include <sys/mutex.h>
85 #include <sys/proc.h>
86 #include <sys/kthread.h>
87 #include <sys/ktr.h>
88 #include <sys/mount.h>
89 #include <sys/racct.h>
90 #include <sys/resourcevar.h>
91 #include <sys/sched.h>
92 #include <sys/signalvar.h>
93 #include <sys/smp.h>
94 #include <sys/vnode.h>
95 #include <sys/vmmeter.h>
96 #include <sys/rwlock.h>
97 #include <sys/sx.h>
98 #include <sys/sysctl.h>
99
100 #include <vm/vm.h>
101 #include <vm/vm_param.h>
102 #include <vm/vm_object.h>
103 #include <vm/vm_page.h>
104 #include <vm/vm_map.h>
105 #include <vm/vm_pageout.h>
106 #include <vm/vm_pager.h>
107 #include <vm/vm_phys.h>
108 #include <vm/swap_pager.h>
109 #include <vm/vm_extern.h>
110 #include <vm/uma.h>
111
112 /*
113  * System initialization
114  */
115
116 /* the kernel process "vm_pageout"*/
117 static void vm_pageout(void);
118 static int vm_pageout_clean(vm_page_t);
119 static void vm_pageout_scan(struct vm_domain *vmd, int pass);
120 static void vm_pageout_mightbe_oom(struct vm_domain *vmd, int pass);
121
122 struct proc *pageproc;
123
124 static struct kproc_desc page_kp = {
125         "pagedaemon",
126         vm_pageout,
127         &pageproc
128 };
129 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, kproc_start,
130     &page_kp);
131
132 #if !defined(NO_SWAPPING)
133 /* the kernel process "vm_daemon"*/
134 static void vm_daemon(void);
135 static struct   proc *vmproc;
136
137 static struct kproc_desc vm_kp = {
138         "vmdaemon",
139         vm_daemon,
140         &vmproc
141 };
142 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
143 #endif
144
145
146 int vm_pages_needed;            /* Event on which pageout daemon sleeps */
147 int vm_pageout_deficit;         /* Estimated number of pages deficit */
148 int vm_pageout_pages_needed;    /* flag saying that the pageout daemon needs pages */
149 int vm_pageout_wakeup_thresh;
150
151 #if !defined(NO_SWAPPING)
152 static int vm_pageout_req_swapout;      /* XXX */
153 static int vm_daemon_needed;
154 static struct mtx vm_daemon_mtx;
155 /* Allow for use by vm_pageout before vm_daemon is initialized. */
156 MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
157 #endif
158 static int vm_max_launder = 32;
159 static int vm_pageout_update_period;
160 static int defer_swap_pageouts;
161 static int disable_swap_pageouts;
162 static int lowmem_period = 10;
163 static int lowmem_ticks;
164
165 #if defined(NO_SWAPPING)
166 static int vm_swap_enabled = 0;
167 static int vm_swap_idle_enabled = 0;
168 #else
169 static int vm_swap_enabled = 1;
170 static int vm_swap_idle_enabled = 0;
171 #endif
172
173 SYSCTL_INT(_vm, OID_AUTO, pageout_wakeup_thresh,
174         CTLFLAG_RW, &vm_pageout_wakeup_thresh, 0,
175         "free page threshold for waking up the pageout daemon");
176
177 SYSCTL_INT(_vm, OID_AUTO, max_launder,
178         CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
179
180 SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
181         CTLFLAG_RW, &vm_pageout_update_period, 0,
182         "Maximum active LRU update period");
183   
184 SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RW, &lowmem_period, 0,
185         "Low memory callback period");
186
187 #if defined(NO_SWAPPING)
188 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
189         CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout");
190 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
191         CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
192 #else
193 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
194         CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
195 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
196         CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
197 #endif
198
199 SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
200         CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
201
202 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
203         CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
204
205 static int pageout_lock_miss;
206 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
207         CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
208
209 #define VM_PAGEOUT_PAGE_COUNT 16
210 int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
211
212 int vm_page_max_wired;          /* XXX max # of wired pages system-wide */
213 SYSCTL_INT(_vm, OID_AUTO, max_wired,
214         CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
215
216 static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
217 static boolean_t vm_pageout_launder(struct vm_pagequeue *pq, int, vm_paddr_t,
218     vm_paddr_t);
219 #if !defined(NO_SWAPPING)
220 static void vm_pageout_map_deactivate_pages(vm_map_t, long);
221 static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
222 static void vm_req_vmdaemon(int req);
223 #endif
224 static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
225
226 /*
227  * Initialize a dummy page for marking the caller's place in the specified
228  * paging queue.  In principle, this function only needs to set the flag
229  * PG_MARKER.  Nonetheless, it wirte busies and initializes the hold count
230  * to one as safety precautions.
231  */ 
232 static void
233 vm_pageout_init_marker(vm_page_t marker, u_short queue)
234 {
235
236         bzero(marker, sizeof(*marker));
237         marker->flags = PG_MARKER;
238         marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
239         marker->queue = queue;
240         marker->hold_count = 1;
241 }
242
243 /*
244  * vm_pageout_fallback_object_lock:
245  * 
246  * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
247  * known to have failed and page queue must be either PQ_ACTIVE or
248  * PQ_INACTIVE.  To avoid lock order violation, unlock the page queues
249  * while locking the vm object.  Use marker page to detect page queue
250  * changes and maintain notion of next page on page queue.  Return
251  * TRUE if no changes were detected, FALSE otherwise.  vm object is
252  * locked on return.
253  * 
254  * This function depends on both the lock portion of struct vm_object
255  * and normal struct vm_page being type stable.
256  */
257 static boolean_t
258 vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
259 {
260         struct vm_page marker;
261         struct vm_pagequeue *pq;
262         boolean_t unchanged;
263         u_short queue;
264         vm_object_t object;
265
266         queue = m->queue;
267         vm_pageout_init_marker(&marker, queue);
268         pq = vm_page_pagequeue(m);
269         object = m->object;
270         
271         TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
272         vm_pagequeue_unlock(pq);
273         vm_page_unlock(m);
274         VM_OBJECT_WLOCK(object);
275         vm_page_lock(m);
276         vm_pagequeue_lock(pq);
277
278         /* Page queue might have changed. */
279         *next = TAILQ_NEXT(&marker, plinks.q);
280         unchanged = (m->queue == queue &&
281                      m->object == object &&
282                      &marker == TAILQ_NEXT(m, plinks.q));
283         TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
284         return (unchanged);
285 }
286
287 /*
288  * Lock the page while holding the page queue lock.  Use marker page
289  * to detect page queue changes and maintain notion of next page on
290  * page queue.  Return TRUE if no changes were detected, FALSE
291  * otherwise.  The page is locked on return. The page queue lock might
292  * be dropped and reacquired.
293  *
294  * This function depends on normal struct vm_page being type stable.
295  */
296 static boolean_t
297 vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
298 {
299         struct vm_page marker;
300         struct vm_pagequeue *pq;
301         boolean_t unchanged;
302         u_short queue;
303
304         vm_page_lock_assert(m, MA_NOTOWNED);
305         if (vm_page_trylock(m))
306                 return (TRUE);
307
308         queue = m->queue;
309         vm_pageout_init_marker(&marker, queue);
310         pq = vm_page_pagequeue(m);
311
312         TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
313         vm_pagequeue_unlock(pq);
314         vm_page_lock(m);
315         vm_pagequeue_lock(pq);
316
317         /* Page queue might have changed. */
318         *next = TAILQ_NEXT(&marker, plinks.q);
319         unchanged = (m->queue == queue && &marker == TAILQ_NEXT(m, plinks.q));
320         TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
321         return (unchanged);
322 }
323
324 /*
325  * vm_pageout_clean:
326  *
327  * Clean the page and remove it from the laundry.
328  * 
329  * We set the busy bit to cause potential page faults on this page to
330  * block.  Note the careful timing, however, the busy bit isn't set till
331  * late and we cannot do anything that will mess with the page.
332  */
333 static int
334 vm_pageout_clean(vm_page_t m)
335 {
336         vm_object_t object;
337         vm_page_t mc[2*vm_pageout_page_count], pb, ps;
338         int pageout_count;
339         int ib, is, page_base;
340         vm_pindex_t pindex = m->pindex;
341
342         vm_page_lock_assert(m, MA_OWNED);
343         object = m->object;
344         VM_OBJECT_ASSERT_WLOCKED(object);
345
346         /*
347          * It doesn't cost us anything to pageout OBJT_DEFAULT or OBJT_SWAP
348          * with the new swapper, but we could have serious problems paging
349          * out other object types if there is insufficient memory.  
350          *
351          * Unfortunately, checking free memory here is far too late, so the
352          * check has been moved up a procedural level.
353          */
354
355         /*
356          * Can't clean the page if it's busy or held.
357          */
358         vm_page_assert_unbusied(m);
359         KASSERT(m->hold_count == 0, ("vm_pageout_clean: page %p is held", m));
360         vm_page_unlock(m);
361
362         mc[vm_pageout_page_count] = pb = ps = m;
363         pageout_count = 1;
364         page_base = vm_pageout_page_count;
365         ib = 1;
366         is = 1;
367
368         /*
369          * Scan object for clusterable pages.
370          *
371          * We can cluster ONLY if: ->> the page is NOT
372          * clean, wired, busy, held, or mapped into a
373          * buffer, and one of the following:
374          * 1) The page is inactive, or a seldom used
375          *    active page.
376          * -or-
377          * 2) we force the issue.
378          *
379          * During heavy mmap/modification loads the pageout
380          * daemon can really fragment the underlying file
381          * due to flushing pages out of order and not trying
382          * align the clusters (which leave sporatic out-of-order
383          * holes).  To solve this problem we do the reverse scan
384          * first and attempt to align our cluster, then do a 
385          * forward scan if room remains.
386          */
387 more:
388         while (ib && pageout_count < vm_pageout_page_count) {
389                 vm_page_t p;
390
391                 if (ib > pindex) {
392                         ib = 0;
393                         break;
394                 }
395
396                 if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
397                         ib = 0;
398                         break;
399                 }
400                 vm_page_lock(p);
401                 vm_page_test_dirty(p);
402                 if (p->dirty == 0 ||
403                     p->queue != PQ_INACTIVE ||
404                     p->hold_count != 0) {       /* may be undergoing I/O */
405                         vm_page_unlock(p);
406                         ib = 0;
407                         break;
408                 }
409                 vm_page_unlock(p);
410                 mc[--page_base] = pb = p;
411                 ++pageout_count;
412                 ++ib;
413                 /*
414                  * alignment boundry, stop here and switch directions.  Do
415                  * not clear ib.
416                  */
417                 if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
418                         break;
419         }
420
421         while (pageout_count < vm_pageout_page_count && 
422             pindex + is < object->size) {
423                 vm_page_t p;
424
425                 if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
426                         break;
427                 vm_page_lock(p);
428                 vm_page_test_dirty(p);
429                 if (p->dirty == 0 ||
430                     p->queue != PQ_INACTIVE ||
431                     p->hold_count != 0) {       /* may be undergoing I/O */
432                         vm_page_unlock(p);
433                         break;
434                 }
435                 vm_page_unlock(p);
436                 mc[page_base + pageout_count] = ps = p;
437                 ++pageout_count;
438                 ++is;
439         }
440
441         /*
442          * If we exhausted our forward scan, continue with the reverse scan
443          * when possible, even past a page boundry.  This catches boundry
444          * conditions.
445          */
446         if (ib && pageout_count < vm_pageout_page_count)
447                 goto more;
448
449         /*
450          * we allow reads during pageouts...
451          */
452         return (vm_pageout_flush(&mc[page_base], pageout_count, 0, 0, NULL,
453             NULL));
454 }
455
456 /*
457  * vm_pageout_flush() - launder the given pages
458  *
459  *      The given pages are laundered.  Note that we setup for the start of
460  *      I/O ( i.e. busy the page ), mark it read-only, and bump the object
461  *      reference count all in here rather then in the parent.  If we want
462  *      the parent to do more sophisticated things we may have to change
463  *      the ordering.
464  *
465  *      Returned runlen is the count of pages between mreq and first
466  *      page after mreq with status VM_PAGER_AGAIN.
467  *      *eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
468  *      for any page in runlen set.
469  */
470 int
471 vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
472     boolean_t *eio)
473 {
474         vm_object_t object = mc[0]->object;
475         int pageout_status[count];
476         int numpagedout = 0;
477         int i, runlen;
478
479         VM_OBJECT_ASSERT_WLOCKED(object);
480
481         /*
482          * Initiate I/O.  Bump the vm_page_t->busy counter and
483          * mark the pages read-only.
484          *
485          * We do not have to fixup the clean/dirty bits here... we can
486          * allow the pager to do it after the I/O completes.
487          *
488          * NOTE! mc[i]->dirty may be partial or fragmented due to an
489          * edge case with file fragments.
490          */
491         for (i = 0; i < count; i++) {
492                 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
493                     ("vm_pageout_flush: partially invalid page %p index %d/%d",
494                         mc[i], i, count));
495                 vm_page_sbusy(mc[i]);
496                 pmap_remove_write(mc[i]);
497         }
498         vm_object_pip_add(object, count);
499
500         vm_pager_put_pages(object, mc, count, flags, pageout_status);
501
502         runlen = count - mreq;
503         if (eio != NULL)
504                 *eio = FALSE;
505         for (i = 0; i < count; i++) {
506                 vm_page_t mt = mc[i];
507
508                 KASSERT(pageout_status[i] == VM_PAGER_PEND ||
509                     !pmap_page_is_write_mapped(mt),
510                     ("vm_pageout_flush: page %p is not write protected", mt));
511                 switch (pageout_status[i]) {
512                 case VM_PAGER_OK:
513                 case VM_PAGER_PEND:
514                         numpagedout++;
515                         break;
516                 case VM_PAGER_BAD:
517                         /*
518                          * Page outside of range of object. Right now we
519                          * essentially lose the changes by pretending it
520                          * worked.
521                          */
522                         vm_page_undirty(mt);
523                         break;
524                 case VM_PAGER_ERROR:
525                 case VM_PAGER_FAIL:
526                         /*
527                          * If page couldn't be paged out, then reactivate the
528                          * page so it doesn't clog the inactive list.  (We
529                          * will try paging out it again later).
530                          */
531                         vm_page_lock(mt);
532                         vm_page_activate(mt);
533                         vm_page_unlock(mt);
534                         if (eio != NULL && i >= mreq && i - mreq < runlen)
535                                 *eio = TRUE;
536                         break;
537                 case VM_PAGER_AGAIN:
538                         if (i >= mreq && i - mreq < runlen)
539                                 runlen = i - mreq;
540                         break;
541                 }
542
543                 /*
544                  * If the operation is still going, leave the page busy to
545                  * block all other accesses. Also, leave the paging in
546                  * progress indicator set so that we don't attempt an object
547                  * collapse.
548                  */
549                 if (pageout_status[i] != VM_PAGER_PEND) {
550                         vm_object_pip_wakeup(object);
551                         vm_page_sunbusy(mt);
552                         if (vm_page_count_severe()) {
553                                 vm_page_lock(mt);
554                                 vm_page_try_to_cache(mt);
555                                 vm_page_unlock(mt);
556                         }
557                 }
558         }
559         if (prunlen != NULL)
560                 *prunlen = runlen;
561         return (numpagedout);
562 }
563
564 static boolean_t
565 vm_pageout_launder(struct vm_pagequeue *pq, int tries, vm_paddr_t low,
566     vm_paddr_t high)
567 {
568         struct mount *mp;
569         struct vnode *vp;
570         vm_object_t object;
571         vm_paddr_t pa;
572         vm_page_t m, m_tmp, next;
573
574         vm_pagequeue_lock(pq);
575         TAILQ_FOREACH_SAFE(m, &pq->pq_pl, plinks.q, next) {
576                 if ((m->flags & PG_MARKER) != 0)
577                         continue;
578                 pa = VM_PAGE_TO_PHYS(m);
579                 if (pa < low || pa + PAGE_SIZE > high)
580                         continue;
581                 if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
582                         vm_page_unlock(m);
583                         continue;
584                 }
585                 object = m->object;
586                 if ((!VM_OBJECT_TRYWLOCK(object) &&
587                     (!vm_pageout_fallback_object_lock(m, &next) ||
588                     m->hold_count != 0)) || vm_page_busied(m)) {
589                         vm_page_unlock(m);
590                         VM_OBJECT_WUNLOCK(object);
591                         continue;
592                 }
593                 vm_page_test_dirty(m);
594                 if (m->dirty == 0 && object->ref_count != 0)
595                         pmap_remove_all(m);
596                 if (m->dirty != 0) {
597                         vm_page_unlock(m);
598                         if (tries == 0 || (object->flags & OBJ_DEAD) != 0) {
599                                 VM_OBJECT_WUNLOCK(object);
600                                 continue;
601                         }
602                         if (object->type == OBJT_VNODE) {
603                                 vm_pagequeue_unlock(pq);
604                                 vp = object->handle;
605                                 vm_object_reference_locked(object);
606                                 VM_OBJECT_WUNLOCK(object);
607                                 (void)vn_start_write(vp, &mp, V_WAIT);
608                                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
609                                 VM_OBJECT_WLOCK(object);
610                                 vm_object_page_clean(object, 0, 0, OBJPC_SYNC);
611                                 VM_OBJECT_WUNLOCK(object);
612                                 VOP_UNLOCK(vp, 0);
613                                 vm_object_deallocate(object);
614                                 vn_finished_write(mp);
615                                 return (TRUE);
616                         } else if (object->type == OBJT_SWAP ||
617                             object->type == OBJT_DEFAULT) {
618                                 vm_pagequeue_unlock(pq);
619                                 m_tmp = m;
620                                 vm_pageout_flush(&m_tmp, 1, VM_PAGER_PUT_SYNC,
621                                     0, NULL, NULL);
622                                 VM_OBJECT_WUNLOCK(object);
623                                 return (TRUE);
624                         }
625                 } else {
626                         /*
627                          * Dequeue here to prevent lock recursion in
628                          * vm_page_cache().
629                          */
630                         vm_page_dequeue_locked(m);
631                         vm_page_cache(m);
632                         vm_page_unlock(m);
633                 }
634                 VM_OBJECT_WUNLOCK(object);
635         }
636         vm_pagequeue_unlock(pq);
637         return (FALSE);
638 }
639
640 /*
641  * Increase the number of cached pages.  The specified value, "tries",
642  * determines which categories of pages are cached:
643  *
644  *  0: All clean, inactive pages within the specified physical address range
645  *     are cached.  Will not sleep.
646  *  1: The vm_lowmem handlers are called.  All inactive pages within
647  *     the specified physical address range are cached.  May sleep.
648  *  2: The vm_lowmem handlers are called.  All inactive and active pages
649  *     within the specified physical address range are cached.  May sleep.
650  */
651 void
652 vm_pageout_grow_cache(int tries, vm_paddr_t low, vm_paddr_t high)
653 {
654         int actl, actmax, inactl, inactmax, dom, initial_dom;
655         static int start_dom = 0;
656
657         if (tries > 0) {
658                 /*
659                  * Decrease registered cache sizes.  The vm_lowmem handlers
660                  * may acquire locks and/or sleep, so they can only be invoked
661                  * when "tries" is greater than zero.
662                  */
663                 EVENTHANDLER_INVOKE(vm_lowmem, 0);
664
665                 /*
666                  * We do this explicitly after the caches have been drained
667                  * above.
668                  */
669                 uma_reclaim();
670         }
671
672         /*
673          * Make the next scan start on the next domain.
674          */
675         initial_dom = atomic_fetchadd_int(&start_dom, 1) % vm_ndomains;
676
677         inactl = 0;
678         inactmax = cnt.v_inactive_count;
679         actl = 0;
680         actmax = tries < 2 ? 0 : cnt.v_active_count;
681         dom = initial_dom;
682
683         /*
684          * Scan domains in round-robin order, first inactive queues,
685          * then active.  Since domain usually owns large physically
686          * contiguous chunk of memory, it makes sense to completely
687          * exhaust one domain before switching to next, while growing
688          * the pool of contiguous physical pages.
689          *
690          * Do not even start launder a domain which cannot contain
691          * the specified address range, as indicated by segments
692          * constituting the domain.
693          */
694 again:
695         if (inactl < inactmax) {
696                 if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
697                     low, high) &&
698                     vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_INACTIVE],
699                     tries, low, high)) {
700                         inactl++;
701                         goto again;
702                 }
703                 if (++dom == vm_ndomains)
704                         dom = 0;
705                 if (dom != initial_dom)
706                         goto again;
707         }
708         if (actl < actmax) {
709                 if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
710                     low, high) &&
711                     vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_ACTIVE],
712                       tries, low, high)) {
713                         actl++;
714                         goto again;
715                 }
716                 if (++dom == vm_ndomains)
717                         dom = 0;
718                 if (dom != initial_dom)
719                         goto again;
720         }
721 }
722
723 #if !defined(NO_SWAPPING)
724 /*
725  *      vm_pageout_object_deactivate_pages
726  *
727  *      Deactivate enough pages to satisfy the inactive target
728  *      requirements.
729  *
730  *      The object and map must be locked.
731  */
732 static void
733 vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
734     long desired)
735 {
736         vm_object_t backing_object, object;
737         vm_page_t p;
738         int act_delta, remove_mode;
739
740         VM_OBJECT_ASSERT_LOCKED(first_object);
741         if ((first_object->flags & OBJ_FICTITIOUS) != 0)
742                 return;
743         for (object = first_object;; object = backing_object) {
744                 if (pmap_resident_count(pmap) <= desired)
745                         goto unlock_return;
746                 VM_OBJECT_ASSERT_LOCKED(object);
747                 if ((object->flags & OBJ_UNMANAGED) != 0 ||
748                     object->paging_in_progress != 0)
749                         goto unlock_return;
750
751                 remove_mode = 0;
752                 if (object->shadow_count > 1)
753                         remove_mode = 1;
754                 /*
755                  * Scan the object's entire memory queue.
756                  */
757                 TAILQ_FOREACH(p, &object->memq, listq) {
758                         if (pmap_resident_count(pmap) <= desired)
759                                 goto unlock_return;
760                         if (vm_page_busied(p))
761                                 continue;
762                         PCPU_INC(cnt.v_pdpages);
763                         vm_page_lock(p);
764                         if (p->wire_count != 0 || p->hold_count != 0 ||
765                             !pmap_page_exists_quick(pmap, p)) {
766                                 vm_page_unlock(p);
767                                 continue;
768                         }
769                         act_delta = pmap_ts_referenced(p);
770                         if ((p->aflags & PGA_REFERENCED) != 0) {
771                                 if (act_delta == 0)
772                                         act_delta = 1;
773                                 vm_page_aflag_clear(p, PGA_REFERENCED);
774                         }
775                         if (p->queue != PQ_ACTIVE && act_delta != 0) {
776                                 vm_page_activate(p);
777                                 p->act_count += act_delta;
778                         } else if (p->queue == PQ_ACTIVE) {
779                                 if (act_delta == 0) {
780                                         p->act_count -= min(p->act_count,
781                                             ACT_DECLINE);
782                                         if (!remove_mode && p->act_count == 0) {
783                                                 pmap_remove_all(p);
784                                                 vm_page_deactivate(p);
785                                         } else
786                                                 vm_page_requeue(p);
787                                 } else {
788                                         vm_page_activate(p);
789                                         if (p->act_count < ACT_MAX -
790                                             ACT_ADVANCE)
791                                                 p->act_count += ACT_ADVANCE;
792                                         vm_page_requeue(p);
793                                 }
794                         } else if (p->queue == PQ_INACTIVE)
795                                 pmap_remove_all(p);
796                         vm_page_unlock(p);
797                 }
798                 if ((backing_object = object->backing_object) == NULL)
799                         goto unlock_return;
800                 VM_OBJECT_RLOCK(backing_object);
801                 if (object != first_object)
802                         VM_OBJECT_RUNLOCK(object);
803         }
804 unlock_return:
805         if (object != first_object)
806                 VM_OBJECT_RUNLOCK(object);
807 }
808
809 /*
810  * deactivate some number of pages in a map, try to do it fairly, but
811  * that is really hard to do.
812  */
813 static void
814 vm_pageout_map_deactivate_pages(map, desired)
815         vm_map_t map;
816         long desired;
817 {
818         vm_map_entry_t tmpe;
819         vm_object_t obj, bigobj;
820         int nothingwired;
821
822         if (!vm_map_trylock(map))
823                 return;
824
825         bigobj = NULL;
826         nothingwired = TRUE;
827
828         /*
829          * first, search out the biggest object, and try to free pages from
830          * that.
831          */
832         tmpe = map->header.next;
833         while (tmpe != &map->header) {
834                 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
835                         obj = tmpe->object.vm_object;
836                         if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
837                                 if (obj->shadow_count <= 1 &&
838                                     (bigobj == NULL ||
839                                      bigobj->resident_page_count < obj->resident_page_count)) {
840                                         if (bigobj != NULL)
841                                                 VM_OBJECT_RUNLOCK(bigobj);
842                                         bigobj = obj;
843                                 } else
844                                         VM_OBJECT_RUNLOCK(obj);
845                         }
846                 }
847                 if (tmpe->wired_count > 0)
848                         nothingwired = FALSE;
849                 tmpe = tmpe->next;
850         }
851
852         if (bigobj != NULL) {
853                 vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
854                 VM_OBJECT_RUNLOCK(bigobj);
855         }
856         /*
857          * Next, hunt around for other pages to deactivate.  We actually
858          * do this search sort of wrong -- .text first is not the best idea.
859          */
860         tmpe = map->header.next;
861         while (tmpe != &map->header) {
862                 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
863                         break;
864                 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
865                         obj = tmpe->object.vm_object;
866                         if (obj != NULL) {
867                                 VM_OBJECT_RLOCK(obj);
868                                 vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
869                                 VM_OBJECT_RUNLOCK(obj);
870                         }
871                 }
872                 tmpe = tmpe->next;
873         }
874
875         /*
876          * Remove all mappings if a process is swapped out, this will free page
877          * table pages.
878          */
879         if (desired == 0 && nothingwired) {
880                 pmap_remove(vm_map_pmap(map), vm_map_min(map),
881                     vm_map_max(map));
882         }
883         vm_map_unlock(map);
884 }
885 #endif          /* !defined(NO_SWAPPING) */
886
887 /*
888  *      vm_pageout_scan does the dirty work for the pageout daemon.
889  *
890  *      pass 0 - Update active LRU/deactivate pages
891  *      pass 1 - Move inactive to cache or free
892  *      pass 2 - Launder dirty pages
893  */
894 static void
895 vm_pageout_scan(struct vm_domain *vmd, int pass)
896 {
897         vm_page_t m, next;
898         struct vm_pagequeue *pq;
899         int page_shortage, maxscan, pcount;
900         int addl_page_shortage;
901         vm_object_t object;
902         int act_delta;
903         int vnodes_skipped = 0;
904         int maxlaunder;
905         boolean_t queues_locked;
906
907         /*
908          * If we need to reclaim memory ask kernel caches to return
909          * some.  We rate limit to avoid thrashing.
910          */
911         if (vmd == &vm_dom[0] && pass > 0 &&
912             lowmem_ticks + (lowmem_period * hz) < ticks) {
913                 /*
914                  * Decrease registered cache sizes.
915                  */
916                 EVENTHANDLER_INVOKE(vm_lowmem, 0);
917                 /*
918                  * We do this explicitly after the caches have been
919                  * drained above.
920                  */
921                 uma_reclaim();
922                 lowmem_ticks = ticks;
923         }
924
925         /*
926          * The addl_page_shortage is the number of temporarily
927          * stuck pages in the inactive queue.  In other words, the
928          * number of pages from the inactive count that should be
929          * discounted in setting the target for the active queue scan.
930          */
931         addl_page_shortage = atomic_readandclear_int(&vm_pageout_deficit);
932
933         /*
934          * Calculate the number of pages we want to either free or move
935          * to the cache.
936          */
937         page_shortage = vm_paging_target() + addl_page_shortage;
938
939         /*
940          * maxlaunder limits the number of dirty pages we flush per scan.
941          * For most systems a smaller value (16 or 32) is more robust under
942          * extreme memory and disk pressure because any unnecessary writes
943          * to disk can result in extreme performance degredation.  However,
944          * systems with excessive dirty pages (especially when MAP_NOSYNC is
945          * used) will die horribly with limited laundering.  If the pageout
946          * daemon cannot clean enough pages in the first pass, we let it go
947          * all out in succeeding passes.
948          */
949         if ((maxlaunder = vm_max_launder) <= 1)
950                 maxlaunder = 1;
951         if (pass > 1)
952                 maxlaunder = 10000;
953
954         /*
955          * Start scanning the inactive queue for pages we can move to the
956          * cache or free.  The scan will stop when the target is reached or
957          * we have scanned the entire inactive queue.  Note that m->act_count
958          * is not used to form decisions for the inactive queue, only for the
959          * active queue.
960          */
961         pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
962         maxscan = pq->pq_cnt;
963         vm_pagequeue_lock(pq);
964         queues_locked = TRUE;
965         for (m = TAILQ_FIRST(&pq->pq_pl);
966              m != NULL && maxscan-- > 0 && page_shortage > 0;
967              m = next) {
968                 vm_pagequeue_assert_locked(pq);
969                 KASSERT(queues_locked, ("unlocked queues"));
970                 KASSERT(m->queue == PQ_INACTIVE, ("Inactive queue %p", m));
971
972                 PCPU_INC(cnt.v_pdpages);
973                 next = TAILQ_NEXT(m, plinks.q);
974
975                 /*
976                  * skip marker pages
977                  */
978                 if (m->flags & PG_MARKER)
979                         continue;
980
981                 KASSERT((m->flags & PG_FICTITIOUS) == 0,
982                     ("Fictitious page %p cannot be in inactive queue", m));
983                 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
984                     ("Unmanaged page %p cannot be in inactive queue", m));
985
986                 /*
987                  * The page or object lock acquisitions fail if the
988                  * page was removed from the queue or moved to a
989                  * different position within the queue.  In either
990                  * case, addl_page_shortage should not be incremented.
991                  */
992                 if (!vm_pageout_page_lock(m, &next)) {
993                         vm_page_unlock(m);
994                         continue;
995                 }
996                 object = m->object;
997                 if (!VM_OBJECT_TRYWLOCK(object) &&
998                     !vm_pageout_fallback_object_lock(m, &next)) {
999                         vm_page_unlock(m);
1000                         VM_OBJECT_WUNLOCK(object);
1001                         continue;
1002                 }
1003
1004                 /*
1005                  * Don't mess with busy pages, keep them at at the
1006                  * front of the queue, most likely they are being
1007                  * paged out.  Increment addl_page_shortage for busy
1008                  * pages, because they may leave the inactive queue
1009                  * shortly after page scan is finished.
1010                  */
1011                 if (vm_page_busied(m)) {
1012                         vm_page_unlock(m);
1013                         VM_OBJECT_WUNLOCK(object);
1014                         addl_page_shortage++;
1015                         continue;
1016                 }
1017
1018                 /*
1019                  * We unlock the inactive page queue, invalidating the
1020                  * 'next' pointer.  Use our marker to remember our
1021                  * place.
1022                  */
1023                 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
1024                 vm_pagequeue_unlock(pq);
1025                 queues_locked = FALSE;
1026
1027                 /*
1028                  * We bump the activation count if the page has been
1029                  * referenced while in the inactive queue.  This makes
1030                  * it less likely that the page will be added back to the
1031                  * inactive queue prematurely again.  Here we check the 
1032                  * page tables (or emulated bits, if any), given the upper 
1033                  * level VM system not knowing anything about existing 
1034                  * references.
1035                  */
1036                 act_delta = 0;
1037                 if ((m->aflags & PGA_REFERENCED) != 0) {
1038                         vm_page_aflag_clear(m, PGA_REFERENCED);
1039                         act_delta = 1;
1040                 }
1041                 if (object->ref_count != 0) {
1042                         act_delta += pmap_ts_referenced(m);
1043                 } else {
1044                         KASSERT(!pmap_page_is_mapped(m),
1045                             ("vm_pageout_scan: page %p is mapped", m));
1046                 }
1047
1048                 /*
1049                  * If the upper level VM system knows about any page 
1050                  * references, we reactivate the page or requeue it.
1051                  */
1052                 if (act_delta != 0) {
1053                         if (object->ref_count) {
1054                                 vm_page_activate(m);
1055                                 m->act_count += act_delta + ACT_ADVANCE;
1056                         } else {
1057                                 vm_pagequeue_lock(pq);
1058                                 queues_locked = TRUE;
1059                                 vm_page_requeue_locked(m);
1060                         }
1061                         VM_OBJECT_WUNLOCK(object);
1062                         vm_page_unlock(m);
1063                         goto relock_queues;
1064                 }
1065
1066                 if (m->hold_count != 0) {
1067                         vm_page_unlock(m);
1068                         VM_OBJECT_WUNLOCK(object);
1069
1070                         /*
1071                          * Held pages are essentially stuck in the
1072                          * queue.  So, they ought to be discounted
1073                          * from the inactive count.  See the
1074                          * calculation of the page_shortage for the
1075                          * loop over the active queue below.
1076                          */
1077                         addl_page_shortage++;
1078                         goto relock_queues;
1079                 }
1080
1081                 /*
1082                  * If the page appears to be clean at the machine-independent
1083                  * layer, then remove all of its mappings from the pmap in
1084                  * anticipation of placing it onto the cache queue.  If,
1085                  * however, any of the page's mappings allow write access,
1086                  * then the page may still be modified until the last of those
1087                  * mappings are removed.
1088                  */
1089                 vm_page_test_dirty(m);
1090                 if (m->dirty == 0 && object->ref_count != 0)
1091                         pmap_remove_all(m);
1092
1093                 if (m->valid == 0) {
1094                         /*
1095                          * Invalid pages can be easily freed
1096                          */
1097                         vm_page_free(m);
1098                         PCPU_INC(cnt.v_dfree);
1099                         --page_shortage;
1100                 } else if (m->dirty == 0) {
1101                         /*
1102                          * Clean pages can be placed onto the cache queue.
1103                          * This effectively frees them.
1104                          */
1105                         vm_page_cache(m);
1106                         --page_shortage;
1107                 } else if ((m->flags & PG_WINATCFLS) == 0 && pass < 2) {
1108                         /*
1109                          * Dirty pages need to be paged out, but flushing
1110                          * a page is extremely expensive verses freeing
1111                          * a clean page.  Rather then artificially limiting
1112                          * the number of pages we can flush, we instead give
1113                          * dirty pages extra priority on the inactive queue
1114                          * by forcing them to be cycled through the queue
1115                          * twice before being flushed, after which the
1116                          * (now clean) page will cycle through once more
1117                          * before being freed.  This significantly extends
1118                          * the thrash point for a heavily loaded machine.
1119                          */
1120                         m->flags |= PG_WINATCFLS;
1121                         vm_pagequeue_lock(pq);
1122                         queues_locked = TRUE;
1123                         vm_page_requeue_locked(m);
1124                 } else if (maxlaunder > 0) {
1125                         /*
1126                          * We always want to try to flush some dirty pages if
1127                          * we encounter them, to keep the system stable.
1128                          * Normally this number is small, but under extreme
1129                          * pressure where there are insufficient clean pages
1130                          * on the inactive queue, we may have to go all out.
1131                          */
1132                         int swap_pageouts_ok;
1133                         struct vnode *vp = NULL;
1134                         struct mount *mp = NULL;
1135
1136                         if ((object->type != OBJT_SWAP) && (object->type != OBJT_DEFAULT)) {
1137                                 swap_pageouts_ok = 1;
1138                         } else {
1139                                 swap_pageouts_ok = !(defer_swap_pageouts || disable_swap_pageouts);
1140                                 swap_pageouts_ok |= (!disable_swap_pageouts && defer_swap_pageouts &&
1141                                 vm_page_count_min());
1142                                                                                 
1143                         }
1144
1145                         /*
1146                          * We don't bother paging objects that are "dead".  
1147                          * Those objects are in a "rundown" state.
1148                          */
1149                         if (!swap_pageouts_ok || (object->flags & OBJ_DEAD)) {
1150                                 vm_pagequeue_lock(pq);
1151                                 vm_page_unlock(m);
1152                                 VM_OBJECT_WUNLOCK(object);
1153                                 queues_locked = TRUE;
1154                                 vm_page_requeue_locked(m);
1155                                 goto relock_queues;
1156                         }
1157
1158                         /*
1159                          * The object is already known NOT to be dead.   It
1160                          * is possible for the vget() to block the whole
1161                          * pageout daemon, but the new low-memory handling
1162                          * code should prevent it.
1163                          *
1164                          * The previous code skipped locked vnodes and, worse,
1165                          * reordered pages in the queue.  This results in
1166                          * completely non-deterministic operation and, on a
1167                          * busy system, can lead to extremely non-optimal
1168                          * pageouts.  For example, it can cause clean pages
1169                          * to be freed and dirty pages to be moved to the end
1170                          * of the queue.  Since dirty pages are also moved to
1171                          * the end of the queue once-cleaned, this gives
1172                          * way too large a weighting to defering the freeing
1173                          * of dirty pages.
1174                          *
1175                          * We can't wait forever for the vnode lock, we might
1176                          * deadlock due to a vn_read() getting stuck in
1177                          * vm_wait while holding this vnode.  We skip the 
1178                          * vnode if we can't get it in a reasonable amount
1179                          * of time.
1180                          */
1181                         if (object->type == OBJT_VNODE) {
1182                                 vm_page_unlock(m);
1183                                 vp = object->handle;
1184                                 if (vp->v_type == VREG &&
1185                                     vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1186                                         mp = NULL;
1187                                         ++pageout_lock_miss;
1188                                         if (object->flags & OBJ_MIGHTBEDIRTY)
1189                                                 vnodes_skipped++;
1190                                         goto unlock_and_continue;
1191                                 }
1192                                 KASSERT(mp != NULL,
1193                                     ("vp %p with NULL v_mount", vp));
1194                                 vm_object_reference_locked(object);
1195                                 VM_OBJECT_WUNLOCK(object);
1196                                 if (vget(vp, LK_EXCLUSIVE | LK_TIMELOCK,
1197                                     curthread)) {
1198                                         VM_OBJECT_WLOCK(object);
1199                                         ++pageout_lock_miss;
1200                                         if (object->flags & OBJ_MIGHTBEDIRTY)
1201                                                 vnodes_skipped++;
1202                                         vp = NULL;
1203                                         goto unlock_and_continue;
1204                                 }
1205                                 VM_OBJECT_WLOCK(object);
1206                                 vm_page_lock(m);
1207                                 vm_pagequeue_lock(pq);
1208                                 queues_locked = TRUE;
1209                                 /*
1210                                  * The page might have been moved to another
1211                                  * queue during potential blocking in vget()
1212                                  * above.  The page might have been freed and
1213                                  * reused for another vnode.
1214                                  */
1215                                 if (m->queue != PQ_INACTIVE ||
1216                                     m->object != object ||
1217                                     TAILQ_NEXT(m, plinks.q) != &vmd->vmd_marker) {
1218                                         vm_page_unlock(m);
1219                                         if (object->flags & OBJ_MIGHTBEDIRTY)
1220                                                 vnodes_skipped++;
1221                                         goto unlock_and_continue;
1222                                 }
1223         
1224                                 /*
1225                                  * The page may have been busied during the
1226                                  * blocking in vget().  We don't move the
1227                                  * page back onto the end of the queue so that
1228                                  * statistics are more correct if we don't.
1229                                  */
1230                                 if (vm_page_busied(m)) {
1231                                         vm_page_unlock(m);
1232                                         goto unlock_and_continue;
1233                                 }
1234
1235                                 /*
1236                                  * If the page has become held it might
1237                                  * be undergoing I/O, so skip it
1238                                  */
1239                                 if (m->hold_count) {
1240                                         vm_page_unlock(m);
1241                                         vm_page_requeue_locked(m);
1242                                         if (object->flags & OBJ_MIGHTBEDIRTY)
1243                                                 vnodes_skipped++;
1244                                         goto unlock_and_continue;
1245                                 }
1246                                 vm_pagequeue_unlock(pq);
1247                                 queues_locked = FALSE;
1248                         }
1249
1250                         /*
1251                          * If a page is dirty, then it is either being washed
1252                          * (but not yet cleaned) or it is still in the
1253                          * laundry.  If it is still in the laundry, then we
1254                          * start the cleaning operation. 
1255                          *
1256                          * decrement page_shortage on success to account for
1257                          * the (future) cleaned page.  Otherwise we could wind
1258                          * up laundering or cleaning too many pages.
1259                          */
1260                         if (vm_pageout_clean(m) != 0) {
1261                                 --page_shortage;
1262                                 --maxlaunder;
1263                         }
1264 unlock_and_continue:
1265                         vm_page_lock_assert(m, MA_NOTOWNED);
1266                         VM_OBJECT_WUNLOCK(object);
1267                         if (mp != NULL) {
1268                                 if (queues_locked) {
1269                                         vm_pagequeue_unlock(pq);
1270                                         queues_locked = FALSE;
1271                                 }
1272                                 if (vp != NULL)
1273                                         vput(vp);
1274                                 vm_object_deallocate(object);
1275                                 vn_finished_write(mp);
1276                         }
1277                         vm_page_lock_assert(m, MA_NOTOWNED);
1278                         goto relock_queues;
1279                 }
1280                 vm_page_unlock(m);
1281                 VM_OBJECT_WUNLOCK(object);
1282 relock_queues:
1283                 if (!queues_locked) {
1284                         vm_pagequeue_lock(pq);
1285                         queues_locked = TRUE;
1286                 }
1287                 next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1288                 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
1289         }
1290         vm_pagequeue_unlock(pq);
1291
1292         /*
1293          * Compute the number of pages we want to try to move from the
1294          * active queue to the inactive queue.
1295          */
1296         pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1297         vm_pagequeue_lock(pq);
1298         pcount = pq->pq_cnt;
1299         page_shortage = vm_paging_target() +
1300             cnt.v_inactive_target - cnt.v_inactive_count;
1301         page_shortage += addl_page_shortage;
1302         /*
1303          * If we're just idle polling attempt to visit every
1304          * active page within 'update_period' seconds.
1305          */
1306          if (pass == 0 && vm_pageout_update_period != 0) {
1307                 pcount /= vm_pageout_update_period;
1308                 page_shortage = pcount;
1309         }
1310
1311         /*
1312          * Scan the active queue for things we can deactivate. We nominally
1313          * track the per-page activity counter and use it to locate
1314          * deactivation candidates.
1315          */
1316         m = TAILQ_FIRST(&pq->pq_pl);
1317         while ((m != NULL) && (pcount-- > 0) && (page_shortage > 0)) {
1318
1319                 KASSERT(m->queue == PQ_ACTIVE,
1320                     ("vm_pageout_scan: page %p isn't active", m));
1321
1322                 next = TAILQ_NEXT(m, plinks.q);
1323                 if ((m->flags & PG_MARKER) != 0) {
1324                         m = next;
1325                         continue;
1326                 }
1327                 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1328                     ("Fictitious page %p cannot be in active queue", m));
1329                 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1330                     ("Unmanaged page %p cannot be in active queue", m));
1331                 if (!vm_pageout_page_lock(m, &next)) {
1332                         vm_page_unlock(m);
1333                         m = next;
1334                         continue;
1335                 }
1336
1337                 /*
1338                  * The count for pagedaemon pages is done after checking the
1339                  * page for eligibility...
1340                  */
1341                 PCPU_INC(cnt.v_pdpages);
1342
1343                 /*
1344                  * Check to see "how much" the page has been used.
1345                  */
1346                 act_delta = 0;
1347                 if (m->aflags & PGA_REFERENCED) {
1348                         vm_page_aflag_clear(m, PGA_REFERENCED);
1349                         act_delta += 1;
1350                 }
1351                 /*
1352                  * Unlocked object ref count check.  Two races are possible.
1353                  * 1) The ref was transitioning to zero and we saw non-zero,
1354                  *    the pmap bits will be checked unnecessarily.
1355                  * 2) The ref was transitioning to one and we saw zero. 
1356                  *    The page lock prevents a new reference to this page so
1357                  *    we need not check the reference bits.
1358                  */
1359                 if (m->object->ref_count != 0)
1360                         act_delta += pmap_ts_referenced(m);
1361
1362                 /*
1363                  * Advance or decay the act_count based on recent usage.
1364                  */
1365                 if (act_delta) {
1366                         m->act_count += ACT_ADVANCE + act_delta;
1367                         if (m->act_count > ACT_MAX)
1368                                 m->act_count = ACT_MAX;
1369                 } else {
1370                         m->act_count -= min(m->act_count, ACT_DECLINE);
1371                         act_delta = m->act_count;
1372                 }
1373
1374                 /*
1375                  * Move this page to the tail of the active or inactive
1376                  * queue depending on usage.
1377                  */
1378                 if (act_delta == 0) {
1379                         /* Dequeue to avoid later lock recursion. */
1380                         vm_page_dequeue_locked(m);
1381                         vm_page_deactivate(m);
1382                         page_shortage--;
1383                 } else
1384                         vm_page_requeue_locked(m);
1385                 vm_page_unlock(m);
1386                 m = next;
1387         }
1388         vm_pagequeue_unlock(pq);
1389 #if !defined(NO_SWAPPING)
1390         /*
1391          * Idle process swapout -- run once per second.
1392          */
1393         if (vm_swap_idle_enabled) {
1394                 static long lsec;
1395                 if (time_second != lsec) {
1396                         vm_req_vmdaemon(VM_SWAP_IDLE);
1397                         lsec = time_second;
1398                 }
1399         }
1400 #endif
1401                 
1402         /*
1403          * If we didn't get enough free pages, and we have skipped a vnode
1404          * in a writeable object, wakeup the sync daemon.  And kick swapout
1405          * if we did not get enough free pages.
1406          */
1407         if (vm_paging_target() > 0) {
1408                 if (vnodes_skipped && vm_page_count_min())
1409                         (void) speedup_syncer();
1410 #if !defined(NO_SWAPPING)
1411                 if (vm_swap_enabled && vm_page_count_target())
1412                         vm_req_vmdaemon(VM_SWAP_NORMAL);
1413 #endif
1414         }
1415
1416         /*
1417          * If we are critically low on one of RAM or swap and low on
1418          * the other, kill the largest process.  However, we avoid
1419          * doing this on the first pass in order to give ourselves a
1420          * chance to flush out dirty vnode-backed pages and to allow
1421          * active pages to be moved to the inactive queue and reclaimed.
1422          */
1423         vm_pageout_mightbe_oom(vmd, pass);
1424 }
1425
1426 static int vm_pageout_oom_vote;
1427
1428 /*
1429  * The pagedaemon threads randlomly select one to perform the
1430  * OOM.  Trying to kill processes before all pagedaemons
1431  * failed to reach free target is premature.
1432  */
1433 static void
1434 vm_pageout_mightbe_oom(struct vm_domain *vmd, int pass)
1435 {
1436         int old_vote;
1437
1438         if (pass <= 1 || !((swap_pager_avail < 64 && vm_page_count_min()) ||
1439             (swap_pager_full && vm_paging_target() > 0))) {
1440                 if (vmd->vmd_oom) {
1441                         vmd->vmd_oom = FALSE;
1442                         atomic_subtract_int(&vm_pageout_oom_vote, 1);
1443                 }
1444                 return;
1445         }
1446
1447         if (vmd->vmd_oom)
1448                 return;
1449
1450         vmd->vmd_oom = TRUE;
1451         old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1452         if (old_vote != vm_ndomains - 1)
1453                 return;
1454
1455         /*
1456          * The current pagedaemon thread is the last in the quorum to
1457          * start OOM.  Initiate the selection and signaling of the
1458          * victim.
1459          */
1460         vm_pageout_oom(VM_OOM_MEM);
1461
1462         /*
1463          * After one round of OOM terror, recall our vote.  On the
1464          * next pass, current pagedaemon would vote again if the low
1465          * memory condition is still there, due to vmd_oom being
1466          * false.
1467          */
1468         vmd->vmd_oom = FALSE;
1469         atomic_subtract_int(&vm_pageout_oom_vote, 1);
1470 }
1471
1472 void
1473 vm_pageout_oom(int shortage)
1474 {
1475         struct proc *p, *bigproc;
1476         vm_offset_t size, bigsize;
1477         struct thread *td;
1478         struct vmspace *vm;
1479
1480         /*
1481          * We keep the process bigproc locked once we find it to keep anyone
1482          * from messing with it; however, there is a possibility of
1483          * deadlock if process B is bigproc and one of it's child processes
1484          * attempts to propagate a signal to B while we are waiting for A's
1485          * lock while walking this list.  To avoid this, we don't block on
1486          * the process lock but just skip a process if it is already locked.
1487          */
1488         bigproc = NULL;
1489         bigsize = 0;
1490         sx_slock(&allproc_lock);
1491         FOREACH_PROC_IN_SYSTEM(p) {
1492                 int breakout;
1493
1494                 if (PROC_TRYLOCK(p) == 0)
1495                         continue;
1496                 /*
1497                  * If this is a system, protected or killed process, skip it.
1498                  */
1499                 if (p->p_state != PRS_NORMAL ||
1500                     (p->p_flag & (P_INEXEC | P_PROTECTED | P_SYSTEM)) ||
1501                     (p->p_pid == 1) || P_KILLED(p) ||
1502                     ((p->p_pid < 48) && (swap_pager_avail != 0))) {
1503                         PROC_UNLOCK(p);
1504                         continue;
1505                 }
1506                 /*
1507                  * If the process is in a non-running type state,
1508                  * don't touch it.  Check all the threads individually.
1509                  */
1510                 breakout = 0;
1511                 FOREACH_THREAD_IN_PROC(p, td) {
1512                         thread_lock(td);
1513                         if (!TD_ON_RUNQ(td) &&
1514                             !TD_IS_RUNNING(td) &&
1515                             !TD_IS_SLEEPING(td) &&
1516                             !TD_IS_SUSPENDED(td)) {
1517                                 thread_unlock(td);
1518                                 breakout = 1;
1519                                 break;
1520                         }
1521                         thread_unlock(td);
1522                 }
1523                 if (breakout) {
1524                         PROC_UNLOCK(p);
1525                         continue;
1526                 }
1527                 /*
1528                  * get the process size
1529                  */
1530                 vm = vmspace_acquire_ref(p);
1531                 if (vm == NULL) {
1532                         PROC_UNLOCK(p);
1533                         continue;
1534                 }
1535                 if (!vm_map_trylock_read(&vm->vm_map)) {
1536                         vmspace_free(vm);
1537                         PROC_UNLOCK(p);
1538                         continue;
1539                 }
1540                 size = vmspace_swap_count(vm);
1541                 vm_map_unlock_read(&vm->vm_map);
1542                 if (shortage == VM_OOM_MEM)
1543                         size += vmspace_resident_count(vm);
1544                 vmspace_free(vm);
1545                 /*
1546                  * if the this process is bigger than the biggest one
1547                  * remember it.
1548                  */
1549                 if (size > bigsize) {
1550                         if (bigproc != NULL)
1551                                 PROC_UNLOCK(bigproc);
1552                         bigproc = p;
1553                         bigsize = size;
1554                 } else
1555                         PROC_UNLOCK(p);
1556         }
1557         sx_sunlock(&allproc_lock);
1558         if (bigproc != NULL) {
1559                 killproc(bigproc, "out of swap space");
1560                 sched_nice(bigproc, PRIO_MIN);
1561                 PROC_UNLOCK(bigproc);
1562                 wakeup(&cnt.v_free_count);
1563         }
1564 }
1565
1566 static void
1567 vm_pageout_worker(void *arg)
1568 {
1569         struct vm_domain *domain;
1570         int domidx;
1571
1572         domidx = (uintptr_t)arg;
1573         domain = &vm_dom[domidx];
1574
1575         /*
1576          * XXXKIB It could be useful to bind pageout daemon threads to
1577          * the cores belonging to the domain, from which vm_page_array
1578          * is allocated.
1579          */
1580
1581         KASSERT(domain->vmd_segs != 0, ("domain without segments"));
1582         vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
1583
1584         /*
1585          * The pageout daemon worker is never done, so loop forever.
1586          */
1587         while (TRUE) {
1588                 /*
1589                  * If we have enough free memory, wakeup waiters.  Do
1590                  * not clear vm_pages_needed until we reach our target,
1591                  * otherwise we may be woken up over and over again and
1592                  * waste a lot of cpu.
1593                  */
1594                 mtx_lock(&vm_page_queue_free_mtx);
1595                 if (vm_pages_needed && !vm_page_count_min()) {
1596                         if (!vm_paging_needed())
1597                                 vm_pages_needed = 0;
1598                         wakeup(&cnt.v_free_count);
1599                 }
1600                 if (vm_pages_needed) {
1601                         /*
1602                          * Still not done, take a second pass without waiting
1603                          * (unlimited dirty cleaning), otherwise sleep a bit
1604                          * and try again.
1605                          */
1606                         if (domain->vmd_pass > 1)
1607                                 msleep(&vm_pages_needed,
1608                                     &vm_page_queue_free_mtx, PVM, "psleep",
1609                                     hz / 2);
1610                 } else {
1611                         /*
1612                          * Good enough, sleep until required to refresh
1613                          * stats.
1614                          */
1615                         domain->vmd_pass = 0;
1616                         msleep(&vm_pages_needed, &vm_page_queue_free_mtx,
1617                             PVM, "psleep", hz);
1618
1619                 }
1620                 if (vm_pages_needed) {
1621                         cnt.v_pdwakeups++;
1622                         domain->vmd_pass++;
1623                 }
1624                 mtx_unlock(&vm_page_queue_free_mtx);
1625                 vm_pageout_scan(domain, domain->vmd_pass);
1626         }
1627 }
1628
1629 /*
1630  *      vm_pageout is the high level pageout daemon.
1631  */
1632 static void
1633 vm_pageout(void)
1634 {
1635 #if MAXMEMDOM > 1
1636         int error, i;
1637 #endif
1638
1639         /*
1640          * Initialize some paging parameters.
1641          */
1642         cnt.v_interrupt_free_min = 2;
1643         if (cnt.v_page_count < 2000)
1644                 vm_pageout_page_count = 8;
1645
1646         /*
1647          * v_free_reserved needs to include enough for the largest
1648          * swap pager structures plus enough for any pv_entry structs
1649          * when paging. 
1650          */
1651         if (cnt.v_page_count > 1024)
1652                 cnt.v_free_min = 4 + (cnt.v_page_count - 1024) / 200;
1653         else
1654                 cnt.v_free_min = 4;
1655         cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1656             cnt.v_interrupt_free_min;
1657         cnt.v_free_reserved = vm_pageout_page_count +
1658             cnt.v_pageout_free_min + (cnt.v_page_count / 768);
1659         cnt.v_free_severe = cnt.v_free_min / 2;
1660         cnt.v_free_target = 4 * cnt.v_free_min + cnt.v_free_reserved;
1661         cnt.v_free_min += cnt.v_free_reserved;
1662         cnt.v_free_severe += cnt.v_free_reserved;
1663         cnt.v_inactive_target = (3 * cnt.v_free_target) / 2;
1664         if (cnt.v_inactive_target > cnt.v_free_count / 3)
1665                 cnt.v_inactive_target = cnt.v_free_count / 3;
1666
1667         /*
1668          * Set the default wakeup threshold to be 10% above the minimum
1669          * page limit.  This keeps the steady state out of shortfall.
1670          */
1671         vm_pageout_wakeup_thresh = (cnt.v_free_min / 10) * 11;
1672
1673         /*
1674          * Set interval in seconds for active scan.  We want to visit each
1675          * page at least once every ten minutes.  This is to prevent worst
1676          * case paging behaviors with stale active LRU.
1677          */
1678         if (vm_pageout_update_period == 0)
1679                 vm_pageout_update_period = 600;
1680
1681         /* XXX does not really belong here */
1682         if (vm_page_max_wired == 0)
1683                 vm_page_max_wired = cnt.v_free_count / 3;
1684
1685         swap_pager_swap_init();
1686 #if MAXMEMDOM > 1
1687         for (i = 1; i < vm_ndomains; i++) {
1688                 error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
1689                     curproc, NULL, 0, 0, "dom%d", i);
1690                 if (error != 0) {
1691                         panic("starting pageout for domain %d, error %d\n",
1692                             i, error);
1693                 }
1694         }
1695 #endif
1696         vm_pageout_worker((uintptr_t)0);
1697 }
1698
1699 /*
1700  * Unless the free page queue lock is held by the caller, this function
1701  * should be regarded as advisory.  Specifically, the caller should
1702  * not msleep() on &cnt.v_free_count following this function unless
1703  * the free page queue lock is held until the msleep() is performed.
1704  */
1705 void
1706 pagedaemon_wakeup(void)
1707 {
1708
1709         if (!vm_pages_needed && curthread->td_proc != pageproc) {
1710                 vm_pages_needed = 1;
1711                 wakeup(&vm_pages_needed);
1712         }
1713 }
1714
1715 #if !defined(NO_SWAPPING)
1716 static void
1717 vm_req_vmdaemon(int req)
1718 {
1719         static int lastrun = 0;
1720
1721         mtx_lock(&vm_daemon_mtx);
1722         vm_pageout_req_swapout |= req;
1723         if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
1724                 wakeup(&vm_daemon_needed);
1725                 lastrun = ticks;
1726         }
1727         mtx_unlock(&vm_daemon_mtx);
1728 }
1729
1730 static void
1731 vm_daemon(void)
1732 {
1733         struct rlimit rsslim;
1734         struct proc *p;
1735         struct thread *td;
1736         struct vmspace *vm;
1737         int breakout, swapout_flags, tryagain, attempts;
1738 #ifdef RACCT
1739         uint64_t rsize, ravailable;
1740 #endif
1741
1742         while (TRUE) {
1743                 mtx_lock(&vm_daemon_mtx);
1744 #ifdef RACCT
1745                 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep", hz);
1746 #else
1747                 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep", 0);
1748 #endif
1749                 swapout_flags = vm_pageout_req_swapout;
1750                 vm_pageout_req_swapout = 0;
1751                 mtx_unlock(&vm_daemon_mtx);
1752                 if (swapout_flags)
1753                         swapout_procs(swapout_flags);
1754
1755                 /*
1756                  * scan the processes for exceeding their rlimits or if
1757                  * process is swapped out -- deactivate pages
1758                  */
1759                 tryagain = 0;
1760                 attempts = 0;
1761 again:
1762                 attempts++;
1763                 sx_slock(&allproc_lock);
1764                 FOREACH_PROC_IN_SYSTEM(p) {
1765                         vm_pindex_t limit, size;
1766
1767                         /*
1768                          * if this is a system process or if we have already
1769                          * looked at this process, skip it.
1770                          */
1771                         PROC_LOCK(p);
1772                         if (p->p_state != PRS_NORMAL ||
1773                             p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
1774                                 PROC_UNLOCK(p);
1775                                 continue;
1776                         }
1777                         /*
1778                          * if the process is in a non-running type state,
1779                          * don't touch it.
1780                          */
1781                         breakout = 0;
1782                         FOREACH_THREAD_IN_PROC(p, td) {
1783                                 thread_lock(td);
1784                                 if (!TD_ON_RUNQ(td) &&
1785                                     !TD_IS_RUNNING(td) &&
1786                                     !TD_IS_SLEEPING(td) &&
1787                                     !TD_IS_SUSPENDED(td)) {
1788                                         thread_unlock(td);
1789                                         breakout = 1;
1790                                         break;
1791                                 }
1792                                 thread_unlock(td);
1793                         }
1794                         if (breakout) {
1795                                 PROC_UNLOCK(p);
1796                                 continue;
1797                         }
1798                         /*
1799                          * get a limit
1800                          */
1801                         lim_rlimit(p, RLIMIT_RSS, &rsslim);
1802                         limit = OFF_TO_IDX(
1803                             qmin(rsslim.rlim_cur, rsslim.rlim_max));
1804
1805                         /*
1806                          * let processes that are swapped out really be
1807                          * swapped out set the limit to nothing (will force a
1808                          * swap-out.)
1809                          */
1810                         if ((p->p_flag & P_INMEM) == 0)
1811                                 limit = 0;      /* XXX */
1812                         vm = vmspace_acquire_ref(p);
1813                         PROC_UNLOCK(p);
1814                         if (vm == NULL)
1815                                 continue;
1816
1817                         size = vmspace_resident_count(vm);
1818                         if (size >= limit) {
1819                                 vm_pageout_map_deactivate_pages(
1820                                     &vm->vm_map, limit);
1821                         }
1822 #ifdef RACCT
1823                         rsize = IDX_TO_OFF(size);
1824                         PROC_LOCK(p);
1825                         racct_set(p, RACCT_RSS, rsize);
1826                         ravailable = racct_get_available(p, RACCT_RSS);
1827                         PROC_UNLOCK(p);
1828                         if (rsize > ravailable) {
1829                                 /*
1830                                  * Don't be overly aggressive; this might be
1831                                  * an innocent process, and the limit could've
1832                                  * been exceeded by some memory hog.  Don't
1833                                  * try to deactivate more than 1/4th of process'
1834                                  * resident set size.
1835                                  */
1836                                 if (attempts <= 8) {
1837                                         if (ravailable < rsize - (rsize / 4))
1838                                                 ravailable = rsize - (rsize / 4);
1839                                 }
1840                                 vm_pageout_map_deactivate_pages(
1841                                     &vm->vm_map, OFF_TO_IDX(ravailable));
1842                                 /* Update RSS usage after paging out. */
1843                                 size = vmspace_resident_count(vm);
1844                                 rsize = IDX_TO_OFF(size);
1845                                 PROC_LOCK(p);
1846                                 racct_set(p, RACCT_RSS, rsize);
1847                                 PROC_UNLOCK(p);
1848                                 if (rsize > ravailable)
1849                                         tryagain = 1;
1850                         }
1851 #endif
1852                         vmspace_free(vm);
1853                 }
1854                 sx_sunlock(&allproc_lock);
1855                 if (tryagain != 0 && attempts <= 10)
1856                         goto again;
1857         }
1858 }
1859 #endif                  /* !defined(NO_SWAPPING) */