]> CyberLeo.Net >> Repos - FreeBSD/releng/8.2.git/blob - sys/vm/vm_page.c
Adjust __FreeBSD_version for the 8.2 release.
[FreeBSD/releng/8.2.git] / sys / vm / vm_page.c
1 /*-
2  * Copyright (c) 1991 Regents of the University of California.
3  * All rights reserved.
4  * Copyright (c) 1998 Matthew Dillon.  All Rights Reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * The Mach Operating System project at Carnegie-Mellon University.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      from: @(#)vm_page.c     7.4 (Berkeley) 5/7/91
34  */
35
36 /*-
37  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38  * All rights reserved.
39  *
40  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41  *
42  * Permission to use, copy, modify and distribute this software and
43  * its documentation is hereby granted, provided that both the copyright
44  * notice and this permission notice appear in all copies of the
45  * software, derivative works or modified versions, and any portions
46  * thereof, and that both notices appear in supporting documentation.
47  *
48  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51  *
52  * Carnegie Mellon requests users of this software to return to
53  *
54  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55  *  School of Computer Science
56  *  Carnegie Mellon University
57  *  Pittsburgh PA 15213-3890
58  *
59  * any improvements or extensions that they make and grant Carnegie the
60  * rights to redistribute these changes.
61  */
62
63 /*
64  *                      GENERAL RULES ON VM_PAGE MANIPULATION
65  *
66  *      - a pageq mutex is required when adding or removing a page from a
67  *        page queue (vm_page_queue[]), regardless of other mutexes or the
68  *        busy state of a page.
69  *
70  *      - a hash chain mutex is required when associating or disassociating
71  *        a page from the VM PAGE CACHE hash table (vm_page_buckets),
72  *        regardless of other mutexes or the busy state of a page.
73  *
74  *      - either a hash chain mutex OR a busied page is required in order
75  *        to modify the page flags.  A hash chain mutex must be obtained in
76  *        order to busy a page.  A page's flags cannot be modified by a
77  *        hash chain mutex if the page is marked busy.
78  *
79  *      - The object memq mutex is held when inserting or removing
80  *        pages from an object (vm_page_insert() or vm_page_remove()).  This
81  *        is different from the object's main mutex.
82  *
83  *      Generally speaking, you have to be aware of side effects when running
84  *      vm_page ops.  A vm_page_lookup() will return with the hash chain
85  *      locked, whether it was able to lookup the page or not.  vm_page_free(),
86  *      vm_page_cache(), vm_page_activate(), and a number of other routines
87  *      will release the hash chain mutex for you.  Intermediate manipulation
88  *      routines such as vm_page_flag_set() expect the hash chain to be held
89  *      on entry and the hash chain will remain held on return.
90  *
91  *      pageq scanning can only occur with the pageq in question locked.
92  *      We have a known bottleneck with the active queue, but the cache
93  *      and free queues are actually arrays already. 
94  */
95
96 /*
97  *      Resident memory management module.
98  */
99
100 #include <sys/cdefs.h>
101 __FBSDID("$FreeBSD$");
102
103 #include "opt_vm.h"
104
105 #include <sys/param.h>
106 #include <sys/systm.h>
107 #include <sys/lock.h>
108 #include <sys/kernel.h>
109 #include <sys/limits.h>
110 #include <sys/malloc.h>
111 #include <sys/mutex.h>
112 #include <sys/proc.h>
113 #include <sys/sysctl.h>
114 #include <sys/vmmeter.h>
115 #include <sys/vnode.h>
116
117 #include <vm/vm.h>
118 #include <vm/vm_param.h>
119 #include <vm/vm_kern.h>
120 #include <vm/vm_object.h>
121 #include <vm/vm_page.h>
122 #include <vm/vm_pageout.h>
123 #include <vm/vm_pager.h>
124 #include <vm/vm_phys.h>
125 #include <vm/vm_reserv.h>
126 #include <vm/vm_extern.h>
127 #include <vm/uma.h>
128 #include <vm/uma_int.h>
129
130 #include <machine/md_var.h>
131
132 /*
133  *      Associated with page of user-allocatable memory is a
134  *      page structure.
135  */
136
137 struct vpgqueues vm_page_queues[PQ_COUNT];
138 struct mtx vm_page_queue_mtx;
139 struct mtx vm_page_queue_free_mtx;
140
141 vm_page_t vm_page_array = 0;
142 int vm_page_array_size = 0;
143 long first_page = 0;
144 int vm_page_zero_count = 0;
145
146 static int boot_pages = UMA_BOOT_PAGES;
147 TUNABLE_INT("vm.boot_pages", &boot_pages);
148 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RD, &boot_pages, 0,
149         "number of pages allocated for bootstrapping the VM system");
150
151 static void vm_page_enqueue(int queue, vm_page_t m);
152
153 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
154 #if PAGE_SIZE == 32768
155 #ifdef CTASSERT
156 CTASSERT(sizeof(u_long) >= 8);
157 #endif
158 #endif
159
160 /*
161  *      vm_set_page_size:
162  *
163  *      Sets the page size, perhaps based upon the memory
164  *      size.  Must be called before any use of page-size
165  *      dependent functions.
166  */
167 void
168 vm_set_page_size(void)
169 {
170         if (cnt.v_page_size == 0)
171                 cnt.v_page_size = PAGE_SIZE;
172         if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
173                 panic("vm_set_page_size: page size not a power of two");
174 }
175
176 /*
177  *      vm_page_blacklist_lookup:
178  *
179  *      See if a physical address in this page has been listed
180  *      in the blacklist tunable.  Entries in the tunable are
181  *      separated by spaces or commas.  If an invalid integer is
182  *      encountered then the rest of the string is skipped.
183  */
184 static int
185 vm_page_blacklist_lookup(char *list, vm_paddr_t pa)
186 {
187         vm_paddr_t bad;
188         char *cp, *pos;
189
190         for (pos = list; *pos != '\0'; pos = cp) {
191                 bad = strtoq(pos, &cp, 0);
192                 if (*cp != '\0') {
193                         if (*cp == ' ' || *cp == ',') {
194                                 cp++;
195                                 if (cp == pos)
196                                         continue;
197                         } else
198                                 break;
199                 }
200                 if (pa == trunc_page(bad))
201                         return (1);
202         }
203         return (0);
204 }
205
206 /*
207  *      vm_page_startup:
208  *
209  *      Initializes the resident memory module.
210  *
211  *      Allocates memory for the page cells, and
212  *      for the object/offset-to-page hash table headers.
213  *      Each page cell is initialized and placed on the free list.
214  */
215 vm_offset_t
216 vm_page_startup(vm_offset_t vaddr)
217 {
218         vm_offset_t mapped;
219         vm_paddr_t page_range;
220         vm_paddr_t new_end;
221         int i;
222         vm_paddr_t pa;
223         int nblocks;
224         vm_paddr_t last_pa;
225         char *list;
226
227         /* the biggest memory array is the second group of pages */
228         vm_paddr_t end;
229         vm_paddr_t biggestsize;
230         vm_paddr_t low_water, high_water;
231         int biggestone;
232
233         biggestsize = 0;
234         biggestone = 0;
235         nblocks = 0;
236         vaddr = round_page(vaddr);
237
238         for (i = 0; phys_avail[i + 1]; i += 2) {
239                 phys_avail[i] = round_page(phys_avail[i]);
240                 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
241         }
242
243         low_water = phys_avail[0];
244         high_water = phys_avail[1];
245
246         for (i = 0; phys_avail[i + 1]; i += 2) {
247                 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
248
249                 if (size > biggestsize) {
250                         biggestone = i;
251                         biggestsize = size;
252                 }
253                 if (phys_avail[i] < low_water)
254                         low_water = phys_avail[i];
255                 if (phys_avail[i + 1] > high_water)
256                         high_water = phys_avail[i + 1];
257                 ++nblocks;
258         }
259
260 #ifdef XEN
261         low_water = 0;
262 #endif  
263
264         end = phys_avail[biggestone+1];
265
266         /*
267          * Initialize the locks.
268          */
269         mtx_init(&vm_page_queue_mtx, "vm page queue mutex", NULL, MTX_DEF |
270             MTX_RECURSE);
271         mtx_init(&vm_page_queue_free_mtx, "vm page queue free mutex", NULL,
272             MTX_DEF);
273
274         /*
275          * Initialize the queue headers for the hold queue, the active queue,
276          * and the inactive queue.
277          */
278         for (i = 0; i < PQ_COUNT; i++)
279                 TAILQ_INIT(&vm_page_queues[i].pl);
280         vm_page_queues[PQ_INACTIVE].cnt = &cnt.v_inactive_count;
281         vm_page_queues[PQ_ACTIVE].cnt = &cnt.v_active_count;
282         vm_page_queues[PQ_HOLD].cnt = &cnt.v_active_count;
283
284         /*
285          * Allocate memory for use when boot strapping the kernel memory
286          * allocator.
287          */
288         new_end = end - (boot_pages * UMA_SLAB_SIZE);
289         new_end = trunc_page(new_end);
290         mapped = pmap_map(&vaddr, new_end, end,
291             VM_PROT_READ | VM_PROT_WRITE);
292         bzero((void *)mapped, end - new_end);
293         uma_startup((void *)mapped, boot_pages);
294
295 #if defined(__amd64__) || defined(__i386__) || defined(__arm__) || \
296     defined(__mips__)
297         /*
298          * Allocate a bitmap to indicate that a random physical page
299          * needs to be included in a minidump.
300          *
301          * The amd64 port needs this to indicate which direct map pages
302          * need to be dumped, via calls to dump_add_page()/dump_drop_page().
303          *
304          * However, i386 still needs this workspace internally within the
305          * minidump code.  In theory, they are not needed on i386, but are
306          * included should the sf_buf code decide to use them.
307          */
308         page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE;
309         vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
310         new_end -= vm_page_dump_size;
311         vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
312             new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
313         bzero((void *)vm_page_dump, vm_page_dump_size);
314 #endif
315         /*
316          * Compute the number of pages of memory that will be available for
317          * use (taking into account the overhead of a page structure per
318          * page).
319          */
320         first_page = low_water / PAGE_SIZE;
321 #ifdef VM_PHYSSEG_SPARSE
322         page_range = 0;
323         for (i = 0; phys_avail[i + 1] != 0; i += 2)
324                 page_range += atop(phys_avail[i + 1] - phys_avail[i]);
325 #elif defined(VM_PHYSSEG_DENSE)
326         page_range = high_water / PAGE_SIZE - first_page;
327 #else
328 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
329 #endif
330         end = new_end;
331
332         /*
333          * Reserve an unmapped guard page to trap access to vm_page_array[-1].
334          */
335         vaddr += PAGE_SIZE;
336
337         /*
338          * Initialize the mem entry structures now, and put them in the free
339          * queue.
340          */
341         new_end = trunc_page(end - page_range * sizeof(struct vm_page));
342         mapped = pmap_map(&vaddr, new_end, end,
343             VM_PROT_READ | VM_PROT_WRITE);
344         vm_page_array = (vm_page_t) mapped;
345 #if VM_NRESERVLEVEL > 0
346         /*
347          * Allocate memory for the reservation management system's data
348          * structures.
349          */
350         new_end = vm_reserv_startup(&vaddr, new_end, high_water);
351 #endif
352 #ifdef __amd64__
353         /*
354          * pmap_map on amd64 comes out of the direct-map, not kvm like i386,
355          * so the pages must be tracked for a crashdump to include this data.
356          * This includes the vm_page_array and the early UMA bootstrap pages.
357          */
358         for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
359                 dump_add_page(pa);
360 #endif  
361         phys_avail[biggestone + 1] = new_end;
362
363         /*
364          * Clear all of the page structures
365          */
366         bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
367         for (i = 0; i < page_range; i++)
368                 vm_page_array[i].order = VM_NFREEORDER;
369         vm_page_array_size = page_range;
370
371         /*
372          * Initialize the physical memory allocator.
373          */
374         vm_phys_init();
375
376         /*
377          * Add every available physical page that is not blacklisted to
378          * the free lists.
379          */
380         cnt.v_page_count = 0;
381         cnt.v_free_count = 0;
382         list = getenv("vm.blacklist");
383         for (i = 0; phys_avail[i + 1] != 0; i += 2) {
384                 pa = phys_avail[i];
385                 last_pa = phys_avail[i + 1];
386                 while (pa < last_pa) {
387                         if (list != NULL &&
388                             vm_page_blacklist_lookup(list, pa))
389                                 printf("Skipping page with pa 0x%jx\n",
390                                     (uintmax_t)pa);
391                         else
392                                 vm_phys_add_page(pa);
393                         pa += PAGE_SIZE;
394                 }
395         }
396         freeenv(list);
397 #if VM_NRESERVLEVEL > 0
398         /*
399          * Initialize the reservation management system.
400          */
401         vm_reserv_init();
402 #endif
403         return (vaddr);
404 }
405
406 void
407 vm_page_flag_set(vm_page_t m, unsigned short bits)
408 {
409
410         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
411         m->flags |= bits;
412
413
414 void
415 vm_page_flag_clear(vm_page_t m, unsigned short bits)
416 {
417
418         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
419         m->flags &= ~bits;
420 }
421
422 void
423 vm_page_busy(vm_page_t m)
424 {
425
426         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
427         KASSERT((m->oflags & VPO_BUSY) == 0,
428             ("vm_page_busy: page already busy!!!"));
429         m->oflags |= VPO_BUSY;
430 }
431
432 /*
433  *      vm_page_flash:
434  *
435  *      wakeup anyone waiting for the page.
436  */
437 void
438 vm_page_flash(vm_page_t m)
439 {
440
441         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
442         if (m->oflags & VPO_WANTED) {
443                 m->oflags &= ~VPO_WANTED;
444                 wakeup(m);
445         }
446 }
447
448 /*
449  *      vm_page_wakeup:
450  *
451  *      clear the VPO_BUSY flag and wakeup anyone waiting for the
452  *      page.
453  *
454  */
455 void
456 vm_page_wakeup(vm_page_t m)
457 {
458
459         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
460         KASSERT(m->oflags & VPO_BUSY, ("vm_page_wakeup: page not busy!!!"));
461         m->oflags &= ~VPO_BUSY;
462         vm_page_flash(m);
463 }
464
465 void
466 vm_page_io_start(vm_page_t m)
467 {
468
469         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
470         m->busy++;
471 }
472
473 void
474 vm_page_io_finish(vm_page_t m)
475 {
476
477         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
478         m->busy--;
479         if (m->busy == 0)
480                 vm_page_flash(m);
481 }
482
483 /*
484  * Keep page from being freed by the page daemon
485  * much of the same effect as wiring, except much lower
486  * overhead and should be used only for *very* temporary
487  * holding ("wiring").
488  */
489 void
490 vm_page_hold(vm_page_t mem)
491 {
492
493         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
494         mem->hold_count++;
495 }
496
497 void
498 vm_page_unhold(vm_page_t mem)
499 {
500
501         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
502         --mem->hold_count;
503         KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
504         if (mem->hold_count == 0 && VM_PAGE_INQUEUE2(mem, PQ_HOLD))
505                 vm_page_free_toq(mem);
506 }
507
508 /*
509  *      vm_page_free:
510  *
511  *      Free a page.
512  */
513 void
514 vm_page_free(vm_page_t m)
515 {
516
517         m->flags &= ~PG_ZERO;
518         vm_page_free_toq(m);
519 }
520
521 /*
522  *      vm_page_free_zero:
523  *
524  *      Free a page to the zerod-pages queue
525  */
526 void
527 vm_page_free_zero(vm_page_t m)
528 {
529
530         m->flags |= PG_ZERO;
531         vm_page_free_toq(m);
532 }
533
534 /*
535  *      vm_page_sleep:
536  *
537  *      Sleep and release the page queues lock.
538  *
539  *      The object containing the given page must be locked.
540  */
541 void
542 vm_page_sleep(vm_page_t m, const char *msg)
543 {
544
545         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
546         if (!mtx_owned(&vm_page_queue_mtx))
547                 vm_page_lock_queues();
548         vm_page_flag_set(m, PG_REFERENCED);
549         vm_page_unlock_queues();
550
551         /*
552          * It's possible that while we sleep, the page will get
553          * unbusied and freed.  If we are holding the object
554          * lock, we will assume we hold a reference to the object
555          * such that even if m->object changes, we can re-lock
556          * it.
557          */
558         m->oflags |= VPO_WANTED;
559         msleep(m, VM_OBJECT_MTX(m->object), PVM, msg, 0);
560 }
561
562 /*
563  *      vm_page_dirty:
564  *
565  *      make page all dirty
566  */
567 void
568 vm_page_dirty(vm_page_t m)
569 {
570
571         KASSERT((m->flags & PG_CACHED) == 0,
572             ("vm_page_dirty: page in cache!"));
573         KASSERT(!VM_PAGE_IS_FREE(m),
574             ("vm_page_dirty: page is free!"));
575         KASSERT(m->valid == VM_PAGE_BITS_ALL,
576             ("vm_page_dirty: page is invalid!"));
577         m->dirty = VM_PAGE_BITS_ALL;
578 }
579
580 /*
581  *      vm_page_splay:
582  *
583  *      Implements Sleator and Tarjan's top-down splay algorithm.  Returns
584  *      the vm_page containing the given pindex.  If, however, that
585  *      pindex is not found in the vm_object, returns a vm_page that is
586  *      adjacent to the pindex, coming before or after it.
587  */
588 vm_page_t
589 vm_page_splay(vm_pindex_t pindex, vm_page_t root)
590 {
591         struct vm_page dummy;
592         vm_page_t lefttreemax, righttreemin, y;
593
594         if (root == NULL)
595                 return (root);
596         lefttreemax = righttreemin = &dummy;
597         for (;; root = y) {
598                 if (pindex < root->pindex) {
599                         if ((y = root->left) == NULL)
600                                 break;
601                         if (pindex < y->pindex) {
602                                 /* Rotate right. */
603                                 root->left = y->right;
604                                 y->right = root;
605                                 root = y;
606                                 if ((y = root->left) == NULL)
607                                         break;
608                         }
609                         /* Link into the new root's right tree. */
610                         righttreemin->left = root;
611                         righttreemin = root;
612                 } else if (pindex > root->pindex) {
613                         if ((y = root->right) == NULL)
614                                 break;
615                         if (pindex > y->pindex) {
616                                 /* Rotate left. */
617                                 root->right = y->left;
618                                 y->left = root;
619                                 root = y;
620                                 if ((y = root->right) == NULL)
621                                         break;
622                         }
623                         /* Link into the new root's left tree. */
624                         lefttreemax->right = root;
625                         lefttreemax = root;
626                 } else
627                         break;
628         }
629         /* Assemble the new root. */
630         lefttreemax->right = root->left;
631         righttreemin->left = root->right;
632         root->left = dummy.right;
633         root->right = dummy.left;
634         return (root);
635 }
636
637 /*
638  *      vm_page_insert:         [ internal use only ]
639  *
640  *      Inserts the given mem entry into the object and object list.
641  *
642  *      The pagetables are not updated but will presumably fault the page
643  *      in if necessary, or if a kernel page the caller will at some point
644  *      enter the page into the kernel's pmap.  We are not allowed to block
645  *      here so we *can't* do this anyway.
646  *
647  *      The object and page must be locked.
648  *      This routine may not block.
649  */
650 void
651 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
652 {
653         vm_page_t root;
654
655         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
656         if (m->object != NULL)
657                 panic("vm_page_insert: page already inserted");
658
659         /*
660          * Record the object/offset pair in this page
661          */
662         m->object = object;
663         m->pindex = pindex;
664
665         /*
666          * Now link into the object's ordered list of backed pages.
667          */
668         root = object->root;
669         if (root == NULL) {
670                 m->left = NULL;
671                 m->right = NULL;
672                 TAILQ_INSERT_TAIL(&object->memq, m, listq);
673         } else {
674                 root = vm_page_splay(pindex, root);
675                 if (pindex < root->pindex) {
676                         m->left = root->left;
677                         m->right = root;
678                         root->left = NULL;
679                         TAILQ_INSERT_BEFORE(root, m, listq);
680                 } else if (pindex == root->pindex)
681                         panic("vm_page_insert: offset already allocated");
682                 else {
683                         m->right = root->right;
684                         m->left = root;
685                         root->right = NULL;
686                         TAILQ_INSERT_AFTER(&object->memq, root, m, listq);
687                 }
688         }
689         object->root = m;
690         object->generation++;
691
692         /*
693          * show that the object has one more resident page.
694          */
695         object->resident_page_count++;
696         /*
697          * Hold the vnode until the last page is released.
698          */
699         if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
700                 vhold((struct vnode *)object->handle);
701
702         /*
703          * Since we are inserting a new and possibly dirty page,
704          * update the object's OBJ_MIGHTBEDIRTY flag.
705          */
706         if (m->flags & PG_WRITEABLE)
707                 vm_object_set_writeable_dirty(object);
708 }
709
710 /*
711  *      vm_page_remove:
712  *                              NOTE: used by device pager as well -wfj
713  *
714  *      Removes the given mem entry from the object/offset-page
715  *      table and the object page list, but do not invalidate/terminate
716  *      the backing store.
717  *
718  *      The object and page must be locked.
719  *      The underlying pmap entry (if any) is NOT removed here.
720  *      This routine may not block.
721  */
722 void
723 vm_page_remove(vm_page_t m)
724 {
725         vm_object_t object;
726         vm_page_t root;
727
728         if ((object = m->object) == NULL)
729                 return;
730         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
731         if (m->oflags & VPO_BUSY) {
732                 m->oflags &= ~VPO_BUSY;
733                 vm_page_flash(m);
734         }
735         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
736
737         /*
738          * Now remove from the object's list of backed pages.
739          */
740         if (m != object->root)
741                 vm_page_splay(m->pindex, object->root);
742         if (m->left == NULL)
743                 root = m->right;
744         else {
745                 root = vm_page_splay(m->pindex, m->left);
746                 root->right = m->right;
747         }
748         object->root = root;
749         TAILQ_REMOVE(&object->memq, m, listq);
750
751         /*
752          * And show that the object has one fewer resident page.
753          */
754         object->resident_page_count--;
755         /*
756          * The vnode may now be recycled.
757          */
758         if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
759                 vdrop((struct vnode *)object->handle);
760
761         m->object = NULL;
762 }
763
764 /*
765  *      vm_page_lookup:
766  *
767  *      Returns the page associated with the object/offset
768  *      pair specified; if none is found, NULL is returned.
769  *
770  *      The object must be locked.
771  *      This routine may not block.
772  *      This is a critical path routine
773  */
774 vm_page_t
775 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
776 {
777         vm_page_t m;
778
779         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
780         if ((m = object->root) != NULL && m->pindex != pindex) {
781                 m = vm_page_splay(pindex, m);
782                 if ((object->root = m)->pindex != pindex)
783                         m = NULL;
784         }
785         return (m);
786 }
787
788 /*
789  *      vm_page_find_least:
790  *
791  *      Returns the page associated with the object with least pindex
792  *      greater than or equal to the parameter pindex, or NULL.
793  *
794  *      The object must be locked.
795  *      The routine may not block.
796  */
797 vm_page_t
798 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
799 {
800         vm_page_t m;
801
802         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
803         if ((m = TAILQ_FIRST(&object->memq)) != NULL) {
804                 if (m->pindex < pindex) {
805                         m = vm_page_splay(pindex, object->root);
806                         if ((object->root = m)->pindex < pindex)
807                                 m = TAILQ_NEXT(m, listq);
808                 }
809         }
810         return (m);
811 }
812
813 /*
814  * Returns the given page's successor (by pindex) within the object if it is
815  * resident; if none is found, NULL is returned.
816  *
817  * The object must be locked.
818  */
819 vm_page_t
820 vm_page_next(vm_page_t m)
821 {
822         vm_page_t next;
823
824         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
825         if ((next = TAILQ_NEXT(m, listq)) != NULL &&
826             next->pindex != m->pindex + 1)
827                 next = NULL;
828         return (next);
829 }
830
831 /*
832  * Returns the given page's predecessor (by pindex) within the object if it is
833  * resident; if none is found, NULL is returned.
834  *
835  * The object must be locked.
836  */
837 vm_page_t
838 vm_page_prev(vm_page_t m)
839 {
840         vm_page_t prev;
841
842         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
843         if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
844             prev->pindex != m->pindex - 1)
845                 prev = NULL;
846         return (prev);
847 }
848
849 /*
850  *      vm_page_rename:
851  *
852  *      Move the given memory entry from its
853  *      current object to the specified target object/offset.
854  *
855  *      The object must be locked.
856  *      This routine may not block.
857  *
858  *      Note: swap associated with the page must be invalidated by the move.  We
859  *            have to do this for several reasons:  (1) we aren't freeing the
860  *            page, (2) we are dirtying the page, (3) the VM system is probably
861  *            moving the page from object A to B, and will then later move
862  *            the backing store from A to B and we can't have a conflict.
863  *
864  *      Note: we *always* dirty the page.  It is necessary both for the
865  *            fact that we moved it, and because we may be invalidating
866  *            swap.  If the page is on the cache, we have to deactivate it
867  *            or vm_page_dirty() will panic.  Dirty pages are not allowed
868  *            on the cache.
869  */
870 void
871 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
872 {
873
874         vm_page_remove(m);
875         vm_page_insert(m, new_object, new_pindex);
876         vm_page_dirty(m);
877 }
878
879 /*
880  *      Convert all of the given object's cached pages that have a
881  *      pindex within the given range into free pages.  If the value
882  *      zero is given for "end", then the range's upper bound is
883  *      infinity.  If the given object is backed by a vnode and it
884  *      transitions from having one or more cached pages to none, the
885  *      vnode's hold count is reduced. 
886  */
887 void
888 vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
889 {
890         vm_page_t m, m_next;
891         boolean_t empty;
892
893         mtx_lock(&vm_page_queue_free_mtx);
894         if (__predict_false(object->cache == NULL)) {
895                 mtx_unlock(&vm_page_queue_free_mtx);
896                 return;
897         }
898         m = object->cache = vm_page_splay(start, object->cache);
899         if (m->pindex < start) {
900                 if (m->right == NULL)
901                         m = NULL;
902                 else {
903                         m_next = vm_page_splay(start, m->right);
904                         m_next->left = m;
905                         m->right = NULL;
906                         m = object->cache = m_next;
907                 }
908         }
909
910         /*
911          * At this point, "m" is either (1) a reference to the page
912          * with the least pindex that is greater than or equal to
913          * "start" or (2) NULL.
914          */
915         for (; m != NULL && (m->pindex < end || end == 0); m = m_next) {
916                 /*
917                  * Find "m"'s successor and remove "m" from the
918                  * object's cache.
919                  */
920                 if (m->right == NULL) {
921                         object->cache = m->left;
922                         m_next = NULL;
923                 } else {
924                         m_next = vm_page_splay(start, m->right);
925                         m_next->left = m->left;
926                         object->cache = m_next;
927                 }
928                 /* Convert "m" to a free page. */
929                 m->object = NULL;
930                 m->valid = 0;
931                 /* Clear PG_CACHED and set PG_FREE. */
932                 m->flags ^= PG_CACHED | PG_FREE;
933                 KASSERT((m->flags & (PG_CACHED | PG_FREE)) == PG_FREE,
934                     ("vm_page_cache_free: page %p has inconsistent flags", m));
935                 cnt.v_cache_count--;
936                 cnt.v_free_count++;
937         }
938         empty = object->cache == NULL;
939         mtx_unlock(&vm_page_queue_free_mtx);
940         if (object->type == OBJT_VNODE && empty)
941                 vdrop(object->handle);
942 }
943
944 /*
945  *      Returns the cached page that is associated with the given
946  *      object and offset.  If, however, none exists, returns NULL.
947  *
948  *      The free page queue must be locked.
949  */
950 static inline vm_page_t
951 vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
952 {
953         vm_page_t m;
954
955         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
956         if ((m = object->cache) != NULL && m->pindex != pindex) {
957                 m = vm_page_splay(pindex, m);
958                 if ((object->cache = m)->pindex != pindex)
959                         m = NULL;
960         }
961         return (m);
962 }
963
964 /*
965  *      Remove the given cached page from its containing object's
966  *      collection of cached pages.
967  *
968  *      The free page queue must be locked.
969  */
970 void
971 vm_page_cache_remove(vm_page_t m)
972 {
973         vm_object_t object;
974         vm_page_t root;
975
976         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
977         KASSERT((m->flags & PG_CACHED) != 0,
978             ("vm_page_cache_remove: page %p is not cached", m));
979         object = m->object;
980         if (m != object->cache) {
981                 root = vm_page_splay(m->pindex, object->cache);
982                 KASSERT(root == m,
983                     ("vm_page_cache_remove: page %p is not cached in object %p",
984                     m, object));
985         }
986         if (m->left == NULL)
987                 root = m->right;
988         else if (m->right == NULL)
989                 root = m->left;
990         else {
991                 root = vm_page_splay(m->pindex, m->left);
992                 root->right = m->right;
993         }
994         object->cache = root;
995         m->object = NULL;
996         cnt.v_cache_count--;
997 }
998
999 /*
1000  *      Transfer all of the cached pages with offset greater than or
1001  *      equal to 'offidxstart' from the original object's cache to the
1002  *      new object's cache.  However, any cached pages with offset
1003  *      greater than or equal to the new object's size are kept in the
1004  *      original object.  Initially, the new object's cache must be
1005  *      empty.  Offset 'offidxstart' in the original object must
1006  *      correspond to offset zero in the new object.
1007  *
1008  *      The new object must be locked.
1009  */
1010 void
1011 vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1012     vm_object_t new_object)
1013 {
1014         vm_page_t m, m_next;
1015
1016         /*
1017          * Insertion into an object's collection of cached pages
1018          * requires the object to be locked.  In contrast, removal does
1019          * not.
1020          */
1021         VM_OBJECT_LOCK_ASSERT(new_object, MA_OWNED);
1022         KASSERT(new_object->cache == NULL,
1023             ("vm_page_cache_transfer: object %p has cached pages",
1024             new_object));
1025         mtx_lock(&vm_page_queue_free_mtx);
1026         if ((m = orig_object->cache) != NULL) {
1027                 /*
1028                  * Transfer all of the pages with offset greater than or
1029                  * equal to 'offidxstart' from the original object's
1030                  * cache to the new object's cache.
1031                  */
1032                 m = vm_page_splay(offidxstart, m);
1033                 if (m->pindex < offidxstart) {
1034                         orig_object->cache = m;
1035                         new_object->cache = m->right;
1036                         m->right = NULL;
1037                 } else {
1038                         orig_object->cache = m->left;
1039                         new_object->cache = m;
1040                         m->left = NULL;
1041                 }
1042                 while ((m = new_object->cache) != NULL) {
1043                         if ((m->pindex - offidxstart) >= new_object->size) {
1044                                 /*
1045                                  * Return all of the cached pages with
1046                                  * offset greater than or equal to the
1047                                  * new object's size to the original
1048                                  * object's cache. 
1049                                  */
1050                                 new_object->cache = m->left;
1051                                 m->left = orig_object->cache;
1052                                 orig_object->cache = m;
1053                                 break;
1054                         }
1055                         m_next = vm_page_splay(m->pindex, m->right);
1056                         /* Update the page's object and offset. */
1057                         m->object = new_object;
1058                         m->pindex -= offidxstart;
1059                         if (m_next == NULL)
1060                                 break;
1061                         m->right = NULL;
1062                         m_next->left = m;
1063                         new_object->cache = m_next;
1064                 }
1065                 KASSERT(new_object->cache == NULL ||
1066                     new_object->type == OBJT_SWAP,
1067                     ("vm_page_cache_transfer: object %p's type is incompatible"
1068                     " with cached pages", new_object));
1069         }
1070         mtx_unlock(&vm_page_queue_free_mtx);
1071 }
1072
1073 /*
1074  *      vm_page_alloc:
1075  *
1076  *      Allocate and return a memory cell associated
1077  *      with this VM object/offset pair.
1078  *
1079  *      The caller must always specify an allocation class.
1080  *
1081  *      allocation classes:
1082  *      VM_ALLOC_NORMAL         normal process request
1083  *      VM_ALLOC_SYSTEM         system *really* needs a page
1084  *      VM_ALLOC_INTERRUPT      interrupt time request
1085  *
1086  *      optional allocation flags:
1087  *      VM_ALLOC_ZERO           prefer a zeroed page
1088  *      VM_ALLOC_WIRED          wire the allocated page
1089  *      VM_ALLOC_NOOBJ          page is not associated with a vm object
1090  *      VM_ALLOC_NOBUSY         do not set the page busy
1091  *      VM_ALLOC_IFCACHED       return page only if it is cached
1092  *      VM_ALLOC_IFNOTCACHED    return NULL, do not reactivate if the page
1093  *                              is cached
1094  *
1095  *      This routine may not sleep.
1096  */
1097 vm_page_t
1098 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1099 {
1100         struct vnode *vp = NULL;
1101         vm_object_t m_object;
1102         vm_page_t m;
1103         int flags, page_req;
1104
1105         page_req = req & VM_ALLOC_CLASS_MASK;
1106         KASSERT(curthread->td_intr_nesting_level == 0 ||
1107             page_req == VM_ALLOC_INTERRUPT,
1108             ("vm_page_alloc(NORMAL|SYSTEM) in interrupt context"));
1109
1110         if ((req & VM_ALLOC_NOOBJ) == 0) {
1111                 KASSERT(object != NULL,
1112                     ("vm_page_alloc: NULL object."));
1113                 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1114         }
1115
1116         /*
1117          * The pager is allowed to eat deeper into the free page list.
1118          */
1119         if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT)) {
1120                 page_req = VM_ALLOC_SYSTEM;
1121         };
1122
1123         mtx_lock(&vm_page_queue_free_mtx);
1124         if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1125             (page_req == VM_ALLOC_SYSTEM && 
1126             cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1127             (page_req == VM_ALLOC_INTERRUPT &&
1128             cnt.v_free_count + cnt.v_cache_count > 0)) {
1129                 /*
1130                  * Allocate from the free queue if the number of free pages
1131                  * exceeds the minimum for the request class.
1132                  */
1133                 if (object != NULL &&
1134                     (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1135                         if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1136                                 mtx_unlock(&vm_page_queue_free_mtx);
1137                                 return (NULL);
1138                         }
1139                         if (vm_phys_unfree_page(m))
1140                                 vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1141 #if VM_NRESERVLEVEL > 0
1142                         else if (!vm_reserv_reactivate_page(m))
1143 #else
1144                         else
1145 #endif
1146                                 panic("vm_page_alloc: cache page %p is missing"
1147                                     " from the free queue", m);
1148                 } else if ((req & VM_ALLOC_IFCACHED) != 0) {
1149                         mtx_unlock(&vm_page_queue_free_mtx);
1150                         return (NULL);
1151 #if VM_NRESERVLEVEL > 0
1152                 } else if (object == NULL || object->type == OBJT_DEVICE ||
1153                     object->type == OBJT_SG ||
1154                     (object->flags & OBJ_COLORED) == 0 ||
1155                     (m = vm_reserv_alloc_page(object, pindex)) == NULL) {
1156 #else
1157                 } else {
1158 #endif
1159                         m = vm_phys_alloc_pages(object != NULL ?
1160                             VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1161 #if VM_NRESERVLEVEL > 0
1162                         if (m == NULL && vm_reserv_reclaim_inactive()) {
1163                                 m = vm_phys_alloc_pages(object != NULL ?
1164                                     VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1165                                     0);
1166                         }
1167 #endif
1168                 }
1169         } else {
1170                 /*
1171                  * Not allocatable, give up.
1172                  */
1173                 mtx_unlock(&vm_page_queue_free_mtx);
1174                 atomic_add_int(&vm_pageout_deficit, 1);
1175                 pagedaemon_wakeup();
1176                 return (NULL);
1177         }
1178
1179         /*
1180          *  At this point we had better have found a good page.
1181          */
1182
1183         KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1184         KASSERT(m->queue == PQ_NONE,
1185             ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1186         KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1187         KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1188         KASSERT(m->busy == 0, ("vm_page_alloc: page %p is busy", m));
1189         KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1190         KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1191             ("vm_page_alloc: page %p has unexpected memattr %d", m,
1192             pmap_page_get_memattr(m)));
1193         if ((m->flags & PG_CACHED) != 0) {
1194                 KASSERT(m->valid != 0,
1195                     ("vm_page_alloc: cached page %p is invalid", m));
1196                 if (m->object == object && m->pindex == pindex)
1197                         cnt.v_reactivated++;
1198                 else
1199                         m->valid = 0;
1200                 m_object = m->object;
1201                 vm_page_cache_remove(m);
1202                 if (m_object->type == OBJT_VNODE && m_object->cache == NULL)
1203                         vp = m_object->handle;
1204         } else {
1205                 KASSERT(VM_PAGE_IS_FREE(m),
1206                     ("vm_page_alloc: page %p is not free", m));
1207                 KASSERT(m->valid == 0,
1208                     ("vm_page_alloc: free page %p is valid", m));
1209                 cnt.v_free_count--;
1210         }
1211
1212         /*
1213          * Initialize structure.  Only the PG_ZERO flag is inherited.
1214          */
1215         flags = 0;
1216         if (m->flags & PG_ZERO) {
1217                 vm_page_zero_count--;
1218                 if (req & VM_ALLOC_ZERO)
1219                         flags = PG_ZERO;
1220         }
1221         if (object == NULL || object->type == OBJT_PHYS)
1222                 flags |= PG_UNMANAGED;
1223         m->flags = flags;
1224         if (req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ))
1225                 m->oflags = 0;
1226         else
1227                 m->oflags = VPO_BUSY;
1228         if (req & VM_ALLOC_WIRED) {
1229                 atomic_add_int(&cnt.v_wire_count, 1);
1230                 m->wire_count = 1;
1231         }
1232         m->act_count = 0;
1233         mtx_unlock(&vm_page_queue_free_mtx);
1234
1235         if (object != NULL) {
1236                 /* Ignore device objects; the pager sets "memattr" for them. */
1237                 if (object->memattr != VM_MEMATTR_DEFAULT &&
1238                     object->type != OBJT_DEVICE && object->type != OBJT_SG)
1239                         pmap_page_set_memattr(m, object->memattr);
1240                 vm_page_insert(m, object, pindex);
1241         } else
1242                 m->pindex = pindex;
1243
1244         /*
1245          * The following call to vdrop() must come after the above call
1246          * to vm_page_insert() in case both affect the same object and
1247          * vnode.  Otherwise, the affected vnode's hold count could
1248          * temporarily become zero.
1249          */
1250         if (vp != NULL)
1251                 vdrop(vp);
1252
1253         /*
1254          * Don't wakeup too often - wakeup the pageout daemon when
1255          * we would be nearly out of memory.
1256          */
1257         if (vm_paging_needed())
1258                 pagedaemon_wakeup();
1259
1260         return (m);
1261 }
1262
1263 /*
1264  * Initialize a page that has been freshly dequeued from a freelist.
1265  * The caller has to drop the vnode returned, if it is not NULL.
1266  *
1267  * To be called with vm_page_queue_free_mtx held.
1268  */
1269 struct vnode *
1270 vm_page_alloc_init(vm_page_t m)
1271 {
1272         struct vnode *drop;
1273         vm_object_t m_object;
1274
1275         KASSERT(m->queue == PQ_NONE,
1276             ("vm_page_alloc_init: page %p has unexpected queue %d",
1277             m, m->queue));
1278         KASSERT(m->wire_count == 0,
1279             ("vm_page_alloc_init: page %p is wired", m));
1280         KASSERT(m->hold_count == 0,
1281             ("vm_page_alloc_init: page %p is held", m));
1282         KASSERT(m->busy == 0,
1283             ("vm_page_alloc_init: page %p is busy", m));
1284         KASSERT(m->dirty == 0,
1285             ("vm_page_alloc_init: page %p is dirty", m));
1286         KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1287             ("vm_page_alloc_init: page %p has unexpected memattr %d",
1288             m, pmap_page_get_memattr(m)));
1289         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1290         drop = NULL;
1291         if ((m->flags & PG_CACHED) != 0) {
1292                 m->valid = 0;
1293                 m_object = m->object;
1294                 vm_page_cache_remove(m);
1295                 if (m_object->type == OBJT_VNODE &&
1296                     m_object->cache == NULL)
1297                         drop = m_object->handle;
1298         } else {
1299                 KASSERT(VM_PAGE_IS_FREE(m),
1300                     ("vm_page_alloc_init: page %p is not free", m));
1301                 KASSERT(m->valid == 0,
1302                     ("vm_page_alloc_init: free page %p is valid", m));
1303                 cnt.v_free_count--;
1304         }
1305         if (m->flags & PG_ZERO)
1306                 vm_page_zero_count--;
1307         /* Don't clear the PG_ZERO flag; we'll need it later. */
1308         m->flags = PG_UNMANAGED | (m->flags & PG_ZERO);
1309         m->oflags = 0;
1310         /* Unmanaged pages don't use "act_count". */
1311         return (drop);
1312 }
1313
1314 /*
1315  *      vm_page_alloc_freelist:
1316  * 
1317  *      Allocate a page from the specified freelist.
1318  *      Only the ALLOC_CLASS values in req are honored, other request flags
1319  *      are ignored.
1320  */
1321 vm_page_t
1322 vm_page_alloc_freelist(int flind, int req)
1323 {
1324         struct vnode *drop;
1325         vm_page_t m;
1326         int page_req;
1327
1328         m = NULL;
1329         page_req = req & VM_ALLOC_CLASS_MASK;
1330         mtx_lock(&vm_page_queue_free_mtx);
1331         /*
1332          * Do not allocate reserved pages unless the req has asked for it.
1333          */
1334         if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1335             (page_req == VM_ALLOC_SYSTEM && 
1336             cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1337             (page_req == VM_ALLOC_INTERRUPT &&
1338             cnt.v_free_count + cnt.v_cache_count > 0)) {
1339                 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1340         }
1341         if (m == NULL) {
1342                 mtx_unlock(&vm_page_queue_free_mtx);
1343                 return (NULL);
1344         }
1345         drop = vm_page_alloc_init(m);
1346         mtx_unlock(&vm_page_queue_free_mtx);
1347         if (drop)
1348                 vdrop(drop);
1349         return (m);
1350 }
1351
1352 /*
1353  *      vm_wait:        (also see VM_WAIT macro)
1354  *
1355  *      Block until free pages are available for allocation
1356  *      - Called in various places before memory allocations.
1357  */
1358 void
1359 vm_wait(void)
1360 {
1361
1362         mtx_lock(&vm_page_queue_free_mtx);
1363         if (curproc == pageproc) {
1364                 vm_pageout_pages_needed = 1;
1365                 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
1366                     PDROP | PSWP, "VMWait", 0);
1367         } else {
1368                 if (!vm_pages_needed) {
1369                         vm_pages_needed = 1;
1370                         wakeup(&vm_pages_needed);
1371                 }
1372                 msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
1373                     "vmwait", 0);
1374         }
1375 }
1376
1377 /*
1378  *      vm_waitpfault:  (also see VM_WAITPFAULT macro)
1379  *
1380  *      Block until free pages are available for allocation
1381  *      - Called only in vm_fault so that processes page faulting
1382  *        can be easily tracked.
1383  *      - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
1384  *        processes will be able to grab memory first.  Do not change
1385  *        this balance without careful testing first.
1386  */
1387 void
1388 vm_waitpfault(void)
1389 {
1390
1391         mtx_lock(&vm_page_queue_free_mtx);
1392         if (!vm_pages_needed) {
1393                 vm_pages_needed = 1;
1394                 wakeup(&vm_pages_needed);
1395         }
1396         msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
1397             "pfault", 0);
1398 }
1399
1400 /*
1401  *      vm_page_requeue:
1402  *
1403  *      If the given page is contained within a page queue, move it to the tail
1404  *      of that queue.
1405  *
1406  *      The page queues must be locked.
1407  */
1408 void
1409 vm_page_requeue(vm_page_t m)
1410 {
1411         int queue = VM_PAGE_GETQUEUE(m);
1412         struct vpgqueues *vpq;
1413
1414         if (queue != PQ_NONE) {
1415                 vpq = &vm_page_queues[queue];
1416                 TAILQ_REMOVE(&vpq->pl, m, pageq);
1417                 TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
1418         }
1419 }
1420
1421 /*
1422  *      vm_pageq_remove:
1423  *
1424  *      Remove a page from its queue.
1425  *
1426  *      The queue containing the given page must be locked.
1427  *      This routine may not block.
1428  */
1429 void
1430 vm_pageq_remove(vm_page_t m)
1431 {
1432         int queue = VM_PAGE_GETQUEUE(m);
1433         struct vpgqueues *pq;
1434
1435         if (queue != PQ_NONE) {
1436                 VM_PAGE_SETQUEUE2(m, PQ_NONE);
1437                 pq = &vm_page_queues[queue];
1438                 TAILQ_REMOVE(&pq->pl, m, pageq);
1439                 (*pq->cnt)--;
1440         }
1441 }
1442
1443 /*
1444  *      vm_page_enqueue:
1445  *
1446  *      Add the given page to the specified queue.
1447  *
1448  *      The page queues must be locked.
1449  */
1450 static void
1451 vm_page_enqueue(int queue, vm_page_t m)
1452 {
1453         struct vpgqueues *vpq;
1454
1455         vpq = &vm_page_queues[queue];
1456         VM_PAGE_SETQUEUE2(m, queue);
1457         TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
1458         ++*vpq->cnt;
1459 }
1460
1461 /*
1462  *      vm_page_activate:
1463  *
1464  *      Put the specified page on the active list (if appropriate).
1465  *      Ensure that act_count is at least ACT_INIT but do not otherwise
1466  *      mess with it.
1467  *
1468  *      The page queues must be locked.
1469  *      This routine may not block.
1470  */
1471 void
1472 vm_page_activate(vm_page_t m)
1473 {
1474
1475         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1476         if (VM_PAGE_GETKNOWNQUEUE2(m) != PQ_ACTIVE) {
1477                 vm_pageq_remove(m);
1478                 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1479                         if (m->act_count < ACT_INIT)
1480                                 m->act_count = ACT_INIT;
1481                         vm_page_enqueue(PQ_ACTIVE, m);
1482                 }
1483         } else {
1484                 if (m->act_count < ACT_INIT)
1485                         m->act_count = ACT_INIT;
1486         }
1487 }
1488
1489 /*
1490  *      vm_page_free_wakeup:
1491  *
1492  *      Helper routine for vm_page_free_toq() and vm_page_cache().  This
1493  *      routine is called when a page has been added to the cache or free
1494  *      queues.
1495  *
1496  *      The page queues must be locked.
1497  *      This routine may not block.
1498  */
1499 static inline void
1500 vm_page_free_wakeup(void)
1501 {
1502
1503         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1504         /*
1505          * if pageout daemon needs pages, then tell it that there are
1506          * some free.
1507          */
1508         if (vm_pageout_pages_needed &&
1509             cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
1510                 wakeup(&vm_pageout_pages_needed);
1511                 vm_pageout_pages_needed = 0;
1512         }
1513         /*
1514          * wakeup processes that are waiting on memory if we hit a
1515          * high water mark. And wakeup scheduler process if we have
1516          * lots of memory. this process will swapin processes.
1517          */
1518         if (vm_pages_needed && !vm_page_count_min()) {
1519                 vm_pages_needed = 0;
1520                 wakeup(&cnt.v_free_count);
1521         }
1522 }
1523
1524 /*
1525  *      vm_page_free_toq:
1526  *
1527  *      Returns the given page to the free list,
1528  *      disassociating it with any VM object.
1529  *
1530  *      Object and page must be locked prior to entry.
1531  *      This routine may not block.
1532  */
1533
1534 void
1535 vm_page_free_toq(vm_page_t m)
1536 {
1537
1538         if (VM_PAGE_GETQUEUE(m) != PQ_NONE)
1539                 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1540         KASSERT(!pmap_page_is_mapped(m),
1541             ("vm_page_free_toq: freeing mapped page %p", m));
1542         PCPU_INC(cnt.v_tfree);
1543
1544         if (m->busy || VM_PAGE_IS_FREE(m)) {
1545                 printf(
1546                 "vm_page_free: pindex(%lu), busy(%d), VPO_BUSY(%d), hold(%d)\n",
1547                     (u_long)m->pindex, m->busy, (m->oflags & VPO_BUSY) ? 1 : 0,
1548                     m->hold_count);
1549                 if (VM_PAGE_IS_FREE(m))
1550                         panic("vm_page_free: freeing free page");
1551                 else
1552                         panic("vm_page_free: freeing busy page");
1553         }
1554
1555         /*
1556          * unqueue, then remove page.  Note that we cannot destroy
1557          * the page here because we do not want to call the pager's
1558          * callback routine until after we've put the page on the
1559          * appropriate free queue.
1560          */
1561         vm_pageq_remove(m);
1562         vm_page_remove(m);
1563
1564         /*
1565          * If fictitious remove object association and
1566          * return, otherwise delay object association removal.
1567          */
1568         if ((m->flags & PG_FICTITIOUS) != 0) {
1569                 return;
1570         }
1571
1572         m->valid = 0;
1573         vm_page_undirty(m);
1574
1575         if (m->wire_count != 0) {
1576                 if (m->wire_count > 1) {
1577                         panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx",
1578                                 m->wire_count, (long)m->pindex);
1579                 }
1580                 panic("vm_page_free: freeing wired page");
1581         }
1582         if (m->hold_count != 0) {
1583                 m->flags &= ~PG_ZERO;
1584                 vm_page_enqueue(PQ_HOLD, m);
1585         } else {
1586                 /*
1587                  * Restore the default memory attribute to the page.
1588                  */
1589                 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
1590                         pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
1591
1592                 /*
1593                  * Insert the page into the physical memory allocator's
1594                  * cache/free page queues.
1595                  */
1596                 mtx_lock(&vm_page_queue_free_mtx);
1597                 m->flags |= PG_FREE;
1598                 cnt.v_free_count++;
1599 #if VM_NRESERVLEVEL > 0
1600                 if (!vm_reserv_free_page(m))
1601 #else
1602                 if (TRUE)
1603 #endif
1604                         vm_phys_free_pages(m, 0);
1605                 if ((m->flags & PG_ZERO) != 0)
1606                         ++vm_page_zero_count;
1607                 else
1608                         vm_page_zero_idle_wakeup();
1609                 vm_page_free_wakeup();
1610                 mtx_unlock(&vm_page_queue_free_mtx);
1611         }
1612 }
1613
1614 /*
1615  *      vm_page_wire:
1616  *
1617  *      Mark this page as wired down by yet
1618  *      another map, removing it from paging queues
1619  *      as necessary.
1620  *
1621  *      The page queues must be locked.
1622  *      This routine may not block.
1623  */
1624 void
1625 vm_page_wire(vm_page_t m)
1626 {
1627
1628         /*
1629          * Only bump the wire statistics if the page is not already wired,
1630          * and only unqueue the page if it is on some queue (if it is unmanaged
1631          * it is already off the queues).
1632          */
1633         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1634         if (m->flags & PG_FICTITIOUS)
1635                 return;
1636         if (m->wire_count == 0) {
1637                 if ((m->flags & PG_UNMANAGED) == 0)
1638                         vm_pageq_remove(m);
1639                 atomic_add_int(&cnt.v_wire_count, 1);
1640         }
1641         m->wire_count++;
1642         KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1643 }
1644
1645 /*
1646  *      vm_page_unwire:
1647  *
1648  *      Release one wiring of this page, potentially
1649  *      enabling it to be paged again.
1650  *
1651  *      Many pages placed on the inactive queue should actually go
1652  *      into the cache, but it is difficult to figure out which.  What
1653  *      we do instead, if the inactive target is well met, is to put
1654  *      clean pages at the head of the inactive queue instead of the tail.
1655  *      This will cause them to be moved to the cache more quickly and
1656  *      if not actively re-referenced, freed more quickly.  If we just
1657  *      stick these pages at the end of the inactive queue, heavy filesystem
1658  *      meta-data accesses can cause an unnecessary paging load on memory bound 
1659  *      processes.  This optimization causes one-time-use metadata to be
1660  *      reused more quickly.
1661  *
1662  *      BUT, if we are in a low-memory situation we have no choice but to
1663  *      put clean pages on the cache queue.
1664  *
1665  *      A number of routines use vm_page_unwire() to guarantee that the page
1666  *      will go into either the inactive or active queues, and will NEVER
1667  *      be placed in the cache - for example, just after dirtying a page.
1668  *      dirty pages in the cache are not allowed.
1669  *
1670  *      The page queues must be locked.
1671  *      This routine may not block.
1672  */
1673 void
1674 vm_page_unwire(vm_page_t m, int activate)
1675 {
1676
1677         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1678         if (m->flags & PG_FICTITIOUS)
1679                 return;
1680         if (m->wire_count > 0) {
1681                 m->wire_count--;
1682                 if (m->wire_count == 0) {
1683                         atomic_subtract_int(&cnt.v_wire_count, 1);
1684                         if (m->flags & PG_UNMANAGED) {
1685                                 ;
1686                         } else if (activate)
1687                                 vm_page_enqueue(PQ_ACTIVE, m);
1688                         else {
1689                                 vm_page_flag_clear(m, PG_WINATCFLS);
1690                                 vm_page_enqueue(PQ_INACTIVE, m);
1691                         }
1692                 }
1693         } else {
1694                 panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
1695         }
1696 }
1697
1698
1699 /*
1700  * Move the specified page to the inactive queue.  If the page has
1701  * any associated swap, the swap is deallocated.
1702  *
1703  * Normally athead is 0 resulting in LRU operation.  athead is set
1704  * to 1 if we want this page to be 'as if it were placed in the cache',
1705  * except without unmapping it from the process address space.
1706  *
1707  * This routine may not block.
1708  */
1709 static inline void
1710 _vm_page_deactivate(vm_page_t m, int athead)
1711 {
1712
1713         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1714
1715         /*
1716          * Ignore if already inactive.
1717          */
1718         if (VM_PAGE_INQUEUE2(m, PQ_INACTIVE))
1719                 return;
1720         if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1721                 vm_page_flag_clear(m, PG_WINATCFLS);
1722                 vm_pageq_remove(m);
1723                 if (athead)
1724                         TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1725                 else
1726                         TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1727                 VM_PAGE_SETQUEUE2(m, PQ_INACTIVE);
1728                 cnt.v_inactive_count++;
1729         }
1730 }
1731
1732 void
1733 vm_page_deactivate(vm_page_t m)
1734 {
1735     _vm_page_deactivate(m, 0);
1736 }
1737
1738 /*
1739  * vm_page_try_to_cache:
1740  *
1741  * Returns 0 on failure, 1 on success
1742  */
1743 int
1744 vm_page_try_to_cache(vm_page_t m)
1745 {
1746
1747         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1748         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1749         if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1750             (m->oflags & VPO_BUSY) || (m->flags & PG_UNMANAGED)) {
1751                 return (0);
1752         }
1753         pmap_remove_all(m);
1754         if (m->dirty)
1755                 return (0);
1756         vm_page_cache(m);
1757         return (1);
1758 }
1759
1760 /*
1761  * vm_page_try_to_free()
1762  *
1763  *      Attempt to free the page.  If we cannot free it, we do nothing.
1764  *      1 is returned on success, 0 on failure.
1765  */
1766 int
1767 vm_page_try_to_free(vm_page_t m)
1768 {
1769
1770         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1771         if (m->object != NULL)
1772                 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1773         if (m->dirty || m->hold_count || m->busy || m->wire_count ||
1774             (m->oflags & VPO_BUSY) || (m->flags & PG_UNMANAGED)) {
1775                 return (0);
1776         }
1777         pmap_remove_all(m);
1778         if (m->dirty)
1779                 return (0);
1780         vm_page_free(m);
1781         return (1);
1782 }
1783
1784 /*
1785  * vm_page_cache
1786  *
1787  * Put the specified page onto the page cache queue (if appropriate).
1788  *
1789  * This routine may not block.
1790  */
1791 void
1792 vm_page_cache(vm_page_t m)
1793 {
1794         vm_object_t object;
1795         vm_page_t root;
1796
1797         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1798         object = m->object;
1799         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1800         if ((m->flags & PG_UNMANAGED) || (m->oflags & VPO_BUSY) || m->busy ||
1801             m->hold_count || m->wire_count) {
1802                 panic("vm_page_cache: attempting to cache busy page");
1803         }
1804         pmap_remove_all(m);
1805         if (m->dirty != 0)
1806                 panic("vm_page_cache: page %p is dirty", m);
1807         if (m->valid == 0 || object->type == OBJT_DEFAULT ||
1808             (object->type == OBJT_SWAP &&
1809             !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
1810                 /*
1811                  * Hypothesis: A cache-elgible page belonging to a
1812                  * default object or swap object but without a backing
1813                  * store must be zero filled.
1814                  */
1815                 vm_page_free(m);
1816                 return;
1817         }
1818         KASSERT((m->flags & PG_CACHED) == 0,
1819             ("vm_page_cache: page %p is already cached", m));
1820         cnt.v_tcached++;
1821
1822         /*
1823          * Remove the page from the paging queues.
1824          */
1825         vm_pageq_remove(m);
1826
1827         /*
1828          * Remove the page from the object's collection of resident
1829          * pages. 
1830          */
1831         if (m != object->root)
1832                 vm_page_splay(m->pindex, object->root);
1833         if (m->left == NULL)
1834                 root = m->right;
1835         else {
1836                 root = vm_page_splay(m->pindex, m->left);
1837                 root->right = m->right;
1838         }
1839         object->root = root;
1840         TAILQ_REMOVE(&object->memq, m, listq);
1841         object->resident_page_count--;
1842
1843         /*
1844          * Restore the default memory attribute to the page.
1845          */
1846         if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
1847                 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
1848
1849         /*
1850          * Insert the page into the object's collection of cached pages
1851          * and the physical memory allocator's cache/free page queues.
1852          */
1853         vm_page_flag_clear(m, PG_ZERO);
1854         mtx_lock(&vm_page_queue_free_mtx);
1855         m->flags |= PG_CACHED;
1856         cnt.v_cache_count++;
1857         root = object->cache;
1858         if (root == NULL) {
1859                 m->left = NULL;
1860                 m->right = NULL;
1861         } else {
1862                 root = vm_page_splay(m->pindex, root);
1863                 if (m->pindex < root->pindex) {
1864                         m->left = root->left;
1865                         m->right = root;
1866                         root->left = NULL;
1867                 } else if (__predict_false(m->pindex == root->pindex))
1868                         panic("vm_page_cache: offset already cached");
1869                 else {
1870                         m->right = root->right;
1871                         m->left = root;
1872                         root->right = NULL;
1873                 }
1874         }
1875         object->cache = m;
1876 #if VM_NRESERVLEVEL > 0
1877         if (!vm_reserv_free_page(m)) {
1878 #else
1879         if (TRUE) {
1880 #endif
1881                 vm_phys_set_pool(VM_FREEPOOL_CACHE, m, 0);
1882                 vm_phys_free_pages(m, 0);
1883         }
1884         vm_page_free_wakeup();
1885         mtx_unlock(&vm_page_queue_free_mtx);
1886
1887         /*
1888          * Increment the vnode's hold count if this is the object's only
1889          * cached page.  Decrement the vnode's hold count if this was
1890          * the object's only resident page.
1891          */
1892         if (object->type == OBJT_VNODE) {
1893                 if (root == NULL && object->resident_page_count != 0)
1894                         vhold(object->handle);
1895                 else if (root != NULL && object->resident_page_count == 0)
1896                         vdrop(object->handle);
1897         }
1898 }
1899
1900 /*
1901  * vm_page_dontneed
1902  *
1903  *      Cache, deactivate, or do nothing as appropriate.  This routine
1904  *      is typically used by madvise() MADV_DONTNEED.
1905  *
1906  *      Generally speaking we want to move the page into the cache so
1907  *      it gets reused quickly.  However, this can result in a silly syndrome
1908  *      due to the page recycling too quickly.  Small objects will not be
1909  *      fully cached.  On the otherhand, if we move the page to the inactive
1910  *      queue we wind up with a problem whereby very large objects 
1911  *      unnecessarily blow away our inactive and cache queues.
1912  *
1913  *      The solution is to move the pages based on a fixed weighting.  We
1914  *      either leave them alone, deactivate them, or move them to the cache,
1915  *      where moving them to the cache has the highest weighting.
1916  *      By forcing some pages into other queues we eventually force the
1917  *      system to balance the queues, potentially recovering other unrelated
1918  *      space from active.  The idea is to not force this to happen too
1919  *      often.
1920  */
1921 void
1922 vm_page_dontneed(vm_page_t m)
1923 {
1924         static int dnweight;
1925         int dnw;
1926         int head;
1927
1928         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1929         dnw = ++dnweight;
1930
1931         /*
1932          * occassionally leave the page alone
1933          */
1934         if ((dnw & 0x01F0) == 0 ||
1935             VM_PAGE_INQUEUE2(m, PQ_INACTIVE)) {
1936                 if (m->act_count >= ACT_INIT)
1937                         --m->act_count;
1938                 return;
1939         }
1940
1941         /*
1942          * Clear any references to the page.  Otherwise, the page daemon will
1943          * immediately reactivate the page.
1944          */
1945         vm_page_flag_clear(m, PG_REFERENCED);
1946         pmap_clear_reference(m);
1947
1948         if (m->dirty == 0 && pmap_is_modified(m))
1949                 vm_page_dirty(m);
1950
1951         if (m->dirty || (dnw & 0x0070) == 0) {
1952                 /*
1953                  * Deactivate the page 3 times out of 32.
1954                  */
1955                 head = 0;
1956         } else {
1957                 /*
1958                  * Cache the page 28 times out of every 32.  Note that
1959                  * the page is deactivated instead of cached, but placed
1960                  * at the head of the queue instead of the tail.
1961                  */
1962                 head = 1;
1963         }
1964         _vm_page_deactivate(m, head);
1965 }
1966
1967 /*
1968  * Grab a page, waiting until we are waken up due to the page
1969  * changing state.  We keep on waiting, if the page continues
1970  * to be in the object.  If the page doesn't exist, first allocate it
1971  * and then conditionally zero it.
1972  *
1973  * This routine may block.
1974  */
1975 vm_page_t
1976 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
1977 {
1978         vm_page_t m;
1979
1980         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1981 retrylookup:
1982         if ((m = vm_page_lookup(object, pindex)) != NULL) {
1983                 if (vm_page_sleep_if_busy(m, TRUE, "pgrbwt")) {
1984                         if ((allocflags & VM_ALLOC_RETRY) == 0)
1985                                 return (NULL);
1986                         goto retrylookup;
1987                 } else {
1988                         if ((allocflags & VM_ALLOC_WIRED) != 0) {
1989                                 vm_page_lock_queues();
1990                                 vm_page_wire(m);
1991                                 vm_page_unlock_queues();
1992                         }
1993                         if ((allocflags & VM_ALLOC_NOBUSY) == 0)
1994                                 vm_page_busy(m);
1995                         return (m);
1996                 }
1997         }
1998         m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
1999         if (m == NULL) {
2000                 VM_OBJECT_UNLOCK(object);
2001                 VM_WAIT;
2002                 VM_OBJECT_LOCK(object);
2003                 if ((allocflags & VM_ALLOC_RETRY) == 0)
2004                         return (NULL);
2005                 goto retrylookup;
2006         } else if (m->valid != 0)
2007                 return (m);
2008         if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
2009                 pmap_zero_page(m);
2010         return (m);
2011 }
2012
2013 /*
2014  * Mapping function for valid bits or for dirty bits in
2015  * a page.  May not block.
2016  *
2017  * Inputs are required to range within a page.
2018  */
2019 int
2020 vm_page_bits(int base, int size)
2021 {
2022         int first_bit;
2023         int last_bit;
2024
2025         KASSERT(
2026             base + size <= PAGE_SIZE,
2027             ("vm_page_bits: illegal base/size %d/%d", base, size)
2028         );
2029
2030         if (size == 0)          /* handle degenerate case */
2031                 return (0);
2032
2033         first_bit = base >> DEV_BSHIFT;
2034         last_bit = (base + size - 1) >> DEV_BSHIFT;
2035
2036         return ((2 << last_bit) - (1 << first_bit));
2037 }
2038
2039 /*
2040  *      vm_page_set_valid:
2041  *
2042  *      Sets portions of a page valid.  The arguments are expected
2043  *      to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2044  *      of any partial chunks touched by the range.  The invalid portion of
2045  *      such chunks will be zeroed.
2046  *
2047  *      (base + size) must be less then or equal to PAGE_SIZE.
2048  */
2049 void
2050 vm_page_set_valid(vm_page_t m, int base, int size)
2051 {
2052         int endoff, frag;
2053
2054         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2055         if (size == 0)  /* handle degenerate case */
2056                 return;
2057
2058         /*
2059          * If the base is not DEV_BSIZE aligned and the valid
2060          * bit is clear, we have to zero out a portion of the
2061          * first block.
2062          */
2063         if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2064             (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2065                 pmap_zero_page_area(m, frag, base - frag);
2066
2067         /*
2068          * If the ending offset is not DEV_BSIZE aligned and the 
2069          * valid bit is clear, we have to zero out a portion of
2070          * the last block.
2071          */
2072         endoff = base + size;
2073         if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2074             (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2075                 pmap_zero_page_area(m, endoff,
2076                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2077
2078         /*
2079          * Assert that no previously invalid block that is now being validated
2080          * is already dirty. 
2081          */
2082         KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
2083             ("vm_page_set_valid: page %p is dirty", m)); 
2084
2085         /*
2086          * Set valid bits inclusive of any overlap.
2087          */
2088         m->valid |= vm_page_bits(base, size);
2089 }
2090
2091 /*
2092  *      vm_page_set_validclean:
2093  *
2094  *      Sets portions of a page valid and clean.  The arguments are expected
2095  *      to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2096  *      of any partial chunks touched by the range.  The invalid portion of
2097  *      such chunks will be zero'd.
2098  *
2099  *      This routine may not block.
2100  *
2101  *      (base + size) must be less then or equal to PAGE_SIZE.
2102  */
2103 void
2104 vm_page_set_validclean(vm_page_t m, int base, int size)
2105 {
2106         int pagebits;
2107         int frag;
2108         int endoff;
2109
2110         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2111         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2112         if (size == 0)  /* handle degenerate case */
2113                 return;
2114
2115         /*
2116          * If the base is not DEV_BSIZE aligned and the valid
2117          * bit is clear, we have to zero out a portion of the
2118          * first block.
2119          */
2120         if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2121             (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2122                 pmap_zero_page_area(m, frag, base - frag);
2123
2124         /*
2125          * If the ending offset is not DEV_BSIZE aligned and the 
2126          * valid bit is clear, we have to zero out a portion of
2127          * the last block.
2128          */
2129         endoff = base + size;
2130         if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2131             (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2132                 pmap_zero_page_area(m, endoff,
2133                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2134
2135         /*
2136          * Set valid, clear dirty bits.  If validating the entire
2137          * page we can safely clear the pmap modify bit.  We also
2138          * use this opportunity to clear the VPO_NOSYNC flag.  If a process
2139          * takes a write fault on a MAP_NOSYNC memory area the flag will
2140          * be set again.
2141          *
2142          * We set valid bits inclusive of any overlap, but we can only
2143          * clear dirty bits for DEV_BSIZE chunks that are fully within
2144          * the range.
2145          */
2146         pagebits = vm_page_bits(base, size);
2147         m->valid |= pagebits;
2148 #if 0   /* NOT YET */
2149         if ((frag = base & (DEV_BSIZE - 1)) != 0) {
2150                 frag = DEV_BSIZE - frag;
2151                 base += frag;
2152                 size -= frag;
2153                 if (size < 0)
2154                         size = 0;
2155         }
2156         pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
2157 #endif
2158         m->dirty &= ~pagebits;
2159         if (base == 0 && size == PAGE_SIZE) {
2160                 pmap_clear_modify(m);
2161                 m->oflags &= ~VPO_NOSYNC;
2162         }
2163 }
2164
2165 void
2166 vm_page_clear_dirty(vm_page_t m, int base, int size)
2167 {
2168
2169         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2170         m->dirty &= ~vm_page_bits(base, size);
2171 }
2172
2173 /*
2174  *      vm_page_set_invalid:
2175  *
2176  *      Invalidates DEV_BSIZE'd chunks within a page.  Both the
2177  *      valid and dirty bits for the effected areas are cleared.
2178  *
2179  *      May not block.
2180  */
2181 void
2182 vm_page_set_invalid(vm_page_t m, int base, int size)
2183 {
2184         int bits;
2185
2186         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2187         bits = vm_page_bits(base, size);
2188         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2189         if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
2190                 pmap_remove_all(m);
2191         m->valid &= ~bits;
2192         m->dirty &= ~bits;
2193 }
2194
2195 /*
2196  * vm_page_zero_invalid()
2197  *
2198  *      The kernel assumes that the invalid portions of a page contain 
2199  *      garbage, but such pages can be mapped into memory by user code.
2200  *      When this occurs, we must zero out the non-valid portions of the
2201  *      page so user code sees what it expects.
2202  *
2203  *      Pages are most often semi-valid when the end of a file is mapped 
2204  *      into memory and the file's size is not page aligned.
2205  */
2206 void
2207 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
2208 {
2209         int b;
2210         int i;
2211
2212         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2213         /*
2214          * Scan the valid bits looking for invalid sections that
2215          * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
2216          * valid bit may be set ) have already been zerod by
2217          * vm_page_set_validclean().
2218          */
2219         for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
2220                 if (i == (PAGE_SIZE / DEV_BSIZE) || 
2221                     (m->valid & (1 << i))
2222                 ) {
2223                         if (i > b) {
2224                                 pmap_zero_page_area(m, 
2225                                     b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
2226                         }
2227                         b = i + 1;
2228                 }
2229         }
2230
2231         /*
2232          * setvalid is TRUE when we can safely set the zero'd areas
2233          * as being valid.  We can do this if there are no cache consistancy
2234          * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
2235          */
2236         if (setvalid)
2237                 m->valid = VM_PAGE_BITS_ALL;
2238 }
2239
2240 /*
2241  *      vm_page_is_valid:
2242  *
2243  *      Is (partial) page valid?  Note that the case where size == 0
2244  *      will return FALSE in the degenerate case where the page is
2245  *      entirely invalid, and TRUE otherwise.
2246  *
2247  *      May not block.
2248  */
2249 int
2250 vm_page_is_valid(vm_page_t m, int base, int size)
2251 {
2252         int bits = vm_page_bits(base, size);
2253
2254         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2255         if (m->valid && ((m->valid & bits) == bits))
2256                 return 1;
2257         else
2258                 return 0;
2259 }
2260
2261 /*
2262  * update dirty bits from pmap/mmu.  May not block.
2263  */
2264 void
2265 vm_page_test_dirty(vm_page_t m)
2266 {
2267         if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
2268                 vm_page_dirty(m);
2269         }
2270 }
2271
2272 int so_zerocp_fullpage = 0;
2273
2274 /*
2275  *      Replace the given page with a copy.  The copied page assumes
2276  *      the portion of the given page's "wire_count" that is not the
2277  *      responsibility of this copy-on-write mechanism.
2278  *
2279  *      The object containing the given page must have a non-zero
2280  *      paging-in-progress count and be locked.
2281  */
2282 void
2283 vm_page_cowfault(vm_page_t m)
2284 {
2285         vm_page_t mnew;
2286         vm_object_t object;
2287         vm_pindex_t pindex;
2288
2289         object = m->object;
2290         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2291         KASSERT(object->paging_in_progress != 0,
2292             ("vm_page_cowfault: object %p's paging-in-progress count is zero.",
2293             object)); 
2294         pindex = m->pindex;
2295
2296  retry_alloc:
2297         pmap_remove_all(m);
2298         vm_page_remove(m);
2299         mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY);
2300         if (mnew == NULL) {
2301                 vm_page_insert(m, object, pindex);
2302                 vm_page_unlock_queues();
2303                 VM_OBJECT_UNLOCK(object);
2304                 VM_WAIT;
2305                 VM_OBJECT_LOCK(object);
2306                 if (m == vm_page_lookup(object, pindex)) {
2307                         vm_page_lock_queues();
2308                         goto retry_alloc;
2309                 } else {
2310                         /*
2311                          * Page disappeared during the wait.
2312                          */
2313                         vm_page_lock_queues();
2314                         return;
2315                 }
2316         }
2317
2318         if (m->cow == 0) {
2319                 /* 
2320                  * check to see if we raced with an xmit complete when 
2321                  * waiting to allocate a page.  If so, put things back 
2322                  * the way they were 
2323                  */
2324                 vm_page_free(mnew);
2325                 vm_page_insert(m, object, pindex);
2326         } else { /* clear COW & copy page */
2327                 if (!so_zerocp_fullpage)
2328                         pmap_copy_page(m, mnew);
2329                 mnew->valid = VM_PAGE_BITS_ALL;
2330                 vm_page_dirty(mnew);
2331                 mnew->wire_count = m->wire_count - m->cow;
2332                 m->wire_count = m->cow;
2333         }
2334 }
2335
2336 void 
2337 vm_page_cowclear(vm_page_t m)
2338 {
2339
2340         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2341         if (m->cow) {
2342                 m->cow--;
2343                 /* 
2344                  * let vm_fault add back write permission  lazily
2345                  */
2346         } 
2347         /*
2348          *  sf_buf_free() will free the page, so we needn't do it here
2349          */ 
2350 }
2351
2352 int
2353 vm_page_cowsetup(vm_page_t m)
2354 {
2355
2356         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2357         if (m->cow == USHRT_MAX - 1)
2358                 return (EBUSY);
2359         m->cow++;
2360         pmap_remove_write(m);
2361         return (0);
2362 }
2363
2364 #include "opt_ddb.h"
2365 #ifdef DDB
2366 #include <sys/kernel.h>
2367
2368 #include <ddb/ddb.h>
2369
2370 DB_SHOW_COMMAND(page, vm_page_print_page_info)
2371 {
2372         db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
2373         db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
2374         db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
2375         db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
2376         db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
2377         db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
2378         db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
2379         db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
2380         db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
2381         db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
2382 }
2383
2384 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
2385 {
2386                 
2387         db_printf("PQ_FREE:");
2388         db_printf(" %d", cnt.v_free_count);
2389         db_printf("\n");
2390                 
2391         db_printf("PQ_CACHE:");
2392         db_printf(" %d", cnt.v_cache_count);
2393         db_printf("\n");
2394
2395         db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
2396                 *vm_page_queues[PQ_ACTIVE].cnt,
2397                 *vm_page_queues[PQ_INACTIVE].cnt);
2398 }
2399 #endif /* DDB */