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