2 * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * The Mach Operating System project at Carnegie-Mellon University.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * from: @(#)vm_map.c 8.3 (Berkeley) 1/12/94
37 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38 * All rights reserved.
40 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
42 * Permission to use, copy, modify and distribute this software and
43 * its documentation is hereby granted, provided that both the copyright
44 * notice and this permission notice appear in all copies of the
45 * software, derivative works or modified versions, and any portions
46 * thereof, and that both notices appear in supporting documentation.
48 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
52 * Carnegie Mellon requests users of this software to return to
54 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
55 * School of Computer Science
56 * Carnegie Mellon University
57 * Pittsburgh PA 15213-3890
59 * any improvements or extensions that they make and grant Carnegie the
60 * rights to redistribute these changes.
64 * Virtual memory mapping module.
67 #include <sys/cdefs.h>
68 __FBSDID("$FreeBSD$");
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/kernel.h>
75 #include <sys/mutex.h>
77 #include <sys/vmmeter.h>
79 #include <sys/vnode.h>
80 #include <sys/racct.h>
81 #include <sys/resourcevar.h>
82 #include <sys/rwlock.h>
84 #include <sys/sysctl.h>
85 #include <sys/sysent.h>
89 #include <vm/vm_param.h>
91 #include <vm/vm_map.h>
92 #include <vm/vm_page.h>
93 #include <vm/vm_pageout.h>
94 #include <vm/vm_object.h>
95 #include <vm/vm_pager.h>
96 #include <vm/vm_kern.h>
97 #include <vm/vm_extern.h>
98 #include <vm/vnode_pager.h>
99 #include <vm/swap_pager.h>
103 * Virtual memory maps provide for the mapping, protection,
104 * and sharing of virtual memory objects. In addition,
105 * this module provides for an efficient virtual copy of
106 * memory from one map to another.
108 * Synchronization is required prior to most operations.
110 * Maps consist of an ordered doubly-linked list of simple
111 * entries; a self-adjusting binary search tree of these
112 * entries is used to speed up lookups.
114 * Since portions of maps are specified by start/end addresses,
115 * which may not align with existing map entries, all
116 * routines merely "clip" entries to these start/end values.
117 * [That is, an entry is split into two, bordering at a
118 * start or end value.] Note that these clippings may not
119 * always be necessary (as the two resulting entries are then
120 * not changed); however, the clipping is done for convenience.
122 * As mentioned above, virtual copy operations are performed
123 * by copying VM object references from one map to
124 * another, and then marking both regions as copy-on-write.
127 static struct mtx map_sleep_mtx;
128 static uma_zone_t mapentzone;
129 static uma_zone_t kmapentzone;
130 static uma_zone_t mapzone;
131 static uma_zone_t vmspace_zone;
132 static int vmspace_zinit(void *mem, int size, int flags);
133 static int vm_map_zinit(void *mem, int ize, int flags);
134 static void _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min,
136 static void vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map);
137 static void vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry);
138 static void vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry);
139 static int vm_map_growstack(vm_map_t map, vm_offset_t addr,
140 vm_map_entry_t gap_entry);
141 static void vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
142 vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags);
144 static void vm_map_zdtor(void *mem, int size, void *arg);
145 static void vmspace_zdtor(void *mem, int size, void *arg);
147 static int vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos,
148 vm_size_t max_ssize, vm_size_t growsize, vm_prot_t prot, vm_prot_t max,
150 static void vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
151 vm_offset_t failed_addr);
153 #define ENTRY_CHARGED(e) ((e)->cred != NULL || \
154 ((e)->object.vm_object != NULL && (e)->object.vm_object->cred != NULL && \
155 !((e)->eflags & MAP_ENTRY_NEEDS_COPY)))
158 * PROC_VMSPACE_{UN,}LOCK() can be a noop as long as vmspaces are type
161 #define PROC_VMSPACE_LOCK(p) do { } while (0)
162 #define PROC_VMSPACE_UNLOCK(p) do { } while (0)
165 * VM_MAP_RANGE_CHECK: [ internal use only ]
167 * Asserts that the starting and ending region
168 * addresses fall within the valid range of the map.
170 #define VM_MAP_RANGE_CHECK(map, start, end) \
172 if (start < vm_map_min(map)) \
173 start = vm_map_min(map); \
174 if (end > vm_map_max(map)) \
175 end = vm_map_max(map); \
183 * Initialize the vm_map module. Must be called before
184 * any other vm_map routines.
186 * Map and entry structures are allocated from the general
187 * purpose memory pool with some exceptions:
189 * - The kernel map and kmem submap are allocated statically.
190 * - Kernel map entries are allocated out of a static pool.
192 * These restrictions are necessary since malloc() uses the
193 * maps and requires map entries.
199 mtx_init(&map_sleep_mtx, "vm map sleep mutex", NULL, MTX_DEF);
200 mapzone = uma_zcreate("MAP", sizeof(struct vm_map), NULL,
206 vm_map_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
207 uma_prealloc(mapzone, MAX_KMAP);
208 kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry),
209 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
210 UMA_ZONE_MTXCLASS | UMA_ZONE_VM);
211 mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry),
212 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
213 vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
219 vmspace_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
223 vmspace_zinit(void *mem, int size, int flags)
227 vm = (struct vmspace *)mem;
229 vm->vm_map.pmap = NULL;
230 (void)vm_map_zinit(&vm->vm_map, sizeof(vm->vm_map), flags);
231 PMAP_LOCK_INIT(vmspace_pmap(vm));
236 vm_map_zinit(void *mem, int size, int flags)
241 memset(map, 0, sizeof(*map));
242 mtx_init(&map->system_mtx, "vm map (system)", NULL, MTX_DEF | MTX_DUPOK);
243 sx_init(&map->lock, "vm map (user)");
249 vmspace_zdtor(void *mem, int size, void *arg)
253 vm = (struct vmspace *)mem;
255 vm_map_zdtor(&vm->vm_map, sizeof(vm->vm_map), arg);
258 vm_map_zdtor(void *mem, int size, void *arg)
263 KASSERT(map->nentries == 0,
264 ("map %p nentries == %d on free.",
265 map, map->nentries));
266 KASSERT(map->size == 0,
267 ("map %p size == %lu on free.",
268 map, (unsigned long)map->size));
270 #endif /* INVARIANTS */
273 * Allocate a vmspace structure, including a vm_map and pmap,
274 * and initialize those structures. The refcnt is set to 1.
276 * If 'pinit' is NULL then the embedded pmap is initialized via pmap_pinit().
279 vmspace_alloc(vm_offset_t min, vm_offset_t max, pmap_pinit_t pinit)
283 vm = uma_zalloc(vmspace_zone, M_WAITOK);
284 KASSERT(vm->vm_map.pmap == NULL, ("vm_map.pmap must be NULL"));
285 if (!pinit(vmspace_pmap(vm))) {
286 uma_zfree(vmspace_zone, vm);
289 CTR1(KTR_VM, "vmspace_alloc: %p", vm);
290 _vm_map_init(&vm->vm_map, vmspace_pmap(vm), min, max);
305 vmspace_container_reset(struct proc *p)
309 racct_set(p, RACCT_DATA, 0);
310 racct_set(p, RACCT_STACK, 0);
311 racct_set(p, RACCT_RSS, 0);
312 racct_set(p, RACCT_MEMLOCK, 0);
313 racct_set(p, RACCT_VMEM, 0);
319 vmspace_dofree(struct vmspace *vm)
322 CTR1(KTR_VM, "vmspace_free: %p", vm);
325 * Make sure any SysV shm is freed, it might not have been in
331 * Lock the map, to wait out all other references to it.
332 * Delete all of the mappings and pages they hold, then call
333 * the pmap module to reclaim anything left.
335 (void)vm_map_remove(&vm->vm_map, vm_map_min(&vm->vm_map),
336 vm_map_max(&vm->vm_map));
338 pmap_release(vmspace_pmap(vm));
339 vm->vm_map.pmap = NULL;
340 uma_zfree(vmspace_zone, vm);
344 vmspace_free(struct vmspace *vm)
347 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
348 "vmspace_free() called");
350 if (vm->vm_refcnt == 0)
351 panic("vmspace_free: attempt to free already freed vmspace");
353 if (atomic_fetchadd_int(&vm->vm_refcnt, -1) == 1)
358 vmspace_exitfree(struct proc *p)
362 PROC_VMSPACE_LOCK(p);
365 PROC_VMSPACE_UNLOCK(p);
366 KASSERT(vm == &vmspace0, ("vmspace_exitfree: wrong vmspace"));
371 vmspace_exit(struct thread *td)
378 * Release user portion of address space.
379 * This releases references to vnodes,
380 * which could cause I/O if the file has been unlinked.
381 * Need to do this early enough that we can still sleep.
383 * The last exiting process to reach this point releases as
384 * much of the environment as it can. vmspace_dofree() is the
385 * slower fallback in case another process had a temporary
386 * reference to the vmspace.
391 atomic_add_int(&vmspace0.vm_refcnt, 1);
392 refcnt = vm->vm_refcnt;
394 if (refcnt > 1 && p->p_vmspace != &vmspace0) {
395 /* Switch now since other proc might free vmspace */
396 PROC_VMSPACE_LOCK(p);
397 p->p_vmspace = &vmspace0;
398 PROC_VMSPACE_UNLOCK(p);
401 } while (!atomic_fcmpset_int(&vm->vm_refcnt, &refcnt, refcnt - 1));
403 if (p->p_vmspace != vm) {
404 /* vmspace not yet freed, switch back */
405 PROC_VMSPACE_LOCK(p);
407 PROC_VMSPACE_UNLOCK(p);
410 pmap_remove_pages(vmspace_pmap(vm));
411 /* Switch now since this proc will free vmspace */
412 PROC_VMSPACE_LOCK(p);
413 p->p_vmspace = &vmspace0;
414 PROC_VMSPACE_UNLOCK(p);
420 vmspace_container_reset(p);
424 /* Acquire reference to vmspace owned by another process. */
427 vmspace_acquire_ref(struct proc *p)
432 PROC_VMSPACE_LOCK(p);
435 PROC_VMSPACE_UNLOCK(p);
438 refcnt = vm->vm_refcnt;
440 if (refcnt <= 0) { /* Avoid 0->1 transition */
441 PROC_VMSPACE_UNLOCK(p);
444 } while (!atomic_fcmpset_int(&vm->vm_refcnt, &refcnt, refcnt + 1));
445 if (vm != p->p_vmspace) {
446 PROC_VMSPACE_UNLOCK(p);
450 PROC_VMSPACE_UNLOCK(p);
455 * Switch between vmspaces in an AIO kernel process.
457 * The AIO kernel processes switch to and from a user process's
458 * vmspace while performing an I/O operation on behalf of a user
459 * process. The new vmspace is either the vmspace of a user process
460 * obtained from an active AIO request or the initial vmspace of the
461 * AIO kernel process (when it is idling). Because user processes
462 * will block to drain any active AIO requests before proceeding in
463 * exit() or execve(), the vmspace reference count for these vmspaces
464 * can never be 0. This allows for a much simpler implementation than
465 * the loop in vmspace_acquire_ref() above. Similarly, AIO kernel
466 * processes hold an extra reference on their initial vmspace for the
467 * life of the process so that this guarantee is true for any vmspace
471 vmspace_switch_aio(struct vmspace *newvm)
473 struct vmspace *oldvm;
475 /* XXX: Need some way to assert that this is an aio daemon. */
477 KASSERT(newvm->vm_refcnt > 0,
478 ("vmspace_switch_aio: newvm unreferenced"));
480 oldvm = curproc->p_vmspace;
485 * Point to the new address space and refer to it.
487 curproc->p_vmspace = newvm;
488 atomic_add_int(&newvm->vm_refcnt, 1);
490 /* Activate the new mapping. */
491 pmap_activate(curthread);
493 /* Remove the daemon's reference to the old address space. */
494 KASSERT(oldvm->vm_refcnt > 1,
495 ("vmspace_switch_aio: oldvm dropping last reference"));
500 _vm_map_lock(vm_map_t map, const char *file, int line)
504 mtx_lock_flags_(&map->system_mtx, 0, file, line);
506 sx_xlock_(&map->lock, file, line);
511 vm_map_entry_set_vnode_text(vm_map_entry_t entry, bool add)
513 vm_object_t object, object1;
516 if ((entry->eflags & MAP_ENTRY_VN_EXEC) == 0)
518 KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
519 ("Submap with execs"));
520 object = entry->object.vm_object;
521 KASSERT(object != NULL, ("No object for text, entry %p", entry));
522 VM_OBJECT_RLOCK(object);
523 while ((object1 = object->backing_object) != NULL) {
524 VM_OBJECT_RLOCK(object1);
525 VM_OBJECT_RUNLOCK(object);
530 if (object->type == OBJT_DEAD) {
532 * For OBJT_DEAD objects, v_writecount was handled in
533 * vnode_pager_dealloc().
535 } else if (object->type == OBJT_VNODE) {
537 } else if (object->type == OBJT_SWAP) {
538 KASSERT((object->flags & OBJ_TMPFS_NODE) != 0,
539 ("vm_map_entry_set_vnode_text: swap and !TMPFS "
540 "entry %p, object %p, add %d", entry, object, add));
542 * Tmpfs VREG node, which was reclaimed, has
543 * OBJ_TMPFS_NODE flag set, but not OBJ_TMPFS. In
544 * this case there is no v_writecount to adjust.
546 if ((object->flags & OBJ_TMPFS) != 0)
547 vp = object->un_pager.swp.swp_tmpfs;
550 ("vm_map_entry_set_vnode_text: wrong object type, "
551 "entry %p, object %p, add %d", entry, object, add));
555 VOP_SET_TEXT_CHECKED(vp);
557 VOP_UNSET_TEXT_CHECKED(vp);
559 VM_OBJECT_RUNLOCK(object);
563 vm_map_process_deferred(void)
566 vm_map_entry_t entry, next;
570 entry = td->td_map_def_user;
571 td->td_map_def_user = NULL;
572 while (entry != NULL) {
574 MPASS((entry->eflags & (MAP_ENTRY_VN_WRITECNT |
575 MAP_ENTRY_VN_EXEC)) != (MAP_ENTRY_VN_WRITECNT |
577 if ((entry->eflags & MAP_ENTRY_VN_WRITECNT) != 0) {
579 * Decrement the object's writemappings and
580 * possibly the vnode's v_writecount.
582 KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
583 ("Submap with writecount"));
584 object = entry->object.vm_object;
585 KASSERT(object != NULL, ("No object for writecount"));
586 vnode_pager_release_writecount(object, entry->start,
589 vm_map_entry_set_vnode_text(entry, false);
590 vm_map_entry_deallocate(entry, FALSE);
596 _vm_map_unlock(vm_map_t map, const char *file, int line)
600 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
602 sx_xunlock_(&map->lock, file, line);
603 vm_map_process_deferred();
608 _vm_map_lock_read(vm_map_t map, const char *file, int line)
612 mtx_lock_flags_(&map->system_mtx, 0, file, line);
614 sx_slock_(&map->lock, file, line);
618 _vm_map_unlock_read(vm_map_t map, const char *file, int line)
622 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
624 sx_sunlock_(&map->lock, file, line);
625 vm_map_process_deferred();
630 _vm_map_trylock(vm_map_t map, const char *file, int line)
634 error = map->system_map ?
635 !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
636 !sx_try_xlock_(&map->lock, file, line);
643 _vm_map_trylock_read(vm_map_t map, const char *file, int line)
647 error = map->system_map ?
648 !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
649 !sx_try_slock_(&map->lock, file, line);
654 * _vm_map_lock_upgrade: [ internal use only ]
656 * Tries to upgrade a read (shared) lock on the specified map to a write
657 * (exclusive) lock. Returns the value "0" if the upgrade succeeds and a
658 * non-zero value if the upgrade fails. If the upgrade fails, the map is
659 * returned without a read or write lock held.
661 * Requires that the map be read locked.
664 _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
666 unsigned int last_timestamp;
668 if (map->system_map) {
669 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
671 if (!sx_try_upgrade_(&map->lock, file, line)) {
672 last_timestamp = map->timestamp;
673 sx_sunlock_(&map->lock, file, line);
674 vm_map_process_deferred();
676 * If the map's timestamp does not change while the
677 * map is unlocked, then the upgrade succeeds.
679 sx_xlock_(&map->lock, file, line);
680 if (last_timestamp != map->timestamp) {
681 sx_xunlock_(&map->lock, file, line);
691 _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
694 if (map->system_map) {
695 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
697 sx_downgrade_(&map->lock, file, line);
703 * Returns a non-zero value if the caller holds a write (exclusive) lock
704 * on the specified map and the value "0" otherwise.
707 vm_map_locked(vm_map_t map)
711 return (mtx_owned(&map->system_mtx));
713 return (sx_xlocked(&map->lock));
718 _vm_map_assert_locked(vm_map_t map, const char *file, int line)
722 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
724 sx_assert_(&map->lock, SA_XLOCKED, file, line);
727 #define VM_MAP_ASSERT_LOCKED(map) \
728 _vm_map_assert_locked(map, LOCK_FILE, LOCK_LINE)
731 static int enable_vmmap_check = 1;
733 static int enable_vmmap_check = 0;
735 SYSCTL_INT(_debug, OID_AUTO, vmmap_check, CTLFLAG_RWTUN,
736 &enable_vmmap_check, 0, "Enable vm map consistency checking");
739 _vm_map_assert_consistent(vm_map_t map)
741 vm_map_entry_t entry;
742 vm_map_entry_t child;
743 vm_size_t max_left, max_right;
745 if (!enable_vmmap_check)
748 for (entry = map->header.next; entry != &map->header;
749 entry = entry->next) {
750 KASSERT(entry->prev->end <= entry->start,
751 ("map %p prev->end = %jx, start = %jx", map,
752 (uintmax_t)entry->prev->end, (uintmax_t)entry->start));
753 KASSERT(entry->start < entry->end,
754 ("map %p start = %jx, end = %jx", map,
755 (uintmax_t)entry->start, (uintmax_t)entry->end));
756 KASSERT(entry->end <= entry->next->start,
757 ("map %p end = %jx, next->start = %jx", map,
758 (uintmax_t)entry->end, (uintmax_t)entry->next->start));
759 KASSERT(entry->left == NULL ||
760 entry->left->start < entry->start,
761 ("map %p left->start = %jx, start = %jx", map,
762 (uintmax_t)entry->left->start, (uintmax_t)entry->start));
763 KASSERT(entry->right == NULL ||
764 entry->start < entry->right->start,
765 ("map %p start = %jx, right->start = %jx", map,
766 (uintmax_t)entry->start, (uintmax_t)entry->right->start));
768 max_left = (child != NULL) ? child->max_free :
769 entry->start - entry->prev->end;
770 child = entry->right;
771 max_right = (child != NULL) ? child->max_free :
772 entry->next->start - entry->end;
773 KASSERT(entry->max_free == MAX(max_left, max_right),
774 ("map %p max = %jx, max_left = %jx, max_right = %jx", map,
775 (uintmax_t)entry->max_free,
776 (uintmax_t)max_left, (uintmax_t)max_right));
780 #define VM_MAP_ASSERT_CONSISTENT(map) \
781 _vm_map_assert_consistent(map)
783 #define VM_MAP_ASSERT_LOCKED(map)
784 #define VM_MAP_ASSERT_CONSISTENT(map)
785 #endif /* INVARIANTS */
788 * _vm_map_unlock_and_wait:
790 * Atomically releases the lock on the specified map and puts the calling
791 * thread to sleep. The calling thread will remain asleep until either
792 * vm_map_wakeup() is performed on the map or the specified timeout is
795 * WARNING! This function does not perform deferred deallocations of
796 * objects and map entries. Therefore, the calling thread is expected to
797 * reacquire the map lock after reawakening and later perform an ordinary
798 * unlock operation, such as vm_map_unlock(), before completing its
799 * operation on the map.
802 _vm_map_unlock_and_wait(vm_map_t map, int timo, const char *file, int line)
805 mtx_lock(&map_sleep_mtx);
807 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
809 sx_xunlock_(&map->lock, file, line);
810 return (msleep(&map->root, &map_sleep_mtx, PDROP | PVM, "vmmaps",
817 * Awaken any threads that have slept on the map using
818 * vm_map_unlock_and_wait().
821 vm_map_wakeup(vm_map_t map)
825 * Acquire and release map_sleep_mtx to prevent a wakeup()
826 * from being performed (and lost) between the map unlock
827 * and the msleep() in _vm_map_unlock_and_wait().
829 mtx_lock(&map_sleep_mtx);
830 mtx_unlock(&map_sleep_mtx);
835 vm_map_busy(vm_map_t map)
838 VM_MAP_ASSERT_LOCKED(map);
843 vm_map_unbusy(vm_map_t map)
846 VM_MAP_ASSERT_LOCKED(map);
847 KASSERT(map->busy, ("vm_map_unbusy: not busy"));
848 if (--map->busy == 0 && (map->flags & MAP_BUSY_WAKEUP)) {
849 vm_map_modflags(map, 0, MAP_BUSY_WAKEUP);
855 vm_map_wait_busy(vm_map_t map)
858 VM_MAP_ASSERT_LOCKED(map);
860 vm_map_modflags(map, MAP_BUSY_WAKEUP, 0);
862 msleep(&map->busy, &map->system_mtx, 0, "mbusy", 0);
864 sx_sleep(&map->busy, &map->lock, 0, "mbusy", 0);
870 vmspace_resident_count(struct vmspace *vmspace)
872 return pmap_resident_count(vmspace_pmap(vmspace));
878 * Creates and returns a new empty VM map with
879 * the given physical map structure, and having
880 * the given lower and upper address bounds.
883 vm_map_create(pmap_t pmap, vm_offset_t min, vm_offset_t max)
887 result = uma_zalloc(mapzone, M_WAITOK);
888 CTR1(KTR_VM, "vm_map_create: %p", result);
889 _vm_map_init(result, pmap, min, max);
894 * Initialize an existing vm_map structure
895 * such as that in the vmspace structure.
898 _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
901 map->header.next = map->header.prev = &map->header;
902 map->header.eflags = MAP_ENTRY_HEADER;
903 map->needs_wakeup = FALSE;
906 map->header.end = min;
907 map->header.start = max;
916 vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
919 _vm_map_init(map, pmap, min, max);
920 mtx_init(&map->system_mtx, "system map", NULL, MTX_DEF | MTX_DUPOK);
921 sx_init(&map->lock, "user map");
925 * vm_map_entry_dispose: [ internal use only ]
927 * Inverse of vm_map_entry_create.
930 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
932 uma_zfree(map->system_map ? kmapentzone : mapentzone, entry);
936 * vm_map_entry_create: [ internal use only ]
938 * Allocates a VM map entry for insertion.
939 * No entry fields are filled in.
941 static vm_map_entry_t
942 vm_map_entry_create(vm_map_t map)
944 vm_map_entry_t new_entry;
947 new_entry = uma_zalloc(kmapentzone, M_NOWAIT);
949 new_entry = uma_zalloc(mapentzone, M_WAITOK);
950 if (new_entry == NULL)
951 panic("vm_map_entry_create: kernel resources exhausted");
956 * vm_map_entry_set_behavior:
958 * Set the expected access behavior, either normal, random, or
962 vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
964 entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
965 (behavior & MAP_ENTRY_BEHAV_MASK);
969 * vm_map_entry_set_max_free:
971 * Set the max_free field in a vm_map_entry.
974 vm_map_entry_set_max_free(vm_map_entry_t entry)
976 vm_map_entry_t child;
977 vm_size_t max_left, max_right;
980 max_left = (child != NULL) ? child->max_free :
981 entry->start - entry->prev->end;
982 child = entry->right;
983 max_right = (child != NULL) ? child->max_free :
984 entry->next->start - entry->end;
985 entry->max_free = MAX(max_left, max_right);
988 #define SPLAY_LEFT_STEP(root, y, rlist, test) do { \
990 if (y != NULL && (test)) { \
991 /* Rotate right and make y root. */ \
992 root->left = y->right; \
994 vm_map_entry_set_max_free(root); \
998 /* Put root on rlist. */ \
999 root->left = rlist; \
1004 #define SPLAY_RIGHT_STEP(root, y, llist, test) do { \
1006 if (y != NULL && (test)) { \
1007 /* Rotate left and make y root. */ \
1008 root->right = y->left; \
1010 vm_map_entry_set_max_free(root); \
1014 /* Put root on llist. */ \
1015 root->right = llist; \
1021 * Walk down the tree until we find addr or a NULL pointer where addr would go,
1022 * breaking off left and right subtrees of nodes less than, or greater than
1023 * addr. Treat pointers to nodes with max_free < length as NULL pointers.
1024 * llist and rlist are the two sides in reverse order (bottom-up), with llist
1025 * linked by the right pointer and rlist linked by the left pointer in the
1028 static vm_map_entry_t
1029 vm_map_splay_split(vm_offset_t addr, vm_size_t length,
1030 vm_map_entry_t root, vm_map_entry_t *out_llist, vm_map_entry_t *out_rlist)
1032 vm_map_entry_t llist, rlist;
1037 while (root != NULL && root->max_free >= length) {
1038 if (addr < root->start) {
1039 SPLAY_LEFT_STEP(root, y, rlist,
1040 y->max_free >= length && addr < y->start);
1041 } else if (addr >= root->end) {
1042 SPLAY_RIGHT_STEP(root, y, llist,
1043 y->max_free >= length && addr >= y->end);
1053 vm_map_splay_findnext(vm_map_entry_t root, vm_map_entry_t *iolist)
1055 vm_map_entry_t rlist, y;
1059 while (root != NULL)
1060 SPLAY_LEFT_STEP(root, y, rlist, true);
1065 vm_map_splay_findprev(vm_map_entry_t root, vm_map_entry_t *iolist)
1067 vm_map_entry_t llist, y;
1071 while (root != NULL)
1072 SPLAY_RIGHT_STEP(root, y, llist, true);
1077 * Walk back up the two spines, flip the pointers and set max_free. The
1078 * subtrees of the root go at the bottom of llist and rlist.
1080 static vm_map_entry_t
1081 vm_map_splay_merge(vm_map_entry_t root,
1082 vm_map_entry_t llist, vm_map_entry_t rlist,
1083 vm_map_entry_t ltree, vm_map_entry_t rtree)
1087 while (llist != NULL) {
1089 llist->right = ltree;
1090 vm_map_entry_set_max_free(llist);
1094 while (rlist != NULL) {
1096 rlist->left = rtree;
1097 vm_map_entry_set_max_free(rlist);
1103 * Final assembly: add ltree and rtree as subtrees of root.
1106 root->right = rtree;
1107 vm_map_entry_set_max_free(root);
1113 * vm_map_entry_splay:
1115 * The Sleator and Tarjan top-down splay algorithm with the
1116 * following variation. Max_free must be computed bottom-up, so
1117 * on the downward pass, maintain the left and right spines in
1118 * reverse order. Then, make a second pass up each side to fix
1119 * the pointers and compute max_free. The time bound is O(log n)
1122 * The new root is the vm_map_entry containing "addr", or else an
1123 * adjacent entry (lower if possible) if addr is not in the tree.
1125 * The map must be locked, and leaves it so.
1127 * Returns: the new root.
1129 static vm_map_entry_t
1130 vm_map_entry_splay(vm_offset_t addr, vm_map_entry_t root)
1132 vm_map_entry_t llist, rlist;
1134 root = vm_map_splay_split(addr, 0, root, &llist, &rlist);
1137 } else if (llist != NULL) {
1139 * Recover the greatest node in the left
1140 * subtree and make it the root.
1143 llist = root->right;
1145 } else if (rlist != NULL) {
1147 * Recover the least node in the right
1148 * subtree and make it the root.
1154 /* There is no root. */
1157 return (vm_map_splay_merge(root, llist, rlist,
1158 root->left, root->right));
1162 * vm_map_entry_{un,}link:
1164 * Insert/remove entries from maps.
1167 vm_map_entry_link(vm_map_t map,
1168 vm_map_entry_t entry)
1170 vm_map_entry_t llist, rlist, root;
1173 "vm_map_entry_link: map %p, nentries %d, entry %p", map,
1174 map->nentries, entry);
1175 VM_MAP_ASSERT_LOCKED(map);
1178 root = vm_map_splay_split(entry->start, 0, root, &llist, &rlist);
1179 KASSERT(root == NULL,
1180 ("vm_map_entry_link: link object already mapped"));
1181 entry->prev = (llist == NULL) ? &map->header : llist;
1182 entry->next = (rlist == NULL) ? &map->header : rlist;
1183 entry->prev->next = entry->next->prev = entry;
1184 root = vm_map_splay_merge(entry, llist, rlist, NULL, NULL);
1186 VM_MAP_ASSERT_CONSISTENT(map);
1189 enum unlink_merge_type {
1196 vm_map_entry_unlink(vm_map_t map,
1197 vm_map_entry_t entry,
1198 enum unlink_merge_type op)
1200 vm_map_entry_t llist, rlist, root, y;
1202 VM_MAP_ASSERT_LOCKED(map);
1203 llist = entry->prev;
1204 rlist = entry->next;
1205 llist->next = rlist;
1206 rlist->prev = llist;
1208 root = vm_map_splay_split(entry->start, 0, root, &llist, &rlist);
1209 KASSERT(root != NULL,
1210 ("vm_map_entry_unlink: unlink object not mapped"));
1213 case UNLINK_MERGE_PREV:
1214 vm_map_splay_findprev(root, &llist);
1215 llist->end = root->end;
1218 llist = root->right;
1221 case UNLINK_MERGE_NEXT:
1222 vm_map_splay_findnext(root, &rlist);
1223 rlist->start = root->start;
1224 rlist->offset = root->offset;
1230 case UNLINK_MERGE_NONE:
1231 vm_map_splay_findprev(root, &llist);
1232 vm_map_splay_findnext(root, &rlist);
1233 if (llist != NULL) {
1235 llist = root->right;
1237 } else if (rlist != NULL) {
1246 root = vm_map_splay_merge(root, llist, rlist,
1247 root->left, root->right);
1249 VM_MAP_ASSERT_CONSISTENT(map);
1251 CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
1252 map->nentries, entry);
1256 * vm_map_entry_resize:
1258 * Resize a vm_map_entry, recompute the amount of free space that
1259 * follows it and propagate that value up the tree.
1261 * The map must be locked, and leaves it so.
1264 vm_map_entry_resize(vm_map_t map, vm_map_entry_t entry, vm_size_t grow_amount)
1266 vm_map_entry_t llist, rlist, root;
1268 VM_MAP_ASSERT_LOCKED(map);
1270 root = vm_map_splay_split(entry->start, 0, root, &llist, &rlist);
1271 KASSERT(root != NULL,
1272 ("%s: resize object not mapped", __func__));
1273 vm_map_splay_findnext(root, &rlist);
1275 entry->end += grow_amount;
1276 map->root = vm_map_splay_merge(root, llist, rlist,
1277 root->left, root->right);
1278 VM_MAP_ASSERT_CONSISTENT(map);
1279 CTR4(KTR_VM, "%s: map %p, nentries %d, entry %p",
1280 __func__, map, map->nentries, entry);
1284 * vm_map_lookup_entry: [ internal use only ]
1286 * Finds the map entry containing (or
1287 * immediately preceding) the specified address
1288 * in the given map; the entry is returned
1289 * in the "entry" parameter. The boolean
1290 * result indicates whether the address is
1291 * actually contained in the map.
1294 vm_map_lookup_entry(
1296 vm_offset_t address,
1297 vm_map_entry_t *entry) /* OUT */
1299 vm_map_entry_t cur, lbound;
1303 * If the map is empty, then the map entry immediately preceding
1304 * "address" is the map's header.
1308 *entry = &map->header;
1311 if (address >= cur->start && cur->end > address) {
1315 if ((locked = vm_map_locked(map)) ||
1316 sx_try_upgrade(&map->lock)) {
1318 * Splay requires a write lock on the map. However, it only
1319 * restructures the binary search tree; it does not otherwise
1320 * change the map. Thus, the map's timestamp need not change
1321 * on a temporary upgrade.
1323 map->root = cur = vm_map_entry_splay(address, cur);
1324 VM_MAP_ASSERT_CONSISTENT(map);
1326 sx_downgrade(&map->lock);
1329 * If "address" is contained within a map entry, the new root
1330 * is that map entry. Otherwise, the new root is a map entry
1331 * immediately before or after "address".
1333 if (address < cur->start) {
1334 *entry = &map->header;
1338 return (address < cur->end);
1341 * Since the map is only locked for read access, perform a
1342 * standard binary search tree lookup for "address".
1344 lbound = &map->header;
1346 if (address < cur->start) {
1348 } else if (cur->end <= address) {
1355 } while (cur != NULL);
1363 * Inserts the given whole VM object into the target
1364 * map at the specified address range. The object's
1365 * size should match that of the address range.
1367 * Requires that the map be locked, and leaves it so.
1369 * If object is non-NULL, ref count must be bumped by caller
1370 * prior to making call to account for the new entry.
1373 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1374 vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max, int cow)
1376 vm_map_entry_t new_entry, prev_entry, temp_entry;
1378 vm_eflags_t protoeflags;
1379 vm_inherit_t inheritance;
1381 VM_MAP_ASSERT_LOCKED(map);
1382 KASSERT(object != kernel_object ||
1383 (cow & MAP_COPY_ON_WRITE) == 0,
1384 ("vm_map_insert: kernel object and COW"));
1385 KASSERT(object == NULL || (cow & MAP_NOFAULT) == 0,
1386 ("vm_map_insert: paradoxical MAP_NOFAULT request"));
1387 KASSERT((prot & ~max) == 0,
1388 ("prot %#x is not subset of max_prot %#x", prot, max));
1391 * Check that the start and end points are not bogus.
1393 if (start < vm_map_min(map) || end > vm_map_max(map) ||
1395 return (KERN_INVALID_ADDRESS);
1398 * Find the entry prior to the proposed starting address; if it's part
1399 * of an existing entry, this range is bogus.
1401 if (vm_map_lookup_entry(map, start, &temp_entry))
1402 return (KERN_NO_SPACE);
1404 prev_entry = temp_entry;
1407 * Assert that the next entry doesn't overlap the end point.
1409 if (prev_entry->next->start < end)
1410 return (KERN_NO_SPACE);
1412 if ((cow & MAP_CREATE_GUARD) != 0 && (object != NULL ||
1413 max != VM_PROT_NONE))
1414 return (KERN_INVALID_ARGUMENT);
1417 if (cow & MAP_COPY_ON_WRITE)
1418 protoeflags |= MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY;
1419 if (cow & MAP_NOFAULT)
1420 protoeflags |= MAP_ENTRY_NOFAULT;
1421 if (cow & MAP_DISABLE_SYNCER)
1422 protoeflags |= MAP_ENTRY_NOSYNC;
1423 if (cow & MAP_DISABLE_COREDUMP)
1424 protoeflags |= MAP_ENTRY_NOCOREDUMP;
1425 if (cow & MAP_STACK_GROWS_DOWN)
1426 protoeflags |= MAP_ENTRY_GROWS_DOWN;
1427 if (cow & MAP_STACK_GROWS_UP)
1428 protoeflags |= MAP_ENTRY_GROWS_UP;
1429 if (cow & MAP_VN_WRITECOUNT)
1430 protoeflags |= MAP_ENTRY_VN_WRITECNT;
1431 if (cow & MAP_VN_EXEC)
1432 protoeflags |= MAP_ENTRY_VN_EXEC;
1433 if ((cow & MAP_CREATE_GUARD) != 0)
1434 protoeflags |= MAP_ENTRY_GUARD;
1435 if ((cow & MAP_CREATE_STACK_GAP_DN) != 0)
1436 protoeflags |= MAP_ENTRY_STACK_GAP_DN;
1437 if ((cow & MAP_CREATE_STACK_GAP_UP) != 0)
1438 protoeflags |= MAP_ENTRY_STACK_GAP_UP;
1439 if (cow & MAP_INHERIT_SHARE)
1440 inheritance = VM_INHERIT_SHARE;
1442 inheritance = VM_INHERIT_DEFAULT;
1445 if ((cow & (MAP_ACC_NO_CHARGE | MAP_NOFAULT | MAP_CREATE_GUARD)) != 0)
1447 if ((cow & MAP_ACC_CHARGED) || ((prot & VM_PROT_WRITE) &&
1448 ((protoeflags & MAP_ENTRY_NEEDS_COPY) || object == NULL))) {
1449 if (!(cow & MAP_ACC_CHARGED) && !swap_reserve(end - start))
1450 return (KERN_RESOURCE_SHORTAGE);
1451 KASSERT(object == NULL ||
1452 (protoeflags & MAP_ENTRY_NEEDS_COPY) != 0 ||
1453 object->cred == NULL,
1454 ("overcommit: vm_map_insert o %p", object));
1455 cred = curthread->td_ucred;
1459 /* Expand the kernel pmap, if necessary. */
1460 if (map == kernel_map && end > kernel_vm_end)
1461 pmap_growkernel(end);
1462 if (object != NULL) {
1464 * OBJ_ONEMAPPING must be cleared unless this mapping
1465 * is trivially proven to be the only mapping for any
1466 * of the object's pages. (Object granularity
1467 * reference counting is insufficient to recognize
1468 * aliases with precision.)
1470 VM_OBJECT_WLOCK(object);
1471 if (object->ref_count > 1 || object->shadow_count != 0)
1472 vm_object_clear_flag(object, OBJ_ONEMAPPING);
1473 VM_OBJECT_WUNLOCK(object);
1474 } else if ((prev_entry->eflags & ~MAP_ENTRY_USER_WIRED) ==
1476 (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP |
1477 MAP_VN_EXEC)) == 0 &&
1478 prev_entry->end == start && (prev_entry->cred == cred ||
1479 (prev_entry->object.vm_object != NULL &&
1480 prev_entry->object.vm_object->cred == cred)) &&
1481 vm_object_coalesce(prev_entry->object.vm_object,
1483 (vm_size_t)(prev_entry->end - prev_entry->start),
1484 (vm_size_t)(end - prev_entry->end), cred != NULL &&
1485 (protoeflags & MAP_ENTRY_NEEDS_COPY) == 0)) {
1487 * We were able to extend the object. Determine if we
1488 * can extend the previous map entry to include the
1489 * new range as well.
1491 if (prev_entry->inheritance == inheritance &&
1492 prev_entry->protection == prot &&
1493 prev_entry->max_protection == max &&
1494 prev_entry->wired_count == 0) {
1495 KASSERT((prev_entry->eflags & MAP_ENTRY_USER_WIRED) ==
1496 0, ("prev_entry %p has incoherent wiring",
1498 if ((prev_entry->eflags & MAP_ENTRY_GUARD) == 0)
1499 map->size += end - prev_entry->end;
1500 vm_map_entry_resize(map, prev_entry,
1501 end - prev_entry->end);
1502 vm_map_simplify_entry(map, prev_entry);
1503 return (KERN_SUCCESS);
1507 * If we can extend the object but cannot extend the
1508 * map entry, we have to create a new map entry. We
1509 * must bump the ref count on the extended object to
1510 * account for it. object may be NULL.
1512 object = prev_entry->object.vm_object;
1513 offset = prev_entry->offset +
1514 (prev_entry->end - prev_entry->start);
1515 vm_object_reference(object);
1516 if (cred != NULL && object != NULL && object->cred != NULL &&
1517 !(prev_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
1518 /* Object already accounts for this uid. */
1526 * Create a new entry
1528 new_entry = vm_map_entry_create(map);
1529 new_entry->start = start;
1530 new_entry->end = end;
1531 new_entry->cred = NULL;
1533 new_entry->eflags = protoeflags;
1534 new_entry->object.vm_object = object;
1535 new_entry->offset = offset;
1537 new_entry->inheritance = inheritance;
1538 new_entry->protection = prot;
1539 new_entry->max_protection = max;
1540 new_entry->wired_count = 0;
1541 new_entry->wiring_thread = NULL;
1542 new_entry->read_ahead = VM_FAULT_READ_AHEAD_INIT;
1543 new_entry->next_read = start;
1545 KASSERT(cred == NULL || !ENTRY_CHARGED(new_entry),
1546 ("overcommit: vm_map_insert leaks vm_map %p", new_entry));
1547 new_entry->cred = cred;
1550 * Insert the new entry into the list
1552 vm_map_entry_link(map, new_entry);
1553 if ((new_entry->eflags & MAP_ENTRY_GUARD) == 0)
1554 map->size += new_entry->end - new_entry->start;
1557 * Try to coalesce the new entry with both the previous and next
1558 * entries in the list. Previously, we only attempted to coalesce
1559 * with the previous entry when object is NULL. Here, we handle the
1560 * other cases, which are less common.
1562 vm_map_simplify_entry(map, new_entry);
1564 if ((cow & (MAP_PREFAULT | MAP_PREFAULT_PARTIAL)) != 0) {
1565 vm_map_pmap_enter(map, start, prot, object, OFF_TO_IDX(offset),
1566 end - start, cow & MAP_PREFAULT_PARTIAL);
1569 return (KERN_SUCCESS);
1575 * Find the first fit (lowest VM address) for "length" free bytes
1576 * beginning at address >= start in the given map.
1578 * In a vm_map_entry, "max_free" is the maximum amount of
1579 * contiguous free space between an entry in its subtree and a
1580 * neighbor of that entry. This allows finding a free region in
1581 * one path down the tree, so O(log n) amortized with splay
1584 * The map must be locked, and leaves it so.
1586 * Returns: starting address if sufficient space,
1587 * vm_map_max(map)-length+1 if insufficient space.
1590 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length)
1592 vm_map_entry_t llist, rlist, root, y;
1593 vm_size_t left_length;
1596 * Request must fit within min/max VM address and must avoid
1599 start = MAX(start, vm_map_min(map));
1600 if (start + length > vm_map_max(map) || start + length < start)
1601 return (vm_map_max(map) - length + 1);
1603 /* Empty tree means wide open address space. */
1604 if (map->root == NULL)
1608 * After splay, if start comes before root node, then there
1609 * must be a gap from start to the root.
1611 root = vm_map_splay_split(start, length, map->root,
1615 else if (rlist != NULL) {
1621 llist = root->right;
1624 map->root = vm_map_splay_merge(root, llist, rlist,
1625 root->left, root->right);
1626 VM_MAP_ASSERT_CONSISTENT(map);
1627 if (start + length <= root->start)
1631 * Root is the last node that might begin its gap before
1632 * start, and this is the last comparison where address
1633 * wrap might be a problem.
1635 if (root->right == NULL &&
1636 start + length <= vm_map_max(map))
1639 /* With max_free, can immediately tell if no solution. */
1640 if (root->right == NULL || length > root->right->max_free)
1641 return (vm_map_max(map) - length + 1);
1644 * Splay for the least large-enough gap in the right subtree.
1648 for (left_length = 0; ;
1649 left_length = root->left != NULL ?
1650 root->left->max_free : root->start - llist->end) {
1651 if (length <= left_length)
1652 SPLAY_LEFT_STEP(root, y, rlist,
1653 length <= (y->left != NULL ?
1654 y->left->max_free : y->start - llist->end));
1656 SPLAY_RIGHT_STEP(root, y, llist,
1657 length > (y->left != NULL ?
1658 y->left->max_free : y->start - root->end));
1663 llist = root->right;
1664 if ((y = rlist) == NULL)
1669 root->right = y->right;
1671 root = vm_map_splay_merge(root, llist, rlist,
1672 root->left, root->right);
1674 y->right = root->right;
1675 vm_map_entry_set_max_free(y);
1677 vm_map_entry_set_max_free(root);
1680 VM_MAP_ASSERT_CONSISTENT(map);
1685 vm_map_fixed(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1686 vm_offset_t start, vm_size_t length, vm_prot_t prot,
1687 vm_prot_t max, int cow)
1692 end = start + length;
1693 KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1695 ("vm_map_fixed: non-NULL backing object for stack"));
1697 VM_MAP_RANGE_CHECK(map, start, end);
1698 if ((cow & MAP_CHECK_EXCL) == 0)
1699 vm_map_delete(map, start, end);
1700 if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1701 result = vm_map_stack_locked(map, start, length, sgrowsiz,
1704 result = vm_map_insert(map, object, offset, start, end,
1711 static const int aslr_pages_rnd_64[2] = {0x1000, 0x10};
1712 static const int aslr_pages_rnd_32[2] = {0x100, 0x4};
1714 static int cluster_anon = 1;
1715 SYSCTL_INT(_vm, OID_AUTO, cluster_anon, CTLFLAG_RW,
1717 "Cluster anonymous mappings: 0 = no, 1 = yes if no hint, 2 = always");
1720 clustering_anon_allowed(vm_offset_t addr)
1723 switch (cluster_anon) {
1734 static long aslr_restarts;
1735 SYSCTL_LONG(_vm, OID_AUTO, aslr_restarts, CTLFLAG_RD,
1737 "Number of aslr failures");
1739 #define MAP_32BIT_MAX_ADDR ((vm_offset_t)1 << 31)
1742 * Searches for the specified amount of free space in the given map with the
1743 * specified alignment. Performs an address-ordered, first-fit search from
1744 * the given address "*addr", with an optional upper bound "max_addr". If the
1745 * parameter "alignment" is zero, then the alignment is computed from the
1746 * given (object, offset) pair so as to enable the greatest possible use of
1747 * superpage mappings. Returns KERN_SUCCESS and the address of the free space
1748 * in "*addr" if successful. Otherwise, returns KERN_NO_SPACE.
1750 * The map must be locked. Initially, there must be at least "length" bytes
1751 * of free space at the given address.
1754 vm_map_alignspace(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1755 vm_offset_t *addr, vm_size_t length, vm_offset_t max_addr,
1756 vm_offset_t alignment)
1758 vm_offset_t aligned_addr, free_addr;
1760 VM_MAP_ASSERT_LOCKED(map);
1762 KASSERT(free_addr == vm_map_findspace(map, free_addr, length),
1763 ("caller failed to provide space %d at address %p",
1764 (int)length, (void*)free_addr));
1767 * At the start of every iteration, the free space at address
1768 * "*addr" is at least "length" bytes.
1771 pmap_align_superpage(object, offset, addr, length);
1772 else if ((*addr & (alignment - 1)) != 0) {
1773 *addr &= ~(alignment - 1);
1776 aligned_addr = *addr;
1777 if (aligned_addr == free_addr) {
1779 * Alignment did not change "*addr", so "*addr" must
1780 * still provide sufficient free space.
1782 return (KERN_SUCCESS);
1786 * Test for address wrap on "*addr". A wrapped "*addr" could
1787 * be a valid address, in which case vm_map_findspace() cannot
1788 * be relied upon to fail.
1790 if (aligned_addr < free_addr)
1791 return (KERN_NO_SPACE);
1792 *addr = vm_map_findspace(map, aligned_addr, length);
1793 if (*addr + length > vm_map_max(map) ||
1794 (max_addr != 0 && *addr + length > max_addr))
1795 return (KERN_NO_SPACE);
1797 if (free_addr == aligned_addr) {
1799 * If a successful call to vm_map_findspace() did not
1800 * change "*addr", then "*addr" must still be aligned
1801 * and provide sufficient free space.
1803 return (KERN_SUCCESS);
1809 * vm_map_find finds an unallocated region in the target address
1810 * map with the given length. The search is defined to be
1811 * first-fit from the specified address; the region found is
1812 * returned in the same parameter.
1814 * If object is non-NULL, ref count must be bumped by caller
1815 * prior to making call to account for the new entry.
1818 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1819 vm_offset_t *addr, /* IN/OUT */
1820 vm_size_t length, vm_offset_t max_addr, int find_space,
1821 vm_prot_t prot, vm_prot_t max, int cow)
1823 vm_offset_t alignment, curr_min_addr, min_addr;
1824 int gap, pidx, rv, try;
1825 bool cluster, en_aslr, update_anon;
1827 KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1829 ("vm_map_find: non-NULL backing object for stack"));
1830 MPASS((cow & MAP_REMAP) == 0 || (find_space == VMFS_NO_SPACE &&
1831 (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0));
1832 if (find_space == VMFS_OPTIMAL_SPACE && (object == NULL ||
1833 (object->flags & OBJ_COLORED) == 0))
1834 find_space = VMFS_ANY_SPACE;
1835 if (find_space >> 8 != 0) {
1836 KASSERT((find_space & 0xff) == 0, ("bad VMFS flags"));
1837 alignment = (vm_offset_t)1 << (find_space >> 8);
1840 en_aslr = (map->flags & MAP_ASLR) != 0;
1841 update_anon = cluster = clustering_anon_allowed(*addr) &&
1842 (map->flags & MAP_IS_SUB_MAP) == 0 && max_addr == 0 &&
1843 find_space != VMFS_NO_SPACE && object == NULL &&
1844 (cow & (MAP_INHERIT_SHARE | MAP_STACK_GROWS_UP |
1845 MAP_STACK_GROWS_DOWN)) == 0 && prot != PROT_NONE;
1846 curr_min_addr = min_addr = *addr;
1847 if (en_aslr && min_addr == 0 && !cluster &&
1848 find_space != VMFS_NO_SPACE &&
1849 (map->flags & MAP_ASLR_IGNSTART) != 0)
1850 curr_min_addr = min_addr = vm_map_min(map);
1854 curr_min_addr = map->anon_loc;
1855 if (curr_min_addr == 0)
1858 if (find_space != VMFS_NO_SPACE) {
1859 KASSERT(find_space == VMFS_ANY_SPACE ||
1860 find_space == VMFS_OPTIMAL_SPACE ||
1861 find_space == VMFS_SUPER_SPACE ||
1862 alignment != 0, ("unexpected VMFS flag"));
1865 * When creating an anonymous mapping, try clustering
1866 * with an existing anonymous mapping first.
1868 * We make up to two attempts to find address space
1869 * for a given find_space value. The first attempt may
1870 * apply randomization or may cluster with an existing
1871 * anonymous mapping. If this first attempt fails,
1872 * perform a first-fit search of the available address
1875 * If all tries failed, and find_space is
1876 * VMFS_OPTIMAL_SPACE, fallback to VMFS_ANY_SPACE.
1877 * Again enable clustering and randomization.
1884 * Second try: we failed either to find a
1885 * suitable region for randomizing the
1886 * allocation, or to cluster with an existing
1887 * mapping. Retry with free run.
1889 curr_min_addr = (map->flags & MAP_ASLR_IGNSTART) != 0 ?
1890 vm_map_min(map) : min_addr;
1891 atomic_add_long(&aslr_restarts, 1);
1894 if (try == 1 && en_aslr && !cluster) {
1896 * Find space for allocation, including
1897 * gap needed for later randomization.
1899 pidx = MAXPAGESIZES > 1 && pagesizes[1] != 0 &&
1900 (find_space == VMFS_SUPER_SPACE || find_space ==
1901 VMFS_OPTIMAL_SPACE) ? 1 : 0;
1902 gap = vm_map_max(map) > MAP_32BIT_MAX_ADDR &&
1903 (max_addr == 0 || max_addr > MAP_32BIT_MAX_ADDR) ?
1904 aslr_pages_rnd_64[pidx] : aslr_pages_rnd_32[pidx];
1905 *addr = vm_map_findspace(map, curr_min_addr,
1906 length + gap * pagesizes[pidx]);
1907 if (*addr + length + gap * pagesizes[pidx] >
1910 /* And randomize the start address. */
1911 *addr += (arc4random() % gap) * pagesizes[pidx];
1912 if (max_addr != 0 && *addr + length > max_addr)
1915 *addr = vm_map_findspace(map, curr_min_addr, length);
1916 if (*addr + length > vm_map_max(map) ||
1917 (max_addr != 0 && *addr + length > max_addr)) {
1928 if (find_space != VMFS_ANY_SPACE &&
1929 (rv = vm_map_alignspace(map, object, offset, addr, length,
1930 max_addr, alignment)) != KERN_SUCCESS) {
1931 if (find_space == VMFS_OPTIMAL_SPACE) {
1932 find_space = VMFS_ANY_SPACE;
1933 curr_min_addr = min_addr;
1934 cluster = update_anon;
1940 } else if ((cow & MAP_REMAP) != 0) {
1941 if (*addr < vm_map_min(map) ||
1942 *addr + length > vm_map_max(map) ||
1943 *addr + length <= length) {
1944 rv = KERN_INVALID_ADDRESS;
1947 vm_map_delete(map, *addr, *addr + length);
1949 if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1950 rv = vm_map_stack_locked(map, *addr, length, sgrowsiz, prot,
1953 rv = vm_map_insert(map, object, offset, *addr, *addr + length,
1956 if (rv == KERN_SUCCESS && update_anon)
1957 map->anon_loc = *addr + length;
1964 * vm_map_find_min() is a variant of vm_map_find() that takes an
1965 * additional parameter (min_addr) and treats the given address
1966 * (*addr) differently. Specifically, it treats *addr as a hint
1967 * and not as the minimum address where the mapping is created.
1969 * This function works in two phases. First, it tries to
1970 * allocate above the hint. If that fails and the hint is
1971 * greater than min_addr, it performs a second pass, replacing
1972 * the hint with min_addr as the minimum address for the
1976 vm_map_find_min(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1977 vm_offset_t *addr, vm_size_t length, vm_offset_t min_addr,
1978 vm_offset_t max_addr, int find_space, vm_prot_t prot, vm_prot_t max,
1986 rv = vm_map_find(map, object, offset, addr, length, max_addr,
1987 find_space, prot, max, cow);
1988 if (rv == KERN_SUCCESS || min_addr >= hint)
1990 *addr = hint = min_addr;
1995 * A map entry with any of the following flags set must not be merged with
1998 #define MAP_ENTRY_NOMERGE_MASK (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP | \
1999 MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP | MAP_ENTRY_VN_EXEC)
2002 vm_map_mergeable_neighbors(vm_map_entry_t prev, vm_map_entry_t entry)
2005 KASSERT((prev->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 ||
2006 (entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0,
2007 ("vm_map_mergeable_neighbors: neither %p nor %p are mergeable",
2009 return (prev->end == entry->start &&
2010 prev->object.vm_object == entry->object.vm_object &&
2011 (prev->object.vm_object == NULL ||
2012 prev->offset + (prev->end - prev->start) == entry->offset) &&
2013 prev->eflags == entry->eflags &&
2014 prev->protection == entry->protection &&
2015 prev->max_protection == entry->max_protection &&
2016 prev->inheritance == entry->inheritance &&
2017 prev->wired_count == entry->wired_count &&
2018 prev->cred == entry->cred);
2022 vm_map_merged_neighbor_dispose(vm_map_t map, vm_map_entry_t entry)
2026 * If the backing object is a vnode object, vm_object_deallocate()
2027 * calls vrele(). However, vrele() does not lock the vnode because
2028 * the vnode has additional references. Thus, the map lock can be
2029 * kept without causing a lock-order reversal with the vnode lock.
2031 * Since we count the number of virtual page mappings in
2032 * object->un_pager.vnp.writemappings, the writemappings value
2033 * should not be adjusted when the entry is disposed of.
2035 if (entry->object.vm_object != NULL)
2036 vm_object_deallocate(entry->object.vm_object);
2037 if (entry->cred != NULL)
2038 crfree(entry->cred);
2039 vm_map_entry_dispose(map, entry);
2043 * vm_map_simplify_entry:
2045 * Simplify the given map entry by merging with either neighbor. This
2046 * routine also has the ability to merge with both neighbors.
2048 * The map must be locked.
2050 * This routine guarantees that the passed entry remains valid (though
2051 * possibly extended). When merging, this routine may delete one or
2055 vm_map_simplify_entry(vm_map_t map, vm_map_entry_t entry)
2057 vm_map_entry_t next, prev;
2059 if ((entry->eflags & MAP_ENTRY_NOMERGE_MASK) != 0)
2062 if (vm_map_mergeable_neighbors(prev, entry)) {
2063 vm_map_entry_unlink(map, prev, UNLINK_MERGE_NEXT);
2064 vm_map_merged_neighbor_dispose(map, prev);
2067 if (vm_map_mergeable_neighbors(entry, next)) {
2068 vm_map_entry_unlink(map, next, UNLINK_MERGE_PREV);
2069 vm_map_merged_neighbor_dispose(map, next);
2074 * vm_map_clip_start: [ internal use only ]
2076 * Asserts that the given entry begins at or after
2077 * the specified address; if necessary,
2078 * it splits the entry into two.
2080 #define vm_map_clip_start(map, entry, startaddr) \
2082 if (startaddr > entry->start) \
2083 _vm_map_clip_start(map, entry, startaddr); \
2087 * This routine is called only when it is known that
2088 * the entry must be split.
2091 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start)
2093 vm_map_entry_t new_entry;
2095 VM_MAP_ASSERT_LOCKED(map);
2096 KASSERT(entry->end > start && entry->start < start,
2097 ("_vm_map_clip_start: invalid clip of entry %p", entry));
2100 * Split off the front portion -- note that we must insert the new
2101 * entry BEFORE this one, so that this entry has the specified
2104 vm_map_simplify_entry(map, entry);
2107 * If there is no object backing this entry, we might as well create
2108 * one now. If we defer it, an object can get created after the map
2109 * is clipped, and individual objects will be created for the split-up
2110 * map. This is a bit of a hack, but is also about the best place to
2111 * put this improvement.
2113 if (entry->object.vm_object == NULL && !map->system_map &&
2114 (entry->eflags & MAP_ENTRY_GUARD) == 0) {
2116 object = vm_object_allocate(OBJT_DEFAULT,
2117 atop(entry->end - entry->start));
2118 entry->object.vm_object = object;
2120 if (entry->cred != NULL) {
2121 object->cred = entry->cred;
2122 object->charge = entry->end - entry->start;
2125 } else if (entry->object.vm_object != NULL &&
2126 ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
2127 entry->cred != NULL) {
2128 VM_OBJECT_WLOCK(entry->object.vm_object);
2129 KASSERT(entry->object.vm_object->cred == NULL,
2130 ("OVERCOMMIT: vm_entry_clip_start: both cred e %p", entry));
2131 entry->object.vm_object->cred = entry->cred;
2132 entry->object.vm_object->charge = entry->end - entry->start;
2133 VM_OBJECT_WUNLOCK(entry->object.vm_object);
2137 new_entry = vm_map_entry_create(map);
2138 *new_entry = *entry;
2140 new_entry->end = start;
2141 entry->offset += (start - entry->start);
2142 entry->start = start;
2143 if (new_entry->cred != NULL)
2144 crhold(entry->cred);
2146 vm_map_entry_link(map, new_entry);
2148 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2149 vm_object_reference(new_entry->object.vm_object);
2150 vm_map_entry_set_vnode_text(new_entry, true);
2152 * The object->un_pager.vnp.writemappings for the
2153 * object of MAP_ENTRY_VN_WRITECNT type entry shall be
2154 * kept as is here. The virtual pages are
2155 * re-distributed among the clipped entries, so the sum is
2162 * vm_map_clip_end: [ internal use only ]
2164 * Asserts that the given entry ends at or before
2165 * the specified address; if necessary,
2166 * it splits the entry into two.
2168 #define vm_map_clip_end(map, entry, endaddr) \
2170 if ((endaddr) < (entry->end)) \
2171 _vm_map_clip_end((map), (entry), (endaddr)); \
2175 * This routine is called only when it is known that
2176 * the entry must be split.
2179 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end)
2181 vm_map_entry_t new_entry;
2183 VM_MAP_ASSERT_LOCKED(map);
2184 KASSERT(entry->start < end && entry->end > end,
2185 ("_vm_map_clip_end: invalid clip of entry %p", entry));
2188 * If there is no object backing this entry, we might as well create
2189 * one now. If we defer it, an object can get created after the map
2190 * is clipped, and individual objects will be created for the split-up
2191 * map. This is a bit of a hack, but is also about the best place to
2192 * put this improvement.
2194 if (entry->object.vm_object == NULL && !map->system_map &&
2195 (entry->eflags & MAP_ENTRY_GUARD) == 0) {
2197 object = vm_object_allocate(OBJT_DEFAULT,
2198 atop(entry->end - entry->start));
2199 entry->object.vm_object = object;
2201 if (entry->cred != NULL) {
2202 object->cred = entry->cred;
2203 object->charge = entry->end - entry->start;
2206 } else if (entry->object.vm_object != NULL &&
2207 ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
2208 entry->cred != NULL) {
2209 VM_OBJECT_WLOCK(entry->object.vm_object);
2210 KASSERT(entry->object.vm_object->cred == NULL,
2211 ("OVERCOMMIT: vm_entry_clip_end: both cred e %p", entry));
2212 entry->object.vm_object->cred = entry->cred;
2213 entry->object.vm_object->charge = entry->end - entry->start;
2214 VM_OBJECT_WUNLOCK(entry->object.vm_object);
2219 * Create a new entry and insert it AFTER the specified entry
2221 new_entry = vm_map_entry_create(map);
2222 *new_entry = *entry;
2224 new_entry->start = entry->end = end;
2225 new_entry->offset += (end - entry->start);
2226 if (new_entry->cred != NULL)
2227 crhold(entry->cred);
2229 vm_map_entry_link(map, new_entry);
2231 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2232 vm_object_reference(new_entry->object.vm_object);
2233 vm_map_entry_set_vnode_text(new_entry, true);
2238 * vm_map_submap: [ kernel use only ]
2240 * Mark the given range as handled by a subordinate map.
2242 * This range must have been created with vm_map_find,
2243 * and no other operations may have been performed on this
2244 * range prior to calling vm_map_submap.
2246 * Only a limited number of operations can be performed
2247 * within this rage after calling vm_map_submap:
2249 * [Don't try vm_map_copy!]
2251 * To remove a submapping, one must first remove the
2252 * range from the superior map, and then destroy the
2253 * submap (if desired). [Better yet, don't try it.]
2262 vm_map_entry_t entry;
2265 result = KERN_INVALID_ARGUMENT;
2267 vm_map_lock(submap);
2268 submap->flags |= MAP_IS_SUB_MAP;
2269 vm_map_unlock(submap);
2273 VM_MAP_RANGE_CHECK(map, start, end);
2275 if (vm_map_lookup_entry(map, start, &entry)) {
2276 vm_map_clip_start(map, entry, start);
2278 entry = entry->next;
2280 vm_map_clip_end(map, entry, end);
2282 if ((entry->start == start) && (entry->end == end) &&
2283 ((entry->eflags & MAP_ENTRY_COW) == 0) &&
2284 (entry->object.vm_object == NULL)) {
2285 entry->object.sub_map = submap;
2286 entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
2287 result = KERN_SUCCESS;
2291 if (result != KERN_SUCCESS) {
2292 vm_map_lock(submap);
2293 submap->flags &= ~MAP_IS_SUB_MAP;
2294 vm_map_unlock(submap);
2300 * The maximum number of pages to map if MAP_PREFAULT_PARTIAL is specified
2302 #define MAX_INIT_PT 96
2305 * vm_map_pmap_enter:
2307 * Preload the specified map's pmap with mappings to the specified
2308 * object's memory-resident pages. No further physical pages are
2309 * allocated, and no further virtual pages are retrieved from secondary
2310 * storage. If the specified flags include MAP_PREFAULT_PARTIAL, then a
2311 * limited number of page mappings are created at the low-end of the
2312 * specified address range. (For this purpose, a superpage mapping
2313 * counts as one page mapping.) Otherwise, all resident pages within
2314 * the specified address range are mapped.
2317 vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
2318 vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
2321 vm_page_t p, p_start;
2322 vm_pindex_t mask, psize, threshold, tmpidx;
2324 if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0 || object == NULL)
2326 VM_OBJECT_RLOCK(object);
2327 if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2328 VM_OBJECT_RUNLOCK(object);
2329 VM_OBJECT_WLOCK(object);
2330 if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2331 pmap_object_init_pt(map->pmap, addr, object, pindex,
2333 VM_OBJECT_WUNLOCK(object);
2336 VM_OBJECT_LOCK_DOWNGRADE(object);
2340 if (psize + pindex > object->size) {
2341 if (object->size < pindex) {
2342 VM_OBJECT_RUNLOCK(object);
2345 psize = object->size - pindex;
2350 threshold = MAX_INIT_PT;
2352 p = vm_page_find_least(object, pindex);
2354 * Assert: the variable p is either (1) the page with the
2355 * least pindex greater than or equal to the parameter pindex
2359 p != NULL && (tmpidx = p->pindex - pindex) < psize;
2360 p = TAILQ_NEXT(p, listq)) {
2362 * don't allow an madvise to blow away our really
2363 * free pages allocating pv entries.
2365 if (((flags & MAP_PREFAULT_MADVISE) != 0 &&
2366 vm_page_count_severe()) ||
2367 ((flags & MAP_PREFAULT_PARTIAL) != 0 &&
2368 tmpidx >= threshold)) {
2372 if (p->valid == VM_PAGE_BITS_ALL) {
2373 if (p_start == NULL) {
2374 start = addr + ptoa(tmpidx);
2377 /* Jump ahead if a superpage mapping is possible. */
2378 if (p->psind > 0 && ((addr + ptoa(tmpidx)) &
2379 (pagesizes[p->psind] - 1)) == 0) {
2380 mask = atop(pagesizes[p->psind]) - 1;
2381 if (tmpidx + mask < psize &&
2382 vm_page_ps_test(p, PS_ALL_VALID, NULL)) {
2387 } else if (p_start != NULL) {
2388 pmap_enter_object(map->pmap, start, addr +
2389 ptoa(tmpidx), p_start, prot);
2393 if (p_start != NULL)
2394 pmap_enter_object(map->pmap, start, addr + ptoa(psize),
2396 VM_OBJECT_RUNLOCK(object);
2402 * Sets the protection of the specified address
2403 * region in the target map. If "set_max" is
2404 * specified, the maximum protection is to be set;
2405 * otherwise, only the current protection is affected.
2408 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
2409 vm_prot_t new_prot, boolean_t set_max)
2411 vm_map_entry_t current, entry, in_tran;
2417 return (KERN_SUCCESS);
2424 * Ensure that we are not concurrently wiring pages. vm_map_wire() may
2425 * need to fault pages into the map and will drop the map lock while
2426 * doing so, and the VM object may end up in an inconsistent state if we
2427 * update the protection on the map entry in between faults.
2429 vm_map_wait_busy(map);
2431 VM_MAP_RANGE_CHECK(map, start, end);
2433 if (vm_map_lookup_entry(map, start, &entry)) {
2434 vm_map_clip_start(map, entry, start);
2436 entry = entry->next;
2440 * Make a first pass to check for protection violations.
2442 for (current = entry; current->start < end; current = current->next) {
2443 if ((current->eflags & MAP_ENTRY_GUARD) != 0)
2445 if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
2447 return (KERN_INVALID_ARGUMENT);
2449 if ((new_prot & current->max_protection) != new_prot) {
2451 return (KERN_PROTECTION_FAILURE);
2453 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0)
2458 * Postpone the operation until all in transition map entries
2459 * are stabilized. In-transition entry might already have its
2460 * pages wired and wired_count incremented, but
2461 * MAP_ENTRY_USER_WIRED flag not yet set, and visible to other
2462 * threads because the map lock is dropped. In this case we
2463 * would miss our call to vm_fault_copy_entry().
2465 if (in_tran != NULL) {
2466 in_tran->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2467 vm_map_unlock_and_wait(map, 0);
2472 * Do an accounting pass for private read-only mappings that
2473 * now will do cow due to allowed write (e.g. debugger sets
2474 * breakpoint on text segment)
2476 for (current = entry; current->start < end; current = current->next) {
2478 vm_map_clip_end(map, current, end);
2481 ((new_prot & ~(current->protection)) & VM_PROT_WRITE) == 0 ||
2482 ENTRY_CHARGED(current) ||
2483 (current->eflags & MAP_ENTRY_GUARD) != 0) {
2487 cred = curthread->td_ucred;
2488 obj = current->object.vm_object;
2490 if (obj == NULL || (current->eflags & MAP_ENTRY_NEEDS_COPY)) {
2491 if (!swap_reserve(current->end - current->start)) {
2493 return (KERN_RESOURCE_SHORTAGE);
2496 current->cred = cred;
2500 VM_OBJECT_WLOCK(obj);
2501 if (obj->type != OBJT_DEFAULT && obj->type != OBJT_SWAP) {
2502 VM_OBJECT_WUNLOCK(obj);
2507 * Charge for the whole object allocation now, since
2508 * we cannot distinguish between non-charged and
2509 * charged clipped mapping of the same object later.
2511 KASSERT(obj->charge == 0,
2512 ("vm_map_protect: object %p overcharged (entry %p)",
2514 if (!swap_reserve(ptoa(obj->size))) {
2515 VM_OBJECT_WUNLOCK(obj);
2517 return (KERN_RESOURCE_SHORTAGE);
2522 obj->charge = ptoa(obj->size);
2523 VM_OBJECT_WUNLOCK(obj);
2527 * Go back and fix up protections. [Note that clipping is not
2528 * necessary the second time.]
2530 for (current = entry; current->start < end; current = current->next) {
2531 if ((current->eflags & MAP_ENTRY_GUARD) != 0)
2534 old_prot = current->protection;
2537 current->protection =
2538 (current->max_protection = new_prot) &
2541 current->protection = new_prot;
2544 * For user wired map entries, the normal lazy evaluation of
2545 * write access upgrades through soft page faults is
2546 * undesirable. Instead, immediately copy any pages that are
2547 * copy-on-write and enable write access in the physical map.
2549 if ((current->eflags & MAP_ENTRY_USER_WIRED) != 0 &&
2550 (current->protection & VM_PROT_WRITE) != 0 &&
2551 (old_prot & VM_PROT_WRITE) == 0)
2552 vm_fault_copy_entry(map, map, current, current, NULL);
2555 * When restricting access, update the physical map. Worry
2556 * about copy-on-write here.
2558 if ((old_prot & ~current->protection) != 0) {
2559 #define MASK(entry) (((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
2561 pmap_protect(map->pmap, current->start,
2563 current->protection & MASK(current));
2566 vm_map_simplify_entry(map, current);
2569 return (KERN_SUCCESS);
2575 * This routine traverses a processes map handling the madvise
2576 * system call. Advisories are classified as either those effecting
2577 * the vm_map_entry structure, or those effecting the underlying
2587 vm_map_entry_t current, entry;
2591 * Some madvise calls directly modify the vm_map_entry, in which case
2592 * we need to use an exclusive lock on the map and we need to perform
2593 * various clipping operations. Otherwise we only need a read-lock
2598 case MADV_SEQUENTIAL:
2615 vm_map_lock_read(map);
2622 * Locate starting entry and clip if necessary.
2624 VM_MAP_RANGE_CHECK(map, start, end);
2626 if (vm_map_lookup_entry(map, start, &entry)) {
2628 vm_map_clip_start(map, entry, start);
2630 entry = entry->next;
2635 * madvise behaviors that are implemented in the vm_map_entry.
2637 * We clip the vm_map_entry so that behavioral changes are
2638 * limited to the specified address range.
2640 for (current = entry; current->start < end;
2641 current = current->next) {
2642 if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2645 vm_map_clip_end(map, current, end);
2649 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
2651 case MADV_SEQUENTIAL:
2652 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
2655 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
2658 current->eflags |= MAP_ENTRY_NOSYNC;
2661 current->eflags &= ~MAP_ENTRY_NOSYNC;
2664 current->eflags |= MAP_ENTRY_NOCOREDUMP;
2667 current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
2672 vm_map_simplify_entry(map, current);
2676 vm_pindex_t pstart, pend;
2679 * madvise behaviors that are implemented in the underlying
2682 * Since we don't clip the vm_map_entry, we have to clip
2683 * the vm_object pindex and count.
2685 for (current = entry; current->start < end;
2686 current = current->next) {
2687 vm_offset_t useEnd, useStart;
2689 if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2692 pstart = OFF_TO_IDX(current->offset);
2693 pend = pstart + atop(current->end - current->start);
2694 useStart = current->start;
2695 useEnd = current->end;
2697 if (current->start < start) {
2698 pstart += atop(start - current->start);
2701 if (current->end > end) {
2702 pend -= atop(current->end - end);
2710 * Perform the pmap_advise() before clearing
2711 * PGA_REFERENCED in vm_page_advise(). Otherwise, a
2712 * concurrent pmap operation, such as pmap_remove(),
2713 * could clear a reference in the pmap and set
2714 * PGA_REFERENCED on the page before the pmap_advise()
2715 * had completed. Consequently, the page would appear
2716 * referenced based upon an old reference that
2717 * occurred before this pmap_advise() ran.
2719 if (behav == MADV_DONTNEED || behav == MADV_FREE)
2720 pmap_advise(map->pmap, useStart, useEnd,
2723 vm_object_madvise(current->object.vm_object, pstart,
2727 * Pre-populate paging structures in the
2728 * WILLNEED case. For wired entries, the
2729 * paging structures are already populated.
2731 if (behav == MADV_WILLNEED &&
2732 current->wired_count == 0) {
2733 vm_map_pmap_enter(map,
2735 current->protection,
2736 current->object.vm_object,
2738 ptoa(pend - pstart),
2739 MAP_PREFAULT_MADVISE
2743 vm_map_unlock_read(map);
2752 * Sets the inheritance of the specified address
2753 * range in the target map. Inheritance
2754 * affects how the map will be shared with
2755 * child maps at the time of vmspace_fork.
2758 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
2759 vm_inherit_t new_inheritance)
2761 vm_map_entry_t entry;
2762 vm_map_entry_t temp_entry;
2764 switch (new_inheritance) {
2765 case VM_INHERIT_NONE:
2766 case VM_INHERIT_COPY:
2767 case VM_INHERIT_SHARE:
2768 case VM_INHERIT_ZERO:
2771 return (KERN_INVALID_ARGUMENT);
2774 return (KERN_SUCCESS);
2776 VM_MAP_RANGE_CHECK(map, start, end);
2777 if (vm_map_lookup_entry(map, start, &temp_entry)) {
2779 vm_map_clip_start(map, entry, start);
2781 entry = temp_entry->next;
2782 while (entry->start < end) {
2783 vm_map_clip_end(map, entry, end);
2784 if ((entry->eflags & MAP_ENTRY_GUARD) == 0 ||
2785 new_inheritance != VM_INHERIT_ZERO)
2786 entry->inheritance = new_inheritance;
2787 vm_map_simplify_entry(map, entry);
2788 entry = entry->next;
2791 return (KERN_SUCCESS);
2797 * Implements both kernel and user unwiring.
2800 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
2803 vm_map_entry_t entry, first_entry, tmp_entry;
2804 vm_offset_t saved_start;
2805 unsigned int last_timestamp;
2807 boolean_t need_wakeup, result, user_unwire;
2810 return (KERN_SUCCESS);
2811 user_unwire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
2813 VM_MAP_RANGE_CHECK(map, start, end);
2814 if (!vm_map_lookup_entry(map, start, &first_entry)) {
2815 if (flags & VM_MAP_WIRE_HOLESOK)
2816 first_entry = first_entry->next;
2819 return (KERN_INVALID_ADDRESS);
2822 last_timestamp = map->timestamp;
2823 entry = first_entry;
2824 while (entry->start < end) {
2825 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2827 * We have not yet clipped the entry.
2829 saved_start = (start >= entry->start) ? start :
2831 entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2832 if (vm_map_unlock_and_wait(map, 0)) {
2834 * Allow interruption of user unwiring?
2838 if (last_timestamp+1 != map->timestamp) {
2840 * Look again for the entry because the map was
2841 * modified while it was unlocked.
2842 * Specifically, the entry may have been
2843 * clipped, merged, or deleted.
2845 if (!vm_map_lookup_entry(map, saved_start,
2847 if (flags & VM_MAP_WIRE_HOLESOK)
2848 tmp_entry = tmp_entry->next;
2850 if (saved_start == start) {
2852 * First_entry has been deleted.
2855 return (KERN_INVALID_ADDRESS);
2858 rv = KERN_INVALID_ADDRESS;
2862 if (entry == first_entry)
2863 first_entry = tmp_entry;
2868 last_timestamp = map->timestamp;
2871 vm_map_clip_start(map, entry, start);
2872 vm_map_clip_end(map, entry, end);
2874 * Mark the entry in case the map lock is released. (See
2877 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
2878 entry->wiring_thread == NULL,
2879 ("owned map entry %p", entry));
2880 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
2881 entry->wiring_thread = curthread;
2883 * Check the map for holes in the specified region.
2884 * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
2886 if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
2887 (entry->end < end && entry->next->start > entry->end)) {
2889 rv = KERN_INVALID_ADDRESS;
2893 * If system unwiring, require that the entry is system wired.
2896 vm_map_entry_system_wired_count(entry) == 0) {
2898 rv = KERN_INVALID_ARGUMENT;
2901 entry = entry->next;
2905 need_wakeup = FALSE;
2906 if (first_entry == NULL) {
2907 result = vm_map_lookup_entry(map, start, &first_entry);
2908 if (!result && (flags & VM_MAP_WIRE_HOLESOK))
2909 first_entry = first_entry->next;
2911 KASSERT(result, ("vm_map_unwire: lookup failed"));
2913 for (entry = first_entry; entry->start < end; entry = entry->next) {
2915 * If VM_MAP_WIRE_HOLESOK was specified, an empty
2916 * space in the unwired region could have been mapped
2917 * while the map lock was dropped for draining
2918 * MAP_ENTRY_IN_TRANSITION. Moreover, another thread
2919 * could be simultaneously wiring this new mapping
2920 * entry. Detect these cases and skip any entries
2921 * marked as in transition by us.
2923 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
2924 entry->wiring_thread != curthread) {
2925 KASSERT((flags & VM_MAP_WIRE_HOLESOK) != 0,
2926 ("vm_map_unwire: !HOLESOK and new/changed entry"));
2930 if (rv == KERN_SUCCESS && (!user_unwire ||
2931 (entry->eflags & MAP_ENTRY_USER_WIRED))) {
2932 if (entry->wired_count == 1)
2933 vm_map_entry_unwire(map, entry);
2935 entry->wired_count--;
2937 entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2939 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
2940 ("vm_map_unwire: in-transition flag missing %p", entry));
2941 KASSERT(entry->wiring_thread == curthread,
2942 ("vm_map_unwire: alien wire %p", entry));
2943 entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
2944 entry->wiring_thread = NULL;
2945 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
2946 entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
2949 vm_map_simplify_entry(map, entry);
2958 vm_map_wire_user_count_sub(u_long npages)
2961 atomic_subtract_long(&vm_user_wire_count, npages);
2965 vm_map_wire_user_count_add(u_long npages)
2969 wired = vm_user_wire_count;
2971 if (npages + wired > vm_page_max_user_wired)
2973 } while (!atomic_fcmpset_long(&vm_user_wire_count, &wired,
2980 * vm_map_wire_entry_failure:
2982 * Handle a wiring failure on the given entry.
2984 * The map should be locked.
2987 vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
2988 vm_offset_t failed_addr)
2991 VM_MAP_ASSERT_LOCKED(map);
2992 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 &&
2993 entry->wired_count == 1,
2994 ("vm_map_wire_entry_failure: entry %p isn't being wired", entry));
2995 KASSERT(failed_addr < entry->end,
2996 ("vm_map_wire_entry_failure: entry %p was fully wired", entry));
2999 * If any pages at the start of this entry were successfully wired,
3002 if (failed_addr > entry->start) {
3003 pmap_unwire(map->pmap, entry->start, failed_addr);
3004 vm_object_unwire(entry->object.vm_object, entry->offset,
3005 failed_addr - entry->start, PQ_ACTIVE);
3009 * Assign an out-of-range value to represent the failure to wire this
3012 entry->wired_count = -1;
3016 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3021 rv = vm_map_wire_locked(map, start, end, flags);
3028 * vm_map_wire_locked:
3030 * Implements both kernel and user wiring. Returns with the map locked,
3031 * the map lock may be dropped.
3034 vm_map_wire_locked(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3036 vm_map_entry_t entry, first_entry, tmp_entry;
3037 vm_offset_t faddr, saved_end, saved_start;
3039 u_int last_timestamp;
3041 boolean_t need_wakeup, result, user_wire;
3044 VM_MAP_ASSERT_LOCKED(map);
3047 return (KERN_SUCCESS);
3049 if (flags & VM_MAP_WIRE_WRITE)
3050 prot |= VM_PROT_WRITE;
3051 user_wire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
3052 VM_MAP_RANGE_CHECK(map, start, end);
3053 if (!vm_map_lookup_entry(map, start, &first_entry)) {
3054 if (flags & VM_MAP_WIRE_HOLESOK)
3055 first_entry = first_entry->next;
3057 return (KERN_INVALID_ADDRESS);
3059 last_timestamp = map->timestamp;
3060 entry = first_entry;
3061 while (entry->start < end) {
3062 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
3064 * We have not yet clipped the entry.
3066 saved_start = (start >= entry->start) ? start :
3068 entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3069 if (vm_map_unlock_and_wait(map, 0)) {
3071 * Allow interruption of user wiring?
3075 if (last_timestamp + 1 != map->timestamp) {
3077 * Look again for the entry because the map was
3078 * modified while it was unlocked.
3079 * Specifically, the entry may have been
3080 * clipped, merged, or deleted.
3082 if (!vm_map_lookup_entry(map, saved_start,
3084 if (flags & VM_MAP_WIRE_HOLESOK)
3085 tmp_entry = tmp_entry->next;
3087 if (saved_start == start) {
3089 * first_entry has been deleted.
3091 return (KERN_INVALID_ADDRESS);
3094 rv = KERN_INVALID_ADDRESS;
3098 if (entry == first_entry)
3099 first_entry = tmp_entry;
3104 last_timestamp = map->timestamp;
3107 vm_map_clip_start(map, entry, start);
3108 vm_map_clip_end(map, entry, end);
3110 * Mark the entry in case the map lock is released. (See
3113 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
3114 entry->wiring_thread == NULL,
3115 ("owned map entry %p", entry));
3116 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
3117 entry->wiring_thread = curthread;
3118 if ((entry->protection & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0
3119 || (entry->protection & prot) != prot) {
3120 entry->eflags |= MAP_ENTRY_WIRE_SKIPPED;
3121 if ((flags & VM_MAP_WIRE_HOLESOK) == 0) {
3123 rv = KERN_INVALID_ADDRESS;
3128 if (entry->wired_count == 0) {
3129 entry->wired_count++;
3131 npages = atop(entry->end - entry->start);
3132 if (user_wire && !vm_map_wire_user_count_add(npages)) {
3133 vm_map_wire_entry_failure(map, entry,
3136 rv = KERN_RESOURCE_SHORTAGE;
3141 * Release the map lock, relying on the in-transition
3142 * mark. Mark the map busy for fork.
3144 saved_start = entry->start;
3145 saved_end = entry->end;
3149 faddr = saved_start;
3152 * Simulate a fault to get the page and enter
3153 * it into the physical map.
3155 if ((rv = vm_fault(map, faddr, VM_PROT_NONE,
3156 VM_FAULT_WIRE)) != KERN_SUCCESS)
3158 } while ((faddr += PAGE_SIZE) < saved_end);
3161 if (last_timestamp + 1 != map->timestamp) {
3163 * Look again for the entry because the map was
3164 * modified while it was unlocked. The entry
3165 * may have been clipped, but NOT merged or
3168 result = vm_map_lookup_entry(map, saved_start,
3170 KASSERT(result, ("vm_map_wire: lookup failed"));
3171 if (entry == first_entry)
3172 first_entry = tmp_entry;
3176 while (entry->end < saved_end) {
3178 * In case of failure, handle entries
3179 * that were not fully wired here;
3180 * fully wired entries are handled
3183 if (rv != KERN_SUCCESS &&
3185 vm_map_wire_entry_failure(map,
3187 entry = entry->next;
3190 last_timestamp = map->timestamp;
3191 if (rv != KERN_SUCCESS) {
3192 vm_map_wire_entry_failure(map, entry, faddr);
3194 vm_map_wire_user_count_sub(npages);
3198 } else if (!user_wire ||
3199 (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3200 entry->wired_count++;
3203 * Check the map for holes in the specified region.
3204 * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
3207 if ((flags & VM_MAP_WIRE_HOLESOK) == 0 &&
3208 entry->end < end && entry->next->start > entry->end) {
3210 rv = KERN_INVALID_ADDRESS;
3213 entry = entry->next;
3217 need_wakeup = FALSE;
3218 if (first_entry == NULL) {
3219 result = vm_map_lookup_entry(map, start, &first_entry);
3220 if (!result && (flags & VM_MAP_WIRE_HOLESOK))
3221 first_entry = first_entry->next;
3223 KASSERT(result, ("vm_map_wire: lookup failed"));
3225 for (entry = first_entry; entry->start < end; entry = entry->next) {
3227 * If VM_MAP_WIRE_HOLESOK was specified, an empty
3228 * space in the unwired region could have been mapped
3229 * while the map lock was dropped for faulting in the
3230 * pages or draining MAP_ENTRY_IN_TRANSITION.
3231 * Moreover, another thread could be simultaneously
3232 * wiring this new mapping entry. Detect these cases
3233 * and skip any entries marked as in transition not by us.
3235 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
3236 entry->wiring_thread != curthread) {
3237 KASSERT((flags & VM_MAP_WIRE_HOLESOK) != 0,
3238 ("vm_map_wire: !HOLESOK and new/changed entry"));
3242 if ((entry->eflags & MAP_ENTRY_WIRE_SKIPPED) != 0)
3243 goto next_entry_done;
3245 if (rv == KERN_SUCCESS) {
3247 entry->eflags |= MAP_ENTRY_USER_WIRED;
3248 } else if (entry->wired_count == -1) {
3250 * Wiring failed on this entry. Thus, unwiring is
3253 entry->wired_count = 0;
3254 } else if (!user_wire ||
3255 (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3257 * Undo the wiring. Wiring succeeded on this entry
3258 * but failed on a later entry.
3260 if (entry->wired_count == 1) {
3261 vm_map_entry_unwire(map, entry);
3263 vm_map_wire_user_count_sub(
3264 atop(entry->end - entry->start));
3266 entry->wired_count--;
3269 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3270 ("vm_map_wire: in-transition flag missing %p", entry));
3271 KASSERT(entry->wiring_thread == curthread,
3272 ("vm_map_wire: alien wire %p", entry));
3273 entry->eflags &= ~(MAP_ENTRY_IN_TRANSITION |
3274 MAP_ENTRY_WIRE_SKIPPED);
3275 entry->wiring_thread = NULL;
3276 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
3277 entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
3280 vm_map_simplify_entry(map, entry);
3290 * Push any dirty cached pages in the address range to their pager.
3291 * If syncio is TRUE, dirty pages are written synchronously.
3292 * If invalidate is TRUE, any cached pages are freed as well.
3294 * If the size of the region from start to end is zero, we are
3295 * supposed to flush all modified pages within the region containing
3296 * start. Unfortunately, a region can be split or coalesced with
3297 * neighboring regions, making it difficult to determine what the
3298 * original region was. Therefore, we approximate this requirement by
3299 * flushing the current region containing start.
3301 * Returns an error if any part of the specified range is not mapped.
3309 boolean_t invalidate)
3311 vm_map_entry_t current;
3312 vm_map_entry_t entry;
3315 vm_ooffset_t offset;
3316 unsigned int last_timestamp;
3319 vm_map_lock_read(map);
3320 VM_MAP_RANGE_CHECK(map, start, end);
3321 if (!vm_map_lookup_entry(map, start, &entry)) {
3322 vm_map_unlock_read(map);
3323 return (KERN_INVALID_ADDRESS);
3324 } else if (start == end) {
3325 start = entry->start;
3329 * Make a first pass to check for user-wired memory and holes.
3331 for (current = entry; current->start < end; current = current->next) {
3332 if (invalidate && (current->eflags & MAP_ENTRY_USER_WIRED)) {
3333 vm_map_unlock_read(map);
3334 return (KERN_INVALID_ARGUMENT);
3336 if (end > current->end &&
3337 current->end != current->next->start) {
3338 vm_map_unlock_read(map);
3339 return (KERN_INVALID_ADDRESS);
3344 pmap_remove(map->pmap, start, end);
3348 * Make a second pass, cleaning/uncaching pages from the indicated
3351 for (current = entry; current->start < end;) {
3352 offset = current->offset + (start - current->start);
3353 size = (end <= current->end ? end : current->end) - start;
3354 if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
3356 vm_map_entry_t tentry;
3359 smap = current->object.sub_map;
3360 vm_map_lock_read(smap);
3361 (void) vm_map_lookup_entry(smap, offset, &tentry);
3362 tsize = tentry->end - offset;
3365 object = tentry->object.vm_object;
3366 offset = tentry->offset + (offset - tentry->start);
3367 vm_map_unlock_read(smap);
3369 object = current->object.vm_object;
3371 vm_object_reference(object);
3372 last_timestamp = map->timestamp;
3373 vm_map_unlock_read(map);
3374 if (!vm_object_sync(object, offset, size, syncio, invalidate))
3377 vm_object_deallocate(object);
3378 vm_map_lock_read(map);
3379 if (last_timestamp == map->timestamp ||
3380 !vm_map_lookup_entry(map, start, ¤t))
3381 current = current->next;
3384 vm_map_unlock_read(map);
3385 return (failed ? KERN_FAILURE : KERN_SUCCESS);
3389 * vm_map_entry_unwire: [ internal use only ]
3391 * Make the region specified by this entry pageable.
3393 * The map in question should be locked.
3394 * [This is the reason for this routine's existence.]
3397 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
3401 VM_MAP_ASSERT_LOCKED(map);
3402 KASSERT(entry->wired_count > 0,
3403 ("vm_map_entry_unwire: entry %p isn't wired", entry));
3405 size = entry->end - entry->start;
3406 if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0)
3407 vm_map_wire_user_count_sub(atop(size));
3408 pmap_unwire(map->pmap, entry->start, entry->end);
3409 vm_object_unwire(entry->object.vm_object, entry->offset, size,
3411 entry->wired_count = 0;
3415 vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map)
3418 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
3419 vm_object_deallocate(entry->object.vm_object);
3420 uma_zfree(system_map ? kmapentzone : mapentzone, entry);
3424 * vm_map_entry_delete: [ internal use only ]
3426 * Deallocate the given entry from the target map.
3429 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
3432 vm_pindex_t offidxstart, offidxend, count, size1;
3435 vm_map_entry_unlink(map, entry, UNLINK_MERGE_NONE);
3436 object = entry->object.vm_object;
3438 if ((entry->eflags & MAP_ENTRY_GUARD) != 0) {
3439 MPASS(entry->cred == NULL);
3440 MPASS((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0);
3441 MPASS(object == NULL);
3442 vm_map_entry_deallocate(entry, map->system_map);
3446 size = entry->end - entry->start;
3449 if (entry->cred != NULL) {
3450 swap_release_by_cred(size, entry->cred);
3451 crfree(entry->cred);
3454 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
3456 KASSERT(entry->cred == NULL || object->cred == NULL ||
3457 (entry->eflags & MAP_ENTRY_NEEDS_COPY),
3458 ("OVERCOMMIT vm_map_entry_delete: both cred %p", entry));
3460 offidxstart = OFF_TO_IDX(entry->offset);
3461 offidxend = offidxstart + count;
3462 VM_OBJECT_WLOCK(object);
3463 if (object->ref_count != 1 && ((object->flags & (OBJ_NOSPLIT |
3464 OBJ_ONEMAPPING)) == OBJ_ONEMAPPING ||
3465 object == kernel_object)) {
3466 vm_object_collapse(object);
3469 * The option OBJPR_NOTMAPPED can be passed here
3470 * because vm_map_delete() already performed
3471 * pmap_remove() on the only mapping to this range
3474 vm_object_page_remove(object, offidxstart, offidxend,
3476 if (object->type == OBJT_SWAP)
3477 swap_pager_freespace(object, offidxstart,
3479 if (offidxend >= object->size &&
3480 offidxstart < object->size) {
3481 size1 = object->size;
3482 object->size = offidxstart;
3483 if (object->cred != NULL) {
3484 size1 -= object->size;
3485 KASSERT(object->charge >= ptoa(size1),
3486 ("object %p charge < 0", object));
3487 swap_release_by_cred(ptoa(size1),
3489 object->charge -= ptoa(size1);
3493 VM_OBJECT_WUNLOCK(object);
3495 entry->object.vm_object = NULL;
3496 if (map->system_map)
3497 vm_map_entry_deallocate(entry, TRUE);
3499 entry->next = curthread->td_map_def_user;
3500 curthread->td_map_def_user = entry;
3505 * vm_map_delete: [ internal use only ]
3507 * Deallocates the given address range from the target
3511 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
3513 vm_map_entry_t entry;
3514 vm_map_entry_t first_entry;
3516 VM_MAP_ASSERT_LOCKED(map);
3518 return (KERN_SUCCESS);
3521 * Find the start of the region, and clip it
3523 if (!vm_map_lookup_entry(map, start, &first_entry))
3524 entry = first_entry->next;
3526 entry = first_entry;
3527 vm_map_clip_start(map, entry, start);
3531 * Step through all entries in this region
3533 while (entry->start < end) {
3534 vm_map_entry_t next;
3537 * Wait for wiring or unwiring of an entry to complete.
3538 * Also wait for any system wirings to disappear on
3541 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
3542 (vm_map_pmap(map) != kernel_pmap &&
3543 vm_map_entry_system_wired_count(entry) != 0)) {
3544 unsigned int last_timestamp;
3545 vm_offset_t saved_start;
3546 vm_map_entry_t tmp_entry;
3548 saved_start = entry->start;
3549 entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3550 last_timestamp = map->timestamp;
3551 (void) vm_map_unlock_and_wait(map, 0);
3553 if (last_timestamp + 1 != map->timestamp) {
3555 * Look again for the entry because the map was
3556 * modified while it was unlocked.
3557 * Specifically, the entry may have been
3558 * clipped, merged, or deleted.
3560 if (!vm_map_lookup_entry(map, saved_start,
3562 entry = tmp_entry->next;
3565 vm_map_clip_start(map, entry,
3571 vm_map_clip_end(map, entry, end);
3576 * Unwire before removing addresses from the pmap; otherwise,
3577 * unwiring will put the entries back in the pmap.
3579 if (entry->wired_count != 0)
3580 vm_map_entry_unwire(map, entry);
3583 * Remove mappings for the pages, but only if the
3584 * mappings could exist. For instance, it does not
3585 * make sense to call pmap_remove() for guard entries.
3587 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 ||
3588 entry->object.vm_object != NULL)
3589 pmap_remove(map->pmap, entry->start, entry->end);
3591 if (entry->end == map->anon_loc)
3592 map->anon_loc = entry->start;
3595 * Delete the entry only after removing all pmap
3596 * entries pointing to its pages. (Otherwise, its
3597 * page frames may be reallocated, and any modify bits
3598 * will be set in the wrong object!)
3600 vm_map_entry_delete(map, entry);
3603 return (KERN_SUCCESS);
3609 * Remove the given address range from the target map.
3610 * This is the exported form of vm_map_delete.
3613 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
3618 VM_MAP_RANGE_CHECK(map, start, end);
3619 result = vm_map_delete(map, start, end);
3625 * vm_map_check_protection:
3627 * Assert that the target map allows the specified privilege on the
3628 * entire address region given. The entire region must be allocated.
3630 * WARNING! This code does not and should not check whether the
3631 * contents of the region is accessible. For example a smaller file
3632 * might be mapped into a larger address space.
3634 * NOTE! This code is also called by munmap().
3636 * The map must be locked. A read lock is sufficient.
3639 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
3640 vm_prot_t protection)
3642 vm_map_entry_t entry;
3643 vm_map_entry_t tmp_entry;
3645 if (!vm_map_lookup_entry(map, start, &tmp_entry))
3649 while (start < end) {
3653 if (start < entry->start)
3656 * Check protection associated with entry.
3658 if ((entry->protection & protection) != protection)
3660 /* go to next entry */
3662 entry = entry->next;
3668 * vm_map_copy_entry:
3670 * Copies the contents of the source entry to the destination
3671 * entry. The entries *must* be aligned properly.
3677 vm_map_entry_t src_entry,
3678 vm_map_entry_t dst_entry,
3679 vm_ooffset_t *fork_charge)
3681 vm_object_t src_object;
3682 vm_map_entry_t fake_entry;
3687 VM_MAP_ASSERT_LOCKED(dst_map);
3689 if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
3692 if (src_entry->wired_count == 0 ||
3693 (src_entry->protection & VM_PROT_WRITE) == 0) {
3695 * If the source entry is marked needs_copy, it is already
3698 if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0 &&
3699 (src_entry->protection & VM_PROT_WRITE) != 0) {
3700 pmap_protect(src_map->pmap,
3703 src_entry->protection & ~VM_PROT_WRITE);
3707 * Make a copy of the object.
3709 size = src_entry->end - src_entry->start;
3710 if ((src_object = src_entry->object.vm_object) != NULL) {
3711 VM_OBJECT_WLOCK(src_object);
3712 charged = ENTRY_CHARGED(src_entry);
3713 if (src_object->handle == NULL &&
3714 (src_object->type == OBJT_DEFAULT ||
3715 src_object->type == OBJT_SWAP)) {
3716 vm_object_collapse(src_object);
3717 if ((src_object->flags & (OBJ_NOSPLIT |
3718 OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
3719 vm_object_split(src_entry);
3721 src_entry->object.vm_object;
3724 vm_object_reference_locked(src_object);
3725 vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
3726 if (src_entry->cred != NULL &&
3727 !(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
3728 KASSERT(src_object->cred == NULL,
3729 ("OVERCOMMIT: vm_map_copy_entry: cred %p",
3731 src_object->cred = src_entry->cred;
3732 src_object->charge = size;
3734 VM_OBJECT_WUNLOCK(src_object);
3735 dst_entry->object.vm_object = src_object;
3737 cred = curthread->td_ucred;
3739 dst_entry->cred = cred;
3740 *fork_charge += size;
3741 if (!(src_entry->eflags &
3742 MAP_ENTRY_NEEDS_COPY)) {
3744 src_entry->cred = cred;
3745 *fork_charge += size;
3748 src_entry->eflags |= MAP_ENTRY_COW |
3749 MAP_ENTRY_NEEDS_COPY;
3750 dst_entry->eflags |= MAP_ENTRY_COW |
3751 MAP_ENTRY_NEEDS_COPY;
3752 dst_entry->offset = src_entry->offset;
3753 if (src_entry->eflags & MAP_ENTRY_VN_WRITECNT) {
3755 * MAP_ENTRY_VN_WRITECNT cannot
3756 * indicate write reference from
3757 * src_entry, since the entry is
3758 * marked as needs copy. Allocate a
3759 * fake entry that is used to
3760 * decrement object->un_pager.vnp.writecount
3761 * at the appropriate time. Attach
3762 * fake_entry to the deferred list.
3764 fake_entry = vm_map_entry_create(dst_map);
3765 fake_entry->eflags = MAP_ENTRY_VN_WRITECNT;
3766 src_entry->eflags &= ~MAP_ENTRY_VN_WRITECNT;
3767 vm_object_reference(src_object);
3768 fake_entry->object.vm_object = src_object;
3769 fake_entry->start = src_entry->start;
3770 fake_entry->end = src_entry->end;
3771 fake_entry->next = curthread->td_map_def_user;
3772 curthread->td_map_def_user = fake_entry;
3775 pmap_copy(dst_map->pmap, src_map->pmap,
3776 dst_entry->start, dst_entry->end - dst_entry->start,
3779 dst_entry->object.vm_object = NULL;
3780 dst_entry->offset = 0;
3781 if (src_entry->cred != NULL) {
3782 dst_entry->cred = curthread->td_ucred;
3783 crhold(dst_entry->cred);
3784 *fork_charge += size;
3789 * We don't want to make writeable wired pages copy-on-write.
3790 * Immediately copy these pages into the new map by simulating
3791 * page faults. The new pages are pageable.
3793 vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry,
3799 * vmspace_map_entry_forked:
3800 * Update the newly-forked vmspace each time a map entry is inherited
3801 * or copied. The values for vm_dsize and vm_tsize are approximate
3802 * (and mostly-obsolete ideas in the face of mmap(2) et al.)
3805 vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
3806 vm_map_entry_t entry)
3808 vm_size_t entrysize;
3811 if ((entry->eflags & MAP_ENTRY_GUARD) != 0)
3813 entrysize = entry->end - entry->start;
3814 vm2->vm_map.size += entrysize;
3815 if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
3816 vm2->vm_ssize += btoc(entrysize);
3817 } else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
3818 entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
3819 newend = MIN(entry->end,
3820 (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
3821 vm2->vm_dsize += btoc(newend - entry->start);
3822 } else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
3823 entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
3824 newend = MIN(entry->end,
3825 (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
3826 vm2->vm_tsize += btoc(newend - entry->start);
3832 * Create a new process vmspace structure and vm_map
3833 * based on those of an existing process. The new map
3834 * is based on the old map, according to the inheritance
3835 * values on the regions in that map.
3837 * XXX It might be worth coalescing the entries added to the new vmspace.
3839 * The source map must not be locked.
3842 vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
3844 struct vmspace *vm2;
3845 vm_map_t new_map, old_map;
3846 vm_map_entry_t new_entry, old_entry;
3851 old_map = &vm1->vm_map;
3852 /* Copy immutable fields of vm1 to vm2. */
3853 vm2 = vmspace_alloc(vm_map_min(old_map), vm_map_max(old_map),
3858 vm2->vm_taddr = vm1->vm_taddr;
3859 vm2->vm_daddr = vm1->vm_daddr;
3860 vm2->vm_maxsaddr = vm1->vm_maxsaddr;
3861 vm_map_lock(old_map);
3863 vm_map_wait_busy(old_map);
3864 new_map = &vm2->vm_map;
3865 locked = vm_map_trylock(new_map); /* trylock to silence WITNESS */
3866 KASSERT(locked, ("vmspace_fork: lock failed"));
3868 error = pmap_vmspace_copy(new_map->pmap, old_map->pmap);
3870 sx_xunlock(&old_map->lock);
3871 sx_xunlock(&new_map->lock);
3872 vm_map_process_deferred();
3877 new_map->anon_loc = old_map->anon_loc;
3879 old_entry = old_map->header.next;
3881 while (old_entry != &old_map->header) {
3882 if (old_entry->eflags & MAP_ENTRY_IS_SUB_MAP)
3883 panic("vm_map_fork: encountered a submap");
3885 inh = old_entry->inheritance;
3886 if ((old_entry->eflags & MAP_ENTRY_GUARD) != 0 &&
3887 inh != VM_INHERIT_NONE)
3888 inh = VM_INHERIT_COPY;
3891 case VM_INHERIT_NONE:
3894 case VM_INHERIT_SHARE:
3896 * Clone the entry, creating the shared object if necessary.
3898 object = old_entry->object.vm_object;
3899 if (object == NULL) {
3900 object = vm_object_allocate(OBJT_DEFAULT,
3901 atop(old_entry->end - old_entry->start));
3902 old_entry->object.vm_object = object;
3903 old_entry->offset = 0;
3904 if (old_entry->cred != NULL) {
3905 object->cred = old_entry->cred;
3906 object->charge = old_entry->end -
3908 old_entry->cred = NULL;
3913 * Add the reference before calling vm_object_shadow
3914 * to insure that a shadow object is created.
3916 vm_object_reference(object);
3917 if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3918 vm_object_shadow(&old_entry->object.vm_object,
3920 old_entry->end - old_entry->start);
3921 old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
3922 /* Transfer the second reference too. */
3923 vm_object_reference(
3924 old_entry->object.vm_object);
3927 * As in vm_map_simplify_entry(), the
3928 * vnode lock will not be acquired in
3929 * this call to vm_object_deallocate().
3931 vm_object_deallocate(object);
3932 object = old_entry->object.vm_object;
3934 VM_OBJECT_WLOCK(object);
3935 vm_object_clear_flag(object, OBJ_ONEMAPPING);
3936 if (old_entry->cred != NULL) {
3937 KASSERT(object->cred == NULL, ("vmspace_fork both cred"));
3938 object->cred = old_entry->cred;
3939 object->charge = old_entry->end - old_entry->start;
3940 old_entry->cred = NULL;
3944 * Assert the correct state of the vnode
3945 * v_writecount while the object is locked, to
3946 * not relock it later for the assertion
3949 if (old_entry->eflags & MAP_ENTRY_VN_WRITECNT &&
3950 object->type == OBJT_VNODE) {
3951 KASSERT(((struct vnode *)object->handle)->
3953 ("vmspace_fork: v_writecount %p", object));
3954 KASSERT(object->un_pager.vnp.writemappings > 0,
3955 ("vmspace_fork: vnp.writecount %p",
3958 VM_OBJECT_WUNLOCK(object);
3961 * Clone the entry, referencing the shared object.
3963 new_entry = vm_map_entry_create(new_map);
3964 *new_entry = *old_entry;
3965 new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
3966 MAP_ENTRY_IN_TRANSITION);
3967 new_entry->wiring_thread = NULL;
3968 new_entry->wired_count = 0;
3969 if (new_entry->eflags & MAP_ENTRY_VN_WRITECNT) {
3970 vnode_pager_update_writecount(object,
3971 new_entry->start, new_entry->end);
3973 vm_map_entry_set_vnode_text(new_entry, true);
3976 * Insert the entry into the new map -- we know we're
3977 * inserting at the end of the new map.
3979 vm_map_entry_link(new_map, new_entry);
3980 vmspace_map_entry_forked(vm1, vm2, new_entry);
3983 * Update the physical map
3985 pmap_copy(new_map->pmap, old_map->pmap,
3987 (old_entry->end - old_entry->start),
3991 case VM_INHERIT_COPY:
3993 * Clone the entry and link into the map.
3995 new_entry = vm_map_entry_create(new_map);
3996 *new_entry = *old_entry;
3998 * Copied entry is COW over the old object.
4000 new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
4001 MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_VN_WRITECNT);
4002 new_entry->wiring_thread = NULL;
4003 new_entry->wired_count = 0;
4004 new_entry->object.vm_object = NULL;
4005 new_entry->cred = NULL;
4006 vm_map_entry_link(new_map, new_entry);
4007 vmspace_map_entry_forked(vm1, vm2, new_entry);
4008 vm_map_copy_entry(old_map, new_map, old_entry,
4009 new_entry, fork_charge);
4010 vm_map_entry_set_vnode_text(new_entry, true);
4013 case VM_INHERIT_ZERO:
4015 * Create a new anonymous mapping entry modelled from
4018 new_entry = vm_map_entry_create(new_map);
4019 memset(new_entry, 0, sizeof(*new_entry));
4021 new_entry->start = old_entry->start;
4022 new_entry->end = old_entry->end;
4023 new_entry->eflags = old_entry->eflags &
4024 ~(MAP_ENTRY_USER_WIRED | MAP_ENTRY_IN_TRANSITION |
4025 MAP_ENTRY_VN_WRITECNT | MAP_ENTRY_VN_EXEC);
4026 new_entry->protection = old_entry->protection;
4027 new_entry->max_protection = old_entry->max_protection;
4028 new_entry->inheritance = VM_INHERIT_ZERO;
4030 vm_map_entry_link(new_map, new_entry);
4031 vmspace_map_entry_forked(vm1, vm2, new_entry);
4033 new_entry->cred = curthread->td_ucred;
4034 crhold(new_entry->cred);
4035 *fork_charge += (new_entry->end - new_entry->start);
4039 old_entry = old_entry->next;
4042 * Use inlined vm_map_unlock() to postpone handling the deferred
4043 * map entries, which cannot be done until both old_map and
4044 * new_map locks are released.
4046 sx_xunlock(&old_map->lock);
4047 sx_xunlock(&new_map->lock);
4048 vm_map_process_deferred();
4054 * Create a process's stack for exec_new_vmspace(). This function is never
4055 * asked to wire the newly created stack.
4058 vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4059 vm_prot_t prot, vm_prot_t max, int cow)
4061 vm_size_t growsize, init_ssize;
4065 MPASS((map->flags & MAP_WIREFUTURE) == 0);
4066 growsize = sgrowsiz;
4067 init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
4069 vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4070 /* If we would blow our VMEM resource limit, no go */
4071 if (map->size + init_ssize > vmemlim) {
4075 rv = vm_map_stack_locked(map, addrbos, max_ssize, growsize, prot,
4082 static int stack_guard_page = 1;
4083 SYSCTL_INT(_security_bsd, OID_AUTO, stack_guard_page, CTLFLAG_RWTUN,
4084 &stack_guard_page, 0,
4085 "Specifies the number of guard pages for a stack that grows");
4088 vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4089 vm_size_t growsize, vm_prot_t prot, vm_prot_t max, int cow)
4091 vm_map_entry_t new_entry, prev_entry;
4092 vm_offset_t bot, gap_bot, gap_top, top;
4093 vm_size_t init_ssize, sgp;
4097 * The stack orientation is piggybacked with the cow argument.
4098 * Extract it into orient and mask the cow argument so that we
4099 * don't pass it around further.
4101 orient = cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP);
4102 KASSERT(orient != 0, ("No stack grow direction"));
4103 KASSERT(orient != (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP),
4106 if (addrbos < vm_map_min(map) ||
4107 addrbos + max_ssize > vm_map_max(map) ||
4108 addrbos + max_ssize <= addrbos)
4109 return (KERN_INVALID_ADDRESS);
4110 sgp = (vm_size_t)stack_guard_page * PAGE_SIZE;
4111 if (sgp >= max_ssize)
4112 return (KERN_INVALID_ARGUMENT);
4114 init_ssize = growsize;
4115 if (max_ssize < init_ssize + sgp)
4116 init_ssize = max_ssize - sgp;
4118 /* If addr is already mapped, no go */
4119 if (vm_map_lookup_entry(map, addrbos, &prev_entry))
4120 return (KERN_NO_SPACE);
4123 * If we can't accommodate max_ssize in the current mapping, no go.
4125 if (prev_entry->next->start < addrbos + max_ssize)
4126 return (KERN_NO_SPACE);
4129 * We initially map a stack of only init_ssize. We will grow as
4130 * needed later. Depending on the orientation of the stack (i.e.
4131 * the grow direction) we either map at the top of the range, the
4132 * bottom of the range or in the middle.
4134 * Note: we would normally expect prot and max to be VM_PROT_ALL,
4135 * and cow to be 0. Possibly we should eliminate these as input
4136 * parameters, and just pass these values here in the insert call.
4138 if (orient == MAP_STACK_GROWS_DOWN) {
4139 bot = addrbos + max_ssize - init_ssize;
4140 top = bot + init_ssize;
4143 } else /* if (orient == MAP_STACK_GROWS_UP) */ {
4145 top = bot + init_ssize;
4147 gap_top = addrbos + max_ssize;
4149 rv = vm_map_insert(map, NULL, 0, bot, top, prot, max, cow);
4150 if (rv != KERN_SUCCESS)
4152 new_entry = prev_entry->next;
4153 KASSERT(new_entry->end == top || new_entry->start == bot,
4154 ("Bad entry start/end for new stack entry"));
4155 KASSERT((orient & MAP_STACK_GROWS_DOWN) == 0 ||
4156 (new_entry->eflags & MAP_ENTRY_GROWS_DOWN) != 0,
4157 ("new entry lacks MAP_ENTRY_GROWS_DOWN"));
4158 KASSERT((orient & MAP_STACK_GROWS_UP) == 0 ||
4159 (new_entry->eflags & MAP_ENTRY_GROWS_UP) != 0,
4160 ("new entry lacks MAP_ENTRY_GROWS_UP"));
4161 rv = vm_map_insert(map, NULL, 0, gap_bot, gap_top, VM_PROT_NONE,
4162 VM_PROT_NONE, MAP_CREATE_GUARD | (orient == MAP_STACK_GROWS_DOWN ?
4163 MAP_CREATE_STACK_GAP_DN : MAP_CREATE_STACK_GAP_UP));
4164 if (rv != KERN_SUCCESS)
4165 (void)vm_map_delete(map, bot, top);
4170 * Attempts to grow a vm stack entry. Returns KERN_SUCCESS if we
4171 * successfully grow the stack.
4174 vm_map_growstack(vm_map_t map, vm_offset_t addr, vm_map_entry_t gap_entry)
4176 vm_map_entry_t stack_entry;
4180 vm_offset_t gap_end, gap_start, grow_start;
4181 vm_size_t grow_amount, guard, max_grow;
4182 rlim_t lmemlim, stacklim, vmemlim;
4184 bool gap_deleted, grow_down, is_procstack;
4196 * Disallow stack growth when the access is performed by a
4197 * debugger or AIO daemon. The reason is that the wrong
4198 * resource limits are applied.
4200 if (map != &p->p_vmspace->vm_map || p->p_textvp == NULL)
4201 return (KERN_FAILURE);
4203 MPASS(!map->system_map);
4205 guard = stack_guard_page * PAGE_SIZE;
4206 lmemlim = lim_cur(curthread, RLIMIT_MEMLOCK);
4207 stacklim = lim_cur(curthread, RLIMIT_STACK);
4208 vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4210 /* If addr is not in a hole for a stack grow area, no need to grow. */
4211 if (gap_entry == NULL && !vm_map_lookup_entry(map, addr, &gap_entry))
4212 return (KERN_FAILURE);
4213 if ((gap_entry->eflags & MAP_ENTRY_GUARD) == 0)
4214 return (KERN_SUCCESS);
4215 if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_DN) != 0) {
4216 stack_entry = gap_entry->next;
4217 if ((stack_entry->eflags & MAP_ENTRY_GROWS_DOWN) == 0 ||
4218 stack_entry->start != gap_entry->end)
4219 return (KERN_FAILURE);
4220 grow_amount = round_page(stack_entry->start - addr);
4222 } else if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_UP) != 0) {
4223 stack_entry = gap_entry->prev;
4224 if ((stack_entry->eflags & MAP_ENTRY_GROWS_UP) == 0 ||
4225 stack_entry->end != gap_entry->start)
4226 return (KERN_FAILURE);
4227 grow_amount = round_page(addr + 1 - stack_entry->end);
4230 return (KERN_FAILURE);
4232 max_grow = gap_entry->end - gap_entry->start;
4233 if (guard > max_grow)
4234 return (KERN_NO_SPACE);
4236 if (grow_amount > max_grow)
4237 return (KERN_NO_SPACE);
4240 * If this is the main process stack, see if we're over the stack
4243 is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr &&
4244 addr < (vm_offset_t)p->p_sysent->sv_usrstack;
4245 if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim))
4246 return (KERN_NO_SPACE);
4251 if (is_procstack && racct_set(p, RACCT_STACK,
4252 ctob(vm->vm_ssize) + grow_amount)) {
4254 return (KERN_NO_SPACE);
4260 grow_amount = roundup(grow_amount, sgrowsiz);
4261 if (grow_amount > max_grow)
4262 grow_amount = max_grow;
4263 if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
4264 grow_amount = trunc_page((vm_size_t)stacklim) -
4270 limit = racct_get_available(p, RACCT_STACK);
4272 if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > limit))
4273 grow_amount = limit - ctob(vm->vm_ssize);
4276 if (!old_mlock && (map->flags & MAP_WIREFUTURE) != 0) {
4277 if (ptoa(pmap_wired_count(map->pmap)) + grow_amount > lmemlim) {
4284 if (racct_set(p, RACCT_MEMLOCK,
4285 ptoa(pmap_wired_count(map->pmap)) + grow_amount)) {
4295 /* If we would blow our VMEM resource limit, no go */
4296 if (map->size + grow_amount > vmemlim) {
4303 if (racct_set(p, RACCT_VMEM, map->size + grow_amount)) {
4312 if (vm_map_lock_upgrade(map)) {
4314 vm_map_lock_read(map);
4319 grow_start = gap_entry->end - grow_amount;
4320 if (gap_entry->start + grow_amount == gap_entry->end) {
4321 gap_start = gap_entry->start;
4322 gap_end = gap_entry->end;
4323 vm_map_entry_delete(map, gap_entry);
4326 MPASS(gap_entry->start < gap_entry->end - grow_amount);
4327 vm_map_entry_resize(map, gap_entry, -grow_amount);
4328 gap_deleted = false;
4330 rv = vm_map_insert(map, NULL, 0, grow_start,
4331 grow_start + grow_amount,
4332 stack_entry->protection, stack_entry->max_protection,
4333 MAP_STACK_GROWS_DOWN);
4334 if (rv != KERN_SUCCESS) {
4336 rv1 = vm_map_insert(map, NULL, 0, gap_start,
4337 gap_end, VM_PROT_NONE, VM_PROT_NONE,
4338 MAP_CREATE_GUARD | MAP_CREATE_STACK_GAP_DN);
4339 MPASS(rv1 == KERN_SUCCESS);
4341 vm_map_entry_resize(map, gap_entry,
4345 grow_start = stack_entry->end;
4346 cred = stack_entry->cred;
4347 if (cred == NULL && stack_entry->object.vm_object != NULL)
4348 cred = stack_entry->object.vm_object->cred;
4349 if (cred != NULL && !swap_reserve_by_cred(grow_amount, cred))
4351 /* Grow the underlying object if applicable. */
4352 else if (stack_entry->object.vm_object == NULL ||
4353 vm_object_coalesce(stack_entry->object.vm_object,
4354 stack_entry->offset,
4355 (vm_size_t)(stack_entry->end - stack_entry->start),
4356 grow_amount, cred != NULL)) {
4357 if (gap_entry->start + grow_amount == gap_entry->end) {
4358 vm_map_entry_delete(map, gap_entry);
4359 vm_map_entry_resize(map, stack_entry,
4362 gap_entry->start += grow_amount;
4363 stack_entry->end += grow_amount;
4365 map->size += grow_amount;
4370 if (rv == KERN_SUCCESS && is_procstack)
4371 vm->vm_ssize += btoc(grow_amount);
4374 * Heed the MAP_WIREFUTURE flag if it was set for this process.
4376 if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE) != 0) {
4377 rv = vm_map_wire_locked(map, grow_start,
4378 grow_start + grow_amount,
4379 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
4381 vm_map_lock_downgrade(map);
4385 if (racct_enable && rv != KERN_SUCCESS) {
4387 error = racct_set(p, RACCT_VMEM, map->size);
4388 KASSERT(error == 0, ("decreasing RACCT_VMEM failed"));
4390 error = racct_set(p, RACCT_MEMLOCK,
4391 ptoa(pmap_wired_count(map->pmap)));
4392 KASSERT(error == 0, ("decreasing RACCT_MEMLOCK failed"));
4394 error = racct_set(p, RACCT_STACK, ctob(vm->vm_ssize));
4395 KASSERT(error == 0, ("decreasing RACCT_STACK failed"));
4404 * Unshare the specified VM space for exec. If other processes are
4405 * mapped to it, then create a new one. The new vmspace is null.
4408 vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
4410 struct vmspace *oldvmspace = p->p_vmspace;
4411 struct vmspace *newvmspace;
4413 KASSERT((curthread->td_pflags & TDP_EXECVMSPC) == 0,
4414 ("vmspace_exec recursed"));
4415 newvmspace = vmspace_alloc(minuser, maxuser, pmap_pinit);
4416 if (newvmspace == NULL)
4418 newvmspace->vm_swrss = oldvmspace->vm_swrss;
4420 * This code is written like this for prototype purposes. The
4421 * goal is to avoid running down the vmspace here, but let the
4422 * other process's that are still using the vmspace to finally
4423 * run it down. Even though there is little or no chance of blocking
4424 * here, it is a good idea to keep this form for future mods.
4426 PROC_VMSPACE_LOCK(p);
4427 p->p_vmspace = newvmspace;
4428 PROC_VMSPACE_UNLOCK(p);
4429 if (p == curthread->td_proc)
4430 pmap_activate(curthread);
4431 curthread->td_pflags |= TDP_EXECVMSPC;
4436 * Unshare the specified VM space for forcing COW. This
4437 * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
4440 vmspace_unshare(struct proc *p)
4442 struct vmspace *oldvmspace = p->p_vmspace;
4443 struct vmspace *newvmspace;
4444 vm_ooffset_t fork_charge;
4446 if (oldvmspace->vm_refcnt == 1)
4449 newvmspace = vmspace_fork(oldvmspace, &fork_charge);
4450 if (newvmspace == NULL)
4452 if (!swap_reserve_by_cred(fork_charge, p->p_ucred)) {
4453 vmspace_free(newvmspace);
4456 PROC_VMSPACE_LOCK(p);
4457 p->p_vmspace = newvmspace;
4458 PROC_VMSPACE_UNLOCK(p);
4459 if (p == curthread->td_proc)
4460 pmap_activate(curthread);
4461 vmspace_free(oldvmspace);
4468 * Finds the VM object, offset, and
4469 * protection for a given virtual address in the
4470 * specified map, assuming a page fault of the
4473 * Leaves the map in question locked for read; return
4474 * values are guaranteed until a vm_map_lookup_done
4475 * call is performed. Note that the map argument
4476 * is in/out; the returned map must be used in
4477 * the call to vm_map_lookup_done.
4479 * A handle (out_entry) is returned for use in
4480 * vm_map_lookup_done, to make that fast.
4482 * If a lookup is requested with "write protection"
4483 * specified, the map may be changed to perform virtual
4484 * copying operations, although the data referenced will
4488 vm_map_lookup(vm_map_t *var_map, /* IN/OUT */
4490 vm_prot_t fault_typea,
4491 vm_map_entry_t *out_entry, /* OUT */
4492 vm_object_t *object, /* OUT */
4493 vm_pindex_t *pindex, /* OUT */
4494 vm_prot_t *out_prot, /* OUT */
4495 boolean_t *wired) /* OUT */
4497 vm_map_entry_t entry;
4498 vm_map_t map = *var_map;
4500 vm_prot_t fault_type = fault_typea;
4501 vm_object_t eobject;
4507 vm_map_lock_read(map);
4511 * Lookup the faulting address.
4513 if (!vm_map_lookup_entry(map, vaddr, out_entry)) {
4514 vm_map_unlock_read(map);
4515 return (KERN_INVALID_ADDRESS);
4523 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4524 vm_map_t old_map = map;
4526 *var_map = map = entry->object.sub_map;
4527 vm_map_unlock_read(old_map);
4532 * Check whether this task is allowed to have this page.
4534 prot = entry->protection;
4535 if ((fault_typea & VM_PROT_FAULT_LOOKUP) != 0) {
4536 fault_typea &= ~VM_PROT_FAULT_LOOKUP;
4537 if (prot == VM_PROT_NONE && map != kernel_map &&
4538 (entry->eflags & MAP_ENTRY_GUARD) != 0 &&
4539 (entry->eflags & (MAP_ENTRY_STACK_GAP_DN |
4540 MAP_ENTRY_STACK_GAP_UP)) != 0 &&
4541 vm_map_growstack(map, vaddr, entry) == KERN_SUCCESS)
4542 goto RetryLookupLocked;
4544 fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
4545 if ((fault_type & prot) != fault_type || prot == VM_PROT_NONE) {
4546 vm_map_unlock_read(map);
4547 return (KERN_PROTECTION_FAILURE);
4549 KASSERT((prot & VM_PROT_WRITE) == 0 || (entry->eflags &
4550 (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY)) !=
4551 (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY),
4552 ("entry %p flags %x", entry, entry->eflags));
4553 if ((fault_typea & VM_PROT_COPY) != 0 &&
4554 (entry->max_protection & VM_PROT_WRITE) == 0 &&
4555 (entry->eflags & MAP_ENTRY_COW) == 0) {
4556 vm_map_unlock_read(map);
4557 return (KERN_PROTECTION_FAILURE);
4561 * If this page is not pageable, we have to get it for all possible
4564 *wired = (entry->wired_count != 0);
4566 fault_type = entry->protection;
4567 size = entry->end - entry->start;
4569 * If the entry was copy-on-write, we either ...
4571 if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4573 * If we want to write the page, we may as well handle that
4574 * now since we've got the map locked.
4576 * If we don't need to write the page, we just demote the
4577 * permissions allowed.
4579 if ((fault_type & VM_PROT_WRITE) != 0 ||
4580 (fault_typea & VM_PROT_COPY) != 0) {
4582 * Make a new object, and place it in the object
4583 * chain. Note that no new references have appeared
4584 * -- one just moved from the map to the new
4587 if (vm_map_lock_upgrade(map))
4590 if (entry->cred == NULL) {
4592 * The debugger owner is charged for
4595 cred = curthread->td_ucred;
4597 if (!swap_reserve_by_cred(size, cred)) {
4600 return (KERN_RESOURCE_SHORTAGE);
4604 vm_object_shadow(&entry->object.vm_object,
4605 &entry->offset, size);
4606 entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
4607 eobject = entry->object.vm_object;
4608 if (eobject->cred != NULL) {
4610 * The object was not shadowed.
4612 swap_release_by_cred(size, entry->cred);
4613 crfree(entry->cred);
4615 } else if (entry->cred != NULL) {
4616 VM_OBJECT_WLOCK(eobject);
4617 eobject->cred = entry->cred;
4618 eobject->charge = size;
4619 VM_OBJECT_WUNLOCK(eobject);
4623 vm_map_lock_downgrade(map);
4626 * We're attempting to read a copy-on-write page --
4627 * don't allow writes.
4629 prot &= ~VM_PROT_WRITE;
4634 * Create an object if necessary.
4636 if (entry->object.vm_object == NULL &&
4638 if (vm_map_lock_upgrade(map))
4640 entry->object.vm_object = vm_object_allocate(OBJT_DEFAULT,
4643 if (entry->cred != NULL) {
4644 VM_OBJECT_WLOCK(entry->object.vm_object);
4645 entry->object.vm_object->cred = entry->cred;
4646 entry->object.vm_object->charge = size;
4647 VM_OBJECT_WUNLOCK(entry->object.vm_object);
4650 vm_map_lock_downgrade(map);
4654 * Return the object/offset from this entry. If the entry was
4655 * copy-on-write or empty, it has been fixed up.
4657 *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4658 *object = entry->object.vm_object;
4661 return (KERN_SUCCESS);
4665 * vm_map_lookup_locked:
4667 * Lookup the faulting address. A version of vm_map_lookup that returns
4668 * KERN_FAILURE instead of blocking on map lock or memory allocation.
4671 vm_map_lookup_locked(vm_map_t *var_map, /* IN/OUT */
4673 vm_prot_t fault_typea,
4674 vm_map_entry_t *out_entry, /* OUT */
4675 vm_object_t *object, /* OUT */
4676 vm_pindex_t *pindex, /* OUT */
4677 vm_prot_t *out_prot, /* OUT */
4678 boolean_t *wired) /* OUT */
4680 vm_map_entry_t entry;
4681 vm_map_t map = *var_map;
4683 vm_prot_t fault_type = fault_typea;
4686 * Lookup the faulting address.
4688 if (!vm_map_lookup_entry(map, vaddr, out_entry))
4689 return (KERN_INVALID_ADDRESS);
4694 * Fail if the entry refers to a submap.
4696 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
4697 return (KERN_FAILURE);
4700 * Check whether this task is allowed to have this page.
4702 prot = entry->protection;
4703 fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
4704 if ((fault_type & prot) != fault_type)
4705 return (KERN_PROTECTION_FAILURE);
4708 * If this page is not pageable, we have to get it for all possible
4711 *wired = (entry->wired_count != 0);
4713 fault_type = entry->protection;
4715 if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4717 * Fail if the entry was copy-on-write for a write fault.
4719 if (fault_type & VM_PROT_WRITE)
4720 return (KERN_FAILURE);
4722 * We're attempting to read a copy-on-write page --
4723 * don't allow writes.
4725 prot &= ~VM_PROT_WRITE;
4729 * Fail if an object should be created.
4731 if (entry->object.vm_object == NULL && !map->system_map)
4732 return (KERN_FAILURE);
4735 * Return the object/offset from this entry. If the entry was
4736 * copy-on-write or empty, it has been fixed up.
4738 *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4739 *object = entry->object.vm_object;
4742 return (KERN_SUCCESS);
4746 * vm_map_lookup_done:
4748 * Releases locks acquired by a vm_map_lookup
4749 * (according to the handle returned by that lookup).
4752 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
4755 * Unlock the main-level map
4757 vm_map_unlock_read(map);
4761 vm_map_max_KBI(const struct vm_map *map)
4764 return (vm_map_max(map));
4768 vm_map_min_KBI(const struct vm_map *map)
4771 return (vm_map_min(map));
4775 vm_map_pmap_KBI(vm_map_t map)
4781 #include "opt_ddb.h"
4783 #include <sys/kernel.h>
4785 #include <ddb/ddb.h>
4788 vm_map_print(vm_map_t map)
4790 vm_map_entry_t entry;
4792 db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
4794 (void *)map->pmap, map->nentries, map->timestamp);
4797 for (entry = map->header.next; entry != &map->header;
4798 entry = entry->next) {
4799 db_iprintf("map entry %p: start=%p, end=%p, eflags=%#x, \n",
4800 (void *)entry, (void *)entry->start, (void *)entry->end,
4803 static char *inheritance_name[4] =
4804 {"share", "copy", "none", "donate_copy"};
4806 db_iprintf(" prot=%x/%x/%s",
4808 entry->max_protection,
4809 inheritance_name[(int)(unsigned char)entry->inheritance]);
4810 if (entry->wired_count != 0)
4811 db_printf(", wired");
4813 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4814 db_printf(", share=%p, offset=0x%jx\n",
4815 (void *)entry->object.sub_map,
4816 (uintmax_t)entry->offset);
4817 if ((entry->prev == &map->header) ||
4818 (entry->prev->object.sub_map !=
4819 entry->object.sub_map)) {
4821 vm_map_print((vm_map_t)entry->object.sub_map);
4825 if (entry->cred != NULL)
4826 db_printf(", ruid %d", entry->cred->cr_ruid);
4827 db_printf(", object=%p, offset=0x%jx",
4828 (void *)entry->object.vm_object,
4829 (uintmax_t)entry->offset);
4830 if (entry->object.vm_object && entry->object.vm_object->cred)
4831 db_printf(", obj ruid %d charge %jx",
4832 entry->object.vm_object->cred->cr_ruid,
4833 (uintmax_t)entry->object.vm_object->charge);
4834 if (entry->eflags & MAP_ENTRY_COW)
4835 db_printf(", copy (%s)",
4836 (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
4839 if ((entry->prev == &map->header) ||
4840 (entry->prev->object.vm_object !=
4841 entry->object.vm_object)) {
4843 vm_object_print((db_expr_t)(intptr_t)
4844 entry->object.vm_object,
4853 DB_SHOW_COMMAND(map, map)
4857 db_printf("usage: show map <addr>\n");
4860 vm_map_print((vm_map_t)addr);
4863 DB_SHOW_COMMAND(procvm, procvm)
4868 p = db_lookup_proc(addr);
4873 db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
4874 (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
4875 (void *)vmspace_pmap(p->p_vmspace));
4877 vm_map_print((vm_map_t)&p->p_vmspace->vm_map);