]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/vm/vm_page.c
MFC r238732 (by alc):
[FreeBSD/stable/9.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  *      - The object mutex is held when inserting or removing
71  *        pages from an object (vm_page_insert() or vm_page_remove()).
72  *
73  */
74
75 /*
76  *      Resident memory management module.
77  */
78
79 #include <sys/cdefs.h>
80 __FBSDID("$FreeBSD$");
81
82 #include "opt_vm.h"
83
84 #include <sys/param.h>
85 #include <sys/systm.h>
86 #include <sys/lock.h>
87 #include <sys/kernel.h>
88 #include <sys/limits.h>
89 #include <sys/malloc.h>
90 #include <sys/msgbuf.h>
91 #include <sys/mutex.h>
92 #include <sys/proc.h>
93 #include <sys/sysctl.h>
94 #include <sys/vmmeter.h>
95 #include <sys/vnode.h>
96
97 #include <vm/vm.h>
98 #include <vm/pmap.h>
99 #include <vm/vm_param.h>
100 #include <vm/vm_kern.h>
101 #include <vm/vm_object.h>
102 #include <vm/vm_page.h>
103 #include <vm/vm_pageout.h>
104 #include <vm/vm_pager.h>
105 #include <vm/vm_phys.h>
106 #include <vm/vm_reserv.h>
107 #include <vm/vm_extern.h>
108 #include <vm/uma.h>
109 #include <vm/uma_int.h>
110
111 #include <machine/md_var.h>
112
113 /*
114  *      Associated with page of user-allocatable memory is a
115  *      page structure.
116  */
117
118 struct vpgqueues vm_page_queues[PQ_COUNT];
119 struct vpglocks vm_page_queue_lock;
120 struct vpglocks vm_page_queue_free_lock;
121
122 struct vpglocks pa_lock[PA_LOCK_COUNT];
123
124 vm_page_t vm_page_array;
125 long vm_page_array_size;
126 long first_page;
127 int vm_page_zero_count;
128
129 static int boot_pages = UMA_BOOT_PAGES;
130 TUNABLE_INT("vm.boot_pages", &boot_pages);
131 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RD, &boot_pages, 0,
132         "number of pages allocated for bootstrapping the VM system");
133
134 int pa_tryrelock_restart;
135 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
136     &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
137
138 static uma_zone_t fakepg_zone;
139
140 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
141 static void vm_page_queue_remove(int queue, vm_page_t m);
142 static void vm_page_enqueue(int queue, vm_page_t m);
143 static void vm_page_init_fakepg(void *dummy);
144
145 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init_fakepg, NULL);
146
147 static void
148 vm_page_init_fakepg(void *dummy)
149 {
150
151         fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
152             NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM); 
153 }
154
155 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
156 #if PAGE_SIZE == 32768
157 #ifdef CTASSERT
158 CTASSERT(sizeof(u_long) >= 8);
159 #endif
160 #endif
161
162 /*
163  * Try to acquire a physical address lock while a pmap is locked.  If we
164  * fail to trylock we unlock and lock the pmap directly and cache the
165  * locked pa in *locked.  The caller should then restart their loop in case
166  * the virtual to physical mapping has changed.
167  */
168 int
169 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
170 {
171         vm_paddr_t lockpa;
172
173         lockpa = *locked;
174         *locked = pa;
175         if (lockpa) {
176                 PA_LOCK_ASSERT(lockpa, MA_OWNED);
177                 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
178                         return (0);
179                 PA_UNLOCK(lockpa);
180         }
181         if (PA_TRYLOCK(pa))
182                 return (0);
183         PMAP_UNLOCK(pmap);
184         atomic_add_int(&pa_tryrelock_restart, 1);
185         PA_LOCK(pa);
186         PMAP_LOCK(pmap);
187         return (EAGAIN);
188 }
189
190 /*
191  *      vm_set_page_size:
192  *
193  *      Sets the page size, perhaps based upon the memory
194  *      size.  Must be called before any use of page-size
195  *      dependent functions.
196  */
197 void
198 vm_set_page_size(void)
199 {
200         if (cnt.v_page_size == 0)
201                 cnt.v_page_size = PAGE_SIZE;
202         if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
203                 panic("vm_set_page_size: page size not a power of two");
204 }
205
206 /*
207  *      vm_page_blacklist_lookup:
208  *
209  *      See if a physical address in this page has been listed
210  *      in the blacklist tunable.  Entries in the tunable are
211  *      separated by spaces or commas.  If an invalid integer is
212  *      encountered then the rest of the string is skipped.
213  */
214 static int
215 vm_page_blacklist_lookup(char *list, vm_paddr_t pa)
216 {
217         vm_paddr_t bad;
218         char *cp, *pos;
219
220         for (pos = list; *pos != '\0'; pos = cp) {
221                 bad = strtoq(pos, &cp, 0);
222                 if (*cp != '\0') {
223                         if (*cp == ' ' || *cp == ',') {
224                                 cp++;
225                                 if (cp == pos)
226                                         continue;
227                         } else
228                                 break;
229                 }
230                 if (pa == trunc_page(bad))
231                         return (1);
232         }
233         return (0);
234 }
235
236 /*
237  *      vm_page_startup:
238  *
239  *      Initializes the resident memory module.
240  *
241  *      Allocates memory for the page cells, and
242  *      for the object/offset-to-page hash table headers.
243  *      Each page cell is initialized and placed on the free list.
244  */
245 vm_offset_t
246 vm_page_startup(vm_offset_t vaddr)
247 {
248         vm_offset_t mapped;
249         vm_paddr_t page_range;
250         vm_paddr_t new_end;
251         int i;
252         vm_paddr_t pa;
253         vm_paddr_t last_pa;
254         char *list;
255
256         /* the biggest memory array is the second group of pages */
257         vm_paddr_t end;
258         vm_paddr_t biggestsize;
259         vm_paddr_t low_water, high_water;
260         int biggestone;
261
262         biggestsize = 0;
263         biggestone = 0;
264         vaddr = round_page(vaddr);
265
266         for (i = 0; phys_avail[i + 1]; i += 2) {
267                 phys_avail[i] = round_page(phys_avail[i]);
268                 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
269         }
270
271         low_water = phys_avail[0];
272         high_water = phys_avail[1];
273
274         for (i = 0; phys_avail[i + 1]; i += 2) {
275                 vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
276
277                 if (size > biggestsize) {
278                         biggestone = i;
279                         biggestsize = size;
280                 }
281                 if (phys_avail[i] < low_water)
282                         low_water = phys_avail[i];
283                 if (phys_avail[i + 1] > high_water)
284                         high_water = phys_avail[i + 1];
285         }
286
287 #ifdef XEN
288         low_water = 0;
289 #endif  
290
291         end = phys_avail[biggestone+1];
292
293         /*
294          * Initialize the locks.
295          */
296         mtx_init(&vm_page_queue_mtx, "vm page queue mutex", NULL, MTX_DEF |
297             MTX_RECURSE);
298         mtx_init(&vm_page_queue_free_mtx, "vm page queue free mutex", NULL,
299             MTX_DEF);
300
301         /* Setup page locks. */
302         for (i = 0; i < PA_LOCK_COUNT; i++)
303                 mtx_init(&pa_lock[i].data, "page lock", NULL, MTX_DEF);
304
305         /*
306          * Initialize the queue headers for the hold queue, the active queue,
307          * and the inactive queue.
308          */
309         for (i = 0; i < PQ_COUNT; i++)
310                 TAILQ_INIT(&vm_page_queues[i].pl);
311         vm_page_queues[PQ_INACTIVE].cnt = &cnt.v_inactive_count;
312         vm_page_queues[PQ_ACTIVE].cnt = &cnt.v_active_count;
313         vm_page_queues[PQ_HOLD].cnt = &cnt.v_active_count;
314
315         /*
316          * Allocate memory for use when boot strapping the kernel memory
317          * allocator.
318          */
319         new_end = end - (boot_pages * UMA_SLAB_SIZE);
320         new_end = trunc_page(new_end);
321         mapped = pmap_map(&vaddr, new_end, end,
322             VM_PROT_READ | VM_PROT_WRITE);
323         bzero((void *)mapped, end - new_end);
324         uma_startup((void *)mapped, boot_pages);
325
326 #if defined(__amd64__) || defined(__i386__) || defined(__arm__) || \
327     defined(__mips__)
328         /*
329          * Allocate a bitmap to indicate that a random physical page
330          * needs to be included in a minidump.
331          *
332          * The amd64 port needs this to indicate which direct map pages
333          * need to be dumped, via calls to dump_add_page()/dump_drop_page().
334          *
335          * However, i386 still needs this workspace internally within the
336          * minidump code.  In theory, they are not needed on i386, but are
337          * included should the sf_buf code decide to use them.
338          */
339         last_pa = 0;
340         for (i = 0; dump_avail[i + 1] != 0; i += 2)
341                 if (dump_avail[i + 1] > last_pa)
342                         last_pa = dump_avail[i + 1];
343         page_range = last_pa / PAGE_SIZE;
344         vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
345         new_end -= vm_page_dump_size;
346         vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
347             new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
348         bzero((void *)vm_page_dump, vm_page_dump_size);
349 #endif
350 #ifdef __amd64__
351         /*
352          * Request that the physical pages underlying the message buffer be
353          * included in a crash dump.  Since the message buffer is accessed
354          * through the direct map, they are not automatically included.
355          */
356         pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
357         last_pa = pa + round_page(msgbufsize);
358         while (pa < last_pa) {
359                 dump_add_page(pa);
360                 pa += PAGE_SIZE;
361         }
362 #endif
363         /*
364          * Compute the number of pages of memory that will be available for
365          * use (taking into account the overhead of a page structure per
366          * page).
367          */
368         first_page = low_water / PAGE_SIZE;
369 #ifdef VM_PHYSSEG_SPARSE
370         page_range = 0;
371         for (i = 0; phys_avail[i + 1] != 0; i += 2)
372                 page_range += atop(phys_avail[i + 1] - phys_avail[i]);
373 #elif defined(VM_PHYSSEG_DENSE)
374         page_range = high_water / PAGE_SIZE - first_page;
375 #else
376 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
377 #endif
378         end = new_end;
379
380         /*
381          * Reserve an unmapped guard page to trap access to vm_page_array[-1].
382          */
383         vaddr += PAGE_SIZE;
384
385         /*
386          * Initialize the mem entry structures now, and put them in the free
387          * queue.
388          */
389         new_end = trunc_page(end - page_range * sizeof(struct vm_page));
390         mapped = pmap_map(&vaddr, new_end, end,
391             VM_PROT_READ | VM_PROT_WRITE);
392         vm_page_array = (vm_page_t) mapped;
393 #if VM_NRESERVLEVEL > 0
394         /*
395          * Allocate memory for the reservation management system's data
396          * structures.
397          */
398         new_end = vm_reserv_startup(&vaddr, new_end, high_water);
399 #endif
400 #if defined(__amd64__) || defined(__mips__)
401         /*
402          * pmap_map on amd64 and mips can come out of the direct-map, not kvm
403          * like i386, so the pages must be tracked for a crashdump to include
404          * this data.  This includes the vm_page_array and the early UMA
405          * bootstrap pages.
406          */
407         for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
408                 dump_add_page(pa);
409 #endif  
410         phys_avail[biggestone + 1] = new_end;
411
412         /*
413          * Clear all of the page structures
414          */
415         bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
416         for (i = 0; i < page_range; i++)
417                 vm_page_array[i].order = VM_NFREEORDER;
418         vm_page_array_size = page_range;
419
420         /*
421          * Initialize the physical memory allocator.
422          */
423         vm_phys_init();
424
425         /*
426          * Add every available physical page that is not blacklisted to
427          * the free lists.
428          */
429         cnt.v_page_count = 0;
430         cnt.v_free_count = 0;
431         list = getenv("vm.blacklist");
432         for (i = 0; phys_avail[i + 1] != 0; i += 2) {
433                 pa = phys_avail[i];
434                 last_pa = phys_avail[i + 1];
435                 while (pa < last_pa) {
436                         if (list != NULL &&
437                             vm_page_blacklist_lookup(list, pa))
438                                 printf("Skipping page with pa 0x%jx\n",
439                                     (uintmax_t)pa);
440                         else
441                                 vm_phys_add_page(pa);
442                         pa += PAGE_SIZE;
443                 }
444         }
445         freeenv(list);
446 #if VM_NRESERVLEVEL > 0
447         /*
448          * Initialize the reservation management system.
449          */
450         vm_reserv_init();
451 #endif
452         return (vaddr);
453 }
454
455
456 CTASSERT(offsetof(struct vm_page, aflags) % sizeof(uint32_t) == 0);
457
458 void
459 vm_page_aflag_set(vm_page_t m, uint8_t bits)
460 {
461         uint32_t *addr, val;
462
463         /*
464          * The PGA_WRITEABLE flag can only be set if the page is managed and
465          * VPO_BUSY.  Currently, this flag is only set by pmap_enter().
466          */
467         KASSERT((bits & PGA_WRITEABLE) == 0 ||
468             (m->oflags & (VPO_UNMANAGED | VPO_BUSY)) == VPO_BUSY,
469             ("PGA_WRITEABLE and !VPO_BUSY"));
470
471         /*
472          * We want to use atomic updates for m->aflags, which is a
473          * byte wide.  Not all architectures provide atomic operations
474          * on the single-byte destination.  Punt and access the whole
475          * 4-byte word with an atomic update.  Parallel non-atomic
476          * updates to the fields included in the update by proximity
477          * are handled properly by atomics.
478          */
479         addr = (void *)&m->aflags;
480         MPASS(((uintptr_t)addr & (sizeof(uint32_t) - 1)) == 0);
481         val = bits;
482 #if BYTE_ORDER == BIG_ENDIAN
483         val <<= 24;
484 #endif
485         atomic_set_32(addr, val);
486
487
488 void
489 vm_page_aflag_clear(vm_page_t m, uint8_t bits)
490 {
491         uint32_t *addr, val;
492
493         /*
494          * The PGA_REFERENCED flag can only be cleared if the object
495          * containing the page is locked.
496          */
497         KASSERT((bits & PGA_REFERENCED) == 0 || VM_OBJECT_LOCKED(m->object),
498             ("PGA_REFERENCED and !VM_OBJECT_LOCKED"));
499
500         /*
501          * See the comment in vm_page_aflag_set().
502          */
503         addr = (void *)&m->aflags;
504         MPASS(((uintptr_t)addr & (sizeof(uint32_t) - 1)) == 0);
505         val = bits;
506 #if BYTE_ORDER == BIG_ENDIAN
507         val <<= 24;
508 #endif
509         atomic_clear_32(addr, val);
510 }
511
512 void
513 vm_page_reference(vm_page_t m)
514 {
515
516         vm_page_aflag_set(m, PGA_REFERENCED);
517 }
518
519 void
520 vm_page_busy(vm_page_t m)
521 {
522
523         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
524         KASSERT((m->oflags & VPO_BUSY) == 0,
525             ("vm_page_busy: page already busy!!!"));
526         m->oflags |= VPO_BUSY;
527 }
528
529 /*
530  *      vm_page_flash:
531  *
532  *      wakeup anyone waiting for the page.
533  */
534 void
535 vm_page_flash(vm_page_t m)
536 {
537
538         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
539         if (m->oflags & VPO_WANTED) {
540                 m->oflags &= ~VPO_WANTED;
541                 wakeup(m);
542         }
543 }
544
545 /*
546  *      vm_page_wakeup:
547  *
548  *      clear the VPO_BUSY flag and wakeup anyone waiting for the
549  *      page.
550  *
551  */
552 void
553 vm_page_wakeup(vm_page_t m)
554 {
555
556         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
557         KASSERT(m->oflags & VPO_BUSY, ("vm_page_wakeup: page not busy!!!"));
558         m->oflags &= ~VPO_BUSY;
559         vm_page_flash(m);
560 }
561
562 void
563 vm_page_io_start(vm_page_t m)
564 {
565
566         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
567         m->busy++;
568 }
569
570 void
571 vm_page_io_finish(vm_page_t m)
572 {
573
574         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
575         KASSERT(m->busy > 0, ("vm_page_io_finish: page %p is not busy", m));
576         m->busy--;
577         if (m->busy == 0)
578                 vm_page_flash(m);
579 }
580
581 /*
582  * Keep page from being freed by the page daemon
583  * much of the same effect as wiring, except much lower
584  * overhead and should be used only for *very* temporary
585  * holding ("wiring").
586  */
587 void
588 vm_page_hold(vm_page_t mem)
589 {
590
591         vm_page_lock_assert(mem, MA_OWNED);
592         mem->hold_count++;
593 }
594
595 void
596 vm_page_unhold(vm_page_t mem)
597 {
598
599         vm_page_lock_assert(mem, MA_OWNED);
600         --mem->hold_count;
601         KASSERT(mem->hold_count >= 0, ("vm_page_unhold: hold count < 0!!!"));
602         if (mem->hold_count == 0 && mem->queue == PQ_HOLD)
603                 vm_page_free_toq(mem);
604 }
605
606 /*
607  *      vm_page_unhold_pages:
608  *
609  *      Unhold each of the pages that is referenced by the given array.
610  */ 
611 void
612 vm_page_unhold_pages(vm_page_t *ma, int count)
613 {
614         struct mtx *mtx, *new_mtx;
615
616         mtx = NULL;
617         for (; count != 0; count--) {
618                 /*
619                  * Avoid releasing and reacquiring the same page lock.
620                  */
621                 new_mtx = vm_page_lockptr(*ma);
622                 if (mtx != new_mtx) {
623                         if (mtx != NULL)
624                                 mtx_unlock(mtx);
625                         mtx = new_mtx;
626                         mtx_lock(mtx);
627                 }
628                 vm_page_unhold(*ma);
629                 ma++;
630         }
631         if (mtx != NULL)
632                 mtx_unlock(mtx);
633 }
634
635 vm_page_t
636 PHYS_TO_VM_PAGE(vm_paddr_t pa)
637 {
638         vm_page_t m;
639
640 #ifdef VM_PHYSSEG_SPARSE
641         m = vm_phys_paddr_to_vm_page(pa);
642         if (m == NULL)
643                 m = vm_phys_fictitious_to_vm_page(pa);
644         return (m);
645 #elif defined(VM_PHYSSEG_DENSE)
646         long pi;
647
648         pi = atop(pa);
649         if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
650                 m = &vm_page_array[pi - first_page];
651                 return (m);
652         }
653         return (vm_phys_fictitious_to_vm_page(pa));
654 #else
655 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
656 #endif
657 }
658
659 /*
660  *      vm_page_getfake:
661  *
662  *      Create a fictitious page with the specified physical address and
663  *      memory attribute.  The memory attribute is the only the machine-
664  *      dependent aspect of a fictitious page that must be initialized.
665  */
666 vm_page_t
667 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
668 {
669         vm_page_t m;
670
671         m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
672         vm_page_initfake(m, paddr, memattr);
673         return (m);
674 }
675
676 void
677 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
678 {
679
680         if ((m->flags & PG_FICTITIOUS) != 0) {
681                 /*
682                  * The page's memattr might have changed since the
683                  * previous initialization.  Update the pmap to the
684                  * new memattr.
685                  */
686                 goto memattr;
687         }
688         m->phys_addr = paddr;
689         m->queue = PQ_NONE;
690         /* Fictitious pages don't use "segind". */
691         m->flags = PG_FICTITIOUS;
692         /* Fictitious pages don't use "order" or "pool". */
693         m->oflags = VPO_BUSY | VPO_UNMANAGED;
694         m->wire_count = 1;
695 memattr:
696         pmap_page_set_memattr(m, memattr);
697 }
698
699 /*
700  *      vm_page_putfake:
701  *
702  *      Release a fictitious page.
703  */
704 void
705 vm_page_putfake(vm_page_t m)
706 {
707
708         KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
709         KASSERT((m->flags & PG_FICTITIOUS) != 0,
710             ("vm_page_putfake: bad page %p", m));
711         uma_zfree(fakepg_zone, m);
712 }
713
714 /*
715  *      vm_page_updatefake:
716  *
717  *      Update the given fictitious page to the specified physical address and
718  *      memory attribute.
719  */
720 void
721 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
722 {
723
724         KASSERT((m->flags & PG_FICTITIOUS) != 0,
725             ("vm_page_updatefake: bad page %p", m));
726         m->phys_addr = paddr;
727         pmap_page_set_memattr(m, memattr);
728 }
729
730 /*
731  *      vm_page_free:
732  *
733  *      Free a page.
734  */
735 void
736 vm_page_free(vm_page_t m)
737 {
738
739         m->flags &= ~PG_ZERO;
740         vm_page_free_toq(m);
741 }
742
743 /*
744  *      vm_page_free_zero:
745  *
746  *      Free a page to the zerod-pages queue
747  */
748 void
749 vm_page_free_zero(vm_page_t m)
750 {
751
752         m->flags |= PG_ZERO;
753         vm_page_free_toq(m);
754 }
755
756 /*
757  * Unbusy and handle the page queueing for a page from the VOP_GETPAGES()
758  * array which is not the request page.
759  */
760 void
761 vm_page_readahead_finish(vm_page_t m)
762 {
763
764         if (m->valid != 0) {
765                 /*
766                  * Since the page is not the requested page, whether
767                  * it should be activated or deactivated is not
768                  * obvious.  Empirical results have shown that
769                  * deactivating the page is usually the best choice,
770                  * unless the page is wanted by another thread.
771                  */
772                 if (m->oflags & VPO_WANTED) {
773                         vm_page_lock(m);
774                         vm_page_activate(m);
775                         vm_page_unlock(m);
776                 } else {
777                         vm_page_lock(m);
778                         vm_page_deactivate(m);
779                         vm_page_unlock(m);
780                 }
781                 vm_page_wakeup(m);
782         } else {
783                 /*
784                  * Free the completely invalid page.  Such page state
785                  * occurs due to the short read operation which did
786                  * not covered our page at all, or in case when a read
787                  * error happens.
788                  */
789                 vm_page_lock(m);
790                 vm_page_free(m);
791                 vm_page_unlock(m);
792         }
793 }
794
795 /*
796  *      vm_page_sleep:
797  *
798  *      Sleep and release the page and page queues locks.
799  *
800  *      The object containing the given page must be locked.
801  */
802 void
803 vm_page_sleep(vm_page_t m, const char *msg)
804 {
805
806         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
807         if (mtx_owned(&vm_page_queue_mtx))
808                 vm_page_unlock_queues();
809         if (mtx_owned(vm_page_lockptr(m)))
810                 vm_page_unlock(m);
811
812         /*
813          * It's possible that while we sleep, the page will get
814          * unbusied and freed.  If we are holding the object
815          * lock, we will assume we hold a reference to the object
816          * such that even if m->object changes, we can re-lock
817          * it.
818          */
819         m->oflags |= VPO_WANTED;
820         msleep(m, VM_OBJECT_MTX(m->object), PVM, msg, 0);
821 }
822
823 /*
824  *      vm_page_dirty:
825  *
826  *      Set all bits in the page's dirty field.
827  *
828  *      The object containing the specified page must be locked if the
829  *      call is made from the machine-independent layer.
830  *
831  *      See vm_page_clear_dirty_mask().
832  */
833 void
834 vm_page_dirty(vm_page_t m)
835 {
836
837         KASSERT((m->flags & PG_CACHED) == 0,
838             ("vm_page_dirty: page in cache!"));
839         KASSERT(!VM_PAGE_IS_FREE(m),
840             ("vm_page_dirty: page is free!"));
841         KASSERT(m->valid == VM_PAGE_BITS_ALL,
842             ("vm_page_dirty: page is invalid!"));
843         m->dirty = VM_PAGE_BITS_ALL;
844 }
845
846 /*
847  *      vm_page_splay:
848  *
849  *      Implements Sleator and Tarjan's top-down splay algorithm.  Returns
850  *      the vm_page containing the given pindex.  If, however, that
851  *      pindex is not found in the vm_object, returns a vm_page that is
852  *      adjacent to the pindex, coming before or after it.
853  */
854 vm_page_t
855 vm_page_splay(vm_pindex_t pindex, vm_page_t root)
856 {
857         struct vm_page dummy;
858         vm_page_t lefttreemax, righttreemin, y;
859
860         if (root == NULL)
861                 return (root);
862         lefttreemax = righttreemin = &dummy;
863         for (;; root = y) {
864                 if (pindex < root->pindex) {
865                         if ((y = root->left) == NULL)
866                                 break;
867                         if (pindex < y->pindex) {
868                                 /* Rotate right. */
869                                 root->left = y->right;
870                                 y->right = root;
871                                 root = y;
872                                 if ((y = root->left) == NULL)
873                                         break;
874                         }
875                         /* Link into the new root's right tree. */
876                         righttreemin->left = root;
877                         righttreemin = root;
878                 } else if (pindex > root->pindex) {
879                         if ((y = root->right) == NULL)
880                                 break;
881                         if (pindex > y->pindex) {
882                                 /* Rotate left. */
883                                 root->right = y->left;
884                                 y->left = root;
885                                 root = y;
886                                 if ((y = root->right) == NULL)
887                                         break;
888                         }
889                         /* Link into the new root's left tree. */
890                         lefttreemax->right = root;
891                         lefttreemax = root;
892                 } else
893                         break;
894         }
895         /* Assemble the new root. */
896         lefttreemax->right = root->left;
897         righttreemin->left = root->right;
898         root->left = dummy.right;
899         root->right = dummy.left;
900         return (root);
901 }
902
903 /*
904  *      vm_page_insert:         [ internal use only ]
905  *
906  *      Inserts the given mem entry into the object and object list.
907  *
908  *      The pagetables are not updated but will presumably fault the page
909  *      in if necessary, or if a kernel page the caller will at some point
910  *      enter the page into the kernel's pmap.  We are not allowed to block
911  *      here so we *can't* do this anyway.
912  *
913  *      The object and page must be locked.
914  *      This routine may not block.
915  */
916 void
917 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
918 {
919         vm_page_t root;
920
921         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
922         if (m->object != NULL)
923                 panic("vm_page_insert: page already inserted");
924
925         /*
926          * Record the object/offset pair in this page
927          */
928         m->object = object;
929         m->pindex = pindex;
930
931         /*
932          * Now link into the object's ordered list of backed pages.
933          */
934         root = object->root;
935         if (root == NULL) {
936                 m->left = NULL;
937                 m->right = NULL;
938                 TAILQ_INSERT_TAIL(&object->memq, m, listq);
939         } else {
940                 root = vm_page_splay(pindex, root);
941                 if (pindex < root->pindex) {
942                         m->left = root->left;
943                         m->right = root;
944                         root->left = NULL;
945                         TAILQ_INSERT_BEFORE(root, m, listq);
946                 } else if (pindex == root->pindex)
947                         panic("vm_page_insert: offset already allocated");
948                 else {
949                         m->right = root->right;
950                         m->left = root;
951                         root->right = NULL;
952                         TAILQ_INSERT_AFTER(&object->memq, root, m, listq);
953                 }
954         }
955         object->root = m;
956
957         /*
958          * show that the object has one more resident page.
959          */
960         object->resident_page_count++;
961         /*
962          * Hold the vnode until the last page is released.
963          */
964         if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
965                 vhold((struct vnode *)object->handle);
966
967         /*
968          * Since we are inserting a new and possibly dirty page,
969          * update the object's OBJ_MIGHTBEDIRTY flag.
970          */
971         if (m->aflags & PGA_WRITEABLE)
972                 vm_object_set_writeable_dirty(object);
973 }
974
975 /*
976  *      vm_page_remove:
977  *                              NOTE: used by device pager as well -wfj
978  *
979  *      Removes the given mem entry from the object/offset-page
980  *      table and the object page list, but do not invalidate/terminate
981  *      the backing store.
982  *
983  *      The object and page must be locked.
984  *      The underlying pmap entry (if any) is NOT removed here.
985  *      This routine may not block.
986  */
987 void
988 vm_page_remove(vm_page_t m)
989 {
990         vm_object_t object;
991         vm_page_t next, prev, root;
992
993         if ((m->oflags & VPO_UNMANAGED) == 0)
994                 vm_page_lock_assert(m, MA_OWNED);
995         if ((object = m->object) == NULL)
996                 return;
997         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
998         if (m->oflags & VPO_BUSY) {
999                 m->oflags &= ~VPO_BUSY;
1000                 vm_page_flash(m);
1001         }
1002
1003         /*
1004          * Now remove from the object's list of backed pages.
1005          */
1006         if ((next = TAILQ_NEXT(m, listq)) != NULL && next->left == m) {
1007                 /*
1008                  * Since the page's successor in the list is also its parent
1009                  * in the tree, its right subtree must be empty.
1010                  */
1011                 next->left = m->left;
1012                 KASSERT(m->right == NULL,
1013                     ("vm_page_remove: page %p has right child", m));
1014         } else if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
1015             prev->right == m) {
1016                 /*
1017                  * Since the page's predecessor in the list is also its parent
1018                  * in the tree, its left subtree must be empty.
1019                  */
1020                 KASSERT(m->left == NULL,
1021                     ("vm_page_remove: page %p has left child", m));
1022                 prev->right = m->right;
1023         } else {
1024                 if (m != object->root)
1025                         vm_page_splay(m->pindex, object->root);
1026                 if (m->left == NULL)
1027                         root = m->right;
1028                 else if (m->right == NULL)
1029                         root = m->left;
1030                 else {
1031                         /*
1032                          * Move the page's successor to the root, because
1033                          * pages are usually removed in ascending order.
1034                          */
1035                         if (m->right != next)
1036                                 vm_page_splay(m->pindex, m->right);
1037                         next->left = m->left;
1038                         root = next;
1039                 }
1040                 object->root = root;
1041         }
1042         TAILQ_REMOVE(&object->memq, m, listq);
1043
1044         /*
1045          * And show that the object has one fewer resident page.
1046          */
1047         object->resident_page_count--;
1048         /*
1049          * The vnode may now be recycled.
1050          */
1051         if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1052                 vdrop((struct vnode *)object->handle);
1053
1054         m->object = NULL;
1055 }
1056
1057 /*
1058  *      vm_page_lookup:
1059  *
1060  *      Returns the page associated with the object/offset
1061  *      pair specified; if none is found, NULL is returned.
1062  *
1063  *      The object must be locked.
1064  *      This routine may not block.
1065  *      This is a critical path routine
1066  */
1067 vm_page_t
1068 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1069 {
1070         vm_page_t m;
1071
1072         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1073         if ((m = object->root) != NULL && m->pindex != pindex) {
1074                 m = vm_page_splay(pindex, m);
1075                 if ((object->root = m)->pindex != pindex)
1076                         m = NULL;
1077         }
1078         return (m);
1079 }
1080
1081 /*
1082  *      vm_page_find_least:
1083  *
1084  *      Returns the page associated with the object with least pindex
1085  *      greater than or equal to the parameter pindex, or NULL.
1086  *
1087  *      The object must be locked.
1088  *      The routine may not block.
1089  */
1090 vm_page_t
1091 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1092 {
1093         vm_page_t m;
1094
1095         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1096         if ((m = TAILQ_FIRST(&object->memq)) != NULL) {
1097                 if (m->pindex < pindex) {
1098                         m = vm_page_splay(pindex, object->root);
1099                         if ((object->root = m)->pindex < pindex)
1100                                 m = TAILQ_NEXT(m, listq);
1101                 }
1102         }
1103         return (m);
1104 }
1105
1106 /*
1107  * Returns the given page's successor (by pindex) within the object if it is
1108  * resident; if none is found, NULL is returned.
1109  *
1110  * The object must be locked.
1111  */
1112 vm_page_t
1113 vm_page_next(vm_page_t m)
1114 {
1115         vm_page_t next;
1116
1117         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1118         if ((next = TAILQ_NEXT(m, listq)) != NULL &&
1119             next->pindex != m->pindex + 1)
1120                 next = NULL;
1121         return (next);
1122 }
1123
1124 /*
1125  * Returns the given page's predecessor (by pindex) within the object if it is
1126  * resident; if none is found, NULL is returned.
1127  *
1128  * The object must be locked.
1129  */
1130 vm_page_t
1131 vm_page_prev(vm_page_t m)
1132 {
1133         vm_page_t prev;
1134
1135         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1136         if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
1137             prev->pindex != m->pindex - 1)
1138                 prev = NULL;
1139         return (prev);
1140 }
1141
1142 /*
1143  *      vm_page_rename:
1144  *
1145  *      Move the given memory entry from its
1146  *      current object to the specified target object/offset.
1147  *
1148  *      The object must be locked.
1149  *      This routine may not block.
1150  *
1151  *      Note: swap associated with the page must be invalidated by the move.  We
1152  *            have to do this for several reasons:  (1) we aren't freeing the
1153  *            page, (2) we are dirtying the page, (3) the VM system is probably
1154  *            moving the page from object A to B, and will then later move
1155  *            the backing store from A to B and we can't have a conflict.
1156  *
1157  *      Note: we *always* dirty the page.  It is necessary both for the
1158  *            fact that we moved it, and because we may be invalidating
1159  *            swap.  If the page is on the cache, we have to deactivate it
1160  *            or vm_page_dirty() will panic.  Dirty pages are not allowed
1161  *            on the cache.
1162  */
1163 void
1164 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1165 {
1166
1167         vm_page_remove(m);
1168         vm_page_insert(m, new_object, new_pindex);
1169         vm_page_dirty(m);
1170 }
1171
1172 /*
1173  *      Convert all of the given object's cached pages that have a
1174  *      pindex within the given range into free pages.  If the value
1175  *      zero is given for "end", then the range's upper bound is
1176  *      infinity.  If the given object is backed by a vnode and it
1177  *      transitions from having one or more cached pages to none, the
1178  *      vnode's hold count is reduced. 
1179  */
1180 void
1181 vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1182 {
1183         vm_page_t m, m_next;
1184         boolean_t empty;
1185
1186         mtx_lock(&vm_page_queue_free_mtx);
1187         if (__predict_false(object->cache == NULL)) {
1188                 mtx_unlock(&vm_page_queue_free_mtx);
1189                 return;
1190         }
1191         m = object->cache = vm_page_splay(start, object->cache);
1192         if (m->pindex < start) {
1193                 if (m->right == NULL)
1194                         m = NULL;
1195                 else {
1196                         m_next = vm_page_splay(start, m->right);
1197                         m_next->left = m;
1198                         m->right = NULL;
1199                         m = object->cache = m_next;
1200                 }
1201         }
1202
1203         /*
1204          * At this point, "m" is either (1) a reference to the page
1205          * with the least pindex that is greater than or equal to
1206          * "start" or (2) NULL.
1207          */
1208         for (; m != NULL && (m->pindex < end || end == 0); m = m_next) {
1209                 /*
1210                  * Find "m"'s successor and remove "m" from the
1211                  * object's cache.
1212                  */
1213                 if (m->right == NULL) {
1214                         object->cache = m->left;
1215                         m_next = NULL;
1216                 } else {
1217                         m_next = vm_page_splay(start, m->right);
1218                         m_next->left = m->left;
1219                         object->cache = m_next;
1220                 }
1221                 /* Convert "m" to a free page. */
1222                 m->object = NULL;
1223                 m->valid = 0;
1224                 /* Clear PG_CACHED and set PG_FREE. */
1225                 m->flags ^= PG_CACHED | PG_FREE;
1226                 KASSERT((m->flags & (PG_CACHED | PG_FREE)) == PG_FREE,
1227                     ("vm_page_cache_free: page %p has inconsistent flags", m));
1228                 cnt.v_cache_count--;
1229                 cnt.v_free_count++;
1230         }
1231         empty = object->cache == NULL;
1232         mtx_unlock(&vm_page_queue_free_mtx);
1233         if (object->type == OBJT_VNODE && empty)
1234                 vdrop(object->handle);
1235 }
1236
1237 /*
1238  *      Returns the cached page that is associated with the given
1239  *      object and offset.  If, however, none exists, returns NULL.
1240  *
1241  *      The free page queue must be locked.
1242  */
1243 static inline vm_page_t
1244 vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1245 {
1246         vm_page_t m;
1247
1248         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1249         if ((m = object->cache) != NULL && m->pindex != pindex) {
1250                 m = vm_page_splay(pindex, m);
1251                 if ((object->cache = m)->pindex != pindex)
1252                         m = NULL;
1253         }
1254         return (m);
1255 }
1256
1257 /*
1258  *      Remove the given cached page from its containing object's
1259  *      collection of cached pages.
1260  *
1261  *      The free page queue must be locked.
1262  */
1263 void
1264 vm_page_cache_remove(vm_page_t m)
1265 {
1266         vm_object_t object;
1267         vm_page_t root;
1268
1269         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1270         KASSERT((m->flags & PG_CACHED) != 0,
1271             ("vm_page_cache_remove: page %p is not cached", m));
1272         object = m->object;
1273         if (m != object->cache) {
1274                 root = vm_page_splay(m->pindex, object->cache);
1275                 KASSERT(root == m,
1276                     ("vm_page_cache_remove: page %p is not cached in object %p",
1277                     m, object));
1278         }
1279         if (m->left == NULL)
1280                 root = m->right;
1281         else if (m->right == NULL)
1282                 root = m->left;
1283         else {
1284                 root = vm_page_splay(m->pindex, m->left);
1285                 root->right = m->right;
1286         }
1287         object->cache = root;
1288         m->object = NULL;
1289         cnt.v_cache_count--;
1290 }
1291
1292 /*
1293  *      Transfer all of the cached pages with offset greater than or
1294  *      equal to 'offidxstart' from the original object's cache to the
1295  *      new object's cache.  However, any cached pages with offset
1296  *      greater than or equal to the new object's size are kept in the
1297  *      original object.  Initially, the new object's cache must be
1298  *      empty.  Offset 'offidxstart' in the original object must
1299  *      correspond to offset zero in the new object.
1300  *
1301  *      The new object must be locked.
1302  */
1303 void
1304 vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1305     vm_object_t new_object)
1306 {
1307         vm_page_t m, m_next;
1308
1309         /*
1310          * Insertion into an object's collection of cached pages
1311          * requires the object to be locked.  In contrast, removal does
1312          * not.
1313          */
1314         VM_OBJECT_LOCK_ASSERT(new_object, MA_OWNED);
1315         KASSERT(new_object->cache == NULL,
1316             ("vm_page_cache_transfer: object %p has cached pages",
1317             new_object));
1318         mtx_lock(&vm_page_queue_free_mtx);
1319         if ((m = orig_object->cache) != NULL) {
1320                 /*
1321                  * Transfer all of the pages with offset greater than or
1322                  * equal to 'offidxstart' from the original object's
1323                  * cache to the new object's cache.
1324                  */
1325                 m = vm_page_splay(offidxstart, m);
1326                 if (m->pindex < offidxstart) {
1327                         orig_object->cache = m;
1328                         new_object->cache = m->right;
1329                         m->right = NULL;
1330                 } else {
1331                         orig_object->cache = m->left;
1332                         new_object->cache = m;
1333                         m->left = NULL;
1334                 }
1335                 while ((m = new_object->cache) != NULL) {
1336                         if ((m->pindex - offidxstart) >= new_object->size) {
1337                                 /*
1338                                  * Return all of the cached pages with
1339                                  * offset greater than or equal to the
1340                                  * new object's size to the original
1341                                  * object's cache. 
1342                                  */
1343                                 new_object->cache = m->left;
1344                                 m->left = orig_object->cache;
1345                                 orig_object->cache = m;
1346                                 break;
1347                         }
1348                         m_next = vm_page_splay(m->pindex, m->right);
1349                         /* Update the page's object and offset. */
1350                         m->object = new_object;
1351                         m->pindex -= offidxstart;
1352                         if (m_next == NULL)
1353                                 break;
1354                         m->right = NULL;
1355                         m_next->left = m;
1356                         new_object->cache = m_next;
1357                 }
1358                 KASSERT(new_object->cache == NULL ||
1359                     new_object->type == OBJT_SWAP,
1360                     ("vm_page_cache_transfer: object %p's type is incompatible"
1361                     " with cached pages", new_object));
1362         }
1363         mtx_unlock(&vm_page_queue_free_mtx);
1364 }
1365
1366 /*
1367  *      Returns TRUE if a cached page is associated with the given object and
1368  *      offset, and FALSE otherwise.
1369  *
1370  *      The object must be locked.
1371  */
1372 boolean_t
1373 vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
1374 {
1375         vm_page_t m;
1376
1377         /*
1378          * Insertion into an object's collection of cached pages requires the
1379          * object to be locked.  Therefore, if the object is locked and the
1380          * object's collection is empty, there is no need to acquire the free
1381          * page queues lock in order to prove that the specified page doesn't
1382          * exist.
1383          */
1384         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1385         if (object->cache == NULL)
1386                 return (FALSE);
1387         mtx_lock(&vm_page_queue_free_mtx);
1388         m = vm_page_cache_lookup(object, pindex);
1389         mtx_unlock(&vm_page_queue_free_mtx);
1390         return (m != NULL);
1391 }
1392
1393 /*
1394  *      vm_page_alloc:
1395  *
1396  *      Allocate and return a memory cell associated
1397  *      with this VM object/offset pair.
1398  *
1399  *      The caller must always specify an allocation class.
1400  *
1401  *      allocation classes:
1402  *      VM_ALLOC_NORMAL         normal process request
1403  *      VM_ALLOC_SYSTEM         system *really* needs a page
1404  *      VM_ALLOC_INTERRUPT      interrupt time request
1405  *
1406  *      optional allocation flags:
1407  *      VM_ALLOC_ZERO           prefer a zeroed page
1408  *      VM_ALLOC_WIRED          wire the allocated page
1409  *      VM_ALLOC_NOOBJ          page is not associated with a vm object
1410  *      VM_ALLOC_NOBUSY         do not set the page busy
1411  *      VM_ALLOC_IFCACHED       return page only if it is cached
1412  *      VM_ALLOC_IFNOTCACHED    return NULL, do not reactivate if the page
1413  *                              is cached
1414  *
1415  *      This routine may not sleep.
1416  */
1417 vm_page_t
1418 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1419 {
1420         struct vnode *vp = NULL;
1421         vm_object_t m_object;
1422         vm_page_t m;
1423         int flags, page_req;
1424
1425         if ((req & VM_ALLOC_NOOBJ) == 0) {
1426                 KASSERT(object != NULL,
1427                     ("vm_page_alloc: NULL object."));
1428                 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1429         }
1430
1431         page_req = req & VM_ALLOC_CLASS_MASK;
1432
1433         /*
1434          * The pager is allowed to eat deeper into the free page list.
1435          */
1436         if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT))
1437                 page_req = VM_ALLOC_SYSTEM;
1438
1439         mtx_lock(&vm_page_queue_free_mtx);
1440         if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1441             (page_req == VM_ALLOC_SYSTEM && 
1442             cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1443             (page_req == VM_ALLOC_INTERRUPT &&
1444             cnt.v_free_count + cnt.v_cache_count > 0)) {
1445                 /*
1446                  * Allocate from the free queue if the number of free pages
1447                  * exceeds the minimum for the request class.
1448                  */
1449                 if (object != NULL &&
1450                     (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1451                         if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1452                                 mtx_unlock(&vm_page_queue_free_mtx);
1453                                 return (NULL);
1454                         }
1455                         if (vm_phys_unfree_page(m))
1456                                 vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1457 #if VM_NRESERVLEVEL > 0
1458                         else if (!vm_reserv_reactivate_page(m))
1459 #else
1460                         else
1461 #endif
1462                                 panic("vm_page_alloc: cache page %p is missing"
1463                                     " from the free queue", m);
1464                 } else if ((req & VM_ALLOC_IFCACHED) != 0) {
1465                         mtx_unlock(&vm_page_queue_free_mtx);
1466                         return (NULL);
1467 #if VM_NRESERVLEVEL > 0
1468                 } else if (object == NULL || object->type == OBJT_DEVICE ||
1469                     object->type == OBJT_SG ||
1470                     (object->flags & OBJ_COLORED) == 0 ||
1471                     (m = vm_reserv_alloc_page(object, pindex)) == NULL) {
1472 #else
1473                 } else {
1474 #endif
1475                         m = vm_phys_alloc_pages(object != NULL ?
1476                             VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1477 #if VM_NRESERVLEVEL > 0
1478                         if (m == NULL && vm_reserv_reclaim_inactive()) {
1479                                 m = vm_phys_alloc_pages(object != NULL ?
1480                                     VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1481                                     0);
1482                         }
1483 #endif
1484                 }
1485         } else {
1486                 /*
1487                  * Not allocatable, give up.
1488                  */
1489                 mtx_unlock(&vm_page_queue_free_mtx);
1490                 atomic_add_int(&vm_pageout_deficit,
1491                     MAX((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1492                 pagedaemon_wakeup();
1493                 return (NULL);
1494         }
1495
1496         /*
1497          *  At this point we had better have found a good page.
1498          */
1499
1500         KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1501         KASSERT(m->queue == PQ_NONE,
1502             ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1503         KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1504         KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1505         KASSERT(m->busy == 0, ("vm_page_alloc: page %p is busy", m));
1506         KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1507         KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1508             ("vm_page_alloc: page %p has unexpected memattr %d", m,
1509             pmap_page_get_memattr(m)));
1510         if ((m->flags & PG_CACHED) != 0) {
1511                 KASSERT(m->valid != 0,
1512                     ("vm_page_alloc: cached page %p is invalid", m));
1513                 if (m->object == object && m->pindex == pindex)
1514                         cnt.v_reactivated++;
1515                 else
1516                         m->valid = 0;
1517                 m_object = m->object;
1518                 vm_page_cache_remove(m);
1519                 if (m_object->type == OBJT_VNODE && m_object->cache == NULL)
1520                         vp = m_object->handle;
1521         } else {
1522                 KASSERT(VM_PAGE_IS_FREE(m),
1523                     ("vm_page_alloc: page %p is not free", m));
1524                 KASSERT(m->valid == 0,
1525                     ("vm_page_alloc: free page %p is valid", m));
1526                 cnt.v_free_count--;
1527         }
1528
1529         /*
1530          * Only the PG_ZERO flag is inherited.  The PG_CACHED or PG_FREE flag
1531          * must be cleared before the free page queues lock is released.
1532          */
1533         flags = 0;
1534         if (req & VM_ALLOC_NODUMP)
1535                 flags |= PG_NODUMP;
1536         if (m->flags & PG_ZERO) {
1537                 vm_page_zero_count--;
1538                 if (req & VM_ALLOC_ZERO)
1539                         flags = PG_ZERO;
1540         }
1541         m->flags = flags;
1542         mtx_unlock(&vm_page_queue_free_mtx);
1543         m->aflags = 0;
1544         if (object == NULL || object->type == OBJT_PHYS)
1545                 m->oflags = VPO_UNMANAGED;
1546         else
1547                 m->oflags = 0;
1548         if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ)) == 0)
1549                 m->oflags |= VPO_BUSY;
1550         if (req & VM_ALLOC_WIRED) {
1551                 /*
1552                  * The page lock is not required for wiring a page until that
1553                  * page is inserted into the object.
1554                  */
1555                 atomic_add_int(&cnt.v_wire_count, 1);
1556                 m->wire_count = 1;
1557         }
1558         m->act_count = 0;
1559
1560         if (object != NULL) {
1561                 /* Ignore device objects; the pager sets "memattr" for them. */
1562                 if (object->memattr != VM_MEMATTR_DEFAULT &&
1563                     object->type != OBJT_DEVICE && object->type != OBJT_SG)
1564                         pmap_page_set_memattr(m, object->memattr);
1565                 vm_page_insert(m, object, pindex);
1566         } else
1567                 m->pindex = pindex;
1568
1569         /*
1570          * The following call to vdrop() must come after the above call
1571          * to vm_page_insert() in case both affect the same object and
1572          * vnode.  Otherwise, the affected vnode's hold count could
1573          * temporarily become zero.
1574          */
1575         if (vp != NULL)
1576                 vdrop(vp);
1577
1578         /*
1579          * Don't wakeup too often - wakeup the pageout daemon when
1580          * we would be nearly out of memory.
1581          */
1582         if (vm_paging_needed())
1583                 pagedaemon_wakeup();
1584
1585         return (m);
1586 }
1587
1588 /*
1589  * Initialize a page that has been freshly dequeued from a freelist.
1590  * The caller has to drop the vnode returned, if it is not NULL.
1591  *
1592  * To be called with vm_page_queue_free_mtx held.
1593  */
1594 struct vnode *
1595 vm_page_alloc_init(vm_page_t m)
1596 {
1597         struct vnode *drop;
1598         vm_object_t m_object;
1599
1600         KASSERT(m->queue == PQ_NONE,
1601             ("vm_page_alloc_init: page %p has unexpected queue %d",
1602             m, m->queue));
1603         KASSERT(m->wire_count == 0,
1604             ("vm_page_alloc_init: page %p is wired", m));
1605         KASSERT(m->hold_count == 0,
1606             ("vm_page_alloc_init: page %p is held", m));
1607         KASSERT(m->busy == 0,
1608             ("vm_page_alloc_init: page %p is busy", m));
1609         KASSERT(m->dirty == 0,
1610             ("vm_page_alloc_init: page %p is dirty", m));
1611         KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1612             ("vm_page_alloc_init: page %p has unexpected memattr %d",
1613             m, pmap_page_get_memattr(m)));
1614         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1615         drop = NULL;
1616         if ((m->flags & PG_CACHED) != 0) {
1617                 m->valid = 0;
1618                 m_object = m->object;
1619                 vm_page_cache_remove(m);
1620                 if (m_object->type == OBJT_VNODE &&
1621                     m_object->cache == NULL)
1622                         drop = m_object->handle;
1623         } else {
1624                 KASSERT(VM_PAGE_IS_FREE(m),
1625                     ("vm_page_alloc_init: page %p is not free", m));
1626                 KASSERT(m->valid == 0,
1627                     ("vm_page_alloc_init: free page %p is valid", m));
1628                 cnt.v_free_count--;
1629         }
1630         if (m->flags & PG_ZERO)
1631                 vm_page_zero_count--;
1632         /* Don't clear the PG_ZERO flag; we'll need it later. */
1633         m->flags &= PG_ZERO;
1634         m->aflags = 0;
1635         m->oflags = VPO_UNMANAGED;
1636         /* Unmanaged pages don't use "act_count". */
1637         return (drop);
1638 }
1639
1640 /*
1641  *      vm_page_alloc_freelist:
1642  * 
1643  *      Allocate a page from the specified freelist.
1644  *      Only the ALLOC_CLASS values in req are honored, other request flags
1645  *      are ignored.
1646  */
1647 vm_page_t
1648 vm_page_alloc_freelist(int flind, int req)
1649 {
1650         struct vnode *drop;
1651         vm_page_t m;
1652         int page_req;
1653
1654         m = NULL;
1655         page_req = req & VM_ALLOC_CLASS_MASK;
1656         mtx_lock(&vm_page_queue_free_mtx);
1657         /*
1658          * Do not allocate reserved pages unless the req has asked for it.
1659          */
1660         if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1661             (page_req == VM_ALLOC_SYSTEM && 
1662             cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1663             (page_req == VM_ALLOC_INTERRUPT &&
1664             cnt.v_free_count + cnt.v_cache_count > 0)) {
1665                 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1666         }
1667         if (m == NULL) {
1668                 mtx_unlock(&vm_page_queue_free_mtx);
1669                 return (NULL);
1670         }
1671         drop = vm_page_alloc_init(m);
1672         mtx_unlock(&vm_page_queue_free_mtx);
1673         if (drop)
1674                 vdrop(drop);
1675         return (m);
1676 }
1677
1678 /*
1679  *      vm_wait:        (also see VM_WAIT macro)
1680  *
1681  *      Block until free pages are available for allocation
1682  *      - Called in various places before memory allocations.
1683  */
1684 void
1685 vm_wait(void)
1686 {
1687
1688         mtx_lock(&vm_page_queue_free_mtx);
1689         if (curproc == pageproc) {
1690                 vm_pageout_pages_needed = 1;
1691                 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
1692                     PDROP | PSWP, "VMWait", 0);
1693         } else {
1694                 if (!vm_pages_needed) {
1695                         vm_pages_needed = 1;
1696                         wakeup(&vm_pages_needed);
1697                 }
1698                 msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
1699                     "vmwait", 0);
1700         }
1701 }
1702
1703 /*
1704  *      vm_waitpfault:  (also see VM_WAITPFAULT macro)
1705  *
1706  *      Block until free pages are available for allocation
1707  *      - Called only in vm_fault so that processes page faulting
1708  *        can be easily tracked.
1709  *      - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
1710  *        processes will be able to grab memory first.  Do not change
1711  *        this balance without careful testing first.
1712  */
1713 void
1714 vm_waitpfault(void)
1715 {
1716
1717         mtx_lock(&vm_page_queue_free_mtx);
1718         if (!vm_pages_needed) {
1719                 vm_pages_needed = 1;
1720                 wakeup(&vm_pages_needed);
1721         }
1722         msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
1723             "pfault", 0);
1724 }
1725
1726 /*
1727  *      vm_page_requeue:
1728  *
1729  *      Move the given page to the tail of its present page queue.
1730  *
1731  *      The page queues must be locked.
1732  */
1733 void
1734 vm_page_requeue(vm_page_t m)
1735 {
1736         struct vpgqueues *vpq;
1737         int queue;
1738
1739         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1740         queue = m->queue;
1741         KASSERT(queue != PQ_NONE,
1742             ("vm_page_requeue: page %p is not queued", m));
1743         vpq = &vm_page_queues[queue];
1744         TAILQ_REMOVE(&vpq->pl, m, pageq);
1745         TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
1746 }
1747
1748 /*
1749  *      vm_page_queue_remove:
1750  *
1751  *      Remove the given page from the specified queue.
1752  *
1753  *      The page and page queues must be locked.
1754  */
1755 static __inline void
1756 vm_page_queue_remove(int queue, vm_page_t m)
1757 {
1758         struct vpgqueues *pq;
1759
1760         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1761         vm_page_lock_assert(m, MA_OWNED);
1762         pq = &vm_page_queues[queue];
1763         TAILQ_REMOVE(&pq->pl, m, pageq);
1764         (*pq->cnt)--;
1765 }
1766
1767 /*
1768  *      vm_pageq_remove:
1769  *
1770  *      Remove a page from its queue.
1771  *
1772  *      The given page must be locked.
1773  *      This routine may not block.
1774  */
1775 void
1776 vm_pageq_remove(vm_page_t m)
1777 {
1778         int queue;
1779
1780         vm_page_lock_assert(m, MA_OWNED);
1781         if ((queue = m->queue) != PQ_NONE) {
1782                 vm_page_lock_queues();
1783                 m->queue = PQ_NONE;
1784                 vm_page_queue_remove(queue, m);
1785                 vm_page_unlock_queues();
1786         }
1787 }
1788
1789 /*
1790  *      vm_page_enqueue:
1791  *
1792  *      Add the given page to the specified queue.
1793  *
1794  *      The page queues must be locked.
1795  */
1796 static void
1797 vm_page_enqueue(int queue, vm_page_t m)
1798 {
1799         struct vpgqueues *vpq;
1800
1801         vpq = &vm_page_queues[queue];
1802         m->queue = queue;
1803         TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
1804         ++*vpq->cnt;
1805 }
1806
1807 /*
1808  *      vm_page_activate:
1809  *
1810  *      Put the specified page on the active list (if appropriate).
1811  *      Ensure that act_count is at least ACT_INIT but do not otherwise
1812  *      mess with it.
1813  *
1814  *      The page must be locked.
1815  *      This routine may not block.
1816  */
1817 void
1818 vm_page_activate(vm_page_t m)
1819 {
1820         int queue;
1821
1822         vm_page_lock_assert(m, MA_OWNED);
1823         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1824         if ((queue = m->queue) != PQ_ACTIVE) {
1825                 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
1826                         if (m->act_count < ACT_INIT)
1827                                 m->act_count = ACT_INIT;
1828                         vm_page_lock_queues();
1829                         if (queue != PQ_NONE)
1830                                 vm_page_queue_remove(queue, m);
1831                         vm_page_enqueue(PQ_ACTIVE, m);
1832                         vm_page_unlock_queues();
1833                 } else
1834                         KASSERT(queue == PQ_NONE,
1835                             ("vm_page_activate: wired page %p is queued", m));
1836         } else {
1837                 if (m->act_count < ACT_INIT)
1838                         m->act_count = ACT_INIT;
1839         }
1840 }
1841
1842 /*
1843  *      vm_page_free_wakeup:
1844  *
1845  *      Helper routine for vm_page_free_toq() and vm_page_cache().  This
1846  *      routine is called when a page has been added to the cache or free
1847  *      queues.
1848  *
1849  *      The page queues must be locked.
1850  *      This routine may not block.
1851  */
1852 static inline void
1853 vm_page_free_wakeup(void)
1854 {
1855
1856         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1857         /*
1858          * if pageout daemon needs pages, then tell it that there are
1859          * some free.
1860          */
1861         if (vm_pageout_pages_needed &&
1862             cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
1863                 wakeup(&vm_pageout_pages_needed);
1864                 vm_pageout_pages_needed = 0;
1865         }
1866         /*
1867          * wakeup processes that are waiting on memory if we hit a
1868          * high water mark. And wakeup scheduler process if we have
1869          * lots of memory. this process will swapin processes.
1870          */
1871         if (vm_pages_needed && !vm_page_count_min()) {
1872                 vm_pages_needed = 0;
1873                 wakeup(&cnt.v_free_count);
1874         }
1875 }
1876
1877 /*
1878  *      vm_page_free_toq:
1879  *
1880  *      Returns the given page to the free list,
1881  *      disassociating it with any VM object.
1882  *
1883  *      Object and page must be locked prior to entry.
1884  *      This routine may not block.
1885  */
1886
1887 void
1888 vm_page_free_toq(vm_page_t m)
1889 {
1890
1891         if ((m->oflags & VPO_UNMANAGED) == 0) {
1892                 vm_page_lock_assert(m, MA_OWNED);
1893                 KASSERT(!pmap_page_is_mapped(m),
1894                     ("vm_page_free_toq: freeing mapped page %p", m));
1895         }
1896         PCPU_INC(cnt.v_tfree);
1897
1898         if (VM_PAGE_IS_FREE(m))
1899                 panic("vm_page_free: freeing free page %p", m);
1900         else if (m->busy != 0)
1901                 panic("vm_page_free: freeing busy page %p", m);
1902
1903         /*
1904          * unqueue, then remove page.  Note that we cannot destroy
1905          * the page here because we do not want to call the pager's
1906          * callback routine until after we've put the page on the
1907          * appropriate free queue.
1908          */
1909         if ((m->oflags & VPO_UNMANAGED) == 0)
1910                 vm_pageq_remove(m);
1911         vm_page_remove(m);
1912
1913         /*
1914          * If fictitious remove object association and
1915          * return, otherwise delay object association removal.
1916          */
1917         if ((m->flags & PG_FICTITIOUS) != 0) {
1918                 return;
1919         }
1920
1921         m->valid = 0;
1922         vm_page_undirty(m);
1923
1924         if (m->wire_count != 0)
1925                 panic("vm_page_free: freeing wired page %p", m);
1926         if (m->hold_count != 0) {
1927                 m->flags &= ~PG_ZERO;
1928                 vm_page_lock_queues();
1929                 vm_page_enqueue(PQ_HOLD, m);
1930                 vm_page_unlock_queues();
1931         } else {
1932                 /*
1933                  * Restore the default memory attribute to the page.
1934                  */
1935                 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
1936                         pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
1937
1938                 /*
1939                  * Insert the page into the physical memory allocator's
1940                  * cache/free page queues.
1941                  */
1942                 mtx_lock(&vm_page_queue_free_mtx);
1943                 m->flags |= PG_FREE;
1944                 cnt.v_free_count++;
1945 #if VM_NRESERVLEVEL > 0
1946                 if (!vm_reserv_free_page(m))
1947 #else
1948                 if (TRUE)
1949 #endif
1950                         vm_phys_free_pages(m, 0);
1951                 if ((m->flags & PG_ZERO) != 0)
1952                         ++vm_page_zero_count;
1953                 else
1954                         vm_page_zero_idle_wakeup();
1955                 vm_page_free_wakeup();
1956                 mtx_unlock(&vm_page_queue_free_mtx);
1957         }
1958 }
1959
1960 /*
1961  *      vm_page_wire:
1962  *
1963  *      Mark this page as wired down by yet
1964  *      another map, removing it from paging queues
1965  *      as necessary.
1966  *
1967  *      If the page is fictitious, then its wire count must remain one.
1968  *
1969  *      The page must be locked.
1970  *      This routine may not block.
1971  */
1972 void
1973 vm_page_wire(vm_page_t m)
1974 {
1975
1976         /*
1977          * Only bump the wire statistics if the page is not already wired,
1978          * and only unqueue the page if it is on some queue (if it is unmanaged
1979          * it is already off the queues).
1980          */
1981         vm_page_lock_assert(m, MA_OWNED);
1982         if ((m->flags & PG_FICTITIOUS) != 0) {
1983                 KASSERT(m->wire_count == 1,
1984                     ("vm_page_wire: fictitious page %p's wire count isn't one",
1985                     m));
1986                 return;
1987         }
1988         if (m->wire_count == 0) {
1989                 if ((m->oflags & VPO_UNMANAGED) == 0)
1990                         vm_pageq_remove(m);
1991                 atomic_add_int(&cnt.v_wire_count, 1);
1992         }
1993         m->wire_count++;
1994         KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1995 }
1996
1997 /*
1998  * vm_page_unwire:
1999  *
2000  * Release one wiring of the specified page, potentially enabling it to be
2001  * paged again.  If paging is enabled, then the value of the parameter
2002  * "activate" determines to which queue the page is added.  If "activate" is
2003  * non-zero, then the page is added to the active queue.  Otherwise, it is
2004  * added to the inactive queue.
2005  *
2006  * However, unless the page belongs to an object, it is not enqueued because
2007  * it cannot be paged out.
2008  *
2009  * If a page is fictitious, then its wire count must alway be one.
2010  *
2011  * A managed page must be locked.
2012  */
2013 void
2014 vm_page_unwire(vm_page_t m, int activate)
2015 {
2016
2017         if ((m->oflags & VPO_UNMANAGED) == 0)
2018                 vm_page_lock_assert(m, MA_OWNED);
2019         if ((m->flags & PG_FICTITIOUS) != 0) {
2020                 KASSERT(m->wire_count == 1,
2021             ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
2022                 return;
2023         }
2024         if (m->wire_count > 0) {
2025                 m->wire_count--;
2026                 if (m->wire_count == 0) {
2027                         atomic_subtract_int(&cnt.v_wire_count, 1);
2028                         if ((m->oflags & VPO_UNMANAGED) != 0 ||
2029                             m->object == NULL)
2030                                 return;
2031                         if (!activate)
2032                                 m->flags &= ~PG_WINATCFLS;
2033                         vm_page_lock_queues();
2034                         vm_page_enqueue(activate ? PQ_ACTIVE : PQ_INACTIVE, m);
2035                         vm_page_unlock_queues();
2036                 }
2037         } else
2038                 panic("vm_page_unwire: page %p's wire count is zero", m);
2039 }
2040
2041 /*
2042  * Move the specified page to the inactive queue.
2043  *
2044  * Many pages placed on the inactive queue should actually go
2045  * into the cache, but it is difficult to figure out which.  What
2046  * we do instead, if the inactive target is well met, is to put
2047  * clean pages at the head of the inactive queue instead of the tail.
2048  * This will cause them to be moved to the cache more quickly and
2049  * if not actively re-referenced, reclaimed more quickly.  If we just
2050  * stick these pages at the end of the inactive queue, heavy filesystem
2051  * meta-data accesses can cause an unnecessary paging load on memory bound 
2052  * processes.  This optimization causes one-time-use metadata to be
2053  * reused more quickly.
2054  *
2055  * Normally athead is 0 resulting in LRU operation.  athead is set
2056  * to 1 if we want this page to be 'as if it were placed in the cache',
2057  * except without unmapping it from the process address space.
2058  *
2059  * This routine may not block.
2060  */
2061 static inline void
2062 _vm_page_deactivate(vm_page_t m, int athead)
2063 {
2064         int queue;
2065
2066         vm_page_lock_assert(m, MA_OWNED);
2067
2068         /*
2069          * Ignore if already inactive.
2070          */
2071         if ((queue = m->queue) == PQ_INACTIVE)
2072                 return;
2073         if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2074                 m->flags &= ~PG_WINATCFLS;
2075                 vm_page_lock_queues();
2076                 if (queue != PQ_NONE)
2077                         vm_page_queue_remove(queue, m);
2078                 if (athead)
2079                         TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m,
2080                             pageq);
2081                 else
2082                         TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m,
2083                             pageq);
2084                 m->queue = PQ_INACTIVE;
2085                 cnt.v_inactive_count++;
2086                 vm_page_unlock_queues();
2087         }
2088 }
2089
2090 /*
2091  * Move the specified page to the inactive queue.
2092  *
2093  * The page must be locked.
2094  */
2095 void
2096 vm_page_deactivate(vm_page_t m)
2097 {
2098
2099         _vm_page_deactivate(m, 0);
2100 }
2101
2102 /*
2103  * vm_page_try_to_cache:
2104  *
2105  * Returns 0 on failure, 1 on success
2106  */
2107 int
2108 vm_page_try_to_cache(vm_page_t m)
2109 {
2110
2111         vm_page_lock_assert(m, MA_OWNED);
2112         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2113         if (m->dirty || m->hold_count || m->busy || m->wire_count ||
2114             (m->oflags & (VPO_BUSY | VPO_UNMANAGED)) != 0)
2115                 return (0);
2116         pmap_remove_all(m);
2117         if (m->dirty)
2118                 return (0);
2119         vm_page_cache(m);
2120         return (1);
2121 }
2122
2123 /*
2124  * vm_page_try_to_free()
2125  *
2126  *      Attempt to free the page.  If we cannot free it, we do nothing.
2127  *      1 is returned on success, 0 on failure.
2128  */
2129 int
2130 vm_page_try_to_free(vm_page_t m)
2131 {
2132
2133         vm_page_lock_assert(m, MA_OWNED);
2134         if (m->object != NULL)
2135                 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2136         if (m->dirty || m->hold_count || m->busy || m->wire_count ||
2137             (m->oflags & (VPO_BUSY | VPO_UNMANAGED)) != 0)
2138                 return (0);
2139         pmap_remove_all(m);
2140         if (m->dirty)
2141                 return (0);
2142         vm_page_free(m);
2143         return (1);
2144 }
2145
2146 /*
2147  * vm_page_cache
2148  *
2149  * Put the specified page onto the page cache queue (if appropriate).
2150  *
2151  * This routine may not block.
2152  */
2153 void
2154 vm_page_cache(vm_page_t m)
2155 {
2156         vm_object_t object;
2157         vm_page_t next, prev, root;
2158
2159         vm_page_lock_assert(m, MA_OWNED);
2160         object = m->object;
2161         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2162         if ((m->oflags & (VPO_UNMANAGED | VPO_BUSY)) || m->busy ||
2163             m->hold_count || m->wire_count)
2164                 panic("vm_page_cache: attempting to cache busy page");
2165         pmap_remove_all(m);
2166         if (m->dirty != 0)
2167                 panic("vm_page_cache: page %p is dirty", m);
2168         if (m->valid == 0 || object->type == OBJT_DEFAULT ||
2169             (object->type == OBJT_SWAP &&
2170             !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
2171                 /*
2172                  * Hypothesis: A cache-elgible page belonging to a
2173                  * default object or swap object but without a backing
2174                  * store must be zero filled.
2175                  */
2176                 vm_page_free(m);
2177                 return;
2178         }
2179         KASSERT((m->flags & PG_CACHED) == 0,
2180             ("vm_page_cache: page %p is already cached", m));
2181         PCPU_INC(cnt.v_tcached);
2182
2183         /*
2184          * Remove the page from the paging queues.
2185          */
2186         vm_pageq_remove(m);
2187
2188         /*
2189          * Remove the page from the object's collection of resident
2190          * pages. 
2191          */
2192         if ((next = TAILQ_NEXT(m, listq)) != NULL && next->left == m) {
2193                 /*
2194                  * Since the page's successor in the list is also its parent
2195                  * in the tree, its right subtree must be empty.
2196                  */
2197                 next->left = m->left;
2198                 KASSERT(m->right == NULL,
2199                     ("vm_page_cache: page %p has right child", m));
2200         } else if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
2201             prev->right == m) {
2202                 /*
2203                  * Since the page's predecessor in the list is also its parent
2204                  * in the tree, its left subtree must be empty.
2205                  */
2206                 KASSERT(m->left == NULL,
2207                     ("vm_page_cache: page %p has left child", m));
2208                 prev->right = m->right;
2209         } else {
2210                 if (m != object->root)
2211                         vm_page_splay(m->pindex, object->root);
2212                 if (m->left == NULL)
2213                         root = m->right;
2214                 else if (m->right == NULL)
2215                         root = m->left;
2216                 else {
2217                         /*
2218                          * Move the page's successor to the root, because
2219                          * pages are usually removed in ascending order.
2220                          */
2221                         if (m->right != next)
2222                                 vm_page_splay(m->pindex, m->right);
2223                         next->left = m->left;
2224                         root = next;
2225                 }
2226                 object->root = root;
2227         }
2228         TAILQ_REMOVE(&object->memq, m, listq);
2229         object->resident_page_count--;
2230
2231         /*
2232          * Restore the default memory attribute to the page.
2233          */
2234         if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2235                 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2236
2237         /*
2238          * Insert the page into the object's collection of cached pages
2239          * and the physical memory allocator's cache/free page queues.
2240          */
2241         m->flags &= ~PG_ZERO;
2242         mtx_lock(&vm_page_queue_free_mtx);
2243         m->flags |= PG_CACHED;
2244         cnt.v_cache_count++;
2245         root = object->cache;
2246         if (root == NULL) {
2247                 m->left = NULL;
2248                 m->right = NULL;
2249         } else {
2250                 root = vm_page_splay(m->pindex, root);
2251                 if (m->pindex < root->pindex) {
2252                         m->left = root->left;
2253                         m->right = root;
2254                         root->left = NULL;
2255                 } else if (__predict_false(m->pindex == root->pindex))
2256                         panic("vm_page_cache: offset already cached");
2257                 else {
2258                         m->right = root->right;
2259                         m->left = root;
2260                         root->right = NULL;
2261                 }
2262         }
2263         object->cache = m;
2264 #if VM_NRESERVLEVEL > 0
2265         if (!vm_reserv_free_page(m)) {
2266 #else
2267         if (TRUE) {
2268 #endif
2269                 vm_phys_set_pool(VM_FREEPOOL_CACHE, m, 0);
2270                 vm_phys_free_pages(m, 0);
2271         }
2272         vm_page_free_wakeup();
2273         mtx_unlock(&vm_page_queue_free_mtx);
2274
2275         /*
2276          * Increment the vnode's hold count if this is the object's only
2277          * cached page.  Decrement the vnode's hold count if this was
2278          * the object's only resident page.
2279          */
2280         if (object->type == OBJT_VNODE) {
2281                 if (root == NULL && object->resident_page_count != 0)
2282                         vhold(object->handle);
2283                 else if (root != NULL && object->resident_page_count == 0)
2284                         vdrop(object->handle);
2285         }
2286 }
2287
2288 /*
2289  * vm_page_dontneed
2290  *
2291  *      Cache, deactivate, or do nothing as appropriate.  This routine
2292  *      is typically used by madvise() MADV_DONTNEED.
2293  *
2294  *      Generally speaking we want to move the page into the cache so
2295  *      it gets reused quickly.  However, this can result in a silly syndrome
2296  *      due to the page recycling too quickly.  Small objects will not be
2297  *      fully cached.  On the otherhand, if we move the page to the inactive
2298  *      queue we wind up with a problem whereby very large objects 
2299  *      unnecessarily blow away our inactive and cache queues.
2300  *
2301  *      The solution is to move the pages based on a fixed weighting.  We
2302  *      either leave them alone, deactivate them, or move them to the cache,
2303  *      where moving them to the cache has the highest weighting.
2304  *      By forcing some pages into other queues we eventually force the
2305  *      system to balance the queues, potentially recovering other unrelated
2306  *      space from active.  The idea is to not force this to happen too
2307  *      often.
2308  */
2309 void
2310 vm_page_dontneed(vm_page_t m)
2311 {
2312         int dnw;
2313         int head;
2314
2315         vm_page_lock_assert(m, MA_OWNED);
2316         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2317         dnw = PCPU_GET(dnweight);
2318         PCPU_INC(dnweight);
2319
2320         /*
2321          * Occasionally leave the page alone.
2322          */
2323         if ((dnw & 0x01F0) == 0 || m->queue == PQ_INACTIVE) {
2324                 if (m->act_count >= ACT_INIT)
2325                         --m->act_count;
2326                 return;
2327         }
2328
2329         /*
2330          * Clear any references to the page.  Otherwise, the page daemon will
2331          * immediately reactivate the page.
2332          *
2333          * Perform the pmap_clear_reference() first.  Otherwise, a concurrent
2334          * pmap operation, such as pmap_remove(), could clear a reference in
2335          * the pmap and set PGA_REFERENCED on the page before the
2336          * pmap_clear_reference() had completed.  Consequently, the page would
2337          * appear referenced based upon an old reference that occurred before
2338          * this function ran.
2339          */
2340         pmap_clear_reference(m);
2341         vm_page_aflag_clear(m, PGA_REFERENCED);
2342
2343         if (m->dirty == 0 && pmap_is_modified(m))
2344                 vm_page_dirty(m);
2345
2346         if (m->dirty || (dnw & 0x0070) == 0) {
2347                 /*
2348                  * Deactivate the page 3 times out of 32.
2349                  */
2350                 head = 0;
2351         } else {
2352                 /*
2353                  * Cache the page 28 times out of every 32.  Note that
2354                  * the page is deactivated instead of cached, but placed
2355                  * at the head of the queue instead of the tail.
2356                  */
2357                 head = 1;
2358         }
2359         _vm_page_deactivate(m, head);
2360 }
2361
2362 /*
2363  * Grab a page, waiting until we are waken up due to the page
2364  * changing state.  We keep on waiting, if the page continues
2365  * to be in the object.  If the page doesn't exist, first allocate it
2366  * and then conditionally zero it.
2367  *
2368  * The caller must always specify the VM_ALLOC_RETRY flag.  This is intended
2369  * to facilitate its eventual removal.
2370  *
2371  * This routine may block.
2372  */
2373 vm_page_t
2374 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2375 {
2376         vm_page_t m;
2377
2378         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2379         KASSERT((allocflags & VM_ALLOC_RETRY) != 0,
2380             ("vm_page_grab: VM_ALLOC_RETRY is required"));
2381 retrylookup:
2382         if ((m = vm_page_lookup(object, pindex)) != NULL) {
2383                 if ((m->oflags & VPO_BUSY) != 0 ||
2384                     ((allocflags & VM_ALLOC_IGN_SBUSY) == 0 && m->busy != 0)) {
2385                         /*
2386                          * Reference the page before unlocking and
2387                          * sleeping so that the page daemon is less
2388                          * likely to reclaim it.
2389                          */
2390                         vm_page_aflag_set(m, PGA_REFERENCED);
2391                         vm_page_sleep(m, "pgrbwt");
2392                         goto retrylookup;
2393                 } else {
2394                         if ((allocflags & VM_ALLOC_WIRED) != 0) {
2395                                 vm_page_lock(m);
2396                                 vm_page_wire(m);
2397                                 vm_page_unlock(m);
2398                         }
2399                         if ((allocflags & VM_ALLOC_NOBUSY) == 0)
2400                                 vm_page_busy(m);
2401                         return (m);
2402                 }
2403         }
2404         m = vm_page_alloc(object, pindex, allocflags & ~(VM_ALLOC_RETRY |
2405             VM_ALLOC_IGN_SBUSY));
2406         if (m == NULL) {
2407                 VM_OBJECT_UNLOCK(object);
2408                 VM_WAIT;
2409                 VM_OBJECT_LOCK(object);
2410                 goto retrylookup;
2411         } else if (m->valid != 0)
2412                 return (m);
2413         if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
2414                 pmap_zero_page(m);
2415         return (m);
2416 }
2417
2418 /*
2419  * Mapping function for valid bits or for dirty bits in
2420  * a page.  May not block.
2421  *
2422  * Inputs are required to range within a page.
2423  */
2424 vm_page_bits_t
2425 vm_page_bits(int base, int size)
2426 {
2427         int first_bit;
2428         int last_bit;
2429
2430         KASSERT(
2431             base + size <= PAGE_SIZE,
2432             ("vm_page_bits: illegal base/size %d/%d", base, size)
2433         );
2434
2435         if (size == 0)          /* handle degenerate case */
2436                 return (0);
2437
2438         first_bit = base >> DEV_BSHIFT;
2439         last_bit = (base + size - 1) >> DEV_BSHIFT;
2440
2441         return (((vm_page_bits_t)2 << last_bit) -
2442             ((vm_page_bits_t)1 << first_bit));
2443 }
2444
2445 /*
2446  *      vm_page_set_valid:
2447  *
2448  *      Sets portions of a page valid.  The arguments are expected
2449  *      to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2450  *      of any partial chunks touched by the range.  The invalid portion of
2451  *      such chunks will be zeroed.
2452  *
2453  *      (base + size) must be less then or equal to PAGE_SIZE.
2454  */
2455 void
2456 vm_page_set_valid(vm_page_t m, int base, int size)
2457 {
2458         int endoff, frag;
2459
2460         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2461         if (size == 0)  /* handle degenerate case */
2462                 return;
2463
2464         /*
2465          * If the base is not DEV_BSIZE aligned and the valid
2466          * bit is clear, we have to zero out a portion of the
2467          * first block.
2468          */
2469         if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2470             (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2471                 pmap_zero_page_area(m, frag, base - frag);
2472
2473         /*
2474          * If the ending offset is not DEV_BSIZE aligned and the 
2475          * valid bit is clear, we have to zero out a portion of
2476          * the last block.
2477          */
2478         endoff = base + size;
2479         if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2480             (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2481                 pmap_zero_page_area(m, endoff,
2482                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2483
2484         /*
2485          * Assert that no previously invalid block that is now being validated
2486          * is already dirty. 
2487          */
2488         KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
2489             ("vm_page_set_valid: page %p is dirty", m)); 
2490
2491         /*
2492          * Set valid bits inclusive of any overlap.
2493          */
2494         m->valid |= vm_page_bits(base, size);
2495 }
2496
2497 /*
2498  * Clear the given bits from the specified page's dirty field.
2499  */
2500 static __inline void
2501 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
2502 {
2503         uintptr_t addr;
2504 #if PAGE_SIZE < 16384
2505         int shift;
2506 #endif
2507
2508         /*
2509          * If the object is locked and the page is neither VPO_BUSY nor
2510          * PGA_WRITEABLE, then the page's dirty field cannot possibly be
2511          * set by a concurrent pmap operation.
2512          */
2513         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2514         if ((m->oflags & VPO_BUSY) == 0 && (m->aflags & PGA_WRITEABLE) == 0)
2515                 m->dirty &= ~pagebits;
2516         else {
2517                 /*
2518                  * The pmap layer can call vm_page_dirty() without
2519                  * holding a distinguished lock.  The combination of
2520                  * the object's lock and an atomic operation suffice
2521                  * to guarantee consistency of the page dirty field.
2522                  *
2523                  * For PAGE_SIZE == 32768 case, compiler already
2524                  * properly aligns the dirty field, so no forcible
2525                  * alignment is needed. Only require existence of
2526                  * atomic_clear_64 when page size is 32768.
2527                  */
2528                 addr = (uintptr_t)&m->dirty;
2529 #if PAGE_SIZE == 32768
2530                 atomic_clear_64((uint64_t *)addr, pagebits);
2531 #elif PAGE_SIZE == 16384
2532                 atomic_clear_32((uint32_t *)addr, pagebits);
2533 #else           /* PAGE_SIZE <= 8192 */
2534                 /*
2535                  * Use a trick to perform a 32-bit atomic on the
2536                  * containing aligned word, to not depend on the existence
2537                  * of atomic_clear_{8, 16}.
2538                  */
2539                 shift = addr & (sizeof(uint32_t) - 1);
2540 #if BYTE_ORDER == BIG_ENDIAN
2541                 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
2542 #else
2543                 shift *= NBBY;
2544 #endif
2545                 addr &= ~(sizeof(uint32_t) - 1);
2546                 atomic_clear_32((uint32_t *)addr, pagebits << shift);
2547 #endif          /* PAGE_SIZE */
2548         }
2549 }
2550
2551 /*
2552  *      vm_page_set_validclean:
2553  *
2554  *      Sets portions of a page valid and clean.  The arguments are expected
2555  *      to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2556  *      of any partial chunks touched by the range.  The invalid portion of
2557  *      such chunks will be zero'd.
2558  *
2559  *      This routine may not block.
2560  *
2561  *      (base + size) must be less then or equal to PAGE_SIZE.
2562  */
2563 void
2564 vm_page_set_validclean(vm_page_t m, int base, int size)
2565 {
2566         vm_page_bits_t oldvalid, pagebits;
2567         int endoff, frag;
2568
2569         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2570         if (size == 0)  /* handle degenerate case */
2571                 return;
2572
2573         /*
2574          * If the base is not DEV_BSIZE aligned and the valid
2575          * bit is clear, we have to zero out a portion of the
2576          * first block.
2577          */
2578         if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2579             (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
2580                 pmap_zero_page_area(m, frag, base - frag);
2581
2582         /*
2583          * If the ending offset is not DEV_BSIZE aligned and the 
2584          * valid bit is clear, we have to zero out a portion of
2585          * the last block.
2586          */
2587         endoff = base + size;
2588         if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2589             (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
2590                 pmap_zero_page_area(m, endoff,
2591                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2592
2593         /*
2594          * Set valid, clear dirty bits.  If validating the entire
2595          * page we can safely clear the pmap modify bit.  We also
2596          * use this opportunity to clear the VPO_NOSYNC flag.  If a process
2597          * takes a write fault on a MAP_NOSYNC memory area the flag will
2598          * be set again.
2599          *
2600          * We set valid bits inclusive of any overlap, but we can only
2601          * clear dirty bits for DEV_BSIZE chunks that are fully within
2602          * the range.
2603          */
2604         oldvalid = m->valid;
2605         pagebits = vm_page_bits(base, size);
2606         m->valid |= pagebits;
2607 #if 0   /* NOT YET */
2608         if ((frag = base & (DEV_BSIZE - 1)) != 0) {
2609                 frag = DEV_BSIZE - frag;
2610                 base += frag;
2611                 size -= frag;
2612                 if (size < 0)
2613                         size = 0;
2614         }
2615         pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
2616 #endif
2617         if (base == 0 && size == PAGE_SIZE) {
2618                 /*
2619                  * The page can only be modified within the pmap if it is
2620                  * mapped, and it can only be mapped if it was previously
2621                  * fully valid.
2622                  */
2623                 if (oldvalid == VM_PAGE_BITS_ALL)
2624                         /*
2625                          * Perform the pmap_clear_modify() first.  Otherwise,
2626                          * a concurrent pmap operation, such as
2627                          * pmap_protect(), could clear a modification in the
2628                          * pmap and set the dirty field on the page before
2629                          * pmap_clear_modify() had begun and after the dirty
2630                          * field was cleared here.
2631                          */
2632                         pmap_clear_modify(m);
2633                 m->dirty = 0;
2634                 m->oflags &= ~VPO_NOSYNC;
2635         } else if (oldvalid != VM_PAGE_BITS_ALL)
2636                 m->dirty &= ~pagebits;
2637         else
2638                 vm_page_clear_dirty_mask(m, pagebits);
2639 }
2640
2641 void
2642 vm_page_clear_dirty(vm_page_t m, int base, int size)
2643 {
2644
2645         vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
2646 }
2647
2648 /*
2649  *      vm_page_set_invalid:
2650  *
2651  *      Invalidates DEV_BSIZE'd chunks within a page.  Both the
2652  *      valid and dirty bits for the effected areas are cleared.
2653  *
2654  *      May not block.
2655  */
2656 void
2657 vm_page_set_invalid(vm_page_t m, int base, int size)
2658 {
2659         vm_page_bits_t bits;
2660
2661         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2662         KASSERT((m->oflags & VPO_BUSY) == 0,
2663             ("vm_page_set_invalid: page %p is busy", m));
2664         bits = vm_page_bits(base, size);
2665         if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
2666                 pmap_remove_all(m);
2667         KASSERT(!pmap_page_is_mapped(m),
2668             ("vm_page_set_invalid: page %p is mapped", m));
2669         m->valid &= ~bits;
2670         m->dirty &= ~bits;
2671 }
2672
2673 /*
2674  * vm_page_zero_invalid()
2675  *
2676  *      The kernel assumes that the invalid portions of a page contain 
2677  *      garbage, but such pages can be mapped into memory by user code.
2678  *      When this occurs, we must zero out the non-valid portions of the
2679  *      page so user code sees what it expects.
2680  *
2681  *      Pages are most often semi-valid when the end of a file is mapped 
2682  *      into memory and the file's size is not page aligned.
2683  */
2684 void
2685 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
2686 {
2687         int b;
2688         int i;
2689
2690         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2691         /*
2692          * Scan the valid bits looking for invalid sections that
2693          * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
2694          * valid bit may be set ) have already been zerod by
2695          * vm_page_set_validclean().
2696          */
2697         for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
2698                 if (i == (PAGE_SIZE / DEV_BSIZE) || 
2699                     (m->valid & ((vm_page_bits_t)1 << i))) {
2700                         if (i > b) {
2701                                 pmap_zero_page_area(m, 
2702                                     b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
2703                         }
2704                         b = i + 1;
2705                 }
2706         }
2707
2708         /*
2709          * setvalid is TRUE when we can safely set the zero'd areas
2710          * as being valid.  We can do this if there are no cache consistancy
2711          * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
2712          */
2713         if (setvalid)
2714                 m->valid = VM_PAGE_BITS_ALL;
2715 }
2716
2717 /*
2718  *      vm_page_is_valid:
2719  *
2720  *      Is (partial) page valid?  Note that the case where size == 0
2721  *      will return FALSE in the degenerate case where the page is
2722  *      entirely invalid, and TRUE otherwise.
2723  *
2724  *      May not block.
2725  */
2726 int
2727 vm_page_is_valid(vm_page_t m, int base, int size)
2728 {
2729         vm_page_bits_t bits;
2730
2731         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2732         bits = vm_page_bits(base, size);
2733         if (m->valid && ((m->valid & bits) == bits))
2734                 return 1;
2735         else
2736                 return 0;
2737 }
2738
2739 /*
2740  * update dirty bits from pmap/mmu.  May not block.
2741  */
2742 void
2743 vm_page_test_dirty(vm_page_t m)
2744 {
2745
2746         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2747         if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
2748                 vm_page_dirty(m);
2749 }
2750
2751 void
2752 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
2753 {
2754
2755         mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
2756 }
2757
2758 void
2759 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
2760 {
2761
2762         mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
2763 }
2764
2765 int
2766 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
2767 {
2768
2769         return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
2770 }
2771
2772 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
2773 void
2774 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
2775 {
2776
2777         mtx_assert_(vm_page_lockptr(m), a, file, line);
2778 }
2779 #endif
2780
2781 int so_zerocp_fullpage = 0;
2782
2783 /*
2784  *      Replace the given page with a copy.  The copied page assumes
2785  *      the portion of the given page's "wire_count" that is not the
2786  *      responsibility of this copy-on-write mechanism.
2787  *
2788  *      The object containing the given page must have a non-zero
2789  *      paging-in-progress count and be locked.
2790  */
2791 void
2792 vm_page_cowfault(vm_page_t m)
2793 {
2794         vm_page_t mnew;
2795         vm_object_t object;
2796         vm_pindex_t pindex;
2797
2798         mtx_assert(&vm_page_queue_mtx, MA_NOTOWNED);
2799         vm_page_lock_assert(m, MA_OWNED);
2800         object = m->object;
2801         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2802         KASSERT(object->paging_in_progress != 0,
2803             ("vm_page_cowfault: object %p's paging-in-progress count is zero.",
2804             object)); 
2805         pindex = m->pindex;
2806
2807  retry_alloc:
2808         pmap_remove_all(m);
2809         vm_page_remove(m);
2810         mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY);
2811         if (mnew == NULL) {
2812                 vm_page_insert(m, object, pindex);
2813                 vm_page_unlock(m);
2814                 VM_OBJECT_UNLOCK(object);
2815                 VM_WAIT;
2816                 VM_OBJECT_LOCK(object);
2817                 if (m == vm_page_lookup(object, pindex)) {
2818                         vm_page_lock(m);
2819                         goto retry_alloc;
2820                 } else {
2821                         /*
2822                          * Page disappeared during the wait.
2823                          */
2824                         return;
2825                 }
2826         }
2827
2828         if (m->cow == 0) {
2829                 /* 
2830                  * check to see if we raced with an xmit complete when 
2831                  * waiting to allocate a page.  If so, put things back 
2832                  * the way they were 
2833                  */
2834                 vm_page_unlock(m);
2835                 vm_page_lock(mnew);
2836                 vm_page_free(mnew);
2837                 vm_page_unlock(mnew);
2838                 vm_page_insert(m, object, pindex);
2839         } else { /* clear COW & copy page */
2840                 if (!so_zerocp_fullpage)
2841                         pmap_copy_page(m, mnew);
2842                 mnew->valid = VM_PAGE_BITS_ALL;
2843                 vm_page_dirty(mnew);
2844                 mnew->wire_count = m->wire_count - m->cow;
2845                 m->wire_count = m->cow;
2846                 vm_page_unlock(m);
2847         }
2848 }
2849
2850 void 
2851 vm_page_cowclear(vm_page_t m)
2852 {
2853
2854         vm_page_lock_assert(m, MA_OWNED);
2855         if (m->cow) {
2856                 m->cow--;
2857                 /* 
2858                  * let vm_fault add back write permission  lazily
2859                  */
2860         } 
2861         /*
2862          *  sf_buf_free() will free the page, so we needn't do it here
2863          */ 
2864 }
2865
2866 int
2867 vm_page_cowsetup(vm_page_t m)
2868 {
2869
2870         vm_page_lock_assert(m, MA_OWNED);
2871         if ((m->flags & PG_FICTITIOUS) != 0 ||
2872             (m->oflags & VPO_UNMANAGED) != 0 ||
2873             m->cow == USHRT_MAX - 1 || !VM_OBJECT_TRYLOCK(m->object))
2874                 return (EBUSY);
2875         m->cow++;
2876         pmap_remove_write(m);
2877         VM_OBJECT_UNLOCK(m->object);
2878         return (0);
2879 }
2880
2881 #ifdef INVARIANTS
2882 void
2883 vm_page_object_lock_assert(vm_page_t m)
2884 {
2885
2886         /*
2887          * Certain of the page's fields may only be modified by the
2888          * holder of the containing object's lock or the setter of the
2889          * page's VPO_BUSY flag.  Unfortunately, the setter of the
2890          * VPO_BUSY flag is not recorded, and thus cannot be checked
2891          * here.
2892          */
2893         if (m->object != NULL && (m->oflags & VPO_BUSY) == 0)
2894                 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2895 }
2896 #endif
2897
2898 #include "opt_ddb.h"
2899 #ifdef DDB
2900 #include <sys/kernel.h>
2901
2902 #include <ddb/ddb.h>
2903
2904 DB_SHOW_COMMAND(page, vm_page_print_page_info)
2905 {
2906         db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
2907         db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
2908         db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
2909         db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
2910         db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
2911         db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
2912         db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
2913         db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
2914         db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
2915         db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
2916 }
2917
2918 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
2919 {
2920                 
2921         db_printf("PQ_FREE:");
2922         db_printf(" %d", cnt.v_free_count);
2923         db_printf("\n");
2924                 
2925         db_printf("PQ_CACHE:");
2926         db_printf(" %d", cnt.v_cache_count);
2927         db_printf("\n");
2928
2929         db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
2930                 *vm_page_queues[PQ_ACTIVE].cnt,
2931                 *vm_page_queues[PQ_INACTIVE].cnt);
2932 }
2933 #endif /* DDB */