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_map.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, 1993
    3  *      The Regents of the University of California.  All rights reserved.
    4  *
    5  * This code is derived from software contributed to Berkeley by
    6  * The Mach Operating System project at Carnegie-Mellon University.
    7  *
    8  * Redistribution and use in source and binary forms, with or without
    9  * modification, are permitted provided that the following conditions
   10  * are met:
   11  * 1. Redistributions of source code must retain the above copyright
   12  *    notice, this list of conditions and the following disclaimer.
   13  * 2. Redistributions in binary form must reproduce the above copyright
   14  *    notice, this list of conditions and the following disclaimer in the
   15  *    documentation and/or other materials provided with the distribution.
   16  * 4. Neither the name of the University nor the names of its contributors
   17  *    may be used to endorse or promote products derived from this software
   18  *    without specific prior written permission.
   19  *
   20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   30  * SUCH DAMAGE.
   31  *
   32  *      from: @(#)vm_map.c      8.3 (Berkeley) 1/12/94
   33  *
   34  *
   35  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
   36  * All rights reserved.
   37  *
   38  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
   39  *
   40  * Permission to use, copy, modify and distribute this software and
   41  * its documentation is hereby granted, provided that both the copyright
   42  * notice and this permission notice appear in all copies of the
   43  * software, derivative works or modified versions, and any portions
   44  * thereof, and that both notices appear in supporting documentation.
   45  *
   46  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
   47  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
   48  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
   49  *
   50  * Carnegie Mellon requests users of this software to return to
   51  *
   52  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
   53  *  School of Computer Science
   54  *  Carnegie Mellon University
   55  *  Pittsburgh PA 15213-3890
   56  *
   57  * any improvements or extensions that they make and grant Carnegie the
   58  * rights to redistribute these changes.
   59  */
   60 
   61 /*
   62  *      Virtual memory mapping module.
   63  */
   64 
   65 #include <sys/cdefs.h>
   66 __FBSDID("$FreeBSD$");
   67 
   68 #include <sys/param.h>
   69 #include <sys/systm.h>
   70 #include <sys/kernel.h>
   71 #include <sys/ktr.h>
   72 #include <sys/lock.h>
   73 #include <sys/mutex.h>
   74 #include <sys/proc.h>
   75 #include <sys/vmmeter.h>
   76 #include <sys/mman.h>
   77 #include <sys/vnode.h>
   78 #include <sys/resourcevar.h>
   79 #include <sys/file.h>
   80 #include <sys/sysctl.h>
   81 #include <sys/sysent.h>
   82 #include <sys/shm.h>
   83 
   84 #include <vm/vm.h>
   85 #include <vm/vm_param.h>
   86 #include <vm/pmap.h>
   87 #include <vm/vm_map.h>
   88 #include <vm/vm_page.h>
   89 #include <vm/vm_object.h>
   90 #include <vm/vm_pager.h>
   91 #include <vm/vm_kern.h>
   92 #include <vm/vm_extern.h>
   93 #include <vm/swap_pager.h>
   94 #include <vm/uma.h>
   95 
   96 /*
   97  *      Virtual memory maps provide for the mapping, protection,
   98  *      and sharing of virtual memory objects.  In addition,
   99  *      this module provides for an efficient virtual copy of
  100  *      memory from one map to another.
  101  *
  102  *      Synchronization is required prior to most operations.
  103  *
  104  *      Maps consist of an ordered doubly-linked list of simple
  105  *      entries; a self-adjusting binary search tree of these
  106  *      entries is used to speed up lookups.
  107  *
  108  *      Since portions of maps are specified by start/end addresses,
  109  *      which may not align with existing map entries, all
  110  *      routines merely "clip" entries to these start/end values.
  111  *      [That is, an entry is split into two, bordering at a
  112  *      start or end value.]  Note that these clippings may not
  113  *      always be necessary (as the two resulting entries are then
  114  *      not changed); however, the clipping is done for convenience.
  115  *
  116  *      As mentioned above, virtual copy operations are performed
  117  *      by copying VM object references from one map to
  118  *      another, and then marking both regions as copy-on-write.
  119  */
  120 
  121 static struct mtx map_sleep_mtx;
  122 static uma_zone_t mapentzone;
  123 static uma_zone_t kmapentzone;
  124 static uma_zone_t mapzone;
  125 static uma_zone_t vmspace_zone;
  126 static struct vm_object kmapentobj;
  127 static int vmspace_zinit(void *mem, int size, int flags);
  128 static void vmspace_zfini(void *mem, int size);
  129 static int vm_map_zinit(void *mem, int ize, int flags);
  130 static void vm_map_zfini(void *mem, int size);
  131 static void _vm_map_init(vm_map_t map, vm_offset_t min, vm_offset_t max);
  132 static void vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map);
  133 static void vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry);
  134 #ifdef INVARIANTS
  135 static void vm_map_zdtor(void *mem, int size, void *arg);
  136 static void vmspace_zdtor(void *mem, int size, void *arg);
  137 #endif
  138 
  139 #define ENTRY_CHARGED(e) ((e)->uip != NULL || \
  140     ((e)->object.vm_object != NULL && (e)->object.vm_object->uip != NULL && \
  141      !((e)->eflags & MAP_ENTRY_NEEDS_COPY)))
  142 
  143 /* 
  144  * PROC_VMSPACE_{UN,}LOCK() can be a noop as long as vmspaces are type
  145  * stable.
  146  */
  147 #define PROC_VMSPACE_LOCK(p) do { } while (0)
  148 #define PROC_VMSPACE_UNLOCK(p) do { } while (0)
  149 
  150 /*
  151  *      VM_MAP_RANGE_CHECK:     [ internal use only ]
  152  *
  153  *      Asserts that the starting and ending region
  154  *      addresses fall within the valid range of the map.
  155  */
  156 #define VM_MAP_RANGE_CHECK(map, start, end)             \
  157                 {                                       \
  158                 if (start < vm_map_min(map))            \
  159                         start = vm_map_min(map);        \
  160                 if (end > vm_map_max(map))              \
  161                         end = vm_map_max(map);          \
  162                 if (start > end)                        \
  163                         start = end;                    \
  164                 }
  165 
  166 /*
  167  *      vm_map_startup:
  168  *
  169  *      Initialize the vm_map module.  Must be called before
  170  *      any other vm_map routines.
  171  *
  172  *      Map and entry structures are allocated from the general
  173  *      purpose memory pool with some exceptions:
  174  *
  175  *      - The kernel map and kmem submap are allocated statically.
  176  *      - Kernel map entries are allocated out of a static pool.
  177  *
  178  *      These restrictions are necessary since malloc() uses the
  179  *      maps and requires map entries.
  180  */
  181 
  182 void
  183 vm_map_startup(void)
  184 {
  185         mtx_init(&map_sleep_mtx, "vm map sleep mutex", NULL, MTX_DEF);
  186         mapzone = uma_zcreate("MAP", sizeof(struct vm_map), NULL,
  187 #ifdef INVARIANTS
  188             vm_map_zdtor,
  189 #else
  190             NULL,
  191 #endif
  192             vm_map_zinit, vm_map_zfini, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
  193         uma_prealloc(mapzone, MAX_KMAP);
  194         kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry),
  195             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
  196             UMA_ZONE_MTXCLASS | UMA_ZONE_VM);
  197         uma_prealloc(kmapentzone, MAX_KMAPENT);
  198         mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry),
  199             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
  200 }
  201 
  202 static void
  203 vmspace_zfini(void *mem, int size)
  204 {
  205         struct vmspace *vm;
  206 
  207         vm = (struct vmspace *)mem;
  208         vm_map_zfini(&vm->vm_map, sizeof(vm->vm_map));
  209 }
  210 
  211 static int
  212 vmspace_zinit(void *mem, int size, int flags)
  213 {
  214         struct vmspace *vm;
  215 
  216         vm = (struct vmspace *)mem;
  217 
  218         vm->vm_map.pmap = NULL;
  219         (void)vm_map_zinit(&vm->vm_map, sizeof(vm->vm_map), flags);
  220         return (0);
  221 }
  222 
  223 static void
  224 vm_map_zfini(void *mem, int size)
  225 {
  226         vm_map_t map;
  227 
  228         map = (vm_map_t)mem;
  229         mtx_destroy(&map->system_mtx);
  230         sx_destroy(&map->lock);
  231 }
  232 
  233 static int
  234 vm_map_zinit(void *mem, int size, int flags)
  235 {
  236         vm_map_t map;
  237 
  238         map = (vm_map_t)mem;
  239         map->nentries = 0;
  240         map->size = 0;
  241         mtx_init(&map->system_mtx, "system map", NULL, MTX_DEF | MTX_DUPOK);
  242         sx_init(&map->lock, "user map");
  243         return (0);
  244 }
  245 
  246 #ifdef INVARIANTS
  247 static void
  248 vmspace_zdtor(void *mem, int size, void *arg)
  249 {
  250         struct vmspace *vm;
  251 
  252         vm = (struct vmspace *)mem;
  253 
  254         vm_map_zdtor(&vm->vm_map, sizeof(vm->vm_map), arg);
  255 }
  256 static void
  257 vm_map_zdtor(void *mem, int size, void *arg)
  258 {
  259         vm_map_t map;
  260 
  261         map = (vm_map_t)mem;
  262         KASSERT(map->nentries == 0,
  263             ("map %p nentries == %d on free.",
  264             map, map->nentries));
  265         KASSERT(map->size == 0,
  266             ("map %p size == %lu on free.",
  267             map, (unsigned long)map->size));
  268 }
  269 #endif  /* INVARIANTS */
  270 
  271 /*
  272  * Allocate a vmspace structure, including a vm_map and pmap,
  273  * and initialize those structures.  The refcnt is set to 1.
  274  */
  275 struct vmspace *
  276 vmspace_alloc(min, max)
  277         vm_offset_t min, max;
  278 {
  279         struct vmspace *vm;
  280 
  281         vm = uma_zalloc(vmspace_zone, M_WAITOK);
  282         if (vm->vm_map.pmap == NULL && !pmap_pinit(vmspace_pmap(vm))) {
  283                 uma_zfree(vmspace_zone, vm);
  284                 return (NULL);
  285         }
  286         CTR1(KTR_VM, "vmspace_alloc: %p", vm);
  287         _vm_map_init(&vm->vm_map, min, max);
  288         vm->vm_map.pmap = vmspace_pmap(vm);             /* XXX */
  289         vm->vm_refcnt = 1;
  290         vm->vm_shm = NULL;
  291         vm->vm_swrss = 0;
  292         vm->vm_tsize = 0;
  293         vm->vm_dsize = 0;
  294         vm->vm_ssize = 0;
  295         vm->vm_taddr = 0;
  296         vm->vm_daddr = 0;
  297         vm->vm_maxsaddr = 0;
  298         return (vm);
  299 }
  300 
  301 void
  302 vm_init2(void)
  303 {
  304         uma_zone_set_obj(kmapentzone, &kmapentobj, lmin(cnt.v_page_count,
  305             (VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS) / PAGE_SIZE) / 8 +
  306              maxproc * 2 + maxfiles);
  307         vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
  308 #ifdef INVARIANTS
  309             vmspace_zdtor,
  310 #else
  311             NULL,
  312 #endif
  313             vmspace_zinit, vmspace_zfini, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
  314 }
  315 
  316 static inline void
  317 vmspace_dofree(struct vmspace *vm)
  318 {
  319 
  320         CTR1(KTR_VM, "vmspace_free: %p", vm);
  321 
  322         /*
  323          * Make sure any SysV shm is freed, it might not have been in
  324          * exit1().
  325          */
  326         shmexit(vm);
  327 
  328         /*
  329          * Lock the map, to wait out all other references to it.
  330          * Delete all of the mappings and pages they hold, then call
  331          * the pmap module to reclaim anything left.
  332          */
  333         (void)vm_map_remove(&vm->vm_map, vm->vm_map.min_offset,
  334             vm->vm_map.max_offset);
  335 
  336         pmap_release(vmspace_pmap(vm));
  337         vm->vm_map.pmap = NULL;
  338         uma_zfree(vmspace_zone, vm);
  339 }
  340 
  341 void
  342 vmspace_free(struct vmspace *vm)
  343 {
  344 
  345         if (vm->vm_refcnt == 0)
  346                 panic("vmspace_free: attempt to free already freed vmspace");
  347 
  348         if (atomic_fetchadd_int(&vm->vm_refcnt, -1) == 1)
  349                 vmspace_dofree(vm);
  350 }
  351 
  352 void
  353 vmspace_exitfree(struct proc *p)
  354 {
  355         struct vmspace *vm;
  356 
  357         PROC_VMSPACE_LOCK(p);
  358         vm = p->p_vmspace;
  359         p->p_vmspace = NULL;
  360         PROC_VMSPACE_UNLOCK(p);
  361         KASSERT(vm == &vmspace0, ("vmspace_exitfree: wrong vmspace"));
  362         vmspace_free(vm);
  363 }
  364 
  365 void
  366 vmspace_exit(struct thread *td)
  367 {
  368         int refcnt;
  369         struct vmspace *vm;
  370         struct proc *p;
  371 
  372         /*
  373          * Release user portion of address space.
  374          * This releases references to vnodes,
  375          * which could cause I/O if the file has been unlinked.
  376          * Need to do this early enough that we can still sleep.
  377          *
  378          * The last exiting process to reach this point releases as
  379          * much of the environment as it can. vmspace_dofree() is the
  380          * slower fallback in case another process had a temporary
  381          * reference to the vmspace.
  382          */
  383 
  384         p = td->td_proc;
  385         vm = p->p_vmspace;
  386         atomic_add_int(&vmspace0.vm_refcnt, 1);
  387         do {
  388                 refcnt = vm->vm_refcnt;
  389                 if (refcnt > 1 && p->p_vmspace != &vmspace0) {
  390                         /* Switch now since other proc might free vmspace */
  391                         PROC_VMSPACE_LOCK(p);
  392                         p->p_vmspace = &vmspace0;
  393                         PROC_VMSPACE_UNLOCK(p);
  394                         pmap_activate(td);
  395                 }
  396         } while (!atomic_cmpset_int(&vm->vm_refcnt, refcnt, refcnt - 1));
  397         if (refcnt == 1) {
  398                 if (p->p_vmspace != vm) {
  399                         /* vmspace not yet freed, switch back */
  400                         PROC_VMSPACE_LOCK(p);
  401                         p->p_vmspace = vm;
  402                         PROC_VMSPACE_UNLOCK(p);
  403                         pmap_activate(td);
  404                 }
  405                 pmap_remove_pages(vmspace_pmap(vm));
  406                 /* Switch now since this proc will free vmspace */
  407                 PROC_VMSPACE_LOCK(p);
  408                 p->p_vmspace = &vmspace0;
  409                 PROC_VMSPACE_UNLOCK(p);
  410                 pmap_activate(td);
  411                 vmspace_dofree(vm);
  412         }
  413 }
  414 
  415 /* Acquire reference to vmspace owned by another process. */
  416 
  417 struct vmspace *
  418 vmspace_acquire_ref(struct proc *p)
  419 {
  420         struct vmspace *vm;
  421         int refcnt;
  422 
  423         PROC_VMSPACE_LOCK(p);
  424         vm = p->p_vmspace;
  425         if (vm == NULL) {
  426                 PROC_VMSPACE_UNLOCK(p);
  427                 return (NULL);
  428         }
  429         do {
  430                 refcnt = vm->vm_refcnt;
  431                 if (refcnt <= 0) {      /* Avoid 0->1 transition */
  432                         PROC_VMSPACE_UNLOCK(p);
  433                         return (NULL);
  434                 }
  435         } while (!atomic_cmpset_int(&vm->vm_refcnt, refcnt, refcnt + 1));
  436         if (vm != p->p_vmspace) {
  437                 PROC_VMSPACE_UNLOCK(p);
  438                 vmspace_free(vm);
  439                 return (NULL);
  440         }
  441         PROC_VMSPACE_UNLOCK(p);
  442         return (vm);
  443 }
  444 
  445 void
  446 _vm_map_lock(vm_map_t map, const char *file, int line)
  447 {
  448 
  449         if (map->system_map)
  450                 _mtx_lock_flags(&map->system_mtx, 0, file, line);
  451         else
  452                 (void)_sx_xlock(&map->lock, 0, file, line);
  453         map->timestamp++;
  454 }
  455 
  456 static void
  457 vm_map_process_deferred(void)
  458 {
  459         struct thread *td;
  460         vm_map_entry_t entry, next;
  461 
  462         td = curthread;
  463         entry = td->td_map_def_user;
  464         td->td_map_def_user = NULL;
  465         while (entry != NULL) {
  466                 next = entry->next;
  467                 vm_map_entry_deallocate(entry, FALSE);
  468                 entry = next;
  469         }
  470 }
  471 
  472 void
  473 _vm_map_unlock(vm_map_t map, const char *file, int line)
  474 {
  475 
  476         if (map->system_map)
  477                 _mtx_unlock_flags(&map->system_mtx, 0, file, line);
  478         else {
  479                 _sx_xunlock(&map->lock, file, line);
  480                 vm_map_process_deferred();
  481         }
  482 }
  483 
  484 void
  485 _vm_map_lock_read(vm_map_t map, const char *file, int line)
  486 {
  487 
  488         if (map->system_map)
  489                 _mtx_lock_flags(&map->system_mtx, 0, file, line);
  490         else
  491                 (void)_sx_slock(&map->lock, 0, file, line);
  492 }
  493 
  494 void
  495 _vm_map_unlock_read(vm_map_t map, const char *file, int line)
  496 {
  497 
  498         if (map->system_map)
  499                 _mtx_unlock_flags(&map->system_mtx, 0, file, line);
  500         else {
  501                 _sx_sunlock(&map->lock, file, line);
  502                 vm_map_process_deferred();
  503         }
  504 }
  505 
  506 int
  507 _vm_map_trylock(vm_map_t map, const char *file, int line)
  508 {
  509         int error;
  510 
  511         error = map->system_map ?
  512             !_mtx_trylock(&map->system_mtx, 0, file, line) :
  513             !_sx_try_xlock(&map->lock, file, line);
  514         if (error == 0)
  515                 map->timestamp++;
  516         return (error == 0);
  517 }
  518 
  519 int
  520 _vm_map_trylock_read(vm_map_t map, const char *file, int line)
  521 {
  522         int error;
  523 
  524         error = map->system_map ?
  525             !_mtx_trylock(&map->system_mtx, 0, file, line) :
  526             !_sx_try_slock(&map->lock, file, line);
  527         return (error == 0);
  528 }
  529 
  530 /*
  531  *      _vm_map_lock_upgrade:   [ internal use only ]
  532  *
  533  *      Tries to upgrade a read (shared) lock on the specified map to a write
  534  *      (exclusive) lock.  Returns the value "" if the upgrade succeeds and a
  535  *      non-zero value if the upgrade fails.  If the upgrade fails, the map is
  536  *      returned without a read or write lock held.
  537  *
  538  *      Requires that the map be read locked.
  539  */
  540 int
  541 _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
  542 {
  543         unsigned int last_timestamp;
  544 
  545         if (map->system_map) {
  546 #ifdef INVARIANTS
  547                 _mtx_assert(&map->system_mtx, MA_OWNED, file, line);
  548 #endif
  549         } else {
  550                 if (!_sx_try_upgrade(&map->lock, file, line)) {
  551                         last_timestamp = map->timestamp;
  552                         _sx_sunlock(&map->lock, file, line);
  553                         vm_map_process_deferred();
  554                         /*
  555                          * If the map's timestamp does not change while the
  556                          * map is unlocked, then the upgrade succeeds.
  557                          */
  558                         (void)_sx_xlock(&map->lock, 0, file, line);
  559                         if (last_timestamp != map->timestamp) {
  560                                 _sx_xunlock(&map->lock, file, line);
  561                                 return (1);
  562                         }
  563                 }
  564         }
  565         map->timestamp++;
  566         return (0);
  567 }
  568 
  569 void
  570 _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
  571 {
  572 
  573         if (map->system_map) {
  574 #ifdef INVARIANTS
  575                 _mtx_assert(&map->system_mtx, MA_OWNED, file, line);
  576 #endif
  577         } else
  578                 _sx_downgrade(&map->lock, file, line);
  579 }
  580 
  581 /*
  582  *      vm_map_locked:
  583  *
  584  *      Returns a non-zero value if the caller holds a write (exclusive) lock
  585  *      on the specified map and the value "" otherwise.
  586  */
  587 int
  588 vm_map_locked(vm_map_t map)
  589 {
  590 
  591         if (map->system_map)
  592                 return (mtx_owned(&map->system_mtx));
  593         else
  594                 return (sx_xlocked(&map->lock));
  595 }
  596 
  597 #ifdef INVARIANTS
  598 static void
  599 _vm_map_assert_locked(vm_map_t map, const char *file, int line)
  600 {
  601 
  602         if (map->system_map)
  603                 _mtx_assert(&map->system_mtx, MA_OWNED, file, line);
  604         else
  605                 _sx_assert(&map->lock, SA_XLOCKED, file, line);
  606 }
  607 
  608 #if 0
  609 static void
  610 _vm_map_assert_locked_read(vm_map_t map, const char *file, int line)
  611 {
  612 
  613         if (map->system_map)
  614                 _mtx_assert(&map->system_mtx, MA_OWNED, file, line);
  615         else
  616                 _sx_assert(&map->lock, SA_SLOCKED, file, line);
  617 }
  618 #endif
  619 
  620 #define VM_MAP_ASSERT_LOCKED(map) \
  621     _vm_map_assert_locked(map, LOCK_FILE, LOCK_LINE)
  622 #define VM_MAP_ASSERT_LOCKED_READ(map) \
  623     _vm_map_assert_locked_read(map, LOCK_FILE, LOCK_LINE)
  624 #else
  625 #define VM_MAP_ASSERT_LOCKED(map)
  626 #define VM_MAP_ASSERT_LOCKED_READ(map)
  627 #endif
  628 
  629 /*
  630  *      _vm_map_unlock_and_wait:
  631  *
  632  *      Atomically releases the lock on the specified map and puts the calling
  633  *      thread to sleep.  The calling thread will remain asleep until either
  634  *      vm_map_wakeup() is performed on the map or the specified timeout is
  635  *      exceeded.
  636  *
  637  *      WARNING!  This function does not perform deferred deallocations of
  638  *      objects and map entries.  Therefore, the calling thread is expected to
  639  *      reacquire the map lock after reawakening and later perform an ordinary
  640  *      unlock operation, such as vm_map_unlock(), before completing its
  641  *      operation on the map.
  642  */
  643 int
  644 _vm_map_unlock_and_wait(vm_map_t map, int timo, const char *file, int line)
  645 {
  646 
  647         mtx_lock(&map_sleep_mtx);
  648         if (map->system_map)
  649                 _mtx_unlock_flags(&map->system_mtx, 0, file, line);
  650         else
  651                 _sx_xunlock(&map->lock, file, line);
  652         return (msleep(&map->root, &map_sleep_mtx, PDROP | PVM, "vmmaps",
  653             timo));
  654 }
  655 
  656 /*
  657  *      vm_map_wakeup:
  658  *
  659  *      Awaken any threads that have slept on the map using
  660  *      vm_map_unlock_and_wait().
  661  */
  662 void
  663 vm_map_wakeup(vm_map_t map)
  664 {
  665 
  666         /*
  667          * Acquire and release map_sleep_mtx to prevent a wakeup()
  668          * from being performed (and lost) between the map unlock
  669          * and the msleep() in _vm_map_unlock_and_wait().
  670          */
  671         mtx_lock(&map_sleep_mtx);
  672         mtx_unlock(&map_sleep_mtx);
  673         wakeup(&map->root);
  674 }
  675 
  676 void
  677 vm_map_busy(vm_map_t map)
  678 {
  679 
  680         VM_MAP_ASSERT_LOCKED(map);
  681         map->busy++;
  682 }
  683 
  684 void
  685 vm_map_unbusy(vm_map_t map)
  686 {
  687 
  688         VM_MAP_ASSERT_LOCKED(map);
  689         KASSERT(map->busy, ("vm_map_unbusy: not busy"));
  690         if (--map->busy == 0 && (map->flags & MAP_BUSY_WAKEUP)) {
  691                 vm_map_modflags(map, 0, MAP_BUSY_WAKEUP);
  692                 wakeup(&map->busy);
  693         }
  694 }
  695 
  696 void 
  697 vm_map_wait_busy(vm_map_t map)
  698 {
  699 
  700         VM_MAP_ASSERT_LOCKED(map);
  701         while (map->busy) {
  702                 vm_map_modflags(map, MAP_BUSY_WAKEUP, 0);
  703                 if (map->system_map)
  704                         msleep(&map->busy, &map->system_mtx, 0, "mbusy", 0);
  705                 else
  706                         sx_sleep(&map->busy, &map->lock, 0, "mbusy", 0);
  707         }
  708         map->timestamp++;
  709 }
  710 
  711 long
  712 vmspace_resident_count(struct vmspace *vmspace)
  713 {
  714         return pmap_resident_count(vmspace_pmap(vmspace));
  715 }
  716 
  717 long
  718 vmspace_wired_count(struct vmspace *vmspace)
  719 {
  720         return pmap_wired_count(vmspace_pmap(vmspace));
  721 }
  722 
  723 /*
  724  *      vm_map_create:
  725  *
  726  *      Creates and returns a new empty VM map with
  727  *      the given physical map structure, and having
  728  *      the given lower and upper address bounds.
  729  */
  730 vm_map_t
  731 vm_map_create(pmap_t pmap, vm_offset_t min, vm_offset_t max)
  732 {
  733         vm_map_t result;
  734 
  735         result = uma_zalloc(mapzone, M_WAITOK);
  736         CTR1(KTR_VM, "vm_map_create: %p", result);
  737         _vm_map_init(result, min, max);
  738         result->pmap = pmap;
  739         return (result);
  740 }
  741 
  742 /*
  743  * Initialize an existing vm_map structure
  744  * such as that in the vmspace structure.
  745  * The pmap is set elsewhere.
  746  */
  747 static void
  748 _vm_map_init(vm_map_t map, vm_offset_t min, vm_offset_t max)
  749 {
  750 
  751         map->header.next = map->header.prev = &map->header;
  752         map->needs_wakeup = FALSE;
  753         map->system_map = 0;
  754         map->min_offset = min;
  755         map->max_offset = max;
  756         map->flags = 0;
  757         map->root = NULL;
  758         map->timestamp = 0;
  759         map->busy = 0;
  760 }
  761 
  762 void
  763 vm_map_init(vm_map_t map, vm_offset_t min, vm_offset_t max)
  764 {
  765         _vm_map_init(map, min, max);
  766         mtx_init(&map->system_mtx, "system map", NULL, MTX_DEF | MTX_DUPOK);
  767         sx_init(&map->lock, "user map");
  768 }
  769 
  770 /*
  771  *      vm_map_entry_dispose:   [ internal use only ]
  772  *
  773  *      Inverse of vm_map_entry_create.
  774  */
  775 static void
  776 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
  777 {
  778         uma_zfree(map->system_map ? kmapentzone : mapentzone, entry);
  779 }
  780 
  781 /*
  782  *      vm_map_entry_create:    [ internal use only ]
  783  *
  784  *      Allocates a VM map entry for insertion.
  785  *      No entry fields are filled in.
  786  */
  787 static vm_map_entry_t
  788 vm_map_entry_create(vm_map_t map)
  789 {
  790         vm_map_entry_t new_entry;
  791 
  792         if (map->system_map)
  793                 new_entry = uma_zalloc(kmapentzone, M_NOWAIT);
  794         else
  795                 new_entry = uma_zalloc(mapentzone, M_WAITOK);
  796         if (new_entry == NULL)
  797                 panic("vm_map_entry_create: kernel resources exhausted");
  798         return (new_entry);
  799 }
  800 
  801 /*
  802  *      vm_map_entry_set_behavior:
  803  *
  804  *      Set the expected access behavior, either normal, random, or
  805  *      sequential.
  806  */
  807 static inline void
  808 vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
  809 {
  810         entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
  811             (behavior & MAP_ENTRY_BEHAV_MASK);
  812 }
  813 
  814 /*
  815  *      vm_map_entry_set_max_free:
  816  *
  817  *      Set the max_free field in a vm_map_entry.
  818  */
  819 static inline void
  820 vm_map_entry_set_max_free(vm_map_entry_t entry)
  821 {
  822 
  823         entry->max_free = entry->adj_free;
  824         if (entry->left != NULL && entry->left->max_free > entry->max_free)
  825                 entry->max_free = entry->left->max_free;
  826         if (entry->right != NULL && entry->right->max_free > entry->max_free)
  827                 entry->max_free = entry->right->max_free;
  828 }
  829 
  830 /*
  831  *      vm_map_entry_splay:
  832  *
  833  *      The Sleator and Tarjan top-down splay algorithm with the
  834  *      following variation.  Max_free must be computed bottom-up, so
  835  *      on the downward pass, maintain the left and right spines in
  836  *      reverse order.  Then, make a second pass up each side to fix
  837  *      the pointers and compute max_free.  The time bound is O(log n)
  838  *      amortized.
  839  *
  840  *      The new root is the vm_map_entry containing "addr", or else an
  841  *      adjacent entry (lower or higher) if addr is not in the tree.
  842  *
  843  *      The map must be locked, and leaves it so.
  844  *
  845  *      Returns: the new root.
  846  */
  847 static vm_map_entry_t
  848 vm_map_entry_splay(vm_offset_t addr, vm_map_entry_t root)
  849 {
  850         vm_map_entry_t llist, rlist;
  851         vm_map_entry_t ltree, rtree;
  852         vm_map_entry_t y;
  853 
  854         /* Special case of empty tree. */
  855         if (root == NULL)
  856                 return (root);
  857 
  858         /*
  859          * Pass One: Splay down the tree until we find addr or a NULL
  860          * pointer where addr would go.  llist and rlist are the two
  861          * sides in reverse order (bottom-up), with llist linked by
  862          * the right pointer and rlist linked by the left pointer in
  863          * the vm_map_entry.  Wait until Pass Two to set max_free on
  864          * the two spines.
  865          */
  866         llist = NULL;
  867         rlist = NULL;
  868         for (;;) {
  869                 /* root is never NULL in here. */
  870                 if (addr < root->start) {
  871                         y = root->left;
  872                         if (y == NULL)
  873                                 break;
  874                         if (addr < y->start && y->left != NULL) {
  875                                 /* Rotate right and put y on rlist. */
  876                                 root->left = y->right;
  877                                 y->right = root;
  878                                 vm_map_entry_set_max_free(root);
  879                                 root = y->left;
  880                                 y->left = rlist;
  881                                 rlist = y;
  882                         } else {
  883                                 /* Put root on rlist. */
  884                                 root->left = rlist;
  885                                 rlist = root;
  886                                 root = y;
  887                         }
  888                 } else if (addr >= root->end) {
  889                         y = root->right;
  890                         if (y == NULL)
  891                                 break;
  892                         if (addr >= y->end && y->right != NULL) {
  893                                 /* Rotate left and put y on llist. */
  894                                 root->right = y->left;
  895                                 y->left = root;
  896                                 vm_map_entry_set_max_free(root);
  897                                 root = y->right;
  898                                 y->right = llist;
  899                                 llist = y;
  900                         } else {
  901                                 /* Put root on llist. */
  902                                 root->right = llist;
  903                                 llist = root;
  904                                 root = y;
  905                         }
  906                 } else
  907                         break;
  908         }
  909 
  910         /*
  911          * Pass Two: Walk back up the two spines, flip the pointers
  912          * and set max_free.  The subtrees of the root go at the
  913          * bottom of llist and rlist.
  914          */
  915         ltree = root->left;
  916         while (llist != NULL) {
  917                 y = llist->right;
  918                 llist->right = ltree;
  919                 vm_map_entry_set_max_free(llist);
  920                 ltree = llist;
  921                 llist = y;
  922         }
  923         rtree = root->right;
  924         while (rlist != NULL) {
  925                 y = rlist->left;
  926                 rlist->left = rtree;
  927                 vm_map_entry_set_max_free(rlist);
  928                 rtree = rlist;
  929                 rlist = y;
  930         }
  931 
  932         /*
  933          * Final assembly: add ltree and rtree as subtrees of root.
  934          */
  935         root->left = ltree;
  936         root->right = rtree;
  937         vm_map_entry_set_max_free(root);
  938 
  939         return (root);
  940 }
  941 
  942 /*
  943  *      vm_map_entry_{un,}link:
  944  *
  945  *      Insert/remove entries from maps.
  946  */
  947 static void
  948 vm_map_entry_link(vm_map_t map,
  949                   vm_map_entry_t after_where,
  950                   vm_map_entry_t entry)
  951 {
  952 
  953         CTR4(KTR_VM,
  954             "vm_map_entry_link: map %p, nentries %d, entry %p, after %p", map,
  955             map->nentries, entry, after_where);
  956         VM_MAP_ASSERT_LOCKED(map);
  957         map->nentries++;
  958         entry->prev = after_where;
  959         entry->next = after_where->next;
  960         entry->next->prev = entry;
  961         after_where->next = entry;
  962 
  963         if (after_where != &map->header) {
  964                 if (after_where != map->root)
  965                         vm_map_entry_splay(after_where->start, map->root);
  966                 entry->right = after_where->right;
  967                 entry->left = after_where;
  968                 after_where->right = NULL;
  969                 after_where->adj_free = entry->start - after_where->end;
  970                 vm_map_entry_set_max_free(after_where);
  971         } else {
  972                 entry->right = map->root;
  973                 entry->left = NULL;
  974         }
  975         entry->adj_free = (entry->next == &map->header ? map->max_offset :
  976             entry->next->start) - entry->end;
  977         vm_map_entry_set_max_free(entry);
  978         map->root = entry;
  979 }
  980 
  981 static void
  982 vm_map_entry_unlink(vm_map_t map,
  983                     vm_map_entry_t entry)
  984 {
  985         vm_map_entry_t next, prev, root;
  986 
  987         VM_MAP_ASSERT_LOCKED(map);
  988         if (entry != map->root)
  989                 vm_map_entry_splay(entry->start, map->root);
  990         if (entry->left == NULL)
  991                 root = entry->right;
  992         else {
  993                 root = vm_map_entry_splay(entry->start, entry->left);
  994                 root->right = entry->right;
  995                 root->adj_free = (entry->next == &map->header ? map->max_offset :
  996                     entry->next->start) - root->end;
  997                 vm_map_entry_set_max_free(root);
  998         }
  999         map->root = root;
 1000 
 1001         prev = entry->prev;
 1002         next = entry->next;
 1003         next->prev = prev;
 1004         prev->next = next;
 1005         map->nentries--;
 1006         CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
 1007             map->nentries, entry);
 1008 }
 1009 
 1010 /*
 1011  *      vm_map_entry_resize_free:
 1012  *
 1013  *      Recompute the amount of free space following a vm_map_entry
 1014  *      and propagate that value up the tree.  Call this function after
 1015  *      resizing a map entry in-place, that is, without a call to
 1016  *      vm_map_entry_link() or _unlink().
 1017  *
 1018  *      The map must be locked, and leaves it so.
 1019  */
 1020 static void
 1021 vm_map_entry_resize_free(vm_map_t map, vm_map_entry_t entry)
 1022 {
 1023 
 1024         /*
 1025          * Using splay trees without parent pointers, propagating
 1026          * max_free up the tree is done by moving the entry to the
 1027          * root and making the change there.
 1028          */
 1029         if (entry != map->root)
 1030                 map->root = vm_map_entry_splay(entry->start, map->root);
 1031 
 1032         entry->adj_free = (entry->next == &map->header ? map->max_offset :
 1033             entry->next->start) - entry->end;
 1034         vm_map_entry_set_max_free(entry);
 1035 }
 1036 
 1037 /*
 1038  *      vm_map_lookup_entry:    [ internal use only ]
 1039  *
 1040  *      Finds the map entry containing (or
 1041  *      immediately preceding) the specified address
 1042  *      in the given map; the entry is returned
 1043  *      in the "entry" parameter.  The boolean
 1044  *      result indicates whether the address is
 1045  *      actually contained in the map.
 1046  */
 1047 boolean_t
 1048 vm_map_lookup_entry(
 1049         vm_map_t map,
 1050         vm_offset_t address,
 1051         vm_map_entry_t *entry)  /* OUT */
 1052 {
 1053         vm_map_entry_t cur;
 1054         boolean_t locked;
 1055 
 1056         /*
 1057          * If the map is empty, then the map entry immediately preceding
 1058          * "address" is the map's header.
 1059          */
 1060         cur = map->root;
 1061         if (cur == NULL)
 1062                 *entry = &map->header;
 1063         else if (address >= cur->start && cur->end > address) {
 1064                 *entry = cur;
 1065                 return (TRUE);
 1066         } else if ((locked = vm_map_locked(map)) ||
 1067             sx_try_upgrade(&map->lock)) {
 1068                 /*
 1069                  * Splay requires a write lock on the map.  However, it only
 1070                  * restructures the binary search tree; it does not otherwise
 1071                  * change the map.  Thus, the map's timestamp need not change
 1072                  * on a temporary upgrade.
 1073                  */
 1074                 map->root = cur = vm_map_entry_splay(address, cur);
 1075                 if (!locked)
 1076                         sx_downgrade(&map->lock);
 1077 
 1078                 /*
 1079                  * If "address" is contained within a map entry, the new root
 1080                  * is that map entry.  Otherwise, the new root is a map entry
 1081                  * immediately before or after "address".
 1082                  */
 1083                 if (address >= cur->start) {
 1084                         *entry = cur;
 1085                         if (cur->end > address)
 1086                                 return (TRUE);
 1087                 } else
 1088                         *entry = cur->prev;
 1089         } else
 1090                 /*
 1091                  * Since the map is only locked for read access, perform a
 1092                  * standard binary search tree lookup for "address".
 1093                  */
 1094                 for (;;) {
 1095                         if (address < cur->start) {
 1096                                 if (cur->left == NULL) {
 1097                                         *entry = cur->prev;
 1098                                         break;
 1099                                 }
 1100                                 cur = cur->left;
 1101                         } else if (cur->end > address) {
 1102                                 *entry = cur;
 1103                                 return (TRUE);
 1104                         } else {
 1105                                 if (cur->right == NULL) {
 1106                                         *entry = cur;
 1107                                         break;
 1108                                 }
 1109                                 cur = cur->right;
 1110                         }
 1111                 }
 1112         return (FALSE);
 1113 }
 1114 
 1115 /*
 1116  *      vm_map_insert:
 1117  *
 1118  *      Inserts the given whole VM object into the target
 1119  *      map at the specified address range.  The object's
 1120  *      size should match that of the address range.
 1121  *
 1122  *      Requires that the map be locked, and leaves it so.
 1123  *
 1124  *      If object is non-NULL, ref count must be bumped by caller
 1125  *      prior to making call to account for the new entry.
 1126  */
 1127 int
 1128 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
 1129               vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max,
 1130               int cow)
 1131 {
 1132         vm_map_entry_t new_entry;
 1133         vm_map_entry_t prev_entry;
 1134         vm_map_entry_t temp_entry;
 1135         vm_eflags_t protoeflags;
 1136         struct uidinfo *uip;
 1137         boolean_t charge_prev_obj;
 1138 
 1139         VM_MAP_ASSERT_LOCKED(map);
 1140 
 1141         /*
 1142          * Check that the start and end points are not bogus.
 1143          */
 1144         if ((start < map->min_offset) || (end > map->max_offset) ||
 1145             (start >= end))
 1146                 return (KERN_INVALID_ADDRESS);
 1147 
 1148         /*
 1149          * Find the entry prior to the proposed starting address; if it's part
 1150          * of an existing entry, this range is bogus.
 1151          */
 1152         if (vm_map_lookup_entry(map, start, &temp_entry))
 1153                 return (KERN_NO_SPACE);
 1154 
 1155         prev_entry = temp_entry;
 1156 
 1157         /*
 1158          * Assert that the next entry doesn't overlap the end point.
 1159          */
 1160         if ((prev_entry->next != &map->header) &&
 1161             (prev_entry->next->start < end))
 1162                 return (KERN_NO_SPACE);
 1163 
 1164         protoeflags = 0;
 1165         charge_prev_obj = FALSE;
 1166 
 1167         if (cow & MAP_COPY_ON_WRITE)
 1168                 protoeflags |= MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY;
 1169 
 1170         if (cow & MAP_NOFAULT) {
 1171                 protoeflags |= MAP_ENTRY_NOFAULT;
 1172 
 1173                 KASSERT(object == NULL,
 1174                         ("vm_map_insert: paradoxical MAP_NOFAULT request"));
 1175         }
 1176         if (cow & MAP_DISABLE_SYNCER)
 1177                 protoeflags |= MAP_ENTRY_NOSYNC;
 1178         if (cow & MAP_DISABLE_COREDUMP)
 1179                 protoeflags |= MAP_ENTRY_NOCOREDUMP;
 1180 
 1181         uip = NULL;
 1182         KASSERT((object != kmem_object && object != kernel_object) ||
 1183             ((object == kmem_object || object == kernel_object) &&
 1184                 !(protoeflags & MAP_ENTRY_NEEDS_COPY)),
 1185             ("kmem or kernel object and cow"));
 1186         if (cow & (MAP_ACC_NO_CHARGE | MAP_NOFAULT))
 1187                 goto charged;
 1188         if ((cow & MAP_ACC_CHARGED) || ((prot & VM_PROT_WRITE) &&
 1189             ((protoeflags & MAP_ENTRY_NEEDS_COPY) || object == NULL))) {
 1190                 if (!(cow & MAP_ACC_CHARGED) && !swap_reserve(end - start))
 1191                         return (KERN_RESOURCE_SHORTAGE);
 1192                 KASSERT(object == NULL || (protoeflags & MAP_ENTRY_NEEDS_COPY) ||
 1193                     object->uip == NULL,
 1194                     ("OVERCOMMIT: vm_map_insert o %p", object));
 1195                 uip = curthread->td_ucred->cr_ruidinfo;
 1196                 uihold(uip);
 1197                 if (object == NULL && !(protoeflags & MAP_ENTRY_NEEDS_COPY))
 1198                         charge_prev_obj = TRUE;
 1199         }
 1200 
 1201 charged:
 1202         /* Expand the kernel pmap, if necessary. */
 1203         if (map == kernel_map && end > kernel_vm_end)
 1204                 pmap_growkernel(end);
 1205         if (object != NULL) {
 1206                 /*
 1207                  * OBJ_ONEMAPPING must be cleared unless this mapping
 1208                  * is trivially proven to be the only mapping for any
 1209                  * of the object's pages.  (Object granularity
 1210                  * reference counting is insufficient to recognize
 1211                  * aliases with precision.)
 1212                  */
 1213                 VM_OBJECT_LOCK(object);
 1214                 if (object->ref_count > 1 || object->shadow_count != 0)
 1215                         vm_object_clear_flag(object, OBJ_ONEMAPPING);
 1216                 VM_OBJECT_UNLOCK(object);
 1217         }
 1218         else if ((prev_entry != &map->header) &&
 1219                  (prev_entry->eflags == protoeflags) &&
 1220                  (cow & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) == 0 &&
 1221                  (prev_entry->end == start) &&
 1222                  (prev_entry->wired_count == 0) &&
 1223                  (prev_entry->uip == uip ||
 1224                   (prev_entry->object.vm_object != NULL &&
 1225                    (prev_entry->object.vm_object->uip == uip))) &&
 1226                    vm_object_coalesce(prev_entry->object.vm_object,
 1227                        prev_entry->offset,
 1228                        (vm_size_t)(prev_entry->end - prev_entry->start),
 1229                        (vm_size_t)(end - prev_entry->end), charge_prev_obj)) {
 1230                 /*
 1231                  * We were able to extend the object.  Determine if we
 1232                  * can extend the previous map entry to include the
 1233                  * new range as well.
 1234                  */
 1235                 if ((prev_entry->inheritance == VM_INHERIT_DEFAULT) &&
 1236                     (prev_entry->protection == prot) &&
 1237                     (prev_entry->max_protection == max)) {
 1238                         map->size += (end - prev_entry->end);
 1239                         prev_entry->end = end;
 1240                         vm_map_entry_resize_free(map, prev_entry);
 1241                         vm_map_simplify_entry(map, prev_entry);
 1242                         if (uip != NULL)
 1243                                 uifree(uip);
 1244                         return (KERN_SUCCESS);
 1245                 }
 1246 
 1247                 /*
 1248                  * If we can extend the object but cannot extend the
 1249                  * map entry, we have to create a new map entry.  We
 1250                  * must bump the ref count on the extended object to
 1251                  * account for it.  object may be NULL.
 1252                  */
 1253                 object = prev_entry->object.vm_object;
 1254                 offset = prev_entry->offset +
 1255                         (prev_entry->end - prev_entry->start);
 1256                 vm_object_reference(object);
 1257                 if (uip != NULL && object != NULL && object->uip != NULL &&
 1258                     !(prev_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
 1259                         /* Object already accounts for this uid. */
 1260                         uifree(uip);
 1261                         uip = NULL;
 1262                 }
 1263         }
 1264 
 1265         /*
 1266          * NOTE: if conditionals fail, object can be NULL here.  This occurs
 1267          * in things like the buffer map where we manage kva but do not manage
 1268          * backing objects.
 1269          */
 1270 
 1271         /*
 1272          * Create a new entry
 1273          */
 1274         new_entry = vm_map_entry_create(map);
 1275         new_entry->start = start;
 1276         new_entry->end = end;
 1277         new_entry->uip = NULL;
 1278 
 1279         new_entry->eflags = protoeflags;
 1280         new_entry->object.vm_object = object;
 1281         new_entry->offset = offset;
 1282         new_entry->avail_ssize = 0;
 1283 
 1284         new_entry->inheritance = VM_INHERIT_DEFAULT;
 1285         new_entry->protection = prot;
 1286         new_entry->max_protection = max;
 1287         new_entry->wired_count = 0;
 1288 
 1289         KASSERT(uip == NULL || !ENTRY_CHARGED(new_entry),
 1290             ("OVERCOMMIT: vm_map_insert leaks vm_map %p", new_entry));
 1291         new_entry->uip = uip;
 1292 
 1293         /*
 1294          * Insert the new entry into the list
 1295          */
 1296         vm_map_entry_link(map, prev_entry, new_entry);
 1297         map->size += new_entry->end - new_entry->start;
 1298 
 1299 #if 0
 1300         /*
 1301          * Temporarily removed to avoid MAP_STACK panic, due to
 1302          * MAP_STACK being a huge hack.  Will be added back in
 1303          * when MAP_STACK (and the user stack mapping) is fixed.
 1304          */
 1305         /*
 1306          * It may be possible to simplify the entry
 1307          */
 1308         vm_map_simplify_entry(map, new_entry);
 1309 #endif
 1310 
 1311         if (cow & (MAP_PREFAULT|MAP_PREFAULT_PARTIAL)) {
 1312                 vm_map_pmap_enter(map, start, prot,
 1313                                     object, OFF_TO_IDX(offset), end - start,
 1314                                     cow & MAP_PREFAULT_PARTIAL);
 1315         }
 1316 
 1317         return (KERN_SUCCESS);
 1318 }
 1319 
 1320 /*
 1321  *      vm_map_findspace:
 1322  *
 1323  *      Find the first fit (lowest VM address) for "length" free bytes
 1324  *      beginning at address >= start in the given map.
 1325  *
 1326  *      In a vm_map_entry, "adj_free" is the amount of free space
 1327  *      adjacent (higher address) to this entry, and "max_free" is the
 1328  *      maximum amount of contiguous free space in its subtree.  This
 1329  *      allows finding a free region in one path down the tree, so
 1330  *      O(log n) amortized with splay trees.
 1331  *
 1332  *      The map must be locked, and leaves it so.
 1333  *
 1334  *      Returns: 0 on success, and starting address in *addr,
 1335  *               1 if insufficient space.
 1336  */
 1337 int
 1338 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length,
 1339     vm_offset_t *addr)  /* OUT */
 1340 {
 1341         vm_map_entry_t entry;
 1342         vm_offset_t st;
 1343 
 1344         /*
 1345          * Request must fit within min/max VM address and must avoid
 1346          * address wrap.
 1347          */
 1348         if (start < map->min_offset)
 1349                 start = map->min_offset;
 1350         if (start + length > map->max_offset || start + length < start)
 1351                 return (1);
 1352 
 1353         /* Empty tree means wide open address space. */
 1354         if (map->root == NULL) {
 1355                 *addr = start;
 1356                 return (0);
 1357         }
 1358 
 1359         /*
 1360          * After splay, if start comes before root node, then there
 1361          * must be a gap from start to the root.
 1362          */
 1363         map->root = vm_map_entry_splay(start, map->root);
 1364         if (start + length <= map->root->start) {
 1365                 *addr = start;
 1366                 return (0);
 1367         }
 1368 
 1369         /*
 1370          * Root is the last node that might begin its gap before
 1371          * start, and this is the last comparison where address
 1372          * wrap might be a problem.
 1373          */
 1374         st = (start > map->root->end) ? start : map->root->end;
 1375         if (length <= map->root->end + map->root->adj_free - st) {
 1376                 *addr = st;
 1377                 return (0);
 1378         }
 1379 
 1380         /* With max_free, can immediately tell if no solution. */
 1381         entry = map->root->right;
 1382         if (entry == NULL || length > entry->max_free)
 1383                 return (1);
 1384 
 1385         /*
 1386          * Search the right subtree in the order: left subtree, root,
 1387          * right subtree (first fit).  The previous splay implies that
 1388          * all regions in the right subtree have addresses > start.
 1389          */
 1390         while (entry != NULL) {
 1391                 if (entry->left != NULL && entry->left->max_free >= length)
 1392                         entry = entry->left;
 1393                 else if (entry->adj_free >= length) {
 1394                         *addr = entry->end;
 1395                         return (0);
 1396                 } else
 1397                         entry = entry->right;
 1398         }
 1399 
 1400         /* Can't get here, so panic if we do. */
 1401         panic("vm_map_findspace: max_free corrupt");
 1402 }
 1403 
 1404 int
 1405 vm_map_fixed(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
 1406     vm_offset_t start, vm_size_t length, vm_prot_t prot,
 1407     vm_prot_t max, int cow)
 1408 {
 1409         vm_offset_t end;
 1410         int result;
 1411 
 1412         end = start + length;
 1413         vm_map_lock(map);
 1414         VM_MAP_RANGE_CHECK(map, start, end);
 1415         (void) vm_map_delete(map, start, end);
 1416         result = vm_map_insert(map, object, offset, start, end, prot,
 1417             max, cow);
 1418         vm_map_unlock(map);
 1419         return (result);
 1420 }
 1421 
 1422 /*
 1423  *      vm_map_find finds an unallocated region in the target address
 1424  *      map with the given length.  The search is defined to be
 1425  *      first-fit from the specified address; the region found is
 1426  *      returned in the same parameter.
 1427  *
 1428  *      If object is non-NULL, ref count must be bumped by caller
 1429  *      prior to making call to account for the new entry.
 1430  */
 1431 int
 1432 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
 1433             vm_offset_t *addr,  /* IN/OUT */
 1434             vm_size_t length, int find_space, vm_prot_t prot,
 1435             vm_prot_t max, int cow)
 1436 {
 1437         vm_offset_t start;
 1438         int result;
 1439 
 1440         start = *addr;
 1441         vm_map_lock(map);
 1442         do {
 1443                 if (find_space != VMFS_NO_SPACE) {
 1444                         if (vm_map_findspace(map, start, length, addr)) {
 1445                                 vm_map_unlock(map);
 1446                                 return (KERN_NO_SPACE);
 1447                         }
 1448                         switch (find_space) {
 1449                         case VMFS_ALIGNED_SPACE:
 1450                                 pmap_align_superpage(object, offset, addr,
 1451                                     length);
 1452                                 break;
 1453 #ifdef VMFS_TLB_ALIGNED_SPACE
 1454                         case VMFS_TLB_ALIGNED_SPACE:
 1455                                 pmap_align_tlb(addr);
 1456                                 break;
 1457 #endif
 1458                         default:
 1459                                 break;
 1460                         }
 1461 
 1462                         start = *addr;
 1463                 }
 1464                 result = vm_map_insert(map, object, offset, start, start +
 1465                     length, prot, max, cow);
 1466         } while (result == KERN_NO_SPACE && find_space == VMFS_ALIGNED_SPACE);
 1467         vm_map_unlock(map);
 1468         return (result);
 1469 }
 1470 
 1471 /*
 1472  *      vm_map_simplify_entry:
 1473  *
 1474  *      Simplify the given map entry by merging with either neighbor.  This
 1475  *      routine also has the ability to merge with both neighbors.
 1476  *
 1477  *      The map must be locked.
 1478  *
 1479  *      This routine guarentees that the passed entry remains valid (though
 1480  *      possibly extended).  When merging, this routine may delete one or
 1481  *      both neighbors.
 1482  */
 1483 void
 1484 vm_map_simplify_entry(vm_map_t map, vm_map_entry_t entry)
 1485 {
 1486         vm_map_entry_t next, prev;
 1487         vm_size_t prevsize, esize;
 1488 
 1489         if (entry->eflags & (MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP))
 1490                 return;
 1491 
 1492         prev = entry->prev;
 1493         if (prev != &map->header) {
 1494                 prevsize = prev->end - prev->start;
 1495                 if ( (prev->end == entry->start) &&
 1496                      (prev->object.vm_object == entry->object.vm_object) &&
 1497                      (!prev->object.vm_object ||
 1498                         (prev->offset + prevsize == entry->offset)) &&
 1499                      (prev->eflags == entry->eflags) &&
 1500                      (prev->protection == entry->protection) &&
 1501                      (prev->max_protection == entry->max_protection) &&
 1502                      (prev->inheritance == entry->inheritance) &&
 1503                      (prev->wired_count == entry->wired_count) &&
 1504                      (prev->uip == entry->uip)) {
 1505                         vm_map_entry_unlink(map, prev);
 1506                         entry->start = prev->start;
 1507                         entry->offset = prev->offset;
 1508                         if (entry->prev != &map->header)
 1509                                 vm_map_entry_resize_free(map, entry->prev);
 1510 
 1511                         /*
 1512                          * If the backing object is a vnode object,
 1513                          * vm_object_deallocate() calls vrele().
 1514                          * However, vrele() does not lock the vnode
 1515                          * because the vnode has additional
 1516                          * references.  Thus, the map lock can be kept
 1517                          * without causing a lock-order reversal with
 1518                          * the vnode lock.
 1519                          */
 1520                         if (prev->object.vm_object)
 1521                                 vm_object_deallocate(prev->object.vm_object);
 1522                         if (prev->uip != NULL)
 1523                                 uifree(prev->uip);
 1524                         vm_map_entry_dispose(map, prev);
 1525                 }
 1526         }
 1527 
 1528         next = entry->next;
 1529         if (next != &map->header) {
 1530                 esize = entry->end - entry->start;
 1531                 if ((entry->end == next->start) &&
 1532                     (next->object.vm_object == entry->object.vm_object) &&
 1533                      (!entry->object.vm_object ||
 1534                         (entry->offset + esize == next->offset)) &&
 1535                     (next->eflags == entry->eflags) &&
 1536                     (next->protection == entry->protection) &&
 1537                     (next->max_protection == entry->max_protection) &&
 1538                     (next->inheritance == entry->inheritance) &&
 1539                     (next->wired_count == entry->wired_count) &&
 1540                     (next->uip == entry->uip)) {
 1541                         vm_map_entry_unlink(map, next);
 1542                         entry->end = next->end;
 1543                         vm_map_entry_resize_free(map, entry);
 1544 
 1545                         /*
 1546                          * See comment above.
 1547                          */
 1548                         if (next->object.vm_object)
 1549                                 vm_object_deallocate(next->object.vm_object);
 1550                         if (next->uip != NULL)
 1551                                 uifree(next->uip);
 1552                         vm_map_entry_dispose(map, next);
 1553                 }
 1554         }
 1555 }
 1556 /*
 1557  *      vm_map_clip_start:      [ internal use only ]
 1558  *
 1559  *      Asserts that the given entry begins at or after
 1560  *      the specified address; if necessary,
 1561  *      it splits the entry into two.
 1562  */
 1563 #define vm_map_clip_start(map, entry, startaddr) \
 1564 { \
 1565         if (startaddr > entry->start) \
 1566                 _vm_map_clip_start(map, entry, startaddr); \
 1567 }
 1568 
 1569 /*
 1570  *      This routine is called only when it is known that
 1571  *      the entry must be split.
 1572  */
 1573 static void
 1574 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start)
 1575 {
 1576         vm_map_entry_t new_entry;
 1577 
 1578         VM_MAP_ASSERT_LOCKED(map);
 1579 
 1580         /*
 1581          * Split off the front portion -- note that we must insert the new
 1582          * entry BEFORE this one, so that this entry has the specified
 1583          * starting address.
 1584          */
 1585         vm_map_simplify_entry(map, entry);
 1586 
 1587         /*
 1588          * If there is no object backing this entry, we might as well create
 1589          * one now.  If we defer it, an object can get created after the map
 1590          * is clipped, and individual objects will be created for the split-up
 1591          * map.  This is a bit of a hack, but is also about the best place to
 1592          * put this improvement.
 1593          */
 1594         if (entry->object.vm_object == NULL && !map->system_map) {
 1595                 vm_object_t object;
 1596                 object = vm_object_allocate(OBJT_DEFAULT,
 1597                                 atop(entry->end - entry->start));
 1598                 entry->object.vm_object = object;
 1599                 entry->offset = 0;
 1600                 if (entry->uip != NULL) {
 1601                         object->uip = entry->uip;
 1602                         object->charge = entry->end - entry->start;
 1603                         entry->uip = NULL;
 1604                 }
 1605         } else if (entry->object.vm_object != NULL &&
 1606                    ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
 1607                    entry->uip != NULL) {
 1608                 VM_OBJECT_LOCK(entry->object.vm_object);
 1609                 KASSERT(entry->object.vm_object->uip == NULL,
 1610                     ("OVERCOMMIT: vm_entry_clip_start: both uip e %p", entry));
 1611                 entry->object.vm_object->uip = entry->uip;
 1612                 entry->object.vm_object->charge = entry->end - entry->start;
 1613                 VM_OBJECT_UNLOCK(entry->object.vm_object);
 1614                 entry->uip = NULL;
 1615         }
 1616 
 1617         new_entry = vm_map_entry_create(map);
 1618         *new_entry = *entry;
 1619 
 1620         new_entry->end = start;
 1621         entry->offset += (start - entry->start);
 1622         entry->start = start;
 1623         if (new_entry->uip != NULL)
 1624                 uihold(entry->uip);
 1625 
 1626         vm_map_entry_link(map, entry->prev, new_entry);
 1627 
 1628         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
 1629                 vm_object_reference(new_entry->object.vm_object);
 1630         }
 1631 }
 1632 
 1633 /*
 1634  *      vm_map_clip_end:        [ internal use only ]
 1635  *
 1636  *      Asserts that the given entry ends at or before
 1637  *      the specified address; if necessary,
 1638  *      it splits the entry into two.
 1639  */
 1640 #define vm_map_clip_end(map, entry, endaddr) \
 1641 { \
 1642         if ((endaddr) < (entry->end)) \
 1643                 _vm_map_clip_end((map), (entry), (endaddr)); \
 1644 }
 1645 
 1646 /*
 1647  *      This routine is called only when it is known that
 1648  *      the entry must be split.
 1649  */
 1650 static void
 1651 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end)
 1652 {
 1653         vm_map_entry_t new_entry;
 1654 
 1655         VM_MAP_ASSERT_LOCKED(map);
 1656 
 1657         /*
 1658          * If there is no object backing this entry, we might as well create
 1659          * one now.  If we defer it, an object can get created after the map
 1660          * is clipped, and individual objects will be created for the split-up
 1661          * map.  This is a bit of a hack, but is also about the best place to
 1662          * put this improvement.
 1663          */
 1664         if (entry->object.vm_object == NULL && !map->system_map) {
 1665                 vm_object_t object;
 1666                 object = vm_object_allocate(OBJT_DEFAULT,
 1667                                 atop(entry->end - entry->start));
 1668                 entry->object.vm_object = object;
 1669                 entry->offset = 0;
 1670                 if (entry->uip != NULL) {
 1671                         object->uip = entry->uip;
 1672                         object->charge = entry->end - entry->start;
 1673                         entry->uip = NULL;
 1674                 }
 1675         } else if (entry->object.vm_object != NULL &&
 1676                    ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
 1677                    entry->uip != NULL) {
 1678                 VM_OBJECT_LOCK(entry->object.vm_object);
 1679                 KASSERT(entry->object.vm_object->uip == NULL,
 1680                     ("OVERCOMMIT: vm_entry_clip_end: both uip e %p", entry));
 1681                 entry->object.vm_object->uip = entry->uip;
 1682                 entry->object.vm_object->charge = entry->end - entry->start;
 1683                 VM_OBJECT_UNLOCK(entry->object.vm_object);
 1684                 entry->uip = NULL;
 1685         }
 1686 
 1687         /*
 1688          * Create a new entry and insert it AFTER the specified entry
 1689          */
 1690         new_entry = vm_map_entry_create(map);
 1691         *new_entry = *entry;
 1692 
 1693         new_entry->start = entry->end = end;
 1694         new_entry->offset += (end - entry->start);
 1695         if (new_entry->uip != NULL)
 1696                 uihold(entry->uip);
 1697 
 1698         vm_map_entry_link(map, entry, new_entry);
 1699 
 1700         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
 1701                 vm_object_reference(new_entry->object.vm_object);
 1702         }
 1703 }
 1704 
 1705 /*
 1706  *      vm_map_submap:          [ kernel use only ]
 1707  *
 1708  *      Mark the given range as handled by a subordinate map.
 1709  *
 1710  *      This range must have been created with vm_map_find,
 1711  *      and no other operations may have been performed on this
 1712  *      range prior to calling vm_map_submap.
 1713  *
 1714  *      Only a limited number of operations can be performed
 1715  *      within this rage after calling vm_map_submap:
 1716  *              vm_fault
 1717  *      [Don't try vm_map_copy!]
 1718  *
 1719  *      To remove a submapping, one must first remove the
 1720  *      range from the superior map, and then destroy the
 1721  *      submap (if desired).  [Better yet, don't try it.]
 1722  */
 1723 int
 1724 vm_map_submap(
 1725         vm_map_t map,
 1726         vm_offset_t start,
 1727         vm_offset_t end,
 1728         vm_map_t submap)
 1729 {
 1730         vm_map_entry_t entry;
 1731         int result = KERN_INVALID_ARGUMENT;
 1732 
 1733         vm_map_lock(map);
 1734 
 1735         VM_MAP_RANGE_CHECK(map, start, end);
 1736 
 1737         if (vm_map_lookup_entry(map, start, &entry)) {
 1738                 vm_map_clip_start(map, entry, start);
 1739         } else
 1740                 entry = entry->next;
 1741 
 1742         vm_map_clip_end(map, entry, end);
 1743 
 1744         if ((entry->start == start) && (entry->end == end) &&
 1745             ((entry->eflags & MAP_ENTRY_COW) == 0) &&
 1746             (entry->object.vm_object == NULL)) {
 1747                 entry->object.sub_map = submap;
 1748                 entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
 1749                 result = KERN_SUCCESS;
 1750         }
 1751         vm_map_unlock(map);
 1752 
 1753         return (result);
 1754 }
 1755 
 1756 /*
 1757  * The maximum number of pages to map
 1758  */
 1759 #define MAX_INIT_PT     96
 1760 
 1761 /*
 1762  *      vm_map_pmap_enter:
 1763  *
 1764  *      Preload read-only mappings for the given object's resident pages into
 1765  *      the given map.  This eliminates the soft faults on process startup and
 1766  *      immediately after an mmap(2).  Because these are speculative mappings,
 1767  *      cached pages are not reactivated and mapped.
 1768  */
 1769 void
 1770 vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
 1771     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
 1772 {
 1773         vm_offset_t start;
 1774         vm_page_t p, p_start;
 1775         vm_pindex_t psize, tmpidx;
 1776         boolean_t are_queues_locked;
 1777 
 1778         if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0 || object == NULL)
 1779                 return;
 1780         VM_OBJECT_LOCK(object);
 1781         if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
 1782                 pmap_object_init_pt(map->pmap, addr, object, pindex, size);
 1783                 goto unlock_return;
 1784         }
 1785 
 1786         psize = atop(size);
 1787 
 1788         if ((flags & MAP_PREFAULT_PARTIAL) && psize > MAX_INIT_PT &&
 1789             object->resident_page_count > MAX_INIT_PT)
 1790                 goto unlock_return;
 1791 
 1792         if (psize + pindex > object->size) {
 1793                 if (object->size < pindex)
 1794                         goto unlock_return;
 1795                 psize = object->size - pindex;
 1796         }
 1797 
 1798         are_queues_locked = FALSE;
 1799         start = 0;
 1800         p_start = NULL;
 1801 
 1802         p = vm_page_find_least(object, pindex);
 1803         /*
 1804          * Assert: the variable p is either (1) the page with the
 1805          * least pindex greater than or equal to the parameter pindex
 1806          * or (2) NULL.
 1807          */
 1808         for (;
 1809              p != NULL && (tmpidx = p->pindex - pindex) < psize;
 1810              p = TAILQ_NEXT(p, listq)) {
 1811                 /*
 1812                  * don't allow an madvise to blow away our really
 1813                  * free pages allocating pv entries.
 1814                  */
 1815                 if ((flags & MAP_PREFAULT_MADVISE) &&
 1816                     cnt.v_free_count < cnt.v_free_reserved) {
 1817                         psize = tmpidx;
 1818                         break;
 1819                 }
 1820                 if (p->valid == VM_PAGE_BITS_ALL) {
 1821                         if (p_start == NULL) {
 1822                                 start = addr + ptoa(tmpidx);
 1823                                 p_start = p;
 1824                         }
 1825                 } else if (p_start != NULL) {
 1826                         if (!are_queues_locked) {
 1827                                 are_queues_locked = TRUE;
 1828                                 vm_page_lock_queues();
 1829                         }
 1830                         pmap_enter_object(map->pmap, start, addr +
 1831                             ptoa(tmpidx), p_start, prot);
 1832                         p_start = NULL;
 1833                 }
 1834         }
 1835         if (p_start != NULL) {
 1836                 if (!are_queues_locked) {
 1837                         are_queues_locked = TRUE;
 1838                         vm_page_lock_queues();
 1839                 }
 1840                 pmap_enter_object(map->pmap, start, addr + ptoa(psize),
 1841                     p_start, prot);
 1842         }
 1843         if (are_queues_locked)
 1844                 vm_page_unlock_queues();
 1845 unlock_return:
 1846         VM_OBJECT_UNLOCK(object);
 1847 }
 1848 
 1849 /*
 1850  *      vm_map_protect:
 1851  *
 1852  *      Sets the protection of the specified address
 1853  *      region in the target map.  If "set_max" is
 1854  *      specified, the maximum protection is to be set;
 1855  *      otherwise, only the current protection is affected.
 1856  */
 1857 int
 1858 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
 1859                vm_prot_t new_prot, boolean_t set_max)
 1860 {
 1861         vm_map_entry_t current, entry;
 1862         vm_object_t obj;
 1863         struct uidinfo *uip;
 1864         vm_prot_t old_prot;
 1865 
 1866         vm_map_lock(map);
 1867 
 1868         VM_MAP_RANGE_CHECK(map, start, end);
 1869 
 1870         if (vm_map_lookup_entry(map, start, &entry)) {
 1871                 vm_map_clip_start(map, entry, start);
 1872         } else {
 1873                 entry = entry->next;
 1874         }
 1875 
 1876         /*
 1877          * Make a first pass to check for protection violations.
 1878          */
 1879         current = entry;
 1880         while ((current != &map->header) && (current->start < end)) {
 1881                 if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
 1882                         vm_map_unlock(map);
 1883                         return (KERN_INVALID_ARGUMENT);
 1884                 }
 1885                 if ((new_prot & current->max_protection) != new_prot) {
 1886                         vm_map_unlock(map);
 1887                         return (KERN_PROTECTION_FAILURE);
 1888                 }
 1889                 current = current->next;
 1890         }
 1891 
 1892 
 1893         /*
 1894          * Do an accounting pass for private read-only mappings that
 1895          * now will do cow due to allowed write (e.g. debugger sets
 1896          * breakpoint on text segment)
 1897          */
 1898         for (current = entry; (current != &map->header) &&
 1899              (current->start < end); current = current->next) {
 1900 
 1901                 vm_map_clip_end(map, current, end);
 1902 
 1903                 if (set_max ||
 1904                     ((new_prot & ~(current->protection)) & VM_PROT_WRITE) == 0 ||
 1905                     ENTRY_CHARGED(current)) {
 1906                         continue;
 1907                 }
 1908 
 1909                 uip = curthread->td_ucred->cr_ruidinfo;
 1910                 obj = current->object.vm_object;
 1911 
 1912                 if (obj == NULL || (current->eflags & MAP_ENTRY_NEEDS_COPY)) {
 1913                         if (!swap_reserve(current->end - current->start)) {
 1914                                 vm_map_unlock(map);
 1915                                 return (KERN_RESOURCE_SHORTAGE);
 1916                         }
 1917                         uihold(uip);
 1918                         current->uip = uip;
 1919                         continue;
 1920                 }
 1921 
 1922                 VM_OBJECT_LOCK(obj);
 1923                 if (obj->type != OBJT_DEFAULT && obj->type != OBJT_SWAP) {
 1924                         VM_OBJECT_UNLOCK(obj);
 1925                         continue;
 1926                 }
 1927 
 1928                 /*
 1929                  * Charge for the whole object allocation now, since
 1930                  * we cannot distinguish between non-charged and
 1931                  * charged clipped mapping of the same object later.
 1932                  */
 1933                 KASSERT(obj->charge == 0,
 1934                     ("vm_map_protect: object %p overcharged\n", obj));
 1935                 if (!swap_reserve(ptoa(obj->size))) {
 1936                         VM_OBJECT_UNLOCK(obj);
 1937                         vm_map_unlock(map);
 1938                         return (KERN_RESOURCE_SHORTAGE);
 1939                 }
 1940 
 1941                 uihold(uip);
 1942                 obj->uip = uip;
 1943                 obj->charge = ptoa(obj->size);
 1944                 VM_OBJECT_UNLOCK(obj);
 1945         }
 1946 
 1947         /*
 1948          * Go back and fix up protections. [Note that clipping is not
 1949          * necessary the second time.]
 1950          */
 1951         current = entry;
 1952         while ((current != &map->header) && (current->start < end)) {
 1953                 old_prot = current->protection;
 1954 
 1955                 if (set_max)
 1956                         current->protection =
 1957                             (current->max_protection = new_prot) &
 1958                             old_prot;
 1959                 else
 1960                         current->protection = new_prot;
 1961 
 1962                 if ((current->eflags & (MAP_ENTRY_COW | MAP_ENTRY_USER_WIRED))
 1963                      == (MAP_ENTRY_COW | MAP_ENTRY_USER_WIRED) &&
 1964                     (current->protection & VM_PROT_WRITE) != 0 &&
 1965                     (old_prot & VM_PROT_WRITE) == 0) {
 1966                         vm_fault_copy_entry(map, map, current, current, NULL);
 1967                 }
 1968 
 1969                 /*
 1970                  * Update physical map if necessary. Worry about copy-on-write
 1971                  * here.
 1972                  */
 1973                 if (current->protection != old_prot) {
 1974 #define MASK(entry)     (((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
 1975                                                         VM_PROT_ALL)
 1976                         pmap_protect(map->pmap, current->start,
 1977                             current->end,
 1978                             current->protection & MASK(current));
 1979 #undef  MASK
 1980                 }
 1981                 vm_map_simplify_entry(map, current);
 1982                 current = current->next;
 1983         }
 1984         vm_map_unlock(map);
 1985         return (KERN_SUCCESS);
 1986 }
 1987 
 1988 /*
 1989  *      vm_map_madvise:
 1990  *
 1991  *      This routine traverses a processes map handling the madvise
 1992  *      system call.  Advisories are classified as either those effecting
 1993  *      the vm_map_entry structure, or those effecting the underlying
 1994  *      objects.
 1995  */
 1996 int
 1997 vm_map_madvise(
 1998         vm_map_t map,
 1999         vm_offset_t start,
 2000         vm_offset_t end,
 2001         int behav)
 2002 {
 2003         vm_map_entry_t current, entry;
 2004         int modify_map = 0;
 2005 
 2006         /*
 2007          * Some madvise calls directly modify the vm_map_entry, in which case
 2008          * we need to use an exclusive lock on the map and we need to perform
 2009          * various clipping operations.  Otherwise we only need a read-lock
 2010          * on the map.
 2011          */
 2012         switch(behav) {
 2013         case MADV_NORMAL:
 2014         case MADV_SEQUENTIAL:
 2015         case MADV_RANDOM:
 2016         case MADV_NOSYNC:
 2017         case MADV_AUTOSYNC:
 2018         case MADV_NOCORE:
 2019         case MADV_CORE:
 2020                 modify_map = 1;
 2021                 vm_map_lock(map);
 2022                 break;
 2023         case MADV_WILLNEED:
 2024         case MADV_DONTNEED:
 2025         case MADV_FREE:
 2026                 vm_map_lock_read(map);
 2027                 break;
 2028         default:
 2029                 return (KERN_INVALID_ARGUMENT);
 2030         }
 2031 
 2032         /*
 2033          * Locate starting entry and clip if necessary.
 2034          */
 2035         VM_MAP_RANGE_CHECK(map, start, end);
 2036 
 2037         if (vm_map_lookup_entry(map, start, &entry)) {
 2038                 if (modify_map)
 2039                         vm_map_clip_start(map, entry, start);
 2040         } else {
 2041                 entry = entry->next;
 2042         }
 2043 
 2044         if (modify_map) {
 2045                 /*
 2046                  * madvise behaviors that are implemented in the vm_map_entry.
 2047                  *
 2048                  * We clip the vm_map_entry so that behavioral changes are
 2049                  * limited to the specified address range.
 2050                  */
 2051                 for (current = entry;
 2052                      (current != &map->header) && (current->start < end);
 2053                      current = current->next
 2054                 ) {
 2055                         if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
 2056                                 continue;
 2057 
 2058                         vm_map_clip_end(map, current, end);
 2059 
 2060                         switch (behav) {
 2061                         case MADV_NORMAL:
 2062                                 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
 2063                                 break;
 2064                         case MADV_SEQUENTIAL:
 2065                                 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
 2066                                 break;
 2067                         case MADV_RANDOM:
 2068                                 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
 2069                                 break;
 2070                         case MADV_NOSYNC:
 2071                                 current->eflags |= MAP_ENTRY_NOSYNC;
 2072                                 break;
 2073                         case MADV_AUTOSYNC:
 2074                                 current->eflags &= ~MAP_ENTRY_NOSYNC;
 2075                                 break;
 2076                         case MADV_NOCORE:
 2077                                 current->eflags |= MAP_ENTRY_NOCOREDUMP;
 2078                                 break;
 2079                         case MADV_CORE:
 2080                                 current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
 2081                                 break;
 2082                         default:
 2083                                 break;
 2084                         }
 2085                         vm_map_simplify_entry(map, current);
 2086                 }
 2087                 vm_map_unlock(map);
 2088         } else {
 2089                 vm_pindex_t pstart, pend;
 2090 
 2091                 /*
 2092                  * madvise behaviors that are implemented in the underlying
 2093                  * vm_object.
 2094                  *
 2095                  * Since we don't clip the vm_map_entry, we have to clip
 2096                  * the vm_object pindex and count.
 2097                  */
 2098                 for (current = entry;
 2099                      (current != &map->header) && (current->start < end);
 2100                      current = current->next
 2101                 ) {
 2102                         vm_offset_t useStart;
 2103 
 2104                         if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
 2105                                 continue;
 2106 
 2107                         pstart = OFF_TO_IDX(current->offset);
 2108                         pend = pstart + atop(current->end - current->start);
 2109                         useStart = current->start;
 2110 
 2111                         if (current->start < start) {
 2112                                 pstart += atop(start - current->start);
 2113                                 useStart = start;
 2114                         }
 2115                         if (current->end > end)
 2116                                 pend -= atop(current->end - end);
 2117 
 2118                         if (pstart >= pend)
 2119                                 continue;
 2120 
 2121                         vm_object_madvise(current->object.vm_object, pstart,
 2122                             pend, behav);
 2123                         if (behav == MADV_WILLNEED) {
 2124                                 vm_map_pmap_enter(map,
 2125                                     useStart,
 2126                                     current->protection,
 2127                                     current->object.vm_object,
 2128                                     pstart,
 2129                                     ptoa(pend - pstart),
 2130                                     MAP_PREFAULT_MADVISE
 2131                                 );
 2132                         }
 2133                 }
 2134                 vm_map_unlock_read(map);
 2135         }
 2136         return (0);
 2137 }
 2138 
 2139 
 2140 /*
 2141  *      vm_map_inherit:
 2142  *
 2143  *      Sets the inheritance of the specified address
 2144  *      range in the target map.  Inheritance
 2145  *      affects how the map will be shared with
 2146  *      child maps at the time of vmspace_fork.
 2147  */
 2148 int
 2149 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
 2150                vm_inherit_t new_inheritance)
 2151 {
 2152         vm_map_entry_t entry;
 2153         vm_map_entry_t temp_entry;
 2154 
 2155         switch (new_inheritance) {
 2156         case VM_INHERIT_NONE:
 2157         case VM_INHERIT_COPY:
 2158         case VM_INHERIT_SHARE:
 2159                 break;
 2160         default:
 2161                 return (KERN_INVALID_ARGUMENT);
 2162         }
 2163         vm_map_lock(map);
 2164         VM_MAP_RANGE_CHECK(map, start, end);
 2165         if (vm_map_lookup_entry(map, start, &temp_entry)) {
 2166                 entry = temp_entry;
 2167                 vm_map_clip_start(map, entry, start);
 2168         } else
 2169                 entry = temp_entry->next;
 2170         while ((entry != &map->header) && (entry->start < end)) {
 2171                 vm_map_clip_end(map, entry, end);
 2172                 entry->inheritance = new_inheritance;
 2173                 vm_map_simplify_entry(map, entry);
 2174                 entry = entry->next;
 2175         }
 2176         vm_map_unlock(map);
 2177         return (KERN_SUCCESS);
 2178 }
 2179 
 2180 /*
 2181  *      vm_map_unwire:
 2182  *
 2183  *      Implements both kernel and user unwiring.
 2184  */
 2185 int
 2186 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
 2187     int flags)
 2188 {
 2189         vm_map_entry_t entry, first_entry, tmp_entry;
 2190         vm_offset_t saved_start;
 2191         unsigned int last_timestamp;
 2192         int rv;
 2193         boolean_t need_wakeup, result, user_unwire;
 2194 
 2195         user_unwire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
 2196         vm_map_lock(map);
 2197         VM_MAP_RANGE_CHECK(map, start, end);
 2198         if (!vm_map_lookup_entry(map, start, &first_entry)) {
 2199                 if (flags & VM_MAP_WIRE_HOLESOK)
 2200                         first_entry = first_entry->next;
 2201                 else {
 2202                         vm_map_unlock(map);
 2203                         return (KERN_INVALID_ADDRESS);
 2204                 }
 2205         }
 2206         last_timestamp = map->timestamp;
 2207         entry = first_entry;
 2208         while (entry != &map->header && entry->start < end) {
 2209                 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
 2210                         /*
 2211                          * We have not yet clipped the entry.
 2212                          */
 2213                         saved_start = (start >= entry->start) ? start :
 2214                             entry->start;
 2215                         entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
 2216                         if (vm_map_unlock_and_wait(map, 0)) {
 2217                                 /*
 2218                                  * Allow interruption of user unwiring?
 2219                                  */
 2220                         }
 2221                         vm_map_lock(map);
 2222                         if (last_timestamp+1 != map->timestamp) {
 2223                                 /*
 2224                                  * Look again for the entry because the map was
 2225                                  * modified while it was unlocked.
 2226                                  * Specifically, the entry may have been
 2227                                  * clipped, merged, or deleted.
 2228                                  */
 2229                                 if (!vm_map_lookup_entry(map, saved_start,
 2230                                     &tmp_entry)) {
 2231                                         if (flags & VM_MAP_WIRE_HOLESOK)
 2232                                                 tmp_entry = tmp_entry->next;
 2233                                         else {
 2234                                                 if (saved_start == start) {
 2235                                                         /*
 2236                                                          * First_entry has been deleted.
 2237                                                          */
 2238                                                         vm_map_unlock(map);
 2239                                                         return (KERN_INVALID_ADDRESS);
 2240                                                 }
 2241                                                 end = saved_start;
 2242                                                 rv = KERN_INVALID_ADDRESS;
 2243                                                 goto done;
 2244                                         }
 2245                                 }
 2246                                 if (entry == first_entry)
 2247                                         first_entry = tmp_entry;
 2248                                 else
 2249                                         first_entry = NULL;
 2250                                 entry = tmp_entry;
 2251                         }
 2252                         last_timestamp = map->timestamp;
 2253                         continue;
 2254                 }
 2255                 vm_map_clip_start(map, entry, start);
 2256                 vm_map_clip_end(map, entry, end);
 2257                 /*
 2258                  * Mark the entry in case the map lock is released.  (See
 2259                  * above.)
 2260                  */
 2261                 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
 2262                 /*
 2263                  * Check the map for holes in the specified region.
 2264                  * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
 2265                  */
 2266                 if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
 2267                     (entry->end < end && (entry->next == &map->header ||
 2268                     entry->next->start > entry->end))) {
 2269                         end = entry->end;
 2270                         rv = KERN_INVALID_ADDRESS;
 2271                         goto done;
 2272                 }
 2273                 /*
 2274                  * If system unwiring, require that the entry is system wired.
 2275                  */
 2276                 if (!user_unwire &&
 2277                     vm_map_entry_system_wired_count(entry) == 0) {
 2278                         end = entry->end;
 2279                         rv = KERN_INVALID_ARGUMENT;
 2280                         goto done;
 2281                 }
 2282                 entry = entry->next;
 2283         }
 2284         rv = KERN_SUCCESS;
 2285 done:
 2286         need_wakeup = FALSE;
 2287         if (first_entry == NULL) {
 2288                 result = vm_map_lookup_entry(map, start, &first_entry);
 2289                 if (!result && (flags & VM_MAP_WIRE_HOLESOK))
 2290                         first_entry = first_entry->next;
 2291                 else
 2292                         KASSERT(result, ("vm_map_unwire: lookup failed"));
 2293         }
 2294         entry = first_entry;
 2295         while (entry != &map->header && entry->start < end) {
 2296                 if (rv == KERN_SUCCESS && (!user_unwire ||
 2297                     (entry->eflags & MAP_ENTRY_USER_WIRED))) {
 2298                         if (user_unwire)
 2299                                 entry->eflags &= ~MAP_ENTRY_USER_WIRED;
 2300                         entry->wired_count--;
 2301                         if (entry->wired_count == 0) {
 2302                                 /*
 2303                                  * Retain the map lock.
 2304                                  */
 2305                                 vm_fault_unwire(map, entry->start, entry->end,
 2306                                     entry->object.vm_object != NULL &&
 2307                                     (entry->object.vm_object->type == OBJT_DEVICE ||
 2308                                     entry->object.vm_object->type == OBJT_SG));
 2309                         }
 2310                 }
 2311                 KASSERT(entry->eflags & MAP_ENTRY_IN_TRANSITION,
 2312                         ("vm_map_unwire: in-transition flag missing"));
 2313                 entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
 2314                 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
 2315                         entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
 2316                         need_wakeup = TRUE;
 2317                 }
 2318                 vm_map_simplify_entry(map, entry);
 2319                 entry = entry->next;
 2320         }
 2321         vm_map_unlock(map);
 2322         if (need_wakeup)
 2323                 vm_map_wakeup(map);
 2324         return (rv);
 2325 }
 2326 
 2327 /*
 2328  *      vm_map_wire:
 2329  *
 2330  *      Implements both kernel and user wiring.
 2331  */
 2332 int
 2333 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end,
 2334     int flags)
 2335 {
 2336         vm_map_entry_t entry, first_entry, tmp_entry;
 2337         vm_offset_t saved_end, saved_start;
 2338         unsigned int last_timestamp;
 2339         int rv;
 2340         boolean_t fictitious, need_wakeup, result, user_wire;
 2341 
 2342         user_wire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
 2343         vm_map_lock(map);
 2344         VM_MAP_RANGE_CHECK(map, start, end);
 2345         if (!vm_map_lookup_entry(map, start, &first_entry)) {
 2346                 if (flags & VM_MAP_WIRE_HOLESOK)
 2347                         first_entry = first_entry->next;
 2348                 else {
 2349                         vm_map_unlock(map);
 2350                         return (KERN_INVALID_ADDRESS);
 2351                 }
 2352         }
 2353         last_timestamp = map->timestamp;
 2354         entry = first_entry;
 2355         while (entry != &map->header && entry->start < end) {
 2356                 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
 2357                         /*
 2358                          * We have not yet clipped the entry.
 2359                          */
 2360                         saved_start = (start >= entry->start) ? start :
 2361                             entry->start;
 2362                         entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
 2363                         if (vm_map_unlock_and_wait(map, 0)) {
 2364                                 /*
 2365                                  * Allow interruption of user wiring?
 2366                                  */
 2367                         }
 2368                         vm_map_lock(map);
 2369                         if (last_timestamp + 1 != map->timestamp) {
 2370                                 /*
 2371                                  * Look again for the entry because the map was
 2372                                  * modified while it was unlocked.
 2373                                  * Specifically, the entry may have been
 2374                                  * clipped, merged, or deleted.
 2375                                  */
 2376                                 if (!vm_map_lookup_entry(map, saved_start,
 2377                                     &tmp_entry)) {
 2378                                         if (flags & VM_MAP_WIRE_HOLESOK)
 2379                                                 tmp_entry = tmp_entry->next;
 2380                                         else {
 2381                                                 if (saved_start == start) {
 2382                                                         /*
 2383                                                          * first_entry has been deleted.
 2384                                                          */
 2385                                                         vm_map_unlock(map);
 2386                                                         return (KERN_INVALID_ADDRESS);
 2387                                                 }
 2388                                                 end = saved_start;
 2389                                                 rv = KERN_INVALID_ADDRESS;
 2390                                                 goto done;
 2391                                         }
 2392                                 }
 2393                                 if (entry == first_entry)
 2394                                         first_entry = tmp_entry;
 2395                                 else
 2396                                         first_entry = NULL;
 2397                                 entry = tmp_entry;
 2398                         }
 2399                         last_timestamp = map->timestamp;
 2400                         continue;
 2401                 }
 2402                 vm_map_clip_start(map, entry, start);
 2403                 vm_map_clip_end(map, entry, end);
 2404                 /*
 2405                  * Mark the entry in case the map lock is released.  (See
 2406                  * above.)
 2407                  */
 2408                 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
 2409                 /*
 2410                  *
 2411                  */
 2412                 if (entry->wired_count == 0) {
 2413                         if ((entry->protection & (VM_PROT_READ|VM_PROT_EXECUTE))
 2414                             == 0) {
 2415                                 entry->eflags |= MAP_ENTRY_WIRE_SKIPPED;
 2416                                 if ((flags & VM_MAP_WIRE_HOLESOK) == 0) {
 2417                                         end = entry->end;
 2418                                         rv = KERN_INVALID_ADDRESS;
 2419                                         goto done;
 2420                                 }
 2421                                 goto next_entry;
 2422                         }
 2423                         entry->wired_count++;
 2424                         saved_start = entry->start;
 2425                         saved_end = entry->end;
 2426                         fictitious = entry->object.vm_object != NULL &&
 2427                             (entry->object.vm_object->type == OBJT_DEVICE ||
 2428                             entry->object.vm_object->type == OBJT_SG);
 2429                         /*
 2430                          * Release the map lock, relying on the in-transition
 2431                          * mark.  Mark the map busy for fork.
 2432                          */
 2433                         vm_map_busy(map);
 2434                         vm_map_unlock(map);
 2435                         rv = vm_fault_wire(map, saved_start, saved_end,
 2436                             user_wire, fictitious);
 2437                         vm_map_lock(map);
 2438                         vm_map_unbusy(map);
 2439                         if (last_timestamp + 1 != map->timestamp) {
 2440                                 /*
 2441                                  * Look again for the entry because the map was
 2442                                  * modified while it was unlocked.  The entry
 2443                                  * may have been clipped, but NOT merged or
 2444                                  * deleted.
 2445                                  */
 2446                                 result = vm_map_lookup_entry(map, saved_start,
 2447                                     &tmp_entry);
 2448                                 KASSERT(result, ("vm_map_wire: lookup failed"));
 2449                                 if (entry == first_entry)
 2450                                         first_entry = tmp_entry;
 2451                                 else
 2452                                         first_entry = NULL;
 2453                                 entry = tmp_entry;
 2454                                 while (entry->end < saved_end) {
 2455                                         if (rv != KERN_SUCCESS) {
 2456                                                 KASSERT(entry->wired_count == 1,
 2457                                                     ("vm_map_wire: bad count"));
 2458                                                 entry->wired_count = -1;
 2459                                         }
 2460                                         entry = entry->next;
 2461                                 }
 2462                         }
 2463                         last_timestamp = map->timestamp;
 2464                         if (rv != KERN_SUCCESS) {
 2465                                 KASSERT(entry->wired_count == 1,
 2466                                     ("vm_map_wire: bad count"));
 2467                                 /*
 2468                                  * Assign an out-of-range value to represent
 2469                                  * the failure to wire this entry.
 2470                                  */
 2471                                 entry->wired_count = -1;
 2472                                 end = entry->end;
 2473                                 goto done;
 2474                         }
 2475                 } else if (!user_wire ||
 2476                            (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
 2477                         entry->wired_count++;
 2478                 }
 2479                 /*
 2480                  * Check the map for holes in the specified region.
 2481                  * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
 2482                  */
 2483         next_entry:
 2484                 if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
 2485                     (entry->end < end && (entry->next == &map->header ||
 2486                     entry->next->start > entry->end))) {
 2487                         end = entry->end;
 2488                         rv = KERN_INVALID_ADDRESS;
 2489                         goto done;
 2490                 }
 2491                 entry = entry->next;
 2492         }
 2493         rv = KERN_SUCCESS;
 2494 done:
 2495         need_wakeup = FALSE;
 2496         if (first_entry == NULL) {
 2497                 result = vm_map_lookup_entry(map, start, &first_entry);
 2498                 if (!result && (flags & VM_MAP_WIRE_HOLESOK))
 2499                         first_entry = first_entry->next;
 2500                 else
 2501                         KASSERT(result, ("vm_map_wire: lookup failed"));
 2502         }
 2503         entry = first_entry;
 2504         while (entry != &map->header && entry->start < end) {
 2505                 if ((entry->eflags & MAP_ENTRY_WIRE_SKIPPED) != 0)
 2506                         goto next_entry_done;
 2507                 if (rv == KERN_SUCCESS) {
 2508                         if (user_wire)
 2509                                 entry->eflags |= MAP_ENTRY_USER_WIRED;
 2510                 } else if (entry->wired_count == -1) {
 2511                         /*
 2512                          * Wiring failed on this entry.  Thus, unwiring is
 2513                          * unnecessary.
 2514                          */
 2515                         entry->wired_count = 0;
 2516                 } else {
 2517                         if (!user_wire ||
 2518                             (entry->eflags & MAP_ENTRY_USER_WIRED) == 0)
 2519                                 entry->wired_count--;
 2520                         if (entry->wired_count == 0) {
 2521                                 /*
 2522                                  * Retain the map lock.
 2523                                  */
 2524                                 vm_fault_unwire(map, entry->start, entry->end,
 2525                                     entry->object.vm_object != NULL &&
 2526                                     (entry->object.vm_object->type == OBJT_DEVICE ||
 2527                                     entry->object.vm_object->type == OBJT_SG));
 2528                         }
 2529                 }
 2530         next_entry_done:
 2531                 KASSERT(entry->eflags & MAP_ENTRY_IN_TRANSITION,
 2532                         ("vm_map_wire: in-transition flag missing"));
 2533                 entry->eflags &= ~(MAP_ENTRY_IN_TRANSITION|MAP_ENTRY_WIRE_SKIPPED);
 2534                 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
 2535                         entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
 2536                         need_wakeup = TRUE;
 2537                 }
 2538                 vm_map_simplify_entry(map, entry);
 2539                 entry = entry->next;
 2540         }
 2541         vm_map_unlock(map);
 2542         if (need_wakeup)
 2543                 vm_map_wakeup(map);
 2544         return (rv);
 2545 }
 2546 
 2547 /*
 2548  * vm_map_sync
 2549  *
 2550  * Push any dirty cached pages in the address range to their pager.
 2551  * If syncio is TRUE, dirty pages are written synchronously.
 2552  * If invalidate is TRUE, any cached pages are freed as well.
 2553  *
 2554  * If the size of the region from start to end is zero, we are
 2555  * supposed to flush all modified pages within the region containing
 2556  * start.  Unfortunately, a region can be split or coalesced with
 2557  * neighboring regions, making it difficult to determine what the
 2558  * original region was.  Therefore, we approximate this requirement by
 2559  * flushing the current region containing start.
 2560  *
 2561  * Returns an error if any part of the specified range is not mapped.
 2562  */
 2563 int
 2564 vm_map_sync(
 2565         vm_map_t map,
 2566         vm_offset_t start,
 2567         vm_offset_t end,
 2568         boolean_t syncio,
 2569         boolean_t invalidate)
 2570 {
 2571         vm_map_entry_t current;
 2572         vm_map_entry_t entry;
 2573         vm_size_t size;
 2574         vm_object_t object;
 2575         vm_ooffset_t offset;
 2576         unsigned int last_timestamp;
 2577         boolean_t failed;
 2578 
 2579         vm_map_lock_read(map);
 2580         VM_MAP_RANGE_CHECK(map, start, end);
 2581         if (!vm_map_lookup_entry(map, start, &entry)) {
 2582                 vm_map_unlock_read(map);
 2583                 return (KERN_INVALID_ADDRESS);
 2584         } else if (start == end) {
 2585                 start = entry->start;
 2586                 end = entry->end;
 2587         }
 2588         /*
 2589          * Make a first pass to check for user-wired memory and holes.
 2590          */
 2591         for (current = entry; current != &map->header && current->start < end;
 2592             current = current->next) {
 2593                 if (invalidate && (current->eflags & MAP_ENTRY_USER_WIRED)) {
 2594                         vm_map_unlock_read(map);
 2595                         return (KERN_INVALID_ARGUMENT);
 2596                 }
 2597                 if (end > current->end &&
 2598                     (current->next == &map->header ||
 2599                         current->end != current->next->start)) {
 2600                         vm_map_unlock_read(map);
 2601                         return (KERN_INVALID_ADDRESS);
 2602                 }
 2603         }
 2604 
 2605         if (invalidate)
 2606                 pmap_remove(map->pmap, start, end);
 2607         failed = FALSE;
 2608 
 2609         /*
 2610          * Make a second pass, cleaning/uncaching pages from the indicated
 2611          * objects as we go.
 2612          */
 2613         for (current = entry; current != &map->header && current->start < end;) {
 2614                 offset = current->offset + (start - current->start);
 2615                 size = (end <= current->end ? end : current->end) - start;
 2616                 if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
 2617                         vm_map_t smap;
 2618                         vm_map_entry_t tentry;
 2619                         vm_size_t tsize;
 2620 
 2621                         smap = current->object.sub_map;
 2622                         vm_map_lock_read(smap);
 2623                         (void) vm_map_lookup_entry(smap, offset, &tentry);
 2624                         tsize = tentry->end - offset;
 2625                         if (tsize < size)
 2626                                 size = tsize;
 2627                         object = tentry->object.vm_object;
 2628                         offset = tentry->offset + (offset - tentry->start);
 2629                         vm_map_unlock_read(smap);
 2630                 } else {
 2631                         object = current->object.vm_object;
 2632                 }
 2633                 vm_object_reference(object);
 2634                 last_timestamp = map->timestamp;
 2635                 vm_map_unlock_read(map);
 2636                 if (!vm_object_sync(object, offset, size, syncio, invalidate))
 2637                         failed = TRUE;
 2638                 start += size;
 2639                 vm_object_deallocate(object);
 2640                 vm_map_lock_read(map);
 2641                 if (last_timestamp == map->timestamp ||
 2642                     !vm_map_lookup_entry(map, start, &current))
 2643                         current = current->next;
 2644         }
 2645 
 2646         vm_map_unlock_read(map);
 2647         return (failed ? KERN_FAILURE : KERN_SUCCESS);
 2648 }
 2649 
 2650 /*
 2651  *      vm_map_entry_unwire:    [ internal use only ]
 2652  *
 2653  *      Make the region specified by this entry pageable.
 2654  *
 2655  *      The map in question should be locked.
 2656  *      [This is the reason for this routine's existence.]
 2657  */
 2658 static void
 2659 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
 2660 {
 2661         vm_fault_unwire(map, entry->start, entry->end,
 2662             entry->object.vm_object != NULL &&
 2663             (entry->object.vm_object->type == OBJT_DEVICE ||
 2664             entry->object.vm_object->type == OBJT_SG));
 2665         entry->wired_count = 0;
 2666 }
 2667 
 2668 static void
 2669 vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map)
 2670 {
 2671 
 2672         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
 2673                 vm_object_deallocate(entry->object.vm_object);
 2674         uma_zfree(system_map ? kmapentzone : mapentzone, entry);
 2675 }
 2676 
 2677 /*
 2678  *      vm_map_entry_delete:    [ internal use only ]
 2679  *
 2680  *      Deallocate the given entry from the target map.
 2681  */
 2682 static void
 2683 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
 2684 {
 2685         vm_object_t object;
 2686         vm_pindex_t offidxstart, offidxend, count, size1;
 2687         vm_ooffset_t size;
 2688 
 2689         vm_map_entry_unlink(map, entry);
 2690         object = entry->object.vm_object;
 2691         size = entry->end - entry->start;
 2692         map->size -= size;
 2693 
 2694         if (entry->uip != NULL) {
 2695                 swap_release_by_uid(size, entry->uip);
 2696                 uifree(entry->uip);
 2697         }
 2698 
 2699         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
 2700             (object != NULL)) {
 2701                 KASSERT(entry->uip == NULL || object->uip == NULL ||
 2702                     (entry->eflags & MAP_ENTRY_NEEDS_COPY),
 2703                     ("OVERCOMMIT vm_map_entry_delete: both uip %p", entry));
 2704                 count = OFF_TO_IDX(size);
 2705                 offidxstart = OFF_TO_IDX(entry->offset);
 2706                 offidxend = offidxstart + count;
 2707                 VM_OBJECT_LOCK(object);
 2708                 if (object->ref_count != 1 &&
 2709                     ((object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING ||
 2710                     object == kernel_object || object == kmem_object)) {
 2711                         vm_object_collapse(object);
 2712                         vm_object_page_remove(object, offidxstart, offidxend, FALSE);
 2713                         if (object->type == OBJT_SWAP)
 2714                                 swap_pager_freespace(object, offidxstart, count);
 2715                         if (offidxend >= object->size &&
 2716                             offidxstart < object->size) {
 2717                                 size1 = object->size;
 2718                                 object->size = offidxstart;
 2719                                 if (object->uip != NULL) {
 2720                                         size1 -= object->size;
 2721                                         KASSERT(object->charge >= ptoa(size1),
 2722                                             ("vm_map_entry_delete: object->charge < 0"));
 2723                                         swap_release_by_uid(ptoa(size1), object->uip);
 2724                                         object->charge -= ptoa(size1);
 2725                                 }
 2726                         }
 2727                 }
 2728                 VM_OBJECT_UNLOCK(object);
 2729         } else
 2730                 entry->object.vm_object = NULL;
 2731         if (map->system_map)
 2732                 vm_map_entry_deallocate(entry, TRUE);
 2733         else {
 2734                 entry->next = curthread->td_map_def_user;
 2735                 curthread->td_map_def_user = entry;
 2736         }
 2737 }
 2738 
 2739 /*
 2740  *      vm_map_delete:  [ internal use only ]
 2741  *
 2742  *      Deallocates the given address range from the target
 2743  *      map.
 2744  */
 2745 int
 2746 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
 2747 {
 2748         vm_map_entry_t entry;
 2749         vm_map_entry_t first_entry;
 2750 
 2751         VM_MAP_ASSERT_LOCKED(map);
 2752 
 2753         /*
 2754          * Find the start of the region, and clip it
 2755          */
 2756         if (!vm_map_lookup_entry(map, start, &first_entry))
 2757                 entry = first_entry->next;
 2758         else {
 2759                 entry = first_entry;
 2760                 vm_map_clip_start(map, entry, start);
 2761         }
 2762 
 2763         /*
 2764          * Step through all entries in this region
 2765          */
 2766         while ((entry != &map->header) && (entry->start < end)) {
 2767                 vm_map_entry_t next;
 2768 
 2769                 /*
 2770                  * Wait for wiring or unwiring of an entry to complete.
 2771                  * Also wait for any system wirings to disappear on
 2772                  * user maps.
 2773                  */
 2774                 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
 2775                     (vm_map_pmap(map) != kernel_pmap &&
 2776                     vm_map_entry_system_wired_count(entry) != 0)) {
 2777                         unsigned int last_timestamp;
 2778                         vm_offset_t saved_start;
 2779                         vm_map_entry_t tmp_entry;
 2780 
 2781                         saved_start = entry->start;
 2782                         entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
 2783                         last_timestamp = map->timestamp;
 2784                         (void) vm_map_unlock_and_wait(map, 0);
 2785                         vm_map_lock(map);
 2786                         if (last_timestamp + 1 != map->timestamp) {
 2787                                 /*
 2788                                  * Look again for the entry because the map was
 2789                                  * modified while it was unlocked.
 2790                                  * Specifically, the entry may have been
 2791                                  * clipped, merged, or deleted.
 2792                                  */
 2793                                 if (!vm_map_lookup_entry(map, saved_start,
 2794                                                          &tmp_entry))
 2795                                         entry = tmp_entry->next;
 2796                                 else {
 2797                                         entry = tmp_entry;
 2798                                         vm_map_clip_start(map, entry,
 2799                                                           saved_start);
 2800                                 }
 2801                         }
 2802                         continue;
 2803                 }
 2804                 vm_map_clip_end(map, entry, end);
 2805 
 2806                 next = entry->next;
 2807 
 2808                 /*
 2809                  * Unwire before removing addresses from the pmap; otherwise,
 2810                  * unwiring will put the entries back in the pmap.
 2811                  */
 2812                 if (entry->wired_count != 0) {
 2813                         vm_map_entry_unwire(map, entry);
 2814                 }
 2815 
 2816                 pmap_remove(map->pmap, entry->start, entry->end);
 2817 
 2818                 /*
 2819                  * Delete the entry only after removing all pmap
 2820                  * entries pointing to its pages.  (Otherwise, its
 2821                  * page frames may be reallocated, and any modify bits
 2822                  * will be set in the wrong object!)
 2823                  */
 2824                 vm_map_entry_delete(map, entry);
 2825                 entry = next;
 2826         }
 2827         return (KERN_SUCCESS);
 2828 }
 2829 
 2830 /*
 2831  *      vm_map_remove:
 2832  *
 2833  *      Remove the given address range from the target map.
 2834  *      This is the exported form of vm_map_delete.
 2835  */
 2836 int
 2837 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
 2838 {
 2839         int result;
 2840 
 2841         vm_map_lock(map);
 2842         VM_MAP_RANGE_CHECK(map, start, end);
 2843         result = vm_map_delete(map, start, end);
 2844         vm_map_unlock(map);
 2845         return (result);
 2846 }
 2847 
 2848 /*
 2849  *      vm_map_check_protection:
 2850  *
 2851  *      Assert that the target map allows the specified privilege on the
 2852  *      entire address region given.  The entire region must be allocated.
 2853  *
 2854  *      WARNING!  This code does not and should not check whether the
 2855  *      contents of the region is accessible.  For example a smaller file
 2856  *      might be mapped into a larger address space.
 2857  *
 2858  *      NOTE!  This code is also called by munmap().
 2859  *
 2860  *      The map must be locked.  A read lock is sufficient.
 2861  */
 2862 boolean_t
 2863 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
 2864                         vm_prot_t protection)
 2865 {
 2866         vm_map_entry_t entry;
 2867         vm_map_entry_t tmp_entry;
 2868 
 2869         if (!vm_map_lookup_entry(map, start, &tmp_entry))
 2870                 return (FALSE);
 2871         entry = tmp_entry;
 2872 
 2873         while (start < end) {
 2874                 if (entry == &map->header)
 2875                         return (FALSE);
 2876                 /*
 2877                  * No holes allowed!
 2878                  */
 2879                 if (start < entry->start)
 2880                         return (FALSE);
 2881                 /*
 2882                  * Check protection associated with entry.
 2883                  */
 2884                 if ((entry->protection & protection) != protection)
 2885                         return (FALSE);
 2886                 /* go to next entry */
 2887                 start = entry->end;
 2888                 entry = entry->next;
 2889         }
 2890         return (TRUE);
 2891 }
 2892 
 2893 /*
 2894  *      vm_map_copy_entry:
 2895  *
 2896  *      Copies the contents of the source entry to the destination
 2897  *      entry.  The entries *must* be aligned properly.
 2898  */
 2899 static void
 2900 vm_map_copy_entry(
 2901         vm_map_t src_map,
 2902         vm_map_t dst_map,
 2903         vm_map_entry_t src_entry,
 2904         vm_map_entry_t dst_entry,
 2905         vm_ooffset_t *fork_charge)
 2906 {
 2907         vm_object_t src_object;
 2908         vm_offset_t size;
 2909         struct uidinfo *uip;
 2910         int charged;
 2911 
 2912         VM_MAP_ASSERT_LOCKED(dst_map);
 2913 
 2914         if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
 2915                 return;
 2916 
 2917         if (src_entry->wired_count == 0) {
 2918 
 2919                 /*
 2920                  * If the source entry is marked needs_copy, it is already
 2921                  * write-protected.
 2922                  */
 2923                 if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
 2924                         pmap_protect(src_map->pmap,
 2925                             src_entry->start,
 2926                             src_entry->end,
 2927                             src_entry->protection & ~VM_PROT_WRITE);
 2928                 }
 2929 
 2930                 /*
 2931                  * Make a copy of the object.
 2932                  */
 2933                 size = src_entry->end - src_entry->start;
 2934                 if ((src_object = src_entry->object.vm_object) != NULL) {
 2935                         VM_OBJECT_LOCK(src_object);
 2936                         charged = ENTRY_CHARGED(src_entry);
 2937                         if ((src_object->handle == NULL) &&
 2938                                 (src_object->type == OBJT_DEFAULT ||
 2939                                  src_object->type == OBJT_SWAP)) {
 2940                                 vm_object_collapse(src_object);
 2941                                 if ((src_object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
 2942                                         vm_object_split(src_entry);
 2943                                         src_object = src_entry->object.vm_object;
 2944                                 }
 2945                         }
 2946                         vm_object_reference_locked(src_object);
 2947                         vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
 2948                         if (src_entry->uip != NULL &&
 2949                             !(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
 2950                                 KASSERT(src_object->uip == NULL,
 2951                                     ("OVERCOMMIT: vm_map_copy_entry: uip %p",
 2952                                      src_object));
 2953                                 src_object->uip = src_entry->uip;
 2954                                 src_object->charge = size;
 2955                         }
 2956                         VM_OBJECT_UNLOCK(src_object);
 2957                         dst_entry->object.vm_object = src_object;
 2958                         if (charged) {
 2959                                 uip = curthread->td_ucred->cr_ruidinfo;
 2960                                 uihold(uip);
 2961                                 dst_entry->uip = uip;
 2962                                 *fork_charge += size;
 2963                                 if (!(src_entry->eflags &
 2964                                       MAP_ENTRY_NEEDS_COPY)) {
 2965                                         uihold(uip);
 2966                                         src_entry->uip = uip;
 2967                                         *fork_charge += size;
 2968                                 }
 2969                         }
 2970                         src_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
 2971                         dst_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
 2972                         dst_entry->offset = src_entry->offset;
 2973                 } else {
 2974                         dst_entry->object.vm_object = NULL;
 2975                         dst_entry->offset = 0;
 2976                         if (src_entry->uip != NULL) {
 2977                                 dst_entry->uip = curthread->td_ucred->cr_ruidinfo;
 2978                                 uihold(dst_entry->uip);
 2979                                 *fork_charge += size;
 2980                         }
 2981                 }
 2982 
 2983                 pmap_copy(dst_map->pmap, src_map->pmap, dst_entry->start,
 2984                     dst_entry->end - dst_entry->start, src_entry->start);
 2985         } else {
 2986                 /*
 2987                  * Of course, wired down pages can't be set copy-on-write.
 2988                  * Cause wired pages to be copied into the new map by
 2989                  * simulating faults (the new pages are pageable)
 2990                  */
 2991                 vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry,
 2992                     fork_charge);
 2993         }
 2994 }
 2995 
 2996 /*
 2997  * vmspace_map_entry_forked:
 2998  * Update the newly-forked vmspace each time a map entry is inherited
 2999  * or copied.  The values for vm_dsize and vm_tsize are approximate
 3000  * (and mostly-obsolete ideas in the face of mmap(2) et al.)
 3001  */
 3002 static void
 3003 vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
 3004     vm_map_entry_t entry)
 3005 {
 3006         vm_size_t entrysize;
 3007         vm_offset_t newend;
 3008 
 3009         entrysize = entry->end - entry->start;
 3010         vm2->vm_map.size += entrysize;
 3011         if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
 3012                 vm2->vm_ssize += btoc(entrysize);
 3013         } else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
 3014             entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
 3015                 newend = MIN(entry->end,
 3016                     (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
 3017                 vm2->vm_dsize += btoc(newend - entry->start);
 3018         } else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
 3019             entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
 3020                 newend = MIN(entry->end,
 3021                     (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
 3022                 vm2->vm_tsize += btoc(newend - entry->start);
 3023         }
 3024 }
 3025 
 3026 /*
 3027  * vmspace_fork:
 3028  * Create a new process vmspace structure and vm_map
 3029  * based on those of an existing process.  The new map
 3030  * is based on the old map, according to the inheritance
 3031  * values on the regions in that map.
 3032  *
 3033  * XXX It might be worth coalescing the entries added to the new vmspace.
 3034  *
 3035  * The source map must not be locked.
 3036  */
 3037 struct vmspace *
 3038 vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
 3039 {
 3040         struct vmspace *vm2;
 3041         vm_map_t old_map = &vm1->vm_map;
 3042         vm_map_t new_map;
 3043         vm_map_entry_t old_entry;
 3044         vm_map_entry_t new_entry;
 3045         vm_object_t object;
 3046         int locked;
 3047 
 3048         vm_map_lock(old_map);
 3049         if (old_map->busy)
 3050                 vm_map_wait_busy(old_map);
 3051         vm2 = vmspace_alloc(old_map->min_offset, old_map->max_offset);
 3052         if (vm2 == NULL)
 3053                 goto unlock_and_return;
 3054         vm2->vm_taddr = vm1->vm_taddr;
 3055         vm2->vm_daddr = vm1->vm_daddr;
 3056         vm2->vm_maxsaddr = vm1->vm_maxsaddr;
 3057         new_map = &vm2->vm_map; /* XXX */
 3058         locked = vm_map_trylock(new_map); /* trylock to silence WITNESS */
 3059         KASSERT(locked, ("vmspace_fork: lock failed"));
 3060         new_map->timestamp = 1;
 3061 
 3062         old_entry = old_map->header.next;
 3063 
 3064         while (old_entry != &old_map->header) {
 3065                 if (old_entry->eflags & MAP_ENTRY_IS_SUB_MAP)
 3066                         panic("vm_map_fork: encountered a submap");
 3067 
 3068                 switch (old_entry->inheritance) {
 3069                 case VM_INHERIT_NONE:
 3070                         break;
 3071 
 3072                 case VM_INHERIT_SHARE:
 3073                         /*
 3074                          * Clone the entry, creating the shared object if necessary.
 3075                          */
 3076                         object = old_entry->object.vm_object;
 3077                         if (object == NULL) {
 3078                                 object = vm_object_allocate(OBJT_DEFAULT,
 3079                                         atop(old_entry->end - old_entry->start));
 3080                                 old_entry->object.vm_object = object;
 3081                                 old_entry->offset = 0;
 3082                                 if (old_entry->uip != NULL) {
 3083                                         object->uip = old_entry->uip;
 3084                                         object->charge = old_entry->end -
 3085                                             old_entry->start;
 3086                                         old_entry->uip = NULL;
 3087                                 }
 3088                         }
 3089 
 3090                         /*
 3091                          * Add the reference before calling vm_object_shadow
 3092                          * to insure that a shadow object is created.
 3093                          */
 3094                         vm_object_reference(object);
 3095                         if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
 3096                                 vm_object_shadow(&old_entry->object.vm_object,
 3097                                         &old_entry->offset,
 3098                                         atop(old_entry->end - old_entry->start));
 3099                                 old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
 3100                                 /* Transfer the second reference too. */
 3101                                 vm_object_reference(
 3102                                     old_entry->object.vm_object);
 3103 
 3104                                 /*
 3105                                  * As in vm_map_simplify_entry(), the
 3106                                  * vnode lock will not be acquired in
 3107                                  * this call to vm_object_deallocate().
 3108                                  */
 3109                                 vm_object_deallocate(object);
 3110                                 object = old_entry->object.vm_object;
 3111                         }
 3112                         VM_OBJECT_LOCK(object);
 3113                         vm_object_clear_flag(object, OBJ_ONEMAPPING);
 3114                         if (old_entry->uip != NULL) {
 3115                                 KASSERT(object->uip == NULL, ("vmspace_fork both uip"));
 3116                                 object->uip = old_entry->uip;
 3117                                 object->charge = old_entry->end - old_entry->start;
 3118                                 old_entry->uip = NULL;
 3119                         }
 3120                         VM_OBJECT_UNLOCK(object);
 3121 
 3122                         /*
 3123                          * Clone the entry, referencing the shared object.
 3124                          */
 3125                         new_entry = vm_map_entry_create(new_map);
 3126                         *new_entry = *old_entry;
 3127                         new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
 3128                             MAP_ENTRY_IN_TRANSITION);
 3129                         new_entry->wired_count = 0;
 3130 
 3131                         /*
 3132                          * Insert the entry into the new map -- we know we're
 3133                          * inserting at the end of the new map.
 3134                          */
 3135                         vm_map_entry_link(new_map, new_map->header.prev,
 3136                             new_entry);
 3137                         vmspace_map_entry_forked(vm1, vm2, new_entry);
 3138 
 3139                         /*
 3140                          * Update the physical map
 3141                          */
 3142                         pmap_copy(new_map->pmap, old_map->pmap,
 3143                             new_entry->start,
 3144                             (old_entry->end - old_entry->start),
 3145                             old_entry->start);
 3146                         break;
 3147 
 3148                 case VM_INHERIT_COPY:
 3149                         /*
 3150                          * Clone the entry and link into the map.
 3151                          */
 3152                         new_entry = vm_map_entry_create(new_map);
 3153                         *new_entry = *old_entry;
 3154                         new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
 3155                             MAP_ENTRY_IN_TRANSITION);
 3156                         new_entry->wired_count = 0;
 3157                         new_entry->object.vm_object = NULL;
 3158                         new_entry->uip = NULL;
 3159                         vm_map_entry_link(new_map, new_map->header.prev,
 3160                             new_entry);
 3161                         vmspace_map_entry_forked(vm1, vm2, new_entry);
 3162                         vm_map_copy_entry(old_map, new_map, old_entry,
 3163                             new_entry, fork_charge);
 3164                         break;
 3165                 }
 3166                 old_entry = old_entry->next;
 3167         }
 3168 unlock_and_return:
 3169         vm_map_unlock(old_map);
 3170         if (vm2 != NULL)
 3171                 vm_map_unlock(new_map);
 3172 
 3173         return (vm2);
 3174 }
 3175 
 3176 int
 3177 vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
 3178     vm_prot_t prot, vm_prot_t max, int cow)
 3179 {
 3180         vm_map_entry_t new_entry, prev_entry;
 3181         vm_offset_t bot, top;
 3182         vm_size_t growsize, init_ssize;
 3183         int orient, rv;
 3184         rlim_t vmemlim;
 3185 
 3186         /*
 3187          * The stack orientation is piggybacked with the cow argument.
 3188          * Extract it into orient and mask the cow argument so that we
 3189          * don't pass it around further.
 3190          * NOTE: We explicitly allow bi-directional stacks.
 3191          */
 3192         orient = cow & (MAP_STACK_GROWS_DOWN|MAP_STACK_GROWS_UP);
 3193         KASSERT(orient != 0, ("No stack grow direction"));
 3194 
 3195         if (addrbos < vm_map_min(map) ||
 3196             addrbos > vm_map_max(map) ||
 3197             addrbos + max_ssize < addrbos)
 3198                 return (KERN_NO_SPACE);
 3199 
 3200         growsize = sgrowsiz;
 3201         init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
 3202 
 3203         PROC_LOCK(curthread->td_proc);
 3204         vmemlim = lim_cur(curthread->td_proc, RLIMIT_VMEM);
 3205         PROC_UNLOCK(curthread->td_proc);
 3206 
 3207         vm_map_lock(map);
 3208 
 3209         /* If addr is already mapped, no go */
 3210         if (vm_map_lookup_entry(map, addrbos, &prev_entry)) {
 3211                 vm_map_unlock(map);
 3212                 return (KERN_NO_SPACE);
 3213         }
 3214 
 3215         /* If we would blow our VMEM resource limit, no go */
 3216         if (map->size + init_ssize > vmemlim) {
 3217                 vm_map_unlock(map);
 3218                 return (KERN_NO_SPACE);
 3219         }
 3220 
 3221         /*
 3222          * If we can't accomodate max_ssize in the current mapping, no go.
 3223          * However, we need to be aware that subsequent user mappings might
 3224          * map into the space we have reserved for stack, and currently this
 3225          * space is not protected.
 3226          *
 3227          * Hopefully we will at least detect this condition when we try to
 3228          * grow the stack.
 3229          */
 3230         if ((prev_entry->next != &map->header) &&
 3231             (prev_entry->next->start < addrbos + max_ssize)) {
 3232                 vm_map_unlock(map);
 3233                 return (KERN_NO_SPACE);
 3234         }
 3235 
 3236         /*
 3237          * We initially map a stack of only init_ssize.  We will grow as
 3238          * needed later.  Depending on the orientation of the stack (i.e.
 3239          * the grow direction) we either map at the top of the range, the
 3240          * bottom of the range or in the middle.
 3241          *
 3242          * Note: we would normally expect prot and max to be VM_PROT_ALL,
 3243          * and cow to be 0.  Possibly we should eliminate these as input
 3244          * parameters, and just pass these values here in the insert call.
 3245          */
 3246         if (orient == MAP_STACK_GROWS_DOWN)
 3247                 bot = addrbos + max_ssize - init_ssize;
 3248         else if (orient == MAP_STACK_GROWS_UP)
 3249                 bot = addrbos;
 3250         else
 3251                 bot = round_page(addrbos + max_ssize/2 - init_ssize/2);
 3252         top = bot + init_ssize;
 3253         rv = vm_map_insert(map, NULL, 0, bot, top, prot, max, cow);
 3254 
 3255         /* Now set the avail_ssize amount. */
 3256         if (rv == KERN_SUCCESS) {
 3257                 if (prev_entry != &map->header)
 3258                         vm_map_clip_end(map, prev_entry, bot);
 3259                 new_entry = prev_entry->next;
 3260                 if (new_entry->end != top || new_entry->start != bot)
 3261                         panic("Bad entry start/end for new stack entry");
 3262 
 3263                 new_entry->avail_ssize = max_ssize - init_ssize;
 3264                 if (orient & MAP_STACK_GROWS_DOWN)
 3265                         new_entry->eflags |= MAP_ENTRY_GROWS_DOWN;
 3266                 if (orient & MAP_STACK_GROWS_UP)
 3267                         new_entry->eflags |= MAP_ENTRY_GROWS_UP;
 3268         }
 3269 
 3270         vm_map_unlock(map);
 3271         return (rv);
 3272 }
 3273 
 3274 static int stack_guard_page = 0;
 3275 TUNABLE_INT("security.bsd.stack_guard_page", &stack_guard_page);
 3276 SYSCTL_INT(_security_bsd, OID_AUTO, stack_guard_page, CTLFLAG_RW,
 3277     &stack_guard_page, 0,
 3278     "Insert stack guard page ahead of the growable segments.");
 3279 
 3280 /* Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if the
 3281  * desired address is already mapped, or if we successfully grow
 3282  * the stack.  Also returns KERN_SUCCESS if addr is outside the
 3283  * stack range (this is strange, but preserves compatibility with
 3284  * the grow function in vm_machdep.c).
 3285  */
 3286 int
 3287 vm_map_growstack(struct proc *p, vm_offset_t addr)
 3288 {
 3289         vm_map_entry_t next_entry, prev_entry;
 3290         vm_map_entry_t new_entry, stack_entry;
 3291         struct vmspace *vm = p->p_vmspace;
 3292         vm_map_t map = &vm->vm_map;
 3293         vm_offset_t end;
 3294         vm_size_t growsize;
 3295         size_t grow_amount, max_grow;
 3296         rlim_t stacklim, vmemlim;
 3297         int is_procstack, rv;
 3298         struct uidinfo *uip;
 3299 
 3300 Retry:
 3301         PROC_LOCK(p);
 3302         stacklim = lim_cur(p, RLIMIT_STACK);
 3303         vmemlim = lim_cur(p, RLIMIT_VMEM);
 3304         PROC_UNLOCK(p);
 3305 
 3306         vm_map_lock_read(map);
 3307 
 3308         /* If addr is already in the entry range, no need to grow.*/
 3309         if (vm_map_lookup_entry(map, addr, &prev_entry)) {
 3310                 vm_map_unlock_read(map);
 3311                 return (KERN_SUCCESS);
 3312         }
 3313 
 3314         next_entry = prev_entry->next;
 3315         if (!(prev_entry->eflags & MAP_ENTRY_GROWS_UP)) {
 3316                 /*
 3317                  * This entry does not grow upwards. Since the address lies
 3318                  * beyond this entry, the next entry (if one exists) has to
 3319                  * be a downward growable entry. The entry list header is
 3320                  * never a growable entry, so it suffices to check the flags.
 3321                  */
 3322                 if (!(next_entry->eflags & MAP_ENTRY_GROWS_DOWN)) {
 3323                         vm_map_unlock_read(map);
 3324                         return (KERN_SUCCESS);
 3325                 }
 3326                 stack_entry = next_entry;
 3327         } else {
 3328                 /*
 3329                  * This entry grows upward. If the next entry does not at
 3330                  * least grow downwards, this is the entry we need to grow.
 3331                  * otherwise we have two possible choices and we have to
 3332                  * select one.
 3333                  */
 3334                 if (next_entry->eflags & MAP_ENTRY_GROWS_DOWN) {
 3335                         /*
 3336                          * We have two choices; grow the entry closest to
 3337                          * the address to minimize the amount of growth.
 3338                          */
 3339                         if (addr - prev_entry->end <= next_entry->start - addr)
 3340                                 stack_entry = prev_entry;
 3341                         else
 3342                                 stack_entry = next_entry;
 3343                 } else
 3344                         stack_entry = prev_entry;
 3345         }
 3346 
 3347         if (stack_entry == next_entry) {
 3348                 KASSERT(stack_entry->eflags & MAP_ENTRY_GROWS_DOWN, ("foo"));
 3349                 KASSERT(addr < stack_entry->start, ("foo"));
 3350                 end = (prev_entry != &map->header) ? prev_entry->end :
 3351                     stack_entry->start - stack_entry->avail_ssize;
 3352                 grow_amount = roundup(stack_entry->start - addr, PAGE_SIZE);
 3353                 max_grow = stack_entry->start - end;
 3354         } else {
 3355                 KASSERT(stack_entry->eflags & MAP_ENTRY_GROWS_UP, ("foo"));
 3356                 KASSERT(addr >= stack_entry->end, ("foo"));
 3357                 end = (next_entry != &map->header) ? next_entry->start :
 3358                     stack_entry->end + stack_entry->avail_ssize;
 3359                 grow_amount = roundup(addr + 1 - stack_entry->end, PAGE_SIZE);
 3360                 max_grow = end - stack_entry->end;
 3361         }
 3362 
 3363         if (grow_amount > stack_entry->avail_ssize) {
 3364                 vm_map_unlock_read(map);
 3365                 return (KERN_NO_SPACE);
 3366         }
 3367 
 3368         /*
 3369          * If there is no longer enough space between the entries nogo, and
 3370          * adjust the available space.  Note: this  should only happen if the
 3371          * user has mapped into the stack area after the stack was created,
 3372          * and is probably an error.
 3373          *
 3374          * This also effectively destroys any guard page the user might have
 3375          * intended by limiting the stack size.
 3376          */
 3377         if (grow_amount + (stack_guard_page ? PAGE_SIZE : 0) > max_grow) {
 3378                 if (vm_map_lock_upgrade(map))
 3379                         goto Retry;
 3380 
 3381                 stack_entry->avail_ssize = max_grow;
 3382 
 3383                 vm_map_unlock(map);
 3384                 return (KERN_NO_SPACE);
 3385         }
 3386 
 3387         is_procstack = (addr >= (vm_offset_t)vm->vm_maxsaddr) ? 1 : 0;
 3388 
 3389         /*
 3390          * If this is the main process stack, see if we're over the stack
 3391          * limit.
 3392          */
 3393         if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
 3394                 vm_map_unlock_read(map);
 3395                 return (KERN_NO_SPACE);
 3396         }
 3397 
 3398         /* Round up the grow amount modulo sgrowsiz */
 3399         growsize = sgrowsiz;
 3400         grow_amount = roundup(grow_amount, growsize);
 3401         if (grow_amount > stack_entry->avail_ssize)
 3402                 grow_amount = stack_entry->avail_ssize;
 3403         if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
 3404                 grow_amount = trunc_page((vm_size_t)stacklim) -
 3405                     ctob(vm->vm_ssize);
 3406         }
 3407 
 3408         /* If we would blow our VMEM resource limit, no go */
 3409         if (map->size + grow_amount > vmemlim) {
 3410                 vm_map_unlock_read(map);
 3411                 return (KERN_NO_SPACE);
 3412         }
 3413 
 3414         if (vm_map_lock_upgrade(map))
 3415                 goto Retry;
 3416 
 3417         if (stack_entry == next_entry) {
 3418                 /*
 3419                  * Growing downward.
 3420                  */
 3421                 /* Get the preliminary new entry start value */
 3422                 addr = stack_entry->start - grow_amount;
 3423 
 3424                 /*
 3425                  * If this puts us into the previous entry, cut back our
 3426                  * growth to the available space. Also, see the note above.
 3427                  */
 3428                 if (addr < end) {
 3429                         stack_entry->avail_ssize = max_grow;
 3430                         addr = end;
 3431                         if (stack_guard_page)
 3432                                 addr += PAGE_SIZE;
 3433                 }
 3434 
 3435                 rv = vm_map_insert(map, NULL, 0, addr, stack_entry->start,
 3436                     p->p_sysent->sv_stackprot, VM_PROT_ALL, 0);
 3437 
 3438                 /* Adjust the available stack space by the amount we grew. */
 3439                 if (rv == KERN_SUCCESS) {
 3440                         if (prev_entry != &map->header)
 3441                                 vm_map_clip_end(map, prev_entry, addr);
 3442                         new_entry = prev_entry->next;
 3443                         KASSERT(new_entry == stack_entry->prev, ("foo"));
 3444                         KASSERT(new_entry->end == stack_entry->start, ("foo"));
 3445                         KASSERT(new_entry->start == addr, ("foo"));
 3446                         grow_amount = new_entry->end - new_entry->start;
 3447                         new_entry->avail_ssize = stack_entry->avail_ssize -
 3448                             grow_amount;
 3449                         stack_entry->eflags &= ~MAP_ENTRY_GROWS_DOWN;
 3450                         new_entry->eflags |= MAP_ENTRY_GROWS_DOWN;
 3451                 }
 3452         } else {
 3453                 /*
 3454                  * Growing upward.
 3455                  */
 3456                 addr = stack_entry->end + grow_amount;
 3457 
 3458                 /*
 3459                  * If this puts us into the next entry, cut back our growth
 3460                  * to the available space. Also, see the note above.
 3461                  */
 3462                 if (addr > end) {
 3463                         stack_entry->avail_ssize = end - stack_entry->end;
 3464                         addr = end;
 3465                         if (stack_guard_page)
 3466                                 addr -= PAGE_SIZE;
 3467                 }
 3468 
 3469                 grow_amount = addr - stack_entry->end;
 3470                 uip = stack_entry->uip;
 3471                 if (uip == NULL && stack_entry->object.vm_object != NULL)
 3472                         uip = stack_entry->object.vm_object->uip;
 3473                 if (uip != NULL && !swap_reserve_by_uid(grow_amount, uip))
 3474                         rv = KERN_NO_SPACE;
 3475                 /* Grow the underlying object if applicable. */
 3476                 else if (stack_entry->object.vm_object == NULL ||
 3477                          vm_object_coalesce(stack_entry->object.vm_object,
 3478                          stack_entry->offset,
 3479                          (vm_size_t)(stack_entry->end - stack_entry->start),
 3480                          (vm_size_t)grow_amount, uip != NULL)) {
 3481                         map->size += (addr - stack_entry->end);
 3482                         /* Update the current entry. */
 3483                         stack_entry->end = addr;
 3484                         stack_entry->avail_ssize -= grow_amount;
 3485                         vm_map_entry_resize_free(map, stack_entry);
 3486                         rv = KERN_SUCCESS;
 3487 
 3488                         if (next_entry != &map->header)
 3489                                 vm_map_clip_start(map, next_entry, addr);
 3490                 } else
 3491                         rv = KERN_FAILURE;
 3492         }
 3493 
 3494         if (rv == KERN_SUCCESS && is_procstack)
 3495                 vm->vm_ssize += btoc(grow_amount);
 3496 
 3497         vm_map_unlock(map);
 3498 
 3499         /*
 3500          * Heed the MAP_WIREFUTURE flag if it was set for this process.
 3501          */
 3502         if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE)) {
 3503                 vm_map_wire(map,
 3504                     (stack_entry == next_entry) ? addr : addr - grow_amount,
 3505                     (stack_entry == next_entry) ? stack_entry->start : addr,
 3506                     (p->p_flag & P_SYSTEM)
 3507                     ? VM_MAP_WIRE_SYSTEM|VM_MAP_WIRE_NOHOLES
 3508                     : VM_MAP_WIRE_USER|VM_MAP_WIRE_NOHOLES);
 3509         }
 3510 
 3511         return (rv);
 3512 }
 3513 
 3514 /*
 3515  * Unshare the specified VM space for exec.  If other processes are
 3516  * mapped to it, then create a new one.  The new vmspace is null.
 3517  */
 3518 int
 3519 vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
 3520 {
 3521         struct vmspace *oldvmspace = p->p_vmspace;
 3522         struct vmspace *newvmspace;
 3523 
 3524         KASSERT((curthread->td_pflags & TDP_EXECVMSPC) == 0,
 3525             ("vmspace_exec recursed"));
 3526         newvmspace = vmspace_alloc(minuser, maxuser);
 3527         if (newvmspace == NULL)
 3528                 return (ENOMEM);
 3529         newvmspace->vm_swrss = oldvmspace->vm_swrss;
 3530         /*
 3531          * This code is written like this for prototype purposes.  The
 3532          * goal is to avoid running down the vmspace here, but let the
 3533          * other process's that are still using the vmspace to finally
 3534          * run it down.  Even though there is little or no chance of blocking
 3535          * here, it is a good idea to keep this form for future mods.
 3536          */
 3537         PROC_VMSPACE_LOCK(p);
 3538         p->p_vmspace = newvmspace;
 3539         PROC_VMSPACE_UNLOCK(p);
 3540         if (p == curthread->td_proc)
 3541                 pmap_activate(curthread);
 3542         curthread->td_pflags |= TDP_EXECVMSPC;
 3543         return (0);
 3544 }
 3545 
 3546 /*
 3547  * Unshare the specified VM space for forcing COW.  This
 3548  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
 3549  */
 3550 int
 3551 vmspace_unshare(struct proc *p)
 3552 {
 3553         struct vmspace *oldvmspace = p->p_vmspace;
 3554         struct vmspace *newvmspace;
 3555         vm_ooffset_t fork_charge;
 3556 
 3557         if (oldvmspace->vm_refcnt == 1)
 3558                 return (0);
 3559         fork_charge = 0;
 3560         newvmspace = vmspace_fork(oldvmspace, &fork_charge);
 3561         if (newvmspace == NULL)
 3562                 return (ENOMEM);
 3563         if (!swap_reserve_by_uid(fork_charge, p->p_ucred->cr_ruidinfo)) {
 3564                 vmspace_free(newvmspace);
 3565                 return (ENOMEM);
 3566         }
 3567         PROC_VMSPACE_LOCK(p);
 3568         p->p_vmspace = newvmspace;
 3569         PROC_VMSPACE_UNLOCK(p);
 3570         if (p == curthread->td_proc)
 3571                 pmap_activate(curthread);
 3572         vmspace_free(oldvmspace);
 3573         return (0);
 3574 }
 3575 
 3576 /*
 3577  *      vm_map_lookup:
 3578  *
 3579  *      Finds the VM object, offset, and
 3580  *      protection for a given virtual address in the
 3581  *      specified map, assuming a page fault of the
 3582  *      type specified.
 3583  *
 3584  *      Leaves the map in question locked for read; return
 3585  *      values are guaranteed until a vm_map_lookup_done
 3586  *      call is performed.  Note that the map argument
 3587  *      is in/out; the returned map must be used in
 3588  *      the call to vm_map_lookup_done.
 3589  *
 3590  *      A handle (out_entry) is returned for use in
 3591  *      vm_map_lookup_done, to make that fast.
 3592  *
 3593  *      If a lookup is requested with "write protection"
 3594  *      specified, the map may be changed to perform virtual
 3595  *      copying operations, although the data referenced will
 3596  *      remain the same.
 3597  */
 3598 int
 3599 vm_map_lookup(vm_map_t *var_map,                /* IN/OUT */
 3600               vm_offset_t vaddr,
 3601               vm_prot_t fault_typea,
 3602               vm_map_entry_t *out_entry,        /* OUT */
 3603               vm_object_t *object,              /* OUT */
 3604               vm_pindex_t *pindex,              /* OUT */
 3605               vm_prot_t *out_prot,              /* OUT */
 3606               boolean_t *wired)                 /* OUT */
 3607 {
 3608         vm_map_entry_t entry;
 3609         vm_map_t map = *var_map;
 3610         vm_prot_t prot;
 3611         vm_prot_t fault_type = fault_typea;
 3612         vm_object_t eobject;
 3613         struct uidinfo *uip;
 3614         vm_ooffset_t size;
 3615 
 3616 RetryLookup:;
 3617 
 3618         vm_map_lock_read(map);
 3619 
 3620         /*
 3621          * Lookup the faulting address.
 3622          */
 3623         if (!vm_map_lookup_entry(map, vaddr, out_entry)) {
 3624                 vm_map_unlock_read(map);
 3625                 return (KERN_INVALID_ADDRESS);
 3626         }
 3627 
 3628         entry = *out_entry;
 3629 
 3630         /*
 3631          * Handle submaps.
 3632          */
 3633         if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
 3634                 vm_map_t old_map = map;
 3635 
 3636                 *var_map = map = entry->object.sub_map;
 3637                 vm_map_unlock_read(old_map);
 3638                 goto RetryLookup;
 3639         }
 3640 
 3641         /*
 3642          * Check whether this task is allowed to have this page.
 3643          * Note the special case for MAP_ENTRY_COW
 3644          * pages with an override.  This is to implement a forced
 3645          * COW for debuggers.
 3646          */
 3647         if (fault_type & VM_PROT_OVERRIDE_WRITE)
 3648                 prot = entry->max_protection;
 3649         else
 3650                 prot = entry->protection;
 3651         fault_type &= (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE);
 3652         if ((fault_type & prot) != fault_type) {
 3653                 vm_map_unlock_read(map);
 3654                 return (KERN_PROTECTION_FAILURE);
 3655         }
 3656         if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
 3657             (entry->eflags & MAP_ENTRY_COW) &&
 3658             (fault_type & VM_PROT_WRITE) &&
 3659             (fault_typea & VM_PROT_OVERRIDE_WRITE) == 0) {
 3660                 vm_map_unlock_read(map);
 3661                 return (KERN_PROTECTION_FAILURE);
 3662         }
 3663 
 3664         /*
 3665          * If this page is not pageable, we have to get it for all possible
 3666          * accesses.
 3667          */
 3668         *wired = (entry->wired_count != 0);
 3669         if (*wired)
 3670                 prot = fault_type = entry->protection;
 3671         size = entry->end - entry->start;
 3672         /*
 3673          * If the entry was copy-on-write, we either ...
 3674          */
 3675         if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
 3676                 /*
 3677                  * If we want to write the page, we may as well handle that
 3678                  * now since we've got the map locked.
 3679                  *
 3680                  * If we don't need to write the page, we just demote the
 3681                  * permissions allowed.
 3682                  */
 3683                 if (fault_type & VM_PROT_WRITE) {
 3684                         /*
 3685                          * Make a new object, and place it in the object
 3686                          * chain.  Note that no new references have appeared
 3687                          * -- one just moved from the map to the new
 3688                          * object.
 3689                          */
 3690                         if (vm_map_lock_upgrade(map))
 3691                                 goto RetryLookup;
 3692 
 3693                         if (entry->uip == NULL) {
 3694                                 /*
 3695                                  * The debugger owner is charged for
 3696                                  * the memory.
 3697                                  */
 3698                                 uip = curthread->td_ucred->cr_ruidinfo;
 3699                                 uihold(uip);
 3700                                 if (!swap_reserve_by_uid(size, uip)) {
 3701                                         uifree(uip);
 3702                                         vm_map_unlock(map);
 3703                                         return (KERN_RESOURCE_SHORTAGE);
 3704                                 }
 3705                                 entry->uip = uip;
 3706                         }
 3707                         vm_object_shadow(
 3708                             &entry->object.vm_object,
 3709                             &entry->offset,
 3710                             atop(size));
 3711                         entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
 3712                         eobject = entry->object.vm_object;
 3713                         if (eobject->uip != NULL) {
 3714                                 /*
 3715                                  * The object was not shadowed.
 3716                                  */
 3717                                 swap_release_by_uid(size, entry->uip);
 3718                                 uifree(entry->uip);
 3719                                 entry->uip = NULL;
 3720                         } else if (entry->uip != NULL) {
 3721                                 VM_OBJECT_LOCK(eobject);
 3722                                 eobject->uip = entry->uip;
 3723                                 eobject->charge = size;
 3724                                 VM_OBJECT_UNLOCK(eobject);
 3725                                 entry->uip = NULL;
 3726                         }
 3727 
 3728                         vm_map_lock_downgrade(map);
 3729                 } else {
 3730                         /*
 3731                          * We're attempting to read a copy-on-write page --
 3732                          * don't allow writes.
 3733                          */
 3734                         prot &= ~VM_PROT_WRITE;
 3735                 }
 3736         }
 3737 
 3738         /*
 3739          * Create an object if necessary.
 3740          */
 3741         if (entry->object.vm_object == NULL &&
 3742             !map->system_map) {
 3743                 if (vm_map_lock_upgrade(map))
 3744                         goto RetryLookup;
 3745                 entry->object.vm_object = vm_object_allocate(OBJT_DEFAULT,
 3746                     atop(size));
 3747                 entry->offset = 0;
 3748                 if (entry->uip != NULL) {
 3749                         VM_OBJECT_LOCK(entry->object.vm_object);
 3750                         entry->object.vm_object->uip = entry->uip;
 3751                         entry->object.vm_object->charge = size;
 3752                         VM_OBJECT_UNLOCK(entry->object.vm_object);
 3753                         entry->uip = NULL;
 3754                 }
 3755                 vm_map_lock_downgrade(map);
 3756         }
 3757 
 3758         /*
 3759          * Return the object/offset from this entry.  If the entry was
 3760          * copy-on-write or empty, it has been fixed up.
 3761          */
 3762         *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
 3763         *object = entry->object.vm_object;
 3764 
 3765         *out_prot = prot;
 3766         return (KERN_SUCCESS);
 3767 }
 3768 
 3769 /*
 3770  *      vm_map_lookup_locked:
 3771  *
 3772  *      Lookup the faulting address.  A version of vm_map_lookup that returns 
 3773  *      KERN_FAILURE instead of blocking on map lock or memory allocation.
 3774  */
 3775 int
 3776 vm_map_lookup_locked(vm_map_t *var_map,         /* IN/OUT */
 3777                      vm_offset_t vaddr,
 3778                      vm_prot_t fault_typea,
 3779                      vm_map_entry_t *out_entry, /* OUT */
 3780                      vm_object_t *object,       /* OUT */
 3781                      vm_pindex_t *pindex,       /* OUT */
 3782                      vm_prot_t *out_prot,       /* OUT */
 3783                      boolean_t *wired)          /* OUT */
 3784 {
 3785         vm_map_entry_t entry;
 3786         vm_map_t map = *var_map;
 3787         vm_prot_t prot;
 3788         vm_prot_t fault_type = fault_typea;
 3789 
 3790         /*
 3791          * Lookup the faulting address.
 3792          */
 3793         if (!vm_map_lookup_entry(map, vaddr, out_entry))
 3794                 return (KERN_INVALID_ADDRESS);
 3795 
 3796         entry = *out_entry;
 3797 
 3798         /*
 3799          * Fail if the entry refers to a submap.
 3800          */
 3801         if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
 3802                 return (KERN_FAILURE);
 3803 
 3804         /*
 3805          * Check whether this task is allowed to have this page.
 3806          * Note the special case for MAP_ENTRY_COW
 3807          * pages with an override.  This is to implement a forced
 3808          * COW for debuggers.
 3809          */
 3810         if (fault_type & VM_PROT_OVERRIDE_WRITE)
 3811                 prot = entry->max_protection;
 3812         else
 3813                 prot = entry->protection;
 3814         fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
 3815         if ((fault_type & prot) != fault_type)
 3816                 return (KERN_PROTECTION_FAILURE);
 3817         if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
 3818             (entry->eflags & MAP_ENTRY_COW) &&
 3819             (fault_type & VM_PROT_WRITE) &&
 3820             (fault_typea & VM_PROT_OVERRIDE_WRITE) == 0)
 3821                 return (KERN_PROTECTION_FAILURE);
 3822 
 3823         /*
 3824          * If this page is not pageable, we have to get it for all possible
 3825          * accesses.
 3826          */
 3827         *wired = (entry->wired_count != 0);
 3828         if (*wired)
 3829                 prot = fault_type = entry->protection;
 3830 
 3831         if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
 3832                 /*
 3833                  * Fail if the entry was copy-on-write for a write fault.
 3834                  */
 3835                 if (fault_type & VM_PROT_WRITE)
 3836                         return (KERN_FAILURE);
 3837                 /*
 3838                  * We're attempting to read a copy-on-write page --
 3839                  * don't allow writes.
 3840                  */
 3841                 prot &= ~VM_PROT_WRITE;
 3842         }
 3843 
 3844         /*
 3845          * Fail if an object should be created.
 3846          */
 3847         if (entry->object.vm_object == NULL && !map->system_map)
 3848                 return (KERN_FAILURE);
 3849 
 3850         /*
 3851          * Return the object/offset from this entry.  If the entry was
 3852          * copy-on-write or empty, it has been fixed up.
 3853          */
 3854         *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
 3855         *object = entry->object.vm_object;
 3856 
 3857         *out_prot = prot;
 3858         return (KERN_SUCCESS);
 3859 }
 3860 
 3861 /*
 3862  *      vm_map_lookup_done:
 3863  *
 3864  *      Releases locks acquired by a vm_map_lookup
 3865  *      (according to the handle returned by that lookup).
 3866  */
 3867 void
 3868 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
 3869 {
 3870         /*
 3871          * Unlock the main-level map
 3872          */
 3873         vm_map_unlock_read(map);
 3874 }
 3875 
 3876 #include "opt_ddb.h"
 3877 #ifdef DDB
 3878 #include <sys/kernel.h>
 3879 
 3880 #include <ddb/ddb.h>
 3881 
 3882 /*
 3883  *      vm_map_print:   [ debug ]
 3884  */
 3885 DB_SHOW_COMMAND(map, vm_map_print)
 3886 {
 3887         static int nlines;
 3888         /* XXX convert args. */
 3889         vm_map_t map = (vm_map_t)addr;
 3890         boolean_t full = have_addr;
 3891 
 3892         vm_map_entry_t entry;
 3893 
 3894         db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
 3895             (void *)map,
 3896             (void *)map->pmap, map->nentries, map->timestamp);
 3897         nlines++;
 3898 
 3899         if (!full && db_indent)
 3900                 return;
 3901 
 3902         db_indent += 2;
 3903         for (entry = map->header.next; entry != &map->header;
 3904             entry = entry->next) {
 3905                 db_iprintf("map entry %p: start=%p, end=%p\n",
 3906                     (void *)entry, (void *)entry->start, (void *)entry->end);
 3907                 nlines++;
 3908                 {
 3909                         static char *inheritance_name[4] =
 3910                         {"share", "copy", "none", "donate_copy"};
 3911 
 3912                         db_iprintf(" prot=%x/%x/%s",
 3913                             entry->protection,
 3914                             entry->max_protection,
 3915                             inheritance_name[(int)(unsigned char)entry->inheritance]);
 3916                         if (entry->wired_count != 0)
 3917                                 db_printf(", wired");
 3918                 }
 3919                 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
 3920                         db_printf(", share=%p, offset=0x%jx\n",
 3921                             (void *)entry->object.sub_map,
 3922                             (uintmax_t)entry->offset);
 3923                         nlines++;
 3924                         if ((entry->prev == &map->header) ||
 3925                             (entry->prev->object.sub_map !=
 3926                                 entry->object.sub_map)) {
 3927                                 db_indent += 2;
 3928                                 vm_map_print((db_expr_t)(intptr_t)
 3929                                              entry->object.sub_map,
 3930                                              full, 0, (char *)0);
 3931                                 db_indent -= 2;
 3932                         }
 3933                 } else {
 3934                         if (entry->uip != NULL)
 3935                                 db_printf(", uip %d", entry->uip->ui_uid);
 3936                         db_printf(", object=%p, offset=0x%jx",
 3937                             (void *)entry->object.vm_object,
 3938                             (uintmax_t)entry->offset);
 3939                         if (entry->object.vm_object && entry->object.vm_object->uip)
 3940                                 db_printf(", obj uip %d charge %jx",
 3941                                     entry->object.vm_object->uip->ui_uid,
 3942                                     (uintmax_t)entry->object.vm_object->charge);
 3943                         if (entry->eflags & MAP_ENTRY_COW)
 3944                                 db_printf(", copy (%s)",
 3945                                     (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
 3946                         db_printf("\n");
 3947                         nlines++;
 3948 
 3949                         if ((entry->prev == &map->header) ||
 3950                             (entry->prev->object.vm_object !=
 3951                                 entry->object.vm_object)) {
 3952                                 db_indent += 2;
 3953                                 vm_object_print((db_expr_t)(intptr_t)
 3954                                                 entry->object.vm_object,
 3955                                                 full, 0, (char *)0);
 3956                                 nlines += 4;
 3957                                 db_indent -= 2;
 3958                         }
 3959                 }
 3960         }
 3961         db_indent -= 2;
 3962         if (db_indent == 0)
 3963                 nlines = 0;
 3964 }
 3965 
 3966 
 3967 DB_SHOW_COMMAND(procvm, procvm)
 3968 {
 3969         struct proc *p;
 3970 
 3971         if (have_addr) {
 3972                 p = (struct proc *) addr;
 3973         } else {
 3974                 p = curproc;
 3975         }
 3976 
 3977         db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
 3978             (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
 3979             (void *)vmspace_pmap(p->p_vmspace));
 3980 
 3981         vm_map_print((db_expr_t)(intptr_t)&p->p_vmspace->vm_map, 1, 0, NULL);
 3982 }
 3983 
 3984 #endif /* DDB */

Cache object: 9fea636e51d74c3e70ab83d274c8bff4


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