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>
73 #include <sys/kernel.h>
76 #include <sys/mutex.h>
78 #include <sys/vmmeter.h>
80 #include <sys/vnode.h>
81 #include <sys/racct.h>
82 #include <sys/resourcevar.h>
83 #include <sys/rwlock.h>
85 #include <sys/sysctl.h>
86 #include <sys/sysent.h>
90 #include <vm/vm_param.h>
92 #include <vm/vm_map.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_pageout.h>
95 #include <vm/vm_object.h>
96 #include <vm/vm_pager.h>
97 #include <vm/vm_kern.h>
98 #include <vm/vm_extern.h>
99 #include <vm/vnode_pager.h>
100 #include <vm/swap_pager.h>
104 * Virtual memory maps provide for the mapping, protection,
105 * and sharing of virtual memory objects. In addition,
106 * this module provides for an efficient virtual copy of
107 * memory from one map to another.
109 * Synchronization is required prior to most operations.
111 * Maps consist of an ordered doubly-linked list of simple
112 * entries; a self-adjusting binary search tree of these
113 * entries is used to speed up lookups.
115 * Since portions of maps are specified by start/end addresses,
116 * which may not align with existing map entries, all
117 * routines merely "clip" entries to these start/end values.
118 * [That is, an entry is split into two, bordering at a
119 * start or end value.] Note that these clippings may not
120 * always be necessary (as the two resulting entries are then
121 * not changed); however, the clipping is done for convenience.
123 * As mentioned above, virtual copy operations are performed
124 * by copying VM object references from one map to
125 * another, and then marking both regions as copy-on-write.
128 static struct mtx map_sleep_mtx;
129 static uma_zone_t mapentzone;
130 static uma_zone_t kmapentzone;
131 static uma_zone_t vmspace_zone;
132 static int vmspace_zinit(void *mem, int size, int flags);
133 static void _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min,
135 static void vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map);
136 static void vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry);
137 static void vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry);
138 static int vm_map_growstack(vm_map_t map, vm_offset_t addr,
139 vm_map_entry_t gap_entry);
140 static void vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
141 vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags);
143 static void vmspace_zdtor(void *mem, int size, void *arg);
145 static int vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos,
146 vm_size_t max_ssize, vm_size_t growsize, vm_prot_t prot, vm_prot_t max,
148 static void vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
149 vm_offset_t failed_addr);
151 #define ENTRY_CHARGED(e) ((e)->cred != NULL || \
152 ((e)->object.vm_object != NULL && (e)->object.vm_object->cred != NULL && \
153 !((e)->eflags & MAP_ENTRY_NEEDS_COPY)))
156 * PROC_VMSPACE_{UN,}LOCK() can be a noop as long as vmspaces are type
159 #define PROC_VMSPACE_LOCK(p) do { } while (0)
160 #define PROC_VMSPACE_UNLOCK(p) do { } while (0)
163 * VM_MAP_RANGE_CHECK: [ internal use only ]
165 * Asserts that the starting and ending region
166 * addresses fall within the valid range of the map.
168 #define VM_MAP_RANGE_CHECK(map, start, end) \
170 if (start < vm_map_min(map)) \
171 start = vm_map_min(map); \
172 if (end > vm_map_max(map)) \
173 end = vm_map_max(map); \
178 #ifndef UMA_MD_SMALL_ALLOC
181 * Allocate a new slab for kernel map entries. The kernel map may be locked or
182 * unlocked, depending on whether the request is coming from the kernel map or a
183 * submap. This function allocates a virtual address range directly from the
184 * kernel map instead of the kmem_* layer to avoid recursion on the kernel map
185 * lock and also to avoid triggering allocator recursion in the vmem boundary
189 kmapent_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
195 *pflag = UMA_SLAB_PRIV;
197 if (!(locked = vm_map_locked(kernel_map)))
198 vm_map_lock(kernel_map);
199 addr = vm_map_findspace(kernel_map, vm_map_min(kernel_map), bytes);
200 if (addr + bytes < addr || addr + bytes > vm_map_max(kernel_map))
201 panic("%s: kernel map is exhausted", __func__);
202 error = vm_map_insert(kernel_map, NULL, 0, addr, addr + bytes,
203 VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
204 if (error != KERN_SUCCESS)
205 panic("%s: vm_map_insert() failed: %d", __func__, error);
207 vm_map_unlock(kernel_map);
208 error = kmem_back_domain(domain, kernel_object, addr, bytes, M_NOWAIT |
209 M_USE_RESERVE | (wait & M_ZERO));
210 if (error == KERN_SUCCESS) {
211 return ((void *)addr);
214 vm_map_lock(kernel_map);
215 vm_map_delete(kernel_map, addr, bytes);
217 vm_map_unlock(kernel_map);
223 kmapent_free(void *item, vm_size_t size, uint8_t pflag)
228 if ((pflag & UMA_SLAB_PRIV) == 0)
232 addr = (vm_offset_t)item;
233 kmem_unback(kernel_object, addr, size);
234 error = vm_map_remove(kernel_map, addr, addr + size);
235 KASSERT(error == KERN_SUCCESS,
236 ("%s: vm_map_remove failed: %d", __func__, error));
240 * The worst-case upper bound on the number of kernel map entries that may be
241 * created before the zone must be replenished in _vm_map_unlock().
243 #define KMAPENT_RESERVE 1
245 #endif /* !UMD_MD_SMALL_ALLOC */
250 * Initialize the vm_map module. Must be called before any other vm_map
253 * User map and entry structures are allocated from the general purpose
254 * memory pool. Kernel maps are statically defined. Kernel map entries
255 * require special handling to avoid recursion; see the comments above
256 * kmapent_alloc() and in vm_map_entry_create().
261 mtx_init(&map_sleep_mtx, "vm map sleep mutex", NULL, MTX_DEF);
264 * Disable the use of per-CPU buckets: map entry allocation is
265 * serialized by the kernel map lock.
267 kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry),
268 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
269 UMA_ZONE_VM | UMA_ZONE_NOBUCKET);
270 #ifndef UMA_MD_SMALL_ALLOC
271 /* Reserve an extra map entry for use when replenishing the reserve. */
272 uma_zone_reserve(kmapentzone, KMAPENT_RESERVE + 1);
273 uma_prealloc(kmapentzone, KMAPENT_RESERVE + 1);
274 uma_zone_set_allocf(kmapentzone, kmapent_alloc);
275 uma_zone_set_freef(kmapentzone, kmapent_free);
278 mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry),
279 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
280 vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
286 vmspace_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
290 vmspace_zinit(void *mem, int size, int flags)
295 vm = (struct vmspace *)mem;
298 memset(map, 0, sizeof(*map));
299 mtx_init(&map->system_mtx, "vm map (system)", NULL,
300 MTX_DEF | MTX_DUPOK);
301 sx_init(&map->lock, "vm map (user)");
302 PMAP_LOCK_INIT(vmspace_pmap(vm));
308 vmspace_zdtor(void *mem, int size, void *arg)
312 vm = (struct vmspace *)mem;
313 KASSERT(vm->vm_map.nentries == 0,
314 ("vmspace %p nentries == %d on free", vm, vm->vm_map.nentries));
315 KASSERT(vm->vm_map.size == 0,
316 ("vmspace %p size == %ju on free", vm, (uintmax_t)vm->vm_map.size));
318 #endif /* INVARIANTS */
321 * Allocate a vmspace structure, including a vm_map and pmap,
322 * and initialize those structures. The refcnt is set to 1.
325 vmspace_alloc(vm_offset_t min, vm_offset_t max, pmap_pinit_t pinit)
329 vm = uma_zalloc(vmspace_zone, M_WAITOK);
330 KASSERT(vm->vm_map.pmap == NULL, ("vm_map.pmap must be NULL"));
331 if (!pinit(vmspace_pmap(vm))) {
332 uma_zfree(vmspace_zone, vm);
335 CTR1(KTR_VM, "vmspace_alloc: %p", vm);
336 _vm_map_init(&vm->vm_map, vmspace_pmap(vm), min, max);
337 refcount_init(&vm->vm_refcnt, 1);
352 vmspace_container_reset(struct proc *p)
356 racct_set(p, RACCT_DATA, 0);
357 racct_set(p, RACCT_STACK, 0);
358 racct_set(p, RACCT_RSS, 0);
359 racct_set(p, RACCT_MEMLOCK, 0);
360 racct_set(p, RACCT_VMEM, 0);
366 vmspace_dofree(struct vmspace *vm)
369 CTR1(KTR_VM, "vmspace_free: %p", vm);
372 * Make sure any SysV shm is freed, it might not have been in
378 * Lock the map, to wait out all other references to it.
379 * Delete all of the mappings and pages they hold, then call
380 * the pmap module to reclaim anything left.
382 (void)vm_map_remove(&vm->vm_map, vm_map_min(&vm->vm_map),
383 vm_map_max(&vm->vm_map));
385 pmap_release(vmspace_pmap(vm));
386 vm->vm_map.pmap = NULL;
387 uma_zfree(vmspace_zone, vm);
391 vmspace_free(struct vmspace *vm)
394 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
395 "vmspace_free() called");
397 if (refcount_release(&vm->vm_refcnt))
402 vmspace_exitfree(struct proc *p)
406 PROC_VMSPACE_LOCK(p);
409 PROC_VMSPACE_UNLOCK(p);
410 KASSERT(vm == &vmspace0, ("vmspace_exitfree: wrong vmspace"));
415 vmspace_exit(struct thread *td)
425 * Prepare to release the vmspace reference. The thread that releases
426 * the last reference is responsible for tearing down the vmspace.
427 * However, threads not releasing the final reference must switch to the
428 * kernel's vmspace0 before the decrement so that the subsequent pmap
429 * deactivation does not modify a freed vmspace.
431 refcount_acquire(&vmspace0.vm_refcnt);
432 if (!(released = refcount_release_if_last(&vm->vm_refcnt))) {
433 if (p->p_vmspace != &vmspace0) {
434 PROC_VMSPACE_LOCK(p);
435 p->p_vmspace = &vmspace0;
436 PROC_VMSPACE_UNLOCK(p);
439 released = refcount_release(&vm->vm_refcnt);
443 * pmap_remove_pages() expects the pmap to be active, so switch
444 * back first if necessary.
446 if (p->p_vmspace != vm) {
447 PROC_VMSPACE_LOCK(p);
449 PROC_VMSPACE_UNLOCK(p);
452 pmap_remove_pages(vmspace_pmap(vm));
453 PROC_VMSPACE_LOCK(p);
454 p->p_vmspace = &vmspace0;
455 PROC_VMSPACE_UNLOCK(p);
461 vmspace_container_reset(p);
465 /* Acquire reference to vmspace owned by another process. */
468 vmspace_acquire_ref(struct proc *p)
472 PROC_VMSPACE_LOCK(p);
474 if (vm == NULL || !refcount_acquire_if_not_zero(&vm->vm_refcnt)) {
475 PROC_VMSPACE_UNLOCK(p);
478 if (vm != p->p_vmspace) {
479 PROC_VMSPACE_UNLOCK(p);
483 PROC_VMSPACE_UNLOCK(p);
488 * Switch between vmspaces in an AIO kernel process.
490 * The new vmspace is either the vmspace of a user process obtained
491 * from an active AIO request or the initial vmspace of the AIO kernel
492 * process (when it is idling). Because user processes will block to
493 * drain any active AIO requests before proceeding in exit() or
494 * execve(), the reference count for vmspaces from AIO requests can
495 * never be 0. Similarly, AIO kernel processes hold an extra
496 * reference on their initial vmspace for the life of the process. As
497 * a result, the 'newvm' vmspace always has a non-zero reference
498 * count. This permits an additional reference on 'newvm' to be
499 * acquired via a simple atomic increment rather than the loop in
500 * vmspace_acquire_ref() above.
503 vmspace_switch_aio(struct vmspace *newvm)
505 struct vmspace *oldvm;
507 /* XXX: Need some way to assert that this is an aio daemon. */
509 KASSERT(refcount_load(&newvm->vm_refcnt) > 0,
510 ("vmspace_switch_aio: newvm unreferenced"));
512 oldvm = curproc->p_vmspace;
517 * Point to the new address space and refer to it.
519 curproc->p_vmspace = newvm;
520 refcount_acquire(&newvm->vm_refcnt);
522 /* Activate the new mapping. */
523 pmap_activate(curthread);
529 _vm_map_lock(vm_map_t map, const char *file, int line)
533 mtx_lock_flags_(&map->system_mtx, 0, file, line);
535 sx_xlock_(&map->lock, file, line);
540 vm_map_entry_set_vnode_text(vm_map_entry_t entry, bool add)
546 if ((entry->eflags & MAP_ENTRY_VN_EXEC) == 0)
548 KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
549 ("Submap with execs"));
550 object = entry->object.vm_object;
551 KASSERT(object != NULL, ("No object for text, entry %p", entry));
552 if ((object->flags & OBJ_ANON) != 0)
553 object = object->handle;
555 KASSERT(object->backing_object == NULL,
556 ("non-anon object %p shadows", object));
557 KASSERT(object != NULL, ("No content object for text, entry %p obj %p",
558 entry, entry->object.vm_object));
561 * Mostly, we do not lock the backing object. It is
562 * referenced by the entry we are processing, so it cannot go
565 vm_pager_getvp(object, &vp, &vp_held);
568 VOP_SET_TEXT_CHECKED(vp);
570 vn_lock(vp, LK_SHARED | LK_RETRY);
571 VOP_UNSET_TEXT_CHECKED(vp);
580 * Use a different name for this vm_map_entry field when it's use
581 * is not consistent with its use as part of an ordered search tree.
583 #define defer_next right
586 vm_map_process_deferred(void)
589 vm_map_entry_t entry, next;
593 entry = td->td_map_def_user;
594 td->td_map_def_user = NULL;
595 while (entry != NULL) {
596 next = entry->defer_next;
597 MPASS((entry->eflags & (MAP_ENTRY_WRITECNT |
598 MAP_ENTRY_VN_EXEC)) != (MAP_ENTRY_WRITECNT |
600 if ((entry->eflags & MAP_ENTRY_WRITECNT) != 0) {
602 * Decrement the object's writemappings and
603 * possibly the vnode's v_writecount.
605 KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
606 ("Submap with writecount"));
607 object = entry->object.vm_object;
608 KASSERT(object != NULL, ("No object for writecount"));
609 vm_pager_release_writecount(object, entry->start,
612 vm_map_entry_set_vnode_text(entry, false);
613 vm_map_entry_deallocate(entry, FALSE);
620 _vm_map_assert_locked(vm_map_t map, const char *file, int line)
624 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
626 sx_assert_(&map->lock, SA_XLOCKED, file, line);
629 #define VM_MAP_ASSERT_LOCKED(map) \
630 _vm_map_assert_locked(map, LOCK_FILE, LOCK_LINE)
632 enum { VMMAP_CHECK_NONE, VMMAP_CHECK_UNLOCK, VMMAP_CHECK_ALL };
634 static int enable_vmmap_check = VMMAP_CHECK_UNLOCK;
636 static int enable_vmmap_check = VMMAP_CHECK_NONE;
638 SYSCTL_INT(_debug, OID_AUTO, vmmap_check, CTLFLAG_RWTUN,
639 &enable_vmmap_check, 0, "Enable vm map consistency checking");
641 static void _vm_map_assert_consistent(vm_map_t map, int check);
643 #define VM_MAP_ASSERT_CONSISTENT(map) \
644 _vm_map_assert_consistent(map, VMMAP_CHECK_ALL)
646 #define VM_MAP_UNLOCK_CONSISTENT(map) do { \
647 if (map->nupdates > map->nentries) { \
648 _vm_map_assert_consistent(map, VMMAP_CHECK_UNLOCK); \
653 #define VM_MAP_UNLOCK_CONSISTENT(map)
656 #define VM_MAP_ASSERT_LOCKED(map)
657 #define VM_MAP_ASSERT_CONSISTENT(map)
658 #define VM_MAP_UNLOCK_CONSISTENT(map)
659 #endif /* INVARIANTS */
662 _vm_map_unlock(vm_map_t map, const char *file, int line)
665 VM_MAP_UNLOCK_CONSISTENT(map);
666 if (map->system_map) {
667 #ifndef UMA_MD_SMALL_ALLOC
668 if (map == kernel_map && (map->flags & MAP_REPLENISH) != 0) {
669 uma_prealloc(kmapentzone, 1);
670 map->flags &= ~MAP_REPLENISH;
673 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
675 sx_xunlock_(&map->lock, file, line);
676 vm_map_process_deferred();
681 _vm_map_lock_read(vm_map_t map, const char *file, int line)
685 mtx_lock_flags_(&map->system_mtx, 0, file, line);
687 sx_slock_(&map->lock, file, line);
691 _vm_map_unlock_read(vm_map_t map, const char *file, int line)
694 if (map->system_map) {
695 KASSERT((map->flags & MAP_REPLENISH) == 0,
696 ("%s: MAP_REPLENISH leaked", __func__));
697 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
699 sx_sunlock_(&map->lock, file, line);
700 vm_map_process_deferred();
705 _vm_map_trylock(vm_map_t map, const char *file, int line)
709 error = map->system_map ?
710 !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
711 !sx_try_xlock_(&map->lock, file, line);
718 _vm_map_trylock_read(vm_map_t map, const char *file, int line)
722 error = map->system_map ?
723 !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
724 !sx_try_slock_(&map->lock, file, line);
729 * _vm_map_lock_upgrade: [ internal use only ]
731 * Tries to upgrade a read (shared) lock on the specified map to a write
732 * (exclusive) lock. Returns the value "0" if the upgrade succeeds and a
733 * non-zero value if the upgrade fails. If the upgrade fails, the map is
734 * returned without a read or write lock held.
736 * Requires that the map be read locked.
739 _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
741 unsigned int last_timestamp;
743 if (map->system_map) {
744 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
746 if (!sx_try_upgrade_(&map->lock, file, line)) {
747 last_timestamp = map->timestamp;
748 sx_sunlock_(&map->lock, file, line);
749 vm_map_process_deferred();
751 * If the map's timestamp does not change while the
752 * map is unlocked, then the upgrade succeeds.
754 sx_xlock_(&map->lock, file, line);
755 if (last_timestamp != map->timestamp) {
756 sx_xunlock_(&map->lock, file, line);
766 _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
769 if (map->system_map) {
770 KASSERT((map->flags & MAP_REPLENISH) == 0,
771 ("%s: MAP_REPLENISH leaked", __func__));
772 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
774 VM_MAP_UNLOCK_CONSISTENT(map);
775 sx_downgrade_(&map->lock, file, line);
782 * Returns a non-zero value if the caller holds a write (exclusive) lock
783 * on the specified map and the value "0" otherwise.
786 vm_map_locked(vm_map_t map)
790 return (mtx_owned(&map->system_mtx));
792 return (sx_xlocked(&map->lock));
796 * _vm_map_unlock_and_wait:
798 * Atomically releases the lock on the specified map and puts the calling
799 * thread to sleep. The calling thread will remain asleep until either
800 * vm_map_wakeup() is performed on the map or the specified timeout is
803 * WARNING! This function does not perform deferred deallocations of
804 * objects and map entries. Therefore, the calling thread is expected to
805 * reacquire the map lock after reawakening and later perform an ordinary
806 * unlock operation, such as vm_map_unlock(), before completing its
807 * operation on the map.
810 _vm_map_unlock_and_wait(vm_map_t map, int timo, const char *file, int line)
813 VM_MAP_UNLOCK_CONSISTENT(map);
814 mtx_lock(&map_sleep_mtx);
815 if (map->system_map) {
816 KASSERT((map->flags & MAP_REPLENISH) == 0,
817 ("%s: MAP_REPLENISH leaked", __func__));
818 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
820 sx_xunlock_(&map->lock, file, line);
822 return (msleep(&map->root, &map_sleep_mtx, PDROP | PVM, "vmmaps",
829 * Awaken any threads that have slept on the map using
830 * vm_map_unlock_and_wait().
833 vm_map_wakeup(vm_map_t map)
837 * Acquire and release map_sleep_mtx to prevent a wakeup()
838 * from being performed (and lost) between the map unlock
839 * and the msleep() in _vm_map_unlock_and_wait().
841 mtx_lock(&map_sleep_mtx);
842 mtx_unlock(&map_sleep_mtx);
847 vm_map_busy(vm_map_t map)
850 VM_MAP_ASSERT_LOCKED(map);
855 vm_map_unbusy(vm_map_t map)
858 VM_MAP_ASSERT_LOCKED(map);
859 KASSERT(map->busy, ("vm_map_unbusy: not busy"));
860 if (--map->busy == 0 && (map->flags & MAP_BUSY_WAKEUP)) {
861 vm_map_modflags(map, 0, MAP_BUSY_WAKEUP);
867 vm_map_wait_busy(vm_map_t map)
870 VM_MAP_ASSERT_LOCKED(map);
872 vm_map_modflags(map, MAP_BUSY_WAKEUP, 0);
874 msleep(&map->busy, &map->system_mtx, 0, "mbusy", 0);
876 sx_sleep(&map->busy, &map->lock, 0, "mbusy", 0);
882 vmspace_resident_count(struct vmspace *vmspace)
884 return pmap_resident_count(vmspace_pmap(vmspace));
888 * Initialize an existing vm_map structure
889 * such as that in the vmspace structure.
892 _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
895 map->header.eflags = MAP_ENTRY_HEADER;
896 map->needs_wakeup = FALSE;
899 map->header.end = min;
900 map->header.start = max;
902 map->header.left = map->header.right = &map->header;
913 vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
916 _vm_map_init(map, pmap, min, max);
917 mtx_init(&map->system_mtx, "vm map (system)", NULL,
918 MTX_DEF | MTX_DUPOK);
919 sx_init(&map->lock, "vm map (user)");
923 * vm_map_entry_dispose: [ internal use only ]
925 * Inverse of vm_map_entry_create.
928 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
930 uma_zfree(map->system_map ? kmapentzone : mapentzone, entry);
934 * vm_map_entry_create: [ internal use only ]
936 * Allocates a VM map entry for insertion.
937 * No entry fields are filled in.
939 static vm_map_entry_t
940 vm_map_entry_create(vm_map_t map)
942 vm_map_entry_t new_entry;
944 #ifndef UMA_MD_SMALL_ALLOC
945 if (map == kernel_map) {
946 VM_MAP_ASSERT_LOCKED(map);
949 * A new slab of kernel map entries cannot be allocated at this
950 * point because the kernel map has not yet been updated to
951 * reflect the caller's request. Therefore, we allocate a new
952 * map entry, dipping into the reserve if necessary, and set a
953 * flag indicating that the reserve must be replenished before
954 * the map is unlocked.
956 new_entry = uma_zalloc(kmapentzone, M_NOWAIT | M_NOVM);
957 if (new_entry == NULL) {
958 new_entry = uma_zalloc(kmapentzone,
959 M_NOWAIT | M_NOVM | M_USE_RESERVE);
960 kernel_map->flags |= MAP_REPLENISH;
964 if (map->system_map) {
965 new_entry = uma_zalloc(kmapentzone, M_NOWAIT);
967 new_entry = uma_zalloc(mapentzone, M_WAITOK);
969 KASSERT(new_entry != NULL,
970 ("vm_map_entry_create: kernel resources exhausted"));
975 * vm_map_entry_set_behavior:
977 * Set the expected access behavior, either normal, random, or
981 vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
983 entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
984 (behavior & MAP_ENTRY_BEHAV_MASK);
988 * vm_map_entry_max_free_{left,right}:
990 * Compute the size of the largest free gap between two entries,
991 * one the root of a tree and the other the ancestor of that root
992 * that is the least or greatest ancestor found on the search path.
994 static inline vm_size_t
995 vm_map_entry_max_free_left(vm_map_entry_t root, vm_map_entry_t left_ancestor)
998 return (root->left != left_ancestor ?
999 root->left->max_free : root->start - left_ancestor->end);
1002 static inline vm_size_t
1003 vm_map_entry_max_free_right(vm_map_entry_t root, vm_map_entry_t right_ancestor)
1006 return (root->right != right_ancestor ?
1007 root->right->max_free : right_ancestor->start - root->end);
1011 * vm_map_entry_{pred,succ}:
1013 * Find the {predecessor, successor} of the entry by taking one step
1014 * in the appropriate direction and backtracking as much as necessary.
1015 * vm_map_entry_succ is defined in vm_map.h.
1017 static inline vm_map_entry_t
1018 vm_map_entry_pred(vm_map_entry_t entry)
1020 vm_map_entry_t prior;
1022 prior = entry->left;
1023 if (prior->right->start < entry->start) {
1025 prior = prior->right;
1026 while (prior->right != entry);
1031 static inline vm_size_t
1032 vm_size_max(vm_size_t a, vm_size_t b)
1035 return (a > b ? a : b);
1038 #define SPLAY_LEFT_STEP(root, y, llist, rlist, test) do { \
1040 vm_size_t max_free; \
1043 * Infer root->right->max_free == root->max_free when \
1044 * y->max_free < root->max_free || root->max_free == 0. \
1045 * Otherwise, look right to find it. \
1048 max_free = root->max_free; \
1049 KASSERT(max_free == vm_size_max( \
1050 vm_map_entry_max_free_left(root, llist), \
1051 vm_map_entry_max_free_right(root, rlist)), \
1052 ("%s: max_free invariant fails", __func__)); \
1053 if (max_free - 1 < vm_map_entry_max_free_left(root, llist)) \
1054 max_free = vm_map_entry_max_free_right(root, rlist); \
1055 if (y != llist && (test)) { \
1056 /* Rotate right and make y root. */ \
1061 if (max_free < y->max_free) \
1062 root->max_free = max_free = \
1063 vm_size_max(max_free, z->max_free); \
1064 } else if (max_free < y->max_free) \
1065 root->max_free = max_free = \
1066 vm_size_max(max_free, root->start - y->end);\
1070 /* Copy right->max_free. Put root on rlist. */ \
1071 root->max_free = max_free; \
1072 KASSERT(max_free == vm_map_entry_max_free_right(root, rlist), \
1073 ("%s: max_free not copied from right", __func__)); \
1074 root->left = rlist; \
1076 root = y != llist ? y : NULL; \
1079 #define SPLAY_RIGHT_STEP(root, y, llist, rlist, test) do { \
1081 vm_size_t max_free; \
1084 * Infer root->left->max_free == root->max_free when \
1085 * y->max_free < root->max_free || root->max_free == 0. \
1086 * Otherwise, look left to find it. \
1089 max_free = root->max_free; \
1090 KASSERT(max_free == vm_size_max( \
1091 vm_map_entry_max_free_left(root, llist), \
1092 vm_map_entry_max_free_right(root, rlist)), \
1093 ("%s: max_free invariant fails", __func__)); \
1094 if (max_free - 1 < vm_map_entry_max_free_right(root, rlist)) \
1095 max_free = vm_map_entry_max_free_left(root, llist); \
1096 if (y != rlist && (test)) { \
1097 /* Rotate left and make y root. */ \
1102 if (max_free < y->max_free) \
1103 root->max_free = max_free = \
1104 vm_size_max(max_free, z->max_free); \
1105 } else if (max_free < y->max_free) \
1106 root->max_free = max_free = \
1107 vm_size_max(max_free, y->start - root->end);\
1111 /* Copy left->max_free. Put root on llist. */ \
1112 root->max_free = max_free; \
1113 KASSERT(max_free == vm_map_entry_max_free_left(root, llist), \
1114 ("%s: max_free not copied from left", __func__)); \
1115 root->right = llist; \
1117 root = y != rlist ? y : NULL; \
1121 * Walk down the tree until we find addr or a gap where addr would go, breaking
1122 * off left and right subtrees of nodes less than, or greater than addr. Treat
1123 * subtrees with root->max_free < length as empty trees. llist and rlist are
1124 * the two sides in reverse order (bottom-up), with llist linked by the right
1125 * pointer and rlist linked by the left pointer in the vm_map_entry, and both
1126 * lists terminated by &map->header. This function, and the subsequent call to
1127 * vm_map_splay_merge_{left,right,pred,succ}, rely on the start and end address
1128 * values in &map->header.
1130 static __always_inline vm_map_entry_t
1131 vm_map_splay_split(vm_map_t map, vm_offset_t addr, vm_size_t length,
1132 vm_map_entry_t *llist, vm_map_entry_t *rlist)
1134 vm_map_entry_t left, right, root, y;
1136 left = right = &map->header;
1138 while (root != NULL && root->max_free >= length) {
1139 KASSERT(left->end <= root->start &&
1140 root->end <= right->start,
1141 ("%s: root not within tree bounds", __func__));
1142 if (addr < root->start) {
1143 SPLAY_LEFT_STEP(root, y, left, right,
1144 y->max_free >= length && addr < y->start);
1145 } else if (addr >= root->end) {
1146 SPLAY_RIGHT_STEP(root, y, left, right,
1147 y->max_free >= length && addr >= y->end);
1156 static __always_inline void
1157 vm_map_splay_findnext(vm_map_entry_t root, vm_map_entry_t *rlist)
1159 vm_map_entry_t hi, right, y;
1162 hi = root->right == right ? NULL : root->right;
1166 SPLAY_LEFT_STEP(hi, y, root, right, true);
1171 static __always_inline void
1172 vm_map_splay_findprev(vm_map_entry_t root, vm_map_entry_t *llist)
1174 vm_map_entry_t left, lo, y;
1177 lo = root->left == left ? NULL : root->left;
1181 SPLAY_RIGHT_STEP(lo, y, left, root, true);
1187 vm_map_entry_swap(vm_map_entry_t *a, vm_map_entry_t *b)
1197 * Walk back up the two spines, flip the pointers and set max_free. The
1198 * subtrees of the root go at the bottom of llist and rlist.
1201 vm_map_splay_merge_left_walk(vm_map_entry_t header, vm_map_entry_t root,
1202 vm_map_entry_t tail, vm_size_t max_free, vm_map_entry_t llist)
1206 * The max_free values of the children of llist are in
1207 * llist->max_free and max_free. Update with the
1210 llist->max_free = max_free =
1211 vm_size_max(llist->max_free, max_free);
1212 vm_map_entry_swap(&llist->right, &tail);
1213 vm_map_entry_swap(&tail, &llist);
1214 } while (llist != header);
1220 * When llist is known to be the predecessor of root.
1222 static inline vm_size_t
1223 vm_map_splay_merge_pred(vm_map_entry_t header, vm_map_entry_t root,
1224 vm_map_entry_t llist)
1228 max_free = root->start - llist->end;
1229 if (llist != header) {
1230 max_free = vm_map_splay_merge_left_walk(header, root,
1231 root, max_free, llist);
1233 root->left = header;
1234 header->right = root;
1240 * When llist may or may not be the predecessor of root.
1242 static inline vm_size_t
1243 vm_map_splay_merge_left(vm_map_entry_t header, vm_map_entry_t root,
1244 vm_map_entry_t llist)
1248 max_free = vm_map_entry_max_free_left(root, llist);
1249 if (llist != header) {
1250 max_free = vm_map_splay_merge_left_walk(header, root,
1251 root->left == llist ? root : root->left,
1258 vm_map_splay_merge_right_walk(vm_map_entry_t header, vm_map_entry_t root,
1259 vm_map_entry_t tail, vm_size_t max_free, vm_map_entry_t rlist)
1263 * The max_free values of the children of rlist are in
1264 * rlist->max_free and max_free. Update with the
1267 rlist->max_free = max_free =
1268 vm_size_max(rlist->max_free, max_free);
1269 vm_map_entry_swap(&rlist->left, &tail);
1270 vm_map_entry_swap(&tail, &rlist);
1271 } while (rlist != header);
1277 * When rlist is known to be the succecessor of root.
1279 static inline vm_size_t
1280 vm_map_splay_merge_succ(vm_map_entry_t header, vm_map_entry_t root,
1281 vm_map_entry_t rlist)
1285 max_free = rlist->start - root->end;
1286 if (rlist != header) {
1287 max_free = vm_map_splay_merge_right_walk(header, root,
1288 root, max_free, rlist);
1290 root->right = header;
1291 header->left = root;
1297 * When rlist may or may not be the succecessor of root.
1299 static inline vm_size_t
1300 vm_map_splay_merge_right(vm_map_entry_t header, vm_map_entry_t root,
1301 vm_map_entry_t rlist)
1305 max_free = vm_map_entry_max_free_right(root, rlist);
1306 if (rlist != header) {
1307 max_free = vm_map_splay_merge_right_walk(header, root,
1308 root->right == rlist ? root : root->right,
1317 * The Sleator and Tarjan top-down splay algorithm with the
1318 * following variation. Max_free must be computed bottom-up, so
1319 * on the downward pass, maintain the left and right spines in
1320 * reverse order. Then, make a second pass up each side to fix
1321 * the pointers and compute max_free. The time bound is O(log n)
1324 * The tree is threaded, which means that there are no null pointers.
1325 * When a node has no left child, its left pointer points to its
1326 * predecessor, which the last ancestor on the search path from the root
1327 * where the search branched right. Likewise, when a node has no right
1328 * child, its right pointer points to its successor. The map header node
1329 * is the predecessor of the first map entry, and the successor of the
1332 * The new root is the vm_map_entry containing "addr", or else an
1333 * adjacent entry (lower if possible) if addr is not in the tree.
1335 * The map must be locked, and leaves it so.
1337 * Returns: the new root.
1339 static vm_map_entry_t
1340 vm_map_splay(vm_map_t map, vm_offset_t addr)
1342 vm_map_entry_t header, llist, rlist, root;
1343 vm_size_t max_free_left, max_free_right;
1345 header = &map->header;
1346 root = vm_map_splay_split(map, addr, 0, &llist, &rlist);
1348 max_free_left = vm_map_splay_merge_left(header, root, llist);
1349 max_free_right = vm_map_splay_merge_right(header, root, rlist);
1350 } else if (llist != header) {
1352 * Recover the greatest node in the left
1353 * subtree and make it the root.
1356 llist = root->right;
1357 max_free_left = vm_map_splay_merge_left(header, root, llist);
1358 max_free_right = vm_map_splay_merge_succ(header, root, rlist);
1359 } else if (rlist != header) {
1361 * Recover the least node in the right
1362 * subtree and make it the root.
1366 max_free_left = vm_map_splay_merge_pred(header, root, llist);
1367 max_free_right = vm_map_splay_merge_right(header, root, rlist);
1369 /* There is no root. */
1372 root->max_free = vm_size_max(max_free_left, max_free_right);
1374 VM_MAP_ASSERT_CONSISTENT(map);
1379 * vm_map_entry_{un,}link:
1381 * Insert/remove entries from maps. On linking, if new entry clips
1382 * existing entry, trim existing entry to avoid overlap, and manage
1383 * offsets. On unlinking, merge disappearing entry with neighbor, if
1384 * called for, and manage offsets. Callers should not modify fields in
1385 * entries already mapped.
1388 vm_map_entry_link(vm_map_t map, vm_map_entry_t entry)
1390 vm_map_entry_t header, llist, rlist, root;
1391 vm_size_t max_free_left, max_free_right;
1394 "vm_map_entry_link: map %p, nentries %d, entry %p", map,
1395 map->nentries, entry);
1396 VM_MAP_ASSERT_LOCKED(map);
1398 header = &map->header;
1399 root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1402 * The new entry does not overlap any existing entry in the
1403 * map, so it becomes the new root of the map tree.
1405 max_free_left = vm_map_splay_merge_pred(header, entry, llist);
1406 max_free_right = vm_map_splay_merge_succ(header, entry, rlist);
1407 } else if (entry->start == root->start) {
1409 * The new entry is a clone of root, with only the end field
1410 * changed. The root entry will be shrunk to abut the new
1411 * entry, and will be the right child of the new root entry in
1414 KASSERT(entry->end < root->end,
1415 ("%s: clip_start not within entry", __func__));
1416 vm_map_splay_findprev(root, &llist);
1417 root->offset += entry->end - root->start;
1418 root->start = entry->end;
1419 max_free_left = vm_map_splay_merge_pred(header, entry, llist);
1420 max_free_right = root->max_free = vm_size_max(
1421 vm_map_splay_merge_pred(entry, root, entry),
1422 vm_map_splay_merge_right(header, root, rlist));
1425 * The new entry is a clone of root, with only the start field
1426 * changed. The root entry will be shrunk to abut the new
1427 * entry, and will be the left child of the new root entry in
1430 KASSERT(entry->end == root->end,
1431 ("%s: clip_start not within entry", __func__));
1432 vm_map_splay_findnext(root, &rlist);
1433 entry->offset += entry->start - root->start;
1434 root->end = entry->start;
1435 max_free_left = root->max_free = vm_size_max(
1436 vm_map_splay_merge_left(header, root, llist),
1437 vm_map_splay_merge_succ(entry, root, entry));
1438 max_free_right = vm_map_splay_merge_succ(header, entry, rlist);
1440 entry->max_free = vm_size_max(max_free_left, max_free_right);
1442 VM_MAP_ASSERT_CONSISTENT(map);
1445 enum unlink_merge_type {
1451 vm_map_entry_unlink(vm_map_t map, vm_map_entry_t entry,
1452 enum unlink_merge_type op)
1454 vm_map_entry_t header, llist, rlist, root;
1455 vm_size_t max_free_left, max_free_right;
1457 VM_MAP_ASSERT_LOCKED(map);
1458 header = &map->header;
1459 root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1460 KASSERT(root != NULL,
1461 ("vm_map_entry_unlink: unlink object not mapped"));
1463 vm_map_splay_findprev(root, &llist);
1464 vm_map_splay_findnext(root, &rlist);
1465 if (op == UNLINK_MERGE_NEXT) {
1466 rlist->start = root->start;
1467 rlist->offset = root->offset;
1469 if (llist != header) {
1471 llist = root->right;
1472 max_free_left = vm_map_splay_merge_left(header, root, llist);
1473 max_free_right = vm_map_splay_merge_succ(header, root, rlist);
1474 } else if (rlist != header) {
1477 max_free_left = vm_map_splay_merge_pred(header, root, llist);
1478 max_free_right = vm_map_splay_merge_right(header, root, rlist);
1480 header->left = header->right = header;
1484 root->max_free = vm_size_max(max_free_left, max_free_right);
1486 VM_MAP_ASSERT_CONSISTENT(map);
1488 CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
1489 map->nentries, entry);
1493 * vm_map_entry_resize:
1495 * Resize a vm_map_entry, recompute the amount of free space that
1496 * follows it and propagate that value up the tree.
1498 * The map must be locked, and leaves it so.
1501 vm_map_entry_resize(vm_map_t map, vm_map_entry_t entry, vm_size_t grow_amount)
1503 vm_map_entry_t header, llist, rlist, root;
1505 VM_MAP_ASSERT_LOCKED(map);
1506 header = &map->header;
1507 root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1508 KASSERT(root != NULL, ("%s: resize object not mapped", __func__));
1509 vm_map_splay_findnext(root, &rlist);
1510 entry->end += grow_amount;
1511 root->max_free = vm_size_max(
1512 vm_map_splay_merge_left(header, root, llist),
1513 vm_map_splay_merge_succ(header, root, rlist));
1515 VM_MAP_ASSERT_CONSISTENT(map);
1516 CTR4(KTR_VM, "%s: map %p, nentries %d, entry %p",
1517 __func__, map, map->nentries, entry);
1521 * vm_map_lookup_entry: [ internal use only ]
1523 * Finds the map entry containing (or
1524 * immediately preceding) the specified address
1525 * in the given map; the entry is returned
1526 * in the "entry" parameter. The boolean
1527 * result indicates whether the address is
1528 * actually contained in the map.
1531 vm_map_lookup_entry(
1533 vm_offset_t address,
1534 vm_map_entry_t *entry) /* OUT */
1536 vm_map_entry_t cur, header, lbound, ubound;
1540 * If the map is empty, then the map entry immediately preceding
1541 * "address" is the map's header.
1543 header = &map->header;
1549 if (address >= cur->start && cur->end > address) {
1553 if ((locked = vm_map_locked(map)) ||
1554 sx_try_upgrade(&map->lock)) {
1556 * Splay requires a write lock on the map. However, it only
1557 * restructures the binary search tree; it does not otherwise
1558 * change the map. Thus, the map's timestamp need not change
1559 * on a temporary upgrade.
1561 cur = vm_map_splay(map, address);
1563 VM_MAP_UNLOCK_CONSISTENT(map);
1564 sx_downgrade(&map->lock);
1568 * If "address" is contained within a map entry, the new root
1569 * is that map entry. Otherwise, the new root is a map entry
1570 * immediately before or after "address".
1572 if (address < cur->start) {
1577 return (address < cur->end);
1580 * Since the map is only locked for read access, perform a
1581 * standard binary search tree lookup for "address".
1583 lbound = ubound = header;
1585 if (address < cur->start) {
1590 } else if (cur->end <= address) {
1607 * Inserts the given whole VM object into the target
1608 * map at the specified address range. The object's
1609 * size should match that of the address range.
1611 * Requires that the map be locked, and leaves it so.
1613 * If object is non-NULL, ref count must be bumped by caller
1614 * prior to making call to account for the new entry.
1617 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1618 vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max, int cow)
1620 vm_map_entry_t new_entry, next_entry, prev_entry;
1622 vm_eflags_t protoeflags;
1623 vm_inherit_t inheritance;
1627 VM_MAP_ASSERT_LOCKED(map);
1628 KASSERT(object != kernel_object ||
1629 (cow & MAP_COPY_ON_WRITE) == 0,
1630 ("vm_map_insert: kernel object and COW"));
1631 KASSERT(object == NULL || (cow & MAP_NOFAULT) == 0 ||
1632 (cow & MAP_SPLIT_BOUNDARY_MASK) != 0,
1633 ("vm_map_insert: paradoxical MAP_NOFAULT request, obj %p cow %#x",
1635 KASSERT((prot & ~max) == 0,
1636 ("prot %#x is not subset of max_prot %#x", prot, max));
1639 * Check that the start and end points are not bogus.
1641 if (start == end || !vm_map_range_valid(map, start, end))
1642 return (KERN_INVALID_ADDRESS);
1644 if ((map->flags & MAP_WXORX) != 0 && (prot & (VM_PROT_WRITE |
1645 VM_PROT_EXECUTE)) == (VM_PROT_WRITE | VM_PROT_EXECUTE))
1646 return (KERN_PROTECTION_FAILURE);
1649 * Find the entry prior to the proposed starting address; if it's part
1650 * of an existing entry, this range is bogus.
1652 if (vm_map_lookup_entry(map, start, &prev_entry))
1653 return (KERN_NO_SPACE);
1656 * Assert that the next entry doesn't overlap the end point.
1658 next_entry = vm_map_entry_succ(prev_entry);
1659 if (next_entry->start < end)
1660 return (KERN_NO_SPACE);
1662 if ((cow & MAP_CREATE_GUARD) != 0 && (object != NULL ||
1663 max != VM_PROT_NONE))
1664 return (KERN_INVALID_ARGUMENT);
1667 if (cow & MAP_COPY_ON_WRITE)
1668 protoeflags |= MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY;
1669 if (cow & MAP_NOFAULT)
1670 protoeflags |= MAP_ENTRY_NOFAULT;
1671 if (cow & MAP_DISABLE_SYNCER)
1672 protoeflags |= MAP_ENTRY_NOSYNC;
1673 if (cow & MAP_DISABLE_COREDUMP)
1674 protoeflags |= MAP_ENTRY_NOCOREDUMP;
1675 if (cow & MAP_STACK_GROWS_DOWN)
1676 protoeflags |= MAP_ENTRY_GROWS_DOWN;
1677 if (cow & MAP_STACK_GROWS_UP)
1678 protoeflags |= MAP_ENTRY_GROWS_UP;
1679 if (cow & MAP_WRITECOUNT)
1680 protoeflags |= MAP_ENTRY_WRITECNT;
1681 if (cow & MAP_VN_EXEC)
1682 protoeflags |= MAP_ENTRY_VN_EXEC;
1683 if ((cow & MAP_CREATE_GUARD) != 0)
1684 protoeflags |= MAP_ENTRY_GUARD;
1685 if ((cow & MAP_CREATE_STACK_GAP_DN) != 0)
1686 protoeflags |= MAP_ENTRY_STACK_GAP_DN;
1687 if ((cow & MAP_CREATE_STACK_GAP_UP) != 0)
1688 protoeflags |= MAP_ENTRY_STACK_GAP_UP;
1689 if (cow & MAP_INHERIT_SHARE)
1690 inheritance = VM_INHERIT_SHARE;
1692 inheritance = VM_INHERIT_DEFAULT;
1693 if ((cow & MAP_SPLIT_BOUNDARY_MASK) != 0) {
1694 /* This magically ignores index 0, for usual page size. */
1695 bidx = (cow & MAP_SPLIT_BOUNDARY_MASK) >>
1696 MAP_SPLIT_BOUNDARY_SHIFT;
1697 if (bidx >= MAXPAGESIZES)
1698 return (KERN_INVALID_ARGUMENT);
1699 bdry = pagesizes[bidx] - 1;
1700 if ((start & bdry) != 0 || (end & bdry) != 0)
1701 return (KERN_INVALID_ARGUMENT);
1702 protoeflags |= bidx << MAP_ENTRY_SPLIT_BOUNDARY_SHIFT;
1706 if ((cow & (MAP_ACC_NO_CHARGE | MAP_NOFAULT | MAP_CREATE_GUARD)) != 0)
1708 if ((cow & MAP_ACC_CHARGED) || ((prot & VM_PROT_WRITE) &&
1709 ((protoeflags & MAP_ENTRY_NEEDS_COPY) || object == NULL))) {
1710 if (!(cow & MAP_ACC_CHARGED) && !swap_reserve(end - start))
1711 return (KERN_RESOURCE_SHORTAGE);
1712 KASSERT(object == NULL ||
1713 (protoeflags & MAP_ENTRY_NEEDS_COPY) != 0 ||
1714 object->cred == NULL,
1715 ("overcommit: vm_map_insert o %p", object));
1716 cred = curthread->td_ucred;
1720 /* Expand the kernel pmap, if necessary. */
1721 if (map == kernel_map && end > kernel_vm_end)
1722 pmap_growkernel(end);
1723 if (object != NULL) {
1725 * OBJ_ONEMAPPING must be cleared unless this mapping
1726 * is trivially proven to be the only mapping for any
1727 * of the object's pages. (Object granularity
1728 * reference counting is insufficient to recognize
1729 * aliases with precision.)
1731 if ((object->flags & OBJ_ANON) != 0) {
1732 VM_OBJECT_WLOCK(object);
1733 if (object->ref_count > 1 || object->shadow_count != 0)
1734 vm_object_clear_flag(object, OBJ_ONEMAPPING);
1735 VM_OBJECT_WUNLOCK(object);
1737 } else if ((prev_entry->eflags & ~MAP_ENTRY_USER_WIRED) ==
1739 (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP |
1740 MAP_VN_EXEC)) == 0 &&
1741 prev_entry->end == start && (prev_entry->cred == cred ||
1742 (prev_entry->object.vm_object != NULL &&
1743 prev_entry->object.vm_object->cred == cred)) &&
1744 vm_object_coalesce(prev_entry->object.vm_object,
1746 (vm_size_t)(prev_entry->end - prev_entry->start),
1747 (vm_size_t)(end - prev_entry->end), cred != NULL &&
1748 (protoeflags & MAP_ENTRY_NEEDS_COPY) == 0)) {
1750 * We were able to extend the object. Determine if we
1751 * can extend the previous map entry to include the
1752 * new range as well.
1754 if (prev_entry->inheritance == inheritance &&
1755 prev_entry->protection == prot &&
1756 prev_entry->max_protection == max &&
1757 prev_entry->wired_count == 0) {
1758 KASSERT((prev_entry->eflags & MAP_ENTRY_USER_WIRED) ==
1759 0, ("prev_entry %p has incoherent wiring",
1761 if ((prev_entry->eflags & MAP_ENTRY_GUARD) == 0)
1762 map->size += end - prev_entry->end;
1763 vm_map_entry_resize(map, prev_entry,
1764 end - prev_entry->end);
1765 vm_map_try_merge_entries(map, prev_entry, next_entry);
1766 return (KERN_SUCCESS);
1770 * If we can extend the object but cannot extend the
1771 * map entry, we have to create a new map entry. We
1772 * must bump the ref count on the extended object to
1773 * account for it. object may be NULL.
1775 object = prev_entry->object.vm_object;
1776 offset = prev_entry->offset +
1777 (prev_entry->end - prev_entry->start);
1778 vm_object_reference(object);
1779 if (cred != NULL && object != NULL && object->cred != NULL &&
1780 !(prev_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
1781 /* Object already accounts for this uid. */
1789 * Create a new entry
1791 new_entry = vm_map_entry_create(map);
1792 new_entry->start = start;
1793 new_entry->end = end;
1794 new_entry->cred = NULL;
1796 new_entry->eflags = protoeflags;
1797 new_entry->object.vm_object = object;
1798 new_entry->offset = offset;
1800 new_entry->inheritance = inheritance;
1801 new_entry->protection = prot;
1802 new_entry->max_protection = max;
1803 new_entry->wired_count = 0;
1804 new_entry->wiring_thread = NULL;
1805 new_entry->read_ahead = VM_FAULT_READ_AHEAD_INIT;
1806 new_entry->next_read = start;
1808 KASSERT(cred == NULL || !ENTRY_CHARGED(new_entry),
1809 ("overcommit: vm_map_insert leaks vm_map %p", new_entry));
1810 new_entry->cred = cred;
1813 * Insert the new entry into the list
1815 vm_map_entry_link(map, new_entry);
1816 if ((new_entry->eflags & MAP_ENTRY_GUARD) == 0)
1817 map->size += new_entry->end - new_entry->start;
1820 * Try to coalesce the new entry with both the previous and next
1821 * entries in the list. Previously, we only attempted to coalesce
1822 * with the previous entry when object is NULL. Here, we handle the
1823 * other cases, which are less common.
1825 vm_map_try_merge_entries(map, prev_entry, new_entry);
1826 vm_map_try_merge_entries(map, new_entry, next_entry);
1828 if ((cow & (MAP_PREFAULT | MAP_PREFAULT_PARTIAL)) != 0) {
1829 vm_map_pmap_enter(map, start, prot, object, OFF_TO_IDX(offset),
1830 end - start, cow & MAP_PREFAULT_PARTIAL);
1833 return (KERN_SUCCESS);
1839 * Find the first fit (lowest VM address) for "length" free bytes
1840 * beginning at address >= start in the given map.
1842 * In a vm_map_entry, "max_free" is the maximum amount of
1843 * contiguous free space between an entry in its subtree and a
1844 * neighbor of that entry. This allows finding a free region in
1845 * one path down the tree, so O(log n) amortized with splay
1848 * The map must be locked, and leaves it so.
1850 * Returns: starting address if sufficient space,
1851 * vm_map_max(map)-length+1 if insufficient space.
1854 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length)
1856 vm_map_entry_t header, llist, rlist, root, y;
1857 vm_size_t left_length, max_free_left, max_free_right;
1858 vm_offset_t gap_end;
1860 VM_MAP_ASSERT_LOCKED(map);
1863 * Request must fit within min/max VM address and must avoid
1866 start = MAX(start, vm_map_min(map));
1867 if (start >= vm_map_max(map) || length > vm_map_max(map) - start)
1868 return (vm_map_max(map) - length + 1);
1870 /* Empty tree means wide open address space. */
1871 if (map->root == NULL)
1875 * After splay_split, if start is within an entry, push it to the start
1876 * of the following gap. If rlist is at the end of the gap containing
1877 * start, save the end of that gap in gap_end to see if the gap is big
1878 * enough; otherwise set gap_end to start skip gap-checking and move
1879 * directly to a search of the right subtree.
1881 header = &map->header;
1882 root = vm_map_splay_split(map, start, length, &llist, &rlist);
1883 gap_end = rlist->start;
1886 if (root->right != rlist)
1888 max_free_left = vm_map_splay_merge_left(header, root, llist);
1889 max_free_right = vm_map_splay_merge_right(header, root, rlist);
1890 } else if (rlist != header) {
1893 max_free_left = vm_map_splay_merge_pred(header, root, llist);
1894 max_free_right = vm_map_splay_merge_right(header, root, rlist);
1897 llist = root->right;
1898 max_free_left = vm_map_splay_merge_left(header, root, llist);
1899 max_free_right = vm_map_splay_merge_succ(header, root, rlist);
1901 root->max_free = vm_size_max(max_free_left, max_free_right);
1903 VM_MAP_ASSERT_CONSISTENT(map);
1904 if (length <= gap_end - start)
1907 /* With max_free, can immediately tell if no solution. */
1908 if (root->right == header || length > root->right->max_free)
1909 return (vm_map_max(map) - length + 1);
1912 * Splay for the least large-enough gap in the right subtree.
1914 llist = rlist = header;
1915 for (left_length = 0;;
1916 left_length = vm_map_entry_max_free_left(root, llist)) {
1917 if (length <= left_length)
1918 SPLAY_LEFT_STEP(root, y, llist, rlist,
1919 length <= vm_map_entry_max_free_left(y, llist));
1921 SPLAY_RIGHT_STEP(root, y, llist, rlist,
1922 length > vm_map_entry_max_free_left(y, root));
1927 llist = root->right;
1928 max_free_left = vm_map_splay_merge_left(header, root, llist);
1929 if (rlist == header) {
1930 root->max_free = vm_size_max(max_free_left,
1931 vm_map_splay_merge_succ(header, root, rlist));
1935 y->max_free = vm_size_max(
1936 vm_map_splay_merge_pred(root, y, root),
1937 vm_map_splay_merge_right(header, y, rlist));
1938 root->max_free = vm_size_max(max_free_left, y->max_free);
1941 VM_MAP_ASSERT_CONSISTENT(map);
1946 vm_map_fixed(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1947 vm_offset_t start, vm_size_t length, vm_prot_t prot,
1948 vm_prot_t max, int cow)
1953 end = start + length;
1954 KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1956 ("vm_map_fixed: non-NULL backing object for stack"));
1958 VM_MAP_RANGE_CHECK(map, start, end);
1959 if ((cow & MAP_CHECK_EXCL) == 0) {
1960 result = vm_map_delete(map, start, end);
1961 if (result != KERN_SUCCESS)
1964 if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1965 result = vm_map_stack_locked(map, start, length, sgrowsiz,
1968 result = vm_map_insert(map, object, offset, start, end,
1976 static const int aslr_pages_rnd_64[2] = {0x1000, 0x10};
1977 static const int aslr_pages_rnd_32[2] = {0x100, 0x4};
1979 static int cluster_anon = 1;
1980 SYSCTL_INT(_vm, OID_AUTO, cluster_anon, CTLFLAG_RW,
1982 "Cluster anonymous mappings: 0 = no, 1 = yes if no hint, 2 = always");
1985 clustering_anon_allowed(vm_offset_t addr)
1988 switch (cluster_anon) {
1999 static long aslr_restarts;
2000 SYSCTL_LONG(_vm, OID_AUTO, aslr_restarts, CTLFLAG_RD,
2002 "Number of aslr failures");
2005 * Searches for the specified amount of free space in the given map with the
2006 * specified alignment. Performs an address-ordered, first-fit search from
2007 * the given address "*addr", with an optional upper bound "max_addr". If the
2008 * parameter "alignment" is zero, then the alignment is computed from the
2009 * given (object, offset) pair so as to enable the greatest possible use of
2010 * superpage mappings. Returns KERN_SUCCESS and the address of the free space
2011 * in "*addr" if successful. Otherwise, returns KERN_NO_SPACE.
2013 * The map must be locked. Initially, there must be at least "length" bytes
2014 * of free space at the given address.
2017 vm_map_alignspace(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
2018 vm_offset_t *addr, vm_size_t length, vm_offset_t max_addr,
2019 vm_offset_t alignment)
2021 vm_offset_t aligned_addr, free_addr;
2023 VM_MAP_ASSERT_LOCKED(map);
2025 KASSERT(free_addr == vm_map_findspace(map, free_addr, length),
2026 ("caller failed to provide space %#jx at address %p",
2027 (uintmax_t)length, (void *)free_addr));
2030 * At the start of every iteration, the free space at address
2031 * "*addr" is at least "length" bytes.
2034 pmap_align_superpage(object, offset, addr, length);
2035 else if ((*addr & (alignment - 1)) != 0) {
2036 *addr &= ~(alignment - 1);
2039 aligned_addr = *addr;
2040 if (aligned_addr == free_addr) {
2042 * Alignment did not change "*addr", so "*addr" must
2043 * still provide sufficient free space.
2045 return (KERN_SUCCESS);
2049 * Test for address wrap on "*addr". A wrapped "*addr" could
2050 * be a valid address, in which case vm_map_findspace() cannot
2051 * be relied upon to fail.
2053 if (aligned_addr < free_addr)
2054 return (KERN_NO_SPACE);
2055 *addr = vm_map_findspace(map, aligned_addr, length);
2056 if (*addr + length > vm_map_max(map) ||
2057 (max_addr != 0 && *addr + length > max_addr))
2058 return (KERN_NO_SPACE);
2060 if (free_addr == aligned_addr) {
2062 * If a successful call to vm_map_findspace() did not
2063 * change "*addr", then "*addr" must still be aligned
2064 * and provide sufficient free space.
2066 return (KERN_SUCCESS);
2072 vm_map_find_aligned(vm_map_t map, vm_offset_t *addr, vm_size_t length,
2073 vm_offset_t max_addr, vm_offset_t alignment)
2075 /* XXXKIB ASLR eh ? */
2076 *addr = vm_map_findspace(map, *addr, length);
2077 if (*addr + length > vm_map_max(map) ||
2078 (max_addr != 0 && *addr + length > max_addr))
2079 return (KERN_NO_SPACE);
2080 return (vm_map_alignspace(map, NULL, 0, addr, length, max_addr,
2085 * vm_map_find finds an unallocated region in the target address
2086 * map with the given length. The search is defined to be
2087 * first-fit from the specified address; the region found is
2088 * returned in the same parameter.
2090 * If object is non-NULL, ref count must be bumped by caller
2091 * prior to making call to account for the new entry.
2094 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
2095 vm_offset_t *addr, /* IN/OUT */
2096 vm_size_t length, vm_offset_t max_addr, int find_space,
2097 vm_prot_t prot, vm_prot_t max, int cow)
2099 vm_offset_t alignment, curr_min_addr, min_addr;
2100 int gap, pidx, rv, try;
2101 bool cluster, en_aslr, update_anon;
2103 KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
2105 ("vm_map_find: non-NULL backing object for stack"));
2106 MPASS((cow & MAP_REMAP) == 0 || (find_space == VMFS_NO_SPACE &&
2107 (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0));
2108 if (find_space == VMFS_OPTIMAL_SPACE && (object == NULL ||
2109 (object->flags & OBJ_COLORED) == 0))
2110 find_space = VMFS_ANY_SPACE;
2111 if (find_space >> 8 != 0) {
2112 KASSERT((find_space & 0xff) == 0, ("bad VMFS flags"));
2113 alignment = (vm_offset_t)1 << (find_space >> 8);
2116 en_aslr = (map->flags & MAP_ASLR) != 0;
2117 update_anon = cluster = clustering_anon_allowed(*addr) &&
2118 (map->flags & MAP_IS_SUB_MAP) == 0 && max_addr == 0 &&
2119 find_space != VMFS_NO_SPACE && object == NULL &&
2120 (cow & (MAP_INHERIT_SHARE | MAP_STACK_GROWS_UP |
2121 MAP_STACK_GROWS_DOWN)) == 0 && prot != PROT_NONE;
2122 curr_min_addr = min_addr = *addr;
2123 if (en_aslr && min_addr == 0 && !cluster &&
2124 find_space != VMFS_NO_SPACE &&
2125 (map->flags & MAP_ASLR_IGNSTART) != 0)
2126 curr_min_addr = min_addr = vm_map_min(map);
2130 curr_min_addr = map->anon_loc;
2131 if (curr_min_addr == 0)
2134 if (find_space != VMFS_NO_SPACE) {
2135 KASSERT(find_space == VMFS_ANY_SPACE ||
2136 find_space == VMFS_OPTIMAL_SPACE ||
2137 find_space == VMFS_SUPER_SPACE ||
2138 alignment != 0, ("unexpected VMFS flag"));
2141 * When creating an anonymous mapping, try clustering
2142 * with an existing anonymous mapping first.
2144 * We make up to two attempts to find address space
2145 * for a given find_space value. The first attempt may
2146 * apply randomization or may cluster with an existing
2147 * anonymous mapping. If this first attempt fails,
2148 * perform a first-fit search of the available address
2151 * If all tries failed, and find_space is
2152 * VMFS_OPTIMAL_SPACE, fallback to VMFS_ANY_SPACE.
2153 * Again enable clustering and randomization.
2160 * Second try: we failed either to find a
2161 * suitable region for randomizing the
2162 * allocation, or to cluster with an existing
2163 * mapping. Retry with free run.
2165 curr_min_addr = (map->flags & MAP_ASLR_IGNSTART) != 0 ?
2166 vm_map_min(map) : min_addr;
2167 atomic_add_long(&aslr_restarts, 1);
2170 if (try == 1 && en_aslr && !cluster) {
2172 * Find space for allocation, including
2173 * gap needed for later randomization.
2175 pidx = MAXPAGESIZES > 1 && pagesizes[1] != 0 &&
2176 (find_space == VMFS_SUPER_SPACE || find_space ==
2177 VMFS_OPTIMAL_SPACE) ? 1 : 0;
2178 gap = vm_map_max(map) > MAP_32BIT_MAX_ADDR &&
2179 (max_addr == 0 || max_addr > MAP_32BIT_MAX_ADDR) ?
2180 aslr_pages_rnd_64[pidx] : aslr_pages_rnd_32[pidx];
2181 *addr = vm_map_findspace(map, curr_min_addr,
2182 length + gap * pagesizes[pidx]);
2183 if (*addr + length + gap * pagesizes[pidx] >
2186 /* And randomize the start address. */
2187 *addr += (arc4random() % gap) * pagesizes[pidx];
2188 if (max_addr != 0 && *addr + length > max_addr)
2191 *addr = vm_map_findspace(map, curr_min_addr, length);
2192 if (*addr + length > vm_map_max(map) ||
2193 (max_addr != 0 && *addr + length > max_addr)) {
2204 if (find_space != VMFS_ANY_SPACE &&
2205 (rv = vm_map_alignspace(map, object, offset, addr, length,
2206 max_addr, alignment)) != KERN_SUCCESS) {
2207 if (find_space == VMFS_OPTIMAL_SPACE) {
2208 find_space = VMFS_ANY_SPACE;
2209 curr_min_addr = min_addr;
2210 cluster = update_anon;
2216 } else if ((cow & MAP_REMAP) != 0) {
2217 if (!vm_map_range_valid(map, *addr, *addr + length)) {
2218 rv = KERN_INVALID_ADDRESS;
2221 rv = vm_map_delete(map, *addr, *addr + length);
2222 if (rv != KERN_SUCCESS)
2225 if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
2226 rv = vm_map_stack_locked(map, *addr, length, sgrowsiz, prot,
2229 rv = vm_map_insert(map, object, offset, *addr, *addr + length,
2232 if (rv == KERN_SUCCESS && update_anon)
2233 map->anon_loc = *addr + length;
2240 * vm_map_find_min() is a variant of vm_map_find() that takes an
2241 * additional parameter (min_addr) and treats the given address
2242 * (*addr) differently. Specifically, it treats *addr as a hint
2243 * and not as the minimum address where the mapping is created.
2245 * This function works in two phases. First, it tries to
2246 * allocate above the hint. If that fails and the hint is
2247 * greater than min_addr, it performs a second pass, replacing
2248 * the hint with min_addr as the minimum address for the
2252 vm_map_find_min(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
2253 vm_offset_t *addr, vm_size_t length, vm_offset_t min_addr,
2254 vm_offset_t max_addr, int find_space, vm_prot_t prot, vm_prot_t max,
2262 rv = vm_map_find(map, object, offset, addr, length, max_addr,
2263 find_space, prot, max, cow);
2264 if (rv == KERN_SUCCESS || min_addr >= hint)
2266 *addr = hint = min_addr;
2271 * A map entry with any of the following flags set must not be merged with
2274 #define MAP_ENTRY_NOMERGE_MASK (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP | \
2275 MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP | MAP_ENTRY_VN_EXEC)
2278 vm_map_mergeable_neighbors(vm_map_entry_t prev, vm_map_entry_t entry)
2281 KASSERT((prev->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 ||
2282 (entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0,
2283 ("vm_map_mergeable_neighbors: neither %p nor %p are mergeable",
2285 return (prev->end == entry->start &&
2286 prev->object.vm_object == entry->object.vm_object &&
2287 (prev->object.vm_object == NULL ||
2288 prev->offset + (prev->end - prev->start) == entry->offset) &&
2289 prev->eflags == entry->eflags &&
2290 prev->protection == entry->protection &&
2291 prev->max_protection == entry->max_protection &&
2292 prev->inheritance == entry->inheritance &&
2293 prev->wired_count == entry->wired_count &&
2294 prev->cred == entry->cred);
2298 vm_map_merged_neighbor_dispose(vm_map_t map, vm_map_entry_t entry)
2302 * If the backing object is a vnode object, vm_object_deallocate()
2303 * calls vrele(). However, vrele() does not lock the vnode because
2304 * the vnode has additional references. Thus, the map lock can be
2305 * kept without causing a lock-order reversal with the vnode lock.
2307 * Since we count the number of virtual page mappings in
2308 * object->un_pager.vnp.writemappings, the writemappings value
2309 * should not be adjusted when the entry is disposed of.
2311 if (entry->object.vm_object != NULL)
2312 vm_object_deallocate(entry->object.vm_object);
2313 if (entry->cred != NULL)
2314 crfree(entry->cred);
2315 vm_map_entry_dispose(map, entry);
2319 * vm_map_try_merge_entries:
2321 * Compare the given map entry to its predecessor, and merge its precessor
2322 * into it if possible. The entry remains valid, and may be extended.
2323 * The predecessor may be deleted.
2325 * The map must be locked.
2328 vm_map_try_merge_entries(vm_map_t map, vm_map_entry_t prev_entry,
2329 vm_map_entry_t entry)
2332 VM_MAP_ASSERT_LOCKED(map);
2333 if ((entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 &&
2334 vm_map_mergeable_neighbors(prev_entry, entry)) {
2335 vm_map_entry_unlink(map, prev_entry, UNLINK_MERGE_NEXT);
2336 vm_map_merged_neighbor_dispose(map, prev_entry);
2341 * vm_map_entry_back:
2343 * Allocate an object to back a map entry.
2346 vm_map_entry_back(vm_map_entry_t entry)
2350 KASSERT(entry->object.vm_object == NULL,
2351 ("map entry %p has backing object", entry));
2352 KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
2353 ("map entry %p is a submap", entry));
2354 object = vm_object_allocate_anon(atop(entry->end - entry->start), NULL,
2355 entry->cred, entry->end - entry->start);
2356 entry->object.vm_object = object;
2362 * vm_map_entry_charge_object
2364 * If there is no object backing this entry, create one. Otherwise, if
2365 * the entry has cred, give it to the backing object.
2368 vm_map_entry_charge_object(vm_map_t map, vm_map_entry_t entry)
2371 VM_MAP_ASSERT_LOCKED(map);
2372 KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
2373 ("map entry %p is a submap", entry));
2374 if (entry->object.vm_object == NULL && !map->system_map &&
2375 (entry->eflags & MAP_ENTRY_GUARD) == 0)
2376 vm_map_entry_back(entry);
2377 else if (entry->object.vm_object != NULL &&
2378 ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
2379 entry->cred != NULL) {
2380 VM_OBJECT_WLOCK(entry->object.vm_object);
2381 KASSERT(entry->object.vm_object->cred == NULL,
2382 ("OVERCOMMIT: %s: both cred e %p", __func__, entry));
2383 entry->object.vm_object->cred = entry->cred;
2384 entry->object.vm_object->charge = entry->end - entry->start;
2385 VM_OBJECT_WUNLOCK(entry->object.vm_object);
2391 * vm_map_entry_clone
2393 * Create a duplicate map entry for clipping.
2395 static vm_map_entry_t
2396 vm_map_entry_clone(vm_map_t map, vm_map_entry_t entry)
2398 vm_map_entry_t new_entry;
2400 VM_MAP_ASSERT_LOCKED(map);
2403 * Create a backing object now, if none exists, so that more individual
2404 * objects won't be created after the map entry is split.
2406 vm_map_entry_charge_object(map, entry);
2408 /* Clone the entry. */
2409 new_entry = vm_map_entry_create(map);
2410 *new_entry = *entry;
2411 if (new_entry->cred != NULL)
2412 crhold(entry->cred);
2413 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2414 vm_object_reference(new_entry->object.vm_object);
2415 vm_map_entry_set_vnode_text(new_entry, true);
2417 * The object->un_pager.vnp.writemappings for the object of
2418 * MAP_ENTRY_WRITECNT type entry shall be kept as is here. The
2419 * virtual pages are re-distributed among the clipped entries,
2420 * so the sum is left the same.
2427 * vm_map_clip_start: [ internal use only ]
2429 * Asserts that the given entry begins at or after
2430 * the specified address; if necessary,
2431 * it splits the entry into two.
2434 vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t startaddr)
2436 vm_map_entry_t new_entry;
2439 if (!map->system_map)
2440 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2441 "%s: map %p entry %p start 0x%jx", __func__, map, entry,
2442 (uintmax_t)startaddr);
2444 if (startaddr <= entry->start)
2445 return (KERN_SUCCESS);
2447 VM_MAP_ASSERT_LOCKED(map);
2448 KASSERT(entry->end > startaddr && entry->start < startaddr,
2449 ("%s: invalid clip of entry %p", __func__, entry));
2451 bdry_idx = (entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK) >>
2452 MAP_ENTRY_SPLIT_BOUNDARY_SHIFT;
2453 if (bdry_idx != 0) {
2454 if ((startaddr & (pagesizes[bdry_idx] - 1)) != 0)
2455 return (KERN_INVALID_ARGUMENT);
2458 new_entry = vm_map_entry_clone(map, entry);
2461 * Split off the front portion. Insert the new entry BEFORE this one,
2462 * so that this entry has the specified starting address.
2464 new_entry->end = startaddr;
2465 vm_map_entry_link(map, new_entry);
2466 return (KERN_SUCCESS);
2470 * vm_map_lookup_clip_start:
2472 * Find the entry at or just after 'start', and clip it if 'start' is in
2473 * the interior of the entry. Return entry after 'start', and in
2474 * prev_entry set the entry before 'start'.
2477 vm_map_lookup_clip_start(vm_map_t map, vm_offset_t start,
2478 vm_map_entry_t *res_entry, vm_map_entry_t *prev_entry)
2480 vm_map_entry_t entry;
2483 if (!map->system_map)
2484 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2485 "%s: map %p start 0x%jx prev %p", __func__, map,
2486 (uintmax_t)start, prev_entry);
2488 if (vm_map_lookup_entry(map, start, prev_entry)) {
2489 entry = *prev_entry;
2490 rv = vm_map_clip_start(map, entry, start);
2491 if (rv != KERN_SUCCESS)
2493 *prev_entry = vm_map_entry_pred(entry);
2495 entry = vm_map_entry_succ(*prev_entry);
2497 return (KERN_SUCCESS);
2501 * vm_map_clip_end: [ internal use only ]
2503 * Asserts that the given entry ends at or before
2504 * the specified address; if necessary,
2505 * it splits the entry into two.
2508 vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t endaddr)
2510 vm_map_entry_t new_entry;
2513 if (!map->system_map)
2514 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2515 "%s: map %p entry %p end 0x%jx", __func__, map, entry,
2516 (uintmax_t)endaddr);
2518 if (endaddr >= entry->end)
2519 return (KERN_SUCCESS);
2521 VM_MAP_ASSERT_LOCKED(map);
2522 KASSERT(entry->start < endaddr && entry->end > endaddr,
2523 ("%s: invalid clip of entry %p", __func__, entry));
2525 bdry_idx = (entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK) >>
2526 MAP_ENTRY_SPLIT_BOUNDARY_SHIFT;
2527 if (bdry_idx != 0) {
2528 if ((endaddr & (pagesizes[bdry_idx] - 1)) != 0)
2529 return (KERN_INVALID_ARGUMENT);
2532 new_entry = vm_map_entry_clone(map, entry);
2535 * Split off the back portion. Insert the new entry AFTER this one,
2536 * so that this entry has the specified ending address.
2538 new_entry->start = endaddr;
2539 vm_map_entry_link(map, new_entry);
2541 return (KERN_SUCCESS);
2545 * vm_map_submap: [ kernel use only ]
2547 * Mark the given range as handled by a subordinate map.
2549 * This range must have been created with vm_map_find,
2550 * and no other operations may have been performed on this
2551 * range prior to calling vm_map_submap.
2553 * Only a limited number of operations can be performed
2554 * within this rage after calling vm_map_submap:
2556 * [Don't try vm_map_copy!]
2558 * To remove a submapping, one must first remove the
2559 * range from the superior map, and then destroy the
2560 * submap (if desired). [Better yet, don't try it.]
2569 vm_map_entry_t entry;
2572 result = KERN_INVALID_ARGUMENT;
2574 vm_map_lock(submap);
2575 submap->flags |= MAP_IS_SUB_MAP;
2576 vm_map_unlock(submap);
2579 VM_MAP_RANGE_CHECK(map, start, end);
2580 if (vm_map_lookup_entry(map, start, &entry) && entry->end >= end &&
2581 (entry->eflags & MAP_ENTRY_COW) == 0 &&
2582 entry->object.vm_object == NULL) {
2583 result = vm_map_clip_start(map, entry, start);
2584 if (result != KERN_SUCCESS)
2586 result = vm_map_clip_end(map, entry, end);
2587 if (result != KERN_SUCCESS)
2589 entry->object.sub_map = submap;
2590 entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
2591 result = KERN_SUCCESS;
2596 if (result != KERN_SUCCESS) {
2597 vm_map_lock(submap);
2598 submap->flags &= ~MAP_IS_SUB_MAP;
2599 vm_map_unlock(submap);
2605 * The maximum number of pages to map if MAP_PREFAULT_PARTIAL is specified
2607 #define MAX_INIT_PT 96
2610 * vm_map_pmap_enter:
2612 * Preload the specified map's pmap with mappings to the specified
2613 * object's memory-resident pages. No further physical pages are
2614 * allocated, and no further virtual pages are retrieved from secondary
2615 * storage. If the specified flags include MAP_PREFAULT_PARTIAL, then a
2616 * limited number of page mappings are created at the low-end of the
2617 * specified address range. (For this purpose, a superpage mapping
2618 * counts as one page mapping.) Otherwise, all resident pages within
2619 * the specified address range are mapped.
2622 vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
2623 vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
2626 vm_page_t p, p_start;
2627 vm_pindex_t mask, psize, threshold, tmpidx;
2629 if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0 || object == NULL)
2631 if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2632 VM_OBJECT_WLOCK(object);
2633 if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2634 pmap_object_init_pt(map->pmap, addr, object, pindex,
2636 VM_OBJECT_WUNLOCK(object);
2639 VM_OBJECT_LOCK_DOWNGRADE(object);
2641 VM_OBJECT_RLOCK(object);
2644 if (psize + pindex > object->size) {
2645 if (pindex >= object->size) {
2646 VM_OBJECT_RUNLOCK(object);
2649 psize = object->size - pindex;
2654 threshold = MAX_INIT_PT;
2656 p = vm_page_find_least(object, pindex);
2658 * Assert: the variable p is either (1) the page with the
2659 * least pindex greater than or equal to the parameter pindex
2663 p != NULL && (tmpidx = p->pindex - pindex) < psize;
2664 p = TAILQ_NEXT(p, listq)) {
2666 * don't allow an madvise to blow away our really
2667 * free pages allocating pv entries.
2669 if (((flags & MAP_PREFAULT_MADVISE) != 0 &&
2670 vm_page_count_severe()) ||
2671 ((flags & MAP_PREFAULT_PARTIAL) != 0 &&
2672 tmpidx >= threshold)) {
2676 if (vm_page_all_valid(p)) {
2677 if (p_start == NULL) {
2678 start = addr + ptoa(tmpidx);
2681 /* Jump ahead if a superpage mapping is possible. */
2682 if (p->psind > 0 && ((addr + ptoa(tmpidx)) &
2683 (pagesizes[p->psind] - 1)) == 0) {
2684 mask = atop(pagesizes[p->psind]) - 1;
2685 if (tmpidx + mask < psize &&
2686 vm_page_ps_test(p, PS_ALL_VALID, NULL)) {
2691 } else if (p_start != NULL) {
2692 pmap_enter_object(map->pmap, start, addr +
2693 ptoa(tmpidx), p_start, prot);
2697 if (p_start != NULL)
2698 pmap_enter_object(map->pmap, start, addr + ptoa(psize),
2700 VM_OBJECT_RUNLOCK(object);
2706 * Sets the protection and/or the maximum protection of the
2707 * specified address region in the target map.
2710 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
2711 vm_prot_t new_prot, vm_prot_t new_maxprot, int flags)
2713 vm_map_entry_t entry, first_entry, in_tran, prev_entry;
2720 return (KERN_SUCCESS);
2722 if ((flags & (VM_MAP_PROTECT_SET_PROT | VM_MAP_PROTECT_SET_MAXPROT)) ==
2723 (VM_MAP_PROTECT_SET_PROT | VM_MAP_PROTECT_SET_MAXPROT) &&
2724 (new_prot & new_maxprot) != new_prot)
2725 return (KERN_OUT_OF_BOUNDS);
2731 if ((map->flags & MAP_WXORX) != 0 &&
2732 (flags & VM_MAP_PROTECT_SET_PROT) != 0 &&
2733 (new_prot & (VM_PROT_WRITE | VM_PROT_EXECUTE)) == (VM_PROT_WRITE |
2736 return (KERN_PROTECTION_FAILURE);
2740 * Ensure that we are not concurrently wiring pages. vm_map_wire() may
2741 * need to fault pages into the map and will drop the map lock while
2742 * doing so, and the VM object may end up in an inconsistent state if we
2743 * update the protection on the map entry in between faults.
2745 vm_map_wait_busy(map);
2747 VM_MAP_RANGE_CHECK(map, start, end);
2749 if (!vm_map_lookup_entry(map, start, &first_entry))
2750 first_entry = vm_map_entry_succ(first_entry);
2753 * Make a first pass to check for protection violations.
2755 for (entry = first_entry; entry->start < end;
2756 entry = vm_map_entry_succ(entry)) {
2757 if ((entry->eflags & MAP_ENTRY_GUARD) != 0)
2759 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0) {
2761 return (KERN_INVALID_ARGUMENT);
2763 if ((flags & VM_MAP_PROTECT_SET_PROT) == 0)
2764 new_prot = entry->protection;
2765 if ((flags & VM_MAP_PROTECT_SET_MAXPROT) == 0)
2766 new_maxprot = entry->max_protection;
2767 if ((new_prot & entry->max_protection) != new_prot ||
2768 (new_maxprot & entry->max_protection) != new_maxprot) {
2770 return (KERN_PROTECTION_FAILURE);
2772 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0)
2777 * Postpone the operation until all in-transition map entries have
2778 * stabilized. An in-transition entry might already have its pages
2779 * wired and wired_count incremented, but not yet have its
2780 * MAP_ENTRY_USER_WIRED flag set. In which case, we would fail to call
2781 * vm_fault_copy_entry() in the final loop below.
2783 if (in_tran != NULL) {
2784 in_tran->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2785 vm_map_unlock_and_wait(map, 0);
2790 * Before changing the protections, try to reserve swap space for any
2791 * private (i.e., copy-on-write) mappings that are transitioning from
2792 * read-only to read/write access. If a reservation fails, break out
2793 * of this loop early and let the next loop simplify the entries, since
2794 * some may now be mergeable.
2796 rv = vm_map_clip_start(map, first_entry, start);
2797 if (rv != KERN_SUCCESS) {
2801 for (entry = first_entry; entry->start < end;
2802 entry = vm_map_entry_succ(entry)) {
2803 rv = vm_map_clip_end(map, entry, end);
2804 if (rv != KERN_SUCCESS) {
2809 if ((flags & VM_MAP_PROTECT_SET_PROT) == 0 ||
2810 ((new_prot & ~entry->protection) & VM_PROT_WRITE) == 0 ||
2811 ENTRY_CHARGED(entry) ||
2812 (entry->eflags & MAP_ENTRY_GUARD) != 0)
2815 cred = curthread->td_ucred;
2816 obj = entry->object.vm_object;
2819 (entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0) {
2820 if (!swap_reserve(entry->end - entry->start)) {
2821 rv = KERN_RESOURCE_SHORTAGE;
2830 if (obj->type != OBJT_DEFAULT &&
2831 (obj->flags & OBJ_SWAP) == 0)
2833 VM_OBJECT_WLOCK(obj);
2834 if (obj->type != OBJT_DEFAULT &&
2835 (obj->flags & OBJ_SWAP) == 0) {
2836 VM_OBJECT_WUNLOCK(obj);
2841 * Charge for the whole object allocation now, since
2842 * we cannot distinguish between non-charged and
2843 * charged clipped mapping of the same object later.
2845 KASSERT(obj->charge == 0,
2846 ("vm_map_protect: object %p overcharged (entry %p)",
2848 if (!swap_reserve(ptoa(obj->size))) {
2849 VM_OBJECT_WUNLOCK(obj);
2850 rv = KERN_RESOURCE_SHORTAGE;
2857 obj->charge = ptoa(obj->size);
2858 VM_OBJECT_WUNLOCK(obj);
2862 * If enough swap space was available, go back and fix up protections.
2863 * Otherwise, just simplify entries, since some may have been modified.
2864 * [Note that clipping is not necessary the second time.]
2866 for (prev_entry = vm_map_entry_pred(first_entry), entry = first_entry;
2868 vm_map_try_merge_entries(map, prev_entry, entry),
2869 prev_entry = entry, entry = vm_map_entry_succ(entry)) {
2870 if (rv != KERN_SUCCESS ||
2871 (entry->eflags & MAP_ENTRY_GUARD) != 0)
2874 old_prot = entry->protection;
2876 if ((flags & VM_MAP_PROTECT_SET_MAXPROT) != 0) {
2877 entry->max_protection = new_maxprot;
2878 entry->protection = new_maxprot & old_prot;
2880 if ((flags & VM_MAP_PROTECT_SET_PROT) != 0)
2881 entry->protection = new_prot;
2884 * For user wired map entries, the normal lazy evaluation of
2885 * write access upgrades through soft page faults is
2886 * undesirable. Instead, immediately copy any pages that are
2887 * copy-on-write and enable write access in the physical map.
2889 if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0 &&
2890 (entry->protection & VM_PROT_WRITE) != 0 &&
2891 (old_prot & VM_PROT_WRITE) == 0)
2892 vm_fault_copy_entry(map, map, entry, entry, NULL);
2895 * When restricting access, update the physical map. Worry
2896 * about copy-on-write here.
2898 if ((old_prot & ~entry->protection) != 0) {
2899 #define MASK(entry) (((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
2901 pmap_protect(map->pmap, entry->start,
2903 entry->protection & MASK(entry));
2907 vm_map_try_merge_entries(map, prev_entry, entry);
2915 * This routine traverses a processes map handling the madvise
2916 * system call. Advisories are classified as either those effecting
2917 * the vm_map_entry structure, or those effecting the underlying
2927 vm_map_entry_t entry, prev_entry;
2932 * Some madvise calls directly modify the vm_map_entry, in which case
2933 * we need to use an exclusive lock on the map and we need to perform
2934 * various clipping operations. Otherwise we only need a read-lock
2939 case MADV_SEQUENTIAL:
2956 vm_map_lock_read(map);
2963 * Locate starting entry and clip if necessary.
2965 VM_MAP_RANGE_CHECK(map, start, end);
2969 * madvise behaviors that are implemented in the vm_map_entry.
2971 * We clip the vm_map_entry so that behavioral changes are
2972 * limited to the specified address range.
2974 rv = vm_map_lookup_clip_start(map, start, &entry, &prev_entry);
2975 if (rv != KERN_SUCCESS) {
2977 return (vm_mmap_to_errno(rv));
2980 for (; entry->start < end; prev_entry = entry,
2981 entry = vm_map_entry_succ(entry)) {
2982 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2985 rv = vm_map_clip_end(map, entry, end);
2986 if (rv != KERN_SUCCESS) {
2988 return (vm_mmap_to_errno(rv));
2993 vm_map_entry_set_behavior(entry,
2994 MAP_ENTRY_BEHAV_NORMAL);
2996 case MADV_SEQUENTIAL:
2997 vm_map_entry_set_behavior(entry,
2998 MAP_ENTRY_BEHAV_SEQUENTIAL);
3001 vm_map_entry_set_behavior(entry,
3002 MAP_ENTRY_BEHAV_RANDOM);
3005 entry->eflags |= MAP_ENTRY_NOSYNC;
3008 entry->eflags &= ~MAP_ENTRY_NOSYNC;
3011 entry->eflags |= MAP_ENTRY_NOCOREDUMP;
3014 entry->eflags &= ~MAP_ENTRY_NOCOREDUMP;
3019 vm_map_try_merge_entries(map, prev_entry, entry);
3021 vm_map_try_merge_entries(map, prev_entry, entry);
3024 vm_pindex_t pstart, pend;
3027 * madvise behaviors that are implemented in the underlying
3030 * Since we don't clip the vm_map_entry, we have to clip
3031 * the vm_object pindex and count.
3033 if (!vm_map_lookup_entry(map, start, &entry))
3034 entry = vm_map_entry_succ(entry);
3035 for (; entry->start < end;
3036 entry = vm_map_entry_succ(entry)) {
3037 vm_offset_t useEnd, useStart;
3039 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
3043 * MADV_FREE would otherwise rewind time to
3044 * the creation of the shadow object. Because
3045 * we hold the VM map read-locked, neither the
3046 * entry's object nor the presence of a
3047 * backing object can change.
3049 if (behav == MADV_FREE &&
3050 entry->object.vm_object != NULL &&
3051 entry->object.vm_object->backing_object != NULL)
3054 pstart = OFF_TO_IDX(entry->offset);
3055 pend = pstart + atop(entry->end - entry->start);
3056 useStart = entry->start;
3057 useEnd = entry->end;
3059 if (entry->start < start) {
3060 pstart += atop(start - entry->start);
3063 if (entry->end > end) {
3064 pend -= atop(entry->end - end);
3072 * Perform the pmap_advise() before clearing
3073 * PGA_REFERENCED in vm_page_advise(). Otherwise, a
3074 * concurrent pmap operation, such as pmap_remove(),
3075 * could clear a reference in the pmap and set
3076 * PGA_REFERENCED on the page before the pmap_advise()
3077 * had completed. Consequently, the page would appear
3078 * referenced based upon an old reference that
3079 * occurred before this pmap_advise() ran.
3081 if (behav == MADV_DONTNEED || behav == MADV_FREE)
3082 pmap_advise(map->pmap, useStart, useEnd,
3085 vm_object_madvise(entry->object.vm_object, pstart,
3089 * Pre-populate paging structures in the
3090 * WILLNEED case. For wired entries, the
3091 * paging structures are already populated.
3093 if (behav == MADV_WILLNEED &&
3094 entry->wired_count == 0) {
3095 vm_map_pmap_enter(map,
3098 entry->object.vm_object,
3100 ptoa(pend - pstart),
3101 MAP_PREFAULT_MADVISE
3105 vm_map_unlock_read(map);
3113 * Sets the inheritance of the specified address
3114 * range in the target map. Inheritance
3115 * affects how the map will be shared with
3116 * child maps at the time of vmspace_fork.
3119 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
3120 vm_inherit_t new_inheritance)
3122 vm_map_entry_t entry, lentry, prev_entry, start_entry;
3125 switch (new_inheritance) {
3126 case VM_INHERIT_NONE:
3127 case VM_INHERIT_COPY:
3128 case VM_INHERIT_SHARE:
3129 case VM_INHERIT_ZERO:
3132 return (KERN_INVALID_ARGUMENT);
3135 return (KERN_SUCCESS);
3137 VM_MAP_RANGE_CHECK(map, start, end);
3138 rv = vm_map_lookup_clip_start(map, start, &start_entry, &prev_entry);
3139 if (rv != KERN_SUCCESS)
3141 if (vm_map_lookup_entry(map, end - 1, &lentry)) {
3142 rv = vm_map_clip_end(map, lentry, end);
3143 if (rv != KERN_SUCCESS)
3146 if (new_inheritance == VM_INHERIT_COPY) {
3147 for (entry = start_entry; entry->start < end;
3148 prev_entry = entry, entry = vm_map_entry_succ(entry)) {
3149 if ((entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK)
3151 rv = KERN_INVALID_ARGUMENT;
3156 for (entry = start_entry; entry->start < end; prev_entry = entry,
3157 entry = vm_map_entry_succ(entry)) {
3158 KASSERT(entry->end <= end, ("non-clipped entry %p end %jx %jx",
3159 entry, (uintmax_t)entry->end, (uintmax_t)end));
3160 if ((entry->eflags & MAP_ENTRY_GUARD) == 0 ||
3161 new_inheritance != VM_INHERIT_ZERO)
3162 entry->inheritance = new_inheritance;
3163 vm_map_try_merge_entries(map, prev_entry, entry);
3165 vm_map_try_merge_entries(map, prev_entry, entry);
3172 * vm_map_entry_in_transition:
3174 * Release the map lock, and sleep until the entry is no longer in
3175 * transition. Awake and acquire the map lock. If the map changed while
3176 * another held the lock, lookup a possibly-changed entry at or after the
3177 * 'start' position of the old entry.
3179 static vm_map_entry_t
3180 vm_map_entry_in_transition(vm_map_t map, vm_offset_t in_start,
3181 vm_offset_t *io_end, bool holes_ok, vm_map_entry_t in_entry)
3183 vm_map_entry_t entry;
3185 u_int last_timestamp;
3187 VM_MAP_ASSERT_LOCKED(map);
3188 KASSERT((in_entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3189 ("not in-tranition map entry %p", in_entry));
3191 * We have not yet clipped the entry.
3193 start = MAX(in_start, in_entry->start);
3194 in_entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3195 last_timestamp = map->timestamp;
3196 if (vm_map_unlock_and_wait(map, 0)) {
3198 * Allow interruption of user wiring/unwiring?
3202 if (last_timestamp + 1 == map->timestamp)
3206 * Look again for the entry because the map was modified while it was
3207 * unlocked. Specifically, the entry may have been clipped, merged, or
3210 if (!vm_map_lookup_entry(map, start, &entry)) {
3215 entry = vm_map_entry_succ(entry);
3223 * Implements both kernel and user unwiring.
3226 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
3229 vm_map_entry_t entry, first_entry, next_entry, prev_entry;
3231 bool holes_ok, need_wakeup, user_unwire;
3234 return (KERN_SUCCESS);
3235 holes_ok = (flags & VM_MAP_WIRE_HOLESOK) != 0;
3236 user_unwire = (flags & VM_MAP_WIRE_USER) != 0;
3238 VM_MAP_RANGE_CHECK(map, start, end);
3239 if (!vm_map_lookup_entry(map, start, &first_entry)) {
3241 first_entry = vm_map_entry_succ(first_entry);
3244 return (KERN_INVALID_ADDRESS);
3248 for (entry = first_entry; entry->start < end; entry = next_entry) {
3249 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
3251 * We have not yet clipped the entry.
3253 next_entry = vm_map_entry_in_transition(map, start,
3254 &end, holes_ok, entry);
3255 if (next_entry == NULL) {
3256 if (entry == first_entry) {
3258 return (KERN_INVALID_ADDRESS);
3260 rv = KERN_INVALID_ADDRESS;
3263 first_entry = (entry == first_entry) ?
3267 rv = vm_map_clip_start(map, entry, start);
3268 if (rv != KERN_SUCCESS)
3270 rv = vm_map_clip_end(map, entry, end);
3271 if (rv != KERN_SUCCESS)
3275 * Mark the entry in case the map lock is released. (See
3278 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
3279 entry->wiring_thread == NULL,
3280 ("owned map entry %p", entry));
3281 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
3282 entry->wiring_thread = curthread;
3283 next_entry = vm_map_entry_succ(entry);
3285 * Check the map for holes in the specified region.
3286 * If holes_ok, skip this check.
3289 entry->end < end && next_entry->start > entry->end) {
3291 rv = KERN_INVALID_ADDRESS;
3295 * If system unwiring, require that the entry is system wired.
3298 vm_map_entry_system_wired_count(entry) == 0) {
3300 rv = KERN_INVALID_ARGUMENT;
3304 need_wakeup = false;
3305 if (first_entry == NULL &&
3306 !vm_map_lookup_entry(map, start, &first_entry)) {
3307 KASSERT(holes_ok, ("vm_map_unwire: lookup failed"));
3308 prev_entry = first_entry;
3309 entry = vm_map_entry_succ(first_entry);
3311 prev_entry = vm_map_entry_pred(first_entry);
3312 entry = first_entry;
3314 for (; entry->start < end;
3315 prev_entry = entry, entry = vm_map_entry_succ(entry)) {
3317 * If holes_ok was specified, an empty
3318 * space in the unwired region could have been mapped
3319 * while the map lock was dropped for draining
3320 * MAP_ENTRY_IN_TRANSITION. Moreover, another thread
3321 * could be simultaneously wiring this new mapping
3322 * entry. Detect these cases and skip any entries
3323 * marked as in transition by us.
3325 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
3326 entry->wiring_thread != curthread) {
3328 ("vm_map_unwire: !HOLESOK and new/changed entry"));
3332 if (rv == KERN_SUCCESS && (!user_unwire ||
3333 (entry->eflags & MAP_ENTRY_USER_WIRED))) {
3334 if (entry->wired_count == 1)
3335 vm_map_entry_unwire(map, entry);
3337 entry->wired_count--;
3339 entry->eflags &= ~MAP_ENTRY_USER_WIRED;
3341 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3342 ("vm_map_unwire: in-transition flag missing %p", entry));
3343 KASSERT(entry->wiring_thread == curthread,
3344 ("vm_map_unwire: alien wire %p", entry));
3345 entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
3346 entry->wiring_thread = NULL;
3347 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
3348 entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
3351 vm_map_try_merge_entries(map, prev_entry, entry);
3353 vm_map_try_merge_entries(map, prev_entry, entry);
3361 vm_map_wire_user_count_sub(u_long npages)
3364 atomic_subtract_long(&vm_user_wire_count, npages);
3368 vm_map_wire_user_count_add(u_long npages)
3372 wired = vm_user_wire_count;
3374 if (npages + wired > vm_page_max_user_wired)
3376 } while (!atomic_fcmpset_long(&vm_user_wire_count, &wired,
3383 * vm_map_wire_entry_failure:
3385 * Handle a wiring failure on the given entry.
3387 * The map should be locked.
3390 vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
3391 vm_offset_t failed_addr)
3394 VM_MAP_ASSERT_LOCKED(map);
3395 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 &&
3396 entry->wired_count == 1,
3397 ("vm_map_wire_entry_failure: entry %p isn't being wired", entry));
3398 KASSERT(failed_addr < entry->end,
3399 ("vm_map_wire_entry_failure: entry %p was fully wired", entry));
3402 * If any pages at the start of this entry were successfully wired,
3405 if (failed_addr > entry->start) {
3406 pmap_unwire(map->pmap, entry->start, failed_addr);
3407 vm_object_unwire(entry->object.vm_object, entry->offset,
3408 failed_addr - entry->start, PQ_ACTIVE);
3412 * Assign an out-of-range value to represent the failure to wire this
3415 entry->wired_count = -1;
3419 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3424 rv = vm_map_wire_locked(map, start, end, flags);
3430 * vm_map_wire_locked:
3432 * Implements both kernel and user wiring. Returns with the map locked,
3433 * the map lock may be dropped.
3436 vm_map_wire_locked(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3438 vm_map_entry_t entry, first_entry, next_entry, prev_entry;
3439 vm_offset_t faddr, saved_end, saved_start;
3440 u_long incr, npages;
3441 u_int bidx, last_timestamp;
3443 bool holes_ok, need_wakeup, user_wire;
3446 VM_MAP_ASSERT_LOCKED(map);
3449 return (KERN_SUCCESS);
3451 if (flags & VM_MAP_WIRE_WRITE)
3452 prot |= VM_PROT_WRITE;
3453 holes_ok = (flags & VM_MAP_WIRE_HOLESOK) != 0;
3454 user_wire = (flags & VM_MAP_WIRE_USER) != 0;
3455 VM_MAP_RANGE_CHECK(map, start, end);
3456 if (!vm_map_lookup_entry(map, start, &first_entry)) {
3458 first_entry = vm_map_entry_succ(first_entry);
3460 return (KERN_INVALID_ADDRESS);
3462 for (entry = first_entry; entry->start < end; entry = next_entry) {
3463 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
3465 * We have not yet clipped the entry.
3467 next_entry = vm_map_entry_in_transition(map, start,
3468 &end, holes_ok, entry);
3469 if (next_entry == NULL) {
3470 if (entry == first_entry)
3471 return (KERN_INVALID_ADDRESS);
3472 rv = KERN_INVALID_ADDRESS;
3475 first_entry = (entry == first_entry) ?
3479 rv = vm_map_clip_start(map, entry, start);
3480 if (rv != KERN_SUCCESS)
3482 rv = vm_map_clip_end(map, entry, end);
3483 if (rv != KERN_SUCCESS)
3487 * Mark the entry in case the map lock is released. (See
3490 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
3491 entry->wiring_thread == NULL,
3492 ("owned map entry %p", entry));
3493 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
3494 entry->wiring_thread = curthread;
3495 if ((entry->protection & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0
3496 || (entry->protection & prot) != prot) {
3497 entry->eflags |= MAP_ENTRY_WIRE_SKIPPED;
3500 rv = KERN_INVALID_ADDRESS;
3503 } else if (entry->wired_count == 0) {
3504 entry->wired_count++;
3506 npages = atop(entry->end - entry->start);
3507 if (user_wire && !vm_map_wire_user_count_add(npages)) {
3508 vm_map_wire_entry_failure(map, entry,
3511 rv = KERN_RESOURCE_SHORTAGE;
3516 * Release the map lock, relying on the in-transition
3517 * mark. Mark the map busy for fork.
3519 saved_start = entry->start;
3520 saved_end = entry->end;
3521 last_timestamp = map->timestamp;
3522 bidx = (entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK)
3523 >> MAP_ENTRY_SPLIT_BOUNDARY_SHIFT;
3524 incr = pagesizes[bidx];
3528 for (faddr = saved_start; faddr < saved_end;
3531 * Simulate a fault to get the page and enter
3532 * it into the physical map.
3534 rv = vm_fault(map, faddr, VM_PROT_NONE,
3535 VM_FAULT_WIRE, NULL);
3536 if (rv != KERN_SUCCESS)
3541 if (last_timestamp + 1 != map->timestamp) {
3543 * Look again for the entry because the map was
3544 * modified while it was unlocked. The entry
3545 * may have been clipped, but NOT merged or
3548 if (!vm_map_lookup_entry(map, saved_start,
3551 ("vm_map_wire: lookup failed"));
3552 first_entry = (entry == first_entry) ?
3554 for (entry = next_entry; entry->end < saved_end;
3555 entry = vm_map_entry_succ(entry)) {
3557 * In case of failure, handle entries
3558 * that were not fully wired here;
3559 * fully wired entries are handled
3562 if (rv != KERN_SUCCESS &&
3564 vm_map_wire_entry_failure(map,
3568 if (rv != KERN_SUCCESS) {
3569 vm_map_wire_entry_failure(map, entry, faddr);
3571 vm_map_wire_user_count_sub(npages);
3575 } else if (!user_wire ||
3576 (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3577 entry->wired_count++;
3580 * Check the map for holes in the specified region.
3581 * If holes_ok was specified, skip this check.
3583 next_entry = vm_map_entry_succ(entry);
3585 entry->end < end && next_entry->start > entry->end) {
3587 rv = KERN_INVALID_ADDRESS;
3593 need_wakeup = false;
3594 if (first_entry == NULL &&
3595 !vm_map_lookup_entry(map, start, &first_entry)) {
3596 KASSERT(holes_ok, ("vm_map_wire: lookup failed"));
3597 prev_entry = first_entry;
3598 entry = vm_map_entry_succ(first_entry);
3600 prev_entry = vm_map_entry_pred(first_entry);
3601 entry = first_entry;
3603 for (; entry->start < end;
3604 prev_entry = entry, entry = vm_map_entry_succ(entry)) {
3606 * If holes_ok was specified, an empty
3607 * space in the unwired region could have been mapped
3608 * while the map lock was dropped for faulting in the
3609 * pages or draining MAP_ENTRY_IN_TRANSITION.
3610 * Moreover, another thread could be simultaneously
3611 * wiring this new mapping entry. Detect these cases
3612 * and skip any entries marked as in transition not by us.
3614 * Another way to get an entry not marked with
3615 * MAP_ENTRY_IN_TRANSITION is after failed clipping,
3616 * which set rv to KERN_INVALID_ARGUMENT.
3618 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
3619 entry->wiring_thread != curthread) {
3620 KASSERT(holes_ok || rv == KERN_INVALID_ARGUMENT,
3621 ("vm_map_wire: !HOLESOK and new/changed entry"));
3625 if ((entry->eflags & MAP_ENTRY_WIRE_SKIPPED) != 0) {
3627 } else if (rv == KERN_SUCCESS) {
3629 entry->eflags |= MAP_ENTRY_USER_WIRED;
3630 } else if (entry->wired_count == -1) {
3632 * Wiring failed on this entry. Thus, unwiring is
3635 entry->wired_count = 0;
3636 } else if (!user_wire ||
3637 (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3639 * Undo the wiring. Wiring succeeded on this entry
3640 * but failed on a later entry.
3642 if (entry->wired_count == 1) {
3643 vm_map_entry_unwire(map, entry);
3645 vm_map_wire_user_count_sub(
3646 atop(entry->end - entry->start));
3648 entry->wired_count--;
3650 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3651 ("vm_map_wire: in-transition flag missing %p", entry));
3652 KASSERT(entry->wiring_thread == curthread,
3653 ("vm_map_wire: alien wire %p", entry));
3654 entry->eflags &= ~(MAP_ENTRY_IN_TRANSITION |
3655 MAP_ENTRY_WIRE_SKIPPED);
3656 entry->wiring_thread = NULL;
3657 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
3658 entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
3661 vm_map_try_merge_entries(map, prev_entry, entry);
3663 vm_map_try_merge_entries(map, prev_entry, entry);
3672 * Push any dirty cached pages in the address range to their pager.
3673 * If syncio is TRUE, dirty pages are written synchronously.
3674 * If invalidate is TRUE, any cached pages are freed as well.
3676 * If the size of the region from start to end is zero, we are
3677 * supposed to flush all modified pages within the region containing
3678 * start. Unfortunately, a region can be split or coalesced with
3679 * neighboring regions, making it difficult to determine what the
3680 * original region was. Therefore, we approximate this requirement by
3681 * flushing the current region containing start.
3683 * Returns an error if any part of the specified range is not mapped.
3691 boolean_t invalidate)
3693 vm_map_entry_t entry, first_entry, next_entry;
3696 vm_ooffset_t offset;
3697 unsigned int last_timestamp;
3701 vm_map_lock_read(map);
3702 VM_MAP_RANGE_CHECK(map, start, end);
3703 if (!vm_map_lookup_entry(map, start, &first_entry)) {
3704 vm_map_unlock_read(map);
3705 return (KERN_INVALID_ADDRESS);
3706 } else if (start == end) {
3707 start = first_entry->start;
3708 end = first_entry->end;
3712 * Make a first pass to check for user-wired memory, holes,
3713 * and partial invalidation of largepage mappings.
3715 for (entry = first_entry; entry->start < end; entry = next_entry) {
3717 if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0) {
3718 vm_map_unlock_read(map);
3719 return (KERN_INVALID_ARGUMENT);
3721 bdry_idx = (entry->eflags &
3722 MAP_ENTRY_SPLIT_BOUNDARY_MASK) >>
3723 MAP_ENTRY_SPLIT_BOUNDARY_SHIFT;
3724 if (bdry_idx != 0 &&
3725 ((start & (pagesizes[bdry_idx] - 1)) != 0 ||
3726 (end & (pagesizes[bdry_idx] - 1)) != 0)) {
3727 vm_map_unlock_read(map);
3728 return (KERN_INVALID_ARGUMENT);
3731 next_entry = vm_map_entry_succ(entry);
3732 if (end > entry->end &&
3733 entry->end != next_entry->start) {
3734 vm_map_unlock_read(map);
3735 return (KERN_INVALID_ADDRESS);
3740 pmap_remove(map->pmap, start, end);
3744 * Make a second pass, cleaning/uncaching pages from the indicated
3747 for (entry = first_entry; entry->start < end;) {
3748 offset = entry->offset + (start - entry->start);
3749 size = (end <= entry->end ? end : entry->end) - start;
3750 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0) {
3752 vm_map_entry_t tentry;
3755 smap = entry->object.sub_map;
3756 vm_map_lock_read(smap);
3757 (void) vm_map_lookup_entry(smap, offset, &tentry);
3758 tsize = tentry->end - offset;
3761 object = tentry->object.vm_object;
3762 offset = tentry->offset + (offset - tentry->start);
3763 vm_map_unlock_read(smap);
3765 object = entry->object.vm_object;
3767 vm_object_reference(object);
3768 last_timestamp = map->timestamp;
3769 vm_map_unlock_read(map);
3770 if (!vm_object_sync(object, offset, size, syncio, invalidate))
3773 vm_object_deallocate(object);
3774 vm_map_lock_read(map);
3775 if (last_timestamp == map->timestamp ||
3776 !vm_map_lookup_entry(map, start, &entry))
3777 entry = vm_map_entry_succ(entry);
3780 vm_map_unlock_read(map);
3781 return (failed ? KERN_FAILURE : KERN_SUCCESS);
3785 * vm_map_entry_unwire: [ internal use only ]
3787 * Make the region specified by this entry pageable.
3789 * The map in question should be locked.
3790 * [This is the reason for this routine's existence.]
3793 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
3797 VM_MAP_ASSERT_LOCKED(map);
3798 KASSERT(entry->wired_count > 0,
3799 ("vm_map_entry_unwire: entry %p isn't wired", entry));
3801 size = entry->end - entry->start;
3802 if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0)
3803 vm_map_wire_user_count_sub(atop(size));
3804 pmap_unwire(map->pmap, entry->start, entry->end);
3805 vm_object_unwire(entry->object.vm_object, entry->offset, size,
3807 entry->wired_count = 0;
3811 vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map)
3814 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
3815 vm_object_deallocate(entry->object.vm_object);
3816 uma_zfree(system_map ? kmapentzone : mapentzone, entry);
3820 * vm_map_entry_delete: [ internal use only ]
3822 * Deallocate the given entry from the target map.
3825 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
3828 vm_pindex_t offidxstart, offidxend, size1;
3831 vm_map_entry_unlink(map, entry, UNLINK_MERGE_NONE);
3832 object = entry->object.vm_object;
3834 if ((entry->eflags & MAP_ENTRY_GUARD) != 0) {
3835 MPASS(entry->cred == NULL);
3836 MPASS((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0);
3837 MPASS(object == NULL);
3838 vm_map_entry_deallocate(entry, map->system_map);
3842 size = entry->end - entry->start;
3845 if (entry->cred != NULL) {
3846 swap_release_by_cred(size, entry->cred);
3847 crfree(entry->cred);
3850 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 || object == NULL) {
3851 entry->object.vm_object = NULL;
3852 } else if ((object->flags & OBJ_ANON) != 0 ||
3853 object == kernel_object) {
3854 KASSERT(entry->cred == NULL || object->cred == NULL ||
3855 (entry->eflags & MAP_ENTRY_NEEDS_COPY),
3856 ("OVERCOMMIT vm_map_entry_delete: both cred %p", entry));
3857 offidxstart = OFF_TO_IDX(entry->offset);
3858 offidxend = offidxstart + atop(size);
3859 VM_OBJECT_WLOCK(object);
3860 if (object->ref_count != 1 &&
3861 ((object->flags & OBJ_ONEMAPPING) != 0 ||
3862 object == kernel_object)) {
3863 vm_object_collapse(object);
3866 * The option OBJPR_NOTMAPPED can be passed here
3867 * because vm_map_delete() already performed
3868 * pmap_remove() on the only mapping to this range
3871 vm_object_page_remove(object, offidxstart, offidxend,
3873 if (offidxend >= object->size &&
3874 offidxstart < object->size) {
3875 size1 = object->size;
3876 object->size = offidxstart;
3877 if (object->cred != NULL) {
3878 size1 -= object->size;
3879 KASSERT(object->charge >= ptoa(size1),
3880 ("object %p charge < 0", object));
3881 swap_release_by_cred(ptoa(size1),
3883 object->charge -= ptoa(size1);
3887 VM_OBJECT_WUNLOCK(object);
3889 if (map->system_map)
3890 vm_map_entry_deallocate(entry, TRUE);
3892 entry->defer_next = curthread->td_map_def_user;
3893 curthread->td_map_def_user = entry;
3898 * vm_map_delete: [ internal use only ]
3900 * Deallocates the given address range from the target
3904 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
3906 vm_map_entry_t entry, next_entry, scratch_entry;
3909 VM_MAP_ASSERT_LOCKED(map);
3912 return (KERN_SUCCESS);
3915 * Find the start of the region, and clip it.
3916 * Step through all entries in this region.
3918 rv = vm_map_lookup_clip_start(map, start, &entry, &scratch_entry);
3919 if (rv != KERN_SUCCESS)
3921 for (; entry->start < end; entry = next_entry) {
3923 * Wait for wiring or unwiring of an entry to complete.
3924 * Also wait for any system wirings to disappear on
3927 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
3928 (vm_map_pmap(map) != kernel_pmap &&
3929 vm_map_entry_system_wired_count(entry) != 0)) {
3930 unsigned int last_timestamp;
3931 vm_offset_t saved_start;
3933 saved_start = entry->start;
3934 entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3935 last_timestamp = map->timestamp;
3936 (void) vm_map_unlock_and_wait(map, 0);
3938 if (last_timestamp + 1 != map->timestamp) {
3940 * Look again for the entry because the map was
3941 * modified while it was unlocked.
3942 * Specifically, the entry may have been
3943 * clipped, merged, or deleted.
3945 rv = vm_map_lookup_clip_start(map, saved_start,
3946 &next_entry, &scratch_entry);
3947 if (rv != KERN_SUCCESS)
3954 /* XXXKIB or delete to the upper superpage boundary ? */
3955 rv = vm_map_clip_end(map, entry, end);
3956 if (rv != KERN_SUCCESS)
3958 next_entry = vm_map_entry_succ(entry);
3961 * Unwire before removing addresses from the pmap; otherwise,
3962 * unwiring will put the entries back in the pmap.
3964 if (entry->wired_count != 0)
3965 vm_map_entry_unwire(map, entry);
3968 * Remove mappings for the pages, but only if the
3969 * mappings could exist. For instance, it does not
3970 * make sense to call pmap_remove() for guard entries.
3972 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 ||
3973 entry->object.vm_object != NULL)
3974 pmap_remove(map->pmap, entry->start, entry->end);
3976 if (entry->end == map->anon_loc)
3977 map->anon_loc = entry->start;
3980 * Delete the entry only after removing all pmap
3981 * entries pointing to its pages. (Otherwise, its
3982 * page frames may be reallocated, and any modify bits
3983 * will be set in the wrong object!)
3985 vm_map_entry_delete(map, entry);
3993 * Remove the given address range from the target map.
3994 * This is the exported form of vm_map_delete.
3997 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
4002 VM_MAP_RANGE_CHECK(map, start, end);
4003 result = vm_map_delete(map, start, end);
4009 * vm_map_check_protection:
4011 * Assert that the target map allows the specified privilege on the
4012 * entire address region given. The entire region must be allocated.
4014 * WARNING! This code does not and should not check whether the
4015 * contents of the region is accessible. For example a smaller file
4016 * might be mapped into a larger address space.
4018 * NOTE! This code is also called by munmap().
4020 * The map must be locked. A read lock is sufficient.
4023 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
4024 vm_prot_t protection)
4026 vm_map_entry_t entry;
4027 vm_map_entry_t tmp_entry;
4029 if (!vm_map_lookup_entry(map, start, &tmp_entry))
4033 while (start < end) {
4037 if (start < entry->start)
4040 * Check protection associated with entry.
4042 if ((entry->protection & protection) != protection)
4044 /* go to next entry */
4046 entry = vm_map_entry_succ(entry);
4053 * vm_map_copy_swap_object:
4055 * Copies a swap-backed object from an existing map entry to a
4056 * new one. Carries forward the swap charge. May change the
4057 * src object on return.
4060 vm_map_copy_swap_object(vm_map_entry_t src_entry, vm_map_entry_t dst_entry,
4061 vm_offset_t size, vm_ooffset_t *fork_charge)
4063 vm_object_t src_object;
4067 src_object = src_entry->object.vm_object;
4068 charged = ENTRY_CHARGED(src_entry);
4069 if ((src_object->flags & OBJ_ANON) != 0) {
4070 VM_OBJECT_WLOCK(src_object);
4071 vm_object_collapse(src_object);
4072 if ((src_object->flags & OBJ_ONEMAPPING) != 0) {
4073 vm_object_split(src_entry);
4074 src_object = src_entry->object.vm_object;
4076 vm_object_reference_locked(src_object);
4077 vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
4078 VM_OBJECT_WUNLOCK(src_object);
4080 vm_object_reference(src_object);
4081 if (src_entry->cred != NULL &&
4082 !(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
4083 KASSERT(src_object->cred == NULL,
4084 ("OVERCOMMIT: vm_map_copy_anon_entry: cred %p",
4086 src_object->cred = src_entry->cred;
4087 src_object->charge = size;
4089 dst_entry->object.vm_object = src_object;
4091 cred = curthread->td_ucred;
4093 dst_entry->cred = cred;
4094 *fork_charge += size;
4095 if (!(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
4097 src_entry->cred = cred;
4098 *fork_charge += size;
4104 * vm_map_copy_entry:
4106 * Copies the contents of the source entry to the destination
4107 * entry. The entries *must* be aligned properly.
4113 vm_map_entry_t src_entry,
4114 vm_map_entry_t dst_entry,
4115 vm_ooffset_t *fork_charge)
4117 vm_object_t src_object;
4118 vm_map_entry_t fake_entry;
4121 VM_MAP_ASSERT_LOCKED(dst_map);
4123 if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
4126 if (src_entry->wired_count == 0 ||
4127 (src_entry->protection & VM_PROT_WRITE) == 0) {
4129 * If the source entry is marked needs_copy, it is already
4132 if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0 &&
4133 (src_entry->protection & VM_PROT_WRITE) != 0) {
4134 pmap_protect(src_map->pmap,
4137 src_entry->protection & ~VM_PROT_WRITE);
4141 * Make a copy of the object.
4143 size = src_entry->end - src_entry->start;
4144 if ((src_object = src_entry->object.vm_object) != NULL) {
4145 if (src_object->type == OBJT_DEFAULT ||
4146 (src_object->flags & OBJ_SWAP) != 0) {
4147 vm_map_copy_swap_object(src_entry, dst_entry,
4149 /* May have split/collapsed, reload obj. */
4150 src_object = src_entry->object.vm_object;
4152 vm_object_reference(src_object);
4153 dst_entry->object.vm_object = src_object;
4155 src_entry->eflags |= MAP_ENTRY_COW |
4156 MAP_ENTRY_NEEDS_COPY;
4157 dst_entry->eflags |= MAP_ENTRY_COW |
4158 MAP_ENTRY_NEEDS_COPY;
4159 dst_entry->offset = src_entry->offset;
4160 if (src_entry->eflags & MAP_ENTRY_WRITECNT) {
4162 * MAP_ENTRY_WRITECNT cannot
4163 * indicate write reference from
4164 * src_entry, since the entry is
4165 * marked as needs copy. Allocate a
4166 * fake entry that is used to
4167 * decrement object->un_pager writecount
4168 * at the appropriate time. Attach
4169 * fake_entry to the deferred list.
4171 fake_entry = vm_map_entry_create(dst_map);
4172 fake_entry->eflags = MAP_ENTRY_WRITECNT;
4173 src_entry->eflags &= ~MAP_ENTRY_WRITECNT;
4174 vm_object_reference(src_object);
4175 fake_entry->object.vm_object = src_object;
4176 fake_entry->start = src_entry->start;
4177 fake_entry->end = src_entry->end;
4178 fake_entry->defer_next =
4179 curthread->td_map_def_user;
4180 curthread->td_map_def_user = fake_entry;
4183 pmap_copy(dst_map->pmap, src_map->pmap,
4184 dst_entry->start, dst_entry->end - dst_entry->start,
4187 dst_entry->object.vm_object = NULL;
4188 dst_entry->offset = 0;
4189 if (src_entry->cred != NULL) {
4190 dst_entry->cred = curthread->td_ucred;
4191 crhold(dst_entry->cred);
4192 *fork_charge += size;
4197 * We don't want to make writeable wired pages copy-on-write.
4198 * Immediately copy these pages into the new map by simulating
4199 * page faults. The new pages are pageable.
4201 vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry,
4207 * vmspace_map_entry_forked:
4208 * Update the newly-forked vmspace each time a map entry is inherited
4209 * or copied. The values for vm_dsize and vm_tsize are approximate
4210 * (and mostly-obsolete ideas in the face of mmap(2) et al.)
4213 vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
4214 vm_map_entry_t entry)
4216 vm_size_t entrysize;
4219 if ((entry->eflags & MAP_ENTRY_GUARD) != 0)
4221 entrysize = entry->end - entry->start;
4222 vm2->vm_map.size += entrysize;
4223 if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
4224 vm2->vm_ssize += btoc(entrysize);
4225 } else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
4226 entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
4227 newend = MIN(entry->end,
4228 (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
4229 vm2->vm_dsize += btoc(newend - entry->start);
4230 } else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
4231 entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
4232 newend = MIN(entry->end,
4233 (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
4234 vm2->vm_tsize += btoc(newend - entry->start);
4240 * Create a new process vmspace structure and vm_map
4241 * based on those of an existing process. The new map
4242 * is based on the old map, according to the inheritance
4243 * values on the regions in that map.
4245 * XXX It might be worth coalescing the entries added to the new vmspace.
4247 * The source map must not be locked.
4250 vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
4252 struct vmspace *vm2;
4253 vm_map_t new_map, old_map;
4254 vm_map_entry_t new_entry, old_entry;
4259 old_map = &vm1->vm_map;
4260 /* Copy immutable fields of vm1 to vm2. */
4261 vm2 = vmspace_alloc(vm_map_min(old_map), vm_map_max(old_map),
4266 vm2->vm_taddr = vm1->vm_taddr;
4267 vm2->vm_daddr = vm1->vm_daddr;
4268 vm2->vm_maxsaddr = vm1->vm_maxsaddr;
4269 vm2->vm_stkgap = vm1->vm_stkgap;
4270 vm_map_lock(old_map);
4272 vm_map_wait_busy(old_map);
4273 new_map = &vm2->vm_map;
4274 locked = vm_map_trylock(new_map); /* trylock to silence WITNESS */
4275 KASSERT(locked, ("vmspace_fork: lock failed"));
4277 error = pmap_vmspace_copy(new_map->pmap, old_map->pmap);
4279 sx_xunlock(&old_map->lock);
4280 sx_xunlock(&new_map->lock);
4281 vm_map_process_deferred();
4286 new_map->anon_loc = old_map->anon_loc;
4287 new_map->flags |= old_map->flags & (MAP_ASLR | MAP_ASLR_IGNSTART |
4290 VM_MAP_ENTRY_FOREACH(old_entry, old_map) {
4291 if ((old_entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
4292 panic("vm_map_fork: encountered a submap");
4294 inh = old_entry->inheritance;
4295 if ((old_entry->eflags & MAP_ENTRY_GUARD) != 0 &&
4296 inh != VM_INHERIT_NONE)
4297 inh = VM_INHERIT_COPY;
4300 case VM_INHERIT_NONE:
4303 case VM_INHERIT_SHARE:
4305 * Clone the entry, creating the shared object if
4308 object = old_entry->object.vm_object;
4309 if (object == NULL) {
4310 vm_map_entry_back(old_entry);
4311 object = old_entry->object.vm_object;
4315 * Add the reference before calling vm_object_shadow
4316 * to insure that a shadow object is created.
4318 vm_object_reference(object);
4319 if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4320 vm_object_shadow(&old_entry->object.vm_object,
4322 old_entry->end - old_entry->start,
4324 /* Transfer the second reference too. */
4326 old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
4327 old_entry->cred = NULL;
4330 * As in vm_map_merged_neighbor_dispose(),
4331 * the vnode lock will not be acquired in
4332 * this call to vm_object_deallocate().
4334 vm_object_deallocate(object);
4335 object = old_entry->object.vm_object;
4337 VM_OBJECT_WLOCK(object);
4338 vm_object_clear_flag(object, OBJ_ONEMAPPING);
4339 if (old_entry->cred != NULL) {
4340 KASSERT(object->cred == NULL,
4341 ("vmspace_fork both cred"));
4342 object->cred = old_entry->cred;
4343 object->charge = old_entry->end -
4345 old_entry->cred = NULL;
4349 * Assert the correct state of the vnode
4350 * v_writecount while the object is locked, to
4351 * not relock it later for the assertion
4354 if (old_entry->eflags & MAP_ENTRY_WRITECNT &&
4355 object->type == OBJT_VNODE) {
4356 KASSERT(((struct vnode *)object->
4357 handle)->v_writecount > 0,
4358 ("vmspace_fork: v_writecount %p",
4360 KASSERT(object->un_pager.vnp.
4362 ("vmspace_fork: vnp.writecount %p",
4365 VM_OBJECT_WUNLOCK(object);
4369 * Clone the entry, referencing the shared object.
4371 new_entry = vm_map_entry_create(new_map);
4372 *new_entry = *old_entry;
4373 new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
4374 MAP_ENTRY_IN_TRANSITION);
4375 new_entry->wiring_thread = NULL;
4376 new_entry->wired_count = 0;
4377 if (new_entry->eflags & MAP_ENTRY_WRITECNT) {
4378 vm_pager_update_writecount(object,
4379 new_entry->start, new_entry->end);
4381 vm_map_entry_set_vnode_text(new_entry, true);
4384 * Insert the entry into the new map -- we know we're
4385 * inserting at the end of the new map.
4387 vm_map_entry_link(new_map, new_entry);
4388 vmspace_map_entry_forked(vm1, vm2, new_entry);
4391 * Update the physical map
4393 pmap_copy(new_map->pmap, old_map->pmap,
4395 (old_entry->end - old_entry->start),
4399 case VM_INHERIT_COPY:
4401 * Clone the entry and link into the map.
4403 new_entry = vm_map_entry_create(new_map);
4404 *new_entry = *old_entry;
4406 * Copied entry is COW over the old object.
4408 new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
4409 MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_WRITECNT);
4410 new_entry->wiring_thread = NULL;
4411 new_entry->wired_count = 0;
4412 new_entry->object.vm_object = NULL;
4413 new_entry->cred = NULL;
4414 vm_map_entry_link(new_map, new_entry);
4415 vmspace_map_entry_forked(vm1, vm2, new_entry);
4416 vm_map_copy_entry(old_map, new_map, old_entry,
4417 new_entry, fork_charge);
4418 vm_map_entry_set_vnode_text(new_entry, true);
4421 case VM_INHERIT_ZERO:
4423 * Create a new anonymous mapping entry modelled from
4426 new_entry = vm_map_entry_create(new_map);
4427 memset(new_entry, 0, sizeof(*new_entry));
4429 new_entry->start = old_entry->start;
4430 new_entry->end = old_entry->end;
4431 new_entry->eflags = old_entry->eflags &
4432 ~(MAP_ENTRY_USER_WIRED | MAP_ENTRY_IN_TRANSITION |
4433 MAP_ENTRY_WRITECNT | MAP_ENTRY_VN_EXEC |
4434 MAP_ENTRY_SPLIT_BOUNDARY_MASK);
4435 new_entry->protection = old_entry->protection;
4436 new_entry->max_protection = old_entry->max_protection;
4437 new_entry->inheritance = VM_INHERIT_ZERO;
4439 vm_map_entry_link(new_map, new_entry);
4440 vmspace_map_entry_forked(vm1, vm2, new_entry);
4442 new_entry->cred = curthread->td_ucred;
4443 crhold(new_entry->cred);
4444 *fork_charge += (new_entry->end - new_entry->start);
4450 * Use inlined vm_map_unlock() to postpone handling the deferred
4451 * map entries, which cannot be done until both old_map and
4452 * new_map locks are released.
4454 sx_xunlock(&old_map->lock);
4455 sx_xunlock(&new_map->lock);
4456 vm_map_process_deferred();
4462 * Create a process's stack for exec_new_vmspace(). This function is never
4463 * asked to wire the newly created stack.
4466 vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4467 vm_prot_t prot, vm_prot_t max, int cow)
4469 vm_size_t growsize, init_ssize;
4473 MPASS((map->flags & MAP_WIREFUTURE) == 0);
4474 growsize = sgrowsiz;
4475 init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
4477 vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4478 /* If we would blow our VMEM resource limit, no go */
4479 if (map->size + init_ssize > vmemlim) {
4483 rv = vm_map_stack_locked(map, addrbos, max_ssize, growsize, prot,
4490 static int stack_guard_page = 1;
4491 SYSCTL_INT(_security_bsd, OID_AUTO, stack_guard_page, CTLFLAG_RWTUN,
4492 &stack_guard_page, 0,
4493 "Specifies the number of guard pages for a stack that grows");
4496 vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4497 vm_size_t growsize, vm_prot_t prot, vm_prot_t max, int cow)
4499 vm_map_entry_t new_entry, prev_entry;
4500 vm_offset_t bot, gap_bot, gap_top, top;
4501 vm_size_t init_ssize, sgp;
4505 * The stack orientation is piggybacked with the cow argument.
4506 * Extract it into orient and mask the cow argument so that we
4507 * don't pass it around further.
4509 orient = cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP);
4510 KASSERT(orient != 0, ("No stack grow direction"));
4511 KASSERT(orient != (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP),
4514 if (max_ssize == 0 ||
4515 !vm_map_range_valid(map, addrbos, addrbos + max_ssize))
4516 return (KERN_INVALID_ADDRESS);
4517 sgp = ((curproc->p_flag2 & P2_STKGAP_DISABLE) != 0 ||
4518 (curproc->p_fctl0 & NT_FREEBSD_FCTL_STKGAP_DISABLE) != 0) ? 0 :
4519 (vm_size_t)stack_guard_page * PAGE_SIZE;
4520 if (sgp >= max_ssize)
4521 return (KERN_INVALID_ARGUMENT);
4523 init_ssize = growsize;
4524 if (max_ssize < init_ssize + sgp)
4525 init_ssize = max_ssize - sgp;
4527 /* If addr is already mapped, no go */
4528 if (vm_map_lookup_entry(map, addrbos, &prev_entry))
4529 return (KERN_NO_SPACE);
4532 * If we can't accommodate max_ssize in the current mapping, no go.
4534 if (vm_map_entry_succ(prev_entry)->start < addrbos + max_ssize)
4535 return (KERN_NO_SPACE);
4538 * We initially map a stack of only init_ssize. We will grow as
4539 * needed later. Depending on the orientation of the stack (i.e.
4540 * the grow direction) we either map at the top of the range, the
4541 * bottom of the range or in the middle.
4543 * Note: we would normally expect prot and max to be VM_PROT_ALL,
4544 * and cow to be 0. Possibly we should eliminate these as input
4545 * parameters, and just pass these values here in the insert call.
4547 if (orient == MAP_STACK_GROWS_DOWN) {
4548 bot = addrbos + max_ssize - init_ssize;
4549 top = bot + init_ssize;
4552 } else /* if (orient == MAP_STACK_GROWS_UP) */ {
4554 top = bot + init_ssize;
4556 gap_top = addrbos + max_ssize;
4558 rv = vm_map_insert(map, NULL, 0, bot, top, prot, max, cow);
4559 if (rv != KERN_SUCCESS)
4561 new_entry = vm_map_entry_succ(prev_entry);
4562 KASSERT(new_entry->end == top || new_entry->start == bot,
4563 ("Bad entry start/end for new stack entry"));
4564 KASSERT((orient & MAP_STACK_GROWS_DOWN) == 0 ||
4565 (new_entry->eflags & MAP_ENTRY_GROWS_DOWN) != 0,
4566 ("new entry lacks MAP_ENTRY_GROWS_DOWN"));
4567 KASSERT((orient & MAP_STACK_GROWS_UP) == 0 ||
4568 (new_entry->eflags & MAP_ENTRY_GROWS_UP) != 0,
4569 ("new entry lacks MAP_ENTRY_GROWS_UP"));
4570 if (gap_bot == gap_top)
4571 return (KERN_SUCCESS);
4572 rv = vm_map_insert(map, NULL, 0, gap_bot, gap_top, VM_PROT_NONE,
4573 VM_PROT_NONE, MAP_CREATE_GUARD | (orient == MAP_STACK_GROWS_DOWN ?
4574 MAP_CREATE_STACK_GAP_DN : MAP_CREATE_STACK_GAP_UP));
4575 if (rv == KERN_SUCCESS) {
4577 * Gap can never successfully handle a fault, so
4578 * read-ahead logic is never used for it. Re-use
4579 * next_read of the gap entry to store
4580 * stack_guard_page for vm_map_growstack().
4582 if (orient == MAP_STACK_GROWS_DOWN)
4583 vm_map_entry_pred(new_entry)->next_read = sgp;
4585 vm_map_entry_succ(new_entry)->next_read = sgp;
4587 (void)vm_map_delete(map, bot, top);
4593 * Attempts to grow a vm stack entry. Returns KERN_SUCCESS if we
4594 * successfully grow the stack.
4597 vm_map_growstack(vm_map_t map, vm_offset_t addr, vm_map_entry_t gap_entry)
4599 vm_map_entry_t stack_entry;
4603 vm_offset_t gap_end, gap_start, grow_start;
4604 vm_size_t grow_amount, guard, max_grow;
4605 rlim_t lmemlim, stacklim, vmemlim;
4607 bool gap_deleted, grow_down, is_procstack;
4619 * Disallow stack growth when the access is performed by a
4620 * debugger or AIO daemon. The reason is that the wrong
4621 * resource limits are applied.
4623 if (p != initproc && (map != &p->p_vmspace->vm_map ||
4624 p->p_textvp == NULL))
4625 return (KERN_FAILURE);
4627 MPASS(!map->system_map);
4629 lmemlim = lim_cur(curthread, RLIMIT_MEMLOCK);
4630 stacklim = lim_cur(curthread, RLIMIT_STACK);
4631 vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4633 /* If addr is not in a hole for a stack grow area, no need to grow. */
4634 if (gap_entry == NULL && !vm_map_lookup_entry(map, addr, &gap_entry))
4635 return (KERN_FAILURE);
4636 if ((gap_entry->eflags & MAP_ENTRY_GUARD) == 0)
4637 return (KERN_SUCCESS);
4638 if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_DN) != 0) {
4639 stack_entry = vm_map_entry_succ(gap_entry);
4640 if ((stack_entry->eflags & MAP_ENTRY_GROWS_DOWN) == 0 ||
4641 stack_entry->start != gap_entry->end)
4642 return (KERN_FAILURE);
4643 grow_amount = round_page(stack_entry->start - addr);
4645 } else if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_UP) != 0) {
4646 stack_entry = vm_map_entry_pred(gap_entry);
4647 if ((stack_entry->eflags & MAP_ENTRY_GROWS_UP) == 0 ||
4648 stack_entry->end != gap_entry->start)
4649 return (KERN_FAILURE);
4650 grow_amount = round_page(addr + 1 - stack_entry->end);
4653 return (KERN_FAILURE);
4655 guard = ((curproc->p_flag2 & P2_STKGAP_DISABLE) != 0 ||
4656 (curproc->p_fctl0 & NT_FREEBSD_FCTL_STKGAP_DISABLE) != 0) ? 0 :
4657 gap_entry->next_read;
4658 max_grow = gap_entry->end - gap_entry->start;
4659 if (guard > max_grow)
4660 return (KERN_NO_SPACE);
4662 if (grow_amount > max_grow)
4663 return (KERN_NO_SPACE);
4666 * If this is the main process stack, see if we're over the stack
4669 is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr &&
4670 addr < (vm_offset_t)p->p_sysent->sv_usrstack;
4671 if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim))
4672 return (KERN_NO_SPACE);
4677 if (is_procstack && racct_set(p, RACCT_STACK,
4678 ctob(vm->vm_ssize) + grow_amount)) {
4680 return (KERN_NO_SPACE);
4686 grow_amount = roundup(grow_amount, sgrowsiz);
4687 if (grow_amount > max_grow)
4688 grow_amount = max_grow;
4689 if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
4690 grow_amount = trunc_page((vm_size_t)stacklim) -
4696 limit = racct_get_available(p, RACCT_STACK);
4698 if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > limit))
4699 grow_amount = limit - ctob(vm->vm_ssize);
4702 if (!old_mlock && (map->flags & MAP_WIREFUTURE) != 0) {
4703 if (ptoa(pmap_wired_count(map->pmap)) + grow_amount > lmemlim) {
4710 if (racct_set(p, RACCT_MEMLOCK,
4711 ptoa(pmap_wired_count(map->pmap)) + grow_amount)) {
4721 /* If we would blow our VMEM resource limit, no go */
4722 if (map->size + grow_amount > vmemlim) {
4729 if (racct_set(p, RACCT_VMEM, map->size + grow_amount)) {
4738 if (vm_map_lock_upgrade(map)) {
4740 vm_map_lock_read(map);
4745 grow_start = gap_entry->end - grow_amount;
4746 if (gap_entry->start + grow_amount == gap_entry->end) {
4747 gap_start = gap_entry->start;
4748 gap_end = gap_entry->end;
4749 vm_map_entry_delete(map, gap_entry);
4752 MPASS(gap_entry->start < gap_entry->end - grow_amount);
4753 vm_map_entry_resize(map, gap_entry, -grow_amount);
4754 gap_deleted = false;
4756 rv = vm_map_insert(map, NULL, 0, grow_start,
4757 grow_start + grow_amount,
4758 stack_entry->protection, stack_entry->max_protection,
4759 MAP_STACK_GROWS_DOWN);
4760 if (rv != KERN_SUCCESS) {
4762 rv1 = vm_map_insert(map, NULL, 0, gap_start,
4763 gap_end, VM_PROT_NONE, VM_PROT_NONE,
4764 MAP_CREATE_GUARD | MAP_CREATE_STACK_GAP_DN);
4765 MPASS(rv1 == KERN_SUCCESS);
4767 vm_map_entry_resize(map, gap_entry,
4771 grow_start = stack_entry->end;
4772 cred = stack_entry->cred;
4773 if (cred == NULL && stack_entry->object.vm_object != NULL)
4774 cred = stack_entry->object.vm_object->cred;
4775 if (cred != NULL && !swap_reserve_by_cred(grow_amount, cred))
4777 /* Grow the underlying object if applicable. */
4778 else if (stack_entry->object.vm_object == NULL ||
4779 vm_object_coalesce(stack_entry->object.vm_object,
4780 stack_entry->offset,
4781 (vm_size_t)(stack_entry->end - stack_entry->start),
4782 grow_amount, cred != NULL)) {
4783 if (gap_entry->start + grow_amount == gap_entry->end) {
4784 vm_map_entry_delete(map, gap_entry);
4785 vm_map_entry_resize(map, stack_entry,
4788 gap_entry->start += grow_amount;
4789 stack_entry->end += grow_amount;
4791 map->size += grow_amount;
4796 if (rv == KERN_SUCCESS && is_procstack)
4797 vm->vm_ssize += btoc(grow_amount);
4800 * Heed the MAP_WIREFUTURE flag if it was set for this process.
4802 if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE) != 0) {
4803 rv = vm_map_wire_locked(map, grow_start,
4804 grow_start + grow_amount,
4805 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
4807 vm_map_lock_downgrade(map);
4811 if (racct_enable && rv != KERN_SUCCESS) {
4813 error = racct_set(p, RACCT_VMEM, map->size);
4814 KASSERT(error == 0, ("decreasing RACCT_VMEM failed"));
4816 error = racct_set(p, RACCT_MEMLOCK,
4817 ptoa(pmap_wired_count(map->pmap)));
4818 KASSERT(error == 0, ("decreasing RACCT_MEMLOCK failed"));
4820 error = racct_set(p, RACCT_STACK, ctob(vm->vm_ssize));
4821 KASSERT(error == 0, ("decreasing RACCT_STACK failed"));
4830 * Unshare the specified VM space for exec. If other processes are
4831 * mapped to it, then create a new one. The new vmspace is null.
4834 vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
4836 struct vmspace *oldvmspace = p->p_vmspace;
4837 struct vmspace *newvmspace;
4839 KASSERT((curthread->td_pflags & TDP_EXECVMSPC) == 0,
4840 ("vmspace_exec recursed"));
4841 newvmspace = vmspace_alloc(minuser, maxuser, pmap_pinit);
4842 if (newvmspace == NULL)
4844 newvmspace->vm_swrss = oldvmspace->vm_swrss;
4846 * This code is written like this for prototype purposes. The
4847 * goal is to avoid running down the vmspace here, but let the
4848 * other process's that are still using the vmspace to finally
4849 * run it down. Even though there is little or no chance of blocking
4850 * here, it is a good idea to keep this form for future mods.
4852 PROC_VMSPACE_LOCK(p);
4853 p->p_vmspace = newvmspace;
4854 PROC_VMSPACE_UNLOCK(p);
4855 if (p == curthread->td_proc)
4856 pmap_activate(curthread);
4857 curthread->td_pflags |= TDP_EXECVMSPC;
4862 * Unshare the specified VM space for forcing COW. This
4863 * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
4866 vmspace_unshare(struct proc *p)
4868 struct vmspace *oldvmspace = p->p_vmspace;
4869 struct vmspace *newvmspace;
4870 vm_ooffset_t fork_charge;
4873 * The caller is responsible for ensuring that the reference count
4874 * cannot concurrently transition 1 -> 2.
4876 if (refcount_load(&oldvmspace->vm_refcnt) == 1)
4879 newvmspace = vmspace_fork(oldvmspace, &fork_charge);
4880 if (newvmspace == NULL)
4882 if (!swap_reserve_by_cred(fork_charge, p->p_ucred)) {
4883 vmspace_free(newvmspace);
4886 PROC_VMSPACE_LOCK(p);
4887 p->p_vmspace = newvmspace;
4888 PROC_VMSPACE_UNLOCK(p);
4889 if (p == curthread->td_proc)
4890 pmap_activate(curthread);
4891 vmspace_free(oldvmspace);
4898 * Finds the VM object, offset, and
4899 * protection for a given virtual address in the
4900 * specified map, assuming a page fault of the
4903 * Leaves the map in question locked for read; return
4904 * values are guaranteed until a vm_map_lookup_done
4905 * call is performed. Note that the map argument
4906 * is in/out; the returned map must be used in
4907 * the call to vm_map_lookup_done.
4909 * A handle (out_entry) is returned for use in
4910 * vm_map_lookup_done, to make that fast.
4912 * If a lookup is requested with "write protection"
4913 * specified, the map may be changed to perform virtual
4914 * copying operations, although the data referenced will
4918 vm_map_lookup(vm_map_t *var_map, /* IN/OUT */
4920 vm_prot_t fault_typea,
4921 vm_map_entry_t *out_entry, /* OUT */
4922 vm_object_t *object, /* OUT */
4923 vm_pindex_t *pindex, /* OUT */
4924 vm_prot_t *out_prot, /* OUT */
4925 boolean_t *wired) /* OUT */
4927 vm_map_entry_t entry;
4928 vm_map_t map = *var_map;
4930 vm_prot_t fault_type;
4931 vm_object_t eobject;
4937 vm_map_lock_read(map);
4941 * Lookup the faulting address.
4943 if (!vm_map_lookup_entry(map, vaddr, out_entry)) {
4944 vm_map_unlock_read(map);
4945 return (KERN_INVALID_ADDRESS);
4953 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4954 vm_map_t old_map = map;
4956 *var_map = map = entry->object.sub_map;
4957 vm_map_unlock_read(old_map);
4962 * Check whether this task is allowed to have this page.
4964 prot = entry->protection;
4965 if ((fault_typea & VM_PROT_FAULT_LOOKUP) != 0) {
4966 fault_typea &= ~VM_PROT_FAULT_LOOKUP;
4967 if (prot == VM_PROT_NONE && map != kernel_map &&
4968 (entry->eflags & MAP_ENTRY_GUARD) != 0 &&
4969 (entry->eflags & (MAP_ENTRY_STACK_GAP_DN |
4970 MAP_ENTRY_STACK_GAP_UP)) != 0 &&
4971 vm_map_growstack(map, vaddr, entry) == KERN_SUCCESS)
4972 goto RetryLookupLocked;
4974 fault_type = fault_typea & VM_PROT_ALL;
4975 if ((fault_type & prot) != fault_type || prot == VM_PROT_NONE) {
4976 vm_map_unlock_read(map);
4977 return (KERN_PROTECTION_FAILURE);
4979 KASSERT((prot & VM_PROT_WRITE) == 0 || (entry->eflags &
4980 (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY)) !=
4981 (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY),
4982 ("entry %p flags %x", entry, entry->eflags));
4983 if ((fault_typea & VM_PROT_COPY) != 0 &&
4984 (entry->max_protection & VM_PROT_WRITE) == 0 &&
4985 (entry->eflags & MAP_ENTRY_COW) == 0) {
4986 vm_map_unlock_read(map);
4987 return (KERN_PROTECTION_FAILURE);
4991 * If this page is not pageable, we have to get it for all possible
4994 *wired = (entry->wired_count != 0);
4996 fault_type = entry->protection;
4997 size = entry->end - entry->start;
5000 * If the entry was copy-on-write, we either ...
5002 if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
5004 * If we want to write the page, we may as well handle that
5005 * now since we've got the map locked.
5007 * If we don't need to write the page, we just demote the
5008 * permissions allowed.
5010 if ((fault_type & VM_PROT_WRITE) != 0 ||
5011 (fault_typea & VM_PROT_COPY) != 0) {
5013 * Make a new object, and place it in the object
5014 * chain. Note that no new references have appeared
5015 * -- one just moved from the map to the new
5018 if (vm_map_lock_upgrade(map))
5021 if (entry->cred == NULL) {
5023 * The debugger owner is charged for
5026 cred = curthread->td_ucred;
5028 if (!swap_reserve_by_cred(size, cred)) {
5031 return (KERN_RESOURCE_SHORTAGE);
5035 eobject = entry->object.vm_object;
5036 vm_object_shadow(&entry->object.vm_object,
5037 &entry->offset, size, entry->cred, false);
5038 if (eobject == entry->object.vm_object) {
5040 * The object was not shadowed.
5042 swap_release_by_cred(size, entry->cred);
5043 crfree(entry->cred);
5046 entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
5048 vm_map_lock_downgrade(map);
5051 * We're attempting to read a copy-on-write page --
5052 * don't allow writes.
5054 prot &= ~VM_PROT_WRITE;
5059 * Create an object if necessary.
5061 if (entry->object.vm_object == NULL && !map->system_map) {
5062 if (vm_map_lock_upgrade(map))
5064 entry->object.vm_object = vm_object_allocate_anon(atop(size),
5065 NULL, entry->cred, entry->cred != NULL ? size : 0);
5068 vm_map_lock_downgrade(map);
5072 * Return the object/offset from this entry. If the entry was
5073 * copy-on-write or empty, it has been fixed up.
5075 *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
5076 *object = entry->object.vm_object;
5079 return (KERN_SUCCESS);
5083 * vm_map_lookup_locked:
5085 * Lookup the faulting address. A version of vm_map_lookup that returns
5086 * KERN_FAILURE instead of blocking on map lock or memory allocation.
5089 vm_map_lookup_locked(vm_map_t *var_map, /* IN/OUT */
5091 vm_prot_t fault_typea,
5092 vm_map_entry_t *out_entry, /* OUT */
5093 vm_object_t *object, /* OUT */
5094 vm_pindex_t *pindex, /* OUT */
5095 vm_prot_t *out_prot, /* OUT */
5096 boolean_t *wired) /* OUT */
5098 vm_map_entry_t entry;
5099 vm_map_t map = *var_map;
5101 vm_prot_t fault_type = fault_typea;
5104 * Lookup the faulting address.
5106 if (!vm_map_lookup_entry(map, vaddr, out_entry))
5107 return (KERN_INVALID_ADDRESS);
5112 * Fail if the entry refers to a submap.
5114 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
5115 return (KERN_FAILURE);
5118 * Check whether this task is allowed to have this page.
5120 prot = entry->protection;
5121 fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
5122 if ((fault_type & prot) != fault_type)
5123 return (KERN_PROTECTION_FAILURE);
5126 * If this page is not pageable, we have to get it for all possible
5129 *wired = (entry->wired_count != 0);
5131 fault_type = entry->protection;
5133 if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
5135 * Fail if the entry was copy-on-write for a write fault.
5137 if (fault_type & VM_PROT_WRITE)
5138 return (KERN_FAILURE);
5140 * We're attempting to read a copy-on-write page --
5141 * don't allow writes.
5143 prot &= ~VM_PROT_WRITE;
5147 * Fail if an object should be created.
5149 if (entry->object.vm_object == NULL && !map->system_map)
5150 return (KERN_FAILURE);
5153 * Return the object/offset from this entry. If the entry was
5154 * copy-on-write or empty, it has been fixed up.
5156 *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
5157 *object = entry->object.vm_object;
5160 return (KERN_SUCCESS);
5164 * vm_map_lookup_done:
5166 * Releases locks acquired by a vm_map_lookup
5167 * (according to the handle returned by that lookup).
5170 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
5173 * Unlock the main-level map
5175 vm_map_unlock_read(map);
5179 vm_map_max_KBI(const struct vm_map *map)
5182 return (vm_map_max(map));
5186 vm_map_min_KBI(const struct vm_map *map)
5189 return (vm_map_min(map));
5193 vm_map_pmap_KBI(vm_map_t map)
5200 vm_map_range_valid_KBI(vm_map_t map, vm_offset_t start, vm_offset_t end)
5203 return (vm_map_range_valid(map, start, end));
5208 _vm_map_assert_consistent(vm_map_t map, int check)
5210 vm_map_entry_t entry, prev;
5211 vm_map_entry_t cur, header, lbound, ubound;
5212 vm_size_t max_left, max_right;
5217 if (enable_vmmap_check != check)
5220 header = prev = &map->header;
5221 VM_MAP_ENTRY_FOREACH(entry, map) {
5222 KASSERT(prev->end <= entry->start,
5223 ("map %p prev->end = %jx, start = %jx", map,
5224 (uintmax_t)prev->end, (uintmax_t)entry->start));
5225 KASSERT(entry->start < entry->end,
5226 ("map %p start = %jx, end = %jx", map,
5227 (uintmax_t)entry->start, (uintmax_t)entry->end));
5228 KASSERT(entry->left == header ||
5229 entry->left->start < entry->start,
5230 ("map %p left->start = %jx, start = %jx", map,
5231 (uintmax_t)entry->left->start, (uintmax_t)entry->start));
5232 KASSERT(entry->right == header ||
5233 entry->start < entry->right->start,
5234 ("map %p start = %jx, right->start = %jx", map,
5235 (uintmax_t)entry->start, (uintmax_t)entry->right->start));
5237 lbound = ubound = header;
5239 if (entry->start < cur->start) {
5242 KASSERT(cur != lbound,
5243 ("map %p cannot find %jx",
5244 map, (uintmax_t)entry->start));
5245 } else if (cur->end <= entry->start) {
5248 KASSERT(cur != ubound,
5249 ("map %p cannot find %jx",
5250 map, (uintmax_t)entry->start));
5252 KASSERT(cur == entry,
5253 ("map %p cannot find %jx",
5254 map, (uintmax_t)entry->start));
5258 max_left = vm_map_entry_max_free_left(entry, lbound);
5259 max_right = vm_map_entry_max_free_right(entry, ubound);
5260 KASSERT(entry->max_free == vm_size_max(max_left, max_right),
5261 ("map %p max = %jx, max_left = %jx, max_right = %jx", map,
5262 (uintmax_t)entry->max_free,
5263 (uintmax_t)max_left, (uintmax_t)max_right));
5266 KASSERT(prev->end <= entry->start,
5267 ("map %p prev->end = %jx, start = %jx", map,
5268 (uintmax_t)prev->end, (uintmax_t)entry->start));
5272 #include "opt_ddb.h"
5274 #include <sys/kernel.h>
5276 #include <ddb/ddb.h>
5279 vm_map_print(vm_map_t map)
5281 vm_map_entry_t entry, prev;
5283 db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
5285 (void *)map->pmap, map->nentries, map->timestamp);
5288 prev = &map->header;
5289 VM_MAP_ENTRY_FOREACH(entry, map) {
5290 db_iprintf("map entry %p: start=%p, end=%p, eflags=%#x, \n",
5291 (void *)entry, (void *)entry->start, (void *)entry->end,
5294 static const char * const inheritance_name[4] =
5295 {"share", "copy", "none", "donate_copy"};
5297 db_iprintf(" prot=%x/%x/%s",
5299 entry->max_protection,
5300 inheritance_name[(int)(unsigned char)
5301 entry->inheritance]);
5302 if (entry->wired_count != 0)
5303 db_printf(", wired");
5305 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
5306 db_printf(", share=%p, offset=0x%jx\n",
5307 (void *)entry->object.sub_map,
5308 (uintmax_t)entry->offset);
5309 if (prev == &map->header ||
5310 prev->object.sub_map !=
5311 entry->object.sub_map) {
5313 vm_map_print((vm_map_t)entry->object.sub_map);
5317 if (entry->cred != NULL)
5318 db_printf(", ruid %d", entry->cred->cr_ruid);
5319 db_printf(", object=%p, offset=0x%jx",
5320 (void *)entry->object.vm_object,
5321 (uintmax_t)entry->offset);
5322 if (entry->object.vm_object && entry->object.vm_object->cred)
5323 db_printf(", obj ruid %d charge %jx",
5324 entry->object.vm_object->cred->cr_ruid,
5325 (uintmax_t)entry->object.vm_object->charge);
5326 if (entry->eflags & MAP_ENTRY_COW)
5327 db_printf(", copy (%s)",
5328 (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
5331 if (prev == &map->header ||
5332 prev->object.vm_object !=
5333 entry->object.vm_object) {
5335 vm_object_print((db_expr_t)(intptr_t)
5336 entry->object.vm_object,
5346 DB_SHOW_COMMAND(map, map)
5350 db_printf("usage: show map <addr>\n");
5353 vm_map_print((vm_map_t)addr);
5356 DB_SHOW_COMMAND(procvm, procvm)
5361 p = db_lookup_proc(addr);
5366 db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
5367 (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
5368 (void *)vmspace_pmap(p->p_vmspace));
5370 vm_map_print((vm_map_t)&p->p_vmspace->vm_map);