xref: /freebsd/sys/vm/vm_map.c (revision 0cb2610ee2dccfde2e385f8e8a10d0b8d6bc0687)
160727d8bSWarner Losh /*-
2796df753SPedro F. Giffuni  * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
351369649SPedro F. Giffuni  *
4df8bae1dSRodney W. Grimes  * Copyright (c) 1991, 1993
5df8bae1dSRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
6df8bae1dSRodney W. Grimes  *
7df8bae1dSRodney W. Grimes  * This code is derived from software contributed to Berkeley by
8df8bae1dSRodney W. Grimes  * The Mach Operating System project at Carnegie-Mellon University.
9df8bae1dSRodney W. Grimes  *
10df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
11df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
12df8bae1dSRodney W. Grimes  * are met:
13df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
14df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
15df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
16df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
17df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
18fbbd9655SWarner Losh  * 3. Neither the name of the University nor the names of its contributors
19df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
20df8bae1dSRodney W. Grimes  *    without specific prior written permission.
21df8bae1dSRodney W. Grimes  *
22df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
33df8bae1dSRodney W. Grimes  *
343c4dd356SDavid Greenman  *	from: @(#)vm_map.c	8.3 (Berkeley) 1/12/94
35df8bae1dSRodney W. Grimes  *
36df8bae1dSRodney W. Grimes  *
37df8bae1dSRodney W. Grimes  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38df8bae1dSRodney W. Grimes  * All rights reserved.
39df8bae1dSRodney W. Grimes  *
40df8bae1dSRodney W. Grimes  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41df8bae1dSRodney W. Grimes  *
42df8bae1dSRodney W. Grimes  * Permission to use, copy, modify and distribute this software and
43df8bae1dSRodney W. Grimes  * its documentation is hereby granted, provided that both the copyright
44df8bae1dSRodney W. Grimes  * notice and this permission notice appear in all copies of the
45df8bae1dSRodney W. Grimes  * software, derivative works or modified versions, and any portions
46df8bae1dSRodney W. Grimes  * thereof, and that both notices appear in supporting documentation.
47df8bae1dSRodney W. Grimes  *
48df8bae1dSRodney W. Grimes  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49df8bae1dSRodney W. Grimes  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50df8bae1dSRodney W. Grimes  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51df8bae1dSRodney W. Grimes  *
52df8bae1dSRodney W. Grimes  * Carnegie Mellon requests users of this software to return to
53df8bae1dSRodney W. Grimes  *
54df8bae1dSRodney W. Grimes  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55df8bae1dSRodney W. Grimes  *  School of Computer Science
56df8bae1dSRodney W. Grimes  *  Carnegie Mellon University
57df8bae1dSRodney W. Grimes  *  Pittsburgh PA 15213-3890
58df8bae1dSRodney W. Grimes  *
59df8bae1dSRodney W. Grimes  * any improvements or extensions that they make and grant Carnegie the
60df8bae1dSRodney W. Grimes  * rights to redistribute these changes.
61df8bae1dSRodney W. Grimes  */
62df8bae1dSRodney W. Grimes 
63df8bae1dSRodney W. Grimes /*
64df8bae1dSRodney W. Grimes  *	Virtual memory mapping module.
65df8bae1dSRodney W. Grimes  */
66df8bae1dSRodney W. Grimes 
67874651b1SDavid E. O'Brien #include <sys/cdefs.h>
68874651b1SDavid E. O'Brien __FBSDID("$FreeBSD$");
69874651b1SDavid E. O'Brien 
70df8bae1dSRodney W. Grimes #include <sys/param.h>
71df8bae1dSRodney W. Grimes #include <sys/systm.h>
72156e8654SKonstantin Belousov #include <sys/elf.h>
739a6d144fSKonstantin Belousov #include <sys/kernel.h>
7461d80e90SJohn Baldwin #include <sys/ktr.h>
75fb919e4dSMark Murray #include <sys/lock.h>
76fb919e4dSMark Murray #include <sys/mutex.h>
77b5e8ce9fSBruce Evans #include <sys/proc.h>
78efeaf95aSDavid Greenman #include <sys/vmmeter.h>
79867a482dSJohn Dyson #include <sys/mman.h>
801efb74fbSJohn Dyson #include <sys/vnode.h>
811ba5ad42SEdward Tomasz Napierala #include <sys/racct.h>
822267af78SJulian Elischer #include <sys/resourcevar.h>
8389f6b863SAttilio Rao #include <sys/rwlock.h>
843fde38dfSMike Silbersack #include <sys/file.h>
859a6d144fSKonstantin Belousov #include <sys/sysctl.h>
8605ba50f5SJake Burkholder #include <sys/sysent.h>
873db161e0SMatthew Dillon #include <sys/shm.h>
88df8bae1dSRodney W. Grimes 
89df8bae1dSRodney W. Grimes #include <vm/vm.h>
90efeaf95aSDavid Greenman #include <vm/vm_param.h>
91efeaf95aSDavid Greenman #include <vm/pmap.h>
92efeaf95aSDavid Greenman #include <vm/vm_map.h>
93df8bae1dSRodney W. Grimes #include <vm/vm_page.h>
9454a3a114SMark Johnston #include <vm/vm_pageout.h>
95df8bae1dSRodney W. Grimes #include <vm/vm_object.h>
9647221757SJohn Dyson #include <vm/vm_pager.h>
9726f9a767SRodney W. Grimes #include <vm/vm_kern.h>
98efeaf95aSDavid Greenman #include <vm/vm_extern.h>
9984110e7eSKonstantin Belousov #include <vm/vnode_pager.h>
10021cd6e62SSeigo Tanimura #include <vm/swap_pager.h>
101670d17b5SJeff Roberson #include <vm/uma.h>
102df8bae1dSRodney W. Grimes 
103df8bae1dSRodney W. Grimes /*
104df8bae1dSRodney W. Grimes  *	Virtual memory maps provide for the mapping, protection,
105df8bae1dSRodney W. Grimes  *	and sharing of virtual memory objects.  In addition,
106df8bae1dSRodney W. Grimes  *	this module provides for an efficient virtual copy of
107df8bae1dSRodney W. Grimes  *	memory from one map to another.
108df8bae1dSRodney W. Grimes  *
109df8bae1dSRodney W. Grimes  *	Synchronization is required prior to most operations.
110df8bae1dSRodney W. Grimes  *
111df8bae1dSRodney W. Grimes  *	Maps consist of an ordered doubly-linked list of simple
112e2abaaaaSAlan Cox  *	entries; a self-adjusting binary search tree of these
113e2abaaaaSAlan Cox  *	entries is used to speed up lookups.
114df8bae1dSRodney W. Grimes  *
115956f3135SPhilippe Charnier  *	Since portions of maps are specified by start/end addresses,
116df8bae1dSRodney W. Grimes  *	which may not align with existing map entries, all
117df8bae1dSRodney W. Grimes  *	routines merely "clip" entries to these start/end values.
118df8bae1dSRodney W. Grimes  *	[That is, an entry is split into two, bordering at a
119df8bae1dSRodney W. Grimes  *	start or end value.]  Note that these clippings may not
120df8bae1dSRodney W. Grimes  *	always be necessary (as the two resulting entries are then
121df8bae1dSRodney W. Grimes  *	not changed); however, the clipping is done for convenience.
122df8bae1dSRodney W. Grimes  *
123df8bae1dSRodney W. Grimes  *	As mentioned above, virtual copy operations are performed
124ad5fca3bSAlan Cox  *	by copying VM object references from one map to
125df8bae1dSRodney W. Grimes  *	another, and then marking both regions as copy-on-write.
126df8bae1dSRodney W. Grimes  */
127df8bae1dSRodney W. Grimes 
1283a92e5d5SAlan Cox static struct mtx map_sleep_mtx;
1298355f576SJeff Roberson static uma_zone_t mapentzone;
1308355f576SJeff Roberson static uma_zone_t kmapentzone;
1318355f576SJeff Roberson static uma_zone_t vmspace_zone;
132b23f72e9SBrian Feldman static int vmspace_zinit(void *mem, int size, int flags);
13392351f16SAlan Cox static void _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min,
13492351f16SAlan Cox     vm_offset_t max);
1350b367bd8SKonstantin Belousov static void vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map);
136655c3490SKonstantin Belousov static void vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry);
13703462509SAlan Cox static void vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry);
13819bd0d9cSKonstantin Belousov static int vm_map_growstack(vm_map_t map, vm_offset_t addr,
13919bd0d9cSKonstantin Belousov     vm_map_entry_t gap_entry);
140077ec27cSAlan Cox static void vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
141077ec27cSAlan Cox     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags);
1428355f576SJeff Roberson #ifdef INVARIANTS
1438355f576SJeff Roberson static void vmspace_zdtor(void *mem, int size, void *arg);
1448355f576SJeff Roberson #endif
1454648ba0aSKonstantin Belousov static int vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos,
1464648ba0aSKonstantin Belousov     vm_size_t max_ssize, vm_size_t growsize, vm_prot_t prot, vm_prot_t max,
1474648ba0aSKonstantin Belousov     int cow);
14866cd575bSAlan Cox static void vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
14966cd575bSAlan Cox     vm_offset_t failed_addr);
150b18bfc3dSJohn Dyson 
151ef694c1aSEdward Tomasz Napierala #define	ENTRY_CHARGED(e) ((e)->cred != NULL || \
152ef694c1aSEdward Tomasz Napierala     ((e)->object.vm_object != NULL && (e)->object.vm_object->cred != NULL && \
1533364c323SKonstantin Belousov      !((e)->eflags & MAP_ENTRY_NEEDS_COPY)))
1543364c323SKonstantin Belousov 
15557051fdcSTor Egge /*
15657051fdcSTor Egge  * PROC_VMSPACE_{UN,}LOCK() can be a noop as long as vmspaces are type
15757051fdcSTor Egge  * stable.
15857051fdcSTor Egge  */
15957051fdcSTor Egge #define PROC_VMSPACE_LOCK(p) do { } while (0)
16057051fdcSTor Egge #define PROC_VMSPACE_UNLOCK(p) do { } while (0)
16157051fdcSTor Egge 
162d239bd3cSKonstantin Belousov /*
163d239bd3cSKonstantin Belousov  *	VM_MAP_RANGE_CHECK:	[ internal use only ]
164d239bd3cSKonstantin Belousov  *
165d239bd3cSKonstantin Belousov  *	Asserts that the starting and ending region
166d239bd3cSKonstantin Belousov  *	addresses fall within the valid range of the map.
167d239bd3cSKonstantin Belousov  */
168d239bd3cSKonstantin Belousov #define	VM_MAP_RANGE_CHECK(map, start, end)		\
169d239bd3cSKonstantin Belousov 		{					\
170d239bd3cSKonstantin Belousov 		if (start < vm_map_min(map))		\
171d239bd3cSKonstantin Belousov 			start = vm_map_min(map);	\
172d239bd3cSKonstantin Belousov 		if (end > vm_map_max(map))		\
173d239bd3cSKonstantin Belousov 			end = vm_map_max(map);		\
174d239bd3cSKonstantin Belousov 		if (start > end)			\
175d239bd3cSKonstantin Belousov 			start = end;			\
176d239bd3cSKonstantin Belousov 		}
177d239bd3cSKonstantin Belousov 
17820f02659SMark Johnston #ifndef UMA_MD_SMALL_ALLOC
17920f02659SMark Johnston 
18020f02659SMark Johnston /*
18120f02659SMark Johnston  * Allocate a new slab for kernel map entries.  The kernel map may be locked or
18220f02659SMark Johnston  * unlocked, depending on whether the request is coming from the kernel map or a
18320f02659SMark Johnston  * submap.  This function allocates a virtual address range directly from the
18420f02659SMark Johnston  * kernel map instead of the kmem_* layer to avoid recursion on the kernel map
18520f02659SMark Johnston  * lock and also to avoid triggering allocator recursion in the vmem boundary
18620f02659SMark Johnston  * tag allocator.
18720f02659SMark Johnston  */
18820f02659SMark Johnston static void *
18920f02659SMark Johnston kmapent_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
19020f02659SMark Johnston     int wait)
19120f02659SMark Johnston {
19220f02659SMark Johnston 	vm_offset_t addr;
19320f02659SMark Johnston 	int error, locked;
19420f02659SMark Johnston 
19520f02659SMark Johnston 	*pflag = UMA_SLAB_PRIV;
19620f02659SMark Johnston 
19720f02659SMark Johnston 	if (!(locked = vm_map_locked(kernel_map)))
19820f02659SMark Johnston 		vm_map_lock(kernel_map);
19920f02659SMark Johnston 	addr = vm_map_findspace(kernel_map, vm_map_min(kernel_map), bytes);
20020f02659SMark Johnston 	if (addr + bytes < addr || addr + bytes > vm_map_max(kernel_map))
20120f02659SMark Johnston 		panic("%s: kernel map is exhausted", __func__);
20220f02659SMark Johnston 	error = vm_map_insert(kernel_map, NULL, 0, addr, addr + bytes,
20320f02659SMark Johnston 	    VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
20420f02659SMark Johnston 	if (error != KERN_SUCCESS)
20520f02659SMark Johnston 		panic("%s: vm_map_insert() failed: %d", __func__, error);
20620f02659SMark Johnston 	if (!locked)
20720f02659SMark Johnston 		vm_map_unlock(kernel_map);
20820f02659SMark Johnston 	error = kmem_back_domain(domain, kernel_object, addr, bytes, M_NOWAIT |
20920f02659SMark Johnston 	    M_USE_RESERVE | (wait & M_ZERO));
21020f02659SMark Johnston 	if (error == KERN_SUCCESS) {
21120f02659SMark Johnston 		return ((void *)addr);
21220f02659SMark Johnston 	} else {
21320f02659SMark Johnston 		if (!locked)
21420f02659SMark Johnston 			vm_map_lock(kernel_map);
21520f02659SMark Johnston 		vm_map_delete(kernel_map, addr, bytes);
21620f02659SMark Johnston 		if (!locked)
21720f02659SMark Johnston 			vm_map_unlock(kernel_map);
21820f02659SMark Johnston 		return (NULL);
21920f02659SMark Johnston 	}
22020f02659SMark Johnston }
22120f02659SMark Johnston 
22220f02659SMark Johnston static void
22320f02659SMark Johnston kmapent_free(void *item, vm_size_t size, uint8_t pflag)
22420f02659SMark Johnston {
22520f02659SMark Johnston 	vm_offset_t addr;
226b8ebd99aSJohn Baldwin 	int error __diagused;
22720f02659SMark Johnston 
22820f02659SMark Johnston 	if ((pflag & UMA_SLAB_PRIV) == 0)
22920f02659SMark Johnston 		/* XXX leaked */
23020f02659SMark Johnston 		return;
23120f02659SMark Johnston 
23220f02659SMark Johnston 	addr = (vm_offset_t)item;
23320f02659SMark Johnston 	kmem_unback(kernel_object, addr, size);
23420f02659SMark Johnston 	error = vm_map_remove(kernel_map, addr, addr + size);
23520f02659SMark Johnston 	KASSERT(error == KERN_SUCCESS,
23620f02659SMark Johnston 	    ("%s: vm_map_remove failed: %d", __func__, error));
23720f02659SMark Johnston }
23820f02659SMark Johnston 
23920f02659SMark Johnston /*
24020f02659SMark Johnston  * The worst-case upper bound on the number of kernel map entries that may be
24120f02659SMark Johnston  * created before the zone must be replenished in _vm_map_unlock().
24220f02659SMark Johnston  */
24320f02659SMark Johnston #define	KMAPENT_RESERVE		1
24420f02659SMark Johnston 
24520f02659SMark Johnston #endif /* !UMD_MD_SMALL_ALLOC */
24620f02659SMark Johnston 
2476fecb26bSKonstantin Belousov /*
2486fecb26bSKonstantin Belousov  *	vm_map_startup:
2496fecb26bSKonstantin Belousov  *
25020f02659SMark Johnston  *	Initialize the vm_map module.  Must be called before any other vm_map
25120f02659SMark Johnston  *	routines.
2526fecb26bSKonstantin Belousov  *
25320f02659SMark Johnston  *	User map and entry structures are allocated from the general purpose
25420f02659SMark Johnston  *	memory pool.  Kernel maps are statically defined.  Kernel map entries
25520f02659SMark Johnston  *	require special handling to avoid recursion; see the comments above
25620f02659SMark Johnston  *	kmapent_alloc() and in vm_map_entry_create().
2576fecb26bSKonstantin Belousov  */
2580d94caffSDavid Greenman void
2591b40f8c0SMatthew Dillon vm_map_startup(void)
260df8bae1dSRodney W. Grimes {
2613a92e5d5SAlan Cox 	mtx_init(&map_sleep_mtx, "vm map sleep mutex", NULL, MTX_DEF);
26220f02659SMark Johnston 
26320f02659SMark Johnston 	/*
26420f02659SMark Johnston 	 * Disable the use of per-CPU buckets: map entry allocation is
26520f02659SMark Johnston 	 * serialized by the kernel map lock.
26620f02659SMark Johnston 	 */
267670d17b5SJeff Roberson 	kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry),
26818aa2de5SJeff Roberson 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
26920f02659SMark Johnston 	    UMA_ZONE_VM | UMA_ZONE_NOBUCKET);
27020f02659SMark Johnston #ifndef UMA_MD_SMALL_ALLOC
27120f02659SMark Johnston 	/* Reserve an extra map entry for use when replenishing the reserve. */
27220f02659SMark Johnston 	uma_zone_reserve(kmapentzone, KMAPENT_RESERVE + 1);
27320f02659SMark Johnston 	uma_prealloc(kmapentzone, KMAPENT_RESERVE + 1);
27420f02659SMark Johnston 	uma_zone_set_allocf(kmapentzone, kmapent_alloc);
27520f02659SMark Johnston 	uma_zone_set_freef(kmapentzone, kmapent_free);
27620f02659SMark Johnston #endif
27720f02659SMark Johnston 
278670d17b5SJeff Roberson 	mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry),
279670d17b5SJeff Roberson 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
2805df87b21SJeff Roberson 	vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
2815df87b21SJeff Roberson #ifdef INVARIANTS
2825df87b21SJeff Roberson 	    vmspace_zdtor,
2835df87b21SJeff Roberson #else
2845df87b21SJeff Roberson 	    NULL,
2855df87b21SJeff Roberson #endif
286f872f6eaSAlan Cox 	    vmspace_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
2878355f576SJeff Roberson }
2888355f576SJeff Roberson 
289b23f72e9SBrian Feldman static int
290b23f72e9SBrian Feldman vmspace_zinit(void *mem, int size, int flags)
2918355f576SJeff Roberson {
2928355f576SJeff Roberson 	struct vmspace *vm;
2938355f576SJeff Roberson 	vm_map_t map;
2948355f576SJeff Roberson 
2957dd979dfSMark Johnston 	vm = (struct vmspace *)mem;
2967dd979dfSMark Johnston 	map = &vm->vm_map;
2977dd979dfSMark Johnston 
298763d9566STim Kientzle 	memset(map, 0, sizeof(*map));
2997dd979dfSMark Johnston 	mtx_init(&map->system_mtx, "vm map (system)", NULL,
3007dd979dfSMark Johnston 	    MTX_DEF | MTX_DUPOK);
301e30df26eSAlan Cox 	sx_init(&map->lock, "vm map (user)");
3027dd979dfSMark Johnston 	PMAP_LOCK_INIT(vmspace_pmap(vm));
303b23f72e9SBrian Feldman 	return (0);
3048355f576SJeff Roberson }
3058355f576SJeff Roberson 
3068355f576SJeff Roberson #ifdef INVARIANTS
3078355f576SJeff Roberson static void
3088355f576SJeff Roberson vmspace_zdtor(void *mem, int size, void *arg)
3098355f576SJeff Roberson {
3108355f576SJeff Roberson 	struct vmspace *vm;
3118355f576SJeff Roberson 
3128355f576SJeff Roberson 	vm = (struct vmspace *)mem;
3137dd979dfSMark Johnston 	KASSERT(vm->vm_map.nentries == 0,
3147dd979dfSMark Johnston 	    ("vmspace %p nentries == %d on free", vm, vm->vm_map.nentries));
3157dd979dfSMark Johnston 	KASSERT(vm->vm_map.size == 0,
3167dd979dfSMark Johnston 	    ("vmspace %p size == %ju on free", vm, (uintmax_t)vm->vm_map.size));
3178355f576SJeff Roberson }
3188355f576SJeff Roberson #endif	/* INVARIANTS */
3198355f576SJeff Roberson 
320df8bae1dSRodney W. Grimes /*
321df8bae1dSRodney W. Grimes  * Allocate a vmspace structure, including a vm_map and pmap,
322df8bae1dSRodney W. Grimes  * and initialize those structures.  The refcnt is set to 1.
323df8bae1dSRodney W. Grimes  */
324df8bae1dSRodney W. Grimes struct vmspace *
32574d1d2b7SNeel Natu vmspace_alloc(vm_offset_t min, vm_offset_t max, pmap_pinit_t pinit)
326df8bae1dSRodney W. Grimes {
327c0877f10SJohn Dyson 	struct vmspace *vm;
3280d94caffSDavid Greenman 
329a163d034SWarner Losh 	vm = uma_zalloc(vmspace_zone, M_WAITOK);
33074d1d2b7SNeel Natu 	KASSERT(vm->vm_map.pmap == NULL, ("vm_map.pmap must be NULL"));
33174d1d2b7SNeel Natu 	if (!pinit(vmspace_pmap(vm))) {
33289b57fcfSKonstantin Belousov 		uma_zfree(vmspace_zone, vm);
33389b57fcfSKonstantin Belousov 		return (NULL);
33489b57fcfSKonstantin Belousov 	}
33521c641b2SJohn Baldwin 	CTR1(KTR_VM, "vmspace_alloc: %p", vm);
33692351f16SAlan Cox 	_vm_map_init(&vm->vm_map, vmspace_pmap(vm), min, max);
337f7db0c95SMark Johnston 	refcount_init(&vm->vm_refcnt, 1);
3382d8acc0fSJohn Dyson 	vm->vm_shm = NULL;
33951ab6c28SAlan Cox 	vm->vm_swrss = 0;
34051ab6c28SAlan Cox 	vm->vm_tsize = 0;
34151ab6c28SAlan Cox 	vm->vm_dsize = 0;
34251ab6c28SAlan Cox 	vm->vm_ssize = 0;
34351ab6c28SAlan Cox 	vm->vm_taddr = 0;
34451ab6c28SAlan Cox 	vm->vm_daddr = 0;
34551ab6c28SAlan Cox 	vm->vm_maxsaddr = 0;
346df8bae1dSRodney W. Grimes 	return (vm);
347df8bae1dSRodney W. Grimes }
348df8bae1dSRodney W. Grimes 
3494b5c9cf6SEdward Tomasz Napierala #ifdef RACCT
3501ba5ad42SEdward Tomasz Napierala static void
3511ba5ad42SEdward Tomasz Napierala vmspace_container_reset(struct proc *p)
3521ba5ad42SEdward Tomasz Napierala {
3531ba5ad42SEdward Tomasz Napierala 
3541ba5ad42SEdward Tomasz Napierala 	PROC_LOCK(p);
3551ba5ad42SEdward Tomasz Napierala 	racct_set(p, RACCT_DATA, 0);
3561ba5ad42SEdward Tomasz Napierala 	racct_set(p, RACCT_STACK, 0);
3571ba5ad42SEdward Tomasz Napierala 	racct_set(p, RACCT_RSS, 0);
3581ba5ad42SEdward Tomasz Napierala 	racct_set(p, RACCT_MEMLOCK, 0);
3591ba5ad42SEdward Tomasz Napierala 	racct_set(p, RACCT_VMEM, 0);
3601ba5ad42SEdward Tomasz Napierala 	PROC_UNLOCK(p);
3611ba5ad42SEdward Tomasz Napierala }
3624b5c9cf6SEdward Tomasz Napierala #endif
3631ba5ad42SEdward Tomasz Napierala 
36462a59e8fSWarner Losh static inline void
365582ec34cSAlfred Perlstein vmspace_dofree(struct vmspace *vm)
366df8bae1dSRodney W. Grimes {
3670ef12795SAlan Cox 
36821c641b2SJohn Baldwin 	CTR1(KTR_VM, "vmspace_free: %p", vm);
3693db161e0SMatthew Dillon 
3703db161e0SMatthew Dillon 	/*
3713db161e0SMatthew Dillon 	 * Make sure any SysV shm is freed, it might not have been in
3723db161e0SMatthew Dillon 	 * exit1().
3733db161e0SMatthew Dillon 	 */
3743db161e0SMatthew Dillon 	shmexit(vm);
3753db161e0SMatthew Dillon 
37630dcfc09SJohn Dyson 	/*
377df8bae1dSRodney W. Grimes 	 * Lock the map, to wait out all other references to it.
3780d94caffSDavid Greenman 	 * Delete all of the mappings and pages they hold, then call
3790d94caffSDavid Greenman 	 * the pmap module to reclaim anything left.
380df8bae1dSRodney W. Grimes 	 */
381f0165b1cSKonstantin Belousov 	(void)vm_map_remove(&vm->vm_map, vm_map_min(&vm->vm_map),
382f0165b1cSKonstantin Belousov 	    vm_map_max(&vm->vm_map));
3838355f576SJeff Roberson 
3840ef12795SAlan Cox 	pmap_release(vmspace_pmap(vm));
3850ef12795SAlan Cox 	vm->vm_map.pmap = NULL;
3868355f576SJeff Roberson 	uma_zfree(vmspace_zone, vm);
387df8bae1dSRodney W. Grimes }
388582ec34cSAlfred Perlstein 
389582ec34cSAlfred Perlstein void
390582ec34cSAlfred Perlstein vmspace_free(struct vmspace *vm)
391582ec34cSAlfred Perlstein {
392582ec34cSAlfred Perlstein 
393423521aaSRyan Stone 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
394164a37a5SJohn Baldwin 	    "vmspace_free() called");
395423521aaSRyan Stone 
396f7db0c95SMark Johnston 	if (refcount_release(&vm->vm_refcnt))
397582ec34cSAlfred Perlstein 		vmspace_dofree(vm);
398582ec34cSAlfred Perlstein }
399582ec34cSAlfred Perlstein 
400582ec34cSAlfred Perlstein void
401582ec34cSAlfred Perlstein vmspace_exitfree(struct proc *p)
402582ec34cSAlfred Perlstein {
403334f7061SPeter Wemm 	struct vmspace *vm;
404582ec34cSAlfred Perlstein 
40557051fdcSTor Egge 	PROC_VMSPACE_LOCK(p);
406334f7061SPeter Wemm 	vm = p->p_vmspace;
407334f7061SPeter Wemm 	p->p_vmspace = NULL;
40857051fdcSTor Egge 	PROC_VMSPACE_UNLOCK(p);
40957051fdcSTor Egge 	KASSERT(vm == &vmspace0, ("vmspace_exitfree: wrong vmspace"));
41057051fdcSTor Egge 	vmspace_free(vm);
41157051fdcSTor Egge }
41257051fdcSTor Egge 
41357051fdcSTor Egge void
41457051fdcSTor Egge vmspace_exit(struct thread *td)
41557051fdcSTor Egge {
41657051fdcSTor Egge 	struct vmspace *vm;
41757051fdcSTor Egge 	struct proc *p;
418f7db0c95SMark Johnston 	bool released;
41957051fdcSTor Egge 
42057051fdcSTor Egge 	p = td->td_proc;
42157051fdcSTor Egge 	vm = p->p_vmspace;
422f7db0c95SMark Johnston 
423f7db0c95SMark Johnston 	/*
424f7db0c95SMark Johnston 	 * Prepare to release the vmspace reference.  The thread that releases
425f7db0c95SMark Johnston 	 * the last reference is responsible for tearing down the vmspace.
426f7db0c95SMark Johnston 	 * However, threads not releasing the final reference must switch to the
427f7db0c95SMark Johnston 	 * kernel's vmspace0 before the decrement so that the subsequent pmap
428f7db0c95SMark Johnston 	 * deactivation does not modify a freed vmspace.
429f7db0c95SMark Johnston 	 */
430f7db0c95SMark Johnston 	refcount_acquire(&vmspace0.vm_refcnt);
431f7db0c95SMark Johnston 	if (!(released = refcount_release_if_last(&vm->vm_refcnt))) {
432f7db0c95SMark Johnston 		if (p->p_vmspace != &vmspace0) {
43357051fdcSTor Egge 			PROC_VMSPACE_LOCK(p);
43457051fdcSTor Egge 			p->p_vmspace = &vmspace0;
43557051fdcSTor Egge 			PROC_VMSPACE_UNLOCK(p);
43657051fdcSTor Egge 			pmap_activate(td);
43757051fdcSTor Egge 		}
438f7db0c95SMark Johnston 		released = refcount_release(&vm->vm_refcnt);
439f7db0c95SMark Johnston 	}
440f7db0c95SMark Johnston 	if (released) {
441f7db0c95SMark Johnston 		/*
442f7db0c95SMark Johnston 		 * pmap_remove_pages() expects the pmap to be active, so switch
443f7db0c95SMark Johnston 		 * back first if necessary.
444f7db0c95SMark Johnston 		 */
44557051fdcSTor Egge 		if (p->p_vmspace != vm) {
44657051fdcSTor Egge 			PROC_VMSPACE_LOCK(p);
44757051fdcSTor Egge 			p->p_vmspace = vm;
44857051fdcSTor Egge 			PROC_VMSPACE_UNLOCK(p);
44957051fdcSTor Egge 			pmap_activate(td);
45057051fdcSTor Egge 		}
45157051fdcSTor Egge 		pmap_remove_pages(vmspace_pmap(vm));
45257051fdcSTor Egge 		PROC_VMSPACE_LOCK(p);
45357051fdcSTor Egge 		p->p_vmspace = &vmspace0;
45457051fdcSTor Egge 		PROC_VMSPACE_UNLOCK(p);
45557051fdcSTor Egge 		pmap_activate(td);
456334f7061SPeter Wemm 		vmspace_dofree(vm);
457334f7061SPeter Wemm 	}
4584b5c9cf6SEdward Tomasz Napierala #ifdef RACCT
4594b5c9cf6SEdward Tomasz Napierala 	if (racct_enable)
4601ba5ad42SEdward Tomasz Napierala 		vmspace_container_reset(p);
4614b5c9cf6SEdward Tomasz Napierala #endif
46257051fdcSTor Egge }
46357051fdcSTor Egge 
46457051fdcSTor Egge /* Acquire reference to vmspace owned by another process. */
46557051fdcSTor Egge 
46657051fdcSTor Egge struct vmspace *
46757051fdcSTor Egge vmspace_acquire_ref(struct proc *p)
46857051fdcSTor Egge {
46957051fdcSTor Egge 	struct vmspace *vm;
47057051fdcSTor Egge 
47157051fdcSTor Egge 	PROC_VMSPACE_LOCK(p);
47257051fdcSTor Egge 	vm = p->p_vmspace;
473f7db0c95SMark Johnston 	if (vm == NULL || !refcount_acquire_if_not_zero(&vm->vm_refcnt)) {
47457051fdcSTor Egge 		PROC_VMSPACE_UNLOCK(p);
47557051fdcSTor Egge 		return (NULL);
47657051fdcSTor Egge 	}
47757051fdcSTor Egge 	if (vm != p->p_vmspace) {
47857051fdcSTor Egge 		PROC_VMSPACE_UNLOCK(p);
47957051fdcSTor Egge 		vmspace_free(vm);
48057051fdcSTor Egge 		return (NULL);
48157051fdcSTor Egge 	}
48257051fdcSTor Egge 	PROC_VMSPACE_UNLOCK(p);
48357051fdcSTor Egge 	return (vm);
48457051fdcSTor Egge }
485df8bae1dSRodney W. Grimes 
4868a4dc40fSJohn Baldwin /*
4878a4dc40fSJohn Baldwin  * Switch between vmspaces in an AIO kernel process.
4888a4dc40fSJohn Baldwin  *
4890b96ca33SJohn Baldwin  * The new vmspace is either the vmspace of a user process obtained
4900b96ca33SJohn Baldwin  * from an active AIO request or the initial vmspace of the AIO kernel
4910b96ca33SJohn Baldwin  * process (when it is idling).  Because user processes will block to
4920b96ca33SJohn Baldwin  * drain any active AIO requests before proceeding in exit() or
4930b96ca33SJohn Baldwin  * execve(), the reference count for vmspaces from AIO requests can
4940b96ca33SJohn Baldwin  * never be 0.  Similarly, AIO kernel processes hold an extra
4950b96ca33SJohn Baldwin  * reference on their initial vmspace for the life of the process.  As
4960b96ca33SJohn Baldwin  * a result, the 'newvm' vmspace always has a non-zero reference
4970b96ca33SJohn Baldwin  * count.  This permits an additional reference on 'newvm' to be
4980b96ca33SJohn Baldwin  * acquired via a simple atomic increment rather than the loop in
4990b96ca33SJohn Baldwin  * vmspace_acquire_ref() above.
5008a4dc40fSJohn Baldwin  */
5018a4dc40fSJohn Baldwin void
5028a4dc40fSJohn Baldwin vmspace_switch_aio(struct vmspace *newvm)
5038a4dc40fSJohn Baldwin {
5048a4dc40fSJohn Baldwin 	struct vmspace *oldvm;
5058a4dc40fSJohn Baldwin 
5068a4dc40fSJohn Baldwin 	/* XXX: Need some way to assert that this is an aio daemon. */
5078a4dc40fSJohn Baldwin 
508f7db0c95SMark Johnston 	KASSERT(refcount_load(&newvm->vm_refcnt) > 0,
5098a4dc40fSJohn Baldwin 	    ("vmspace_switch_aio: newvm unreferenced"));
5108a4dc40fSJohn Baldwin 
5118a4dc40fSJohn Baldwin 	oldvm = curproc->p_vmspace;
5128a4dc40fSJohn Baldwin 	if (oldvm == newvm)
5138a4dc40fSJohn Baldwin 		return;
5148a4dc40fSJohn Baldwin 
5158a4dc40fSJohn Baldwin 	/*
5168a4dc40fSJohn Baldwin 	 * Point to the new address space and refer to it.
5178a4dc40fSJohn Baldwin 	 */
5188a4dc40fSJohn Baldwin 	curproc->p_vmspace = newvm;
519f7db0c95SMark Johnston 	refcount_acquire(&newvm->vm_refcnt);
5208a4dc40fSJohn Baldwin 
5218a4dc40fSJohn Baldwin 	/* Activate the new mapping. */
5228a4dc40fSJohn Baldwin 	pmap_activate(curthread);
5238a4dc40fSJohn Baldwin 
5248a4dc40fSJohn Baldwin 	vmspace_free(oldvm);
5258a4dc40fSJohn Baldwin }
5268a4dc40fSJohn Baldwin 
5271b40f8c0SMatthew Dillon void
528780b1c09SAlan Cox _vm_map_lock(vm_map_t map, const char *file, int line)
5291b40f8c0SMatthew Dillon {
530bc91c510SAlan Cox 
53193bc4879SAlan Cox 	if (map->system_map)
532ccdf2333SAttilio Rao 		mtx_lock_flags_(&map->system_mtx, 0, file, line);
53312c64974SMaxime Henrion 	else
5349fde98bbSAttilio Rao 		sx_xlock_(&map->lock, file, line);
5351b40f8c0SMatthew Dillon 	map->timestamp++;
5361b40f8c0SMatthew Dillon }
5371b40f8c0SMatthew Dillon 
53878022527SKonstantin Belousov void
53978022527SKonstantin Belousov vm_map_entry_set_vnode_text(vm_map_entry_t entry, bool add)
54078022527SKonstantin Belousov {
54167388836SKonstantin Belousov 	vm_object_t object;
54278022527SKonstantin Belousov 	struct vnode *vp;
54367388836SKonstantin Belousov 	bool vp_held;
54478022527SKonstantin Belousov 
54578022527SKonstantin Belousov 	if ((entry->eflags & MAP_ENTRY_VN_EXEC) == 0)
54678022527SKonstantin Belousov 		return;
54778022527SKonstantin Belousov 	KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
54878022527SKonstantin Belousov 	    ("Submap with execs"));
54978022527SKonstantin Belousov 	object = entry->object.vm_object;
55078022527SKonstantin Belousov 	KASSERT(object != NULL, ("No object for text, entry %p", entry));
55167388836SKonstantin Belousov 	if ((object->flags & OBJ_ANON) != 0)
55267388836SKonstantin Belousov 		object = object->handle;
55367388836SKonstantin Belousov 	else
55467388836SKonstantin Belousov 		KASSERT(object->backing_object == NULL,
55567388836SKonstantin Belousov 		    ("non-anon object %p shadows", object));
55667388836SKonstantin Belousov 	KASSERT(object != NULL, ("No content object for text, entry %p obj %p",
55767388836SKonstantin Belousov 	    entry, entry->object.vm_object));
55878022527SKonstantin Belousov 
55967388836SKonstantin Belousov 	/*
56067388836SKonstantin Belousov 	 * Mostly, we do not lock the backing object.  It is
56167388836SKonstantin Belousov 	 * referenced by the entry we are processing, so it cannot go
56267388836SKonstantin Belousov 	 * away.
56367388836SKonstantin Belousov 	 */
564192112b7SKonstantin Belousov 	vm_pager_getvp(object, &vp, &vp_held);
56532d2014dSKonstantin Belousov 	if (vp != NULL) {
566bb9e2184SKonstantin Belousov 		if (add) {
56778022527SKonstantin Belousov 			VOP_SET_TEXT_CHECKED(vp);
568bb9e2184SKonstantin Belousov 		} else {
569bb9e2184SKonstantin Belousov 			vn_lock(vp, LK_SHARED | LK_RETRY);
570bb9e2184SKonstantin Belousov 			VOP_UNSET_TEXT_CHECKED(vp);
571b249ce48SMateusz Guzik 			VOP_UNLOCK(vp);
572bb9e2184SKonstantin Belousov 		}
57367388836SKonstantin Belousov 		if (vp_held)
57467388836SKonstantin Belousov 			vdrop(vp);
575bb9e2184SKonstantin Belousov 	}
57678022527SKonstantin Belousov }
57778022527SKonstantin Belousov 
5787cdcf863SDoug Moore /*
5797cdcf863SDoug Moore  * Use a different name for this vm_map_entry field when it's use
5807cdcf863SDoug Moore  * is not consistent with its use as part of an ordered search tree.
5817cdcf863SDoug Moore  */
5827cdcf863SDoug Moore #define defer_next right
5837cdcf863SDoug Moore 
5840b367bd8SKonstantin Belousov static void
5850b367bd8SKonstantin Belousov vm_map_process_deferred(void)
5860e0af8ecSBrian Feldman {
5870b367bd8SKonstantin Belousov 	struct thread *td;
5886fbe60faSJohn Baldwin 	vm_map_entry_t entry, next;
58984110e7eSKonstantin Belousov 	vm_object_t object;
590655c3490SKonstantin Belousov 
5910b367bd8SKonstantin Belousov 	td = curthread;
5926fbe60faSJohn Baldwin 	entry = td->td_map_def_user;
5936fbe60faSJohn Baldwin 	td->td_map_def_user = NULL;
5946fbe60faSJohn Baldwin 	while (entry != NULL) {
5957cdcf863SDoug Moore 		next = entry->defer_next;
596fe7bcbafSKyle Evans 		MPASS((entry->eflags & (MAP_ENTRY_WRITECNT |
597fe7bcbafSKyle Evans 		    MAP_ENTRY_VN_EXEC)) != (MAP_ENTRY_WRITECNT |
59878022527SKonstantin Belousov 		    MAP_ENTRY_VN_EXEC));
599fe7bcbafSKyle Evans 		if ((entry->eflags & MAP_ENTRY_WRITECNT) != 0) {
60084110e7eSKonstantin Belousov 			/*
60184110e7eSKonstantin Belousov 			 * Decrement the object's writemappings and
60284110e7eSKonstantin Belousov 			 * possibly the vnode's v_writecount.
60384110e7eSKonstantin Belousov 			 */
60484110e7eSKonstantin Belousov 			KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
60584110e7eSKonstantin Belousov 			    ("Submap with writecount"));
60684110e7eSKonstantin Belousov 			object = entry->object.vm_object;
60784110e7eSKonstantin Belousov 			KASSERT(object != NULL, ("No object for writecount"));
608fe7bcbafSKyle Evans 			vm_pager_release_writecount(object, entry->start,
60984110e7eSKonstantin Belousov 			    entry->end);
61084110e7eSKonstantin Belousov 		}
61178022527SKonstantin Belousov 		vm_map_entry_set_vnode_text(entry, false);
6120b367bd8SKonstantin Belousov 		vm_map_entry_deallocate(entry, FALSE);
6136fbe60faSJohn Baldwin 		entry = next;
6140b367bd8SKonstantin Belousov 	}
6150b367bd8SKonstantin Belousov }
6160b367bd8SKonstantin Belousov 
617461587dcSDoug Moore #ifdef INVARIANTS
618461587dcSDoug Moore static void
619461587dcSDoug Moore _vm_map_assert_locked(vm_map_t map, const char *file, int line)
620461587dcSDoug Moore {
621461587dcSDoug Moore 
622461587dcSDoug Moore 	if (map->system_map)
623461587dcSDoug Moore 		mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
624461587dcSDoug Moore 	else
625461587dcSDoug Moore 		sx_assert_(&map->lock, SA_XLOCKED, file, line);
626461587dcSDoug Moore }
627461587dcSDoug Moore 
628461587dcSDoug Moore #define	VM_MAP_ASSERT_LOCKED(map) \
629461587dcSDoug Moore     _vm_map_assert_locked(map, LOCK_FILE, LOCK_LINE)
630461587dcSDoug Moore 
631461587dcSDoug Moore enum { VMMAP_CHECK_NONE, VMMAP_CHECK_UNLOCK, VMMAP_CHECK_ALL };
632461587dcSDoug Moore #ifdef DIAGNOSTIC
633461587dcSDoug Moore static int enable_vmmap_check = VMMAP_CHECK_UNLOCK;
634461587dcSDoug Moore #else
635461587dcSDoug Moore static int enable_vmmap_check = VMMAP_CHECK_NONE;
636461587dcSDoug Moore #endif
637461587dcSDoug Moore SYSCTL_INT(_debug, OID_AUTO, vmmap_check, CTLFLAG_RWTUN,
638461587dcSDoug Moore     &enable_vmmap_check, 0, "Enable vm map consistency checking");
639461587dcSDoug Moore 
640461587dcSDoug Moore static void _vm_map_assert_consistent(vm_map_t map, int check);
641461587dcSDoug Moore 
642461587dcSDoug Moore #define VM_MAP_ASSERT_CONSISTENT(map) \
643461587dcSDoug Moore     _vm_map_assert_consistent(map, VMMAP_CHECK_ALL)
644461587dcSDoug Moore #ifdef DIAGNOSTIC
645461587dcSDoug Moore #define VM_MAP_UNLOCK_CONSISTENT(map) do {				\
646461587dcSDoug Moore 	if (map->nupdates > map->nentries) {				\
647461587dcSDoug Moore 		_vm_map_assert_consistent(map, VMMAP_CHECK_UNLOCK);	\
648461587dcSDoug Moore 		map->nupdates = 0;					\
649461587dcSDoug Moore 	}								\
650461587dcSDoug Moore } while (0)
651461587dcSDoug Moore #else
652461587dcSDoug Moore #define VM_MAP_UNLOCK_CONSISTENT(map)
653461587dcSDoug Moore #endif
654461587dcSDoug Moore #else
655461587dcSDoug Moore #define	VM_MAP_ASSERT_LOCKED(map)
656461587dcSDoug Moore #define VM_MAP_ASSERT_CONSISTENT(map)
657461587dcSDoug Moore #define VM_MAP_UNLOCK_CONSISTENT(map)
658461587dcSDoug Moore #endif /* INVARIANTS */
659461587dcSDoug Moore 
6600b367bd8SKonstantin Belousov void
6610b367bd8SKonstantin Belousov _vm_map_unlock(vm_map_t map, const char *file, int line)
6620b367bd8SKonstantin Belousov {
6630b367bd8SKonstantin Belousov 
664461587dcSDoug Moore 	VM_MAP_UNLOCK_CONSISTENT(map);
66520f02659SMark Johnston 	if (map->system_map) {
66620f02659SMark Johnston #ifndef UMA_MD_SMALL_ALLOC
66720f02659SMark Johnston 		if (map == kernel_map && (map->flags & MAP_REPLENISH) != 0) {
66820f02659SMark Johnston 			uma_prealloc(kmapentzone, 1);
66920f02659SMark Johnston 			map->flags &= ~MAP_REPLENISH;
67020f02659SMark Johnston 		}
67120f02659SMark Johnston #endif
672ccdf2333SAttilio Rao 		mtx_unlock_flags_(&map->system_mtx, 0, file, line);
67320f02659SMark Johnston 	} else {
6749fde98bbSAttilio Rao 		sx_xunlock_(&map->lock, file, line);
6750b367bd8SKonstantin Belousov 		vm_map_process_deferred();
676655c3490SKonstantin Belousov 	}
6770e0af8ecSBrian Feldman }
6780e0af8ecSBrian Feldman 
6790e0af8ecSBrian Feldman void
680780b1c09SAlan Cox _vm_map_lock_read(vm_map_t map, const char *file, int line)
6810e0af8ecSBrian Feldman {
682bc91c510SAlan Cox 
68393bc4879SAlan Cox 	if (map->system_map)
684ccdf2333SAttilio Rao 		mtx_lock_flags_(&map->system_mtx, 0, file, line);
68512c64974SMaxime Henrion 	else
6869fde98bbSAttilio Rao 		sx_slock_(&map->lock, file, line);
68736daaecdSAlan Cox }
6880e0af8ecSBrian Feldman 
6890e0af8ecSBrian Feldman void
690780b1c09SAlan Cox _vm_map_unlock_read(vm_map_t map, const char *file, int line)
6910e0af8ecSBrian Feldman {
692bc91c510SAlan Cox 
69320f02659SMark Johnston 	if (map->system_map) {
69420f02659SMark Johnston 		KASSERT((map->flags & MAP_REPLENISH) == 0,
69520f02659SMark Johnston 		    ("%s: MAP_REPLENISH leaked", __func__));
696ccdf2333SAttilio Rao 		mtx_unlock_flags_(&map->system_mtx, 0, file, line);
69720f02659SMark Johnston 	} else {
6989fde98bbSAttilio Rao 		sx_sunlock_(&map->lock, file, line);
6990b367bd8SKonstantin Belousov 		vm_map_process_deferred();
7000b367bd8SKonstantin Belousov 	}
70125adb370SBrian Feldman }
70225adb370SBrian Feldman 
703d974f03cSAlan Cox int
704780b1c09SAlan Cox _vm_map_trylock(vm_map_t map, const char *file, int line)
705d974f03cSAlan Cox {
70625adb370SBrian Feldman 	int error;
70725adb370SBrian Feldman 
70836daaecdSAlan Cox 	error = map->system_map ?
709ccdf2333SAttilio Rao 	    !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
7109fde98bbSAttilio Rao 	    !sx_try_xlock_(&map->lock, file, line);
7113a92e5d5SAlan Cox 	if (error == 0)
7123a92e5d5SAlan Cox 		map->timestamp++;
713bc91c510SAlan Cox 	return (error == 0);
7140e0af8ecSBrian Feldman }
7150e0af8ecSBrian Feldman 
7160e0af8ecSBrian Feldman int
71772d97679SDavid Schultz _vm_map_trylock_read(vm_map_t map, const char *file, int line)
71872d97679SDavid Schultz {
71972d97679SDavid Schultz 	int error;
72072d97679SDavid Schultz 
72172d97679SDavid Schultz 	error = map->system_map ?
722ccdf2333SAttilio Rao 	    !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
7239fde98bbSAttilio Rao 	    !sx_try_slock_(&map->lock, file, line);
72472d97679SDavid Schultz 	return (error == 0);
72572d97679SDavid Schultz }
72672d97679SDavid Schultz 
72705a8c414SAlan Cox /*
72805a8c414SAlan Cox  *	_vm_map_lock_upgrade:	[ internal use only ]
72905a8c414SAlan Cox  *
73005a8c414SAlan Cox  *	Tries to upgrade a read (shared) lock on the specified map to a write
73105a8c414SAlan Cox  *	(exclusive) lock.  Returns the value "0" if the upgrade succeeds and a
73205a8c414SAlan Cox  *	non-zero value if the upgrade fails.  If the upgrade fails, the map is
73305a8c414SAlan Cox  *	returned without a read or write lock held.
73405a8c414SAlan Cox  *
73505a8c414SAlan Cox  *	Requires that the map be read locked.
73605a8c414SAlan Cox  */
73772d97679SDavid Schultz int
738780b1c09SAlan Cox _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
7390e0af8ecSBrian Feldman {
74005a8c414SAlan Cox 	unsigned int last_timestamp;
741bc91c510SAlan Cox 
74212c64974SMaxime Henrion 	if (map->system_map) {
743ccdf2333SAttilio Rao 		mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
74405a8c414SAlan Cox 	} else {
7459fde98bbSAttilio Rao 		if (!sx_try_upgrade_(&map->lock, file, line)) {
74605a8c414SAlan Cox 			last_timestamp = map->timestamp;
7479fde98bbSAttilio Rao 			sx_sunlock_(&map->lock, file, line);
7480b367bd8SKonstantin Belousov 			vm_map_process_deferred();
74905a8c414SAlan Cox 			/*
75005a8c414SAlan Cox 			 * If the map's timestamp does not change while the
75105a8c414SAlan Cox 			 * map is unlocked, then the upgrade succeeds.
75205a8c414SAlan Cox 			 */
7539fde98bbSAttilio Rao 			sx_xlock_(&map->lock, file, line);
75405a8c414SAlan Cox 			if (last_timestamp != map->timestamp) {
7559fde98bbSAttilio Rao 				sx_xunlock_(&map->lock, file, line);
75605a8c414SAlan Cox 				return (1);
75705a8c414SAlan Cox 			}
75805a8c414SAlan Cox 		}
75905a8c414SAlan Cox 	}
760bc91c510SAlan Cox 	map->timestamp++;
761bc91c510SAlan Cox 	return (0);
7620e0af8ecSBrian Feldman }
7630e0af8ecSBrian Feldman 
7640e0af8ecSBrian Feldman void
765780b1c09SAlan Cox _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
7661b40f8c0SMatthew Dillon {
767bc91c510SAlan Cox 
76812c64974SMaxime Henrion 	if (map->system_map) {
76920f02659SMark Johnston 		KASSERT((map->flags & MAP_REPLENISH) == 0,
77020f02659SMark Johnston 		    ("%s: MAP_REPLENISH leaked", __func__));
771ccdf2333SAttilio Rao 		mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
772461587dcSDoug Moore 	} else {
773461587dcSDoug Moore 		VM_MAP_UNLOCK_CONSISTENT(map);
7749fde98bbSAttilio Rao 		sx_downgrade_(&map->lock, file, line);
77505a8c414SAlan Cox 	}
776461587dcSDoug Moore }
77705a8c414SAlan Cox 
77805a8c414SAlan Cox /*
77905a8c414SAlan Cox  *	vm_map_locked:
78005a8c414SAlan Cox  *
78105a8c414SAlan Cox  *	Returns a non-zero value if the caller holds a write (exclusive) lock
78205a8c414SAlan Cox  *	on the specified map and the value "0" otherwise.
78305a8c414SAlan Cox  */
78405a8c414SAlan Cox int
78505a8c414SAlan Cox vm_map_locked(vm_map_t map)
78605a8c414SAlan Cox {
78705a8c414SAlan Cox 
78805a8c414SAlan Cox 	if (map->system_map)
78905a8c414SAlan Cox 		return (mtx_owned(&map->system_mtx));
79005a8c414SAlan Cox 	else
79105a8c414SAlan Cox 		return (sx_xlocked(&map->lock));
79225adb370SBrian Feldman }
79325adb370SBrian Feldman 
794acd9a301SAlan Cox /*
7958304adaaSAlan Cox  *	_vm_map_unlock_and_wait:
7968304adaaSAlan Cox  *
7978304adaaSAlan Cox  *	Atomically releases the lock on the specified map and puts the calling
7988304adaaSAlan Cox  *	thread to sleep.  The calling thread will remain asleep until either
7998304adaaSAlan Cox  *	vm_map_wakeup() is performed on the map or the specified timeout is
8008304adaaSAlan Cox  *	exceeded.
8018304adaaSAlan Cox  *
8028304adaaSAlan Cox  *	WARNING!  This function does not perform deferred deallocations of
8038304adaaSAlan Cox  *	objects and map	entries.  Therefore, the calling thread is expected to
8048304adaaSAlan Cox  *	reacquire the map lock after reawakening and later perform an ordinary
8058304adaaSAlan Cox  *	unlock operation, such as vm_map_unlock(), before completing its
8068304adaaSAlan Cox  *	operation on the map.
807acd9a301SAlan Cox  */
8089688f931SAlan Cox int
8098304adaaSAlan Cox _vm_map_unlock_and_wait(vm_map_t map, int timo, const char *file, int line)
810acd9a301SAlan Cox {
811acd9a301SAlan Cox 
812461587dcSDoug Moore 	VM_MAP_UNLOCK_CONSISTENT(map);
8133a92e5d5SAlan Cox 	mtx_lock(&map_sleep_mtx);
81420f02659SMark Johnston 	if (map->system_map) {
81520f02659SMark Johnston 		KASSERT((map->flags & MAP_REPLENISH) == 0,
81620f02659SMark Johnston 		    ("%s: MAP_REPLENISH leaked", __func__));
817ccdf2333SAttilio Rao 		mtx_unlock_flags_(&map->system_mtx, 0, file, line);
81820f02659SMark Johnston 	} else {
8199fde98bbSAttilio Rao 		sx_xunlock_(&map->lock, file, line);
82020f02659SMark Johnston 	}
8218304adaaSAlan Cox 	return (msleep(&map->root, &map_sleep_mtx, PDROP | PVM, "vmmaps",
8228304adaaSAlan Cox 	    timo));
823acd9a301SAlan Cox }
824acd9a301SAlan Cox 
825acd9a301SAlan Cox /*
826acd9a301SAlan Cox  *	vm_map_wakeup:
8278304adaaSAlan Cox  *
8288304adaaSAlan Cox  *	Awaken any threads that have slept on the map using
8298304adaaSAlan Cox  *	vm_map_unlock_and_wait().
830acd9a301SAlan Cox  */
8319688f931SAlan Cox void
832acd9a301SAlan Cox vm_map_wakeup(vm_map_t map)
833acd9a301SAlan Cox {
834acd9a301SAlan Cox 
835b49ecb86SAlan Cox 	/*
8363a92e5d5SAlan Cox 	 * Acquire and release map_sleep_mtx to prevent a wakeup()
8378304adaaSAlan Cox 	 * from being performed (and lost) between the map unlock
8388304adaaSAlan Cox 	 * and the msleep() in _vm_map_unlock_and_wait().
839b49ecb86SAlan Cox 	 */
8403a92e5d5SAlan Cox 	mtx_lock(&map_sleep_mtx);
8413a92e5d5SAlan Cox 	mtx_unlock(&map_sleep_mtx);
842acd9a301SAlan Cox 	wakeup(&map->root);
843acd9a301SAlan Cox }
844acd9a301SAlan Cox 
845a5db445dSMax Laier void
846a5db445dSMax Laier vm_map_busy(vm_map_t map)
847a5db445dSMax Laier {
848a5db445dSMax Laier 
849a5db445dSMax Laier 	VM_MAP_ASSERT_LOCKED(map);
850a5db445dSMax Laier 	map->busy++;
851a5db445dSMax Laier }
852a5db445dSMax Laier 
853a5db445dSMax Laier void
854a5db445dSMax Laier vm_map_unbusy(vm_map_t map)
855a5db445dSMax Laier {
856a5db445dSMax Laier 
857a5db445dSMax Laier 	VM_MAP_ASSERT_LOCKED(map);
858a5db445dSMax Laier 	KASSERT(map->busy, ("vm_map_unbusy: not busy"));
859a5db445dSMax Laier 	if (--map->busy == 0 && (map->flags & MAP_BUSY_WAKEUP)) {
860a5db445dSMax Laier 		vm_map_modflags(map, 0, MAP_BUSY_WAKEUP);
861a5db445dSMax Laier 		wakeup(&map->busy);
862a5db445dSMax Laier 	}
863a5db445dSMax Laier }
864a5db445dSMax Laier 
865a5db445dSMax Laier void
866a5db445dSMax Laier vm_map_wait_busy(vm_map_t map)
867a5db445dSMax Laier {
868a5db445dSMax Laier 
869a5db445dSMax Laier 	VM_MAP_ASSERT_LOCKED(map);
870a5db445dSMax Laier 	while (map->busy) {
871a5db445dSMax Laier 		vm_map_modflags(map, MAP_BUSY_WAKEUP, 0);
872a5db445dSMax Laier 		if (map->system_map)
873a5db445dSMax Laier 			msleep(&map->busy, &map->system_mtx, 0, "mbusy", 0);
874a5db445dSMax Laier 		else
875a5db445dSMax Laier 			sx_sleep(&map->busy, &map->lock, 0, "mbusy", 0);
876a5db445dSMax Laier 	}
877a5db445dSMax Laier 	map->timestamp++;
878a5db445dSMax Laier }
879a5db445dSMax Laier 
8801b40f8c0SMatthew Dillon long
8811b40f8c0SMatthew Dillon vmspace_resident_count(struct vmspace *vmspace)
8821b40f8c0SMatthew Dillon {
8831b40f8c0SMatthew Dillon 	return pmap_resident_count(vmspace_pmap(vmspace));
8841b40f8c0SMatthew Dillon }
8851b40f8c0SMatthew Dillon 
886ff2b5645SMatthew Dillon /*
887df8bae1dSRodney W. Grimes  * Initialize an existing vm_map structure
888df8bae1dSRodney W. Grimes  * such as that in the vmspace structure.
889df8bae1dSRodney W. Grimes  */
8908355f576SJeff Roberson static void
89192351f16SAlan Cox _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
892df8bae1dSRodney W. Grimes {
89321c641b2SJohn Baldwin 
8942203c46dSMark Johnston 	map->header.eflags = MAP_ENTRY_HEADER;
8959688f931SAlan Cox 	map->needs_wakeup = FALSE;
8963075778bSJohn Dyson 	map->system_map = 0;
89792351f16SAlan Cox 	map->pmap = pmap;
898f0165b1cSKonstantin Belousov 	map->header.end = min;
899f0165b1cSKonstantin Belousov 	map->header.start = max;
900af7cd0c5SBrian Feldman 	map->flags = 0;
901c1ad5342SDoug Moore 	map->header.left = map->header.right = &map->header;
9024e94f402SAlan Cox 	map->root = NULL;
903df8bae1dSRodney W. Grimes 	map->timestamp = 0;
904a5db445dSMax Laier 	map->busy = 0;
905fa50a355SKonstantin Belousov 	map->anon_loc = 0;
906461587dcSDoug Moore #ifdef DIAGNOSTIC
907461587dcSDoug Moore 	map->nupdates = 0;
908461587dcSDoug Moore #endif
909df8bae1dSRodney W. Grimes }
910df8bae1dSRodney W. Grimes 
911a18b1f1dSJason Evans void
91292351f16SAlan Cox vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
913a18b1f1dSJason Evans {
91492351f16SAlan Cox 
91592351f16SAlan Cox 	_vm_map_init(map, pmap, min, max);
9167dd979dfSMark Johnston 	mtx_init(&map->system_mtx, "vm map (system)", NULL,
9177dd979dfSMark Johnston 	    MTX_DEF | MTX_DUPOK);
9187dd979dfSMark Johnston 	sx_init(&map->lock, "vm map (user)");
919a18b1f1dSJason Evans }
920a18b1f1dSJason Evans 
921df8bae1dSRodney W. Grimes /*
922b18bfc3dSJohn Dyson  *	vm_map_entry_dispose:	[ internal use only ]
923b18bfc3dSJohn Dyson  *
924b18bfc3dSJohn Dyson  *	Inverse of vm_map_entry_create.
925b18bfc3dSJohn Dyson  */
92662487bb4SJohn Dyson static void
9271b40f8c0SMatthew Dillon vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
928b18bfc3dSJohn Dyson {
9292b4a2c27SAlan Cox 	uma_zfree(map->system_map ? kmapentzone : mapentzone, entry);
930b18bfc3dSJohn Dyson }
931b18bfc3dSJohn Dyson 
932b18bfc3dSJohn Dyson /*
933df8bae1dSRodney W. Grimes  *	vm_map_entry_create:	[ internal use only ]
934df8bae1dSRodney W. Grimes  *
935df8bae1dSRodney W. Grimes  *	Allocates a VM map entry for insertion.
936b28cb1caSAlfred Perlstein  *	No entry fields are filled in.
937df8bae1dSRodney W. Grimes  */
938f708ef1bSPoul-Henning Kamp static vm_map_entry_t
9391b40f8c0SMatthew Dillon vm_map_entry_create(vm_map_t map)
940df8bae1dSRodney W. Grimes {
9411f6889a1SMatthew Dillon 	vm_map_entry_t new_entry;
9421f6889a1SMatthew Dillon 
94320f02659SMark Johnston #ifndef UMA_MD_SMALL_ALLOC
94420f02659SMark Johnston 	if (map == kernel_map) {
94520f02659SMark Johnston 		VM_MAP_ASSERT_LOCKED(map);
94620f02659SMark Johnston 
94720f02659SMark Johnston 		/*
94820f02659SMark Johnston 		 * A new slab of kernel map entries cannot be allocated at this
94920f02659SMark Johnston 		 * point because the kernel map has not yet been updated to
95020f02659SMark Johnston 		 * reflect the caller's request.  Therefore, we allocate a new
95120f02659SMark Johnston 		 * map entry, dipping into the reserve if necessary, and set a
95220f02659SMark Johnston 		 * flag indicating that the reserve must be replenished before
95320f02659SMark Johnston 		 * the map is unlocked.
95420f02659SMark Johnston 		 */
95520f02659SMark Johnston 		new_entry = uma_zalloc(kmapentzone, M_NOWAIT | M_NOVM);
95620f02659SMark Johnston 		if (new_entry == NULL) {
95720f02659SMark Johnston 			new_entry = uma_zalloc(kmapentzone,
95820f02659SMark Johnston 			    M_NOWAIT | M_NOVM | M_USE_RESERVE);
95920f02659SMark Johnston 			kernel_map->flags |= MAP_REPLENISH;
96020f02659SMark Johnston 		}
96120f02659SMark Johnston 	} else
96220f02659SMark Johnston #endif
96320f02659SMark Johnston 	if (map->system_map) {
9642b4a2c27SAlan Cox 		new_entry = uma_zalloc(kmapentzone, M_NOWAIT);
96520f02659SMark Johnston 	} else {
966a163d034SWarner Losh 		new_entry = uma_zalloc(mapentzone, M_WAITOK);
96720f02659SMark Johnston 	}
96820f02659SMark Johnston 	KASSERT(new_entry != NULL,
96920f02659SMark Johnston 	    ("vm_map_entry_create: kernel resources exhausted"));
9701f6889a1SMatthew Dillon 	return (new_entry);
971df8bae1dSRodney W. Grimes }
972df8bae1dSRodney W. Grimes 
973df8bae1dSRodney W. Grimes /*
974794316a8SAlan Cox  *	vm_map_entry_set_behavior:
975794316a8SAlan Cox  *
976794316a8SAlan Cox  *	Set the expected access behavior, either normal, random, or
977794316a8SAlan Cox  *	sequential.
978794316a8SAlan Cox  */
97962a59e8fSWarner Losh static inline void
980794316a8SAlan Cox vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
981794316a8SAlan Cox {
982794316a8SAlan Cox 	entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
983794316a8SAlan Cox 	    (behavior & MAP_ENTRY_BEHAV_MASK);
984794316a8SAlan Cox }
985794316a8SAlan Cox 
986794316a8SAlan Cox /*
9875a0879daSDoug Moore  *	vm_map_entry_max_free_{left,right}:
9880164e057SAlan Cox  *
9895a0879daSDoug Moore  *	Compute the size of the largest free gap between two entries,
9905a0879daSDoug Moore  *	one the root of a tree and the other the ancestor of that root
9915a0879daSDoug Moore  *	that is the least or greatest ancestor found on the search path.
9920164e057SAlan Cox  */
9935a0879daSDoug Moore static inline vm_size_t
9945a0879daSDoug Moore vm_map_entry_max_free_left(vm_map_entry_t root, vm_map_entry_t left_ancestor)
9950164e057SAlan Cox {
9960164e057SAlan Cox 
997c1ad5342SDoug Moore 	return (root->left != left_ancestor ?
9985a0879daSDoug Moore 	    root->left->max_free : root->start - left_ancestor->end);
9995a0879daSDoug Moore }
10005a0879daSDoug Moore 
10015a0879daSDoug Moore static inline vm_size_t
10025a0879daSDoug Moore vm_map_entry_max_free_right(vm_map_entry_t root, vm_map_entry_t right_ancestor)
10035a0879daSDoug Moore {
10045a0879daSDoug Moore 
1005c1ad5342SDoug Moore 	return (root->right != right_ancestor ?
10065a0879daSDoug Moore 	    root->right->max_free : right_ancestor->start - root->end);
10070164e057SAlan Cox }
10080164e057SAlan Cox 
100983704cc2SDoug Moore /*
101083704cc2SDoug Moore  *	vm_map_entry_{pred,succ}:
101183704cc2SDoug Moore  *
101283704cc2SDoug Moore  *	Find the {predecessor, successor} of the entry by taking one step
101383704cc2SDoug Moore  *	in the appropriate direction and backtracking as much as necessary.
1014c1ad5342SDoug Moore  *	vm_map_entry_succ is defined in vm_map.h.
101583704cc2SDoug Moore  */
101683704cc2SDoug Moore static inline vm_map_entry_t
101783704cc2SDoug Moore vm_map_entry_pred(vm_map_entry_t entry)
101883704cc2SDoug Moore {
1019c1ad5342SDoug Moore 	vm_map_entry_t prior;
102083704cc2SDoug Moore 
1021c1ad5342SDoug Moore 	prior = entry->left;
1022c1ad5342SDoug Moore 	if (prior->right->start < entry->start) {
1023c1ad5342SDoug Moore 		do
1024c1ad5342SDoug Moore 			prior = prior->right;
1025c1ad5342SDoug Moore 		while (prior->right != entry);
102683704cc2SDoug Moore 	}
1027c1ad5342SDoug Moore 	return (prior);
1028c1ad5342SDoug Moore }
102983704cc2SDoug Moore 
103085b7bedbSDoug Moore static inline vm_size_t
103185b7bedbSDoug Moore vm_size_max(vm_size_t a, vm_size_t b)
103285b7bedbSDoug Moore {
103385b7bedbSDoug Moore 
103485b7bedbSDoug Moore 	return (a > b ? a : b);
103585b7bedbSDoug Moore }
103685b7bedbSDoug Moore 
1037c1ad5342SDoug Moore #define SPLAY_LEFT_STEP(root, y, llist, rlist, test) do {		\
1038c1ad5342SDoug Moore 	vm_map_entry_t z;						\
10395a0879daSDoug Moore 	vm_size_t max_free;						\
10405a0879daSDoug Moore 									\
10415a0879daSDoug Moore 	/*								\
10425a0879daSDoug Moore 	 * Infer root->right->max_free == root->max_free when		\
10435a0879daSDoug Moore 	 * y->max_free < root->max_free || root->max_free == 0.		\
10445a0879daSDoug Moore 	 * Otherwise, look right to find it.				\
10455a0879daSDoug Moore 	 */								\
10469f701172SKonstantin Belousov 	y = root->left;							\
10475a0879daSDoug Moore 	max_free = root->max_free;					\
1048668a8aa8SDoug Moore 	KASSERT(max_free == vm_size_max(				\
1049668a8aa8SDoug Moore 	    vm_map_entry_max_free_left(root, llist),			\
1050668a8aa8SDoug Moore 	    vm_map_entry_max_free_right(root, rlist)),			\
10515a0879daSDoug Moore 	    ("%s: max_free invariant fails", __func__));		\
1052668a8aa8SDoug Moore 	if (max_free - 1 < vm_map_entry_max_free_left(root, llist))	\
10535a0879daSDoug Moore 		max_free = vm_map_entry_max_free_right(root, rlist);	\
1054c1ad5342SDoug Moore 	if (y != llist && (test)) {					\
10559f701172SKonstantin Belousov 		/* Rotate right and make y root. */			\
1056c1ad5342SDoug Moore 		z = y->right;						\
1057c1ad5342SDoug Moore 		if (z != root) {					\
1058c1ad5342SDoug Moore 			root->left = z;					\
10599f701172SKonstantin Belousov 			y->right = root;				\
10605a0879daSDoug Moore 			if (max_free < y->max_free)			\
106185b7bedbSDoug Moore 			    root->max_free = max_free =			\
1062c1ad5342SDoug Moore 			    vm_size_max(max_free, z->max_free);		\
1063c1ad5342SDoug Moore 		} else if (max_free < y->max_free)			\
1064c1ad5342SDoug Moore 			root->max_free = max_free =			\
1065c1ad5342SDoug Moore 			    vm_size_max(max_free, root->start - y->end);\
10669f701172SKonstantin Belousov 		root = y;						\
10679f701172SKonstantin Belousov 		y = root->left;						\
10689f701172SKonstantin Belousov 	}								\
10695a0879daSDoug Moore 	/* Copy right->max_free.  Put root on rlist. */			\
10705a0879daSDoug Moore 	root->max_free = max_free;					\
10715a0879daSDoug Moore 	KASSERT(max_free == vm_map_entry_max_free_right(root, rlist),	\
10725a0879daSDoug Moore 	    ("%s: max_free not copied from right", __func__));		\
10739f701172SKonstantin Belousov 	root->left = rlist;						\
10749f701172SKonstantin Belousov 	rlist = root;							\
1075c1ad5342SDoug Moore 	root = y != llist ? y : NULL;					\
10769f701172SKonstantin Belousov } while (0)
10779f701172SKonstantin Belousov 
1078c1ad5342SDoug Moore #define SPLAY_RIGHT_STEP(root, y, llist, rlist, test) do {		\
1079c1ad5342SDoug Moore 	vm_map_entry_t z;						\
10805a0879daSDoug Moore 	vm_size_t max_free;						\
10815a0879daSDoug Moore 									\
10825a0879daSDoug Moore 	/*								\
10835a0879daSDoug Moore 	 * Infer root->left->max_free == root->max_free when		\
10845a0879daSDoug Moore 	 * y->max_free < root->max_free || root->max_free == 0.		\
10855a0879daSDoug Moore 	 * Otherwise, look left to find it.				\
10865a0879daSDoug Moore 	 */								\
10879f701172SKonstantin Belousov 	y = root->right;						\
10885a0879daSDoug Moore 	max_free = root->max_free;					\
1089668a8aa8SDoug Moore 	KASSERT(max_free == vm_size_max(				\
1090668a8aa8SDoug Moore 	    vm_map_entry_max_free_left(root, llist),			\
1091668a8aa8SDoug Moore 	    vm_map_entry_max_free_right(root, rlist)),			\
10925a0879daSDoug Moore 	    ("%s: max_free invariant fails", __func__));		\
1093668a8aa8SDoug Moore 	if (max_free - 1 < vm_map_entry_max_free_right(root, rlist))	\
10945a0879daSDoug Moore 		max_free = vm_map_entry_max_free_left(root, llist);	\
1095c1ad5342SDoug Moore 	if (y != rlist && (test)) {					\
10969f701172SKonstantin Belousov 		/* Rotate left and make y root. */			\
1097c1ad5342SDoug Moore 		z = y->left;						\
1098c1ad5342SDoug Moore 		if (z != root) {					\
1099c1ad5342SDoug Moore 			root->right = z;				\
11009f701172SKonstantin Belousov 			y->left = root;					\
11015a0879daSDoug Moore 			if (max_free < y->max_free)			\
110285b7bedbSDoug Moore 			    root->max_free = max_free =			\
1103c1ad5342SDoug Moore 			    vm_size_max(max_free, z->max_free);		\
1104c1ad5342SDoug Moore 		} else if (max_free < y->max_free)			\
1105c1ad5342SDoug Moore 			root->max_free = max_free =			\
1106c1ad5342SDoug Moore 			    vm_size_max(max_free, y->start - root->end);\
11079f701172SKonstantin Belousov 		root = y;						\
11089f701172SKonstantin Belousov 		y = root->right;					\
11099f701172SKonstantin Belousov 	}								\
11105a0879daSDoug Moore 	/* Copy left->max_free.  Put root on llist. */			\
11115a0879daSDoug Moore 	root->max_free = max_free;					\
11125a0879daSDoug Moore 	KASSERT(max_free == vm_map_entry_max_free_left(root, llist),	\
11135a0879daSDoug Moore 	    ("%s: max_free not copied from left", __func__));		\
11149f701172SKonstantin Belousov 	root->right = llist;						\
11159f701172SKonstantin Belousov 	llist = root;							\
1116c1ad5342SDoug Moore 	root = y != rlist ? y : NULL;					\
11179f701172SKonstantin Belousov } while (0)
11189f701172SKonstantin Belousov 
11190164e057SAlan Cox /*
1120c1ad5342SDoug Moore  * Walk down the tree until we find addr or a gap where addr would go, breaking
1121c1ad5342SDoug Moore  * off left and right subtrees of nodes less than, or greater than addr.  Treat
1122c1ad5342SDoug Moore  * subtrees with root->max_free < length as empty trees.  llist and rlist are
1123c1ad5342SDoug Moore  * the two sides in reverse order (bottom-up), with llist linked by the right
1124c1ad5342SDoug Moore  * pointer and rlist linked by the left pointer in the vm_map_entry, and both
1125c1ad5342SDoug Moore  * lists terminated by &map->header.  This function, and the subsequent call to
1126c1ad5342SDoug Moore  * vm_map_splay_merge_{left,right,pred,succ}, rely on the start and end address
11275a0879daSDoug Moore  * values in &map->header.
11284e94f402SAlan Cox  */
11291867d2f2SDoug Moore static __always_inline vm_map_entry_t
11305a0879daSDoug Moore vm_map_splay_split(vm_map_t map, vm_offset_t addr, vm_size_t length,
11311867d2f2SDoug Moore     vm_map_entry_t *llist, vm_map_entry_t *rlist)
11324e94f402SAlan Cox {
1133c1ad5342SDoug Moore 	vm_map_entry_t left, right, root, y;
11344e94f402SAlan Cox 
1135c1ad5342SDoug Moore 	left = right = &map->header;
11365a0879daSDoug Moore 	root = map->root;
11379f701172SKonstantin Belousov 	while (root != NULL && root->max_free >= length) {
1138c1ad5342SDoug Moore 		KASSERT(left->end <= root->start &&
1139c1ad5342SDoug Moore 		    root->end <= right->start,
11405a0879daSDoug Moore 		    ("%s: root not within tree bounds", __func__));
11410164e057SAlan Cox 		if (addr < root->start) {
1142c1ad5342SDoug Moore 			SPLAY_LEFT_STEP(root, y, left, right,
11439f701172SKonstantin Belousov 			    y->max_free >= length && addr < y->start);
11447438d60bSAlan Cox 		} else if (addr >= root->end) {
1145c1ad5342SDoug Moore 			SPLAY_RIGHT_STEP(root, y, left, right,
11469f701172SKonstantin Belousov 			    y->max_free >= length && addr >= y->end);
11477438d60bSAlan Cox 		} else
11487438d60bSAlan Cox 			break;
11490164e057SAlan Cox 	}
1150c1ad5342SDoug Moore 	*llist = left;
1151c1ad5342SDoug Moore 	*rlist = right;
11529f701172SKonstantin Belousov 	return (root);
11539f701172SKonstantin Belousov }
11549f701172SKonstantin Belousov 
11551867d2f2SDoug Moore static __always_inline void
11561867d2f2SDoug Moore vm_map_splay_findnext(vm_map_entry_t root, vm_map_entry_t *rlist)
11579f701172SKonstantin Belousov {
1158c1ad5342SDoug Moore 	vm_map_entry_t hi, right, y;
11599f701172SKonstantin Belousov 
1160c1ad5342SDoug Moore 	right = *rlist;
1161c1ad5342SDoug Moore 	hi = root->right == right ? NULL : root->right;
1162c1ad5342SDoug Moore 	if (hi == NULL)
1163c1ad5342SDoug Moore 		return;
1164c1ad5342SDoug Moore 	do
1165c1ad5342SDoug Moore 		SPLAY_LEFT_STEP(hi, y, root, right, true);
1166c1ad5342SDoug Moore 	while (hi != NULL);
1167c1ad5342SDoug Moore 	*rlist = right;
11689f701172SKonstantin Belousov }
11699f701172SKonstantin Belousov 
11701867d2f2SDoug Moore static __always_inline void
11711867d2f2SDoug Moore vm_map_splay_findprev(vm_map_entry_t root, vm_map_entry_t *llist)
11729f701172SKonstantin Belousov {
1173c1ad5342SDoug Moore 	vm_map_entry_t left, lo, y;
11749f701172SKonstantin Belousov 
1175c1ad5342SDoug Moore 	left = *llist;
1176c1ad5342SDoug Moore 	lo = root->left == left ? NULL : root->left;
1177c1ad5342SDoug Moore 	if (lo == NULL)
1178c1ad5342SDoug Moore 		return;
1179c1ad5342SDoug Moore 	do
1180c1ad5342SDoug Moore 		SPLAY_RIGHT_STEP(lo, y, left, root, true);
1181c1ad5342SDoug Moore 	while (lo != NULL);
1182c1ad5342SDoug Moore 	*llist = left;
11839f701172SKonstantin Belousov }
11840164e057SAlan Cox 
11855a0879daSDoug Moore static inline void
11865a0879daSDoug Moore vm_map_entry_swap(vm_map_entry_t *a, vm_map_entry_t *b)
11875a0879daSDoug Moore {
11885a0879daSDoug Moore 	vm_map_entry_t tmp;
11895a0879daSDoug Moore 
11905a0879daSDoug Moore 	tmp = *b;
11915a0879daSDoug Moore 	*b = *a;
11925a0879daSDoug Moore 	*a = tmp;
11935a0879daSDoug Moore }
11945a0879daSDoug Moore 
11950164e057SAlan Cox /*
11969f701172SKonstantin Belousov  * Walk back up the two spines, flip the pointers and set max_free.  The
11979f701172SKonstantin Belousov  * subtrees of the root go at the bottom of llist and rlist.
11980164e057SAlan Cox  */
119985b7bedbSDoug Moore static vm_size_t
120085b7bedbSDoug Moore vm_map_splay_merge_left_walk(vm_map_entry_t header, vm_map_entry_t root,
120185b7bedbSDoug Moore     vm_map_entry_t tail, vm_size_t max_free, vm_map_entry_t llist)
12029f701172SKonstantin Belousov {
12035a0879daSDoug Moore 	do {
12040164e057SAlan Cox 		/*
12055a0879daSDoug Moore 		 * The max_free values of the children of llist are in
120685b7bedbSDoug Moore 		 * llist->max_free and max_free.  Update with the
12075a0879daSDoug Moore 		 * max value.
12080164e057SAlan Cox 		 */
120985b7bedbSDoug Moore 		llist->max_free = max_free =
121085b7bedbSDoug Moore 		    vm_size_max(llist->max_free, max_free);
121185b7bedbSDoug Moore 		vm_map_entry_swap(&llist->right, &tail);
121285b7bedbSDoug Moore 		vm_map_entry_swap(&tail, &llist);
121385b7bedbSDoug Moore 	} while (llist != header);
121485b7bedbSDoug Moore 	root->left = tail;
121585b7bedbSDoug Moore 	return (max_free);
12165a0879daSDoug Moore }
121785b7bedbSDoug Moore 
121885b7bedbSDoug Moore /*
121985b7bedbSDoug Moore  * When llist is known to be the predecessor of root.
122085b7bedbSDoug Moore  */
122185b7bedbSDoug Moore static inline vm_size_t
122285b7bedbSDoug Moore vm_map_splay_merge_pred(vm_map_entry_t header, vm_map_entry_t root,
122385b7bedbSDoug Moore     vm_map_entry_t llist)
122485b7bedbSDoug Moore {
122585b7bedbSDoug Moore 	vm_size_t max_free;
122685b7bedbSDoug Moore 
122785b7bedbSDoug Moore 	max_free = root->start - llist->end;
122885b7bedbSDoug Moore 	if (llist != header) {
122985b7bedbSDoug Moore 		max_free = vm_map_splay_merge_left_walk(header, root,
1230c1ad5342SDoug Moore 		    root, max_free, llist);
123185b7bedbSDoug Moore 	} else {
1232c1ad5342SDoug Moore 		root->left = header;
1233c1ad5342SDoug Moore 		header->right = root;
123485b7bedbSDoug Moore 	}
123585b7bedbSDoug Moore 	return (max_free);
123685b7bedbSDoug Moore }
123785b7bedbSDoug Moore 
123885b7bedbSDoug Moore /*
123985b7bedbSDoug Moore  * When llist may or may not be the predecessor of root.
124085b7bedbSDoug Moore  */
124185b7bedbSDoug Moore static inline vm_size_t
124285b7bedbSDoug Moore vm_map_splay_merge_left(vm_map_entry_t header, vm_map_entry_t root,
124385b7bedbSDoug Moore     vm_map_entry_t llist)
124485b7bedbSDoug Moore {
124585b7bedbSDoug Moore 	vm_size_t max_free;
124685b7bedbSDoug Moore 
124785b7bedbSDoug Moore 	max_free = vm_map_entry_max_free_left(root, llist);
124885b7bedbSDoug Moore 	if (llist != header) {
124985b7bedbSDoug Moore 		max_free = vm_map_splay_merge_left_walk(header, root,
1250c1ad5342SDoug Moore 		    root->left == llist ? root : root->left,
1251c1ad5342SDoug Moore 		    max_free, llist);
125285b7bedbSDoug Moore 	}
125385b7bedbSDoug Moore 	return (max_free);
125485b7bedbSDoug Moore }
125585b7bedbSDoug Moore 
125685b7bedbSDoug Moore static vm_size_t
125785b7bedbSDoug Moore vm_map_splay_merge_right_walk(vm_map_entry_t header, vm_map_entry_t root,
125885b7bedbSDoug Moore     vm_map_entry_t tail, vm_size_t max_free, vm_map_entry_t rlist)
125985b7bedbSDoug Moore {
12605a0879daSDoug Moore 	do {
12615a0879daSDoug Moore 		/*
12625a0879daSDoug Moore 		 * The max_free values of the children of rlist are in
126385b7bedbSDoug Moore 		 * rlist->max_free and max_free.  Update with the
12645a0879daSDoug Moore 		 * max value.
12655a0879daSDoug Moore 		 */
126685b7bedbSDoug Moore 		rlist->max_free = max_free =
126785b7bedbSDoug Moore 		    vm_size_max(rlist->max_free, max_free);
126885b7bedbSDoug Moore 		vm_map_entry_swap(&rlist->left, &tail);
126985b7bedbSDoug Moore 		vm_map_entry_swap(&tail, &rlist);
127085b7bedbSDoug Moore 	} while (rlist != header);
127185b7bedbSDoug Moore 	root->right = tail;
127285b7bedbSDoug Moore 	return (max_free);
12735a0879daSDoug Moore }
127485b7bedbSDoug Moore 
127585b7bedbSDoug Moore /*
127685b7bedbSDoug Moore  * When rlist is known to be the succecessor of root.
127785b7bedbSDoug Moore  */
127885b7bedbSDoug Moore static inline vm_size_t
127985b7bedbSDoug Moore vm_map_splay_merge_succ(vm_map_entry_t header, vm_map_entry_t root,
128085b7bedbSDoug Moore     vm_map_entry_t rlist)
128185b7bedbSDoug Moore {
128285b7bedbSDoug Moore 	vm_size_t max_free;
128385b7bedbSDoug Moore 
128485b7bedbSDoug Moore 	max_free = rlist->start - root->end;
128585b7bedbSDoug Moore 	if (rlist != header) {
128685b7bedbSDoug Moore 		max_free = vm_map_splay_merge_right_walk(header, root,
1287c1ad5342SDoug Moore 		    root, max_free, rlist);
128885b7bedbSDoug Moore 	} else {
1289c1ad5342SDoug Moore 		root->right = header;
1290c1ad5342SDoug Moore 		header->left = root;
129185b7bedbSDoug Moore 	}
129285b7bedbSDoug Moore 	return (max_free);
129385b7bedbSDoug Moore }
129485b7bedbSDoug Moore 
129585b7bedbSDoug Moore /*
129685b7bedbSDoug Moore  * When rlist may or may not be the succecessor of root.
129785b7bedbSDoug Moore  */
129885b7bedbSDoug Moore static inline vm_size_t
129985b7bedbSDoug Moore vm_map_splay_merge_right(vm_map_entry_t header, vm_map_entry_t root,
130085b7bedbSDoug Moore     vm_map_entry_t rlist)
130185b7bedbSDoug Moore {
130285b7bedbSDoug Moore 	vm_size_t max_free;
130385b7bedbSDoug Moore 
130485b7bedbSDoug Moore 	max_free = vm_map_entry_max_free_right(root, rlist);
130585b7bedbSDoug Moore 	if (rlist != header) {
130685b7bedbSDoug Moore 		max_free = vm_map_splay_merge_right_walk(header, root,
1307c1ad5342SDoug Moore 		    root->right == rlist ? root : root->right,
1308c1ad5342SDoug Moore 		    max_free, rlist);
130985b7bedbSDoug Moore 	}
131085b7bedbSDoug Moore 	return (max_free);
13114e94f402SAlan Cox }
13124e94f402SAlan Cox 
13134e94f402SAlan Cox /*
1314d1d3f7e1SDoug Moore  *	vm_map_splay:
1315d1d3f7e1SDoug Moore  *
1316d1d3f7e1SDoug Moore  *	The Sleator and Tarjan top-down splay algorithm with the
1317d1d3f7e1SDoug Moore  *	following variation.  Max_free must be computed bottom-up, so
1318d1d3f7e1SDoug Moore  *	on the downward pass, maintain the left and right spines in
1319d1d3f7e1SDoug Moore  *	reverse order.  Then, make a second pass up each side to fix
1320d1d3f7e1SDoug Moore  *	the pointers and compute max_free.  The time bound is O(log n)
1321d1d3f7e1SDoug Moore  *	amortized.
1322d1d3f7e1SDoug Moore  *
1323c1ad5342SDoug Moore  *	The tree is threaded, which means that there are no null pointers.
1324c1ad5342SDoug Moore  *	When a node has no left child, its left pointer points to its
1325c1ad5342SDoug Moore  *	predecessor, which the last ancestor on the search path from the root
1326c1ad5342SDoug Moore  *	where the search branched right.  Likewise, when a node has no right
1327c1ad5342SDoug Moore  *	child, its right pointer points to its successor.  The map header node
1328c1ad5342SDoug Moore  *	is the predecessor of the first map entry, and the successor of the
1329c1ad5342SDoug Moore  *	last.
1330c1ad5342SDoug Moore  *
1331d1d3f7e1SDoug Moore  *	The new root is the vm_map_entry containing "addr", or else an
1332d1d3f7e1SDoug Moore  *	adjacent entry (lower if possible) if addr is not in the tree.
1333d1d3f7e1SDoug Moore  *
1334d1d3f7e1SDoug Moore  *	The map must be locked, and leaves it so.
1335d1d3f7e1SDoug Moore  *
1336d1d3f7e1SDoug Moore  *	Returns: the new root.
1337d1d3f7e1SDoug Moore  */
1338d1d3f7e1SDoug Moore static vm_map_entry_t
1339d1d3f7e1SDoug Moore vm_map_splay(vm_map_t map, vm_offset_t addr)
1340d1d3f7e1SDoug Moore {
134185b7bedbSDoug Moore 	vm_map_entry_t header, llist, rlist, root;
134285b7bedbSDoug Moore 	vm_size_t max_free_left, max_free_right;
1343d1d3f7e1SDoug Moore 
134485b7bedbSDoug Moore 	header = &map->header;
1345d1d3f7e1SDoug Moore 	root = vm_map_splay_split(map, addr, 0, &llist, &rlist);
1346d1d3f7e1SDoug Moore 	if (root != NULL) {
134785b7bedbSDoug Moore 		max_free_left = vm_map_splay_merge_left(header, root, llist);
134885b7bedbSDoug Moore 		max_free_right = vm_map_splay_merge_right(header, root, rlist);
134985b7bedbSDoug Moore 	} else if (llist != header) {
1350d1d3f7e1SDoug Moore 		/*
1351d1d3f7e1SDoug Moore 		 * Recover the greatest node in the left
1352d1d3f7e1SDoug Moore 		 * subtree and make it the root.
1353d1d3f7e1SDoug Moore 		 */
1354d1d3f7e1SDoug Moore 		root = llist;
1355d1d3f7e1SDoug Moore 		llist = root->right;
135685b7bedbSDoug Moore 		max_free_left = vm_map_splay_merge_left(header, root, llist);
135785b7bedbSDoug Moore 		max_free_right = vm_map_splay_merge_succ(header, root, rlist);
135885b7bedbSDoug Moore 	} else if (rlist != header) {
1359d1d3f7e1SDoug Moore 		/*
1360d1d3f7e1SDoug Moore 		 * Recover the least node in the right
1361d1d3f7e1SDoug Moore 		 * subtree and make it the root.
1362d1d3f7e1SDoug Moore 		 */
1363d1d3f7e1SDoug Moore 		root = rlist;
1364d1d3f7e1SDoug Moore 		rlist = root->left;
136585b7bedbSDoug Moore 		max_free_left = vm_map_splay_merge_pred(header, root, llist);
136685b7bedbSDoug Moore 		max_free_right = vm_map_splay_merge_right(header, root, rlist);
1367d1d3f7e1SDoug Moore 	} else {
1368d1d3f7e1SDoug Moore 		/* There is no root. */
1369d1d3f7e1SDoug Moore 		return (NULL);
1370d1d3f7e1SDoug Moore 	}
137185b7bedbSDoug Moore 	root->max_free = vm_size_max(max_free_left, max_free_right);
137285b7bedbSDoug Moore 	map->root = root;
1373d1d3f7e1SDoug Moore 	VM_MAP_ASSERT_CONSISTENT(map);
1374d1d3f7e1SDoug Moore 	return (root);
1375d1d3f7e1SDoug Moore }
1376d1d3f7e1SDoug Moore 
1377d1d3f7e1SDoug Moore /*
1378df8bae1dSRodney W. Grimes  *	vm_map_entry_{un,}link:
1379df8bae1dSRodney W. Grimes  *
1380668a8aa8SDoug Moore  *	Insert/remove entries from maps.  On linking, if new entry clips
1381668a8aa8SDoug Moore  *	existing entry, trim existing entry to avoid overlap, and manage
1382668a8aa8SDoug Moore  *	offsets.  On unlinking, merge disappearing entry with neighbor, if
1383668a8aa8SDoug Moore  *	called for, and manage offsets.  Callers should not modify fields in
1384668a8aa8SDoug Moore  *	entries already mapped.
1385df8bae1dSRodney W. Grimes  */
13864e94f402SAlan Cox static void
13875a0879daSDoug Moore vm_map_entry_link(vm_map_t map, vm_map_entry_t entry)
138899c81ca9SAlan Cox {
138985b7bedbSDoug Moore 	vm_map_entry_t header, llist, rlist, root;
1390668a8aa8SDoug Moore 	vm_size_t max_free_left, max_free_right;
139121c641b2SJohn Baldwin 
13929f701172SKonstantin Belousov 	CTR3(KTR_VM,
13939f701172SKonstantin Belousov 	    "vm_map_entry_link: map %p, nentries %d, entry %p", map,
13949f701172SKonstantin Belousov 	    map->nentries, entry);
13953a0916b8SKonstantin Belousov 	VM_MAP_ASSERT_LOCKED(map);
139699c81ca9SAlan Cox 	map->nentries++;
139785b7bedbSDoug Moore 	header = &map->header;
13985a0879daSDoug Moore 	root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1399668a8aa8SDoug Moore 	if (root == NULL) {
1400668a8aa8SDoug Moore 		/*
1401668a8aa8SDoug Moore 		 * The new entry does not overlap any existing entry in the
1402668a8aa8SDoug Moore 		 * map, so it becomes the new root of the map tree.
1403668a8aa8SDoug Moore 		 */
1404668a8aa8SDoug Moore 		max_free_left = vm_map_splay_merge_pred(header, entry, llist);
1405668a8aa8SDoug Moore 		max_free_right = vm_map_splay_merge_succ(header, entry, rlist);
1406668a8aa8SDoug Moore 	} else if (entry->start == root->start) {
1407668a8aa8SDoug Moore 		/*
1408668a8aa8SDoug Moore 		 * The new entry is a clone of root, with only the end field
1409668a8aa8SDoug Moore 		 * changed.  The root entry will be shrunk to abut the new
1410668a8aa8SDoug Moore 		 * entry, and will be the right child of the new root entry in
1411668a8aa8SDoug Moore 		 * the modified map.
1412668a8aa8SDoug Moore 		 */
1413668a8aa8SDoug Moore 		KASSERT(entry->end < root->end,
1414668a8aa8SDoug Moore 		    ("%s: clip_start not within entry", __func__));
1415668a8aa8SDoug Moore 		vm_map_splay_findprev(root, &llist);
1416668a8aa8SDoug Moore 		root->offset += entry->end - root->start;
1417668a8aa8SDoug Moore 		root->start = entry->end;
1418668a8aa8SDoug Moore 		max_free_left = vm_map_splay_merge_pred(header, entry, llist);
1419668a8aa8SDoug Moore 		max_free_right = root->max_free = vm_size_max(
1420668a8aa8SDoug Moore 		    vm_map_splay_merge_pred(entry, root, entry),
1421668a8aa8SDoug Moore 		    vm_map_splay_merge_right(header, root, rlist));
1422668a8aa8SDoug Moore 	} else {
1423668a8aa8SDoug Moore 		/*
1424668a8aa8SDoug Moore 		 * The new entry is a clone of root, with only the start field
1425668a8aa8SDoug Moore 		 * changed.  The root entry will be shrunk to abut the new
1426668a8aa8SDoug Moore 		 * entry, and will be the left child of the new root entry in
1427668a8aa8SDoug Moore 		 * the modified map.
1428668a8aa8SDoug Moore 		 */
1429668a8aa8SDoug Moore 		KASSERT(entry->end == root->end,
1430668a8aa8SDoug Moore 		    ("%s: clip_start not within entry", __func__));
1431668a8aa8SDoug Moore 		vm_map_splay_findnext(root, &rlist);
1432668a8aa8SDoug Moore 		entry->offset += entry->start - root->start;
1433668a8aa8SDoug Moore 		root->end = entry->start;
1434668a8aa8SDoug Moore 		max_free_left = root->max_free = vm_size_max(
1435668a8aa8SDoug Moore 		    vm_map_splay_merge_left(header, root, llist),
1436668a8aa8SDoug Moore 		    vm_map_splay_merge_succ(entry, root, entry));
1437668a8aa8SDoug Moore 		max_free_right = vm_map_splay_merge_succ(header, entry, rlist);
1438668a8aa8SDoug Moore 	}
1439668a8aa8SDoug Moore 	entry->max_free = vm_size_max(max_free_left, max_free_right);
1440668a8aa8SDoug Moore 	map->root = entry;
14419f701172SKonstantin Belousov 	VM_MAP_ASSERT_CONSISTENT(map);
1442df8bae1dSRodney W. Grimes }
144399c81ca9SAlan Cox 
14449f701172SKonstantin Belousov enum unlink_merge_type {
14459f701172SKonstantin Belousov 	UNLINK_MERGE_NONE,
14469f701172SKonstantin Belousov 	UNLINK_MERGE_NEXT
14479f701172SKonstantin Belousov };
14489f701172SKonstantin Belousov 
14494e94f402SAlan Cox static void
14505a0879daSDoug Moore vm_map_entry_unlink(vm_map_t map, vm_map_entry_t entry,
14519f701172SKonstantin Belousov     enum unlink_merge_type op)
145299c81ca9SAlan Cox {
1453c1ad5342SDoug Moore 	vm_map_entry_t header, llist, rlist, root;
145485b7bedbSDoug Moore 	vm_size_t max_free_left, max_free_right;
145599c81ca9SAlan Cox 
14563a0916b8SKonstantin Belousov 	VM_MAP_ASSERT_LOCKED(map);
145785b7bedbSDoug Moore 	header = &map->header;
14585a0879daSDoug Moore 	root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
14599f701172SKonstantin Belousov 	KASSERT(root != NULL,
14609f701172SKonstantin Belousov 	    ("vm_map_entry_unlink: unlink object not mapped"));
14614e94f402SAlan Cox 
14621867d2f2SDoug Moore 	vm_map_splay_findprev(root, &llist);
14639f701172SKonstantin Belousov 	vm_map_splay_findnext(root, &rlist);
14641867d2f2SDoug Moore 	if (op == UNLINK_MERGE_NEXT) {
14659f701172SKonstantin Belousov 		rlist->start = root->start;
14669f701172SKonstantin Belousov 		rlist->offset = root->offset;
14671867d2f2SDoug Moore 	}
146885b7bedbSDoug Moore 	if (llist != header) {
14699f701172SKonstantin Belousov 		root = llist;
14709f701172SKonstantin Belousov 		llist = root->right;
147185b7bedbSDoug Moore 		max_free_left = vm_map_splay_merge_left(header, root, llist);
147285b7bedbSDoug Moore 		max_free_right = vm_map_splay_merge_succ(header, root, rlist);
147385b7bedbSDoug Moore 	} else if (rlist != header) {
14749f701172SKonstantin Belousov 		root = rlist;
14759f701172SKonstantin Belousov 		rlist = root->left;
147685b7bedbSDoug Moore 		max_free_left = vm_map_splay_merge_pred(header, root, llist);
147785b7bedbSDoug Moore 		max_free_right = vm_map_splay_merge_right(header, root, rlist);
1478c1ad5342SDoug Moore 	} else {
1479c1ad5342SDoug Moore 		header->left = header->right = header;
14809f701172SKonstantin Belousov 		root = NULL;
1481c1ad5342SDoug Moore 	}
14829f701172SKonstantin Belousov 	if (root != NULL)
148385b7bedbSDoug Moore 		root->max_free = vm_size_max(max_free_left, max_free_right);
148485b7bedbSDoug Moore 	map->root = root;
14859f701172SKonstantin Belousov 	VM_MAP_ASSERT_CONSISTENT(map);
148699c81ca9SAlan Cox 	map->nentries--;
148721c641b2SJohn Baldwin 	CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
148821c641b2SJohn Baldwin 	    map->nentries, entry);
1489df8bae1dSRodney W. Grimes }
1490df8bae1dSRodney W. Grimes 
1491df8bae1dSRodney W. Grimes /*
1492fa581662SDoug Moore  *	vm_map_entry_resize:
14930164e057SAlan Cox  *
1494fa581662SDoug Moore  *	Resize a vm_map_entry, recompute the amount of free space that
1495fa581662SDoug Moore  *	follows it and propagate that value up the tree.
14960164e057SAlan Cox  *
14970164e057SAlan Cox  *	The map must be locked, and leaves it so.
14980164e057SAlan Cox  */
14990164e057SAlan Cox static void
1500fa581662SDoug Moore vm_map_entry_resize(vm_map_t map, vm_map_entry_t entry, vm_size_t grow_amount)
15010164e057SAlan Cox {
150285b7bedbSDoug Moore 	vm_map_entry_t header, llist, rlist, root;
15030164e057SAlan Cox 
15049f701172SKonstantin Belousov 	VM_MAP_ASSERT_LOCKED(map);
150585b7bedbSDoug Moore 	header = &map->header;
15065a0879daSDoug Moore 	root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
15071867d2f2SDoug Moore 	KASSERT(root != NULL, ("%s: resize object not mapped", __func__));
15089f701172SKonstantin Belousov 	vm_map_splay_findnext(root, &rlist);
15091895f520SDoug Moore 	entry->end += grow_amount;
151085b7bedbSDoug Moore 	root->max_free = vm_size_max(
151185b7bedbSDoug Moore 	    vm_map_splay_merge_left(header, root, llist),
151285b7bedbSDoug Moore 	    vm_map_splay_merge_succ(header, root, rlist));
151385b7bedbSDoug Moore 	map->root = root;
15149f701172SKonstantin Belousov 	VM_MAP_ASSERT_CONSISTENT(map);
1515fa581662SDoug Moore 	CTR4(KTR_VM, "%s: map %p, nentries %d, entry %p",
151673f11451SDoug Moore 	    __func__, map, map->nentries, entry);
15170164e057SAlan Cox }
15180164e057SAlan Cox 
15190164e057SAlan Cox /*
1520d1d3f7e1SDoug Moore  *	vm_map_lookup_entry:	[ internal use only ]
1521df8bae1dSRodney W. Grimes  *
1522d1d3f7e1SDoug Moore  *	Finds the map entry containing (or
1523d1d3f7e1SDoug Moore  *	immediately preceding) the specified address
1524d1d3f7e1SDoug Moore  *	in the given map; the entry is returned
1525d1d3f7e1SDoug Moore  *	in the "entry" parameter.  The boolean
1526d1d3f7e1SDoug Moore  *	result indicates whether the address is
1527d1d3f7e1SDoug Moore  *	actually contained in the map.
1528df8bae1dSRodney W. Grimes  */
1529d1d3f7e1SDoug Moore boolean_t
1530d1d3f7e1SDoug Moore vm_map_lookup_entry(
1531d1d3f7e1SDoug Moore 	vm_map_t map,
1532d1d3f7e1SDoug Moore 	vm_offset_t address,
1533d1d3f7e1SDoug Moore 	vm_map_entry_t *entry)	/* OUT */
1534df8bae1dSRodney W. Grimes {
1535c1ad5342SDoug Moore 	vm_map_entry_t cur, header, lbound, ubound;
1536d1d3f7e1SDoug Moore 	boolean_t locked;
1537df8bae1dSRodney W. Grimes 
15384c3ef59eSAlan Cox 	/*
15394c3ef59eSAlan Cox 	 * If the map is empty, then the map entry immediately preceding
1540d1d3f7e1SDoug Moore 	 * "address" is the map's header.
15414c3ef59eSAlan Cox 	 */
154285b7bedbSDoug Moore 	header = &map->header;
1543d1d3f7e1SDoug Moore 	cur = map->root;
1544d1d3f7e1SDoug Moore 	if (cur == NULL) {
154585b7bedbSDoug Moore 		*entry = header;
1546d1d3f7e1SDoug Moore 		return (FALSE);
1547d1d3f7e1SDoug Moore 	}
1548d1d3f7e1SDoug Moore 	if (address >= cur->start && cur->end > address) {
1549d1d3f7e1SDoug Moore 		*entry = cur;
1550d1d3f7e1SDoug Moore 		return (TRUE);
15519f701172SKonstantin Belousov 	}
15529f701172SKonstantin Belousov 	if ((locked = vm_map_locked(map)) ||
155305a8c414SAlan Cox 	    sx_try_upgrade(&map->lock)) {
155405a8c414SAlan Cox 		/*
155505a8c414SAlan Cox 		 * Splay requires a write lock on the map.  However, it only
155605a8c414SAlan Cox 		 * restructures the binary search tree; it does not otherwise
155705a8c414SAlan Cox 		 * change the map.  Thus, the map's timestamp need not change
155805a8c414SAlan Cox 		 * on a temporary upgrade.
155905a8c414SAlan Cox 		 */
1560d1d3f7e1SDoug Moore 		cur = vm_map_splay(map, address);
1561461587dcSDoug Moore 		if (!locked) {
1562461587dcSDoug Moore 			VM_MAP_UNLOCK_CONSISTENT(map);
156305a8c414SAlan Cox 			sx_downgrade(&map->lock);
1564461587dcSDoug Moore 		}
1565d1d3f7e1SDoug Moore 
1566d1d3f7e1SDoug Moore 		/*
1567d1d3f7e1SDoug Moore 		 * If "address" is contained within a map entry, the new root
1568d1d3f7e1SDoug Moore 		 * is that map entry.  Otherwise, the new root is a map entry
1569d1d3f7e1SDoug Moore 		 * immediately before or after "address".
1570d1d3f7e1SDoug Moore 		 */
1571d1d3f7e1SDoug Moore 		if (address < cur->start) {
157285b7bedbSDoug Moore 			*entry = header;
1573d1d3f7e1SDoug Moore 			return (FALSE);
1574d1d3f7e1SDoug Moore 		}
1575d1d3f7e1SDoug Moore 		*entry = cur;
1576d1d3f7e1SDoug Moore 		return (address < cur->end);
15779f701172SKonstantin Belousov 	}
157805a8c414SAlan Cox 	/*
157905a8c414SAlan Cox 	 * Since the map is only locked for read access, perform a
1580d1d3f7e1SDoug Moore 	 * standard binary search tree lookup for "address".
158105a8c414SAlan Cox 	 */
1582c1ad5342SDoug Moore 	lbound = ubound = header;
1583c1ad5342SDoug Moore 	for (;;) {
1584d1d3f7e1SDoug Moore 		if (address < cur->start) {
1585c1ad5342SDoug Moore 			ubound = cur;
1586d1d3f7e1SDoug Moore 			cur = cur->left;
1587c1ad5342SDoug Moore 			if (cur == lbound)
1588c1ad5342SDoug Moore 				break;
1589d1d3f7e1SDoug Moore 		} else if (cur->end <= address) {
1590d1d3f7e1SDoug Moore 			lbound = cur;
1591d1d3f7e1SDoug Moore 			cur = cur->right;
1592c1ad5342SDoug Moore 			if (cur == ubound)
1593c1ad5342SDoug Moore 				break;
15949f701172SKonstantin Belousov 		} else {
1595d1d3f7e1SDoug Moore 			*entry = cur;
1596d1d3f7e1SDoug Moore 			return (TRUE);
159705a8c414SAlan Cox 		}
1598c1ad5342SDoug Moore 	}
1599d1d3f7e1SDoug Moore 	*entry = lbound;
1600d1d3f7e1SDoug Moore 	return (FALSE);
1601df8bae1dSRodney W. Grimes }
1602df8bae1dSRodney W. Grimes 
1603df8bae1dSRodney W. Grimes /*
160430dcfc09SJohn Dyson  *	vm_map_insert:
160530dcfc09SJohn Dyson  *
160630dcfc09SJohn Dyson  *	Inserts the given whole VM object into the target
160730dcfc09SJohn Dyson  *	map at the specified address range.  The object's
160830dcfc09SJohn Dyson  *	size should match that of the address range.
160930dcfc09SJohn Dyson  *
161030dcfc09SJohn Dyson  *	Requires that the map be locked, and leaves it so.
16112aaeadf8SMatthew Dillon  *
16122aaeadf8SMatthew Dillon  *	If object is non-NULL, ref count must be bumped by caller
16132aaeadf8SMatthew Dillon  *	prior to making call to account for the new entry.
161430dcfc09SJohn Dyson  */
161530dcfc09SJohn Dyson int
1616b9dcd593SBruce Evans vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
161733314db0SAlan Cox     vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max, int cow)
161830dcfc09SJohn Dyson {
161983704cc2SDoug Moore 	vm_map_entry_t new_entry, next_entry, prev_entry;
1620ef694c1aSEdward Tomasz Napierala 	struct ucred *cred;
16211569205fSKonstantin Belousov 	vm_eflags_t protoeflags;
16228211bd45SKonstantin Belousov 	vm_inherit_t inheritance;
1623e2e80fb3SKonstantin Belousov 	u_long bdry;
1624e2e80fb3SKonstantin Belousov 	u_int bidx;
162530dcfc09SJohn Dyson 
16263a0916b8SKonstantin Belousov 	VM_MAP_ASSERT_LOCKED(map);
16272e47807cSJeff Roberson 	KASSERT(object != kernel_object ||
162833314db0SAlan Cox 	    (cow & MAP_COPY_ON_WRITE) == 0,
16292e47807cSJeff Roberson 	    ("vm_map_insert: kernel object and COW"));
1630e2e80fb3SKonstantin Belousov 	KASSERT(object == NULL || (cow & MAP_NOFAULT) == 0 ||
1631e2e80fb3SKonstantin Belousov 	    (cow & MAP_SPLIT_BOUNDARY_MASK) != 0,
1632e2e80fb3SKonstantin Belousov 	    ("vm_map_insert: paradoxical MAP_NOFAULT request, obj %p cow %#x",
1633e2e80fb3SKonstantin Belousov 	    object, cow));
163400de6773SKonstantin Belousov 	KASSERT((prot & ~max) == 0,
163500de6773SKonstantin Belousov 	    ("prot %#x is not subset of max_prot %#x", prot, max));
16363a0916b8SKonstantin Belousov 
163730dcfc09SJohn Dyson 	/*
163830dcfc09SJohn Dyson 	 * Check that the start and end points are not bogus.
163930dcfc09SJohn Dyson 	 */
1640f0340740SMark Johnston 	if (start == end || !vm_map_range_valid(map, start, end))
164130dcfc09SJohn Dyson 		return (KERN_INVALID_ADDRESS);
164230dcfc09SJohn Dyson 
16432e1c94aaSKonstantin Belousov 	if ((map->flags & MAP_WXORX) != 0 && (prot & (VM_PROT_WRITE |
16442e1c94aaSKonstantin Belousov 	    VM_PROT_EXECUTE)) == (VM_PROT_WRITE | VM_PROT_EXECUTE))
16452e1c94aaSKonstantin Belousov 		return (KERN_PROTECTION_FAILURE);
16462e1c94aaSKonstantin Belousov 
164730dcfc09SJohn Dyson 	/*
164830dcfc09SJohn Dyson 	 * Find the entry prior to the proposed starting address; if it's part
164930dcfc09SJohn Dyson 	 * of an existing entry, this range is bogus.
165030dcfc09SJohn Dyson 	 */
1651723413beSDoug Moore 	if (vm_map_lookup_entry(map, start, &prev_entry))
165230dcfc09SJohn Dyson 		return (KERN_NO_SPACE);
165330dcfc09SJohn Dyson 
165430dcfc09SJohn Dyson 	/*
165530dcfc09SJohn Dyson 	 * Assert that the next entry doesn't overlap the end point.
165630dcfc09SJohn Dyson 	 */
165783704cc2SDoug Moore 	next_entry = vm_map_entry_succ(prev_entry);
165883704cc2SDoug Moore 	if (next_entry->start < end)
165930dcfc09SJohn Dyson 		return (KERN_NO_SPACE);
166030dcfc09SJohn Dyson 
166119bd0d9cSKonstantin Belousov 	if ((cow & MAP_CREATE_GUARD) != 0 && (object != NULL ||
166219bd0d9cSKonstantin Belousov 	    max != VM_PROT_NONE))
166319bd0d9cSKonstantin Belousov 		return (KERN_INVALID_ARGUMENT);
166419bd0d9cSKonstantin Belousov 
1665afa07f7eSJohn Dyson 	protoeflags = 0;
1666afa07f7eSJohn Dyson 	if (cow & MAP_COPY_ON_WRITE)
1667e5f13bddSAlan Cox 		protoeflags |= MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY;
166833314db0SAlan Cox 	if (cow & MAP_NOFAULT)
1669afa07f7eSJohn Dyson 		protoeflags |= MAP_ENTRY_NOFAULT;
16704f79d873SMatthew Dillon 	if (cow & MAP_DISABLE_SYNCER)
16714f79d873SMatthew Dillon 		protoeflags |= MAP_ENTRY_NOSYNC;
16729730a5daSPaul Saab 	if (cow & MAP_DISABLE_COREDUMP)
16739730a5daSPaul Saab 		protoeflags |= MAP_ENTRY_NOCOREDUMP;
1674712efe66SAlan Cox 	if (cow & MAP_STACK_GROWS_DOWN)
1675712efe66SAlan Cox 		protoeflags |= MAP_ENTRY_GROWS_DOWN;
1676712efe66SAlan Cox 	if (cow & MAP_STACK_GROWS_UP)
1677712efe66SAlan Cox 		protoeflags |= MAP_ENTRY_GROWS_UP;
1678fe7bcbafSKyle Evans 	if (cow & MAP_WRITECOUNT)
1679fe7bcbafSKyle Evans 		protoeflags |= MAP_ENTRY_WRITECNT;
168078022527SKonstantin Belousov 	if (cow & MAP_VN_EXEC)
168178022527SKonstantin Belousov 		protoeflags |= MAP_ENTRY_VN_EXEC;
168219bd0d9cSKonstantin Belousov 	if ((cow & MAP_CREATE_GUARD) != 0)
168319bd0d9cSKonstantin Belousov 		protoeflags |= MAP_ENTRY_GUARD;
168419bd0d9cSKonstantin Belousov 	if ((cow & MAP_CREATE_STACK_GAP_DN) != 0)
168519bd0d9cSKonstantin Belousov 		protoeflags |= MAP_ENTRY_STACK_GAP_DN;
168619bd0d9cSKonstantin Belousov 	if ((cow & MAP_CREATE_STACK_GAP_UP) != 0)
168719bd0d9cSKonstantin Belousov 		protoeflags |= MAP_ENTRY_STACK_GAP_UP;
16888211bd45SKonstantin Belousov 	if (cow & MAP_INHERIT_SHARE)
16898211bd45SKonstantin Belousov 		inheritance = VM_INHERIT_SHARE;
16908211bd45SKonstantin Belousov 	else
16918211bd45SKonstantin Belousov 		inheritance = VM_INHERIT_DEFAULT;
1692e2e80fb3SKonstantin Belousov 	if ((cow & MAP_SPLIT_BOUNDARY_MASK) != 0) {
1693e2e80fb3SKonstantin Belousov 		/* This magically ignores index 0, for usual page size. */
1694e2e80fb3SKonstantin Belousov 		bidx = (cow & MAP_SPLIT_BOUNDARY_MASK) >>
1695e2e80fb3SKonstantin Belousov 		    MAP_SPLIT_BOUNDARY_SHIFT;
1696e2e80fb3SKonstantin Belousov 		if (bidx >= MAXPAGESIZES)
1697e2e80fb3SKonstantin Belousov 			return (KERN_INVALID_ARGUMENT);
1698e2e80fb3SKonstantin Belousov 		bdry = pagesizes[bidx] - 1;
1699e2e80fb3SKonstantin Belousov 		if ((start & bdry) != 0 || (end & bdry) != 0)
1700e2e80fb3SKonstantin Belousov 			return (KERN_INVALID_ARGUMENT);
1701e2e80fb3SKonstantin Belousov 		protoeflags |= bidx << MAP_ENTRY_SPLIT_BOUNDARY_SHIFT;
1702e2e80fb3SKonstantin Belousov 	}
17034f79d873SMatthew Dillon 
1704ef694c1aSEdward Tomasz Napierala 	cred = NULL;
170519bd0d9cSKonstantin Belousov 	if ((cow & (MAP_ACC_NO_CHARGE | MAP_NOFAULT | MAP_CREATE_GUARD)) != 0)
17063364c323SKonstantin Belousov 		goto charged;
17073364c323SKonstantin Belousov 	if ((cow & MAP_ACC_CHARGED) || ((prot & VM_PROT_WRITE) &&
17083364c323SKonstantin Belousov 	    ((protoeflags & MAP_ENTRY_NEEDS_COPY) || object == NULL))) {
17093364c323SKonstantin Belousov 		if (!(cow & MAP_ACC_CHARGED) && !swap_reserve(end - start))
17103364c323SKonstantin Belousov 			return (KERN_RESOURCE_SHORTAGE);
17111569205fSKonstantin Belousov 		KASSERT(object == NULL ||
17121569205fSKonstantin Belousov 		    (protoeflags & MAP_ENTRY_NEEDS_COPY) != 0 ||
1713ef694c1aSEdward Tomasz Napierala 		    object->cred == NULL,
17141569205fSKonstantin Belousov 		    ("overcommit: vm_map_insert o %p", object));
1715ef694c1aSEdward Tomasz Napierala 		cred = curthread->td_ucred;
17163364c323SKonstantin Belousov 	}
17173364c323SKonstantin Belousov 
17183364c323SKonstantin Belousov charged:
1719f8616ebfSAlan Cox 	/* Expand the kernel pmap, if necessary. */
1720f8616ebfSAlan Cox 	if (map == kernel_map && end > kernel_vm_end)
1721f8616ebfSAlan Cox 		pmap_growkernel(end);
17221d284e00SAlan Cox 	if (object != NULL) {
172330dcfc09SJohn Dyson 		/*
17241d284e00SAlan Cox 		 * OBJ_ONEMAPPING must be cleared unless this mapping
17251d284e00SAlan Cox 		 * is trivially proven to be the only mapping for any
17261d284e00SAlan Cox 		 * of the object's pages.  (Object granularity
17271d284e00SAlan Cox 		 * reference counting is insufficient to recognize
17281d284e00SAlan Cox 		 * aliases with precision.)
172930dcfc09SJohn Dyson 		 */
173063967687SJeff Roberson 		if ((object->flags & OBJ_ANON) != 0) {
173189f6b863SAttilio Rao 			VM_OBJECT_WLOCK(object);
17321d284e00SAlan Cox 			if (object->ref_count > 1 || object->shadow_count != 0)
17332aaeadf8SMatthew Dillon 				vm_object_clear_flag(object, OBJ_ONEMAPPING);
173489f6b863SAttilio Rao 			VM_OBJECT_WUNLOCK(object);
173563967687SJeff Roberson 		}
17362203c46dSMark Johnston 	} else if ((prev_entry->eflags & ~MAP_ENTRY_USER_WIRED) ==
17372203c46dSMark Johnston 	    protoeflags &&
173878022527SKonstantin Belousov 	    (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP |
173978022527SKonstantin Belousov 	    MAP_VN_EXEC)) == 0 &&
1740737e25f7SAlan Cox 	    prev_entry->end == start && (prev_entry->cred == cred ||
17413364c323SKonstantin Belousov 	    (prev_entry->object.vm_object != NULL &&
17421569205fSKonstantin Belousov 	    prev_entry->object.vm_object->cred == cred)) &&
17438cc7e047SJohn Dyson 	    vm_object_coalesce(prev_entry->object.vm_object,
174457a21abaSAlan Cox 	    prev_entry->offset,
17458cc7e047SJohn Dyson 	    (vm_size_t)(prev_entry->end - prev_entry->start),
174660169c88SAlan Cox 	    (vm_size_t)(end - prev_entry->end), cred != NULL &&
174760169c88SAlan Cox 	    (protoeflags & MAP_ENTRY_NEEDS_COPY) == 0)) {
174830dcfc09SJohn Dyson 		/*
17492aaeadf8SMatthew Dillon 		 * We were able to extend the object.  Determine if we
17502aaeadf8SMatthew Dillon 		 * can extend the previous map entry to include the
17512aaeadf8SMatthew Dillon 		 * new range as well.
175230dcfc09SJohn Dyson 		 */
17531569205fSKonstantin Belousov 		if (prev_entry->inheritance == inheritance &&
17541569205fSKonstantin Belousov 		    prev_entry->protection == prot &&
1755737e25f7SAlan Cox 		    prev_entry->max_protection == max &&
1756737e25f7SAlan Cox 		    prev_entry->wired_count == 0) {
1757737e25f7SAlan Cox 			KASSERT((prev_entry->eflags & MAP_ENTRY_USER_WIRED) ==
1758737e25f7SAlan Cox 			    0, ("prev_entry %p has incoherent wiring",
1759737e25f7SAlan Cox 			    prev_entry));
176019bd0d9cSKonstantin Belousov 			if ((prev_entry->eflags & MAP_ENTRY_GUARD) == 0)
17611569205fSKonstantin Belousov 				map->size += end - prev_entry->end;
1762fa581662SDoug Moore 			vm_map_entry_resize(map, prev_entry,
17631895f520SDoug Moore 			    end - prev_entry->end);
176483704cc2SDoug Moore 			vm_map_try_merge_entries(map, prev_entry, next_entry);
176530dcfc09SJohn Dyson 			return (KERN_SUCCESS);
176630dcfc09SJohn Dyson 		}
17678cc7e047SJohn Dyson 
17682aaeadf8SMatthew Dillon 		/*
17692aaeadf8SMatthew Dillon 		 * If we can extend the object but cannot extend the
17702aaeadf8SMatthew Dillon 		 * map entry, we have to create a new map entry.  We
17712aaeadf8SMatthew Dillon 		 * must bump the ref count on the extended object to
17724e71e795SMatthew Dillon 		 * account for it.  object may be NULL.
17732aaeadf8SMatthew Dillon 		 */
17742aaeadf8SMatthew Dillon 		object = prev_entry->object.vm_object;
17752aaeadf8SMatthew Dillon 		offset = prev_entry->offset +
17762aaeadf8SMatthew Dillon 		    (prev_entry->end - prev_entry->start);
17778cc7e047SJohn Dyson 		vm_object_reference(object);
1778ef694c1aSEdward Tomasz Napierala 		if (cred != NULL && object != NULL && object->cred != NULL &&
17793364c323SKonstantin Belousov 		    !(prev_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
17803364c323SKonstantin Belousov 			/* Object already accounts for this uid. */
1781ef694c1aSEdward Tomasz Napierala 			cred = NULL;
17823364c323SKonstantin Belousov 		}
1783b18bfc3dSJohn Dyson 	}
178460169c88SAlan Cox 	if (cred != NULL)
178560169c88SAlan Cox 		crhold(cred);
17862aaeadf8SMatthew Dillon 
17872aaeadf8SMatthew Dillon 	/*
178830dcfc09SJohn Dyson 	 * Create a new entry
178930dcfc09SJohn Dyson 	 */
179030dcfc09SJohn Dyson 	new_entry = vm_map_entry_create(map);
179130dcfc09SJohn Dyson 	new_entry->start = start;
179230dcfc09SJohn Dyson 	new_entry->end = end;
1793ef694c1aSEdward Tomasz Napierala 	new_entry->cred = NULL;
179430dcfc09SJohn Dyson 
1795afa07f7eSJohn Dyson 	new_entry->eflags = protoeflags;
179630dcfc09SJohn Dyson 	new_entry->object.vm_object = object;
179730dcfc09SJohn Dyson 	new_entry->offset = offset;
17982267af78SJulian Elischer 
17998211bd45SKonstantin Belousov 	new_entry->inheritance = inheritance;
180030dcfc09SJohn Dyson 	new_entry->protection = prot;
180130dcfc09SJohn Dyson 	new_entry->max_protection = max;
180230dcfc09SJohn Dyson 	new_entry->wired_count = 0;
1803997ac690SKonstantin Belousov 	new_entry->wiring_thread = NULL;
180413458803SAlan Cox 	new_entry->read_ahead = VM_FAULT_READ_AHEAD_INIT;
1805381b7242SAlan Cox 	new_entry->next_read = start;
1806e5f251d2SAlan Cox 
1807ef694c1aSEdward Tomasz Napierala 	KASSERT(cred == NULL || !ENTRY_CHARGED(new_entry),
18081569205fSKonstantin Belousov 	    ("overcommit: vm_map_insert leaks vm_map %p", new_entry));
1809ef694c1aSEdward Tomasz Napierala 	new_entry->cred = cred;
18103364c323SKonstantin Belousov 
181130dcfc09SJohn Dyson 	/*
181230dcfc09SJohn Dyson 	 * Insert the new entry into the list
181330dcfc09SJohn Dyson 	 */
18149f701172SKonstantin Belousov 	vm_map_entry_link(map, new_entry);
181519bd0d9cSKonstantin Belousov 	if ((new_entry->eflags & MAP_ENTRY_GUARD) == 0)
181630dcfc09SJohn Dyson 		map->size += new_entry->end - new_entry->start;
181730dcfc09SJohn Dyson 
18181a484d28SMatthew Dillon 	/*
1819eaaf9f7fSAlan Cox 	 * Try to coalesce the new entry with both the previous and next
1820eaaf9f7fSAlan Cox 	 * entries in the list.  Previously, we only attempted to coalesce
1821eaaf9f7fSAlan Cox 	 * with the previous entry when object is NULL.  Here, we handle the
1822eaaf9f7fSAlan Cox 	 * other cases, which are less common.
18231a484d28SMatthew Dillon 	 */
182483ea714fSDoug Moore 	vm_map_try_merge_entries(map, prev_entry, new_entry);
182583704cc2SDoug Moore 	vm_map_try_merge_entries(map, new_entry, next_entry);
18264e71e795SMatthew Dillon 
18271569205fSKonstantin Belousov 	if ((cow & (MAP_PREFAULT | MAP_PREFAULT_PARTIAL)) != 0) {
18281569205fSKonstantin Belousov 		vm_map_pmap_enter(map, start, prot, object, OFF_TO_IDX(offset),
18291569205fSKonstantin Belousov 		    end - start, cow & MAP_PREFAULT_PARTIAL);
18304f79d873SMatthew Dillon 	}
1831e972780aSAlan Cox 
183230dcfc09SJohn Dyson 	return (KERN_SUCCESS);
183330dcfc09SJohn Dyson }
183430dcfc09SJohn Dyson 
183530dcfc09SJohn Dyson /*
18360164e057SAlan Cox  *	vm_map_findspace:
18370164e057SAlan Cox  *
18380164e057SAlan Cox  *	Find the first fit (lowest VM address) for "length" free bytes
18390164e057SAlan Cox  *	beginning at address >= start in the given map.
18400164e057SAlan Cox  *
18419f701172SKonstantin Belousov  *	In a vm_map_entry, "max_free" is the maximum amount of
18429f701172SKonstantin Belousov  *	contiguous free space between an entry in its subtree and a
18439f701172SKonstantin Belousov  *	neighbor of that entry.  This allows finding a free region in
18449f701172SKonstantin Belousov  *	one path down the tree, so O(log n) amortized with splay
18459f701172SKonstantin Belousov  *	trees.
18460164e057SAlan Cox  *
18470164e057SAlan Cox  *	The map must be locked, and leaves it so.
18480164e057SAlan Cox  *
18499f701172SKonstantin Belousov  *	Returns: starting address if sufficient space,
18509f701172SKonstantin Belousov  *		 vm_map_max(map)-length+1 if insufficient space.
1851df8bae1dSRodney W. Grimes  */
18529f701172SKonstantin Belousov vm_offset_t
18539f701172SKonstantin Belousov vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length)
1854df8bae1dSRodney W. Grimes {
185585b7bedbSDoug Moore 	vm_map_entry_t header, llist, rlist, root, y;
185685b7bedbSDoug Moore 	vm_size_t left_length, max_free_left, max_free_right;
1857e65d58a0SDoug Moore 	vm_offset_t gap_end;
1858df8bae1dSRodney W. Grimes 
185920f02659SMark Johnston 	VM_MAP_ASSERT_LOCKED(map);
186020f02659SMark Johnston 
1861986b43f8SAlan Cox 	/*
1862986b43f8SAlan Cox 	 * Request must fit within min/max VM address and must avoid
1863986b43f8SAlan Cox 	 * address wrap.
1864986b43f8SAlan Cox 	 */
1865f0165b1cSKonstantin Belousov 	start = MAX(start, vm_map_min(map));
1866e65d58a0SDoug Moore 	if (start >= vm_map_max(map) || length > vm_map_max(map) - start)
18679f701172SKonstantin Belousov 		return (vm_map_max(map) - length + 1);
1868df8bae1dSRodney W. Grimes 
18690164e057SAlan Cox 	/* Empty tree means wide open address space. */
18709f701172SKonstantin Belousov 	if (map->root == NULL)
18719f701172SKonstantin Belousov 		return (start);
18720164e057SAlan Cox 
18730164e057SAlan Cox 	/*
1874e65d58a0SDoug Moore 	 * After splay_split, if start is within an entry, push it to the start
1875e65d58a0SDoug Moore 	 * of the following gap.  If rlist is at the end of the gap containing
1876e65d58a0SDoug Moore 	 * start, save the end of that gap in gap_end to see if the gap is big
1877e65d58a0SDoug Moore 	 * enough; otherwise set gap_end to start skip gap-checking and move
1878e65d58a0SDoug Moore 	 * directly to a search of the right subtree.
18790164e057SAlan Cox 	 */
188085b7bedbSDoug Moore 	header = &map->header;
18815a0879daSDoug Moore 	root = vm_map_splay_split(map, start, length, &llist, &rlist);
1882e65d58a0SDoug Moore 	gap_end = rlist->start;
1883e65d58a0SDoug Moore 	if (root != NULL) {
18849f701172SKonstantin Belousov 		start = root->end;
1885c1ad5342SDoug Moore 		if (root->right != rlist)
1886e65d58a0SDoug Moore 			gap_end = start;
188785b7bedbSDoug Moore 		max_free_left = vm_map_splay_merge_left(header, root, llist);
188885b7bedbSDoug Moore 		max_free_right = vm_map_splay_merge_right(header, root, rlist);
188985b7bedbSDoug Moore 	} else if (rlist != header) {
18909f701172SKonstantin Belousov 		root = rlist;
18919f701172SKonstantin Belousov 		rlist = root->left;
189285b7bedbSDoug Moore 		max_free_left = vm_map_splay_merge_pred(header, root, llist);
189385b7bedbSDoug Moore 		max_free_right = vm_map_splay_merge_right(header, root, rlist);
18949f701172SKonstantin Belousov 	} else {
18959f701172SKonstantin Belousov 		root = llist;
18969f701172SKonstantin Belousov 		llist = root->right;
189785b7bedbSDoug Moore 		max_free_left = vm_map_splay_merge_left(header, root, llist);
189885b7bedbSDoug Moore 		max_free_right = vm_map_splay_merge_succ(header, root, rlist);
18990164e057SAlan Cox 	}
190085b7bedbSDoug Moore 	root->max_free = vm_size_max(max_free_left, max_free_right);
190185b7bedbSDoug Moore 	map->root = root;
19029f701172SKonstantin Belousov 	VM_MAP_ASSERT_CONSISTENT(map);
1903e65d58a0SDoug Moore 	if (length <= gap_end - start)
19049f701172SKonstantin Belousov 		return (start);
19050164e057SAlan Cox 
19060164e057SAlan Cox 	/* With max_free, can immediately tell if no solution. */
1907c1ad5342SDoug Moore 	if (root->right == header || length > root->right->max_free)
19089f701172SKonstantin Belousov 		return (vm_map_max(map) - length + 1);
19090164e057SAlan Cox 
19100164e057SAlan Cox 	/*
19119f701172SKonstantin Belousov 	 * Splay for the least large-enough gap in the right subtree.
19120164e057SAlan Cox 	 */
191385b7bedbSDoug Moore 	llist = rlist = header;
19149f701172SKonstantin Belousov 	for (left_length = 0;;
19155a0879daSDoug Moore 	    left_length = vm_map_entry_max_free_left(root, llist)) {
19169f701172SKonstantin Belousov 		if (length <= left_length)
1917c1ad5342SDoug Moore 			SPLAY_LEFT_STEP(root, y, llist, rlist,
19185a0879daSDoug Moore 			    length <= vm_map_entry_max_free_left(y, llist));
19199f701172SKonstantin Belousov 		else
1920c1ad5342SDoug Moore 			SPLAY_RIGHT_STEP(root, y, llist, rlist,
19215a0879daSDoug Moore 			    length > vm_map_entry_max_free_left(y, root));
19229f701172SKonstantin Belousov 		if (root == NULL)
19239f701172SKonstantin Belousov 			break;
19240164e057SAlan Cox 	}
19259f701172SKonstantin Belousov 	root = llist;
19269f701172SKonstantin Belousov 	llist = root->right;
192785b7bedbSDoug Moore 	max_free_left = vm_map_splay_merge_left(header, root, llist);
192885b7bedbSDoug Moore 	if (rlist == header) {
192985b7bedbSDoug Moore 		root->max_free = vm_size_max(max_free_left,
193085b7bedbSDoug Moore 		    vm_map_splay_merge_succ(header, root, rlist));
193185b7bedbSDoug Moore 	} else {
19325a0879daSDoug Moore 		y = rlist;
19339f701172SKonstantin Belousov 		rlist = y->left;
193485b7bedbSDoug Moore 		y->max_free = vm_size_max(
193585b7bedbSDoug Moore 		    vm_map_splay_merge_pred(root, y, root),
193685b7bedbSDoug Moore 		    vm_map_splay_merge_right(header, y, rlist));
193785b7bedbSDoug Moore 		root->max_free = vm_size_max(max_free_left, y->max_free);
19389f701172SKonstantin Belousov 	}
193985b7bedbSDoug Moore 	map->root = root;
19409f701172SKonstantin Belousov 	VM_MAP_ASSERT_CONSISTENT(map);
19419f701172SKonstantin Belousov 	return (root->end);
1942df8bae1dSRodney W. Grimes }
1943df8bae1dSRodney W. Grimes 
1944d239bd3cSKonstantin Belousov int
1945d239bd3cSKonstantin Belousov vm_map_fixed(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1946b8ca4ef2SAlan Cox     vm_offset_t start, vm_size_t length, vm_prot_t prot,
1947d239bd3cSKonstantin Belousov     vm_prot_t max, int cow)
1948d239bd3cSKonstantin Belousov {
1949b8ca4ef2SAlan Cox 	vm_offset_t end;
1950d239bd3cSKonstantin Belousov 	int result;
1951d239bd3cSKonstantin Belousov 
1952d239bd3cSKonstantin Belousov 	end = start + length;
19534648ba0aSKonstantin Belousov 	KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
19544648ba0aSKonstantin Belousov 	    object == NULL,
19554648ba0aSKonstantin Belousov 	    ("vm_map_fixed: non-NULL backing object for stack"));
1956897d81a0SKonstantin Belousov 	vm_map_lock(map);
1957d239bd3cSKonstantin Belousov 	VM_MAP_RANGE_CHECK(map, start, end);
1958e8f77c20SKonstantin Belousov 	if ((cow & MAP_CHECK_EXCL) == 0) {
1959e8f77c20SKonstantin Belousov 		result = vm_map_delete(map, start, end);
1960e8f77c20SKonstantin Belousov 		if (result != KERN_SUCCESS)
1961e8f77c20SKonstantin Belousov 			goto out;
1962e8f77c20SKonstantin Belousov 	}
19634648ba0aSKonstantin Belousov 	if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
19644648ba0aSKonstantin Belousov 		result = vm_map_stack_locked(map, start, length, sgrowsiz,
19654648ba0aSKonstantin Belousov 		    prot, max, cow);
19664648ba0aSKonstantin Belousov 	} else {
19674648ba0aSKonstantin Belousov 		result = vm_map_insert(map, object, offset, start, end,
19684648ba0aSKonstantin Belousov 		    prot, max, cow);
19694648ba0aSKonstantin Belousov 	}
1970e8f77c20SKonstantin Belousov out:
1971d239bd3cSKonstantin Belousov 	vm_map_unlock(map);
1972d239bd3cSKonstantin Belousov 	return (result);
1973d239bd3cSKonstantin Belousov }
1974d239bd3cSKonstantin Belousov 
1975fa50a355SKonstantin Belousov static const int aslr_pages_rnd_64[2] = {0x1000, 0x10};
1976fa50a355SKonstantin Belousov static const int aslr_pages_rnd_32[2] = {0x100, 0x4};
1977fa50a355SKonstantin Belousov 
1978fa50a355SKonstantin Belousov static int cluster_anon = 1;
1979fa50a355SKonstantin Belousov SYSCTL_INT(_vm, OID_AUTO, cluster_anon, CTLFLAG_RW,
1980fa50a355SKonstantin Belousov     &cluster_anon, 0,
1981484e9d03SKonstantin Belousov     "Cluster anonymous mappings: 0 = no, 1 = yes if no hint, 2 = always");
1982484e9d03SKonstantin Belousov 
1983484e9d03SKonstantin Belousov static bool
1984484e9d03SKonstantin Belousov clustering_anon_allowed(vm_offset_t addr)
1985484e9d03SKonstantin Belousov {
1986484e9d03SKonstantin Belousov 
1987484e9d03SKonstantin Belousov 	switch (cluster_anon) {
1988484e9d03SKonstantin Belousov 	case 0:
1989484e9d03SKonstantin Belousov 		return (false);
1990484e9d03SKonstantin Belousov 	case 1:
1991484e9d03SKonstantin Belousov 		return (addr == 0);
1992484e9d03SKonstantin Belousov 	case 2:
1993484e9d03SKonstantin Belousov 	default:
1994484e9d03SKonstantin Belousov 		return (true);
1995484e9d03SKonstantin Belousov 	}
1996484e9d03SKonstantin Belousov }
1997fa50a355SKonstantin Belousov 
1998fa50a355SKonstantin Belousov static long aslr_restarts;
1999fa50a355SKonstantin Belousov SYSCTL_LONG(_vm, OID_AUTO, aslr_restarts, CTLFLAG_RD,
2000fa50a355SKonstantin Belousov     &aslr_restarts, 0,
2001fa50a355SKonstantin Belousov     "Number of aslr failures");
2002fa50a355SKonstantin Belousov 
2003df8bae1dSRodney W. Grimes /*
2004fec29688SAlan Cox  * Searches for the specified amount of free space in the given map with the
2005fec29688SAlan Cox  * specified alignment.  Performs an address-ordered, first-fit search from
2006fec29688SAlan Cox  * the given address "*addr", with an optional upper bound "max_addr".  If the
2007fec29688SAlan Cox  * parameter "alignment" is zero, then the alignment is computed from the
2008fec29688SAlan Cox  * given (object, offset) pair so as to enable the greatest possible use of
2009fec29688SAlan Cox  * superpage mappings.  Returns KERN_SUCCESS and the address of the free space
2010fec29688SAlan Cox  * in "*addr" if successful.  Otherwise, returns KERN_NO_SPACE.
2011fec29688SAlan Cox  *
2012fec29688SAlan Cox  * The map must be locked.  Initially, there must be at least "length" bytes
2013fec29688SAlan Cox  * of free space at the given address.
2014fec29688SAlan Cox  */
2015fec29688SAlan Cox static int
2016fec29688SAlan Cox vm_map_alignspace(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
2017fec29688SAlan Cox     vm_offset_t *addr, vm_size_t length, vm_offset_t max_addr,
2018fec29688SAlan Cox     vm_offset_t alignment)
2019fec29688SAlan Cox {
2020fec29688SAlan Cox 	vm_offset_t aligned_addr, free_addr;
2021fec29688SAlan Cox 
2022fec29688SAlan Cox 	VM_MAP_ASSERT_LOCKED(map);
2023fec29688SAlan Cox 	free_addr = *addr;
20249f701172SKonstantin Belousov 	KASSERT(free_addr == vm_map_findspace(map, free_addr, length),
2025e65d58a0SDoug Moore 	    ("caller failed to provide space %#jx at address %p",
2026e65d58a0SDoug Moore 	     (uintmax_t)length, (void *)free_addr));
2027fec29688SAlan Cox 	for (;;) {
2028fec29688SAlan Cox 		/*
2029fec29688SAlan Cox 		 * At the start of every iteration, the free space at address
2030fec29688SAlan Cox 		 * "*addr" is at least "length" bytes.
2031fec29688SAlan Cox 		 */
2032fec29688SAlan Cox 		if (alignment == 0)
2033fec29688SAlan Cox 			pmap_align_superpage(object, offset, addr, length);
2034c606ab59SDoug Moore 		else
2035c606ab59SDoug Moore 			*addr = roundup2(*addr, alignment);
2036fec29688SAlan Cox 		aligned_addr = *addr;
2037fec29688SAlan Cox 		if (aligned_addr == free_addr) {
2038fec29688SAlan Cox 			/*
2039fec29688SAlan Cox 			 * Alignment did not change "*addr", so "*addr" must
2040fec29688SAlan Cox 			 * still provide sufficient free space.
2041fec29688SAlan Cox 			 */
2042fec29688SAlan Cox 			return (KERN_SUCCESS);
2043fec29688SAlan Cox 		}
2044fec29688SAlan Cox 
2045fec29688SAlan Cox 		/*
2046fec29688SAlan Cox 		 * Test for address wrap on "*addr".  A wrapped "*addr" could
2047fec29688SAlan Cox 		 * be a valid address, in which case vm_map_findspace() cannot
2048fec29688SAlan Cox 		 * be relied upon to fail.
2049fec29688SAlan Cox 		 */
20509f701172SKonstantin Belousov 		if (aligned_addr < free_addr)
20519f701172SKonstantin Belousov 			return (KERN_NO_SPACE);
20529f701172SKonstantin Belousov 		*addr = vm_map_findspace(map, aligned_addr, length);
20539f701172SKonstantin Belousov 		if (*addr + length > vm_map_max(map) ||
2054fec29688SAlan Cox 		    (max_addr != 0 && *addr + length > max_addr))
2055fec29688SAlan Cox 			return (KERN_NO_SPACE);
2056fec29688SAlan Cox 		free_addr = *addr;
2057fec29688SAlan Cox 		if (free_addr == aligned_addr) {
2058fec29688SAlan Cox 			/*
2059fec29688SAlan Cox 			 * If a successful call to vm_map_findspace() did not
2060fec29688SAlan Cox 			 * change "*addr", then "*addr" must still be aligned
2061fec29688SAlan Cox 			 * and provide sufficient free space.
2062fec29688SAlan Cox 			 */
2063fec29688SAlan Cox 			return (KERN_SUCCESS);
2064fec29688SAlan Cox 		}
2065fec29688SAlan Cox 	}
2066fec29688SAlan Cox }
2067fec29688SAlan Cox 
20687a9f2da3SKonstantin Belousov int
20697a9f2da3SKonstantin Belousov vm_map_find_aligned(vm_map_t map, vm_offset_t *addr, vm_size_t length,
20707a9f2da3SKonstantin Belousov     vm_offset_t max_addr, vm_offset_t alignment)
20717a9f2da3SKonstantin Belousov {
20727a9f2da3SKonstantin Belousov 	/* XXXKIB ASLR eh ? */
20737a9f2da3SKonstantin Belousov 	*addr = vm_map_findspace(map, *addr, length);
20747a9f2da3SKonstantin Belousov 	if (*addr + length > vm_map_max(map) ||
20757a9f2da3SKonstantin Belousov 	    (max_addr != 0 && *addr + length > max_addr))
20767a9f2da3SKonstantin Belousov 		return (KERN_NO_SPACE);
20777a9f2da3SKonstantin Belousov 	return (vm_map_alignspace(map, NULL, 0, addr, length, max_addr,
20787a9f2da3SKonstantin Belousov 	    alignment));
20797a9f2da3SKonstantin Belousov }
20807a9f2da3SKonstantin Belousov 
2081fec29688SAlan Cox /*
2082df8bae1dSRodney W. Grimes  *	vm_map_find finds an unallocated region in the target address
2083df8bae1dSRodney W. Grimes  *	map with the given length.  The search is defined to be
2084df8bae1dSRodney W. Grimes  *	first-fit from the specified address; the region found is
2085df8bae1dSRodney W. Grimes  *	returned in the same parameter.
2086df8bae1dSRodney W. Grimes  *
20872aaeadf8SMatthew Dillon  *	If object is non-NULL, ref count must be bumped by caller
20882aaeadf8SMatthew Dillon  *	prior to making call to account for the new entry.
2089df8bae1dSRodney W. Grimes  */
2090df8bae1dSRodney W. Grimes int
2091b9dcd593SBruce Evans vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
2092b9dcd593SBruce Evans 	    vm_offset_t *addr,	/* IN/OUT */
2093edb572a3SJohn Baldwin 	    vm_size_t length, vm_offset_t max_addr, int find_space,
2094edb572a3SJohn Baldwin 	    vm_prot_t prot, vm_prot_t max, int cow)
2095df8bae1dSRodney W. Grimes {
2096fa50a355SKonstantin Belousov 	vm_offset_t alignment, curr_min_addr, min_addr;
2097fa50a355SKonstantin Belousov 	int gap, pidx, rv, try;
2098fa50a355SKonstantin Belousov 	bool cluster, en_aslr, update_anon;
2099df8bae1dSRodney W. Grimes 
21004648ba0aSKonstantin Belousov 	KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
21014648ba0aSKonstantin Belousov 	    object == NULL,
21024648ba0aSKonstantin Belousov 	    ("vm_map_find: non-NULL backing object for stack"));
2103ea7e7006SKonstantin Belousov 	MPASS((cow & MAP_REMAP) == 0 || (find_space == VMFS_NO_SPACE &&
2104ea7e7006SKonstantin Belousov 	    (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0));
2105ff74a3faSJohn Baldwin 	if (find_space == VMFS_OPTIMAL_SPACE && (object == NULL ||
2106ff74a3faSJohn Baldwin 	    (object->flags & OBJ_COLORED) == 0))
2107ff74a3faSJohn Baldwin 		find_space = VMFS_ANY_SPACE;
21085aa60b6fSJohn Baldwin 	if (find_space >> 8 != 0) {
21095aa60b6fSJohn Baldwin 		KASSERT((find_space & 0xff) == 0, ("bad VMFS flags"));
21105aa60b6fSJohn Baldwin 		alignment = (vm_offset_t)1 << (find_space >> 8);
21115aa60b6fSJohn Baldwin 	} else
21125aa60b6fSJohn Baldwin 		alignment = 0;
2113fa50a355SKonstantin Belousov 	en_aslr = (map->flags & MAP_ASLR) != 0;
2114484e9d03SKonstantin Belousov 	update_anon = cluster = clustering_anon_allowed(*addr) &&
2115fa50a355SKonstantin Belousov 	    (map->flags & MAP_IS_SUB_MAP) == 0 && max_addr == 0 &&
2116fa50a355SKonstantin Belousov 	    find_space != VMFS_NO_SPACE && object == NULL &&
2117fa50a355SKonstantin Belousov 	    (cow & (MAP_INHERIT_SHARE | MAP_STACK_GROWS_UP |
2118fa50a355SKonstantin Belousov 	    MAP_STACK_GROWS_DOWN)) == 0 && prot != PROT_NONE;
2119fa50a355SKonstantin Belousov 	curr_min_addr = min_addr = *addr;
2120fa50a355SKonstantin Belousov 	if (en_aslr && min_addr == 0 && !cluster &&
2121fa50a355SKonstantin Belousov 	    find_space != VMFS_NO_SPACE &&
2122fa50a355SKonstantin Belousov 	    (map->flags & MAP_ASLR_IGNSTART) != 0)
2123fa50a355SKonstantin Belousov 		curr_min_addr = min_addr = vm_map_min(map);
2124fa50a355SKonstantin Belousov 	try = 0;
21254d572bb3SAlan Cox 	vm_map_lock(map);
2126fa50a355SKonstantin Belousov 	if (cluster) {
2127fa50a355SKonstantin Belousov 		curr_min_addr = map->anon_loc;
2128fa50a355SKonstantin Belousov 		if (curr_min_addr == 0)
2129fa50a355SKonstantin Belousov 			cluster = false;
2130fa50a355SKonstantin Belousov 	}
213126c538ffSAlan Cox 	if (find_space != VMFS_NO_SPACE) {
2132fec29688SAlan Cox 		KASSERT(find_space == VMFS_ANY_SPACE ||
2133fec29688SAlan Cox 		    find_space == VMFS_OPTIMAL_SPACE ||
2134fec29688SAlan Cox 		    find_space == VMFS_SUPER_SPACE ||
2135fec29688SAlan Cox 		    alignment != 0, ("unexpected VMFS flag"));
2136fec29688SAlan Cox again:
2137fa50a355SKonstantin Belousov 		/*
2138fa50a355SKonstantin Belousov 		 * When creating an anonymous mapping, try clustering
2139fa50a355SKonstantin Belousov 		 * with an existing anonymous mapping first.
2140fa50a355SKonstantin Belousov 		 *
2141fa50a355SKonstantin Belousov 		 * We make up to two attempts to find address space
2142fa50a355SKonstantin Belousov 		 * for a given find_space value. The first attempt may
2143fa50a355SKonstantin Belousov 		 * apply randomization or may cluster with an existing
2144fa50a355SKonstantin Belousov 		 * anonymous mapping. If this first attempt fails,
2145fa50a355SKonstantin Belousov 		 * perform a first-fit search of the available address
2146fa50a355SKonstantin Belousov 		 * space.
2147fa50a355SKonstantin Belousov 		 *
2148fa50a355SKonstantin Belousov 		 * If all tries failed, and find_space is
2149fa50a355SKonstantin Belousov 		 * VMFS_OPTIMAL_SPACE, fallback to VMFS_ANY_SPACE.
2150fa50a355SKonstantin Belousov 		 * Again enable clustering and randomization.
2151fa50a355SKonstantin Belousov 		 */
2152fa50a355SKonstantin Belousov 		try++;
2153fa50a355SKonstantin Belousov 		MPASS(try <= 2);
2154fa50a355SKonstantin Belousov 
2155fa50a355SKonstantin Belousov 		if (try == 2) {
2156fa50a355SKonstantin Belousov 			/*
2157fa50a355SKonstantin Belousov 			 * Second try: we failed either to find a
2158fa50a355SKonstantin Belousov 			 * suitable region for randomizing the
2159fa50a355SKonstantin Belousov 			 * allocation, or to cluster with an existing
2160fa50a355SKonstantin Belousov 			 * mapping.  Retry with free run.
2161fa50a355SKonstantin Belousov 			 */
2162fa50a355SKonstantin Belousov 			curr_min_addr = (map->flags & MAP_ASLR_IGNSTART) != 0 ?
2163fa50a355SKonstantin Belousov 			    vm_map_min(map) : min_addr;
2164fa50a355SKonstantin Belousov 			atomic_add_long(&aslr_restarts, 1);
2165fa50a355SKonstantin Belousov 		}
2166fa50a355SKonstantin Belousov 
2167fa50a355SKonstantin Belousov 		if (try == 1 && en_aslr && !cluster) {
2168fa50a355SKonstantin Belousov 			/*
2169fa50a355SKonstantin Belousov 			 * Find space for allocation, including
2170fa50a355SKonstantin Belousov 			 * gap needed for later randomization.
2171fa50a355SKonstantin Belousov 			 */
2172fa50a355SKonstantin Belousov 			pidx = MAXPAGESIZES > 1 && pagesizes[1] != 0 &&
2173fa50a355SKonstantin Belousov 			    (find_space == VMFS_SUPER_SPACE || find_space ==
2174fa50a355SKonstantin Belousov 			    VMFS_OPTIMAL_SPACE) ? 1 : 0;
2175fa50a355SKonstantin Belousov 			gap = vm_map_max(map) > MAP_32BIT_MAX_ADDR &&
2176fa50a355SKonstantin Belousov 			    (max_addr == 0 || max_addr > MAP_32BIT_MAX_ADDR) ?
2177fa50a355SKonstantin Belousov 			    aslr_pages_rnd_64[pidx] : aslr_pages_rnd_32[pidx];
21789f701172SKonstantin Belousov 			*addr = vm_map_findspace(map, curr_min_addr,
21799f701172SKonstantin Belousov 			    length + gap * pagesizes[pidx]);
21809f701172SKonstantin Belousov 			if (*addr + length + gap * pagesizes[pidx] >
2181a5a02ef4SKonstantin Belousov 			    vm_map_max(map))
2182fa50a355SKonstantin Belousov 				goto again;
2183fa50a355SKonstantin Belousov 			/* And randomize the start address. */
2184fa50a355SKonstantin Belousov 			*addr += (arc4random() % gap) * pagesizes[pidx];
21855019dac9SKonstantin Belousov 			if (max_addr != 0 && *addr + length > max_addr)
21865019dac9SKonstantin Belousov 				goto again;
21879f701172SKonstantin Belousov 		} else {
21889f701172SKonstantin Belousov 			*addr = vm_map_findspace(map, curr_min_addr, length);
21899f701172SKonstantin Belousov 			if (*addr + length > vm_map_max(map) ||
2190edb572a3SJohn Baldwin 			    (max_addr != 0 && *addr + length > max_addr)) {
2191fa50a355SKonstantin Belousov 				if (cluster) {
2192fa50a355SKonstantin Belousov 					cluster = false;
2193fa50a355SKonstantin Belousov 					MPASS(try == 1);
2194fa50a355SKonstantin Belousov 					goto again;
2195fa50a355SKonstantin Belousov 				}
2196fec29688SAlan Cox 				rv = KERN_NO_SPACE;
2197fec29688SAlan Cox 				goto done;
2198fec29688SAlan Cox 			}
21999f701172SKonstantin Belousov 		}
2200fa50a355SKonstantin Belousov 
2201fec29688SAlan Cox 		if (find_space != VMFS_ANY_SPACE &&
2202fec29688SAlan Cox 		    (rv = vm_map_alignspace(map, object, offset, addr, length,
2203fec29688SAlan Cox 		    max_addr, alignment)) != KERN_SUCCESS) {
2204ff74a3faSJohn Baldwin 			if (find_space == VMFS_OPTIMAL_SPACE) {
2205ff74a3faSJohn Baldwin 				find_space = VMFS_ANY_SPACE;
2206fa50a355SKonstantin Belousov 				curr_min_addr = min_addr;
2207fa50a355SKonstantin Belousov 				cluster = update_anon;
2208fa50a355SKonstantin Belousov 				try = 0;
2209ff74a3faSJohn Baldwin 				goto again;
2210ff74a3faSJohn Baldwin 			}
2211fec29688SAlan Cox 			goto done;
2212df8bae1dSRodney W. Grimes 		}
2213ea7e7006SKonstantin Belousov 	} else if ((cow & MAP_REMAP) != 0) {
22140f1e6ec5SMark Johnston 		if (!vm_map_range_valid(map, *addr, *addr + length)) {
2215ea7e7006SKonstantin Belousov 			rv = KERN_INVALID_ADDRESS;
2216ea7e7006SKonstantin Belousov 			goto done;
2217ea7e7006SKonstantin Belousov 		}
2218e8f77c20SKonstantin Belousov 		rv = vm_map_delete(map, *addr, *addr + length);
2219e8f77c20SKonstantin Belousov 		if (rv != KERN_SUCCESS)
2220e8f77c20SKonstantin Belousov 			goto done;
2221df8bae1dSRodney W. Grimes 	}
22224648ba0aSKonstantin Belousov 	if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
2223fec29688SAlan Cox 		rv = vm_map_stack_locked(map, *addr, length, sgrowsiz, prot,
2224fec29688SAlan Cox 		    max, cow);
22254648ba0aSKonstantin Belousov 	} else {
2226fec29688SAlan Cox 		rv = vm_map_insert(map, object, offset, *addr, *addr + length,
2227fec29688SAlan Cox 		    prot, max, cow);
22284648ba0aSKonstantin Belousov 	}
2229fa50a355SKonstantin Belousov 	if (rv == KERN_SUCCESS && update_anon)
2230fa50a355SKonstantin Belousov 		map->anon_loc = *addr + length;
2231fec29688SAlan Cox done:
2232df8bae1dSRodney W. Grimes 	vm_map_unlock(map);
2233fec29688SAlan Cox 	return (rv);
2234df8bae1dSRodney W. Grimes }
2235df8bae1dSRodney W. Grimes 
2236e8502826SKonstantin Belousov /*
2237e8502826SKonstantin Belousov  *	vm_map_find_min() is a variant of vm_map_find() that takes an
2238e8502826SKonstantin Belousov  *	additional parameter (min_addr) and treats the given address
2239e8502826SKonstantin Belousov  *	(*addr) differently.  Specifically, it treats *addr as a hint
2240e8502826SKonstantin Belousov  *	and not as the minimum address where the mapping is created.
2241e8502826SKonstantin Belousov  *
2242e8502826SKonstantin Belousov  *	This function works in two phases.  First, it tries to
2243e8502826SKonstantin Belousov  *	allocate above the hint.  If that fails and the hint is
2244e8502826SKonstantin Belousov  *	greater than min_addr, it performs a second pass, replacing
2245e8502826SKonstantin Belousov  *	the hint with min_addr as the minimum address for the
2246e8502826SKonstantin Belousov  *	allocation.
2247e8502826SKonstantin Belousov  */
22486a97a3f7SKonstantin Belousov int
22496a97a3f7SKonstantin Belousov vm_map_find_min(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
22506a97a3f7SKonstantin Belousov     vm_offset_t *addr, vm_size_t length, vm_offset_t min_addr,
22516a97a3f7SKonstantin Belousov     vm_offset_t max_addr, int find_space, vm_prot_t prot, vm_prot_t max,
22526a97a3f7SKonstantin Belousov     int cow)
22536a97a3f7SKonstantin Belousov {
22546a97a3f7SKonstantin Belousov 	vm_offset_t hint;
22556a97a3f7SKonstantin Belousov 	int rv;
22566a97a3f7SKonstantin Belousov 
22576a97a3f7SKonstantin Belousov 	hint = *addr;
22586a97a3f7SKonstantin Belousov 	for (;;) {
22596a97a3f7SKonstantin Belousov 		rv = vm_map_find(map, object, offset, addr, length, max_addr,
22606a97a3f7SKonstantin Belousov 		    find_space, prot, max, cow);
22616a97a3f7SKonstantin Belousov 		if (rv == KERN_SUCCESS || min_addr >= hint)
22626a97a3f7SKonstantin Belousov 			return (rv);
22637683ad70SKonstantin Belousov 		*addr = hint = min_addr;
22646a97a3f7SKonstantin Belousov 	}
22656a97a3f7SKonstantin Belousov }
22666a97a3f7SKonstantin Belousov 
226792e78c10SAlan Cox /*
226892e78c10SAlan Cox  * A map entry with any of the following flags set must not be merged with
226992e78c10SAlan Cox  * another entry.
227092e78c10SAlan Cox  */
227192e78c10SAlan Cox #define	MAP_ENTRY_NOMERGE_MASK	(MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP | \
227278022527SKonstantin Belousov 	    MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP | MAP_ENTRY_VN_EXEC)
227392e78c10SAlan Cox 
227407424462SKonstantin Belousov static bool
227507424462SKonstantin Belousov vm_map_mergeable_neighbors(vm_map_entry_t prev, vm_map_entry_t entry)
227607424462SKonstantin Belousov {
227707424462SKonstantin Belousov 
227892e78c10SAlan Cox 	KASSERT((prev->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 ||
227992e78c10SAlan Cox 	    (entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0,
228092e78c10SAlan Cox 	    ("vm_map_mergeable_neighbors: neither %p nor %p are mergeable",
228192e78c10SAlan Cox 	    prev, entry));
228207424462SKonstantin Belousov 	return (prev->end == entry->start &&
228307424462SKonstantin Belousov 	    prev->object.vm_object == entry->object.vm_object &&
228407424462SKonstantin Belousov 	    (prev->object.vm_object == NULL ||
228592e78c10SAlan Cox 	    prev->offset + (prev->end - prev->start) == entry->offset) &&
228607424462SKonstantin Belousov 	    prev->eflags == entry->eflags &&
228707424462SKonstantin Belousov 	    prev->protection == entry->protection &&
228807424462SKonstantin Belousov 	    prev->max_protection == entry->max_protection &&
228907424462SKonstantin Belousov 	    prev->inheritance == entry->inheritance &&
229007424462SKonstantin Belousov 	    prev->wired_count == entry->wired_count &&
229107424462SKonstantin Belousov 	    prev->cred == entry->cred);
229207424462SKonstantin Belousov }
229307424462SKonstantin Belousov 
229407424462SKonstantin Belousov static void
229507424462SKonstantin Belousov vm_map_merged_neighbor_dispose(vm_map_t map, vm_map_entry_t entry)
229607424462SKonstantin Belousov {
229707424462SKonstantin Belousov 
229807424462SKonstantin Belousov 	/*
229992e78c10SAlan Cox 	 * If the backing object is a vnode object, vm_object_deallocate()
230092e78c10SAlan Cox 	 * calls vrele().  However, vrele() does not lock the vnode because
230192e78c10SAlan Cox 	 * the vnode has additional references.  Thus, the map lock can be
230292e78c10SAlan Cox 	 * kept without causing a lock-order reversal with the vnode lock.
230307424462SKonstantin Belousov 	 *
230492e78c10SAlan Cox 	 * Since we count the number of virtual page mappings in
230592e78c10SAlan Cox 	 * object->un_pager.vnp.writemappings, the writemappings value
230692e78c10SAlan Cox 	 * should not be adjusted when the entry is disposed of.
230707424462SKonstantin Belousov 	 */
230807424462SKonstantin Belousov 	if (entry->object.vm_object != NULL)
230907424462SKonstantin Belousov 		vm_object_deallocate(entry->object.vm_object);
231007424462SKonstantin Belousov 	if (entry->cred != NULL)
231107424462SKonstantin Belousov 		crfree(entry->cred);
231207424462SKonstantin Belousov 	vm_map_entry_dispose(map, entry);
231307424462SKonstantin Belousov }
231407424462SKonstantin Belousov 
2315df8bae1dSRodney W. Grimes /*
231683ea714fSDoug Moore  *	vm_map_try_merge_entries:
231767bf6868SJohn Dyson  *
231883ea714fSDoug Moore  *	Compare the given map entry to its predecessor, and merge its precessor
231983ea714fSDoug Moore  *	into it if possible.  The entry remains valid, and may be extended.
232083ea714fSDoug Moore  *	The predecessor may be deleted.
23214e71e795SMatthew Dillon  *
23224e71e795SMatthew Dillon  *	The map must be locked.
2323df8bae1dSRodney W. Grimes  */
23240afcd3afSAlan Cox void
23252767c9f3SDoug Moore vm_map_try_merge_entries(vm_map_t map, vm_map_entry_t prev_entry,
23262767c9f3SDoug Moore     vm_map_entry_t entry)
2327df8bae1dSRodney W. Grimes {
2328df8bae1dSRodney W. Grimes 
232983ea714fSDoug Moore 	VM_MAP_ASSERT_LOCKED(map);
233083ea714fSDoug Moore 	if ((entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 &&
23312767c9f3SDoug Moore 	    vm_map_mergeable_neighbors(prev_entry, entry)) {
23322767c9f3SDoug Moore 		vm_map_entry_unlink(map, prev_entry, UNLINK_MERGE_NEXT);
23332767c9f3SDoug Moore 		vm_map_merged_neighbor_dispose(map, prev_entry);
2334308c24baSJohn Dyson 	}
2335df8bae1dSRodney W. Grimes }
233692e78c10SAlan Cox 
2337df8bae1dSRodney W. Grimes /*
2338af1d6d6aSDoug Moore  *	vm_map_entry_back:
2339af1d6d6aSDoug Moore  *
2340af1d6d6aSDoug Moore  *	Allocate an object to back a map entry.
2341af1d6d6aSDoug Moore  */
2342af1d6d6aSDoug Moore static inline void
2343af1d6d6aSDoug Moore vm_map_entry_back(vm_map_entry_t entry)
2344af1d6d6aSDoug Moore {
2345af1d6d6aSDoug Moore 	vm_object_t object;
2346af1d6d6aSDoug Moore 
2347af1d6d6aSDoug Moore 	KASSERT(entry->object.vm_object == NULL,
2348af1d6d6aSDoug Moore 	    ("map entry %p has backing object", entry));
2349af1d6d6aSDoug Moore 	KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
2350af1d6d6aSDoug Moore 	    ("map entry %p is a submap", entry));
235167388836SKonstantin Belousov 	object = vm_object_allocate_anon(atop(entry->end - entry->start), NULL,
235267388836SKonstantin Belousov 	    entry->cred, entry->end - entry->start);
2353af1d6d6aSDoug Moore 	entry->object.vm_object = object;
2354af1d6d6aSDoug Moore 	entry->offset = 0;
2355af1d6d6aSDoug Moore 	entry->cred = NULL;
2356af1d6d6aSDoug Moore }
2357af1d6d6aSDoug Moore 
2358af1d6d6aSDoug Moore /*
2359af1d6d6aSDoug Moore  *	vm_map_entry_charge_object
2360af1d6d6aSDoug Moore  *
2361af1d6d6aSDoug Moore  *	If there is no object backing this entry, create one.  Otherwise, if
2362af1d6d6aSDoug Moore  *	the entry has cred, give it to the backing object.
2363af1d6d6aSDoug Moore  */
2364af1d6d6aSDoug Moore static inline void
2365af1d6d6aSDoug Moore vm_map_entry_charge_object(vm_map_t map, vm_map_entry_t entry)
2366af1d6d6aSDoug Moore {
2367af1d6d6aSDoug Moore 
2368af1d6d6aSDoug Moore 	VM_MAP_ASSERT_LOCKED(map);
2369af1d6d6aSDoug Moore 	KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
2370af1d6d6aSDoug Moore 	    ("map entry %p is a submap", entry));
2371af1d6d6aSDoug Moore 	if (entry->object.vm_object == NULL && !map->system_map &&
2372af1d6d6aSDoug Moore 	    (entry->eflags & MAP_ENTRY_GUARD) == 0)
2373af1d6d6aSDoug Moore 		vm_map_entry_back(entry);
2374af1d6d6aSDoug Moore 	else if (entry->object.vm_object != NULL &&
2375af1d6d6aSDoug Moore 	    ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
2376af1d6d6aSDoug Moore 	    entry->cred != NULL) {
2377af1d6d6aSDoug Moore 		VM_OBJECT_WLOCK(entry->object.vm_object);
2378af1d6d6aSDoug Moore 		KASSERT(entry->object.vm_object->cred == NULL,
2379af1d6d6aSDoug Moore 		    ("OVERCOMMIT: %s: both cred e %p", __func__, entry));
2380af1d6d6aSDoug Moore 		entry->object.vm_object->cred = entry->cred;
2381af1d6d6aSDoug Moore 		entry->object.vm_object->charge = entry->end - entry->start;
2382af1d6d6aSDoug Moore 		VM_OBJECT_WUNLOCK(entry->object.vm_object);
2383af1d6d6aSDoug Moore 		entry->cred = NULL;
2384af1d6d6aSDoug Moore 	}
2385af1d6d6aSDoug Moore }
2386af1d6d6aSDoug Moore 
2387af1d6d6aSDoug Moore /*
2388037c0994SDoug Moore  *	vm_map_entry_clone
2389037c0994SDoug Moore  *
2390037c0994SDoug Moore  *	Create a duplicate map entry for clipping.
2391037c0994SDoug Moore  */
2392037c0994SDoug Moore static vm_map_entry_t
2393037c0994SDoug Moore vm_map_entry_clone(vm_map_t map, vm_map_entry_t entry)
2394037c0994SDoug Moore {
2395037c0994SDoug Moore 	vm_map_entry_t new_entry;
2396037c0994SDoug Moore 
2397037c0994SDoug Moore 	VM_MAP_ASSERT_LOCKED(map);
2398037c0994SDoug Moore 
2399037c0994SDoug Moore 	/*
2400037c0994SDoug Moore 	 * Create a backing object now, if none exists, so that more individual
2401037c0994SDoug Moore 	 * objects won't be created after the map entry is split.
2402037c0994SDoug Moore 	 */
2403037c0994SDoug Moore 	vm_map_entry_charge_object(map, entry);
2404037c0994SDoug Moore 
2405037c0994SDoug Moore 	/* Clone the entry. */
2406037c0994SDoug Moore 	new_entry = vm_map_entry_create(map);
2407037c0994SDoug Moore 	*new_entry = *entry;
2408037c0994SDoug Moore 	if (new_entry->cred != NULL)
2409037c0994SDoug Moore 		crhold(entry->cred);
2410037c0994SDoug Moore 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2411037c0994SDoug Moore 		vm_object_reference(new_entry->object.vm_object);
2412037c0994SDoug Moore 		vm_map_entry_set_vnode_text(new_entry, true);
2413037c0994SDoug Moore 		/*
2414037c0994SDoug Moore 		 * The object->un_pager.vnp.writemappings for the object of
2415037c0994SDoug Moore 		 * MAP_ENTRY_WRITECNT type entry shall be kept as is here.  The
2416037c0994SDoug Moore 		 * virtual pages are re-distributed among the clipped entries,
2417037c0994SDoug Moore 		 * so the sum is left the same.
2418037c0994SDoug Moore 		 */
2419037c0994SDoug Moore 	}
2420037c0994SDoug Moore 	return (new_entry);
2421037c0994SDoug Moore }
2422037c0994SDoug Moore 
2423037c0994SDoug Moore /*
2424df8bae1dSRodney W. Grimes  *	vm_map_clip_start:	[ internal use only ]
2425df8bae1dSRodney W. Grimes  *
2426df8bae1dSRodney W. Grimes  *	Asserts that the given entry begins at or after
2427df8bae1dSRodney W. Grimes  *	the specified address; if necessary,
2428df8bae1dSRodney W. Grimes  *	it splits the entry into two.
2429df8bae1dSRodney W. Grimes  */
2430e2e80fb3SKonstantin Belousov static int
2431e2e80fb3SKonstantin Belousov vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t startaddr)
2432df8bae1dSRodney W. Grimes {
2433c0877f10SJohn Dyson 	vm_map_entry_t new_entry;
2434e2e80fb3SKonstantin Belousov 	int bdry_idx;
2435df8bae1dSRodney W. Grimes 
24368a64110eSConrad Meyer 	if (!map->system_map)
24378a64110eSConrad Meyer 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
24388a64110eSConrad Meyer 		    "%s: map %p entry %p start 0x%jx", __func__, map, entry,
2439e2e80fb3SKonstantin Belousov 		    (uintmax_t)startaddr);
24408a64110eSConrad Meyer 
2441e2e80fb3SKonstantin Belousov 	if (startaddr <= entry->start)
2442e2e80fb3SKonstantin Belousov 		return (KERN_SUCCESS);
2443a116b5d3SConrad Meyer 
24443a0916b8SKonstantin Belousov 	VM_MAP_ASSERT_LOCKED(map);
2445e2e80fb3SKonstantin Belousov 	KASSERT(entry->end > startaddr && entry->start < startaddr,
2446a116b5d3SConrad Meyer 	    ("%s: invalid clip of entry %p", __func__, entry));
24473a0916b8SKonstantin Belousov 
2448e2e80fb3SKonstantin Belousov 	bdry_idx = (entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK) >>
2449e2e80fb3SKonstantin Belousov 	    MAP_ENTRY_SPLIT_BOUNDARY_SHIFT;
2450e2e80fb3SKonstantin Belousov 	if (bdry_idx != 0) {
2451e2e80fb3SKonstantin Belousov 		if ((startaddr & (pagesizes[bdry_idx] - 1)) != 0)
2452e2e80fb3SKonstantin Belousov 			return (KERN_INVALID_ARGUMENT);
2453e2e80fb3SKonstantin Belousov 	}
2454e2e80fb3SKonstantin Belousov 
2455037c0994SDoug Moore 	new_entry = vm_map_entry_clone(map, entry);
2456df8bae1dSRodney W. Grimes 
24574766eba1SDoug Moore 	/*
24584766eba1SDoug Moore 	 * Split off the front portion.  Insert the new entry BEFORE this one,
24594766eba1SDoug Moore 	 * so that this entry has the specified starting address.
24604766eba1SDoug Moore 	 */
2461e2e80fb3SKonstantin Belousov 	new_entry->end = startaddr;
24629f701172SKonstantin Belousov 	vm_map_entry_link(map, new_entry);
2463e2e80fb3SKonstantin Belousov 	return (KERN_SUCCESS);
2464c0877f10SJohn Dyson }
2465df8bae1dSRodney W. Grimes 
2466df8bae1dSRodney W. Grimes /*
2467c7b23459SDoug Moore  *	vm_map_lookup_clip_start:
2468c7b23459SDoug Moore  *
2469c7b23459SDoug Moore  *	Find the entry at or just after 'start', and clip it if 'start' is in
2470c7b23459SDoug Moore  *	the interior of the entry.  Return entry after 'start', and in
2471c7b23459SDoug Moore  *	prev_entry set the entry before 'start'.
2472c7b23459SDoug Moore  */
2473e2e80fb3SKonstantin Belousov static int
2474c7b23459SDoug Moore vm_map_lookup_clip_start(vm_map_t map, vm_offset_t start,
2475e2e80fb3SKonstantin Belousov     vm_map_entry_t *res_entry, vm_map_entry_t *prev_entry)
2476c7b23459SDoug Moore {
2477c7b23459SDoug Moore 	vm_map_entry_t entry;
2478e2e80fb3SKonstantin Belousov 	int rv;
2479c7b23459SDoug Moore 
24808a64110eSConrad Meyer 	if (!map->system_map)
24818a64110eSConrad Meyer 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
24828a64110eSConrad Meyer 		    "%s: map %p start 0x%jx prev %p", __func__, map,
24838a64110eSConrad Meyer 		    (uintmax_t)start, prev_entry);
24848a64110eSConrad Meyer 
2485c7b23459SDoug Moore 	if (vm_map_lookup_entry(map, start, prev_entry)) {
2486c7b23459SDoug Moore 		entry = *prev_entry;
2487e2e80fb3SKonstantin Belousov 		rv = vm_map_clip_start(map, entry, start);
2488e2e80fb3SKonstantin Belousov 		if (rv != KERN_SUCCESS)
2489e2e80fb3SKonstantin Belousov 			return (rv);
2490c7b23459SDoug Moore 		*prev_entry = vm_map_entry_pred(entry);
2491c7b23459SDoug Moore 	} else
2492c7b23459SDoug Moore 		entry = vm_map_entry_succ(*prev_entry);
2493e2e80fb3SKonstantin Belousov 	*res_entry = entry;
2494e2e80fb3SKonstantin Belousov 	return (KERN_SUCCESS);
2495c7b23459SDoug Moore }
2496c7b23459SDoug Moore 
2497c7b23459SDoug Moore /*
2498df8bae1dSRodney W. Grimes  *	vm_map_clip_end:	[ internal use only ]
2499df8bae1dSRodney W. Grimes  *
2500df8bae1dSRodney W. Grimes  *	Asserts that the given entry ends at or before
2501df8bae1dSRodney W. Grimes  *	the specified address; if necessary,
2502df8bae1dSRodney W. Grimes  *	it splits the entry into two.
2503df8bae1dSRodney W. Grimes  */
2504e2e80fb3SKonstantin Belousov static int
2505e2e80fb3SKonstantin Belousov vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t endaddr)
2506df8bae1dSRodney W. Grimes {
2507c0877f10SJohn Dyson 	vm_map_entry_t new_entry;
2508e2e80fb3SKonstantin Belousov 	int bdry_idx;
2509df8bae1dSRodney W. Grimes 
25108a64110eSConrad Meyer 	if (!map->system_map)
25118a64110eSConrad Meyer 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
25128a64110eSConrad Meyer 		    "%s: map %p entry %p end 0x%jx", __func__, map, entry,
2513e2e80fb3SKonstantin Belousov 		    (uintmax_t)endaddr);
25148a64110eSConrad Meyer 
2515e2e80fb3SKonstantin Belousov 	if (endaddr >= entry->end)
2516e2e80fb3SKonstantin Belousov 		return (KERN_SUCCESS);
2517a116b5d3SConrad Meyer 
25183a0916b8SKonstantin Belousov 	VM_MAP_ASSERT_LOCKED(map);
2519e2e80fb3SKonstantin Belousov 	KASSERT(entry->start < endaddr && entry->end > endaddr,
2520a116b5d3SConrad Meyer 	    ("%s: invalid clip of entry %p", __func__, entry));
25213a0916b8SKonstantin Belousov 
2522e2e80fb3SKonstantin Belousov 	bdry_idx = (entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK) >>
2523e2e80fb3SKonstantin Belousov 	    MAP_ENTRY_SPLIT_BOUNDARY_SHIFT;
2524e2e80fb3SKonstantin Belousov 	if (bdry_idx != 0) {
2525e2e80fb3SKonstantin Belousov 		if ((endaddr & (pagesizes[bdry_idx] - 1)) != 0)
2526e2e80fb3SKonstantin Belousov 			return (KERN_INVALID_ARGUMENT);
2527e2e80fb3SKonstantin Belousov 	}
2528e2e80fb3SKonstantin Belousov 
2529037c0994SDoug Moore 	new_entry = vm_map_entry_clone(map, entry);
2530df8bae1dSRodney W. Grimes 
25314766eba1SDoug Moore 	/*
25324766eba1SDoug Moore 	 * Split off the back portion.  Insert the new entry AFTER this one,
25334766eba1SDoug Moore 	 * so that this entry has the specified ending address.
25344766eba1SDoug Moore 	 */
2535e2e80fb3SKonstantin Belousov 	new_entry->start = endaddr;
25369f701172SKonstantin Belousov 	vm_map_entry_link(map, new_entry);
2537e2e80fb3SKonstantin Belousov 
2538e2e80fb3SKonstantin Belousov 	return (KERN_SUCCESS);
2539c0877f10SJohn Dyson }
2540df8bae1dSRodney W. Grimes 
2541df8bae1dSRodney W. Grimes /*
2542df8bae1dSRodney W. Grimes  *	vm_map_submap:		[ kernel use only ]
2543df8bae1dSRodney W. Grimes  *
2544df8bae1dSRodney W. Grimes  *	Mark the given range as handled by a subordinate map.
2545df8bae1dSRodney W. Grimes  *
2546df8bae1dSRodney W. Grimes  *	This range must have been created with vm_map_find,
2547df8bae1dSRodney W. Grimes  *	and no other operations may have been performed on this
2548df8bae1dSRodney W. Grimes  *	range prior to calling vm_map_submap.
2549df8bae1dSRodney W. Grimes  *
2550df8bae1dSRodney W. Grimes  *	Only a limited number of operations can be performed
2551df8bae1dSRodney W. Grimes  *	within this rage after calling vm_map_submap:
2552df8bae1dSRodney W. Grimes  *		vm_fault
2553df8bae1dSRodney W. Grimes  *	[Don't try vm_map_copy!]
2554df8bae1dSRodney W. Grimes  *
2555df8bae1dSRodney W. Grimes  *	To remove a submapping, one must first remove the
2556df8bae1dSRodney W. Grimes  *	range from the superior map, and then destroy the
2557df8bae1dSRodney W. Grimes  *	submap (if desired).  [Better yet, don't try it.]
2558df8bae1dSRodney W. Grimes  */
2559df8bae1dSRodney W. Grimes int
25601b40f8c0SMatthew Dillon vm_map_submap(
25611b40f8c0SMatthew Dillon 	vm_map_t map,
25621b40f8c0SMatthew Dillon 	vm_offset_t start,
25631b40f8c0SMatthew Dillon 	vm_offset_t end,
25641b40f8c0SMatthew Dillon 	vm_map_t submap)
2565df8bae1dSRodney W. Grimes {
2566df8bae1dSRodney W. Grimes 	vm_map_entry_t entry;
2567fa50a355SKonstantin Belousov 	int result;
2568fa50a355SKonstantin Belousov 
2569fa50a355SKonstantin Belousov 	result = KERN_INVALID_ARGUMENT;
2570fa50a355SKonstantin Belousov 
2571fa50a355SKonstantin Belousov 	vm_map_lock(submap);
2572fa50a355SKonstantin Belousov 	submap->flags |= MAP_IS_SUB_MAP;
2573fa50a355SKonstantin Belousov 	vm_map_unlock(submap);
2574df8bae1dSRodney W. Grimes 
2575df8bae1dSRodney W. Grimes 	vm_map_lock(map);
2576df8bae1dSRodney W. Grimes 	VM_MAP_RANGE_CHECK(map, start, end);
2577e6bd3a81SMark Johnston 	if (vm_map_lookup_entry(map, start, &entry) && entry->end >= end &&
2578e6bd3a81SMark Johnston 	    (entry->eflags & MAP_ENTRY_COW) == 0 &&
2579e6bd3a81SMark Johnston 	    entry->object.vm_object == NULL) {
2580e2e80fb3SKonstantin Belousov 		result = vm_map_clip_start(map, entry, start);
2581e2e80fb3SKonstantin Belousov 		if (result != KERN_SUCCESS)
2582e2e80fb3SKonstantin Belousov 			goto unlock;
2583e2e80fb3SKonstantin Belousov 		result = vm_map_clip_end(map, entry, end);
2584e2e80fb3SKonstantin Belousov 		if (result != KERN_SUCCESS)
2585e2e80fb3SKonstantin Belousov 			goto unlock;
25862d8acc0fSJohn Dyson 		entry->object.sub_map = submap;
2587afa07f7eSJohn Dyson 		entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
2588df8bae1dSRodney W. Grimes 		result = KERN_SUCCESS;
2589df8bae1dSRodney W. Grimes 	}
2590e2e80fb3SKonstantin Belousov unlock:
2591df8bae1dSRodney W. Grimes 	vm_map_unlock(map);
2592df8bae1dSRodney W. Grimes 
2593fa50a355SKonstantin Belousov 	if (result != KERN_SUCCESS) {
2594fa50a355SKonstantin Belousov 		vm_map_lock(submap);
2595fa50a355SKonstantin Belousov 		submap->flags &= ~MAP_IS_SUB_MAP;
2596fa50a355SKonstantin Belousov 		vm_map_unlock(submap);
2597fa50a355SKonstantin Belousov 	}
2598df8bae1dSRodney W. Grimes 	return (result);
2599df8bae1dSRodney W. Grimes }
2600df8bae1dSRodney W. Grimes 
2601df8bae1dSRodney W. Grimes /*
2602dd05fa19SAlan Cox  * The maximum number of pages to map if MAP_PREFAULT_PARTIAL is specified
26031f78f902SAlan Cox  */
26041f78f902SAlan Cox #define	MAX_INIT_PT	96
26051f78f902SAlan Cox 
26061f78f902SAlan Cox /*
26070551c08dSAlan Cox  *	vm_map_pmap_enter:
26080551c08dSAlan Cox  *
2609dd05fa19SAlan Cox  *	Preload the specified map's pmap with mappings to the specified
2610dd05fa19SAlan Cox  *	object's memory-resident pages.  No further physical pages are
2611dd05fa19SAlan Cox  *	allocated, and no further virtual pages are retrieved from secondary
2612dd05fa19SAlan Cox  *	storage.  If the specified flags include MAP_PREFAULT_PARTIAL, then a
2613dd05fa19SAlan Cox  *	limited number of page mappings are created at the low-end of the
2614dd05fa19SAlan Cox  *	specified address range.  (For this purpose, a superpage mapping
2615dd05fa19SAlan Cox  *	counts as one page mapping.)  Otherwise, all resident pages within
26163453bca8SAlan Cox  *	the specified address range are mapped.
26170551c08dSAlan Cox  */
2618077ec27cSAlan Cox static void
26194da4d293SAlan Cox vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
26200551c08dSAlan Cox     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
26210551c08dSAlan Cox {
26228fece8c3SAlan Cox 	vm_offset_t start;
2623ce142d9eSAlan Cox 	vm_page_t p, p_start;
2624dd05fa19SAlan Cox 	vm_pindex_t mask, psize, threshold, tmpidx;
26250551c08dSAlan Cox 
2626ba8bca61SAlan Cox 	if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0 || object == NULL)
26271f78f902SAlan Cox 		return;
26289af6d512SAttilio Rao 	if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
262989f6b863SAttilio Rao 		VM_OBJECT_WLOCK(object);
263001381811SJohn Baldwin 		if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
26319af6d512SAttilio Rao 			pmap_object_init_pt(map->pmap, addr, object, pindex,
26329af6d512SAttilio Rao 			    size);
26339af6d512SAttilio Rao 			VM_OBJECT_WUNLOCK(object);
26349af6d512SAttilio Rao 			return;
26359af6d512SAttilio Rao 		}
26369af6d512SAttilio Rao 		VM_OBJECT_LOCK_DOWNGRADE(object);
2637886b9021SJeff Roberson 	} else
2638886b9021SJeff Roberson 		VM_OBJECT_RLOCK(object);
26391f78f902SAlan Cox 
26401f78f902SAlan Cox 	psize = atop(size);
26411f78f902SAlan Cox 	if (psize + pindex > object->size) {
2642ed2f945aSMark Johnston 		if (pindex >= object->size) {
26439af6d512SAttilio Rao 			VM_OBJECT_RUNLOCK(object);
26449af6d512SAttilio Rao 			return;
26459af6d512SAttilio Rao 		}
26461f78f902SAlan Cox 		psize = object->size - pindex;
26471f78f902SAlan Cox 	}
26481f78f902SAlan Cox 
2649ce142d9eSAlan Cox 	start = 0;
2650ce142d9eSAlan Cox 	p_start = NULL;
2651dd05fa19SAlan Cox 	threshold = MAX_INIT_PT;
26521f78f902SAlan Cox 
2653b382c10aSKonstantin Belousov 	p = vm_page_find_least(object, pindex);
26541f78f902SAlan Cox 	/*
26551f78f902SAlan Cox 	 * Assert: the variable p is either (1) the page with the
26561f78f902SAlan Cox 	 * least pindex greater than or equal to the parameter pindex
26571f78f902SAlan Cox 	 * or (2) NULL.
26581f78f902SAlan Cox 	 */
26591f78f902SAlan Cox 	for (;
26601f78f902SAlan Cox 	     p != NULL && (tmpidx = p->pindex - pindex) < psize;
26611f78f902SAlan Cox 	     p = TAILQ_NEXT(p, listq)) {
26621f78f902SAlan Cox 		/*
26631f78f902SAlan Cox 		 * don't allow an madvise to blow away our really
26641f78f902SAlan Cox 		 * free pages allocating pv entries.
26651f78f902SAlan Cox 		 */
2666dd05fa19SAlan Cox 		if (((flags & MAP_PREFAULT_MADVISE) != 0 &&
2667e2068d0bSJeff Roberson 		    vm_page_count_severe()) ||
2668dd05fa19SAlan Cox 		    ((flags & MAP_PREFAULT_PARTIAL) != 0 &&
2669dd05fa19SAlan Cox 		    tmpidx >= threshold)) {
2670379fb642SAlan Cox 			psize = tmpidx;
26711f78f902SAlan Cox 			break;
26721f78f902SAlan Cox 		}
26730012f373SJeff Roberson 		if (vm_page_all_valid(p)) {
2674ce142d9eSAlan Cox 			if (p_start == NULL) {
2675ce142d9eSAlan Cox 				start = addr + ptoa(tmpidx);
2676ce142d9eSAlan Cox 				p_start = p;
2677ce142d9eSAlan Cox 			}
2678dd05fa19SAlan Cox 			/* Jump ahead if a superpage mapping is possible. */
2679dd05fa19SAlan Cox 			if (p->psind > 0 && ((addr + ptoa(tmpidx)) &
2680dd05fa19SAlan Cox 			    (pagesizes[p->psind] - 1)) == 0) {
2681dd05fa19SAlan Cox 				mask = atop(pagesizes[p->psind]) - 1;
2682dd05fa19SAlan Cox 				if (tmpidx + mask < psize &&
268388302601SAlan Cox 				    vm_page_ps_test(p, PS_ALL_VALID, NULL)) {
2684dd05fa19SAlan Cox 					p += mask;
2685dd05fa19SAlan Cox 					threshold += mask;
2686dd05fa19SAlan Cox 				}
2687dd05fa19SAlan Cox 			}
26887bfda801SAlan Cox 		} else if (p_start != NULL) {
2689cf4682aeSAlan Cox 			pmap_enter_object(map->pmap, start, addr +
2690cf4682aeSAlan Cox 			    ptoa(tmpidx), p_start, prot);
2691cf4682aeSAlan Cox 			p_start = NULL;
2692cf4682aeSAlan Cox 		}
2693cf4682aeSAlan Cox 	}
2694c46b90e9SAlan Cox 	if (p_start != NULL)
2695379fb642SAlan Cox 		pmap_enter_object(map->pmap, start, addr + ptoa(psize),
2696379fb642SAlan Cox 		    p_start, prot);
26979af6d512SAttilio Rao 	VM_OBJECT_RUNLOCK(object);
26980551c08dSAlan Cox }
26990551c08dSAlan Cox 
27000551c08dSAlan Cox /*
2701df8bae1dSRodney W. Grimes  *	vm_map_protect:
2702df8bae1dSRodney W. Grimes  *
27030659df6fSKonstantin Belousov  *	Sets the protection and/or the maximum protection of the
27040659df6fSKonstantin Belousov  *	specified address region in the target map.
2705df8bae1dSRodney W. Grimes  */
2706df8bae1dSRodney W. Grimes int
2707b9dcd593SBruce Evans vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
27080659df6fSKonstantin Belousov     vm_prot_t new_prot, vm_prot_t new_maxprot, int flags)
2709df8bae1dSRodney W. Grimes {
27102767c9f3SDoug Moore 	vm_map_entry_t entry, first_entry, in_tran, prev_entry;
27113364c323SKonstantin Belousov 	vm_object_t obj;
2712ef694c1aSEdward Tomasz Napierala 	struct ucred *cred;
2713210a6886SKonstantin Belousov 	vm_prot_t old_prot;
2714a72dce34SDoug Moore 	int rv;
2715df8bae1dSRodney W. Grimes 
271679e9451fSKonstantin Belousov 	if (start == end)
271779e9451fSKonstantin Belousov 		return (KERN_SUCCESS);
271879e9451fSKonstantin Belousov 
27190659df6fSKonstantin Belousov 	if ((flags & (VM_MAP_PROTECT_SET_PROT | VM_MAP_PROTECT_SET_MAXPROT)) ==
27200659df6fSKonstantin Belousov 	    (VM_MAP_PROTECT_SET_PROT | VM_MAP_PROTECT_SET_MAXPROT) &&
27210659df6fSKonstantin Belousov 	    (new_prot & new_maxprot) != new_prot)
27220659df6fSKonstantin Belousov 		return (KERN_OUT_OF_BOUNDS);
27230659df6fSKonstantin Belousov 
272419f5d9f2SKonstantin Belousov again:
272519f5d9f2SKonstantin Belousov 	in_tran = NULL;
2726df8bae1dSRodney W. Grimes 	vm_map_lock(map);
2727df8bae1dSRodney W. Grimes 
27280659df6fSKonstantin Belousov 	if ((map->flags & MAP_WXORX) != 0 &&
27290659df6fSKonstantin Belousov 	    (flags & VM_MAP_PROTECT_SET_PROT) != 0 &&
27300659df6fSKonstantin Belousov 	    (new_prot & (VM_PROT_WRITE | VM_PROT_EXECUTE)) == (VM_PROT_WRITE |
27312e1c94aaSKonstantin Belousov 	    VM_PROT_EXECUTE)) {
27322e1c94aaSKonstantin Belousov 		vm_map_unlock(map);
27332e1c94aaSKonstantin Belousov 		return (KERN_PROTECTION_FAILURE);
27342e1c94aaSKonstantin Belousov 	}
27352e1c94aaSKonstantin Belousov 
2736e1cb9d37SMark Johnston 	/*
2737e1cb9d37SMark Johnston 	 * Ensure that we are not concurrently wiring pages.  vm_map_wire() may
2738e1cb9d37SMark Johnston 	 * need to fault pages into the map and will drop the map lock while
2739e1cb9d37SMark Johnston 	 * doing so, and the VM object may end up in an inconsistent state if we
2740e1cb9d37SMark Johnston 	 * update the protection on the map entry in between faults.
2741e1cb9d37SMark Johnston 	 */
2742e1cb9d37SMark Johnston 	vm_map_wait_busy(map);
2743e1cb9d37SMark Johnston 
2744df8bae1dSRodney W. Grimes 	VM_MAP_RANGE_CHECK(map, start, end);
2745df8bae1dSRodney W. Grimes 
27462767c9f3SDoug Moore 	if (!vm_map_lookup_entry(map, start, &first_entry))
27472767c9f3SDoug Moore 		first_entry = vm_map_entry_succ(first_entry);
2748df8bae1dSRodney W. Grimes 
2749df8bae1dSRodney W. Grimes 	/*
27500d94caffSDavid Greenman 	 * Make a first pass to check for protection violations.
2751df8bae1dSRodney W. Grimes 	 */
27522767c9f3SDoug Moore 	for (entry = first_entry; entry->start < end;
27532767c9f3SDoug Moore 	    entry = vm_map_entry_succ(entry)) {
27542767c9f3SDoug Moore 		if ((entry->eflags & MAP_ENTRY_GUARD) != 0)
27558a89ca94SKonstantin Belousov 			continue;
27562767c9f3SDoug Moore 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0) {
2757a1f6d91cSDavid Greenman 			vm_map_unlock(map);
2758df8bae1dSRodney W. Grimes 			return (KERN_INVALID_ARGUMENT);
2759a1f6d91cSDavid Greenman 		}
27600659df6fSKonstantin Belousov 		if ((flags & VM_MAP_PROTECT_SET_PROT) == 0)
27610659df6fSKonstantin Belousov 			new_prot = entry->protection;
27620659df6fSKonstantin Belousov 		if ((flags & VM_MAP_PROTECT_SET_MAXPROT) == 0)
27630659df6fSKonstantin Belousov 			new_maxprot = entry->max_protection;
27640659df6fSKonstantin Belousov 		if ((new_prot & entry->max_protection) != new_prot ||
27650659df6fSKonstantin Belousov 		    (new_maxprot & entry->max_protection) != new_maxprot) {
2766df8bae1dSRodney W. Grimes 			vm_map_unlock(map);
2767df8bae1dSRodney W. Grimes 			return (KERN_PROTECTION_FAILURE);
2768df8bae1dSRodney W. Grimes 		}
27692767c9f3SDoug Moore 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0)
27702767c9f3SDoug Moore 			in_tran = entry;
277119f5d9f2SKonstantin Belousov 	}
277219f5d9f2SKonstantin Belousov 
277319f5d9f2SKonstantin Belousov 	/*
2774bdb90e76SDoug Moore 	 * Postpone the operation until all in-transition map entries have
2775bdb90e76SDoug Moore 	 * stabilized.  An in-transition entry might already have its pages
2776bdb90e76SDoug Moore 	 * wired and wired_count incremented, but not yet have its
2777bdb90e76SDoug Moore 	 * MAP_ENTRY_USER_WIRED flag set.  In which case, we would fail to call
2778bdb90e76SDoug Moore 	 * vm_fault_copy_entry() in the final loop below.
277919f5d9f2SKonstantin Belousov 	 */
278019f5d9f2SKonstantin Belousov 	if (in_tran != NULL) {
278119f5d9f2SKonstantin Belousov 		in_tran->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
278219f5d9f2SKonstantin Belousov 		vm_map_unlock_and_wait(map, 0);
278319f5d9f2SKonstantin Belousov 		goto again;
2784df8bae1dSRodney W. Grimes 	}
2785df8bae1dSRodney W. Grimes 
27863364c323SKonstantin Belousov 	/*
2787a72dce34SDoug Moore 	 * Before changing the protections, try to reserve swap space for any
2788a72dce34SDoug Moore 	 * private (i.e., copy-on-write) mappings that are transitioning from
2789a72dce34SDoug Moore 	 * read-only to read/write access.  If a reservation fails, break out
2790a72dce34SDoug Moore 	 * of this loop early and let the next loop simplify the entries, since
2791a72dce34SDoug Moore 	 * some may now be mergeable.
27923364c323SKonstantin Belousov 	 */
2793e2e80fb3SKonstantin Belousov 	rv = vm_map_clip_start(map, first_entry, start);
2794e2e80fb3SKonstantin Belousov 	if (rv != KERN_SUCCESS) {
2795e2e80fb3SKonstantin Belousov 		vm_map_unlock(map);
2796e2e80fb3SKonstantin Belousov 		return (rv);
2797e2e80fb3SKonstantin Belousov 	}
27982767c9f3SDoug Moore 	for (entry = first_entry; entry->start < end;
27992767c9f3SDoug Moore 	    entry = vm_map_entry_succ(entry)) {
2800e2e80fb3SKonstantin Belousov 		rv = vm_map_clip_end(map, entry, end);
2801e2e80fb3SKonstantin Belousov 		if (rv != KERN_SUCCESS) {
2802e2e80fb3SKonstantin Belousov 			vm_map_unlock(map);
2803e2e80fb3SKonstantin Belousov 			return (rv);
2804e2e80fb3SKonstantin Belousov 		}
28053364c323SKonstantin Belousov 
28060659df6fSKonstantin Belousov 		if ((flags & VM_MAP_PROTECT_SET_PROT) == 0 ||
28072767c9f3SDoug Moore 		    ((new_prot & ~entry->protection) & VM_PROT_WRITE) == 0 ||
28082767c9f3SDoug Moore 		    ENTRY_CHARGED(entry) ||
28090659df6fSKonstantin Belousov 		    (entry->eflags & MAP_ENTRY_GUARD) != 0)
28103364c323SKonstantin Belousov 			continue;
28113364c323SKonstantin Belousov 
2812ef694c1aSEdward Tomasz Napierala 		cred = curthread->td_ucred;
28132767c9f3SDoug Moore 		obj = entry->object.vm_object;
28143364c323SKonstantin Belousov 
28152767c9f3SDoug Moore 		if (obj == NULL ||
28162767c9f3SDoug Moore 		    (entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0) {
28172767c9f3SDoug Moore 			if (!swap_reserve(entry->end - entry->start)) {
2818a72dce34SDoug Moore 				rv = KERN_RESOURCE_SHORTAGE;
28192767c9f3SDoug Moore 				end = entry->end;
2820a72dce34SDoug Moore 				break;
28213364c323SKonstantin Belousov 			}
2822ef694c1aSEdward Tomasz Napierala 			crhold(cred);
28232767c9f3SDoug Moore 			entry->cred = cred;
28243364c323SKonstantin Belousov 			continue;
28253364c323SKonstantin Belousov 		}
28263364c323SKonstantin Belousov 
282789f6b863SAttilio Rao 		VM_OBJECT_WLOCK(obj);
2828*0cb2610eSMark Johnston 		if ((obj->flags & OBJ_SWAP) == 0) {
282989f6b863SAttilio Rao 			VM_OBJECT_WUNLOCK(obj);
28303364c323SKonstantin Belousov 			continue;
28313364c323SKonstantin Belousov 		}
28323364c323SKonstantin Belousov 
28333364c323SKonstantin Belousov 		/*
28343364c323SKonstantin Belousov 		 * Charge for the whole object allocation now, since
28353364c323SKonstantin Belousov 		 * we cannot distinguish between non-charged and
28363364c323SKonstantin Belousov 		 * charged clipped mapping of the same object later.
28373364c323SKonstantin Belousov 		 */
28383364c323SKonstantin Belousov 		KASSERT(obj->charge == 0,
28393d95614fSKonstantin Belousov 		    ("vm_map_protect: object %p overcharged (entry %p)",
28402767c9f3SDoug Moore 		    obj, entry));
28413364c323SKonstantin Belousov 		if (!swap_reserve(ptoa(obj->size))) {
284289f6b863SAttilio Rao 			VM_OBJECT_WUNLOCK(obj);
2843a72dce34SDoug Moore 			rv = KERN_RESOURCE_SHORTAGE;
28442767c9f3SDoug Moore 			end = entry->end;
2845a72dce34SDoug Moore 			break;
28463364c323SKonstantin Belousov 		}
28473364c323SKonstantin Belousov 
2848ef694c1aSEdward Tomasz Napierala 		crhold(cred);
2849ef694c1aSEdward Tomasz Napierala 		obj->cred = cred;
28503364c323SKonstantin Belousov 		obj->charge = ptoa(obj->size);
285189f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(obj);
28523364c323SKonstantin Belousov 	}
28533364c323SKonstantin Belousov 
2854df8bae1dSRodney W. Grimes 	/*
2855a72dce34SDoug Moore 	 * If enough swap space was available, go back and fix up protections.
2856a72dce34SDoug Moore 	 * Otherwise, just simplify entries, since some may have been modified.
2857a72dce34SDoug Moore 	 * [Note that clipping is not necessary the second time.]
2858df8bae1dSRodney W. Grimes 	 */
28592767c9f3SDoug Moore 	for (prev_entry = vm_map_entry_pred(first_entry), entry = first_entry;
28602767c9f3SDoug Moore 	    entry->start < end;
28612767c9f3SDoug Moore 	    vm_map_try_merge_entries(map, prev_entry, entry),
28622767c9f3SDoug Moore 	    prev_entry = entry, entry = vm_map_entry_succ(entry)) {
2863a72dce34SDoug Moore 		if (rv != KERN_SUCCESS ||
28642767c9f3SDoug Moore 		    (entry->eflags & MAP_ENTRY_GUARD) != 0)
286519bd0d9cSKonstantin Belousov 			continue;
286619bd0d9cSKonstantin Belousov 
28672767c9f3SDoug Moore 		old_prot = entry->protection;
2868210a6886SKonstantin Belousov 
28690659df6fSKonstantin Belousov 		if ((flags & VM_MAP_PROTECT_SET_MAXPROT) != 0) {
28700659df6fSKonstantin Belousov 			entry->max_protection = new_maxprot;
28710659df6fSKonstantin Belousov 			entry->protection = new_maxprot & old_prot;
28720659df6fSKonstantin Belousov 		}
28730659df6fSKonstantin Belousov 		if ((flags & VM_MAP_PROTECT_SET_PROT) != 0)
28742767c9f3SDoug Moore 			entry->protection = new_prot;
2875df8bae1dSRodney W. Grimes 
2876dd006a1bSAlan Cox 		/*
2877dd006a1bSAlan Cox 		 * For user wired map entries, the normal lazy evaluation of
2878dd006a1bSAlan Cox 		 * write access upgrades through soft page faults is
2879dd006a1bSAlan Cox 		 * undesirable.  Instead, immediately copy any pages that are
2880dd006a1bSAlan Cox 		 * copy-on-write and enable write access in the physical map.
2881dd006a1bSAlan Cox 		 */
28822767c9f3SDoug Moore 		if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0 &&
28832767c9f3SDoug Moore 		    (entry->protection & VM_PROT_WRITE) != 0 &&
28845930251aSKonstantin Belousov 		    (old_prot & VM_PROT_WRITE) == 0)
28852767c9f3SDoug Moore 			vm_fault_copy_entry(map, map, entry, entry, NULL);
2886210a6886SKonstantin Belousov 
2887df8bae1dSRodney W. Grimes 		/*
28882fafce9eSAlan Cox 		 * When restricting access, update the physical map.  Worry
28892fafce9eSAlan Cox 		 * about copy-on-write here.
2890df8bae1dSRodney W. Grimes 		 */
28912767c9f3SDoug Moore 		if ((old_prot & ~entry->protection) != 0) {
2892afa07f7eSJohn Dyson #define MASK(entry)	(((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
2893df8bae1dSRodney W. Grimes 							VM_PROT_ALL)
28942767c9f3SDoug Moore 			pmap_protect(map->pmap, entry->start,
28952767c9f3SDoug Moore 			    entry->end,
28962767c9f3SDoug Moore 			    entry->protection & MASK(entry));
2897df8bae1dSRodney W. Grimes #undef	MASK
2898df8bae1dSRodney W. Grimes 		}
2899df8bae1dSRodney W. Grimes 	}
29002767c9f3SDoug Moore 	vm_map_try_merge_entries(map, prev_entry, entry);
2901df8bae1dSRodney W. Grimes 	vm_map_unlock(map);
2902a72dce34SDoug Moore 	return (rv);
2903df8bae1dSRodney W. Grimes }
2904df8bae1dSRodney W. Grimes 
2905df8bae1dSRodney W. Grimes /*
2906867a482dSJohn Dyson  *	vm_map_madvise:
2907867a482dSJohn Dyson  *
2908867a482dSJohn Dyson  *	This routine traverses a processes map handling the madvise
2909f7fc307aSAlan Cox  *	system call.  Advisories are classified as either those effecting
2910f7fc307aSAlan Cox  *	the vm_map_entry structure, or those effecting the underlying
2911f7fc307aSAlan Cox  *	objects.
2912867a482dSJohn Dyson  */
2913b4309055SMatthew Dillon int
29141b40f8c0SMatthew Dillon vm_map_madvise(
29151b40f8c0SMatthew Dillon 	vm_map_t map,
29161b40f8c0SMatthew Dillon 	vm_offset_t start,
29171b40f8c0SMatthew Dillon 	vm_offset_t end,
29181b40f8c0SMatthew Dillon 	int behav)
2919867a482dSJohn Dyson {
29202767c9f3SDoug Moore 	vm_map_entry_t entry, prev_entry;
2921e2e80fb3SKonstantin Belousov 	int rv;
29223e7cb27cSAlan Cox 	bool modify_map;
2923867a482dSJohn Dyson 
2924b4309055SMatthew Dillon 	/*
2925b4309055SMatthew Dillon 	 * Some madvise calls directly modify the vm_map_entry, in which case
2926b4309055SMatthew Dillon 	 * we need to use an exclusive lock on the map and we need to perform
2927b4309055SMatthew Dillon 	 * various clipping operations.  Otherwise we only need a read-lock
2928b4309055SMatthew Dillon 	 * on the map.
2929b4309055SMatthew Dillon 	 */
2930b4309055SMatthew Dillon 	switch(behav) {
2931b4309055SMatthew Dillon 	case MADV_NORMAL:
2932b4309055SMatthew Dillon 	case MADV_SEQUENTIAL:
2933b4309055SMatthew Dillon 	case MADV_RANDOM:
29344f79d873SMatthew Dillon 	case MADV_NOSYNC:
29354f79d873SMatthew Dillon 	case MADV_AUTOSYNC:
29369730a5daSPaul Saab 	case MADV_NOCORE:
29379730a5daSPaul Saab 	case MADV_CORE:
293879e9451fSKonstantin Belousov 		if (start == end)
29393e7cb27cSAlan Cox 			return (0);
29403e7cb27cSAlan Cox 		modify_map = true;
2941867a482dSJohn Dyson 		vm_map_lock(map);
2942b4309055SMatthew Dillon 		break;
2943b4309055SMatthew Dillon 	case MADV_WILLNEED:
2944b4309055SMatthew Dillon 	case MADV_DONTNEED:
2945b4309055SMatthew Dillon 	case MADV_FREE:
294679e9451fSKonstantin Belousov 		if (start == end)
29473e7cb27cSAlan Cox 			return (0);
29483e7cb27cSAlan Cox 		modify_map = false;
2949f7fc307aSAlan Cox 		vm_map_lock_read(map);
2950b4309055SMatthew Dillon 		break;
2951b4309055SMatthew Dillon 	default:
29523e7cb27cSAlan Cox 		return (EINVAL);
2953b4309055SMatthew Dillon 	}
2954b4309055SMatthew Dillon 
2955b4309055SMatthew Dillon 	/*
2956b4309055SMatthew Dillon 	 * Locate starting entry and clip if necessary.
2957b4309055SMatthew Dillon 	 */
2958867a482dSJohn Dyson 	VM_MAP_RANGE_CHECK(map, start, end);
2959867a482dSJohn Dyson 
2960f7fc307aSAlan Cox 	if (modify_map) {
2961f7fc307aSAlan Cox 		/*
2962f7fc307aSAlan Cox 		 * madvise behaviors that are implemented in the vm_map_entry.
2963f7fc307aSAlan Cox 		 *
2964f7fc307aSAlan Cox 		 * We clip the vm_map_entry so that behavioral changes are
2965f7fc307aSAlan Cox 		 * limited to the specified address range.
2966f7fc307aSAlan Cox 		 */
2967e2e80fb3SKonstantin Belousov 		rv = vm_map_lookup_clip_start(map, start, &entry, &prev_entry);
2968e2e80fb3SKonstantin Belousov 		if (rv != KERN_SUCCESS) {
2969e2e80fb3SKonstantin Belousov 			vm_map_unlock(map);
2970e2e80fb3SKonstantin Belousov 			return (vm_mmap_to_errno(rv));
2971e2e80fb3SKonstantin Belousov 		}
2972e2e80fb3SKonstantin Belousov 
2973e2e80fb3SKonstantin Belousov 		for (; entry->start < end; prev_entry = entry,
2974e2e80fb3SKonstantin Belousov 		    entry = vm_map_entry_succ(entry)) {
29752767c9f3SDoug Moore 			if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
2976867a482dSJohn Dyson 				continue;
2977fed9a903SJohn Dyson 
2978e2e80fb3SKonstantin Belousov 			rv = vm_map_clip_end(map, entry, end);
2979e2e80fb3SKonstantin Belousov 			if (rv != KERN_SUCCESS) {
2980e2e80fb3SKonstantin Belousov 				vm_map_unlock(map);
2981e2e80fb3SKonstantin Belousov 				return (vm_mmap_to_errno(rv));
2982e2e80fb3SKonstantin Belousov 			}
2983fed9a903SJohn Dyson 
2984f7fc307aSAlan Cox 			switch (behav) {
2985867a482dSJohn Dyson 			case MADV_NORMAL:
29862767c9f3SDoug Moore 				vm_map_entry_set_behavior(entry,
29872767c9f3SDoug Moore 				    MAP_ENTRY_BEHAV_NORMAL);
2988867a482dSJohn Dyson 				break;
2989867a482dSJohn Dyson 			case MADV_SEQUENTIAL:
29902767c9f3SDoug Moore 				vm_map_entry_set_behavior(entry,
29912767c9f3SDoug Moore 				    MAP_ENTRY_BEHAV_SEQUENTIAL);
2992867a482dSJohn Dyson 				break;
2993867a482dSJohn Dyson 			case MADV_RANDOM:
29942767c9f3SDoug Moore 				vm_map_entry_set_behavior(entry,
29952767c9f3SDoug Moore 				    MAP_ENTRY_BEHAV_RANDOM);
2996867a482dSJohn Dyson 				break;
29974f79d873SMatthew Dillon 			case MADV_NOSYNC:
29982767c9f3SDoug Moore 				entry->eflags |= MAP_ENTRY_NOSYNC;
29994f79d873SMatthew Dillon 				break;
30004f79d873SMatthew Dillon 			case MADV_AUTOSYNC:
30012767c9f3SDoug Moore 				entry->eflags &= ~MAP_ENTRY_NOSYNC;
30024f79d873SMatthew Dillon 				break;
30039730a5daSPaul Saab 			case MADV_NOCORE:
30042767c9f3SDoug Moore 				entry->eflags |= MAP_ENTRY_NOCOREDUMP;
30059730a5daSPaul Saab 				break;
30069730a5daSPaul Saab 			case MADV_CORE:
30072767c9f3SDoug Moore 				entry->eflags &= ~MAP_ENTRY_NOCOREDUMP;
30089730a5daSPaul Saab 				break;
3009867a482dSJohn Dyson 			default:
3010867a482dSJohn Dyson 				break;
3011867a482dSJohn Dyson 			}
30122767c9f3SDoug Moore 			vm_map_try_merge_entries(map, prev_entry, entry);
3013867a482dSJohn Dyson 		}
30142767c9f3SDoug Moore 		vm_map_try_merge_entries(map, prev_entry, entry);
3015867a482dSJohn Dyson 		vm_map_unlock(map);
3016b4309055SMatthew Dillon 	} else {
301792a59946SJohn Baldwin 		vm_pindex_t pstart, pend;
3018f7fc307aSAlan Cox 
3019f7fc307aSAlan Cox 		/*
3020f7fc307aSAlan Cox 		 * madvise behaviors that are implemented in the underlying
3021f7fc307aSAlan Cox 		 * vm_object.
3022f7fc307aSAlan Cox 		 *
3023f7fc307aSAlan Cox 		 * Since we don't clip the vm_map_entry, we have to clip
3024f7fc307aSAlan Cox 		 * the vm_object pindex and count.
3025f7fc307aSAlan Cox 		 */
3026c7b23459SDoug Moore 		if (!vm_map_lookup_entry(map, start, &entry))
3027c7b23459SDoug Moore 			entry = vm_map_entry_succ(entry);
30282767c9f3SDoug Moore 		for (; entry->start < end;
30292767c9f3SDoug Moore 		    entry = vm_map_entry_succ(entry)) {
303051321f7cSAlan Cox 			vm_offset_t useEnd, useStart;
30315f99b57cSMatthew Dillon 
30322767c9f3SDoug Moore 			if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
3033f7fc307aSAlan Cox 				continue;
3034f7fc307aSAlan Cox 
3035bf5661f4SKonstantin Belousov 			/*
3036bf5661f4SKonstantin Belousov 			 * MADV_FREE would otherwise rewind time to
3037bf5661f4SKonstantin Belousov 			 * the creation of the shadow object.  Because
3038bf5661f4SKonstantin Belousov 			 * we hold the VM map read-locked, neither the
3039bf5661f4SKonstantin Belousov 			 * entry's object nor the presence of a
3040bf5661f4SKonstantin Belousov 			 * backing object can change.
3041bf5661f4SKonstantin Belousov 			 */
3042bf5661f4SKonstantin Belousov 			if (behav == MADV_FREE &&
30432767c9f3SDoug Moore 			    entry->object.vm_object != NULL &&
30442767c9f3SDoug Moore 			    entry->object.vm_object->backing_object != NULL)
3045bf5661f4SKonstantin Belousov 				continue;
3046bf5661f4SKonstantin Belousov 
30472767c9f3SDoug Moore 			pstart = OFF_TO_IDX(entry->offset);
30482767c9f3SDoug Moore 			pend = pstart + atop(entry->end - entry->start);
30492767c9f3SDoug Moore 			useStart = entry->start;
30502767c9f3SDoug Moore 			useEnd = entry->end;
3051f7fc307aSAlan Cox 
30522767c9f3SDoug Moore 			if (entry->start < start) {
30532767c9f3SDoug Moore 				pstart += atop(start - entry->start);
30545f99b57cSMatthew Dillon 				useStart = start;
3055f7fc307aSAlan Cox 			}
30562767c9f3SDoug Moore 			if (entry->end > end) {
30572767c9f3SDoug Moore 				pend -= atop(entry->end - end);
305851321f7cSAlan Cox 				useEnd = end;
305951321f7cSAlan Cox 			}
3060f7fc307aSAlan Cox 
306192a59946SJohn Baldwin 			if (pstart >= pend)
3062f7fc307aSAlan Cox 				continue;
3063f7fc307aSAlan Cox 
306451321f7cSAlan Cox 			/*
306551321f7cSAlan Cox 			 * Perform the pmap_advise() before clearing
306651321f7cSAlan Cox 			 * PGA_REFERENCED in vm_page_advise().  Otherwise, a
306751321f7cSAlan Cox 			 * concurrent pmap operation, such as pmap_remove(),
306851321f7cSAlan Cox 			 * could clear a reference in the pmap and set
306951321f7cSAlan Cox 			 * PGA_REFERENCED on the page before the pmap_advise()
307051321f7cSAlan Cox 			 * had completed.  Consequently, the page would appear
307151321f7cSAlan Cox 			 * referenced based upon an old reference that
307251321f7cSAlan Cox 			 * occurred before this pmap_advise() ran.
307351321f7cSAlan Cox 			 */
307451321f7cSAlan Cox 			if (behav == MADV_DONTNEED || behav == MADV_FREE)
307551321f7cSAlan Cox 				pmap_advise(map->pmap, useStart, useEnd,
307651321f7cSAlan Cox 				    behav);
307751321f7cSAlan Cox 
30782767c9f3SDoug Moore 			vm_object_madvise(entry->object.vm_object, pstart,
307992a59946SJohn Baldwin 			    pend, behav);
308054432196SKonstantin Belousov 
308154432196SKonstantin Belousov 			/*
308254432196SKonstantin Belousov 			 * Pre-populate paging structures in the
308354432196SKonstantin Belousov 			 * WILLNEED case.  For wired entries, the
308454432196SKonstantin Belousov 			 * paging structures are already populated.
308554432196SKonstantin Belousov 			 */
308654432196SKonstantin Belousov 			if (behav == MADV_WILLNEED &&
30872767c9f3SDoug Moore 			    entry->wired_count == 0) {
30880551c08dSAlan Cox 				vm_map_pmap_enter(map,
30895f99b57cSMatthew Dillon 				    useStart,
30902767c9f3SDoug Moore 				    entry->protection,
30912767c9f3SDoug Moore 				    entry->object.vm_object,
309292a59946SJohn Baldwin 				    pstart,
309392a59946SJohn Baldwin 				    ptoa(pend - pstart),
3094e3026983SMatthew Dillon 				    MAP_PREFAULT_MADVISE
3095b4309055SMatthew Dillon 				);
3096f7fc307aSAlan Cox 			}
3097f7fc307aSAlan Cox 		}
3098f7fc307aSAlan Cox 		vm_map_unlock_read(map);
3099f7fc307aSAlan Cox 	}
3100b4309055SMatthew Dillon 	return (0);
3101867a482dSJohn Dyson }
3102867a482dSJohn Dyson 
3103867a482dSJohn Dyson /*
3104df8bae1dSRodney W. Grimes  *	vm_map_inherit:
3105df8bae1dSRodney W. Grimes  *
3106df8bae1dSRodney W. Grimes  *	Sets the inheritance of the specified address
3107df8bae1dSRodney W. Grimes  *	range in the target map.  Inheritance
3108df8bae1dSRodney W. Grimes  *	affects how the map will be shared with
3109e2abaaaaSAlan Cox  *	child maps at the time of vmspace_fork.
3110df8bae1dSRodney W. Grimes  */
3111df8bae1dSRodney W. Grimes int
3112b9dcd593SBruce Evans vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
3113b9dcd593SBruce Evans 	       vm_inherit_t new_inheritance)
3114df8bae1dSRodney W. Grimes {
3115e2e80fb3SKonstantin Belousov 	vm_map_entry_t entry, lentry, prev_entry, start_entry;
3116e2e80fb3SKonstantin Belousov 	int rv;
3117df8bae1dSRodney W. Grimes 
3118df8bae1dSRodney W. Grimes 	switch (new_inheritance) {
3119df8bae1dSRodney W. Grimes 	case VM_INHERIT_NONE:
3120df8bae1dSRodney W. Grimes 	case VM_INHERIT_COPY:
3121df8bae1dSRodney W. Grimes 	case VM_INHERIT_SHARE:
312278d7964bSXin LI 	case VM_INHERIT_ZERO:
3123df8bae1dSRodney W. Grimes 		break;
3124df8bae1dSRodney W. Grimes 	default:
3125df8bae1dSRodney W. Grimes 		return (KERN_INVALID_ARGUMENT);
3126df8bae1dSRodney W. Grimes 	}
312779e9451fSKonstantin Belousov 	if (start == end)
312879e9451fSKonstantin Belousov 		return (KERN_SUCCESS);
3129df8bae1dSRodney W. Grimes 	vm_map_lock(map);
3130df8bae1dSRodney W. Grimes 	VM_MAP_RANGE_CHECK(map, start, end);
3131e2e80fb3SKonstantin Belousov 	rv = vm_map_lookup_clip_start(map, start, &start_entry, &prev_entry);
3132e2e80fb3SKonstantin Belousov 	if (rv != KERN_SUCCESS)
3133e2e80fb3SKonstantin Belousov 		goto unlock;
3134e2e80fb3SKonstantin Belousov 	if (vm_map_lookup_entry(map, end - 1, &lentry)) {
3135e2e80fb3SKonstantin Belousov 		rv = vm_map_clip_end(map, lentry, end);
3136e2e80fb3SKonstantin Belousov 		if (rv != KERN_SUCCESS)
3137e2e80fb3SKonstantin Belousov 			goto unlock;
3138e2e80fb3SKonstantin Belousov 	}
3139e2e80fb3SKonstantin Belousov 	if (new_inheritance == VM_INHERIT_COPY) {
3140e2e80fb3SKonstantin Belousov 		for (entry = start_entry; entry->start < end;
314183704cc2SDoug Moore 		    prev_entry = entry, entry = vm_map_entry_succ(entry)) {
3142e2e80fb3SKonstantin Belousov 			if ((entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK)
3143e2e80fb3SKonstantin Belousov 			    != 0) {
3144e2e80fb3SKonstantin Belousov 				rv = KERN_INVALID_ARGUMENT;
3145e2e80fb3SKonstantin Belousov 				goto unlock;
3146e2e80fb3SKonstantin Belousov 			}
3147e2e80fb3SKonstantin Belousov 		}
3148e2e80fb3SKonstantin Belousov 	}
3149e2e80fb3SKonstantin Belousov 	for (entry = start_entry; entry->start < end; prev_entry = entry,
3150e2e80fb3SKonstantin Belousov 	    entry = vm_map_entry_succ(entry)) {
3151e2e80fb3SKonstantin Belousov 		KASSERT(entry->end <= end, ("non-clipped entry %p end %jx %jx",
3152e2e80fb3SKonstantin Belousov 		    entry, (uintmax_t)entry->end, (uintmax_t)end));
315319bd0d9cSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_GUARD) == 0 ||
315419bd0d9cSKonstantin Belousov 		    new_inheritance != VM_INHERIT_ZERO)
3155df8bae1dSRodney W. Grimes 			entry->inheritance = new_inheritance;
315683704cc2SDoug Moore 		vm_map_try_merge_entries(map, prev_entry, entry);
3157df8bae1dSRodney W. Grimes 	}
315883704cc2SDoug Moore 	vm_map_try_merge_entries(map, prev_entry, entry);
3159e2e80fb3SKonstantin Belousov unlock:
3160df8bae1dSRodney W. Grimes 	vm_map_unlock(map);
3161e2e80fb3SKonstantin Belousov 	return (rv);
3162df8bae1dSRodney W. Grimes }
3163df8bae1dSRodney W. Grimes 
3164df8bae1dSRodney W. Grimes /*
3165312df2c1SDoug Moore  *	vm_map_entry_in_transition:
3166312df2c1SDoug Moore  *
3167312df2c1SDoug Moore  *	Release the map lock, and sleep until the entry is no longer in
3168312df2c1SDoug Moore  *	transition.  Awake and acquire the map lock.  If the map changed while
3169312df2c1SDoug Moore  *	another held the lock, lookup a possibly-changed entry at or after the
3170312df2c1SDoug Moore  *	'start' position of the old entry.
3171312df2c1SDoug Moore  */
3172312df2c1SDoug Moore static vm_map_entry_t
3173312df2c1SDoug Moore vm_map_entry_in_transition(vm_map_t map, vm_offset_t in_start,
3174312df2c1SDoug Moore     vm_offset_t *io_end, bool holes_ok, vm_map_entry_t in_entry)
3175312df2c1SDoug Moore {
3176312df2c1SDoug Moore 	vm_map_entry_t entry;
3177312df2c1SDoug Moore 	vm_offset_t start;
3178312df2c1SDoug Moore 	u_int last_timestamp;
3179312df2c1SDoug Moore 
3180312df2c1SDoug Moore 	VM_MAP_ASSERT_LOCKED(map);
3181312df2c1SDoug Moore 	KASSERT((in_entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3182312df2c1SDoug Moore 	    ("not in-tranition map entry %p", in_entry));
3183312df2c1SDoug Moore 	/*
3184312df2c1SDoug Moore 	 * We have not yet clipped the entry.
3185312df2c1SDoug Moore 	 */
3186312df2c1SDoug Moore 	start = MAX(in_start, in_entry->start);
3187312df2c1SDoug Moore 	in_entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3188312df2c1SDoug Moore 	last_timestamp = map->timestamp;
3189312df2c1SDoug Moore 	if (vm_map_unlock_and_wait(map, 0)) {
3190312df2c1SDoug Moore 		/*
3191312df2c1SDoug Moore 		 * Allow interruption of user wiring/unwiring?
3192312df2c1SDoug Moore 		 */
3193312df2c1SDoug Moore 	}
3194312df2c1SDoug Moore 	vm_map_lock(map);
3195312df2c1SDoug Moore 	if (last_timestamp + 1 == map->timestamp)
3196312df2c1SDoug Moore 		return (in_entry);
3197312df2c1SDoug Moore 
3198312df2c1SDoug Moore 	/*
3199312df2c1SDoug Moore 	 * Look again for the entry because the map was modified while it was
3200312df2c1SDoug Moore 	 * unlocked.  Specifically, the entry may have been clipped, merged, or
3201312df2c1SDoug Moore 	 * deleted.
3202312df2c1SDoug Moore 	 */
3203312df2c1SDoug Moore 	if (!vm_map_lookup_entry(map, start, &entry)) {
3204312df2c1SDoug Moore 		if (!holes_ok) {
3205312df2c1SDoug Moore 			*io_end = start;
3206312df2c1SDoug Moore 			return (NULL);
3207312df2c1SDoug Moore 		}
32087cdcf863SDoug Moore 		entry = vm_map_entry_succ(entry);
3209312df2c1SDoug Moore 	}
3210312df2c1SDoug Moore 	return (entry);
3211312df2c1SDoug Moore }
3212312df2c1SDoug Moore 
3213312df2c1SDoug Moore /*
3214acd9a301SAlan Cox  *	vm_map_unwire:
3215acd9a301SAlan Cox  *
3216e27e17b7SAlan Cox  *	Implements both kernel and user unwiring.
3217acd9a301SAlan Cox  */
3218acd9a301SAlan Cox int
3219acd9a301SAlan Cox vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
3220abd498aaSBruce M Simpson     int flags)
3221acd9a301SAlan Cox {
322283704cc2SDoug Moore 	vm_map_entry_t entry, first_entry, next_entry, prev_entry;
3223acd9a301SAlan Cox 	int rv;
322483704cc2SDoug Moore 	bool holes_ok, need_wakeup, user_unwire;
3225acd9a301SAlan Cox 
322679e9451fSKonstantin Belousov 	if (start == end)
322779e9451fSKonstantin Belousov 		return (KERN_SUCCESS);
32289a0cdf94SDoug Moore 	holes_ok = (flags & VM_MAP_WIRE_HOLESOK) != 0;
32299a0cdf94SDoug Moore 	user_unwire = (flags & VM_MAP_WIRE_USER) != 0;
3230acd9a301SAlan Cox 	vm_map_lock(map);
3231acd9a301SAlan Cox 	VM_MAP_RANGE_CHECK(map, start, end);
3232d1d3f7e1SDoug Moore 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
32339a0cdf94SDoug Moore 		if (holes_ok)
32347cdcf863SDoug Moore 			first_entry = vm_map_entry_succ(first_entry);
3235d1d3f7e1SDoug Moore 		else {
3236acd9a301SAlan Cox 			vm_map_unlock(map);
3237acd9a301SAlan Cox 			return (KERN_INVALID_ADDRESS);
3238acd9a301SAlan Cox 		}
3239abd498aaSBruce M Simpson 	}
3240d2860f22SDoug Moore 	rv = KERN_SUCCESS;
324183704cc2SDoug Moore 	for (entry = first_entry; entry->start < end; entry = next_entry) {
3242acd9a301SAlan Cox 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
3243acd9a301SAlan Cox 			/*
3244acd9a301SAlan Cox 			 * We have not yet clipped the entry.
3245acd9a301SAlan Cox 			 */
324683704cc2SDoug Moore 			next_entry = vm_map_entry_in_transition(map, start,
324783704cc2SDoug Moore 			    &end, holes_ok, entry);
324883704cc2SDoug Moore 			if (next_entry == NULL) {
324983704cc2SDoug Moore 				if (entry == first_entry) {
3250acd9a301SAlan Cox 					vm_map_unlock(map);
3251acd9a301SAlan Cox 					return (KERN_INVALID_ADDRESS);
3252acd9a301SAlan Cox 				}
3253acd9a301SAlan Cox 				rv = KERN_INVALID_ADDRESS;
3254d2860f22SDoug Moore 				break;
3255acd9a301SAlan Cox 			}
325683704cc2SDoug Moore 			first_entry = (entry == first_entry) ?
325783704cc2SDoug Moore 			    next_entry : NULL;
3258acd9a301SAlan Cox 			continue;
3259acd9a301SAlan Cox 		}
3260e2e80fb3SKonstantin Belousov 		rv = vm_map_clip_start(map, entry, start);
3261e2e80fb3SKonstantin Belousov 		if (rv != KERN_SUCCESS)
3262e2e80fb3SKonstantin Belousov 			break;
3263e2e80fb3SKonstantin Belousov 		rv = vm_map_clip_end(map, entry, end);
3264e2e80fb3SKonstantin Belousov 		if (rv != KERN_SUCCESS)
3265e2e80fb3SKonstantin Belousov 			break;
3266e2e80fb3SKonstantin Belousov 
3267acd9a301SAlan Cox 		/*
3268acd9a301SAlan Cox 		 * Mark the entry in case the map lock is released.  (See
3269acd9a301SAlan Cox 		 * above.)
3270acd9a301SAlan Cox 		 */
3271ff3ae454SKonstantin Belousov 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
3272ff3ae454SKonstantin Belousov 		    entry->wiring_thread == NULL,
3273ff3ae454SKonstantin Belousov 		    ("owned map entry %p", entry));
3274acd9a301SAlan Cox 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
32750acea7dfSKonstantin Belousov 		entry->wiring_thread = curthread;
327683704cc2SDoug Moore 		next_entry = vm_map_entry_succ(entry);
3277acd9a301SAlan Cox 		/*
3278acd9a301SAlan Cox 		 * Check the map for holes in the specified region.
32799a0cdf94SDoug Moore 		 * If holes_ok, skip this check.
3280acd9a301SAlan Cox 		 */
32819a0cdf94SDoug Moore 		if (!holes_ok &&
328283704cc2SDoug Moore 		    entry->end < end && next_entry->start > entry->end) {
3283acd9a301SAlan Cox 			end = entry->end;
3284acd9a301SAlan Cox 			rv = KERN_INVALID_ADDRESS;
3285d2860f22SDoug Moore 			break;
3286acd9a301SAlan Cox 		}
3287acd9a301SAlan Cox 		/*
32883ffbc0cdSAlan Cox 		 * If system unwiring, require that the entry is system wired.
3289acd9a301SAlan Cox 		 */
32900ada205eSBrian Feldman 		if (!user_unwire &&
32910ada205eSBrian Feldman 		    vm_map_entry_system_wired_count(entry) == 0) {
3292acd9a301SAlan Cox 			end = entry->end;
3293acd9a301SAlan Cox 			rv = KERN_INVALID_ARGUMENT;
3294d2860f22SDoug Moore 			break;
3295acd9a301SAlan Cox 		}
3296acd9a301SAlan Cox 	}
32979a0cdf94SDoug Moore 	need_wakeup = false;
32989a0cdf94SDoug Moore 	if (first_entry == NULL &&
32999a0cdf94SDoug Moore 	    !vm_map_lookup_entry(map, start, &first_entry)) {
33009a0cdf94SDoug Moore 		KASSERT(holes_ok, ("vm_map_unwire: lookup failed"));
330183704cc2SDoug Moore 		prev_entry = first_entry;
330283704cc2SDoug Moore 		entry = vm_map_entry_succ(first_entry);
330383704cc2SDoug Moore 	} else {
330483704cc2SDoug Moore 		prev_entry = vm_map_entry_pred(first_entry);
330583704cc2SDoug Moore 		entry = first_entry;
3306acd9a301SAlan Cox 	}
330783704cc2SDoug Moore 	for (; entry->start < end;
330883704cc2SDoug Moore 	    prev_entry = entry, entry = vm_map_entry_succ(entry)) {
33090acea7dfSKonstantin Belousov 		/*
33109a0cdf94SDoug Moore 		 * If holes_ok was specified, an empty
33110acea7dfSKonstantin Belousov 		 * space in the unwired region could have been mapped
33120acea7dfSKonstantin Belousov 		 * while the map lock was dropped for draining
33130acea7dfSKonstantin Belousov 		 * MAP_ENTRY_IN_TRANSITION.  Moreover, another thread
33140acea7dfSKonstantin Belousov 		 * could be simultaneously wiring this new mapping
33150acea7dfSKonstantin Belousov 		 * entry.  Detect these cases and skip any entries
33160acea7dfSKonstantin Belousov 		 * marked as in transition by us.
33170acea7dfSKonstantin Belousov 		 */
33180acea7dfSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
33190acea7dfSKonstantin Belousov 		    entry->wiring_thread != curthread) {
33209a0cdf94SDoug Moore 			KASSERT(holes_ok,
33210acea7dfSKonstantin Belousov 			    ("vm_map_unwire: !HOLESOK and new/changed entry"));
33220acea7dfSKonstantin Belousov 			continue;
33230acea7dfSKonstantin Belousov 		}
33240acea7dfSKonstantin Belousov 
33253ffbc0cdSAlan Cox 		if (rv == KERN_SUCCESS && (!user_unwire ||
33263ffbc0cdSAlan Cox 		    (entry->eflags & MAP_ENTRY_USER_WIRED))) {
332703462509SAlan Cox 			if (entry->wired_count == 1)
332803462509SAlan Cox 				vm_map_entry_unwire(map, entry);
332903462509SAlan Cox 			else
3330b2f3846aSAlan Cox 				entry->wired_count--;
333154a3a114SMark Johnston 			if (user_unwire)
333254a3a114SMark Johnston 				entry->eflags &= ~MAP_ENTRY_USER_WIRED;
3333b2f3846aSAlan Cox 		}
33340acea7dfSKonstantin Belousov 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3335ff3ae454SKonstantin Belousov 		    ("vm_map_unwire: in-transition flag missing %p", entry));
3336ff3ae454SKonstantin Belousov 		KASSERT(entry->wiring_thread == curthread,
3337ff3ae454SKonstantin Belousov 		    ("vm_map_unwire: alien wire %p", entry));
3338acd9a301SAlan Cox 		entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
33390acea7dfSKonstantin Belousov 		entry->wiring_thread = NULL;
3340acd9a301SAlan Cox 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
3341acd9a301SAlan Cox 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
33429a0cdf94SDoug Moore 			need_wakeup = true;
3343acd9a301SAlan Cox 		}
334483704cc2SDoug Moore 		vm_map_try_merge_entries(map, prev_entry, entry);
3345acd9a301SAlan Cox 	}
334683704cc2SDoug Moore 	vm_map_try_merge_entries(map, prev_entry, entry);
3347acd9a301SAlan Cox 	vm_map_unlock(map);
3348acd9a301SAlan Cox 	if (need_wakeup)
3349acd9a301SAlan Cox 		vm_map_wakeup(map);
3350acd9a301SAlan Cox 	return (rv);
3351acd9a301SAlan Cox }
3352acd9a301SAlan Cox 
335354a3a114SMark Johnston static void
335454a3a114SMark Johnston vm_map_wire_user_count_sub(u_long npages)
335554a3a114SMark Johnston {
335654a3a114SMark Johnston 
335754a3a114SMark Johnston 	atomic_subtract_long(&vm_user_wire_count, npages);
335854a3a114SMark Johnston }
335954a3a114SMark Johnston 
336054a3a114SMark Johnston static bool
336154a3a114SMark Johnston vm_map_wire_user_count_add(u_long npages)
336254a3a114SMark Johnston {
336354a3a114SMark Johnston 	u_long wired;
336454a3a114SMark Johnston 
336554a3a114SMark Johnston 	wired = vm_user_wire_count;
336654a3a114SMark Johnston 	do {
336754a3a114SMark Johnston 		if (npages + wired > vm_page_max_user_wired)
336854a3a114SMark Johnston 			return (false);
336954a3a114SMark Johnston 	} while (!atomic_fcmpset_long(&vm_user_wire_count, &wired,
337054a3a114SMark Johnston 	    npages + wired));
337154a3a114SMark Johnston 
337254a3a114SMark Johnston 	return (true);
337354a3a114SMark Johnston }
337454a3a114SMark Johnston 
3375acd9a301SAlan Cox /*
337666cd575bSAlan Cox  *	vm_map_wire_entry_failure:
337766cd575bSAlan Cox  *
337866cd575bSAlan Cox  *	Handle a wiring failure on the given entry.
337966cd575bSAlan Cox  *
338066cd575bSAlan Cox  *	The map should be locked.
338166cd575bSAlan Cox  */
338266cd575bSAlan Cox static void
338366cd575bSAlan Cox vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
338466cd575bSAlan Cox     vm_offset_t failed_addr)
338566cd575bSAlan Cox {
338666cd575bSAlan Cox 
338766cd575bSAlan Cox 	VM_MAP_ASSERT_LOCKED(map);
338866cd575bSAlan Cox 	KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 &&
338966cd575bSAlan Cox 	    entry->wired_count == 1,
339066cd575bSAlan Cox 	    ("vm_map_wire_entry_failure: entry %p isn't being wired", entry));
339166cd575bSAlan Cox 	KASSERT(failed_addr < entry->end,
339266cd575bSAlan Cox 	    ("vm_map_wire_entry_failure: entry %p was fully wired", entry));
339366cd575bSAlan Cox 
339466cd575bSAlan Cox 	/*
339566cd575bSAlan Cox 	 * If any pages at the start of this entry were successfully wired,
339666cd575bSAlan Cox 	 * then unwire them.
339766cd575bSAlan Cox 	 */
339866cd575bSAlan Cox 	if (failed_addr > entry->start) {
339966cd575bSAlan Cox 		pmap_unwire(map->pmap, entry->start, failed_addr);
340066cd575bSAlan Cox 		vm_object_unwire(entry->object.vm_object, entry->offset,
340166cd575bSAlan Cox 		    failed_addr - entry->start, PQ_ACTIVE);
340266cd575bSAlan Cox 	}
340366cd575bSAlan Cox 
340466cd575bSAlan Cox 	/*
340566cd575bSAlan Cox 	 * Assign an out-of-range value to represent the failure to wire this
340666cd575bSAlan Cox 	 * entry.
340766cd575bSAlan Cox 	 */
340866cd575bSAlan Cox 	entry->wired_count = -1;
340966cd575bSAlan Cox }
341066cd575bSAlan Cox 
341154a3a114SMark Johnston int
341254a3a114SMark Johnston vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
341354a3a114SMark Johnston {
341454a3a114SMark Johnston 	int rv;
341554a3a114SMark Johnston 
341654a3a114SMark Johnston 	vm_map_lock(map);
341754a3a114SMark Johnston 	rv = vm_map_wire_locked(map, start, end, flags);
341854a3a114SMark Johnston 	vm_map_unlock(map);
341954a3a114SMark Johnston 	return (rv);
342054a3a114SMark Johnston }
342154a3a114SMark Johnston 
342266cd575bSAlan Cox /*
342354a3a114SMark Johnston  *	vm_map_wire_locked:
3424e27e17b7SAlan Cox  *
342554a3a114SMark Johnston  *	Implements both kernel and user wiring.  Returns with the map locked,
342654a3a114SMark Johnston  *	the map lock may be dropped.
3427e27e17b7SAlan Cox  */
3428e27e17b7SAlan Cox int
342954a3a114SMark Johnston vm_map_wire_locked(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3430e27e17b7SAlan Cox {
343183704cc2SDoug Moore 	vm_map_entry_t entry, first_entry, next_entry, prev_entry;
343266cd575bSAlan Cox 	vm_offset_t faddr, saved_end, saved_start;
3433e2e80fb3SKonstantin Belousov 	u_long incr, npages;
3434e2e80fb3SKonstantin Belousov 	u_int bidx, last_timestamp;
343512d7cc84SAlan Cox 	int rv;
343683704cc2SDoug Moore 	bool holes_ok, need_wakeup, user_wire;
3437e4cd31ddSJeff Roberson 	vm_prot_t prot;
3438e27e17b7SAlan Cox 
343954a3a114SMark Johnston 	VM_MAP_ASSERT_LOCKED(map);
344054a3a114SMark Johnston 
344179e9451fSKonstantin Belousov 	if (start == end)
344279e9451fSKonstantin Belousov 		return (KERN_SUCCESS);
3443e4cd31ddSJeff Roberson 	prot = 0;
3444e4cd31ddSJeff Roberson 	if (flags & VM_MAP_WIRE_WRITE)
3445e4cd31ddSJeff Roberson 		prot |= VM_PROT_WRITE;
34469a0cdf94SDoug Moore 	holes_ok = (flags & VM_MAP_WIRE_HOLESOK) != 0;
34479a0cdf94SDoug Moore 	user_wire = (flags & VM_MAP_WIRE_USER) != 0;
344812d7cc84SAlan Cox 	VM_MAP_RANGE_CHECK(map, start, end);
3449d1d3f7e1SDoug Moore 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
34509a0cdf94SDoug Moore 		if (holes_ok)
34517cdcf863SDoug Moore 			first_entry = vm_map_entry_succ(first_entry);
3452d1d3f7e1SDoug Moore 		else
345312d7cc84SAlan Cox 			return (KERN_INVALID_ADDRESS);
345412d7cc84SAlan Cox 	}
345583704cc2SDoug Moore 	for (entry = first_entry; entry->start < end; entry = next_entry) {
345612d7cc84SAlan Cox 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
345712d7cc84SAlan Cox 			/*
345812d7cc84SAlan Cox 			 * We have not yet clipped the entry.
345912d7cc84SAlan Cox 			 */
346083704cc2SDoug Moore 			next_entry = vm_map_entry_in_transition(map, start,
346183704cc2SDoug Moore 			    &end, holes_ok, entry);
346283704cc2SDoug Moore 			if (next_entry == NULL) {
346383704cc2SDoug Moore 				if (entry == first_entry)
346412d7cc84SAlan Cox 					return (KERN_INVALID_ADDRESS);
346512d7cc84SAlan Cox 				rv = KERN_INVALID_ADDRESS;
346612d7cc84SAlan Cox 				goto done;
346712d7cc84SAlan Cox 			}
346883704cc2SDoug Moore 			first_entry = (entry == first_entry) ?
346983704cc2SDoug Moore 			    next_entry : NULL;
347012d7cc84SAlan Cox 			continue;
347112d7cc84SAlan Cox 		}
3472e2e80fb3SKonstantin Belousov 		rv = vm_map_clip_start(map, entry, start);
3473e2e80fb3SKonstantin Belousov 		if (rv != KERN_SUCCESS)
3474e2e80fb3SKonstantin Belousov 			goto done;
3475e2e80fb3SKonstantin Belousov 		rv = vm_map_clip_end(map, entry, end);
3476e2e80fb3SKonstantin Belousov 		if (rv != KERN_SUCCESS)
3477e2e80fb3SKonstantin Belousov 			goto done;
3478e2e80fb3SKonstantin Belousov 
347912d7cc84SAlan Cox 		/*
348012d7cc84SAlan Cox 		 * Mark the entry in case the map lock is released.  (See
348112d7cc84SAlan Cox 		 * above.)
348212d7cc84SAlan Cox 		 */
3483ff3ae454SKonstantin Belousov 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
3484ff3ae454SKonstantin Belousov 		    entry->wiring_thread == NULL,
3485ff3ae454SKonstantin Belousov 		    ("owned map entry %p", entry));
348612d7cc84SAlan Cox 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
34870acea7dfSKonstantin Belousov 		entry->wiring_thread = curthread;
3488e4cd31ddSJeff Roberson 		if ((entry->protection & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0
3489e4cd31ddSJeff Roberson 		    || (entry->protection & prot) != prot) {
3490529ab57bSKonstantin Belousov 			entry->eflags |= MAP_ENTRY_WIRE_SKIPPED;
34919a0cdf94SDoug Moore 			if (!holes_ok) {
34926d7e8091SKonstantin Belousov 				end = entry->end;
34936d7e8091SKonstantin Belousov 				rv = KERN_INVALID_ADDRESS;
34946d7e8091SKonstantin Belousov 				goto done;
34956d7e8091SKonstantin Belousov 			}
349638e220e8SDoug Moore 		} else if (entry->wired_count == 0) {
34970ada205eSBrian Feldman 			entry->wired_count++;
349854a3a114SMark Johnston 
349954a3a114SMark Johnston 			npages = atop(entry->end - entry->start);
350054a3a114SMark Johnston 			if (user_wire && !vm_map_wire_user_count_add(npages)) {
350154a3a114SMark Johnston 				vm_map_wire_entry_failure(map, entry,
350254a3a114SMark Johnston 				    entry->start);
350354a3a114SMark Johnston 				end = entry->end;
350454a3a114SMark Johnston 				rv = KERN_RESOURCE_SHORTAGE;
350554a3a114SMark Johnston 				goto done;
350654a3a114SMark Johnston 			}
350766cd575bSAlan Cox 
350812d7cc84SAlan Cox 			/*
350912d7cc84SAlan Cox 			 * Release the map lock, relying on the in-transition
3510a5db445dSMax Laier 			 * mark.  Mark the map busy for fork.
351112d7cc84SAlan Cox 			 */
351254a3a114SMark Johnston 			saved_start = entry->start;
351354a3a114SMark Johnston 			saved_end = entry->end;
3514312df2c1SDoug Moore 			last_timestamp = map->timestamp;
3515e2e80fb3SKonstantin Belousov 			bidx = (entry->eflags & MAP_ENTRY_SPLIT_BOUNDARY_MASK)
3516e2e80fb3SKonstantin Belousov 			    >> MAP_ENTRY_SPLIT_BOUNDARY_SHIFT;
3517e2e80fb3SKonstantin Belousov 			incr =  pagesizes[bidx];
3518a5db445dSMax Laier 			vm_map_busy(map);
351912d7cc84SAlan Cox 			vm_map_unlock(map);
352066cd575bSAlan Cox 
3521e2e80fb3SKonstantin Belousov 			for (faddr = saved_start; faddr < saved_end;
3522e2e80fb3SKonstantin Belousov 			    faddr += incr) {
352366cd575bSAlan Cox 				/*
352466cd575bSAlan Cox 				 * Simulate a fault to get the page and enter
352566cd575bSAlan Cox 				 * it into the physical map.
352666cd575bSAlan Cox 				 */
3527e2e80fb3SKonstantin Belousov 				rv = vm_fault(map, faddr, VM_PROT_NONE,
3528e2e80fb3SKonstantin Belousov 				    VM_FAULT_WIRE, NULL);
3529e2e80fb3SKonstantin Belousov 				if (rv != KERN_SUCCESS)
353066cd575bSAlan Cox 					break;
3531e2e80fb3SKonstantin Belousov 			}
353212d7cc84SAlan Cox 			vm_map_lock(map);
3533a5db445dSMax Laier 			vm_map_unbusy(map);
353412d7cc84SAlan Cox 			if (last_timestamp + 1 != map->timestamp) {
353512d7cc84SAlan Cox 				/*
353612d7cc84SAlan Cox 				 * Look again for the entry because the map was
353712d7cc84SAlan Cox 				 * modified while it was unlocked.  The entry
353812d7cc84SAlan Cox 				 * may have been clipped, but NOT merged or
353912d7cc84SAlan Cox 				 * deleted.
354012d7cc84SAlan Cox 				 */
35419a0cdf94SDoug Moore 				if (!vm_map_lookup_entry(map, saved_start,
354283704cc2SDoug Moore 				    &next_entry))
35439a0cdf94SDoug Moore 					KASSERT(false,
35449a0cdf94SDoug Moore 					    ("vm_map_wire: lookup failed"));
354583704cc2SDoug Moore 				first_entry = (entry == first_entry) ?
354683704cc2SDoug Moore 				    next_entry : NULL;
354783704cc2SDoug Moore 				for (entry = next_entry; entry->end < saved_end;
354883704cc2SDoug Moore 				    entry = vm_map_entry_succ(entry)) {
354966cd575bSAlan Cox 					/*
355066cd575bSAlan Cox 					 * In case of failure, handle entries
355166cd575bSAlan Cox 					 * that were not fully wired here;
355266cd575bSAlan Cox 					 * fully wired entries are handled
355366cd575bSAlan Cox 					 * later.
355466cd575bSAlan Cox 					 */
355566cd575bSAlan Cox 					if (rv != KERN_SUCCESS &&
355666cd575bSAlan Cox 					    faddr < entry->end)
355766cd575bSAlan Cox 						vm_map_wire_entry_failure(map,
355866cd575bSAlan Cox 						    entry, faddr);
355912d7cc84SAlan Cox 				}
356028c58286SAlan Cox 			}
356112d7cc84SAlan Cox 			if (rv != KERN_SUCCESS) {
356266cd575bSAlan Cox 				vm_map_wire_entry_failure(map, entry, faddr);
356354a3a114SMark Johnston 				if (user_wire)
356454a3a114SMark Johnston 					vm_map_wire_user_count_sub(npages);
356512d7cc84SAlan Cox 				end = entry->end;
356612d7cc84SAlan Cox 				goto done;
356712d7cc84SAlan Cox 			}
35680ada205eSBrian Feldman 		} else if (!user_wire ||
35690ada205eSBrian Feldman 			   (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
35700ada205eSBrian Feldman 			entry->wired_count++;
357112d7cc84SAlan Cox 		}
357212d7cc84SAlan Cox 		/*
357312d7cc84SAlan Cox 		 * Check the map for holes in the specified region.
35749a0cdf94SDoug Moore 		 * If holes_ok was specified, skip this check.
357512d7cc84SAlan Cox 		 */
357683704cc2SDoug Moore 		next_entry = vm_map_entry_succ(entry);
35779a0cdf94SDoug Moore 		if (!holes_ok &&
357883704cc2SDoug Moore 		    entry->end < end && next_entry->start > entry->end) {
357912d7cc84SAlan Cox 			end = entry->end;
358012d7cc84SAlan Cox 			rv = KERN_INVALID_ADDRESS;
358112d7cc84SAlan Cox 			goto done;
358212d7cc84SAlan Cox 		}
358312d7cc84SAlan Cox 	}
358412d7cc84SAlan Cox 	rv = KERN_SUCCESS;
358512d7cc84SAlan Cox done:
35869a0cdf94SDoug Moore 	need_wakeup = false;
35879a0cdf94SDoug Moore 	if (first_entry == NULL &&
35889a0cdf94SDoug Moore 	    !vm_map_lookup_entry(map, start, &first_entry)) {
35899a0cdf94SDoug Moore 		KASSERT(holes_ok, ("vm_map_wire: lookup failed"));
359083704cc2SDoug Moore 		prev_entry = first_entry;
359183704cc2SDoug Moore 		entry = vm_map_entry_succ(first_entry);
359283704cc2SDoug Moore 	} else {
359383704cc2SDoug Moore 		prev_entry = vm_map_entry_pred(first_entry);
359483704cc2SDoug Moore 		entry = first_entry;
359512d7cc84SAlan Cox 	}
359683704cc2SDoug Moore 	for (; entry->start < end;
359783704cc2SDoug Moore 	    prev_entry = entry, entry = vm_map_entry_succ(entry)) {
35980acea7dfSKonstantin Belousov 		/*
35999a0cdf94SDoug Moore 		 * If holes_ok was specified, an empty
36000acea7dfSKonstantin Belousov 		 * space in the unwired region could have been mapped
36010acea7dfSKonstantin Belousov 		 * while the map lock was dropped for faulting in the
36020acea7dfSKonstantin Belousov 		 * pages or draining MAP_ENTRY_IN_TRANSITION.
36030acea7dfSKonstantin Belousov 		 * Moreover, another thread could be simultaneously
36040acea7dfSKonstantin Belousov 		 * wiring this new mapping entry.  Detect these cases
3605546bb2d7SKonstantin Belousov 		 * and skip any entries marked as in transition not by us.
3606e2e80fb3SKonstantin Belousov 		 *
3607e2e80fb3SKonstantin Belousov 		 * Another way to get an entry not marked with
3608e2e80fb3SKonstantin Belousov 		 * MAP_ENTRY_IN_TRANSITION is after failed clipping,
3609e2e80fb3SKonstantin Belousov 		 * which set rv to KERN_INVALID_ARGUMENT.
36100acea7dfSKonstantin Belousov 		 */
36110acea7dfSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
36120acea7dfSKonstantin Belousov 		    entry->wiring_thread != curthread) {
3613e2e80fb3SKonstantin Belousov 			KASSERT(holes_ok || rv == KERN_INVALID_ARGUMENT,
36140acea7dfSKonstantin Belousov 			    ("vm_map_wire: !HOLESOK and new/changed entry"));
36150acea7dfSKonstantin Belousov 			continue;
36160acea7dfSKonstantin Belousov 		}
36170acea7dfSKonstantin Belousov 
3618b71f9b0dSDoug Moore 		if ((entry->eflags & MAP_ENTRY_WIRE_SKIPPED) != 0) {
3619b71f9b0dSDoug Moore 			/* do nothing */
3620b71f9b0dSDoug Moore 		} else if (rv == KERN_SUCCESS) {
362112d7cc84SAlan Cox 			if (user_wire)
362212d7cc84SAlan Cox 				entry->eflags |= MAP_ENTRY_USER_WIRED;
362328c58286SAlan Cox 		} else if (entry->wired_count == -1) {
362428c58286SAlan Cox 			/*
362528c58286SAlan Cox 			 * Wiring failed on this entry.  Thus, unwiring is
362628c58286SAlan Cox 			 * unnecessary.
362728c58286SAlan Cox 			 */
362828c58286SAlan Cox 			entry->wired_count = 0;
362903462509SAlan Cox 		} else if (!user_wire ||
363003462509SAlan Cox 		    (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
363166cd575bSAlan Cox 			/*
363266cd575bSAlan Cox 			 * Undo the wiring.  Wiring succeeded on this entry
363366cd575bSAlan Cox 			 * but failed on a later entry.
363466cd575bSAlan Cox 			 */
363554a3a114SMark Johnston 			if (entry->wired_count == 1) {
363603462509SAlan Cox 				vm_map_entry_unwire(map, entry);
363754a3a114SMark Johnston 				if (user_wire)
363854a3a114SMark Johnston 					vm_map_wire_user_count_sub(
363954a3a114SMark Johnston 					    atop(entry->end - entry->start));
364054a3a114SMark Johnston 			} else
364112d7cc84SAlan Cox 				entry->wired_count--;
364212d7cc84SAlan Cox 		}
36430acea7dfSKonstantin Belousov 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
36440acea7dfSKonstantin Belousov 		    ("vm_map_wire: in-transition flag missing %p", entry));
36450acea7dfSKonstantin Belousov 		KASSERT(entry->wiring_thread == curthread,
36460acea7dfSKonstantin Belousov 		    ("vm_map_wire: alien wire %p", entry));
36470acea7dfSKonstantin Belousov 		entry->eflags &= ~(MAP_ENTRY_IN_TRANSITION |
36480acea7dfSKonstantin Belousov 		    MAP_ENTRY_WIRE_SKIPPED);
36490acea7dfSKonstantin Belousov 		entry->wiring_thread = NULL;
365012d7cc84SAlan Cox 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
365112d7cc84SAlan Cox 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
36529a0cdf94SDoug Moore 			need_wakeup = true;
365312d7cc84SAlan Cox 		}
365483704cc2SDoug Moore 		vm_map_try_merge_entries(map, prev_entry, entry);
365512d7cc84SAlan Cox 	}
365683704cc2SDoug Moore 	vm_map_try_merge_entries(map, prev_entry, entry);
365712d7cc84SAlan Cox 	if (need_wakeup)
365812d7cc84SAlan Cox 		vm_map_wakeup(map);
365912d7cc84SAlan Cox 	return (rv);
3660e27e17b7SAlan Cox }
3661e27e17b7SAlan Cox 
3662e27e17b7SAlan Cox /*
3663950f8459SAlan Cox  * vm_map_sync
3664df8bae1dSRodney W. Grimes  *
3665df8bae1dSRodney W. Grimes  * Push any dirty cached pages in the address range to their pager.
3666df8bae1dSRodney W. Grimes  * If syncio is TRUE, dirty pages are written synchronously.
3667df8bae1dSRodney W. Grimes  * If invalidate is TRUE, any cached pages are freed as well.
3668df8bae1dSRodney W. Grimes  *
3669637315edSAlan Cox  * If the size of the region from start to end is zero, we are
3670637315edSAlan Cox  * supposed to flush all modified pages within the region containing
3671637315edSAlan Cox  * start.  Unfortunately, a region can be split or coalesced with
3672637315edSAlan Cox  * neighboring regions, making it difficult to determine what the
3673637315edSAlan Cox  * original region was.  Therefore, we approximate this requirement by
3674637315edSAlan Cox  * flushing the current region containing start.
3675637315edSAlan Cox  *
3676df8bae1dSRodney W. Grimes  * Returns an error if any part of the specified range is not mapped.
3677df8bae1dSRodney W. Grimes  */
3678df8bae1dSRodney W. Grimes int
3679950f8459SAlan Cox vm_map_sync(
36801b40f8c0SMatthew Dillon 	vm_map_t map,
36811b40f8c0SMatthew Dillon 	vm_offset_t start,
36821b40f8c0SMatthew Dillon 	vm_offset_t end,
36831b40f8c0SMatthew Dillon 	boolean_t syncio,
36841b40f8c0SMatthew Dillon 	boolean_t invalidate)
3685df8bae1dSRodney W. Grimes {
36862767c9f3SDoug Moore 	vm_map_entry_t entry, first_entry, next_entry;
3687df8bae1dSRodney W. Grimes 	vm_size_t size;
3688df8bae1dSRodney W. Grimes 	vm_object_t object;
3689a316d390SJohn Dyson 	vm_ooffset_t offset;
3690e53fa61bSKonstantin Belousov 	unsigned int last_timestamp;
3691e2e80fb3SKonstantin Belousov 	int bdry_idx;
3692126d6082SKonstantin Belousov 	boolean_t failed;
3693df8bae1dSRodney W. Grimes 
3694df8bae1dSRodney W. Grimes 	vm_map_lock_read(map);
3695df8bae1dSRodney W. Grimes 	VM_MAP_RANGE_CHECK(map, start, end);
36962767c9f3SDoug Moore 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
3697df8bae1dSRodney W. Grimes 		vm_map_unlock_read(map);
3698df8bae1dSRodney W. Grimes 		return (KERN_INVALID_ADDRESS);
3699d1d3f7e1SDoug Moore 	} else if (start == end) {
37002767c9f3SDoug Moore 		start = first_entry->start;
37012767c9f3SDoug Moore 		end = first_entry->end;
3702df8bae1dSRodney W. Grimes 	}
3703e2e80fb3SKonstantin Belousov 
3704df8bae1dSRodney W. Grimes 	/*
3705e2e80fb3SKonstantin Belousov 	 * Make a first pass to check for user-wired memory, holes,
3706e2e80fb3SKonstantin Belousov 	 * and partial invalidation of largepage mappings.
3707df8bae1dSRodney W. Grimes 	 */
37082767c9f3SDoug Moore 	for (entry = first_entry; entry->start < end; entry = next_entry) {
3709e2e80fb3SKonstantin Belousov 		if (invalidate) {
3710e2e80fb3SKonstantin Belousov 			if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0) {
3711df8bae1dSRodney W. Grimes 				vm_map_unlock_read(map);
3712df8bae1dSRodney W. Grimes 				return (KERN_INVALID_ARGUMENT);
3713df8bae1dSRodney W. Grimes 			}
3714e2e80fb3SKonstantin Belousov 			bdry_idx = (entry->eflags &
3715e2e80fb3SKonstantin Belousov 			    MAP_ENTRY_SPLIT_BOUNDARY_MASK) >>
3716e2e80fb3SKonstantin Belousov 			    MAP_ENTRY_SPLIT_BOUNDARY_SHIFT;
3717e2e80fb3SKonstantin Belousov 			if (bdry_idx != 0 &&
3718e2e80fb3SKonstantin Belousov 			    ((start & (pagesizes[bdry_idx] - 1)) != 0 ||
3719e2e80fb3SKonstantin Belousov 			    (end & (pagesizes[bdry_idx] - 1)) != 0)) {
3720e2e80fb3SKonstantin Belousov 				vm_map_unlock_read(map);
3721e2e80fb3SKonstantin Belousov 				return (KERN_INVALID_ARGUMENT);
3722e2e80fb3SKonstantin Belousov 			}
3723e2e80fb3SKonstantin Belousov 		}
37242767c9f3SDoug Moore 		next_entry = vm_map_entry_succ(entry);
37252767c9f3SDoug Moore 		if (end > entry->end &&
37262767c9f3SDoug Moore 		    entry->end != next_entry->start) {
3727df8bae1dSRodney W. Grimes 			vm_map_unlock_read(map);
3728df8bae1dSRodney W. Grimes 			return (KERN_INVALID_ADDRESS);
3729df8bae1dSRodney W. Grimes 		}
3730df8bae1dSRodney W. Grimes 	}
3731df8bae1dSRodney W. Grimes 
37322cf13952SAlan Cox 	if (invalidate)
3733bc105a67SAlan Cox 		pmap_remove(map->pmap, start, end);
3734126d6082SKonstantin Belousov 	failed = FALSE;
37352cf13952SAlan Cox 
3736df8bae1dSRodney W. Grimes 	/*
3737df8bae1dSRodney W. Grimes 	 * Make a second pass, cleaning/uncaching pages from the indicated
3738df8bae1dSRodney W. Grimes 	 * objects as we go.
3739df8bae1dSRodney W. Grimes 	 */
37402767c9f3SDoug Moore 	for (entry = first_entry; entry->start < end;) {
37412767c9f3SDoug Moore 		offset = entry->offset + (start - entry->start);
37422767c9f3SDoug Moore 		size = (end <= entry->end ? end : entry->end) - start;
37432767c9f3SDoug Moore 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0) {
3744c0877f10SJohn Dyson 			vm_map_t smap;
3745df8bae1dSRodney W. Grimes 			vm_map_entry_t tentry;
3746df8bae1dSRodney W. Grimes 			vm_size_t tsize;
3747df8bae1dSRodney W. Grimes 
37482767c9f3SDoug Moore 			smap = entry->object.sub_map;
3749df8bae1dSRodney W. Grimes 			vm_map_lock_read(smap);
3750df8bae1dSRodney W. Grimes 			(void) vm_map_lookup_entry(smap, offset, &tentry);
3751df8bae1dSRodney W. Grimes 			tsize = tentry->end - offset;
3752df8bae1dSRodney W. Grimes 			if (tsize < size)
3753df8bae1dSRodney W. Grimes 				size = tsize;
3754df8bae1dSRodney W. Grimes 			object = tentry->object.vm_object;
3755df8bae1dSRodney W. Grimes 			offset = tentry->offset + (offset - tentry->start);
3756df8bae1dSRodney W. Grimes 			vm_map_unlock_read(smap);
3757df8bae1dSRodney W. Grimes 		} else {
37582767c9f3SDoug Moore 			object = entry->object.vm_object;
3759df8bae1dSRodney W. Grimes 		}
3760e53fa61bSKonstantin Belousov 		vm_object_reference(object);
3761e53fa61bSKonstantin Belousov 		last_timestamp = map->timestamp;
3762e53fa61bSKonstantin Belousov 		vm_map_unlock_read(map);
3763126d6082SKonstantin Belousov 		if (!vm_object_sync(object, offset, size, syncio, invalidate))
3764126d6082SKonstantin Belousov 			failed = TRUE;
3765df8bae1dSRodney W. Grimes 		start += size;
3766e53fa61bSKonstantin Belousov 		vm_object_deallocate(object);
3767e53fa61bSKonstantin Belousov 		vm_map_lock_read(map);
3768d1d3f7e1SDoug Moore 		if (last_timestamp == map->timestamp ||
37692767c9f3SDoug Moore 		    !vm_map_lookup_entry(map, start, &entry))
37702767c9f3SDoug Moore 			entry = vm_map_entry_succ(entry);
3771df8bae1dSRodney W. Grimes 	}
3772df8bae1dSRodney W. Grimes 
3773df8bae1dSRodney W. Grimes 	vm_map_unlock_read(map);
3774126d6082SKonstantin Belousov 	return (failed ? KERN_FAILURE : KERN_SUCCESS);
3775df8bae1dSRodney W. Grimes }
3776df8bae1dSRodney W. Grimes 
3777df8bae1dSRodney W. Grimes /*
3778df8bae1dSRodney W. Grimes  *	vm_map_entry_unwire:	[ internal use only ]
3779df8bae1dSRodney W. Grimes  *
3780df8bae1dSRodney W. Grimes  *	Make the region specified by this entry pageable.
3781df8bae1dSRodney W. Grimes  *
3782df8bae1dSRodney W. Grimes  *	The map in question should be locked.
3783df8bae1dSRodney W. Grimes  *	[This is the reason for this routine's existence.]
3784df8bae1dSRodney W. Grimes  */
37850362d7d7SJohn Dyson static void
37861b40f8c0SMatthew Dillon vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
3787df8bae1dSRodney W. Grimes {
378854a3a114SMark Johnston 	vm_size_t size;
378903462509SAlan Cox 
379003462509SAlan Cox 	VM_MAP_ASSERT_LOCKED(map);
379103462509SAlan Cox 	KASSERT(entry->wired_count > 0,
379203462509SAlan Cox 	    ("vm_map_entry_unwire: entry %p isn't wired", entry));
379354a3a114SMark Johnston 
379454a3a114SMark Johnston 	size = entry->end - entry->start;
379554a3a114SMark Johnston 	if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0)
379654a3a114SMark Johnston 		vm_map_wire_user_count_sub(atop(size));
379703462509SAlan Cox 	pmap_unwire(map->pmap, entry->start, entry->end);
379854a3a114SMark Johnston 	vm_object_unwire(entry->object.vm_object, entry->offset, size,
379954a3a114SMark Johnston 	    PQ_ACTIVE);
3800df8bae1dSRodney W. Grimes 	entry->wired_count = 0;
3801df8bae1dSRodney W. Grimes }
3802df8bae1dSRodney W. Grimes 
38030b367bd8SKonstantin Belousov static void
38040b367bd8SKonstantin Belousov vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map)
38050b367bd8SKonstantin Belousov {
38060b367bd8SKonstantin Belousov 
38070b367bd8SKonstantin Belousov 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
38080b367bd8SKonstantin Belousov 		vm_object_deallocate(entry->object.vm_object);
38090b367bd8SKonstantin Belousov 	uma_zfree(system_map ? kmapentzone : mapentzone, entry);
38100b367bd8SKonstantin Belousov }
38110b367bd8SKonstantin Belousov 
3812df8bae1dSRodney W. Grimes /*
3813df8bae1dSRodney W. Grimes  *	vm_map_entry_delete:	[ internal use only ]
3814df8bae1dSRodney W. Grimes  *
3815df8bae1dSRodney W. Grimes  *	Deallocate the given entry from the target map.
3816df8bae1dSRodney W. Grimes  */
38170362d7d7SJohn Dyson static void
38181b40f8c0SMatthew Dillon vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
3819df8bae1dSRodney W. Grimes {
382032a89c32SAlan Cox 	vm_object_t object;
382184242cf6SMark Johnston 	vm_pindex_t offidxstart, offidxend, size1;
3822d1780e8dSKonstantin Belousov 	vm_size_t size;
382332a89c32SAlan Cox 
38249f701172SKonstantin Belousov 	vm_map_entry_unlink(map, entry, UNLINK_MERGE_NONE);
38253364c323SKonstantin Belousov 	object = entry->object.vm_object;
382619bd0d9cSKonstantin Belousov 
382719bd0d9cSKonstantin Belousov 	if ((entry->eflags & MAP_ENTRY_GUARD) != 0) {
382819bd0d9cSKonstantin Belousov 		MPASS(entry->cred == NULL);
382919bd0d9cSKonstantin Belousov 		MPASS((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0);
383019bd0d9cSKonstantin Belousov 		MPASS(object == NULL);
383119bd0d9cSKonstantin Belousov 		vm_map_entry_deallocate(entry, map->system_map);
383219bd0d9cSKonstantin Belousov 		return;
383319bd0d9cSKonstantin Belousov 	}
383419bd0d9cSKonstantin Belousov 
38353364c323SKonstantin Belousov 	size = entry->end - entry->start;
38363364c323SKonstantin Belousov 	map->size -= size;
38373364c323SKonstantin Belousov 
3838ef694c1aSEdward Tomasz Napierala 	if (entry->cred != NULL) {
3839ef694c1aSEdward Tomasz Napierala 		swap_release_by_cred(size, entry->cred);
3840ef694c1aSEdward Tomasz Napierala 		crfree(entry->cred);
38413364c323SKonstantin Belousov 	}
3842df8bae1dSRodney W. Grimes 
384363967687SJeff Roberson 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 || object == NULL) {
384463967687SJeff Roberson 		entry->object.vm_object = NULL;
384563967687SJeff Roberson 	} else if ((object->flags & OBJ_ANON) != 0 ||
384663967687SJeff Roberson 	    object == kernel_object) {
3847ef694c1aSEdward Tomasz Napierala 		KASSERT(entry->cred == NULL || object->cred == NULL ||
38483364c323SKonstantin Belousov 		    (entry->eflags & MAP_ENTRY_NEEDS_COPY),
3849ef694c1aSEdward Tomasz Napierala 		    ("OVERCOMMIT vm_map_entry_delete: both cred %p", entry));
385032a89c32SAlan Cox 		offidxstart = OFF_TO_IDX(entry->offset);
385184242cf6SMark Johnston 		offidxend = offidxstart + atop(size);
385289f6b863SAttilio Rao 		VM_OBJECT_WLOCK(object);
385363967687SJeff Roberson 		if (object->ref_count != 1 &&
385463967687SJeff Roberson 		    ((object->flags & OBJ_ONEMAPPING) != 0 ||
38552e47807cSJeff Roberson 		    object == kernel_object)) {
385632a89c32SAlan Cox 			vm_object_collapse(object);
38576bbee8e2SAlan Cox 
38586bbee8e2SAlan Cox 			/*
38596bbee8e2SAlan Cox 			 * The option OBJPR_NOTMAPPED can be passed here
38606bbee8e2SAlan Cox 			 * because vm_map_delete() already performed
38616bbee8e2SAlan Cox 			 * pmap_remove() on the only mapping to this range
38626bbee8e2SAlan Cox 			 * of pages.
38636bbee8e2SAlan Cox 			 */
38646bbee8e2SAlan Cox 			vm_object_page_remove(object, offidxstart, offidxend,
38656bbee8e2SAlan Cox 			    OBJPR_NOTMAPPED);
386632a89c32SAlan Cox 			if (offidxend >= object->size &&
38673364c323SKonstantin Belousov 			    offidxstart < object->size) {
38683364c323SKonstantin Belousov 				size1 = object->size;
386932a89c32SAlan Cox 				object->size = offidxstart;
3870ef694c1aSEdward Tomasz Napierala 				if (object->cred != NULL) {
38713364c323SKonstantin Belousov 					size1 -= object->size;
38723364c323SKonstantin Belousov 					KASSERT(object->charge >= ptoa(size1),
38739a4ee196SKonstantin Belousov 					    ("object %p charge < 0", object));
38749a4ee196SKonstantin Belousov 					swap_release_by_cred(ptoa(size1),
38759a4ee196SKonstantin Belousov 					    object->cred);
38763364c323SKonstantin Belousov 					object->charge -= ptoa(size1);
38773364c323SKonstantin Belousov 				}
38783364c323SKonstantin Belousov 			}
387932a89c32SAlan Cox 		}
388089f6b863SAttilio Rao 		VM_OBJECT_WUNLOCK(object);
388163967687SJeff Roberson 	}
38820b367bd8SKonstantin Belousov 	if (map->system_map)
38830b367bd8SKonstantin Belousov 		vm_map_entry_deallocate(entry, TRUE);
38840b367bd8SKonstantin Belousov 	else {
38857cdcf863SDoug Moore 		entry->defer_next = curthread->td_map_def_user;
38860b367bd8SKonstantin Belousov 		curthread->td_map_def_user = entry;
38870b367bd8SKonstantin Belousov 	}
3888df8bae1dSRodney W. Grimes }
3889df8bae1dSRodney W. Grimes 
3890df8bae1dSRodney W. Grimes /*
3891df8bae1dSRodney W. Grimes  *	vm_map_delete:	[ internal use only ]
3892df8bae1dSRodney W. Grimes  *
3893df8bae1dSRodney W. Grimes  *	Deallocates the given address range from the target
3894df8bae1dSRodney W. Grimes  *	map.
3895df8bae1dSRodney W. Grimes  */
3896df8bae1dSRodney W. Grimes int
3897655c3490SKonstantin Belousov vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
3898df8bae1dSRodney W. Grimes {
3899e2e80fb3SKonstantin Belousov 	vm_map_entry_t entry, next_entry, scratch_entry;
3900e2e80fb3SKonstantin Belousov 	int rv;
3901df8bae1dSRodney W. Grimes 
39023a0916b8SKonstantin Belousov 	VM_MAP_ASSERT_LOCKED(map);
39038a64110eSConrad Meyer 
390479e9451fSKonstantin Belousov 	if (start == end)
390579e9451fSKonstantin Belousov 		return (KERN_SUCCESS);
39063a0916b8SKonstantin Belousov 
3907df8bae1dSRodney W. Grimes 	/*
3908c7b23459SDoug Moore 	 * Find the start of the region, and clip it.
3909c7b23459SDoug Moore 	 * Step through all entries in this region.
3910df8bae1dSRodney W. Grimes 	 */
3911e2e80fb3SKonstantin Belousov 	rv = vm_map_lookup_clip_start(map, start, &entry, &scratch_entry);
3912e2e80fb3SKonstantin Belousov 	if (rv != KERN_SUCCESS)
3913e2e80fb3SKonstantin Belousov 		return (rv);
3914e2e80fb3SKonstantin Belousov 	for (; entry->start < end; entry = next_entry) {
391573b2baceSAlan Cox 		/*
391673b2baceSAlan Cox 		 * Wait for wiring or unwiring of an entry to complete.
39177c938963SBrian Feldman 		 * Also wait for any system wirings to disappear on
39187c938963SBrian Feldman 		 * user maps.
391973b2baceSAlan Cox 		 */
39207c938963SBrian Feldman 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
39217c938963SBrian Feldman 		    (vm_map_pmap(map) != kernel_pmap &&
39227c938963SBrian Feldman 		    vm_map_entry_system_wired_count(entry) != 0)) {
392373b2baceSAlan Cox 			unsigned int last_timestamp;
392473b2baceSAlan Cox 			vm_offset_t saved_start;
392573b2baceSAlan Cox 
392673b2baceSAlan Cox 			saved_start = entry->start;
392773b2baceSAlan Cox 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
392873b2baceSAlan Cox 			last_timestamp = map->timestamp;
39298ce2d00aSPawel Jakub Dawidek 			(void) vm_map_unlock_and_wait(map, 0);
393073b2baceSAlan Cox 			vm_map_lock(map);
3931d1d3f7e1SDoug Moore 			if (last_timestamp + 1 != map->timestamp) {
393273b2baceSAlan Cox 				/*
393373b2baceSAlan Cox 				 * Look again for the entry because the map was
3934d1d3f7e1SDoug Moore 				 * modified while it was unlocked.
3935d1d3f7e1SDoug Moore 				 * Specifically, the entry may have been
3936d1d3f7e1SDoug Moore 				 * clipped, merged, or deleted.
393773b2baceSAlan Cox 				 */
3938e2e80fb3SKonstantin Belousov 				rv = vm_map_lookup_clip_start(map, saved_start,
3939e2e80fb3SKonstantin Belousov 				    &next_entry, &scratch_entry);
3940e2e80fb3SKonstantin Belousov 				if (rv != KERN_SUCCESS)
3941e2e80fb3SKonstantin Belousov 					break;
3942c7b23459SDoug Moore 			} else
3943c7b23459SDoug Moore 				next_entry = entry;
394473b2baceSAlan Cox 			continue;
394573b2baceSAlan Cox 		}
3946e2e80fb3SKonstantin Belousov 
3947e2e80fb3SKonstantin Belousov 		/* XXXKIB or delete to the upper superpage boundary ? */
3948e2e80fb3SKonstantin Belousov 		rv = vm_map_clip_end(map, entry, end);
3949e2e80fb3SKonstantin Belousov 		if (rv != KERN_SUCCESS)
3950e2e80fb3SKonstantin Belousov 			break;
3951c7b23459SDoug Moore 		next_entry = vm_map_entry_succ(entry);
3952df8bae1dSRodney W. Grimes 
3953df8bae1dSRodney W. Grimes 		/*
39540d94caffSDavid Greenman 		 * Unwire before removing addresses from the pmap; otherwise,
39550d94caffSDavid Greenman 		 * unwiring will put the entries back in the pmap.
3956df8bae1dSRodney W. Grimes 		 */
3957be7be412SKonstantin Belousov 		if (entry->wired_count != 0)
3958df8bae1dSRodney W. Grimes 			vm_map_entry_unwire(map, entry);
3959df8bae1dSRodney W. Grimes 
396032f0fefcSKonstantin Belousov 		/*
396132f0fefcSKonstantin Belousov 		 * Remove mappings for the pages, but only if the
396232f0fefcSKonstantin Belousov 		 * mappings could exist.  For instance, it does not
396332f0fefcSKonstantin Belousov 		 * make sense to call pmap_remove() for guard entries.
396432f0fefcSKonstantin Belousov 		 */
396532f0fefcSKonstantin Belousov 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 ||
396632f0fefcSKonstantin Belousov 		    entry->object.vm_object != NULL)
396732a89c32SAlan Cox 			pmap_remove(map->pmap, entry->start, entry->end);
3968df8bae1dSRodney W. Grimes 
3969fa50a355SKonstantin Belousov 		if (entry->end == map->anon_loc)
3970fa50a355SKonstantin Belousov 			map->anon_loc = entry->start;
3971fa50a355SKonstantin Belousov 
3972df8bae1dSRodney W. Grimes 		/*
3973e608cc3cSKonstantin Belousov 		 * Delete the entry only after removing all pmap
3974e608cc3cSKonstantin Belousov 		 * entries pointing to its pages.  (Otherwise, its
3975e608cc3cSKonstantin Belousov 		 * page frames may be reallocated, and any modify bits
3976e608cc3cSKonstantin Belousov 		 * will be set in the wrong object!)
3977df8bae1dSRodney W. Grimes 		 */
3978df8bae1dSRodney W. Grimes 		vm_map_entry_delete(map, entry);
3979df8bae1dSRodney W. Grimes 	}
3980e2e80fb3SKonstantin Belousov 	return (rv);
3981df8bae1dSRodney W. Grimes }
3982df8bae1dSRodney W. Grimes 
3983df8bae1dSRodney W. Grimes /*
3984df8bae1dSRodney W. Grimes  *	vm_map_remove:
3985df8bae1dSRodney W. Grimes  *
3986df8bae1dSRodney W. Grimes  *	Remove the given address range from the target map.
3987df8bae1dSRodney W. Grimes  *	This is the exported form of vm_map_delete.
3988df8bae1dSRodney W. Grimes  */
3989df8bae1dSRodney W. Grimes int
39901b40f8c0SMatthew Dillon vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
3991df8bae1dSRodney W. Grimes {
39926eaee3feSAlan Cox 	int result;
3993df8bae1dSRodney W. Grimes 
3994df8bae1dSRodney W. Grimes 	vm_map_lock(map);
3995df8bae1dSRodney W. Grimes 	VM_MAP_RANGE_CHECK(map, start, end);
3996655c3490SKonstantin Belousov 	result = vm_map_delete(map, start, end);
3997df8bae1dSRodney W. Grimes 	vm_map_unlock(map);
3998df8bae1dSRodney W. Grimes 	return (result);
3999df8bae1dSRodney W. Grimes }
4000df8bae1dSRodney W. Grimes 
4001df8bae1dSRodney W. Grimes /*
4002df8bae1dSRodney W. Grimes  *	vm_map_check_protection:
4003df8bae1dSRodney W. Grimes  *
40042d5c7e45SMatthew Dillon  *	Assert that the target map allows the specified privilege on the
40052d5c7e45SMatthew Dillon  *	entire address region given.  The entire region must be allocated.
40062d5c7e45SMatthew Dillon  *
40072d5c7e45SMatthew Dillon  *	WARNING!  This code does not and should not check whether the
40082d5c7e45SMatthew Dillon  *	contents of the region is accessible.  For example a smaller file
40092d5c7e45SMatthew Dillon  *	might be mapped into a larger address space.
40102d5c7e45SMatthew Dillon  *
40112d5c7e45SMatthew Dillon  *	NOTE!  This code is also called by munmap().
4012d8834602SAlan Cox  *
4013d8834602SAlan Cox  *	The map must be locked.  A read lock is sufficient.
4014df8bae1dSRodney W. Grimes  */
40150d94caffSDavid Greenman boolean_t
4016b9dcd593SBruce Evans vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
4017b9dcd593SBruce Evans 			vm_prot_t protection)
4018df8bae1dSRodney W. Grimes {
4019c0877f10SJohn Dyson 	vm_map_entry_t entry;
4020d1d3f7e1SDoug Moore 	vm_map_entry_t tmp_entry;
4021df8bae1dSRodney W. Grimes 
4022d1d3f7e1SDoug Moore 	if (!vm_map_lookup_entry(map, start, &tmp_entry))
4023df8bae1dSRodney W. Grimes 		return (FALSE);
4024d1d3f7e1SDoug Moore 	entry = tmp_entry;
4025df8bae1dSRodney W. Grimes 
4026df8bae1dSRodney W. Grimes 	while (start < end) {
4027df8bae1dSRodney W. Grimes 		/*
4028df8bae1dSRodney W. Grimes 		 * No holes allowed!
4029df8bae1dSRodney W. Grimes 		 */
4030d8834602SAlan Cox 		if (start < entry->start)
4031df8bae1dSRodney W. Grimes 			return (FALSE);
4032df8bae1dSRodney W. Grimes 		/*
4033df8bae1dSRodney W. Grimes 		 * Check protection associated with entry.
4034df8bae1dSRodney W. Grimes 		 */
4035d8834602SAlan Cox 		if ((entry->protection & protection) != protection)
4036df8bae1dSRodney W. Grimes 			return (FALSE);
4037df8bae1dSRodney W. Grimes 		/* go to next entry */
4038df8bae1dSRodney W. Grimes 		start = entry->end;
40397cdcf863SDoug Moore 		entry = vm_map_entry_succ(entry);
4040df8bae1dSRodney W. Grimes 	}
4041df8bae1dSRodney W. Grimes 	return (TRUE);
4042df8bae1dSRodney W. Grimes }
4043df8bae1dSRodney W. Grimes 
40444d987866SJeff Roberson /*
40454d987866SJeff Roberson  *
4046886b9021SJeff Roberson  *	vm_map_copy_swap_object:
40474d987866SJeff Roberson  *
4048886b9021SJeff Roberson  *	Copies a swap-backed object from an existing map entry to a
40494d987866SJeff Roberson  *	new one.  Carries forward the swap charge.  May change the
40504d987866SJeff Roberson  *	src object on return.
40514d987866SJeff Roberson  */
40524d987866SJeff Roberson static void
4053886b9021SJeff Roberson vm_map_copy_swap_object(vm_map_entry_t src_entry, vm_map_entry_t dst_entry,
40544d987866SJeff Roberson     vm_offset_t size, vm_ooffset_t *fork_charge)
40554d987866SJeff Roberson {
40564d987866SJeff Roberson 	vm_object_t src_object;
40574d987866SJeff Roberson 	struct ucred *cred;
40584d987866SJeff Roberson 	int charged;
40594d987866SJeff Roberson 
40604d987866SJeff Roberson 	src_object = src_entry->object.vm_object;
40614d987866SJeff Roberson 	charged = ENTRY_CHARGED(src_entry);
4062d966c761SJeff Roberson 	if ((src_object->flags & OBJ_ANON) != 0) {
4063d966c761SJeff Roberson 		VM_OBJECT_WLOCK(src_object);
40644d987866SJeff Roberson 		vm_object_collapse(src_object);
40654d987866SJeff Roberson 		if ((src_object->flags & OBJ_ONEMAPPING) != 0) {
40664d987866SJeff Roberson 			vm_object_split(src_entry);
40674d987866SJeff Roberson 			src_object = src_entry->object.vm_object;
40684d987866SJeff Roberson 		}
40694d987866SJeff Roberson 		vm_object_reference_locked(src_object);
40704d987866SJeff Roberson 		vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
4071d966c761SJeff Roberson 		VM_OBJECT_WUNLOCK(src_object);
4072d966c761SJeff Roberson 	} else
4073d966c761SJeff Roberson 		vm_object_reference(src_object);
40744d987866SJeff Roberson 	if (src_entry->cred != NULL &&
40754d987866SJeff Roberson 	    !(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
40764d987866SJeff Roberson 		KASSERT(src_object->cred == NULL,
40774d987866SJeff Roberson 		    ("OVERCOMMIT: vm_map_copy_anon_entry: cred %p",
40784d987866SJeff Roberson 		     src_object));
40794d987866SJeff Roberson 		src_object->cred = src_entry->cred;
40804d987866SJeff Roberson 		src_object->charge = size;
40814d987866SJeff Roberson 	}
40824d987866SJeff Roberson 	dst_entry->object.vm_object = src_object;
40834d987866SJeff Roberson 	if (charged) {
40844d987866SJeff Roberson 		cred = curthread->td_ucred;
40854d987866SJeff Roberson 		crhold(cred);
40864d987866SJeff Roberson 		dst_entry->cred = cred;
40874d987866SJeff Roberson 		*fork_charge += size;
40884d987866SJeff Roberson 		if (!(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
40894d987866SJeff Roberson 			crhold(cred);
40904d987866SJeff Roberson 			src_entry->cred = cred;
40914d987866SJeff Roberson 			*fork_charge += size;
40924d987866SJeff Roberson 		}
40934d987866SJeff Roberson 	}
40944d987866SJeff Roberson }
40954d987866SJeff Roberson 
409686524867SJohn Dyson /*
4097df8bae1dSRodney W. Grimes  *	vm_map_copy_entry:
4098df8bae1dSRodney W. Grimes  *
4099df8bae1dSRodney W. Grimes  *	Copies the contents of the source entry to the destination
4100df8bae1dSRodney W. Grimes  *	entry.  The entries *must* be aligned properly.
4101df8bae1dSRodney W. Grimes  */
4102f708ef1bSPoul-Henning Kamp static void
41031b40f8c0SMatthew Dillon vm_map_copy_entry(
41041b40f8c0SMatthew Dillon 	vm_map_t src_map,
41051b40f8c0SMatthew Dillon 	vm_map_t dst_map,
41061b40f8c0SMatthew Dillon 	vm_map_entry_t src_entry,
41073364c323SKonstantin Belousov 	vm_map_entry_t dst_entry,
41083364c323SKonstantin Belousov 	vm_ooffset_t *fork_charge)
4109df8bae1dSRodney W. Grimes {
4110c0877f10SJohn Dyson 	vm_object_t src_object;
411184110e7eSKonstantin Belousov 	vm_map_entry_t fake_entry;
41123364c323SKonstantin Belousov 	vm_offset_t size;
4113c0877f10SJohn Dyson 
41143a0916b8SKonstantin Belousov 	VM_MAP_ASSERT_LOCKED(dst_map);
41153a0916b8SKonstantin Belousov 
41169fdfe602SMatthew Dillon 	if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
4117df8bae1dSRodney W. Grimes 		return;
4118df8bae1dSRodney W. Grimes 
4119afaa41f6SAlan Cox 	if (src_entry->wired_count == 0 ||
4120afaa41f6SAlan Cox 	    (src_entry->protection & VM_PROT_WRITE) == 0) {
4121df8bae1dSRodney W. Grimes 		/*
41220d94caffSDavid Greenman 		 * If the source entry is marked needs_copy, it is already
41230d94caffSDavid Greenman 		 * write-protected.
4124df8bae1dSRodney W. Grimes 		 */
4125d9a9209aSAlan Cox 		if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0 &&
4126d9a9209aSAlan Cox 		    (src_entry->protection & VM_PROT_WRITE) != 0) {
4127df8bae1dSRodney W. Grimes 			pmap_protect(src_map->pmap,
4128df8bae1dSRodney W. Grimes 			    src_entry->start,
4129df8bae1dSRodney W. Grimes 			    src_entry->end,
4130df8bae1dSRodney W. Grimes 			    src_entry->protection & ~VM_PROT_WRITE);
4131df8bae1dSRodney W. Grimes 		}
4132b18bfc3dSJohn Dyson 
4133df8bae1dSRodney W. Grimes 		/*
4134df8bae1dSRodney W. Grimes 		 * Make a copy of the object.
4135df8bae1dSRodney W. Grimes 		 */
41363364c323SKonstantin Belousov 		size = src_entry->end - src_entry->start;
41378aef1712SMatthew Dillon 		if ((src_object = src_entry->object.vm_object) != NULL) {
4138*0cb2610eSMark Johnston 			if ((src_object->flags & OBJ_SWAP) != 0) {
4139886b9021SJeff Roberson 				vm_map_copy_swap_object(src_entry, dst_entry,
41404d987866SJeff Roberson 				    size, fork_charge);
41414d987866SJeff Roberson 				/* May have split/collapsed, reload obj. */
41424d987866SJeff Roberson 				src_object = src_entry->object.vm_object;
41434d987866SJeff Roberson 			} else {
41444d987866SJeff Roberson 				vm_object_reference(src_object);
4145c0877f10SJohn Dyson 				dst_entry->object.vm_object = src_object;
41463364c323SKonstantin Belousov 			}
41479a4ee196SKonstantin Belousov 			src_entry->eflags |= MAP_ENTRY_COW |
41489a4ee196SKonstantin Belousov 			    MAP_ENTRY_NEEDS_COPY;
41499a4ee196SKonstantin Belousov 			dst_entry->eflags |= MAP_ENTRY_COW |
41509a4ee196SKonstantin Belousov 			    MAP_ENTRY_NEEDS_COPY;
4151b18bfc3dSJohn Dyson 			dst_entry->offset = src_entry->offset;
4152fe7bcbafSKyle Evans 			if (src_entry->eflags & MAP_ENTRY_WRITECNT) {
415384110e7eSKonstantin Belousov 				/*
4154fe7bcbafSKyle Evans 				 * MAP_ENTRY_WRITECNT cannot
415584110e7eSKonstantin Belousov 				 * indicate write reference from
415684110e7eSKonstantin Belousov 				 * src_entry, since the entry is
415784110e7eSKonstantin Belousov 				 * marked as needs copy.  Allocate a
415884110e7eSKonstantin Belousov 				 * fake entry that is used to
4159fe7bcbafSKyle Evans 				 * decrement object->un_pager writecount
416084110e7eSKonstantin Belousov 				 * at the appropriate time.  Attach
416184110e7eSKonstantin Belousov 				 * fake_entry to the deferred list.
416284110e7eSKonstantin Belousov 				 */
416384110e7eSKonstantin Belousov 				fake_entry = vm_map_entry_create(dst_map);
4164fe7bcbafSKyle Evans 				fake_entry->eflags = MAP_ENTRY_WRITECNT;
4165fe7bcbafSKyle Evans 				src_entry->eflags &= ~MAP_ENTRY_WRITECNT;
416684110e7eSKonstantin Belousov 				vm_object_reference(src_object);
416784110e7eSKonstantin Belousov 				fake_entry->object.vm_object = src_object;
416884110e7eSKonstantin Belousov 				fake_entry->start = src_entry->start;
416984110e7eSKonstantin Belousov 				fake_entry->end = src_entry->end;
41707cdcf863SDoug Moore 				fake_entry->defer_next =
41717cdcf863SDoug Moore 				    curthread->td_map_def_user;
417284110e7eSKonstantin Belousov 				curthread->td_map_def_user = fake_entry;
417384110e7eSKonstantin Belousov 			}
41740ec97ffcSKonstantin Belousov 
41750ec97ffcSKonstantin Belousov 			pmap_copy(dst_map->pmap, src_map->pmap,
41760ec97ffcSKonstantin Belousov 			    dst_entry->start, dst_entry->end - dst_entry->start,
41770ec97ffcSKonstantin Belousov 			    src_entry->start);
4178b18bfc3dSJohn Dyson 		} else {
4179b18bfc3dSJohn Dyson 			dst_entry->object.vm_object = NULL;
4180b18bfc3dSJohn Dyson 			dst_entry->offset = 0;
4181ef694c1aSEdward Tomasz Napierala 			if (src_entry->cred != NULL) {
4182ef694c1aSEdward Tomasz Napierala 				dst_entry->cred = curthread->td_ucred;
4183ef694c1aSEdward Tomasz Napierala 				crhold(dst_entry->cred);
41843364c323SKonstantin Belousov 				*fork_charge += size;
41853364c323SKonstantin Belousov 			}
4186b18bfc3dSJohn Dyson 		}
41870d94caffSDavid Greenman 	} else {
4188df8bae1dSRodney W. Grimes 		/*
4189afaa41f6SAlan Cox 		 * We don't want to make writeable wired pages copy-on-write.
4190afaa41f6SAlan Cox 		 * Immediately copy these pages into the new map by simulating
4191afaa41f6SAlan Cox 		 * page faults.  The new pages are pageable.
4192df8bae1dSRodney W. Grimes 		 */
4193121fd461SKonstantin Belousov 		vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry,
4194121fd461SKonstantin Belousov 		    fork_charge);
4195df8bae1dSRodney W. Grimes 	}
4196df8bae1dSRodney W. Grimes }
4197df8bae1dSRodney W. Grimes 
4198df8bae1dSRodney W. Grimes /*
41992a7be1b6SBrian Feldman  * vmspace_map_entry_forked:
42002a7be1b6SBrian Feldman  * Update the newly-forked vmspace each time a map entry is inherited
42012a7be1b6SBrian Feldman  * or copied.  The values for vm_dsize and vm_tsize are approximate
42022a7be1b6SBrian Feldman  * (and mostly-obsolete ideas in the face of mmap(2) et al.)
42032a7be1b6SBrian Feldman  */
42042a7be1b6SBrian Feldman static void
42052a7be1b6SBrian Feldman vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
42062a7be1b6SBrian Feldman     vm_map_entry_t entry)
42072a7be1b6SBrian Feldman {
42082a7be1b6SBrian Feldman 	vm_size_t entrysize;
42092a7be1b6SBrian Feldman 	vm_offset_t newend;
42102a7be1b6SBrian Feldman 
421119bd0d9cSKonstantin Belousov 	if ((entry->eflags & MAP_ENTRY_GUARD) != 0)
421219bd0d9cSKonstantin Belousov 		return;
42132a7be1b6SBrian Feldman 	entrysize = entry->end - entry->start;
42142a7be1b6SBrian Feldman 	vm2->vm_map.size += entrysize;
42152a7be1b6SBrian Feldman 	if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
42162a7be1b6SBrian Feldman 		vm2->vm_ssize += btoc(entrysize);
42172a7be1b6SBrian Feldman 	} else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
42182a7be1b6SBrian Feldman 	    entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
4219b351299cSAndrew Gallatin 		newend = MIN(entry->end,
42202a7be1b6SBrian Feldman 		    (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
42212a7be1b6SBrian Feldman 		vm2->vm_dsize += btoc(newend - entry->start);
42222a7be1b6SBrian Feldman 	} else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
42232a7be1b6SBrian Feldman 	    entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
4224b351299cSAndrew Gallatin 		newend = MIN(entry->end,
42252a7be1b6SBrian Feldman 		    (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
42262a7be1b6SBrian Feldman 		vm2->vm_tsize += btoc(newend - entry->start);
42272a7be1b6SBrian Feldman 	}
42282a7be1b6SBrian Feldman }
42292a7be1b6SBrian Feldman 
42302a7be1b6SBrian Feldman /*
4231df8bae1dSRodney W. Grimes  * vmspace_fork:
4232df8bae1dSRodney W. Grimes  * Create a new process vmspace structure and vm_map
4233df8bae1dSRodney W. Grimes  * based on those of an existing process.  The new map
4234df8bae1dSRodney W. Grimes  * is based on the old map, according to the inheritance
4235df8bae1dSRodney W. Grimes  * values on the regions in that map.
4236df8bae1dSRodney W. Grimes  *
42372a7be1b6SBrian Feldman  * XXX It might be worth coalescing the entries added to the new vmspace.
42382a7be1b6SBrian Feldman  *
4239df8bae1dSRodney W. Grimes  * The source map must not be locked.
4240df8bae1dSRodney W. Grimes  */
4241df8bae1dSRodney W. Grimes struct vmspace *
42423364c323SKonstantin Belousov vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
4243df8bae1dSRodney W. Grimes {
4244c0877f10SJohn Dyson 	struct vmspace *vm2;
424579e53838SAlan Cox 	vm_map_t new_map, old_map;
424679e53838SAlan Cox 	vm_map_entry_t new_entry, old_entry;
4247de5f6a77SJohn Dyson 	vm_object_t object;
4248b8ebd99aSJohn Baldwin 	int error, locked __diagused;
424919bd0d9cSKonstantin Belousov 	vm_inherit_t inh;
4250df8bae1dSRodney W. Grimes 
425179e53838SAlan Cox 	old_map = &vm1->vm_map;
425279e53838SAlan Cox 	/* Copy immutable fields of vm1 to vm2. */
42536e00f3a3SKonstantin Belousov 	vm2 = vmspace_alloc(vm_map_min(old_map), vm_map_max(old_map),
42546e00f3a3SKonstantin Belousov 	    pmap_pinit);
425589b57fcfSKonstantin Belousov 	if (vm2 == NULL)
425679e53838SAlan Cox 		return (NULL);
4257e7a9df16SKonstantin Belousov 
42582a7be1b6SBrian Feldman 	vm2->vm_taddr = vm1->vm_taddr;
42592a7be1b6SBrian Feldman 	vm2->vm_daddr = vm1->vm_daddr;
42602a7be1b6SBrian Feldman 	vm2->vm_maxsaddr = vm1->vm_maxsaddr;
426146d35d41SMark Johnston 	vm2->vm_stacktop = vm1->vm_stacktop;
426279e53838SAlan Cox 	vm_map_lock(old_map);
426379e53838SAlan Cox 	if (old_map->busy)
426479e53838SAlan Cox 		vm_map_wait_busy(old_map);
426579e53838SAlan Cox 	new_map = &vm2->vm_map;
42661fac7d7fSKonstantin Belousov 	locked = vm_map_trylock(new_map); /* trylock to silence WITNESS */
42671fac7d7fSKonstantin Belousov 	KASSERT(locked, ("vmspace_fork: lock failed"));
4268df8bae1dSRodney W. Grimes 
4269e7a9df16SKonstantin Belousov 	error = pmap_vmspace_copy(new_map->pmap, old_map->pmap);
4270e7a9df16SKonstantin Belousov 	if (error != 0) {
4271e7a9df16SKonstantin Belousov 		sx_xunlock(&old_map->lock);
4272e7a9df16SKonstantin Belousov 		sx_xunlock(&new_map->lock);
4273e7a9df16SKonstantin Belousov 		vm_map_process_deferred();
4274e7a9df16SKonstantin Belousov 		vmspace_free(vm2);
4275e7a9df16SKonstantin Belousov 		return (NULL);
4276e7a9df16SKonstantin Belousov 	}
4277e7a9df16SKonstantin Belousov 
4278fa50a355SKonstantin Belousov 	new_map->anon_loc = old_map->anon_loc;
42799402bb44SKonstantin Belousov 	new_map->flags |= old_map->flags & (MAP_ASLR | MAP_ASLR_IGNSTART |
42801811c1e9SMark Johnston 	    MAP_ASLR_STACK | MAP_WXORX);
4281e7a9df16SKonstantin Belousov 
42822767c9f3SDoug Moore 	VM_MAP_ENTRY_FOREACH(old_entry, old_map) {
42832767c9f3SDoug Moore 		if ((old_entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
4284df8bae1dSRodney W. Grimes 			panic("vm_map_fork: encountered a submap");
4285df8bae1dSRodney W. Grimes 
428619bd0d9cSKonstantin Belousov 		inh = old_entry->inheritance;
428719bd0d9cSKonstantin Belousov 		if ((old_entry->eflags & MAP_ENTRY_GUARD) != 0 &&
428819bd0d9cSKonstantin Belousov 		    inh != VM_INHERIT_NONE)
428919bd0d9cSKonstantin Belousov 			inh = VM_INHERIT_COPY;
429019bd0d9cSKonstantin Belousov 
429119bd0d9cSKonstantin Belousov 		switch (inh) {
4292df8bae1dSRodney W. Grimes 		case VM_INHERIT_NONE:
4293df8bae1dSRodney W. Grimes 			break;
4294df8bae1dSRodney W. Grimes 
4295df8bae1dSRodney W. Grimes 		case VM_INHERIT_SHARE:
4296df8bae1dSRodney W. Grimes 			/*
42972767c9f3SDoug Moore 			 * Clone the entry, creating the shared object if
42982767c9f3SDoug Moore 			 * necessary.
4299fed9a903SJohn Dyson 			 */
4300fed9a903SJohn Dyson 			object = old_entry->object.vm_object;
4301fed9a903SJohn Dyson 			if (object == NULL) {
4302af1d6d6aSDoug Moore 				vm_map_entry_back(old_entry);
4303af1d6d6aSDoug Moore 				object = old_entry->object.vm_object;
43049a2f6362SAlan Cox 			}
43059a2f6362SAlan Cox 
43069a2f6362SAlan Cox 			/*
43079a2f6362SAlan Cox 			 * Add the reference before calling vm_object_shadow
43089a2f6362SAlan Cox 			 * to insure that a shadow object is created.
43099a2f6362SAlan Cox 			 */
43109a2f6362SAlan Cox 			vm_object_reference(object);
43119a2f6362SAlan Cox 			if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
43125069bf57SJohn Dyson 				vm_object_shadow(&old_entry->object.vm_object,
43135069bf57SJohn Dyson 				    &old_entry->offset,
431467388836SKonstantin Belousov 				    old_entry->end - old_entry->start,
431567388836SKonstantin Belousov 				    old_entry->cred,
4316d30344bdSIan Dowse 				    /* Transfer the second reference too. */
431767388836SKonstantin Belousov 				    true);
431867388836SKonstantin Belousov 				old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
431967388836SKonstantin Belousov 				old_entry->cred = NULL;
43207fd10fb3SKonstantin Belousov 
43217fd10fb3SKonstantin Belousov 				/*
432283ea714fSDoug Moore 				 * As in vm_map_merged_neighbor_dispose(),
432383ea714fSDoug Moore 				 * the vnode lock will not be acquired in
43247fd10fb3SKonstantin Belousov 				 * this call to vm_object_deallocate().
43257fd10fb3SKonstantin Belousov 				 */
4326d30344bdSIan Dowse 				vm_object_deallocate(object);
43275069bf57SJohn Dyson 				object = old_entry->object.vm_object;
432867388836SKonstantin Belousov 			} else {
432989f6b863SAttilio Rao 				VM_OBJECT_WLOCK(object);
4330069e9bc1SDoug Rabson 				vm_object_clear_flag(object, OBJ_ONEMAPPING);
4331ef694c1aSEdward Tomasz Napierala 				if (old_entry->cred != NULL) {
433267388836SKonstantin Belousov 					KASSERT(object->cred == NULL,
433367388836SKonstantin Belousov 					    ("vmspace_fork both cred"));
4334ef694c1aSEdward Tomasz Napierala 					object->cred = old_entry->cred;
433567388836SKonstantin Belousov 					object->charge = old_entry->end -
433667388836SKonstantin Belousov 					    old_entry->start;
4337ef694c1aSEdward Tomasz Napierala 					old_entry->cred = NULL;
43383364c323SKonstantin Belousov 				}
4339b9781cf6SKonstantin Belousov 
4340b9781cf6SKonstantin Belousov 				/*
4341b9781cf6SKonstantin Belousov 				 * Assert the correct state of the vnode
4342b9781cf6SKonstantin Belousov 				 * v_writecount while the object is locked, to
4343b9781cf6SKonstantin Belousov 				 * not relock it later for the assertion
4344b9781cf6SKonstantin Belousov 				 * correctness.
4345b9781cf6SKonstantin Belousov 				 */
4346fe7bcbafSKyle Evans 				if (old_entry->eflags & MAP_ENTRY_WRITECNT &&
4347b9781cf6SKonstantin Belousov 				    object->type == OBJT_VNODE) {
434867388836SKonstantin Belousov 					KASSERT(((struct vnode *)object->
434967388836SKonstantin Belousov 					    handle)->v_writecount > 0,
435067388836SKonstantin Belousov 					    ("vmspace_fork: v_writecount %p",
435167388836SKonstantin Belousov 					    object));
435267388836SKonstantin Belousov 					KASSERT(object->un_pager.vnp.
435367388836SKonstantin Belousov 					    writemappings > 0,
4354b9781cf6SKonstantin Belousov 					    ("vmspace_fork: vnp.writecount %p",
4355b9781cf6SKonstantin Belousov 					    object));
4356b9781cf6SKonstantin Belousov 				}
435789f6b863SAttilio Rao 				VM_OBJECT_WUNLOCK(object);
435867388836SKonstantin Belousov 			}
4359fed9a903SJohn Dyson 
4360fed9a903SJohn Dyson 			/*
4361ad5fca3bSAlan Cox 			 * Clone the entry, referencing the shared object.
4362df8bae1dSRodney W. Grimes 			 */
4363df8bae1dSRodney W. Grimes 			new_entry = vm_map_entry_create(new_map);
4364df8bae1dSRodney W. Grimes 			*new_entry = *old_entry;
43659f6acfd1SKonstantin Belousov 			new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
43669f6acfd1SKonstantin Belousov 			    MAP_ENTRY_IN_TRANSITION);
43670acea7dfSKonstantin Belousov 			new_entry->wiring_thread = NULL;
4368df8bae1dSRodney W. Grimes 			new_entry->wired_count = 0;
4369fe7bcbafSKyle Evans 			if (new_entry->eflags & MAP_ENTRY_WRITECNT) {
4370fe7bcbafSKyle Evans 				vm_pager_update_writecount(object,
437184110e7eSKonstantin Belousov 				    new_entry->start, new_entry->end);
437284110e7eSKonstantin Belousov 			}
437378022527SKonstantin Belousov 			vm_map_entry_set_vnode_text(new_entry, true);
4374df8bae1dSRodney W. Grimes 
4375df8bae1dSRodney W. Grimes 			/*
43760d94caffSDavid Greenman 			 * Insert the entry into the new map -- we know we're
43770d94caffSDavid Greenman 			 * inserting at the end of the new map.
4378df8bae1dSRodney W. Grimes 			 */
43799f701172SKonstantin Belousov 			vm_map_entry_link(new_map, new_entry);
43802a7be1b6SBrian Feldman 			vmspace_map_entry_forked(vm1, vm2, new_entry);
4381df8bae1dSRodney W. Grimes 
4382df8bae1dSRodney W. Grimes 			/*
4383df8bae1dSRodney W. Grimes 			 * Update the physical map
4384df8bae1dSRodney W. Grimes 			 */
4385df8bae1dSRodney W. Grimes 			pmap_copy(new_map->pmap, old_map->pmap,
4386df8bae1dSRodney W. Grimes 			    new_entry->start,
4387df8bae1dSRodney W. Grimes 			    (old_entry->end - old_entry->start),
4388df8bae1dSRodney W. Grimes 			    old_entry->start);
4389df8bae1dSRodney W. Grimes 			break;
4390df8bae1dSRodney W. Grimes 
4391df8bae1dSRodney W. Grimes 		case VM_INHERIT_COPY:
4392df8bae1dSRodney W. Grimes 			/*
4393df8bae1dSRodney W. Grimes 			 * Clone the entry and link into the map.
4394df8bae1dSRodney W. Grimes 			 */
4395df8bae1dSRodney W. Grimes 			new_entry = vm_map_entry_create(new_map);
4396df8bae1dSRodney W. Grimes 			*new_entry = *old_entry;
439784110e7eSKonstantin Belousov 			/*
439884110e7eSKonstantin Belousov 			 * Copied entry is COW over the old object.
439984110e7eSKonstantin Belousov 			 */
44009f6acfd1SKonstantin Belousov 			new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
4401fe7bcbafSKyle Evans 			    MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_WRITECNT);
44020acea7dfSKonstantin Belousov 			new_entry->wiring_thread = NULL;
4403df8bae1dSRodney W. Grimes 			new_entry->wired_count = 0;
4404df8bae1dSRodney W. Grimes 			new_entry->object.vm_object = NULL;
4405ef694c1aSEdward Tomasz Napierala 			new_entry->cred = NULL;
44069f701172SKonstantin Belousov 			vm_map_entry_link(new_map, new_entry);
44072a7be1b6SBrian Feldman 			vmspace_map_entry_forked(vm1, vm2, new_entry);
4408bd7e5f99SJohn Dyson 			vm_map_copy_entry(old_map, new_map, old_entry,
44093364c323SKonstantin Belousov 			    new_entry, fork_charge);
441078022527SKonstantin Belousov 			vm_map_entry_set_vnode_text(new_entry, true);
4411df8bae1dSRodney W. Grimes 			break;
441278d7964bSXin LI 
441378d7964bSXin LI 		case VM_INHERIT_ZERO:
441478d7964bSXin LI 			/*
441578d7964bSXin LI 			 * Create a new anonymous mapping entry modelled from
441678d7964bSXin LI 			 * the old one.
441778d7964bSXin LI 			 */
441878d7964bSXin LI 			new_entry = vm_map_entry_create(new_map);
441978d7964bSXin LI 			memset(new_entry, 0, sizeof(*new_entry));
442078d7964bSXin LI 
442178d7964bSXin LI 			new_entry->start = old_entry->start;
442278d7964bSXin LI 			new_entry->end = old_entry->end;
442378d7964bSXin LI 			new_entry->eflags = old_entry->eflags &
442478d7964bSXin LI 			    ~(MAP_ENTRY_USER_WIRED | MAP_ENTRY_IN_TRANSITION |
4425e2e80fb3SKonstantin Belousov 			    MAP_ENTRY_WRITECNT | MAP_ENTRY_VN_EXEC |
4426e2e80fb3SKonstantin Belousov 			    MAP_ENTRY_SPLIT_BOUNDARY_MASK);
442778d7964bSXin LI 			new_entry->protection = old_entry->protection;
442878d7964bSXin LI 			new_entry->max_protection = old_entry->max_protection;
442978d7964bSXin LI 			new_entry->inheritance = VM_INHERIT_ZERO;
443078d7964bSXin LI 
44319f701172SKonstantin Belousov 			vm_map_entry_link(new_map, new_entry);
443278d7964bSXin LI 			vmspace_map_entry_forked(vm1, vm2, new_entry);
443378d7964bSXin LI 
443478d7964bSXin LI 			new_entry->cred = curthread->td_ucred;
443578d7964bSXin LI 			crhold(new_entry->cred);
443678d7964bSXin LI 			*fork_charge += (new_entry->end - new_entry->start);
443778d7964bSXin LI 
443878d7964bSXin LI 			break;
4439df8bae1dSRodney W. Grimes 		}
4440df8bae1dSRodney W. Grimes 	}
444184110e7eSKonstantin Belousov 	/*
444284110e7eSKonstantin Belousov 	 * Use inlined vm_map_unlock() to postpone handling the deferred
444384110e7eSKonstantin Belousov 	 * map entries, which cannot be done until both old_map and
444484110e7eSKonstantin Belousov 	 * new_map locks are released.
444584110e7eSKonstantin Belousov 	 */
444684110e7eSKonstantin Belousov 	sx_xunlock(&old_map->lock);
444784110e7eSKonstantin Belousov 	sx_xunlock(&new_map->lock);
444884110e7eSKonstantin Belousov 	vm_map_process_deferred();
4449df8bae1dSRodney W. Grimes 
4450df8bae1dSRodney W. Grimes 	return (vm2);
4451df8bae1dSRodney W. Grimes }
4452df8bae1dSRodney W. Grimes 
44538056df6eSAlan Cox /*
44548056df6eSAlan Cox  * Create a process's stack for exec_new_vmspace().  This function is never
44558056df6eSAlan Cox  * asked to wire the newly created stack.
44568056df6eSAlan Cox  */
445794f7e29aSAlan Cox int
445894f7e29aSAlan Cox vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
445994f7e29aSAlan Cox     vm_prot_t prot, vm_prot_t max, int cow)
446094f7e29aSAlan Cox {
44614648ba0aSKonstantin Belousov 	vm_size_t growsize, init_ssize;
44628056df6eSAlan Cox 	rlim_t vmemlim;
44634648ba0aSKonstantin Belousov 	int rv;
44644648ba0aSKonstantin Belousov 
44658056df6eSAlan Cox 	MPASS((map->flags & MAP_WIREFUTURE) == 0);
44664648ba0aSKonstantin Belousov 	growsize = sgrowsiz;
44674648ba0aSKonstantin Belousov 	init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
44684648ba0aSKonstantin Belousov 	vm_map_lock(map);
4469f6f6d240SMateusz Guzik 	vmemlim = lim_cur(curthread, RLIMIT_VMEM);
44704648ba0aSKonstantin Belousov 	/* If we would blow our VMEM resource limit, no go */
44714648ba0aSKonstantin Belousov 	if (map->size + init_ssize > vmemlim) {
44724648ba0aSKonstantin Belousov 		rv = KERN_NO_SPACE;
44734648ba0aSKonstantin Belousov 		goto out;
44744648ba0aSKonstantin Belousov 	}
4475e1f92cccSAlan Cox 	rv = vm_map_stack_locked(map, addrbos, max_ssize, growsize, prot,
44764648ba0aSKonstantin Belousov 	    max, cow);
44774648ba0aSKonstantin Belousov out:
44784648ba0aSKonstantin Belousov 	vm_map_unlock(map);
44794648ba0aSKonstantin Belousov 	return (rv);
44804648ba0aSKonstantin Belousov }
44814648ba0aSKonstantin Belousov 
448219f49ad3SKonstantin Belousov static int stack_guard_page = 1;
448319f49ad3SKonstantin Belousov SYSCTL_INT(_security_bsd, OID_AUTO, stack_guard_page, CTLFLAG_RWTUN,
448419f49ad3SKonstantin Belousov     &stack_guard_page, 0,
448519f49ad3SKonstantin Belousov     "Specifies the number of guard pages for a stack that grows");
448619f49ad3SKonstantin Belousov 
44874648ba0aSKonstantin Belousov static int
44884648ba0aSKonstantin Belousov vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
44894648ba0aSKonstantin Belousov     vm_size_t growsize, vm_prot_t prot, vm_prot_t max, int cow)
44904648ba0aSKonstantin Belousov {
4491d1d3f7e1SDoug Moore 	vm_map_entry_t new_entry, prev_entry;
449219bd0d9cSKonstantin Belousov 	vm_offset_t bot, gap_bot, gap_top, top;
449319f49ad3SKonstantin Belousov 	vm_size_t init_ssize, sgp;
4494fd75d710SMarcel Moolenaar 	int orient, rv;
449594f7e29aSAlan Cox 
4496fd75d710SMarcel Moolenaar 	/*
4497fd75d710SMarcel Moolenaar 	 * The stack orientation is piggybacked with the cow argument.
4498fd75d710SMarcel Moolenaar 	 * Extract it into orient and mask the cow argument so that we
4499fd75d710SMarcel Moolenaar 	 * don't pass it around further.
4500fd75d710SMarcel Moolenaar 	 */
4501fd75d710SMarcel Moolenaar 	orient = cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP);
4502fd75d710SMarcel Moolenaar 	KASSERT(orient != 0, ("No stack grow direction"));
450319bd0d9cSKonstantin Belousov 	KASSERT(orient != (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP),
450419bd0d9cSKonstantin Belousov 	    ("bi-dir stack"));
4505fd75d710SMarcel Moolenaar 
45060f1e6ec5SMark Johnston 	if (max_ssize == 0 ||
45070f1e6ec5SMark Johnston 	    !vm_map_range_valid(map, addrbos, addrbos + max_ssize))
45089410cd7dSKonstantin Belousov 		return (KERN_INVALID_ADDRESS);
4509156e8654SKonstantin Belousov 	sgp = ((curproc->p_flag2 & P2_STKGAP_DISABLE) != 0 ||
4510156e8654SKonstantin Belousov 	    (curproc->p_fctl0 & NT_FREEBSD_FCTL_STKGAP_DISABLE) != 0) ? 0 :
4511fe69291fSKonstantin Belousov 	    (vm_size_t)stack_guard_page * PAGE_SIZE;
45129410cd7dSKonstantin Belousov 	if (sgp >= max_ssize)
45139410cd7dSKonstantin Belousov 		return (KERN_INVALID_ARGUMENT);
4514fd75d710SMarcel Moolenaar 
451519f49ad3SKonstantin Belousov 	init_ssize = growsize;
451619f49ad3SKonstantin Belousov 	if (max_ssize < init_ssize + sgp)
451719f49ad3SKonstantin Belousov 		init_ssize = max_ssize - sgp;
451894f7e29aSAlan Cox 
451994f7e29aSAlan Cox 	/* If addr is already mapped, no go */
4520d1d3f7e1SDoug Moore 	if (vm_map_lookup_entry(map, addrbos, &prev_entry))
452194f7e29aSAlan Cox 		return (KERN_NO_SPACE);
4522a69ac174SMatthew Dillon 
4523fd75d710SMarcel Moolenaar 	/*
4524763df3ecSPedro F. Giffuni 	 * If we can't accommodate max_ssize in the current mapping, no go.
452594f7e29aSAlan Cox 	 */
45267cdcf863SDoug Moore 	if (vm_map_entry_succ(prev_entry)->start < addrbos + max_ssize)
452794f7e29aSAlan Cox 		return (KERN_NO_SPACE);
452894f7e29aSAlan Cox 
4529fd75d710SMarcel Moolenaar 	/*
4530fd75d710SMarcel Moolenaar 	 * We initially map a stack of only init_ssize.  We will grow as
4531fd75d710SMarcel Moolenaar 	 * needed later.  Depending on the orientation of the stack (i.e.
4532fd75d710SMarcel Moolenaar 	 * the grow direction) we either map at the top of the range, the
4533fd75d710SMarcel Moolenaar 	 * bottom of the range or in the middle.
453494f7e29aSAlan Cox 	 *
4535fd75d710SMarcel Moolenaar 	 * Note: we would normally expect prot and max to be VM_PROT_ALL,
4536fd75d710SMarcel Moolenaar 	 * and cow to be 0.  Possibly we should eliminate these as input
4537fd75d710SMarcel Moolenaar 	 * parameters, and just pass these values here in the insert call.
453894f7e29aSAlan Cox 	 */
453919bd0d9cSKonstantin Belousov 	if (orient == MAP_STACK_GROWS_DOWN) {
4540fd75d710SMarcel Moolenaar 		bot = addrbos + max_ssize - init_ssize;
4541fd75d710SMarcel Moolenaar 		top = bot + init_ssize;
454219bd0d9cSKonstantin Belousov 		gap_bot = addrbos;
454319bd0d9cSKonstantin Belousov 		gap_top = bot;
454419bd0d9cSKonstantin Belousov 	} else /* if (orient == MAP_STACK_GROWS_UP) */ {
454519bd0d9cSKonstantin Belousov 		bot = addrbos;
454619bd0d9cSKonstantin Belousov 		top = bot + init_ssize;
454719bd0d9cSKonstantin Belousov 		gap_bot = top;
454819bd0d9cSKonstantin Belousov 		gap_top = addrbos + max_ssize;
454919bd0d9cSKonstantin Belousov 	}
4550fd75d710SMarcel Moolenaar 	rv = vm_map_insert(map, NULL, 0, bot, top, prot, max, cow);
455119bd0d9cSKonstantin Belousov 	if (rv != KERN_SUCCESS)
455219bd0d9cSKonstantin Belousov 		return (rv);
45537cdcf863SDoug Moore 	new_entry = vm_map_entry_succ(prev_entry);
455419bd0d9cSKonstantin Belousov 	KASSERT(new_entry->end == top || new_entry->start == bot,
455519bd0d9cSKonstantin Belousov 	    ("Bad entry start/end for new stack entry"));
4556712efe66SAlan Cox 	KASSERT((orient & MAP_STACK_GROWS_DOWN) == 0 ||
4557712efe66SAlan Cox 	    (new_entry->eflags & MAP_ENTRY_GROWS_DOWN) != 0,
4558712efe66SAlan Cox 	    ("new entry lacks MAP_ENTRY_GROWS_DOWN"));
4559712efe66SAlan Cox 	KASSERT((orient & MAP_STACK_GROWS_UP) == 0 ||
4560712efe66SAlan Cox 	    (new_entry->eflags & MAP_ENTRY_GROWS_UP) != 0,
4561712efe66SAlan Cox 	    ("new entry lacks MAP_ENTRY_GROWS_UP"));
4562fe69291fSKonstantin Belousov 	if (gap_bot == gap_top)
4563fe69291fSKonstantin Belousov 		return (KERN_SUCCESS);
456419bd0d9cSKonstantin Belousov 	rv = vm_map_insert(map, NULL, 0, gap_bot, gap_top, VM_PROT_NONE,
456519bd0d9cSKonstantin Belousov 	    VM_PROT_NONE, MAP_CREATE_GUARD | (orient == MAP_STACK_GROWS_DOWN ?
456619bd0d9cSKonstantin Belousov 	    MAP_CREATE_STACK_GAP_DN : MAP_CREATE_STACK_GAP_UP));
4567a7751d32SKonstantin Belousov 	if (rv == KERN_SUCCESS) {
4568a7751d32SKonstantin Belousov 		/*
4569a7751d32SKonstantin Belousov 		 * Gap can never successfully handle a fault, so
4570a7751d32SKonstantin Belousov 		 * read-ahead logic is never used for it.  Re-use
4571a7751d32SKonstantin Belousov 		 * next_read of the gap entry to store
4572a7751d32SKonstantin Belousov 		 * stack_guard_page for vm_map_growstack().
4573a7751d32SKonstantin Belousov 		 */
4574a7751d32SKonstantin Belousov 		if (orient == MAP_STACK_GROWS_DOWN)
45757cdcf863SDoug Moore 			vm_map_entry_pred(new_entry)->next_read = sgp;
4576a7751d32SKonstantin Belousov 		else
45777cdcf863SDoug Moore 			vm_map_entry_succ(new_entry)->next_read = sgp;
4578a7751d32SKonstantin Belousov 	} else {
457919bd0d9cSKonstantin Belousov 		(void)vm_map_delete(map, bot, top);
4580a7751d32SKonstantin Belousov 	}
458194f7e29aSAlan Cox 	return (rv);
458294f7e29aSAlan Cox }
458394f7e29aSAlan Cox 
458419bd0d9cSKonstantin Belousov /*
458519bd0d9cSKonstantin Belousov  * Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if we
458619bd0d9cSKonstantin Belousov  * successfully grow the stack.
458794f7e29aSAlan Cox  */
458819bd0d9cSKonstantin Belousov static int
458919bd0d9cSKonstantin Belousov vm_map_growstack(vm_map_t map, vm_offset_t addr, vm_map_entry_t gap_entry)
459094f7e29aSAlan Cox {
459119bd0d9cSKonstantin Belousov 	vm_map_entry_t stack_entry;
459219bd0d9cSKonstantin Belousov 	struct proc *p;
459319bd0d9cSKonstantin Belousov 	struct vmspace *vm;
459419bd0d9cSKonstantin Belousov 	struct ucred *cred;
459519bd0d9cSKonstantin Belousov 	vm_offset_t gap_end, gap_start, grow_start;
4596fa581662SDoug Moore 	vm_size_t grow_amount, guard, max_grow;
45977e19eda4SAndrey Zonov 	rlim_t lmemlim, stacklim, vmemlim;
4598b8ebd99aSJohn Baldwin 	int rv, rv1 __diagused;
459919bd0d9cSKonstantin Belousov 	bool gap_deleted, grow_down, is_procstack;
46001ba5ad42SEdward Tomasz Napierala #ifdef notyet
46011ba5ad42SEdward Tomasz Napierala 	uint64_t limit;
46021ba5ad42SEdward Tomasz Napierala #endif
4603afcc55f3SEdward Tomasz Napierala #ifdef RACCT
4604b8ebd99aSJohn Baldwin 	int error __diagused;
4605afcc55f3SEdward Tomasz Napierala #endif
460623955314SAlfred Perlstein 
460719bd0d9cSKonstantin Belousov 	p = curproc;
460819bd0d9cSKonstantin Belousov 	vm = p->p_vmspace;
4609eb5ea878SKonstantin Belousov 
4610eb5ea878SKonstantin Belousov 	/*
4611eb5ea878SKonstantin Belousov 	 * Disallow stack growth when the access is performed by a
4612eb5ea878SKonstantin Belousov 	 * debugger or AIO daemon.  The reason is that the wrong
4613eb5ea878SKonstantin Belousov 	 * resource limits are applied.
4614eb5ea878SKonstantin Belousov 	 */
461510ae16c7SKonstantin Belousov 	if (p != initproc && (map != &p->p_vmspace->vm_map ||
461610ae16c7SKonstantin Belousov 	    p->p_textvp == NULL))
4617f758aaddSKonstantin Belousov 		return (KERN_FAILURE);
4618eb5ea878SKonstantin Belousov 
461919bd0d9cSKonstantin Belousov 	MPASS(!map->system_map);
462019bd0d9cSKonstantin Belousov 
4621f6f6d240SMateusz Guzik 	lmemlim = lim_cur(curthread, RLIMIT_MEMLOCK);
4622f6f6d240SMateusz Guzik 	stacklim = lim_cur(curthread, RLIMIT_STACK);
4623f6f6d240SMateusz Guzik 	vmemlim = lim_cur(curthread, RLIMIT_VMEM);
462419bd0d9cSKonstantin Belousov retry:
462519bd0d9cSKonstantin Belousov 	/* If addr is not in a hole for a stack grow area, no need to grow. */
4626d1d3f7e1SDoug Moore 	if (gap_entry == NULL && !vm_map_lookup_entry(map, addr, &gap_entry))
462719bd0d9cSKonstantin Belousov 		return (KERN_FAILURE);
462819bd0d9cSKonstantin Belousov 	if ((gap_entry->eflags & MAP_ENTRY_GUARD) == 0)
46290cddd8f0SMatthew Dillon 		return (KERN_SUCCESS);
463019bd0d9cSKonstantin Belousov 	if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_DN) != 0) {
46317cdcf863SDoug Moore 		stack_entry = vm_map_entry_succ(gap_entry);
463219bd0d9cSKonstantin Belousov 		if ((stack_entry->eflags & MAP_ENTRY_GROWS_DOWN) == 0 ||
463319bd0d9cSKonstantin Belousov 		    stack_entry->start != gap_entry->end)
463419bd0d9cSKonstantin Belousov 			return (KERN_FAILURE);
463519bd0d9cSKonstantin Belousov 		grow_amount = round_page(stack_entry->start - addr);
463619bd0d9cSKonstantin Belousov 		grow_down = true;
463719bd0d9cSKonstantin Belousov 	} else if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_UP) != 0) {
46387cdcf863SDoug Moore 		stack_entry = vm_map_entry_pred(gap_entry);
463919bd0d9cSKonstantin Belousov 		if ((stack_entry->eflags & MAP_ENTRY_GROWS_UP) == 0 ||
464019bd0d9cSKonstantin Belousov 		    stack_entry->end != gap_entry->start)
464119bd0d9cSKonstantin Belousov 			return (KERN_FAILURE);
464219bd0d9cSKonstantin Belousov 		grow_amount = round_page(addr + 1 - stack_entry->end);
464319bd0d9cSKonstantin Belousov 		grow_down = false;
4644b21a0008SMarcel Moolenaar 	} else {
464519bd0d9cSKonstantin Belousov 		return (KERN_FAILURE);
4646b21a0008SMarcel Moolenaar 	}
4647156e8654SKonstantin Belousov 	guard = ((curproc->p_flag2 & P2_STKGAP_DISABLE) != 0 ||
4648156e8654SKonstantin Belousov 	    (curproc->p_fctl0 & NT_FREEBSD_FCTL_STKGAP_DISABLE) != 0) ? 0 :
4649fe69291fSKonstantin Belousov 	    gap_entry->next_read;
4650201f03b8SAlan Cox 	max_grow = gap_entry->end - gap_entry->start;
4651201f03b8SAlan Cox 	if (guard > max_grow)
4652201f03b8SAlan Cox 		return (KERN_NO_SPACE);
4653201f03b8SAlan Cox 	max_grow -= guard;
465419bd0d9cSKonstantin Belousov 	if (grow_amount > max_grow)
46550cddd8f0SMatthew Dillon 		return (KERN_NO_SPACE);
465694f7e29aSAlan Cox 
4657b21a0008SMarcel Moolenaar 	/*
4658b21a0008SMarcel Moolenaar 	 * If this is the main process stack, see if we're over the stack
4659b21a0008SMarcel Moolenaar 	 * limit.
466094f7e29aSAlan Cox 	 */
466119bd0d9cSKonstantin Belousov 	is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr &&
4662becaf643SJohn Baldwin 	    addr < (vm_offset_t)vm->vm_stacktop;
466319bd0d9cSKonstantin Belousov 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim))
46640cddd8f0SMatthew Dillon 		return (KERN_NO_SPACE);
466519bd0d9cSKonstantin Belousov 
4666afcc55f3SEdward Tomasz Napierala #ifdef RACCT
46674b5c9cf6SEdward Tomasz Napierala 	if (racct_enable) {
46681ba5ad42SEdward Tomasz Napierala 		PROC_LOCK(p);
46694b5c9cf6SEdward Tomasz Napierala 		if (is_procstack && racct_set(p, RACCT_STACK,
46704b5c9cf6SEdward Tomasz Napierala 		    ctob(vm->vm_ssize) + grow_amount)) {
46711ba5ad42SEdward Tomasz Napierala 			PROC_UNLOCK(p);
46721ba5ad42SEdward Tomasz Napierala 			return (KERN_NO_SPACE);
46731ba5ad42SEdward Tomasz Napierala 		}
46741ba5ad42SEdward Tomasz Napierala 		PROC_UNLOCK(p);
46754b5c9cf6SEdward Tomasz Napierala 	}
4676afcc55f3SEdward Tomasz Napierala #endif
467794f7e29aSAlan Cox 
467819bd0d9cSKonstantin Belousov 	grow_amount = roundup(grow_amount, sgrowsiz);
467919bd0d9cSKonstantin Belousov 	if (grow_amount > max_grow)
468019bd0d9cSKonstantin Belousov 		grow_amount = max_grow;
468191d5354aSJohn Baldwin 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
4682e4826248SAlan Cox 		grow_amount = trunc_page((vm_size_t)stacklim) -
4683e4826248SAlan Cox 		    ctob(vm->vm_ssize);
468494f7e29aSAlan Cox 	}
468519bd0d9cSKonstantin Belousov 
46861ba5ad42SEdward Tomasz Napierala #ifdef notyet
46871ba5ad42SEdward Tomasz Napierala 	PROC_LOCK(p);
46881ba5ad42SEdward Tomasz Napierala 	limit = racct_get_available(p, RACCT_STACK);
46891ba5ad42SEdward Tomasz Napierala 	PROC_UNLOCK(p);
46901ba5ad42SEdward Tomasz Napierala 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > limit))
46911ba5ad42SEdward Tomasz Napierala 		grow_amount = limit - ctob(vm->vm_ssize);
46921ba5ad42SEdward Tomasz Napierala #endif
469319bd0d9cSKonstantin Belousov 
469419bd0d9cSKonstantin Belousov 	if (!old_mlock && (map->flags & MAP_WIREFUTURE) != 0) {
46953ac7d297SAndrey Zonov 		if (ptoa(pmap_wired_count(map->pmap)) + grow_amount > lmemlim) {
46967e19eda4SAndrey Zonov 			rv = KERN_NO_SPACE;
46977e19eda4SAndrey Zonov 			goto out;
46987e19eda4SAndrey Zonov 		}
46997e19eda4SAndrey Zonov #ifdef RACCT
47004b5c9cf6SEdward Tomasz Napierala 		if (racct_enable) {
47017e19eda4SAndrey Zonov 			PROC_LOCK(p);
47027e19eda4SAndrey Zonov 			if (racct_set(p, RACCT_MEMLOCK,
47033ac7d297SAndrey Zonov 			    ptoa(pmap_wired_count(map->pmap)) + grow_amount)) {
47047e19eda4SAndrey Zonov 				PROC_UNLOCK(p);
47057e19eda4SAndrey Zonov 				rv = KERN_NO_SPACE;
47067e19eda4SAndrey Zonov 				goto out;
47077e19eda4SAndrey Zonov 			}
47087e19eda4SAndrey Zonov 			PROC_UNLOCK(p);
47094b5c9cf6SEdward Tomasz Napierala 		}
47107e19eda4SAndrey Zonov #endif
47117e19eda4SAndrey Zonov 	}
471219bd0d9cSKonstantin Belousov 
4713a69ac174SMatthew Dillon 	/* If we would blow our VMEM resource limit, no go */
471491d5354aSJohn Baldwin 	if (map->size + grow_amount > vmemlim) {
47151ba5ad42SEdward Tomasz Napierala 		rv = KERN_NO_SPACE;
47161ba5ad42SEdward Tomasz Napierala 		goto out;
4717a69ac174SMatthew Dillon 	}
4718afcc55f3SEdward Tomasz Napierala #ifdef RACCT
47194b5c9cf6SEdward Tomasz Napierala 	if (racct_enable) {
47201ba5ad42SEdward Tomasz Napierala 		PROC_LOCK(p);
47211ba5ad42SEdward Tomasz Napierala 		if (racct_set(p, RACCT_VMEM, map->size + grow_amount)) {
47221ba5ad42SEdward Tomasz Napierala 			PROC_UNLOCK(p);
47231ba5ad42SEdward Tomasz Napierala 			rv = KERN_NO_SPACE;
47241ba5ad42SEdward Tomasz Napierala 			goto out;
47251ba5ad42SEdward Tomasz Napierala 		}
47261ba5ad42SEdward Tomasz Napierala 		PROC_UNLOCK(p);
47274b5c9cf6SEdward Tomasz Napierala 	}
4728afcc55f3SEdward Tomasz Napierala #endif
4729a69ac174SMatthew Dillon 
473019bd0d9cSKonstantin Belousov 	if (vm_map_lock_upgrade(map)) {
473119bd0d9cSKonstantin Belousov 		gap_entry = NULL;
473219bd0d9cSKonstantin Belousov 		vm_map_lock_read(map);
473319bd0d9cSKonstantin Belousov 		goto retry;
473494f7e29aSAlan Cox 	}
473594f7e29aSAlan Cox 
473619bd0d9cSKonstantin Belousov 	if (grow_down) {
473719bd0d9cSKonstantin Belousov 		grow_start = gap_entry->end - grow_amount;
473819bd0d9cSKonstantin Belousov 		if (gap_entry->start + grow_amount == gap_entry->end) {
473919bd0d9cSKonstantin Belousov 			gap_start = gap_entry->start;
474019bd0d9cSKonstantin Belousov 			gap_end = gap_entry->end;
474119bd0d9cSKonstantin Belousov 			vm_map_entry_delete(map, gap_entry);
474219bd0d9cSKonstantin Belousov 			gap_deleted = true;
474319bd0d9cSKonstantin Belousov 		} else {
474419bd0d9cSKonstantin Belousov 			MPASS(gap_entry->start < gap_entry->end - grow_amount);
4745fa581662SDoug Moore 			vm_map_entry_resize(map, gap_entry, -grow_amount);
474619bd0d9cSKonstantin Belousov 			gap_deleted = false;
474719bd0d9cSKonstantin Belousov 		}
474819bd0d9cSKonstantin Belousov 		rv = vm_map_insert(map, NULL, 0, grow_start,
474919bd0d9cSKonstantin Belousov 		    grow_start + grow_amount,
475019bd0d9cSKonstantin Belousov 		    stack_entry->protection, stack_entry->max_protection,
4751712efe66SAlan Cox 		    MAP_STACK_GROWS_DOWN);
475219bd0d9cSKonstantin Belousov 		if (rv != KERN_SUCCESS) {
475319bd0d9cSKonstantin Belousov 			if (gap_deleted) {
475419bd0d9cSKonstantin Belousov 				rv1 = vm_map_insert(map, NULL, 0, gap_start,
475519bd0d9cSKonstantin Belousov 				    gap_end, VM_PROT_NONE, VM_PROT_NONE,
475619bd0d9cSKonstantin Belousov 				    MAP_CREATE_GUARD | MAP_CREATE_STACK_GAP_DN);
475719bd0d9cSKonstantin Belousov 				MPASS(rv1 == KERN_SUCCESS);
47581895f520SDoug Moore 			} else
4759fa581662SDoug Moore 				vm_map_entry_resize(map, gap_entry,
47601895f520SDoug Moore 				    grow_amount);
476194f7e29aSAlan Cox 		}
4762b21a0008SMarcel Moolenaar 	} else {
476319bd0d9cSKonstantin Belousov 		grow_start = stack_entry->end;
4764ef694c1aSEdward Tomasz Napierala 		cred = stack_entry->cred;
4765ef694c1aSEdward Tomasz Napierala 		if (cred == NULL && stack_entry->object.vm_object != NULL)
4766ef694c1aSEdward Tomasz Napierala 			cred = stack_entry->object.vm_object->cred;
4767ef694c1aSEdward Tomasz Napierala 		if (cred != NULL && !swap_reserve_by_cred(grow_amount, cred))
47683364c323SKonstantin Belousov 			rv = KERN_NO_SPACE;
4769b21a0008SMarcel Moolenaar 		/* Grow the underlying object if applicable. */
47703364c323SKonstantin Belousov 		else if (stack_entry->object.vm_object == NULL ||
4771b21a0008SMarcel Moolenaar 		    vm_object_coalesce(stack_entry->object.vm_object,
477257a21abaSAlan Cox 		    stack_entry->offset,
4773b21a0008SMarcel Moolenaar 		    (vm_size_t)(stack_entry->end - stack_entry->start),
4774fa581662SDoug Moore 		    grow_amount, cred != NULL)) {
4775fa581662SDoug Moore 			if (gap_entry->start + grow_amount == gap_entry->end) {
477619bd0d9cSKonstantin Belousov 				vm_map_entry_delete(map, gap_entry);
4777fa581662SDoug Moore 				vm_map_entry_resize(map, stack_entry,
4778fa581662SDoug Moore 				    grow_amount);
4779fa581662SDoug Moore 			} else {
478019bd0d9cSKonstantin Belousov 				gap_entry->start += grow_amount;
4781fa581662SDoug Moore 				stack_entry->end += grow_amount;
4782fa581662SDoug Moore 			}
478319bd0d9cSKonstantin Belousov 			map->size += grow_amount;
4784b21a0008SMarcel Moolenaar 			rv = KERN_SUCCESS;
4785b21a0008SMarcel Moolenaar 		} else
4786b21a0008SMarcel Moolenaar 			rv = KERN_FAILURE;
4787b21a0008SMarcel Moolenaar 	}
4788b21a0008SMarcel Moolenaar 	if (rv == KERN_SUCCESS && is_procstack)
4789b21a0008SMarcel Moolenaar 		vm->vm_ssize += btoc(grow_amount);
4790b21a0008SMarcel Moolenaar 
4791abd498aaSBruce M Simpson 	/*
4792abd498aaSBruce M Simpson 	 * Heed the MAP_WIREFUTURE flag if it was set for this process.
4793abd498aaSBruce M Simpson 	 */
479419bd0d9cSKonstantin Belousov 	if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE) != 0) {
479554a3a114SMark Johnston 		rv = vm_map_wire_locked(map, grow_start,
479654a3a114SMark Johnston 		    grow_start + grow_amount,
4797212e02c8SKonstantin Belousov 		    VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
479854a3a114SMark Johnston 	}
479919bd0d9cSKonstantin Belousov 	vm_map_lock_downgrade(map);
4800abd498aaSBruce M Simpson 
48011ba5ad42SEdward Tomasz Napierala out:
4802afcc55f3SEdward Tomasz Napierala #ifdef RACCT
48034b5c9cf6SEdward Tomasz Napierala 	if (racct_enable && rv != KERN_SUCCESS) {
48041ba5ad42SEdward Tomasz Napierala 		PROC_LOCK(p);
48051ba5ad42SEdward Tomasz Napierala 		error = racct_set(p, RACCT_VMEM, map->size);
48061ba5ad42SEdward Tomasz Napierala 		KASSERT(error == 0, ("decreasing RACCT_VMEM failed"));
48077e19eda4SAndrey Zonov 		if (!old_mlock) {
48087e19eda4SAndrey Zonov 			error = racct_set(p, RACCT_MEMLOCK,
48093ac7d297SAndrey Zonov 			    ptoa(pmap_wired_count(map->pmap)));
48107e19eda4SAndrey Zonov 			KASSERT(error == 0, ("decreasing RACCT_MEMLOCK failed"));
48117e19eda4SAndrey Zonov 		}
48121ba5ad42SEdward Tomasz Napierala 	    	error = racct_set(p, RACCT_STACK, ctob(vm->vm_ssize));
48131ba5ad42SEdward Tomasz Napierala 		KASSERT(error == 0, ("decreasing RACCT_STACK failed"));
48141ba5ad42SEdward Tomasz Napierala 		PROC_UNLOCK(p);
48151ba5ad42SEdward Tomasz Napierala 	}
4816afcc55f3SEdward Tomasz Napierala #endif
48171ba5ad42SEdward Tomasz Napierala 
48180cddd8f0SMatthew Dillon 	return (rv);
481994f7e29aSAlan Cox }
482094f7e29aSAlan Cox 
4821df8bae1dSRodney W. Grimes /*
48225856e12eSJohn Dyson  * Unshare the specified VM space for exec.  If other processes are
48235856e12eSJohn Dyson  * mapped to it, then create a new one.  The new vmspace is null.
48245856e12eSJohn Dyson  */
482589b57fcfSKonstantin Belousov int
48263ebc1248SPeter Wemm vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
48271b40f8c0SMatthew Dillon {
48285856e12eSJohn Dyson 	struct vmspace *oldvmspace = p->p_vmspace;
48295856e12eSJohn Dyson 	struct vmspace *newvmspace;
48305856e12eSJohn Dyson 
48317032434eSKonstantin Belousov 	KASSERT((curthread->td_pflags & TDP_EXECVMSPC) == 0,
48327032434eSKonstantin Belousov 	    ("vmspace_exec recursed"));
48336e00f3a3SKonstantin Belousov 	newvmspace = vmspace_alloc(minuser, maxuser, pmap_pinit);
483489b57fcfSKonstantin Belousov 	if (newvmspace == NULL)
483589b57fcfSKonstantin Belousov 		return (ENOMEM);
483651ab6c28SAlan Cox 	newvmspace->vm_swrss = oldvmspace->vm_swrss;
48375856e12eSJohn Dyson 	/*
48385856e12eSJohn Dyson 	 * This code is written like this for prototype purposes.  The
48395856e12eSJohn Dyson 	 * goal is to avoid running down the vmspace here, but let the
48405856e12eSJohn Dyson 	 * other process's that are still using the vmspace to finally
48415856e12eSJohn Dyson 	 * run it down.  Even though there is little or no chance of blocking
48425856e12eSJohn Dyson 	 * here, it is a good idea to keep this form for future mods.
48435856e12eSJohn Dyson 	 */
484457051fdcSTor Egge 	PROC_VMSPACE_LOCK(p);
48455856e12eSJohn Dyson 	p->p_vmspace = newvmspace;
484657051fdcSTor Egge 	PROC_VMSPACE_UNLOCK(p);
48476617724cSJeff Roberson 	if (p == curthread->td_proc)
4848b40ce416SJulian Elischer 		pmap_activate(curthread);
48497032434eSKonstantin Belousov 	curthread->td_pflags |= TDP_EXECVMSPC;
485089b57fcfSKonstantin Belousov 	return (0);
48515856e12eSJohn Dyson }
48525856e12eSJohn Dyson 
48535856e12eSJohn Dyson /*
48545856e12eSJohn Dyson  * Unshare the specified VM space for forcing COW.  This
48555856e12eSJohn Dyson  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
48565856e12eSJohn Dyson  */
485789b57fcfSKonstantin Belousov int
48581b40f8c0SMatthew Dillon vmspace_unshare(struct proc *p)
48591b40f8c0SMatthew Dillon {
48605856e12eSJohn Dyson 	struct vmspace *oldvmspace = p->p_vmspace;
48615856e12eSJohn Dyson 	struct vmspace *newvmspace;
48623364c323SKonstantin Belousov 	vm_ooffset_t fork_charge;
48635856e12eSJohn Dyson 
48649246b309SMark Johnston 	/*
48659246b309SMark Johnston 	 * The caller is responsible for ensuring that the reference count
48669246b309SMark Johnston 	 * cannot concurrently transition 1 -> 2.
48679246b309SMark Johnston 	 */
4868f7db0c95SMark Johnston 	if (refcount_load(&oldvmspace->vm_refcnt) == 1)
486989b57fcfSKonstantin Belousov 		return (0);
48703364c323SKonstantin Belousov 	fork_charge = 0;
48713364c323SKonstantin Belousov 	newvmspace = vmspace_fork(oldvmspace, &fork_charge);
487289b57fcfSKonstantin Belousov 	if (newvmspace == NULL)
487389b57fcfSKonstantin Belousov 		return (ENOMEM);
4874ef694c1aSEdward Tomasz Napierala 	if (!swap_reserve_by_cred(fork_charge, p->p_ucred)) {
48753364c323SKonstantin Belousov 		vmspace_free(newvmspace);
48763364c323SKonstantin Belousov 		return (ENOMEM);
48773364c323SKonstantin Belousov 	}
487857051fdcSTor Egge 	PROC_VMSPACE_LOCK(p);
48795856e12eSJohn Dyson 	p->p_vmspace = newvmspace;
488057051fdcSTor Egge 	PROC_VMSPACE_UNLOCK(p);
48816617724cSJeff Roberson 	if (p == curthread->td_proc)
4882b40ce416SJulian Elischer 		pmap_activate(curthread);
4883b56ef1c1SJohn Baldwin 	vmspace_free(oldvmspace);
488489b57fcfSKonstantin Belousov 	return (0);
48855856e12eSJohn Dyson }
48865856e12eSJohn Dyson 
48875856e12eSJohn Dyson /*
4888df8bae1dSRodney W. Grimes  *	vm_map_lookup:
4889df8bae1dSRodney W. Grimes  *
4890df8bae1dSRodney W. Grimes  *	Finds the VM object, offset, and
4891df8bae1dSRodney W. Grimes  *	protection for a given virtual address in the
4892df8bae1dSRodney W. Grimes  *	specified map, assuming a page fault of the
4893df8bae1dSRodney W. Grimes  *	type specified.
4894df8bae1dSRodney W. Grimes  *
4895df8bae1dSRodney W. Grimes  *	Leaves the map in question locked for read; return
4896df8bae1dSRodney W. Grimes  *	values are guaranteed until a vm_map_lookup_done
4897df8bae1dSRodney W. Grimes  *	call is performed.  Note that the map argument
4898df8bae1dSRodney W. Grimes  *	is in/out; the returned map must be used in
4899df8bae1dSRodney W. Grimes  *	the call to vm_map_lookup_done.
4900df8bae1dSRodney W. Grimes  *
4901df8bae1dSRodney W. Grimes  *	A handle (out_entry) is returned for use in
4902df8bae1dSRodney W. Grimes  *	vm_map_lookup_done, to make that fast.
4903df8bae1dSRodney W. Grimes  *
4904df8bae1dSRodney W. Grimes  *	If a lookup is requested with "write protection"
4905df8bae1dSRodney W. Grimes  *	specified, the map may be changed to perform virtual
4906df8bae1dSRodney W. Grimes  *	copying operations, although the data referenced will
4907df8bae1dSRodney W. Grimes  *	remain the same.
4908df8bae1dSRodney W. Grimes  */
4909df8bae1dSRodney W. Grimes int
4910b9dcd593SBruce Evans vm_map_lookup(vm_map_t *var_map,		/* IN/OUT */
4911b9dcd593SBruce Evans 	      vm_offset_t vaddr,
491247221757SJohn Dyson 	      vm_prot_t fault_typea,
4913b9dcd593SBruce Evans 	      vm_map_entry_t *out_entry,	/* OUT */
4914b9dcd593SBruce Evans 	      vm_object_t *object,		/* OUT */
4915b9dcd593SBruce Evans 	      vm_pindex_t *pindex,		/* OUT */
4916b9dcd593SBruce Evans 	      vm_prot_t *out_prot,		/* OUT */
49172d8acc0fSJohn Dyson 	      boolean_t *wired)			/* OUT */
4918df8bae1dSRodney W. Grimes {
4919c0877f10SJohn Dyson 	vm_map_entry_t entry;
4920c0877f10SJohn Dyson 	vm_map_t map = *var_map;
4921c0877f10SJohn Dyson 	vm_prot_t prot;
4922a6f21d15SMark Johnston 	vm_prot_t fault_type;
49233364c323SKonstantin Belousov 	vm_object_t eobject;
49240cc74f14SAlan Cox 	vm_size_t size;
4925ef694c1aSEdward Tomasz Napierala 	struct ucred *cred;
4926df8bae1dSRodney W. Grimes 
492719bd0d9cSKonstantin Belousov RetryLookup:
4928df8bae1dSRodney W. Grimes 
4929df8bae1dSRodney W. Grimes 	vm_map_lock_read(map);
4930df8bae1dSRodney W. Grimes 
493119bd0d9cSKonstantin Belousov RetryLookupLocked:
4932df8bae1dSRodney W. Grimes 	/*
49334c3ef59eSAlan Cox 	 * Lookup the faulting address.
4934df8bae1dSRodney W. Grimes 	 */
4935095104acSAlan Cox 	if (!vm_map_lookup_entry(map, vaddr, out_entry)) {
4936095104acSAlan Cox 		vm_map_unlock_read(map);
4937095104acSAlan Cox 		return (KERN_INVALID_ADDRESS);
4938095104acSAlan Cox 	}
4939df8bae1dSRodney W. Grimes 
49404e94f402SAlan Cox 	entry = *out_entry;
4941b7b2aac2SJohn Dyson 
4942df8bae1dSRodney W. Grimes 	/*
4943df8bae1dSRodney W. Grimes 	 * Handle submaps.
4944df8bae1dSRodney W. Grimes 	 */
4945afa07f7eSJohn Dyson 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4946df8bae1dSRodney W. Grimes 		vm_map_t old_map = map;
4947df8bae1dSRodney W. Grimes 
4948df8bae1dSRodney W. Grimes 		*var_map = map = entry->object.sub_map;
4949df8bae1dSRodney W. Grimes 		vm_map_unlock_read(old_map);
4950df8bae1dSRodney W. Grimes 		goto RetryLookup;
4951df8bae1dSRodney W. Grimes 	}
4952a04c970aSJohn Dyson 
4953df8bae1dSRodney W. Grimes 	/*
49540d94caffSDavid Greenman 	 * Check whether this task is allowed to have this page.
4955df8bae1dSRodney W. Grimes 	 */
4956df8bae1dSRodney W. Grimes 	prot = entry->protection;
495719bd0d9cSKonstantin Belousov 	if ((fault_typea & VM_PROT_FAULT_LOOKUP) != 0) {
495819bd0d9cSKonstantin Belousov 		fault_typea &= ~VM_PROT_FAULT_LOOKUP;
495919bd0d9cSKonstantin Belousov 		if (prot == VM_PROT_NONE && map != kernel_map &&
496019bd0d9cSKonstantin Belousov 		    (entry->eflags & MAP_ENTRY_GUARD) != 0 &&
496119bd0d9cSKonstantin Belousov 		    (entry->eflags & (MAP_ENTRY_STACK_GAP_DN |
496219bd0d9cSKonstantin Belousov 		    MAP_ENTRY_STACK_GAP_UP)) != 0 &&
496319bd0d9cSKonstantin Belousov 		    vm_map_growstack(map, vaddr, entry) == KERN_SUCCESS)
496419bd0d9cSKonstantin Belousov 			goto RetryLookupLocked;
496519bd0d9cSKonstantin Belousov 	}
4966a6f21d15SMark Johnston 	fault_type = fault_typea & VM_PROT_ALL;
49672db65ab4SAlan Cox 	if ((fault_type & prot) != fault_type || prot == VM_PROT_NONE) {
4968095104acSAlan Cox 		vm_map_unlock_read(map);
4969095104acSAlan Cox 		return (KERN_PROTECTION_FAILURE);
497047221757SJohn Dyson 	}
4971b8db9776SKonstantin Belousov 	KASSERT((prot & VM_PROT_WRITE) == 0 || (entry->eflags &
4972b8db9776SKonstantin Belousov 	    (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY)) !=
4973b8db9776SKonstantin Belousov 	    (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY),
4974b8db9776SKonstantin Belousov 	    ("entry %p flags %x", entry, entry->eflags));
49755b3e0257SDag-Erling Smørgrav 	if ((fault_typea & VM_PROT_COPY) != 0 &&
49765b3e0257SDag-Erling Smørgrav 	    (entry->max_protection & VM_PROT_WRITE) == 0 &&
49775b3e0257SDag-Erling Smørgrav 	    (entry->eflags & MAP_ENTRY_COW) == 0) {
49785b3e0257SDag-Erling Smørgrav 		vm_map_unlock_read(map);
49795b3e0257SDag-Erling Smørgrav 		return (KERN_PROTECTION_FAILURE);
49805b3e0257SDag-Erling Smørgrav 	}
4981df8bae1dSRodney W. Grimes 
4982df8bae1dSRodney W. Grimes 	/*
49830d94caffSDavid Greenman 	 * If this page is not pageable, we have to get it for all possible
49840d94caffSDavid Greenman 	 * accesses.
4985df8bae1dSRodney W. Grimes 	 */
498605f0fdd2SPoul-Henning Kamp 	*wired = (entry->wired_count != 0);
498705f0fdd2SPoul-Henning Kamp 	if (*wired)
4988a6d42a0dSAlan Cox 		fault_type = entry->protection;
49893364c323SKonstantin Belousov 	size = entry->end - entry->start;
499067388836SKonstantin Belousov 
4991df8bae1dSRodney W. Grimes 	/*
4992df8bae1dSRodney W. Grimes 	 * If the entry was copy-on-write, we either ...
4993df8bae1dSRodney W. Grimes 	 */
4994afa07f7eSJohn Dyson 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4995df8bae1dSRodney W. Grimes 		/*
49960d94caffSDavid Greenman 		 * If we want to write the page, we may as well handle that
4997ad5fca3bSAlan Cox 		 * now since we've got the map locked.
4998df8bae1dSRodney W. Grimes 		 *
49990d94caffSDavid Greenman 		 * If we don't need to write the page, we just demote the
50000d94caffSDavid Greenman 		 * permissions allowed.
5001df8bae1dSRodney W. Grimes 		 */
5002a6d42a0dSAlan Cox 		if ((fault_type & VM_PROT_WRITE) != 0 ||
5003a6d42a0dSAlan Cox 		    (fault_typea & VM_PROT_COPY) != 0) {
5004df8bae1dSRodney W. Grimes 			/*
50050d94caffSDavid Greenman 			 * Make a new object, and place it in the object
50060d94caffSDavid Greenman 			 * chain.  Note that no new references have appeared
5007ad5fca3bSAlan Cox 			 * -- one just moved from the map to the new
50080d94caffSDavid Greenman 			 * object.
5009df8bae1dSRodney W. Grimes 			 */
501025adb370SBrian Feldman 			if (vm_map_lock_upgrade(map))
5011df8bae1dSRodney W. Grimes 				goto RetryLookup;
50129917e010SAlan Cox 
5013ef694c1aSEdward Tomasz Napierala 			if (entry->cred == NULL) {
50143364c323SKonstantin Belousov 				/*
50153364c323SKonstantin Belousov 				 * The debugger owner is charged for
50163364c323SKonstantin Belousov 				 * the memory.
50173364c323SKonstantin Belousov 				 */
5018ef694c1aSEdward Tomasz Napierala 				cred = curthread->td_ucred;
5019ef694c1aSEdward Tomasz Napierala 				crhold(cred);
5020ef694c1aSEdward Tomasz Napierala 				if (!swap_reserve_by_cred(size, cred)) {
5021ef694c1aSEdward Tomasz Napierala 					crfree(cred);
50223364c323SKonstantin Belousov 					vm_map_unlock(map);
50233364c323SKonstantin Belousov 					return (KERN_RESOURCE_SHORTAGE);
50243364c323SKonstantin Belousov 				}
5025ef694c1aSEdward Tomasz Napierala 				entry->cred = cred;
50263364c323SKonstantin Belousov 			}
50273364c323SKonstantin Belousov 			eobject = entry->object.vm_object;
502867388836SKonstantin Belousov 			vm_object_shadow(&entry->object.vm_object,
502967388836SKonstantin Belousov 			    &entry->offset, size, entry->cred, false);
503067388836SKonstantin Belousov 			if (eobject == entry->object.vm_object) {
50313364c323SKonstantin Belousov 				/*
50323364c323SKonstantin Belousov 				 * The object was not shadowed.
50333364c323SKonstantin Belousov 				 */
5034ef694c1aSEdward Tomasz Napierala 				swap_release_by_cred(size, entry->cred);
5035ef694c1aSEdward Tomasz Napierala 				crfree(entry->cred);
50363364c323SKonstantin Belousov 			}
503767388836SKonstantin Belousov 			entry->cred = NULL;
503867388836SKonstantin Belousov 			entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
50399917e010SAlan Cox 
50409b09b6c7SMatthew Dillon 			vm_map_lock_downgrade(map);
50410d94caffSDavid Greenman 		} else {
5042df8bae1dSRodney W. Grimes 			/*
50430d94caffSDavid Greenman 			 * We're attempting to read a copy-on-write page --
50440d94caffSDavid Greenman 			 * don't allow writes.
5045df8bae1dSRodney W. Grimes 			 */
50462d8acc0fSJohn Dyson 			prot &= ~VM_PROT_WRITE;
5047df8bae1dSRodney W. Grimes 		}
5048df8bae1dSRodney W. Grimes 	}
50492d8acc0fSJohn Dyson 
5050df8bae1dSRodney W. Grimes 	/*
5051df8bae1dSRodney W. Grimes 	 * Create an object if necessary.
5052df8bae1dSRodney W. Grimes 	 */
505367388836SKonstantin Belousov 	if (entry->object.vm_object == NULL && !map->system_map) {
505425adb370SBrian Feldman 		if (vm_map_lock_upgrade(map))
5055df8bae1dSRodney W. Grimes 			goto RetryLookup;
505667388836SKonstantin Belousov 		entry->object.vm_object = vm_object_allocate_anon(atop(size),
505770b29961SMark Johnston 		    NULL, entry->cred, size);
5058df8bae1dSRodney W. Grimes 		entry->offset = 0;
5059ef694c1aSEdward Tomasz Napierala 		entry->cred = NULL;
50609b09b6c7SMatthew Dillon 		vm_map_lock_downgrade(map);
5061df8bae1dSRodney W. Grimes 	}
5062b5b40fa6SJohn Dyson 
5063df8bae1dSRodney W. Grimes 	/*
50640d94caffSDavid Greenman 	 * Return the object/offset from this entry.  If the entry was
50650d94caffSDavid Greenman 	 * copy-on-write or empty, it has been fixed up.
5066df8bae1dSRodney W. Grimes 	 */
506710d9120cSKonstantin Belousov 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
5068df8bae1dSRodney W. Grimes 	*object = entry->object.vm_object;
5069df8bae1dSRodney W. Grimes 
5070df8bae1dSRodney W. Grimes 	*out_prot = prot;
5071df8bae1dSRodney W. Grimes 	return (KERN_SUCCESS);
5072df8bae1dSRodney W. Grimes }
5073df8bae1dSRodney W. Grimes 
5074df8bae1dSRodney W. Grimes /*
507519dc5607STor Egge  *	vm_map_lookup_locked:
507619dc5607STor Egge  *
507719dc5607STor Egge  *	Lookup the faulting address.  A version of vm_map_lookup that returns
507819dc5607STor Egge  *      KERN_FAILURE instead of blocking on map lock or memory allocation.
507919dc5607STor Egge  */
508019dc5607STor Egge int
508119dc5607STor Egge vm_map_lookup_locked(vm_map_t *var_map,		/* IN/OUT */
508219dc5607STor Egge 		     vm_offset_t vaddr,
508319dc5607STor Egge 		     vm_prot_t fault_typea,
508419dc5607STor Egge 		     vm_map_entry_t *out_entry,	/* OUT */
508519dc5607STor Egge 		     vm_object_t *object,	/* OUT */
508619dc5607STor Egge 		     vm_pindex_t *pindex,	/* OUT */
508719dc5607STor Egge 		     vm_prot_t *out_prot,	/* OUT */
508819dc5607STor Egge 		     boolean_t *wired)		/* OUT */
508919dc5607STor Egge {
509019dc5607STor Egge 	vm_map_entry_t entry;
509119dc5607STor Egge 	vm_map_t map = *var_map;
509219dc5607STor Egge 	vm_prot_t prot;
509319dc5607STor Egge 	vm_prot_t fault_type = fault_typea;
509419dc5607STor Egge 
509519dc5607STor Egge 	/*
50964c3ef59eSAlan Cox 	 * Lookup the faulting address.
509719dc5607STor Egge 	 */
509819dc5607STor Egge 	if (!vm_map_lookup_entry(map, vaddr, out_entry))
509919dc5607STor Egge 		return (KERN_INVALID_ADDRESS);
510019dc5607STor Egge 
510119dc5607STor Egge 	entry = *out_entry;
510219dc5607STor Egge 
510319dc5607STor Egge 	/*
510419dc5607STor Egge 	 * Fail if the entry refers to a submap.
510519dc5607STor Egge 	 */
510619dc5607STor Egge 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
510719dc5607STor Egge 		return (KERN_FAILURE);
510819dc5607STor Egge 
510919dc5607STor Egge 	/*
511019dc5607STor Egge 	 * Check whether this task is allowed to have this page.
511119dc5607STor Egge 	 */
511219dc5607STor Egge 	prot = entry->protection;
511319dc5607STor Egge 	fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
511419dc5607STor Egge 	if ((fault_type & prot) != fault_type)
511519dc5607STor Egge 		return (KERN_PROTECTION_FAILURE);
511619dc5607STor Egge 
511719dc5607STor Egge 	/*
511819dc5607STor Egge 	 * If this page is not pageable, we have to get it for all possible
511919dc5607STor Egge 	 * accesses.
512019dc5607STor Egge 	 */
512119dc5607STor Egge 	*wired = (entry->wired_count != 0);
512219dc5607STor Egge 	if (*wired)
5123a6d42a0dSAlan Cox 		fault_type = entry->protection;
512419dc5607STor Egge 
512519dc5607STor Egge 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
512619dc5607STor Egge 		/*
512719dc5607STor Egge 		 * Fail if the entry was copy-on-write for a write fault.
512819dc5607STor Egge 		 */
512919dc5607STor Egge 		if (fault_type & VM_PROT_WRITE)
513019dc5607STor Egge 			return (KERN_FAILURE);
513119dc5607STor Egge 		/*
513219dc5607STor Egge 		 * We're attempting to read a copy-on-write page --
513319dc5607STor Egge 		 * don't allow writes.
513419dc5607STor Egge 		 */
513519dc5607STor Egge 		prot &= ~VM_PROT_WRITE;
513619dc5607STor Egge 	}
513719dc5607STor Egge 
513819dc5607STor Egge 	/*
513919dc5607STor Egge 	 * Fail if an object should be created.
514019dc5607STor Egge 	 */
514119dc5607STor Egge 	if (entry->object.vm_object == NULL && !map->system_map)
514219dc5607STor Egge 		return (KERN_FAILURE);
514319dc5607STor Egge 
514419dc5607STor Egge 	/*
514519dc5607STor Egge 	 * Return the object/offset from this entry.  If the entry was
514619dc5607STor Egge 	 * copy-on-write or empty, it has been fixed up.
514719dc5607STor Egge 	 */
514810d9120cSKonstantin Belousov 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
514919dc5607STor Egge 	*object = entry->object.vm_object;
515019dc5607STor Egge 
515119dc5607STor Egge 	*out_prot = prot;
515219dc5607STor Egge 	return (KERN_SUCCESS);
515319dc5607STor Egge }
515419dc5607STor Egge 
515519dc5607STor Egge /*
5156df8bae1dSRodney W. Grimes  *	vm_map_lookup_done:
5157df8bae1dSRodney W. Grimes  *
5158df8bae1dSRodney W. Grimes  *	Releases locks acquired by a vm_map_lookup
5159df8bae1dSRodney W. Grimes  *	(according to the handle returned by that lookup).
5160df8bae1dSRodney W. Grimes  */
51610d94caffSDavid Greenman void
51621b40f8c0SMatthew Dillon vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
5163df8bae1dSRodney W. Grimes {
5164df8bae1dSRodney W. Grimes 	/*
5165df8bae1dSRodney W. Grimes 	 * Unlock the main-level map
5166df8bae1dSRodney W. Grimes 	 */
5167df8bae1dSRodney W. Grimes 	vm_map_unlock_read(map);
5168df8bae1dSRodney W. Grimes }
5169df8bae1dSRodney W. Grimes 
517019ea042eSKonstantin Belousov vm_offset_t
517119ea042eSKonstantin Belousov vm_map_max_KBI(const struct vm_map *map)
517219ea042eSKonstantin Belousov {
517319ea042eSKonstantin Belousov 
5174f0165b1cSKonstantin Belousov 	return (vm_map_max(map));
517519ea042eSKonstantin Belousov }
517619ea042eSKonstantin Belousov 
517719ea042eSKonstantin Belousov vm_offset_t
517819ea042eSKonstantin Belousov vm_map_min_KBI(const struct vm_map *map)
517919ea042eSKonstantin Belousov {
518019ea042eSKonstantin Belousov 
5181f0165b1cSKonstantin Belousov 	return (vm_map_min(map));
518219ea042eSKonstantin Belousov }
518319ea042eSKonstantin Belousov 
518419ea042eSKonstantin Belousov pmap_t
518519ea042eSKonstantin Belousov vm_map_pmap_KBI(vm_map_t map)
518619ea042eSKonstantin Belousov {
518719ea042eSKonstantin Belousov 
518819ea042eSKonstantin Belousov 	return (map->pmap);
518919ea042eSKonstantin Belousov }
519019ea042eSKonstantin Belousov 
5191a7752896SMark Johnston bool
5192a7752896SMark Johnston vm_map_range_valid_KBI(vm_map_t map, vm_offset_t start, vm_offset_t end)
5193a7752896SMark Johnston {
5194a7752896SMark Johnston 
5195a7752896SMark Johnston 	return (vm_map_range_valid(map, start, end));
5196a7752896SMark Johnston }
5197a7752896SMark Johnston 
5198721899b1SDoug Moore #ifdef INVARIANTS
5199721899b1SDoug Moore static void
5200461587dcSDoug Moore _vm_map_assert_consistent(vm_map_t map, int check)
5201721899b1SDoug Moore {
5202721899b1SDoug Moore 	vm_map_entry_t entry, prev;
5203c1ad5342SDoug Moore 	vm_map_entry_t cur, header, lbound, ubound;
5204721899b1SDoug Moore 	vm_size_t max_left, max_right;
5205721899b1SDoug Moore 
520685b7bedbSDoug Moore #ifdef DIAGNOSTIC
520785b7bedbSDoug Moore 	++map->nupdates;
520885b7bedbSDoug Moore #endif
5209461587dcSDoug Moore 	if (enable_vmmap_check != check)
5210721899b1SDoug Moore 		return;
5211721899b1SDoug Moore 
5212c1ad5342SDoug Moore 	header = prev = &map->header;
5213721899b1SDoug Moore 	VM_MAP_ENTRY_FOREACH(entry, map) {
5214721899b1SDoug Moore 		KASSERT(prev->end <= entry->start,
5215721899b1SDoug Moore 		    ("map %p prev->end = %jx, start = %jx", map,
5216721899b1SDoug Moore 		    (uintmax_t)prev->end, (uintmax_t)entry->start));
5217721899b1SDoug Moore 		KASSERT(entry->start < entry->end,
5218721899b1SDoug Moore 		    ("map %p start = %jx, end = %jx", map,
5219721899b1SDoug Moore 		    (uintmax_t)entry->start, (uintmax_t)entry->end));
5220c1ad5342SDoug Moore 		KASSERT(entry->left == header ||
5221721899b1SDoug Moore 		    entry->left->start < entry->start,
5222721899b1SDoug Moore 		    ("map %p left->start = %jx, start = %jx", map,
5223721899b1SDoug Moore 		    (uintmax_t)entry->left->start, (uintmax_t)entry->start));
5224c1ad5342SDoug Moore 		KASSERT(entry->right == header ||
5225721899b1SDoug Moore 		    entry->start < entry->right->start,
5226721899b1SDoug Moore 		    ("map %p start = %jx, right->start = %jx", map,
5227721899b1SDoug Moore 		    (uintmax_t)entry->start, (uintmax_t)entry->right->start));
5228c1ad5342SDoug Moore 		cur = map->root;
5229c1ad5342SDoug Moore 		lbound = ubound = header;
5230c1ad5342SDoug Moore 		for (;;) {
5231c1ad5342SDoug Moore 			if (entry->start < cur->start) {
5232c1ad5342SDoug Moore 				ubound = cur;
5233c1ad5342SDoug Moore 				cur = cur->left;
5234c1ad5342SDoug Moore 				KASSERT(cur != lbound,
5235c1ad5342SDoug Moore 				    ("map %p cannot find %jx",
5236c0829bb1SMark Johnston 				    map, (uintmax_t)entry->start));
5237c1ad5342SDoug Moore 			} else if (cur->end <= entry->start) {
5238c1ad5342SDoug Moore 				lbound = cur;
5239c1ad5342SDoug Moore 				cur = cur->right;
5240c1ad5342SDoug Moore 				KASSERT(cur != ubound,
5241c1ad5342SDoug Moore 				    ("map %p cannot find %jx",
5242c0829bb1SMark Johnston 				    map, (uintmax_t)entry->start));
5243c1ad5342SDoug Moore 			} else {
5244c1ad5342SDoug Moore 				KASSERT(cur == entry,
5245c1ad5342SDoug Moore 				    ("map %p cannot find %jx",
5246c0829bb1SMark Johnston 				    map, (uintmax_t)entry->start));
5247c1ad5342SDoug Moore 				break;
5248c1ad5342SDoug Moore 			}
5249c1ad5342SDoug Moore 		}
5250c1ad5342SDoug Moore 		max_left = vm_map_entry_max_free_left(entry, lbound);
5251c1ad5342SDoug Moore 		max_right = vm_map_entry_max_free_right(entry, ubound);
5252c1ad5342SDoug Moore 		KASSERT(entry->max_free == vm_size_max(max_left, max_right),
5253721899b1SDoug Moore 		    ("map %p max = %jx, max_left = %jx, max_right = %jx", map,
5254721899b1SDoug Moore 		    (uintmax_t)entry->max_free,
5255721899b1SDoug Moore 		    (uintmax_t)max_left, (uintmax_t)max_right));
5256721899b1SDoug Moore 		prev = entry;
5257721899b1SDoug Moore 	}
5258721899b1SDoug Moore 	KASSERT(prev->end <= entry->start,
5259721899b1SDoug Moore 	    ("map %p prev->end = %jx, start = %jx", map,
5260721899b1SDoug Moore 	    (uintmax_t)prev->end, (uintmax_t)entry->start));
5261721899b1SDoug Moore }
5262721899b1SDoug Moore #endif
5263721899b1SDoug Moore 
5264c7c34a24SBruce Evans #include "opt_ddb.h"
5265c3cb3e12SDavid Greenman #ifdef DDB
5266c7c34a24SBruce Evans #include <sys/kernel.h>
5267c7c34a24SBruce Evans 
5268c7c34a24SBruce Evans #include <ddb/ddb.h>
5269c7c34a24SBruce Evans 
52702ebcd458SAttilio Rao static void
52712ebcd458SAttilio Rao vm_map_print(vm_map_t map)
5272df8bae1dSRodney W. Grimes {
527377131528SDoug Moore 	vm_map_entry_t entry, prev;
5274c7c34a24SBruce Evans 
5275e5f251d2SAlan Cox 	db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
5276e5f251d2SAlan Cox 	    (void *)map,
5277101eeb7fSBruce Evans 	    (void *)map->pmap, map->nentries, map->timestamp);
5278df8bae1dSRodney W. Grimes 
5279c7c34a24SBruce Evans 	db_indent += 2;
5280721899b1SDoug Moore 	prev = &map->header;
5281721899b1SDoug Moore 	VM_MAP_ENTRY_FOREACH(entry, map) {
528219bd0d9cSKonstantin Belousov 		db_iprintf("map entry %p: start=%p, end=%p, eflags=%#x, \n",
528319bd0d9cSKonstantin Belousov 		    (void *)entry, (void *)entry->start, (void *)entry->end,
528419bd0d9cSKonstantin Belousov 		    entry->eflags);
5285e5f251d2SAlan Cox 		{
5286eaa17d42SRyan Libby 			static const char * const inheritance_name[4] =
5287df8bae1dSRodney W. Grimes 			{"share", "copy", "none", "donate_copy"};
52880d94caffSDavid Greenman 
528995e5e988SJohn Dyson 			db_iprintf(" prot=%x/%x/%s",
5290df8bae1dSRodney W. Grimes 			    entry->protection,
5291df8bae1dSRodney W. Grimes 			    entry->max_protection,
529277131528SDoug Moore 			    inheritance_name[(int)(unsigned char)
529377131528SDoug Moore 			    entry->inheritance]);
5294df8bae1dSRodney W. Grimes 			if (entry->wired_count != 0)
529595e5e988SJohn Dyson 				db_printf(", wired");
5296df8bae1dSRodney W. Grimes 		}
52979fdfe602SMatthew Dillon 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
5298cd034a5bSMaxime Henrion 			db_printf(", share=%p, offset=0x%jx\n",
52999fdfe602SMatthew Dillon 			    (void *)entry->object.sub_map,
5300cd034a5bSMaxime Henrion 			    (uintmax_t)entry->offset);
530177131528SDoug Moore 			if (prev == &map->header ||
530277131528SDoug Moore 			    prev->object.sub_map !=
530377131528SDoug Moore 				entry->object.sub_map) {
5304c7c34a24SBruce Evans 				db_indent += 2;
53052ebcd458SAttilio Rao 				vm_map_print((vm_map_t)entry->object.sub_map);
5306c7c34a24SBruce Evans 				db_indent -= 2;
5307df8bae1dSRodney W. Grimes 			}
53080d94caffSDavid Greenman 		} else {
5309ef694c1aSEdward Tomasz Napierala 			if (entry->cred != NULL)
5310ef694c1aSEdward Tomasz Napierala 				db_printf(", ruid %d", entry->cred->cr_ruid);
5311cd034a5bSMaxime Henrion 			db_printf(", object=%p, offset=0x%jx",
5312101eeb7fSBruce Evans 			    (void *)entry->object.vm_object,
5313cd034a5bSMaxime Henrion 			    (uintmax_t)entry->offset);
5314ef694c1aSEdward Tomasz Napierala 			if (entry->object.vm_object && entry->object.vm_object->cred)
5315ef694c1aSEdward Tomasz Napierala 				db_printf(", obj ruid %d charge %jx",
5316ef694c1aSEdward Tomasz Napierala 				    entry->object.vm_object->cred->cr_ruid,
53173364c323SKonstantin Belousov 				    (uintmax_t)entry->object.vm_object->charge);
5318afa07f7eSJohn Dyson 			if (entry->eflags & MAP_ENTRY_COW)
5319c7c34a24SBruce Evans 				db_printf(", copy (%s)",
5320afa07f7eSJohn Dyson 				    (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
5321c7c34a24SBruce Evans 			db_printf("\n");
5322df8bae1dSRodney W. Grimes 
532377131528SDoug Moore 			if (prev == &map->header ||
532477131528SDoug Moore 			    prev->object.vm_object !=
532577131528SDoug Moore 				entry->object.vm_object) {
5326c7c34a24SBruce Evans 				db_indent += 2;
5327101eeb7fSBruce Evans 				vm_object_print((db_expr_t)(intptr_t)
5328101eeb7fSBruce Evans 						entry->object.vm_object,
532944bbc3b7SKonstantin Belousov 						0, 0, (char *)0);
5330c7c34a24SBruce Evans 				db_indent -= 2;
5331df8bae1dSRodney W. Grimes 			}
5332df8bae1dSRodney W. Grimes 		}
5333721899b1SDoug Moore 		prev = entry;
5334df8bae1dSRodney W. Grimes 	}
5335c7c34a24SBruce Evans 	db_indent -= 2;
5336df8bae1dSRodney W. Grimes }
533795e5e988SJohn Dyson 
53382ebcd458SAttilio Rao DB_SHOW_COMMAND(map, map)
53392ebcd458SAttilio Rao {
53402ebcd458SAttilio Rao 
53412ebcd458SAttilio Rao 	if (!have_addr) {
53422ebcd458SAttilio Rao 		db_printf("usage: show map <addr>\n");
53432ebcd458SAttilio Rao 		return;
53442ebcd458SAttilio Rao 	}
53452ebcd458SAttilio Rao 	vm_map_print((vm_map_t)addr);
53462ebcd458SAttilio Rao }
534795e5e988SJohn Dyson 
534895e5e988SJohn Dyson DB_SHOW_COMMAND(procvm, procvm)
534995e5e988SJohn Dyson {
535095e5e988SJohn Dyson 	struct proc *p;
535195e5e988SJohn Dyson 
535295e5e988SJohn Dyson 	if (have_addr) {
5353a9546a6bSJohn Baldwin 		p = db_lookup_proc(addr);
535495e5e988SJohn Dyson 	} else {
535595e5e988SJohn Dyson 		p = curproc;
535695e5e988SJohn Dyson 	}
535795e5e988SJohn Dyson 
5358ac1e407bSBruce Evans 	db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
5359ac1e407bSBruce Evans 	    (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
5360b1028ad1SLuoqi Chen 	    (void *)vmspace_pmap(p->p_vmspace));
536195e5e988SJohn Dyson 
53622ebcd458SAttilio Rao 	vm_map_print((vm_map_t)&p->p_vmspace->vm_map);
536395e5e988SJohn Dyson }
536495e5e988SJohn Dyson 
5365c7c34a24SBruce Evans #endif /* DDB */
5366