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: releng/7.3/sys/vm/vm_page.c 197197 2009-09-14 17:34:49Z jhb $");
  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(m != NULL, ("vm_page_alloc: missing page"));
 1098         KASSERT(m->queue == PQ_NONE,
 1099             ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
 1100         KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
 1101         KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
 1102         KASSERT(m->busy == 0, ("vm_page_alloc: page %p is busy", m));
 1103         KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
 1104         KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
 1105             ("vm_page_alloc: page %p has unexpected memattr %d", m,
 1106             pmap_page_get_memattr(m)));
 1107         if ((m->flags & PG_CACHED) != 0) {
 1108                 KASSERT(m->valid != 0,
 1109                     ("vm_page_alloc: cached page %p is invalid", m));
 1110                 if (m->object == object && m->pindex == pindex)
 1111                         cnt.v_reactivated++;
 1112                 else
 1113                         m->valid = 0;
 1114                 m_object = m->object;
 1115                 vm_page_cache_remove(m);
 1116                 if (m_object->type == OBJT_VNODE && m_object->cache == NULL)
 1117                         vp = m_object->handle;
 1118         } else {
 1119                 KASSERT(VM_PAGE_IS_FREE(m),
 1120                     ("vm_page_alloc: page %p is not free", m));
 1121                 KASSERT(m->valid == 0,
 1122                     ("vm_page_alloc: free page %p is valid", m));
 1123                 cnt.v_free_count--;
 1124         }
 1125 
 1126         /*
 1127          * Initialize structure.  Only the PG_ZERO flag is inherited.
 1128          */
 1129         flags = 0;
 1130         if (m->flags & PG_ZERO) {
 1131                 vm_page_zero_count--;
 1132                 if (req & VM_ALLOC_ZERO)
 1133                         flags = PG_ZERO;
 1134         }
 1135         if (object == NULL || object->type == OBJT_PHYS)
 1136                 flags |= PG_UNMANAGED;
 1137         m->flags = flags;
 1138         if (req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ))
 1139                 m->oflags = 0;
 1140         else
 1141                 m->oflags = VPO_BUSY;
 1142         if (req & VM_ALLOC_WIRED) {
 1143                 atomic_add_int(&cnt.v_wire_count, 1);
 1144                 m->wire_count = 1;
 1145         }
 1146         m->act_count = 0;
 1147         mtx_unlock(&vm_page_queue_free_mtx);
 1148 
 1149         if (object != NULL) {
 1150                 /* Ignore device objects; the pager sets "memattr" for them. */
 1151                 if (object->memattr != VM_MEMATTR_DEFAULT &&
 1152                     object->type != OBJT_DEVICE && object->type != OBJT_SG)
 1153                         pmap_page_set_memattr(m, object->memattr);
 1154                 vm_page_insert(m, object, pindex);
 1155         } else
 1156                 m->pindex = pindex;
 1157 
 1158         /*
 1159          * The following call to vdrop() must come after the above call
 1160          * to vm_page_insert() in case both affect the same object and
 1161          * vnode.  Otherwise, the affected vnode's hold count could
 1162          * temporarily become zero.
 1163          */
 1164         if (vp != NULL)
 1165                 vdrop(vp);
 1166 
 1167         /*
 1168          * Don't wakeup too often - wakeup the pageout daemon when
 1169          * we would be nearly out of memory.
 1170          */
 1171         if (vm_paging_needed())
 1172                 pagedaemon_wakeup();
 1173 
 1174         return (m);
 1175 }
 1176 
 1177 /*
 1178  *      vm_wait:        (also see VM_WAIT macro)
 1179  *
 1180  *      Block until free pages are available for allocation
 1181  *      - Called in various places before memory allocations.
 1182  */
 1183 void
 1184 vm_wait(void)
 1185 {
 1186 
 1187         mtx_lock(&vm_page_queue_free_mtx);
 1188         if (curproc == pageproc) {
 1189                 vm_pageout_pages_needed = 1;
 1190                 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
 1191                     PDROP | PSWP, "VMWait", 0);
 1192         } else {
 1193                 if (!vm_pages_needed) {
 1194                         vm_pages_needed = 1;
 1195                         wakeup(&vm_pages_needed);
 1196                 }
 1197                 msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
 1198                     "vmwait", 0);
 1199         }
 1200 }
 1201 
 1202 /*
 1203  *      vm_waitpfault:  (also see VM_WAITPFAULT macro)
 1204  *
 1205  *      Block until free pages are available for allocation
 1206  *      - Called only in vm_fault so that processes page faulting
 1207  *        can be easily tracked.
 1208  *      - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
 1209  *        processes will be able to grab memory first.  Do not change
 1210  *        this balance without careful testing first.
 1211  */
 1212 void
 1213 vm_waitpfault(void)
 1214 {
 1215 
 1216         mtx_lock(&vm_page_queue_free_mtx);
 1217         if (!vm_pages_needed) {
 1218                 vm_pages_needed = 1;
 1219                 wakeup(&vm_pages_needed);
 1220         }
 1221         msleep(&cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
 1222             "pfault", 0);
 1223 }
 1224 
 1225 /*
 1226  *      vm_page_requeue:
 1227  *
 1228  *      If the given page is contained within a page queue, move it to the tail
 1229  *      of that queue.
 1230  *
 1231  *      The page queues must be locked.
 1232  */
 1233 void
 1234 vm_page_requeue(vm_page_t m)
 1235 {
 1236         int queue = VM_PAGE_GETQUEUE(m);
 1237         struct vpgqueues *vpq;
 1238 
 1239         if (queue != PQ_NONE) {
 1240                 vpq = &vm_page_queues[queue];
 1241                 TAILQ_REMOVE(&vpq->pl, m, pageq);
 1242                 TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
 1243         }
 1244 }
 1245 
 1246 /*
 1247  *      vm_pageq_remove:
 1248  *
 1249  *      Remove a page from its queue.
 1250  *
 1251  *      The queue containing the given page must be locked.
 1252  *      This routine may not block.
 1253  */
 1254 void
 1255 vm_pageq_remove(vm_page_t m)
 1256 {
 1257         int queue = VM_PAGE_GETQUEUE(m);
 1258         struct vpgqueues *pq;
 1259 
 1260         if (queue != PQ_NONE) {
 1261                 VM_PAGE_SETQUEUE2(m, PQ_NONE);
 1262                 pq = &vm_page_queues[queue];
 1263                 TAILQ_REMOVE(&pq->pl, m, pageq);
 1264                 (*pq->cnt)--;
 1265         }
 1266 }
 1267 
 1268 /*
 1269  *      vm_page_enqueue:
 1270  *
 1271  *      Add the given page to the specified queue.
 1272  *
 1273  *      The page queues must be locked.
 1274  */
 1275 static void
 1276 vm_page_enqueue(int queue, vm_page_t m)
 1277 {
 1278         struct vpgqueues *vpq;
 1279 
 1280         vpq = &vm_page_queues[queue];
 1281         VM_PAGE_SETQUEUE2(m, queue);
 1282         TAILQ_INSERT_TAIL(&vpq->pl, m, pageq);
 1283         ++*vpq->cnt;
 1284 }
 1285 
 1286 /*
 1287  *      vm_page_activate:
 1288  *
 1289  *      Put the specified page on the active list (if appropriate).
 1290  *      Ensure that act_count is at least ACT_INIT but do not otherwise
 1291  *      mess with it.
 1292  *
 1293  *      The page queues must be locked.
 1294  *      This routine may not block.
 1295  */
 1296 void
 1297 vm_page_activate(vm_page_t m)
 1298 {
 1299 
 1300         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 1301         if (VM_PAGE_GETKNOWNQUEUE2(m) != PQ_ACTIVE) {
 1302                 vm_pageq_remove(m);
 1303                 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
 1304                         if (m->act_count < ACT_INIT)
 1305                                 m->act_count = ACT_INIT;
 1306                         vm_page_enqueue(PQ_ACTIVE, m);
 1307                 }
 1308         } else {
 1309                 if (m->act_count < ACT_INIT)
 1310                         m->act_count = ACT_INIT;
 1311         }
 1312 }
 1313 
 1314 /*
 1315  *      vm_page_free_wakeup:
 1316  *
 1317  *      Helper routine for vm_page_free_toq() and vm_page_cache().  This
 1318  *      routine is called when a page has been added to the cache or free
 1319  *      queues.
 1320  *
 1321  *      The page queues must be locked.
 1322  *      This routine may not block.
 1323  */
 1324 static inline void
 1325 vm_page_free_wakeup(void)
 1326 {
 1327 
 1328         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
 1329         /*
 1330          * if pageout daemon needs pages, then tell it that there are
 1331          * some free.
 1332          */
 1333         if (vm_pageout_pages_needed &&
 1334             cnt.v_cache_count + cnt.v_free_count >= cnt.v_pageout_free_min) {
 1335                 wakeup(&vm_pageout_pages_needed);
 1336                 vm_pageout_pages_needed = 0;
 1337         }
 1338         /*
 1339          * wakeup processes that are waiting on memory if we hit a
 1340          * high water mark. And wakeup scheduler process if we have
 1341          * lots of memory. this process will swapin processes.
 1342          */
 1343         if (vm_pages_needed && !vm_page_count_min()) {
 1344                 vm_pages_needed = 0;
 1345                 wakeup(&cnt.v_free_count);
 1346         }
 1347 }
 1348 
 1349 /*
 1350  *      vm_page_free_toq:
 1351  *
 1352  *      Returns the given page to the free list,
 1353  *      disassociating it with any VM object.
 1354  *
 1355  *      Object and page must be locked prior to entry.
 1356  *      This routine may not block.
 1357  */
 1358 
 1359 void
 1360 vm_page_free_toq(vm_page_t m)
 1361 {
 1362 
 1363         if (VM_PAGE_GETQUEUE(m) != PQ_NONE)
 1364                 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 1365         KASSERT(!pmap_page_is_mapped(m),
 1366             ("vm_page_free_toq: freeing mapped page %p", m));
 1367         PCPU_INC(cnt.v_tfree);
 1368 
 1369         if (m->busy || VM_PAGE_IS_FREE(m)) {
 1370                 printf(
 1371                 "vm_page_free: pindex(%lu), busy(%d), VPO_BUSY(%d), hold(%d)\n",
 1372                     (u_long)m->pindex, m->busy, (m->oflags & VPO_BUSY) ? 1 : 0,
 1373                     m->hold_count);
 1374                 if (VM_PAGE_IS_FREE(m))
 1375                         panic("vm_page_free: freeing free page");
 1376                 else
 1377                         panic("vm_page_free: freeing busy page");
 1378         }
 1379 
 1380         /*
 1381          * unqueue, then remove page.  Note that we cannot destroy
 1382          * the page here because we do not want to call the pager's
 1383          * callback routine until after we've put the page on the
 1384          * appropriate free queue.
 1385          */
 1386         vm_pageq_remove(m);
 1387         vm_page_remove(m);
 1388 
 1389         /*
 1390          * If fictitious remove object association and
 1391          * return, otherwise delay object association removal.
 1392          */
 1393         if ((m->flags & PG_FICTITIOUS) != 0) {
 1394                 return;
 1395         }
 1396 
 1397         m->valid = 0;
 1398         vm_page_undirty(m);
 1399 
 1400         if (m->wire_count != 0) {
 1401                 if (m->wire_count > 1) {
 1402                         panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx",
 1403                                 m->wire_count, (long)m->pindex);
 1404                 }
 1405                 panic("vm_page_free: freeing wired page");
 1406         }
 1407         if (m->hold_count != 0) {
 1408                 m->flags &= ~PG_ZERO;
 1409                 vm_page_enqueue(PQ_HOLD, m);
 1410         } else {
 1411                 /*
 1412                  * Restore the default memory attribute to the page.
 1413                  */
 1414                 if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
 1415                         pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
 1416 
 1417                 /*
 1418                  * Insert the page into the physical memory allocator's
 1419                  * cache/free page queues.
 1420                  */
 1421                 mtx_lock(&vm_page_queue_free_mtx);
 1422                 m->flags |= PG_FREE;
 1423                 cnt.v_free_count++;
 1424 #if VM_NRESERVLEVEL > 0
 1425                 if (!vm_reserv_free_page(m))
 1426 #else
 1427                 if (TRUE)
 1428 #endif
 1429                         vm_phys_free_pages(m, 0);
 1430                 if ((m->flags & PG_ZERO) != 0)
 1431                         ++vm_page_zero_count;
 1432                 else
 1433                         vm_page_zero_idle_wakeup();
 1434                 vm_page_free_wakeup();
 1435                 mtx_unlock(&vm_page_queue_free_mtx);
 1436         }
 1437 }
 1438 
 1439 /*
 1440  *      vm_page_wire:
 1441  *
 1442  *      Mark this page as wired down by yet
 1443  *      another map, removing it from paging queues
 1444  *      as necessary.
 1445  *
 1446  *      The page queues must be locked.
 1447  *      This routine may not block.
 1448  */
 1449 void
 1450 vm_page_wire(vm_page_t m)
 1451 {
 1452 
 1453         /*
 1454          * Only bump the wire statistics if the page is not already wired,
 1455          * and only unqueue the page if it is on some queue (if it is unmanaged
 1456          * it is already off the queues).
 1457          */
 1458         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 1459         if (m->flags & PG_FICTITIOUS)
 1460                 return;
 1461         if (m->wire_count == 0) {
 1462                 if ((m->flags & PG_UNMANAGED) == 0)
 1463                         vm_pageq_remove(m);
 1464                 atomic_add_int(&cnt.v_wire_count, 1);
 1465         }
 1466         m->wire_count++;
 1467         KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
 1468 }
 1469 
 1470 /*
 1471  *      vm_page_unwire:
 1472  *
 1473  *      Release one wiring of this page, potentially
 1474  *      enabling it to be paged again.
 1475  *
 1476  *      Many pages placed on the inactive queue should actually go
 1477  *      into the cache, but it is difficult to figure out which.  What
 1478  *      we do instead, if the inactive target is well met, is to put
 1479  *      clean pages at the head of the inactive queue instead of the tail.
 1480  *      This will cause them to be moved to the cache more quickly and
 1481  *      if not actively re-referenced, freed more quickly.  If we just
 1482  *      stick these pages at the end of the inactive queue, heavy filesystem
 1483  *      meta-data accesses can cause an unnecessary paging load on memory bound 
 1484  *      processes.  This optimization causes one-time-use metadata to be
 1485  *      reused more quickly.
 1486  *
 1487  *      BUT, if we are in a low-memory situation we have no choice but to
 1488  *      put clean pages on the cache queue.
 1489  *
 1490  *      A number of routines use vm_page_unwire() to guarantee that the page
 1491  *      will go into either the inactive or active queues, and will NEVER
 1492  *      be placed in the cache - for example, just after dirtying a page.
 1493  *      dirty pages in the cache are not allowed.
 1494  *
 1495  *      The page queues must be locked.
 1496  *      This routine may not block.
 1497  */
 1498 void
 1499 vm_page_unwire(vm_page_t m, int activate)
 1500 {
 1501 
 1502         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 1503         if (m->flags & PG_FICTITIOUS)
 1504                 return;
 1505         if (m->wire_count > 0) {
 1506                 m->wire_count--;
 1507                 if (m->wire_count == 0) {
 1508                         atomic_subtract_int(&cnt.v_wire_count, 1);
 1509                         if (m->flags & PG_UNMANAGED) {
 1510                                 ;
 1511                         } else if (activate)
 1512                                 vm_page_enqueue(PQ_ACTIVE, m);
 1513                         else {
 1514                                 vm_page_flag_clear(m, PG_WINATCFLS);
 1515                                 vm_page_enqueue(PQ_INACTIVE, m);
 1516                         }
 1517                 }
 1518         } else {
 1519                 panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
 1520         }
 1521 }
 1522 
 1523 
 1524 /*
 1525  * Move the specified page to the inactive queue.  If the page has
 1526  * any associated swap, the swap is deallocated.
 1527  *
 1528  * Normally athead is 0 resulting in LRU operation.  athead is set
 1529  * to 1 if we want this page to be 'as if it were placed in the cache',
 1530  * except without unmapping it from the process address space.
 1531  *
 1532  * This routine may not block.
 1533  */
 1534 static inline void
 1535 _vm_page_deactivate(vm_page_t m, int athead)
 1536 {
 1537 
 1538         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 1539 
 1540         /*
 1541          * Ignore if already inactive.
 1542          */
 1543         if (VM_PAGE_INQUEUE2(m, PQ_INACTIVE))
 1544                 return;
 1545         if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
 1546                 vm_page_flag_clear(m, PG_WINATCFLS);
 1547                 vm_pageq_remove(m);
 1548                 if (athead)
 1549                         TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
 1550                 else
 1551                         TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
 1552                 VM_PAGE_SETQUEUE2(m, PQ_INACTIVE);
 1553                 cnt.v_inactive_count++;
 1554         }
 1555 }
 1556 
 1557 void
 1558 vm_page_deactivate(vm_page_t m)
 1559 {
 1560     _vm_page_deactivate(m, 0);
 1561 }
 1562 
 1563 /*
 1564  * vm_page_try_to_cache:
 1565  *
 1566  * Returns 0 on failure, 1 on success
 1567  */
 1568 int
 1569 vm_page_try_to_cache(vm_page_t m)
 1570 {
 1571 
 1572         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 1573         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
 1574         if (m->dirty || m->hold_count || m->busy || m->wire_count ||
 1575             (m->oflags & VPO_BUSY) || (m->flags & PG_UNMANAGED)) {
 1576                 return (0);
 1577         }
 1578         pmap_remove_all(m);
 1579         if (m->dirty)
 1580                 return (0);
 1581         vm_page_cache(m);
 1582         return (1);
 1583 }
 1584 
 1585 /*
 1586  * vm_page_try_to_free()
 1587  *
 1588  *      Attempt to free the page.  If we cannot free it, we do nothing.
 1589  *      1 is returned on success, 0 on failure.
 1590  */
 1591 int
 1592 vm_page_try_to_free(vm_page_t m)
 1593 {
 1594 
 1595         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 1596         if (m->object != NULL)
 1597                 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
 1598         if (m->dirty || m->hold_count || m->busy || m->wire_count ||
 1599             (m->oflags & VPO_BUSY) || (m->flags & PG_UNMANAGED)) {
 1600                 return (0);
 1601         }
 1602         pmap_remove_all(m);
 1603         if (m->dirty)
 1604                 return (0);
 1605         vm_page_free(m);
 1606         return (1);
 1607 }
 1608 
 1609 /*
 1610  * vm_page_cache
 1611  *
 1612  * Put the specified page onto the page cache queue (if appropriate).
 1613  *
 1614  * This routine may not block.
 1615  */
 1616 void
 1617 vm_page_cache(vm_page_t m)
 1618 {
 1619         vm_object_t object;
 1620         vm_page_t root;
 1621 
 1622         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 1623         object = m->object;
 1624         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
 1625         if ((m->flags & PG_UNMANAGED) || (m->oflags & VPO_BUSY) || m->busy ||
 1626             m->hold_count || m->wire_count) {
 1627                 panic("vm_page_cache: attempting to cache busy page");
 1628         }
 1629         pmap_remove_all(m);
 1630         if (m->dirty != 0)
 1631                 panic("vm_page_cache: page %p is dirty", m);
 1632         if (m->valid == 0 || object->type == OBJT_DEFAULT ||
 1633             (object->type == OBJT_SWAP &&
 1634             !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
 1635                 /*
 1636                  * Hypothesis: A cache-elgible page belonging to a
 1637                  * default object or swap object but without a backing
 1638                  * store must be zero filled.
 1639                  */
 1640                 vm_page_free(m);
 1641                 return;
 1642         }
 1643         KASSERT((m->flags & PG_CACHED) == 0,
 1644             ("vm_page_cache: page %p is already cached", m));
 1645         cnt.v_tcached++;
 1646 
 1647         /*
 1648          * Remove the page from the paging queues.
 1649          */
 1650         vm_pageq_remove(m);
 1651 
 1652         /*
 1653          * Remove the page from the object's collection of resident
 1654          * pages. 
 1655          */
 1656         if (m != object->root)
 1657                 vm_page_splay(m->pindex, object->root);
 1658         if (m->left == NULL)
 1659                 root = m->right;
 1660         else {
 1661                 root = vm_page_splay(m->pindex, m->left);
 1662                 root->right = m->right;
 1663         }
 1664         object->root = root;
 1665         TAILQ_REMOVE(&object->memq, m, listq);
 1666         object->resident_page_count--;
 1667         object->generation++;
 1668 
 1669         /*
 1670          * Restore the default memory attribute to the page.
 1671          */
 1672         if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
 1673                 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
 1674 
 1675         /*
 1676          * Insert the page into the object's collection of cached pages
 1677          * and the physical memory allocator's cache/free page queues.
 1678          */
 1679         vm_page_flag_clear(m, PG_ZERO);
 1680         mtx_lock(&vm_page_queue_free_mtx);
 1681         m->flags |= PG_CACHED;
 1682         cnt.v_cache_count++;
 1683         root = object->cache;
 1684         if (root == NULL) {
 1685                 m->left = NULL;
 1686                 m->right = NULL;
 1687         } else {
 1688                 root = vm_page_splay(m->pindex, root);
 1689                 if (m->pindex < root->pindex) {
 1690                         m->left = root->left;
 1691                         m->right = root;
 1692                         root->left = NULL;
 1693                 } else if (__predict_false(m->pindex == root->pindex))
 1694                         panic("vm_page_cache: offset already cached");
 1695                 else {
 1696                         m->right = root->right;
 1697                         m->left = root;
 1698                         root->right = NULL;
 1699                 }
 1700         }
 1701         object->cache = m;
 1702 #if VM_NRESERVLEVEL > 0
 1703         if (!vm_reserv_free_page(m)) {
 1704 #else
 1705         if (TRUE) {
 1706 #endif
 1707                 vm_phys_set_pool(VM_FREEPOOL_CACHE, m, 0);
 1708                 vm_phys_free_pages(m, 0);
 1709         }
 1710         vm_page_free_wakeup();
 1711         mtx_unlock(&vm_page_queue_free_mtx);
 1712 
 1713         /*
 1714          * Increment the vnode's hold count if this is the object's only
 1715          * cached page.  Decrement the vnode's hold count if this was
 1716          * the object's only resident page.
 1717          */
 1718         if (object->type == OBJT_VNODE) {
 1719                 if (root == NULL && object->resident_page_count != 0)
 1720                         vhold(object->handle);
 1721                 else if (root != NULL && object->resident_page_count == 0)
 1722                         vdrop(object->handle);
 1723         }
 1724 }
 1725 
 1726 /*
 1727  * vm_page_dontneed
 1728  *
 1729  *      Cache, deactivate, or do nothing as appropriate.  This routine
 1730  *      is typically used by madvise() MADV_DONTNEED.
 1731  *
 1732  *      Generally speaking we want to move the page into the cache so
 1733  *      it gets reused quickly.  However, this can result in a silly syndrome
 1734  *      due to the page recycling too quickly.  Small objects will not be
 1735  *      fully cached.  On the otherhand, if we move the page to the inactive
 1736  *      queue we wind up with a problem whereby very large objects 
 1737  *      unnecessarily blow away our inactive and cache queues.
 1738  *
 1739  *      The solution is to move the pages based on a fixed weighting.  We
 1740  *      either leave them alone, deactivate them, or move them to the cache,
 1741  *      where moving them to the cache has the highest weighting.
 1742  *      By forcing some pages into other queues we eventually force the
 1743  *      system to balance the queues, potentially recovering other unrelated
 1744  *      space from active.  The idea is to not force this to happen too
 1745  *      often.
 1746  */
 1747 void
 1748 vm_page_dontneed(vm_page_t m)
 1749 {
 1750         static int dnweight;
 1751         int dnw;
 1752         int head;
 1753 
 1754         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 1755         dnw = ++dnweight;
 1756 
 1757         /*
 1758          * occassionally leave the page alone
 1759          */
 1760         if ((dnw & 0x01F0) == 0 ||
 1761             VM_PAGE_INQUEUE2(m, PQ_INACTIVE)) {
 1762                 if (m->act_count >= ACT_INIT)
 1763                         --m->act_count;
 1764                 return;
 1765         }
 1766 
 1767         /*
 1768          * Clear any references to the page.  Otherwise, the page daemon will
 1769          * immediately reactivate the page.
 1770          */
 1771         vm_page_flag_clear(m, PG_REFERENCED);
 1772         pmap_clear_reference(m);
 1773 
 1774         if (m->dirty == 0 && pmap_is_modified(m))
 1775                 vm_page_dirty(m);
 1776 
 1777         if (m->dirty || (dnw & 0x0070) == 0) {
 1778                 /*
 1779                  * Deactivate the page 3 times out of 32.
 1780                  */
 1781                 head = 0;
 1782         } else {
 1783                 /*
 1784                  * Cache the page 28 times out of every 32.  Note that
 1785                  * the page is deactivated instead of cached, but placed
 1786                  * at the head of the queue instead of the tail.
 1787                  */
 1788                 head = 1;
 1789         }
 1790         _vm_page_deactivate(m, head);
 1791 }
 1792 
 1793 /*
 1794  * Grab a page, waiting until we are waken up due to the page
 1795  * changing state.  We keep on waiting, if the page continues
 1796  * to be in the object.  If the page doesn't exist, first allocate it
 1797  * and then conditionally zero it.
 1798  *
 1799  * This routine may block.
 1800  */
 1801 vm_page_t
 1802 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
 1803 {
 1804         vm_page_t m;
 1805 
 1806         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
 1807 retrylookup:
 1808         if ((m = vm_page_lookup(object, pindex)) != NULL) {
 1809                 if (vm_page_sleep_if_busy(m, TRUE, "pgrbwt")) {
 1810                         if ((allocflags & VM_ALLOC_RETRY) == 0)
 1811                                 return (NULL);
 1812                         goto retrylookup;
 1813                 } else {
 1814                         if ((allocflags & VM_ALLOC_WIRED) != 0) {
 1815                                 vm_page_lock_queues();
 1816                                 vm_page_wire(m);
 1817                                 vm_page_unlock_queues();
 1818                         }
 1819                         if ((allocflags & VM_ALLOC_NOBUSY) == 0)
 1820                                 vm_page_busy(m);
 1821                         return (m);
 1822                 }
 1823         }
 1824         m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
 1825         if (m == NULL) {
 1826                 VM_OBJECT_UNLOCK(object);
 1827                 VM_WAIT;
 1828                 VM_OBJECT_LOCK(object);
 1829                 if ((allocflags & VM_ALLOC_RETRY) == 0)
 1830                         return (NULL);
 1831                 goto retrylookup;
 1832         } else if (m->valid != 0)
 1833                 return (m);
 1834         if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
 1835                 pmap_zero_page(m);
 1836         return (m);
 1837 }
 1838 
 1839 /*
 1840  * Mapping function for valid bits or for dirty bits in
 1841  * a page.  May not block.
 1842  *
 1843  * Inputs are required to range within a page.
 1844  */
 1845 int
 1846 vm_page_bits(int base, int size)
 1847 {
 1848         int first_bit;
 1849         int last_bit;
 1850 
 1851         KASSERT(
 1852             base + size <= PAGE_SIZE,
 1853             ("vm_page_bits: illegal base/size %d/%d", base, size)
 1854         );
 1855 
 1856         if (size == 0)          /* handle degenerate case */
 1857                 return (0);
 1858 
 1859         first_bit = base >> DEV_BSHIFT;
 1860         last_bit = (base + size - 1) >> DEV_BSHIFT;
 1861 
 1862         return ((2 << last_bit) - (1 << first_bit));
 1863 }
 1864 
 1865 /*
 1866  *      vm_page_set_validclean:
 1867  *
 1868  *      Sets portions of a page valid and clean.  The arguments are expected
 1869  *      to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
 1870  *      of any partial chunks touched by the range.  The invalid portion of
 1871  *      such chunks will be zero'd.
 1872  *
 1873  *      This routine may not block.
 1874  *
 1875  *      (base + size) must be less then or equal to PAGE_SIZE.
 1876  */
 1877 void
 1878 vm_page_set_validclean(vm_page_t m, int base, int size)
 1879 {
 1880         int pagebits;
 1881         int frag;
 1882         int endoff;
 1883 
 1884         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 1885         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
 1886         if (size == 0)  /* handle degenerate case */
 1887                 return;
 1888 
 1889         /*
 1890          * If the base is not DEV_BSIZE aligned and the valid
 1891          * bit is clear, we have to zero out a portion of the
 1892          * first block.
 1893          */
 1894         if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
 1895             (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
 1896                 pmap_zero_page_area(m, frag, base - frag);
 1897 
 1898         /*
 1899          * If the ending offset is not DEV_BSIZE aligned and the 
 1900          * valid bit is clear, we have to zero out a portion of
 1901          * the last block.
 1902          */
 1903         endoff = base + size;
 1904         if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
 1905             (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
 1906                 pmap_zero_page_area(m, endoff,
 1907                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
 1908 
 1909         /*
 1910          * Set valid, clear dirty bits.  If validating the entire
 1911          * page we can safely clear the pmap modify bit.  We also
 1912          * use this opportunity to clear the VPO_NOSYNC flag.  If a process
 1913          * takes a write fault on a MAP_NOSYNC memory area the flag will
 1914          * be set again.
 1915          *
 1916          * We set valid bits inclusive of any overlap, but we can only
 1917          * clear dirty bits for DEV_BSIZE chunks that are fully within
 1918          * the range.
 1919          */
 1920         pagebits = vm_page_bits(base, size);
 1921         m->valid |= pagebits;
 1922 #if 0   /* NOT YET */
 1923         if ((frag = base & (DEV_BSIZE - 1)) != 0) {
 1924                 frag = DEV_BSIZE - frag;
 1925                 base += frag;
 1926                 size -= frag;
 1927                 if (size < 0)
 1928                         size = 0;
 1929         }
 1930         pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
 1931 #endif
 1932         m->dirty &= ~pagebits;
 1933         if (base == 0 && size == PAGE_SIZE) {
 1934                 pmap_clear_modify(m);
 1935                 m->oflags &= ~VPO_NOSYNC;
 1936         }
 1937 }
 1938 
 1939 void
 1940 vm_page_clear_dirty(vm_page_t m, int base, int size)
 1941 {
 1942 
 1943         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 1944         m->dirty &= ~vm_page_bits(base, size);
 1945 }
 1946 
 1947 /*
 1948  *      vm_page_set_invalid:
 1949  *
 1950  *      Invalidates DEV_BSIZE'd chunks within a page.  Both the
 1951  *      valid and dirty bits for the effected areas are cleared.
 1952  *
 1953  *      May not block.
 1954  */
 1955 void
 1956 vm_page_set_invalid(vm_page_t m, int base, int size)
 1957 {
 1958         int bits;
 1959 
 1960         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
 1961         bits = vm_page_bits(base, size);
 1962         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 1963         if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
 1964                 pmap_remove_all(m);
 1965         m->valid &= ~bits;
 1966         m->dirty &= ~bits;
 1967         m->object->generation++;
 1968 }
 1969 
 1970 /*
 1971  * vm_page_zero_invalid()
 1972  *
 1973  *      The kernel assumes that the invalid portions of a page contain 
 1974  *      garbage, but such pages can be mapped into memory by user code.
 1975  *      When this occurs, we must zero out the non-valid portions of the
 1976  *      page so user code sees what it expects.
 1977  *
 1978  *      Pages are most often semi-valid when the end of a file is mapped 
 1979  *      into memory and the file's size is not page aligned.
 1980  */
 1981 void
 1982 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
 1983 {
 1984         int b;
 1985         int i;
 1986 
 1987         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
 1988         /*
 1989          * Scan the valid bits looking for invalid sections that
 1990          * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
 1991          * valid bit may be set ) have already been zerod by
 1992          * vm_page_set_validclean().
 1993          */
 1994         for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
 1995                 if (i == (PAGE_SIZE / DEV_BSIZE) || 
 1996                     (m->valid & (1 << i))
 1997                 ) {
 1998                         if (i > b) {
 1999                                 pmap_zero_page_area(m, 
 2000                                     b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
 2001                         }
 2002                         b = i + 1;
 2003                 }
 2004         }
 2005 
 2006         /*
 2007          * setvalid is TRUE when we can safely set the zero'd areas
 2008          * as being valid.  We can do this if there are no cache consistancy
 2009          * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
 2010          */
 2011         if (setvalid)
 2012                 m->valid = VM_PAGE_BITS_ALL;
 2013 }
 2014 
 2015 /*
 2016  *      vm_page_is_valid:
 2017  *
 2018  *      Is (partial) page valid?  Note that the case where size == 0
 2019  *      will return FALSE in the degenerate case where the page is
 2020  *      entirely invalid, and TRUE otherwise.
 2021  *
 2022  *      May not block.
 2023  */
 2024 int
 2025 vm_page_is_valid(vm_page_t m, int base, int size)
 2026 {
 2027         int bits = vm_page_bits(base, size);
 2028 
 2029         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
 2030         if (m->valid && ((m->valid & bits) == bits))
 2031                 return 1;
 2032         else
 2033                 return 0;
 2034 }
 2035 
 2036 /*
 2037  * update dirty bits from pmap/mmu.  May not block.
 2038  */
 2039 void
 2040 vm_page_test_dirty(vm_page_t m)
 2041 {
 2042         if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
 2043                 vm_page_dirty(m);
 2044         }
 2045 }
 2046 
 2047 int so_zerocp_fullpage = 0;
 2048 
 2049 /*
 2050  *      Replace the given page with a copy.  The copied page assumes
 2051  *      the portion of the given page's "wire_count" that is not the
 2052  *      responsibility of this copy-on-write mechanism.
 2053  *
 2054  *      The object containing the given page must have a non-zero
 2055  *      paging-in-progress count and be locked.
 2056  */
 2057 void
 2058 vm_page_cowfault(vm_page_t m)
 2059 {
 2060         vm_page_t mnew;
 2061         vm_object_t object;
 2062         vm_pindex_t pindex;
 2063 
 2064         object = m->object;
 2065         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
 2066         KASSERT(object->paging_in_progress != 0,
 2067             ("vm_page_cowfault: object %p's paging-in-progress count is zero.",
 2068             object)); 
 2069         pindex = m->pindex;
 2070 
 2071  retry_alloc:
 2072         pmap_remove_all(m);
 2073         vm_page_remove(m);
 2074         mnew = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY);
 2075         if (mnew == NULL) {
 2076                 vm_page_insert(m, object, pindex);
 2077                 vm_page_unlock_queues();
 2078                 VM_OBJECT_UNLOCK(object);
 2079                 VM_WAIT;
 2080                 VM_OBJECT_LOCK(object);
 2081                 if (m == vm_page_lookup(object, pindex)) {
 2082                         vm_page_lock_queues();
 2083                         goto retry_alloc;
 2084                 } else {
 2085                         /*
 2086                          * Page disappeared during the wait.
 2087                          */
 2088                         vm_page_lock_queues();
 2089                         return;
 2090                 }
 2091         }
 2092 
 2093         if (m->cow == 0) {
 2094                 /* 
 2095                  * check to see if we raced with an xmit complete when 
 2096                  * waiting to allocate a page.  If so, put things back 
 2097                  * the way they were 
 2098                  */
 2099                 vm_page_free(mnew);
 2100                 vm_page_insert(m, object, pindex);
 2101         } else { /* clear COW & copy page */
 2102                 if (!so_zerocp_fullpage)
 2103                         pmap_copy_page(m, mnew);
 2104                 mnew->valid = VM_PAGE_BITS_ALL;
 2105                 vm_page_dirty(mnew);
 2106                 mnew->wire_count = m->wire_count - m->cow;
 2107                 m->wire_count = m->cow;
 2108         }
 2109 }
 2110 
 2111 void 
 2112 vm_page_cowclear(vm_page_t m)
 2113 {
 2114 
 2115         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2116         if (m->cow) {
 2117                 m->cow--;
 2118                 /* 
 2119                  * let vm_fault add back write permission  lazily
 2120                  */
 2121         } 
 2122         /*
 2123          *  sf_buf_free() will free the page, so we needn't do it here
 2124          */ 
 2125 }
 2126 
 2127 int
 2128 vm_page_cowsetup(vm_page_t m)
 2129 {
 2130 
 2131         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2132         if (m->cow == USHRT_MAX - 1)
 2133                 return (EBUSY);
 2134         m->cow++;
 2135         pmap_remove_write(m);
 2136         return (0);
 2137 }
 2138 
 2139 #include "opt_ddb.h"
 2140 #ifdef DDB
 2141 #include <sys/kernel.h>
 2142 
 2143 #include <ddb/ddb.h>
 2144 
 2145 DB_SHOW_COMMAND(page, vm_page_print_page_info)
 2146 {
 2147         db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
 2148         db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
 2149         db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
 2150         db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
 2151         db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
 2152         db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
 2153         db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
 2154         db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
 2155         db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
 2156         db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
 2157 }
 2158 
 2159 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
 2160 {
 2161                 
 2162         db_printf("PQ_FREE:");
 2163         db_printf(" %d", cnt.v_free_count);
 2164         db_printf("\n");
 2165                 
 2166         db_printf("PQ_CACHE:");
 2167         db_printf(" %d", cnt.v_cache_count);
 2168         db_printf("\n");
 2169 
 2170         db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
 2171                 *vm_page_queues[PQ_ACTIVE].cnt,
 2172                 *vm_page_queues[PQ_INACTIVE].cnt);
 2173 }
 2174 #endif /* DDB */

Cache object: 598b924f5223dfa10b150c7bd101bca2


[ 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.