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 page queue lock is required when adding or removing a page from a
   67  *        page queue regardless of other locks or the busy state of a page.
   68  *
   69  *              * In general, no thread besides the page daemon can acquire or
   70  *                hold more than one page queue lock at a time.
   71  *
   72  *              * The page daemon can acquire and hold any pair of page queue
   73  *                locks in any order.
   74  *
   75  *      - The object lock is required when inserting or removing
   76  *        pages from an object (vm_page_insert() or vm_page_remove()).
   77  *
   78  */
   79 
   80 /*
   81  *      Resident memory management module.
   82  */
   83 
   84 #include <sys/cdefs.h>
   85 __FBSDID("$FreeBSD$");
   86 
   87 #include "opt_vm.h"
   88 
   89 #include <sys/param.h>
   90 #include <sys/systm.h>
   91 #include <sys/lock.h>
   92 #include <sys/kernel.h>
   93 #include <sys/limits.h>
   94 #include <sys/linker.h>
   95 #include <sys/malloc.h>
   96 #include <sys/mman.h>
   97 #include <sys/msgbuf.h>
   98 #include <sys/mutex.h>
   99 #include <sys/proc.h>
  100 #include <sys/rwlock.h>
  101 #include <sys/sbuf.h>
  102 #include <sys/smp.h>
  103 #include <sys/sysctl.h>
  104 #include <sys/vmmeter.h>
  105 #include <sys/vnode.h>
  106 
  107 #include <vm/vm.h>
  108 #include <vm/pmap.h>
  109 #include <vm/vm_param.h>
  110 #include <vm/vm_kern.h>
  111 #include <vm/vm_object.h>
  112 #include <vm/vm_page.h>
  113 #include <vm/vm_pageout.h>
  114 #include <vm/vm_pager.h>
  115 #include <vm/vm_phys.h>
  116 #include <vm/vm_radix.h>
  117 #include <vm/vm_reserv.h>
  118 #include <vm/vm_extern.h>
  119 #include <vm/uma.h>
  120 #include <vm/uma_int.h>
  121 
  122 #include <machine/md_var.h>
  123 
  124 /*
  125  *      Associated with page of user-allocatable memory is a
  126  *      page structure.
  127  */
  128 
  129 struct vm_domain vm_dom[MAXMEMDOM];
  130 struct mtx_padalign __exclusive_cache_line vm_page_queue_free_mtx;
  131 
  132 struct mtx_padalign __exclusive_cache_line pa_lock[PA_LOCK_COUNT];
  133 
  134 vm_page_t vm_page_array;
  135 long vm_page_array_size;
  136 long first_page;
  137 int vm_page_zero_count;
  138 
  139 static int boot_pages = UMA_BOOT_PAGES;
  140 SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
  141     &boot_pages, 0,
  142     "number of pages allocated for bootstrapping the VM system");
  143 
  144 static int pa_tryrelock_restart;
  145 SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
  146     &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
  147 
  148 static TAILQ_HEAD(, vm_page) blacklist_head;
  149 static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
  150 SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
  151     CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
  152 
  153 /* Is the page daemon waiting for free pages? */
  154 static int vm_pageout_pages_needed;
  155 
  156 static uma_zone_t fakepg_zone;
  157 
  158 static void vm_page_alloc_check(vm_page_t m);
  159 static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
  160 static void vm_page_enqueue(uint8_t queue, vm_page_t m);
  161 static void vm_page_free_phys(vm_page_t m);
  162 static void vm_page_free_wakeup(void);
  163 static void vm_page_init_fakepg(void *dummy);
  164 static int vm_page_insert_after(vm_page_t m, vm_object_t object,
  165     vm_pindex_t pindex, vm_page_t mpred);
  166 static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
  167     vm_page_t mpred);
  168 static int vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
  169     vm_paddr_t high);
  170 static int vm_page_alloc_fail(vm_object_t object, int req);
  171 
  172 SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init_fakepg, NULL);
  173 
  174 static void
  175 vm_page_init_fakepg(void *dummy)
  176 {
  177 
  178         fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
  179             NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
  180 }
  181 
  182 /* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
  183 #if PAGE_SIZE == 32768
  184 #ifdef CTASSERT
  185 CTASSERT(sizeof(u_long) >= 8);
  186 #endif
  187 #endif
  188 
  189 /*
  190  * Try to acquire a physical address lock while a pmap is locked.  If we
  191  * fail to trylock we unlock and lock the pmap directly and cache the
  192  * locked pa in *locked.  The caller should then restart their loop in case
  193  * the virtual to physical mapping has changed.
  194  */
  195 int
  196 vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
  197 {
  198         vm_paddr_t lockpa;
  199 
  200         lockpa = *locked;
  201         *locked = pa;
  202         if (lockpa) {
  203                 PA_LOCK_ASSERT(lockpa, MA_OWNED);
  204                 if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
  205                         return (0);
  206                 PA_UNLOCK(lockpa);
  207         }
  208         if (PA_TRYLOCK(pa))
  209                 return (0);
  210         PMAP_UNLOCK(pmap);
  211         atomic_add_int(&pa_tryrelock_restart, 1);
  212         PA_LOCK(pa);
  213         PMAP_LOCK(pmap);
  214         return (EAGAIN);
  215 }
  216 
  217 /*
  218  *      vm_set_page_size:
  219  *
  220  *      Sets the page size, perhaps based upon the memory
  221  *      size.  Must be called before any use of page-size
  222  *      dependent functions.
  223  */
  224 void
  225 vm_set_page_size(void)
  226 {
  227         if (vm_cnt.v_page_size == 0)
  228                 vm_cnt.v_page_size = PAGE_SIZE;
  229         if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
  230                 panic("vm_set_page_size: page size not a power of two");
  231 }
  232 
  233 /*
  234  *      vm_page_blacklist_next:
  235  *
  236  *      Find the next entry in the provided string of blacklist
  237  *      addresses.  Entries are separated by space, comma, or newline.
  238  *      If an invalid integer is encountered then the rest of the
  239  *      string is skipped.  Updates the list pointer to the next
  240  *      character, or NULL if the string is exhausted or invalid.
  241  */
  242 static vm_paddr_t
  243 vm_page_blacklist_next(char **list, char *end)
  244 {
  245         vm_paddr_t bad;
  246         char *cp, *pos;
  247 
  248         if (list == NULL || *list == NULL)
  249                 return (0);
  250         if (**list =='\0') {
  251                 *list = NULL;
  252                 return (0);
  253         }
  254 
  255         /*
  256          * If there's no end pointer then the buffer is coming from
  257          * the kenv and we know it's null-terminated.
  258          */
  259         if (end == NULL)
  260                 end = *list + strlen(*list);
  261 
  262         /* Ensure that strtoq() won't walk off the end */
  263         if (*end != '\0') {
  264                 if (*end == '\n' || *end == ' ' || *end  == ',')
  265                         *end = '\0';
  266                 else {
  267                         printf("Blacklist not terminated, skipping\n");
  268                         *list = NULL;
  269                         return (0);
  270                 }
  271         }
  272 
  273         for (pos = *list; *pos != '\0'; pos = cp) {
  274                 bad = strtoq(pos, &cp, 0);
  275                 if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
  276                         if (bad == 0) {
  277                                 if (++cp < end)
  278                                         continue;
  279                                 else
  280                                         break;
  281                         }
  282                 } else
  283                         break;
  284                 if (*cp == '\0' || ++cp >= end)
  285                         *list = NULL;
  286                 else
  287                         *list = cp;
  288                 return (trunc_page(bad));
  289         }
  290         printf("Garbage in RAM blacklist, skipping\n");
  291         *list = NULL;
  292         return (0);
  293 }
  294 
  295 bool
  296 vm_page_blacklist_add(vm_paddr_t pa, bool verbose)
  297 {
  298         vm_page_t m;
  299         int ret;
  300 
  301         m = vm_phys_paddr_to_vm_page(pa);
  302         if (m == NULL)
  303                 return (true); /* page does not exist, no failure */
  304 
  305         mtx_lock(&vm_page_queue_free_mtx);
  306         ret = vm_phys_unfree_page(m);
  307         if (ret != 0)
  308                 vm_phys_freecnt_adj(m, -1);
  309         mtx_unlock(&vm_page_queue_free_mtx);
  310         if (ret != 0) {
  311                 TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
  312                 if (verbose)
  313                         printf("Skipping page with pa 0x%jx\n", (uintmax_t)pa);
  314         }
  315         return (ret);
  316 }
  317 
  318 /*
  319  *      vm_page_blacklist_check:
  320  *
  321  *      Iterate through the provided string of blacklist addresses, pulling
  322  *      each entry out of the physical allocator free list and putting it
  323  *      onto a list for reporting via the vm.page_blacklist sysctl.
  324  */
  325 static void
  326 vm_page_blacklist_check(char *list, char *end)
  327 {
  328         vm_paddr_t pa;
  329         char *next;
  330 
  331         next = list;
  332         while (next != NULL) {
  333                 if ((pa = vm_page_blacklist_next(&next, end)) == 0)
  334                         continue;
  335                 vm_page_blacklist_add(pa, bootverbose);
  336         }
  337 }
  338 
  339 /*
  340  *      vm_page_blacklist_load:
  341  *
  342  *      Search for a special module named "ram_blacklist".  It'll be a
  343  *      plain text file provided by the user via the loader directive
  344  *      of the same name.
  345  */
  346 static void
  347 vm_page_blacklist_load(char **list, char **end)
  348 {
  349         void *mod;
  350         u_char *ptr;
  351         u_int len;
  352 
  353         mod = NULL;
  354         ptr = NULL;
  355 
  356         mod = preload_search_by_type("ram_blacklist");
  357         if (mod != NULL) {
  358                 ptr = preload_fetch_addr(mod);
  359                 len = preload_fetch_size(mod);
  360         }
  361         *list = ptr;
  362         if (ptr != NULL)
  363                 *end = ptr + len;
  364         else
  365                 *end = NULL;
  366         return;
  367 }
  368 
  369 static int
  370 sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
  371 {
  372         vm_page_t m;
  373         struct sbuf sbuf;
  374         int error, first;
  375 
  376         first = 1;
  377         error = sysctl_wire_old_buffer(req, 0);
  378         if (error != 0)
  379                 return (error);
  380         sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
  381         TAILQ_FOREACH(m, &blacklist_head, listq) {
  382                 sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
  383                     (uintmax_t)m->phys_addr);
  384                 first = 0;
  385         }
  386         error = sbuf_finish(&sbuf);
  387         sbuf_delete(&sbuf);
  388         return (error);
  389 }
  390 
  391 static void
  392 vm_page_domain_init(struct vm_domain *vmd)
  393 {
  394         struct vm_pagequeue *pq;
  395         int i;
  396 
  397         *__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
  398             "vm inactive pagequeue";
  399         *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_vcnt) =
  400             &vm_cnt.v_inactive_count;
  401         *__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
  402             "vm active pagequeue";
  403         *__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_vcnt) =
  404             &vm_cnt.v_active_count;
  405         *__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
  406             "vm laundry pagequeue";
  407         *__DECONST(int **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_vcnt) =
  408             &vm_cnt.v_laundry_count;
  409         vmd->vmd_page_count = 0;
  410         vmd->vmd_free_count = 0;
  411         vmd->vmd_segs = 0;
  412         vmd->vmd_oom = FALSE;
  413         for (i = 0; i < PQ_COUNT; i++) {
  414                 pq = &vmd->vmd_pagequeues[i];
  415                 TAILQ_INIT(&pq->pq_pl);
  416                 mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
  417                     MTX_DEF | MTX_DUPOK);
  418         }
  419 }
  420 
  421 /*
  422  * Initialize a physical page in preparation for adding it to the free
  423  * lists.
  424  */
  425 static void
  426 vm_page_init_page(vm_page_t m, vm_paddr_t pa, int segind)
  427 {
  428 
  429         m->object = NULL;
  430         m->wire_count = 0;
  431         m->busy_lock = VPB_UNBUSIED;
  432         m->hold_count = 0;
  433         m->flags = 0;
  434         m->phys_addr = pa;
  435         m->queue = PQ_NONE;
  436         m->psind = 0;
  437         m->segind = segind;
  438         m->order = VM_NFREEORDER;
  439         m->pool = VM_FREEPOOL_DEFAULT;
  440         m->valid = m->dirty = 0;
  441         pmap_page_init(m);
  442 }
  443 
  444 /*
  445  *      vm_page_startup:
  446  *
  447  *      Initializes the resident memory module.  Allocates physical memory for
  448  *      bootstrapping UMA and some data structures that are used to manage
  449  *      physical pages.  Initializes these structures, and populates the free
  450  *      page queues.
  451  */
  452 vm_offset_t
  453 vm_page_startup(vm_offset_t vaddr)
  454 {
  455         struct vm_domain *vmd;
  456         struct vm_phys_seg *seg;
  457         vm_page_t m;
  458         char *list, *listend;
  459         vm_offset_t mapped;
  460         vm_paddr_t end, high_avail, low_avail, new_end, page_range, size;
  461         vm_paddr_t biggestsize, last_pa, pa;
  462         u_long pagecount;
  463         int biggestone, i, pages_per_zone, segind;
  464 
  465         biggestsize = 0;
  466         biggestone = 0;
  467         vaddr = round_page(vaddr);
  468 
  469         for (i = 0; phys_avail[i + 1]; i += 2) {
  470                 phys_avail[i] = round_page(phys_avail[i]);
  471                 phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
  472         }
  473         for (i = 0; phys_avail[i + 1]; i += 2) {
  474                 size = phys_avail[i + 1] - phys_avail[i];
  475                 if (size > biggestsize) {
  476                         biggestone = i;
  477                         biggestsize = size;
  478                 }
  479         }
  480 
  481         end = phys_avail[biggestone+1];
  482 
  483         /*
  484          * Initialize the page and queue locks.
  485          */
  486         mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
  487         for (i = 0; i < PA_LOCK_COUNT; i++)
  488                 mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
  489         for (i = 0; i < vm_ndomains; i++)
  490                 vm_page_domain_init(&vm_dom[i]);
  491 
  492         /*
  493          * Almost all of the pages needed for bootstrapping UMA are used
  494          * for zone structures, so if the number of CPUs results in those
  495          * structures taking more than one page each, we set aside more pages
  496          * in proportion to the zone structure size.
  497          */
  498         pages_per_zone = howmany(sizeof(struct uma_zone) +
  499             sizeof(struct uma_cache) * (mp_maxid + 1) +
  500             roundup2(sizeof(struct uma_slab), sizeof(void *)), UMA_SLAB_SIZE);
  501         if (pages_per_zone > 1) {
  502                 /* Reserve more pages so that we don't run out. */
  503                 boot_pages = UMA_BOOT_PAGES_ZONES * pages_per_zone;
  504         }
  505 
  506         /*
  507          * Allocate memory for use when boot strapping the kernel memory
  508          * allocator.
  509          *
  510          * CTFLAG_RDTUN doesn't work during the early boot process, so we must
  511          * manually fetch the value.
  512          */
  513         TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
  514         new_end = end - (boot_pages * UMA_SLAB_SIZE);
  515         new_end = trunc_page(new_end);
  516         mapped = pmap_map(&vaddr, new_end, end,
  517             VM_PROT_READ | VM_PROT_WRITE);
  518         bzero((void *)mapped, end - new_end);
  519         uma_startup((void *)mapped, boot_pages);
  520 
  521 #if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
  522     defined(__i386__) || defined(__mips__)
  523         /*
  524          * Allocate a bitmap to indicate that a random physical page
  525          * needs to be included in a minidump.
  526          *
  527          * The amd64 port needs this to indicate which direct map pages
  528          * need to be dumped, via calls to dump_add_page()/dump_drop_page().
  529          *
  530          * However, i386 still needs this workspace internally within the
  531          * minidump code.  In theory, they are not needed on i386, but are
  532          * included should the sf_buf code decide to use them.
  533          */
  534         last_pa = 0;
  535         for (i = 0; dump_avail[i + 1] != 0; i += 2)
  536                 if (dump_avail[i + 1] > last_pa)
  537                         last_pa = dump_avail[i + 1];
  538         page_range = last_pa / PAGE_SIZE;
  539         vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
  540         new_end -= vm_page_dump_size;
  541         vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
  542             new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
  543         bzero((void *)vm_page_dump, vm_page_dump_size);
  544 #else
  545         (void)last_pa;
  546 #endif
  547 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
  548         /*
  549          * Include the UMA bootstrap pages and vm_page_dump in a crash dump.
  550          * When pmap_map() uses the direct map, they are not automatically 
  551          * included.
  552          */
  553         for (pa = new_end; pa < end; pa += PAGE_SIZE)
  554                 dump_add_page(pa);
  555 #endif
  556         phys_avail[biggestone + 1] = new_end;
  557 #ifdef __amd64__
  558         /*
  559          * Request that the physical pages underlying the message buffer be
  560          * included in a crash dump.  Since the message buffer is accessed
  561          * through the direct map, they are not automatically included.
  562          */
  563         pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
  564         last_pa = pa + round_page(msgbufsize);
  565         while (pa < last_pa) {
  566                 dump_add_page(pa);
  567                 pa += PAGE_SIZE;
  568         }
  569 #endif
  570         /*
  571          * Compute the number of pages of memory that will be available for
  572          * use, taking into account the overhead of a page structure per page.
  573          * In other words, solve
  574          *      "available physical memory" - round_page(page_range *
  575          *          sizeof(struct vm_page)) = page_range * PAGE_SIZE 
  576          * for page_range.  
  577          */
  578         low_avail = phys_avail[0];
  579         high_avail = phys_avail[1];
  580         for (i = 0; i < vm_phys_nsegs; i++) {
  581                 if (vm_phys_segs[i].start < low_avail)
  582                         low_avail = vm_phys_segs[i].start;
  583                 if (vm_phys_segs[i].end > high_avail)
  584                         high_avail = vm_phys_segs[i].end;
  585         }
  586         /* Skip the first chunk.  It is already accounted for. */
  587         for (i = 2; phys_avail[i + 1] != 0; i += 2) {
  588                 if (phys_avail[i] < low_avail)
  589                         low_avail = phys_avail[i];
  590                 if (phys_avail[i + 1] > high_avail)
  591                         high_avail = phys_avail[i + 1];
  592         }
  593         first_page = low_avail / PAGE_SIZE;
  594 #ifdef VM_PHYSSEG_SPARSE
  595         size = 0;
  596         for (i = 0; i < vm_phys_nsegs; i++)
  597                 size += vm_phys_segs[i].end - vm_phys_segs[i].start;
  598         for (i = 0; phys_avail[i + 1] != 0; i += 2)
  599                 size += phys_avail[i + 1] - phys_avail[i];
  600 #elif defined(VM_PHYSSEG_DENSE)
  601         size = high_avail - low_avail;
  602 #else
  603 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
  604 #endif
  605 
  606 #ifdef VM_PHYSSEG_DENSE
  607         /*
  608          * In the VM_PHYSSEG_DENSE case, the number of pages can account for
  609          * the overhead of a page structure per page only if vm_page_array is
  610          * allocated from the last physical memory chunk.  Otherwise, we must
  611          * allocate page structures representing the physical memory
  612          * underlying vm_page_array, even though they will not be used.
  613          */
  614         if (new_end != high_avail)
  615                 page_range = size / PAGE_SIZE;
  616         else
  617 #endif
  618         {
  619                 page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
  620 
  621                 /*
  622                  * If the partial bytes remaining are large enough for
  623                  * a page (PAGE_SIZE) without a corresponding
  624                  * 'struct vm_page', then new_end will contain an
  625                  * extra page after subtracting the length of the VM
  626                  * page array.  Compensate by subtracting an extra
  627                  * page from new_end.
  628                  */
  629                 if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
  630                         if (new_end == high_avail)
  631                                 high_avail -= PAGE_SIZE;
  632                         new_end -= PAGE_SIZE;
  633                 }
  634         }
  635         end = new_end;
  636 
  637         /*
  638          * Reserve an unmapped guard page to trap access to vm_page_array[-1].
  639          * However, because this page is allocated from KVM, out-of-bounds
  640          * accesses using the direct map will not be trapped.
  641          */
  642         vaddr += PAGE_SIZE;
  643 
  644         /*
  645          * Allocate physical memory for the page structures, and map it.
  646          */
  647         new_end = trunc_page(end - page_range * sizeof(struct vm_page));
  648         mapped = pmap_map(&vaddr, new_end, end,
  649             VM_PROT_READ | VM_PROT_WRITE);
  650         vm_page_array = (vm_page_t)mapped;
  651         vm_page_array_size = page_range;
  652 
  653 #if VM_NRESERVLEVEL > 0
  654         /*
  655          * Allocate physical memory for the reservation management system's
  656          * data structures, and map it.
  657          */
  658         if (high_avail == end)
  659                 high_avail = new_end;
  660         new_end = vm_reserv_startup(&vaddr, new_end, high_avail);
  661 #endif
  662 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
  663         /*
  664          * Include vm_page_array and vm_reserv_array in a crash dump.
  665          */
  666         for (pa = new_end; pa < end; pa += PAGE_SIZE)
  667                 dump_add_page(pa);
  668 #endif
  669         phys_avail[biggestone + 1] = new_end;
  670 
  671         /*
  672          * Add physical memory segments corresponding to the available
  673          * physical pages.
  674          */
  675         for (i = 0; phys_avail[i + 1] != 0; i += 2)
  676                 vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
  677 
  678         /*
  679          * Initialize the physical memory allocator.
  680          */
  681         vm_phys_init();
  682 
  683         /*
  684          * Initialize the page structures and add every available page to the
  685          * physical memory allocator's free lists.
  686          */
  687         vm_cnt.v_page_count = 0;
  688         vm_cnt.v_free_count = 0;
  689         for (segind = 0; segind < vm_phys_nsegs; segind++) {
  690                 seg = &vm_phys_segs[segind];
  691                 for (m = seg->first_page, pa = seg->start; pa < seg->end;
  692                     m++, pa += PAGE_SIZE)
  693                         vm_page_init_page(m, pa, segind);
  694 
  695                 /*
  696                  * Add the segment to the free lists only if it is covered by
  697                  * one of the ranges in phys_avail.  Because we've added the
  698                  * ranges to the vm_phys_segs array, we can assume that each
  699                  * segment is either entirely contained in one of the ranges,
  700                  * or doesn't overlap any of them.
  701                  */
  702                 for (i = 0; phys_avail[i + 1] != 0; i += 2) {
  703                         if (seg->start < phys_avail[i] ||
  704                             seg->end > phys_avail[i + 1])
  705                                 continue;
  706 
  707                         m = seg->first_page;
  708                         pagecount = (u_long)atop(seg->end - seg->start);
  709 
  710                         mtx_lock(&vm_page_queue_free_mtx);
  711                         vm_phys_free_contig(m, pagecount);
  712                         vm_phys_freecnt_adj(m, (int)pagecount);
  713                         mtx_unlock(&vm_page_queue_free_mtx);
  714                         vm_cnt.v_page_count += (u_int)pagecount;
  715 
  716                         vmd = &vm_dom[seg->domain];
  717                         vmd->vmd_page_count += (u_int)pagecount;
  718                         vmd->vmd_segs |= 1UL << m->segind;
  719                         break;
  720                 }
  721         }
  722 
  723         /*
  724          * Remove blacklisted pages from the physical memory allocator.
  725          */
  726         TAILQ_INIT(&blacklist_head);
  727         vm_page_blacklist_load(&list, &listend);
  728         vm_page_blacklist_check(list, listend);
  729 
  730         list = kern_getenv("vm.blacklist");
  731         vm_page_blacklist_check(list, NULL);
  732 
  733         freeenv(list);
  734 #if VM_NRESERVLEVEL > 0
  735         /*
  736          * Initialize the reservation management system.
  737          */
  738         vm_reserv_init();
  739 #endif
  740         return (vaddr);
  741 }
  742 
  743 void
  744 vm_page_reference(vm_page_t m)
  745 {
  746 
  747         vm_page_aflag_set(m, PGA_REFERENCED);
  748 }
  749 
  750 /*
  751  *      vm_page_busy_downgrade:
  752  *
  753  *      Downgrade an exclusive busy page into a single shared busy page.
  754  */
  755 void
  756 vm_page_busy_downgrade(vm_page_t m)
  757 {
  758         u_int x;
  759         bool locked;
  760 
  761         vm_page_assert_xbusied(m);
  762         locked = mtx_owned(vm_page_lockptr(m));
  763 
  764         for (;;) {
  765                 x = m->busy_lock;
  766                 x &= VPB_BIT_WAITERS;
  767                 if (x != 0 && !locked)
  768                         vm_page_lock(m);
  769                 if (atomic_cmpset_rel_int(&m->busy_lock,
  770                     VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
  771                         break;
  772                 if (x != 0 && !locked)
  773                         vm_page_unlock(m);
  774         }
  775         if (x != 0) {
  776                 wakeup(m);
  777                 if (!locked)
  778                         vm_page_unlock(m);
  779         }
  780 }
  781 
  782 /*
  783  *      vm_page_sbusied:
  784  *
  785  *      Return a positive value if the page is shared busied, 0 otherwise.
  786  */
  787 int
  788 vm_page_sbusied(vm_page_t m)
  789 {
  790         u_int x;
  791 
  792         x = m->busy_lock;
  793         return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
  794 }
  795 
  796 /*
  797  *      vm_page_sunbusy:
  798  *
  799  *      Shared unbusy a page.
  800  */
  801 void
  802 vm_page_sunbusy(vm_page_t m)
  803 {
  804         u_int x;
  805 
  806         vm_page_lock_assert(m, MA_NOTOWNED);
  807         vm_page_assert_sbusied(m);
  808 
  809         for (;;) {
  810                 x = m->busy_lock;
  811                 if (VPB_SHARERS(x) > 1) {
  812                         if (atomic_cmpset_int(&m->busy_lock, x,
  813                             x - VPB_ONE_SHARER))
  814                                 break;
  815                         continue;
  816                 }
  817                 if ((x & VPB_BIT_WAITERS) == 0) {
  818                         KASSERT(x == VPB_SHARERS_WORD(1),
  819                             ("vm_page_sunbusy: invalid lock state"));
  820                         if (atomic_cmpset_int(&m->busy_lock,
  821                             VPB_SHARERS_WORD(1), VPB_UNBUSIED))
  822                                 break;
  823                         continue;
  824                 }
  825                 KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
  826                     ("vm_page_sunbusy: invalid lock state for waiters"));
  827 
  828                 vm_page_lock(m);
  829                 if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
  830                         vm_page_unlock(m);
  831                         continue;
  832                 }
  833                 wakeup(m);
  834                 vm_page_unlock(m);
  835                 break;
  836         }
  837 }
  838 
  839 /*
  840  *      vm_page_busy_sleep:
  841  *
  842  *      Sleep and release the page lock, using the page pointer as wchan.
  843  *      This is used to implement the hard-path of busying mechanism.
  844  *
  845  *      The given page must be locked.
  846  *
  847  *      If nonshared is true, sleep only if the page is xbusy.
  848  */
  849 void
  850 vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
  851 {
  852         u_int x;
  853 
  854         vm_page_assert_locked(m);
  855 
  856         x = m->busy_lock;
  857         if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
  858             ((x & VPB_BIT_WAITERS) == 0 &&
  859             !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
  860                 vm_page_unlock(m);
  861                 return;
  862         }
  863         msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
  864 }
  865 
  866 /*
  867  *      vm_page_trysbusy:
  868  *
  869  *      Try to shared busy a page.
  870  *      If the operation succeeds 1 is returned otherwise 0.
  871  *      The operation never sleeps.
  872  */
  873 int
  874 vm_page_trysbusy(vm_page_t m)
  875 {
  876         u_int x;
  877 
  878         for (;;) {
  879                 x = m->busy_lock;
  880                 if ((x & VPB_BIT_SHARED) == 0)
  881                         return (0);
  882                 if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
  883                         return (1);
  884         }
  885 }
  886 
  887 static void
  888 vm_page_xunbusy_locked(vm_page_t m)
  889 {
  890 
  891         vm_page_assert_xbusied(m);
  892         vm_page_assert_locked(m);
  893 
  894         atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
  895         /* There is a waiter, do wakeup() instead of vm_page_flash(). */
  896         wakeup(m);
  897 }
  898 
  899 void
  900 vm_page_xunbusy_maybelocked(vm_page_t m)
  901 {
  902         bool lockacq;
  903 
  904         vm_page_assert_xbusied(m);
  905 
  906         /*
  907          * Fast path for unbusy.  If it succeeds, we know that there
  908          * are no waiters, so we do not need a wakeup.
  909          */
  910         if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
  911             VPB_UNBUSIED))
  912                 return;
  913 
  914         lockacq = !mtx_owned(vm_page_lockptr(m));
  915         if (lockacq)
  916                 vm_page_lock(m);
  917         vm_page_xunbusy_locked(m);
  918         if (lockacq)
  919                 vm_page_unlock(m);
  920 }
  921 
  922 /*
  923  *      vm_page_xunbusy_hard:
  924  *
  925  *      Called after the first try the exclusive unbusy of a page failed.
  926  *      It is assumed that the waiters bit is on.
  927  */
  928 void
  929 vm_page_xunbusy_hard(vm_page_t m)
  930 {
  931 
  932         vm_page_assert_xbusied(m);
  933 
  934         vm_page_lock(m);
  935         vm_page_xunbusy_locked(m);
  936         vm_page_unlock(m);
  937 }
  938 
  939 /*
  940  *      vm_page_flash:
  941  *
  942  *      Wakeup anyone waiting for the page.
  943  *      The ownership bits do not change.
  944  *
  945  *      The given page must be locked.
  946  */
  947 void
  948 vm_page_flash(vm_page_t m)
  949 {
  950         u_int x;
  951 
  952         vm_page_lock_assert(m, MA_OWNED);
  953 
  954         for (;;) {
  955                 x = m->busy_lock;
  956                 if ((x & VPB_BIT_WAITERS) == 0)
  957                         return;
  958                 if (atomic_cmpset_int(&m->busy_lock, x,
  959                     x & (~VPB_BIT_WAITERS)))
  960                         break;
  961         }
  962         wakeup(m);
  963 }
  964 
  965 /*
  966  * Avoid releasing and reacquiring the same page lock.
  967  */
  968 void
  969 vm_page_change_lock(vm_page_t m, struct mtx **mtx)
  970 {
  971         struct mtx *mtx1;
  972 
  973         mtx1 = vm_page_lockptr(m);
  974         if (*mtx == mtx1)
  975                 return;
  976         if (*mtx != NULL)
  977                 mtx_unlock(*mtx);
  978         *mtx = mtx1;
  979         mtx_lock(mtx1);
  980 }
  981 
  982 /*
  983  * Keep page from being freed by the page daemon
  984  * much of the same effect as wiring, except much lower
  985  * overhead and should be used only for *very* temporary
  986  * holding ("wiring").
  987  */
  988 void
  989 vm_page_hold(vm_page_t mem)
  990 {
  991 
  992         vm_page_lock_assert(mem, MA_OWNED);
  993         mem->hold_count++;
  994 }
  995 
  996 void
  997 vm_page_unhold(vm_page_t mem)
  998 {
  999 
 1000         vm_page_lock_assert(mem, MA_OWNED);
 1001         KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
 1002         --mem->hold_count;
 1003         if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
 1004                 vm_page_free_toq(mem);
 1005 }
 1006 
 1007 /*
 1008  *      vm_page_unhold_pages:
 1009  *
 1010  *      Unhold each of the pages that is referenced by the given array.
 1011  */
 1012 void
 1013 vm_page_unhold_pages(vm_page_t *ma, int count)
 1014 {
 1015         struct mtx *mtx;
 1016 
 1017         mtx = NULL;
 1018         for (; count != 0; count--) {
 1019                 vm_page_change_lock(*ma, &mtx);
 1020                 vm_page_unhold(*ma);
 1021                 ma++;
 1022         }
 1023         if (mtx != NULL)
 1024                 mtx_unlock(mtx);
 1025 }
 1026 
 1027 vm_page_t
 1028 PHYS_TO_VM_PAGE(vm_paddr_t pa)
 1029 {
 1030         vm_page_t m;
 1031 
 1032 #ifdef VM_PHYSSEG_SPARSE
 1033         m = vm_phys_paddr_to_vm_page(pa);
 1034         if (m == NULL)
 1035                 m = vm_phys_fictitious_to_vm_page(pa);
 1036         return (m);
 1037 #elif defined(VM_PHYSSEG_DENSE)
 1038         long pi;
 1039 
 1040         pi = atop(pa);
 1041         if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
 1042                 m = &vm_page_array[pi - first_page];
 1043                 return (m);
 1044         }
 1045         return (vm_phys_fictitious_to_vm_page(pa));
 1046 #else
 1047 #error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
 1048 #endif
 1049 }
 1050 
 1051 /*
 1052  *      vm_page_getfake:
 1053  *
 1054  *      Create a fictitious page with the specified physical address and
 1055  *      memory attribute.  The memory attribute is the only the machine-
 1056  *      dependent aspect of a fictitious page that must be initialized.
 1057  */
 1058 vm_page_t
 1059 vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
 1060 {
 1061         vm_page_t m;
 1062 
 1063         m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
 1064         vm_page_initfake(m, paddr, memattr);
 1065         return (m);
 1066 }
 1067 
 1068 void
 1069 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
 1070 {
 1071 
 1072         if ((m->flags & PG_FICTITIOUS) != 0) {
 1073                 /*
 1074                  * The page's memattr might have changed since the
 1075                  * previous initialization.  Update the pmap to the
 1076                  * new memattr.
 1077                  */
 1078                 goto memattr;
 1079         }
 1080         m->phys_addr = paddr;
 1081         m->queue = PQ_NONE;
 1082         /* Fictitious pages don't use "segind". */
 1083         m->flags = PG_FICTITIOUS;
 1084         /* Fictitious pages don't use "order" or "pool". */
 1085         m->oflags = VPO_UNMANAGED;
 1086         m->busy_lock = VPB_SINGLE_EXCLUSIVER;
 1087         m->wire_count = 1;
 1088         pmap_page_init(m);
 1089 memattr:
 1090         pmap_page_set_memattr(m, memattr);
 1091 }
 1092 
 1093 /*
 1094  *      vm_page_putfake:
 1095  *
 1096  *      Release a fictitious page.
 1097  */
 1098 void
 1099 vm_page_putfake(vm_page_t m)
 1100 {
 1101 
 1102         KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
 1103         KASSERT((m->flags & PG_FICTITIOUS) != 0,
 1104             ("vm_page_putfake: bad page %p", m));
 1105         uma_zfree(fakepg_zone, m);
 1106 }
 1107 
 1108 /*
 1109  *      vm_page_updatefake:
 1110  *
 1111  *      Update the given fictitious page to the specified physical address and
 1112  *      memory attribute.
 1113  */
 1114 void
 1115 vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
 1116 {
 1117 
 1118         KASSERT((m->flags & PG_FICTITIOUS) != 0,
 1119             ("vm_page_updatefake: bad page %p", m));
 1120         m->phys_addr = paddr;
 1121         pmap_page_set_memattr(m, memattr);
 1122 }
 1123 
 1124 /*
 1125  *      vm_page_free:
 1126  *
 1127  *      Free a page.
 1128  */
 1129 void
 1130 vm_page_free(vm_page_t m)
 1131 {
 1132 
 1133         m->flags &= ~PG_ZERO;
 1134         vm_page_free_toq(m);
 1135 }
 1136 
 1137 /*
 1138  *      vm_page_free_zero:
 1139  *
 1140  *      Free a page to the zerod-pages queue
 1141  */
 1142 void
 1143 vm_page_free_zero(vm_page_t m)
 1144 {
 1145 
 1146         m->flags |= PG_ZERO;
 1147         vm_page_free_toq(m);
 1148 }
 1149 
 1150 /*
 1151  * Unbusy and handle the page queueing for a page from a getpages request that
 1152  * was optionally read ahead or behind.
 1153  */
 1154 void
 1155 vm_page_readahead_finish(vm_page_t m)
 1156 {
 1157 
 1158         /* We shouldn't put invalid pages on queues. */
 1159         KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
 1160 
 1161         /*
 1162          * Since the page is not the actually needed one, whether it should
 1163          * be activated or deactivated is not obvious.  Empirical results
 1164          * have shown that deactivating the page is usually the best choice,
 1165          * unless the page is wanted by another thread.
 1166          */
 1167         vm_page_lock(m);
 1168         if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
 1169                 vm_page_activate(m);
 1170         else
 1171                 vm_page_deactivate(m);
 1172         vm_page_unlock(m);
 1173         vm_page_xunbusy(m);
 1174 }
 1175 
 1176 /*
 1177  *      vm_page_sleep_if_busy:
 1178  *
 1179  *      Sleep and release the page queues lock if the page is busied.
 1180  *      Returns TRUE if the thread slept.
 1181  *
 1182  *      The given page must be unlocked and object containing it must
 1183  *      be locked.
 1184  */
 1185 int
 1186 vm_page_sleep_if_busy(vm_page_t m, const char *msg)
 1187 {
 1188         vm_object_t obj;
 1189 
 1190         vm_page_lock_assert(m, MA_NOTOWNED);
 1191         VM_OBJECT_ASSERT_WLOCKED(m->object);
 1192 
 1193         if (vm_page_busied(m)) {
 1194                 /*
 1195                  * The page-specific object must be cached because page
 1196                  * identity can change during the sleep, causing the
 1197                  * re-lock of a different object.
 1198                  * It is assumed that a reference to the object is already
 1199                  * held by the callers.
 1200                  */
 1201                 obj = m->object;
 1202                 vm_page_lock(m);
 1203                 VM_OBJECT_WUNLOCK(obj);
 1204                 vm_page_busy_sleep(m, msg, false);
 1205                 VM_OBJECT_WLOCK(obj);
 1206                 return (TRUE);
 1207         }
 1208         return (FALSE);
 1209 }
 1210 
 1211 /*
 1212  *      vm_page_dirty_KBI:              [ internal use only ]
 1213  *
 1214  *      Set all bits in the page's dirty field.
 1215  *
 1216  *      The object containing the specified page must be locked if the
 1217  *      call is made from the machine-independent layer.
 1218  *
 1219  *      See vm_page_clear_dirty_mask().
 1220  *
 1221  *      This function should only be called by vm_page_dirty().
 1222  */
 1223 void
 1224 vm_page_dirty_KBI(vm_page_t m)
 1225 {
 1226 
 1227         /* Refer to this operation by its public name. */
 1228         KASSERT(m->valid == VM_PAGE_BITS_ALL,
 1229             ("vm_page_dirty: page is invalid!"));
 1230         m->dirty = VM_PAGE_BITS_ALL;
 1231 }
 1232 
 1233 /*
 1234  *      vm_page_insert:         [ internal use only ]
 1235  *
 1236  *      Inserts the given mem entry into the object and object list.
 1237  *
 1238  *      The object must be locked.
 1239  */
 1240 int
 1241 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
 1242 {
 1243         vm_page_t mpred;
 1244 
 1245         VM_OBJECT_ASSERT_WLOCKED(object);
 1246         mpred = vm_radix_lookup_le(&object->rtree, pindex);
 1247         return (vm_page_insert_after(m, object, pindex, mpred));
 1248 }
 1249 
 1250 /*
 1251  *      vm_page_insert_after:
 1252  *
 1253  *      Inserts the page "m" into the specified object at offset "pindex".
 1254  *
 1255  *      The page "mpred" must immediately precede the offset "pindex" within
 1256  *      the specified object.
 1257  *
 1258  *      The object must be locked.
 1259  */
 1260 static int
 1261 vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
 1262     vm_page_t mpred)
 1263 {
 1264         vm_page_t msucc;
 1265 
 1266         VM_OBJECT_ASSERT_WLOCKED(object);
 1267         KASSERT(m->object == NULL,
 1268             ("vm_page_insert_after: page already inserted"));
 1269         if (mpred != NULL) {
 1270                 KASSERT(mpred->object == object,
 1271                     ("vm_page_insert_after: object doesn't contain mpred"));
 1272                 KASSERT(mpred->pindex < pindex,
 1273                     ("vm_page_insert_after: mpred doesn't precede pindex"));
 1274                 msucc = TAILQ_NEXT(mpred, listq);
 1275         } else
 1276                 msucc = TAILQ_FIRST(&object->memq);
 1277         if (msucc != NULL)
 1278                 KASSERT(msucc->pindex > pindex,
 1279                     ("vm_page_insert_after: msucc doesn't succeed pindex"));
 1280 
 1281         /*
 1282          * Record the object/offset pair in this page
 1283          */
 1284         m->object = object;
 1285         m->pindex = pindex;
 1286 
 1287         /*
 1288          * Now link into the object's ordered list of backed pages.
 1289          */
 1290         if (vm_radix_insert(&object->rtree, m)) {
 1291                 m->object = NULL;
 1292                 m->pindex = 0;
 1293                 return (1);
 1294         }
 1295         vm_page_insert_radixdone(m, object, mpred);
 1296         return (0);
 1297 }
 1298 
 1299 /*
 1300  *      vm_page_insert_radixdone:
 1301  *
 1302  *      Complete page "m" insertion into the specified object after the
 1303  *      radix trie hooking.
 1304  *
 1305  *      The page "mpred" must precede the offset "m->pindex" within the
 1306  *      specified object.
 1307  *
 1308  *      The object must be locked.
 1309  */
 1310 static void
 1311 vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
 1312 {
 1313 
 1314         VM_OBJECT_ASSERT_WLOCKED(object);
 1315         KASSERT(object != NULL && m->object == object,
 1316             ("vm_page_insert_radixdone: page %p has inconsistent object", m));
 1317         if (mpred != NULL) {
 1318                 KASSERT(mpred->object == object,
 1319                     ("vm_page_insert_after: object doesn't contain mpred"));
 1320                 KASSERT(mpred->pindex < m->pindex,
 1321                     ("vm_page_insert_after: mpred doesn't precede pindex"));
 1322         }
 1323 
 1324         if (mpred != NULL)
 1325                 TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
 1326         else
 1327                 TAILQ_INSERT_HEAD(&object->memq, m, listq);
 1328 
 1329         /*
 1330          * Show that the object has one more resident page.
 1331          */
 1332         object->resident_page_count++;
 1333 
 1334         /*
 1335          * Hold the vnode until the last page is released.
 1336          */
 1337         if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
 1338                 vhold(object->handle);
 1339 
 1340         /*
 1341          * Since we are inserting a new and possibly dirty page,
 1342          * update the object's OBJ_MIGHTBEDIRTY flag.
 1343          */
 1344         if (pmap_page_is_write_mapped(m))
 1345                 vm_object_set_writeable_dirty(object);
 1346 }
 1347 
 1348 /*
 1349  *      vm_page_remove:
 1350  *
 1351  *      Removes the specified page from its containing object, but does not
 1352  *      invalidate any backing storage.
 1353  *
 1354  *      The object must be locked.  The page must be locked if it is managed.
 1355  */
 1356 void
 1357 vm_page_remove(vm_page_t m)
 1358 {
 1359         vm_object_t object;
 1360         vm_page_t mrem;
 1361 
 1362         if ((m->oflags & VPO_UNMANAGED) == 0)
 1363                 vm_page_assert_locked(m);
 1364         if ((object = m->object) == NULL)
 1365                 return;
 1366         VM_OBJECT_ASSERT_WLOCKED(object);
 1367         if (vm_page_xbusied(m))
 1368                 vm_page_xunbusy_maybelocked(m);
 1369         mrem = vm_radix_remove(&object->rtree, m->pindex);
 1370         KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
 1371 
 1372         /*
 1373          * Now remove from the object's list of backed pages.
 1374          */
 1375         TAILQ_REMOVE(&object->memq, m, listq);
 1376 
 1377         /*
 1378          * And show that the object has one fewer resident page.
 1379          */
 1380         object->resident_page_count--;
 1381 
 1382         /*
 1383          * The vnode may now be recycled.
 1384          */
 1385         if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
 1386                 vdrop(object->handle);
 1387 
 1388         m->object = NULL;
 1389 }
 1390 
 1391 /*
 1392  *      vm_page_lookup:
 1393  *
 1394  *      Returns the page associated with the object/offset
 1395  *      pair specified; if none is found, NULL is returned.
 1396  *
 1397  *      The object must be locked.
 1398  */
 1399 vm_page_t
 1400 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
 1401 {
 1402 
 1403         VM_OBJECT_ASSERT_LOCKED(object);
 1404         return (vm_radix_lookup(&object->rtree, pindex));
 1405 }
 1406 
 1407 /*
 1408  *      vm_page_find_least:
 1409  *
 1410  *      Returns the page associated with the object with least pindex
 1411  *      greater than or equal to the parameter pindex, or NULL.
 1412  *
 1413  *      The object must be locked.
 1414  */
 1415 vm_page_t
 1416 vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
 1417 {
 1418         vm_page_t m;
 1419 
 1420         VM_OBJECT_ASSERT_LOCKED(object);
 1421         if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
 1422                 m = vm_radix_lookup_ge(&object->rtree, pindex);
 1423         return (m);
 1424 }
 1425 
 1426 /*
 1427  * Returns the given page's successor (by pindex) within the object if it is
 1428  * resident; if none is found, NULL is returned.
 1429  *
 1430  * The object must be locked.
 1431  */
 1432 vm_page_t
 1433 vm_page_next(vm_page_t m)
 1434 {
 1435         vm_page_t next;
 1436 
 1437         VM_OBJECT_ASSERT_LOCKED(m->object);
 1438         if ((next = TAILQ_NEXT(m, listq)) != NULL) {
 1439                 MPASS(next->object == m->object);
 1440                 if (next->pindex != m->pindex + 1)
 1441                         next = NULL;
 1442         }
 1443         return (next);
 1444 }
 1445 
 1446 /*
 1447  * Returns the given page's predecessor (by pindex) within the object if it is
 1448  * resident; if none is found, NULL is returned.
 1449  *
 1450  * The object must be locked.
 1451  */
 1452 vm_page_t
 1453 vm_page_prev(vm_page_t m)
 1454 {
 1455         vm_page_t prev;
 1456 
 1457         VM_OBJECT_ASSERT_LOCKED(m->object);
 1458         if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
 1459                 MPASS(prev->object == m->object);
 1460                 if (prev->pindex != m->pindex - 1)
 1461                         prev = NULL;
 1462         }
 1463         return (prev);
 1464 }
 1465 
 1466 /*
 1467  * Uses the page mnew as a replacement for an existing page at index
 1468  * pindex which must be already present in the object.
 1469  *
 1470  * The existing page must not be on a paging queue.
 1471  */
 1472 vm_page_t
 1473 vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
 1474 {
 1475         vm_page_t mold;
 1476 
 1477         VM_OBJECT_ASSERT_WLOCKED(object);
 1478         KASSERT(mnew->object == NULL,
 1479             ("vm_page_replace: page %p already in object", mnew));
 1480         KASSERT(mnew->queue == PQ_NONE,
 1481             ("vm_page_replace: new page %p is on a paging queue", mnew));
 1482 
 1483         /*
 1484          * This function mostly follows vm_page_insert() and
 1485          * vm_page_remove() without the radix, object count and vnode
 1486          * dance.  Double check such functions for more comments.
 1487          */
 1488 
 1489         mnew->object = object;
 1490         mnew->pindex = pindex;
 1491         mold = vm_radix_replace(&object->rtree, mnew);
 1492         KASSERT(mold->queue == PQ_NONE,
 1493             ("vm_page_replace: old page %p is on a paging queue", mold));
 1494 
 1495         /* Keep the resident page list in sorted order. */
 1496         TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
 1497         TAILQ_REMOVE(&object->memq, mold, listq);
 1498 
 1499         mold->object = NULL;
 1500         vm_page_xunbusy_maybelocked(mold);
 1501 
 1502         /*
 1503          * The object's resident_page_count does not change because we have
 1504          * swapped one page for another, but OBJ_MIGHTBEDIRTY.
 1505          */
 1506         if (pmap_page_is_write_mapped(mnew))
 1507                 vm_object_set_writeable_dirty(object);
 1508         return (mold);
 1509 }
 1510 
 1511 /*
 1512  *      vm_page_rename:
 1513  *
 1514  *      Move the given memory entry from its
 1515  *      current object to the specified target object/offset.
 1516  *
 1517  *      Note: swap associated with the page must be invalidated by the move.  We
 1518  *            have to do this for several reasons:  (1) we aren't freeing the
 1519  *            page, (2) we are dirtying the page, (3) the VM system is probably
 1520  *            moving the page from object A to B, and will then later move
 1521  *            the backing store from A to B and we can't have a conflict.
 1522  *
 1523  *      Note: we *always* dirty the page.  It is necessary both for the
 1524  *            fact that we moved it, and because we may be invalidating
 1525  *            swap.
 1526  *
 1527  *      The objects must be locked.
 1528  */
 1529 int
 1530 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
 1531 {
 1532         vm_page_t mpred;
 1533         vm_pindex_t opidx;
 1534 
 1535         VM_OBJECT_ASSERT_WLOCKED(new_object);
 1536 
 1537         mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
 1538         KASSERT(mpred == NULL || mpred->pindex != new_pindex,
 1539             ("vm_page_rename: pindex already renamed"));
 1540 
 1541         /*
 1542          * Create a custom version of vm_page_insert() which does not depend
 1543          * by m_prev and can cheat on the implementation aspects of the
 1544          * function.
 1545          */
 1546         opidx = m->pindex;
 1547         m->pindex = new_pindex;
 1548         if (vm_radix_insert(&new_object->rtree, m)) {
 1549                 m->pindex = opidx;
 1550                 return (1);
 1551         }
 1552 
 1553         /*
 1554          * The operation cannot fail anymore.  The removal must happen before
 1555          * the listq iterator is tainted.
 1556          */
 1557         m->pindex = opidx;
 1558         vm_page_lock(m);
 1559         vm_page_remove(m);
 1560 
 1561         /* Return back to the new pindex to complete vm_page_insert(). */
 1562         m->pindex = new_pindex;
 1563         m->object = new_object;
 1564         vm_page_unlock(m);
 1565         vm_page_insert_radixdone(m, new_object, mpred);
 1566         vm_page_dirty(m);
 1567         return (0);
 1568 }
 1569 
 1570 /*
 1571  *      vm_page_alloc:
 1572  *
 1573  *      Allocate and return a page that is associated with the specified
 1574  *      object and offset pair.  By default, this page is exclusive busied.
 1575  *
 1576  *      The caller must always specify an allocation class.
 1577  *
 1578  *      allocation classes:
 1579  *      VM_ALLOC_NORMAL         normal process request
 1580  *      VM_ALLOC_SYSTEM         system *really* needs a page
 1581  *      VM_ALLOC_INTERRUPT      interrupt time request
 1582  *
 1583  *      optional allocation flags:
 1584  *      VM_ALLOC_COUNT(number)  the number of additional pages that the caller
 1585  *                              intends to allocate
 1586  *      VM_ALLOC_NOBUSY         do not exclusive busy the page
 1587  *      VM_ALLOC_NODUMP         do not include the page in a kernel core dump
 1588  *      VM_ALLOC_NOOBJ          page is not associated with an object and
 1589  *                              should not be exclusive busy
 1590  *      VM_ALLOC_SBUSY          shared busy the allocated page
 1591  *      VM_ALLOC_WIRED          wire the allocated page
 1592  *      VM_ALLOC_ZERO           prefer a zeroed page
 1593  *
 1594  *      This routine may not sleep.
 1595  */
 1596 vm_page_t
 1597 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
 1598 {
 1599 
 1600         return (vm_page_alloc_after(object, pindex, req, object != NULL ?
 1601             vm_radix_lookup_le(&object->rtree, pindex) : NULL));
 1602 }
 1603 
 1604 /*
 1605  * Allocate a page in the specified object with the given page index.  To
 1606  * optimize insertion of the page into the object, the caller must also specifiy
 1607  * the resident page in the object with largest index smaller than the given
 1608  * page index, or NULL if no such page exists.
 1609  */
 1610 vm_page_t
 1611 vm_page_alloc_after(vm_object_t object, vm_pindex_t pindex, int req,
 1612     vm_page_t mpred)
 1613 {
 1614         vm_page_t m;
 1615         int flags, req_class;
 1616         u_int free_count;
 1617 
 1618         KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
 1619             (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
 1620             ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
 1621             (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
 1622             ("inconsistent object(%p)/req(%x)", object, req));
 1623         KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
 1624             ("Can't sleep and retry object insertion."));
 1625         KASSERT(mpred == NULL || mpred->pindex < pindex,
 1626             ("mpred %p doesn't precede pindex 0x%jx", mpred,
 1627             (uintmax_t)pindex));
 1628         if (object != NULL)
 1629                 VM_OBJECT_ASSERT_WLOCKED(object);
 1630 
 1631         if (__predict_false((req & VM_ALLOC_IFCACHED) != 0))
 1632                 return (NULL);
 1633 
 1634         req_class = req & VM_ALLOC_CLASS_MASK;
 1635 
 1636         /*
 1637          * The page daemon is allowed to dig deeper into the free page list.
 1638          */
 1639         if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
 1640                 req_class = VM_ALLOC_SYSTEM;
 1641 
 1642         /*
 1643          * Allocate a page if the number of free pages exceeds the minimum
 1644          * for the request class.
 1645          */
 1646 again:
 1647         mtx_lock(&vm_page_queue_free_mtx);
 1648         if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
 1649             (req_class == VM_ALLOC_SYSTEM &&
 1650             vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
 1651             (req_class == VM_ALLOC_INTERRUPT &&
 1652             vm_cnt.v_free_count > 0)) {
 1653                 /*
 1654                  * Can we allocate the page from a reservation?
 1655                  */
 1656 #if VM_NRESERVLEVEL > 0
 1657                 if (object == NULL || (object->flags & (OBJ_COLORED |
 1658                     OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
 1659                     vm_reserv_alloc_page(object, pindex, mpred)) == NULL)
 1660 #endif
 1661                 {
 1662                         /*
 1663                          * If not, allocate it from the free page queues.
 1664                          */
 1665                         m = vm_phys_alloc_pages(object != NULL ?
 1666                             VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
 1667 #if VM_NRESERVLEVEL > 0
 1668                         if (m == NULL && vm_reserv_reclaim_inactive()) {
 1669                                 m = vm_phys_alloc_pages(object != NULL ?
 1670                                     VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
 1671                                     0);
 1672                         }
 1673 #endif
 1674                 }
 1675         } else {
 1676                 /*
 1677                  * Not allocatable, give up.
 1678                  */
 1679                 if (vm_page_alloc_fail(object, req))
 1680                         goto again;
 1681                 return (NULL);
 1682         }
 1683 
 1684         /*
 1685          *  At this point we had better have found a good page.
 1686          */
 1687         KASSERT(m != NULL, ("missing page"));
 1688         free_count = vm_phys_freecnt_adj(m, -1);
 1689         if ((m->flags & PG_ZERO) != 0)
 1690                 vm_page_zero_count--;
 1691         mtx_unlock(&vm_page_queue_free_mtx);
 1692         vm_page_alloc_check(m);
 1693 
 1694         /*
 1695          * Initialize the page.  Only the PG_ZERO flag is inherited.
 1696          */
 1697         flags = 0;
 1698         if ((req & VM_ALLOC_ZERO) != 0)
 1699                 flags = PG_ZERO;
 1700         flags &= m->flags;
 1701         if ((req & VM_ALLOC_NODUMP) != 0)
 1702                 flags |= PG_NODUMP;
 1703         m->flags = flags;
 1704         m->aflags = 0;
 1705         m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
 1706             VPO_UNMANAGED : 0;
 1707         m->busy_lock = VPB_UNBUSIED;
 1708         if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
 1709                 m->busy_lock = VPB_SINGLE_EXCLUSIVER;
 1710         if ((req & VM_ALLOC_SBUSY) != 0)
 1711                 m->busy_lock = VPB_SHARERS_WORD(1);
 1712         if (req & VM_ALLOC_WIRED) {
 1713                 /*
 1714                  * The page lock is not required for wiring a page until that
 1715                  * page is inserted into the object.
 1716                  */
 1717                 atomic_add_int(&vm_cnt.v_wire_count, 1);
 1718                 m->wire_count = 1;
 1719         }
 1720         m->act_count = 0;
 1721 
 1722         if (object != NULL) {
 1723                 if (vm_page_insert_after(m, object, pindex, mpred)) {
 1724                         pagedaemon_wakeup();
 1725                         if (req & VM_ALLOC_WIRED) {
 1726                                 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
 1727                                 m->wire_count = 0;
 1728                         }
 1729                         KASSERT(m->object == NULL, ("page %p has object", m));
 1730                         m->oflags = VPO_UNMANAGED;
 1731                         m->busy_lock = VPB_UNBUSIED;
 1732                         /* Don't change PG_ZERO. */
 1733                         vm_page_free_toq(m);
 1734                         if (req & VM_ALLOC_WAITFAIL) {
 1735                                 VM_OBJECT_WUNLOCK(object);
 1736                                 vm_radix_wait();
 1737                                 VM_OBJECT_WLOCK(object);
 1738                         }
 1739                         return (NULL);
 1740                 }
 1741 
 1742                 /* Ignore device objects; the pager sets "memattr" for them. */
 1743                 if (object->memattr != VM_MEMATTR_DEFAULT &&
 1744                     (object->flags & OBJ_FICTITIOUS) == 0)
 1745                         pmap_page_set_memattr(m, object->memattr);
 1746         } else
 1747                 m->pindex = pindex;
 1748 
 1749         /*
 1750          * Don't wakeup too often - wakeup the pageout daemon when
 1751          * we would be nearly out of memory.
 1752          */
 1753         if (vm_paging_needed(free_count))
 1754                 pagedaemon_wakeup();
 1755 
 1756         return (m);
 1757 }
 1758 
 1759 /*
 1760  *      vm_page_alloc_contig:
 1761  *
 1762  *      Allocate a contiguous set of physical pages of the given size "npages"
 1763  *      from the free lists.  All of the physical pages must be at or above
 1764  *      the given physical address "low" and below the given physical address
 1765  *      "high".  The given value "alignment" determines the alignment of the
 1766  *      first physical page in the set.  If the given value "boundary" is
 1767  *      non-zero, then the set of physical pages cannot cross any physical
 1768  *      address boundary that is a multiple of that value.  Both "alignment"
 1769  *      and "boundary" must be a power of two.
 1770  *
 1771  *      If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
 1772  *      then the memory attribute setting for the physical pages is configured
 1773  *      to the object's memory attribute setting.  Otherwise, the memory
 1774  *      attribute setting for the physical pages is configured to "memattr",
 1775  *      overriding the object's memory attribute setting.  However, if the
 1776  *      object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
 1777  *      memory attribute setting for the physical pages cannot be configured
 1778  *      to VM_MEMATTR_DEFAULT.
 1779  *
 1780  *      The specified object may not contain fictitious pages.
 1781  *
 1782  *      The caller must always specify an allocation class.
 1783  *
 1784  *      allocation classes:
 1785  *      VM_ALLOC_NORMAL         normal process request
 1786  *      VM_ALLOC_SYSTEM         system *really* needs a page
 1787  *      VM_ALLOC_INTERRUPT      interrupt time request
 1788  *
 1789  *      optional allocation flags:
 1790  *      VM_ALLOC_NOBUSY         do not exclusive busy the page
 1791  *      VM_ALLOC_NODUMP         do not include the page in a kernel core dump
 1792  *      VM_ALLOC_NOOBJ          page is not associated with an object and
 1793  *                              should not be exclusive busy
 1794  *      VM_ALLOC_SBUSY          shared busy the allocated page
 1795  *      VM_ALLOC_WIRED          wire the allocated page
 1796  *      VM_ALLOC_ZERO           prefer a zeroed page
 1797  *
 1798  *      This routine may not sleep.
 1799  */
 1800 vm_page_t
 1801 vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
 1802     u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
 1803     vm_paddr_t boundary, vm_memattr_t memattr)
 1804 {
 1805         vm_page_t m, m_ret, mpred;
 1806         u_int busy_lock, flags, oflags;
 1807         int req_class;
 1808 
 1809         mpred = NULL;   /* XXX: pacify gcc */
 1810         KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
 1811             (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
 1812             ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
 1813             (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
 1814             ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
 1815             req));
 1816         KASSERT(object == NULL || (req & VM_ALLOC_WAITOK) == 0,
 1817             ("Can't sleep and retry object insertion."));
 1818         if (object != NULL) {
 1819                 VM_OBJECT_ASSERT_WLOCKED(object);
 1820                 KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
 1821                     ("vm_page_alloc_contig: object %p has fictitious pages",
 1822                     object));
 1823         }
 1824         KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
 1825         req_class = req & VM_ALLOC_CLASS_MASK;
 1826 
 1827         /*
 1828          * The page daemon is allowed to dig deeper into the free page list.
 1829          */
 1830         if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
 1831                 req_class = VM_ALLOC_SYSTEM;
 1832 
 1833         if (object != NULL) {
 1834                 mpred = vm_radix_lookup_le(&object->rtree, pindex);
 1835                 KASSERT(mpred == NULL || mpred->pindex != pindex,
 1836                     ("vm_page_alloc_contig: pindex already allocated"));
 1837         }
 1838 
 1839         /*
 1840          * Can we allocate the pages without the number of free pages falling
 1841          * below the lower bound for the allocation class?
 1842          */
 1843 again:
 1844         mtx_lock(&vm_page_queue_free_mtx);
 1845         if (vm_cnt.v_free_count >= npages + vm_cnt.v_free_reserved ||
 1846             (req_class == VM_ALLOC_SYSTEM &&
 1847             vm_cnt.v_free_count >= npages + vm_cnt.v_interrupt_free_min) ||
 1848             (req_class == VM_ALLOC_INTERRUPT &&
 1849             vm_cnt.v_free_count >= npages)) {
 1850                 /*
 1851                  * Can we allocate the pages from a reservation?
 1852                  */
 1853 #if VM_NRESERVLEVEL > 0
 1854 retry:
 1855                 if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
 1856                     (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
 1857                     low, high, alignment, boundary, mpred)) == NULL)
 1858 #endif
 1859                         /*
 1860                          * If not, allocate them from the free page queues.
 1861                          */
 1862                         m_ret = vm_phys_alloc_contig(npages, low, high,
 1863                             alignment, boundary);
 1864         } else {
 1865                 if (vm_page_alloc_fail(object, req))
 1866                         goto again;
 1867                 return (NULL);
 1868         }
 1869         if (m_ret != NULL) {
 1870                 vm_phys_freecnt_adj(m_ret, -npages);
 1871                 for (m = m_ret; m < &m_ret[npages]; m++)
 1872                         if ((m->flags & PG_ZERO) != 0)
 1873                                 vm_page_zero_count--;
 1874         } else {
 1875 #if VM_NRESERVLEVEL > 0
 1876                 if (vm_reserv_reclaim_contig(npages, low, high, alignment,
 1877                     boundary))
 1878                         goto retry;
 1879 #endif
 1880         }
 1881         mtx_unlock(&vm_page_queue_free_mtx);
 1882         if (m_ret == NULL)
 1883                 return (NULL);
 1884         for (m = m_ret; m < &m_ret[npages]; m++)
 1885                 vm_page_alloc_check(m);
 1886 
 1887         /*
 1888          * Initialize the pages.  Only the PG_ZERO flag is inherited.
 1889          */
 1890         flags = 0;
 1891         if ((req & VM_ALLOC_ZERO) != 0)
 1892                 flags = PG_ZERO;
 1893         if ((req & VM_ALLOC_NODUMP) != 0)
 1894                 flags |= PG_NODUMP;
 1895         oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
 1896             VPO_UNMANAGED : 0;
 1897         busy_lock = VPB_UNBUSIED;
 1898         if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
 1899                 busy_lock = VPB_SINGLE_EXCLUSIVER;
 1900         if ((req & VM_ALLOC_SBUSY) != 0)
 1901                 busy_lock = VPB_SHARERS_WORD(1);
 1902         if ((req & VM_ALLOC_WIRED) != 0)
 1903                 atomic_add_int(&vm_cnt.v_wire_count, npages);
 1904         if (object != NULL) {
 1905                 if (object->memattr != VM_MEMATTR_DEFAULT &&
 1906                     memattr == VM_MEMATTR_DEFAULT)
 1907                         memattr = object->memattr;
 1908         }
 1909         for (m = m_ret; m < &m_ret[npages]; m++) {
 1910                 m->aflags = 0;
 1911                 m->flags = (m->flags | PG_NODUMP) & flags;
 1912                 m->busy_lock = busy_lock;
 1913                 if ((req & VM_ALLOC_WIRED) != 0)
 1914                         m->wire_count = 1;
 1915                 m->act_count = 0;
 1916                 m->oflags = oflags;
 1917                 if (object != NULL) {
 1918                         if (vm_page_insert_after(m, object, pindex, mpred)) {
 1919                                 pagedaemon_wakeup();
 1920                                 if ((req & VM_ALLOC_WIRED) != 0)
 1921                                         atomic_subtract_int(
 1922                                             &vm_cnt.v_wire_count, npages);
 1923                                 KASSERT(m->object == NULL,
 1924                                     ("page %p has object", m));
 1925                                 mpred = m;
 1926                                 for (m = m_ret; m < &m_ret[npages]; m++) {
 1927                                         if (m <= mpred &&
 1928                                             (req & VM_ALLOC_WIRED) != 0)
 1929                                                 m->wire_count = 0;
 1930                                         m->oflags = VPO_UNMANAGED;
 1931                                         m->busy_lock = VPB_UNBUSIED;
 1932                                         /* Don't change PG_ZERO. */
 1933                                         vm_page_free_toq(m);
 1934                                 }
 1935                                 if (req & VM_ALLOC_WAITFAIL) {
 1936                                         VM_OBJECT_WUNLOCK(object);
 1937                                         vm_radix_wait();
 1938                                         VM_OBJECT_WLOCK(object);
 1939                                 }
 1940                                 return (NULL);
 1941                         }
 1942                         mpred = m;
 1943                 } else
 1944                         m->pindex = pindex;
 1945                 if (memattr != VM_MEMATTR_DEFAULT)
 1946                         pmap_page_set_memattr(m, memattr);
 1947                 pindex++;
 1948         }
 1949         if (vm_paging_needed(vm_cnt.v_free_count))
 1950                 pagedaemon_wakeup();
 1951         return (m_ret);
 1952 }
 1953 
 1954 /*
 1955  * Check a page that has been freshly dequeued from a freelist.
 1956  */
 1957 static void
 1958 vm_page_alloc_check(vm_page_t m)
 1959 {
 1960 
 1961         KASSERT(m->object == NULL, ("page %p has object", m));
 1962         KASSERT(m->queue == PQ_NONE,
 1963             ("page %p has unexpected queue %d", m, m->queue));
 1964         KASSERT(m->wire_count == 0, ("page %p is wired", m));
 1965         KASSERT(m->hold_count == 0, ("page %p is held", m));
 1966         KASSERT(!vm_page_busied(m), ("page %p is busy", m));
 1967         KASSERT(m->dirty == 0, ("page %p is dirty", m));
 1968         KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
 1969             ("page %p has unexpected memattr %d",
 1970             m, pmap_page_get_memattr(m)));
 1971         KASSERT(m->valid == 0, ("free page %p is valid", m));
 1972 }
 1973 
 1974 /*
 1975  *      vm_page_alloc_freelist:
 1976  *
 1977  *      Allocate a physical page from the specified free page list.
 1978  *
 1979  *      The caller must always specify an allocation class.
 1980  *
 1981  *      allocation classes:
 1982  *      VM_ALLOC_NORMAL         normal process request
 1983  *      VM_ALLOC_SYSTEM         system *really* needs a page
 1984  *      VM_ALLOC_INTERRUPT      interrupt time request
 1985  *
 1986  *      optional allocation flags:
 1987  *      VM_ALLOC_COUNT(number)  the number of additional pages that the caller
 1988  *                              intends to allocate
 1989  *      VM_ALLOC_WIRED          wire the allocated page
 1990  *      VM_ALLOC_ZERO           prefer a zeroed page
 1991  *
 1992  *      This routine may not sleep.
 1993  */
 1994 vm_page_t
 1995 vm_page_alloc_freelist(int flind, int req)
 1996 {
 1997         vm_page_t m;
 1998         u_int flags, free_count;
 1999         int req_class;
 2000 
 2001         req_class = req & VM_ALLOC_CLASS_MASK;
 2002 
 2003         /*
 2004          * The page daemon is allowed to dig deeper into the free page list.
 2005          */
 2006         if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
 2007                 req_class = VM_ALLOC_SYSTEM;
 2008 
 2009         /*
 2010          * Do not allocate reserved pages unless the req has asked for it.
 2011          */
 2012 again:
 2013         mtx_lock(&vm_page_queue_free_mtx);
 2014         if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
 2015             (req_class == VM_ALLOC_SYSTEM &&
 2016             vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
 2017             (req_class == VM_ALLOC_INTERRUPT &&
 2018             vm_cnt.v_free_count > 0)) {
 2019                 m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
 2020         } else {
 2021                 if (vm_page_alloc_fail(NULL, req))
 2022                         goto again;
 2023                 return (NULL);
 2024         }
 2025         if (m == NULL) {
 2026                 mtx_unlock(&vm_page_queue_free_mtx);
 2027                 return (NULL);
 2028         }
 2029         free_count = vm_phys_freecnt_adj(m, -1);
 2030         if ((m->flags & PG_ZERO) != 0)
 2031                 vm_page_zero_count--;
 2032         mtx_unlock(&vm_page_queue_free_mtx);
 2033         vm_page_alloc_check(m);
 2034 
 2035         /*
 2036          * Initialize the page.  Only the PG_ZERO flag is inherited.
 2037          */
 2038         m->aflags = 0;
 2039         flags = 0;
 2040         if ((req & VM_ALLOC_ZERO) != 0)
 2041                 flags = PG_ZERO;
 2042         m->flags &= flags;
 2043         if ((req & VM_ALLOC_WIRED) != 0) {
 2044                 /*
 2045                  * The page lock is not required for wiring a page that does
 2046                  * not belong to an object.
 2047                  */
 2048                 atomic_add_int(&vm_cnt.v_wire_count, 1);
 2049                 m->wire_count = 1;
 2050         }
 2051         /* Unmanaged pages don't use "act_count". */
 2052         m->oflags = VPO_UNMANAGED;
 2053         if (vm_paging_needed(free_count))
 2054                 pagedaemon_wakeup();
 2055         return (m);
 2056 }
 2057 
 2058 #define VPSC_ANY        0       /* No restrictions. */
 2059 #define VPSC_NORESERV   1       /* Skip reservations; implies VPSC_NOSUPER. */
 2060 #define VPSC_NOSUPER    2       /* Skip superpages. */
 2061 
 2062 /*
 2063  *      vm_page_scan_contig:
 2064  *
 2065  *      Scan vm_page_array[] between the specified entries "m_start" and
 2066  *      "m_end" for a run of contiguous physical pages that satisfy the
 2067  *      specified conditions, and return the lowest page in the run.  The
 2068  *      specified "alignment" determines the alignment of the lowest physical
 2069  *      page in the run.  If the specified "boundary" is non-zero, then the
 2070  *      run of physical pages cannot span a physical address that is a
 2071  *      multiple of "boundary".
 2072  *
 2073  *      "m_end" is never dereferenced, so it need not point to a vm_page
 2074  *      structure within vm_page_array[].
 2075  *
 2076  *      "npages" must be greater than zero.  "m_start" and "m_end" must not
 2077  *      span a hole (or discontiguity) in the physical address space.  Both
 2078  *      "alignment" and "boundary" must be a power of two.
 2079  */
 2080 vm_page_t
 2081 vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
 2082     u_long alignment, vm_paddr_t boundary, int options)
 2083 {
 2084         struct mtx *m_mtx;
 2085         vm_object_t object;
 2086         vm_paddr_t pa;
 2087         vm_page_t m, m_run;
 2088 #if VM_NRESERVLEVEL > 0
 2089         int level;
 2090 #endif
 2091         int m_inc, order, run_ext, run_len;
 2092 
 2093         KASSERT(npages > 0, ("npages is 0"));
 2094         KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
 2095         KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
 2096         m_run = NULL;
 2097         run_len = 0;
 2098         m_mtx = NULL;
 2099         for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
 2100                 KASSERT((m->flags & PG_MARKER) == 0,
 2101                     ("page %p is PG_MARKER", m));
 2102                 KASSERT((m->flags & PG_FICTITIOUS) == 0 || m->wire_count == 1,
 2103                     ("fictitious page %p has invalid wire count", m));
 2104 
 2105                 /*
 2106                  * If the current page would be the start of a run, check its
 2107                  * physical address against the end, alignment, and boundary
 2108                  * conditions.  If it doesn't satisfy these conditions, either
 2109                  * terminate the scan or advance to the next page that
 2110                  * satisfies the failed condition.
 2111                  */
 2112                 if (run_len == 0) {
 2113                         KASSERT(m_run == NULL, ("m_run != NULL"));
 2114                         if (m + npages > m_end)
 2115                                 break;
 2116                         pa = VM_PAGE_TO_PHYS(m);
 2117                         if ((pa & (alignment - 1)) != 0) {
 2118                                 m_inc = atop(roundup2(pa, alignment) - pa);
 2119                                 continue;
 2120                         }
 2121                         if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
 2122                             boundary) != 0) {
 2123                                 m_inc = atop(roundup2(pa, boundary) - pa);
 2124                                 continue;
 2125                         }
 2126                 } else
 2127                         KASSERT(m_run != NULL, ("m_run == NULL"));
 2128 
 2129                 vm_page_change_lock(m, &m_mtx);
 2130                 m_inc = 1;
 2131 retry:
 2132                 if (m->wire_count != 0 || m->hold_count != 0)
 2133                         run_ext = 0;
 2134 #if VM_NRESERVLEVEL > 0
 2135                 else if ((level = vm_reserv_level(m)) >= 0 &&
 2136                     (options & VPSC_NORESERV) != 0) {
 2137                         run_ext = 0;
 2138                         /* Advance to the end of the reservation. */
 2139                         pa = VM_PAGE_TO_PHYS(m);
 2140                         m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
 2141                             pa);
 2142                 }
 2143 #endif
 2144                 else if ((object = m->object) != NULL) {
 2145                         /*
 2146                          * The page is considered eligible for relocation if
 2147                          * and only if it could be laundered or reclaimed by
 2148                          * the page daemon.
 2149                          */
 2150                         if (!VM_OBJECT_TRYRLOCK(object)) {
 2151                                 mtx_unlock(m_mtx);
 2152                                 VM_OBJECT_RLOCK(object);
 2153                                 mtx_lock(m_mtx);
 2154                                 if (m->object != object) {
 2155                                         /*
 2156                                          * The page may have been freed.
 2157                                          */
 2158                                         VM_OBJECT_RUNLOCK(object);
 2159                                         goto retry;
 2160                                 } else if (m->wire_count != 0 ||
 2161                                     m->hold_count != 0) {
 2162                                         run_ext = 0;
 2163                                         goto unlock;
 2164                                 }
 2165                         }
 2166                         KASSERT((m->flags & PG_UNHOLDFREE) == 0,
 2167                             ("page %p is PG_UNHOLDFREE", m));
 2168                         /* Don't care: PG_NODUMP, PG_ZERO. */
 2169                         if (object->type != OBJT_DEFAULT &&
 2170                             object->type != OBJT_SWAP &&
 2171                             object->type != OBJT_VNODE) {
 2172                                 run_ext = 0;
 2173 #if VM_NRESERVLEVEL > 0
 2174                         } else if ((options & VPSC_NOSUPER) != 0 &&
 2175                             (level = vm_reserv_level_iffullpop(m)) >= 0) {
 2176                                 run_ext = 0;
 2177                                 /* Advance to the end of the superpage. */
 2178                                 pa = VM_PAGE_TO_PHYS(m);
 2179                                 m_inc = atop(roundup2(pa + 1,
 2180                                     vm_reserv_size(level)) - pa);
 2181 #endif
 2182                         } else if (object->memattr == VM_MEMATTR_DEFAULT &&
 2183                             m->queue != PQ_NONE && !vm_page_busied(m)) {
 2184                                 /*
 2185                                  * The page is allocated but eligible for
 2186                                  * relocation.  Extend the current run by one
 2187                                  * page.
 2188                                  */
 2189                                 KASSERT(pmap_page_get_memattr(m) ==
 2190                                     VM_MEMATTR_DEFAULT,
 2191                                     ("page %p has an unexpected memattr", m));
 2192                                 KASSERT((m->oflags & (VPO_SWAPINPROG |
 2193                                     VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
 2194                                     ("page %p has unexpected oflags", m));
 2195                                 /* Don't care: VPO_NOSYNC. */
 2196                                 run_ext = 1;
 2197                         } else
 2198                                 run_ext = 0;
 2199 unlock:
 2200                         VM_OBJECT_RUNLOCK(object);
 2201 #if VM_NRESERVLEVEL > 0
 2202                 } else if (level >= 0) {
 2203                         /*
 2204                          * The page is reserved but not yet allocated.  In
 2205                          * other words, it is still free.  Extend the current
 2206                          * run by one page.
 2207                          */
 2208                         run_ext = 1;
 2209 #endif
 2210                 } else if ((order = m->order) < VM_NFREEORDER) {
 2211                         /*
 2212                          * The page is enqueued in the physical memory
 2213                          * allocator's free page queues.  Moreover, it is the
 2214                          * first page in a power-of-two-sized run of
 2215                          * contiguous free pages.  Add these pages to the end
 2216                          * of the current run, and jump ahead.
 2217                          */
 2218                         run_ext = 1 << order;
 2219                         m_inc = 1 << order;
 2220                 } else {
 2221                         /*
 2222                          * Skip the page for one of the following reasons: (1)
 2223                          * It is enqueued in the physical memory allocator's
 2224                          * free page queues.  However, it is not the first
 2225                          * page in a run of contiguous free pages.  (This case
 2226                          * rarely occurs because the scan is performed in
 2227                          * ascending order.) (2) It is not reserved, and it is
 2228                          * transitioning from free to allocated.  (Conversely,
 2229                          * the transition from allocated to free for managed
 2230                          * pages is blocked by the page lock.) (3) It is
 2231                          * allocated but not contained by an object and not
 2232                          * wired, e.g., allocated by Xen's balloon driver.
 2233                          */
 2234                         run_ext = 0;
 2235                 }
 2236 
 2237                 /*
 2238                  * Extend or reset the current run of pages.
 2239                  */
 2240                 if (run_ext > 0) {
 2241                         if (run_len == 0)
 2242                                 m_run = m;
 2243                         run_len += run_ext;
 2244                 } else {
 2245                         if (run_len > 0) {
 2246                                 m_run = NULL;
 2247                                 run_len = 0;
 2248                         }
 2249                 }
 2250         }
 2251         if (m_mtx != NULL)
 2252                 mtx_unlock(m_mtx);
 2253         if (run_len >= npages)
 2254                 return (m_run);
 2255         return (NULL);
 2256 }
 2257 
 2258 /*
 2259  *      vm_page_reclaim_run:
 2260  *
 2261  *      Try to relocate each of the allocated virtual pages within the
 2262  *      specified run of physical pages to a new physical address.  Free the
 2263  *      physical pages underlying the relocated virtual pages.  A virtual page
 2264  *      is relocatable if and only if it could be laundered or reclaimed by
 2265  *      the page daemon.  Whenever possible, a virtual page is relocated to a
 2266  *      physical address above "high".
 2267  *
 2268  *      Returns 0 if every physical page within the run was already free or
 2269  *      just freed by a successful relocation.  Otherwise, returns a non-zero
 2270  *      value indicating why the last attempt to relocate a virtual page was
 2271  *      unsuccessful.
 2272  *
 2273  *      "req_class" must be an allocation class.
 2274  */
 2275 static int
 2276 vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
 2277     vm_paddr_t high)
 2278 {
 2279         struct mtx *m_mtx;
 2280         struct spglist free;
 2281         vm_object_t object;
 2282         vm_paddr_t pa;
 2283         vm_page_t m, m_end, m_new;
 2284         int error, order, req;
 2285 
 2286         KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
 2287             ("req_class is not an allocation class"));
 2288         SLIST_INIT(&free);
 2289         error = 0;
 2290         m = m_run;
 2291         m_end = m_run + npages;
 2292         m_mtx = NULL;
 2293         for (; error == 0 && m < m_end; m++) {
 2294                 KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
 2295                     ("page %p is PG_FICTITIOUS or PG_MARKER", m));
 2296 
 2297                 /*
 2298                  * Avoid releasing and reacquiring the same page lock.
 2299                  */
 2300                 vm_page_change_lock(m, &m_mtx);
 2301 retry:
 2302                 if (m->wire_count != 0 || m->hold_count != 0)
 2303                         error = EBUSY;
 2304                 else if ((object = m->object) != NULL) {
 2305                         /*
 2306                          * The page is relocated if and only if it could be
 2307                          * laundered or reclaimed by the page daemon.
 2308                          */
 2309                         if (!VM_OBJECT_TRYWLOCK(object)) {
 2310                                 mtx_unlock(m_mtx);
 2311                                 VM_OBJECT_WLOCK(object);
 2312                                 mtx_lock(m_mtx);
 2313                                 if (m->object != object) {
 2314                                         /*
 2315                                          * The page may have been freed.
 2316                                          */
 2317                                         VM_OBJECT_WUNLOCK(object);
 2318                                         goto retry;
 2319                                 } else if (m->wire_count != 0 ||
 2320                                     m->hold_count != 0) {
 2321                                         error = EBUSY;
 2322                                         goto unlock;
 2323                                 }
 2324                         }
 2325                         KASSERT((m->flags & PG_UNHOLDFREE) == 0,
 2326                             ("page %p is PG_UNHOLDFREE", m));
 2327                         /* Don't care: PG_NODUMP, PG_ZERO. */
 2328                         if (object->type != OBJT_DEFAULT &&
 2329                             object->type != OBJT_SWAP &&
 2330                             object->type != OBJT_VNODE)
 2331                                 error = EINVAL;
 2332                         else if (object->memattr != VM_MEMATTR_DEFAULT)
 2333                                 error = EINVAL;
 2334                         else if (m->queue != PQ_NONE && !vm_page_busied(m)) {
 2335                                 KASSERT(pmap_page_get_memattr(m) ==
 2336                                     VM_MEMATTR_DEFAULT,
 2337                                     ("page %p has an unexpected memattr", m));
 2338                                 KASSERT((m->oflags & (VPO_SWAPINPROG |
 2339                                     VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
 2340                                     ("page %p has unexpected oflags", m));
 2341                                 /* Don't care: VPO_NOSYNC. */
 2342                                 if (m->valid != 0) {
 2343                                         /*
 2344                                          * First, try to allocate a new page
 2345                                          * that is above "high".  Failing
 2346                                          * that, try to allocate a new page
 2347                                          * that is below "m_run".  Allocate
 2348                                          * the new page between the end of
 2349                                          * "m_run" and "high" only as a last
 2350                                          * resort.
 2351                                          */
 2352                                         req = req_class | VM_ALLOC_NOOBJ;
 2353                                         if ((m->flags & PG_NODUMP) != 0)
 2354                                                 req |= VM_ALLOC_NODUMP;
 2355                                         if (trunc_page(high) !=
 2356                                             ~(vm_paddr_t)PAGE_MASK) {
 2357                                                 m_new = vm_page_alloc_contig(
 2358                                                     NULL, 0, req, 1,
 2359                                                     round_page(high),
 2360                                                     ~(vm_paddr_t)0,
 2361                                                     PAGE_SIZE, 0,
 2362                                                     VM_MEMATTR_DEFAULT);
 2363                                         } else
 2364                                                 m_new = NULL;
 2365                                         if (m_new == NULL) {
 2366                                                 pa = VM_PAGE_TO_PHYS(m_run);
 2367                                                 m_new = vm_page_alloc_contig(
 2368                                                     NULL, 0, req, 1,
 2369                                                     0, pa - 1, PAGE_SIZE, 0,
 2370                                                     VM_MEMATTR_DEFAULT);
 2371                                         }
 2372                                         if (m_new == NULL) {
 2373                                                 pa += ptoa(npages);
 2374                                                 m_new = vm_page_alloc_contig(
 2375                                                     NULL, 0, req, 1,
 2376                                                     pa, high, PAGE_SIZE, 0,
 2377                                                     VM_MEMATTR_DEFAULT);
 2378                                         }
 2379                                         if (m_new == NULL) {
 2380                                                 error = ENOMEM;
 2381                                                 goto unlock;
 2382                                         }
 2383                                         KASSERT(m_new->wire_count == 0,
 2384                                             ("page %p is wired", m_new));
 2385 
 2386                                         /*
 2387                                          * Replace "m" with the new page.  For
 2388                                          * vm_page_replace(), "m" must be busy
 2389                                          * and dequeued.  Finally, change "m"
 2390                                          * as if vm_page_free() was called.
 2391                                          */
 2392                                         if (object->ref_count != 0)
 2393                                                 pmap_remove_all(m);
 2394                                         m_new->aflags = m->aflags;
 2395                                         KASSERT(m_new->oflags == VPO_UNMANAGED,
 2396                                             ("page %p is managed", m_new));
 2397                                         m_new->oflags = m->oflags & VPO_NOSYNC;
 2398                                         pmap_copy_page(m, m_new);
 2399                                         m_new->valid = m->valid;
 2400                                         m_new->dirty = m->dirty;
 2401                                         m->flags &= ~PG_ZERO;
 2402                                         vm_page_xbusy(m);
 2403                                         vm_page_remque(m);
 2404                                         vm_page_replace_checked(m_new, object,
 2405                                             m->pindex, m);
 2406                                         m->valid = 0;
 2407                                         vm_page_undirty(m);
 2408 
 2409                                         /*
 2410                                          * The new page must be deactivated
 2411                                          * before the object is unlocked.
 2412                                          */
 2413                                         vm_page_change_lock(m_new, &m_mtx);
 2414                                         vm_page_deactivate(m_new);
 2415                                 } else {
 2416                                         m->flags &= ~PG_ZERO;
 2417                                         vm_page_remque(m);
 2418                                         vm_page_remove(m);
 2419                                         KASSERT(m->dirty == 0,
 2420                                             ("page %p is dirty", m));
 2421                                 }
 2422                                 SLIST_INSERT_HEAD(&free, m, plinks.s.ss);
 2423                         } else
 2424                                 error = EBUSY;
 2425 unlock:
 2426                         VM_OBJECT_WUNLOCK(object);
 2427                 } else {
 2428                         mtx_lock(&vm_page_queue_free_mtx);
 2429                         order = m->order;
 2430                         if (order < VM_NFREEORDER) {
 2431                                 /*
 2432                                  * The page is enqueued in the physical memory
 2433                                  * allocator's free page queues.  Moreover, it
 2434                                  * is the first page in a power-of-two-sized
 2435                                  * run of contiguous free pages.  Jump ahead
 2436                                  * to the last page within that run, and
 2437                                  * continue from there.
 2438                                  */
 2439                                 m += (1 << order) - 1;
 2440                         }
 2441 #if VM_NRESERVLEVEL > 0
 2442                         else if (vm_reserv_is_page_free(m))
 2443                                 order = 0;
 2444 #endif
 2445                         mtx_unlock(&vm_page_queue_free_mtx);
 2446                         if (order == VM_NFREEORDER)
 2447                                 error = EINVAL;
 2448                 }
 2449         }
 2450         if (m_mtx != NULL)
 2451                 mtx_unlock(m_mtx);
 2452         if ((m = SLIST_FIRST(&free)) != NULL) {
 2453                 mtx_lock(&vm_page_queue_free_mtx);
 2454                 do {
 2455                         SLIST_REMOVE_HEAD(&free, plinks.s.ss);
 2456                         vm_page_free_phys(m);
 2457                 } while ((m = SLIST_FIRST(&free)) != NULL);
 2458                 vm_page_zero_idle_wakeup();
 2459                 vm_page_free_wakeup();
 2460                 mtx_unlock(&vm_page_queue_free_mtx);
 2461         }
 2462         return (error);
 2463 }
 2464 
 2465 #define NRUNS   16
 2466 
 2467 CTASSERT(powerof2(NRUNS));
 2468 
 2469 #define RUN_INDEX(count)        ((count) & (NRUNS - 1))
 2470 
 2471 #define MIN_RECLAIM     8
 2472 
 2473 /*
 2474  *      vm_page_reclaim_contig:
 2475  *
 2476  *      Reclaim allocated, contiguous physical memory satisfying the specified
 2477  *      conditions by relocating the virtual pages using that physical memory.
 2478  *      Returns true if reclamation is successful and false otherwise.  Since
 2479  *      relocation requires the allocation of physical pages, reclamation may
 2480  *      fail due to a shortage of free pages.  When reclamation fails, callers
 2481  *      are expected to perform VM_WAIT before retrying a failed allocation
 2482  *      operation, e.g., vm_page_alloc_contig().
 2483  *
 2484  *      The caller must always specify an allocation class through "req".
 2485  *
 2486  *      allocation classes:
 2487  *      VM_ALLOC_NORMAL         normal process request
 2488  *      VM_ALLOC_SYSTEM         system *really* needs a page
 2489  *      VM_ALLOC_INTERRUPT      interrupt time request
 2490  *
 2491  *      The optional allocation flags are ignored.
 2492  *
 2493  *      "npages" must be greater than zero.  Both "alignment" and "boundary"
 2494  *      must be a power of two.
 2495  */
 2496 bool
 2497 vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
 2498     u_long alignment, vm_paddr_t boundary)
 2499 {
 2500         vm_paddr_t curr_low;
 2501         vm_page_t m_run, m_runs[NRUNS];
 2502         u_long count, reclaimed;
 2503         int error, i, options, req_class;
 2504 
 2505         KASSERT(npages > 0, ("npages is 0"));
 2506         KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
 2507         KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
 2508         req_class = req & VM_ALLOC_CLASS_MASK;
 2509 
 2510         /*
 2511          * The page daemon is allowed to dig deeper into the free page list.
 2512          */
 2513         if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
 2514                 req_class = VM_ALLOC_SYSTEM;
 2515 
 2516         /*
 2517          * Return if the number of free pages cannot satisfy the requested
 2518          * allocation.
 2519          */
 2520         count = vm_cnt.v_free_count;
 2521         if (count < npages + vm_cnt.v_free_reserved || (count < npages +
 2522             vm_cnt.v_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
 2523             (count < npages && req_class == VM_ALLOC_INTERRUPT))
 2524                 return (false);
 2525 
 2526         /*
 2527          * Scan up to three times, relaxing the restrictions ("options") on
 2528          * the reclamation of reservations and superpages each time.
 2529          */
 2530         for (options = VPSC_NORESERV;;) {
 2531                 /*
 2532                  * Find the highest runs that satisfy the given constraints
 2533                  * and restrictions, and record them in "m_runs".
 2534                  */
 2535                 curr_low = low;
 2536                 count = 0;
 2537                 for (;;) {
 2538                         m_run = vm_phys_scan_contig(npages, curr_low, high,
 2539                             alignment, boundary, options);
 2540                         if (m_run == NULL)
 2541                                 break;
 2542                         curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
 2543                         m_runs[RUN_INDEX(count)] = m_run;
 2544                         count++;
 2545                 }
 2546 
 2547                 /*
 2548                  * Reclaim the highest runs in LIFO (descending) order until
 2549                  * the number of reclaimed pages, "reclaimed", is at least
 2550                  * MIN_RECLAIM.  Reset "reclaimed" each time because each
 2551                  * reclamation is idempotent, and runs will (likely) recur
 2552                  * from one scan to the next as restrictions are relaxed.
 2553                  */
 2554                 reclaimed = 0;
 2555                 for (i = 0; count > 0 && i < NRUNS; i++) {
 2556                         count--;
 2557                         m_run = m_runs[RUN_INDEX(count)];
 2558                         error = vm_page_reclaim_run(req_class, npages, m_run,
 2559                             high);
 2560                         if (error == 0) {
 2561                                 reclaimed += npages;
 2562                                 if (reclaimed >= MIN_RECLAIM)
 2563                                         return (true);
 2564                         }
 2565                 }
 2566 
 2567                 /*
 2568                  * Either relax the restrictions on the next scan or return if
 2569                  * the last scan had no restrictions.
 2570                  */
 2571                 if (options == VPSC_NORESERV)
 2572                         options = VPSC_NOSUPER;
 2573                 else if (options == VPSC_NOSUPER)
 2574                         options = VPSC_ANY;
 2575                 else if (options == VPSC_ANY)
 2576                         return (reclaimed != 0);
 2577         }
 2578 }
 2579 
 2580 /*
 2581  *      vm_wait:        (also see VM_WAIT macro)
 2582  *
 2583  *      Sleep until free pages are available for allocation.
 2584  *      - Called in various places before memory allocations.
 2585  */
 2586 static void
 2587 _vm_wait(void)
 2588 {
 2589 
 2590         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
 2591         if (curproc == pageproc) {
 2592                 vm_pageout_pages_needed = 1;
 2593                 msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
 2594                     PDROP | PSWP, "VMWait", 0);
 2595         } else {
 2596                 if (pageproc == NULL)
 2597                         panic("vm_wait in early boot");
 2598                 pagedaemon_wait(PVM, "vmwait");
 2599         }
 2600 }
 2601 
 2602 void
 2603 vm_wait(void)
 2604 {
 2605 
 2606         mtx_lock(&vm_page_queue_free_mtx);
 2607         _vm_wait();
 2608 }
 2609 
 2610 /*
 2611  *      vm_page_alloc_fail:
 2612  *
 2613  *      Called when a page allocation function fails.  Informs the
 2614  *      pagedaemon and performs the requested wait.  Requires the
 2615  *      page_queue_free and object lock on entry.  Returns with the
 2616  *      object lock held and free lock released.  Returns an error when
 2617  *      retry is necessary.
 2618  *
 2619  */
 2620 static int
 2621 vm_page_alloc_fail(vm_object_t object, int req)
 2622 {
 2623 
 2624         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
 2625 
 2626         atomic_add_int(&vm_pageout_deficit,
 2627             max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
 2628         if (req & (VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL)) {
 2629                 if (object != NULL) 
 2630                         VM_OBJECT_WUNLOCK(object);
 2631                 _vm_wait();
 2632                 if (object != NULL) 
 2633                         VM_OBJECT_WLOCK(object);
 2634                 if (req & VM_ALLOC_WAITOK)
 2635                         return (EAGAIN);
 2636         } else {
 2637                 mtx_unlock(&vm_page_queue_free_mtx);
 2638                 pagedaemon_wakeup();
 2639         }
 2640         return (0);
 2641 }
 2642 
 2643 /*
 2644  *      vm_waitpfault:  (also see VM_WAITPFAULT macro)
 2645  *
 2646  *      Sleep until free pages are available for allocation.
 2647  *      - Called only in vm_fault so that processes page faulting
 2648  *        can be easily tracked.
 2649  *      - Sleeps at a lower priority than vm_wait() so that vm_wait()ing
 2650  *        processes will be able to grab memory first.  Do not change
 2651  *        this balance without careful testing first.
 2652  */
 2653 void
 2654 vm_waitpfault(void)
 2655 {
 2656 
 2657         mtx_lock(&vm_page_queue_free_mtx);
 2658         pagedaemon_wait(PUSER, "pfault");
 2659 }
 2660 
 2661 struct vm_pagequeue *
 2662 vm_page_pagequeue(vm_page_t m)
 2663 {
 2664 
 2665         if (vm_page_in_laundry(m))
 2666                 return (&vm_dom[0].vmd_pagequeues[m->queue]);
 2667         else
 2668                 return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
 2669 }
 2670 
 2671 /*
 2672  *      vm_page_dequeue:
 2673  *
 2674  *      Remove the given page from its current page queue.
 2675  *
 2676  *      The page must be locked.
 2677  */
 2678 void
 2679 vm_page_dequeue(vm_page_t m)
 2680 {
 2681         struct vm_pagequeue *pq;
 2682 
 2683         vm_page_assert_locked(m);
 2684         KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
 2685             m));
 2686         pq = vm_page_pagequeue(m);
 2687         vm_pagequeue_lock(pq);
 2688         m->queue = PQ_NONE;
 2689         TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
 2690         vm_pagequeue_cnt_dec(pq);
 2691         vm_pagequeue_unlock(pq);
 2692 }
 2693 
 2694 /*
 2695  *      vm_page_dequeue_locked:
 2696  *
 2697  *      Remove the given page from its current page queue.
 2698  *
 2699  *      The page and page queue must be locked.
 2700  */
 2701 void
 2702 vm_page_dequeue_locked(vm_page_t m)
 2703 {
 2704         struct vm_pagequeue *pq;
 2705 
 2706         vm_page_lock_assert(m, MA_OWNED);
 2707         pq = vm_page_pagequeue(m);
 2708         vm_pagequeue_assert_locked(pq);
 2709         m->queue = PQ_NONE;
 2710         TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
 2711         vm_pagequeue_cnt_dec(pq);
 2712 }
 2713 
 2714 /*
 2715  *      vm_page_enqueue:
 2716  *
 2717  *      Add the given page to the specified page queue.
 2718  *
 2719  *      The page must be locked.
 2720  */
 2721 static void
 2722 vm_page_enqueue(uint8_t queue, vm_page_t m)
 2723 {
 2724         struct vm_pagequeue *pq;
 2725 
 2726         vm_page_lock_assert(m, MA_OWNED);
 2727         KASSERT(queue < PQ_COUNT,
 2728             ("vm_page_enqueue: invalid queue %u request for page %p",
 2729             queue, m));
 2730         if (queue == PQ_LAUNDRY)
 2731                 pq = &vm_dom[0].vmd_pagequeues[queue];
 2732         else
 2733                 pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
 2734         vm_pagequeue_lock(pq);
 2735         m->queue = queue;
 2736         TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
 2737         vm_pagequeue_cnt_inc(pq);
 2738         vm_pagequeue_unlock(pq);
 2739 }
 2740 
 2741 /*
 2742  *      vm_page_requeue:
 2743  *
 2744  *      Move the given page to the tail of its current page queue.
 2745  *
 2746  *      The page must be locked.
 2747  */
 2748 void
 2749 vm_page_requeue(vm_page_t m)
 2750 {
 2751         struct vm_pagequeue *pq;
 2752 
 2753         vm_page_lock_assert(m, MA_OWNED);
 2754         KASSERT(m->queue != PQ_NONE,
 2755             ("vm_page_requeue: page %p is not queued", m));
 2756         pq = vm_page_pagequeue(m);
 2757         vm_pagequeue_lock(pq);
 2758         TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
 2759         TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
 2760         vm_pagequeue_unlock(pq);
 2761 }
 2762 
 2763 /*
 2764  *      vm_page_requeue_locked:
 2765  *
 2766  *      Move the given page to the tail of its current page queue.
 2767  *
 2768  *      The page queue must be locked.
 2769  */
 2770 void
 2771 vm_page_requeue_locked(vm_page_t m)
 2772 {
 2773         struct vm_pagequeue *pq;
 2774 
 2775         KASSERT(m->queue != PQ_NONE,
 2776             ("vm_page_requeue_locked: page %p is not queued", m));
 2777         pq = vm_page_pagequeue(m);
 2778         vm_pagequeue_assert_locked(pq);
 2779         TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
 2780         TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
 2781 }
 2782 
 2783 /*
 2784  *      vm_page_activate:
 2785  *
 2786  *      Put the specified page on the active list (if appropriate).
 2787  *      Ensure that act_count is at least ACT_INIT but do not otherwise
 2788  *      mess with it.
 2789  *
 2790  *      The page must be locked.
 2791  */
 2792 void
 2793 vm_page_activate(vm_page_t m)
 2794 {
 2795         int queue;
 2796 
 2797         vm_page_lock_assert(m, MA_OWNED);
 2798         if ((queue = m->queue) != PQ_ACTIVE) {
 2799                 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
 2800                         if (m->act_count < ACT_INIT)
 2801                                 m->act_count = ACT_INIT;
 2802                         if (queue != PQ_NONE)
 2803                                 vm_page_dequeue(m);
 2804                         vm_page_enqueue(PQ_ACTIVE, m);
 2805                 } else
 2806                         KASSERT(queue == PQ_NONE,
 2807                             ("vm_page_activate: wired page %p is queued", m));
 2808         } else {
 2809                 if (m->act_count < ACT_INIT)
 2810                         m->act_count = ACT_INIT;
 2811         }
 2812 }
 2813 
 2814 /*
 2815  *      vm_page_free_wakeup:
 2816  *
 2817  *      Helper routine for vm_page_free_toq().  This routine is called
 2818  *      when a page is added to the free queues.
 2819  *
 2820  *      The page queues must be locked.
 2821  */
 2822 static void
 2823 vm_page_free_wakeup(void)
 2824 {
 2825 
 2826         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
 2827         /*
 2828          * if pageout daemon needs pages, then tell it that there are
 2829          * some free.
 2830          */
 2831         if (vm_pageout_pages_needed &&
 2832             vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
 2833                 wakeup(&vm_pageout_pages_needed);
 2834                 vm_pageout_pages_needed = 0;
 2835         }
 2836         /*
 2837          * wakeup processes that are waiting on memory if we hit a
 2838          * high water mark. And wakeup scheduler process if we have
 2839          * lots of memory. this process will swapin processes.
 2840          */
 2841         if (vm_pages_needed && !vm_page_count_min()) {
 2842                 vm_pages_needed = false;
 2843                 wakeup(&vm_cnt.v_free_count);
 2844         }
 2845 }
 2846 
 2847 /*
 2848  *      vm_page_free_prep:
 2849  *
 2850  *      Prepares the given page to be put on the free list,
 2851  *      disassociating it from any VM object. The caller may return
 2852  *      the page to the free list only if this function returns true.
 2853  *
 2854  *      The object must be locked.  The page must be locked if it is
 2855  *      managed.  For a queued managed page, the pagequeue_locked
 2856  *      argument specifies whether the page queue is already locked.
 2857  */
 2858 bool
 2859 vm_page_free_prep(vm_page_t m, bool pagequeue_locked)
 2860 {
 2861 
 2862 #if defined(DIAGNOSTIC) && defined(PHYS_TO_DMAP)
 2863         if ((m->flags & PG_ZERO) != 0) {
 2864                 uint64_t *p;
 2865                 int i;
 2866                 p = (uint64_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
 2867                 for (i = 0; i < PAGE_SIZE / sizeof(uint64_t); i++, p++)
 2868                         KASSERT(*p == 0, ("vm_page_free_prep %p PG_ZERO %d %jx",
 2869                             m, i, (uintmax_t)*p));
 2870         }
 2871 #endif
 2872         if ((m->oflags & VPO_UNMANAGED) == 0) {
 2873                 vm_page_lock_assert(m, MA_OWNED);
 2874                 KASSERT(!pmap_page_is_mapped(m),
 2875                     ("vm_page_free_toq: freeing mapped page %p", m));
 2876         } else
 2877                 KASSERT(m->queue == PQ_NONE,
 2878                     ("vm_page_free_toq: unmanaged page %p is queued", m));
 2879         PCPU_INC(cnt.v_tfree);
 2880 
 2881         if (vm_page_sbusied(m))
 2882                 panic("vm_page_free: freeing busy page %p", m);
 2883 
 2884         /*
 2885          * Unqueue, then remove page.  Note that we cannot destroy
 2886          * the page here because we do not want to call the pager's
 2887          * callback routine until after we've put the page on the
 2888          * appropriate free queue.
 2889          */
 2890         if (m->queue != PQ_NONE) {
 2891                 if (pagequeue_locked)
 2892                         vm_page_dequeue_locked(m);
 2893                 else
 2894                         vm_page_dequeue(m);
 2895         }
 2896         vm_page_remove(m);
 2897 
 2898         /*
 2899          * If fictitious remove object association and
 2900          * return, otherwise delay object association removal.
 2901          */
 2902         if ((m->flags & PG_FICTITIOUS) != 0)
 2903                 return (false);
 2904 
 2905         m->valid = 0;
 2906         vm_page_undirty(m);
 2907 
 2908         if (m->wire_count != 0)
 2909                 panic("vm_page_free: freeing wired page %p", m);
 2910         if (m->hold_count != 0) {
 2911                 m->flags &= ~PG_ZERO;
 2912                 KASSERT((m->flags & PG_UNHOLDFREE) == 0,
 2913                     ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
 2914                 m->flags |= PG_UNHOLDFREE;
 2915                 return (false);
 2916         }
 2917 
 2918         /*
 2919          * Restore the default memory attribute to the page.
 2920          */
 2921         if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
 2922                 pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
 2923 
 2924         return (true);
 2925 }
 2926 
 2927 /*
 2928  * Insert the page into the physical memory allocator's free page
 2929  * queues.  This is the last step to free a page.
 2930  */
 2931 static void
 2932 vm_page_free_phys(vm_page_t m)
 2933 {
 2934 
 2935         mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
 2936 
 2937         vm_phys_freecnt_adj(m, 1);
 2938 #if VM_NRESERVLEVEL > 0
 2939         if (!vm_reserv_free_page(m))
 2940 #endif
 2941                         vm_phys_free_pages(m, 0);
 2942         if ((m->flags & PG_ZERO) != 0)
 2943                 ++vm_page_zero_count;
 2944         else
 2945                 vm_page_zero_idle_wakeup();
 2946 }
 2947 
 2948 void
 2949 vm_page_free_phys_pglist(struct pglist *tq)
 2950 {
 2951         vm_page_t m;
 2952 
 2953         if (TAILQ_EMPTY(tq))
 2954                 return;
 2955         mtx_lock(&vm_page_queue_free_mtx);
 2956         TAILQ_FOREACH(m, tq, listq)
 2957                 vm_page_free_phys(m);
 2958         vm_page_free_wakeup();
 2959         mtx_unlock(&vm_page_queue_free_mtx);
 2960 }
 2961 
 2962 /*
 2963  *      vm_page_free_toq:
 2964  *
 2965  *      Returns the given page to the free list, disassociating it
 2966  *      from any VM object.
 2967  *
 2968  *      The object must be locked.  The page must be locked if it is
 2969  *      managed.
 2970  */
 2971 void
 2972 vm_page_free_toq(vm_page_t m)
 2973 {
 2974 
 2975         if (!vm_page_free_prep(m, false))
 2976                 return;
 2977         mtx_lock(&vm_page_queue_free_mtx);
 2978         vm_page_free_phys(m);
 2979         vm_page_free_wakeup();
 2980         mtx_unlock(&vm_page_queue_free_mtx);
 2981 }
 2982 
 2983 /*
 2984  *      vm_page_wire:
 2985  *
 2986  *      Mark this page as wired down by yet
 2987  *      another map, removing it from paging queues
 2988  *      as necessary.
 2989  *
 2990  *      If the page is fictitious, then its wire count must remain one.
 2991  *
 2992  *      The page must be locked.
 2993  */
 2994 void
 2995 vm_page_wire(vm_page_t m)
 2996 {
 2997 
 2998         /*
 2999          * Only bump the wire statistics if the page is not already wired,
 3000          * and only unqueue the page if it is on some queue (if it is unmanaged
 3001          * it is already off the queues).
 3002          */
 3003         vm_page_lock_assert(m, MA_OWNED);
 3004         if ((m->flags & PG_FICTITIOUS) != 0) {
 3005                 KASSERT(m->wire_count == 1,
 3006                     ("vm_page_wire: fictitious page %p's wire count isn't one",
 3007                     m));
 3008                 return;
 3009         }
 3010         if (m->wire_count == 0) {
 3011                 KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
 3012                     m->queue == PQ_NONE,
 3013                     ("vm_page_wire: unmanaged page %p is queued", m));
 3014                 vm_page_remque(m);
 3015                 atomic_add_int(&vm_cnt.v_wire_count, 1);
 3016         }
 3017         m->wire_count++;
 3018         KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
 3019 }
 3020 
 3021 /*
 3022  * vm_page_unwire:
 3023  *
 3024  * Release one wiring of the specified page, potentially allowing it to be
 3025  * paged out.  Returns TRUE if the number of wirings transitions to zero and
 3026  * FALSE otherwise.
 3027  *
 3028  * Only managed pages belonging to an object can be paged out.  If the number
 3029  * of wirings transitions to zero and the page is eligible for page out, then
 3030  * the page is added to the specified paging queue (unless PQ_NONE is
 3031  * specified).
 3032  *
 3033  * If a page is fictitious, then its wire count must always be one.
 3034  *
 3035  * A managed page must be locked.
 3036  */
 3037 boolean_t
 3038 vm_page_unwire(vm_page_t m, uint8_t queue)
 3039 {
 3040 
 3041         KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
 3042             ("vm_page_unwire: invalid queue %u request for page %p",
 3043             queue, m));
 3044         if ((m->oflags & VPO_UNMANAGED) == 0)
 3045                 vm_page_assert_locked(m);
 3046         if ((m->flags & PG_FICTITIOUS) != 0) {
 3047                 KASSERT(m->wire_count == 1,
 3048             ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
 3049                 return (FALSE);
 3050         }
 3051         if (m->wire_count > 0) {
 3052                 m->wire_count--;
 3053                 if (m->wire_count == 0) {
 3054                         atomic_subtract_int(&vm_cnt.v_wire_count, 1);
 3055                         if ((m->oflags & VPO_UNMANAGED) == 0 &&
 3056                             m->object != NULL && queue != PQ_NONE)
 3057                                 vm_page_enqueue(queue, m);
 3058                         return (TRUE);
 3059                 } else
 3060                         return (FALSE);
 3061         } else
 3062                 panic("vm_page_unwire: page %p's wire count is zero", m);
 3063 }
 3064 
 3065 /*
 3066  * Move the specified page to the inactive queue.
 3067  *
 3068  * Normally, "noreuse" is FALSE, resulting in LRU ordering of the inactive
 3069  * queue.  However, setting "noreuse" to TRUE will accelerate the specified
 3070  * page's reclamation, but it will not unmap the page from any address space.
 3071  * This is implemented by inserting the page near the head of the inactive
 3072  * queue, using a marker page to guide FIFO insertion ordering.
 3073  *
 3074  * The page must be locked.
 3075  */
 3076 static inline void
 3077 _vm_page_deactivate(vm_page_t m, boolean_t noreuse)
 3078 {
 3079         struct vm_pagequeue *pq;
 3080         int queue;
 3081 
 3082         vm_page_assert_locked(m);
 3083 
 3084         /*
 3085          * Ignore if the page is already inactive, unless it is unlikely to be
 3086          * reactivated.
 3087          */
 3088         if ((queue = m->queue) == PQ_INACTIVE && !noreuse)
 3089                 return;
 3090         if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
 3091                 pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
 3092                 /* Avoid multiple acquisitions of the inactive queue lock. */
 3093                 if (queue == PQ_INACTIVE) {
 3094                         vm_pagequeue_lock(pq);
 3095                         vm_page_dequeue_locked(m);
 3096                 } else {
 3097                         if (queue != PQ_NONE)
 3098                                 vm_page_dequeue(m);
 3099                         vm_pagequeue_lock(pq);
 3100                 }
 3101                 m->queue = PQ_INACTIVE;
 3102                 if (noreuse)
 3103                         TAILQ_INSERT_BEFORE(&vm_phys_domain(m)->vmd_inacthead,
 3104                             m, plinks.q);
 3105                 else
 3106                         TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
 3107                 vm_pagequeue_cnt_inc(pq);
 3108                 vm_pagequeue_unlock(pq);
 3109         }
 3110 }
 3111 
 3112 /*
 3113  * Move the specified page to the inactive queue.
 3114  *
 3115  * The page must be locked.
 3116  */
 3117 void
 3118 vm_page_deactivate(vm_page_t m)
 3119 {
 3120 
 3121         _vm_page_deactivate(m, FALSE);
 3122 }
 3123 
 3124 /*
 3125  * Move the specified page to the inactive queue with the expectation
 3126  * that it is unlikely to be reused.
 3127  *
 3128  * The page must be locked.
 3129  */
 3130 void
 3131 vm_page_deactivate_noreuse(vm_page_t m)
 3132 {
 3133 
 3134         _vm_page_deactivate(m, TRUE);
 3135 }
 3136 
 3137 /*
 3138  * vm_page_launder
 3139  *
 3140  *      Put a page in the laundry.
 3141  */
 3142 void
 3143 vm_page_launder(vm_page_t m)
 3144 {
 3145         int queue;
 3146 
 3147         vm_page_assert_locked(m);
 3148         if ((queue = m->queue) != PQ_LAUNDRY) {
 3149                 if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
 3150                         if (queue != PQ_NONE)
 3151                                 vm_page_dequeue(m);
 3152                         vm_page_enqueue(PQ_LAUNDRY, m);
 3153                 } else
 3154                         KASSERT(queue == PQ_NONE,
 3155                             ("wired page %p is queued", m));
 3156         }
 3157 }
 3158 
 3159 /*
 3160  * vm_page_try_to_free()
 3161  *
 3162  *      Attempt to free the page.  If we cannot free it, we do nothing.
 3163  *      true is returned on success, false on failure.
 3164  */
 3165 bool
 3166 vm_page_try_to_free(vm_page_t m)
 3167 {
 3168 
 3169         vm_page_assert_locked(m);
 3170         if (m->object != NULL)
 3171                 VM_OBJECT_ASSERT_WLOCKED(m->object);
 3172         if (m->dirty != 0 || m->hold_count != 0 || m->wire_count != 0 ||
 3173             (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
 3174                 return (false);
 3175         if (m->object != NULL && m->object->ref_count != 0) {
 3176                 pmap_remove_all(m);
 3177                 if (m->dirty != 0)
 3178                         return (false);
 3179         }
 3180         vm_page_free(m);
 3181         return (true);
 3182 }
 3183 
 3184 /*
 3185  * vm_page_advise
 3186  *
 3187  *      Apply the specified advice to the given page.
 3188  *
 3189  *      The object and page must be locked.
 3190  */
 3191 void
 3192 vm_page_advise(vm_page_t m, int advice)
 3193 {
 3194 
 3195         vm_page_assert_locked(m);
 3196         VM_OBJECT_ASSERT_WLOCKED(m->object);
 3197         if (advice == MADV_FREE)
 3198                 /*
 3199                  * Mark the page clean.  This will allow the page to be freed
 3200                  * without first paging it out.  MADV_FREE pages are often
 3201                  * quickly reused by malloc(3), so we do not do anything that
 3202                  * would result in a page fault on a later access.
 3203                  */
 3204                 vm_page_undirty(m);
 3205         else if (advice != MADV_DONTNEED) {
 3206                 if (advice == MADV_WILLNEED)
 3207                         vm_page_activate(m);
 3208                 return;
 3209         }
 3210 
 3211         /*
 3212          * Clear any references to the page.  Otherwise, the page daemon will
 3213          * immediately reactivate the page.
 3214          */
 3215         vm_page_aflag_clear(m, PGA_REFERENCED);
 3216 
 3217         if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
 3218                 vm_page_dirty(m);
 3219 
 3220         /*
 3221          * Place clean pages near the head of the inactive queue rather than
 3222          * the tail, thus defeating the queue's LRU operation and ensuring that
 3223          * the page will be reused quickly.  Dirty pages not already in the
 3224          * laundry are moved there.
 3225          */
 3226         if (m->dirty == 0)
 3227                 vm_page_deactivate_noreuse(m);
 3228         else
 3229                 vm_page_launder(m);
 3230 }
 3231 
 3232 /*
 3233  * Grab a page, waiting until we are waken up due to the page
 3234  * changing state.  We keep on waiting, if the page continues
 3235  * to be in the object.  If the page doesn't exist, first allocate it
 3236  * and then conditionally zero it.
 3237  *
 3238  * This routine may sleep.
 3239  *
 3240  * The object must be locked on entry.  The lock will, however, be released
 3241  * and reacquired if the routine sleeps.
 3242  */
 3243 vm_page_t
 3244 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
 3245 {
 3246         vm_page_t m;
 3247         int sleep;
 3248         int pflags;
 3249 
 3250         VM_OBJECT_ASSERT_WLOCKED(object);
 3251         KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
 3252             (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
 3253             ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
 3254         pflags = allocflags &
 3255             ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK | VM_ALLOC_WAITFAIL);
 3256         if ((allocflags & VM_ALLOC_NOWAIT) == 0)
 3257                 pflags |= VM_ALLOC_WAITFAIL;
 3258 retrylookup:
 3259         if ((m = vm_page_lookup(object, pindex)) != NULL) {
 3260                 sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
 3261                     vm_page_xbusied(m) : vm_page_busied(m);
 3262                 if (sleep) {
 3263                         if ((allocflags & VM_ALLOC_NOWAIT) != 0)
 3264                                 return (NULL);
 3265                         /*
 3266                          * Reference the page before unlocking and
 3267                          * sleeping so that the page daemon is less
 3268                          * likely to reclaim it.
 3269                          */
 3270                         vm_page_aflag_set(m, PGA_REFERENCED);
 3271                         vm_page_lock(m);
 3272                         VM_OBJECT_WUNLOCK(object);
 3273                         vm_page_busy_sleep(m, "pgrbwt", (allocflags &
 3274                             VM_ALLOC_IGN_SBUSY) != 0);
 3275                         VM_OBJECT_WLOCK(object);
 3276                         goto retrylookup;
 3277                 } else {
 3278                         if ((allocflags & VM_ALLOC_WIRED) != 0) {
 3279                                 vm_page_lock(m);
 3280                                 vm_page_wire(m);
 3281                                 vm_page_unlock(m);
 3282                         }
 3283                         if ((allocflags &
 3284                             (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
 3285                                 vm_page_xbusy(m);
 3286                         if ((allocflags & VM_ALLOC_SBUSY) != 0)
 3287                                 vm_page_sbusy(m);
 3288                         return (m);
 3289                 }
 3290         }
 3291         m = vm_page_alloc(object, pindex, pflags);
 3292         if (m == NULL) {
 3293                 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
 3294                         return (NULL);
 3295                 goto retrylookup;
 3296         }
 3297         if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
 3298                 pmap_zero_page(m);
 3299         return (m);
 3300 }
 3301 
 3302 /*
 3303  * Return the specified range of pages from the given object.  For each
 3304  * page offset within the range, if a page already exists within the object
 3305  * at that offset and it is busy, then wait for it to change state.  If,
 3306  * instead, the page doesn't exist, then allocate it.
 3307  *
 3308  * The caller must always specify an allocation class.
 3309  *
 3310  * allocation classes:
 3311  *      VM_ALLOC_NORMAL         normal process request
 3312  *      VM_ALLOC_SYSTEM         system *really* needs the pages
 3313  *
 3314  * The caller must always specify that the pages are to be busied and/or
 3315  * wired.
 3316  *
 3317  * optional allocation flags:
 3318  *      VM_ALLOC_IGN_SBUSY      do not sleep on soft busy pages
 3319  *      VM_ALLOC_NOBUSY         do not exclusive busy the page
 3320  *      VM_ALLOC_NOWAIT         do not sleep
 3321  *      VM_ALLOC_SBUSY          set page to sbusy state
 3322  *      VM_ALLOC_WIRED          wire the pages
 3323  *      VM_ALLOC_ZERO           zero and validate any invalid pages
 3324  *
 3325  * If VM_ALLOC_NOWAIT is not specified, this routine may sleep.  Otherwise, it
 3326  * may return a partial prefix of the requested range.
 3327  */
 3328 int
 3329 vm_page_grab_pages(vm_object_t object, vm_pindex_t pindex, int allocflags,
 3330     vm_page_t *ma, int count)
 3331 {
 3332         vm_page_t m, mpred;
 3333         int pflags;
 3334         int i;
 3335         bool sleep;
 3336 
 3337         VM_OBJECT_ASSERT_WLOCKED(object);
 3338         KASSERT(((u_int)allocflags >> VM_ALLOC_COUNT_SHIFT) == 0,
 3339             ("vm_page_grap_pages: VM_ALLOC_COUNT() is not allowed"));
 3340         KASSERT((allocflags & VM_ALLOC_NOBUSY) == 0 ||
 3341             (allocflags & VM_ALLOC_WIRED) != 0,
 3342             ("vm_page_grab_pages: the pages must be busied or wired"));
 3343         KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
 3344             (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
 3345             ("vm_page_grab_pages: VM_ALLOC_SBUSY/IGN_SBUSY mismatch"));
 3346         if (count == 0)
 3347                 return (0);
 3348         pflags = allocflags & ~(VM_ALLOC_NOWAIT | VM_ALLOC_WAITOK |
 3349             VM_ALLOC_WAITFAIL | VM_ALLOC_IGN_SBUSY);
 3350         if ((allocflags & VM_ALLOC_NOWAIT) == 0)
 3351                 pflags |= VM_ALLOC_WAITFAIL;
 3352         i = 0;
 3353 retrylookup:
 3354         m = vm_radix_lookup_le(&object->rtree, pindex + i);
 3355         if (m == NULL || m->pindex != pindex + i) {
 3356                 mpred = m;
 3357                 m = NULL;
 3358         } else
 3359                 mpred = TAILQ_PREV(m, pglist, listq);
 3360         for (; i < count; i++) {
 3361                 if (m != NULL) {
 3362                         sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
 3363                             vm_page_xbusied(m) : vm_page_busied(m);
 3364                         if (sleep) {
 3365                                 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
 3366                                         break;
 3367                                 /*
 3368                                  * Reference the page before unlocking and
 3369                                  * sleeping so that the page daemon is less
 3370                                  * likely to reclaim it.
 3371                                  */
 3372                                 vm_page_aflag_set(m, PGA_REFERENCED);
 3373                                 vm_page_lock(m);
 3374                                 VM_OBJECT_WUNLOCK(object);
 3375                                 vm_page_busy_sleep(m, "grbmaw", (allocflags &
 3376                                     VM_ALLOC_IGN_SBUSY) != 0);
 3377                                 VM_OBJECT_WLOCK(object);
 3378                                 goto retrylookup;
 3379                         }
 3380                         if ((allocflags & VM_ALLOC_WIRED) != 0) {
 3381                                 vm_page_lock(m);
 3382                                 vm_page_wire(m);
 3383                                 vm_page_unlock(m);
 3384                         }
 3385                         if ((allocflags & (VM_ALLOC_NOBUSY |
 3386                             VM_ALLOC_SBUSY)) == 0)
 3387                                 vm_page_xbusy(m);
 3388                         if ((allocflags & VM_ALLOC_SBUSY) != 0)
 3389                                 vm_page_sbusy(m);
 3390                 } else {
 3391                         m = vm_page_alloc_after(object, pindex + i,
 3392                             pflags | VM_ALLOC_COUNT(count - i), mpred);
 3393                         if (m == NULL) {
 3394                                 if ((allocflags & VM_ALLOC_NOWAIT) != 0)
 3395                                         break;
 3396                                 goto retrylookup;
 3397                         }
 3398                 }
 3399                 if (m->valid == 0 && (allocflags & VM_ALLOC_ZERO) != 0) {
 3400                         if ((m->flags & PG_ZERO) == 0)
 3401                                 pmap_zero_page(m);
 3402                         m->valid = VM_PAGE_BITS_ALL;
 3403                 }
 3404                 ma[i] = mpred = m;
 3405                 m = vm_page_next(m);
 3406         }
 3407         return (i);
 3408 }
 3409 
 3410 /*
 3411  * Mapping function for valid or dirty bits in a page.
 3412  *
 3413  * Inputs are required to range within a page.
 3414  */
 3415 vm_page_bits_t
 3416 vm_page_bits(int base, int size)
 3417 {
 3418         int first_bit;
 3419         int last_bit;
 3420 
 3421         KASSERT(
 3422             base + size <= PAGE_SIZE,
 3423             ("vm_page_bits: illegal base/size %d/%d", base, size)
 3424         );
 3425 
 3426         if (size == 0)          /* handle degenerate case */
 3427                 return (0);
 3428 
 3429         first_bit = base >> DEV_BSHIFT;
 3430         last_bit = (base + size - 1) >> DEV_BSHIFT;
 3431 
 3432         return (((vm_page_bits_t)2 << last_bit) -
 3433             ((vm_page_bits_t)1 << first_bit));
 3434 }
 3435 
 3436 /*
 3437  *      vm_page_set_valid_range:
 3438  *
 3439  *      Sets portions of a page valid.  The arguments are expected
 3440  *      to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
 3441  *      of any partial chunks touched by the range.  The invalid portion of
 3442  *      such chunks will be zeroed.
 3443  *
 3444  *      (base + size) must be less then or equal to PAGE_SIZE.
 3445  */
 3446 void
 3447 vm_page_set_valid_range(vm_page_t m, int base, int size)
 3448 {
 3449         int endoff, frag;
 3450 
 3451         VM_OBJECT_ASSERT_WLOCKED(m->object);
 3452         if (size == 0)  /* handle degenerate case */
 3453                 return;
 3454 
 3455         /*
 3456          * If the base is not DEV_BSIZE aligned and the valid
 3457          * bit is clear, we have to zero out a portion of the
 3458          * first block.
 3459          */
 3460         if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
 3461             (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
 3462                 pmap_zero_page_area(m, frag, base - frag);
 3463 
 3464         /*
 3465          * If the ending offset is not DEV_BSIZE aligned and the
 3466          * valid bit is clear, we have to zero out a portion of
 3467          * the last block.
 3468          */
 3469         endoff = base + size;
 3470         if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
 3471             (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
 3472                 pmap_zero_page_area(m, endoff,
 3473                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
 3474 
 3475         /*
 3476          * Assert that no previously invalid block that is now being validated
 3477          * is already dirty.
 3478          */
 3479         KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
 3480             ("vm_page_set_valid_range: page %p is dirty", m));
 3481 
 3482         /*
 3483          * Set valid bits inclusive of any overlap.
 3484          */
 3485         m->valid |= vm_page_bits(base, size);
 3486 }
 3487 
 3488 /*
 3489  * Clear the given bits from the specified page's dirty field.
 3490  */
 3491 static __inline void
 3492 vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
 3493 {
 3494         uintptr_t addr;
 3495 #if PAGE_SIZE < 16384
 3496         int shift;
 3497 #endif
 3498 
 3499         /*
 3500          * If the object is locked and the page is neither exclusive busy nor
 3501          * write mapped, then the page's dirty field cannot possibly be
 3502          * set by a concurrent pmap operation.
 3503          */
 3504         VM_OBJECT_ASSERT_WLOCKED(m->object);
 3505         if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
 3506                 m->dirty &= ~pagebits;
 3507         else {
 3508                 /*
 3509                  * The pmap layer can call vm_page_dirty() without
 3510                  * holding a distinguished lock.  The combination of
 3511                  * the object's lock and an atomic operation suffice
 3512                  * to guarantee consistency of the page dirty field.
 3513                  *
 3514                  * For PAGE_SIZE == 32768 case, compiler already
 3515                  * properly aligns the dirty field, so no forcible
 3516                  * alignment is needed. Only require existence of
 3517                  * atomic_clear_64 when page size is 32768.
 3518                  */
 3519                 addr = (uintptr_t)&m->dirty;
 3520 #if PAGE_SIZE == 32768
 3521                 atomic_clear_64((uint64_t *)addr, pagebits);
 3522 #elif PAGE_SIZE == 16384
 3523                 atomic_clear_32((uint32_t *)addr, pagebits);
 3524 #else           /* PAGE_SIZE <= 8192 */
 3525                 /*
 3526                  * Use a trick to perform a 32-bit atomic on the
 3527                  * containing aligned word, to not depend on the existence
 3528                  * of atomic_clear_{8, 16}.
 3529                  */
 3530                 shift = addr & (sizeof(uint32_t) - 1);
 3531 #if BYTE_ORDER == BIG_ENDIAN
 3532                 shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
 3533 #else
 3534                 shift *= NBBY;
 3535 #endif
 3536                 addr &= ~(sizeof(uint32_t) - 1);
 3537                 atomic_clear_32((uint32_t *)addr, pagebits << shift);
 3538 #endif          /* PAGE_SIZE */
 3539         }
 3540 }
 3541 
 3542 /*
 3543  *      vm_page_set_validclean:
 3544  *
 3545  *      Sets portions of a page valid and clean.  The arguments are expected
 3546  *      to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
 3547  *      of any partial chunks touched by the range.  The invalid portion of
 3548  *      such chunks will be zero'd.
 3549  *
 3550  *      (base + size) must be less then or equal to PAGE_SIZE.
 3551  */
 3552 void
 3553 vm_page_set_validclean(vm_page_t m, int base, int size)
 3554 {
 3555         vm_page_bits_t oldvalid, pagebits;
 3556         int endoff, frag;
 3557 
 3558         VM_OBJECT_ASSERT_WLOCKED(m->object);
 3559         if (size == 0)  /* handle degenerate case */
 3560                 return;
 3561 
 3562         /*
 3563          * If the base is not DEV_BSIZE aligned and the valid
 3564          * bit is clear, we have to zero out a portion of the
 3565          * first block.
 3566          */
 3567         if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
 3568             (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
 3569                 pmap_zero_page_area(m, frag, base - frag);
 3570 
 3571         /*
 3572          * If the ending offset is not DEV_BSIZE aligned and the
 3573          * valid bit is clear, we have to zero out a portion of
 3574          * the last block.
 3575          */
 3576         endoff = base + size;
 3577         if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
 3578             (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
 3579                 pmap_zero_page_area(m, endoff,
 3580                     DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
 3581 
 3582         /*
 3583          * Set valid, clear dirty bits.  If validating the entire
 3584          * page we can safely clear the pmap modify bit.  We also
 3585          * use this opportunity to clear the VPO_NOSYNC flag.  If a process
 3586          * takes a write fault on a MAP_NOSYNC memory area the flag will
 3587          * be set again.
 3588          *
 3589          * We set valid bits inclusive of any overlap, but we can only
 3590          * clear dirty bits for DEV_BSIZE chunks that are fully within
 3591          * the range.
 3592          */
 3593         oldvalid = m->valid;
 3594         pagebits = vm_page_bits(base, size);
 3595         m->valid |= pagebits;
 3596 #if 0   /* NOT YET */
 3597         if ((frag = base & (DEV_BSIZE - 1)) != 0) {
 3598                 frag = DEV_BSIZE - frag;
 3599                 base += frag;
 3600                 size -= frag;
 3601                 if (size < 0)
 3602                         size = 0;
 3603         }
 3604         pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
 3605 #endif
 3606         if (base == 0 && size == PAGE_SIZE) {
 3607                 /*
 3608                  * The page can only be modified within the pmap if it is
 3609                  * mapped, and it can only be mapped if it was previously
 3610                  * fully valid.
 3611                  */
 3612                 if (oldvalid == VM_PAGE_BITS_ALL)
 3613                         /*
 3614                          * Perform the pmap_clear_modify() first.  Otherwise,
 3615                          * a concurrent pmap operation, such as
 3616                          * pmap_protect(), could clear a modification in the
 3617                          * pmap and set the dirty field on the page before
 3618                          * pmap_clear_modify() had begun and after the dirty
 3619                          * field was cleared here.
 3620                          */
 3621                         pmap_clear_modify(m);
 3622                 m->dirty = 0;
 3623                 m->oflags &= ~VPO_NOSYNC;
 3624         } else if (oldvalid != VM_PAGE_BITS_ALL)
 3625                 m->dirty &= ~pagebits;
 3626         else
 3627                 vm_page_clear_dirty_mask(m, pagebits);
 3628 }
 3629 
 3630 void
 3631 vm_page_clear_dirty(vm_page_t m, int base, int size)
 3632 {
 3633 
 3634         vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
 3635 }
 3636 
 3637 /*
 3638  *      vm_page_set_invalid:
 3639  *
 3640  *      Invalidates DEV_BSIZE'd chunks within a page.  Both the
 3641  *      valid and dirty bits for the effected areas are cleared.
 3642  */
 3643 void
 3644 vm_page_set_invalid(vm_page_t m, int base, int size)
 3645 {
 3646         vm_page_bits_t bits;
 3647         vm_object_t object;
 3648 
 3649         object = m->object;
 3650         VM_OBJECT_ASSERT_WLOCKED(object);
 3651         if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
 3652             size >= object->un_pager.vnp.vnp_size)
 3653                 bits = VM_PAGE_BITS_ALL;
 3654         else
 3655                 bits = vm_page_bits(base, size);
 3656         if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
 3657             bits != 0)
 3658                 pmap_remove_all(m);
 3659         KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
 3660             !pmap_page_is_mapped(m),
 3661             ("vm_page_set_invalid: page %p is mapped", m));
 3662         m->valid &= ~bits;
 3663         m->dirty &= ~bits;
 3664 }
 3665 
 3666 /*
 3667  * vm_page_zero_invalid()
 3668  *
 3669  *      The kernel assumes that the invalid portions of a page contain
 3670  *      garbage, but such pages can be mapped into memory by user code.
 3671  *      When this occurs, we must zero out the non-valid portions of the
 3672  *      page so user code sees what it expects.
 3673  *
 3674  *      Pages are most often semi-valid when the end of a file is mapped
 3675  *      into memory and the file's size is not page aligned.
 3676  */
 3677 void
 3678 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
 3679 {
 3680         int b;
 3681         int i;
 3682 
 3683         VM_OBJECT_ASSERT_WLOCKED(m->object);
 3684         /*
 3685          * Scan the valid bits looking for invalid sections that
 3686          * must be zeroed.  Invalid sub-DEV_BSIZE'd areas ( where the
 3687          * valid bit may be set ) have already been zeroed by
 3688          * vm_page_set_validclean().
 3689          */
 3690         for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
 3691                 if (i == (PAGE_SIZE / DEV_BSIZE) ||
 3692                     (m->valid & ((vm_page_bits_t)1 << i))) {
 3693                         if (i > b) {
 3694                                 pmap_zero_page_area(m,
 3695                                     b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
 3696                         }
 3697                         b = i + 1;
 3698                 }
 3699         }
 3700 
 3701         /*
 3702          * setvalid is TRUE when we can safely set the zero'd areas
 3703          * as being valid.  We can do this if there are no cache consistancy
 3704          * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
 3705          */
 3706         if (setvalid)
 3707                 m->valid = VM_PAGE_BITS_ALL;
 3708 }
 3709 
 3710 /*
 3711  *      vm_page_is_valid:
 3712  *
 3713  *      Is (partial) page valid?  Note that the case where size == 0
 3714  *      will return FALSE in the degenerate case where the page is
 3715  *      entirely invalid, and TRUE otherwise.
 3716  */
 3717 int
 3718 vm_page_is_valid(vm_page_t m, int base, int size)
 3719 {
 3720         vm_page_bits_t bits;
 3721 
 3722         VM_OBJECT_ASSERT_LOCKED(m->object);
 3723         bits = vm_page_bits(base, size);
 3724         return (m->valid != 0 && (m->valid & bits) == bits);
 3725 }
 3726 
 3727 /*
 3728  * Returns true if all of the specified predicates are true for the entire
 3729  * (super)page and false otherwise.
 3730  */
 3731 bool
 3732 vm_page_ps_test(vm_page_t m, int flags, vm_page_t skip_m)
 3733 {
 3734         vm_object_t object;
 3735         int i, npages;
 3736 
 3737         object = m->object;
 3738         if (skip_m != NULL && skip_m->object != object)
 3739                 return (false);
 3740         VM_OBJECT_ASSERT_LOCKED(object);
 3741         npages = atop(pagesizes[m->psind]);
 3742 
 3743         /*
 3744          * The physically contiguous pages that make up a superpage, i.e., a
 3745          * page with a page size index ("psind") greater than zero, will
 3746          * occupy adjacent entries in vm_page_array[].
 3747          */
 3748         for (i = 0; i < npages; i++) {
 3749                 /* Always test object consistency, including "skip_m". */
 3750                 if (m[i].object != object)
 3751                         return (false);
 3752                 if (&m[i] == skip_m)
 3753                         continue;
 3754                 if ((flags & PS_NONE_BUSY) != 0 && vm_page_busied(&m[i]))
 3755                         return (false);
 3756                 if ((flags & PS_ALL_DIRTY) != 0) {
 3757                         /*
 3758                          * Calling vm_page_test_dirty() or pmap_is_modified()
 3759                          * might stop this case from spuriously returning
 3760                          * "false".  However, that would require a write lock
 3761                          * on the object containing "m[i]".
 3762                          */
 3763                         if (m[i].dirty != VM_PAGE_BITS_ALL)
 3764                                 return (false);
 3765                 }
 3766                 if ((flags & PS_ALL_VALID) != 0 &&
 3767                     m[i].valid != VM_PAGE_BITS_ALL)
 3768                         return (false);
 3769         }
 3770         return (true);
 3771 }
 3772 
 3773 /*
 3774  * Set the page's dirty bits if the page is modified.
 3775  */
 3776 void
 3777 vm_page_test_dirty(vm_page_t m)
 3778 {
 3779 
 3780         VM_OBJECT_ASSERT_WLOCKED(m->object);
 3781         if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
 3782                 vm_page_dirty(m);
 3783 }
 3784 
 3785 void
 3786 vm_page_lock_KBI(vm_page_t m, const char *file, int line)
 3787 {
 3788 
 3789         mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
 3790 }
 3791 
 3792 void
 3793 vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
 3794 {
 3795 
 3796         mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
 3797 }
 3798 
 3799 int
 3800 vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
 3801 {
 3802 
 3803         return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
 3804 }
 3805 
 3806 #if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
 3807 void
 3808 vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
 3809 {
 3810 
 3811         vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
 3812 }
 3813 
 3814 void
 3815 vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
 3816 {
 3817 
 3818         mtx_assert_(vm_page_lockptr(m), a, file, line);
 3819 }
 3820 #endif
 3821 
 3822 #ifdef INVARIANTS
 3823 void
 3824 vm_page_object_lock_assert(vm_page_t m)
 3825 {
 3826 
 3827         /*
 3828          * Certain of the page's fields may only be modified by the
 3829          * holder of the containing object's lock or the exclusive busy.
 3830          * holder.  Unfortunately, the holder of the write busy is
 3831          * not recorded, and thus cannot be checked here.
 3832          */
 3833         if (m->object != NULL && !vm_page_xbusied(m))
 3834                 VM_OBJECT_ASSERT_WLOCKED(m->object);
 3835 }
 3836 
 3837 void
 3838 vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
 3839 {
 3840 
 3841         if ((bits & PGA_WRITEABLE) == 0)
 3842                 return;
 3843 
 3844         /*
 3845          * The PGA_WRITEABLE flag can only be set if the page is
 3846          * managed, is exclusively busied or the object is locked.
 3847          * Currently, this flag is only set by pmap_enter().
 3848          */
 3849         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 3850             ("PGA_WRITEABLE on unmanaged page"));
 3851         if (!vm_page_xbusied(m))
 3852                 VM_OBJECT_ASSERT_LOCKED(m->object);
 3853 }
 3854 #endif
 3855 
 3856 #include "opt_ddb.h"
 3857 #ifdef DDB
 3858 #include <sys/kernel.h>
 3859 
 3860 #include <ddb/ddb.h>
 3861 
 3862 DB_SHOW_COMMAND(page, vm_page_print_page_info)
 3863 {
 3864 
 3865         db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
 3866         db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
 3867         db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
 3868         db_printf("vm_cnt.v_laundry_count: %d\n", vm_cnt.v_laundry_count);
 3869         db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
 3870         db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
 3871         db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
 3872         db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
 3873         db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
 3874 }
 3875 
 3876 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
 3877 {
 3878         int dom;
 3879 
 3880         db_printf("pq_free %d\n", vm_cnt.v_free_count);
 3881         for (dom = 0; dom < vm_ndomains; dom++) {
 3882                 db_printf(
 3883             "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d\n",
 3884                     dom,
 3885                     vm_dom[dom].vmd_page_count,
 3886                     vm_dom[dom].vmd_free_count,
 3887                     vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
 3888                     vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
 3889                     vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt);
 3890         }
 3891 }
 3892 
 3893 DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
 3894 {
 3895         vm_page_t m;
 3896         boolean_t phys, virt;
 3897 
 3898         if (!have_addr) {
 3899                 db_printf("show pginfo addr\n");
 3900                 return;
 3901         }
 3902 
 3903         phys = strchr(modif, 'p') != NULL;
 3904         virt = strchr(modif, 'v') != NULL;
 3905         if (virt)
 3906                 m = PHYS_TO_VM_PAGE(pmap_kextract(addr));
 3907         else if (phys)
 3908                 m = PHYS_TO_VM_PAGE(addr);
 3909         else
 3910                 m = (vm_page_t)addr;
 3911         db_printf(
 3912     "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
 3913     "  af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
 3914             m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
 3915             m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
 3916             m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);
 3917 }
 3918 #endif /* DDB */

Cache object: 7f4d5ccc2b2cd6ba88f90b088c7e8238


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