]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vm_page.c
Relax the page queue lock assertions in vm_page_remove() and
[FreeBSD/FreeBSD.git] / sys / vm / vm_page.c
1 /*-
2  * Copyright (c) 1991 Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * The Mach Operating System project at Carnegie-Mellon University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      from: @(#)vm_page.c     7.4 (Berkeley) 5/7/91
33  */
34
35 /*-
36  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
37  * All rights reserved.
38  *
39  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
40  *
41  * Permission to use, copy, modify and distribute this software and
42  * its documentation is hereby granted, provided that both the copyright
43  * notice and this permission notice appear in all copies of the
44  * software, derivative works or modified versions, and any portions
45  * thereof, and that both notices appear in supporting documentation.
46  *
47  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
48  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
49  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
50  *
51  * Carnegie Mellon requests users of this software to return to
52  *
53  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
54  *  School of Computer Science
55  *  Carnegie Mellon University
56  *  Pittsburgh PA 15213-3890
57  *
58  * any improvements or extensions that they make and grant Carnegie the
59  * rights to redistribute these changes.
60  */
61
62 /*
63  *                      GENERAL RULES ON VM_PAGE MANIPULATION
64  *
65  *      - a pageq mutex is required when adding or removing a page from a
66  *        page queue (vm_page_queue[]), regardless of other mutexes or the
67  *        busy state of a page.
68  *
69  *      - a hash chain mutex is required when associating or disassociating
70  *        a page from the VM PAGE CACHE hash table (vm_page_buckets),
71  *        regardless of other mutexes or the busy state of a page.
72  *
73  *      - either a hash chain mutex OR a busied page is required in order
74  *        to modify the page flags.  A hash chain mutex must be obtained in
75  *        order to busy a page.  A page's flags cannot be modified by a
76  *        hash chain mutex if the page is marked busy.
77  *
78  *      - The object memq mutex is held when inserting or removing
79  *        pages from an object (vm_page_insert() or vm_page_remove()).  This
80  *        is different from the object's main mutex.
81  *
82  *      Generally speaking, you have to be aware of side effects when running
83  *      vm_page ops.  A vm_page_lookup() will return with the hash chain
84  *      locked, whether it was able to lookup the page or not.  vm_page_free(),
85  *      vm_page_cache(), vm_page_activate(), and a number of other routines
86  *      will release the hash chain mutex for you.  Intermediate manipulation
87  *      routines such as vm_page_flag_set() expect the hash chain to be held
88  *      on entry and the hash chain will remain held on return.
89  *
90  *      pageq scanning can only occur with the pageq in question locked.
91  *      We have a known bottleneck with the active queue, but the cache
92  *      and free queues are actually arrays already. 
93  */
94
95 /*
96  *      Resident memory management module.
97  */
98
99 #include <sys/cdefs.h>
100 __FBSDID("$FreeBSD$");
101
102 #include <sys/param.h>
103 #include <sys/systm.h>
104 #include <sys/lock.h>
105 #include <sys/kernel.h>
106 #include <sys/malloc.h>
107 #include <sys/mutex.h>
108 #include <sys/proc.h>
109 #include <sys/sysctl.h>
110 #include <sys/vmmeter.h>
111 #include <sys/vnode.h>
112
113 #include <vm/vm.h>
114 #include <vm/vm_param.h>
115 #include <vm/vm_kern.h>
116 #include <vm/vm_object.h>
117 #include <vm/vm_page.h>
118 #include <vm/vm_pageout.h>
119 #include <vm/vm_pager.h>
120 #include <vm/vm_extern.h>
121 #include <vm/uma.h>
122 #include <vm/uma_int.h>
123
124 #include <machine/md_var.h>
125
126 /*
127  *      Associated with page of user-allocatable memory is a
128  *      page structure.
129  */
130
131 struct mtx vm_page_queue_mtx;
132 struct mtx vm_page_queue_free_mtx;
133
134 vm_page_t vm_page_array = 0;
135 int vm_page_array_size = 0;
136 long first_page = 0;
137 int vm_page_zero_count = 0;
138
139 static int boot_pages = UMA_BOOT_PAGES;
140 TUNABLE_INT("vm.boot_pages", &boot_pages);
141 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RD, &boot_pages, 0,
142         "number of pages allocated for bootstrapping the VM system");
143
144 /*
145  *      vm_set_page_size:
146  *
147  *      Sets the page size, perhaps based upon the memory
148  *      size.  Must be called before any use of page-size
149  *      dependent functions.
150  */
151 void
152 vm_set_page_size(void)
153 {
154         if (cnt.v_page_size == 0)
155                 cnt.v_page_size = PAGE_SIZE;
156         if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
157                 panic("vm_set_page_size: page size not a power of two");
158 }
159
160 /*
161  *      vm_page_blacklist_lookup:
162  *
163  *      See if a physical address in this page has been listed
164  *      in the blacklist tunable.  Entries in the tunable are
165  *      separated by spaces or commas.  If an invalid integer is
166  *      encountered then the rest of the string is skipped.
167  */
168 static int
169 vm_page_blacklist_lookup(char *list, vm_paddr_t pa)
170 {
171         vm_paddr_t bad;
172         char *cp, *pos;
173
174         for (pos = list; *pos != '\0'; pos = cp) {
175                 bad = strtoq(pos, &cp, 0);
176                 if (*cp != '\0') {
177                         if (*cp == ' ' || *cp == ',') {
178                                 cp++;
179                                 if (cp == pos)
180                                         continue;
181                         } else
182                                 break;
183                 }
184                 if (pa == trunc_page(bad))
185                         return (1);
186         }
187         return (0);
188 }
189
190 /*
191  *      vm_page_startup:
192  *
193  *      Initializes the resident memory module.
194  *
195  *      Allocates memory for the page cells, and
196  *      for the object/offset-to-page hash table headers.
197  *      Each page cell is initialized and placed on the free list.
198  */
199 vm_offset_t
200 vm_page_startup(vm_offset_t vaddr)
201 {
202         vm_offset_t mapped;
203         vm_size_t npages;
204         vm_paddr_t page_range;
205         vm_paddr_t new_end;
206         int i;
207         vm_paddr_t pa;
208         int nblocks;
209         vm_paddr_t last_pa;
210         char *list;
211
212         /* the biggest memory array is the second group of pages */
213         vm_paddr_t end;
214         vm_paddr_t biggestsize;
215         vm_paddr_t low_water, high_water;
216         int biggestone;
217
218         vm_paddr_t total;
219
220         total = 0;
221         biggestsize = 0;
222         biggestone = 0;
223         nblocks = 0;
224         vaddr = round_page(vaddr);
225
226         for (i = 0; phys_avail[i + 1]; i += 2) {
227                 phys_avail[i] = round_page(phys_avail[i]);
228                 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
229         }
230
231         low_water = phys_avail[0];
232         high_water = phys_avail[1];
233
234         for (i = 0; phys_avail[i + 1]; i += 2) {
235                 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
236
237                 if (size > biggestsize) {
238                         biggestone = i;
239                         biggestsize = size;
240                 }
241                 if (phys_avail[i] < low_water)
242                         low_water = phys_avail[i];
243                 if (phys_avail[i + 1] > high_water)
244                         high_water = phys_avail[i + 1];
245                 ++nblocks;
246                 total += size;
247         }
248
249         end = phys_avail[biggestone+1];
250
251         /*
252          * Initialize the locks.
253          */
254         mtx_init(&vm_page_queue_mtx, "vm page queue mutex", NULL, MTX_DEF |
255             MTX_RECURSE);
256         mtx_init(&vm_page_queue_free_mtx, "vm page queue free mutex", NULL,
257             MTX_DEF);
258
259         /*
260          * Initialize the queue headers for the free queue, the active queue
261          * and the inactive queue.
262          */
263         vm_pageq_init();
264
265         /*
266          * Allocate memory for use when boot strapping the kernel memory
267          * allocator.
268          */
269         new_end = end - (boot_pages * UMA_SLAB_SIZE);
270         new_end = trunc_page(new_end);
271         mapped = pmap_map(&vaddr, new_end, end,
272             VM_PROT_READ | VM_PROT_WRITE);
273         bzero((void *)mapped, end - new_end);
274         uma_startup((void *)mapped, boot_pages);
275
276 #if defined(__amd64__) || defined(__i386__)
277         /*
278          * Allocate a bitmap to indicate that a random physical page
279          * needs to be included in a minidump.
280          *
281          * The amd64 port needs this to indicate which direct map pages
282          * need to be dumped, via calls to dump_add_page()/dump_drop_page().
283          *
284          * However, i386 still needs this workspace internally within the
285          * minidump code.  In theory, they are not needed on i386, but are
286          * included should the sf_buf code decide to use them.
287          */
288         page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE;
289         vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
290         new_end -= vm_page_dump_size;
291         vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
292             new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
293         bzero((void *)vm_page_dump, vm_page_dump_size);
294 #endif
295         /*
296          * Compute the number of pages of memory that will be available for
297          * use (taking into account the overhead of a page structure per
298          * page).
299          */
300         first_page = low_water / PAGE_SIZE;
301         page_range = high_water / PAGE_SIZE - first_page;
302         npages = (total - (page_range * sizeof(struct vm_page)) -
303             (end - new_end)) / PAGE_SIZE;
304         end = new_end;
305
306         /*
307          * Reserve an unmapped guard page to trap access to vm_page_array[-1].
308          */
309         vaddr += PAGE_SIZE;
310
311         /*
312          * Initialize the mem entry structures now, and put them in the free
313          * queue.
314          */
315         new_end = trunc_page(end - page_range * sizeof(struct vm_page));
316         mapped = pmap_map(&vaddr, new_end, end,
317             VM_PROT_READ | VM_PROT_WRITE);
318         vm_page_array = (vm_page_t) mapped;
319 #ifdef __amd64__
320         /*
321          * pmap_map on amd64 comes out of the direct-map, not kvm like i386,
322          * so the pages must be tracked for a crashdump to include this data.
323          * This includes the vm_page_array and the early UMA bootstrap pages.
324          */
325         for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
326                 dump_add_page(pa);
327 #endif  
328         phys_avail[biggestone + 1] = new_end;
329
330         /*
331          * Clear all of the page structures
332          */
333         bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
334         vm_page_array_size = page_range;
335
336         /*
337          * This assertion tests the hypothesis that npages and total are
338          * redundant.  XXX
339          */
340         page_range = 0;
341         for (i = 0; phys_avail[i + 1] != 0; i += 2)
342                 page_range += atop(phys_avail[i + 1] - phys_avail[i]);
343         KASSERT(page_range == npages,
344             ("vm_page_startup: inconsistent page counts"));
345
346         /*
347          * Construct the free queue(s) in descending order (by physical
348          * address) so that the first 16MB of physical memory is allocated
349          * last rather than first.  On large-memory machines, this avoids
350          * the exhaustion of low physical memory before isa_dma_init has run.
351          */
352         cnt.v_page_count = 0;
353         cnt.v_free_count = 0;
354         list = getenv("vm.blacklist");
355         for (i = 0; phys_avail[i + 1] != 0; i += 2) {
356                 pa = phys_avail[i];
357                 last_pa = phys_avail[i + 1];
358                 while (pa < last_pa) {
359                         if (list != NULL &&
360                             vm_page_blacklist_lookup(list, pa))
361                                 printf("Skipping page with pa 0x%jx\n",
362                                     (uintmax_t)pa);
363                         else
364                                 vm_pageq_add_new_page(pa);
365                         pa += PAGE_SIZE;
366                 }
367         }
368         freeenv(list);
369         return (vaddr);
370 }
371
372 void
373 vm_page_flag_set(vm_page_t m, unsigned short bits)
374 {
375
376         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
377         m->flags |= bits;
378
379
380 void
381 vm_page_flag_clear(vm_page_t m, unsigned short bits)
382 {
383
384         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
385         m->flags &= ~bits;
386 }
387
388 void
389 vm_page_busy(vm_page_t m)
390 {
391
392         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
393         KASSERT((m->oflags & VPO_BUSY) == 0,
394             ("vm_page_busy: page already busy!!!"));
395         m->oflags |= VPO_BUSY;
396 }
397
398 /*
399  *      vm_page_flash:
400  *
401  *      wakeup anyone waiting for the page.
402  */
403 void
404 vm_page_flash(vm_page_t m)
405 {
406
407         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
408         if (m->oflags & VPO_WANTED) {
409                 m->oflags &= ~VPO_WANTED;
410                 wakeup(m);
411         }
412 }
413
414 /*
415  *      vm_page_wakeup:
416  *
417  *      clear the VPO_BUSY flag and wakeup anyone waiting for the
418  *      page.
419  *
420  */
421 void
422 vm_page_wakeup(vm_page_t m)
423 {
424
425         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
426         KASSERT(m->oflags & VPO_BUSY, ("vm_page_wakeup: page not busy!!!"));
427         m->oflags &= ~VPO_BUSY;
428         vm_page_flash(m);
429 }
430
431 void
432 vm_page_io_start(vm_page_t m)
433 {
434
435         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
436         m->busy++;
437 }
438
439 void
440 vm_page_io_finish(vm_page_t m)
441 {
442
443         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
444         m->busy--;
445         if (m->busy == 0)
446                 vm_page_flash(m);
447 }
448
449 /*
450  * Keep page from being freed by the page daemon
451  * much of the same effect as wiring, except much lower
452  * overhead and should be used only for *very* temporary
453  * holding ("wiring").
454  */
455 void
456 vm_page_hold(vm_page_t mem)
457 {
458
459         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
460         mem->hold_count++;
461 }
462
463 void
464 vm_page_unhold(vm_page_t mem)
465 {
466
467         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
468         --mem->hold_count;
469         KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
470         if (mem->hold_count == 0 && VM_PAGE_INQUEUE2(mem, PQ_HOLD))
471                 vm_page_free_toq(mem);
472 }
473
474 /*
475  *      vm_page_free:
476  *
477  *      Free a page
478  *
479  *      The clearing of PG_ZERO is a temporary safety until the code can be
480  *      reviewed to determine that PG_ZERO is being properly cleared on
481  *      write faults or maps.  PG_ZERO was previously cleared in
482  *      vm_page_alloc().
483  */
484 void
485 vm_page_free(vm_page_t m)
486 {
487         vm_page_flag_clear(m, PG_ZERO);
488         vm_page_free_toq(m);
489 }
490
491 /*
492  *      vm_page_free_zero:
493  *
494  *      Free a page to the zerod-pages queue
495  */
496 void
497 vm_page_free_zero(vm_page_t m)
498 {
499         vm_page_flag_set(m, PG_ZERO);
500         vm_page_free_toq(m);
501 }
502
503 /*
504  *      vm_page_sleep:
505  *
506  *      Sleep and release the page queues lock.
507  *
508  *      The object containing the given page must be locked.
509  */
510 void
511 vm_page_sleep(vm_page_t m, const char *msg)
512 {
513
514         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
515         if (!mtx_owned(&vm_page_queue_mtx))
516                 vm_page_lock_queues();
517         vm_page_flag_set(m, PG_REFERENCED);
518         vm_page_unlock_queues();
519
520         /*
521          * It's possible that while we sleep, the page will get
522          * unbusied and freed.  If we are holding the object
523          * lock, we will assume we hold a reference to the object
524          * such that even if m->object changes, we can re-lock
525          * it.
526          */
527         m->oflags |= VPO_WANTED;
528         msleep(m, VM_OBJECT_MTX(m->object), PVM, msg, 0);
529 }
530
531 /*
532  *      vm_page_dirty:
533  *
534  *      make page all dirty
535  */
536 void
537 vm_page_dirty(vm_page_t m)
538 {
539         KASSERT(VM_PAGE_GETKNOWNQUEUE1(m) != PQ_CACHE,
540             ("vm_page_dirty: page in cache!"));
541         KASSERT(VM_PAGE_GETKNOWNQUEUE1(m) != PQ_FREE,
542             ("vm_page_dirty: page is free!"));
543         m->dirty = VM_PAGE_BITS_ALL;
544 }
545
546 /*
547  *      vm_page_splay:
548  *
549  *      Implements Sleator and Tarjan's top-down splay algorithm.  Returns
550  *      the vm_page containing the given pindex.  If, however, that
551  *      pindex is not found in the vm_object, returns a vm_page that is
552  *      adjacent to the pindex, coming before or after it.
553  */
554 vm_page_t
555 vm_page_splay(vm_pindex_t pindex, vm_page_t root)
556 {
557         struct vm_page dummy;
558         vm_page_t lefttreemax, righttreemin, y;
559
560         if (root == NULL)
561                 return (root);
562         lefttreemax = righttreemin = &dummy;
563         for (;; root = y) {
564                 if (pindex < root->pindex) {
565                         if ((y = root->left) == NULL)
566                                 break;
567                         if (pindex < y->pindex) {
568                                 /* Rotate right. */
569                                 root->left = y->right;
570                                 y->right = root;
571                                 root = y;
572                                 if ((y = root->left) == NULL)
573                                         break;
574                         }
575                         /* Link into the new root's right tree. */
576                         righttreemin->left = root;
577                         righttreemin = root;
578                 } else if (pindex > root->pindex) {
579                         if ((y = root->right) == NULL)
580                                 break;
581                         if (pindex > y->pindex) {
582                                 /* Rotate left. */
583                                 root->right = y->left;
584                                 y->left = root;
585                                 root = y;
586                                 if ((y = root->right) == NULL)
587                                         break;
588                         }
589                         /* Link into the new root's left tree. */
590                         lefttreemax->right = root;
591                         lefttreemax = root;
592                 } else
593                         break;
594         }
595         /* Assemble the new root. */
596         lefttreemax->right = root->left;
597         righttreemin->left = root->right;
598         root->left = dummy.right;
599         root->right = dummy.left;
600         return (root);
601 }
602
603 /*
604  *      vm_page_insert:         [ internal use only ]
605  *
606  *      Inserts the given mem entry into the object and object list.
607  *
608  *      The pagetables are not updated but will presumably fault the page
609  *      in if necessary, or if a kernel page the caller will at some point
610  *      enter the page into the kernel's pmap.  We are not allowed to block
611  *      here so we *can't* do this anyway.
612  *
613  *      The object and page must be locked.
614  *      This routine may not block.
615  */
616 void
617 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
618 {
619         vm_page_t root;
620
621         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
622         if (m->object != NULL)
623                 panic("vm_page_insert: page already inserted");
624
625         /*
626          * Record the object/offset pair in this page
627          */
628         m->object = object;
629         m->pindex = pindex;
630
631         /*
632          * Now link into the object's ordered list of backed pages.
633          */
634         root = object->root;
635         if (root == NULL) {
636                 m->left = NULL;
637                 m->right = NULL;
638                 TAILQ_INSERT_TAIL(&object->memq, m, listq);
639         } else {
640                 root = vm_page_splay(pindex, root);
641                 if (pindex < root->pindex) {
642                         m->left = root->left;
643                         m->right = root;
644                         root->left = NULL;
645                         TAILQ_INSERT_BEFORE(root, m, listq);
646                 } else if (pindex == root->pindex)
647                         panic("vm_page_insert: offset already allocated");
648                 else {
649                         m->right = root->right;
650                         m->left = root;
651                         root->right = NULL;
652                         TAILQ_INSERT_AFTER(&object->memq, root, m, listq);
653                 }
654         }
655         object->root = m;
656         object->generation++;
657
658         /*
659          * show that the object has one more resident page.
660          */
661         object->resident_page_count++;
662         /*
663          * Hold the vnode until the last page is released.
664          */
665         if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
666                 vhold((struct vnode *)object->handle);
667
668         /*
669          * Since we are inserting a new and possibly dirty page,
670          * update the object's OBJ_MIGHTBEDIRTY flag.
671          */
672         if (m->flags & PG_WRITEABLE)
673                 vm_object_set_writeable_dirty(object);
674 }
675
676 /*
677  *      vm_page_remove:
678  *                              NOTE: used by device pager as well -wfj
679  *
680  *      Removes the given mem entry from the object/offset-page
681  *      table and the object page list, but do not invalidate/terminate
682  *      the backing store.
683  *
684  *      The object and page must be locked.
685  *      The underlying pmap entry (if any) is NOT removed here.
686  *      This routine may not block.
687  */
688 void
689 vm_page_remove(vm_page_t m)
690 {
691         vm_object_t object;
692         vm_page_t root;
693
694         if ((object = m->object) == NULL)
695                 return;
696         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
697         if (m->oflags & VPO_BUSY) {
698                 m->oflags &= ~VPO_BUSY;
699                 vm_page_flash(m);
700         }
701         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
702
703         /*
704          * Now remove from the object's list of backed pages.
705          */
706         if (m != object->root)
707                 vm_page_splay(m->pindex, object->root);
708         if (m->left == NULL)
709                 root = m->right;
710         else {
711                 root = vm_page_splay(m->pindex, m->left);
712                 root->right = m->right;
713         }
714         object->root = root;
715         TAILQ_REMOVE(&object->memq, m, listq);
716
717         /*
718          * And show that the object has one fewer resident page.
719          */
720         object->resident_page_count--;
721         object->generation++;
722         /*
723          * The vnode may now be recycled.
724          */
725         if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
726                 vdrop((struct vnode *)object->handle);
727
728         m->object = NULL;
729 }
730
731 /*
732  *      vm_page_lookup:
733  *
734  *      Returns the page associated with the object/offset
735  *      pair specified; if none is found, NULL is returned.
736  *
737  *      The object must be locked.
738  *      This routine may not block.
739  *      This is a critical path routine
740  */
741 vm_page_t
742 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
743 {
744         vm_page_t m;
745
746         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
747         if ((m = object->root) != NULL && m->pindex != pindex) {
748                 m = vm_page_splay(pindex, m);
749                 if ((object->root = m)->pindex != pindex)
750                         m = NULL;
751         }
752         return (m);
753 }
754
755 /*
756  *      vm_page_rename:
757  *
758  *      Move the given memory entry from its
759  *      current object to the specified target object/offset.
760  *
761  *      The object must be locked.
762  *      This routine may not block.
763  *
764  *      Note: swap associated with the page must be invalidated by the move.  We
765  *            have to do this for several reasons:  (1) we aren't freeing the
766  *            page, (2) we are dirtying the page, (3) the VM system is probably
767  *            moving the page from object A to B, and will then later move
768  *            the backing store from A to B and we can't have a conflict.
769  *
770  *      Note: we *always* dirty the page.  It is necessary both for the
771  *            fact that we moved it, and because we may be invalidating
772  *            swap.  If the page is on the cache, we have to deactivate it
773  *            or vm_page_dirty() will panic.  Dirty pages are not allowed
774  *            on the cache.
775  */
776 void
777 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
778 {
779
780         vm_page_remove(m);
781         vm_page_insert(m, new_object, new_pindex);
782         if (VM_PAGE_INQUEUE1(m, PQ_CACHE))
783                 vm_page_deactivate(m);
784         vm_page_dirty(m);
785 }
786
787 /*
788  *      vm_page_select_cache:
789  *
790  *      Move a page of the given color from the cache queue to the free
791  *      queue.  As pages might be found, but are not applicable, they are
792  *      deactivated.
793  *
794  *      This routine may not block.
795  */
796 vm_page_t
797 vm_page_select_cache(int color)
798 {
799         vm_object_t object;
800         vm_page_t m;
801         boolean_t was_trylocked;
802
803         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
804         while ((m = vm_pageq_find(PQ_CACHE, color, FALSE)) != NULL) {
805                 KASSERT(m->dirty == 0, ("Found dirty cache page %p", m));
806                 KASSERT(!pmap_page_is_mapped(m),
807                     ("Found mapped cache page %p", m));
808                 KASSERT((m->flags & PG_UNMANAGED) == 0,
809                     ("Found unmanaged cache page %p", m));
810                 KASSERT(m->wire_count == 0, ("Found wired cache page %p", m));
811                 if (m->hold_count == 0 && (object = m->object,
812                     (was_trylocked = VM_OBJECT_TRYLOCK(object)) ||
813                     VM_OBJECT_LOCKED(object))) {
814                         KASSERT((m->oflags & VPO_BUSY) == 0 && m->busy == 0,
815                             ("Found busy cache page %p", m));
816                         vm_page_free(m);
817                         if (was_trylocked)
818                                 VM_OBJECT_UNLOCK(object);
819                         break;
820                 }
821                 vm_page_deactivate(m);
822         }
823         return (m);
824 }
825
826 /*
827  *      vm_page_alloc:
828  *
829  *      Allocate and return a memory cell associated
830  *      with this VM object/offset pair.
831  *
832  *      page_req classes:
833  *      VM_ALLOC_NORMAL         normal process request
834  *      VM_ALLOC_SYSTEM         system *really* needs a page
835  *      VM_ALLOC_INTERRUPT      interrupt time request
836  *      VM_ALLOC_ZERO           zero page
837  *
838  *      This routine may not block.
839  *
840  *      Additional special handling is required when called from an
841  *      interrupt (VM_ALLOC_INTERRUPT).  We are not allowed to mess with
842  *      the page cache in this case.
843  */
844 vm_page_t
845 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
846 {
847         vm_page_t m = NULL;
848         int color, flags, page_req;
849
850         page_req = req & VM_ALLOC_CLASS_MASK;
851         KASSERT(curthread->td_intr_nesting_level == 0 ||
852             page_req == VM_ALLOC_INTERRUPT,
853             ("vm_page_alloc(NORMAL|SYSTEM) in interrupt context"));
854
855         if ((req & VM_ALLOC_NOOBJ) == 0) {
856                 KASSERT(object != NULL,
857                     ("vm_page_alloc: NULL object."));
858                 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
859                 color = (pindex + object->pg_color) & PQ_COLORMASK;
860         } else
861                 color = pindex & PQ_COLORMASK;
862
863         /*
864          * The pager is allowed to eat deeper into the free page list.
865          */
866         if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT)) {
867                 page_req = VM_ALLOC_SYSTEM;
868         };
869
870 loop:
871         mtx_lock(&vm_page_queue_free_mtx);
872         if (cnt.v_free_count > cnt.v_free_reserved ||
873             (page_req == VM_ALLOC_SYSTEM && 
874              cnt.v_cache_count == 0 && 
875              cnt.v_free_count > cnt.v_interrupt_free_min) ||
876             (page_req == VM_ALLOC_INTERRUPT && cnt.v_free_count > 0)) {
877                 /*
878                  * Allocate from the free queue if the number of free pages
879                  * exceeds the minimum for the request class.
880                  */
881                 m = vm_pageq_find(PQ_FREE, color, (req & VM_ALLOC_ZERO) != 0);
882         } else if (page_req != VM_ALLOC_INTERRUPT) {
883                 mtx_unlock(&vm_page_queue_free_mtx);
884                 /*
885                  * Allocatable from cache (non-interrupt only).  On success,
886                  * we must free the page and try again, thus ensuring that
887                  * cnt.v_*_free_min counters are replenished.
888                  */
889                 vm_page_lock_queues();
890                 if ((m = vm_page_select_cache(color)) == NULL) {
891                         KASSERT(cnt.v_cache_count == 0,
892                             ("vm_page_alloc: cache queue is missing %d pages",
893                             cnt.v_cache_count));
894                         vm_page_unlock_queues();
895                         atomic_add_int(&vm_pageout_deficit, 1);
896                         pagedaemon_wakeup();
897
898                         if (page_req != VM_ALLOC_SYSTEM) 
899                                 return (NULL);
900
901                         mtx_lock(&vm_page_queue_free_mtx);
902                         if (cnt.v_free_count <= cnt.v_interrupt_free_min) {
903                                 mtx_unlock(&vm_page_queue_free_mtx);
904                                 return (NULL);
905                         }
906                         m = vm_pageq_find(PQ_FREE, color, (req & VM_ALLOC_ZERO) != 0);
907                 } else {
908                         vm_page_unlock_queues();
909                         goto loop;
910                 }
911         } else {
912                 /*
913                  * Not allocatable from cache from interrupt, give up.
914                  */
915                 mtx_unlock(&vm_page_queue_free_mtx);
916                 atomic_add_int(&vm_pageout_deficit, 1);
917                 pagedaemon_wakeup();
918                 return (NULL);
919         }
920
921         /*
922          *  At this point we had better have found a good page.
923          */
924
925         KASSERT(
926             m != NULL,
927             ("vm_page_alloc(): missing page on free queue")
928         );
929
930         /*
931          * Remove from free queue
932          */
933         vm_pageq_remove_nowakeup(m);
934
935         /*
936          * Initialize structure.  Only the PG_ZERO flag is inherited.
937          */
938         flags = 0;
939         if (m->flags & PG_ZERO) {
940                 vm_page_zero_count--;
941                 if (req & VM_ALLOC_ZERO)
942                         flags = PG_ZERO;
943         }
944         m->flags = flags;
945         if (req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ))
946                 m->oflags = 0;
947         else
948                 m->oflags = VPO_BUSY;
949         if (req & VM_ALLOC_WIRED) {
950                 atomic_add_int(&cnt.v_wire_count, 1);
951                 m->wire_count = 1;
952         } else
953                 m->wire_count = 0;
954         m->hold_count = 0;
955         m->act_count = 0;
956         m->busy = 0;
957         m->valid = 0;
958         KASSERT(m->dirty == 0, ("vm_page_alloc: free/cache page %p was dirty", m));
959         mtx_unlock(&vm_page_queue_free_mtx);
960
961         if ((req & VM_ALLOC_NOOBJ) == 0)
962                 vm_page_insert(m, object, pindex);
963         else
964                 m->pindex = pindex;
965
966         /*
967          * Don't wakeup too often - wakeup the pageout daemon when
968          * we would be nearly out of memory.
969          */
970         if (vm_paging_needed())
971                 pagedaemon_wakeup();
972
973         return (m);
974 }
975
976 /*
977  *      vm_wait:        (also see VM_WAIT macro)
978  *
979  *      Block until free pages are available for allocation
980  *      - Called in various places before memory allocations.
981  */
982 void
983 vm_wait(void)
984 {
985
986         mtx_lock(&vm_page_queue_free_mtx);
987         if (curproc == pageproc) {
988                 vm_pageout_pages_needed = 1;
989                 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
990                     PDROP | PSWP, "VMWait", 0);
991         } else {
992                 if (!vm_pages_needed) {
993                         vm_pages_needed = 1;
994                         wakeup(&vm_pages_needed);
995                 }
996                 msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
997                     "vmwait", 0);
998         }
999 }
1000
1001 /*
1002  *      vm_waitpfault:  (also see VM_WAITPFAULT macro)
1003  *
1004  *      Block until free pages are available for allocation
1005  *      - Called only in vm_fault so that processes page faulting
1006  *        can be easily tracked.
1007  *      - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
1008  *        processes will be able to grab memory first.  Do not change
1009  *        this balance without careful testing first.
1010  */
1011 void
1012 vm_waitpfault(void)
1013 {
1014
1015         mtx_lock(&vm_page_queue_free_mtx);
1016         if (!vm_pages_needed) {
1017                 vm_pages_needed = 1;
1018                 wakeup(&vm_pages_needed);
1019         }
1020         msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
1021             "pfault", 0);
1022 }
1023
1024 /*
1025  *      vm_page_activate:
1026  *
1027  *      Put the specified page on the active list (if appropriate).
1028  *      Ensure that act_count is at least ACT_INIT but do not otherwise
1029  *      mess with it.
1030  *
1031  *      The page queues must be locked.
1032  *      This routine may not block.
1033  */
1034 void
1035 vm_page_activate(vm_page_t m)
1036 {
1037
1038         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1039         if (VM_PAGE_GETKNOWNQUEUE2(m) != PQ_ACTIVE) {
1040                 if (VM_PAGE_INQUEUE1(m, PQ_CACHE))
1041                         cnt.v_reactivated++;
1042                 vm_pageq_remove(m);
1043                 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1044                         if (m->act_count < ACT_INIT)
1045                                 m->act_count = ACT_INIT;
1046                         vm_pageq_enqueue(PQ_ACTIVE, m);
1047                 }
1048         } else {
1049                 if (m->act_count < ACT_INIT)
1050                         m->act_count = ACT_INIT;
1051         }
1052 }
1053
1054 /*
1055  *      vm_page_free_wakeup:
1056  *
1057  *      Helper routine for vm_page_free_toq() and vm_page_cache().  This
1058  *      routine is called when a page has been added to the cache or free
1059  *      queues.
1060  *
1061  *      The page queues must be locked.
1062  *      This routine may not block.
1063  */
1064 static inline void
1065 vm_page_free_wakeup(void)
1066 {
1067
1068         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1069         /*
1070          * if pageout daemon needs pages, then tell it that there are
1071          * some free.
1072          */
1073         if (vm_pageout_pages_needed &&
1074             cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
1075                 wakeup(&vm_pageout_pages_needed);
1076                 vm_pageout_pages_needed = 0;
1077         }
1078         /*
1079          * wakeup processes that are waiting on memory if we hit a
1080          * high water mark. And wakeup scheduler process if we have
1081          * lots of memory. this process will swapin processes.
1082          */
1083         if (vm_pages_needed && !vm_page_count_min()) {
1084                 vm_pages_needed = 0;
1085                 wakeup(&cnt.v_free_count);
1086         }
1087 }
1088
1089 /*
1090  *      vm_page_free_toq:
1091  *
1092  *      Returns the given page to the PQ_FREE list,
1093  *      disassociating it with any VM object.
1094  *
1095  *      Object and page must be locked prior to entry.
1096  *      This routine may not block.
1097  */
1098
1099 void
1100 vm_page_free_toq(vm_page_t m)
1101 {
1102         struct vpgqueues *pq;
1103
1104         if (VM_PAGE_GETQUEUE(m) != PQ_NONE)
1105                 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1106         KASSERT(!pmap_page_is_mapped(m),
1107             ("vm_page_free_toq: freeing mapped page %p", m));
1108         cnt.v_tfree++;
1109
1110         if (m->busy || VM_PAGE_INQUEUE1(m, PQ_FREE)) {
1111                 printf(
1112                 "vm_page_free: pindex(%lu), busy(%d), VPO_BUSY(%d), hold(%d)\n",
1113                     (u_long)m->pindex, m->busy, (m->oflags & VPO_BUSY) ? 1 : 0,
1114                     m->hold_count);
1115                 if (VM_PAGE_INQUEUE1(m, PQ_FREE))
1116                         panic("vm_page_free: freeing free page");
1117                 else
1118                         panic("vm_page_free: freeing busy page");
1119         }
1120
1121         /*
1122          * unqueue, then remove page.  Note that we cannot destroy
1123          * the page here because we do not want to call the pager's
1124          * callback routine until after we've put the page on the
1125          * appropriate free queue.
1126          */
1127         vm_pageq_remove_nowakeup(m);
1128         vm_page_remove(m);
1129
1130         /*
1131          * If fictitious remove object association and
1132          * return, otherwise delay object association removal.
1133          */
1134         if ((m->flags & PG_FICTITIOUS) != 0) {
1135                 return;
1136         }
1137
1138         m->valid = 0;
1139         vm_page_undirty(m);
1140
1141         if (m->wire_count != 0) {
1142                 if (m->wire_count > 1) {
1143                         panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx",
1144                                 m->wire_count, (long)m->pindex);
1145                 }
1146                 panic("vm_page_free: freeing wired page");
1147         }
1148         if (m->hold_count != 0) {
1149                 m->flags &= ~PG_ZERO;
1150                 vm_pageq_enqueue(PQ_HOLD, m);
1151                 return;
1152         }
1153         VM_PAGE_SETQUEUE1(m, PQ_FREE);
1154         mtx_lock(&vm_page_queue_free_mtx);
1155         pq = &vm_page_queues[VM_PAGE_GETQUEUE(m)];
1156         pq->lcnt++;
1157         ++(*pq->cnt);
1158
1159         /*
1160          * Put zero'd pages on the end ( where we look for zero'd pages
1161          * first ) and non-zerod pages at the head.
1162          */
1163         if (m->flags & PG_ZERO) {
1164                 TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
1165                 ++vm_page_zero_count;
1166         } else {
1167                 TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
1168                 vm_page_zero_idle_wakeup();
1169         }
1170         vm_page_free_wakeup();
1171         mtx_unlock(&vm_page_queue_free_mtx);
1172 }
1173
1174 /*
1175  *      vm_page_unmanage:
1176  *
1177  *      Prevent PV management from being done on the page.  The page is
1178  *      removed from the paging queues as if it were wired, and as a 
1179  *      consequence of no longer being managed the pageout daemon will not
1180  *      touch it (since there is no way to locate the pte mappings for the
1181  *      page).  madvise() calls that mess with the pmap will also no longer
1182  *      operate on the page.
1183  *
1184  *      Beyond that the page is still reasonably 'normal'.  Freeing the page
1185  *      will clear the flag.
1186  *
1187  *      This routine is used by OBJT_PHYS objects - objects using unswappable
1188  *      physical memory as backing store rather then swap-backed memory and
1189  *      will eventually be extended to support 4MB unmanaged physical 
1190  *      mappings.
1191  */
1192 void
1193 vm_page_unmanage(vm_page_t m)
1194 {
1195
1196         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1197         if ((m->flags & PG_UNMANAGED) == 0) {
1198                 if (m->wire_count == 0)
1199                         vm_pageq_remove(m);
1200         }
1201         vm_page_flag_set(m, PG_UNMANAGED);
1202 }
1203
1204 /*
1205  *      vm_page_wire:
1206  *
1207  *      Mark this page as wired down by yet
1208  *      another map, removing it from paging queues
1209  *      as necessary.
1210  *
1211  *      The page queues must be locked.
1212  *      This routine may not block.
1213  */
1214 void
1215 vm_page_wire(vm_page_t m)
1216 {
1217
1218         /*
1219          * Only bump the wire statistics if the page is not already wired,
1220          * and only unqueue the page if it is on some queue (if it is unmanaged
1221          * it is already off the queues).
1222          */
1223         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1224         if (m->flags & PG_FICTITIOUS)
1225                 return;
1226         if (m->wire_count == 0) {
1227                 if ((m->flags & PG_UNMANAGED) == 0)
1228                         vm_pageq_remove(m);
1229                 atomic_add_int(&cnt.v_wire_count, 1);
1230         }
1231         m->wire_count++;
1232         KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1233 }
1234
1235 /*
1236  *      vm_page_unwire:
1237  *
1238  *      Release one wiring of this page, potentially
1239  *      enabling it to be paged again.
1240  *
1241  *      Many pages placed on the inactive queue should actually go
1242  *      into the cache, but it is difficult to figure out which.  What
1243  *      we do instead, if the inactive target is well met, is to put
1244  *      clean pages at the head of the inactive queue instead of the tail.
1245  *      This will cause them to be moved to the cache more quickly and
1246  *      if not actively re-referenced, freed more quickly.  If we just
1247  *      stick these pages at the end of the inactive queue, heavy filesystem
1248  *      meta-data accesses can cause an unnecessary paging load on memory bound 
1249  *      processes.  This optimization causes one-time-use metadata to be
1250  *      reused more quickly.
1251  *
1252  *      BUT, if we are in a low-memory situation we have no choice but to
1253  *      put clean pages on the cache queue.
1254  *
1255  *      A number of routines use vm_page_unwire() to guarantee that the page
1256  *      will go into either the inactive or active queues, and will NEVER
1257  *      be placed in the cache - for example, just after dirtying a page.
1258  *      dirty pages in the cache are not allowed.
1259  *
1260  *      The page queues must be locked.
1261  *      This routine may not block.
1262  */
1263 void
1264 vm_page_unwire(vm_page_t m, int activate)
1265 {
1266
1267         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1268         if (m->flags & PG_FICTITIOUS)
1269                 return;
1270         if (m->wire_count > 0) {
1271                 m->wire_count--;
1272                 if (m->wire_count == 0) {
1273                         atomic_subtract_int(&cnt.v_wire_count, 1);
1274                         if (m->flags & PG_UNMANAGED) {
1275                                 ;
1276                         } else if (activate)
1277                                 vm_pageq_enqueue(PQ_ACTIVE, m);
1278                         else {
1279                                 vm_page_flag_clear(m, PG_WINATCFLS);
1280                                 vm_pageq_enqueue(PQ_INACTIVE, m);
1281                         }
1282                 }
1283         } else {
1284                 panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
1285         }
1286 }
1287
1288
1289 /*
1290  * Move the specified page to the inactive queue.  If the page has
1291  * any associated swap, the swap is deallocated.
1292  *
1293  * Normally athead is 0 resulting in LRU operation.  athead is set
1294  * to 1 if we want this page to be 'as if it were placed in the cache',
1295  * except without unmapping it from the process address space.
1296  *
1297  * This routine may not block.
1298  */
1299 static inline void
1300 _vm_page_deactivate(vm_page_t m, int athead)
1301 {
1302
1303         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1304
1305         /*
1306          * Ignore if already inactive.
1307          */
1308         if (VM_PAGE_INQUEUE2(m, PQ_INACTIVE))
1309                 return;
1310         if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1311                 if (VM_PAGE_INQUEUE1(m, PQ_CACHE))
1312                         cnt.v_reactivated++;
1313                 vm_page_flag_clear(m, PG_WINATCFLS);
1314                 vm_pageq_remove(m);
1315                 if (athead)
1316                         TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1317                 else
1318                         TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1319                 VM_PAGE_SETQUEUE2(m, PQ_INACTIVE);
1320                 vm_page_queues[PQ_INACTIVE].lcnt++;
1321                 cnt.v_inactive_count++;
1322         }
1323 }
1324
1325 void
1326 vm_page_deactivate(vm_page_t m)
1327 {
1328     _vm_page_deactivate(m, 0);
1329 }
1330
1331 /*
1332  * vm_page_try_to_cache:
1333  *
1334  * Returns 0 on failure, 1 on success
1335  */
1336 int
1337 vm_page_try_to_cache(vm_page_t m)
1338 {
1339
1340         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1341         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1342         if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1343             (m->oflags & VPO_BUSY) || (m->flags & PG_UNMANAGED)) {
1344                 return (0);
1345         }
1346         pmap_remove_all(m);
1347         if (m->dirty)
1348                 return (0);
1349         vm_page_cache(m);
1350         return (1);
1351 }
1352
1353 /*
1354  * vm_page_try_to_free()
1355  *
1356  *      Attempt to free the page.  If we cannot free it, we do nothing.
1357  *      1 is returned on success, 0 on failure.
1358  */
1359 int
1360 vm_page_try_to_free(vm_page_t m)
1361 {
1362
1363         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1364         if (m->object != NULL)
1365                 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1366         if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1367             (m->oflags & VPO_BUSY) || (m->flags & PG_UNMANAGED)) {
1368                 return (0);
1369         }
1370         pmap_remove_all(m);
1371         if (m->dirty)
1372                 return (0);
1373         vm_page_free(m);
1374         return (1);
1375 }
1376
1377 /*
1378  * vm_page_cache
1379  *
1380  * Put the specified page onto the page cache queue (if appropriate).
1381  *
1382  * This routine may not block.
1383  */
1384 void
1385 vm_page_cache(vm_page_t m)
1386 {
1387
1388         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1389         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1390         if ((m->flags & PG_UNMANAGED) || (m->oflags & VPO_BUSY) || m->busy ||
1391             m->hold_count || m->wire_count) {
1392                 printf("vm_page_cache: attempting to cache busy page\n");
1393                 return;
1394         }
1395         if (VM_PAGE_INQUEUE1(m, PQ_CACHE))
1396                 return;
1397
1398         /*
1399          * Remove all pmaps and indicate that the page is not
1400          * writeable or mapped.
1401          */
1402         pmap_remove_all(m);
1403         if (m->dirty != 0) {
1404                 panic("vm_page_cache: caching a dirty page, pindex: %ld",
1405                         (long)m->pindex);
1406         }
1407         vm_pageq_remove_nowakeup(m);
1408         vm_pageq_enqueue(PQ_CACHE + m->pc, m);
1409         mtx_lock(&vm_page_queue_free_mtx);
1410         vm_page_free_wakeup();
1411         mtx_unlock(&vm_page_queue_free_mtx);
1412 }
1413
1414 /*
1415  * vm_page_dontneed
1416  *
1417  *      Cache, deactivate, or do nothing as appropriate.  This routine
1418  *      is typically used by madvise() MADV_DONTNEED.
1419  *
1420  *      Generally speaking we want to move the page into the cache so
1421  *      it gets reused quickly.  However, this can result in a silly syndrome
1422  *      due to the page recycling too quickly.  Small objects will not be
1423  *      fully cached.  On the otherhand, if we move the page to the inactive
1424  *      queue we wind up with a problem whereby very large objects 
1425  *      unnecessarily blow away our inactive and cache queues.
1426  *
1427  *      The solution is to move the pages based on a fixed weighting.  We
1428  *      either leave them alone, deactivate them, or move them to the cache,
1429  *      where moving them to the cache has the highest weighting.
1430  *      By forcing some pages into other queues we eventually force the
1431  *      system to balance the queues, potentially recovering other unrelated
1432  *      space from active.  The idea is to not force this to happen too
1433  *      often.
1434  */
1435 void
1436 vm_page_dontneed(vm_page_t m)
1437 {
1438         static int dnweight;
1439         int dnw;
1440         int head;
1441
1442         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1443         dnw = ++dnweight;
1444
1445         /*
1446          * occassionally leave the page alone
1447          */
1448         if ((dnw & 0x01F0) == 0 ||
1449             VM_PAGE_INQUEUE2(m, PQ_INACTIVE) || 
1450             VM_PAGE_INQUEUE1(m, PQ_CACHE)
1451         ) {
1452                 if (m->act_count >= ACT_INIT)
1453                         --m->act_count;
1454                 return;
1455         }
1456
1457         if (m->dirty == 0 && pmap_is_modified(m))
1458                 vm_page_dirty(m);
1459
1460         if (m->dirty || (dnw & 0x0070) == 0) {
1461                 /*
1462                  * Deactivate the page 3 times out of 32.
1463                  */
1464                 head = 0;
1465         } else {
1466                 /*
1467                  * Cache the page 28 times out of every 32.  Note that
1468                  * the page is deactivated instead of cached, but placed
1469                  * at the head of the queue instead of the tail.
1470                  */
1471                 head = 1;
1472         }
1473         _vm_page_deactivate(m, head);
1474 }
1475
1476 /*
1477  * Grab a page, waiting until we are waken up due to the page
1478  * changing state.  We keep on waiting, if the page continues
1479  * to be in the object.  If the page doesn't exist, first allocate it
1480  * and then conditionally zero it.
1481  *
1482  * This routine may block.
1483  */
1484 vm_page_t
1485 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
1486 {
1487         vm_page_t m;
1488
1489         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1490 retrylookup:
1491         if ((m = vm_page_lookup(object, pindex)) != NULL) {
1492                 if (vm_page_sleep_if_busy(m, TRUE, "pgrbwt")) {
1493                         if ((allocflags & VM_ALLOC_RETRY) == 0)
1494                                 return (NULL);
1495                         goto retrylookup;
1496                 } else {
1497                         if ((allocflags & VM_ALLOC_WIRED) != 0) {
1498                                 vm_page_lock_queues();
1499                                 vm_page_wire(m);
1500                                 vm_page_unlock_queues();
1501                         }
1502                         if ((allocflags & VM_ALLOC_NOBUSY) == 0)
1503                                 vm_page_busy(m);
1504                         return (m);
1505                 }
1506         }
1507         m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
1508         if (m == NULL) {
1509                 VM_OBJECT_UNLOCK(object);
1510                 VM_WAIT;
1511                 VM_OBJECT_LOCK(object);
1512                 if ((allocflags & VM_ALLOC_RETRY) == 0)
1513                         return (NULL);
1514                 goto retrylookup;
1515         }
1516         if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
1517                 pmap_zero_page(m);
1518         return (m);
1519 }
1520
1521 /*
1522  * Mapping function for valid bits or for dirty bits in
1523  * a page.  May not block.
1524  *
1525  * Inputs are required to range within a page.
1526  */
1527 inline int
1528 vm_page_bits(int base, int size)
1529 {
1530         int first_bit;
1531         int last_bit;
1532
1533         KASSERT(
1534             base + size <= PAGE_SIZE,
1535             ("vm_page_bits: illegal base/size %d/%d", base, size)
1536         );
1537
1538         if (size == 0)          /* handle degenerate case */
1539                 return (0);
1540
1541         first_bit = base >> DEV_BSHIFT;
1542         last_bit = (base + size - 1) >> DEV_BSHIFT;
1543
1544         return ((2 << last_bit) - (1 << first_bit));
1545 }
1546
1547 /*
1548  *      vm_page_set_validclean:
1549  *
1550  *      Sets portions of a page valid and clean.  The arguments are expected
1551  *      to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
1552  *      of any partial chunks touched by the range.  The invalid portion of
1553  *      such chunks will be zero'd.
1554  *
1555  *      This routine may not block.
1556  *
1557  *      (base + size) must be less then or equal to PAGE_SIZE.
1558  */
1559 void
1560 vm_page_set_validclean(vm_page_t m, int base, int size)
1561 {
1562         int pagebits;
1563         int frag;
1564         int endoff;
1565
1566         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1567         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1568         if (size == 0)  /* handle degenerate case */
1569                 return;
1570
1571         /*
1572          * If the base is not DEV_BSIZE aligned and the valid
1573          * bit is clear, we have to zero out a portion of the
1574          * first block.
1575          */
1576         if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
1577             (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
1578                 pmap_zero_page_area(m, frag, base - frag);
1579
1580         /*
1581          * If the ending offset is not DEV_BSIZE aligned and the 
1582          * valid bit is clear, we have to zero out a portion of
1583          * the last block.
1584          */
1585         endoff = base + size;
1586         if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
1587             (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
1588                 pmap_zero_page_area(m, endoff,
1589                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
1590
1591         /*
1592          * Set valid, clear dirty bits.  If validating the entire
1593          * page we can safely clear the pmap modify bit.  We also
1594          * use this opportunity to clear the VPO_NOSYNC flag.  If a process
1595          * takes a write fault on a MAP_NOSYNC memory area the flag will
1596          * be set again.
1597          *
1598          * We set valid bits inclusive of any overlap, but we can only
1599          * clear dirty bits for DEV_BSIZE chunks that are fully within
1600          * the range.
1601          */
1602         pagebits = vm_page_bits(base, size);
1603         m->valid |= pagebits;
1604 #if 0   /* NOT YET */
1605         if ((frag = base & (DEV_BSIZE - 1)) != 0) {
1606                 frag = DEV_BSIZE - frag;
1607                 base += frag;
1608                 size -= frag;
1609                 if (size < 0)
1610                         size = 0;
1611         }
1612         pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
1613 #endif
1614         m->dirty &= ~pagebits;
1615         if (base == 0 && size == PAGE_SIZE) {
1616                 pmap_clear_modify(m);
1617                 m->oflags &= ~VPO_NOSYNC;
1618         }
1619 }
1620
1621 void
1622 vm_page_clear_dirty(vm_page_t m, int base, int size)
1623 {
1624
1625         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1626         m->dirty &= ~vm_page_bits(base, size);
1627 }
1628
1629 /*
1630  *      vm_page_set_invalid:
1631  *
1632  *      Invalidates DEV_BSIZE'd chunks within a page.  Both the
1633  *      valid and dirty bits for the effected areas are cleared.
1634  *
1635  *      May not block.
1636  */
1637 void
1638 vm_page_set_invalid(vm_page_t m, int base, int size)
1639 {
1640         int bits;
1641
1642         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1643         bits = vm_page_bits(base, size);
1644         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1645         if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
1646                 pmap_remove_all(m);
1647         m->valid &= ~bits;
1648         m->dirty &= ~bits;
1649         m->object->generation++;
1650 }
1651
1652 /*
1653  * vm_page_zero_invalid()
1654  *
1655  *      The kernel assumes that the invalid portions of a page contain 
1656  *      garbage, but such pages can be mapped into memory by user code.
1657  *      When this occurs, we must zero out the non-valid portions of the
1658  *      page so user code sees what it expects.
1659  *
1660  *      Pages are most often semi-valid when the end of a file is mapped 
1661  *      into memory and the file's size is not page aligned.
1662  */
1663 void
1664 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
1665 {
1666         int b;
1667         int i;
1668
1669         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1670         /*
1671          * Scan the valid bits looking for invalid sections that
1672          * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
1673          * valid bit may be set ) have already been zerod by
1674          * vm_page_set_validclean().
1675          */
1676         for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
1677                 if (i == (PAGE_SIZE / DEV_BSIZE) || 
1678                     (m->valid & (1 << i))
1679                 ) {
1680                         if (i > b) {
1681                                 pmap_zero_page_area(m, 
1682                                     b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
1683                         }
1684                         b = i + 1;
1685                 }
1686         }
1687
1688         /*
1689          * setvalid is TRUE when we can safely set the zero'd areas
1690          * as being valid.  We can do this if there are no cache consistancy
1691          * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
1692          */
1693         if (setvalid)
1694                 m->valid = VM_PAGE_BITS_ALL;
1695 }
1696
1697 /*
1698  *      vm_page_is_valid:
1699  *
1700  *      Is (partial) page valid?  Note that the case where size == 0
1701  *      will return FALSE in the degenerate case where the page is
1702  *      entirely invalid, and TRUE otherwise.
1703  *
1704  *      May not block.
1705  */
1706 int
1707 vm_page_is_valid(vm_page_t m, int base, int size)
1708 {
1709         int bits = vm_page_bits(base, size);
1710
1711         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1712         if (m->valid && ((m->valid & bits) == bits))
1713                 return 1;
1714         else
1715                 return 0;
1716 }
1717
1718 /*
1719  * update dirty bits from pmap/mmu.  May not block.
1720  */
1721 void
1722 vm_page_test_dirty(vm_page_t m)
1723 {
1724         if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
1725                 vm_page_dirty(m);
1726         }
1727 }
1728
1729 int so_zerocp_fullpage = 0;
1730
1731 void
1732 vm_page_cowfault(vm_page_t m)
1733 {
1734         vm_page_t mnew;
1735         vm_object_t object;
1736         vm_pindex_t pindex;
1737
1738         object = m->object;
1739         pindex = m->pindex;
1740
1741  retry_alloc:
1742         pmap_remove_all(m);
1743         vm_page_remove(m);
1744         mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY);
1745         if (mnew == NULL) {
1746                 vm_page_insert(m, object, pindex);
1747                 vm_page_unlock_queues();
1748                 VM_OBJECT_UNLOCK(object);
1749                 VM_WAIT;
1750                 VM_OBJECT_LOCK(object);
1751                 vm_page_lock_queues();
1752                 goto retry_alloc;
1753         }
1754
1755         if (m->cow == 0) {
1756                 /* 
1757                  * check to see if we raced with an xmit complete when 
1758                  * waiting to allocate a page.  If so, put things back 
1759                  * the way they were 
1760                  */
1761                 vm_page_free(mnew);
1762                 vm_page_insert(m, object, pindex);
1763         } else { /* clear COW & copy page */
1764                 if (!so_zerocp_fullpage)
1765                         pmap_copy_page(m, mnew);
1766                 mnew->valid = VM_PAGE_BITS_ALL;
1767                 vm_page_dirty(mnew);
1768                 mnew->wire_count = m->wire_count - m->cow;
1769                 m->wire_count = m->cow;
1770         }
1771 }
1772
1773 void 
1774 vm_page_cowclear(vm_page_t m)
1775 {
1776
1777         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1778         if (m->cow) {
1779                 m->cow--;
1780                 /* 
1781                  * let vm_fault add back write permission  lazily
1782                  */
1783         } 
1784         /*
1785          *  sf_buf_free() will free the page, so we needn't do it here
1786          */ 
1787 }
1788
1789 void
1790 vm_page_cowsetup(vm_page_t m)
1791 {
1792
1793         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1794         m->cow++;
1795         pmap_remove_write(m);
1796 }
1797
1798 #include "opt_ddb.h"
1799 #ifdef DDB
1800 #include <sys/kernel.h>
1801
1802 #include <ddb/ddb.h>
1803
1804 DB_SHOW_COMMAND(page, vm_page_print_page_info)
1805 {
1806         db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
1807         db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
1808         db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
1809         db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
1810         db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
1811         db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
1812         db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
1813         db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
1814         db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
1815         db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
1816 }
1817
1818 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
1819 {
1820         int i;
1821         db_printf("PQ_FREE:");
1822         for (i = 0; i < PQ_NUMCOLORS; i++) {
1823                 db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
1824         }
1825         db_printf("\n");
1826                 
1827         db_printf("PQ_CACHE:");
1828         for (i = 0; i < PQ_NUMCOLORS; i++) {
1829                 db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
1830         }
1831         db_printf("\n");
1832
1833         db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
1834                 vm_page_queues[PQ_ACTIVE].lcnt,
1835                 vm_page_queues[PQ_INACTIVE].lcnt);
1836 }
1837 #endif /* DDB */