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