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
35 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
36 * All rights reserved.
38 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
40 * Permission to use, copy, modify and distribute this software and
41 * its documentation is hereby granted, provided that both the copyright
42 * notice and this permission notice appear in all copies of the
43 * software, derivative works or modified versions, and any portions
44 * thereof, and that both notices appear in supporting documentation.
46 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
47 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
48 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
50 * Carnegie Mellon requests users of this software to return to
52 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
53 * School of Computer Science
54 * Carnegie Mellon University
55 * Pittsburgh PA 15213-3890
57 * any improvements or extensions that they make and grant Carnegie the
58 * rights to redistribute these changes.
62 * Virtual memory mapping module.
65 #include <sys/param.h>
66 #include <sys/systm.h>
68 #include <sys/kernel.h>
71 #include <sys/mutex.h>
73 #include <sys/vmmeter.h>
75 #include <sys/vnode.h>
76 #include <sys/racct.h>
77 #include <sys/resourcevar.h>
78 #include <sys/rwlock.h>
80 #include <sys/sysctl.h>
81 #include <sys/sysent.h>
85 #include <vm/vm_param.h>
87 #include <vm/vm_map.h>
88 #include <vm/vm_page.h>
89 #include <vm/vm_pageout.h>
90 #include <vm/vm_object.h>
91 #include <vm/vm_pager.h>
92 #include <vm/vm_kern.h>
93 #include <vm/vm_extern.h>
94 #include <vm/vnode_pager.h>
95 #include <vm/swap_pager.h>
99 * Virtual memory maps provide for the mapping, protection,
100 * and sharing of virtual memory objects. In addition,
101 * this module provides for an efficient virtual copy of
102 * memory from one map to another.
104 * Synchronization is required prior to most operations.
106 * Maps consist of an ordered doubly-linked list of simple
107 * entries; a self-adjusting binary search tree of these
108 * entries is used to speed up lookups.
110 * Since portions of maps are specified by start/end addresses,
111 * which may not align with existing map entries, all
112 * routines merely "clip" entries to these start/end values.
113 * [That is, an entry is split into two, bordering at a
114 * start or end value.] Note that these clippings may not
115 * always be necessary (as the two resulting entries are then
116 * not changed); however, the clipping is done for convenience.
118 * As mentioned above, virtual copy operations are performed
119 * by copying VM object references from one map to
120 * another, and then marking both regions as copy-on-write.
123 static struct mtx map_sleep_mtx;
124 static uma_zone_t mapentzone;
125 static uma_zone_t kmapentzone;
126 static uma_zone_t vmspace_zone;
127 static int vmspace_zinit(void *mem, int size, int flags);
128 static void _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min,
130 static void vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map);
131 static void vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry);
132 static void vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry);
133 static int vm_map_growstack(vm_map_t map, vm_offset_t addr,
134 vm_map_entry_t gap_entry);
135 static void vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
136 vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags);
138 static void vmspace_zdtor(void *mem, int size, void *arg);
140 static int vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos,
141 vm_size_t max_ssize, vm_size_t growsize, vm_prot_t prot, vm_prot_t max,
143 static void vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
144 vm_offset_t failed_addr);
146 #define CONTAINS_BITS(set, bits) ((~(set) & (bits)) == 0)
148 #define ENTRY_CHARGED(e) ((e)->cred != NULL || \
149 ((e)->object.vm_object != NULL && (e)->object.vm_object->cred != NULL && \
150 !((e)->eflags & MAP_ENTRY_NEEDS_COPY)))
153 * PROC_VMSPACE_{UN,}LOCK() can be a noop as long as vmspaces are type
156 #define PROC_VMSPACE_LOCK(p) do { } while (0)
157 #define PROC_VMSPACE_UNLOCK(p) do { } while (0)
160 * VM_MAP_RANGE_CHECK: [ internal use only ]
162 * Asserts that the starting and ending region
163 * addresses fall within the valid range of the map.
165 #define VM_MAP_RANGE_CHECK(map, start, end) \
167 if (start < vm_map_min(map)) \
168 start = vm_map_min(map); \
169 if (end > vm_map_max(map)) \
170 end = vm_map_max(map); \
175 #ifndef UMA_MD_SMALL_ALLOC
178 * Allocate a new slab for kernel map entries. The kernel map may be locked or
179 * unlocked, depending on whether the request is coming from the kernel map or a
180 * submap. This function allocates a virtual address range directly from the
181 * kernel map instead of the kmem_* layer to avoid recursion on the kernel map
182 * lock and also to avoid triggering allocator recursion in the vmem boundary
186 kmapent_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
192 *pflag = UMA_SLAB_PRIV;
194 if (!(locked = vm_map_locked(kernel_map)))
195 vm_map_lock(kernel_map);
196 addr = vm_map_findspace(kernel_map, vm_map_min(kernel_map), bytes);
197 if (addr + bytes < addr || addr + bytes > vm_map_max(kernel_map))
198 panic("%s: kernel map is exhausted", __func__);
199 error = vm_map_insert(kernel_map, NULL, 0, addr, addr + bytes,
200 VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
201 if (error != KERN_SUCCESS)
202 panic("%s: vm_map_insert() failed: %d", __func__, error);
204 vm_map_unlock(kernel_map);
205 error = kmem_back_domain(domain, kernel_object, addr, bytes, M_NOWAIT |
206 M_USE_RESERVE | (wait & M_ZERO));
207 if (error == KERN_SUCCESS) {
208 return ((void *)addr);
211 vm_map_lock(kernel_map);
212 vm_map_delete(kernel_map, addr, bytes);
214 vm_map_unlock(kernel_map);
220 kmapent_free(void *item, vm_size_t size, uint8_t pflag)
223 int error __diagused;
225 if ((pflag & UMA_SLAB_PRIV) == 0)
229 addr = (vm_offset_t)item;
230 kmem_unback(kernel_object, addr, size);
231 error = vm_map_remove(kernel_map, addr, addr + size);
232 KASSERT(error == KERN_SUCCESS,
233 ("%s: vm_map_remove failed: %d", __func__, error));
237 * The worst-case upper bound on the number of kernel map entries that may be
238 * created before the zone must be replenished in _vm_map_unlock().
240 #define KMAPENT_RESERVE 1
242 #endif /* !UMD_MD_SMALL_ALLOC */
247 * Initialize the vm_map module. Must be called before any other vm_map
250 * User map and entry structures are allocated from the general purpose
251 * memory pool. Kernel maps are statically defined. Kernel map entries
252 * require special handling to avoid recursion; see the comments above
253 * kmapent_alloc() and in vm_map_entry_create().
258 mtx_init(&map_sleep_mtx, "vm map sleep mutex", NULL, MTX_DEF);
261 * Disable the use of per-CPU buckets: map entry allocation is
262 * serialized by the kernel map lock.
264 kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry),
265 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
266 UMA_ZONE_VM | UMA_ZONE_NOBUCKET);
267 #ifndef UMA_MD_SMALL_ALLOC
268 /* Reserve an extra map entry for use when replenishing the reserve. */
269 uma_zone_reserve(kmapentzone, KMAPENT_RESERVE + 1);
270 uma_prealloc(kmapentzone, KMAPENT_RESERVE + 1);
271 uma_zone_set_allocf(kmapentzone, kmapent_alloc);
272 uma_zone_set_freef(kmapentzone, kmapent_free);
275 mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry),
276 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
277 vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
283 vmspace_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
287 vmspace_zinit(void *mem, int size, int flags)
292 vm = (struct vmspace *)mem;
295 memset(map, 0, sizeof(*map));
296 mtx_init(&map->system_mtx, "vm map (system)", NULL,
297 MTX_DEF | MTX_DUPOK);
298 sx_init(&map->lock, "vm map (user)");
299 PMAP_LOCK_INIT(vmspace_pmap(vm));
305 vmspace_zdtor(void *mem, int size, void *arg)
309 vm = (struct vmspace *)mem;
310 KASSERT(vm->vm_map.nentries == 0,
311 ("vmspace %p nentries == %d on free", vm, vm->vm_map.nentries));
312 KASSERT(vm->vm_map.size == 0,
313 ("vmspace %p size == %ju on free", vm, (uintmax_t)vm->vm_map.size));
315 #endif /* INVARIANTS */
318 * Allocate a vmspace structure, including a vm_map and pmap,
319 * and initialize those structures. The refcnt is set to 1.
322 vmspace_alloc(vm_offset_t min, vm_offset_t max, pmap_pinit_t pinit)
326 vm = uma_zalloc(vmspace_zone, M_WAITOK);
327 KASSERT(vm->vm_map.pmap == NULL, ("vm_map.pmap must be NULL"));
328 if (!pinit(vmspace_pmap(vm))) {
329 uma_zfree(vmspace_zone, vm);
332 CTR1(KTR_VM, "vmspace_alloc: %p", vm);
333 _vm_map_init(&vm->vm_map, vmspace_pmap(vm), min, max);
334 refcount_init(&vm->vm_refcnt, 1);
348 vmspace_container_reset(struct proc *p)
352 racct_set(p, RACCT_DATA, 0);
353 racct_set(p, RACCT_STACK, 0);
354 racct_set(p, RACCT_RSS, 0);
355 racct_set(p, RACCT_MEMLOCK, 0);
356 racct_set(p, RACCT_VMEM, 0);
362 vmspace_dofree(struct vmspace *vm)
365 CTR1(KTR_VM, "vmspace_free: %p", vm);
368 * Make sure any SysV shm is freed, it might not have been in
374 * Lock the map, to wait out all other references to it.
375 * Delete all of the mappings and pages they hold, then call
376 * the pmap module to reclaim anything left.
378 (void)vm_map_remove(&vm->vm_map, vm_map_min(&vm->vm_map),
379 vm_map_max(&vm->vm_map));
381 pmap_release(vmspace_pmap(vm));
382 vm->vm_map.pmap = NULL;
383 uma_zfree(vmspace_zone, vm);
387 vmspace_free(struct vmspace *vm)
390 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
391 "vmspace_free() called");
393 if (refcount_release(&vm->vm_refcnt))
398 vmspace_exitfree(struct proc *p)
402 PROC_VMSPACE_LOCK(p);
405 PROC_VMSPACE_UNLOCK(p);
406 KASSERT(vm == &vmspace0, ("vmspace_exitfree: wrong vmspace"));
411 vmspace_exit(struct thread *td)
421 * Prepare to release the vmspace reference. The thread that releases
422 * the last reference is responsible for tearing down the vmspace.
423 * However, threads not releasing the final reference must switch to the
424 * kernel's vmspace0 before the decrement so that the subsequent pmap
425 * deactivation does not modify a freed vmspace.
427 refcount_acquire(&vmspace0.vm_refcnt);
428 if (!(released = refcount_release_if_last(&vm->vm_refcnt))) {
429 if (p->p_vmspace != &vmspace0) {
430 PROC_VMSPACE_LOCK(p);
431 p->p_vmspace = &vmspace0;
432 PROC_VMSPACE_UNLOCK(p);
435 released = refcount_release(&vm->vm_refcnt);
439 * pmap_remove_pages() expects the pmap to be active, so switch
440 * back first if necessary.
442 if (p->p_vmspace != vm) {
443 PROC_VMSPACE_LOCK(p);
445 PROC_VMSPACE_UNLOCK(p);
448 pmap_remove_pages(vmspace_pmap(vm));
449 PROC_VMSPACE_LOCK(p);
450 p->p_vmspace = &vmspace0;
451 PROC_VMSPACE_UNLOCK(p);
457 vmspace_container_reset(p);
461 /* Acquire reference to vmspace owned by another process. */
464 vmspace_acquire_ref(struct proc *p)
468 PROC_VMSPACE_LOCK(p);
470 if (vm == NULL || !refcount_acquire_if_not_zero(&vm->vm_refcnt)) {
471 PROC_VMSPACE_UNLOCK(p);
474 if (vm != p->p_vmspace) {
475 PROC_VMSPACE_UNLOCK(p);
479 PROC_VMSPACE_UNLOCK(p);
484 * Switch between vmspaces in an AIO kernel process.
486 * The new vmspace is either the vmspace of a user process obtained
487 * from an active AIO request or the initial vmspace of the AIO kernel
488 * process (when it is idling). Because user processes will block to
489 * drain any active AIO requests before proceeding in exit() or
490 * execve(), the reference count for vmspaces from AIO requests can
491 * never be 0. Similarly, AIO kernel processes hold an extra
492 * reference on their initial vmspace for the life of the process. As
493 * a result, the 'newvm' vmspace always has a non-zero reference
494 * count. This permits an additional reference on 'newvm' to be
495 * acquired via a simple atomic increment rather than the loop in
496 * vmspace_acquire_ref() above.
499 vmspace_switch_aio(struct vmspace *newvm)
501 struct vmspace *oldvm;
503 /* XXX: Need some way to assert that this is an aio daemon. */
505 KASSERT(refcount_load(&newvm->vm_refcnt) > 0,
506 ("vmspace_switch_aio: newvm unreferenced"));
508 oldvm = curproc->p_vmspace;
513 * Point to the new address space and refer to it.
515 curproc->p_vmspace = newvm;
516 refcount_acquire(&newvm->vm_refcnt);
518 /* Activate the new mapping. */
519 pmap_activate(curthread);
525 _vm_map_lock(vm_map_t map, const char *file, int line)
529 mtx_lock_flags_(&map->system_mtx, 0, file, line);
531 sx_xlock_(&map->lock, file, line);
536 vm_map_entry_set_vnode_text(vm_map_entry_t entry, bool add)
542 if ((entry->eflags & MAP_ENTRY_VN_EXEC) == 0)
544 KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
545 ("Submap with execs"));
546 object = entry->object.vm_object;
547 KASSERT(object != NULL, ("No object for text, entry %p", entry));
548 if ((object->flags & OBJ_ANON) != 0)
549 object = object->handle;
551 KASSERT(object->backing_object == NULL,
552 ("non-anon object %p shadows", object));
553 KASSERT(object != NULL, ("No content object for text, entry %p obj %p",
554 entry, entry->object.vm_object));
557 * Mostly, we do not lock the backing object. It is
558 * referenced by the entry we are processing, so it cannot go
561 vm_pager_getvp(object, &vp, &vp_held);
564 VOP_SET_TEXT_CHECKED(vp);
566 vn_lock(vp, LK_SHARED | LK_RETRY);
567 VOP_UNSET_TEXT_CHECKED(vp);
576 * Use a different name for this vm_map_entry field when it's use
577 * is not consistent with its use as part of an ordered search tree.
579 #define defer_next right
582 vm_map_process_deferred(void)
585 vm_map_entry_t entry, next;
589 entry = td->td_map_def_user;
590 td->td_map_def_user = NULL;
591 while (entry != NULL) {
592 next = entry->defer_next;
593 MPASS((entry->eflags & (MAP_ENTRY_WRITECNT |
594 MAP_ENTRY_VN_EXEC)) != (MAP_ENTRY_WRITECNT |
596 if ((entry->eflags & MAP_ENTRY_WRITECNT) != 0) {
598 * Decrement the object's writemappings and
599 * possibly the vnode's v_writecount.
601 KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
602 ("Submap with writecount"));
603 object = entry->object.vm_object;
604 KASSERT(object != NULL, ("No object for writecount"));
605 vm_pager_release_writecount(object, entry->start,
608 vm_map_entry_set_vnode_text(entry, false);
609 vm_map_entry_deallocate(entry, FALSE);
616 _vm_map_assert_locked(vm_map_t map, const char *file, int line)
620 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
622 sx_assert_(&map->lock, SA_XLOCKED, file, line);
625 #define VM_MAP_ASSERT_LOCKED(map) \
626 _vm_map_assert_locked(map, LOCK_FILE, LOCK_LINE)
628 enum { VMMAP_CHECK_NONE, VMMAP_CHECK_UNLOCK, VMMAP_CHECK_ALL };
630 static int enable_vmmap_check = VMMAP_CHECK_UNLOCK;
632 static int enable_vmmap_check = VMMAP_CHECK_NONE;
634 SYSCTL_INT(_debug, OID_AUTO, vmmap_check, CTLFLAG_RWTUN,
635 &enable_vmmap_check, 0, "Enable vm map consistency checking");
637 static void _vm_map_assert_consistent(vm_map_t map, int check);
639 #define VM_MAP_ASSERT_CONSISTENT(map) \
640 _vm_map_assert_consistent(map, VMMAP_CHECK_ALL)
642 #define VM_MAP_UNLOCK_CONSISTENT(map) do { \
643 if (map->nupdates > map->nentries) { \
644 _vm_map_assert_consistent(map, VMMAP_CHECK_UNLOCK); \
649 #define VM_MAP_UNLOCK_CONSISTENT(map)
652 #define VM_MAP_ASSERT_LOCKED(map)
653 #define VM_MAP_ASSERT_CONSISTENT(map)
654 #define VM_MAP_UNLOCK_CONSISTENT(map)
655 #endif /* INVARIANTS */
658 _vm_map_unlock(vm_map_t map, const char *file, int line)
661 VM_MAP_UNLOCK_CONSISTENT(map);
662 if (map->system_map) {
663 #ifndef UMA_MD_SMALL_ALLOC
664 if (map == kernel_map && (map->flags & MAP_REPLENISH) != 0) {
665 uma_prealloc(kmapentzone, 1);
666 map->flags &= ~MAP_REPLENISH;
669 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
671 sx_xunlock_(&map->lock, file, line);
672 vm_map_process_deferred();
677 _vm_map_lock_read(vm_map_t map, const char *file, int line)
681 mtx_lock_flags_(&map->system_mtx, 0, file, line);
683 sx_slock_(&map->lock, file, line);
687 _vm_map_unlock_read(vm_map_t map, const char *file, int line)
690 if (map->system_map) {
691 KASSERT((map->flags & MAP_REPLENISH) == 0,
692 ("%s: MAP_REPLENISH leaked", __func__));
693 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
695 sx_sunlock_(&map->lock, file, line);
696 vm_map_process_deferred();
701 _vm_map_trylock(vm_map_t map, const char *file, int line)
705 error = map->system_map ?
706 !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
707 !sx_try_xlock_(&map->lock, file, line);
714 _vm_map_trylock_read(vm_map_t map, const char *file, int line)
718 error = map->system_map ?
719 !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
720 !sx_try_slock_(&map->lock, file, line);
725 * _vm_map_lock_upgrade: [ internal use only ]
727 * Tries to upgrade a read (shared) lock on the specified map to a write
728 * (exclusive) lock. Returns the value "0" if the upgrade succeeds and a
729 * non-zero value if the upgrade fails. If the upgrade fails, the map is
730 * returned without a read or write lock held.
732 * Requires that the map be read locked.
735 _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
737 unsigned int last_timestamp;
739 if (map->system_map) {
740 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
742 if (!sx_try_upgrade_(&map->lock, file, line)) {
743 last_timestamp = map->timestamp;
744 sx_sunlock_(&map->lock, file, line);
745 vm_map_process_deferred();
747 * If the map's timestamp does not change while the
748 * map is unlocked, then the upgrade succeeds.
750 sx_xlock_(&map->lock, file, line);
751 if (last_timestamp != map->timestamp) {
752 sx_xunlock_(&map->lock, file, line);
762 _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
765 if (map->system_map) {
766 KASSERT((map->flags & MAP_REPLENISH) == 0,
767 ("%s: MAP_REPLENISH leaked", __func__));
768 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
770 VM_MAP_UNLOCK_CONSISTENT(map);
771 sx_downgrade_(&map->lock, file, line);
778 * Returns a non-zero value if the caller holds a write (exclusive) lock
779 * on the specified map and the value "0" otherwise.
782 vm_map_locked(vm_map_t map)
786 return (mtx_owned(&map->system_mtx));
788 return (sx_xlocked(&map->lock));
792 * _vm_map_unlock_and_wait:
794 * Atomically releases the lock on the specified map and puts the calling
795 * thread to sleep. The calling thread will remain asleep until either
796 * vm_map_wakeup() is performed on the map or the specified timeout is
799 * WARNING! This function does not perform deferred deallocations of
800 * objects and map entries. Therefore, the calling thread is expected to
801 * reacquire the map lock after reawakening and later perform an ordinary
802 * unlock operation, such as vm_map_unlock(), before completing its
803 * operation on the map.
806 _vm_map_unlock_and_wait(vm_map_t map, int timo, const char *file, int line)
809 VM_MAP_UNLOCK_CONSISTENT(map);
810 mtx_lock(&map_sleep_mtx);
811 if (map->system_map) {
812 KASSERT((map->flags & MAP_REPLENISH) == 0,
813 ("%s: MAP_REPLENISH leaked", __func__));
814 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
816 sx_xunlock_(&map->lock, file, line);
818 return (msleep(&map->root, &map_sleep_mtx, PDROP | PVM, "vmmaps",
825 * Awaken any threads that have slept on the map using
826 * vm_map_unlock_and_wait().
829 vm_map_wakeup(vm_map_t map)
833 * Acquire and release map_sleep_mtx to prevent a wakeup()
834 * from being performed (and lost) between the map unlock
835 * and the msleep() in _vm_map_unlock_and_wait().
837 mtx_lock(&map_sleep_mtx);
838 mtx_unlock(&map_sleep_mtx);
843 vm_map_busy(vm_map_t map)
846 VM_MAP_ASSERT_LOCKED(map);
851 vm_map_unbusy(vm_map_t map)
854 VM_MAP_ASSERT_LOCKED(map);
855 KASSERT(map->busy, ("vm_map_unbusy: not busy"));
856 if (--map->busy == 0 && (map->flags & MAP_BUSY_WAKEUP)) {
857 vm_map_modflags(map, 0, MAP_BUSY_WAKEUP);
863 vm_map_wait_busy(vm_map_t map)
866 VM_MAP_ASSERT_LOCKED(map);
868 vm_map_modflags(map, MAP_BUSY_WAKEUP, 0);
870 msleep(&map->busy, &map->system_mtx, 0, "mbusy", 0);
872 sx_sleep(&map->busy, &map->lock, 0, "mbusy", 0);
878 vmspace_resident_count(struct vmspace *vmspace)
880 return pmap_resident_count(vmspace_pmap(vmspace));
884 * Initialize an existing vm_map structure
885 * such as that in the vmspace structure.
888 _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
891 map->header.eflags = MAP_ENTRY_HEADER;
892 map->needs_wakeup = FALSE;
895 map->header.end = min;
896 map->header.start = max;
898 map->header.left = map->header.right = &map->header;
909 vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
912 _vm_map_init(map, pmap, min, max);
913 mtx_init(&map->system_mtx, "vm map (system)", NULL,
914 MTX_DEF | MTX_DUPOK);
915 sx_init(&map->lock, "vm map (user)");
919 * vm_map_entry_dispose: [ internal use only ]
921 * Inverse of vm_map_entry_create.
924 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
926 uma_zfree(map->system_map ? kmapentzone : mapentzone, entry);
930 * vm_map_entry_create: [ internal use only ]
932 * Allocates a VM map entry for insertion.
933 * No entry fields are filled in.
935 static vm_map_entry_t
936 vm_map_entry_create(vm_map_t map)
938 vm_map_entry_t new_entry;
940 #ifndef UMA_MD_SMALL_ALLOC
941 if (map == kernel_map) {
942 VM_MAP_ASSERT_LOCKED(map);
945 * A new slab of kernel map entries cannot be allocated at this
946 * point because the kernel map has not yet been updated to
947 * reflect the caller's request. Therefore, we allocate a new
948 * map entry, dipping into the reserve if necessary, and set a
949 * flag indicating that the reserve must be replenished before
950 * the map is unlocked.
952 new_entry = uma_zalloc(kmapentzone, M_NOWAIT | M_NOVM);
953 if (new_entry == NULL) {
954 new_entry = uma_zalloc(kmapentzone,
955 M_NOWAIT | M_NOVM | M_USE_RESERVE);
956 kernel_map->flags |= MAP_REPLENISH;
960 if (map->system_map) {
961 new_entry = uma_zalloc(kmapentzone, M_NOWAIT);
963 new_entry = uma_zalloc(mapentzone, M_WAITOK);
965 KASSERT(new_entry != NULL,
966 ("vm_map_entry_create: kernel resources exhausted"));
971 * vm_map_entry_set_behavior:
973 * Set the expected access behavior, either normal, random, or
977 vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
979 entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
980 (behavior & MAP_ENTRY_BEHAV_MASK);
984 * vm_map_entry_max_free_{left,right}:
986 * Compute the size of the largest free gap between two entries,
987 * one the root of a tree and the other the ancestor of that root
988 * that is the least or greatest ancestor found on the search path.
990 static inline vm_size_t
991 vm_map_entry_max_free_left(vm_map_entry_t root, vm_map_entry_t left_ancestor)
994 return (root->left != left_ancestor ?
995 root->left->max_free : root->start - left_ancestor->end);
998 static inline vm_size_t
999 vm_map_entry_max_free_right(vm_map_entry_t root, vm_map_entry_t right_ancestor)
1002 return (root->right != right_ancestor ?
1003 root->right->max_free : right_ancestor->start - root->end);
1007 * vm_map_entry_{pred,succ}:
1009 * Find the {predecessor, successor} of the entry by taking one step
1010 * in the appropriate direction and backtracking as much as necessary.
1011 * vm_map_entry_succ is defined in vm_map.h.
1013 static inline vm_map_entry_t
1014 vm_map_entry_pred(vm_map_entry_t entry)
1016 vm_map_entry_t prior;
1018 prior = entry->left;
1019 if (prior->right->start < entry->start) {
1021 prior = prior->right;
1022 while (prior->right != entry);
1027 static inline vm_size_t
1028 vm_size_max(vm_size_t a, vm_size_t b)
1031 return (a > b ? a : b);
1034 #define SPLAY_LEFT_STEP(root, y, llist, rlist, test) do { \
1036 vm_size_t max_free; \
1039 * Infer root->right->max_free == root->max_free when \
1040 * y->max_free < root->max_free || root->max_free == 0. \
1041 * Otherwise, look right to find it. \
1044 max_free = root->max_free; \
1045 KASSERT(max_free == vm_size_max( \
1046 vm_map_entry_max_free_left(root, llist), \
1047 vm_map_entry_max_free_right(root, rlist)), \
1048 ("%s: max_free invariant fails", __func__)); \
1049 if (max_free - 1 < vm_map_entry_max_free_left(root, llist)) \
1050 max_free = vm_map_entry_max_free_right(root, rlist); \
1051 if (y != llist && (test)) { \
1052 /* Rotate right and make y root. */ \
1057 if (max_free < y->max_free) \
1058 root->max_free = max_free = \
1059 vm_size_max(max_free, z->max_free); \
1060 } else if (max_free < y->max_free) \
1061 root->max_free = max_free = \
1062 vm_size_max(max_free, root->start - y->end);\
1066 /* Copy right->max_free. Put root on rlist. */ \
1067 root->max_free = max_free; \
1068 KASSERT(max_free == vm_map_entry_max_free_right(root, rlist), \
1069 ("%s: max_free not copied from right", __func__)); \
1070 root->left = rlist; \
1072 root = y != llist ? y : NULL; \
1075 #define SPLAY_RIGHT_STEP(root, y, llist, rlist, test) do { \
1077 vm_size_t max_free; \
1080 * Infer root->left->max_free == root->max_free when \
1081 * y->max_free < root->max_free || root->max_free == 0. \
1082 * Otherwise, look left to find it. \
1085 max_free = root->max_free; \
1086 KASSERT(max_free == vm_size_max( \
1087 vm_map_entry_max_free_left(root, llist), \
1088 vm_map_entry_max_free_right(root, rlist)), \
1089 ("%s: max_free invariant fails", __func__)); \
1090 if (max_free - 1 < vm_map_entry_max_free_right(root, rlist)) \
1091 max_free = vm_map_entry_max_free_left(root, llist); \
1092 if (y != rlist && (test)) { \
1093 /* Rotate left and make y root. */ \
1098 if (max_free < y->max_free) \
1099 root->max_free = max_free = \
1100 vm_size_max(max_free, z->max_free); \
1101 } else if (max_free < y->max_free) \
1102 root->max_free = max_free = \
1103 vm_size_max(max_free, y->start - root->end);\
1107 /* Copy left->max_free. Put root on llist. */ \
1108 root->max_free = max_free; \
1109 KASSERT(max_free == vm_map_entry_max_free_left(root, llist), \
1110 ("%s: max_free not copied from left", __func__)); \
1111 root->right = llist; \
1113 root = y != rlist ? y : NULL; \
1117 * Walk down the tree until we find addr or a gap where addr would go, breaking
1118 * off left and right subtrees of nodes less than, or greater than addr. Treat
1119 * subtrees with root->max_free < length as empty trees. llist and rlist are
1120 * the two sides in reverse order (bottom-up), with llist linked by the right
1121 * pointer and rlist linked by the left pointer in the vm_map_entry, and both
1122 * lists terminated by &map->header. This function, and the subsequent call to
1123 * vm_map_splay_merge_{left,right,pred,succ}, rely on the start and end address
1124 * values in &map->header.
1126 static __always_inline vm_map_entry_t
1127 vm_map_splay_split(vm_map_t map, vm_offset_t addr, vm_size_t length,
1128 vm_map_entry_t *llist, vm_map_entry_t *rlist)
1130 vm_map_entry_t left, right, root, y;
1132 left = right = &map->header;
1134 while (root != NULL && root->max_free >= length) {
1135 KASSERT(left->end <= root->start &&
1136 root->end <= right->start,
1137 ("%s: root not within tree bounds", __func__));
1138 if (addr < root->start) {
1139 SPLAY_LEFT_STEP(root, y, left, right,
1140 y->max_free >= length && addr < y->start);
1141 } else if (addr >= root->end) {
1142 SPLAY_RIGHT_STEP(root, y, left, right,
1143 y->max_free >= length && addr >= y->end);
1152 static __always_inline void
1153 vm_map_splay_findnext(vm_map_entry_t root, vm_map_entry_t *rlist)
1155 vm_map_entry_t hi, right, y;
1158 hi = root->right == right ? NULL : root->right;
1162 SPLAY_LEFT_STEP(hi, y, root, right, true);
1167 static __always_inline void
1168 vm_map_splay_findprev(vm_map_entry_t root, vm_map_entry_t *llist)
1170 vm_map_entry_t left, lo, y;
1173 lo = root->left == left ? NULL : root->left;
1177 SPLAY_RIGHT_STEP(lo, y, left, root, true);
1183 vm_map_entry_swap(vm_map_entry_t *a, vm_map_entry_t *b)
1193 * Walk back up the two spines, flip the pointers and set max_free. The
1194 * subtrees of the root go at the bottom of llist and rlist.
1197 vm_map_splay_merge_left_walk(vm_map_entry_t header, vm_map_entry_t root,
1198 vm_map_entry_t tail, vm_size_t max_free, vm_map_entry_t llist)
1202 * The max_free values of the children of llist are in
1203 * llist->max_free and max_free. Update with the
1206 llist->max_free = max_free =
1207 vm_size_max(llist->max_free, max_free);
1208 vm_map_entry_swap(&llist->right, &tail);
1209 vm_map_entry_swap(&tail, &llist);
1210 } while (llist != header);
1216 * When llist is known to be the predecessor of root.
1218 static inline vm_size_t
1219 vm_map_splay_merge_pred(vm_map_entry_t header, vm_map_entry_t root,
1220 vm_map_entry_t llist)
1224 max_free = root->start - llist->end;
1225 if (llist != header) {
1226 max_free = vm_map_splay_merge_left_walk(header, root,
1227 root, max_free, llist);
1229 root->left = header;
1230 header->right = root;
1236 * When llist may or may not be the predecessor of root.
1238 static inline vm_size_t
1239 vm_map_splay_merge_left(vm_map_entry_t header, vm_map_entry_t root,
1240 vm_map_entry_t llist)
1244 max_free = vm_map_entry_max_free_left(root, llist);
1245 if (llist != header) {
1246 max_free = vm_map_splay_merge_left_walk(header, root,
1247 root->left == llist ? root : root->left,
1254 vm_map_splay_merge_right_walk(vm_map_entry_t header, vm_map_entry_t root,
1255 vm_map_entry_t tail, vm_size_t max_free, vm_map_entry_t rlist)
1259 * The max_free values of the children of rlist are in
1260 * rlist->max_free and max_free. Update with the
1263 rlist->max_free = max_free =
1264 vm_size_max(rlist->max_free, max_free);
1265 vm_map_entry_swap(&rlist->left, &tail);
1266 vm_map_entry_swap(&tail, &rlist);
1267 } while (rlist != header);
1273 * When rlist is known to be the succecessor of root.
1275 static inline vm_size_t
1276 vm_map_splay_merge_succ(vm_map_entry_t header, vm_map_entry_t root,
1277 vm_map_entry_t rlist)
1281 max_free = rlist->start - root->end;
1282 if (rlist != header) {
1283 max_free = vm_map_splay_merge_right_walk(header, root,
1284 root, max_free, rlist);
1286 root->right = header;
1287 header->left = root;
1293 * When rlist may or may not be the succecessor of root.
1295 static inline vm_size_t
1296 vm_map_splay_merge_right(vm_map_entry_t header, vm_map_entry_t root,
1297 vm_map_entry_t rlist)
1301 max_free = vm_map_entry_max_free_right(root, rlist);
1302 if (rlist != header) {
1303 max_free = vm_map_splay_merge_right_walk(header, root,
1304 root->right == rlist ? root : root->right,
1313 * The Sleator and Tarjan top-down splay algorithm with the
1314 * following variation. Max_free must be computed bottom-up, so
1315 * on the downward pass, maintain the left and right spines in
1316 * reverse order. Then, make a second pass up each side to fix
1317 * the pointers and compute max_free. The time bound is O(log n)
1320 * The tree is threaded, which means that there are no null pointers.
1321 * When a node has no left child, its left pointer points to its
1322 * predecessor, which the last ancestor on the search path from the root
1323 * where the search branched right. Likewise, when a node has no right
1324 * child, its right pointer points to its successor. The map header node
1325 * is the predecessor of the first map entry, and the successor of the
1328 * The new root is the vm_map_entry containing "addr", or else an
1329 * adjacent entry (lower if possible) if addr is not in the tree.
1331 * The map must be locked, and leaves it so.
1333 * Returns: the new root.
1335 static vm_map_entry_t
1336 vm_map_splay(vm_map_t map, vm_offset_t addr)
1338 vm_map_entry_t header, llist, rlist, root;
1339 vm_size_t max_free_left, max_free_right;
1341 header = &map->header;
1342 root = vm_map_splay_split(map, addr, 0, &llist, &rlist);
1344 max_free_left = vm_map_splay_merge_left(header, root, llist);
1345 max_free_right = vm_map_splay_merge_right(header, root, rlist);
1346 } else if (llist != header) {
1348 * Recover the greatest node in the left
1349 * subtree and make it the root.
1352 llist = root->right;
1353 max_free_left = vm_map_splay_merge_left(header, root, llist);
1354 max_free_right = vm_map_splay_merge_succ(header, root, rlist);
1355 } else if (rlist != header) {
1357 * Recover the least node in the right
1358 * subtree and make it the root.
1362 max_free_left = vm_map_splay_merge_pred(header, root, llist);
1363 max_free_right = vm_map_splay_merge_right(header, root, rlist);
1365 /* There is no root. */
1368 root->max_free = vm_size_max(max_free_left, max_free_right);
1370 VM_MAP_ASSERT_CONSISTENT(map);
1375 * vm_map_entry_{un,}link:
1377 * Insert/remove entries from maps. On linking, if new entry clips
1378 * existing entry, trim existing entry to avoid overlap, and manage
1379 * offsets. On unlinking, merge disappearing entry with neighbor, if
1380 * called for, and manage offsets. Callers should not modify fields in
1381 * entries already mapped.
1384 vm_map_entry_link(vm_map_t map, vm_map_entry_t entry)
1386 vm_map_entry_t header, llist, rlist, root;
1387 vm_size_t max_free_left, max_free_right;
1390 "vm_map_entry_link: map %p, nentries %d, entry %p", map,
1391 map->nentries, entry);
1392 VM_MAP_ASSERT_LOCKED(map);
1394 header = &map->header;
1395 root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1398 * The new entry does not overlap any existing entry in the
1399 * map, so it becomes the new root of the map tree.
1401 max_free_left = vm_map_splay_merge_pred(header, entry, llist);
1402 max_free_right = vm_map_splay_merge_succ(header, entry, rlist);
1403 } else if (entry->start == root->start) {
1405 * The new entry is a clone of root, with only the end field
1406 * changed. The root entry will be shrunk to abut the new
1407 * entry, and will be the right child of the new root entry in
1410 KASSERT(entry->end < root->end,
1411 ("%s: clip_start not within entry", __func__));
1412 vm_map_splay_findprev(root, &llist);
1413 if ((root->eflags & (MAP_ENTRY_STACK_GAP_DN |
1414 MAP_ENTRY_STACK_GAP_UP)) == 0)
1415 root->offset += entry->end - root->start;
1416 root->start = entry->end;
1417 max_free_left = vm_map_splay_merge_pred(header, entry, llist);
1418 max_free_right = root->max_free = vm_size_max(
1419 vm_map_splay_merge_pred(entry, root, entry),
1420 vm_map_splay_merge_right(header, root, rlist));
1423 * The new entry is a clone of root, with only the start field
1424 * changed. The root entry will be shrunk to abut the new
1425 * entry, and will be the left child of the new root entry in
1428 KASSERT(entry->end == root->end,
1429 ("%s: clip_start not within entry", __func__));
1430 vm_map_splay_findnext(root, &rlist);
1431 if ((entry->eflags & (MAP_ENTRY_STACK_GAP_DN |
1432 MAP_ENTRY_STACK_GAP_UP)) == 0)
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 MPASS((rlist->eflags & (MAP_ENTRY_STACK_GAP_DN |
1468 MAP_ENTRY_STACK_GAP_UP)) == 0);
1469 rlist->offset = root->offset;
1471 if (llist != header) {
1473 llist = root->right;
1474 max_free_left = vm_map_splay_merge_left(header, root, llist);
1475 max_free_right = vm_map_splay_merge_succ(header, root, rlist);
1476 } else if (rlist != header) {
1479 max_free_left = vm_map_splay_merge_pred(header, root, llist);
1480 max_free_right = vm_map_splay_merge_right(header, root, rlist);
1482 header->left = header->right = header;
1486 root->max_free = vm_size_max(max_free_left, max_free_right);
1488 VM_MAP_ASSERT_CONSISTENT(map);
1490 CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
1491 map->nentries, entry);
1495 * vm_map_entry_resize:
1497 * Resize a vm_map_entry, recompute the amount of free space that
1498 * follows it and propagate that value up the tree.
1500 * The map must be locked, and leaves it so.
1503 vm_map_entry_resize(vm_map_t map, vm_map_entry_t entry, vm_size_t grow_amount)
1505 vm_map_entry_t header, llist, rlist, root;
1507 VM_MAP_ASSERT_LOCKED(map);
1508 header = &map->header;
1509 root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1510 KASSERT(root != NULL, ("%s: resize object not mapped", __func__));
1511 vm_map_splay_findnext(root, &rlist);
1512 entry->end += grow_amount;
1513 root->max_free = vm_size_max(
1514 vm_map_splay_merge_left(header, root, llist),
1515 vm_map_splay_merge_succ(header, root, rlist));
1517 VM_MAP_ASSERT_CONSISTENT(map);
1518 CTR4(KTR_VM, "%s: map %p, nentries %d, entry %p",
1519 __func__, map, map->nentries, entry);
1523 * vm_map_lookup_entry: [ internal use only ]
1525 * Finds the map entry containing (or
1526 * immediately preceding) the specified address
1527 * in the given map; the entry is returned
1528 * in the "entry" parameter. The boolean
1529 * result indicates whether the address is
1530 * actually contained in the map.
1533 vm_map_lookup_entry(
1535 vm_offset_t address,
1536 vm_map_entry_t *entry) /* OUT */
1538 vm_map_entry_t cur, header, lbound, ubound;
1542 * If the map is empty, then the map entry immediately preceding
1543 * "address" is the map's header.
1545 header = &map->header;
1551 if (address >= cur->start && cur->end > address) {
1555 if ((locked = vm_map_locked(map)) ||
1556 sx_try_upgrade(&map->lock)) {
1558 * Splay requires a write lock on the map. However, it only
1559 * restructures the binary search tree; it does not otherwise
1560 * change the map. Thus, the map's timestamp need not change
1561 * on a temporary upgrade.
1563 cur = vm_map_splay(map, address);
1565 VM_MAP_UNLOCK_CONSISTENT(map);
1566 sx_downgrade(&map->lock);
1570 * If "address" is contained within a map entry, the new root
1571 * is that map entry. Otherwise, the new root is a map entry
1572 * immediately before or after "address".
1574 if (address < cur->start) {
1579 return (address < cur->end);
1582 * Since the map is only locked for read access, perform a
1583 * standard binary search tree lookup for "address".
1585 lbound = ubound = header;
1587 if (address < cur->start) {
1592 } else if (cur->end <= address) {
1607 * vm_map_insert1() is identical to vm_map_insert() except that it
1608 * returns the newly inserted map entry in '*res'. In case the new
1609 * entry is coalesced with a neighbor or an existing entry was
1610 * resized, that entry is returned. In any case, the returned entry
1611 * covers the specified address range.
1614 vm_map_insert1(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1615 vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max, int cow,
1616 vm_map_entry_t *res)
1618 vm_map_entry_t new_entry, next_entry, prev_entry;
1620 vm_eflags_t protoeflags;
1621 vm_inherit_t inheritance;
1625 VM_MAP_ASSERT_LOCKED(map);
1626 KASSERT(object != kernel_object ||
1627 (cow & MAP_COPY_ON_WRITE) == 0,
1628 ("vm_map_insert: kernel object and COW"));
1629 KASSERT(object == NULL || (cow & MAP_NOFAULT) == 0 ||
1630 (cow & MAP_SPLIT_BOUNDARY_MASK) != 0,
1631 ("vm_map_insert: paradoxical MAP_NOFAULT request, obj %p cow %#x",
1633 KASSERT((prot & ~max) == 0,
1634 ("prot %#x is not subset of max_prot %#x", prot, max));
1637 * Check that the start and end points are not bogus.
1639 if (start == end || !vm_map_range_valid(map, start, end))
1640 return (KERN_INVALID_ADDRESS);
1642 if ((map->flags & MAP_WXORX) != 0 && (prot & (VM_PROT_WRITE |
1643 VM_PROT_EXECUTE)) == (VM_PROT_WRITE | VM_PROT_EXECUTE))
1644 return (KERN_PROTECTION_FAILURE);
1647 * Find the entry prior to the proposed starting address; if it's part
1648 * of an existing entry, this range is bogus.
1650 if (vm_map_lookup_entry(map, start, &prev_entry))
1651 return (KERN_NO_SPACE);
1654 * Assert that the next entry doesn't overlap the end point.
1656 next_entry = vm_map_entry_succ(prev_entry);
1657 if (next_entry->start < end)
1658 return (KERN_NO_SPACE);
1660 if ((cow & MAP_CREATE_GUARD) != 0 && (object != NULL ||
1661 max != VM_PROT_NONE))
1662 return (KERN_INVALID_ARGUMENT);
1665 if (cow & MAP_COPY_ON_WRITE)
1666 protoeflags |= MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY;
1667 if (cow & MAP_NOFAULT)
1668 protoeflags |= MAP_ENTRY_NOFAULT;
1669 if (cow & MAP_DISABLE_SYNCER)
1670 protoeflags |= MAP_ENTRY_NOSYNC;
1671 if (cow & MAP_DISABLE_COREDUMP)
1672 protoeflags |= MAP_ENTRY_NOCOREDUMP;
1673 if (cow & MAP_STACK_GROWS_DOWN)
1674 protoeflags |= MAP_ENTRY_GROWS_DOWN;
1675 if (cow & MAP_STACK_GROWS_UP)
1676 protoeflags |= MAP_ENTRY_GROWS_UP;
1677 if (cow & MAP_WRITECOUNT)
1678 protoeflags |= MAP_ENTRY_WRITECNT;
1679 if (cow & MAP_VN_EXEC)
1680 protoeflags |= MAP_ENTRY_VN_EXEC;
1681 if ((cow & MAP_CREATE_GUARD) != 0)
1682 protoeflags |= MAP_ENTRY_GUARD;
1683 if ((cow & MAP_CREATE_STACK_GAP_DN) != 0)
1684 protoeflags |= MAP_ENTRY_STACK_GAP_DN;
1685 if ((cow & MAP_CREATE_STACK_GAP_UP) != 0)
1686 protoeflags |= MAP_ENTRY_STACK_GAP_UP;
1687 if (cow & MAP_INHERIT_SHARE)
1688 inheritance = VM_INHERIT_SHARE;
1690 inheritance = VM_INHERIT_DEFAULT;
1691 if ((cow & MAP_SPLIT_BOUNDARY_MASK) != 0) {
1692 /* This magically ignores index 0, for usual page size. */
1693 bidx = (cow & MAP_SPLIT_BOUNDARY_MASK) >>
1694 MAP_SPLIT_BOUNDARY_SHIFT;
1695 if (bidx >= MAXPAGESIZES)
1696 return (KERN_INVALID_ARGUMENT);
1697 bdry = pagesizes[bidx] - 1;
1698 if ((start & bdry) != 0 || (end & bdry) != 0)
1699 return (KERN_INVALID_ARGUMENT);
1700 protoeflags |= bidx << MAP_ENTRY_SPLIT_BOUNDARY_SHIFT;
1704 if ((cow & (MAP_ACC_NO_CHARGE | MAP_NOFAULT | MAP_CREATE_GUARD)) != 0)
1706 if ((cow & MAP_ACC_CHARGED) || ((prot & VM_PROT_WRITE) &&
1707 ((protoeflags & MAP_ENTRY_NEEDS_COPY) || object == NULL))) {
1708 if (!(cow & MAP_ACC_CHARGED) && !swap_reserve(end - start))
1709 return (KERN_RESOURCE_SHORTAGE);
1710 KASSERT(object == NULL ||
1711 (protoeflags & MAP_ENTRY_NEEDS_COPY) != 0 ||
1712 object->cred == NULL,
1713 ("overcommit: vm_map_insert o %p", object));
1714 cred = curthread->td_ucred;
1718 /* Expand the kernel pmap, if necessary. */
1719 if (map == kernel_map && end > kernel_vm_end)
1720 pmap_growkernel(end);
1721 if (object != NULL) {
1723 * OBJ_ONEMAPPING must be cleared unless this mapping
1724 * is trivially proven to be the only mapping for any
1725 * of the object's pages. (Object granularity
1726 * reference counting is insufficient to recognize
1727 * aliases with precision.)
1729 if ((object->flags & OBJ_ANON) != 0) {
1730 VM_OBJECT_WLOCK(object);
1731 if (object->ref_count > 1 || object->shadow_count != 0)
1732 vm_object_clear_flag(object, OBJ_ONEMAPPING);
1733 VM_OBJECT_WUNLOCK(object);
1735 } else if ((prev_entry->eflags & ~MAP_ENTRY_USER_WIRED) ==
1737 (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP |
1738 MAP_VN_EXEC)) == 0 &&
1739 prev_entry->end == start && (prev_entry->cred == cred ||
1740 (prev_entry->object.vm_object != NULL &&
1741 prev_entry->object.vm_object->cred == cred)) &&
1742 vm_object_coalesce(prev_entry->object.vm_object,
1744 (vm_size_t)(prev_entry->end - prev_entry->start),
1745 (vm_size_t)(end - prev_entry->end), cred != NULL &&
1746 (protoeflags & MAP_ENTRY_NEEDS_COPY) == 0)) {
1748 * We were able to extend the object. Determine if we
1749 * can extend the previous map entry to include the
1750 * new range as well.
1752 if (prev_entry->inheritance == inheritance &&
1753 prev_entry->protection == prot &&
1754 prev_entry->max_protection == max &&
1755 prev_entry->wired_count == 0) {
1756 KASSERT((prev_entry->eflags & MAP_ENTRY_USER_WIRED) ==
1757 0, ("prev_entry %p has incoherent wiring",
1759 if ((prev_entry->eflags & MAP_ENTRY_GUARD) == 0)
1760 map->size += end - prev_entry->end;
1761 vm_map_entry_resize(map, prev_entry,
1762 end - prev_entry->end);
1763 *res = vm_map_try_merge_entries(map, prev_entry,
1765 return (KERN_SUCCESS);
1769 * If we can extend the object but cannot extend the
1770 * map entry, we have to create a new map entry. We
1771 * must bump the ref count on the extended object to
1772 * account for it. object may be NULL.
1774 object = prev_entry->object.vm_object;
1775 offset = prev_entry->offset +
1776 (prev_entry->end - prev_entry->start);
1777 vm_object_reference(object);
1778 if (cred != NULL && object != NULL && object->cred != NULL &&
1779 !(prev_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
1780 /* Object already accounts for this uid. */
1788 * Create a new entry
1790 new_entry = vm_map_entry_create(map);
1791 new_entry->start = start;
1792 new_entry->end = end;
1793 new_entry->cred = NULL;
1795 new_entry->eflags = protoeflags;
1796 new_entry->object.vm_object = object;
1797 new_entry->offset = offset;
1799 new_entry->inheritance = inheritance;
1800 new_entry->protection = prot;
1801 new_entry->max_protection = max;
1802 new_entry->wired_count = 0;
1803 new_entry->wiring_thread = NULL;
1804 new_entry->read_ahead = VM_FAULT_READ_AHEAD_INIT;
1805 new_entry->next_read = start;
1807 KASSERT(cred == NULL || !ENTRY_CHARGED(new_entry),
1808 ("overcommit: vm_map_insert leaks vm_map %p", new_entry));
1809 new_entry->cred = cred;
1812 * Insert the new entry into the list
1814 vm_map_entry_link(map, new_entry);
1815 if ((new_entry->eflags & MAP_ENTRY_GUARD) == 0)
1816 map->size += new_entry->end - new_entry->start;
1819 * Try to coalesce the new entry with both the previous and next
1820 * entries in the list. Previously, we only attempted to coalesce
1821 * with the previous entry when object is NULL. Here, we handle the
1822 * other cases, which are less common.
1824 vm_map_try_merge_entries(map, prev_entry, new_entry);
1825 *res = vm_map_try_merge_entries(map, new_entry, next_entry);
1827 if ((cow & (MAP_PREFAULT | MAP_PREFAULT_PARTIAL)) != 0) {
1828 vm_map_pmap_enter(map, start, prot, object, OFF_TO_IDX(offset),
1829 end - start, cow & MAP_PREFAULT_PARTIAL);
1832 return (KERN_SUCCESS);
1838 * Inserts the given VM object into the target map at the
1839 * specified address range.
1841 * Requires that the map be locked, and leaves it so.
1843 * If object is non-NULL, ref count must be bumped by caller
1844 * prior to making call to account for the new entry.
1847 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1848 vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max, int cow)
1852 return (vm_map_insert1(map, object, offset, start, end, prot, max,
1859 * Find the first fit (lowest VM address) for "length" free bytes
1860 * beginning at address >= start in the given map.
1862 * In a vm_map_entry, "max_free" is the maximum amount of
1863 * contiguous free space between an entry in its subtree and a
1864 * neighbor of that entry. This allows finding a free region in
1865 * one path down the tree, so O(log n) amortized with splay
1868 * The map must be locked, and leaves it so.
1870 * Returns: starting address if sufficient space,
1871 * vm_map_max(map)-length+1 if insufficient space.
1874 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length)
1876 vm_map_entry_t header, llist, rlist, root, y;
1877 vm_size_t left_length, max_free_left, max_free_right;
1878 vm_offset_t gap_end;
1880 VM_MAP_ASSERT_LOCKED(map);
1883 * Request must fit within min/max VM address and must avoid
1886 start = MAX(start, vm_map_min(map));
1887 if (start >= vm_map_max(map) || length > vm_map_max(map) - start)
1888 return (vm_map_max(map) - length + 1);
1890 /* Empty tree means wide open address space. */
1891 if (map->root == NULL)
1895 * After splay_split, if start is within an entry, push it to the start
1896 * of the following gap. If rlist is at the end of the gap containing
1897 * start, save the end of that gap in gap_end to see if the gap is big
1898 * enough; otherwise set gap_end to start skip gap-checking and move
1899 * directly to a search of the right subtree.
1901 header = &map->header;
1902 root = vm_map_splay_split(map, start, length, &llist, &rlist);
1903 gap_end = rlist->start;
1906 if (root->right != rlist)
1908 max_free_left = vm_map_splay_merge_left(header, root, llist);
1909 max_free_right = vm_map_splay_merge_right(header, root, rlist);
1910 } else if (rlist != header) {
1913 max_free_left = vm_map_splay_merge_pred(header, root, llist);
1914 max_free_right = vm_map_splay_merge_right(header, root, rlist);
1917 llist = root->right;
1918 max_free_left = vm_map_splay_merge_left(header, root, llist);
1919 max_free_right = vm_map_splay_merge_succ(header, root, rlist);
1921 root->max_free = vm_size_max(max_free_left, max_free_right);
1923 VM_MAP_ASSERT_CONSISTENT(map);
1924 if (length <= gap_end - start)
1927 /* With max_free, can immediately tell if no solution. */
1928 if (root->right == header || length > root->right->max_free)
1929 return (vm_map_max(map) - length + 1);
1932 * Splay for the least large-enough gap in the right subtree.
1934 llist = rlist = header;
1935 for (left_length = 0;;
1936 left_length = vm_map_entry_max_free_left(root, llist)) {
1937 if (length <= left_length)
1938 SPLAY_LEFT_STEP(root, y, llist, rlist,
1939 length <= vm_map_entry_max_free_left(y, llist));
1941 SPLAY_RIGHT_STEP(root, y, llist, rlist,
1942 length > vm_map_entry_max_free_left(y, root));
1947 llist = root->right;
1948 max_free_left = vm_map_splay_merge_left(header, root, llist);
1949 if (rlist == header) {
1950 root->max_free = vm_size_max(max_free_left,
1951 vm_map_splay_merge_succ(header, root, rlist));
1955 y->max_free = vm_size_max(
1956 vm_map_splay_merge_pred(root, y, root),
1957 vm_map_splay_merge_right(header, y, rlist));
1958 root->max_free = vm_size_max(max_free_left, y->max_free);
1961 VM_MAP_ASSERT_CONSISTENT(map);
1966 vm_map_fixed(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1967 vm_offset_t start, vm_size_t length, vm_prot_t prot,
1968 vm_prot_t max, int cow)
1973 end = start + length;
1974 KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1976 ("vm_map_fixed: non-NULL backing object for stack"));
1978 VM_MAP_RANGE_CHECK(map, start, end);
1979 if ((cow & MAP_CHECK_EXCL) == 0) {
1980 result = vm_map_delete(map, start, end);
1981 if (result != KERN_SUCCESS)
1984 if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1985 result = vm_map_stack_locked(map, start, length, sgrowsiz,
1988 result = vm_map_insert(map, object, offset, start, end,
1996 static const int aslr_pages_rnd_64[2] = {0x1000, 0x10};
1997 static const int aslr_pages_rnd_32[2] = {0x100, 0x4};
1999 static int cluster_anon = 1;
2000 SYSCTL_INT(_vm, OID_AUTO, cluster_anon, CTLFLAG_RW,
2002 "Cluster anonymous mappings: 0 = no, 1 = yes if no hint, 2 = always");
2005 clustering_anon_allowed(vm_offset_t addr, int cow)
2008 switch (cluster_anon) {
2012 return (addr == 0 || (cow & MAP_NO_HINT) != 0);
2019 static long aslr_restarts;
2020 SYSCTL_LONG(_vm, OID_AUTO, aslr_restarts, CTLFLAG_RD,
2022 "Number of aslr failures");
2025 * Searches for the specified amount of free space in the given map with the
2026 * specified alignment. Performs an address-ordered, first-fit search from
2027 * the given address "*addr", with an optional upper bound "max_addr". If the
2028 * parameter "alignment" is zero, then the alignment is computed from the
2029 * given (object, offset) pair so as to enable the greatest possible use of
2030 * superpage mappings. Returns KERN_SUCCESS and the address of the free space
2031 * in "*addr" if successful. Otherwise, returns KERN_NO_SPACE.
2033 * The map must be locked. Initially, there must be at least "length" bytes
2034 * of free space at the given address.
2037 vm_map_alignspace(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
2038 vm_offset_t *addr, vm_size_t length, vm_offset_t max_addr,
2039 vm_offset_t alignment)
2041 vm_offset_t aligned_addr, free_addr;
2043 VM_MAP_ASSERT_LOCKED(map);
2045 KASSERT(free_addr == vm_map_findspace(map, free_addr, length),
2046 ("caller failed to provide space %#jx at address %p",
2047 (uintmax_t)length, (void *)free_addr));
2050 * At the start of every iteration, the free space at address
2051 * "*addr" is at least "length" bytes.
2054 pmap_align_superpage(object, offset, addr, length);
2056 *addr = roundup2(*addr, alignment);
2057 aligned_addr = *addr;
2058 if (aligned_addr == free_addr) {
2060 * Alignment did not change "*addr", so "*addr" must
2061 * still provide sufficient free space.
2063 return (KERN_SUCCESS);
2067 * Test for address wrap on "*addr". A wrapped "*addr" could
2068 * be a valid address, in which case vm_map_findspace() cannot
2069 * be relied upon to fail.
2071 if (aligned_addr < free_addr)
2072 return (KERN_NO_SPACE);
2073 *addr = vm_map_findspace(map, aligned_addr, length);
2074 if (*addr + length > vm_map_max(map) ||
2075 (max_addr != 0 && *addr + length > max_addr))
2076 return (KERN_NO_SPACE);
2078 if (free_addr == aligned_addr) {
2080 * If a successful call to vm_map_findspace() did not
2081 * change "*addr", then "*addr" must still be aligned
2082 * and provide sufficient free space.
2084 return (KERN_SUCCESS);
2090 vm_map_find_aligned(vm_map_t map, vm_offset_t *addr, vm_size_t length,
2091 vm_offset_t max_addr, vm_offset_t alignment)
2093 /* XXXKIB ASLR eh ? */
2094 *addr = vm_map_findspace(map, *addr, length);
2095 if (*addr + length > vm_map_max(map) ||
2096 (max_addr != 0 && *addr + length > max_addr))
2097 return (KERN_NO_SPACE);
2098 return (vm_map_alignspace(map, NULL, 0, addr, length, max_addr,
2103 * vm_map_find finds an unallocated region in the target address
2104 * map with the given length. The search is defined to be
2105 * first-fit from the specified address; the region found is
2106 * returned in the same parameter.
2108 * If object is non-NULL, ref count must be bumped by caller
2109 * prior to making call to account for the new entry.
2112 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
2113 vm_offset_t *addr, /* IN/OUT */
2114 vm_size_t length, vm_offset_t max_addr, int find_space,
2115 vm_prot_t prot, vm_prot_t max, int cow)
2117 vm_offset_t alignment, curr_min_addr, min_addr;
2118 int gap, pidx, rv, try;
2119 bool cluster, en_aslr, update_anon;
2121 KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
2123 ("vm_map_find: non-NULL backing object for stack"));
2124 MPASS((cow & MAP_REMAP) == 0 || (find_space == VMFS_NO_SPACE &&
2125 (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0));
2126 if (find_space == VMFS_OPTIMAL_SPACE && (object == NULL ||
2127 (object->flags & OBJ_COLORED) == 0))
2128 find_space = VMFS_ANY_SPACE;
2129 if (find_space >> 8 != 0) {
2130 KASSERT((find_space & 0xff) == 0, ("bad VMFS flags"));
2131 alignment = (vm_offset_t)1 << (find_space >> 8);
2134 en_aslr = (map->flags & MAP_ASLR) != 0;
2135 update_anon = cluster = clustering_anon_allowed(*addr, cow) &&
2136 (map->flags & MAP_IS_SUB_MAP) == 0 && max_addr == 0 &&
2137 find_space != VMFS_NO_SPACE && object == NULL &&
2138 (cow & (MAP_INHERIT_SHARE | MAP_STACK_GROWS_UP |
2139 MAP_STACK_GROWS_DOWN)) == 0 && prot != PROT_NONE;
2140 curr_min_addr = min_addr = *addr;
2141 if (en_aslr && min_addr == 0 && !cluster &&
2142 find_space != VMFS_NO_SPACE &&
2143 (map->flags & MAP_ASLR_IGNSTART) != 0)
2144 curr_min_addr = min_addr = vm_map_min(map);
2148 curr_min_addr = map->anon_loc;
2149 if (curr_min_addr == 0)
2152 if (find_space != VMFS_NO_SPACE) {
2153 KASSERT(find_space == VMFS_ANY_SPACE ||
2154 find_space == VMFS_OPTIMAL_SPACE ||
2155 find_space == VMFS_SUPER_SPACE ||
2156 alignment != 0, ("unexpected VMFS flag"));
2159 * When creating an anonymous mapping, try clustering
2160 * with an existing anonymous mapping first.
2162 * We make up to two attempts to find address space
2163 * for a given find_space value. The first attempt may
2164 * apply randomization or may cluster with an existing
2165 * anonymous mapping. If this first attempt fails,
2166 * perform a first-fit search of the available address
2169 * If all tries failed, and find_space is
2170 * VMFS_OPTIMAL_SPACE, fallback to VMFS_ANY_SPACE.
2171 * Again enable clustering and randomization.
2178 * Second try: we failed either to find a
2179 * suitable region for randomizing the
2180 * allocation, or to cluster with an existing
2181 * mapping. Retry with free run.
2183 curr_min_addr = (map->flags & MAP_ASLR_IGNSTART) != 0 ?
2184 vm_map_min(map) : min_addr;
2185 atomic_add_long(&aslr_restarts, 1);
2188 if (try == 1 && en_aslr && !cluster) {
2190 * Find space for allocation, including
2191 * gap needed for later randomization.
2193 pidx = MAXPAGESIZES > 1 && pagesizes[1] != 0 &&
2194 (find_space == VMFS_SUPER_SPACE || find_space ==
2195 VMFS_OPTIMAL_SPACE) ? 1 : 0;
2196 gap = vm_map_max(map) > MAP_32BIT_MAX_ADDR &&
2197 (max_addr == 0 || max_addr > MAP_32BIT_MAX_ADDR) ?
2198 aslr_pages_rnd_64[pidx] : aslr_pages_rnd_32[pidx];
2199 *addr = vm_map_findspace(map, curr_min_addr,
2200 length + gap * pagesizes[pidx]);
2201 if (*addr + length + gap * pagesizes[pidx] >
2204 /* And randomize the start address. */
2205 *addr += (arc4random() % gap) * pagesizes[pidx];
2206 if (max_addr != 0 && *addr + length > max_addr)
2209 *addr = vm_map_findspace(map, curr_min_addr, length);
2210 if (*addr + length > vm_map_max(map) ||
2211 (max_addr != 0 && *addr + length > max_addr)) {
2222 if (find_space != VMFS_ANY_SPACE &&
2223 (rv = vm_map_alignspace(map, object, offset, addr, length,
2224 max_addr, alignment)) != KERN_SUCCESS) {
2225 if (find_space == VMFS_OPTIMAL_SPACE) {
2226 find_space = VMFS_ANY_SPACE;
2227 curr_min_addr = min_addr;
2228 cluster = update_anon;
2234 } else if ((cow & MAP_REMAP) != 0) {
2235 if (!vm_map_range_valid(map, *addr, *addr + length)) {
2236 rv = KERN_INVALID_ADDRESS;
2239 rv = vm_map_delete(map, *addr, *addr + length);
2240 if (rv != KERN_SUCCESS)
2243 if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
2244 rv = vm_map_stack_locked(map, *addr, length, sgrowsiz, prot,
2247 rv = vm_map_insert(map, object, offset, *addr, *addr + length,
2250 if (rv == KERN_SUCCESS && update_anon)
2251 map->anon_loc = *addr + length;
2258 * vm_map_find_min() is a variant of vm_map_find() that takes an
2259 * additional parameter ("default_addr") and treats the given address
2260 * ("*addr") differently. Specifically, it treats "*addr" as a hint
2261 * and not as the minimum address where the mapping is created.
2263 * This function works in two phases. First, it tries to
2264 * allocate above the hint. If that fails and the hint is
2265 * greater than "default_addr", it performs a second pass, replacing
2266 * the hint with "default_addr" as the minimum address for the
2270 vm_map_find_min(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
2271 vm_offset_t *addr, vm_size_t length, vm_offset_t default_addr,
2272 vm_offset_t max_addr, int find_space, vm_prot_t prot, vm_prot_t max,
2281 *addr = hint = default_addr;
2284 rv = vm_map_find(map, object, offset, addr, length, max_addr,
2285 find_space, prot, max, cow);
2286 if (rv == KERN_SUCCESS || default_addr >= hint)
2288 *addr = hint = default_addr;
2293 * A map entry with any of the following flags set must not be merged with
2296 #define MAP_ENTRY_NOMERGE_MASK (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP | \
2297 MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP | MAP_ENTRY_VN_EXEC | \
2298 MAP_ENTRY_STACK_GAP_UP | MAP_ENTRY_STACK_GAP_DN)
2301 vm_map_mergeable_neighbors(vm_map_entry_t prev, vm_map_entry_t entry)
2304 KASSERT((prev->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 ||
2305 (entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0,
2306 ("vm_map_mergeable_neighbors: neither %p nor %p are mergeable",
2308 return (prev->end == entry->start &&
2309 prev->object.vm_object == entry->object.vm_object &&
2310 (prev->object.vm_object == NULL ||
2311 prev->offset + (prev->end - prev->start) == entry->offset) &&
2312 prev->eflags == entry->eflags &&
2313 prev->protection == entry->protection &&
2314 prev->max_protection == entry->max_protection &&
2315 prev->inheritance == entry->inheritance &&
2316 prev->wired_count == entry->wired_count &&
2317 prev->cred == entry->cred);
2321 vm_map_merged_neighbor_dispose(vm_map_t map, vm_map_entry_t entry)
2325 * If the backing object is a vnode object, vm_object_deallocate()
2326 * calls vrele(). However, vrele() does not lock the vnode because
2327 * the vnode has additional references. Thus, the map lock can be
2328 * kept without causing a lock-order reversal with the vnode lock.
2330 * Since we count the number of virtual page mappings in
2331 * object->un_pager.vnp.writemappings, the writemappings value
2332 * should not be adjusted when the entry is disposed of.
2334 if (entry->object.vm_object != NULL)
2335 vm_object_deallocate(entry->object.vm_object);
2336 if (entry->cred != NULL)
2337 crfree(entry->cred);
2338 vm_map_entry_dispose(map, entry);
2342 * vm_map_try_merge_entries:
2344 * Compare two map entries that represent consecutive ranges. If
2345 * the entries can be merged, expand the range of the second to
2346 * cover the range of the first and delete the first. Then return
2347 * the map entry that includes the first range.
2349 * The map must be locked.
2352 vm_map_try_merge_entries(vm_map_t map, vm_map_entry_t prev_entry,
2353 vm_map_entry_t entry)
2356 VM_MAP_ASSERT_LOCKED(map);
2357 if ((entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 &&
2358 vm_map_mergeable_neighbors(prev_entry, entry)) {
2359 vm_map_entry_unlink(map, prev_entry, UNLINK_MERGE_NEXT);
2360 vm_map_merged_neighbor_dispose(map, prev_entry);
2363 return (prev_entry);
2367 * vm_map_entry_back:
2369 * Allocate an object to back a map entry.
2372 vm_map_entry_back(vm_map_entry_t entry)
2376 KASSERT(entry->object.vm_object == NULL,
2377 ("map entry %p has backing object", entry));
2378 KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
2379 ("map entry %p is a submap", entry));
2380 object = vm_object_allocate_anon(atop(entry->end - entry->start), NULL,
2381 entry->cred, entry->end - entry->start);
2382 entry->object.vm_object = object;
2388 * vm_map_entry_charge_object
2390 * If there is no object backing this entry, create one. Otherwise, if
2391 * the entry has cred, give it to the backing object.
2394 vm_map_entry_charge_object(vm_map_t map, vm_map_entry_t entry)
2397 VM_MAP_ASSERT_LOCKED(map);
2398 KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
2399 ("map entry %p is a submap", entry));
2400 if (entry->object.vm_object == NULL && !map->system_map &&
2401 (entry->eflags & MAP_ENTRY_GUARD) == 0)
2402 vm_map_entry_back(entry);
2403 else if (entry->object.vm_object != NULL &&
2404 ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
2405 entry->cred != NULL) {
2406 VM_OBJECT_WLOCK(entry->object.vm_object);
2407 KASSERT(entry->object.vm_object->cred == NULL,
2408 ("OVERCOMMIT: %s: both cred e %p", __func__, entry));
2409 entry->object.vm_object->cred = entry->cred;
2410 entry->object.vm_object->charge = entry->end - entry->start;
2411 VM_OBJECT_WUNLOCK(entry->object.vm_object);
2417 * vm_map_entry_clone
2419 * Create a duplicate map entry for clipping.
2421 static vm_map_entry_t
2422 vm_map_entry_clone(vm_map_t map, vm_map_entry_t entry)
2424 vm_map_entry_t new_entry;
2426 VM_MAP_ASSERT_LOCKED(map);
2429 * Create a backing object now, if none exists, so that more individual
2430 * objects won't be created after the map entry is split.
2432 vm_map_entry_charge_object(map, entry);
2434 /* Clone the entry. */
2435 new_entry = vm_map_entry_create(map);
2436 *new_entry = *entry;
2437 if (new_entry->cred != NULL)
2438 crhold(entry->cred);
2439 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2440 vm_object_reference(new_entry->object.vm_object);
2441 vm_map_entry_set_vnode_text(new_entry, true);
2443 * The object->un_pager.vnp.writemappings for the object of
2444 * MAP_ENTRY_WRITECNT type entry shall be kept as is here. The
2445 * virtual pages are re-distributed among the clipped entries,
2446 * so the sum is left the same.
2453 * vm_map_clip_start: [ internal use only ]
2455 * Asserts that the given entry begins at or after
2456 * the specified address; if necessary,
2457 * it splits the entry into two.
2460 vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t startaddr)
2462 vm_map_entry_t new_entry;
2465 if (!map->system_map)
2466 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2467 "%s: map %p entry %p start 0x%jx", __func__, map, entry,
2468 (uintmax_t)startaddr);
2470 if (startaddr <= entry->start)
2471 return (KERN_SUCCESS);
2473 VM_MAP_ASSERT_LOCKED(map);
2474 KASSERT(entry->end > startaddr && entry->start < startaddr,
2475 ("%s: invalid clip of entry %p", __func__, entry));
2477 bdry_idx = MAP_ENTRY_SPLIT_BOUNDARY_INDEX(entry);
2478 if (bdry_idx != 0) {
2479 if ((startaddr & (pagesizes[bdry_idx] - 1)) != 0)
2480 return (KERN_INVALID_ARGUMENT);
2483 new_entry = vm_map_entry_clone(map, entry);
2486 * Split off the front portion. Insert the new entry BEFORE this one,
2487 * so that this entry has the specified starting address.
2489 new_entry->end = startaddr;
2490 vm_map_entry_link(map, new_entry);
2491 return (KERN_SUCCESS);
2495 * vm_map_lookup_clip_start:
2497 * Find the entry at or just after 'start', and clip it if 'start' is in
2498 * the interior of the entry. Return entry after 'start', and in
2499 * prev_entry set the entry before 'start'.
2502 vm_map_lookup_clip_start(vm_map_t map, vm_offset_t start,
2503 vm_map_entry_t *res_entry, vm_map_entry_t *prev_entry)
2505 vm_map_entry_t entry;
2508 if (!map->system_map)
2509 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2510 "%s: map %p start 0x%jx prev %p", __func__, map,
2511 (uintmax_t)start, prev_entry);
2513 if (vm_map_lookup_entry(map, start, prev_entry)) {
2514 entry = *prev_entry;
2515 rv = vm_map_clip_start(map, entry, start);
2516 if (rv != KERN_SUCCESS)
2518 *prev_entry = vm_map_entry_pred(entry);
2520 entry = vm_map_entry_succ(*prev_entry);
2522 return (KERN_SUCCESS);
2526 * vm_map_clip_end: [ internal use only ]
2528 * Asserts that the given entry ends at or before
2529 * the specified address; if necessary,
2530 * it splits the entry into two.
2533 vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t endaddr)
2535 vm_map_entry_t new_entry;
2538 if (!map->system_map)
2539 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2540 "%s: map %p entry %p end 0x%jx", __func__, map, entry,
2541 (uintmax_t)endaddr);
2543 if (endaddr >= entry->end)
2544 return (KERN_SUCCESS);
2546 VM_MAP_ASSERT_LOCKED(map);
2547 KASSERT(entry->start < endaddr && entry->end > endaddr,
2548 ("%s: invalid clip of entry %p", __func__, entry));
2550 bdry_idx = MAP_ENTRY_SPLIT_BOUNDARY_INDEX(entry);
2551 if (bdry_idx != 0) {
2552 if ((endaddr & (pagesizes[bdry_idx] - 1)) != 0)
2553 return (KERN_INVALID_ARGUMENT);
2556 new_entry = vm_map_entry_clone(map, entry);
2559 * Split off the back portion. Insert the new entry AFTER this one,
2560 * so that this entry has the specified ending address.
2562 new_entry->start = endaddr;
2563 vm_map_entry_link(map, new_entry);
2565 return (KERN_SUCCESS);
2569 * vm_map_submap: [ kernel use only ]
2571 * Mark the given range as handled by a subordinate map.
2573 * This range must have been created with vm_map_find,
2574 * and no other operations may have been performed on this
2575 * range prior to calling vm_map_submap.
2577 * Only a limited number of operations can be performed
2578 * within this rage after calling vm_map_submap:
2580 * [Don't try vm_map_copy!]
2582 * To remove a submapping, one must first remove the
2583 * range from the superior map, and then destroy the
2584 * submap (if desired). [Better yet, don't try it.]
2593 vm_map_entry_t entry;
2596 result = KERN_INVALID_ARGUMENT;
2598 vm_map_lock(submap);
2599 submap->flags |= MAP_IS_SUB_MAP;
2600 vm_map_unlock(submap);
2603 VM_MAP_RANGE_CHECK(map, start, end);
2604 if (vm_map_lookup_entry(map, start, &entry) && entry->end >= end &&
2605 (entry->eflags & MAP_ENTRY_COW) == 0 &&
2606 entry->object.vm_object == NULL) {
2607 result = vm_map_clip_start(map, entry, start);
2608 if (result != KERN_SUCCESS)
2610 result = vm_map_clip_end(map, entry, end);
2611 if (result != KERN_SUCCESS)
2613 entry->object.sub_map = submap;
2614 entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
2615 result = KERN_SUCCESS;
2620 if (result != KERN_SUCCESS) {
2621 vm_map_lock(submap);
2622 submap->flags &= ~MAP_IS_SUB_MAP;
2623 vm_map_unlock(submap);
2629 * The maximum number of pages to map if MAP_PREFAULT_PARTIAL is specified
2631 #define MAX_INIT_PT 96
2634 * vm_map_pmap_enter:
2636 * Preload the specified map's pmap with mappings to the specified
2637 * object's memory-resident pages. No further physical pages are
2638 * allocated, and no further virtual pages are retrieved from secondary
2639 * storage. If the specified flags include MAP_PREFAULT_PARTIAL, then a
2640 * limited number of page mappings are created at the low-end of the
2641 * specified address range. (For this purpose, a superpage mapping
2642 * counts as one page mapping.) Otherwise, all resident pages within
2643 * the specified address range are mapped.
2646 vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
2647 vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
2650 vm_page_t p, p_start;
2651 vm_pindex_t mask, psize, threshold, tmpidx;
2653 if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0 || object == NULL)
2655 if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2656 VM_OBJECT_WLOCK(object);
2657 if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2658 pmap_object_init_pt(map->pmap, addr, object, pindex,
2660 VM_OBJECT_WUNLOCK(object);
2663 VM_OBJECT_LOCK_DOWNGRADE(object);
2665 VM_OBJECT_RLOCK(object);
2668 if (psize + pindex > object->size) {
2669 if (pindex >= object->size) {
2670 VM_OBJECT_RUNLOCK(object);
2673 psize = object->size - pindex;
2678 threshold = MAX_INIT_PT;
2680 p = vm_page_find_least(object, pindex);
2682 * Assert: the variable p is either (1) the page with the
2683 * least pindex greater than or equal to the parameter pindex
2687 p != NULL && (tmpidx = p->pindex - pindex) < psize;
2688 p = TAILQ_NEXT(p, listq)) {
2690 * don't allow an madvise to blow away our really
2691 * free pages allocating pv entries.
2693 if (((flags & MAP_PREFAULT_MADVISE) != 0 &&
2694 vm_page_count_severe()) ||
2695 ((flags & MAP_PREFAULT_PARTIAL) != 0 &&
2696 tmpidx >= threshold)) {
2700 if (vm_page_all_valid(p)) {
2701 if (p_start == NULL) {
2702 start = addr + ptoa(tmpidx);
2705 /* Jump ahead if a superpage mapping is possible. */
2706 if (p->psind > 0 && ((addr + ptoa(tmpidx)) &
2707 (pagesizes[p->psind] - 1)) == 0) {
2708 mask = atop(pagesizes[p->psind]) - 1;
2709 if (tmpidx + mask < psize &&
2710 vm_page_ps_test(p, PS_ALL_VALID, NULL)) {
2715 } else if (p_start != NULL) {
2716 pmap_enter_object(map->pmap, start, addr +
2717 ptoa(tmpidx), p_start, prot);
2721 if (p_start != NULL)
2722 pmap_enter_object(map->pmap, start, addr + ptoa(psize),
2724 VM_OBJECT_RUNLOCK(object);
2728 vm_map_protect_guard(vm_map_entry_t entry, vm_prot_t new_prot,
2729 vm_prot_t new_maxprot, int flags)
2733 MPASS((entry->eflags & MAP_ENTRY_GUARD) != 0);
2734 if ((entry->eflags & (MAP_ENTRY_STACK_GAP_UP |
2735 MAP_ENTRY_STACK_GAP_DN)) == 0)
2738 old_prot = PROT_EXTRACT(entry->offset);
2739 if ((flags & VM_MAP_PROTECT_SET_MAXPROT) != 0) {
2740 entry->offset = PROT_MAX(new_maxprot) |
2741 (new_maxprot & old_prot);
2743 if ((flags & VM_MAP_PROTECT_SET_PROT) != 0) {
2744 entry->offset = new_prot | PROT_MAX(
2745 PROT_MAX_EXTRACT(entry->offset));
2752 * Sets the protection and/or the maximum protection of the
2753 * specified address region in the target map.
2756 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
2757 vm_prot_t new_prot, vm_prot_t new_maxprot, int flags)
2759 vm_map_entry_t entry, first_entry, in_tran, prev_entry;
2762 vm_offset_t orig_start;
2763 vm_prot_t check_prot, max_prot, old_prot;
2767 return (KERN_SUCCESS);
2769 if (CONTAINS_BITS(flags, VM_MAP_PROTECT_SET_PROT |
2770 VM_MAP_PROTECT_SET_MAXPROT) &&
2771 !CONTAINS_BITS(new_maxprot, new_prot))
2772 return (KERN_OUT_OF_BOUNDS);
2780 if ((map->flags & MAP_WXORX) != 0 &&
2781 (flags & VM_MAP_PROTECT_SET_PROT) != 0 &&
2782 CONTAINS_BITS(new_prot, VM_PROT_WRITE | VM_PROT_EXECUTE)) {
2784 return (KERN_PROTECTION_FAILURE);
2788 * Ensure that we are not concurrently wiring pages. vm_map_wire() may
2789 * need to fault pages into the map and will drop the map lock while
2790 * doing so, and the VM object may end up in an inconsistent state if we
2791 * update the protection on the map entry in between faults.
2793 vm_map_wait_busy(map);
2795 VM_MAP_RANGE_CHECK(map, start, end);
2797 if (!vm_map_lookup_entry(map, start, &first_entry))
2798 first_entry = vm_map_entry_succ(first_entry);
2800 if ((flags & VM_MAP_PROTECT_GROWSDOWN) != 0 &&
2801 (first_entry->eflags & MAP_ENTRY_GROWS_DOWN) != 0) {
2803 * Handle Linux's PROT_GROWSDOWN flag.
2804 * It means that protection is applied down to the
2805 * whole stack, including the specified range of the
2806 * mapped region, and the grow down region (AKA
2809 while (!CONTAINS_BITS(first_entry->eflags,
2810 MAP_ENTRY_GUARD | MAP_ENTRY_STACK_GAP_DN) &&
2811 first_entry != vm_map_entry_first(map))
2812 first_entry = vm_map_entry_pred(first_entry);
2813 start = first_entry->start;
2817 * Make a first pass to check for protection violations.
2820 if ((flags & VM_MAP_PROTECT_SET_PROT) != 0)
2821 check_prot |= new_prot;
2822 if ((flags & VM_MAP_PROTECT_SET_MAXPROT) != 0)
2823 check_prot |= new_maxprot;
2824 for (entry = first_entry; entry->start < end;
2825 entry = vm_map_entry_succ(entry)) {
2826 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0) {
2828 return (KERN_INVALID_ARGUMENT);
2830 if ((entry->eflags & (MAP_ENTRY_GUARD |
2831 MAP_ENTRY_STACK_GAP_DN | MAP_ENTRY_STACK_GAP_UP)) ==
2834 max_prot = (entry->eflags & (MAP_ENTRY_STACK_GAP_DN |
2835 MAP_ENTRY_STACK_GAP_UP)) != 0 ?
2836 PROT_MAX_EXTRACT(entry->offset) : entry->max_protection;
2837 if (!CONTAINS_BITS(max_prot, check_prot)) {
2839 return (KERN_PROTECTION_FAILURE);
2841 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0)
2846 * Postpone the operation until all in-transition map entries have
2847 * stabilized. An in-transition entry might already have its pages
2848 * wired and wired_count incremented, but not yet have its
2849 * MAP_ENTRY_USER_WIRED flag set. In which case, we would fail to call
2850 * vm_fault_copy_entry() in the final loop below.
2852 if (in_tran != NULL) {
2853 in_tran->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2854 vm_map_unlock_and_wait(map, 0);
2859 * Before changing the protections, try to reserve swap space for any
2860 * private (i.e., copy-on-write) mappings that are transitioning from
2861 * read-only to read/write access. If a reservation fails, break out
2862 * of this loop early and let the next loop simplify the entries, since
2863 * some may now be mergeable.
2865 rv = vm_map_clip_start(map, first_entry, start);
2866 if (rv != KERN_SUCCESS) {
2870 for (entry = first_entry; entry->start < end;
2871 entry = vm_map_entry_succ(entry)) {
2872 rv = vm_map_clip_end(map, entry, end);
2873 if (rv != KERN_SUCCESS) {
2878 if ((flags & VM_MAP_PROTECT_SET_PROT) == 0 ||
2879 ((new_prot & ~entry->protection) & VM_PROT_WRITE) == 0 ||
2880 ENTRY_CHARGED(entry) ||
2881 (entry->eflags & MAP_ENTRY_GUARD) != 0)
2884 cred = curthread->td_ucred;
2885 obj = entry->object.vm_object;
2888 (entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0) {
2889 if (!swap_reserve(entry->end - entry->start)) {
2890 rv = KERN_RESOURCE_SHORTAGE;
2899 VM_OBJECT_WLOCK(obj);
2900 if ((obj->flags & OBJ_SWAP) == 0) {
2901 VM_OBJECT_WUNLOCK(obj);
2906 * Charge for the whole object allocation now, since
2907 * we cannot distinguish between non-charged and
2908 * charged clipped mapping of the same object later.
2910 KASSERT(obj->charge == 0,
2911 ("vm_map_protect: object %p overcharged (entry %p)",
2913 if (!swap_reserve(ptoa(obj->size))) {
2914 VM_OBJECT_WUNLOCK(obj);
2915 rv = KERN_RESOURCE_SHORTAGE;
2922 obj->charge = ptoa(obj->size);
2923 VM_OBJECT_WUNLOCK(obj);
2927 * If enough swap space was available, go back and fix up protections.
2928 * Otherwise, just simplify entries, since some may have been modified.
2929 * [Note that clipping is not necessary the second time.]
2931 for (prev_entry = vm_map_entry_pred(first_entry), entry = first_entry;
2933 vm_map_try_merge_entries(map, prev_entry, entry),
2934 prev_entry = entry, entry = vm_map_entry_succ(entry)) {
2935 if (rv != KERN_SUCCESS)
2938 if ((entry->eflags & MAP_ENTRY_GUARD) != 0) {
2939 vm_map_protect_guard(entry, new_prot, new_maxprot,
2944 old_prot = entry->protection;
2946 if ((flags & VM_MAP_PROTECT_SET_MAXPROT) != 0) {
2947 entry->max_protection = new_maxprot;
2948 entry->protection = new_maxprot & old_prot;
2950 if ((flags & VM_MAP_PROTECT_SET_PROT) != 0)
2951 entry->protection = new_prot;
2954 * For user wired map entries, the normal lazy evaluation of
2955 * write access upgrades through soft page faults is
2956 * undesirable. Instead, immediately copy any pages that are
2957 * copy-on-write and enable write access in the physical map.
2959 if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0 &&
2960 (entry->protection & VM_PROT_WRITE) != 0 &&
2961 (old_prot & VM_PROT_WRITE) == 0)
2962 vm_fault_copy_entry(map, map, entry, entry, NULL);
2965 * When restricting access, update the physical map. Worry
2966 * about copy-on-write here.
2968 if ((old_prot & ~entry->protection) != 0) {
2969 #define MASK(entry) (((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
2971 pmap_protect(map->pmap, entry->start,
2973 entry->protection & MASK(entry));
2977 vm_map_try_merge_entries(map, prev_entry, entry);
2985 * This routine traverses a processes map handling the madvise
2986 * system call. Advisories are classified as either those effecting
2987 * the vm_map_entry structure, or those effecting the underlying
2997 vm_map_entry_t entry, prev_entry;
3002 * Some madvise calls directly modify the vm_map_entry, in which case
3003 * we need to use an exclusive lock on the map and we need to perform
3004 * various clipping operations. Otherwise we only need a read-lock
3009 case MADV_SEQUENTIAL:
3026 vm_map_lock_read(map);
3033 * Locate starting entry and clip if necessary.
3035 VM_MAP_RANGE_CHECK(map, start, end);
3039 * madvise behaviors that are implemented in the vm_map_entry.
3041 * We clip the vm_map_entry so that behavioral changes are
3042 * limited to the specified address range.
3044 rv = vm_map_lookup_clip_start(map, start, &entry, &prev_entry);
3045 if (rv != KERN_SUCCESS) {
3047 return (vm_mmap_to_errno(rv));
3050 for (; entry->start < end; prev_entry = entry,
3051 entry = vm_map_entry_succ(entry)) {
3052 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
3055 rv = vm_map_clip_end(map, entry, end);
3056 if (rv != KERN_SUCCESS) {
3058 return (vm_mmap_to_errno(rv));
3063 vm_map_entry_set_behavior(entry,
3064 MAP_ENTRY_BEHAV_NORMAL);
3066 case MADV_SEQUENTIAL:
3067 vm_map_entry_set_behavior(entry,
3068 MAP_ENTRY_BEHAV_SEQUENTIAL);
3071 vm_map_entry_set_behavior(entry,
3072 MAP_ENTRY_BEHAV_RANDOM);
3075 entry->eflags |= MAP_ENTRY_NOSYNC;
3078 entry->eflags &= ~MAP_ENTRY_NOSYNC;
3081 entry->eflags |= MAP_ENTRY_NOCOREDUMP;
3084 entry->eflags &= ~MAP_ENTRY_NOCOREDUMP;
3089 vm_map_try_merge_entries(map, prev_entry, entry);
3091 vm_map_try_merge_entries(map, prev_entry, entry);
3094 vm_pindex_t pstart, pend;
3097 * madvise behaviors that are implemented in the underlying
3100 * Since we don't clip the vm_map_entry, we have to clip
3101 * the vm_object pindex and count.
3103 if (!vm_map_lookup_entry(map, start, &entry))
3104 entry = vm_map_entry_succ(entry);
3105 for (; entry->start < end;
3106 entry = vm_map_entry_succ(entry)) {
3107 vm_offset_t useEnd, useStart;
3109 if ((entry->eflags & (MAP_ENTRY_IS_SUB_MAP |
3110 MAP_ENTRY_GUARD)) != 0)
3114 * MADV_FREE would otherwise rewind time to
3115 * the creation of the shadow object. Because
3116 * we hold the VM map read-locked, neither the
3117 * entry's object nor the presence of a
3118 * backing object can change.
3120 if (behav == MADV_FREE &&
3121 entry->object.vm_object != NULL &&
3122 entry->object.vm_object->backing_object != NULL)
3125 pstart = OFF_TO_IDX(entry->offset);
3126 pend = pstart + atop(entry->end - entry->start);
3127 useStart = entry->start;
3128 useEnd = entry->end;
3130 if (entry->start < start) {
3131 pstart += atop(start - entry->start);
3134 if (entry->end > end) {
3135 pend -= atop(entry->end - end);
3143 * Perform the pmap_advise() before clearing
3144 * PGA_REFERENCED in vm_page_advise(). Otherwise, a
3145 * concurrent pmap operation, such as pmap_remove(),
3146 * could clear a reference in the pmap and set
3147 * PGA_REFERENCED on the page before the pmap_advise()
3148 * had completed. Consequently, the page would appear
3149 * referenced based upon an old reference that
3150 * occurred before this pmap_advise() ran.
3152 if (behav == MADV_DONTNEED || behav == MADV_FREE)
3153 pmap_advise(map->pmap, useStart, useEnd,
3156 vm_object_madvise(entry->object.vm_object, pstart,
3160 * Pre-populate paging structures in the
3161 * WILLNEED case. For wired entries, the
3162 * paging structures are already populated.
3164 if (behav == MADV_WILLNEED &&
3165 entry->wired_count == 0) {
3166 vm_map_pmap_enter(map,
3169 entry->object.vm_object,
3171 ptoa(pend - pstart),
3172 MAP_PREFAULT_MADVISE
3176 vm_map_unlock_read(map);
3184 * Sets the inheritance of the specified address
3185 * range in the target map. Inheritance
3186 * affects how the map will be shared with
3187 * child maps at the time of vmspace_fork.
3190 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
3191 vm_inherit_t new_inheritance)
3193 vm_map_entry_t entry, lentry, prev_entry, start_entry;
3196 switch (new_inheritance) {
3197 case VM_INHERIT_NONE:
3198 case VM_INHERIT_COPY:
3199 case VM_INHERIT_SHARE:
3200 case VM_INHERIT_ZERO:
3203 return (KERN_INVALID_ARGUMENT);
3206 return (KERN_SUCCESS);
3208 VM_MAP_RANGE_CHECK(map, start, end);
3209 rv = vm_map_lookup_clip_start(map, start, &start_entry, &prev_entry);
3210 if (rv != KERN_SUCCESS)
3212 if (vm_map_lookup_entry(map, end - 1, &lentry)) {
3213 rv = vm_map_clip_end(map, lentry, end);
3214 if (rv != KERN_SUCCESS)
3217 if (new_inheritance == VM_INHERIT_COPY) {
3218 for (entry = start_entry; entry->start < end;
3219 prev_entry = entry, entry = vm_map_entry_succ(entry)) {
3220 if ((entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK)
3222 rv = KERN_INVALID_ARGUMENT;
3227 for (entry = start_entry; entry->start < end; prev_entry = entry,
3228 entry = vm_map_entry_succ(entry)) {
3229 KASSERT(entry->end <= end, ("non-clipped entry %p end %jx %jx",
3230 entry, (uintmax_t)entry->end, (uintmax_t)end));
3231 if ((entry->eflags & MAP_ENTRY_GUARD) == 0 ||
3232 new_inheritance != VM_INHERIT_ZERO)
3233 entry->inheritance = new_inheritance;
3234 vm_map_try_merge_entries(map, prev_entry, entry);
3236 vm_map_try_merge_entries(map, prev_entry, entry);
3243 * vm_map_entry_in_transition:
3245 * Release the map lock, and sleep until the entry is no longer in
3246 * transition. Awake and acquire the map lock. If the map changed while
3247 * another held the lock, lookup a possibly-changed entry at or after the
3248 * 'start' position of the old entry.
3250 static vm_map_entry_t
3251 vm_map_entry_in_transition(vm_map_t map, vm_offset_t in_start,
3252 vm_offset_t *io_end, bool holes_ok, vm_map_entry_t in_entry)
3254 vm_map_entry_t entry;
3256 u_int last_timestamp;
3258 VM_MAP_ASSERT_LOCKED(map);
3259 KASSERT((in_entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3260 ("not in-tranition map entry %p", in_entry));
3262 * We have not yet clipped the entry.
3264 start = MAX(in_start, in_entry->start);
3265 in_entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3266 last_timestamp = map->timestamp;
3267 if (vm_map_unlock_and_wait(map, 0)) {
3269 * Allow interruption of user wiring/unwiring?
3273 if (last_timestamp + 1 == map->timestamp)
3277 * Look again for the entry because the map was modified while it was
3278 * unlocked. Specifically, the entry may have been clipped, merged, or
3281 if (!vm_map_lookup_entry(map, start, &entry)) {
3286 entry = vm_map_entry_succ(entry);
3294 * Implements both kernel and user unwiring.
3297 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
3300 vm_map_entry_t entry, first_entry, next_entry, prev_entry;
3302 bool holes_ok, need_wakeup, user_unwire;
3305 return (KERN_SUCCESS);
3306 holes_ok = (flags & VM_MAP_WIRE_HOLESOK) != 0;
3307 user_unwire = (flags & VM_MAP_WIRE_USER) != 0;
3309 VM_MAP_RANGE_CHECK(map, start, end);
3310 if (!vm_map_lookup_entry(map, start, &first_entry)) {
3312 first_entry = vm_map_entry_succ(first_entry);
3315 return (KERN_INVALID_ADDRESS);
3319 for (entry = first_entry; entry->start < end; entry = next_entry) {
3320 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
3322 * We have not yet clipped the entry.
3324 next_entry = vm_map_entry_in_transition(map, start,
3325 &end, holes_ok, entry);
3326 if (next_entry == NULL) {
3327 if (entry == first_entry) {
3329 return (KERN_INVALID_ADDRESS);
3331 rv = KERN_INVALID_ADDRESS;
3334 first_entry = (entry == first_entry) ?
3338 rv = vm_map_clip_start(map, entry, start);
3339 if (rv != KERN_SUCCESS)
3341 rv = vm_map_clip_end(map, entry, end);
3342 if (rv != KERN_SUCCESS)
3346 * Mark the entry in case the map lock is released. (See
3349 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
3350 entry->wiring_thread == NULL,
3351 ("owned map entry %p", entry));
3352 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
3353 entry->wiring_thread = curthread;
3354 next_entry = vm_map_entry_succ(entry);
3356 * Check the map for holes in the specified region.
3357 * If holes_ok, skip this check.
3360 entry->end < end && next_entry->start > entry->end) {
3362 rv = KERN_INVALID_ADDRESS;
3366 * If system unwiring, require that the entry is system wired.
3369 vm_map_entry_system_wired_count(entry) == 0) {
3371 rv = KERN_INVALID_ARGUMENT;
3375 need_wakeup = false;
3376 if (first_entry == NULL &&
3377 !vm_map_lookup_entry(map, start, &first_entry)) {
3378 KASSERT(holes_ok, ("vm_map_unwire: lookup failed"));
3379 prev_entry = first_entry;
3380 entry = vm_map_entry_succ(first_entry);
3382 prev_entry = vm_map_entry_pred(first_entry);
3383 entry = first_entry;
3385 for (; entry->start < end;
3386 prev_entry = entry, entry = vm_map_entry_succ(entry)) {
3388 * If holes_ok was specified, an empty
3389 * space in the unwired region could have been mapped
3390 * while the map lock was dropped for draining
3391 * MAP_ENTRY_IN_TRANSITION. Moreover, another thread
3392 * could be simultaneously wiring this new mapping
3393 * entry. Detect these cases and skip any entries
3394 * marked as in transition by us.
3396 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
3397 entry->wiring_thread != curthread) {
3399 ("vm_map_unwire: !HOLESOK and new/changed entry"));
3403 if (rv == KERN_SUCCESS && (!user_unwire ||
3404 (entry->eflags & MAP_ENTRY_USER_WIRED))) {
3405 if (entry->wired_count == 1)
3406 vm_map_entry_unwire(map, entry);
3408 entry->wired_count--;
3410 entry->eflags &= ~MAP_ENTRY_USER_WIRED;
3412 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3413 ("vm_map_unwire: in-transition flag missing %p", entry));
3414 KASSERT(entry->wiring_thread == curthread,
3415 ("vm_map_unwire: alien wire %p", entry));
3416 entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
3417 entry->wiring_thread = NULL;
3418 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
3419 entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
3422 vm_map_try_merge_entries(map, prev_entry, entry);
3424 vm_map_try_merge_entries(map, prev_entry, entry);
3432 vm_map_wire_user_count_sub(u_long npages)
3435 atomic_subtract_long(&vm_user_wire_count, npages);
3439 vm_map_wire_user_count_add(u_long npages)
3443 wired = vm_user_wire_count;
3445 if (npages + wired > vm_page_max_user_wired)
3447 } while (!atomic_fcmpset_long(&vm_user_wire_count, &wired,
3454 * vm_map_wire_entry_failure:
3456 * Handle a wiring failure on the given entry.
3458 * The map should be locked.
3461 vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
3462 vm_offset_t failed_addr)
3465 VM_MAP_ASSERT_LOCKED(map);
3466 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 &&
3467 entry->wired_count == 1,
3468 ("vm_map_wire_entry_failure: entry %p isn't being wired", entry));
3469 KASSERT(failed_addr < entry->end,
3470 ("vm_map_wire_entry_failure: entry %p was fully wired", entry));
3473 * If any pages at the start of this entry were successfully wired,
3476 if (failed_addr > entry->start) {
3477 pmap_unwire(map->pmap, entry->start, failed_addr);
3478 vm_object_unwire(entry->object.vm_object, entry->offset,
3479 failed_addr - entry->start, PQ_ACTIVE);
3483 * Assign an out-of-range value to represent the failure to wire this
3486 entry->wired_count = -1;
3490 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3495 rv = vm_map_wire_locked(map, start, end, flags);
3501 * vm_map_wire_locked:
3503 * Implements both kernel and user wiring. Returns with the map locked,
3504 * the map lock may be dropped.
3507 vm_map_wire_locked(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3509 vm_map_entry_t entry, first_entry, next_entry, prev_entry;
3510 vm_offset_t faddr, saved_end, saved_start;
3511 u_long incr, npages;
3512 u_int bidx, last_timestamp;
3514 bool holes_ok, need_wakeup, user_wire;
3517 VM_MAP_ASSERT_LOCKED(map);
3520 return (KERN_SUCCESS);
3522 if (flags & VM_MAP_WIRE_WRITE)
3523 prot |= VM_PROT_WRITE;
3524 holes_ok = (flags & VM_MAP_WIRE_HOLESOK) != 0;
3525 user_wire = (flags & VM_MAP_WIRE_USER) != 0;
3526 VM_MAP_RANGE_CHECK(map, start, end);
3527 if (!vm_map_lookup_entry(map, start, &first_entry)) {
3529 first_entry = vm_map_entry_succ(first_entry);
3531 return (KERN_INVALID_ADDRESS);
3533 for (entry = first_entry; entry->start < end; entry = next_entry) {
3534 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
3536 * We have not yet clipped the entry.
3538 next_entry = vm_map_entry_in_transition(map, start,
3539 &end, holes_ok, entry);
3540 if (next_entry == NULL) {
3541 if (entry == first_entry)
3542 return (KERN_INVALID_ADDRESS);
3543 rv = KERN_INVALID_ADDRESS;
3546 first_entry = (entry == first_entry) ?
3550 rv = vm_map_clip_start(map, entry, start);
3551 if (rv != KERN_SUCCESS)
3553 rv = vm_map_clip_end(map, entry, end);
3554 if (rv != KERN_SUCCESS)
3558 * Mark the entry in case the map lock is released. (See
3561 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
3562 entry->wiring_thread == NULL,
3563 ("owned map entry %p", entry));
3564 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
3565 entry->wiring_thread = curthread;
3566 if ((entry->protection & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0
3567 || (entry->protection & prot) != prot) {
3568 entry->eflags |= MAP_ENTRY_WIRE_SKIPPED;
3571 rv = KERN_INVALID_ADDRESS;
3574 } else if (entry->wired_count == 0) {
3575 entry->wired_count++;
3577 npages = atop(entry->end - entry->start);
3578 if (user_wire && !vm_map_wire_user_count_add(npages)) {
3579 vm_map_wire_entry_failure(map, entry,
3582 rv = KERN_RESOURCE_SHORTAGE;
3587 * Release the map lock, relying on the in-transition
3588 * mark. Mark the map busy for fork.
3590 saved_start = entry->start;
3591 saved_end = entry->end;
3592 last_timestamp = map->timestamp;
3593 bidx = MAP_ENTRY_SPLIT_BOUNDARY_INDEX(entry);
3594 incr = pagesizes[bidx];
3598 for (faddr = saved_start; faddr < saved_end;
3601 * Simulate a fault to get the page and enter
3602 * it into the physical map.
3604 rv = vm_fault(map, faddr, VM_PROT_NONE,
3605 VM_FAULT_WIRE, NULL);
3606 if (rv != KERN_SUCCESS)
3611 if (last_timestamp + 1 != map->timestamp) {
3613 * Look again for the entry because the map was
3614 * modified while it was unlocked. The entry
3615 * may have been clipped, but NOT merged or
3618 if (!vm_map_lookup_entry(map, saved_start,
3621 ("vm_map_wire: lookup failed"));
3622 first_entry = (entry == first_entry) ?
3624 for (entry = next_entry; entry->end < saved_end;
3625 entry = vm_map_entry_succ(entry)) {
3627 * In case of failure, handle entries
3628 * that were not fully wired here;
3629 * fully wired entries are handled
3632 if (rv != KERN_SUCCESS &&
3634 vm_map_wire_entry_failure(map,
3638 if (rv != KERN_SUCCESS) {
3639 vm_map_wire_entry_failure(map, entry, faddr);
3641 vm_map_wire_user_count_sub(npages);
3645 } else if (!user_wire ||
3646 (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3647 entry->wired_count++;
3650 * Check the map for holes in the specified region.
3651 * If holes_ok was specified, skip this check.
3653 next_entry = vm_map_entry_succ(entry);
3655 entry->end < end && next_entry->start > entry->end) {
3657 rv = KERN_INVALID_ADDRESS;
3663 need_wakeup = false;
3664 if (first_entry == NULL &&
3665 !vm_map_lookup_entry(map, start, &first_entry)) {
3666 KASSERT(holes_ok, ("vm_map_wire: lookup failed"));
3667 prev_entry = first_entry;
3668 entry = vm_map_entry_succ(first_entry);
3670 prev_entry = vm_map_entry_pred(first_entry);
3671 entry = first_entry;
3673 for (; entry->start < end;
3674 prev_entry = entry, entry = vm_map_entry_succ(entry)) {
3676 * If holes_ok was specified, an empty
3677 * space in the unwired region could have been mapped
3678 * while the map lock was dropped for faulting in the
3679 * pages or draining MAP_ENTRY_IN_TRANSITION.
3680 * Moreover, another thread could be simultaneously
3681 * wiring this new mapping entry. Detect these cases
3682 * and skip any entries marked as in transition not by us.
3684 * Another way to get an entry not marked with
3685 * MAP_ENTRY_IN_TRANSITION is after failed clipping,
3686 * which set rv to KERN_INVALID_ARGUMENT.
3688 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
3689 entry->wiring_thread != curthread) {
3690 KASSERT(holes_ok || rv == KERN_INVALID_ARGUMENT,
3691 ("vm_map_wire: !HOLESOK and new/changed entry"));
3695 if ((entry->eflags & MAP_ENTRY_WIRE_SKIPPED) != 0) {
3697 } else if (rv == KERN_SUCCESS) {
3699 entry->eflags |= MAP_ENTRY_USER_WIRED;
3700 } else if (entry->wired_count == -1) {
3702 * Wiring failed on this entry. Thus, unwiring is
3705 entry->wired_count = 0;
3706 } else if (!user_wire ||
3707 (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3709 * Undo the wiring. Wiring succeeded on this entry
3710 * but failed on a later entry.
3712 if (entry->wired_count == 1) {
3713 vm_map_entry_unwire(map, entry);
3715 vm_map_wire_user_count_sub(
3716 atop(entry->end - entry->start));
3718 entry->wired_count--;
3720 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3721 ("vm_map_wire: in-transition flag missing %p", entry));
3722 KASSERT(entry->wiring_thread == curthread,
3723 ("vm_map_wire: alien wire %p", entry));
3724 entry->eflags &= ~(MAP_ENTRY_IN_TRANSITION |
3725 MAP_ENTRY_WIRE_SKIPPED);
3726 entry->wiring_thread = NULL;
3727 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
3728 entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
3731 vm_map_try_merge_entries(map, prev_entry, entry);
3733 vm_map_try_merge_entries(map, prev_entry, entry);
3742 * Push any dirty cached pages in the address range to their pager.
3743 * If syncio is TRUE, dirty pages are written synchronously.
3744 * If invalidate is TRUE, any cached pages are freed as well.
3746 * If the size of the region from start to end is zero, we are
3747 * supposed to flush all modified pages within the region containing
3748 * start. Unfortunately, a region can be split or coalesced with
3749 * neighboring regions, making it difficult to determine what the
3750 * original region was. Therefore, we approximate this requirement by
3751 * flushing the current region containing start.
3753 * Returns an error if any part of the specified range is not mapped.
3761 boolean_t invalidate)
3763 vm_map_entry_t entry, first_entry, next_entry;
3766 vm_ooffset_t offset;
3767 unsigned int last_timestamp;
3771 vm_map_lock_read(map);
3772 VM_MAP_RANGE_CHECK(map, start, end);
3773 if (!vm_map_lookup_entry(map, start, &first_entry)) {
3774 vm_map_unlock_read(map);
3775 return (KERN_INVALID_ADDRESS);
3776 } else if (start == end) {
3777 start = first_entry->start;
3778 end = first_entry->end;
3782 * Make a first pass to check for user-wired memory, holes,
3783 * and partial invalidation of largepage mappings.
3785 for (entry = first_entry; entry->start < end; entry = next_entry) {
3787 if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0) {
3788 vm_map_unlock_read(map);
3789 return (KERN_INVALID_ARGUMENT);
3791 bdry_idx = MAP_ENTRY_SPLIT_BOUNDARY_INDEX(entry);
3792 if (bdry_idx != 0 &&
3793 ((start & (pagesizes[bdry_idx] - 1)) != 0 ||
3794 (end & (pagesizes[bdry_idx] - 1)) != 0)) {
3795 vm_map_unlock_read(map);
3796 return (KERN_INVALID_ARGUMENT);
3799 next_entry = vm_map_entry_succ(entry);
3800 if (end > entry->end &&
3801 entry->end != next_entry->start) {
3802 vm_map_unlock_read(map);
3803 return (KERN_INVALID_ADDRESS);
3808 pmap_remove(map->pmap, start, end);
3812 * Make a second pass, cleaning/uncaching pages from the indicated
3815 for (entry = first_entry; entry->start < end;) {
3816 offset = entry->offset + (start - entry->start);
3817 size = (end <= entry->end ? end : entry->end) - start;
3818 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0) {
3820 vm_map_entry_t tentry;
3823 smap = entry->object.sub_map;
3824 vm_map_lock_read(smap);
3825 (void) vm_map_lookup_entry(smap, offset, &tentry);
3826 tsize = tentry->end - offset;
3829 object = tentry->object.vm_object;
3830 offset = tentry->offset + (offset - tentry->start);
3831 vm_map_unlock_read(smap);
3833 object = entry->object.vm_object;
3835 vm_object_reference(object);
3836 last_timestamp = map->timestamp;
3837 vm_map_unlock_read(map);
3838 if (!vm_object_sync(object, offset, size, syncio, invalidate))
3841 vm_object_deallocate(object);
3842 vm_map_lock_read(map);
3843 if (last_timestamp == map->timestamp ||
3844 !vm_map_lookup_entry(map, start, &entry))
3845 entry = vm_map_entry_succ(entry);
3848 vm_map_unlock_read(map);
3849 return (failed ? KERN_FAILURE : KERN_SUCCESS);
3853 * vm_map_entry_unwire: [ internal use only ]
3855 * Make the region specified by this entry pageable.
3857 * The map in question should be locked.
3858 * [This is the reason for this routine's existence.]
3861 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
3865 VM_MAP_ASSERT_LOCKED(map);
3866 KASSERT(entry->wired_count > 0,
3867 ("vm_map_entry_unwire: entry %p isn't wired", entry));
3869 size = entry->end - entry->start;
3870 if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0)
3871 vm_map_wire_user_count_sub(atop(size));
3872 pmap_unwire(map->pmap, entry->start, entry->end);
3873 vm_object_unwire(entry->object.vm_object, entry->offset, size,
3875 entry->wired_count = 0;
3879 vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map)
3882 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
3883 vm_object_deallocate(entry->object.vm_object);
3884 uma_zfree(system_map ? kmapentzone : mapentzone, entry);
3888 * vm_map_entry_delete: [ internal use only ]
3890 * Deallocate the given entry from the target map.
3893 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
3896 vm_pindex_t offidxstart, offidxend, size1;
3899 vm_map_entry_unlink(map, entry, UNLINK_MERGE_NONE);
3900 object = entry->object.vm_object;
3902 if ((entry->eflags & MAP_ENTRY_GUARD) != 0) {
3903 MPASS(entry->cred == NULL);
3904 MPASS((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0);
3905 MPASS(object == NULL);
3906 vm_map_entry_deallocate(entry, map->system_map);
3910 size = entry->end - entry->start;
3913 if (entry->cred != NULL) {
3914 swap_release_by_cred(size, entry->cred);
3915 crfree(entry->cred);
3918 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 || object == NULL) {
3919 entry->object.vm_object = NULL;
3920 } else if ((object->flags & OBJ_ANON) != 0 ||
3921 object == kernel_object) {
3922 KASSERT(entry->cred == NULL || object->cred == NULL ||
3923 (entry->eflags & MAP_ENTRY_NEEDS_COPY),
3924 ("OVERCOMMIT vm_map_entry_delete: both cred %p", entry));
3925 offidxstart = OFF_TO_IDX(entry->offset);
3926 offidxend = offidxstart + atop(size);
3927 VM_OBJECT_WLOCK(object);
3928 if (object->ref_count != 1 &&
3929 ((object->flags & OBJ_ONEMAPPING) != 0 ||
3930 object == kernel_object)) {
3931 vm_object_collapse(object);
3934 * The option OBJPR_NOTMAPPED can be passed here
3935 * because vm_map_delete() already performed
3936 * pmap_remove() on the only mapping to this range
3939 vm_object_page_remove(object, offidxstart, offidxend,
3941 if (offidxend >= object->size &&
3942 offidxstart < object->size) {
3943 size1 = object->size;
3944 object->size = offidxstart;
3945 if (object->cred != NULL) {
3946 size1 -= object->size;
3947 KASSERT(object->charge >= ptoa(size1),
3948 ("object %p charge < 0", object));
3949 swap_release_by_cred(ptoa(size1),
3951 object->charge -= ptoa(size1);
3955 VM_OBJECT_WUNLOCK(object);
3957 if (map->system_map)
3958 vm_map_entry_deallocate(entry, TRUE);
3960 entry->defer_next = curthread->td_map_def_user;
3961 curthread->td_map_def_user = entry;
3966 * vm_map_delete: [ internal use only ]
3968 * Deallocates the given address range from the target
3972 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
3974 vm_map_entry_t entry, next_entry, scratch_entry;
3977 VM_MAP_ASSERT_LOCKED(map);
3980 return (KERN_SUCCESS);
3983 * Find the start of the region, and clip it.
3984 * Step through all entries in this region.
3986 rv = vm_map_lookup_clip_start(map, start, &entry, &scratch_entry);
3987 if (rv != KERN_SUCCESS)
3989 for (; entry->start < end; entry = next_entry) {
3991 * Wait for wiring or unwiring of an entry to complete.
3992 * Also wait for any system wirings to disappear on
3995 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
3996 (vm_map_pmap(map) != kernel_pmap &&
3997 vm_map_entry_system_wired_count(entry) != 0)) {
3998 unsigned int last_timestamp;
3999 vm_offset_t saved_start;
4001 saved_start = entry->start;
4002 entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
4003 last_timestamp = map->timestamp;
4004 (void) vm_map_unlock_and_wait(map, 0);
4006 if (last_timestamp + 1 != map->timestamp) {
4008 * Look again for the entry because the map was
4009 * modified while it was unlocked.
4010 * Specifically, the entry may have been
4011 * clipped, merged, or deleted.
4013 rv = vm_map_lookup_clip_start(map, saved_start,
4014 &next_entry, &scratch_entry);
4015 if (rv != KERN_SUCCESS)
4022 /* XXXKIB or delete to the upper superpage boundary ? */
4023 rv = vm_map_clip_end(map, entry, end);
4024 if (rv != KERN_SUCCESS)
4026 next_entry = vm_map_entry_succ(entry);
4029 * Unwire before removing addresses from the pmap; otherwise,
4030 * unwiring will put the entries back in the pmap.
4032 if (entry->wired_count != 0)
4033 vm_map_entry_unwire(map, entry);
4036 * Remove mappings for the pages, but only if the
4037 * mappings could exist. For instance, it does not
4038 * make sense to call pmap_remove() for guard entries.
4040 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 ||
4041 entry->object.vm_object != NULL)
4042 pmap_map_delete(map->pmap, entry->start, entry->end);
4044 if (entry->end == map->anon_loc)
4045 map->anon_loc = entry->start;
4048 * Delete the entry only after removing all pmap
4049 * entries pointing to its pages. (Otherwise, its
4050 * page frames may be reallocated, and any modify bits
4051 * will be set in the wrong object!)
4053 vm_map_entry_delete(map, entry);
4061 * Remove the given address range from the target map.
4062 * This is the exported form of vm_map_delete.
4065 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
4070 VM_MAP_RANGE_CHECK(map, start, end);
4071 result = vm_map_delete(map, start, end);
4077 * vm_map_check_protection:
4079 * Assert that the target map allows the specified privilege on the
4080 * entire address region given. The entire region must be allocated.
4082 * WARNING! This code does not and should not check whether the
4083 * contents of the region is accessible. For example a smaller file
4084 * might be mapped into a larger address space.
4086 * NOTE! This code is also called by munmap().
4088 * The map must be locked. A read lock is sufficient.
4091 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
4092 vm_prot_t protection)
4094 vm_map_entry_t entry;
4095 vm_map_entry_t tmp_entry;
4097 if (!vm_map_lookup_entry(map, start, &tmp_entry))
4101 while (start < end) {
4105 if (start < entry->start)
4108 * Check protection associated with entry.
4110 if ((entry->protection & protection) != protection)
4112 /* go to next entry */
4114 entry = vm_map_entry_succ(entry);
4121 * vm_map_copy_swap_object:
4123 * Copies a swap-backed object from an existing map entry to a
4124 * new one. Carries forward the swap charge. May change the
4125 * src object on return.
4128 vm_map_copy_swap_object(vm_map_entry_t src_entry, vm_map_entry_t dst_entry,
4129 vm_offset_t size, vm_ooffset_t *fork_charge)
4131 vm_object_t src_object;
4135 src_object = src_entry->object.vm_object;
4136 charged = ENTRY_CHARGED(src_entry);
4137 if ((src_object->flags & OBJ_ANON) != 0) {
4138 VM_OBJECT_WLOCK(src_object);
4139 vm_object_collapse(src_object);
4140 if ((src_object->flags & OBJ_ONEMAPPING) != 0) {
4141 vm_object_split(src_entry);
4142 src_object = src_entry->object.vm_object;
4144 vm_object_reference_locked(src_object);
4145 vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
4146 VM_OBJECT_WUNLOCK(src_object);
4148 vm_object_reference(src_object);
4149 if (src_entry->cred != NULL &&
4150 !(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
4151 KASSERT(src_object->cred == NULL,
4152 ("OVERCOMMIT: vm_map_copy_anon_entry: cred %p",
4154 src_object->cred = src_entry->cred;
4155 src_object->charge = size;
4157 dst_entry->object.vm_object = src_object;
4159 cred = curthread->td_ucred;
4161 dst_entry->cred = cred;
4162 *fork_charge += size;
4163 if (!(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
4165 src_entry->cred = cred;
4166 *fork_charge += size;
4172 * vm_map_copy_entry:
4174 * Copies the contents of the source entry to the destination
4175 * entry. The entries *must* be aligned properly.
4181 vm_map_entry_t src_entry,
4182 vm_map_entry_t dst_entry,
4183 vm_ooffset_t *fork_charge)
4185 vm_object_t src_object;
4186 vm_map_entry_t fake_entry;
4189 VM_MAP_ASSERT_LOCKED(dst_map);
4191 if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
4194 if (src_entry->wired_count == 0 ||
4195 (src_entry->protection & VM_PROT_WRITE) == 0) {
4197 * If the source entry is marked needs_copy, it is already
4200 if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0 &&
4201 (src_entry->protection & VM_PROT_WRITE) != 0) {
4202 pmap_protect(src_map->pmap,
4205 src_entry->protection & ~VM_PROT_WRITE);
4209 * Make a copy of the object.
4211 size = src_entry->end - src_entry->start;
4212 if ((src_object = src_entry->object.vm_object) != NULL) {
4213 if ((src_object->flags & OBJ_SWAP) != 0) {
4214 vm_map_copy_swap_object(src_entry, dst_entry,
4216 /* May have split/collapsed, reload obj. */
4217 src_object = src_entry->object.vm_object;
4219 vm_object_reference(src_object);
4220 dst_entry->object.vm_object = src_object;
4222 src_entry->eflags |= MAP_ENTRY_COW |
4223 MAP_ENTRY_NEEDS_COPY;
4224 dst_entry->eflags |= MAP_ENTRY_COW |
4225 MAP_ENTRY_NEEDS_COPY;
4226 dst_entry->offset = src_entry->offset;
4227 if (src_entry->eflags & MAP_ENTRY_WRITECNT) {
4229 * MAP_ENTRY_WRITECNT cannot
4230 * indicate write reference from
4231 * src_entry, since the entry is
4232 * marked as needs copy. Allocate a
4233 * fake entry that is used to
4234 * decrement object->un_pager writecount
4235 * at the appropriate time. Attach
4236 * fake_entry to the deferred list.
4238 fake_entry = vm_map_entry_create(dst_map);
4239 fake_entry->eflags = MAP_ENTRY_WRITECNT;
4240 src_entry->eflags &= ~MAP_ENTRY_WRITECNT;
4241 vm_object_reference(src_object);
4242 fake_entry->object.vm_object = src_object;
4243 fake_entry->start = src_entry->start;
4244 fake_entry->end = src_entry->end;
4245 fake_entry->defer_next =
4246 curthread->td_map_def_user;
4247 curthread->td_map_def_user = fake_entry;
4250 pmap_copy(dst_map->pmap, src_map->pmap,
4251 dst_entry->start, dst_entry->end - dst_entry->start,
4254 dst_entry->object.vm_object = NULL;
4255 if ((dst_entry->eflags & MAP_ENTRY_GUARD) == 0)
4256 dst_entry->offset = 0;
4257 if (src_entry->cred != NULL) {
4258 dst_entry->cred = curthread->td_ucred;
4259 crhold(dst_entry->cred);
4260 *fork_charge += size;
4265 * We don't want to make writeable wired pages copy-on-write.
4266 * Immediately copy these pages into the new map by simulating
4267 * page faults. The new pages are pageable.
4269 vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry,
4275 * vmspace_map_entry_forked:
4276 * Update the newly-forked vmspace each time a map entry is inherited
4277 * or copied. The values for vm_dsize and vm_tsize are approximate
4278 * (and mostly-obsolete ideas in the face of mmap(2) et al.)
4281 vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
4282 vm_map_entry_t entry)
4284 vm_size_t entrysize;
4287 if ((entry->eflags & MAP_ENTRY_GUARD) != 0)
4289 entrysize = entry->end - entry->start;
4290 vm2->vm_map.size += entrysize;
4291 if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
4292 vm2->vm_ssize += btoc(entrysize);
4293 } else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
4294 entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
4295 newend = MIN(entry->end,
4296 (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
4297 vm2->vm_dsize += btoc(newend - entry->start);
4298 } else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
4299 entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
4300 newend = MIN(entry->end,
4301 (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
4302 vm2->vm_tsize += btoc(newend - entry->start);
4308 * Create a new process vmspace structure and vm_map
4309 * based on those of an existing process. The new map
4310 * is based on the old map, according to the inheritance
4311 * values on the regions in that map.
4313 * XXX It might be worth coalescing the entries added to the new vmspace.
4315 * The source map must not be locked.
4318 vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
4320 struct vmspace *vm2;
4321 vm_map_t new_map, old_map;
4322 vm_map_entry_t new_entry, old_entry;
4324 int error, locked __diagused;
4327 old_map = &vm1->vm_map;
4328 /* Copy immutable fields of vm1 to vm2. */
4329 vm2 = vmspace_alloc(vm_map_min(old_map), vm_map_max(old_map),
4334 vm2->vm_taddr = vm1->vm_taddr;
4335 vm2->vm_daddr = vm1->vm_daddr;
4336 vm2->vm_maxsaddr = vm1->vm_maxsaddr;
4337 vm2->vm_stacktop = vm1->vm_stacktop;
4338 vm2->vm_shp_base = vm1->vm_shp_base;
4339 vm_map_lock(old_map);
4341 vm_map_wait_busy(old_map);
4342 new_map = &vm2->vm_map;
4343 locked = vm_map_trylock(new_map); /* trylock to silence WITNESS */
4344 KASSERT(locked, ("vmspace_fork: lock failed"));
4346 error = pmap_vmspace_copy(new_map->pmap, old_map->pmap);
4348 sx_xunlock(&old_map->lock);
4349 sx_xunlock(&new_map->lock);
4350 vm_map_process_deferred();
4355 new_map->anon_loc = old_map->anon_loc;
4356 new_map->flags |= old_map->flags & (MAP_ASLR | MAP_ASLR_IGNSTART |
4357 MAP_ASLR_STACK | MAP_WXORX);
4359 VM_MAP_ENTRY_FOREACH(old_entry, old_map) {
4360 if ((old_entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
4361 panic("vm_map_fork: encountered a submap");
4363 inh = old_entry->inheritance;
4364 if ((old_entry->eflags & MAP_ENTRY_GUARD) != 0 &&
4365 inh != VM_INHERIT_NONE)
4366 inh = VM_INHERIT_COPY;
4369 case VM_INHERIT_NONE:
4372 case VM_INHERIT_SHARE:
4374 * Clone the entry, creating the shared object if
4377 object = old_entry->object.vm_object;
4378 if (object == NULL) {
4379 vm_map_entry_back(old_entry);
4380 object = old_entry->object.vm_object;
4384 * Add the reference before calling vm_object_shadow
4385 * to insure that a shadow object is created.
4387 vm_object_reference(object);
4388 if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4389 vm_object_shadow(&old_entry->object.vm_object,
4391 old_entry->end - old_entry->start,
4393 /* Transfer the second reference too. */
4395 old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
4396 old_entry->cred = NULL;
4399 * As in vm_map_merged_neighbor_dispose(),
4400 * the vnode lock will not be acquired in
4401 * this call to vm_object_deallocate().
4403 vm_object_deallocate(object);
4404 object = old_entry->object.vm_object;
4406 VM_OBJECT_WLOCK(object);
4407 vm_object_clear_flag(object, OBJ_ONEMAPPING);
4408 if (old_entry->cred != NULL) {
4409 KASSERT(object->cred == NULL,
4410 ("vmspace_fork both cred"));
4411 object->cred = old_entry->cred;
4412 object->charge = old_entry->end -
4414 old_entry->cred = NULL;
4418 * Assert the correct state of the vnode
4419 * v_writecount while the object is locked, to
4420 * not relock it later for the assertion
4423 if (old_entry->eflags & MAP_ENTRY_WRITECNT &&
4424 object->type == OBJT_VNODE) {
4425 KASSERT(((struct vnode *)object->
4426 handle)->v_writecount > 0,
4427 ("vmspace_fork: v_writecount %p",
4429 KASSERT(object->un_pager.vnp.
4431 ("vmspace_fork: vnp.writecount %p",
4434 VM_OBJECT_WUNLOCK(object);
4438 * Clone the entry, referencing the shared object.
4440 new_entry = vm_map_entry_create(new_map);
4441 *new_entry = *old_entry;
4442 new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
4443 MAP_ENTRY_IN_TRANSITION);
4444 new_entry->wiring_thread = NULL;
4445 new_entry->wired_count = 0;
4446 if (new_entry->eflags & MAP_ENTRY_WRITECNT) {
4447 vm_pager_update_writecount(object,
4448 new_entry->start, new_entry->end);
4450 vm_map_entry_set_vnode_text(new_entry, true);
4453 * Insert the entry into the new map -- we know we're
4454 * inserting at the end of the new map.
4456 vm_map_entry_link(new_map, new_entry);
4457 vmspace_map_entry_forked(vm1, vm2, new_entry);
4460 * Update the physical map
4462 pmap_copy(new_map->pmap, old_map->pmap,
4464 (old_entry->end - old_entry->start),
4468 case VM_INHERIT_COPY:
4470 * Clone the entry and link into the map.
4472 new_entry = vm_map_entry_create(new_map);
4473 *new_entry = *old_entry;
4475 * Copied entry is COW over the old object.
4477 new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
4478 MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_WRITECNT);
4479 new_entry->wiring_thread = NULL;
4480 new_entry->wired_count = 0;
4481 new_entry->object.vm_object = NULL;
4482 new_entry->cred = NULL;
4483 vm_map_entry_link(new_map, new_entry);
4484 vmspace_map_entry_forked(vm1, vm2, new_entry);
4485 vm_map_copy_entry(old_map, new_map, old_entry,
4486 new_entry, fork_charge);
4487 vm_map_entry_set_vnode_text(new_entry, true);
4490 case VM_INHERIT_ZERO:
4492 * Create a new anonymous mapping entry modelled from
4495 new_entry = vm_map_entry_create(new_map);
4496 memset(new_entry, 0, sizeof(*new_entry));
4498 new_entry->start = old_entry->start;
4499 new_entry->end = old_entry->end;
4500 new_entry->eflags = old_entry->eflags &
4501 ~(MAP_ENTRY_USER_WIRED | MAP_ENTRY_IN_TRANSITION |
4502 MAP_ENTRY_WRITECNT | MAP_ENTRY_VN_EXEC |
4503 MAP_ENTRY_SPLIT_BOUNDARY_MASK);
4504 new_entry->protection = old_entry->protection;
4505 new_entry->max_protection = old_entry->max_protection;
4506 new_entry->inheritance = VM_INHERIT_ZERO;
4508 vm_map_entry_link(new_map, new_entry);
4509 vmspace_map_entry_forked(vm1, vm2, new_entry);
4511 new_entry->cred = curthread->td_ucred;
4512 crhold(new_entry->cred);
4513 *fork_charge += (new_entry->end - new_entry->start);
4519 * Use inlined vm_map_unlock() to postpone handling the deferred
4520 * map entries, which cannot be done until both old_map and
4521 * new_map locks are released.
4523 sx_xunlock(&old_map->lock);
4524 sx_xunlock(&new_map->lock);
4525 vm_map_process_deferred();
4531 * Create a process's stack for exec_new_vmspace(). This function is never
4532 * asked to wire the newly created stack.
4535 vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4536 vm_prot_t prot, vm_prot_t max, int cow)
4538 vm_size_t growsize, init_ssize;
4542 MPASS((map->flags & MAP_WIREFUTURE) == 0);
4543 growsize = sgrowsiz;
4544 init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
4546 vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4547 /* If we would blow our VMEM resource limit, no go */
4548 if (map->size + init_ssize > vmemlim) {
4552 rv = vm_map_stack_locked(map, addrbos, max_ssize, growsize, prot,
4559 static int stack_guard_page = 1;
4560 SYSCTL_INT(_security_bsd, OID_AUTO, stack_guard_page, CTLFLAG_RWTUN,
4561 &stack_guard_page, 0,
4562 "Specifies the number of guard pages for a stack that grows");
4565 vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4566 vm_size_t growsize, vm_prot_t prot, vm_prot_t max, int cow)
4568 vm_map_entry_t gap_entry, new_entry, prev_entry;
4569 vm_offset_t bot, gap_bot, gap_top, top;
4570 vm_size_t init_ssize, sgp;
4574 * The stack orientation is piggybacked with the cow argument.
4575 * Extract it into orient and mask the cow argument so that we
4576 * don't pass it around further.
4578 orient = cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP);
4579 KASSERT(orient != 0, ("No stack grow direction"));
4580 KASSERT(orient != (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP),
4583 if (max_ssize == 0 ||
4584 !vm_map_range_valid(map, addrbos, addrbos + max_ssize))
4585 return (KERN_INVALID_ADDRESS);
4586 sgp = ((curproc->p_flag2 & P2_STKGAP_DISABLE) != 0 ||
4587 (curproc->p_fctl0 & NT_FREEBSD_FCTL_STKGAP_DISABLE) != 0) ? 0 :
4588 (vm_size_t)stack_guard_page * PAGE_SIZE;
4589 if (sgp >= max_ssize)
4590 return (KERN_INVALID_ARGUMENT);
4592 init_ssize = growsize;
4593 if (max_ssize < init_ssize + sgp)
4594 init_ssize = max_ssize - sgp;
4596 /* If addr is already mapped, no go */
4597 if (vm_map_lookup_entry(map, addrbos, &prev_entry))
4598 return (KERN_NO_SPACE);
4601 * If we can't accommodate max_ssize in the current mapping, no go.
4603 if (vm_map_entry_succ(prev_entry)->start < addrbos + max_ssize)
4604 return (KERN_NO_SPACE);
4607 * We initially map a stack of only init_ssize. We will grow as
4608 * needed later. Depending on the orientation of the stack (i.e.
4609 * the grow direction) we either map at the top of the range, the
4610 * bottom of the range or in the middle.
4612 * Note: we would normally expect prot and max to be VM_PROT_ALL,
4613 * and cow to be 0. Possibly we should eliminate these as input
4614 * parameters, and just pass these values here in the insert call.
4616 if (orient == MAP_STACK_GROWS_DOWN) {
4617 bot = addrbos + max_ssize - init_ssize;
4618 top = bot + init_ssize;
4621 } else /* if (orient == MAP_STACK_GROWS_UP) */ {
4623 top = bot + init_ssize;
4625 gap_top = addrbos + max_ssize;
4627 rv = vm_map_insert1(map, NULL, 0, bot, top, prot, max, cow,
4629 if (rv != KERN_SUCCESS)
4631 KASSERT(new_entry->end == top || new_entry->start == bot,
4632 ("Bad entry start/end for new stack entry"));
4633 KASSERT((orient & MAP_STACK_GROWS_DOWN) == 0 ||
4634 (new_entry->eflags & MAP_ENTRY_GROWS_DOWN) != 0,
4635 ("new entry lacks MAP_ENTRY_GROWS_DOWN"));
4636 KASSERT((orient & MAP_STACK_GROWS_UP) == 0 ||
4637 (new_entry->eflags & MAP_ENTRY_GROWS_UP) != 0,
4638 ("new entry lacks MAP_ENTRY_GROWS_UP"));
4639 if (gap_bot == gap_top)
4640 return (KERN_SUCCESS);
4641 rv = vm_map_insert1(map, NULL, 0, gap_bot, gap_top, VM_PROT_NONE,
4642 VM_PROT_NONE, MAP_CREATE_GUARD | (orient == MAP_STACK_GROWS_DOWN ?
4643 MAP_CREATE_STACK_GAP_DN : MAP_CREATE_STACK_GAP_UP), &gap_entry);
4644 if (rv == KERN_SUCCESS) {
4645 KASSERT((gap_entry->eflags & MAP_ENTRY_GUARD) != 0,
4646 ("entry %p not gap %#x", gap_entry, gap_entry->eflags));
4647 KASSERT((gap_entry->eflags & (MAP_ENTRY_STACK_GAP_DN |
4648 MAP_ENTRY_STACK_GAP_UP)) != 0,
4649 ("entry %p not stack gap %#x", gap_entry,
4650 gap_entry->eflags));
4653 * Gap can never successfully handle a fault, so
4654 * read-ahead logic is never used for it. Re-use
4655 * next_read of the gap entry to store
4656 * stack_guard_page for vm_map_growstack().
4657 * Similarly, since a gap cannot have a backing object,
4658 * store the original stack protections in the
4661 gap_entry->next_read = sgp;
4662 gap_entry->offset = prot | PROT_MAX(max);
4664 (void)vm_map_delete(map, bot, top);
4670 * Attempts to grow a vm stack entry. Returns KERN_SUCCESS if we
4671 * successfully grow the stack.
4674 vm_map_growstack(vm_map_t map, vm_offset_t addr, vm_map_entry_t gap_entry)
4676 vm_map_entry_t stack_entry;
4680 vm_offset_t gap_end, gap_start, grow_start;
4681 vm_size_t grow_amount, guard, max_grow, sgp;
4682 vm_prot_t prot, max;
4683 rlim_t lmemlim, stacklim, vmemlim;
4684 int rv, rv1 __diagused;
4685 bool gap_deleted, grow_down, is_procstack;
4690 int error __diagused;
4697 * Disallow stack growth when the access is performed by a
4698 * debugger or AIO daemon. The reason is that the wrong
4699 * resource limits are applied.
4701 if (p != initproc && (map != &p->p_vmspace->vm_map ||
4702 p->p_textvp == NULL))
4703 return (KERN_FAILURE);
4705 MPASS(!map->system_map);
4707 lmemlim = lim_cur(curthread, RLIMIT_MEMLOCK);
4708 stacklim = lim_cur(curthread, RLIMIT_STACK);
4709 vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4711 /* If addr is not in a hole for a stack grow area, no need to grow. */
4712 if (gap_entry == NULL && !vm_map_lookup_entry(map, addr, &gap_entry))
4713 return (KERN_FAILURE);
4714 if ((gap_entry->eflags & MAP_ENTRY_GUARD) == 0)
4715 return (KERN_SUCCESS);
4716 if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_DN) != 0) {
4717 stack_entry = vm_map_entry_succ(gap_entry);
4718 if ((stack_entry->eflags & MAP_ENTRY_GROWS_DOWN) == 0 ||
4719 stack_entry->start != gap_entry->end)
4720 return (KERN_FAILURE);
4721 grow_amount = round_page(stack_entry->start - addr);
4723 } else if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_UP) != 0) {
4724 stack_entry = vm_map_entry_pred(gap_entry);
4725 if ((stack_entry->eflags & MAP_ENTRY_GROWS_UP) == 0 ||
4726 stack_entry->end != gap_entry->start)
4727 return (KERN_FAILURE);
4728 grow_amount = round_page(addr + 1 - stack_entry->end);
4731 return (KERN_FAILURE);
4733 guard = ((curproc->p_flag2 & P2_STKGAP_DISABLE) != 0 ||
4734 (curproc->p_fctl0 & NT_FREEBSD_FCTL_STKGAP_DISABLE) != 0) ? 0 :
4735 gap_entry->next_read;
4736 max_grow = gap_entry->end - gap_entry->start;
4737 if (guard > max_grow)
4738 return (KERN_NO_SPACE);
4740 if (grow_amount > max_grow)
4741 return (KERN_NO_SPACE);
4744 * If this is the main process stack, see if we're over the stack
4747 is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr &&
4748 addr < (vm_offset_t)vm->vm_stacktop;
4749 if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim))
4750 return (KERN_NO_SPACE);
4755 if (is_procstack && racct_set(p, RACCT_STACK,
4756 ctob(vm->vm_ssize) + grow_amount)) {
4758 return (KERN_NO_SPACE);
4764 grow_amount = roundup(grow_amount, sgrowsiz);
4765 if (grow_amount > max_grow)
4766 grow_amount = max_grow;
4767 if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
4768 grow_amount = trunc_page((vm_size_t)stacklim) -
4774 limit = racct_get_available(p, RACCT_STACK);
4776 if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > limit))
4777 grow_amount = limit - ctob(vm->vm_ssize);
4780 if (!old_mlock && (map->flags & MAP_WIREFUTURE) != 0) {
4781 if (ptoa(pmap_wired_count(map->pmap)) + grow_amount > lmemlim) {
4788 if (racct_set(p, RACCT_MEMLOCK,
4789 ptoa(pmap_wired_count(map->pmap)) + grow_amount)) {
4799 /* If we would blow our VMEM resource limit, no go */
4800 if (map->size + grow_amount > vmemlim) {
4807 if (racct_set(p, RACCT_VMEM, map->size + grow_amount)) {
4816 if (vm_map_lock_upgrade(map)) {
4818 vm_map_lock_read(map);
4824 * The gap_entry "offset" field is overloaded. See
4825 * vm_map_stack_locked().
4827 prot = PROT_EXTRACT(gap_entry->offset);
4828 max = PROT_MAX_EXTRACT(gap_entry->offset);
4829 sgp = gap_entry->next_read;
4831 grow_start = gap_entry->end - grow_amount;
4832 if (gap_entry->start + grow_amount == gap_entry->end) {
4833 gap_start = gap_entry->start;
4834 gap_end = gap_entry->end;
4835 vm_map_entry_delete(map, gap_entry);
4838 MPASS(gap_entry->start < gap_entry->end - grow_amount);
4839 vm_map_entry_resize(map, gap_entry, -grow_amount);
4840 gap_deleted = false;
4842 rv = vm_map_insert(map, NULL, 0, grow_start,
4843 grow_start + grow_amount, prot, max, MAP_STACK_GROWS_DOWN);
4844 if (rv != KERN_SUCCESS) {
4846 rv1 = vm_map_insert1(map, NULL, 0, gap_start,
4847 gap_end, VM_PROT_NONE, VM_PROT_NONE,
4848 MAP_CREATE_GUARD | MAP_CREATE_STACK_GAP_DN,
4850 MPASS(rv1 == KERN_SUCCESS);
4851 gap_entry->next_read = sgp;
4852 gap_entry->offset = prot | PROT_MAX(max);
4854 vm_map_entry_resize(map, gap_entry,
4858 grow_start = stack_entry->end;
4859 cred = stack_entry->cred;
4860 if (cred == NULL && stack_entry->object.vm_object != NULL)
4861 cred = stack_entry->object.vm_object->cred;
4862 if (cred != NULL && !swap_reserve_by_cred(grow_amount, cred))
4864 /* Grow the underlying object if applicable. */
4865 else if (stack_entry->object.vm_object == NULL ||
4866 vm_object_coalesce(stack_entry->object.vm_object,
4867 stack_entry->offset,
4868 (vm_size_t)(stack_entry->end - stack_entry->start),
4869 grow_amount, cred != NULL)) {
4870 if (gap_entry->start + grow_amount == gap_entry->end) {
4871 vm_map_entry_delete(map, gap_entry);
4872 vm_map_entry_resize(map, stack_entry,
4875 gap_entry->start += grow_amount;
4876 stack_entry->end += grow_amount;
4878 map->size += grow_amount;
4883 if (rv == KERN_SUCCESS && is_procstack)
4884 vm->vm_ssize += btoc(grow_amount);
4887 * Heed the MAP_WIREFUTURE flag if it was set for this process.
4889 if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE) != 0) {
4890 rv = vm_map_wire_locked(map, grow_start,
4891 grow_start + grow_amount,
4892 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
4894 vm_map_lock_downgrade(map);
4898 if (racct_enable && rv != KERN_SUCCESS) {
4900 error = racct_set(p, RACCT_VMEM, map->size);
4901 KASSERT(error == 0, ("decreasing RACCT_VMEM failed"));
4903 error = racct_set(p, RACCT_MEMLOCK,
4904 ptoa(pmap_wired_count(map->pmap)));
4905 KASSERT(error == 0, ("decreasing RACCT_MEMLOCK failed"));
4907 error = racct_set(p, RACCT_STACK, ctob(vm->vm_ssize));
4908 KASSERT(error == 0, ("decreasing RACCT_STACK failed"));
4917 * Unshare the specified VM space for exec. If other processes are
4918 * mapped to it, then create a new one. The new vmspace is null.
4921 vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
4923 struct vmspace *oldvmspace = p->p_vmspace;
4924 struct vmspace *newvmspace;
4926 KASSERT((curthread->td_pflags & TDP_EXECVMSPC) == 0,
4927 ("vmspace_exec recursed"));
4928 newvmspace = vmspace_alloc(minuser, maxuser, pmap_pinit);
4929 if (newvmspace == NULL)
4931 newvmspace->vm_swrss = oldvmspace->vm_swrss;
4933 * This code is written like this for prototype purposes. The
4934 * goal is to avoid running down the vmspace here, but let the
4935 * other process's that are still using the vmspace to finally
4936 * run it down. Even though there is little or no chance of blocking
4937 * here, it is a good idea to keep this form for future mods.
4939 PROC_VMSPACE_LOCK(p);
4940 p->p_vmspace = newvmspace;
4941 PROC_VMSPACE_UNLOCK(p);
4942 if (p == curthread->td_proc)
4943 pmap_activate(curthread);
4944 curthread->td_pflags |= TDP_EXECVMSPC;
4949 * Unshare the specified VM space for forcing COW. This
4950 * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
4953 vmspace_unshare(struct proc *p)
4955 struct vmspace *oldvmspace = p->p_vmspace;
4956 struct vmspace *newvmspace;
4957 vm_ooffset_t fork_charge;
4960 * The caller is responsible for ensuring that the reference count
4961 * cannot concurrently transition 1 -> 2.
4963 if (refcount_load(&oldvmspace->vm_refcnt) == 1)
4966 newvmspace = vmspace_fork(oldvmspace, &fork_charge);
4967 if (newvmspace == NULL)
4969 if (!swap_reserve_by_cred(fork_charge, p->p_ucred)) {
4970 vmspace_free(newvmspace);
4973 PROC_VMSPACE_LOCK(p);
4974 p->p_vmspace = newvmspace;
4975 PROC_VMSPACE_UNLOCK(p);
4976 if (p == curthread->td_proc)
4977 pmap_activate(curthread);
4978 vmspace_free(oldvmspace);
4985 * Finds the VM object, offset, and
4986 * protection for a given virtual address in the
4987 * specified map, assuming a page fault of the
4990 * Leaves the map in question locked for read; return
4991 * values are guaranteed until a vm_map_lookup_done
4992 * call is performed. Note that the map argument
4993 * is in/out; the returned map must be used in
4994 * the call to vm_map_lookup_done.
4996 * A handle (out_entry) is returned for use in
4997 * vm_map_lookup_done, to make that fast.
4999 * If a lookup is requested with "write protection"
5000 * specified, the map may be changed to perform virtual
5001 * copying operations, although the data referenced will
5005 vm_map_lookup(vm_map_t *var_map, /* IN/OUT */
5007 vm_prot_t fault_typea,
5008 vm_map_entry_t *out_entry, /* OUT */
5009 vm_object_t *object, /* OUT */
5010 vm_pindex_t *pindex, /* OUT */
5011 vm_prot_t *out_prot, /* OUT */
5012 boolean_t *wired) /* OUT */
5014 vm_map_entry_t entry;
5015 vm_map_t map = *var_map;
5017 vm_prot_t fault_type;
5018 vm_object_t eobject;
5024 vm_map_lock_read(map);
5028 * Lookup the faulting address.
5030 if (!vm_map_lookup_entry(map, vaddr, out_entry)) {
5031 vm_map_unlock_read(map);
5032 return (KERN_INVALID_ADDRESS);
5040 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
5041 vm_map_t old_map = map;
5043 *var_map = map = entry->object.sub_map;
5044 vm_map_unlock_read(old_map);
5049 * Check whether this task is allowed to have this page.
5051 prot = entry->protection;
5052 if ((fault_typea & VM_PROT_FAULT_LOOKUP) != 0) {
5053 fault_typea &= ~VM_PROT_FAULT_LOOKUP;
5054 if (prot == VM_PROT_NONE && map != kernel_map &&
5055 (entry->eflags & MAP_ENTRY_GUARD) != 0 &&
5056 (entry->eflags & (MAP_ENTRY_STACK_GAP_DN |
5057 MAP_ENTRY_STACK_GAP_UP)) != 0 &&
5058 vm_map_growstack(map, vaddr, entry) == KERN_SUCCESS)
5059 goto RetryLookupLocked;
5061 fault_type = fault_typea & VM_PROT_ALL;
5062 if ((fault_type & prot) != fault_type || prot == VM_PROT_NONE) {
5063 vm_map_unlock_read(map);
5064 return (KERN_PROTECTION_FAILURE);
5066 KASSERT((prot & VM_PROT_WRITE) == 0 || (entry->eflags &
5067 (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY)) !=
5068 (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY),
5069 ("entry %p flags %x", entry, entry->eflags));
5070 if ((fault_typea & VM_PROT_COPY) != 0 &&
5071 (entry->max_protection & VM_PROT_WRITE) == 0 &&
5072 (entry->eflags & MAP_ENTRY_COW) == 0) {
5073 vm_map_unlock_read(map);
5074 return (KERN_PROTECTION_FAILURE);
5078 * If this page is not pageable, we have to get it for all possible
5081 *wired = (entry->wired_count != 0);
5083 fault_type = entry->protection;
5084 size = entry->end - entry->start;
5087 * If the entry was copy-on-write, we either ...
5089 if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
5091 * If we want to write the page, we may as well handle that
5092 * now since we've got the map locked.
5094 * If we don't need to write the page, we just demote the
5095 * permissions allowed.
5097 if ((fault_type & VM_PROT_WRITE) != 0 ||
5098 (fault_typea & VM_PROT_COPY) != 0) {
5100 * Make a new object, and place it in the object
5101 * chain. Note that no new references have appeared
5102 * -- one just moved from the map to the new
5105 if (vm_map_lock_upgrade(map))
5108 if (entry->cred == NULL) {
5110 * The debugger owner is charged for
5113 cred = curthread->td_ucred;
5115 if (!swap_reserve_by_cred(size, cred)) {
5118 return (KERN_RESOURCE_SHORTAGE);
5122 eobject = entry->object.vm_object;
5123 vm_object_shadow(&entry->object.vm_object,
5124 &entry->offset, size, entry->cred, false);
5125 if (eobject == entry->object.vm_object) {
5127 * The object was not shadowed.
5129 swap_release_by_cred(size, entry->cred);
5130 crfree(entry->cred);
5133 entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
5135 vm_map_lock_downgrade(map);
5138 * We're attempting to read a copy-on-write page --
5139 * don't allow writes.
5141 prot &= ~VM_PROT_WRITE;
5146 * Create an object if necessary.
5148 if (entry->object.vm_object == NULL && !map->system_map) {
5149 if (vm_map_lock_upgrade(map))
5151 entry->object.vm_object = vm_object_allocate_anon(atop(size),
5152 NULL, entry->cred, size);
5155 vm_map_lock_downgrade(map);
5159 * Return the object/offset from this entry. If the entry was
5160 * copy-on-write or empty, it has been fixed up.
5162 *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
5163 *object = entry->object.vm_object;
5166 return (KERN_SUCCESS);
5170 * vm_map_lookup_locked:
5172 * Lookup the faulting address. A version of vm_map_lookup that returns
5173 * KERN_FAILURE instead of blocking on map lock or memory allocation.
5176 vm_map_lookup_locked(vm_map_t *var_map, /* IN/OUT */
5178 vm_prot_t fault_typea,
5179 vm_map_entry_t *out_entry, /* OUT */
5180 vm_object_t *object, /* OUT */
5181 vm_pindex_t *pindex, /* OUT */
5182 vm_prot_t *out_prot, /* OUT */
5183 boolean_t *wired) /* OUT */
5185 vm_map_entry_t entry;
5186 vm_map_t map = *var_map;
5188 vm_prot_t fault_type = fault_typea;
5191 * Lookup the faulting address.
5193 if (!vm_map_lookup_entry(map, vaddr, out_entry))
5194 return (KERN_INVALID_ADDRESS);
5199 * Fail if the entry refers to a submap.
5201 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
5202 return (KERN_FAILURE);
5205 * Check whether this task is allowed to have this page.
5207 prot = entry->protection;
5208 fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
5209 if ((fault_type & prot) != fault_type)
5210 return (KERN_PROTECTION_FAILURE);
5213 * If this page is not pageable, we have to get it for all possible
5216 *wired = (entry->wired_count != 0);
5218 fault_type = entry->protection;
5220 if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
5222 * Fail if the entry was copy-on-write for a write fault.
5224 if (fault_type & VM_PROT_WRITE)
5225 return (KERN_FAILURE);
5227 * We're attempting to read a copy-on-write page --
5228 * don't allow writes.
5230 prot &= ~VM_PROT_WRITE;
5234 * Fail if an object should be created.
5236 if (entry->object.vm_object == NULL && !map->system_map)
5237 return (KERN_FAILURE);
5240 * Return the object/offset from this entry. If the entry was
5241 * copy-on-write or empty, it has been fixed up.
5243 *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
5244 *object = entry->object.vm_object;
5247 return (KERN_SUCCESS);
5251 * vm_map_lookup_done:
5253 * Releases locks acquired by a vm_map_lookup
5254 * (according to the handle returned by that lookup).
5257 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
5260 * Unlock the main-level map
5262 vm_map_unlock_read(map);
5266 vm_map_max_KBI(const struct vm_map *map)
5269 return (vm_map_max(map));
5273 vm_map_min_KBI(const struct vm_map *map)
5276 return (vm_map_min(map));
5280 vm_map_pmap_KBI(vm_map_t map)
5287 vm_map_range_valid_KBI(vm_map_t map, vm_offset_t start, vm_offset_t end)
5290 return (vm_map_range_valid(map, start, end));
5295 _vm_map_assert_consistent(vm_map_t map, int check)
5297 vm_map_entry_t entry, prev;
5298 vm_map_entry_t cur, header, lbound, ubound;
5299 vm_size_t max_left, max_right;
5304 if (enable_vmmap_check != check)
5307 header = prev = &map->header;
5308 VM_MAP_ENTRY_FOREACH(entry, map) {
5309 KASSERT(prev->end <= entry->start,
5310 ("map %p prev->end = %jx, start = %jx", map,
5311 (uintmax_t)prev->end, (uintmax_t)entry->start));
5312 KASSERT(entry->start < entry->end,
5313 ("map %p start = %jx, end = %jx", map,
5314 (uintmax_t)entry->start, (uintmax_t)entry->end));
5315 KASSERT(entry->left == header ||
5316 entry->left->start < entry->start,
5317 ("map %p left->start = %jx, start = %jx", map,
5318 (uintmax_t)entry->left->start, (uintmax_t)entry->start));
5319 KASSERT(entry->right == header ||
5320 entry->start < entry->right->start,
5321 ("map %p start = %jx, right->start = %jx", map,
5322 (uintmax_t)entry->start, (uintmax_t)entry->right->start));
5324 lbound = ubound = header;
5326 if (entry->start < cur->start) {
5329 KASSERT(cur != lbound,
5330 ("map %p cannot find %jx",
5331 map, (uintmax_t)entry->start));
5332 } else if (cur->end <= entry->start) {
5335 KASSERT(cur != ubound,
5336 ("map %p cannot find %jx",
5337 map, (uintmax_t)entry->start));
5339 KASSERT(cur == entry,
5340 ("map %p cannot find %jx",
5341 map, (uintmax_t)entry->start));
5345 max_left = vm_map_entry_max_free_left(entry, lbound);
5346 max_right = vm_map_entry_max_free_right(entry, ubound);
5347 KASSERT(entry->max_free == vm_size_max(max_left, max_right),
5348 ("map %p max = %jx, max_left = %jx, max_right = %jx", map,
5349 (uintmax_t)entry->max_free,
5350 (uintmax_t)max_left, (uintmax_t)max_right));
5353 KASSERT(prev->end <= entry->start,
5354 ("map %p prev->end = %jx, start = %jx", map,
5355 (uintmax_t)prev->end, (uintmax_t)entry->start));
5359 #include "opt_ddb.h"
5361 #include <sys/kernel.h>
5363 #include <ddb/ddb.h>
5366 vm_map_print(vm_map_t map)
5368 vm_map_entry_t entry, prev;
5370 db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
5372 (void *)map->pmap, map->nentries, map->timestamp);
5375 prev = &map->header;
5376 VM_MAP_ENTRY_FOREACH(entry, map) {
5377 db_iprintf("map entry %p: start=%p, end=%p, eflags=%#x, \n",
5378 (void *)entry, (void *)entry->start, (void *)entry->end,
5381 static const char * const inheritance_name[4] =
5382 {"share", "copy", "none", "donate_copy"};
5384 db_iprintf(" prot=%x/%x/%s",
5386 entry->max_protection,
5387 inheritance_name[(int)(unsigned char)
5388 entry->inheritance]);
5389 if (entry->wired_count != 0)
5390 db_printf(", wired");
5392 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
5393 db_printf(", share=%p, offset=0x%jx\n",
5394 (void *)entry->object.sub_map,
5395 (uintmax_t)entry->offset);
5396 if (prev == &map->header ||
5397 prev->object.sub_map !=
5398 entry->object.sub_map) {
5400 vm_map_print((vm_map_t)entry->object.sub_map);
5404 if (entry->cred != NULL)
5405 db_printf(", ruid %d", entry->cred->cr_ruid);
5406 db_printf(", object=%p, offset=0x%jx",
5407 (void *)entry->object.vm_object,
5408 (uintmax_t)entry->offset);
5409 if (entry->object.vm_object && entry->object.vm_object->cred)
5410 db_printf(", obj ruid %d charge %jx",
5411 entry->object.vm_object->cred->cr_ruid,
5412 (uintmax_t)entry->object.vm_object->charge);
5413 if (entry->eflags & MAP_ENTRY_COW)
5414 db_printf(", copy (%s)",
5415 (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
5418 if (prev == &map->header ||
5419 prev->object.vm_object !=
5420 entry->object.vm_object) {
5422 vm_object_print((db_expr_t)(intptr_t)
5423 entry->object.vm_object,
5433 DB_SHOW_COMMAND(map, map)
5437 db_printf("usage: show map <addr>\n");
5440 vm_map_print((vm_map_t)addr);
5443 DB_SHOW_COMMAND(procvm, procvm)
5448 p = db_lookup_proc(addr);
5453 db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
5454 (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
5455 (void *)vmspace_pmap(p->p_vmspace));
5457 vm_map_print((vm_map_t)&p->p_vmspace->vm_map);