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