]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vm_page.c
Reduce diffs against HEAD.
[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         if (vm_radix_insert(&object->rtree, pindex, m) != 0)
837                 panic("vm_page_insert: unable to insert the new page");
838
839         /*
840          * Show that the object has one more resident page.
841          */
842         object->resident_page_count++;
843
844         /*
845          * Hold the vnode until the last page is released.
846          */
847         if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
848                 vhold(object->handle);
849
850         /*
851          * Since we are inserting a new and possibly dirty page,
852          * update the object's OBJ_MIGHTBEDIRTY flag.
853          */
854         if (pmap_page_is_write_mapped(m))
855                 vm_object_set_writeable_dirty(object);
856 }
857
858 /*
859  *      vm_page_remove:
860  *
861  *      Removes the given mem entry from the object/offset-page
862  *      table and the object page list, but do not invalidate/terminate
863  *      the backing store.
864  *
865  *      The underlying pmap entry (if any) is NOT removed here.
866  *
867  *      The object must be locked.  The page must be locked if it is managed.
868  */
869 void
870 vm_page_remove(vm_page_t m)
871 {
872         vm_object_t object;
873
874         if ((m->oflags & VPO_UNMANAGED) == 0)
875                 vm_page_lock_assert(m, MA_OWNED);
876         if ((object = m->object) == NULL)
877                 return;
878         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
879         if (m->oflags & VPO_BUSY) {
880                 m->oflags &= ~VPO_BUSY;
881                 vm_page_flash(m);
882         }
883
884         vm_radix_remove(&object->rtree, m->pindex);
885         TAILQ_REMOVE(&object->memq, m, listq);
886
887         /*
888          * And show that the object has one fewer resident page.
889          */
890         object->resident_page_count--;
891
892         /*
893          * The vnode may now be recycled.
894          */
895         if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
896                 vdrop(object->handle);
897
898         m->object = NULL;
899 }
900
901 /*
902  *      vm_page_lookup:
903  *
904  *      Returns the page associated with the object/offset
905  *      pair specified; if none is found, NULL is returned.
906  *
907  *      The object must be locked.
908  */
909 vm_page_t
910 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
911 {
912
913         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
914
915         return vm_radix_lookup(&object->rtree, pindex);
916 }
917
918 /*
919  *      vm_page_find_least:
920  *
921  *      Returns the page associated with the object with least pindex
922  *      greater than or equal to the parameter pindex, or NULL.
923  *
924  *      The object must be locked.
925  */
926 vm_page_t
927 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
928 {
929
930         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
931         if (object->resident_page_count)
932                 return (vm_radix_lookup_ge(&object->rtree, pindex));
933         return (NULL);
934 }
935
936 /*
937  * Returns the given page's successor (by pindex) within the object if it is
938  * resident; if none is found, NULL is returned.
939  *
940  * The object must be locked.
941  */
942 vm_page_t
943 vm_page_next(vm_page_t m)
944 {
945         vm_page_t next;
946
947         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
948         if ((next = TAILQ_NEXT(m, listq)) != NULL &&
949             next->pindex != m->pindex + 1)
950                 next = NULL;
951         return (next);
952 }
953
954 /*
955  * Returns the given page's predecessor (by pindex) within the object if it is
956  * resident; if none is found, NULL is returned.
957  *
958  * The object must be locked.
959  */
960 vm_page_t
961 vm_page_prev(vm_page_t m)
962 {
963         vm_page_t prev;
964
965         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
966         if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
967             prev->pindex != m->pindex - 1)
968                 prev = NULL;
969         return (prev);
970 }
971
972 /*
973  *      vm_page_rename:
974  *
975  *      Move the given memory entry from its
976  *      current object to the specified target object/offset.
977  *
978  *      Note: swap associated with the page must be invalidated by the move.  We
979  *            have to do this for several reasons:  (1) we aren't freeing the
980  *            page, (2) we are dirtying the page, (3) the VM system is probably
981  *            moving the page from object A to B, and will then later move
982  *            the backing store from A to B and we can't have a conflict.
983  *
984  *      Note: we *always* dirty the page.  It is necessary both for the
985  *            fact that we moved it, and because we may be invalidating
986  *            swap.  If the page is on the cache, we have to deactivate it
987  *            or vm_page_dirty() will panic.  Dirty pages are not allowed
988  *            on the cache.
989  *
990  *      The objects must be locked.  The page must be locked if it is managed.
991  */
992 void
993 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
994 {
995
996         vm_page_remove(m);
997         vm_page_insert(m, new_object, new_pindex);
998         vm_page_dirty(m);
999 }
1000
1001 /*
1002  *      Convert all of the given object's cached pages that have a
1003  *      pindex within the given range into free pages.  If the value
1004  *      zero is given for "end", then the range's upper bound is
1005  *      infinity.  If the given object is backed by a vnode and it
1006  *      transitions from having one or more cached pages to none, the
1007  *      vnode's hold count is reduced. 
1008  */
1009 void
1010 vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1011 {
1012         vm_page_t m;
1013         boolean_t empty;
1014
1015         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1016
1017         mtx_lock(&vm_page_queue_free_mtx);
1018         if (vm_object_cache_is_empty(object)) {
1019                 mtx_unlock(&vm_page_queue_free_mtx);
1020                 return;
1021         }
1022         while ((m = vm_radix_lookup_ge(&object->cache, start)) != NULL) {
1023                 if (end != 0 && m->pindex >= end)
1024                         break;
1025                 vm_radix_remove(&object->cache, m->pindex);
1026                 m->object = NULL;
1027                 m->valid = 0;
1028                 /* Clear PG_CACHED and set PG_FREE. */
1029                 m->flags ^= PG_CACHED | PG_FREE;
1030                 KASSERT((m->flags & (PG_CACHED | PG_FREE)) == PG_FREE,
1031                     ("vm_page_cache_free: page %p has inconsistent flags", m));
1032                 cnt.v_cache_count--;
1033                 cnt.v_free_count++;
1034         }
1035         empty = vm_object_cache_is_empty(object);
1036         mtx_unlock(&vm_page_queue_free_mtx);
1037         if (object->type == OBJT_VNODE && empty)
1038                 vdrop(object->handle);
1039 }
1040
1041 /*
1042  *      Returns the cached page that is associated with the given
1043  *      object and offset.  If, however, none exists, returns NULL.
1044  *
1045  *      The free page queue must be locked.
1046  */
1047 static inline vm_page_t
1048 vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1049 {
1050
1051         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1052         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1053         if (!vm_object_cache_is_empty(object))
1054                 return (vm_radix_lookup(&object->cache, pindex));
1055         return (NULL);
1056 }
1057
1058 /*
1059  *      Remove the given cached page from its containing object's
1060  *      collection of cached pages.
1061  *
1062  *      The free page queue must be locked.
1063  */
1064 static void
1065 vm_page_cache_remove(vm_page_t m)
1066 {
1067
1068         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1069         KASSERT((m->flags & PG_CACHED) != 0,
1070             ("vm_page_cache_remove: page %p is not cached", m));
1071         vm_radix_remove(&m->object->cache, m->pindex);
1072         m->object = NULL;
1073         cnt.v_cache_count--;
1074 }
1075
1076 /*
1077  *      Transfer all of the cached pages with offset greater than or
1078  *      equal to 'offidxstart' from the original object's cache to the
1079  *      new object's cache.  However, any cached pages with offset
1080  *      greater than or equal to the new object's size are kept in the
1081  *      original object.  Initially, the new object's cache must be
1082  *      empty.  Offset 'offidxstart' in the original object must
1083  *      correspond to offset zero in the new object.
1084  *
1085  *      The new object must be locked.
1086  */
1087 void
1088 vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1089     vm_object_t new_object)
1090 {
1091         vm_page_t m;
1092
1093         /*
1094          * Insertion into an object's collection of cached pages
1095          * requires the object to be locked.  In contrast, removal does
1096          * not.
1097          */
1098         VM_OBJECT_LOCK_ASSERT(new_object, MA_OWNED);
1099         VM_OBJECT_LOCK_ASSERT(orig_object, MA_OWNED);
1100         KASSERT(vm_object_cache_is_empty(new_object),
1101             ("vm_page_cache_transfer: object %p has cached pages",
1102             new_object));
1103         mtx_lock(&vm_page_queue_free_mtx);
1104         while ((m = vm_radix_lookup_ge(&orig_object->cache,
1105             offidxstart)) != NULL) {
1106                 if ((m->pindex - offidxstart) >= new_object->size)
1107                         break;
1108                 vm_radix_remove(&orig_object->cache, m->pindex);
1109                 if (vm_radix_insert(&new_object->cache,
1110                     m->pindex - offidxstart, m) != 0)
1111                         panic("vm_page_cache_transfer: failed vm_radix_insert");
1112                 m->object = new_object;
1113                 m->pindex -= offidxstart;
1114         }
1115         mtx_unlock(&vm_page_queue_free_mtx);
1116 }
1117
1118 /*
1119  *      Returns TRUE if a cached page is associated with the given object and
1120  *      offset, and FALSE otherwise.
1121  *
1122  *      The object must be locked.
1123  */
1124 boolean_t
1125 vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
1126 {
1127         vm_page_t m;
1128
1129         /*
1130          * Insertion into an object's collection of cached pages requires the
1131          * object to be locked.  Therefore, if the object is locked and the
1132          * object's collection is empty, there is no need to acquire the free
1133          * page queues lock in order to prove that the specified page doesn't
1134          * exist.
1135          */
1136         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1137         if (vm_object_cache_is_empty(object))
1138                 return (FALSE);
1139         mtx_lock(&vm_page_queue_free_mtx);
1140         m = vm_page_cache_lookup(object, pindex);
1141         mtx_unlock(&vm_page_queue_free_mtx);
1142         return (m != NULL);
1143 }
1144
1145 /*
1146  *      vm_page_alloc:
1147  *
1148  *      Allocate and return a page that is associated with the specified
1149  *      object and offset pair.  By default, this page has the flag VPO_BUSY
1150  *      set.
1151  *
1152  *      The caller must always specify an allocation class.
1153  *
1154  *      allocation classes:
1155  *      VM_ALLOC_NORMAL         normal process request
1156  *      VM_ALLOC_SYSTEM         system *really* needs a page
1157  *      VM_ALLOC_INTERRUPT      interrupt time request
1158  *
1159  *      optional allocation flags:
1160  *      VM_ALLOC_COUNT(number)  the number of additional pages that the caller
1161  *                              intends to allocate
1162  *      VM_ALLOC_IFCACHED       return page only if it is cached
1163  *      VM_ALLOC_IFNOTCACHED    return NULL, do not reactivate if the page
1164  *                              is cached
1165  *      VM_ALLOC_NOBUSY         do not set the flag VPO_BUSY on the page
1166  *      VM_ALLOC_NODUMP         do not include the page in a kernel core dump
1167  *      VM_ALLOC_NOOBJ          page is not associated with an object and
1168  *                              should not have the flag VPO_BUSY set
1169  *      VM_ALLOC_WIRED          wire the allocated page
1170  *      VM_ALLOC_ZERO           prefer a zeroed page
1171  *
1172  *      This routine may not sleep.
1173  */
1174 vm_page_t
1175 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1176 {
1177         struct vnode *vp = NULL;
1178         vm_object_t m_object;
1179         vm_page_t m;
1180         int flags, req_class;
1181
1182         KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0),
1183             ("vm_page_alloc: inconsistent object/req"));
1184         if (object != NULL)
1185                 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1186
1187         req_class = req & VM_ALLOC_CLASS_MASK;
1188
1189         /*
1190          * The page daemon is allowed to dig deeper into the free page list.
1191          */
1192         if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1193                 req_class = VM_ALLOC_SYSTEM;
1194
1195         mtx_lock(&vm_page_queue_free_mtx);
1196         if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1197             (req_class == VM_ALLOC_SYSTEM &&
1198             cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1199             (req_class == VM_ALLOC_INTERRUPT &&
1200             cnt.v_free_count + cnt.v_cache_count > 0)) {
1201                 /*
1202                  * Allocate from the free queue if the number of free pages
1203                  * exceeds the minimum for the request class.
1204                  */
1205                 if (object != NULL &&
1206                     (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1207                         if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1208                                 mtx_unlock(&vm_page_queue_free_mtx);
1209                                 return (NULL);
1210                         }
1211                         if (vm_phys_unfree_page(m))
1212                                 vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1213 #if VM_NRESERVLEVEL > 0
1214                         else if (!vm_reserv_reactivate_page(m))
1215 #else
1216                         else
1217 #endif
1218                                 panic("vm_page_alloc: cache page %p is missing"
1219                                     " from the free queue", m);
1220                 } else if ((req & VM_ALLOC_IFCACHED) != 0) {
1221                         mtx_unlock(&vm_page_queue_free_mtx);
1222                         return (NULL);
1223 #if VM_NRESERVLEVEL > 0
1224                 } else if (object == NULL || (object->flags & (OBJ_COLORED |
1225                     OBJ_FICTITIOUS)) != OBJ_COLORED ||
1226                     (m = vm_reserv_alloc_page(object, pindex)) == NULL) {
1227 #else
1228                 } else {
1229 #endif
1230                         m = vm_phys_alloc_pages(object != NULL ?
1231                             VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1232 #if VM_NRESERVLEVEL > 0
1233                         if (m == NULL && vm_reserv_reclaim_inactive()) {
1234                                 m = vm_phys_alloc_pages(object != NULL ?
1235                                     VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1236                                     0);
1237                         }
1238 #endif
1239                 }
1240         } else {
1241                 /*
1242                  * Not allocatable, give up.
1243                  */
1244                 mtx_unlock(&vm_page_queue_free_mtx);
1245                 atomic_add_int(&vm_pageout_deficit,
1246                     max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1247                 pagedaemon_wakeup();
1248                 return (NULL);
1249         }
1250
1251         /*
1252          *  At this point we had better have found a good page.
1253          */
1254         KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1255         KASSERT(m->queue == PQ_NONE,
1256             ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1257         KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1258         KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1259         KASSERT(m->busy == 0, ("vm_page_alloc: page %p is busy", m));
1260         KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1261         KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1262             ("vm_page_alloc: page %p has unexpected memattr %d", m,
1263             pmap_page_get_memattr(m)));
1264         if ((m->flags & PG_CACHED) != 0) {
1265                 KASSERT((m->flags & PG_ZERO) == 0,
1266                     ("vm_page_alloc: cached page %p is PG_ZERO", m));
1267                 KASSERT(m->valid != 0,
1268                     ("vm_page_alloc: cached page %p is invalid", m));
1269                 if (m->object == object && m->pindex == pindex)
1270                         cnt.v_reactivated++;
1271                 else
1272                         m->valid = 0;
1273                 m_object = m->object;
1274                 vm_page_cache_remove(m);
1275                 if (m_object->type == OBJT_VNODE &&
1276                     vm_object_cache_is_empty(m_object))
1277                         vp = m_object->handle;
1278         } else {
1279                 KASSERT(VM_PAGE_IS_FREE(m),
1280                     ("vm_page_alloc: page %p is not free", m));
1281                 KASSERT(m->valid == 0,
1282                     ("vm_page_alloc: free page %p is valid", m));
1283                 cnt.v_free_count--;
1284         }
1285
1286         /*
1287          * Only the PG_ZERO flag is inherited.  The PG_CACHED or PG_FREE flag
1288          * must be cleared before the free page queues lock is released.
1289          */
1290         flags = 0;
1291         if (m->flags & PG_ZERO) {
1292                 vm_page_zero_count--;
1293                 if (req & VM_ALLOC_ZERO)
1294                         flags = PG_ZERO;
1295         }
1296         if (req & VM_ALLOC_NODUMP)
1297                 flags |= PG_NODUMP;
1298         m->flags = flags;
1299         mtx_unlock(&vm_page_queue_free_mtx);
1300         m->aflags = 0;
1301         m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1302             VPO_UNMANAGED : 0;
1303         if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ)) == 0)
1304                 m->oflags |= VPO_BUSY;
1305         if (req & VM_ALLOC_WIRED) {
1306                 /*
1307                  * The page lock is not required for wiring a page until that
1308                  * page is inserted into the object.
1309                  */
1310                 atomic_add_int(&cnt.v_wire_count, 1);
1311                 m->wire_count = 1;
1312         }
1313         m->act_count = 0;
1314
1315         if (object != NULL) {
1316                 /* Ignore device objects; the pager sets "memattr" for them. */
1317                 if (object->memattr != VM_MEMATTR_DEFAULT &&
1318                     (object->flags & OBJ_FICTITIOUS) == 0)
1319                         pmap_page_set_memattr(m, object->memattr);
1320                 vm_page_insert(m, object, pindex);
1321         } else
1322                 m->pindex = pindex;
1323
1324         /*
1325          * The following call to vdrop() must come after the above call
1326          * to vm_page_insert() in case both affect the same object and
1327          * vnode.  Otherwise, the affected vnode's hold count could
1328          * temporarily become zero.
1329          */
1330         if (vp != NULL)
1331                 vdrop(vp);
1332
1333         /*
1334          * Don't wakeup too often - wakeup the pageout daemon when
1335          * we would be nearly out of memory.
1336          */
1337         if (vm_paging_needed())
1338                 pagedaemon_wakeup();
1339
1340         return (m);
1341 }
1342
1343 /*
1344  *      vm_page_alloc_contig:
1345  *
1346  *      Allocate a contiguous set of physical pages of the given size "npages"
1347  *      from the free lists.  All of the physical pages must be at or above
1348  *      the given physical address "low" and below the given physical address
1349  *      "high".  The given value "alignment" determines the alignment of the
1350  *      first physical page in the set.  If the given value "boundary" is
1351  *      non-zero, then the set of physical pages cannot cross any physical
1352  *      address boundary that is a multiple of that value.  Both "alignment"
1353  *      and "boundary" must be a power of two.
1354  *
1355  *      If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1356  *      then the memory attribute setting for the physical pages is configured
1357  *      to the object's memory attribute setting.  Otherwise, the memory
1358  *      attribute setting for the physical pages is configured to "memattr",
1359  *      overriding the object's memory attribute setting.  However, if the
1360  *      object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1361  *      memory attribute setting for the physical pages cannot be configured
1362  *      to VM_MEMATTR_DEFAULT.
1363  *
1364  *      The caller must always specify an allocation class.
1365  *
1366  *      allocation classes:
1367  *      VM_ALLOC_NORMAL         normal process request
1368  *      VM_ALLOC_SYSTEM         system *really* needs a page
1369  *      VM_ALLOC_INTERRUPT      interrupt time request
1370  *
1371  *      optional allocation flags:
1372  *      VM_ALLOC_NOBUSY         do not set the flag VPO_BUSY on the page
1373  *      VM_ALLOC_NOOBJ          page is not associated with an object and
1374  *                              should not have the flag VPO_BUSY set
1375  *      VM_ALLOC_WIRED          wire the allocated page
1376  *      VM_ALLOC_ZERO           prefer a zeroed page
1377  *
1378  *      This routine may not sleep.
1379  */
1380 vm_page_t
1381 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1382     u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1383     vm_paddr_t boundary, vm_memattr_t memattr)
1384 {
1385         struct vnode *drop;
1386         vm_page_t deferred_vdrop_list, m, m_ret;
1387         u_int flags, oflags;
1388         int req_class;
1389
1390         KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0),
1391             ("vm_page_alloc_contig: inconsistent object/req"));
1392         if (object != NULL) {
1393                 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1394                 KASSERT(object->type == OBJT_PHYS,
1395                     ("vm_page_alloc_contig: object %p isn't OBJT_PHYS",
1396                     object));
1397         }
1398         KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1399         req_class = req & VM_ALLOC_CLASS_MASK;
1400
1401         /*
1402          * The page daemon is allowed to dig deeper into the free page list.
1403          */
1404         if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1405                 req_class = VM_ALLOC_SYSTEM;
1406
1407         deferred_vdrop_list = NULL;
1408         mtx_lock(&vm_page_queue_free_mtx);
1409         if (cnt.v_free_count + cnt.v_cache_count >= npages +
1410             cnt.v_free_reserved || (req_class == VM_ALLOC_SYSTEM &&
1411             cnt.v_free_count + cnt.v_cache_count >= npages +
1412             cnt.v_interrupt_free_min) || (req_class == VM_ALLOC_INTERRUPT &&
1413             cnt.v_free_count + cnt.v_cache_count >= npages)) {
1414 #if VM_NRESERVLEVEL > 0
1415 retry:
1416                 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1417                     (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1418                     low, high, alignment, boundary)) == NULL)
1419 #endif
1420                         m_ret = vm_phys_alloc_contig(npages, low, high,
1421                             alignment, boundary);
1422         } else {
1423                 mtx_unlock(&vm_page_queue_free_mtx);
1424                 atomic_add_int(&vm_pageout_deficit, npages);
1425                 pagedaemon_wakeup();
1426                 return (NULL);
1427         }
1428         if (m_ret != NULL)
1429                 for (m = m_ret; m < &m_ret[npages]; m++) {
1430                         drop = vm_page_alloc_init(m);
1431                         if (drop != NULL) {
1432                                 /*
1433                                  * Enqueue the vnode for deferred vdrop().
1434                                  *
1435                                  * Once the pages are removed from the free
1436                                  * page list, "pageq" can be safely abused to
1437                                  * construct a short-lived list of vnodes.
1438                                  */
1439                                 m->pageq.tqe_prev = (void *)drop;
1440                                 m->pageq.tqe_next = deferred_vdrop_list;
1441                                 deferred_vdrop_list = m;
1442                         }
1443                 }
1444         else {
1445 #if VM_NRESERVLEVEL > 0
1446                 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1447                     boundary))
1448                         goto retry;
1449 #endif
1450         }
1451         mtx_unlock(&vm_page_queue_free_mtx);
1452         if (m_ret == NULL)
1453                 return (NULL);
1454
1455         /*
1456          * Initialize the pages.  Only the PG_ZERO flag is inherited.
1457          */
1458         flags = 0;
1459         if ((req & VM_ALLOC_ZERO) != 0)
1460                 flags = PG_ZERO;
1461         if ((req & VM_ALLOC_NODUMP) != 0)
1462                 flags |= PG_NODUMP;
1463         if ((req & VM_ALLOC_WIRED) != 0)
1464                 atomic_add_int(&cnt.v_wire_count, npages);
1465         oflags = VPO_UNMANAGED;
1466         if (object != NULL) {
1467                 if ((req & VM_ALLOC_NOBUSY) == 0)
1468                         oflags |= VPO_BUSY;
1469                 if (object->memattr != VM_MEMATTR_DEFAULT &&
1470                     memattr == VM_MEMATTR_DEFAULT)
1471                         memattr = object->memattr;
1472         }
1473         for (m = m_ret; m < &m_ret[npages]; m++) {
1474                 m->aflags = 0;
1475                 m->flags = (m->flags | PG_NODUMP) & flags;
1476                 if ((req & VM_ALLOC_WIRED) != 0)
1477                         m->wire_count = 1;
1478                 /* Unmanaged pages don't use "act_count". */
1479                 m->oflags = oflags;
1480                 if (memattr != VM_MEMATTR_DEFAULT)
1481                         pmap_page_set_memattr(m, memattr);
1482                 if (object != NULL)
1483                         vm_page_insert(m, object, pindex);
1484                 else
1485                         m->pindex = pindex;
1486                 pindex++;
1487         }
1488         while (deferred_vdrop_list != NULL) {
1489                 vdrop((struct vnode *)deferred_vdrop_list->pageq.tqe_prev);
1490                 deferred_vdrop_list = deferred_vdrop_list->pageq.tqe_next;
1491         }
1492         if (vm_paging_needed())
1493                 pagedaemon_wakeup();
1494         return (m_ret);
1495 }
1496
1497 /*
1498  * Initialize a page that has been freshly dequeued from a freelist.
1499  * The caller has to drop the vnode returned, if it is not NULL.
1500  *
1501  * This function may only be used to initialize unmanaged pages.
1502  *
1503  * To be called with vm_page_queue_free_mtx held.
1504  */
1505 static struct vnode *
1506 vm_page_alloc_init(vm_page_t m)
1507 {
1508         struct vnode *drop;
1509         vm_object_t m_object;
1510
1511         KASSERT(m->queue == PQ_NONE,
1512             ("vm_page_alloc_init: page %p has unexpected queue %d",
1513             m, m->queue));
1514         KASSERT(m->wire_count == 0,
1515             ("vm_page_alloc_init: page %p is wired", m));
1516         KASSERT(m->hold_count == 0,
1517             ("vm_page_alloc_init: page %p is held", m));
1518         KASSERT(m->busy == 0,
1519             ("vm_page_alloc_init: page %p is busy", m));
1520         KASSERT(m->dirty == 0,
1521             ("vm_page_alloc_init: page %p is dirty", m));
1522         KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1523             ("vm_page_alloc_init: page %p has unexpected memattr %d",
1524             m, pmap_page_get_memattr(m)));
1525         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1526         drop = NULL;
1527         if ((m->flags & PG_CACHED) != 0) {
1528                 KASSERT((m->flags & PG_ZERO) == 0,
1529                     ("vm_page_alloc_init: cached page %p is PG_ZERO", m));
1530                 m->valid = 0;
1531                 m_object = m->object;
1532                 vm_page_cache_remove(m);
1533                 if (m_object->type == OBJT_VNODE &&
1534                     vm_object_cache_is_empty(m_object))
1535                         drop = m_object->handle;
1536         } else {
1537                 KASSERT(VM_PAGE_IS_FREE(m),
1538                     ("vm_page_alloc_init: page %p is not free", m));
1539                 KASSERT(m->valid == 0,
1540                     ("vm_page_alloc_init: free page %p is valid", m));
1541                 cnt.v_free_count--;
1542                 if ((m->flags & PG_ZERO) != 0)
1543                         vm_page_zero_count--;
1544         }
1545         /* Don't clear the PG_ZERO flag; we'll need it later. */
1546         m->flags &= PG_ZERO;
1547         return (drop);
1548 }
1549
1550 /*
1551  *      vm_page_alloc_freelist:
1552  *
1553  *      Allocate a physical page from the specified free page list.
1554  *
1555  *      The caller must always specify an allocation class.
1556  *
1557  *      allocation classes:
1558  *      VM_ALLOC_NORMAL         normal process request
1559  *      VM_ALLOC_SYSTEM         system *really* needs a page
1560  *      VM_ALLOC_INTERRUPT      interrupt time request
1561  *
1562  *      optional allocation flags:
1563  *      VM_ALLOC_COUNT(number)  the number of additional pages that the caller
1564  *                              intends to allocate
1565  *      VM_ALLOC_WIRED          wire the allocated page
1566  *      VM_ALLOC_ZERO           prefer a zeroed page
1567  *
1568  *      This routine may not sleep.
1569  */
1570 vm_page_t
1571 vm_page_alloc_freelist(int flind, int req)
1572 {
1573         struct vnode *drop;
1574         vm_page_t m;
1575         u_int flags;
1576         int req_class;
1577
1578         req_class = req & VM_ALLOC_CLASS_MASK;
1579
1580         /*
1581          * The page daemon is allowed to dig deeper into the free page list.
1582          */
1583         if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1584                 req_class = VM_ALLOC_SYSTEM;
1585
1586         /*
1587          * Do not allocate reserved pages unless the req has asked for it.
1588          */
1589         mtx_lock(&vm_page_queue_free_mtx);
1590         if (cnt.v_free_count + cnt.v_cache_count > cnt.v_free_reserved ||
1591             (req_class == VM_ALLOC_SYSTEM &&
1592             cnt.v_free_count + cnt.v_cache_count > cnt.v_interrupt_free_min) ||
1593             (req_class == VM_ALLOC_INTERRUPT &&
1594             cnt.v_free_count + cnt.v_cache_count > 0))
1595                 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1596         else {
1597                 mtx_unlock(&vm_page_queue_free_mtx);
1598                 atomic_add_int(&vm_pageout_deficit,
1599                     max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1600                 pagedaemon_wakeup();
1601                 return (NULL);
1602         }
1603         if (m == NULL) {
1604                 mtx_unlock(&vm_page_queue_free_mtx);
1605                 return (NULL);
1606         }
1607         drop = vm_page_alloc_init(m);
1608         mtx_unlock(&vm_page_queue_free_mtx);
1609
1610         /*
1611          * Initialize the page.  Only the PG_ZERO flag is inherited.
1612          */
1613         m->aflags = 0;
1614         flags = 0;
1615         if ((req & VM_ALLOC_ZERO) != 0)
1616                 flags = PG_ZERO;
1617         m->flags &= flags;
1618         if ((req & VM_ALLOC_WIRED) != 0) {
1619                 /*
1620                  * The page lock is not required for wiring a page that does
1621                  * not belong to an object.
1622                  */
1623                 atomic_add_int(&cnt.v_wire_count, 1);
1624                 m->wire_count = 1;
1625         }
1626         /* Unmanaged pages don't use "act_count". */
1627         m->oflags = VPO_UNMANAGED;
1628         if (drop != NULL)
1629                 vdrop(drop);
1630         if (vm_paging_needed())
1631                 pagedaemon_wakeup();
1632         return (m);
1633 }
1634
1635 /*
1636  *      vm_wait:        (also see VM_WAIT macro)
1637  *
1638  *      Sleep until free pages are available for allocation.
1639  *      - Called in various places before memory allocations.
1640  */
1641 void
1642 vm_wait(void)
1643 {
1644
1645         mtx_lock(&vm_page_queue_free_mtx);
1646         if (curproc == pageproc) {
1647                 vm_pageout_pages_needed = 1;
1648                 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
1649                     PDROP | PSWP, "VMWait", 0);
1650         } else {
1651                 if (!vm_pages_needed) {
1652                         vm_pages_needed = 1;
1653                         wakeup(&vm_pages_needed);
1654                 }
1655                 msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
1656                     "vmwait", 0);
1657         }
1658 }
1659
1660 /*
1661  *      vm_waitpfault:  (also see VM_WAITPFAULT macro)
1662  *
1663  *      Sleep until free pages are available for allocation.
1664  *      - Called only in vm_fault so that processes page faulting
1665  *        can be easily tracked.
1666  *      - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
1667  *        processes will be able to grab memory first.  Do not change
1668  *        this balance without careful testing first.
1669  */
1670 void
1671 vm_waitpfault(void)
1672 {
1673
1674         mtx_lock(&vm_page_queue_free_mtx);
1675         if (!vm_pages_needed) {
1676                 vm_pages_needed = 1;
1677                 wakeup(&vm_pages_needed);
1678         }
1679         msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
1680             "pfault", 0);
1681 }
1682
1683 /*
1684  *      vm_page_dequeue:
1685  *
1686  *      Remove the given page from its current page queue.
1687  *
1688  *      The page must be locked.
1689  */
1690 void
1691 vm_page_dequeue(vm_page_t m)
1692 {
1693         struct vm_pagequeue *pq;
1694
1695         vm_page_lock_assert(m, MA_OWNED);
1696         KASSERT(m->queue != PQ_NONE,
1697             ("vm_page_dequeue: page %p is not queued", m));
1698         pq = &vm_pagequeues[m->queue];
1699         vm_pagequeue_lock(pq);
1700         m->queue = PQ_NONE;
1701         TAILQ_REMOVE(&pq->pq_pl, m, pageq);
1702         (*pq->pq_cnt)--;
1703         vm_pagequeue_unlock(pq);
1704 }
1705
1706 /*
1707  *      vm_page_dequeue_locked:
1708  *
1709  *      Remove the given page from its current page queue.
1710  *
1711  *      The page and page queue must be locked.
1712  */
1713 void
1714 vm_page_dequeue_locked(vm_page_t m)
1715 {
1716         struct vm_pagequeue *pq;
1717
1718         vm_page_lock_assert(m, MA_OWNED);
1719         pq = &vm_pagequeues[m->queue];
1720         vm_pagequeue_assert_locked(pq);
1721         m->queue = PQ_NONE;
1722         TAILQ_REMOVE(&pq->pq_pl, m, pageq);
1723         (*pq->pq_cnt)--;
1724 }
1725
1726 /*
1727  *      vm_page_enqueue:
1728  *
1729  *      Add the given page to the specified page queue.
1730  *
1731  *      The page must be locked.
1732  */
1733 static void
1734 vm_page_enqueue(int queue, vm_page_t m)
1735 {
1736         struct vm_pagequeue *pq;
1737
1738         vm_page_lock_assert(m, MA_OWNED);
1739         pq = &vm_pagequeues[queue];
1740         vm_pagequeue_lock(pq);
1741         m->queue = queue;
1742         TAILQ_INSERT_TAIL(&pq->pq_pl, m, pageq);
1743         ++*pq->pq_cnt;
1744         vm_pagequeue_unlock(pq);
1745 }
1746
1747 /*
1748  *      vm_page_requeue:
1749  *
1750  *      Move the given page to the tail of its current page queue.
1751  *
1752  *      The page must be locked.
1753  */
1754 void
1755 vm_page_requeue(vm_page_t m)
1756 {
1757         struct vm_pagequeue *pq;
1758
1759         vm_page_lock_assert(m, MA_OWNED);
1760         KASSERT(m->queue != PQ_NONE,
1761             ("vm_page_requeue: page %p is not queued", m));
1762         pq = &vm_pagequeues[m->queue];
1763         vm_pagequeue_lock(pq);
1764         TAILQ_REMOVE(&pq->pq_pl, m, pageq);
1765         TAILQ_INSERT_TAIL(&pq->pq_pl, m, pageq);
1766         vm_pagequeue_unlock(pq);
1767 }
1768
1769 /*
1770  *      vm_page_requeue_locked:
1771  *
1772  *      Move the given page to the tail of its current page queue.
1773  *
1774  *      The page queue must be locked.
1775  */
1776 void
1777 vm_page_requeue_locked(vm_page_t m)
1778 {
1779         struct vm_pagequeue *pq;
1780
1781         KASSERT(m->queue != PQ_NONE,
1782             ("vm_page_requeue_locked: page %p is not queued", m));
1783         pq = &vm_pagequeues[m->queue];
1784         vm_pagequeue_assert_locked(pq);
1785         TAILQ_REMOVE(&pq->pq_pl, m, pageq);
1786         TAILQ_INSERT_TAIL(&pq->pq_pl, m, pageq);
1787 }
1788
1789 /*
1790  *      vm_page_activate:
1791  *
1792  *      Put the specified page on the active list (if appropriate).
1793  *      Ensure that act_count is at least ACT_INIT but do not otherwise
1794  *      mess with it.
1795  *
1796  *      The page must be locked.
1797  */
1798 void
1799 vm_page_activate(vm_page_t m)
1800 {
1801         int queue;
1802
1803         vm_page_lock_assert(m, MA_OWNED);
1804         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
1805         if ((queue = m->queue) != PQ_ACTIVE) {
1806                 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
1807                         if (m->act_count < ACT_INIT)
1808                                 m->act_count = ACT_INIT;
1809                         if (queue != PQ_NONE)
1810                                 vm_page_dequeue(m);
1811                         vm_page_enqueue(PQ_ACTIVE, m);
1812                 } else
1813                         KASSERT(queue == PQ_NONE,
1814                             ("vm_page_activate: wired page %p is queued", m));
1815         } else {
1816                 if (m->act_count < ACT_INIT)
1817                         m->act_count = ACT_INIT;
1818         }
1819 }
1820
1821 /*
1822  *      vm_page_free_wakeup:
1823  *
1824  *      Helper routine for vm_page_free_toq() and vm_page_cache().  This
1825  *      routine is called when a page has been added to the cache or free
1826  *      queues.
1827  *
1828  *      The page queues must be locked.
1829  */
1830 static inline void
1831 vm_page_free_wakeup(void)
1832 {
1833
1834         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1835         /*
1836          * if pageout daemon needs pages, then tell it that there are
1837          * some free.
1838          */
1839         if (vm_pageout_pages_needed &&
1840             cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
1841                 wakeup(&vm_pageout_pages_needed);
1842                 vm_pageout_pages_needed = 0;
1843         }
1844         /*
1845          * wakeup processes that are waiting on memory if we hit a
1846          * high water mark. And wakeup scheduler process if we have
1847          * lots of memory. this process will swapin processes.
1848          */
1849         if (vm_pages_needed && !vm_page_count_min()) {
1850                 vm_pages_needed = 0;
1851                 wakeup(&cnt.v_free_count);
1852         }
1853 }
1854
1855 /*
1856  *      vm_page_free_toq:
1857  *
1858  *      Returns the given page to the free list,
1859  *      disassociating it with any VM object.
1860  *
1861  *      The object must be locked.  The page must be locked if it is managed.
1862  */
1863 void
1864 vm_page_free_toq(vm_page_t m)
1865 {
1866
1867         if ((m->oflags & VPO_UNMANAGED) == 0) {
1868                 vm_page_lock_assert(m, MA_OWNED);
1869                 KASSERT(!pmap_page_is_mapped(m),
1870                     ("vm_page_free_toq: freeing mapped page %p", m));
1871         } else
1872                 KASSERT(m->queue == PQ_NONE,
1873                     ("vm_page_free_toq: unmanaged page %p is queued", m));
1874         PCPU_INC(cnt.v_tfree);
1875
1876         if (VM_PAGE_IS_FREE(m))
1877                 panic("vm_page_free: freeing free page %p", m);
1878         else if (m->busy != 0)
1879                 panic("vm_page_free: freeing busy page %p", m);
1880
1881         /*
1882          * Unqueue, then remove page.  Note that we cannot destroy
1883          * the page here because we do not want to call the pager's
1884          * callback routine until after we've put the page on the
1885          * appropriate free queue.
1886          */
1887         vm_page_remque(m);
1888         vm_page_remove(m);
1889
1890         /*
1891          * If fictitious remove object association and
1892          * return, otherwise delay object association removal.
1893          */
1894         if ((m->flags & PG_FICTITIOUS) != 0) {
1895                 return;
1896         }
1897
1898         m->valid = 0;
1899         vm_page_undirty(m);
1900
1901         if (m->wire_count != 0)
1902                 panic("vm_page_free: freeing wired page %p", m);
1903         if (m->hold_count != 0) {
1904                 m->flags &= ~PG_ZERO;
1905                 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
1906                     ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
1907                 m->flags |= PG_UNHOLDFREE;
1908         } else {
1909                 /*
1910                  * Restore the default memory attribute to the page.
1911                  */
1912                 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
1913                         pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
1914
1915                 /*
1916                  * Insert the page into the physical memory allocator's
1917                  * cache/free page queues.
1918                  */
1919                 mtx_lock(&vm_page_queue_free_mtx);
1920                 m->flags |= PG_FREE;
1921                 cnt.v_free_count++;
1922 #if VM_NRESERVLEVEL > 0
1923                 if (!vm_reserv_free_page(m))
1924 #else
1925                 if (TRUE)
1926 #endif
1927                         vm_phys_free_pages(m, 0);
1928                 if ((m->flags & PG_ZERO) != 0)
1929                         ++vm_page_zero_count;
1930                 else
1931                         vm_page_zero_idle_wakeup();
1932                 vm_page_free_wakeup();
1933                 mtx_unlock(&vm_page_queue_free_mtx);
1934         }
1935 }
1936
1937 /*
1938  *      vm_page_wire:
1939  *
1940  *      Mark this page as wired down by yet
1941  *      another map, removing it from paging queues
1942  *      as necessary.
1943  *
1944  *      If the page is fictitious, then its wire count must remain one.
1945  *
1946  *      The page must be locked.
1947  */
1948 void
1949 vm_page_wire(vm_page_t m)
1950 {
1951
1952         /*
1953          * Only bump the wire statistics if the page is not already wired,
1954          * and only unqueue the page if it is on some queue (if it is unmanaged
1955          * it is already off the queues).
1956          */
1957         vm_page_lock_assert(m, MA_OWNED);
1958         if ((m->flags & PG_FICTITIOUS) != 0) {
1959                 KASSERT(m->wire_count == 1,
1960                     ("vm_page_wire: fictitious page %p's wire count isn't one",
1961                     m));
1962                 return;
1963         }
1964         if (m->wire_count == 0) {
1965                 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
1966                     m->queue == PQ_NONE,
1967                     ("vm_page_wire: unmanaged page %p is queued", m));
1968                 vm_page_remque(m);
1969                 atomic_add_int(&cnt.v_wire_count, 1);
1970         }
1971         m->wire_count++;
1972         KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
1973 }
1974
1975 /*
1976  * vm_page_unwire:
1977  *
1978  * Release one wiring of the specified page, potentially enabling it to be
1979  * paged again.  If paging is enabled, then the value of the parameter
1980  * "activate" determines to which queue the page is added.  If "activate" is
1981  * non-zero, then the page is added to the active queue.  Otherwise, it is
1982  * added to the inactive queue.
1983  *
1984  * However, unless the page belongs to an object, it is not enqueued because
1985  * it cannot be paged out.
1986  *
1987  * If a page is fictitious, then its wire count must alway be one.
1988  *
1989  * A managed page must be locked.
1990  */
1991 void
1992 vm_page_unwire(vm_page_t m, int activate)
1993 {
1994
1995         if ((m->oflags & VPO_UNMANAGED) == 0)
1996                 vm_page_lock_assert(m, MA_OWNED);
1997         if ((m->flags & PG_FICTITIOUS) != 0) {
1998                 KASSERT(m->wire_count == 1,
1999             ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
2000                 return;
2001         }
2002         if (m->wire_count > 0) {
2003                 m->wire_count--;
2004                 if (m->wire_count == 0) {
2005                         atomic_subtract_int(&cnt.v_wire_count, 1);
2006                         if ((m->oflags & VPO_UNMANAGED) != 0 ||
2007                             m->object == NULL)
2008                                 return;
2009                         if (!activate)
2010                                 m->flags &= ~PG_WINATCFLS;
2011                         vm_page_enqueue(activate ? PQ_ACTIVE : PQ_INACTIVE, m);
2012                 }
2013         } else
2014                 panic("vm_page_unwire: page %p's wire count is zero", m);
2015 }
2016
2017 /*
2018  * Move the specified page to the inactive queue.
2019  *
2020  * Many pages placed on the inactive queue should actually go
2021  * into the cache, but it is difficult to figure out which.  What
2022  * we do instead, if the inactive target is well met, is to put
2023  * clean pages at the head of the inactive queue instead of the tail.
2024  * This will cause them to be moved to the cache more quickly and
2025  * if not actively re-referenced, reclaimed more quickly.  If we just
2026  * stick these pages at the end of the inactive queue, heavy filesystem
2027  * meta-data accesses can cause an unnecessary paging load on memory bound 
2028  * processes.  This optimization causes one-time-use metadata to be
2029  * reused more quickly.
2030  *
2031  * Normally athead is 0 resulting in LRU operation.  athead is set
2032  * to 1 if we want this page to be 'as if it were placed in the cache',
2033  * except without unmapping it from the process address space.
2034  *
2035  * The page must be locked.
2036  */
2037 static inline void
2038 _vm_page_deactivate(vm_page_t m, int athead)
2039 {
2040         struct vm_pagequeue *pq;
2041         int queue;
2042
2043         vm_page_lock_assert(m, MA_OWNED);
2044
2045         /*
2046          * Ignore if already inactive.
2047          */
2048         if ((queue = m->queue) == PQ_INACTIVE)
2049                 return;
2050         if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2051                 if (queue != PQ_NONE)
2052                         vm_page_dequeue(m);
2053                 m->flags &= ~PG_WINATCFLS;
2054                 pq = &vm_pagequeues[PQ_INACTIVE];
2055                 vm_pagequeue_lock(pq);
2056                 m->queue = PQ_INACTIVE;
2057                 if (athead)
2058                         TAILQ_INSERT_HEAD(&pq->pq_pl, m, pageq);
2059                 else
2060                         TAILQ_INSERT_TAIL(&pq->pq_pl, m, pageq);
2061                 cnt.v_inactive_count++;
2062                 vm_pagequeue_unlock(pq);
2063         }
2064 }
2065
2066 /*
2067  * Move the specified page to the inactive queue.
2068  *
2069  * The page must be locked.
2070  */
2071 void
2072 vm_page_deactivate(vm_page_t m)
2073 {
2074
2075         _vm_page_deactivate(m, 0);
2076 }
2077
2078 /*
2079  * vm_page_try_to_cache:
2080  *
2081  * Returns 0 on failure, 1 on success
2082  */
2083 int
2084 vm_page_try_to_cache(vm_page_t m)
2085 {
2086
2087         vm_page_lock_assert(m, MA_OWNED);
2088         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2089         if (m->dirty || m->hold_count || m->busy || m->wire_count ||
2090             (m->oflags & (VPO_BUSY | VPO_UNMANAGED)) != 0)
2091                 return (0);
2092         pmap_remove_all(m);
2093         if (m->dirty)
2094                 return (0);
2095         vm_page_cache(m);
2096         return (1);
2097 }
2098
2099 /*
2100  * vm_page_try_to_free()
2101  *
2102  *      Attempt to free the page.  If we cannot free it, we do nothing.
2103  *      1 is returned on success, 0 on failure.
2104  */
2105 int
2106 vm_page_try_to_free(vm_page_t m)
2107 {
2108
2109         vm_page_lock_assert(m, MA_OWNED);
2110         if (m->object != NULL)
2111                 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2112         if (m->dirty || m->hold_count || m->busy || m->wire_count ||
2113             (m->oflags & (VPO_BUSY | VPO_UNMANAGED)) != 0)
2114                 return (0);
2115         pmap_remove_all(m);
2116         if (m->dirty)
2117                 return (0);
2118         vm_page_free(m);
2119         return (1);
2120 }
2121
2122 /*
2123  * vm_page_cache
2124  *
2125  * Put the specified page onto the page cache queue (if appropriate).
2126  *
2127  * The object and page must be locked.
2128  */
2129 void
2130 vm_page_cache(vm_page_t m)
2131 {
2132         vm_object_t object;
2133         int old_empty_cache;
2134
2135         vm_page_lock_assert(m, MA_OWNED);
2136         object = m->object;
2137         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2138         if ((m->oflags & (VPO_UNMANAGED | VPO_BUSY)) || m->busy ||
2139             m->hold_count || m->wire_count)
2140                 panic("vm_page_cache: attempting to cache busy page");
2141         KASSERT(!pmap_page_is_mapped(m),
2142             ("vm_page_cache: page %p is mapped", m));
2143         KASSERT(m->dirty == 0, ("vm_page_cache: page %p is dirty", m));
2144         if (m->valid == 0 || object->type == OBJT_DEFAULT ||
2145             (object->type == OBJT_SWAP &&
2146             !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
2147                 /*
2148                  * Hypothesis: A cache-elgible page belonging to a
2149                  * default object or swap object but without a backing
2150                  * store must be zero filled.
2151                  */
2152                 vm_page_free(m);
2153                 return;
2154         }
2155         KASSERT((m->flags & PG_CACHED) == 0,
2156             ("vm_page_cache: page %p is already cached", m));
2157         PCPU_INC(cnt.v_tcached);
2158
2159         /*
2160          * Remove the page from the paging queues.
2161          */
2162         vm_page_remque(m);
2163
2164         vm_radix_remove(&object->rtree, m->pindex);
2165         TAILQ_REMOVE(&object->memq, m, listq);
2166         object->resident_page_count--;
2167
2168         /*
2169          * Restore the default memory attribute to the page.
2170          */
2171         if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2172                 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2173
2174         /*
2175          * Insert the page into the object's collection of cached pages
2176          * and the physical memory allocator's cache/free page queues.
2177          */
2178         m->flags &= ~PG_ZERO;
2179         mtx_lock(&vm_page_queue_free_mtx);
2180         m->flags |= PG_CACHED;
2181         old_empty_cache = vm_object_cache_is_empty(object);
2182         cnt.v_cache_count++;
2183         if (vm_radix_insert(&object->cache, m->pindex, m) != 0)
2184                 panic("vm_page_cache: vm_radix_insert failed");
2185 #if VM_NRESERVLEVEL > 0
2186         if (!vm_reserv_free_page(m)) {
2187 #else
2188         if (TRUE) {
2189 #endif
2190                 vm_phys_set_pool(VM_FREEPOOL_CACHE, m, 0);
2191                 vm_phys_free_pages(m, 0);
2192         }
2193         vm_page_free_wakeup();
2194         mtx_unlock(&vm_page_queue_free_mtx);
2195
2196         /*
2197          * Increment the vnode's hold count if this is the object's only
2198          * cached page.  Decrement the vnode's hold count if this was
2199          * the object's only resident page.
2200          */
2201         if (object->type == OBJT_VNODE) {
2202                 if (old_empty_cache != 0 && object->resident_page_count != 0)
2203                         vhold(object->handle);
2204                 else if (old_empty_cache == 0 &&
2205                     object->resident_page_count == 0)
2206                         vdrop(object->handle);
2207         }
2208 }
2209
2210 /*
2211  * vm_page_dontneed
2212  *
2213  *      Cache, deactivate, or do nothing as appropriate.  This routine
2214  *      is typically used by madvise() MADV_DONTNEED.
2215  *
2216  *      Generally speaking we want to move the page into the cache so
2217  *      it gets reused quickly.  However, this can result in a silly syndrome
2218  *      due to the page recycling too quickly.  Small objects will not be
2219  *      fully cached.  On the otherhand, if we move the page to the inactive
2220  *      queue we wind up with a problem whereby very large objects 
2221  *      unnecessarily blow away our inactive and cache queues.
2222  *
2223  *      The solution is to move the pages based on a fixed weighting.  We
2224  *      either leave them alone, deactivate them, or move them to the cache,
2225  *      where moving them to the cache has the highest weighting.
2226  *      By forcing some pages into other queues we eventually force the
2227  *      system to balance the queues, potentially recovering other unrelated
2228  *      space from active.  The idea is to not force this to happen too
2229  *      often.
2230  *
2231  *      The object and page must be locked.
2232  */
2233 void
2234 vm_page_dontneed(vm_page_t m)
2235 {
2236         int dnw;
2237         int head;
2238
2239         vm_page_lock_assert(m, MA_OWNED);
2240         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2241         dnw = PCPU_GET(dnweight);
2242         PCPU_INC(dnweight);
2243
2244         /*
2245          * Occasionally leave the page alone.
2246          */
2247         if ((dnw & 0x01F0) == 0 || m->queue == PQ_INACTIVE) {
2248                 if (m->act_count >= ACT_INIT)
2249                         --m->act_count;
2250                 return;
2251         }
2252
2253         /*
2254          * Clear any references to the page.  Otherwise, the page daemon will
2255          * immediately reactivate the page.
2256          *
2257          * Perform the pmap_clear_reference() first.  Otherwise, a concurrent
2258          * pmap operation, such as pmap_remove(), could clear a reference in
2259          * the pmap and set PGA_REFERENCED on the page before the
2260          * pmap_clear_reference() had completed.  Consequently, the page would
2261          * appear referenced based upon an old reference that occurred before
2262          * this function ran.
2263          */
2264         pmap_clear_reference(m);
2265         vm_page_aflag_clear(m, PGA_REFERENCED);
2266
2267         if (m->dirty == 0 && pmap_is_modified(m))
2268                 vm_page_dirty(m);
2269
2270         if (m->dirty || (dnw & 0x0070) == 0) {
2271                 /*
2272                  * Deactivate the page 3 times out of 32.
2273                  */
2274                 head = 0;
2275         } else {
2276                 /*
2277                  * Cache the page 28 times out of every 32.  Note that
2278                  * the page is deactivated instead of cached, but placed
2279                  * at the head of the queue instead of the tail.
2280                  */
2281                 head = 1;
2282         }
2283         _vm_page_deactivate(m, head);
2284 }
2285
2286 /*
2287  * Grab a page, waiting until we are waken up due to the page
2288  * changing state.  We keep on waiting, if the page continues
2289  * to be in the object.  If the page doesn't exist, first allocate it
2290  * and then conditionally zero it.
2291  *
2292  * The caller must always specify the VM_ALLOC_RETRY flag.  This is intended
2293  * to facilitate its eventual removal.
2294  *
2295  * This routine may sleep.
2296  *
2297  * The object must be locked on entry.  The lock will, however, be released
2298  * and reacquired if the routine sleeps.
2299  */
2300 vm_page_t
2301 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2302 {
2303         vm_page_t m;
2304
2305         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2306         KASSERT((allocflags & VM_ALLOC_RETRY) != 0,
2307             ("vm_page_grab: VM_ALLOC_RETRY is required"));
2308 retrylookup:
2309         if ((m = vm_page_lookup(object, pindex)) != NULL) {
2310                 if ((m->oflags & VPO_BUSY) != 0 ||
2311                     ((allocflags & VM_ALLOC_IGN_SBUSY) == 0 && m->busy != 0)) {
2312                         /*
2313                          * Reference the page before unlocking and
2314                          * sleeping so that the page daemon is less
2315                          * likely to reclaim it.
2316                          */
2317                         vm_page_aflag_set(m, PGA_REFERENCED);
2318                         vm_page_sleep(m, "pgrbwt");
2319                         goto retrylookup;
2320                 } else {
2321                         if ((allocflags & VM_ALLOC_WIRED) != 0) {
2322                                 vm_page_lock(m);
2323                                 vm_page_wire(m);
2324                                 vm_page_unlock(m);
2325                         }
2326                         if ((allocflags & VM_ALLOC_NOBUSY) == 0)
2327                                 vm_page_busy(m);
2328                         return (m);
2329                 }
2330         }
2331         m = vm_page_alloc(object, pindex, allocflags & ~(VM_ALLOC_RETRY |
2332             VM_ALLOC_IGN_SBUSY));
2333         if (m == NULL) {
2334                 VM_OBJECT_UNLOCK(object);
2335                 VM_WAIT;
2336                 VM_OBJECT_LOCK(object);
2337                 goto retrylookup;
2338         } else if (m->valid != 0)
2339                 return (m);
2340         if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
2341                 pmap_zero_page(m);
2342         return (m);
2343 }
2344
2345 /*
2346  * Mapping function for valid or dirty bits in a page.
2347  *
2348  * Inputs are required to range within a page.
2349  */
2350 vm_page_bits_t
2351 vm_page_bits(int base, int size)
2352 {
2353         int first_bit;
2354         int last_bit;
2355
2356         KASSERT(
2357             base + size <= PAGE_SIZE,
2358             ("vm_page_bits: illegal base/size %d/%d", base, size)
2359         );
2360
2361         if (size == 0)          /* handle degenerate case */
2362                 return (0);
2363
2364         first_bit = base >> DEV_BSHIFT;
2365         last_bit = (base + size - 1) >> DEV_BSHIFT;
2366
2367         return (((vm_page_bits_t)2 << last_bit) -
2368             ((vm_page_bits_t)1 << first_bit));
2369 }
2370
2371 /*
2372  *      vm_page_set_valid_range:
2373  *
2374  *      Sets portions of a page valid.  The arguments are expected
2375  *      to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2376  *      of any partial chunks touched by the range.  The invalid portion of
2377  *      such chunks will be zeroed.
2378  *
2379  *      (base + size) must be less then or equal to PAGE_SIZE.
2380  */
2381 void
2382 vm_page_set_valid_range(vm_page_t m, int base, int size)
2383 {
2384         int endoff, frag;
2385
2386         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2387         if (size == 0)  /* handle degenerate case */
2388                 return;
2389
2390         /*
2391          * If the base is not DEV_BSIZE aligned and the valid
2392          * bit is clear, we have to zero out a portion of the
2393          * first block.
2394          */
2395         if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2396             (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2397                 pmap_zero_page_area(m, frag, base - frag);
2398
2399         /*
2400          * If the ending offset is not DEV_BSIZE aligned and the 
2401          * valid bit is clear, we have to zero out a portion of
2402          * the last block.
2403          */
2404         endoff = base + size;
2405         if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2406             (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2407                 pmap_zero_page_area(m, endoff,
2408                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2409
2410         /*
2411          * Assert that no previously invalid block that is now being validated
2412          * is already dirty. 
2413          */
2414         KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
2415             ("vm_page_set_valid_range: page %p is dirty", m));
2416
2417         /*
2418          * Set valid bits inclusive of any overlap.
2419          */
2420         m->valid |= vm_page_bits(base, size);
2421 }
2422
2423 /*
2424  * Clear the given bits from the specified page's dirty field.
2425  */
2426 static __inline void
2427 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
2428 {
2429         uintptr_t addr;
2430 #if PAGE_SIZE < 16384
2431         int shift;
2432 #endif
2433
2434         /*
2435          * If the object is locked and the page is neither VPO_BUSY nor
2436          * write mapped, then the page's dirty field cannot possibly be
2437          * set by a concurrent pmap operation.
2438          */
2439         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2440         if ((m->oflags & VPO_BUSY) == 0 && !pmap_page_is_write_mapped(m))
2441                 m->dirty &= ~pagebits;
2442         else {
2443                 /*
2444                  * The pmap layer can call vm_page_dirty() without
2445                  * holding a distinguished lock.  The combination of
2446                  * the object's lock and an atomic operation suffice
2447                  * to guarantee consistency of the page dirty field.
2448                  *
2449                  * For PAGE_SIZE == 32768 case, compiler already
2450                  * properly aligns the dirty field, so no forcible
2451                  * alignment is needed. Only require existence of
2452                  * atomic_clear_64 when page size is 32768.
2453                  */
2454                 addr = (uintptr_t)&m->dirty;
2455 #if PAGE_SIZE == 32768
2456                 atomic_clear_64((uint64_t *)addr, pagebits);
2457 #elif PAGE_SIZE == 16384
2458                 atomic_clear_32((uint32_t *)addr, pagebits);
2459 #else           /* PAGE_SIZE <= 8192 */
2460                 /*
2461                  * Use a trick to perform a 32-bit atomic on the
2462                  * containing aligned word, to not depend on the existence
2463                  * of atomic_clear_{8, 16}.
2464                  */
2465                 shift = addr & (sizeof(uint32_t) - 1);
2466 #if BYTE_ORDER == BIG_ENDIAN
2467                 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
2468 #else
2469                 shift *= NBBY;
2470 #endif
2471                 addr &= ~(sizeof(uint32_t) - 1);
2472                 atomic_clear_32((uint32_t *)addr, pagebits << shift);
2473 #endif          /* PAGE_SIZE */
2474         }
2475 }
2476
2477 /*
2478  *      vm_page_set_validclean:
2479  *
2480  *      Sets portions of a page valid and clean.  The arguments are expected
2481  *      to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2482  *      of any partial chunks touched by the range.  The invalid portion of
2483  *      such chunks will be zero'd.
2484  *
2485  *      (base + size) must be less then or equal to PAGE_SIZE.
2486  */
2487 void
2488 vm_page_set_validclean(vm_page_t m, int base, int size)
2489 {
2490         vm_page_bits_t oldvalid, pagebits;
2491         int endoff, frag;
2492
2493         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2494         if (size == 0)  /* handle degenerate case */
2495                 return;
2496
2497         /*
2498          * If the base is not DEV_BSIZE aligned and the valid
2499          * bit is clear, we have to zero out a portion of the
2500          * first block.
2501          */
2502         if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2503             (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
2504                 pmap_zero_page_area(m, frag, base - frag);
2505
2506         /*
2507          * If the ending offset is not DEV_BSIZE aligned and the 
2508          * valid bit is clear, we have to zero out a portion of
2509          * the last block.
2510          */
2511         endoff = base + size;
2512         if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2513             (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
2514                 pmap_zero_page_area(m, endoff,
2515                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2516
2517         /*
2518          * Set valid, clear dirty bits.  If validating the entire
2519          * page we can safely clear the pmap modify bit.  We also
2520          * use this opportunity to clear the VPO_NOSYNC flag.  If a process
2521          * takes a write fault on a MAP_NOSYNC memory area the flag will
2522          * be set again.
2523          *
2524          * We set valid bits inclusive of any overlap, but we can only
2525          * clear dirty bits for DEV_BSIZE chunks that are fully within
2526          * the range.
2527          */
2528         oldvalid = m->valid;
2529         pagebits = vm_page_bits(base, size);
2530         m->valid |= pagebits;
2531 #if 0   /* NOT YET */
2532         if ((frag = base & (DEV_BSIZE - 1)) != 0) {
2533                 frag = DEV_BSIZE - frag;
2534                 base += frag;
2535                 size -= frag;
2536                 if (size < 0)
2537                         size = 0;
2538         }
2539         pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
2540 #endif
2541         if (base == 0 && size == PAGE_SIZE) {
2542                 /*
2543                  * The page can only be modified within the pmap if it is
2544                  * mapped, and it can only be mapped if it was previously
2545                  * fully valid.
2546                  */
2547                 if (oldvalid == VM_PAGE_BITS_ALL)
2548                         /*
2549                          * Perform the pmap_clear_modify() first.  Otherwise,
2550                          * a concurrent pmap operation, such as
2551                          * pmap_protect(), could clear a modification in the
2552                          * pmap and set the dirty field on the page before
2553                          * pmap_clear_modify() had begun and after the dirty
2554                          * field was cleared here.
2555                          */
2556                         pmap_clear_modify(m);
2557                 m->dirty = 0;
2558                 m->oflags &= ~VPO_NOSYNC;
2559         } else if (oldvalid != VM_PAGE_BITS_ALL)
2560                 m->dirty &= ~pagebits;
2561         else
2562                 vm_page_clear_dirty_mask(m, pagebits);
2563 }
2564
2565 void
2566 vm_page_clear_dirty(vm_page_t m, int base, int size)
2567 {
2568
2569         vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
2570 }
2571
2572 /*
2573  *      vm_page_set_invalid:
2574  *
2575  *      Invalidates DEV_BSIZE'd chunks within a page.  Both the
2576  *      valid and dirty bits for the effected areas are cleared.
2577  */
2578 void
2579 vm_page_set_invalid(vm_page_t m, int base, int size)
2580 {
2581         vm_page_bits_t bits;
2582
2583         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2584         KASSERT((m->oflags & VPO_BUSY) == 0,
2585             ("vm_page_set_invalid: page %p is busy", m));
2586         bits = vm_page_bits(base, size);
2587         if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
2588                 pmap_remove_all(m);
2589         KASSERT(!pmap_page_is_mapped(m),
2590             ("vm_page_set_invalid: page %p is mapped", m));
2591         m->valid &= ~bits;
2592         m->dirty &= ~bits;
2593 }
2594
2595 /*
2596  * vm_page_zero_invalid()
2597  *
2598  *      The kernel assumes that the invalid portions of a page contain 
2599  *      garbage, but such pages can be mapped into memory by user code.
2600  *      When this occurs, we must zero out the non-valid portions of the
2601  *      page so user code sees what it expects.
2602  *
2603  *      Pages are most often semi-valid when the end of a file is mapped 
2604  *      into memory and the file's size is not page aligned.
2605  */
2606 void
2607 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
2608 {
2609         int b;
2610         int i;
2611
2612         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2613         /*
2614          * Scan the valid bits looking for invalid sections that
2615          * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
2616          * valid bit may be set ) have already been zerod by
2617          * vm_page_set_validclean().
2618          */
2619         for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
2620                 if (i == (PAGE_SIZE / DEV_BSIZE) || 
2621                     (m->valid & ((vm_page_bits_t)1 << i))) {
2622                         if (i > b) {
2623                                 pmap_zero_page_area(m, 
2624                                     b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
2625                         }
2626                         b = i + 1;
2627                 }
2628         }
2629
2630         /*
2631          * setvalid is TRUE when we can safely set the zero'd areas
2632          * as being valid.  We can do this if there are no cache consistancy
2633          * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
2634          */
2635         if (setvalid)
2636                 m->valid = VM_PAGE_BITS_ALL;
2637 }
2638
2639 /*
2640  *      vm_page_is_valid:
2641  *
2642  *      Is (partial) page valid?  Note that the case where size == 0
2643  *      will return FALSE in the degenerate case where the page is
2644  *      entirely invalid, and TRUE otherwise.
2645  */
2646 int
2647 vm_page_is_valid(vm_page_t m, int base, int size)
2648 {
2649         vm_page_bits_t bits;
2650
2651         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2652         bits = vm_page_bits(base, size);
2653         if (m->valid && ((m->valid & bits) == bits))
2654                 return 1;
2655         else
2656                 return 0;
2657 }
2658
2659 /*
2660  * Set the page's dirty bits if the page is modified.
2661  */
2662 void
2663 vm_page_test_dirty(vm_page_t m)
2664 {
2665
2666         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2667         if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
2668                 vm_page_dirty(m);
2669 }
2670
2671 void
2672 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
2673 {
2674
2675         mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
2676 }
2677
2678 void
2679 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
2680 {
2681
2682         mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
2683 }
2684
2685 int
2686 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
2687 {
2688
2689         return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
2690 }
2691
2692 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
2693 void
2694 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
2695 {
2696
2697         mtx_assert_(vm_page_lockptr(m), a, file, line);
2698 }
2699 #endif
2700
2701 int so_zerocp_fullpage = 0;
2702
2703 /*
2704  *      Replace the given page with a copy.  The copied page assumes
2705  *      the portion of the given page's "wire_count" that is not the
2706  *      responsibility of this copy-on-write mechanism.
2707  *
2708  *      The object containing the given page must have a non-zero
2709  *      paging-in-progress count and be locked.
2710  */
2711 void
2712 vm_page_cowfault(vm_page_t m)
2713 {
2714         vm_page_t mnew;
2715         vm_object_t object;
2716         vm_pindex_t pindex;
2717
2718         vm_page_lock_assert(m, MA_OWNED);
2719         object = m->object;
2720         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2721         KASSERT(object->paging_in_progress != 0,
2722             ("vm_page_cowfault: object %p's paging-in-progress count is zero.",
2723             object)); 
2724         pindex = m->pindex;
2725
2726  retry_alloc:
2727         pmap_remove_all(m);
2728         vm_page_remove(m);
2729         mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY);
2730         if (mnew == NULL) {
2731                 vm_page_insert(m, object, pindex);
2732                 vm_page_unlock(m);
2733                 VM_OBJECT_UNLOCK(object);
2734                 VM_WAIT;
2735                 VM_OBJECT_LOCK(object);
2736                 if (m == vm_page_lookup(object, pindex)) {
2737                         vm_page_lock(m);
2738                         goto retry_alloc;
2739                 } else {
2740                         /*
2741                          * Page disappeared during the wait.
2742                          */
2743                         return;
2744                 }
2745         }
2746
2747         if (m->cow == 0) {
2748                 /* 
2749                  * check to see if we raced with an xmit complete when 
2750                  * waiting to allocate a page.  If so, put things back 
2751                  * the way they were 
2752                  */
2753                 vm_page_unlock(m);
2754                 vm_page_lock(mnew);
2755                 vm_page_free(mnew);
2756                 vm_page_unlock(mnew);
2757                 vm_page_insert(m, object, pindex);
2758         } else { /* clear COW & copy page */
2759                 if (!so_zerocp_fullpage)
2760                         pmap_copy_page(m, mnew);
2761                 mnew->valid = VM_PAGE_BITS_ALL;
2762                 vm_page_dirty(mnew);
2763                 mnew->wire_count = m->wire_count - m->cow;
2764                 m->wire_count = m->cow;
2765                 vm_page_unlock(m);
2766         }
2767 }
2768
2769 void 
2770 vm_page_cowclear(vm_page_t m)
2771 {
2772
2773         vm_page_lock_assert(m, MA_OWNED);
2774         if (m->cow) {
2775                 m->cow--;
2776                 /* 
2777                  * let vm_fault add back write permission  lazily
2778                  */
2779         } 
2780         /*
2781          *  sf_buf_free() will free the page, so we needn't do it here
2782          */ 
2783 }
2784
2785 int
2786 vm_page_cowsetup(vm_page_t m)
2787 {
2788
2789         vm_page_lock_assert(m, MA_OWNED);
2790         if ((m->flags & PG_FICTITIOUS) != 0 ||
2791             (m->oflags & VPO_UNMANAGED) != 0 ||
2792             m->cow == USHRT_MAX - 1 || !VM_OBJECT_TRYLOCK(m->object))
2793                 return (EBUSY);
2794         m->cow++;
2795         pmap_remove_write(m);
2796         VM_OBJECT_UNLOCK(m->object);
2797         return (0);
2798 }
2799
2800 #ifdef INVARIANTS
2801 void
2802 vm_page_object_lock_assert(vm_page_t m)
2803 {
2804
2805         /*
2806          * Certain of the page's fields may only be modified by the
2807          * holder of the containing object's lock or the setter of the
2808          * page's VPO_BUSY flag.  Unfortunately, the setter of the
2809          * VPO_BUSY flag is not recorded, and thus cannot be checked
2810          * here.
2811          */
2812         if (m->object != NULL && (m->oflags & VPO_BUSY) == 0)
2813                 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2814 }
2815 #endif
2816
2817 #include "opt_ddb.h"
2818 #ifdef DDB
2819 #include <sys/kernel.h>
2820
2821 #include <ddb/ddb.h>
2822
2823 DB_SHOW_COMMAND(page, vm_page_print_page_info)
2824 {
2825         db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
2826         db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
2827         db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
2828         db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
2829         db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
2830         db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
2831         db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
2832         db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
2833         db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
2834         db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
2835 }
2836
2837 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
2838 {
2839                 
2840         db_printf("PQ_FREE:");
2841         db_printf(" %d", cnt.v_free_count);
2842         db_printf("\n");
2843                 
2844         db_printf("PQ_CACHE:");
2845         db_printf(" %d", cnt.v_cache_count);
2846         db_printf("\n");
2847
2848         db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
2849                 *vm_pagequeues[PQ_ACTIVE].pq_cnt,
2850                 *vm_pagequeues[PQ_INACTIVE].pq_cnt);
2851 }
2852 #endif /* DDB */