The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/vm/vm_page.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

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

Cache object: 7d1a4107f5ef3608edf7acfda5dc4455


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.