2 * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * The Mach Operating System project at Carnegie-Mellon University.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * from: @(#)vm_map.c 8.3 (Berkeley) 1/12/94
37 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38 * All rights reserved.
40 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
42 * Permission to use, copy, modify and distribute this software and
43 * its documentation is hereby granted, provided that both the copyright
44 * notice and this permission notice appear in all copies of the
45 * software, derivative works or modified versions, and any portions
46 * thereof, and that both notices appear in supporting documentation.
48 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
52 * Carnegie Mellon requests users of this software to return to
54 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
55 * School of Computer Science
56 * Carnegie Mellon University
57 * Pittsburgh PA 15213-3890
59 * any improvements or extensions that they make and grant Carnegie the
60 * rights to redistribute these changes.
64 * Virtual memory mapping module.
67 #include <sys/cdefs.h>
68 __FBSDID("$FreeBSD$");
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/kernel.h>
75 #include <sys/mutex.h>
77 #include <sys/vmmeter.h>
79 #include <sys/vnode.h>
80 #include <sys/racct.h>
81 #include <sys/resourcevar.h>
82 #include <sys/rwlock.h>
84 #include <sys/sysctl.h>
85 #include <sys/sysent.h>
89 #include <vm/vm_param.h>
91 #include <vm/vm_map.h>
92 #include <vm/vm_page.h>
93 #include <vm/vm_object.h>
94 #include <vm/vm_pager.h>
95 #include <vm/vm_kern.h>
96 #include <vm/vm_extern.h>
97 #include <vm/vnode_pager.h>
98 #include <vm/swap_pager.h>
102 * Virtual memory maps provide for the mapping, protection,
103 * and sharing of virtual memory objects. In addition,
104 * this module provides for an efficient virtual copy of
105 * memory from one map to another.
107 * Synchronization is required prior to most operations.
109 * Maps consist of an ordered doubly-linked list of simple
110 * entries; a self-adjusting binary search tree of these
111 * entries is used to speed up lookups.
113 * Since portions of maps are specified by start/end addresses,
114 * which may not align with existing map entries, all
115 * routines merely "clip" entries to these start/end values.
116 * [That is, an entry is split into two, bordering at a
117 * start or end value.] Note that these clippings may not
118 * always be necessary (as the two resulting entries are then
119 * not changed); however, the clipping is done for convenience.
121 * As mentioned above, virtual copy operations are performed
122 * by copying VM object references from one map to
123 * another, and then marking both regions as copy-on-write.
126 static struct mtx map_sleep_mtx;
127 static uma_zone_t mapentzone;
128 static uma_zone_t kmapentzone;
129 static uma_zone_t mapzone;
130 static uma_zone_t vmspace_zone;
131 static int vmspace_zinit(void *mem, int size, int flags);
132 static int vm_map_zinit(void *mem, int ize, int flags);
133 static void _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min,
135 static int vm_map_alignspace(vm_map_t map, vm_object_t object,
136 vm_ooffset_t offset, vm_offset_t *addr, vm_size_t length,
137 vm_offset_t max_addr, vm_offset_t alignment);
138 static void vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map);
139 static void vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry);
140 static void vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry);
141 static int vm_map_growstack(vm_map_t map, vm_offset_t addr,
142 vm_map_entry_t gap_entry);
143 static void vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
144 vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags);
146 static void vm_map_zdtor(void *mem, int size, void *arg);
147 static void vmspace_zdtor(void *mem, int size, void *arg);
149 static int vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos,
150 vm_size_t max_ssize, vm_size_t growsize, vm_prot_t prot, vm_prot_t max,
152 static void vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
153 vm_offset_t failed_addr);
155 #define ENTRY_CHARGED(e) ((e)->cred != NULL || \
156 ((e)->object.vm_object != NULL && (e)->object.vm_object->cred != NULL && \
157 !((e)->eflags & MAP_ENTRY_NEEDS_COPY)))
160 * PROC_VMSPACE_{UN,}LOCK() can be a noop as long as vmspaces are type
163 #define PROC_VMSPACE_LOCK(p) do { } while (0)
164 #define PROC_VMSPACE_UNLOCK(p) do { } while (0)
167 * VM_MAP_RANGE_CHECK: [ internal use only ]
169 * Asserts that the starting and ending region
170 * addresses fall within the valid range of the map.
172 #define VM_MAP_RANGE_CHECK(map, start, end) \
174 if (start < vm_map_min(map)) \
175 start = vm_map_min(map); \
176 if (end > vm_map_max(map)) \
177 end = vm_map_max(map); \
185 * Initialize the vm_map module. Must be called before
186 * any other vm_map routines.
188 * Map and entry structures are allocated from the general
189 * purpose memory pool with some exceptions:
191 * - The kernel map and kmem submap are allocated statically.
192 * - Kernel map entries are allocated out of a static pool.
194 * These restrictions are necessary since malloc() uses the
195 * maps and requires map entries.
201 mtx_init(&map_sleep_mtx, "vm map sleep mutex", NULL, MTX_DEF);
202 mapzone = uma_zcreate("MAP", sizeof(struct vm_map), NULL,
208 vm_map_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
209 uma_prealloc(mapzone, MAX_KMAP);
210 kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry),
211 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
212 UMA_ZONE_MTXCLASS | UMA_ZONE_VM);
213 mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry),
214 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
215 vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
221 vmspace_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
225 vmspace_zinit(void *mem, int size, int flags)
229 vm = (struct vmspace *)mem;
231 vm->vm_map.pmap = NULL;
232 (void)vm_map_zinit(&vm->vm_map, sizeof(vm->vm_map), flags);
233 PMAP_LOCK_INIT(vmspace_pmap(vm));
238 vm_map_zinit(void *mem, int size, int flags)
243 memset(map, 0, sizeof(*map));
244 mtx_init(&map->system_mtx, "vm map (system)", NULL, MTX_DEF | MTX_DUPOK);
245 sx_init(&map->lock, "vm map (user)");
251 vmspace_zdtor(void *mem, int size, void *arg)
255 vm = (struct vmspace *)mem;
257 vm_map_zdtor(&vm->vm_map, sizeof(vm->vm_map), arg);
260 vm_map_zdtor(void *mem, int size, void *arg)
265 KASSERT(map->nentries == 0,
266 ("map %p nentries == %d on free.",
267 map, map->nentries));
268 KASSERT(map->size == 0,
269 ("map %p size == %lu on free.",
270 map, (unsigned long)map->size));
272 #endif /* INVARIANTS */
275 * Allocate a vmspace structure, including a vm_map and pmap,
276 * and initialize those structures. The refcnt is set to 1.
278 * If 'pinit' is NULL then the embedded pmap is initialized via pmap_pinit().
281 vmspace_alloc(vm_offset_t min, vm_offset_t max, pmap_pinit_t pinit)
285 vm = uma_zalloc(vmspace_zone, M_WAITOK);
286 KASSERT(vm->vm_map.pmap == NULL, ("vm_map.pmap must be NULL"));
287 if (!pinit(vmspace_pmap(vm))) {
288 uma_zfree(vmspace_zone, vm);
291 CTR1(KTR_VM, "vmspace_alloc: %p", vm);
292 _vm_map_init(&vm->vm_map, vmspace_pmap(vm), min, max);
307 vmspace_container_reset(struct proc *p)
311 racct_set(p, RACCT_DATA, 0);
312 racct_set(p, RACCT_STACK, 0);
313 racct_set(p, RACCT_RSS, 0);
314 racct_set(p, RACCT_MEMLOCK, 0);
315 racct_set(p, RACCT_VMEM, 0);
321 vmspace_dofree(struct vmspace *vm)
324 CTR1(KTR_VM, "vmspace_free: %p", vm);
327 * Make sure any SysV shm is freed, it might not have been in
333 * Lock the map, to wait out all other references to it.
334 * Delete all of the mappings and pages they hold, then call
335 * the pmap module to reclaim anything left.
337 (void)vm_map_remove(&vm->vm_map, vm_map_min(&vm->vm_map),
338 vm_map_max(&vm->vm_map));
340 pmap_release(vmspace_pmap(vm));
341 vm->vm_map.pmap = NULL;
342 uma_zfree(vmspace_zone, vm);
346 vmspace_free(struct vmspace *vm)
349 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
350 "vmspace_free() called");
352 if (vm->vm_refcnt == 0)
353 panic("vmspace_free: attempt to free already freed vmspace");
355 if (atomic_fetchadd_int(&vm->vm_refcnt, -1) == 1)
360 vmspace_exitfree(struct proc *p)
364 PROC_VMSPACE_LOCK(p);
367 PROC_VMSPACE_UNLOCK(p);
368 KASSERT(vm == &vmspace0, ("vmspace_exitfree: wrong vmspace"));
373 vmspace_exit(struct thread *td)
380 * Release user portion of address space.
381 * This releases references to vnodes,
382 * which could cause I/O if the file has been unlinked.
383 * Need to do this early enough that we can still sleep.
385 * The last exiting process to reach this point releases as
386 * much of the environment as it can. vmspace_dofree() is the
387 * slower fallback in case another process had a temporary
388 * reference to the vmspace.
393 atomic_add_int(&vmspace0.vm_refcnt, 1);
394 refcnt = vm->vm_refcnt;
396 if (refcnt > 1 && p->p_vmspace != &vmspace0) {
397 /* Switch now since other proc might free vmspace */
398 PROC_VMSPACE_LOCK(p);
399 p->p_vmspace = &vmspace0;
400 PROC_VMSPACE_UNLOCK(p);
403 } while (!atomic_fcmpset_int(&vm->vm_refcnt, &refcnt, refcnt - 1));
405 if (p->p_vmspace != vm) {
406 /* vmspace not yet freed, switch back */
407 PROC_VMSPACE_LOCK(p);
409 PROC_VMSPACE_UNLOCK(p);
412 pmap_remove_pages(vmspace_pmap(vm));
413 /* Switch now since this proc will free vmspace */
414 PROC_VMSPACE_LOCK(p);
415 p->p_vmspace = &vmspace0;
416 PROC_VMSPACE_UNLOCK(p);
422 vmspace_container_reset(p);
426 /* Acquire reference to vmspace owned by another process. */
429 vmspace_acquire_ref(struct proc *p)
434 PROC_VMSPACE_LOCK(p);
437 PROC_VMSPACE_UNLOCK(p);
440 refcnt = vm->vm_refcnt;
442 if (refcnt <= 0) { /* Avoid 0->1 transition */
443 PROC_VMSPACE_UNLOCK(p);
446 } while (!atomic_fcmpset_int(&vm->vm_refcnt, &refcnt, refcnt + 1));
447 if (vm != p->p_vmspace) {
448 PROC_VMSPACE_UNLOCK(p);
452 PROC_VMSPACE_UNLOCK(p);
457 * Switch between vmspaces in an AIO kernel process.
459 * The AIO kernel processes switch to and from a user process's
460 * vmspace while performing an I/O operation on behalf of a user
461 * process. The new vmspace is either the vmspace of a user process
462 * obtained from an active AIO request or the initial vmspace of the
463 * AIO kernel process (when it is idling). Because user processes
464 * will block to drain any active AIO requests before proceeding in
465 * exit() or execve(), the vmspace reference count for these vmspaces
466 * can never be 0. This allows for a much simpler implementation than
467 * the loop in vmspace_acquire_ref() above. Similarly, AIO kernel
468 * processes hold an extra reference on their initial vmspace for the
469 * life of the process so that this guarantee is true for any vmspace
473 vmspace_switch_aio(struct vmspace *newvm)
475 struct vmspace *oldvm;
477 /* XXX: Need some way to assert that this is an aio daemon. */
479 KASSERT(newvm->vm_refcnt > 0,
480 ("vmspace_switch_aio: newvm unreferenced"));
482 oldvm = curproc->p_vmspace;
487 * Point to the new address space and refer to it.
489 curproc->p_vmspace = newvm;
490 atomic_add_int(&newvm->vm_refcnt, 1);
492 /* Activate the new mapping. */
493 pmap_activate(curthread);
495 /* Remove the daemon's reference to the old address space. */
496 KASSERT(oldvm->vm_refcnt > 1,
497 ("vmspace_switch_aio: oldvm dropping last reference"));
502 _vm_map_lock(vm_map_t map, const char *file, int line)
506 mtx_lock_flags_(&map->system_mtx, 0, file, line);
508 sx_xlock_(&map->lock, file, line);
513 vm_map_process_deferred(void)
516 vm_map_entry_t entry, next;
520 entry = td->td_map_def_user;
521 td->td_map_def_user = NULL;
522 while (entry != NULL) {
524 if ((entry->eflags & MAP_ENTRY_VN_WRITECNT) != 0) {
526 * Decrement the object's writemappings and
527 * possibly the vnode's v_writecount.
529 KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
530 ("Submap with writecount"));
531 object = entry->object.vm_object;
532 KASSERT(object != NULL, ("No object for writecount"));
533 vnode_pager_release_writecount(object, entry->start,
536 vm_map_entry_deallocate(entry, FALSE);
542 _vm_map_unlock(vm_map_t map, const char *file, int line)
546 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
548 sx_xunlock_(&map->lock, file, line);
549 vm_map_process_deferred();
554 _vm_map_lock_read(vm_map_t map, const char *file, int line)
558 mtx_lock_flags_(&map->system_mtx, 0, file, line);
560 sx_slock_(&map->lock, file, line);
564 _vm_map_unlock_read(vm_map_t map, const char *file, int line)
568 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
570 sx_sunlock_(&map->lock, file, line);
571 vm_map_process_deferred();
576 _vm_map_trylock(vm_map_t map, const char *file, int line)
580 error = map->system_map ?
581 !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
582 !sx_try_xlock_(&map->lock, file, line);
589 _vm_map_trylock_read(vm_map_t map, const char *file, int line)
593 error = map->system_map ?
594 !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
595 !sx_try_slock_(&map->lock, file, line);
600 * _vm_map_lock_upgrade: [ internal use only ]
602 * Tries to upgrade a read (shared) lock on the specified map to a write
603 * (exclusive) lock. Returns the value "0" if the upgrade succeeds and a
604 * non-zero value if the upgrade fails. If the upgrade fails, the map is
605 * returned without a read or write lock held.
607 * Requires that the map be read locked.
610 _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
612 unsigned int last_timestamp;
614 if (map->system_map) {
615 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
617 if (!sx_try_upgrade_(&map->lock, file, line)) {
618 last_timestamp = map->timestamp;
619 sx_sunlock_(&map->lock, file, line);
620 vm_map_process_deferred();
622 * If the map's timestamp does not change while the
623 * map is unlocked, then the upgrade succeeds.
625 sx_xlock_(&map->lock, file, line);
626 if (last_timestamp != map->timestamp) {
627 sx_xunlock_(&map->lock, file, line);
637 _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
640 if (map->system_map) {
641 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
643 sx_downgrade_(&map->lock, file, line);
649 * Returns a non-zero value if the caller holds a write (exclusive) lock
650 * on the specified map and the value "0" otherwise.
653 vm_map_locked(vm_map_t map)
657 return (mtx_owned(&map->system_mtx));
659 return (sx_xlocked(&map->lock));
664 _vm_map_assert_locked(vm_map_t map, const char *file, int line)
668 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
670 sx_assert_(&map->lock, SA_XLOCKED, file, line);
673 #define VM_MAP_ASSERT_LOCKED(map) \
674 _vm_map_assert_locked(map, LOCK_FILE, LOCK_LINE)
676 #define VM_MAP_ASSERT_LOCKED(map)
680 * _vm_map_unlock_and_wait:
682 * Atomically releases the lock on the specified map and puts the calling
683 * thread to sleep. The calling thread will remain asleep until either
684 * vm_map_wakeup() is performed on the map or the specified timeout is
687 * WARNING! This function does not perform deferred deallocations of
688 * objects and map entries. Therefore, the calling thread is expected to
689 * reacquire the map lock after reawakening and later perform an ordinary
690 * unlock operation, such as vm_map_unlock(), before completing its
691 * operation on the map.
694 _vm_map_unlock_and_wait(vm_map_t map, int timo, const char *file, int line)
697 mtx_lock(&map_sleep_mtx);
699 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
701 sx_xunlock_(&map->lock, file, line);
702 return (msleep(&map->root, &map_sleep_mtx, PDROP | PVM, "vmmaps",
709 * Awaken any threads that have slept on the map using
710 * vm_map_unlock_and_wait().
713 vm_map_wakeup(vm_map_t map)
717 * Acquire and release map_sleep_mtx to prevent a wakeup()
718 * from being performed (and lost) between the map unlock
719 * and the msleep() in _vm_map_unlock_and_wait().
721 mtx_lock(&map_sleep_mtx);
722 mtx_unlock(&map_sleep_mtx);
727 vm_map_busy(vm_map_t map)
730 VM_MAP_ASSERT_LOCKED(map);
735 vm_map_unbusy(vm_map_t map)
738 VM_MAP_ASSERT_LOCKED(map);
739 KASSERT(map->busy, ("vm_map_unbusy: not busy"));
740 if (--map->busy == 0 && (map->flags & MAP_BUSY_WAKEUP)) {
741 vm_map_modflags(map, 0, MAP_BUSY_WAKEUP);
747 vm_map_wait_busy(vm_map_t map)
750 VM_MAP_ASSERT_LOCKED(map);
752 vm_map_modflags(map, MAP_BUSY_WAKEUP, 0);
754 msleep(&map->busy, &map->system_mtx, 0, "mbusy", 0);
756 sx_sleep(&map->busy, &map->lock, 0, "mbusy", 0);
762 vmspace_resident_count(struct vmspace *vmspace)
764 return pmap_resident_count(vmspace_pmap(vmspace));
770 * Creates and returns a new empty VM map with
771 * the given physical map structure, and having
772 * the given lower and upper address bounds.
775 vm_map_create(pmap_t pmap, vm_offset_t min, vm_offset_t max)
779 result = uma_zalloc(mapzone, M_WAITOK);
780 CTR1(KTR_VM, "vm_map_create: %p", result);
781 _vm_map_init(result, pmap, min, max);
786 * Initialize an existing vm_map structure
787 * such as that in the vmspace structure.
790 _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
793 map->header.next = map->header.prev = &map->header;
794 map->header.eflags = MAP_ENTRY_HEADER;
795 map->needs_wakeup = FALSE;
798 map->header.end = min;
799 map->header.start = max;
808 vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
811 _vm_map_init(map, pmap, min, max);
812 mtx_init(&map->system_mtx, "system map", NULL, MTX_DEF | MTX_DUPOK);
813 sx_init(&map->lock, "user map");
817 * vm_map_entry_dispose: [ internal use only ]
819 * Inverse of vm_map_entry_create.
822 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
824 uma_zfree(map->system_map ? kmapentzone : mapentzone, entry);
828 * vm_map_entry_create: [ internal use only ]
830 * Allocates a VM map entry for insertion.
831 * No entry fields are filled in.
833 static vm_map_entry_t
834 vm_map_entry_create(vm_map_t map)
836 vm_map_entry_t new_entry;
839 new_entry = uma_zalloc(kmapentzone, M_NOWAIT);
841 new_entry = uma_zalloc(mapentzone, M_WAITOK);
842 if (new_entry == NULL)
843 panic("vm_map_entry_create: kernel resources exhausted");
848 * vm_map_entry_set_behavior:
850 * Set the expected access behavior, either normal, random, or
854 vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
856 entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
857 (behavior & MAP_ENTRY_BEHAV_MASK);
861 * vm_map_entry_set_max_free:
863 * Set the max_free field in a vm_map_entry.
866 vm_map_entry_set_max_free(vm_map_entry_t entry)
869 entry->max_free = entry->adj_free;
870 if (entry->left != NULL && entry->left->max_free > entry->max_free)
871 entry->max_free = entry->left->max_free;
872 if (entry->right != NULL && entry->right->max_free > entry->max_free)
873 entry->max_free = entry->right->max_free;
877 * vm_map_entry_splay:
879 * The Sleator and Tarjan top-down splay algorithm with the
880 * following variation. Max_free must be computed bottom-up, so
881 * on the downward pass, maintain the left and right spines in
882 * reverse order. Then, make a second pass up each side to fix
883 * the pointers and compute max_free. The time bound is O(log n)
886 * The new root is the vm_map_entry containing "addr", or else an
887 * adjacent entry (lower or higher) if addr is not in the tree.
889 * The map must be locked, and leaves it so.
891 * Returns: the new root.
893 static vm_map_entry_t
894 vm_map_entry_splay(vm_offset_t addr, vm_map_entry_t root)
896 vm_map_entry_t llist, rlist;
897 vm_map_entry_t ltree, rtree;
900 /* Special case of empty tree. */
905 * Pass One: Splay down the tree until we find addr or a NULL
906 * pointer where addr would go. llist and rlist are the two
907 * sides in reverse order (bottom-up), with llist linked by
908 * the right pointer and rlist linked by the left pointer in
909 * the vm_map_entry. Wait until Pass Two to set max_free on
915 /* root is never NULL in here. */
916 if (addr < root->start) {
920 if (addr < y->start && y->left != NULL) {
921 /* Rotate right and put y on rlist. */
922 root->left = y->right;
924 vm_map_entry_set_max_free(root);
929 /* Put root on rlist. */
934 } else if (addr >= root->end) {
938 if (addr >= y->end && y->right != NULL) {
939 /* Rotate left and put y on llist. */
940 root->right = y->left;
942 vm_map_entry_set_max_free(root);
947 /* Put root on llist. */
957 * Pass Two: Walk back up the two spines, flip the pointers
958 * and set max_free. The subtrees of the root go at the
959 * bottom of llist and rlist.
962 while (llist != NULL) {
964 llist->right = ltree;
965 vm_map_entry_set_max_free(llist);
970 while (rlist != NULL) {
973 vm_map_entry_set_max_free(rlist);
979 * Final assembly: add ltree and rtree as subtrees of root.
983 vm_map_entry_set_max_free(root);
989 * vm_map_entry_{un,}link:
991 * Insert/remove entries from maps.
994 vm_map_entry_link(vm_map_t map,
995 vm_map_entry_t after_where,
996 vm_map_entry_t entry)
1000 "vm_map_entry_link: map %p, nentries %d, entry %p, after %p", map,
1001 map->nentries, entry, after_where);
1002 VM_MAP_ASSERT_LOCKED(map);
1003 KASSERT(after_where->end <= entry->start,
1004 ("vm_map_entry_link: prev end %jx new start %jx overlap",
1005 (uintmax_t)after_where->end, (uintmax_t)entry->start));
1006 KASSERT(entry->end <= after_where->next->start,
1007 ("vm_map_entry_link: new end %jx next start %jx overlap",
1008 (uintmax_t)entry->end, (uintmax_t)after_where->next->start));
1011 entry->prev = after_where;
1012 entry->next = after_where->next;
1013 entry->next->prev = entry;
1014 after_where->next = entry;
1016 if (after_where != &map->header) {
1017 if (after_where != map->root)
1018 vm_map_entry_splay(after_where->start, map->root);
1019 entry->right = after_where->right;
1020 entry->left = after_where;
1021 after_where->right = NULL;
1022 after_where->adj_free = entry->start - after_where->end;
1023 vm_map_entry_set_max_free(after_where);
1025 entry->right = map->root;
1028 entry->adj_free = entry->next->start - entry->end;
1029 vm_map_entry_set_max_free(entry);
1034 vm_map_entry_unlink(vm_map_t map,
1035 vm_map_entry_t entry)
1037 vm_map_entry_t next, prev, root;
1039 VM_MAP_ASSERT_LOCKED(map);
1040 if (entry != map->root)
1041 vm_map_entry_splay(entry->start, map->root);
1042 if (entry->left == NULL)
1043 root = entry->right;
1045 root = vm_map_entry_splay(entry->start, entry->left);
1046 root->right = entry->right;
1047 root->adj_free = entry->next->start - root->end;
1048 vm_map_entry_set_max_free(root);
1057 CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
1058 map->nentries, entry);
1062 * vm_map_entry_resize_free:
1064 * Recompute the amount of free space following a vm_map_entry
1065 * and propagate that value up the tree. Call this function after
1066 * resizing a map entry in-place, that is, without a call to
1067 * vm_map_entry_link() or _unlink().
1069 * The map must be locked, and leaves it so.
1072 vm_map_entry_resize_free(vm_map_t map, vm_map_entry_t entry)
1076 * Using splay trees without parent pointers, propagating
1077 * max_free up the tree is done by moving the entry to the
1078 * root and making the change there.
1080 if (entry != map->root)
1081 map->root = vm_map_entry_splay(entry->start, map->root);
1083 entry->adj_free = entry->next->start - entry->end;
1084 vm_map_entry_set_max_free(entry);
1088 * vm_map_lookup_entry: [ internal use only ]
1090 * Finds the map entry containing (or
1091 * immediately preceding) the specified address
1092 * in the given map; the entry is returned
1093 * in the "entry" parameter. The boolean
1094 * result indicates whether the address is
1095 * actually contained in the map.
1098 vm_map_lookup_entry(
1100 vm_offset_t address,
1101 vm_map_entry_t *entry) /* OUT */
1107 * If the map is empty, then the map entry immediately preceding
1108 * "address" is the map's header.
1112 *entry = &map->header;
1113 else if (address >= cur->start && cur->end > address) {
1116 } else if ((locked = vm_map_locked(map)) ||
1117 sx_try_upgrade(&map->lock)) {
1119 * Splay requires a write lock on the map. However, it only
1120 * restructures the binary search tree; it does not otherwise
1121 * change the map. Thus, the map's timestamp need not change
1122 * on a temporary upgrade.
1124 map->root = cur = vm_map_entry_splay(address, cur);
1126 sx_downgrade(&map->lock);
1129 * If "address" is contained within a map entry, the new root
1130 * is that map entry. Otherwise, the new root is a map entry
1131 * immediately before or after "address".
1133 if (address >= cur->start) {
1135 if (cur->end > address)
1141 * Since the map is only locked for read access, perform a
1142 * standard binary search tree lookup for "address".
1145 if (address < cur->start) {
1146 if (cur->left == NULL) {
1151 } else if (cur->end > address) {
1155 if (cur->right == NULL) {
1168 * Inserts the given whole VM object into the target
1169 * map at the specified address range. The object's
1170 * size should match that of the address range.
1172 * Requires that the map be locked, and leaves it so.
1174 * If object is non-NULL, ref count must be bumped by caller
1175 * prior to making call to account for the new entry.
1178 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1179 vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max, int cow)
1181 vm_map_entry_t new_entry, prev_entry, temp_entry;
1183 vm_eflags_t protoeflags;
1184 vm_inherit_t inheritance;
1186 VM_MAP_ASSERT_LOCKED(map);
1187 KASSERT(object != kernel_object ||
1188 (cow & MAP_COPY_ON_WRITE) == 0,
1189 ("vm_map_insert: kernel object and COW"));
1190 KASSERT(object == NULL || (cow & MAP_NOFAULT) == 0,
1191 ("vm_map_insert: paradoxical MAP_NOFAULT request"));
1192 KASSERT((prot & ~max) == 0,
1193 ("prot %#x is not subset of max_prot %#x", prot, max));
1196 * Check that the start and end points are not bogus.
1198 if (start < vm_map_min(map) || end > vm_map_max(map) ||
1200 return (KERN_INVALID_ADDRESS);
1203 * Find the entry prior to the proposed starting address; if it's part
1204 * of an existing entry, this range is bogus.
1206 if (vm_map_lookup_entry(map, start, &temp_entry))
1207 return (KERN_NO_SPACE);
1209 prev_entry = temp_entry;
1212 * Assert that the next entry doesn't overlap the end point.
1214 if (prev_entry->next->start < end)
1215 return (KERN_NO_SPACE);
1217 if ((cow & MAP_CREATE_GUARD) != 0 && (object != NULL ||
1218 max != VM_PROT_NONE))
1219 return (KERN_INVALID_ARGUMENT);
1222 if (cow & MAP_COPY_ON_WRITE)
1223 protoeflags |= MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY;
1224 if (cow & MAP_NOFAULT)
1225 protoeflags |= MAP_ENTRY_NOFAULT;
1226 if (cow & MAP_DISABLE_SYNCER)
1227 protoeflags |= MAP_ENTRY_NOSYNC;
1228 if (cow & MAP_DISABLE_COREDUMP)
1229 protoeflags |= MAP_ENTRY_NOCOREDUMP;
1230 if (cow & MAP_STACK_GROWS_DOWN)
1231 protoeflags |= MAP_ENTRY_GROWS_DOWN;
1232 if (cow & MAP_STACK_GROWS_UP)
1233 protoeflags |= MAP_ENTRY_GROWS_UP;
1234 if (cow & MAP_VN_WRITECOUNT)
1235 protoeflags |= MAP_ENTRY_VN_WRITECNT;
1236 if ((cow & MAP_CREATE_GUARD) != 0)
1237 protoeflags |= MAP_ENTRY_GUARD;
1238 if ((cow & MAP_CREATE_STACK_GAP_DN) != 0)
1239 protoeflags |= MAP_ENTRY_STACK_GAP_DN;
1240 if ((cow & MAP_CREATE_STACK_GAP_UP) != 0)
1241 protoeflags |= MAP_ENTRY_STACK_GAP_UP;
1242 if (cow & MAP_INHERIT_SHARE)
1243 inheritance = VM_INHERIT_SHARE;
1245 inheritance = VM_INHERIT_DEFAULT;
1248 if ((cow & (MAP_ACC_NO_CHARGE | MAP_NOFAULT | MAP_CREATE_GUARD)) != 0)
1250 if ((cow & MAP_ACC_CHARGED) || ((prot & VM_PROT_WRITE) &&
1251 ((protoeflags & MAP_ENTRY_NEEDS_COPY) || object == NULL))) {
1252 if (!(cow & MAP_ACC_CHARGED) && !swap_reserve(end - start))
1253 return (KERN_RESOURCE_SHORTAGE);
1254 KASSERT(object == NULL ||
1255 (protoeflags & MAP_ENTRY_NEEDS_COPY) != 0 ||
1256 object->cred == NULL,
1257 ("overcommit: vm_map_insert o %p", object));
1258 cred = curthread->td_ucred;
1262 /* Expand the kernel pmap, if necessary. */
1263 if (map == kernel_map && end > kernel_vm_end)
1264 pmap_growkernel(end);
1265 if (object != NULL) {
1267 * OBJ_ONEMAPPING must be cleared unless this mapping
1268 * is trivially proven to be the only mapping for any
1269 * of the object's pages. (Object granularity
1270 * reference counting is insufficient to recognize
1271 * aliases with precision.)
1273 VM_OBJECT_WLOCK(object);
1274 if (object->ref_count > 1 || object->shadow_count != 0)
1275 vm_object_clear_flag(object, OBJ_ONEMAPPING);
1276 VM_OBJECT_WUNLOCK(object);
1277 } else if ((prev_entry->eflags & ~MAP_ENTRY_USER_WIRED) ==
1279 (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 &&
1280 prev_entry->end == start && (prev_entry->cred == cred ||
1281 (prev_entry->object.vm_object != NULL &&
1282 prev_entry->object.vm_object->cred == cred)) &&
1283 vm_object_coalesce(prev_entry->object.vm_object,
1285 (vm_size_t)(prev_entry->end - prev_entry->start),
1286 (vm_size_t)(end - prev_entry->end), cred != NULL &&
1287 (protoeflags & MAP_ENTRY_NEEDS_COPY) == 0)) {
1289 * We were able to extend the object. Determine if we
1290 * can extend the previous map entry to include the
1291 * new range as well.
1293 if (prev_entry->inheritance == inheritance &&
1294 prev_entry->protection == prot &&
1295 prev_entry->max_protection == max &&
1296 prev_entry->wired_count == 0) {
1297 KASSERT((prev_entry->eflags & MAP_ENTRY_USER_WIRED) ==
1298 0, ("prev_entry %p has incoherent wiring",
1300 if ((prev_entry->eflags & MAP_ENTRY_GUARD) == 0)
1301 map->size += end - prev_entry->end;
1302 prev_entry->end = end;
1303 vm_map_entry_resize_free(map, prev_entry);
1304 vm_map_simplify_entry(map, prev_entry);
1305 return (KERN_SUCCESS);
1309 * If we can extend the object but cannot extend the
1310 * map entry, we have to create a new map entry. We
1311 * must bump the ref count on the extended object to
1312 * account for it. object may be NULL.
1314 object = prev_entry->object.vm_object;
1315 offset = prev_entry->offset +
1316 (prev_entry->end - prev_entry->start);
1317 vm_object_reference(object);
1318 if (cred != NULL && object != NULL && object->cred != NULL &&
1319 !(prev_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
1320 /* Object already accounts for this uid. */
1328 * Create a new entry
1330 new_entry = vm_map_entry_create(map);
1331 new_entry->start = start;
1332 new_entry->end = end;
1333 new_entry->cred = NULL;
1335 new_entry->eflags = protoeflags;
1336 new_entry->object.vm_object = object;
1337 new_entry->offset = offset;
1339 new_entry->inheritance = inheritance;
1340 new_entry->protection = prot;
1341 new_entry->max_protection = max;
1342 new_entry->wired_count = 0;
1343 new_entry->wiring_thread = NULL;
1344 new_entry->read_ahead = VM_FAULT_READ_AHEAD_INIT;
1345 new_entry->next_read = start;
1347 KASSERT(cred == NULL || !ENTRY_CHARGED(new_entry),
1348 ("overcommit: vm_map_insert leaks vm_map %p", new_entry));
1349 new_entry->cred = cred;
1352 * Insert the new entry into the list
1354 vm_map_entry_link(map, prev_entry, new_entry);
1355 if ((new_entry->eflags & MAP_ENTRY_GUARD) == 0)
1356 map->size += new_entry->end - new_entry->start;
1359 * Try to coalesce the new entry with both the previous and next
1360 * entries in the list. Previously, we only attempted to coalesce
1361 * with the previous entry when object is NULL. Here, we handle the
1362 * other cases, which are less common.
1364 vm_map_simplify_entry(map, new_entry);
1366 if ((cow & (MAP_PREFAULT | MAP_PREFAULT_PARTIAL)) != 0) {
1367 vm_map_pmap_enter(map, start, prot, object, OFF_TO_IDX(offset),
1368 end - start, cow & MAP_PREFAULT_PARTIAL);
1371 return (KERN_SUCCESS);
1377 * Find the first fit (lowest VM address) for "length" free bytes
1378 * beginning at address >= start in the given map.
1380 * In a vm_map_entry, "adj_free" is the amount of free space
1381 * adjacent (higher address) to this entry, and "max_free" is the
1382 * maximum amount of contiguous free space in its subtree. This
1383 * allows finding a free region in one path down the tree, so
1384 * O(log n) amortized with splay trees.
1386 * The map must be locked, and leaves it so.
1388 * Returns: 0 on success, and starting address in *addr,
1389 * 1 if insufficient space.
1392 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length,
1393 vm_offset_t *addr) /* OUT */
1395 vm_map_entry_t entry;
1399 * Request must fit within min/max VM address and must avoid
1402 start = MAX(start, vm_map_min(map));
1403 if (start + length > vm_map_max(map) || start + length < start)
1406 /* Empty tree means wide open address space. */
1407 if (map->root == NULL) {
1413 * After splay, if start comes before root node, then there
1414 * must be a gap from start to the root.
1416 map->root = vm_map_entry_splay(start, map->root);
1417 if (start + length <= map->root->start) {
1423 * Root is the last node that might begin its gap before
1424 * start, and this is the last comparison where address
1425 * wrap might be a problem.
1427 st = (start > map->root->end) ? start : map->root->end;
1428 if (length <= map->root->end + map->root->adj_free - st) {
1433 /* With max_free, can immediately tell if no solution. */
1434 entry = map->root->right;
1435 if (entry == NULL || length > entry->max_free)
1439 * Search the right subtree in the order: left subtree, root,
1440 * right subtree (first fit). The previous splay implies that
1441 * all regions in the right subtree have addresses > start.
1443 while (entry != NULL) {
1444 if (entry->left != NULL && entry->left->max_free >= length)
1445 entry = entry->left;
1446 else if (entry->adj_free >= length) {
1450 entry = entry->right;
1453 /* Can't get here, so panic if we do. */
1454 panic("vm_map_findspace: max_free corrupt");
1458 vm_map_fixed(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1459 vm_offset_t start, vm_size_t length, vm_prot_t prot,
1460 vm_prot_t max, int cow)
1465 end = start + length;
1466 KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1468 ("vm_map_fixed: non-NULL backing object for stack"));
1470 VM_MAP_RANGE_CHECK(map, start, end);
1471 if ((cow & MAP_CHECK_EXCL) == 0)
1472 vm_map_delete(map, start, end);
1473 if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1474 result = vm_map_stack_locked(map, start, length, sgrowsiz,
1477 result = vm_map_insert(map, object, offset, start, end,
1484 static const int aslr_pages_rnd_64[2] = {0x1000, 0x10};
1485 static const int aslr_pages_rnd_32[2] = {0x100, 0x4};
1487 static int cluster_anon = 1;
1488 SYSCTL_INT(_vm, OID_AUTO, cluster_anon, CTLFLAG_RW,
1490 "Cluster anonymous mappings: 0 = no, 1 = yes if no hint, 2 = always");
1493 clustering_anon_allowed(vm_offset_t addr)
1496 switch (cluster_anon) {
1507 static long aslr_restarts;
1508 SYSCTL_LONG(_vm, OID_AUTO, aslr_restarts, CTLFLAG_RD,
1510 "Number of aslr failures");
1512 #define MAP_32BIT_MAX_ADDR ((vm_offset_t)1 << 31)
1515 * Searches for the specified amount of free space in the given map with the
1516 * specified alignment. Performs an address-ordered, first-fit search from
1517 * the given address "*addr", with an optional upper bound "max_addr". If the
1518 * parameter "alignment" is zero, then the alignment is computed from the
1519 * given (object, offset) pair so as to enable the greatest possible use of
1520 * superpage mappings. Returns KERN_SUCCESS and the address of the free space
1521 * in "*addr" if successful. Otherwise, returns KERN_NO_SPACE.
1523 * The map must be locked. Initially, there must be at least "length" bytes
1524 * of free space at the given address.
1527 vm_map_alignspace(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1528 vm_offset_t *addr, vm_size_t length, vm_offset_t max_addr,
1529 vm_offset_t alignment)
1531 vm_offset_t aligned_addr, free_addr;
1533 VM_MAP_ASSERT_LOCKED(map);
1535 KASSERT(!vm_map_findspace(map, free_addr, length, addr) &&
1536 free_addr == *addr, ("caller provided insufficient free space"));
1539 * At the start of every iteration, the free space at address
1540 * "*addr" is at least "length" bytes.
1543 pmap_align_superpage(object, offset, addr, length);
1544 else if ((*addr & (alignment - 1)) != 0) {
1545 *addr &= ~(alignment - 1);
1548 aligned_addr = *addr;
1549 if (aligned_addr == free_addr) {
1551 * Alignment did not change "*addr", so "*addr" must
1552 * still provide sufficient free space.
1554 return (KERN_SUCCESS);
1558 * Test for address wrap on "*addr". A wrapped "*addr" could
1559 * be a valid address, in which case vm_map_findspace() cannot
1560 * be relied upon to fail.
1562 if (aligned_addr < free_addr ||
1563 vm_map_findspace(map, aligned_addr, length, addr) ||
1564 (max_addr != 0 && *addr + length > max_addr))
1565 return (KERN_NO_SPACE);
1567 if (free_addr == aligned_addr) {
1569 * If a successful call to vm_map_findspace() did not
1570 * change "*addr", then "*addr" must still be aligned
1571 * and provide sufficient free space.
1573 return (KERN_SUCCESS);
1579 * vm_map_find finds an unallocated region in the target address
1580 * map with the given length. The search is defined to be
1581 * first-fit from the specified address; the region found is
1582 * returned in the same parameter.
1584 * If object is non-NULL, ref count must be bumped by caller
1585 * prior to making call to account for the new entry.
1588 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1589 vm_offset_t *addr, /* IN/OUT */
1590 vm_size_t length, vm_offset_t max_addr, int find_space,
1591 vm_prot_t prot, vm_prot_t max, int cow)
1593 vm_offset_t alignment, curr_min_addr, min_addr;
1594 int gap, pidx, rv, try;
1595 bool cluster, en_aslr, update_anon;
1597 KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1599 ("vm_map_find: non-NULL backing object for stack"));
1600 MPASS((cow & MAP_REMAP) == 0 || (find_space == VMFS_NO_SPACE &&
1601 (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0));
1602 if (find_space == VMFS_OPTIMAL_SPACE && (object == NULL ||
1603 (object->flags & OBJ_COLORED) == 0))
1604 find_space = VMFS_ANY_SPACE;
1605 if (find_space >> 8 != 0) {
1606 KASSERT((find_space & 0xff) == 0, ("bad VMFS flags"));
1607 alignment = (vm_offset_t)1 << (find_space >> 8);
1610 en_aslr = (map->flags & MAP_ASLR) != 0;
1611 update_anon = cluster = clustering_anon_allowed(*addr) &&
1612 (map->flags & MAP_IS_SUB_MAP) == 0 && max_addr == 0 &&
1613 find_space != VMFS_NO_SPACE && object == NULL &&
1614 (cow & (MAP_INHERIT_SHARE | MAP_STACK_GROWS_UP |
1615 MAP_STACK_GROWS_DOWN)) == 0 && prot != PROT_NONE;
1616 curr_min_addr = min_addr = *addr;
1617 if (en_aslr && min_addr == 0 && !cluster &&
1618 find_space != VMFS_NO_SPACE &&
1619 (map->flags & MAP_ASLR_IGNSTART) != 0)
1620 curr_min_addr = min_addr = vm_map_min(map);
1624 curr_min_addr = map->anon_loc;
1625 if (curr_min_addr == 0)
1628 if (find_space != VMFS_NO_SPACE) {
1629 KASSERT(find_space == VMFS_ANY_SPACE ||
1630 find_space == VMFS_OPTIMAL_SPACE ||
1631 find_space == VMFS_SUPER_SPACE ||
1632 alignment != 0, ("unexpected VMFS flag"));
1635 * When creating an anonymous mapping, try clustering
1636 * with an existing anonymous mapping first.
1638 * We make up to two attempts to find address space
1639 * for a given find_space value. The first attempt may
1640 * apply randomization or may cluster with an existing
1641 * anonymous mapping. If this first attempt fails,
1642 * perform a first-fit search of the available address
1645 * If all tries failed, and find_space is
1646 * VMFS_OPTIMAL_SPACE, fallback to VMFS_ANY_SPACE.
1647 * Again enable clustering and randomization.
1654 * Second try: we failed either to find a
1655 * suitable region for randomizing the
1656 * allocation, or to cluster with an existing
1657 * mapping. Retry with free run.
1659 curr_min_addr = (map->flags & MAP_ASLR_IGNSTART) != 0 ?
1660 vm_map_min(map) : min_addr;
1661 atomic_add_long(&aslr_restarts, 1);
1664 if (try == 1 && en_aslr && !cluster) {
1666 * Find space for allocation, including
1667 * gap needed for later randomization.
1669 pidx = MAXPAGESIZES > 1 && pagesizes[1] != 0 &&
1670 (find_space == VMFS_SUPER_SPACE || find_space ==
1671 VMFS_OPTIMAL_SPACE) ? 1 : 0;
1672 gap = vm_map_max(map) > MAP_32BIT_MAX_ADDR &&
1673 (max_addr == 0 || max_addr > MAP_32BIT_MAX_ADDR) ?
1674 aslr_pages_rnd_64[pidx] : aslr_pages_rnd_32[pidx];
1675 if (vm_map_findspace(map, curr_min_addr, length +
1676 gap * pagesizes[pidx], addr))
1678 /* And randomize the start address. */
1679 *addr += (arc4random() % gap) * pagesizes[pidx];
1680 if (max_addr != 0 && *addr + length > max_addr)
1682 } else if (vm_map_findspace(map, curr_min_addr, length, addr) ||
1683 (max_addr != 0 && *addr + length > max_addr)) {
1693 if (find_space != VMFS_ANY_SPACE &&
1694 (rv = vm_map_alignspace(map, object, offset, addr, length,
1695 max_addr, alignment)) != KERN_SUCCESS) {
1696 if (find_space == VMFS_OPTIMAL_SPACE) {
1697 find_space = VMFS_ANY_SPACE;
1698 curr_min_addr = min_addr;
1699 cluster = update_anon;
1705 } else if ((cow & MAP_REMAP) != 0) {
1706 if (*addr < vm_map_min(map) ||
1707 *addr + length > vm_map_max(map) ||
1708 *addr + length <= length) {
1709 rv = KERN_INVALID_ADDRESS;
1712 vm_map_delete(map, *addr, *addr + length);
1714 if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1715 rv = vm_map_stack_locked(map, *addr, length, sgrowsiz, prot,
1718 rv = vm_map_insert(map, object, offset, *addr, *addr + length,
1721 if (rv == KERN_SUCCESS && update_anon)
1722 map->anon_loc = *addr + length;
1729 * vm_map_find_min() is a variant of vm_map_find() that takes an
1730 * additional parameter (min_addr) and treats the given address
1731 * (*addr) differently. Specifically, it treats *addr as a hint
1732 * and not as the minimum address where the mapping is created.
1734 * This function works in two phases. First, it tries to
1735 * allocate above the hint. If that fails and the hint is
1736 * greater than min_addr, it performs a second pass, replacing
1737 * the hint with min_addr as the minimum address for the
1741 vm_map_find_min(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1742 vm_offset_t *addr, vm_size_t length, vm_offset_t min_addr,
1743 vm_offset_t max_addr, int find_space, vm_prot_t prot, vm_prot_t max,
1751 rv = vm_map_find(map, object, offset, addr, length, max_addr,
1752 find_space, prot, max, cow);
1753 if (rv == KERN_SUCCESS || min_addr >= hint)
1755 *addr = hint = min_addr;
1760 * A map entry with any of the following flags set must not be merged with
1763 #define MAP_ENTRY_NOMERGE_MASK (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP | \
1764 MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP)
1767 vm_map_mergeable_neighbors(vm_map_entry_t prev, vm_map_entry_t entry)
1770 KASSERT((prev->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 ||
1771 (entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0,
1772 ("vm_map_mergeable_neighbors: neither %p nor %p are mergeable",
1774 return (prev->end == entry->start &&
1775 prev->object.vm_object == entry->object.vm_object &&
1776 (prev->object.vm_object == NULL ||
1777 prev->offset + (prev->end - prev->start) == entry->offset) &&
1778 prev->eflags == entry->eflags &&
1779 prev->protection == entry->protection &&
1780 prev->max_protection == entry->max_protection &&
1781 prev->inheritance == entry->inheritance &&
1782 prev->wired_count == entry->wired_count &&
1783 prev->cred == entry->cred);
1787 vm_map_merged_neighbor_dispose(vm_map_t map, vm_map_entry_t entry)
1791 * If the backing object is a vnode object, vm_object_deallocate()
1792 * calls vrele(). However, vrele() does not lock the vnode because
1793 * the vnode has additional references. Thus, the map lock can be
1794 * kept without causing a lock-order reversal with the vnode lock.
1796 * Since we count the number of virtual page mappings in
1797 * object->un_pager.vnp.writemappings, the writemappings value
1798 * should not be adjusted when the entry is disposed of.
1800 if (entry->object.vm_object != NULL)
1801 vm_object_deallocate(entry->object.vm_object);
1802 if (entry->cred != NULL)
1803 crfree(entry->cred);
1804 vm_map_entry_dispose(map, entry);
1808 * vm_map_simplify_entry:
1810 * Simplify the given map entry by merging with either neighbor. This
1811 * routine also has the ability to merge with both neighbors.
1813 * The map must be locked.
1815 * This routine guarantees that the passed entry remains valid (though
1816 * possibly extended). When merging, this routine may delete one or
1820 vm_map_simplify_entry(vm_map_t map, vm_map_entry_t entry)
1822 vm_map_entry_t next, prev;
1824 if ((entry->eflags & MAP_ENTRY_NOMERGE_MASK) != 0)
1827 if (vm_map_mergeable_neighbors(prev, entry)) {
1828 vm_map_entry_unlink(map, prev);
1829 entry->start = prev->start;
1830 entry->offset = prev->offset;
1831 if (entry->prev != &map->header)
1832 vm_map_entry_resize_free(map, entry->prev);
1833 vm_map_merged_neighbor_dispose(map, prev);
1836 if (vm_map_mergeable_neighbors(entry, next)) {
1837 vm_map_entry_unlink(map, next);
1838 entry->end = next->end;
1839 vm_map_entry_resize_free(map, entry);
1840 vm_map_merged_neighbor_dispose(map, next);
1845 * vm_map_clip_start: [ internal use only ]
1847 * Asserts that the given entry begins at or after
1848 * the specified address; if necessary,
1849 * it splits the entry into two.
1851 #define vm_map_clip_start(map, entry, startaddr) \
1853 if (startaddr > entry->start) \
1854 _vm_map_clip_start(map, entry, startaddr); \
1858 * This routine is called only when it is known that
1859 * the entry must be split.
1862 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start)
1864 vm_map_entry_t new_entry;
1866 VM_MAP_ASSERT_LOCKED(map);
1867 KASSERT(entry->end > start && entry->start < start,
1868 ("_vm_map_clip_start: invalid clip of entry %p", entry));
1871 * Split off the front portion -- note that we must insert the new
1872 * entry BEFORE this one, so that this entry has the specified
1875 vm_map_simplify_entry(map, entry);
1878 * If there is no object backing this entry, we might as well create
1879 * one now. If we defer it, an object can get created after the map
1880 * is clipped, and individual objects will be created for the split-up
1881 * map. This is a bit of a hack, but is also about the best place to
1882 * put this improvement.
1884 if (entry->object.vm_object == NULL && !map->system_map &&
1885 (entry->eflags & MAP_ENTRY_GUARD) == 0) {
1887 object = vm_object_allocate(OBJT_DEFAULT,
1888 atop(entry->end - entry->start));
1889 entry->object.vm_object = object;
1891 if (entry->cred != NULL) {
1892 object->cred = entry->cred;
1893 object->charge = entry->end - entry->start;
1896 } else if (entry->object.vm_object != NULL &&
1897 ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
1898 entry->cred != NULL) {
1899 VM_OBJECT_WLOCK(entry->object.vm_object);
1900 KASSERT(entry->object.vm_object->cred == NULL,
1901 ("OVERCOMMIT: vm_entry_clip_start: both cred e %p", entry));
1902 entry->object.vm_object->cred = entry->cred;
1903 entry->object.vm_object->charge = entry->end - entry->start;
1904 VM_OBJECT_WUNLOCK(entry->object.vm_object);
1908 new_entry = vm_map_entry_create(map);
1909 *new_entry = *entry;
1911 new_entry->end = start;
1912 entry->offset += (start - entry->start);
1913 entry->start = start;
1914 if (new_entry->cred != NULL)
1915 crhold(entry->cred);
1917 vm_map_entry_link(map, entry->prev, new_entry);
1919 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1920 vm_object_reference(new_entry->object.vm_object);
1922 * The object->un_pager.vnp.writemappings for the
1923 * object of MAP_ENTRY_VN_WRITECNT type entry shall be
1924 * kept as is here. The virtual pages are
1925 * re-distributed among the clipped entries, so the sum is
1932 * vm_map_clip_end: [ internal use only ]
1934 * Asserts that the given entry ends at or before
1935 * the specified address; if necessary,
1936 * it splits the entry into two.
1938 #define vm_map_clip_end(map, entry, endaddr) \
1940 if ((endaddr) < (entry->end)) \
1941 _vm_map_clip_end((map), (entry), (endaddr)); \
1945 * This routine is called only when it is known that
1946 * the entry must be split.
1949 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end)
1951 vm_map_entry_t new_entry;
1953 VM_MAP_ASSERT_LOCKED(map);
1954 KASSERT(entry->start < end && entry->end > end,
1955 ("_vm_map_clip_end: invalid clip of entry %p", entry));
1958 * If there is no object backing this entry, we might as well create
1959 * one now. If we defer it, an object can get created after the map
1960 * is clipped, and individual objects will be created for the split-up
1961 * map. This is a bit of a hack, but is also about the best place to
1962 * put this improvement.
1964 if (entry->object.vm_object == NULL && !map->system_map &&
1965 (entry->eflags & MAP_ENTRY_GUARD) == 0) {
1967 object = vm_object_allocate(OBJT_DEFAULT,
1968 atop(entry->end - entry->start));
1969 entry->object.vm_object = object;
1971 if (entry->cred != NULL) {
1972 object->cred = entry->cred;
1973 object->charge = entry->end - entry->start;
1976 } else if (entry->object.vm_object != NULL &&
1977 ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
1978 entry->cred != NULL) {
1979 VM_OBJECT_WLOCK(entry->object.vm_object);
1980 KASSERT(entry->object.vm_object->cred == NULL,
1981 ("OVERCOMMIT: vm_entry_clip_end: both cred e %p", entry));
1982 entry->object.vm_object->cred = entry->cred;
1983 entry->object.vm_object->charge = entry->end - entry->start;
1984 VM_OBJECT_WUNLOCK(entry->object.vm_object);
1989 * Create a new entry and insert it AFTER the specified entry
1991 new_entry = vm_map_entry_create(map);
1992 *new_entry = *entry;
1994 new_entry->start = entry->end = end;
1995 new_entry->offset += (end - entry->start);
1996 if (new_entry->cred != NULL)
1997 crhold(entry->cred);
1999 vm_map_entry_link(map, entry, new_entry);
2001 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2002 vm_object_reference(new_entry->object.vm_object);
2007 * vm_map_submap: [ kernel use only ]
2009 * Mark the given range as handled by a subordinate map.
2011 * This range must have been created with vm_map_find,
2012 * and no other operations may have been performed on this
2013 * range prior to calling vm_map_submap.
2015 * Only a limited number of operations can be performed
2016 * within this rage after calling vm_map_submap:
2018 * [Don't try vm_map_copy!]
2020 * To remove a submapping, one must first remove the
2021 * range from the superior map, and then destroy the
2022 * submap (if desired). [Better yet, don't try it.]
2031 vm_map_entry_t entry;
2034 result = KERN_INVALID_ARGUMENT;
2036 vm_map_lock(submap);
2037 submap->flags |= MAP_IS_SUB_MAP;
2038 vm_map_unlock(submap);
2042 VM_MAP_RANGE_CHECK(map, start, end);
2044 if (vm_map_lookup_entry(map, start, &entry)) {
2045 vm_map_clip_start(map, entry, start);
2047 entry = entry->next;
2049 vm_map_clip_end(map, entry, end);
2051 if ((entry->start == start) && (entry->end == end) &&
2052 ((entry->eflags & MAP_ENTRY_COW) == 0) &&
2053 (entry->object.vm_object == NULL)) {
2054 entry->object.sub_map = submap;
2055 entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
2056 result = KERN_SUCCESS;
2060 if (result != KERN_SUCCESS) {
2061 vm_map_lock(submap);
2062 submap->flags &= ~MAP_IS_SUB_MAP;
2063 vm_map_unlock(submap);
2069 * The maximum number of pages to map if MAP_PREFAULT_PARTIAL is specified
2071 #define MAX_INIT_PT 96
2074 * vm_map_pmap_enter:
2076 * Preload the specified map's pmap with mappings to the specified
2077 * object's memory-resident pages. No further physical pages are
2078 * allocated, and no further virtual pages are retrieved from secondary
2079 * storage. If the specified flags include MAP_PREFAULT_PARTIAL, then a
2080 * limited number of page mappings are created at the low-end of the
2081 * specified address range. (For this purpose, a superpage mapping
2082 * counts as one page mapping.) Otherwise, all resident pages within
2083 * the specified address range are mapped.
2086 vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
2087 vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
2090 vm_page_t p, p_start;
2091 vm_pindex_t mask, psize, threshold, tmpidx;
2093 if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0 || object == NULL)
2095 VM_OBJECT_RLOCK(object);
2096 if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2097 VM_OBJECT_RUNLOCK(object);
2098 VM_OBJECT_WLOCK(object);
2099 if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2100 pmap_object_init_pt(map->pmap, addr, object, pindex,
2102 VM_OBJECT_WUNLOCK(object);
2105 VM_OBJECT_LOCK_DOWNGRADE(object);
2109 if (psize + pindex > object->size) {
2110 if (object->size < pindex) {
2111 VM_OBJECT_RUNLOCK(object);
2114 psize = object->size - pindex;
2119 threshold = MAX_INIT_PT;
2121 p = vm_page_find_least(object, pindex);
2123 * Assert: the variable p is either (1) the page with the
2124 * least pindex greater than or equal to the parameter pindex
2128 p != NULL && (tmpidx = p->pindex - pindex) < psize;
2129 p = TAILQ_NEXT(p, listq)) {
2131 * don't allow an madvise to blow away our really
2132 * free pages allocating pv entries.
2134 if (((flags & MAP_PREFAULT_MADVISE) != 0 &&
2135 vm_page_count_severe()) ||
2136 ((flags & MAP_PREFAULT_PARTIAL) != 0 &&
2137 tmpidx >= threshold)) {
2141 if (p->valid == VM_PAGE_BITS_ALL) {
2142 if (p_start == NULL) {
2143 start = addr + ptoa(tmpidx);
2146 /* Jump ahead if a superpage mapping is possible. */
2147 if (p->psind > 0 && ((addr + ptoa(tmpidx)) &
2148 (pagesizes[p->psind] - 1)) == 0) {
2149 mask = atop(pagesizes[p->psind]) - 1;
2150 if (tmpidx + mask < psize &&
2151 vm_page_ps_test(p, PS_ALL_VALID, NULL)) {
2156 } else if (p_start != NULL) {
2157 pmap_enter_object(map->pmap, start, addr +
2158 ptoa(tmpidx), p_start, prot);
2162 if (p_start != NULL)
2163 pmap_enter_object(map->pmap, start, addr + ptoa(psize),
2165 VM_OBJECT_RUNLOCK(object);
2171 * Sets the protection of the specified address
2172 * region in the target map. If "set_max" is
2173 * specified, the maximum protection is to be set;
2174 * otherwise, only the current protection is affected.
2177 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
2178 vm_prot_t new_prot, boolean_t set_max)
2180 vm_map_entry_t current, entry;
2186 return (KERN_SUCCESS);
2191 * Ensure that we are not concurrently wiring pages. vm_map_wire() may
2192 * need to fault pages into the map and will drop the map lock while
2193 * doing so, and the VM object may end up in an inconsistent state if we
2194 * update the protection on the map entry in between faults.
2196 vm_map_wait_busy(map);
2198 VM_MAP_RANGE_CHECK(map, start, end);
2200 if (vm_map_lookup_entry(map, start, &entry)) {
2201 vm_map_clip_start(map, entry, start);
2203 entry = entry->next;
2207 * Make a first pass to check for protection violations.
2209 for (current = entry; current->start < end; current = current->next) {
2210 if ((current->eflags & MAP_ENTRY_GUARD) != 0)
2212 if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
2214 return (KERN_INVALID_ARGUMENT);
2216 if ((new_prot & current->max_protection) != new_prot) {
2218 return (KERN_PROTECTION_FAILURE);
2223 * Do an accounting pass for private read-only mappings that
2224 * now will do cow due to allowed write (e.g. debugger sets
2225 * breakpoint on text segment)
2227 for (current = entry; current->start < end; current = current->next) {
2229 vm_map_clip_end(map, current, end);
2232 ((new_prot & ~(current->protection)) & VM_PROT_WRITE) == 0 ||
2233 ENTRY_CHARGED(current) ||
2234 (current->eflags & MAP_ENTRY_GUARD) != 0) {
2238 cred = curthread->td_ucred;
2239 obj = current->object.vm_object;
2241 if (obj == NULL || (current->eflags & MAP_ENTRY_NEEDS_COPY)) {
2242 if (!swap_reserve(current->end - current->start)) {
2244 return (KERN_RESOURCE_SHORTAGE);
2247 current->cred = cred;
2251 VM_OBJECT_WLOCK(obj);
2252 if (obj->type != OBJT_DEFAULT && obj->type != OBJT_SWAP) {
2253 VM_OBJECT_WUNLOCK(obj);
2258 * Charge for the whole object allocation now, since
2259 * we cannot distinguish between non-charged and
2260 * charged clipped mapping of the same object later.
2262 KASSERT(obj->charge == 0,
2263 ("vm_map_protect: object %p overcharged (entry %p)",
2265 if (!swap_reserve(ptoa(obj->size))) {
2266 VM_OBJECT_WUNLOCK(obj);
2268 return (KERN_RESOURCE_SHORTAGE);
2273 obj->charge = ptoa(obj->size);
2274 VM_OBJECT_WUNLOCK(obj);
2278 * Go back and fix up protections. [Note that clipping is not
2279 * necessary the second time.]
2281 for (current = entry; current->start < end; current = current->next) {
2282 if ((current->eflags & MAP_ENTRY_GUARD) != 0)
2285 old_prot = current->protection;
2288 current->protection =
2289 (current->max_protection = new_prot) &
2292 current->protection = new_prot;
2295 * For user wired map entries, the normal lazy evaluation of
2296 * write access upgrades through soft page faults is
2297 * undesirable. Instead, immediately copy any pages that are
2298 * copy-on-write and enable write access in the physical map.
2300 if ((current->eflags & MAP_ENTRY_USER_WIRED) != 0 &&
2301 (current->protection & VM_PROT_WRITE) != 0 &&
2302 (old_prot & VM_PROT_WRITE) == 0)
2303 vm_fault_copy_entry(map, map, current, current, NULL);
2306 * When restricting access, update the physical map. Worry
2307 * about copy-on-write here.
2309 if ((old_prot & ~current->protection) != 0) {
2310 #define MASK(entry) (((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
2312 pmap_protect(map->pmap, current->start,
2314 current->protection & MASK(current));
2317 vm_map_simplify_entry(map, current);
2320 return (KERN_SUCCESS);
2326 * This routine traverses a processes map handling the madvise
2327 * system call. Advisories are classified as either those effecting
2328 * the vm_map_entry structure, or those effecting the underlying
2338 vm_map_entry_t current, entry;
2342 * Some madvise calls directly modify the vm_map_entry, in which case
2343 * we need to use an exclusive lock on the map and we need to perform
2344 * various clipping operations. Otherwise we only need a read-lock
2349 case MADV_SEQUENTIAL:
2366 vm_map_lock_read(map);
2373 * Locate starting entry and clip if necessary.
2375 VM_MAP_RANGE_CHECK(map, start, end);
2377 if (vm_map_lookup_entry(map, start, &entry)) {
2379 vm_map_clip_start(map, entry, start);
2381 entry = entry->next;
2386 * madvise behaviors that are implemented in the vm_map_entry.
2388 * We clip the vm_map_entry so that behavioral changes are
2389 * limited to the specified address range.
2391 for (current = entry; current->start < end;
2392 current = current->next) {
2393 if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2396 vm_map_clip_end(map, current, end);
2400 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
2402 case MADV_SEQUENTIAL:
2403 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
2406 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
2409 current->eflags |= MAP_ENTRY_NOSYNC;
2412 current->eflags &= ~MAP_ENTRY_NOSYNC;
2415 current->eflags |= MAP_ENTRY_NOCOREDUMP;
2418 current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
2423 vm_map_simplify_entry(map, current);
2427 vm_pindex_t pstart, pend;
2430 * madvise behaviors that are implemented in the underlying
2433 * Since we don't clip the vm_map_entry, we have to clip
2434 * the vm_object pindex and count.
2436 for (current = entry; current->start < end;
2437 current = current->next) {
2438 vm_offset_t useEnd, useStart;
2440 if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2443 pstart = OFF_TO_IDX(current->offset);
2444 pend = pstart + atop(current->end - current->start);
2445 useStart = current->start;
2446 useEnd = current->end;
2448 if (current->start < start) {
2449 pstart += atop(start - current->start);
2452 if (current->end > end) {
2453 pend -= atop(current->end - end);
2461 * Perform the pmap_advise() before clearing
2462 * PGA_REFERENCED in vm_page_advise(). Otherwise, a
2463 * concurrent pmap operation, such as pmap_remove(),
2464 * could clear a reference in the pmap and set
2465 * PGA_REFERENCED on the page before the pmap_advise()
2466 * had completed. Consequently, the page would appear
2467 * referenced based upon an old reference that
2468 * occurred before this pmap_advise() ran.
2470 if (behav == MADV_DONTNEED || behav == MADV_FREE)
2471 pmap_advise(map->pmap, useStart, useEnd,
2474 vm_object_madvise(current->object.vm_object, pstart,
2478 * Pre-populate paging structures in the
2479 * WILLNEED case. For wired entries, the
2480 * paging structures are already populated.
2482 if (behav == MADV_WILLNEED &&
2483 current->wired_count == 0) {
2484 vm_map_pmap_enter(map,
2486 current->protection,
2487 current->object.vm_object,
2489 ptoa(pend - pstart),
2490 MAP_PREFAULT_MADVISE
2494 vm_map_unlock_read(map);
2503 * Sets the inheritance of the specified address
2504 * range in the target map. Inheritance
2505 * affects how the map will be shared with
2506 * child maps at the time of vmspace_fork.
2509 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
2510 vm_inherit_t new_inheritance)
2512 vm_map_entry_t entry;
2513 vm_map_entry_t temp_entry;
2515 switch (new_inheritance) {
2516 case VM_INHERIT_NONE:
2517 case VM_INHERIT_COPY:
2518 case VM_INHERIT_SHARE:
2519 case VM_INHERIT_ZERO:
2522 return (KERN_INVALID_ARGUMENT);
2525 return (KERN_SUCCESS);
2527 VM_MAP_RANGE_CHECK(map, start, end);
2528 if (vm_map_lookup_entry(map, start, &temp_entry)) {
2530 vm_map_clip_start(map, entry, start);
2532 entry = temp_entry->next;
2533 while (entry->start < end) {
2534 vm_map_clip_end(map, entry, end);
2535 if ((entry->eflags & MAP_ENTRY_GUARD) == 0 ||
2536 new_inheritance != VM_INHERIT_ZERO)
2537 entry->inheritance = new_inheritance;
2538 vm_map_simplify_entry(map, entry);
2539 entry = entry->next;
2542 return (KERN_SUCCESS);
2548 * Implements both kernel and user unwiring.
2551 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
2554 vm_map_entry_t entry, first_entry, tmp_entry;
2555 vm_offset_t saved_start;
2556 unsigned int last_timestamp;
2558 boolean_t need_wakeup, result, user_unwire;
2561 return (KERN_SUCCESS);
2562 user_unwire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
2564 VM_MAP_RANGE_CHECK(map, start, end);
2565 if (!vm_map_lookup_entry(map, start, &first_entry)) {
2566 if (flags & VM_MAP_WIRE_HOLESOK)
2567 first_entry = first_entry->next;
2570 return (KERN_INVALID_ADDRESS);
2573 last_timestamp = map->timestamp;
2574 entry = first_entry;
2575 while (entry->start < end) {
2576 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2578 * We have not yet clipped the entry.
2580 saved_start = (start >= entry->start) ? start :
2582 entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2583 if (vm_map_unlock_and_wait(map, 0)) {
2585 * Allow interruption of user unwiring?
2589 if (last_timestamp+1 != map->timestamp) {
2591 * Look again for the entry because the map was
2592 * modified while it was unlocked.
2593 * Specifically, the entry may have been
2594 * clipped, merged, or deleted.
2596 if (!vm_map_lookup_entry(map, saved_start,
2598 if (flags & VM_MAP_WIRE_HOLESOK)
2599 tmp_entry = tmp_entry->next;
2601 if (saved_start == start) {
2603 * First_entry has been deleted.
2606 return (KERN_INVALID_ADDRESS);
2609 rv = KERN_INVALID_ADDRESS;
2613 if (entry == first_entry)
2614 first_entry = tmp_entry;
2619 last_timestamp = map->timestamp;
2622 vm_map_clip_start(map, entry, start);
2623 vm_map_clip_end(map, entry, end);
2625 * Mark the entry in case the map lock is released. (See
2628 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
2629 entry->wiring_thread == NULL,
2630 ("owned map entry %p", entry));
2631 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
2632 entry->wiring_thread = curthread;
2634 * Check the map for holes in the specified region.
2635 * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
2637 if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
2638 (entry->end < end && entry->next->start > entry->end)) {
2640 rv = KERN_INVALID_ADDRESS;
2644 * If system unwiring, require that the entry is system wired.
2647 vm_map_entry_system_wired_count(entry) == 0) {
2649 rv = KERN_INVALID_ARGUMENT;
2652 entry = entry->next;
2656 need_wakeup = FALSE;
2657 if (first_entry == NULL) {
2658 result = vm_map_lookup_entry(map, start, &first_entry);
2659 if (!result && (flags & VM_MAP_WIRE_HOLESOK))
2660 first_entry = first_entry->next;
2662 KASSERT(result, ("vm_map_unwire: lookup failed"));
2664 for (entry = first_entry; entry->start < end; entry = entry->next) {
2666 * If VM_MAP_WIRE_HOLESOK was specified, an empty
2667 * space in the unwired region could have been mapped
2668 * while the map lock was dropped for draining
2669 * MAP_ENTRY_IN_TRANSITION. Moreover, another thread
2670 * could be simultaneously wiring this new mapping
2671 * entry. Detect these cases and skip any entries
2672 * marked as in transition by us.
2674 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
2675 entry->wiring_thread != curthread) {
2676 KASSERT((flags & VM_MAP_WIRE_HOLESOK) != 0,
2677 ("vm_map_unwire: !HOLESOK and new/changed entry"));
2681 if (rv == KERN_SUCCESS && (!user_unwire ||
2682 (entry->eflags & MAP_ENTRY_USER_WIRED))) {
2684 entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2685 if (entry->wired_count == 1)
2686 vm_map_entry_unwire(map, entry);
2688 entry->wired_count--;
2690 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
2691 ("vm_map_unwire: in-transition flag missing %p", entry));
2692 KASSERT(entry->wiring_thread == curthread,
2693 ("vm_map_unwire: alien wire %p", entry));
2694 entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
2695 entry->wiring_thread = NULL;
2696 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
2697 entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
2700 vm_map_simplify_entry(map, entry);
2709 * vm_map_wire_entry_failure:
2711 * Handle a wiring failure on the given entry.
2713 * The map should be locked.
2716 vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
2717 vm_offset_t failed_addr)
2720 VM_MAP_ASSERT_LOCKED(map);
2721 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 &&
2722 entry->wired_count == 1,
2723 ("vm_map_wire_entry_failure: entry %p isn't being wired", entry));
2724 KASSERT(failed_addr < entry->end,
2725 ("vm_map_wire_entry_failure: entry %p was fully wired", entry));
2728 * If any pages at the start of this entry were successfully wired,
2731 if (failed_addr > entry->start) {
2732 pmap_unwire(map->pmap, entry->start, failed_addr);
2733 vm_object_unwire(entry->object.vm_object, entry->offset,
2734 failed_addr - entry->start, PQ_ACTIVE);
2738 * Assign an out-of-range value to represent the failure to wire this
2741 entry->wired_count = -1;
2747 * Implements both kernel and user wiring.
2750 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end,
2753 vm_map_entry_t entry, first_entry, tmp_entry;
2754 vm_offset_t faddr, saved_end, saved_start;
2755 unsigned int last_timestamp;
2757 boolean_t need_wakeup, result, user_wire;
2761 return (KERN_SUCCESS);
2763 if (flags & VM_MAP_WIRE_WRITE)
2764 prot |= VM_PROT_WRITE;
2765 user_wire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
2767 VM_MAP_RANGE_CHECK(map, start, end);
2768 if (!vm_map_lookup_entry(map, start, &first_entry)) {
2769 if (flags & VM_MAP_WIRE_HOLESOK)
2770 first_entry = first_entry->next;
2773 return (KERN_INVALID_ADDRESS);
2776 last_timestamp = map->timestamp;
2777 entry = first_entry;
2778 while (entry->start < end) {
2779 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2781 * We have not yet clipped the entry.
2783 saved_start = (start >= entry->start) ? start :
2785 entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2786 if (vm_map_unlock_and_wait(map, 0)) {
2788 * Allow interruption of user wiring?
2792 if (last_timestamp + 1 != map->timestamp) {
2794 * Look again for the entry because the map was
2795 * modified while it was unlocked.
2796 * Specifically, the entry may have been
2797 * clipped, merged, or deleted.
2799 if (!vm_map_lookup_entry(map, saved_start,
2801 if (flags & VM_MAP_WIRE_HOLESOK)
2802 tmp_entry = tmp_entry->next;
2804 if (saved_start == start) {
2806 * first_entry has been deleted.
2809 return (KERN_INVALID_ADDRESS);
2812 rv = KERN_INVALID_ADDRESS;
2816 if (entry == first_entry)
2817 first_entry = tmp_entry;
2822 last_timestamp = map->timestamp;
2825 vm_map_clip_start(map, entry, start);
2826 vm_map_clip_end(map, entry, end);
2828 * Mark the entry in case the map lock is released. (See
2831 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
2832 entry->wiring_thread == NULL,
2833 ("owned map entry %p", entry));
2834 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
2835 entry->wiring_thread = curthread;
2836 if ((entry->protection & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0
2837 || (entry->protection & prot) != prot) {
2838 entry->eflags |= MAP_ENTRY_WIRE_SKIPPED;
2839 if ((flags & VM_MAP_WIRE_HOLESOK) == 0) {
2841 rv = KERN_INVALID_ADDRESS;
2846 if (entry->wired_count == 0) {
2847 entry->wired_count++;
2848 saved_start = entry->start;
2849 saved_end = entry->end;
2852 * Release the map lock, relying on the in-transition
2853 * mark. Mark the map busy for fork.
2858 faddr = saved_start;
2861 * Simulate a fault to get the page and enter
2862 * it into the physical map.
2864 if ((rv = vm_fault(map, faddr, VM_PROT_NONE,
2865 VM_FAULT_WIRE)) != KERN_SUCCESS)
2867 } while ((faddr += PAGE_SIZE) < saved_end);
2870 if (last_timestamp + 1 != map->timestamp) {
2872 * Look again for the entry because the map was
2873 * modified while it was unlocked. The entry
2874 * may have been clipped, but NOT merged or
2877 result = vm_map_lookup_entry(map, saved_start,
2879 KASSERT(result, ("vm_map_wire: lookup failed"));
2880 if (entry == first_entry)
2881 first_entry = tmp_entry;
2885 while (entry->end < saved_end) {
2887 * In case of failure, handle entries
2888 * that were not fully wired here;
2889 * fully wired entries are handled
2892 if (rv != KERN_SUCCESS &&
2894 vm_map_wire_entry_failure(map,
2896 entry = entry->next;
2899 last_timestamp = map->timestamp;
2900 if (rv != KERN_SUCCESS) {
2901 vm_map_wire_entry_failure(map, entry, faddr);
2905 } else if (!user_wire ||
2906 (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
2907 entry->wired_count++;
2910 * Check the map for holes in the specified region.
2911 * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
2914 if ((flags & VM_MAP_WIRE_HOLESOK) == 0 &&
2915 entry->end < end && entry->next->start > entry->end) {
2917 rv = KERN_INVALID_ADDRESS;
2920 entry = entry->next;
2924 need_wakeup = FALSE;
2925 if (first_entry == NULL) {
2926 result = vm_map_lookup_entry(map, start, &first_entry);
2927 if (!result && (flags & VM_MAP_WIRE_HOLESOK))
2928 first_entry = first_entry->next;
2930 KASSERT(result, ("vm_map_wire: lookup failed"));
2932 for (entry = first_entry; entry->start < end; entry = entry->next) {
2934 * If VM_MAP_WIRE_HOLESOK was specified, an empty
2935 * space in the unwired region could have been mapped
2936 * while the map lock was dropped for faulting in the
2937 * pages or draining MAP_ENTRY_IN_TRANSITION.
2938 * Moreover, another thread could be simultaneously
2939 * wiring this new mapping entry. Detect these cases
2940 * and skip any entries marked as in transition not by us.
2942 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
2943 entry->wiring_thread != curthread) {
2944 KASSERT((flags & VM_MAP_WIRE_HOLESOK) != 0,
2945 ("vm_map_wire: !HOLESOK and new/changed entry"));
2949 if ((entry->eflags & MAP_ENTRY_WIRE_SKIPPED) != 0)
2950 goto next_entry_done;
2952 if (rv == KERN_SUCCESS) {
2954 entry->eflags |= MAP_ENTRY_USER_WIRED;
2955 } else if (entry->wired_count == -1) {
2957 * Wiring failed on this entry. Thus, unwiring is
2960 entry->wired_count = 0;
2961 } else if (!user_wire ||
2962 (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
2964 * Undo the wiring. Wiring succeeded on this entry
2965 * but failed on a later entry.
2967 if (entry->wired_count == 1)
2968 vm_map_entry_unwire(map, entry);
2970 entry->wired_count--;
2973 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
2974 ("vm_map_wire: in-transition flag missing %p", entry));
2975 KASSERT(entry->wiring_thread == curthread,
2976 ("vm_map_wire: alien wire %p", entry));
2977 entry->eflags &= ~(MAP_ENTRY_IN_TRANSITION |
2978 MAP_ENTRY_WIRE_SKIPPED);
2979 entry->wiring_thread = NULL;
2980 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
2981 entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
2984 vm_map_simplify_entry(map, entry);
2995 * Push any dirty cached pages in the address range to their pager.
2996 * If syncio is TRUE, dirty pages are written synchronously.
2997 * If invalidate is TRUE, any cached pages are freed as well.
2999 * If the size of the region from start to end is zero, we are
3000 * supposed to flush all modified pages within the region containing
3001 * start. Unfortunately, a region can be split or coalesced with
3002 * neighboring regions, making it difficult to determine what the
3003 * original region was. Therefore, we approximate this requirement by
3004 * flushing the current region containing start.
3006 * Returns an error if any part of the specified range is not mapped.
3014 boolean_t invalidate)
3016 vm_map_entry_t current;
3017 vm_map_entry_t entry;
3020 vm_ooffset_t offset;
3021 unsigned int last_timestamp;
3024 vm_map_lock_read(map);
3025 VM_MAP_RANGE_CHECK(map, start, end);
3026 if (!vm_map_lookup_entry(map, start, &entry)) {
3027 vm_map_unlock_read(map);
3028 return (KERN_INVALID_ADDRESS);
3029 } else if (start == end) {
3030 start = entry->start;
3034 * Make a first pass to check for user-wired memory and holes.
3036 for (current = entry; current->start < end; current = current->next) {
3037 if (invalidate && (current->eflags & MAP_ENTRY_USER_WIRED)) {
3038 vm_map_unlock_read(map);
3039 return (KERN_INVALID_ARGUMENT);
3041 if (end > current->end &&
3042 current->end != current->next->start) {
3043 vm_map_unlock_read(map);
3044 return (KERN_INVALID_ADDRESS);
3049 pmap_remove(map->pmap, start, end);
3053 * Make a second pass, cleaning/uncaching pages from the indicated
3056 for (current = entry; current->start < end;) {
3057 offset = current->offset + (start - current->start);
3058 size = (end <= current->end ? end : current->end) - start;
3059 if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
3061 vm_map_entry_t tentry;
3064 smap = current->object.sub_map;
3065 vm_map_lock_read(smap);
3066 (void) vm_map_lookup_entry(smap, offset, &tentry);
3067 tsize = tentry->end - offset;
3070 object = tentry->object.vm_object;
3071 offset = tentry->offset + (offset - tentry->start);
3072 vm_map_unlock_read(smap);
3074 object = current->object.vm_object;
3076 vm_object_reference(object);
3077 last_timestamp = map->timestamp;
3078 vm_map_unlock_read(map);
3079 if (!vm_object_sync(object, offset, size, syncio, invalidate))
3082 vm_object_deallocate(object);
3083 vm_map_lock_read(map);
3084 if (last_timestamp == map->timestamp ||
3085 !vm_map_lookup_entry(map, start, ¤t))
3086 current = current->next;
3089 vm_map_unlock_read(map);
3090 return (failed ? KERN_FAILURE : KERN_SUCCESS);
3094 * vm_map_entry_unwire: [ internal use only ]
3096 * Make the region specified by this entry pageable.
3098 * The map in question should be locked.
3099 * [This is the reason for this routine's existence.]
3102 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
3105 VM_MAP_ASSERT_LOCKED(map);
3106 KASSERT(entry->wired_count > 0,
3107 ("vm_map_entry_unwire: entry %p isn't wired", entry));
3108 pmap_unwire(map->pmap, entry->start, entry->end);
3109 vm_object_unwire(entry->object.vm_object, entry->offset, entry->end -
3110 entry->start, PQ_ACTIVE);
3111 entry->wired_count = 0;
3115 vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map)
3118 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
3119 vm_object_deallocate(entry->object.vm_object);
3120 uma_zfree(system_map ? kmapentzone : mapentzone, entry);
3124 * vm_map_entry_delete: [ internal use only ]
3126 * Deallocate the given entry from the target map.
3129 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
3132 vm_pindex_t offidxstart, offidxend, count, size1;
3135 vm_map_entry_unlink(map, entry);
3136 object = entry->object.vm_object;
3138 if ((entry->eflags & MAP_ENTRY_GUARD) != 0) {
3139 MPASS(entry->cred == NULL);
3140 MPASS((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0);
3141 MPASS(object == NULL);
3142 vm_map_entry_deallocate(entry, map->system_map);
3146 size = entry->end - entry->start;
3149 if (entry->cred != NULL) {
3150 swap_release_by_cred(size, entry->cred);
3151 crfree(entry->cred);
3154 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
3156 KASSERT(entry->cred == NULL || object->cred == NULL ||
3157 (entry->eflags & MAP_ENTRY_NEEDS_COPY),
3158 ("OVERCOMMIT vm_map_entry_delete: both cred %p", entry));
3160 offidxstart = OFF_TO_IDX(entry->offset);
3161 offidxend = offidxstart + count;
3162 VM_OBJECT_WLOCK(object);
3163 if (object->ref_count != 1 && ((object->flags & (OBJ_NOSPLIT |
3164 OBJ_ONEMAPPING)) == OBJ_ONEMAPPING ||
3165 object == kernel_object)) {
3166 vm_object_collapse(object);
3169 * The option OBJPR_NOTMAPPED can be passed here
3170 * because vm_map_delete() already performed
3171 * pmap_remove() on the only mapping to this range
3174 vm_object_page_remove(object, offidxstart, offidxend,
3176 if (object->type == OBJT_SWAP)
3177 swap_pager_freespace(object, offidxstart,
3179 if (offidxend >= object->size &&
3180 offidxstart < object->size) {
3181 size1 = object->size;
3182 object->size = offidxstart;
3183 if (object->cred != NULL) {
3184 size1 -= object->size;
3185 KASSERT(object->charge >= ptoa(size1),
3186 ("object %p charge < 0", object));
3187 swap_release_by_cred(ptoa(size1),
3189 object->charge -= ptoa(size1);
3193 VM_OBJECT_WUNLOCK(object);
3195 entry->object.vm_object = NULL;
3196 if (map->system_map)
3197 vm_map_entry_deallocate(entry, TRUE);
3199 entry->next = curthread->td_map_def_user;
3200 curthread->td_map_def_user = entry;
3205 * vm_map_delete: [ internal use only ]
3207 * Deallocates the given address range from the target
3211 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
3213 vm_map_entry_t entry;
3214 vm_map_entry_t first_entry;
3216 VM_MAP_ASSERT_LOCKED(map);
3218 return (KERN_SUCCESS);
3221 * Find the start of the region, and clip it
3223 if (!vm_map_lookup_entry(map, start, &first_entry))
3224 entry = first_entry->next;
3226 entry = first_entry;
3227 vm_map_clip_start(map, entry, start);
3231 * Step through all entries in this region
3233 while (entry->start < end) {
3234 vm_map_entry_t next;
3237 * Wait for wiring or unwiring of an entry to complete.
3238 * Also wait for any system wirings to disappear on
3241 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
3242 (vm_map_pmap(map) != kernel_pmap &&
3243 vm_map_entry_system_wired_count(entry) != 0)) {
3244 unsigned int last_timestamp;
3245 vm_offset_t saved_start;
3246 vm_map_entry_t tmp_entry;
3248 saved_start = entry->start;
3249 entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3250 last_timestamp = map->timestamp;
3251 (void) vm_map_unlock_and_wait(map, 0);
3253 if (last_timestamp + 1 != map->timestamp) {
3255 * Look again for the entry because the map was
3256 * modified while it was unlocked.
3257 * Specifically, the entry may have been
3258 * clipped, merged, or deleted.
3260 if (!vm_map_lookup_entry(map, saved_start,
3262 entry = tmp_entry->next;
3265 vm_map_clip_start(map, entry,
3271 vm_map_clip_end(map, entry, end);
3276 * Unwire before removing addresses from the pmap; otherwise,
3277 * unwiring will put the entries back in the pmap.
3279 if (entry->wired_count != 0)
3280 vm_map_entry_unwire(map, entry);
3283 * Remove mappings for the pages, but only if the
3284 * mappings could exist. For instance, it does not
3285 * make sense to call pmap_remove() for guard entries.
3287 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 ||
3288 entry->object.vm_object != NULL)
3289 pmap_remove(map->pmap, entry->start, entry->end);
3291 if (entry->end == map->anon_loc)
3292 map->anon_loc = entry->start;
3295 * Delete the entry only after removing all pmap
3296 * entries pointing to its pages. (Otherwise, its
3297 * page frames may be reallocated, and any modify bits
3298 * will be set in the wrong object!)
3300 vm_map_entry_delete(map, entry);
3303 return (KERN_SUCCESS);
3309 * Remove the given address range from the target map.
3310 * This is the exported form of vm_map_delete.
3313 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
3318 VM_MAP_RANGE_CHECK(map, start, end);
3319 result = vm_map_delete(map, start, end);
3325 * vm_map_check_protection:
3327 * Assert that the target map allows the specified privilege on the
3328 * entire address region given. The entire region must be allocated.
3330 * WARNING! This code does not and should not check whether the
3331 * contents of the region is accessible. For example a smaller file
3332 * might be mapped into a larger address space.
3334 * NOTE! This code is also called by munmap().
3336 * The map must be locked. A read lock is sufficient.
3339 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
3340 vm_prot_t protection)
3342 vm_map_entry_t entry;
3343 vm_map_entry_t tmp_entry;
3345 if (!vm_map_lookup_entry(map, start, &tmp_entry))
3349 while (start < end) {
3353 if (start < entry->start)
3356 * Check protection associated with entry.
3358 if ((entry->protection & protection) != protection)
3360 /* go to next entry */
3362 entry = entry->next;
3368 * vm_map_copy_entry:
3370 * Copies the contents of the source entry to the destination
3371 * entry. The entries *must* be aligned properly.
3377 vm_map_entry_t src_entry,
3378 vm_map_entry_t dst_entry,
3379 vm_ooffset_t *fork_charge)
3381 vm_object_t src_object;
3382 vm_map_entry_t fake_entry;
3387 VM_MAP_ASSERT_LOCKED(dst_map);
3389 if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
3392 if (src_entry->wired_count == 0 ||
3393 (src_entry->protection & VM_PROT_WRITE) == 0) {
3395 * If the source entry is marked needs_copy, it is already
3398 if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0 &&
3399 (src_entry->protection & VM_PROT_WRITE) != 0) {
3400 pmap_protect(src_map->pmap,
3403 src_entry->protection & ~VM_PROT_WRITE);
3407 * Make a copy of the object.
3409 size = src_entry->end - src_entry->start;
3410 if ((src_object = src_entry->object.vm_object) != NULL) {
3411 VM_OBJECT_WLOCK(src_object);
3412 charged = ENTRY_CHARGED(src_entry);
3413 if (src_object->handle == NULL &&
3414 (src_object->type == OBJT_DEFAULT ||
3415 src_object->type == OBJT_SWAP)) {
3416 vm_object_collapse(src_object);
3417 if ((src_object->flags & (OBJ_NOSPLIT |
3418 OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
3419 vm_object_split(src_entry);
3421 src_entry->object.vm_object;
3424 vm_object_reference_locked(src_object);
3425 vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
3426 if (src_entry->cred != NULL &&
3427 !(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
3428 KASSERT(src_object->cred == NULL,
3429 ("OVERCOMMIT: vm_map_copy_entry: cred %p",
3431 src_object->cred = src_entry->cred;
3432 src_object->charge = size;
3434 VM_OBJECT_WUNLOCK(src_object);
3435 dst_entry->object.vm_object = src_object;
3437 cred = curthread->td_ucred;
3439 dst_entry->cred = cred;
3440 *fork_charge += size;
3441 if (!(src_entry->eflags &
3442 MAP_ENTRY_NEEDS_COPY)) {
3444 src_entry->cred = cred;
3445 *fork_charge += size;
3448 src_entry->eflags |= MAP_ENTRY_COW |
3449 MAP_ENTRY_NEEDS_COPY;
3450 dst_entry->eflags |= MAP_ENTRY_COW |
3451 MAP_ENTRY_NEEDS_COPY;
3452 dst_entry->offset = src_entry->offset;
3453 if (src_entry->eflags & MAP_ENTRY_VN_WRITECNT) {
3455 * MAP_ENTRY_VN_WRITECNT cannot
3456 * indicate write reference from
3457 * src_entry, since the entry is
3458 * marked as needs copy. Allocate a
3459 * fake entry that is used to
3460 * decrement object->un_pager.vnp.writecount
3461 * at the appropriate time. Attach
3462 * fake_entry to the deferred list.
3464 fake_entry = vm_map_entry_create(dst_map);
3465 fake_entry->eflags = MAP_ENTRY_VN_WRITECNT;
3466 src_entry->eflags &= ~MAP_ENTRY_VN_WRITECNT;
3467 vm_object_reference(src_object);
3468 fake_entry->object.vm_object = src_object;
3469 fake_entry->start = src_entry->start;
3470 fake_entry->end = src_entry->end;
3471 fake_entry->next = curthread->td_map_def_user;
3472 curthread->td_map_def_user = fake_entry;
3475 pmap_copy(dst_map->pmap, src_map->pmap,
3476 dst_entry->start, dst_entry->end - dst_entry->start,
3479 dst_entry->object.vm_object = NULL;
3480 dst_entry->offset = 0;
3481 if (src_entry->cred != NULL) {
3482 dst_entry->cred = curthread->td_ucred;
3483 crhold(dst_entry->cred);
3484 *fork_charge += size;
3489 * We don't want to make writeable wired pages copy-on-write.
3490 * Immediately copy these pages into the new map by simulating
3491 * page faults. The new pages are pageable.
3493 vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry,
3499 * vmspace_map_entry_forked:
3500 * Update the newly-forked vmspace each time a map entry is inherited
3501 * or copied. The values for vm_dsize and vm_tsize are approximate
3502 * (and mostly-obsolete ideas in the face of mmap(2) et al.)
3505 vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
3506 vm_map_entry_t entry)
3508 vm_size_t entrysize;
3511 if ((entry->eflags & MAP_ENTRY_GUARD) != 0)
3513 entrysize = entry->end - entry->start;
3514 vm2->vm_map.size += entrysize;
3515 if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
3516 vm2->vm_ssize += btoc(entrysize);
3517 } else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
3518 entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
3519 newend = MIN(entry->end,
3520 (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
3521 vm2->vm_dsize += btoc(newend - entry->start);
3522 } else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
3523 entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
3524 newend = MIN(entry->end,
3525 (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
3526 vm2->vm_tsize += btoc(newend - entry->start);
3532 * Create a new process vmspace structure and vm_map
3533 * based on those of an existing process. The new map
3534 * is based on the old map, according to the inheritance
3535 * values on the regions in that map.
3537 * XXX It might be worth coalescing the entries added to the new vmspace.
3539 * The source map must not be locked.
3542 vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
3544 struct vmspace *vm2;
3545 vm_map_t new_map, old_map;
3546 vm_map_entry_t new_entry, old_entry;
3551 old_map = &vm1->vm_map;
3552 /* Copy immutable fields of vm1 to vm2. */
3553 vm2 = vmspace_alloc(vm_map_min(old_map), vm_map_max(old_map),
3558 vm2->vm_taddr = vm1->vm_taddr;
3559 vm2->vm_daddr = vm1->vm_daddr;
3560 vm2->vm_maxsaddr = vm1->vm_maxsaddr;
3561 vm_map_lock(old_map);
3563 vm_map_wait_busy(old_map);
3564 new_map = &vm2->vm_map;
3565 locked = vm_map_trylock(new_map); /* trylock to silence WITNESS */
3566 KASSERT(locked, ("vmspace_fork: lock failed"));
3568 error = pmap_vmspace_copy(new_map->pmap, old_map->pmap);
3570 sx_xunlock(&old_map->lock);
3571 sx_xunlock(&new_map->lock);
3572 vm_map_process_deferred();
3577 new_map->anon_loc = old_map->anon_loc;
3579 old_entry = old_map->header.next;
3581 while (old_entry != &old_map->header) {
3582 if (old_entry->eflags & MAP_ENTRY_IS_SUB_MAP)
3583 panic("vm_map_fork: encountered a submap");
3585 inh = old_entry->inheritance;
3586 if ((old_entry->eflags & MAP_ENTRY_GUARD) != 0 &&
3587 inh != VM_INHERIT_NONE)
3588 inh = VM_INHERIT_COPY;
3591 case VM_INHERIT_NONE:
3594 case VM_INHERIT_SHARE:
3596 * Clone the entry, creating the shared object if necessary.
3598 object = old_entry->object.vm_object;
3599 if (object == NULL) {
3600 object = vm_object_allocate(OBJT_DEFAULT,
3601 atop(old_entry->end - old_entry->start));
3602 old_entry->object.vm_object = object;
3603 old_entry->offset = 0;
3604 if (old_entry->cred != NULL) {
3605 object->cred = old_entry->cred;
3606 object->charge = old_entry->end -
3608 old_entry->cred = NULL;
3613 * Add the reference before calling vm_object_shadow
3614 * to insure that a shadow object is created.
3616 vm_object_reference(object);
3617 if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3618 vm_object_shadow(&old_entry->object.vm_object,
3620 old_entry->end - old_entry->start);
3621 old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
3622 /* Transfer the second reference too. */
3623 vm_object_reference(
3624 old_entry->object.vm_object);
3627 * As in vm_map_simplify_entry(), the
3628 * vnode lock will not be acquired in
3629 * this call to vm_object_deallocate().
3631 vm_object_deallocate(object);
3632 object = old_entry->object.vm_object;
3634 VM_OBJECT_WLOCK(object);
3635 vm_object_clear_flag(object, OBJ_ONEMAPPING);
3636 if (old_entry->cred != NULL) {
3637 KASSERT(object->cred == NULL, ("vmspace_fork both cred"));
3638 object->cred = old_entry->cred;
3639 object->charge = old_entry->end - old_entry->start;
3640 old_entry->cred = NULL;
3644 * Assert the correct state of the vnode
3645 * v_writecount while the object is locked, to
3646 * not relock it later for the assertion
3649 if (old_entry->eflags & MAP_ENTRY_VN_WRITECNT &&
3650 object->type == OBJT_VNODE) {
3651 KASSERT(((struct vnode *)object->handle)->
3653 ("vmspace_fork: v_writecount %p", object));
3654 KASSERT(object->un_pager.vnp.writemappings > 0,
3655 ("vmspace_fork: vnp.writecount %p",
3658 VM_OBJECT_WUNLOCK(object);
3661 * Clone the entry, referencing the shared object.
3663 new_entry = vm_map_entry_create(new_map);
3664 *new_entry = *old_entry;
3665 new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
3666 MAP_ENTRY_IN_TRANSITION);
3667 new_entry->wiring_thread = NULL;
3668 new_entry->wired_count = 0;
3669 if (new_entry->eflags & MAP_ENTRY_VN_WRITECNT) {
3670 vnode_pager_update_writecount(object,
3671 new_entry->start, new_entry->end);
3675 * Insert the entry into the new map -- we know we're
3676 * inserting at the end of the new map.
3678 vm_map_entry_link(new_map, new_map->header.prev,
3680 vmspace_map_entry_forked(vm1, vm2, new_entry);
3683 * Update the physical map
3685 pmap_copy(new_map->pmap, old_map->pmap,
3687 (old_entry->end - old_entry->start),
3691 case VM_INHERIT_COPY:
3693 * Clone the entry and link into the map.
3695 new_entry = vm_map_entry_create(new_map);
3696 *new_entry = *old_entry;
3698 * Copied entry is COW over the old object.
3700 new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
3701 MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_VN_WRITECNT);
3702 new_entry->wiring_thread = NULL;
3703 new_entry->wired_count = 0;
3704 new_entry->object.vm_object = NULL;
3705 new_entry->cred = NULL;
3706 vm_map_entry_link(new_map, new_map->header.prev,
3708 vmspace_map_entry_forked(vm1, vm2, new_entry);
3709 vm_map_copy_entry(old_map, new_map, old_entry,
3710 new_entry, fork_charge);
3713 case VM_INHERIT_ZERO:
3715 * Create a new anonymous mapping entry modelled from
3718 new_entry = vm_map_entry_create(new_map);
3719 memset(new_entry, 0, sizeof(*new_entry));
3721 new_entry->start = old_entry->start;
3722 new_entry->end = old_entry->end;
3723 new_entry->eflags = old_entry->eflags &
3724 ~(MAP_ENTRY_USER_WIRED | MAP_ENTRY_IN_TRANSITION |
3725 MAP_ENTRY_VN_WRITECNT);
3726 new_entry->protection = old_entry->protection;
3727 new_entry->max_protection = old_entry->max_protection;
3728 new_entry->inheritance = VM_INHERIT_ZERO;
3730 vm_map_entry_link(new_map, new_map->header.prev,
3732 vmspace_map_entry_forked(vm1, vm2, new_entry);
3734 new_entry->cred = curthread->td_ucred;
3735 crhold(new_entry->cred);
3736 *fork_charge += (new_entry->end - new_entry->start);
3740 old_entry = old_entry->next;
3743 * Use inlined vm_map_unlock() to postpone handling the deferred
3744 * map entries, which cannot be done until both old_map and
3745 * new_map locks are released.
3747 sx_xunlock(&old_map->lock);
3748 sx_xunlock(&new_map->lock);
3749 vm_map_process_deferred();
3755 * Create a process's stack for exec_new_vmspace(). This function is never
3756 * asked to wire the newly created stack.
3759 vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
3760 vm_prot_t prot, vm_prot_t max, int cow)
3762 vm_size_t growsize, init_ssize;
3766 MPASS((map->flags & MAP_WIREFUTURE) == 0);
3767 growsize = sgrowsiz;
3768 init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
3770 vmemlim = lim_cur(curthread, RLIMIT_VMEM);
3771 /* If we would blow our VMEM resource limit, no go */
3772 if (map->size + init_ssize > vmemlim) {
3776 rv = vm_map_stack_locked(map, addrbos, max_ssize, growsize, prot,
3783 static int stack_guard_page = 1;
3784 SYSCTL_INT(_security_bsd, OID_AUTO, stack_guard_page, CTLFLAG_RWTUN,
3785 &stack_guard_page, 0,
3786 "Specifies the number of guard pages for a stack that grows");
3789 vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
3790 vm_size_t growsize, vm_prot_t prot, vm_prot_t max, int cow)
3792 vm_map_entry_t new_entry, prev_entry;
3793 vm_offset_t bot, gap_bot, gap_top, top;
3794 vm_size_t init_ssize, sgp;
3798 * The stack orientation is piggybacked with the cow argument.
3799 * Extract it into orient and mask the cow argument so that we
3800 * don't pass it around further.
3802 orient = cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP);
3803 KASSERT(orient != 0, ("No stack grow direction"));
3804 KASSERT(orient != (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP),
3807 if (addrbos < vm_map_min(map) ||
3808 addrbos + max_ssize > vm_map_max(map) ||
3809 addrbos + max_ssize <= addrbos)
3810 return (KERN_INVALID_ADDRESS);
3811 sgp = (vm_size_t)stack_guard_page * PAGE_SIZE;
3812 if (sgp >= max_ssize)
3813 return (KERN_INVALID_ARGUMENT);
3815 init_ssize = growsize;
3816 if (max_ssize < init_ssize + sgp)
3817 init_ssize = max_ssize - sgp;
3819 /* If addr is already mapped, no go */
3820 if (vm_map_lookup_entry(map, addrbos, &prev_entry))
3821 return (KERN_NO_SPACE);
3824 * If we can't accommodate max_ssize in the current mapping, no go.
3826 if (prev_entry->next->start < addrbos + max_ssize)
3827 return (KERN_NO_SPACE);
3830 * We initially map a stack of only init_ssize. We will grow as
3831 * needed later. Depending on the orientation of the stack (i.e.
3832 * the grow direction) we either map at the top of the range, the
3833 * bottom of the range or in the middle.
3835 * Note: we would normally expect prot and max to be VM_PROT_ALL,
3836 * and cow to be 0. Possibly we should eliminate these as input
3837 * parameters, and just pass these values here in the insert call.
3839 if (orient == MAP_STACK_GROWS_DOWN) {
3840 bot = addrbos + max_ssize - init_ssize;
3841 top = bot + init_ssize;
3844 } else /* if (orient == MAP_STACK_GROWS_UP) */ {
3846 top = bot + init_ssize;
3848 gap_top = addrbos + max_ssize;
3850 rv = vm_map_insert(map, NULL, 0, bot, top, prot, max, cow);
3851 if (rv != KERN_SUCCESS)
3853 new_entry = prev_entry->next;
3854 KASSERT(new_entry->end == top || new_entry->start == bot,
3855 ("Bad entry start/end for new stack entry"));
3856 KASSERT((orient & MAP_STACK_GROWS_DOWN) == 0 ||
3857 (new_entry->eflags & MAP_ENTRY_GROWS_DOWN) != 0,
3858 ("new entry lacks MAP_ENTRY_GROWS_DOWN"));
3859 KASSERT((orient & MAP_STACK_GROWS_UP) == 0 ||
3860 (new_entry->eflags & MAP_ENTRY_GROWS_UP) != 0,
3861 ("new entry lacks MAP_ENTRY_GROWS_UP"));
3862 rv = vm_map_insert(map, NULL, 0, gap_bot, gap_top, VM_PROT_NONE,
3863 VM_PROT_NONE, MAP_CREATE_GUARD | (orient == MAP_STACK_GROWS_DOWN ?
3864 MAP_CREATE_STACK_GAP_DN : MAP_CREATE_STACK_GAP_UP));
3865 if (rv != KERN_SUCCESS)
3866 (void)vm_map_delete(map, bot, top);
3871 * Attempts to grow a vm stack entry. Returns KERN_SUCCESS if we
3872 * successfully grow the stack.
3875 vm_map_growstack(vm_map_t map, vm_offset_t addr, vm_map_entry_t gap_entry)
3877 vm_map_entry_t stack_entry;
3881 vm_offset_t gap_end, gap_start, grow_start;
3882 size_t grow_amount, guard, max_grow;
3883 rlim_t lmemlim, stacklim, vmemlim;
3885 bool gap_deleted, grow_down, is_procstack;
3897 * Disallow stack growth when the access is performed by a
3898 * debugger or AIO daemon. The reason is that the wrong
3899 * resource limits are applied.
3901 if (map != &p->p_vmspace->vm_map || p->p_textvp == NULL)
3902 return (KERN_FAILURE);
3904 MPASS(!map->system_map);
3906 guard = stack_guard_page * PAGE_SIZE;
3907 lmemlim = lim_cur(curthread, RLIMIT_MEMLOCK);
3908 stacklim = lim_cur(curthread, RLIMIT_STACK);
3909 vmemlim = lim_cur(curthread, RLIMIT_VMEM);
3911 /* If addr is not in a hole for a stack grow area, no need to grow. */
3912 if (gap_entry == NULL && !vm_map_lookup_entry(map, addr, &gap_entry))
3913 return (KERN_FAILURE);
3914 if ((gap_entry->eflags & MAP_ENTRY_GUARD) == 0)
3915 return (KERN_SUCCESS);
3916 if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_DN) != 0) {
3917 stack_entry = gap_entry->next;
3918 if ((stack_entry->eflags & MAP_ENTRY_GROWS_DOWN) == 0 ||
3919 stack_entry->start != gap_entry->end)
3920 return (KERN_FAILURE);
3921 grow_amount = round_page(stack_entry->start - addr);
3923 } else if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_UP) != 0) {
3924 stack_entry = gap_entry->prev;
3925 if ((stack_entry->eflags & MAP_ENTRY_GROWS_UP) == 0 ||
3926 stack_entry->end != gap_entry->start)
3927 return (KERN_FAILURE);
3928 grow_amount = round_page(addr + 1 - stack_entry->end);
3931 return (KERN_FAILURE);
3933 max_grow = gap_entry->end - gap_entry->start;
3934 if (guard > max_grow)
3935 return (KERN_NO_SPACE);
3937 if (grow_amount > max_grow)
3938 return (KERN_NO_SPACE);
3941 * If this is the main process stack, see if we're over the stack
3944 is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr &&
3945 addr < (vm_offset_t)p->p_sysent->sv_usrstack;
3946 if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim))
3947 return (KERN_NO_SPACE);
3952 if (is_procstack && racct_set(p, RACCT_STACK,
3953 ctob(vm->vm_ssize) + grow_amount)) {
3955 return (KERN_NO_SPACE);
3961 grow_amount = roundup(grow_amount, sgrowsiz);
3962 if (grow_amount > max_grow)
3963 grow_amount = max_grow;
3964 if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
3965 grow_amount = trunc_page((vm_size_t)stacklim) -
3971 limit = racct_get_available(p, RACCT_STACK);
3973 if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > limit))
3974 grow_amount = limit - ctob(vm->vm_ssize);
3977 if (!old_mlock && (map->flags & MAP_WIREFUTURE) != 0) {
3978 if (ptoa(pmap_wired_count(map->pmap)) + grow_amount > lmemlim) {
3985 if (racct_set(p, RACCT_MEMLOCK,
3986 ptoa(pmap_wired_count(map->pmap)) + grow_amount)) {
3996 /* If we would blow our VMEM resource limit, no go */
3997 if (map->size + grow_amount > vmemlim) {
4004 if (racct_set(p, RACCT_VMEM, map->size + grow_amount)) {
4013 if (vm_map_lock_upgrade(map)) {
4015 vm_map_lock_read(map);
4020 grow_start = gap_entry->end - grow_amount;
4021 if (gap_entry->start + grow_amount == gap_entry->end) {
4022 gap_start = gap_entry->start;
4023 gap_end = gap_entry->end;
4024 vm_map_entry_delete(map, gap_entry);
4027 MPASS(gap_entry->start < gap_entry->end - grow_amount);
4028 gap_entry->end -= grow_amount;
4029 vm_map_entry_resize_free(map, gap_entry);
4030 gap_deleted = false;
4032 rv = vm_map_insert(map, NULL, 0, grow_start,
4033 grow_start + grow_amount,
4034 stack_entry->protection, stack_entry->max_protection,
4035 MAP_STACK_GROWS_DOWN);
4036 if (rv != KERN_SUCCESS) {
4038 rv1 = vm_map_insert(map, NULL, 0, gap_start,
4039 gap_end, VM_PROT_NONE, VM_PROT_NONE,
4040 MAP_CREATE_GUARD | MAP_CREATE_STACK_GAP_DN);
4041 MPASS(rv1 == KERN_SUCCESS);
4043 gap_entry->end += grow_amount;
4044 vm_map_entry_resize_free(map, gap_entry);
4048 grow_start = stack_entry->end;
4049 cred = stack_entry->cred;
4050 if (cred == NULL && stack_entry->object.vm_object != NULL)
4051 cred = stack_entry->object.vm_object->cred;
4052 if (cred != NULL && !swap_reserve_by_cred(grow_amount, cred))
4054 /* Grow the underlying object if applicable. */
4055 else if (stack_entry->object.vm_object == NULL ||
4056 vm_object_coalesce(stack_entry->object.vm_object,
4057 stack_entry->offset,
4058 (vm_size_t)(stack_entry->end - stack_entry->start),
4059 (vm_size_t)grow_amount, cred != NULL)) {
4060 if (gap_entry->start + grow_amount == gap_entry->end)
4061 vm_map_entry_delete(map, gap_entry);
4063 gap_entry->start += grow_amount;
4064 stack_entry->end += grow_amount;
4065 map->size += grow_amount;
4066 vm_map_entry_resize_free(map, stack_entry);
4071 if (rv == KERN_SUCCESS && is_procstack)
4072 vm->vm_ssize += btoc(grow_amount);
4075 * Heed the MAP_WIREFUTURE flag if it was set for this process.
4077 if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE) != 0) {
4079 vm_map_wire(map, grow_start, grow_start + grow_amount,
4080 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
4081 vm_map_lock_read(map);
4083 vm_map_lock_downgrade(map);
4087 if (racct_enable && rv != KERN_SUCCESS) {
4089 error = racct_set(p, RACCT_VMEM, map->size);
4090 KASSERT(error == 0, ("decreasing RACCT_VMEM failed"));
4092 error = racct_set(p, RACCT_MEMLOCK,
4093 ptoa(pmap_wired_count(map->pmap)));
4094 KASSERT(error == 0, ("decreasing RACCT_MEMLOCK failed"));
4096 error = racct_set(p, RACCT_STACK, ctob(vm->vm_ssize));
4097 KASSERT(error == 0, ("decreasing RACCT_STACK failed"));
4106 * Unshare the specified VM space for exec. If other processes are
4107 * mapped to it, then create a new one. The new vmspace is null.
4110 vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
4112 struct vmspace *oldvmspace = p->p_vmspace;
4113 struct vmspace *newvmspace;
4115 KASSERT((curthread->td_pflags & TDP_EXECVMSPC) == 0,
4116 ("vmspace_exec recursed"));
4117 newvmspace = vmspace_alloc(minuser, maxuser, pmap_pinit);
4118 if (newvmspace == NULL)
4120 newvmspace->vm_swrss = oldvmspace->vm_swrss;
4122 * This code is written like this for prototype purposes. The
4123 * goal is to avoid running down the vmspace here, but let the
4124 * other process's that are still using the vmspace to finally
4125 * run it down. Even though there is little or no chance of blocking
4126 * here, it is a good idea to keep this form for future mods.
4128 PROC_VMSPACE_LOCK(p);
4129 p->p_vmspace = newvmspace;
4130 PROC_VMSPACE_UNLOCK(p);
4131 if (p == curthread->td_proc)
4132 pmap_activate(curthread);
4133 curthread->td_pflags |= TDP_EXECVMSPC;
4138 * Unshare the specified VM space for forcing COW. This
4139 * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
4142 vmspace_unshare(struct proc *p)
4144 struct vmspace *oldvmspace = p->p_vmspace;
4145 struct vmspace *newvmspace;
4146 vm_ooffset_t fork_charge;
4148 if (oldvmspace->vm_refcnt == 1)
4151 newvmspace = vmspace_fork(oldvmspace, &fork_charge);
4152 if (newvmspace == NULL)
4154 if (!swap_reserve_by_cred(fork_charge, p->p_ucred)) {
4155 vmspace_free(newvmspace);
4158 PROC_VMSPACE_LOCK(p);
4159 p->p_vmspace = newvmspace;
4160 PROC_VMSPACE_UNLOCK(p);
4161 if (p == curthread->td_proc)
4162 pmap_activate(curthread);
4163 vmspace_free(oldvmspace);
4170 * Finds the VM object, offset, and
4171 * protection for a given virtual address in the
4172 * specified map, assuming a page fault of the
4175 * Leaves the map in question locked for read; return
4176 * values are guaranteed until a vm_map_lookup_done
4177 * call is performed. Note that the map argument
4178 * is in/out; the returned map must be used in
4179 * the call to vm_map_lookup_done.
4181 * A handle (out_entry) is returned for use in
4182 * vm_map_lookup_done, to make that fast.
4184 * If a lookup is requested with "write protection"
4185 * specified, the map may be changed to perform virtual
4186 * copying operations, although the data referenced will
4190 vm_map_lookup(vm_map_t *var_map, /* IN/OUT */
4192 vm_prot_t fault_typea,
4193 vm_map_entry_t *out_entry, /* OUT */
4194 vm_object_t *object, /* OUT */
4195 vm_pindex_t *pindex, /* OUT */
4196 vm_prot_t *out_prot, /* OUT */
4197 boolean_t *wired) /* OUT */
4199 vm_map_entry_t entry;
4200 vm_map_t map = *var_map;
4202 vm_prot_t fault_type = fault_typea;
4203 vm_object_t eobject;
4209 vm_map_lock_read(map);
4213 * Lookup the faulting address.
4215 if (!vm_map_lookup_entry(map, vaddr, out_entry)) {
4216 vm_map_unlock_read(map);
4217 return (KERN_INVALID_ADDRESS);
4225 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4226 vm_map_t old_map = map;
4228 *var_map = map = entry->object.sub_map;
4229 vm_map_unlock_read(old_map);
4234 * Check whether this task is allowed to have this page.
4236 prot = entry->protection;
4237 if ((fault_typea & VM_PROT_FAULT_LOOKUP) != 0) {
4238 fault_typea &= ~VM_PROT_FAULT_LOOKUP;
4239 if (prot == VM_PROT_NONE && map != kernel_map &&
4240 (entry->eflags & MAP_ENTRY_GUARD) != 0 &&
4241 (entry->eflags & (MAP_ENTRY_STACK_GAP_DN |
4242 MAP_ENTRY_STACK_GAP_UP)) != 0 &&
4243 vm_map_growstack(map, vaddr, entry) == KERN_SUCCESS)
4244 goto RetryLookupLocked;
4246 fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
4247 if ((fault_type & prot) != fault_type || prot == VM_PROT_NONE) {
4248 vm_map_unlock_read(map);
4249 return (KERN_PROTECTION_FAILURE);
4251 KASSERT((prot & VM_PROT_WRITE) == 0 || (entry->eflags &
4252 (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY)) !=
4253 (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY),
4254 ("entry %p flags %x", entry, entry->eflags));
4255 if ((fault_typea & VM_PROT_COPY) != 0 &&
4256 (entry->max_protection & VM_PROT_WRITE) == 0 &&
4257 (entry->eflags & MAP_ENTRY_COW) == 0) {
4258 vm_map_unlock_read(map);
4259 return (KERN_PROTECTION_FAILURE);
4263 * If this page is not pageable, we have to get it for all possible
4266 *wired = (entry->wired_count != 0);
4268 fault_type = entry->protection;
4269 size = entry->end - entry->start;
4271 * If the entry was copy-on-write, we either ...
4273 if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4275 * If we want to write the page, we may as well handle that
4276 * now since we've got the map locked.
4278 * If we don't need to write the page, we just demote the
4279 * permissions allowed.
4281 if ((fault_type & VM_PROT_WRITE) != 0 ||
4282 (fault_typea & VM_PROT_COPY) != 0) {
4284 * Make a new object, and place it in the object
4285 * chain. Note that no new references have appeared
4286 * -- one just moved from the map to the new
4289 if (vm_map_lock_upgrade(map))
4292 if (entry->cred == NULL) {
4294 * The debugger owner is charged for
4297 cred = curthread->td_ucred;
4299 if (!swap_reserve_by_cred(size, cred)) {
4302 return (KERN_RESOURCE_SHORTAGE);
4306 vm_object_shadow(&entry->object.vm_object,
4307 &entry->offset, size);
4308 entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
4309 eobject = entry->object.vm_object;
4310 if (eobject->cred != NULL) {
4312 * The object was not shadowed.
4314 swap_release_by_cred(size, entry->cred);
4315 crfree(entry->cred);
4317 } else if (entry->cred != NULL) {
4318 VM_OBJECT_WLOCK(eobject);
4319 eobject->cred = entry->cred;
4320 eobject->charge = size;
4321 VM_OBJECT_WUNLOCK(eobject);
4325 vm_map_lock_downgrade(map);
4328 * We're attempting to read a copy-on-write page --
4329 * don't allow writes.
4331 prot &= ~VM_PROT_WRITE;
4336 * Create an object if necessary.
4338 if (entry->object.vm_object == NULL &&
4340 if (vm_map_lock_upgrade(map))
4342 entry->object.vm_object = vm_object_allocate(OBJT_DEFAULT,
4345 if (entry->cred != NULL) {
4346 VM_OBJECT_WLOCK(entry->object.vm_object);
4347 entry->object.vm_object->cred = entry->cred;
4348 entry->object.vm_object->charge = size;
4349 VM_OBJECT_WUNLOCK(entry->object.vm_object);
4352 vm_map_lock_downgrade(map);
4356 * Return the object/offset from this entry. If the entry was
4357 * copy-on-write or empty, it has been fixed up.
4359 *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4360 *object = entry->object.vm_object;
4363 return (KERN_SUCCESS);
4367 * vm_map_lookup_locked:
4369 * Lookup the faulting address. A version of vm_map_lookup that returns
4370 * KERN_FAILURE instead of blocking on map lock or memory allocation.
4373 vm_map_lookup_locked(vm_map_t *var_map, /* IN/OUT */
4375 vm_prot_t fault_typea,
4376 vm_map_entry_t *out_entry, /* OUT */
4377 vm_object_t *object, /* OUT */
4378 vm_pindex_t *pindex, /* OUT */
4379 vm_prot_t *out_prot, /* OUT */
4380 boolean_t *wired) /* OUT */
4382 vm_map_entry_t entry;
4383 vm_map_t map = *var_map;
4385 vm_prot_t fault_type = fault_typea;
4388 * Lookup the faulting address.
4390 if (!vm_map_lookup_entry(map, vaddr, out_entry))
4391 return (KERN_INVALID_ADDRESS);
4396 * Fail if the entry refers to a submap.
4398 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
4399 return (KERN_FAILURE);
4402 * Check whether this task is allowed to have this page.
4404 prot = entry->protection;
4405 fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
4406 if ((fault_type & prot) != fault_type)
4407 return (KERN_PROTECTION_FAILURE);
4410 * If this page is not pageable, we have to get it for all possible
4413 *wired = (entry->wired_count != 0);
4415 fault_type = entry->protection;
4417 if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4419 * Fail if the entry was copy-on-write for a write fault.
4421 if (fault_type & VM_PROT_WRITE)
4422 return (KERN_FAILURE);
4424 * We're attempting to read a copy-on-write page --
4425 * don't allow writes.
4427 prot &= ~VM_PROT_WRITE;
4431 * Fail if an object should be created.
4433 if (entry->object.vm_object == NULL && !map->system_map)
4434 return (KERN_FAILURE);
4437 * Return the object/offset from this entry. If the entry was
4438 * copy-on-write or empty, it has been fixed up.
4440 *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4441 *object = entry->object.vm_object;
4444 return (KERN_SUCCESS);
4448 * vm_map_lookup_done:
4450 * Releases locks acquired by a vm_map_lookup
4451 * (according to the handle returned by that lookup).
4454 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
4457 * Unlock the main-level map
4459 vm_map_unlock_read(map);
4463 vm_map_max_KBI(const struct vm_map *map)
4466 return (vm_map_max(map));
4470 vm_map_min_KBI(const struct vm_map *map)
4473 return (vm_map_min(map));
4477 vm_map_pmap_KBI(vm_map_t map)
4483 #include "opt_ddb.h"
4485 #include <sys/kernel.h>
4487 #include <ddb/ddb.h>
4490 vm_map_print(vm_map_t map)
4492 vm_map_entry_t entry;
4494 db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
4496 (void *)map->pmap, map->nentries, map->timestamp);
4499 for (entry = map->header.next; entry != &map->header;
4500 entry = entry->next) {
4501 db_iprintf("map entry %p: start=%p, end=%p, eflags=%#x, \n",
4502 (void *)entry, (void *)entry->start, (void *)entry->end,
4505 static char *inheritance_name[4] =
4506 {"share", "copy", "none", "donate_copy"};
4508 db_iprintf(" prot=%x/%x/%s",
4510 entry->max_protection,
4511 inheritance_name[(int)(unsigned char)entry->inheritance]);
4512 if (entry->wired_count != 0)
4513 db_printf(", wired");
4515 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4516 db_printf(", share=%p, offset=0x%jx\n",
4517 (void *)entry->object.sub_map,
4518 (uintmax_t)entry->offset);
4519 if ((entry->prev == &map->header) ||
4520 (entry->prev->object.sub_map !=
4521 entry->object.sub_map)) {
4523 vm_map_print((vm_map_t)entry->object.sub_map);
4527 if (entry->cred != NULL)
4528 db_printf(", ruid %d", entry->cred->cr_ruid);
4529 db_printf(", object=%p, offset=0x%jx",
4530 (void *)entry->object.vm_object,
4531 (uintmax_t)entry->offset);
4532 if (entry->object.vm_object && entry->object.vm_object->cred)
4533 db_printf(", obj ruid %d charge %jx",
4534 entry->object.vm_object->cred->cr_ruid,
4535 (uintmax_t)entry->object.vm_object->charge);
4536 if (entry->eflags & MAP_ENTRY_COW)
4537 db_printf(", copy (%s)",
4538 (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
4541 if ((entry->prev == &map->header) ||
4542 (entry->prev->object.vm_object !=
4543 entry->object.vm_object)) {
4545 vm_object_print((db_expr_t)(intptr_t)
4546 entry->object.vm_object,
4555 DB_SHOW_COMMAND(map, map)
4559 db_printf("usage: show map <addr>\n");
4562 vm_map_print((vm_map_t)addr);
4565 DB_SHOW_COMMAND(procvm, procvm)
4570 p = db_lookup_proc(addr);
4575 db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
4576 (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
4577 (void *)vmspace_pmap(p->p_vmspace));
4579 vm_map_print((vm_map_t)&p->p_vmspace->vm_map);