1 /*-
2  * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * The Mach Operating System project at Carnegie-Mellon University.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	from: @(#)vm_map.c	8.3 (Berkeley) 1/12/94
35  *
36  *
37  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38  * All rights reserved.
39  *
40  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41  *
42  * Permission to use, copy, modify and distribute this software and
43  * its documentation is hereby granted, provided that both the copyright
44  * notice and this permission notice appear in all copies of the
45  * software, derivative works or modified versions, and any portions
46  * thereof, and that both notices appear in supporting documentation.
47  *
48  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51  *
52  * Carnegie Mellon requests users of this software to return to
53  *
54  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55  *  School of Computer Science
56  *  Carnegie Mellon University
57  *  Pittsburgh PA 15213-3890
58  *
59  * any improvements or extensions that they make and grant Carnegie the
60  * rights to redistribute these changes.
61  */
62 
63 /*
64  *	Virtual memory mapping module.
65  */
66 
67 #include <sys/cdefs.h>
68 __FBSDID("$FreeBSD: stable/12/sys/vm/vm_map.c 365806 2020-09-16 15:48:32Z kib $");
69 
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/elf.h>
73 #include <sys/kernel.h>
74 #include <sys/ktr.h>
75 #include <sys/lock.h>
76 #include <sys/mutex.h>
77 #include <sys/proc.h>
78 #include <sys/vmmeter.h>
79 #include <sys/mman.h>
80 #include <sys/vnode.h>
81 #include <sys/racct.h>
82 #include <sys/resourcevar.h>
83 #include <sys/rwlock.h>
84 #include <sys/file.h>
85 #include <sys/sysctl.h>
86 #include <sys/sysent.h>
87 #include <sys/shm.h>
88 
89 #include <vm/vm.h>
90 #include <vm/vm_param.h>
91 #include <vm/pmap.h>
92 #include <vm/vm_map.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_pageout.h>
95 #include <vm/vm_object.h>
96 #include <vm/vm_pager.h>
97 #include <vm/vm_kern.h>
98 #include <vm/vm_extern.h>
99 #include <vm/vnode_pager.h>
100 #include <vm/swap_pager.h>
101 #include <vm/uma.h>
102 
103 /*
104  *	Virtual memory maps provide for the mapping, protection,
105  *	and sharing of virtual memory objects.  In addition,
106  *	this module provides for an efficient virtual copy of
107  *	memory from one map to another.
108  *
109  *	Synchronization is required prior to most operations.
110  *
111  *	Maps consist of an ordered doubly-linked list of simple
112  *	entries; a self-adjusting binary search tree of these
113  *	entries is used to speed up lookups.
114  *
115  *	Since portions of maps are specified by start/end addresses,
116  *	which may not align with existing map entries, all
117  *	routines merely "clip" entries to these start/end values.
118  *	[That is, an entry is split into two, bordering at a
119  *	start or end value.]  Note that these clippings may not
120  *	always be necessary (as the two resulting entries are then
121  *	not changed); however, the clipping is done for convenience.
122  *
123  *	As mentioned above, virtual copy operations are performed
124  *	by copying VM object references from one map to
125  *	another, and then marking both regions as copy-on-write.
126  */
127 
128 static struct mtx map_sleep_mtx;
129 static uma_zone_t mapentzone;
130 static uma_zone_t kmapentzone;
131 static uma_zone_t mapzone;
132 static uma_zone_t vmspace_zone;
133 static int vmspace_zinit(void *mem, int size, int flags);
134 static int vm_map_zinit(void *mem, int ize, int flags);
135 static void _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min,
136     vm_offset_t max);
137 static void vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map);
138 static void vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry);
139 static void vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry);
140 static int vm_map_growstack(vm_map_t map, vm_offset_t addr,
141     vm_map_entry_t gap_entry);
142 static void vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
143     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags);
144 #ifdef INVARIANTS
145 static void vm_map_zdtor(void *mem, int size, void *arg);
146 static void vmspace_zdtor(void *mem, int size, void *arg);
147 #endif
148 static int vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos,
149     vm_size_t max_ssize, vm_size_t growsize, vm_prot_t prot, vm_prot_t max,
150     int cow);
151 static void vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
152     vm_offset_t failed_addr);
153 
154 #define	ENTRY_CHARGED(e) ((e)->cred != NULL || \
155     ((e)->object.vm_object != NULL && (e)->object.vm_object->cred != NULL && \
156      !((e)->eflags & MAP_ENTRY_NEEDS_COPY)))
157 
158 /*
159  * PROC_VMSPACE_{UN,}LOCK() can be a noop as long as vmspaces are type
160  * stable.
161  */
162 #define PROC_VMSPACE_LOCK(p) do { } while (0)
163 #define PROC_VMSPACE_UNLOCK(p) do { } while (0)
164 
165 /*
166  *	VM_MAP_RANGE_CHECK:	[ internal use only ]
167  *
168  *	Asserts that the starting and ending region
169  *	addresses fall within the valid range of the map.
170  */
171 #define	VM_MAP_RANGE_CHECK(map, start, end)		\
172 		{					\
173 		if (start < vm_map_min(map))		\
174 			start = vm_map_min(map);	\
175 		if (end > vm_map_max(map))		\
176 			end = vm_map_max(map);		\
177 		if (start > end)			\
178 			start = end;			\
179 		}
180 
181 /*
182  *	vm_map_startup:
183  *
184  *	Initialize the vm_map module.  Must be called before
185  *	any other vm_map routines.
186  *
187  *	Map and entry structures are allocated from the general
188  *	purpose memory pool with some exceptions:
189  *
190  *	- The kernel map and kmem submap are allocated statically.
191  *	- Kernel map entries are allocated out of a static pool.
192  *
193  *	These restrictions are necessary since malloc() uses the
194  *	maps and requires map entries.
195  */
196 
197 void
vm_map_startup(void)198 vm_map_startup(void)
199 {
200 	mtx_init(&map_sleep_mtx, "vm map sleep mutex", NULL, MTX_DEF);
201 	mapzone = uma_zcreate("MAP", sizeof(struct vm_map), NULL,
202 #ifdef INVARIANTS
203 	    vm_map_zdtor,
204 #else
205 	    NULL,
206 #endif
207 	    vm_map_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
208 	uma_prealloc(mapzone, MAX_KMAP);
209 	kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry),
210 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
211 	    UMA_ZONE_MTXCLASS | UMA_ZONE_VM);
212 	mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry),
213 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
214 	vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
215 #ifdef INVARIANTS
216 	    vmspace_zdtor,
217 #else
218 	    NULL,
219 #endif
220 	    vmspace_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
221 }
222 
223 static int
vmspace_zinit(void * mem,int size,int flags)224 vmspace_zinit(void *mem, int size, int flags)
225 {
226 	struct vmspace *vm;
227 
228 	vm = (struct vmspace *)mem;
229 
230 	vm->vm_map.pmap = NULL;
231 	(void)vm_map_zinit(&vm->vm_map, sizeof(vm->vm_map), flags);
232 	PMAP_LOCK_INIT(vmspace_pmap(vm));
233 	return (0);
234 }
235 
236 static int
vm_map_zinit(void * mem,int size,int flags)237 vm_map_zinit(void *mem, int size, int flags)
238 {
239 	vm_map_t map;
240 
241 	map = (vm_map_t)mem;
242 	memset(map, 0, sizeof(*map));
243 	mtx_init(&map->system_mtx, "vm map (system)", NULL, MTX_DEF | MTX_DUPOK);
244 	sx_init(&map->lock, "vm map (user)");
245 	return (0);
246 }
247 
248 #ifdef INVARIANTS
249 static void
vmspace_zdtor(void * mem,int size,void * arg)250 vmspace_zdtor(void *mem, int size, void *arg)
251 {
252 	struct vmspace *vm;
253 
254 	vm = (struct vmspace *)mem;
255 
256 	vm_map_zdtor(&vm->vm_map, sizeof(vm->vm_map), arg);
257 }
258 static void
vm_map_zdtor(void * mem,int size,void * arg)259 vm_map_zdtor(void *mem, int size, void *arg)
260 {
261 	vm_map_t map;
262 
263 	map = (vm_map_t)mem;
264 	KASSERT(map->nentries == 0,
265 	    ("map %p nentries == %d on free.",
266 	    map, map->nentries));
267 	KASSERT(map->size == 0,
268 	    ("map %p size == %lu on free.",
269 	    map, (unsigned long)map->size));
270 }
271 #endif	/* INVARIANTS */
272 
273 /*
274  * Allocate a vmspace structure, including a vm_map and pmap,
275  * and initialize those structures.  The refcnt is set to 1.
276  *
277  * If 'pinit' is NULL then the embedded pmap is initialized via pmap_pinit().
278  */
279 struct vmspace *
vmspace_alloc(vm_offset_t min,vm_offset_t max,pmap_pinit_t pinit)280 vmspace_alloc(vm_offset_t min, vm_offset_t max, pmap_pinit_t pinit)
281 {
282 	struct vmspace *vm;
283 
284 	vm = uma_zalloc(vmspace_zone, M_WAITOK);
285 	KASSERT(vm->vm_map.pmap == NULL, ("vm_map.pmap must be NULL"));
286 	if (!pinit(vmspace_pmap(vm))) {
287 		uma_zfree(vmspace_zone, vm);
288 		return (NULL);
289 	}
290 	CTR1(KTR_VM, "vmspace_alloc: %p", vm);
291 	_vm_map_init(&vm->vm_map, vmspace_pmap(vm), min, max);
292 	vm->vm_refcnt = 1;
293 	vm->vm_shm = NULL;
294 	vm->vm_swrss = 0;
295 	vm->vm_tsize = 0;
296 	vm->vm_dsize = 0;
297 	vm->vm_ssize = 0;
298 	vm->vm_taddr = 0;
299 	vm->vm_daddr = 0;
300 	vm->vm_maxsaddr = 0;
301 	return (vm);
302 }
303 
304 #ifdef RACCT
305 static void
vmspace_container_reset(struct proc * p)306 vmspace_container_reset(struct proc *p)
307 {
308 
309 	PROC_LOCK(p);
310 	racct_set(p, RACCT_DATA, 0);
311 	racct_set(p, RACCT_STACK, 0);
312 	racct_set(p, RACCT_RSS, 0);
313 	racct_set(p, RACCT_MEMLOCK, 0);
314 	racct_set(p, RACCT_VMEM, 0);
315 	PROC_UNLOCK(p);
316 }
317 #endif
318 
319 static inline void
vmspace_dofree(struct vmspace * vm)320 vmspace_dofree(struct vmspace *vm)
321 {
322 
323 	CTR1(KTR_VM, "vmspace_free: %p", vm);
324 
325 	/*
326 	 * Make sure any SysV shm is freed, it might not have been in
327 	 * exit1().
328 	 */
329 	shmexit(vm);
330 
331 	/*
332 	 * Lock the map, to wait out all other references to it.
333 	 * Delete all of the mappings and pages they hold, then call
334 	 * the pmap module to reclaim anything left.
335 	 */
336 	(void)vm_map_remove(&vm->vm_map, vm_map_min(&vm->vm_map),
337 	    vm_map_max(&vm->vm_map));
338 
339 	pmap_release(vmspace_pmap(vm));
340 	vm->vm_map.pmap = NULL;
341 	uma_zfree(vmspace_zone, vm);
342 }
343 
344 void
vmspace_free(struct vmspace * vm)345 vmspace_free(struct vmspace *vm)
346 {
347 
348 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
349 	    "vmspace_free() called");
350 
351 	if (vm->vm_refcnt == 0)
352 		panic("vmspace_free: attempt to free already freed vmspace");
353 
354 	if (atomic_fetchadd_int(&vm->vm_refcnt, -1) == 1)
355 		vmspace_dofree(vm);
356 }
357 
358 void
vmspace_exitfree(struct proc * p)359 vmspace_exitfree(struct proc *p)
360 {
361 	struct vmspace *vm;
362 
363 	PROC_VMSPACE_LOCK(p);
364 	vm = p->p_vmspace;
365 	p->p_vmspace = NULL;
366 	PROC_VMSPACE_UNLOCK(p);
367 	KASSERT(vm == &vmspace0, ("vmspace_exitfree: wrong vmspace"));
368 	vmspace_free(vm);
369 }
370 
371 void
vmspace_exit(struct thread * td)372 vmspace_exit(struct thread *td)
373 {
374 	int refcnt;
375 	struct vmspace *vm;
376 	struct proc *p;
377 
378 	/*
379 	 * Release user portion of address space.
380 	 * This releases references to vnodes,
381 	 * which could cause I/O if the file has been unlinked.
382 	 * Need to do this early enough that we can still sleep.
383 	 *
384 	 * The last exiting process to reach this point releases as
385 	 * much of the environment as it can. vmspace_dofree() is the
386 	 * slower fallback in case another process had a temporary
387 	 * reference to the vmspace.
388 	 */
389 
390 	p = td->td_proc;
391 	vm = p->p_vmspace;
392 	atomic_add_int(&vmspace0.vm_refcnt, 1);
393 	do {
394 		refcnt = vm->vm_refcnt;
395 		if (refcnt > 1 && p->p_vmspace != &vmspace0) {
396 			/* Switch now since other proc might free vmspace */
397 			PROC_VMSPACE_LOCK(p);
398 			p->p_vmspace = &vmspace0;
399 			PROC_VMSPACE_UNLOCK(p);
400 			pmap_activate(td);
401 		}
402 	} while (!atomic_cmpset_int(&vm->vm_refcnt, refcnt, refcnt - 1));
403 	if (refcnt == 1) {
404 		if (p->p_vmspace != vm) {
405 			/* vmspace not yet freed, switch back */
406 			PROC_VMSPACE_LOCK(p);
407 			p->p_vmspace = vm;
408 			PROC_VMSPACE_UNLOCK(p);
409 			pmap_activate(td);
410 		}
411 		pmap_remove_pages(vmspace_pmap(vm));
412 		/* Switch now since this proc will free vmspace */
413 		PROC_VMSPACE_LOCK(p);
414 		p->p_vmspace = &vmspace0;
415 		PROC_VMSPACE_UNLOCK(p);
416 		pmap_activate(td);
417 		vmspace_dofree(vm);
418 	}
419 #ifdef RACCT
420 	if (racct_enable)
421 		vmspace_container_reset(p);
422 #endif
423 }
424 
425 /* Acquire reference to vmspace owned by another process. */
426 
427 struct vmspace *
vmspace_acquire_ref(struct proc * p)428 vmspace_acquire_ref(struct proc *p)
429 {
430 	struct vmspace *vm;
431 	int refcnt;
432 
433 	PROC_VMSPACE_LOCK(p);
434 	vm = p->p_vmspace;
435 	if (vm == NULL) {
436 		PROC_VMSPACE_UNLOCK(p);
437 		return (NULL);
438 	}
439 	do {
440 		refcnt = vm->vm_refcnt;
441 		if (refcnt <= 0) { 	/* Avoid 0->1 transition */
442 			PROC_VMSPACE_UNLOCK(p);
443 			return (NULL);
444 		}
445 	} while (!atomic_cmpset_int(&vm->vm_refcnt, refcnt, refcnt + 1));
446 	if (vm != p->p_vmspace) {
447 		PROC_VMSPACE_UNLOCK(p);
448 		vmspace_free(vm);
449 		return (NULL);
450 	}
451 	PROC_VMSPACE_UNLOCK(p);
452 	return (vm);
453 }
454 
455 /*
456  * Switch between vmspaces in an AIO kernel process.
457  *
458  * The new vmspace is either the vmspace of a user process obtained
459  * from an active AIO request or the initial vmspace of the AIO kernel
460  * process (when it is idling).  Because user processes will block to
461  * drain any active AIO requests before proceeding in exit() or
462  * execve(), the reference count for vmspaces from AIO requests can
463  * never be 0.  Similarly, AIO kernel processes hold an extra
464  * reference on their initial vmspace for the life of the process.  As
465  * a result, the 'newvm' vmspace always has a non-zero reference
466  * count.  This permits an additional reference on 'newvm' to be
467  * acquired via a simple atomic increment rather than the loop in
468  * vmspace_acquire_ref() above.
469  */
470 void
vmspace_switch_aio(struct vmspace * newvm)471 vmspace_switch_aio(struct vmspace *newvm)
472 {
473 	struct vmspace *oldvm;
474 
475 	/* XXX: Need some way to assert that this is an aio daemon. */
476 
477 	KASSERT(newvm->vm_refcnt > 0,
478 	    ("vmspace_switch_aio: newvm unreferenced"));
479 
480 	oldvm = curproc->p_vmspace;
481 	if (oldvm == newvm)
482 		return;
483 
484 	/*
485 	 * Point to the new address space and refer to it.
486 	 */
487 	curproc->p_vmspace = newvm;
488 	atomic_add_int(&newvm->vm_refcnt, 1);
489 
490 	/* Activate the new mapping. */
491 	pmap_activate(curthread);
492 
493 	vmspace_free(oldvm);
494 }
495 
496 void
_vm_map_lock(vm_map_t map,const char * file,int line)497 _vm_map_lock(vm_map_t map, const char *file, int line)
498 {
499 
500 	if (map->system_map)
501 		mtx_lock_flags_(&map->system_mtx, 0, file, line);
502 	else
503 		sx_xlock_(&map->lock, file, line);
504 	map->timestamp++;
505 }
506 
507 void
vm_map_entry_set_vnode_text(vm_map_entry_t entry,bool add)508 vm_map_entry_set_vnode_text(vm_map_entry_t entry, bool add)
509 {
510 	vm_object_t object, object1;
511 	struct vnode *vp;
512 
513 	if ((entry->eflags & MAP_ENTRY_VN_EXEC) == 0)
514 		return;
515 	KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
516 	    ("Submap with execs"));
517 	object = entry->object.vm_object;
518 	KASSERT(object != NULL, ("No object for text, entry %p", entry));
519 	VM_OBJECT_RLOCK(object);
520 	while ((object1 = object->backing_object) != NULL) {
521 		VM_OBJECT_RLOCK(object1);
522 		VM_OBJECT_RUNLOCK(object);
523 		object = object1;
524 	}
525 
526 	vp = NULL;
527 	if (object->type == OBJT_DEAD) {
528 		/*
529 		 * For OBJT_DEAD objects, v_writecount was handled in
530 		 * vnode_pager_dealloc().
531 		 */
532 	} else if (object->type == OBJT_VNODE) {
533 		vp = object->handle;
534 	} else if (object->type == OBJT_SWAP) {
535 		KASSERT((object->flags & OBJ_TMPFS_NODE) != 0,
536 		    ("vm_map_entry_set_vnode_text: swap and !TMPFS "
537 		    "entry %p, object %p, add %d", entry, object, add));
538 		/*
539 		 * Tmpfs VREG node, which was reclaimed, has
540 		 * OBJ_TMPFS_NODE flag set, but not OBJ_TMPFS.  In
541 		 * this case there is no v_writecount to adjust.
542 		 */
543 		if ((object->flags & OBJ_TMPFS) != 0)
544 			vp = object->un_pager.swp.swp_tmpfs;
545 	} else {
546 		KASSERT(0,
547 		    ("vm_map_entry_set_vnode_text: wrong object type, "
548 		    "entry %p, object %p, add %d", entry, object, add));
549 	}
550 	if (vp != NULL) {
551 		if (add) {
552 			VOP_SET_TEXT_CHECKED(vp);
553 			VM_OBJECT_RUNLOCK(object);
554 		} else {
555 			vhold(vp);
556 			VM_OBJECT_RUNLOCK(object);
557 			vn_lock(vp, LK_SHARED | LK_RETRY);
558 			VOP_UNSET_TEXT_CHECKED(vp);
559 			VOP_UNLOCK(vp, 0);
560 			vdrop(vp);
561 		}
562 	} else {
563 		VM_OBJECT_RUNLOCK(object);
564 	}
565 }
566 
567 static void
vm_map_process_deferred(void)568 vm_map_process_deferred(void)
569 {
570 	struct thread *td;
571 	vm_map_entry_t entry, next;
572 	vm_object_t object;
573 
574 	td = curthread;
575 	entry = td->td_map_def_user;
576 	td->td_map_def_user = NULL;
577 	while (entry != NULL) {
578 		next = entry->next;
579 		MPASS((entry->eflags & (MAP_ENTRY_WRITECNT |
580 		    MAP_ENTRY_VN_EXEC)) != (MAP_ENTRY_WRITECNT |
581 		    MAP_ENTRY_VN_EXEC));
582 		if ((entry->eflags & MAP_ENTRY_WRITECNT) != 0) {
583 			/*
584 			 * Decrement the object's writemappings and
585 			 * possibly the vnode's v_writecount.
586 			 */
587 			KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
588 			    ("Submap with writecount"));
589 			object = entry->object.vm_object;
590 			KASSERT(object != NULL, ("No object for writecount"));
591 			vm_pager_release_writecount(object, entry->start,
592 			    entry->end);
593 		}
594 		vm_map_entry_set_vnode_text(entry, false);
595 		vm_map_entry_deallocate(entry, FALSE);
596 		entry = next;
597 	}
598 }
599 
600 void
_vm_map_unlock(vm_map_t map,const char * file,int line)601 _vm_map_unlock(vm_map_t map, const char *file, int line)
602 {
603 
604 	if (map->system_map)
605 		mtx_unlock_flags_(&map->system_mtx, 0, file, line);
606 	else {
607 		sx_xunlock_(&map->lock, file, line);
608 		vm_map_process_deferred();
609 	}
610 }
611 
612 void
_vm_map_lock_read(vm_map_t map,const char * file,int line)613 _vm_map_lock_read(vm_map_t map, const char *file, int line)
614 {
615 
616 	if (map->system_map)
617 		mtx_lock_flags_(&map->system_mtx, 0, file, line);
618 	else
619 		sx_slock_(&map->lock, file, line);
620 }
621 
622 void
_vm_map_unlock_read(vm_map_t map,const char * file,int line)623 _vm_map_unlock_read(vm_map_t map, const char *file, int line)
624 {
625 
626 	if (map->system_map)
627 		mtx_unlock_flags_(&map->system_mtx, 0, file, line);
628 	else {
629 		sx_sunlock_(&map->lock, file, line);
630 		vm_map_process_deferred();
631 	}
632 }
633 
634 int
_vm_map_trylock(vm_map_t map,const char * file,int line)635 _vm_map_trylock(vm_map_t map, const char *file, int line)
636 {
637 	int error;
638 
639 	error = map->system_map ?
640 	    !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
641 	    !sx_try_xlock_(&map->lock, file, line);
642 	if (error == 0)
643 		map->timestamp++;
644 	return (error == 0);
645 }
646 
647 int
_vm_map_trylock_read(vm_map_t map,const char * file,int line)648 _vm_map_trylock_read(vm_map_t map, const char *file, int line)
649 {
650 	int error;
651 
652 	error = map->system_map ?
653 	    !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
654 	    !sx_try_slock_(&map->lock, file, line);
655 	return (error == 0);
656 }
657 
658 /*
659  *	_vm_map_lock_upgrade:	[ internal use only ]
660  *
661  *	Tries to upgrade a read (shared) lock on the specified map to a write
662  *	(exclusive) lock.  Returns the value "0" if the upgrade succeeds and a
663  *	non-zero value if the upgrade fails.  If the upgrade fails, the map is
664  *	returned without a read or write lock held.
665  *
666  *	Requires that the map be read locked.
667  */
668 int
_vm_map_lock_upgrade(vm_map_t map,const char * file,int line)669 _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
670 {
671 	unsigned int last_timestamp;
672 
673 	if (map->system_map) {
674 		mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
675 	} else {
676 		if (!sx_try_upgrade_(&map->lock, file, line)) {
677 			last_timestamp = map->timestamp;
678 			sx_sunlock_(&map->lock, file, line);
679 			vm_map_process_deferred();
680 			/*
681 			 * If the map's timestamp does not change while the
682 			 * map is unlocked, then the upgrade succeeds.
683 			 */
684 			sx_xlock_(&map->lock, file, line);
685 			if (last_timestamp != map->timestamp) {
686 				sx_xunlock_(&map->lock, file, line);
687 				return (1);
688 			}
689 		}
690 	}
691 	map->timestamp++;
692 	return (0);
693 }
694 
695 void
_vm_map_lock_downgrade(vm_map_t map,const char * file,int line)696 _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
697 {
698 
699 	if (map->system_map) {
700 		mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
701 	} else
702 		sx_downgrade_(&map->lock, file, line);
703 }
704 
705 /*
706  *	vm_map_locked:
707  *
708  *	Returns a non-zero value if the caller holds a write (exclusive) lock
709  *	on the specified map and the value "0" otherwise.
710  */
711 int
vm_map_locked(vm_map_t map)712 vm_map_locked(vm_map_t map)
713 {
714 
715 	if (map->system_map)
716 		return (mtx_owned(&map->system_mtx));
717 	else
718 		return (sx_xlocked(&map->lock));
719 }
720 
721 #ifdef INVARIANTS
722 static void
_vm_map_assert_locked(vm_map_t map,const char * file,int line)723 _vm_map_assert_locked(vm_map_t map, const char *file, int line)
724 {
725 
726 	if (map->system_map)
727 		mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
728 	else
729 		sx_assert_(&map->lock, SA_XLOCKED, file, line);
730 }
731 
732 #define	VM_MAP_ASSERT_LOCKED(map) \
733     _vm_map_assert_locked(map, LOCK_FILE, LOCK_LINE)
734 
735 #ifdef DIAGNOSTIC
736 static int enable_vmmap_check = 1;
737 #else
738 static int enable_vmmap_check = 0;
739 #endif
740 SYSCTL_INT(_debug, OID_AUTO, vmmap_check, CTLFLAG_RWTUN,
741     &enable_vmmap_check, 0, "Enable vm map consistency checking");
742 
743 static void
_vm_map_assert_consistent(vm_map_t map)744 _vm_map_assert_consistent(vm_map_t map)
745 {
746 	vm_map_entry_t entry;
747 	vm_map_entry_t child;
748 	vm_size_t max_left, max_right;
749 
750 	if (!enable_vmmap_check)
751 		return;
752 
753 	for (entry = map->header.next; entry != &map->header;
754 	    entry = entry->next) {
755 		KASSERT(entry->prev->end <= entry->start,
756 		    ("map %p prev->end = %jx, start = %jx", map,
757 		    (uintmax_t)entry->prev->end, (uintmax_t)entry->start));
758 		KASSERT(entry->start < entry->end,
759 		    ("map %p start = %jx, end = %jx", map,
760 		    (uintmax_t)entry->start, (uintmax_t)entry->end));
761 		KASSERT(entry->end <= entry->next->start,
762 		    ("map %p end = %jx, next->start = %jx", map,
763 		    (uintmax_t)entry->end, (uintmax_t)entry->next->start));
764 		KASSERT(entry->left == NULL ||
765 		    entry->left->start < entry->start,
766 		    ("map %p left->start = %jx, start = %jx", map,
767 		    (uintmax_t)entry->left->start, (uintmax_t)entry->start));
768 		KASSERT(entry->right == NULL ||
769 		    entry->start < entry->right->start,
770 		    ("map %p start = %jx, right->start = %jx", map,
771 		    (uintmax_t)entry->start, (uintmax_t)entry->right->start));
772 		child = entry->left;
773 		max_left = (child != NULL) ? child->max_free :
774 			entry->start - entry->prev->end;
775 		child = entry->right;
776 		max_right = (child != NULL) ? child->max_free :
777 			entry->next->start - entry->end;
778 		KASSERT(entry->max_free == MAX(max_left, max_right),
779 		    ("map %p max = %jx, max_left = %jx, max_right = %jx", map,
780 		     (uintmax_t)entry->max_free,
781 		     (uintmax_t)max_left, (uintmax_t)max_right));
782 	}
783 }
784 
785 #define VM_MAP_ASSERT_CONSISTENT(map) \
786     _vm_map_assert_consistent(map)
787 #else
788 #define	VM_MAP_ASSERT_LOCKED(map)
789 #define VM_MAP_ASSERT_CONSISTENT(map)
790 #endif /* INVARIANTS */
791 
792 /*
793  *	_vm_map_unlock_and_wait:
794  *
795  *	Atomically releases the lock on the specified map and puts the calling
796  *	thread to sleep.  The calling thread will remain asleep until either
797  *	vm_map_wakeup() is performed on the map or the specified timeout is
798  *	exceeded.
799  *
800  *	WARNING!  This function does not perform deferred deallocations of
801  *	objects and map	entries.  Therefore, the calling thread is expected to
802  *	reacquire the map lock after reawakening and later perform an ordinary
803  *	unlock operation, such as vm_map_unlock(), before completing its
804  *	operation on the map.
805  */
806 int
_vm_map_unlock_and_wait(vm_map_t map,int timo,const char * file,int line)807 _vm_map_unlock_and_wait(vm_map_t map, int timo, const char *file, int line)
808 {
809 
810 	mtx_lock(&map_sleep_mtx);
811 	if (map->system_map)
812 		mtx_unlock_flags_(&map->system_mtx, 0, file, line);
813 	else
814 		sx_xunlock_(&map->lock, file, line);
815 	return (msleep(&map->root, &map_sleep_mtx, PDROP | PVM, "vmmaps",
816 	    timo));
817 }
818 
819 /*
820  *	vm_map_wakeup:
821  *
822  *	Awaken any threads that have slept on the map using
823  *	vm_map_unlock_and_wait().
824  */
825 void
vm_map_wakeup(vm_map_t map)826 vm_map_wakeup(vm_map_t map)
827 {
828 
829 	/*
830 	 * Acquire and release map_sleep_mtx to prevent a wakeup()
831 	 * from being performed (and lost) between the map unlock
832 	 * and the msleep() in _vm_map_unlock_and_wait().
833 	 */
834 	mtx_lock(&map_sleep_mtx);
835 	mtx_unlock(&map_sleep_mtx);
836 	wakeup(&map->root);
837 }
838 
839 void
vm_map_busy(vm_map_t map)840 vm_map_busy(vm_map_t map)
841 {
842 
843 	VM_MAP_ASSERT_LOCKED(map);
844 	map->busy++;
845 }
846 
847 void
vm_map_unbusy(vm_map_t map)848 vm_map_unbusy(vm_map_t map)
849 {
850 
851 	VM_MAP_ASSERT_LOCKED(map);
852 	KASSERT(map->busy, ("vm_map_unbusy: not busy"));
853 	if (--map->busy == 0 && (map->flags & MAP_BUSY_WAKEUP)) {
854 		vm_map_modflags(map, 0, MAP_BUSY_WAKEUP);
855 		wakeup(&map->busy);
856 	}
857 }
858 
859 void
vm_map_wait_busy(vm_map_t map)860 vm_map_wait_busy(vm_map_t map)
861 {
862 
863 	VM_MAP_ASSERT_LOCKED(map);
864 	while (map->busy) {
865 		vm_map_modflags(map, MAP_BUSY_WAKEUP, 0);
866 		if (map->system_map)
867 			msleep(&map->busy, &map->system_mtx, 0, "mbusy", 0);
868 		else
869 			sx_sleep(&map->busy, &map->lock, 0, "mbusy", 0);
870 	}
871 	map->timestamp++;
872 }
873 
874 long
vmspace_resident_count(struct vmspace * vmspace)875 vmspace_resident_count(struct vmspace *vmspace)
876 {
877 	return pmap_resident_count(vmspace_pmap(vmspace));
878 }
879 
880 /*
881  *	vm_map_create:
882  *
883  *	Creates and returns a new empty VM map with
884  *	the given physical map structure, and having
885  *	the given lower and upper address bounds.
886  */
887 vm_map_t
vm_map_create(pmap_t pmap,vm_offset_t min,vm_offset_t max)888 vm_map_create(pmap_t pmap, vm_offset_t min, vm_offset_t max)
889 {
890 	vm_map_t result;
891 
892 	result = uma_zalloc(mapzone, M_WAITOK);
893 	CTR1(KTR_VM, "vm_map_create: %p", result);
894 	_vm_map_init(result, pmap, min, max);
895 	return (result);
896 }
897 
898 /*
899  * Initialize an existing vm_map structure
900  * such as that in the vmspace structure.
901  */
902 static void
_vm_map_init(vm_map_t map,pmap_t pmap,vm_offset_t min,vm_offset_t max)903 _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
904 {
905 
906 	map->header.next = map->header.prev = &map->header;
907 	map->header.eflags = MAP_ENTRY_HEADER;
908 	map->needs_wakeup = FALSE;
909 	map->system_map = 0;
910 	map->pmap = pmap;
911 	map->header.end = min;
912 	map->header.start = max;
913 	map->flags = 0;
914 	map->root = NULL;
915 	map->timestamp = 0;
916 	map->busy = 0;
917 	map->anon_loc = 0;
918 }
919 
920 void
vm_map_init(vm_map_t map,pmap_t pmap,vm_offset_t min,vm_offset_t max)921 vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
922 {
923 
924 	_vm_map_init(map, pmap, min, max);
925 	mtx_init(&map->system_mtx, "system map", NULL, MTX_DEF | MTX_DUPOK);
926 	sx_init(&map->lock, "user map");
927 }
928 
929 /*
930  *	vm_map_entry_dispose:	[ internal use only ]
931  *
932  *	Inverse of vm_map_entry_create.
933  */
934 static void
vm_map_entry_dispose(vm_map_t map,vm_map_entry_t entry)935 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
936 {
937 	uma_zfree(map->system_map ? kmapentzone : mapentzone, entry);
938 }
939 
940 /*
941  *	vm_map_entry_create:	[ internal use only ]
942  *
943  *	Allocates a VM map entry for insertion.
944  *	No entry fields are filled in.
945  */
946 static vm_map_entry_t
vm_map_entry_create(vm_map_t map)947 vm_map_entry_create(vm_map_t map)
948 {
949 	vm_map_entry_t new_entry;
950 
951 	if (map->system_map)
952 		new_entry = uma_zalloc(kmapentzone, M_NOWAIT);
953 	else
954 		new_entry = uma_zalloc(mapentzone, M_WAITOK);
955 	if (new_entry == NULL)
956 		panic("vm_map_entry_create: kernel resources exhausted");
957 	return (new_entry);
958 }
959 
960 /*
961  *	vm_map_entry_set_behavior:
962  *
963  *	Set the expected access behavior, either normal, random, or
964  *	sequential.
965  */
966 static inline void
vm_map_entry_set_behavior(vm_map_entry_t entry,u_char behavior)967 vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
968 {
969 	entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
970 	    (behavior & MAP_ENTRY_BEHAV_MASK);
971 }
972 
973 /*
974  *	vm_map_entry_max_free_{left,right}:
975  *
976  *	Compute the size of the largest free gap between two entries,
977  *	one the root of a tree and the other the ancestor of that root
978  *	that is the least or greatest ancestor found on the search path.
979  */
980 static inline vm_size_t
vm_map_entry_max_free_left(vm_map_entry_t root,vm_map_entry_t left_ancestor)981 vm_map_entry_max_free_left(vm_map_entry_t root, vm_map_entry_t left_ancestor)
982 {
983 
984 	return (root->left != NULL ?
985 	    root->left->max_free : root->start - left_ancestor->end);
986 }
987 
988 static inline vm_size_t
vm_map_entry_max_free_right(vm_map_entry_t root,vm_map_entry_t right_ancestor)989 vm_map_entry_max_free_right(vm_map_entry_t root, vm_map_entry_t right_ancestor)
990 {
991 
992 	return (root->right != NULL ?
993 	    root->right->max_free : right_ancestor->start - root->end);
994 }
995 
996 #define SPLAY_LEFT_STEP(root, y, rlist, test) do {			\
997 	vm_size_t max_free;						\
998 									\
999 	/*								\
1000 	 * Infer root->right->max_free == root->max_free when		\
1001 	 * y->max_free < root->max_free || root->max_free == 0.		\
1002 	 * Otherwise, look right to find it.				\
1003 	 */								\
1004 	y = root->left;							\
1005 	max_free = root->max_free;					\
1006 	KASSERT(max_free >= vm_map_entry_max_free_right(root, rlist),	\
1007 	    ("%s: max_free invariant fails", __func__));		\
1008 	if (y == NULL ? max_free > 0 : max_free - 1 < y->max_free)	\
1009 		max_free = vm_map_entry_max_free_right(root, rlist);	\
1010 	if (y != NULL && (test)) {					\
1011 		/* Rotate right and make y root. */			\
1012 		root->left = y->right;					\
1013 		y->right = root;					\
1014 		if (max_free < y->max_free)				\
1015 			root->max_free = max_free = MAX(max_free,	\
1016 			    vm_map_entry_max_free_left(root, y));	\
1017 		root = y;						\
1018 		y = root->left;						\
1019 	}								\
1020 	/* Copy right->max_free.  Put root on rlist. */			\
1021 	root->max_free = max_free;					\
1022 	KASSERT(max_free == vm_map_entry_max_free_right(root, rlist),	\
1023 	    ("%s: max_free not copied from right", __func__));		\
1024 	root->left = rlist;						\
1025 	rlist = root;							\
1026 	root = y;							\
1027 } while (0)
1028 
1029 #define SPLAY_RIGHT_STEP(root, y, llist, test) do {			\
1030 	vm_size_t max_free;						\
1031 									\
1032 	/*								\
1033 	 * Infer root->left->max_free == root->max_free when		\
1034 	 * y->max_free < root->max_free || root->max_free == 0.		\
1035 	 * Otherwise, look left to find it.				\
1036 	 */								\
1037 	y = root->right;						\
1038 	max_free = root->max_free;					\
1039 	KASSERT(max_free >= vm_map_entry_max_free_left(root, llist),	\
1040 	    ("%s: max_free invariant fails", __func__));		\
1041 	if (y == NULL ? max_free > 0 : max_free - 1 < y->max_free)	\
1042 		max_free = vm_map_entry_max_free_left(root, llist);	\
1043 	if (y != NULL && (test)) {					\
1044 		/* Rotate left and make y root. */			\
1045 		root->right = y->left;					\
1046 		y->left = root;						\
1047 		if (max_free < y->max_free)				\
1048 			root->max_free = max_free = MAX(max_free,	\
1049 			    vm_map_entry_max_free_right(root, y));	\
1050 		root = y;						\
1051 		y = root->right;					\
1052 	}								\
1053 	/* Copy left->max_free.  Put root on llist. */			\
1054 	root->max_free = max_free;					\
1055 	KASSERT(max_free == vm_map_entry_max_free_left(root, llist),	\
1056 	    ("%s: max_free not copied from left", __func__));		\
1057 	root->right = llist;						\
1058 	llist = root;							\
1059 	root = y;							\
1060 } while (0)
1061 
1062 /*
1063  * Walk down the tree until we find addr or a NULL pointer where addr would go,
1064  * breaking off left and right subtrees of nodes less than, or greater than
1065  * addr.  Treat pointers to nodes with max_free < length as NULL pointers.
1066  * llist and rlist are the two sides in reverse order (bottom-up), with llist
1067  * linked by the right pointer and rlist linked by the left pointer in the
1068  * vm_map_entry, and both lists terminated by &map->header.  This function, and
1069  * the subsequent call to vm_map_splay_merge, rely on the start and end address
1070  * values in &map->header.
1071  */
1072 static vm_map_entry_t
vm_map_splay_split(vm_map_t map,vm_offset_t addr,vm_size_t length,vm_map_entry_t * out_llist,vm_map_entry_t * out_rlist)1073 vm_map_splay_split(vm_map_t map, vm_offset_t addr, vm_size_t length,
1074     vm_map_entry_t *out_llist, vm_map_entry_t *out_rlist)
1075 {
1076 	vm_map_entry_t llist, rlist, root, y;
1077 
1078 	llist = rlist = &map->header;
1079 	root = map->root;
1080 	while (root != NULL && root->max_free >= length) {
1081 		KASSERT(llist->end <= root->start && root->end <= rlist->start,
1082 		    ("%s: root not within tree bounds", __func__));
1083 		if (addr < root->start) {
1084 			SPLAY_LEFT_STEP(root, y, rlist,
1085 			    y->max_free >= length && addr < y->start);
1086 		} else if (addr >= root->end) {
1087 			SPLAY_RIGHT_STEP(root, y, llist,
1088 			    y->max_free >= length && addr >= y->end);
1089 		} else
1090 			break;
1091 	}
1092 	*out_llist = llist;
1093 	*out_rlist = rlist;
1094 	return (root);
1095 }
1096 
1097 static void
vm_map_splay_findnext(vm_map_entry_t root,vm_map_entry_t * iolist)1098 vm_map_splay_findnext(vm_map_entry_t root, vm_map_entry_t *iolist)
1099 {
1100 	vm_map_entry_t rlist, y;
1101 
1102 	root = root->right;
1103 	rlist = *iolist;
1104 	while (root != NULL)
1105 		SPLAY_LEFT_STEP(root, y, rlist, true);
1106 	*iolist = rlist;
1107 }
1108 
1109 static void
vm_map_splay_findprev(vm_map_entry_t root,vm_map_entry_t * iolist)1110 vm_map_splay_findprev(vm_map_entry_t root, vm_map_entry_t *iolist)
1111 {
1112 	vm_map_entry_t llist, y;
1113 
1114 	root = root->left;
1115 	llist = *iolist;
1116 	while (root != NULL)
1117 		SPLAY_RIGHT_STEP(root, y, llist, true);
1118 	*iolist = llist;
1119 }
1120 
1121 static inline void
vm_map_entry_swap(vm_map_entry_t * a,vm_map_entry_t * b)1122 vm_map_entry_swap(vm_map_entry_t *a, vm_map_entry_t *b)
1123 {
1124 	vm_map_entry_t tmp;
1125 
1126 	tmp = *b;
1127 	*b = *a;
1128 	*a = tmp;
1129 }
1130 
1131 /*
1132  * Walk back up the two spines, flip the pointers and set max_free.  The
1133  * subtrees of the root go at the bottom of llist and rlist.
1134  */
1135 static void
vm_map_splay_merge(vm_map_t map,vm_map_entry_t root,vm_map_entry_t llist,vm_map_entry_t rlist)1136 vm_map_splay_merge(vm_map_t map, vm_map_entry_t root,
1137     vm_map_entry_t llist, vm_map_entry_t rlist)
1138 {
1139 	vm_map_entry_t prev;
1140 	vm_size_t max_free_left, max_free_right;
1141 
1142 	max_free_left = vm_map_entry_max_free_left(root, llist);
1143 	if (llist != &map->header) {
1144 		prev = root->left;
1145 		do {
1146 			/*
1147 			 * The max_free values of the children of llist are in
1148 			 * llist->max_free and max_free_left.  Update with the
1149 			 * max value.
1150 			 */
1151 			llist->max_free = max_free_left =
1152 			    MAX(llist->max_free, max_free_left);
1153 			vm_map_entry_swap(&llist->right, &prev);
1154 			vm_map_entry_swap(&prev, &llist);
1155 		} while (llist != &map->header);
1156 		root->left = prev;
1157 	}
1158 	max_free_right = vm_map_entry_max_free_right(root, rlist);
1159 	if (rlist != &map->header) {
1160 		prev = root->right;
1161 		do {
1162 			/*
1163 			 * The max_free values of the children of rlist are in
1164 			 * rlist->max_free and max_free_right.  Update with the
1165 			 * max value.
1166 			 */
1167 			rlist->max_free = max_free_right =
1168 			    MAX(rlist->max_free, max_free_right);
1169 			vm_map_entry_swap(&rlist->left, &prev);
1170 			vm_map_entry_swap(&prev, &rlist);
1171 		} while (rlist != &map->header);
1172 		root->right = prev;
1173 	}
1174 	root->max_free = MAX(max_free_left, max_free_right);
1175 	map->root = root;
1176 }
1177 
1178 /*
1179  *	vm_map_splay:
1180  *
1181  *	The Sleator and Tarjan top-down splay algorithm with the
1182  *	following variation.  Max_free must be computed bottom-up, so
1183  *	on the downward pass, maintain the left and right spines in
1184  *	reverse order.  Then, make a second pass up each side to fix
1185  *	the pointers and compute max_free.  The time bound is O(log n)
1186  *	amortized.
1187  *
1188  *	The new root is the vm_map_entry containing "addr", or else an
1189  *	adjacent entry (lower if possible) if addr is not in the tree.
1190  *
1191  *	The map must be locked, and leaves it so.
1192  *
1193  *	Returns: the new root.
1194  */
1195 static vm_map_entry_t
vm_map_splay(vm_map_t map,vm_offset_t addr)1196 vm_map_splay(vm_map_t map, vm_offset_t addr)
1197 {
1198 	vm_map_entry_t llist, rlist, root;
1199 
1200 	root = vm_map_splay_split(map, addr, 0, &llist, &rlist);
1201 	if (root != NULL) {
1202 		/* do nothing */
1203 	} else if (llist != &map->header) {
1204 		/*
1205 		 * Recover the greatest node in the left
1206 		 * subtree and make it the root.
1207 		 */
1208 		root = llist;
1209 		llist = root->right;
1210 		root->right = NULL;
1211 	} else if (rlist != &map->header) {
1212 		/*
1213 		 * Recover the least node in the right
1214 		 * subtree and make it the root.
1215 		 */
1216 		root = rlist;
1217 		rlist = root->left;
1218 		root->left = NULL;
1219 	} else {
1220 		/* There is no root. */
1221 		return (NULL);
1222 	}
1223 	vm_map_splay_merge(map, root, llist, rlist);
1224 	VM_MAP_ASSERT_CONSISTENT(map);
1225 	return (root);
1226 }
1227 
1228 /*
1229  *	vm_map_entry_{un,}link:
1230  *
1231  *	Insert/remove entries from maps.
1232  */
1233 static void
vm_map_entry_link(vm_map_t map,vm_map_entry_t entry)1234 vm_map_entry_link(vm_map_t map, vm_map_entry_t entry)
1235 {
1236 	vm_map_entry_t llist, rlist, root;
1237 
1238 	CTR3(KTR_VM,
1239 	    "vm_map_entry_link: map %p, nentries %d, entry %p", map,
1240 	    map->nentries, entry);
1241 	VM_MAP_ASSERT_LOCKED(map);
1242 	map->nentries++;
1243 	root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1244 	KASSERT(root == NULL,
1245 	    ("vm_map_entry_link: link object already mapped"));
1246 	entry->prev = llist;
1247 	entry->next = rlist;
1248 	llist->next = rlist->prev = entry;
1249 	entry->left = entry->right = NULL;
1250 	vm_map_splay_merge(map, entry, llist, rlist);
1251 	VM_MAP_ASSERT_CONSISTENT(map);
1252 }
1253 
1254 enum unlink_merge_type {
1255 	UNLINK_MERGE_PREV,
1256 	UNLINK_MERGE_NONE,
1257 	UNLINK_MERGE_NEXT
1258 };
1259 
1260 static void
vm_map_entry_unlink(vm_map_t map,vm_map_entry_t entry,enum unlink_merge_type op)1261 vm_map_entry_unlink(vm_map_t map, vm_map_entry_t entry,
1262     enum unlink_merge_type op)
1263 {
1264 	vm_map_entry_t llist, rlist, root, y;
1265 
1266 	VM_MAP_ASSERT_LOCKED(map);
1267 	root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1268 	KASSERT(root != NULL,
1269 	    ("vm_map_entry_unlink: unlink object not mapped"));
1270 
1271 	switch (op) {
1272 	case UNLINK_MERGE_PREV:
1273 		vm_map_splay_findprev(root, &llist);
1274 		llist->end = root->end;
1275 		y = root->right;
1276 		root = llist;
1277 		llist = root->right;
1278 		root->right = y;
1279 		break;
1280 	case UNLINK_MERGE_NEXT:
1281 		vm_map_splay_findnext(root, &rlist);
1282 		rlist->start = root->start;
1283 		rlist->offset = root->offset;
1284 		y = root->left;
1285 		root = rlist;
1286 		rlist = root->left;
1287 		root->left = y;
1288 		break;
1289 	case UNLINK_MERGE_NONE:
1290 		vm_map_splay_findprev(root, &llist);
1291 		vm_map_splay_findnext(root, &rlist);
1292 		if (llist != &map->header) {
1293 			root = llist;
1294 			llist = root->right;
1295 			root->right = NULL;
1296 		} else if (rlist != &map->header) {
1297 			root = rlist;
1298 			rlist = root->left;
1299 			root->left = NULL;
1300 		} else
1301 			root = NULL;
1302 		break;
1303 	}
1304 	y = entry->next;
1305 	y->prev = entry->prev;
1306 	y->prev->next = y;
1307 	if (root != NULL)
1308 		vm_map_splay_merge(map, root, llist, rlist);
1309 	else
1310 		map->root = NULL;
1311 	VM_MAP_ASSERT_CONSISTENT(map);
1312 	map->nentries--;
1313 	CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
1314 	    map->nentries, entry);
1315 }
1316 
1317 /*
1318  *	vm_map_entry_resize_free:
1319  *
1320  *	Recompute the amount of free space following a modified vm_map_entry
1321  *	and propagate those values up the tree.  Call this function after
1322  *	resizing a map entry in-place by changing the end value, without a
1323  *	call to vm_map_entry_link() or _unlink().
1324  *
1325  *	The map must be locked, and leaves it so.
1326  */
1327 static void
vm_map_entry_resize_free(vm_map_t map,vm_map_entry_t entry)1328 vm_map_entry_resize_free(vm_map_t map, vm_map_entry_t entry)
1329 {
1330 	vm_map_entry_t llist, rlist, root;
1331 
1332 	VM_MAP_ASSERT_LOCKED(map);
1333 	root = vm_map_splay_split(map, entry->start, 0, &llist, &rlist);
1334 	KASSERT(root != NULL,
1335 	    ("vm_map_entry_resize_free: resize_free object not mapped"));
1336 	vm_map_splay_findnext(root, &rlist);
1337 	root->right = NULL;
1338 	vm_map_splay_merge(map, root, llist, rlist);
1339 	VM_MAP_ASSERT_CONSISTENT(map);
1340 	CTR3(KTR_VM, "vm_map_entry_resize_free: map %p, nentries %d, entry %p", map,
1341 	    map->nentries, entry);
1342 }
1343 
1344 /*
1345  *	vm_map_lookup_entry:	[ internal use only ]
1346  *
1347  *	Finds the map entry containing (or
1348  *	immediately preceding) the specified address
1349  *	in the given map; the entry is returned
1350  *	in the "entry" parameter.  The boolean
1351  *	result indicates whether the address is
1352  *	actually contained in the map.
1353  */
1354 boolean_t
vm_map_lookup_entry(vm_map_t map,vm_offset_t address,vm_map_entry_t * entry)1355 vm_map_lookup_entry(
1356 	vm_map_t map,
1357 	vm_offset_t address,
1358 	vm_map_entry_t *entry)	/* OUT */
1359 {
1360 	vm_map_entry_t cur, lbound;
1361 	boolean_t locked;
1362 
1363 	/*
1364 	 * If the map is empty, then the map entry immediately preceding
1365 	 * "address" is the map's header.
1366 	 */
1367 	cur = map->root;
1368 	if (cur == NULL) {
1369 		*entry = &map->header;
1370 		return (FALSE);
1371 	}
1372 	if (address >= cur->start && cur->end > address) {
1373 		*entry = cur;
1374 		return (TRUE);
1375 	}
1376 	if ((locked = vm_map_locked(map)) ||
1377 	    sx_try_upgrade(&map->lock)) {
1378 		/*
1379 		 * Splay requires a write lock on the map.  However, it only
1380 		 * restructures the binary search tree; it does not otherwise
1381 		 * change the map.  Thus, the map's timestamp need not change
1382 		 * on a temporary upgrade.
1383 		 */
1384 		cur = vm_map_splay(map, address);
1385 		if (!locked)
1386 			sx_downgrade(&map->lock);
1387 
1388 		/*
1389 		 * If "address" is contained within a map entry, the new root
1390 		 * is that map entry.  Otherwise, the new root is a map entry
1391 		 * immediately before or after "address".
1392 		 */
1393 		if (address < cur->start) {
1394 			*entry = &map->header;
1395 			return (FALSE);
1396 		}
1397 		*entry = cur;
1398 		return (address < cur->end);
1399 	}
1400 	/*
1401 	 * Since the map is only locked for read access, perform a
1402 	 * standard binary search tree lookup for "address".
1403 	 */
1404 	lbound = &map->header;
1405 	do {
1406 		if (address < cur->start) {
1407 			cur = cur->left;
1408 		} else if (cur->end <= address) {
1409 			lbound = cur;
1410 			cur = cur->right;
1411 		} else {
1412 			*entry = cur;
1413 			return (TRUE);
1414 		}
1415 	} while (cur != NULL);
1416 	*entry = lbound;
1417 	return (FALSE);
1418 }
1419 
1420 /*
1421  *	vm_map_insert:
1422  *
1423  *	Inserts the given whole VM object into the target
1424  *	map at the specified address range.  The object's
1425  *	size should match that of the address range.
1426  *
1427  *	Requires that the map be locked, and leaves it so.
1428  *
1429  *	If object is non-NULL, ref count must be bumped by caller
1430  *	prior to making call to account for the new entry.
1431  */
1432 int
vm_map_insert(vm_map_t map,vm_object_t object,vm_ooffset_t offset,vm_offset_t start,vm_offset_t end,vm_prot_t prot,vm_prot_t max,int cow)1433 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1434     vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max, int cow)
1435 {
1436 	vm_map_entry_t new_entry, prev_entry, temp_entry;
1437 	struct ucred *cred;
1438 	vm_eflags_t protoeflags;
1439 	vm_inherit_t inheritance;
1440 
1441 	VM_MAP_ASSERT_LOCKED(map);
1442 	KASSERT(object != kernel_object ||
1443 	    (cow & MAP_COPY_ON_WRITE) == 0,
1444 	    ("vm_map_insert: kernel object and COW"));
1445 	KASSERT(object == NULL || (cow & MAP_NOFAULT) == 0,
1446 	    ("vm_map_insert: paradoxical MAP_NOFAULT request"));
1447 	KASSERT((prot & ~max) == 0,
1448 	    ("prot %#x is not subset of max_prot %#x", prot, max));
1449 
1450 	/*
1451 	 * Check that the start and end points are not bogus.
1452 	 */
1453 	if (start == end || !vm_map_range_valid(map, start, end))
1454 		return (KERN_INVALID_ADDRESS);
1455 
1456 	/*
1457 	 * Find the entry prior to the proposed starting address; if it's part
1458 	 * of an existing entry, this range is bogus.
1459 	 */
1460 	if (vm_map_lookup_entry(map, start, &temp_entry))
1461 		return (KERN_NO_SPACE);
1462 
1463 	prev_entry = temp_entry;
1464 
1465 	/*
1466 	 * Assert that the next entry doesn't overlap the end point.
1467 	 */
1468 	if (prev_entry->next->start < end)
1469 		return (KERN_NO_SPACE);
1470 
1471 	if ((cow & MAP_CREATE_GUARD) != 0 && (object != NULL ||
1472 	    max != VM_PROT_NONE))
1473 		return (KERN_INVALID_ARGUMENT);
1474 
1475 	protoeflags = 0;
1476 	if (cow & MAP_COPY_ON_WRITE)
1477 		protoeflags |= MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY;
1478 	if (cow & MAP_NOFAULT)
1479 		protoeflags |= MAP_ENTRY_NOFAULT;
1480 	if (cow & MAP_DISABLE_SYNCER)
1481 		protoeflags |= MAP_ENTRY_NOSYNC;
1482 	if (cow & MAP_DISABLE_COREDUMP)
1483 		protoeflags |= MAP_ENTRY_NOCOREDUMP;
1484 	if (cow & MAP_STACK_GROWS_DOWN)
1485 		protoeflags |= MAP_ENTRY_GROWS_DOWN;
1486 	if (cow & MAP_STACK_GROWS_UP)
1487 		protoeflags |= MAP_ENTRY_GROWS_UP;
1488 	if (cow & MAP_WRITECOUNT)
1489 		protoeflags |= MAP_ENTRY_WRITECNT;
1490 	if (cow & MAP_VN_EXEC)
1491 		protoeflags |= MAP_ENTRY_VN_EXEC;
1492 	if ((cow & MAP_CREATE_GUARD) != 0)
1493 		protoeflags |= MAP_ENTRY_GUARD;
1494 	if ((cow & MAP_CREATE_STACK_GAP_DN) != 0)
1495 		protoeflags |= MAP_ENTRY_STACK_GAP_DN;
1496 	if ((cow & MAP_CREATE_STACK_GAP_UP) != 0)
1497 		protoeflags |= MAP_ENTRY_STACK_GAP_UP;
1498 	if (cow & MAP_INHERIT_SHARE)
1499 		inheritance = VM_INHERIT_SHARE;
1500 	else
1501 		inheritance = VM_INHERIT_DEFAULT;
1502 
1503 	cred = NULL;
1504 	if ((cow & (MAP_ACC_NO_CHARGE | MAP_NOFAULT | MAP_CREATE_GUARD)) != 0)
1505 		goto charged;
1506 	if ((cow & MAP_ACC_CHARGED) || ((prot & VM_PROT_WRITE) &&
1507 	    ((protoeflags & MAP_ENTRY_NEEDS_COPY) || object == NULL))) {
1508 		if (!(cow & MAP_ACC_CHARGED) && !swap_reserve(end - start))
1509 			return (KERN_RESOURCE_SHORTAGE);
1510 		KASSERT(object == NULL ||
1511 		    (protoeflags & MAP_ENTRY_NEEDS_COPY) != 0 ||
1512 		    object->cred == NULL,
1513 		    ("overcommit: vm_map_insert o %p", object));
1514 		cred = curthread->td_ucred;
1515 	}
1516 
1517 charged:
1518 	/* Expand the kernel pmap, if necessary. */
1519 	if (map == kernel_map && end > kernel_vm_end)
1520 		pmap_growkernel(end);
1521 	if (object != NULL) {
1522 		/*
1523 		 * OBJ_ONEMAPPING must be cleared unless this mapping
1524 		 * is trivially proven to be the only mapping for any
1525 		 * of the object's pages.  (Object granularity
1526 		 * reference counting is insufficient to recognize
1527 		 * aliases with precision.)
1528 		 */
1529 		VM_OBJECT_WLOCK(object);
1530 		if (object->ref_count > 1 || object->shadow_count != 0)
1531 			vm_object_clear_flag(object, OBJ_ONEMAPPING);
1532 		VM_OBJECT_WUNLOCK(object);
1533 	} else if ((prev_entry->eflags & ~MAP_ENTRY_USER_WIRED) ==
1534 	    protoeflags &&
1535 	    (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP |
1536 	    MAP_VN_EXEC)) == 0 &&
1537 	    prev_entry->end == start && (prev_entry->cred == cred ||
1538 	    (prev_entry->object.vm_object != NULL &&
1539 	    prev_entry->object.vm_object->cred == cred)) &&
1540 	    vm_object_coalesce(prev_entry->object.vm_object,
1541 	    prev_entry->offset,
1542 	    (vm_size_t)(prev_entry->end - prev_entry->start),
1543 	    (vm_size_t)(end - prev_entry->end), cred != NULL &&
1544 	    (protoeflags & MAP_ENTRY_NEEDS_COPY) == 0)) {
1545 		/*
1546 		 * We were able to extend the object.  Determine if we
1547 		 * can extend the previous map entry to include the
1548 		 * new range as well.
1549 		 */
1550 		if (prev_entry->inheritance == inheritance &&
1551 		    prev_entry->protection == prot &&
1552 		    prev_entry->max_protection == max &&
1553 		    prev_entry->wired_count == 0) {
1554 			KASSERT((prev_entry->eflags & MAP_ENTRY_USER_WIRED) ==
1555 			    0, ("prev_entry %p has incoherent wiring",
1556 			    prev_entry));
1557 			if ((prev_entry->eflags & MAP_ENTRY_GUARD) == 0)
1558 				map->size += end - prev_entry->end;
1559 			prev_entry->end = end;
1560 			vm_map_entry_resize_free(map, prev_entry);
1561 			vm_map_simplify_entry(map, prev_entry);
1562 			return (KERN_SUCCESS);
1563 		}
1564 
1565 		/*
1566 		 * If we can extend the object but cannot extend the
1567 		 * map entry, we have to create a new map entry.  We
1568 		 * must bump the ref count on the extended object to
1569 		 * account for it.  object may be NULL.
1570 		 */
1571 		object = prev_entry->object.vm_object;
1572 		offset = prev_entry->offset +
1573 		    (prev_entry->end - prev_entry->start);
1574 		vm_object_reference(object);
1575 		if (cred != NULL && object != NULL && object->cred != NULL &&
1576 		    !(prev_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
1577 			/* Object already accounts for this uid. */
1578 			cred = NULL;
1579 		}
1580 	}
1581 	if (cred != NULL)
1582 		crhold(cred);
1583 
1584 	/*
1585 	 * Create a new entry
1586 	 */
1587 	new_entry = vm_map_entry_create(map);
1588 	new_entry->start = start;
1589 	new_entry->end = end;
1590 	new_entry->cred = NULL;
1591 
1592 	new_entry->eflags = protoeflags;
1593 	new_entry->object.vm_object = object;
1594 	new_entry->offset = offset;
1595 
1596 	new_entry->inheritance = inheritance;
1597 	new_entry->protection = prot;
1598 	new_entry->max_protection = max;
1599 	new_entry->wired_count = 0;
1600 	new_entry->wiring_thread = NULL;
1601 	new_entry->read_ahead = VM_FAULT_READ_AHEAD_INIT;
1602 	new_entry->next_read = start;
1603 
1604 	KASSERT(cred == NULL || !ENTRY_CHARGED(new_entry),
1605 	    ("overcommit: vm_map_insert leaks vm_map %p", new_entry));
1606 	new_entry->cred = cred;
1607 
1608 	/*
1609 	 * Insert the new entry into the list
1610 	 */
1611 	vm_map_entry_link(map, new_entry);
1612 	if ((new_entry->eflags & MAP_ENTRY_GUARD) == 0)
1613 		map->size += new_entry->end - new_entry->start;
1614 
1615 	/*
1616 	 * Try to coalesce the new entry with both the previous and next
1617 	 * entries in the list.  Previously, we only attempted to coalesce
1618 	 * with the previous entry when object is NULL.  Here, we handle the
1619 	 * other cases, which are less common.
1620 	 */
1621 	vm_map_simplify_entry(map, new_entry);
1622 
1623 	if ((cow & (MAP_PREFAULT | MAP_PREFAULT_PARTIAL)) != 0) {
1624 		vm_map_pmap_enter(map, start, prot, object, OFF_TO_IDX(offset),
1625 		    end - start, cow & MAP_PREFAULT_PARTIAL);
1626 	}
1627 
1628 	return (KERN_SUCCESS);
1629 }
1630 
1631 /*
1632  *	vm_map_findspace:
1633  *
1634  *	Find the first fit (lowest VM address) for "length" free bytes
1635  *	beginning at address >= start in the given map.
1636  *
1637  *	In a vm_map_entry, "max_free" is the maximum amount of
1638  *	contiguous free space between an entry in its subtree and a
1639  *	neighbor of that entry.  This allows finding a free region in
1640  *	one path down the tree, so O(log n) amortized with splay
1641  *	trees.
1642  *
1643  *	The map must be locked, and leaves it so.
1644  *
1645  *	Returns: starting address if sufficient space,
1646  *		 vm_map_max(map)-length+1 if insufficient space.
1647  */
1648 vm_offset_t
vm_map_findspace(vm_map_t map,vm_offset_t start,vm_size_t length)1649 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length)
1650 {
1651 	vm_map_entry_t llist, rlist, root, y;
1652 	vm_size_t left_length;
1653 	vm_offset_t gap_end;
1654 
1655 	/*
1656 	 * Request must fit within min/max VM address and must avoid
1657 	 * address wrap.
1658 	 */
1659 	start = MAX(start, vm_map_min(map));
1660 	if (start >= vm_map_max(map) || length > vm_map_max(map) - start)
1661 		return (vm_map_max(map) - length + 1);
1662 
1663 	/* Empty tree means wide open address space. */
1664 	if (map->root == NULL)
1665 		return (start);
1666 
1667 	/*
1668 	 * After splay_split, if start is within an entry, push it to the start
1669 	 * of the following gap.  If rlist is at the end of the gap containing
1670 	 * start, save the end of that gap in gap_end to see if the gap is big
1671 	 * enough; otherwise set gap_end to start skip gap-checking and move
1672 	 * directly to a search of the right subtree.
1673 	 */
1674 	root = vm_map_splay_split(map, start, length, &llist, &rlist);
1675 	gap_end = rlist->start;
1676 	if (root != NULL) {
1677 		start = root->end;
1678 		if (root->right != NULL)
1679 			gap_end = start;
1680 	} else if (rlist != &map->header) {
1681 		root = rlist;
1682 		rlist = root->left;
1683 		root->left = NULL;
1684 	} else {
1685 		root = llist;
1686 		llist = root->right;
1687 		root->right = NULL;
1688 	}
1689 	vm_map_splay_merge(map, root, llist, rlist);
1690 	VM_MAP_ASSERT_CONSISTENT(map);
1691 	if (length <= gap_end - start)
1692 		return (start);
1693 
1694 	/* With max_free, can immediately tell if no solution. */
1695 	if (root->right == NULL || length > root->right->max_free)
1696 		return (vm_map_max(map) - length + 1);
1697 
1698 	/*
1699 	 * Splay for the least large-enough gap in the right subtree.
1700 	 */
1701 	llist = rlist = &map->header;
1702 	for (left_length = 0;;
1703 	    left_length = vm_map_entry_max_free_left(root, llist)) {
1704 		if (length <= left_length)
1705 			SPLAY_LEFT_STEP(root, y, rlist,
1706 			    length <= vm_map_entry_max_free_left(y, llist));
1707 		else
1708 			SPLAY_RIGHT_STEP(root, y, llist,
1709 			    length > vm_map_entry_max_free_left(y, root));
1710 		if (root == NULL)
1711 			break;
1712 	}
1713 	root = llist;
1714 	llist = root->right;
1715 	root->right = NULL;
1716 	if (rlist != &map->header) {
1717 		y = rlist;
1718 		rlist = y->left;
1719 		y->left = NULL;
1720 		vm_map_splay_merge(map, y, &map->header, rlist);
1721 		y->max_free = MAX(
1722 		    vm_map_entry_max_free_left(y, root),
1723 		    vm_map_entry_max_free_right(y, &map->header));
1724 		root->right = y;
1725 	}
1726 	vm_map_splay_merge(map, root, llist, &map->header);
1727 	VM_MAP_ASSERT_CONSISTENT(map);
1728 	return (root->end);
1729 }
1730 
1731 int
vm_map_fixed(vm_map_t map,vm_object_t object,vm_ooffset_t offset,vm_offset_t start,vm_size_t length,vm_prot_t prot,vm_prot_t max,int cow)1732 vm_map_fixed(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1733     vm_offset_t start, vm_size_t length, vm_prot_t prot,
1734     vm_prot_t max, int cow)
1735 {
1736 	vm_offset_t end;
1737 	int result;
1738 
1739 	end = start + length;
1740 	KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1741 	    object == NULL,
1742 	    ("vm_map_fixed: non-NULL backing object for stack"));
1743 	vm_map_lock(map);
1744 	VM_MAP_RANGE_CHECK(map, start, end);
1745 	if ((cow & MAP_CHECK_EXCL) == 0) {
1746 		result = vm_map_delete(map, start, end);
1747 		if (result != KERN_SUCCESS)
1748 			goto out;
1749 	}
1750 	if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1751 		result = vm_map_stack_locked(map, start, length, sgrowsiz,
1752 		    prot, max, cow);
1753 	} else {
1754 		result = vm_map_insert(map, object, offset, start, end,
1755 		    prot, max, cow);
1756 	}
1757 out:
1758 	vm_map_unlock(map);
1759 	return (result);
1760 }
1761 
1762 static const int aslr_pages_rnd_64[2] = {0x1000, 0x10};
1763 static const int aslr_pages_rnd_32[2] = {0x100, 0x4};
1764 
1765 static int cluster_anon = 1;
1766 SYSCTL_INT(_vm, OID_AUTO, cluster_anon, CTLFLAG_RW,
1767     &cluster_anon, 0,
1768     "Cluster anonymous mappings: 0 = no, 1 = yes if no hint, 2 = always");
1769 
1770 static bool
clustering_anon_allowed(vm_offset_t addr)1771 clustering_anon_allowed(vm_offset_t addr)
1772 {
1773 
1774 	switch (cluster_anon) {
1775 	case 0:
1776 		return (false);
1777 	case 1:
1778 		return (addr == 0);
1779 	case 2:
1780 	default:
1781 		return (true);
1782 	}
1783 }
1784 
1785 static long aslr_restarts;
1786 SYSCTL_LONG(_vm, OID_AUTO, aslr_restarts, CTLFLAG_RD,
1787     &aslr_restarts, 0,
1788     "Number of aslr failures");
1789 
1790 /*
1791  * Searches for the specified amount of free space in the given map with the
1792  * specified alignment.  Performs an address-ordered, first-fit search from
1793  * the given address "*addr", with an optional upper bound "max_addr".  If the
1794  * parameter "alignment" is zero, then the alignment is computed from the
1795  * given (object, offset) pair so as to enable the greatest possible use of
1796  * superpage mappings.  Returns KERN_SUCCESS and the address of the free space
1797  * in "*addr" if successful.  Otherwise, returns KERN_NO_SPACE.
1798  *
1799  * The map must be locked.  Initially, there must be at least "length" bytes
1800  * of free space at the given address.
1801  */
1802 static int
vm_map_alignspace(vm_map_t map,vm_object_t object,vm_ooffset_t offset,vm_offset_t * addr,vm_size_t length,vm_offset_t max_addr,vm_offset_t alignment)1803 vm_map_alignspace(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1804     vm_offset_t *addr, vm_size_t length, vm_offset_t max_addr,
1805     vm_offset_t alignment)
1806 {
1807 	vm_offset_t aligned_addr, free_addr;
1808 
1809 	VM_MAP_ASSERT_LOCKED(map);
1810 	free_addr = *addr;
1811 	KASSERT(free_addr == vm_map_findspace(map, free_addr, length),
1812 	    ("caller failed to provide space %#jx at address %p",
1813 	     (uintmax_t)length, (void *)free_addr));
1814 	for (;;) {
1815 		/*
1816 		 * At the start of every iteration, the free space at address
1817 		 * "*addr" is at least "length" bytes.
1818 		 */
1819 		if (alignment == 0)
1820 			pmap_align_superpage(object, offset, addr, length);
1821 		else if ((*addr & (alignment - 1)) != 0) {
1822 			*addr &= ~(alignment - 1);
1823 			*addr += alignment;
1824 		}
1825 		aligned_addr = *addr;
1826 		if (aligned_addr == free_addr) {
1827 			/*
1828 			 * Alignment did not change "*addr", so "*addr" must
1829 			 * still provide sufficient free space.
1830 			 */
1831 			return (KERN_SUCCESS);
1832 		}
1833 
1834 		/*
1835 		 * Test for address wrap on "*addr".  A wrapped "*addr" could
1836 		 * be a valid address, in which case vm_map_findspace() cannot
1837 		 * be relied upon to fail.
1838 		 */
1839 		if (aligned_addr < free_addr)
1840 			return (KERN_NO_SPACE);
1841 		*addr = vm_map_findspace(map, aligned_addr, length);
1842 		if (*addr + length > vm_map_max(map) ||
1843 		    (max_addr != 0 && *addr + length > max_addr))
1844 			return (KERN_NO_SPACE);
1845 		free_addr = *addr;
1846 		if (free_addr == aligned_addr) {
1847 			/*
1848 			 * If a successful call to vm_map_findspace() did not
1849 			 * change "*addr", then "*addr" must still be aligned
1850 			 * and provide sufficient free space.
1851 			 */
1852 			return (KERN_SUCCESS);
1853 		}
1854 	}
1855 }
1856 
1857 int
vm_map_find_aligned(vm_map_t map,vm_offset_t * addr,vm_size_t length,vm_offset_t max_addr,vm_offset_t alignment)1858 vm_map_find_aligned(vm_map_t map, vm_offset_t *addr, vm_size_t length,
1859     vm_offset_t max_addr, vm_offset_t alignment)
1860 {
1861 	/* XXXKIB ASLR eh ? */
1862 	*addr = vm_map_findspace(map, *addr, length);
1863 	if (*addr + length > vm_map_max(map) ||
1864 	    (max_addr != 0 && *addr + length > max_addr))
1865 		return (KERN_NO_SPACE);
1866 	return (vm_map_alignspace(map, NULL, 0, addr, length, max_addr,
1867 	    alignment));
1868 }
1869 
1870 /*
1871  *	vm_map_find finds an unallocated region in the target address
1872  *	map with the given length.  The search is defined to be
1873  *	first-fit from the specified address; the region found is
1874  *	returned in the same parameter.
1875  *
1876  *	If object is non-NULL, ref count must be bumped by caller
1877  *	prior to making call to account for the new entry.
1878  */
1879 int
vm_map_find(vm_map_t map,vm_object_t object,vm_ooffset_t offset,vm_offset_t * addr,vm_size_t length,vm_offset_t max_addr,int find_space,vm_prot_t prot,vm_prot_t max,int cow)1880 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1881 	    vm_offset_t *addr,	/* IN/OUT */
1882 	    vm_size_t length, vm_offset_t max_addr, int find_space,
1883 	    vm_prot_t prot, vm_prot_t max, int cow)
1884 {
1885 	vm_offset_t alignment, curr_min_addr, min_addr;
1886 	int gap, pidx, rv, try;
1887 	bool cluster, en_aslr, update_anon;
1888 
1889 	KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1890 	    object == NULL,
1891 	    ("vm_map_find: non-NULL backing object for stack"));
1892 	MPASS((cow & MAP_REMAP) == 0 || (find_space == VMFS_NO_SPACE &&
1893 	    (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0));
1894 	if (find_space == VMFS_OPTIMAL_SPACE && (object == NULL ||
1895 	    (object->flags & OBJ_COLORED) == 0))
1896 		find_space = VMFS_ANY_SPACE;
1897 	if (find_space >> 8 != 0) {
1898 		KASSERT((find_space & 0xff) == 0, ("bad VMFS flags"));
1899 		alignment = (vm_offset_t)1 << (find_space >> 8);
1900 	} else
1901 		alignment = 0;
1902 	en_aslr = (map->flags & MAP_ASLR) != 0;
1903 	update_anon = cluster = clustering_anon_allowed(*addr) &&
1904 	    (map->flags & MAP_IS_SUB_MAP) == 0 && max_addr == 0 &&
1905 	    find_space != VMFS_NO_SPACE && object == NULL &&
1906 	    (cow & (MAP_INHERIT_SHARE | MAP_STACK_GROWS_UP |
1907 	    MAP_STACK_GROWS_DOWN)) == 0 && prot != PROT_NONE;
1908 	curr_min_addr = min_addr = *addr;
1909 	if (en_aslr && min_addr == 0 && !cluster &&
1910 	    find_space != VMFS_NO_SPACE &&
1911 	    (map->flags & MAP_ASLR_IGNSTART) != 0)
1912 		curr_min_addr = min_addr = vm_map_min(map);
1913 	try = 0;
1914 	vm_map_lock(map);
1915 	if (cluster) {
1916 		curr_min_addr = map->anon_loc;
1917 		if (curr_min_addr == 0)
1918 			cluster = false;
1919 	}
1920 	if (find_space != VMFS_NO_SPACE) {
1921 		KASSERT(find_space == VMFS_ANY_SPACE ||
1922 		    find_space == VMFS_OPTIMAL_SPACE ||
1923 		    find_space == VMFS_SUPER_SPACE ||
1924 		    alignment != 0, ("unexpected VMFS flag"));
1925 again:
1926 		/*
1927 		 * When creating an anonymous mapping, try clustering
1928 		 * with an existing anonymous mapping first.
1929 		 *
1930 		 * We make up to two attempts to find address space
1931 		 * for a given find_space value. The first attempt may
1932 		 * apply randomization or may cluster with an existing
1933 		 * anonymous mapping. If this first attempt fails,
1934 		 * perform a first-fit search of the available address
1935 		 * space.
1936 		 *
1937 		 * If all tries failed, and find_space is
1938 		 * VMFS_OPTIMAL_SPACE, fallback to VMFS_ANY_SPACE.
1939 		 * Again enable clustering and randomization.
1940 		 */
1941 		try++;
1942 		MPASS(try <= 2);
1943 
1944 		if (try == 2) {
1945 			/*
1946 			 * Second try: we failed either to find a
1947 			 * suitable region for randomizing the
1948 			 * allocation, or to cluster with an existing
1949 			 * mapping.  Retry with free run.
1950 			 */
1951 			curr_min_addr = (map->flags & MAP_ASLR_IGNSTART) != 0 ?
1952 			    vm_map_min(map) : min_addr;
1953 			atomic_add_long(&aslr_restarts, 1);
1954 		}
1955 
1956 		if (try == 1 && en_aslr && !cluster) {
1957 			/*
1958 			 * Find space for allocation, including
1959 			 * gap needed for later randomization.
1960 			 */
1961 			pidx = MAXPAGESIZES > 1 && pagesizes[1] != 0 &&
1962 			    (find_space == VMFS_SUPER_SPACE || find_space ==
1963 			    VMFS_OPTIMAL_SPACE) ? 1 : 0;
1964 			gap = vm_map_max(map) > MAP_32BIT_MAX_ADDR &&
1965 			    (max_addr == 0 || max_addr > MAP_32BIT_MAX_ADDR) ?
1966 			    aslr_pages_rnd_64[pidx] : aslr_pages_rnd_32[pidx];
1967 			*addr = vm_map_findspace(map, curr_min_addr,
1968 			    length + gap * pagesizes[pidx]);
1969 			if (*addr + length + gap * pagesizes[pidx] >
1970 			    vm_map_max(map))
1971 				goto again;
1972 			/* And randomize the start address. */
1973 			*addr += (arc4random() % gap) * pagesizes[pidx];
1974 			if (max_addr != 0 && *addr + length > max_addr)
1975 				goto again;
1976 		} else {
1977 			*addr = vm_map_findspace(map, curr_min_addr, length);
1978 			if (*addr + length > vm_map_max(map) ||
1979 			    (max_addr != 0 && *addr + length > max_addr)) {
1980 				if (cluster) {
1981 					cluster = false;
1982 					MPASS(try == 1);
1983 					goto again;
1984 				}
1985 				rv = KERN_NO_SPACE;
1986 				goto done;
1987 			}
1988 		}
1989 
1990 		if (find_space != VMFS_ANY_SPACE &&
1991 		    (rv = vm_map_alignspace(map, object, offset, addr, length,
1992 		    max_addr, alignment)) != KERN_SUCCESS) {
1993 			if (find_space == VMFS_OPTIMAL_SPACE) {
1994 				find_space = VMFS_ANY_SPACE;
1995 				curr_min_addr = min_addr;
1996 				cluster = update_anon;
1997 				try = 0;
1998 				goto again;
1999 			}
2000 			goto done;
2001 		}
2002 	} else if ((cow & MAP_REMAP) != 0) {
2003 		if (!vm_map_range_valid(map, *addr, *addr + length)) {
2004 			rv = KERN_INVALID_ADDRESS;
2005 			goto done;
2006 		}
2007 		rv = vm_map_delete(map, *addr, *addr + length);
2008 		if (rv != KERN_SUCCESS)
2009 			goto done;
2010 	}
2011 	if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
2012 		rv = vm_map_stack_locked(map, *addr, length, sgrowsiz, prot,
2013 		    max, cow);
2014 	} else {
2015 		rv = vm_map_insert(map, object, offset, *addr, *addr + length,
2016 		    prot, max, cow);
2017 	}
2018 	if (rv == KERN_SUCCESS && update_anon)
2019 		map->anon_loc = *addr + length;
2020 done:
2021 	vm_map_unlock(map);
2022 	return (rv);
2023 }
2024 
2025 /*
2026  *	vm_map_find_min() is a variant of vm_map_find() that takes an
2027  *	additional parameter (min_addr) and treats the given address
2028  *	(*addr) differently.  Specifically, it treats *addr as a hint
2029  *	and not as the minimum address where the mapping is created.
2030  *
2031  *	This function works in two phases.  First, it tries to
2032  *	allocate above the hint.  If that fails and the hint is
2033  *	greater than min_addr, it performs a second pass, replacing
2034  *	the hint with min_addr as the minimum address for the
2035  *	allocation.
2036  */
2037 int
vm_map_find_min(vm_map_t map,vm_object_t object,vm_ooffset_t offset,vm_offset_t * addr,vm_size_t length,vm_offset_t min_addr,vm_offset_t max_addr,int find_space,vm_prot_t prot,vm_prot_t max,int cow)2038 vm_map_find_min(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
2039     vm_offset_t *addr, vm_size_t length, vm_offset_t min_addr,
2040     vm_offset_t max_addr, int find_space, vm_prot_t prot, vm_prot_t max,
2041     int cow)
2042 {
2043 	vm_offset_t hint;
2044 	int rv;
2045 
2046 	hint = *addr;
2047 	for (;;) {
2048 		rv = vm_map_find(map, object, offset, addr, length, max_addr,
2049 		    find_space, prot, max, cow);
2050 		if (rv == KERN_SUCCESS || min_addr >= hint)
2051 			return (rv);
2052 		*addr = hint = min_addr;
2053 	}
2054 }
2055 
2056 /*
2057  * A map entry with any of the following flags set must not be merged with
2058  * another entry.
2059  */
2060 #define	MAP_ENTRY_NOMERGE_MASK	(MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP | \
2061 	    MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP | MAP_ENTRY_VN_EXEC)
2062 
2063 static bool
vm_map_mergeable_neighbors(vm_map_entry_t prev,vm_map_entry_t entry)2064 vm_map_mergeable_neighbors(vm_map_entry_t prev, vm_map_entry_t entry)
2065 {
2066 
2067 	KASSERT((prev->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 ||
2068 	    (entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0,
2069 	    ("vm_map_mergeable_neighbors: neither %p nor %p are mergeable",
2070 	    prev, entry));
2071 	return (prev->end == entry->start &&
2072 	    prev->object.vm_object == entry->object.vm_object &&
2073 	    (prev->object.vm_object == NULL ||
2074 	    prev->offset + (prev->end - prev->start) == entry->offset) &&
2075 	    prev->eflags == entry->eflags &&
2076 	    prev->protection == entry->protection &&
2077 	    prev->max_protection == entry->max_protection &&
2078 	    prev->inheritance == entry->inheritance &&
2079 	    prev->wired_count == entry->wired_count &&
2080 	    prev->cred == entry->cred);
2081 }
2082 
2083 static void
vm_map_merged_neighbor_dispose(vm_map_t map,vm_map_entry_t entry)2084 vm_map_merged_neighbor_dispose(vm_map_t map, vm_map_entry_t entry)
2085 {
2086 
2087 	/*
2088 	 * If the backing object is a vnode object, vm_object_deallocate()
2089 	 * calls vrele().  However, vrele() does not lock the vnode because
2090 	 * the vnode has additional references.  Thus, the map lock can be
2091 	 * kept without causing a lock-order reversal with the vnode lock.
2092 	 *
2093 	 * Since we count the number of virtual page mappings in
2094 	 * object->un_pager.vnp.writemappings, the writemappings value
2095 	 * should not be adjusted when the entry is disposed of.
2096 	 */
2097 	if (entry->object.vm_object != NULL)
2098 		vm_object_deallocate(entry->object.vm_object);
2099 	if (entry->cred != NULL)
2100 		crfree(entry->cred);
2101 	vm_map_entry_dispose(map, entry);
2102 }
2103 
2104 /*
2105  *	vm_map_simplify_entry:
2106  *
2107  *	Simplify the given map entry by merging with either neighbor.  This
2108  *	routine also has the ability to merge with both neighbors.
2109  *
2110  *	The map must be locked.
2111  *
2112  *	This routine guarantees that the passed entry remains valid (though
2113  *	possibly extended).  When merging, this routine may delete one or
2114  *	both neighbors.
2115  */
2116 void
vm_map_simplify_entry(vm_map_t map,vm_map_entry_t entry)2117 vm_map_simplify_entry(vm_map_t map, vm_map_entry_t entry)
2118 {
2119 	vm_map_entry_t next, prev;
2120 
2121 	if ((entry->eflags & MAP_ENTRY_NOMERGE_MASK) != 0)
2122 		return;
2123 	prev = entry->prev;
2124 	if (vm_map_mergeable_neighbors(prev, entry)) {
2125 		vm_map_entry_unlink(map, prev, UNLINK_MERGE_NEXT);
2126 		vm_map_merged_neighbor_dispose(map, prev);
2127 	}
2128 	next = entry->next;
2129 	if (vm_map_mergeable_neighbors(entry, next)) {
2130 		vm_map_entry_unlink(map, next, UNLINK_MERGE_PREV);
2131 		vm_map_merged_neighbor_dispose(map, next);
2132 	}
2133 }
2134 
2135 /*
2136  *	vm_map_clip_start:	[ internal use only ]
2137  *
2138  *	Asserts that the given entry begins at or after
2139  *	the specified address; if necessary,
2140  *	it splits the entry into two.
2141  */
2142 #define vm_map_clip_start(map, entry, startaddr) \
2143 { \
2144 	if (startaddr > entry->start) \
2145 		_vm_map_clip_start(map, entry, startaddr); \
2146 }
2147 
2148 /*
2149  *	This routine is called only when it is known that
2150  *	the entry must be split.
2151  */
2152 static void
_vm_map_clip_start(vm_map_t map,vm_map_entry_t entry,vm_offset_t start)2153 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start)
2154 {
2155 	vm_map_entry_t new_entry;
2156 
2157 	VM_MAP_ASSERT_LOCKED(map);
2158 	KASSERT(entry->end > start && entry->start < start,
2159 	    ("_vm_map_clip_start: invalid clip of entry %p", entry));
2160 
2161 	/*
2162 	 * Split off the front portion -- note that we must insert the new
2163 	 * entry BEFORE this one, so that this entry has the specified
2164 	 * starting address.
2165 	 */
2166 	vm_map_simplify_entry(map, entry);
2167 
2168 	/*
2169 	 * If there is no object backing this entry, we might as well create
2170 	 * one now.  If we defer it, an object can get created after the map
2171 	 * is clipped, and individual objects will be created for the split-up
2172 	 * map.  This is a bit of a hack, but is also about the best place to
2173 	 * put this improvement.
2174 	 */
2175 	if (entry->object.vm_object == NULL && !map->system_map &&
2176 	    (entry->eflags & MAP_ENTRY_GUARD) == 0) {
2177 		vm_object_t object;
2178 		object = vm_object_allocate(OBJT_DEFAULT,
2179 				atop(entry->end - entry->start));
2180 		entry->object.vm_object = object;
2181 		entry->offset = 0;
2182 		if (entry->cred != NULL) {
2183 			object->cred = entry->cred;
2184 			object->charge = entry->end - entry->start;
2185 			entry->cred = NULL;
2186 		}
2187 	} else if (entry->object.vm_object != NULL &&
2188 		   ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
2189 		   entry->cred != NULL) {
2190 		VM_OBJECT_WLOCK(entry->object.vm_object);
2191 		KASSERT(entry->object.vm_object->cred == NULL,
2192 		    ("OVERCOMMIT: vm_entry_clip_start: both cred e %p", entry));
2193 		entry->object.vm_object->cred = entry->cred;
2194 		entry->object.vm_object->charge = entry->end - entry->start;
2195 		VM_OBJECT_WUNLOCK(entry->object.vm_object);
2196 		entry->cred = NULL;
2197 	}
2198 
2199 	new_entry = vm_map_entry_create(map);
2200 	*new_entry = *entry;
2201 
2202 	new_entry->end = start;
2203 	entry->offset += (start - entry->start);
2204 	entry->start = start;
2205 	if (new_entry->cred != NULL)
2206 		crhold(entry->cred);
2207 
2208 	vm_map_entry_link(map, new_entry);
2209 
2210 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2211 		vm_object_reference(new_entry->object.vm_object);
2212 		vm_map_entry_set_vnode_text(new_entry, true);
2213 		/*
2214 		 * The object->un_pager.vnp.writemappings for the
2215 		 * object of MAP_ENTRY_WRITECNT type entry shall be
2216 		 * kept as is here.  The virtual pages are
2217 		 * re-distributed among the clipped entries, so the sum is
2218 		 * left the same.
2219 		 */
2220 	}
2221 }
2222 
2223 /*
2224  *	vm_map_clip_end:	[ internal use only ]
2225  *
2226  *	Asserts that the given entry ends at or before
2227  *	the specified address; if necessary,
2228  *	it splits the entry into two.
2229  */
2230 #define vm_map_clip_end(map, entry, endaddr) \
2231 { \
2232 	if ((endaddr) < (entry->end)) \
2233 		_vm_map_clip_end((map), (entry), (endaddr)); \
2234 }
2235 
2236 /*
2237  *	This routine is called only when it is known that
2238  *	the entry must be split.
2239  */
2240 static void
_vm_map_clip_end(vm_map_t map,vm_map_entry_t entry,vm_offset_t end)2241 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end)
2242 {
2243 	vm_map_entry_t new_entry;
2244 
2245 	VM_MAP_ASSERT_LOCKED(map);
2246 	KASSERT(entry->start < end && entry->end > end,
2247 	    ("_vm_map_clip_end: invalid clip of entry %p", entry));
2248 
2249 	/*
2250 	 * If there is no object backing this entry, we might as well create
2251 	 * one now.  If we defer it, an object can get created after the map
2252 	 * is clipped, and individual objects will be created for the split-up
2253 	 * map.  This is a bit of a hack, but is also about the best place to
2254 	 * put this improvement.
2255 	 */
2256 	if (entry->object.vm_object == NULL && !map->system_map &&
2257 	    (entry->eflags & MAP_ENTRY_GUARD) == 0) {
2258 		vm_object_t object;
2259 		object = vm_object_allocate(OBJT_DEFAULT,
2260 				atop(entry->end - entry->start));
2261 		entry->object.vm_object = object;
2262 		entry->offset = 0;
2263 		if (entry->cred != NULL) {
2264 			object->cred = entry->cred;
2265 			object->charge = entry->end - entry->start;
2266 			entry->cred = NULL;
2267 		}
2268 	} else if (entry->object.vm_object != NULL &&
2269 		   ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
2270 		   entry->cred != NULL) {
2271 		VM_OBJECT_WLOCK(entry->object.vm_object);
2272 		KASSERT(entry->object.vm_object->cred == NULL,
2273 		    ("OVERCOMMIT: vm_entry_clip_end: both cred e %p", entry));
2274 		entry->object.vm_object->cred = entry->cred;
2275 		entry->object.vm_object->charge = entry->end - entry->start;
2276 		VM_OBJECT_WUNLOCK(entry->object.vm_object);
2277 		entry->cred = NULL;
2278 	}
2279 
2280 	/*
2281 	 * Create a new entry and insert it AFTER the specified entry
2282 	 */
2283 	new_entry = vm_map_entry_create(map);
2284 	*new_entry = *entry;
2285 
2286 	new_entry->start = entry->end = end;
2287 	new_entry->offset += (end - entry->start);
2288 	if (new_entry->cred != NULL)
2289 		crhold(entry->cred);
2290 
2291 	vm_map_entry_link(map, new_entry);
2292 
2293 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2294 		vm_object_reference(new_entry->object.vm_object);
2295 		vm_map_entry_set_vnode_text(new_entry, true);
2296 	}
2297 }
2298 
2299 /*
2300  *	vm_map_submap:		[ kernel use only ]
2301  *
2302  *	Mark the given range as handled by a subordinate map.
2303  *
2304  *	This range must have been created with vm_map_find,
2305  *	and no other operations may have been performed on this
2306  *	range prior to calling vm_map_submap.
2307  *
2308  *	Only a limited number of operations can be performed
2309  *	within this rage after calling vm_map_submap:
2310  *		vm_fault
2311  *	[Don't try vm_map_copy!]
2312  *
2313  *	To remove a submapping, one must first remove the
2314  *	range from the superior map, and then destroy the
2315  *	submap (if desired).  [Better yet, don't try it.]
2316  */
2317 int
vm_map_submap(vm_map_t map,vm_offset_t start,vm_offset_t end,vm_map_t submap)2318 vm_map_submap(
2319 	vm_map_t map,
2320 	vm_offset_t start,
2321 	vm_offset_t end,
2322 	vm_map_t submap)
2323 {
2324 	vm_map_entry_t entry;
2325 	int result;
2326 
2327 	result = KERN_INVALID_ARGUMENT;
2328 
2329 	vm_map_lock(submap);
2330 	submap->flags |= MAP_IS_SUB_MAP;
2331 	vm_map_unlock(submap);
2332 
2333 	vm_map_lock(map);
2334 
2335 	VM_MAP_RANGE_CHECK(map, start, end);
2336 
2337 	if (vm_map_lookup_entry(map, start, &entry)) {
2338 		vm_map_clip_start(map, entry, start);
2339 	} else
2340 		entry = entry->next;
2341 
2342 	vm_map_clip_end(map, entry, end);
2343 
2344 	if ((entry->start == start) && (entry->end == end) &&
2345 	    ((entry->eflags & MAP_ENTRY_COW) == 0) &&
2346 	    (entry->object.vm_object == NULL)) {
2347 		entry->object.sub_map = submap;
2348 		entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
2349 		result = KERN_SUCCESS;
2350 	}
2351 	vm_map_unlock(map);
2352 
2353 	if (result != KERN_SUCCESS) {
2354 		vm_map_lock(submap);
2355 		submap->flags &= ~MAP_IS_SUB_MAP;
2356 		vm_map_unlock(submap);
2357 	}
2358 	return (result);
2359 }
2360 
2361 /*
2362  * The maximum number of pages to map if MAP_PREFAULT_PARTIAL is specified
2363  */
2364 #define	MAX_INIT_PT	96
2365 
2366 /*
2367  *	vm_map_pmap_enter:
2368  *
2369  *	Preload the specified map's pmap with mappings to the specified
2370  *	object's memory-resident pages.  No further physical pages are
2371  *	allocated, and no further virtual pages are retrieved from secondary
2372  *	storage.  If the specified flags include MAP_PREFAULT_PARTIAL, then a
2373  *	limited number of page mappings are created at the low-end of the
2374  *	specified address range.  (For this purpose, a superpage mapping
2375  *	counts as one page mapping.)  Otherwise, all resident pages within
2376  *	the specified address range are mapped.
2377  */
2378 static void
vm_map_pmap_enter(vm_map_t map,vm_offset_t addr,vm_prot_t prot,vm_object_t object,vm_pindex_t pindex,vm_size_t size,int flags)2379 vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
2380     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
2381 {
2382 	vm_offset_t start;
2383 	vm_page_t p, p_start;
2384 	vm_pindex_t mask, psize, threshold, tmpidx;
2385 
2386 	if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0 || object == NULL)
2387 		return;
2388 	VM_OBJECT_RLOCK(object);
2389 	if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2390 		VM_OBJECT_RUNLOCK(object);
2391 		VM_OBJECT_WLOCK(object);
2392 		if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2393 			pmap_object_init_pt(map->pmap, addr, object, pindex,
2394 			    size);
2395 			VM_OBJECT_WUNLOCK(object);
2396 			return;
2397 		}
2398 		VM_OBJECT_LOCK_DOWNGRADE(object);
2399 	}
2400 
2401 	psize = atop(size);
2402 	if (psize + pindex > object->size) {
2403 		if (pindex >= object->size) {
2404 			VM_OBJECT_RUNLOCK(object);
2405 			return;
2406 		}
2407 		psize = object->size - pindex;
2408 	}
2409 
2410 	start = 0;
2411 	p_start = NULL;
2412 	threshold = MAX_INIT_PT;
2413 
2414 	p = vm_page_find_least(object, pindex);
2415 	/*
2416 	 * Assert: the variable p is either (1) the page with the
2417 	 * least pindex greater than or equal to the parameter pindex
2418 	 * or (2) NULL.
2419 	 */
2420 	for (;
2421 	     p != NULL && (tmpidx = p->pindex - pindex) < psize;
2422 	     p = TAILQ_NEXT(p, listq)) {
2423 		/*
2424 		 * don't allow an madvise to blow away our really
2425 		 * free pages allocating pv entries.
2426 		 */
2427 		if (((flags & MAP_PREFAULT_MADVISE) != 0 &&
2428 		    vm_page_count_severe()) ||
2429 		    ((flags & MAP_PREFAULT_PARTIAL) != 0 &&
2430 		    tmpidx >= threshold)) {
2431 			psize = tmpidx;
2432 			break;
2433 		}
2434 		if (p->valid == VM_PAGE_BITS_ALL) {
2435 			if (p_start == NULL) {
2436 				start = addr + ptoa(tmpidx);
2437 				p_start = p;
2438 			}
2439 			/* Jump ahead if a superpage mapping is possible. */
2440 			if (p->psind > 0 && ((addr + ptoa(tmpidx)) &
2441 			    (pagesizes[p->psind] - 1)) == 0) {
2442 				mask = atop(pagesizes[p->psind]) - 1;
2443 				if (tmpidx + mask < psize &&
2444 				    vm_page_ps_test(p, PS_ALL_VALID, NULL)) {
2445 					p += mask;
2446 					threshold += mask;
2447 				}
2448 			}
2449 		} else if (p_start != NULL) {
2450 			pmap_enter_object(map->pmap, start, addr +
2451 			    ptoa(tmpidx), p_start, prot);
2452 			p_start = NULL;
2453 		}
2454 	}
2455 	if (p_start != NULL)
2456 		pmap_enter_object(map->pmap, start, addr + ptoa(psize),
2457 		    p_start, prot);
2458 	VM_OBJECT_RUNLOCK(object);
2459 }
2460 
2461 /*
2462  *	vm_map_protect:
2463  *
2464  *	Sets the protection of the specified address
2465  *	region in the target map.  If "set_max" is
2466  *	specified, the maximum protection is to be set;
2467  *	otherwise, only the current protection is affected.
2468  */
2469 int
vm_map_protect(vm_map_t map,vm_offset_t start,vm_offset_t end,vm_prot_t new_prot,boolean_t set_max)2470 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
2471 	       vm_prot_t new_prot, boolean_t set_max)
2472 {
2473 	vm_map_entry_t current, entry, in_tran;
2474 	vm_object_t obj;
2475 	struct ucred *cred;
2476 	vm_prot_t old_prot;
2477 
2478 	if (start == end)
2479 		return (KERN_SUCCESS);
2480 
2481 again:
2482 	in_tran = NULL;
2483 	vm_map_lock(map);
2484 
2485 	/*
2486 	 * Ensure that we are not concurrently wiring pages.  vm_map_wire() may
2487 	 * need to fault pages into the map and will drop the map lock while
2488 	 * doing so, and the VM object may end up in an inconsistent state if we
2489 	 * update the protection on the map entry in between faults.
2490 	 */
2491 	vm_map_wait_busy(map);
2492 
2493 	VM_MAP_RANGE_CHECK(map, start, end);
2494 
2495 	if (vm_map_lookup_entry(map, start, &entry)) {
2496 		vm_map_clip_start(map, entry, start);
2497 	} else {
2498 		entry = entry->next;
2499 	}
2500 
2501 	/*
2502 	 * Make a first pass to check for protection violations.
2503 	 */
2504 	for (current = entry; current->start < end; current = current->next) {
2505 		if ((current->eflags & MAP_ENTRY_GUARD) != 0)
2506 			continue;
2507 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
2508 			vm_map_unlock(map);
2509 			return (KERN_INVALID_ARGUMENT);
2510 		}
2511 		if ((new_prot & current->max_protection) != new_prot) {
2512 			vm_map_unlock(map);
2513 			return (KERN_PROTECTION_FAILURE);
2514 		}
2515 		if ((current->eflags & MAP_ENTRY_IN_TRANSITION) != 0)
2516 			in_tran = current;
2517 	}
2518 
2519 	/*
2520 	 * Postpone the operation until all in-transition map entries have
2521 	 * stabilized.  An in-transition entry might already have its pages
2522 	 * wired and wired_count incremented, but not yet have its
2523 	 * MAP_ENTRY_USER_WIRED flag set.  In which case, we would fail to call
2524 	 * vm_fault_copy_entry() in the final loop below.
2525 	 */
2526 	if (in_tran != NULL) {
2527 		in_tran->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2528 		vm_map_unlock_and_wait(map, 0);
2529 		goto again;
2530 	}
2531 
2532 	/*
2533 	 * Do an accounting pass for private read-only mappings that
2534 	 * now will do cow due to allowed write (e.g. debugger sets
2535 	 * breakpoint on text segment)
2536 	 */
2537 	for (current = entry; current->start < end; current = current->next) {
2538 
2539 		vm_map_clip_end(map, current, end);
2540 
2541 		if (set_max ||
2542 		    ((new_prot & ~(current->protection)) & VM_PROT_WRITE) == 0 ||
2543 		    ENTRY_CHARGED(current) ||
2544 		    (current->eflags & MAP_ENTRY_GUARD) != 0) {
2545 			continue;
2546 		}
2547 
2548 		cred = curthread->td_ucred;
2549 		obj = current->object.vm_object;
2550 
2551 		if (obj == NULL || (current->eflags & MAP_ENTRY_NEEDS_COPY)) {
2552 			if (!swap_reserve(current->end - current->start)) {
2553 				vm_map_unlock(map);
2554 				return (KERN_RESOURCE_SHORTAGE);
2555 			}
2556 			crhold(cred);
2557 			current->cred = cred;
2558 			continue;
2559 		}
2560 
2561 		VM_OBJECT_WLOCK(obj);
2562 		if (obj->type != OBJT_DEFAULT && obj->type != OBJT_SWAP) {
2563 			VM_OBJECT_WUNLOCK(obj);
2564 			continue;
2565 		}
2566 
2567 		/*
2568 		 * Charge for the whole object allocation now, since
2569 		 * we cannot distinguish between non-charged and
2570 		 * charged clipped mapping of the same object later.
2571 		 */
2572 		KASSERT(obj->charge == 0,
2573 		    ("vm_map_protect: object %p overcharged (entry %p)",
2574 		    obj, current));
2575 		if (!swap_reserve(ptoa(obj->size))) {
2576 			VM_OBJECT_WUNLOCK(obj);
2577 			vm_map_unlock(map);
2578 			return (KERN_RESOURCE_SHORTAGE);
2579 		}
2580 
2581 		crhold(cred);
2582 		obj->cred = cred;
2583 		obj->charge = ptoa(obj->size);
2584 		VM_OBJECT_WUNLOCK(obj);
2585 	}
2586 
2587 	/*
2588 	 * Go back and fix up protections. [Note that clipping is not
2589 	 * necessary the second time.]
2590 	 */
2591 	for (current = entry; current->start < end; current = current->next) {
2592 		if ((current->eflags & MAP_ENTRY_GUARD) != 0)
2593 			continue;
2594 
2595 		old_prot = current->protection;
2596 
2597 		if (set_max)
2598 			current->protection =
2599 			    (current->max_protection = new_prot) &
2600 			    old_prot;
2601 		else
2602 			current->protection = new_prot;
2603 
2604 		/*
2605 		 * For user wired map entries, the normal lazy evaluation of
2606 		 * write access upgrades through soft page faults is
2607 		 * undesirable.  Instead, immediately copy any pages that are
2608 		 * copy-on-write and enable write access in the physical map.
2609 		 */
2610 		if ((current->eflags & MAP_ENTRY_USER_WIRED) != 0 &&
2611 		    (current->protection & VM_PROT_WRITE) != 0 &&
2612 		    (old_prot & VM_PROT_WRITE) == 0)
2613 			vm_fault_copy_entry(map, map, current, current, NULL);
2614 
2615 		/*
2616 		 * When restricting access, update the physical map.  Worry
2617 		 * about copy-on-write here.
2618 		 */
2619 		if ((old_prot & ~current->protection) != 0) {
2620 #define MASK(entry)	(((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
2621 							VM_PROT_ALL)
2622 			pmap_protect(map->pmap, current->start,
2623 			    current->end,
2624 			    current->protection & MASK(current));
2625 #undef	MASK
2626 		}
2627 		vm_map_simplify_entry(map, current);
2628 	}
2629 	vm_map_unlock(map);
2630 	return (KERN_SUCCESS);
2631 }
2632 
2633 /*
2634  *	vm_map_madvise:
2635  *
2636  *	This routine traverses a processes map handling the madvise
2637  *	system call.  Advisories are classified as either those effecting
2638  *	the vm_map_entry structure, or those effecting the underlying
2639  *	objects.
2640  */
2641 int
vm_map_madvise(vm_map_t map,vm_offset_t start,vm_offset_t end,int behav)2642 vm_map_madvise(
2643 	vm_map_t map,
2644 	vm_offset_t start,
2645 	vm_offset_t end,
2646 	int behav)
2647 {
2648 	vm_map_entry_t current, entry;
2649 	bool modify_map;
2650 
2651 	/*
2652 	 * Some madvise calls directly modify the vm_map_entry, in which case
2653 	 * we need to use an exclusive lock on the map and we need to perform
2654 	 * various clipping operations.  Otherwise we only need a read-lock
2655 	 * on the map.
2656 	 */
2657 	switch(behav) {
2658 	case MADV_NORMAL:
2659 	case MADV_SEQUENTIAL:
2660 	case MADV_RANDOM:
2661 	case MADV_NOSYNC:
2662 	case MADV_AUTOSYNC:
2663 	case MADV_NOCORE:
2664 	case MADV_CORE:
2665 		if (start == end)
2666 			return (0);
2667 		modify_map = true;
2668 		vm_map_lock(map);
2669 		break;
2670 	case MADV_WILLNEED:
2671 	case MADV_DONTNEED:
2672 	case MADV_FREE:
2673 		if (start == end)
2674 			return (0);
2675 		modify_map = false;
2676 		vm_map_lock_read(map);
2677 		break;
2678 	default:
2679 		return (EINVAL);
2680 	}
2681 
2682 	/*
2683 	 * Locate starting entry and clip if necessary.
2684 	 */
2685 	VM_MAP_RANGE_CHECK(map, start, end);
2686 
2687 	if (vm_map_lookup_entry(map, start, &entry)) {
2688 		if (modify_map)
2689 			vm_map_clip_start(map, entry, start);
2690 	} else {
2691 		entry = entry->next;
2692 	}
2693 
2694 	if (modify_map) {
2695 		/*
2696 		 * madvise behaviors that are implemented in the vm_map_entry.
2697 		 *
2698 		 * We clip the vm_map_entry so that behavioral changes are
2699 		 * limited to the specified address range.
2700 		 */
2701 		for (current = entry; current->start < end;
2702 		    current = current->next) {
2703 			if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2704 				continue;
2705 
2706 			vm_map_clip_end(map, current, end);
2707 
2708 			switch (behav) {
2709 			case MADV_NORMAL:
2710 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
2711 				break;
2712 			case MADV_SEQUENTIAL:
2713 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
2714 				break;
2715 			case MADV_RANDOM:
2716 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
2717 				break;
2718 			case MADV_NOSYNC:
2719 				current->eflags |= MAP_ENTRY_NOSYNC;
2720 				break;
2721 			case MADV_AUTOSYNC:
2722 				current->eflags &= ~MAP_ENTRY_NOSYNC;
2723 				break;
2724 			case MADV_NOCORE:
2725 				current->eflags |= MAP_ENTRY_NOCOREDUMP;
2726 				break;
2727 			case MADV_CORE:
2728 				current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
2729 				break;
2730 			default:
2731 				break;
2732 			}
2733 			vm_map_simplify_entry(map, current);
2734 		}
2735 		vm_map_unlock(map);
2736 	} else {
2737 		vm_pindex_t pstart, pend;
2738 
2739 		/*
2740 		 * madvise behaviors that are implemented in the underlying
2741 		 * vm_object.
2742 		 *
2743 		 * Since we don't clip the vm_map_entry, we have to clip
2744 		 * the vm_object pindex and count.
2745 		 */
2746 		for (current = entry; current->start < end;
2747 		    current = current->next) {
2748 			vm_offset_t useEnd, useStart;
2749 
2750 			if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2751 				continue;
2752 
2753 			/*
2754 			 * MADV_FREE would otherwise rewind time to
2755 			 * the creation of the shadow object.  Because
2756 			 * we hold the VM map read-locked, neither the
2757 			 * entry's object nor the presence of a
2758 			 * backing object can change.
2759 			 */
2760 			if (behav == MADV_FREE &&
2761 			    current->object.vm_object != NULL &&
2762 			    current->object.vm_object->backing_object != NULL)
2763 				continue;
2764 
2765 			pstart = OFF_TO_IDX(current->offset);
2766 			pend = pstart + atop(current->end - current->start);
2767 			useStart = current->start;
2768 			useEnd = current->end;
2769 
2770 			if (current->start < start) {
2771 				pstart += atop(start - current->start);
2772 				useStart = start;
2773 			}
2774 			if (current->end > end) {
2775 				pend -= atop(current->end - end);
2776 				useEnd = end;
2777 			}
2778 
2779 			if (pstart >= pend)
2780 				continue;
2781 
2782 			/*
2783 			 * Perform the pmap_advise() before clearing
2784 			 * PGA_REFERENCED in vm_page_advise().  Otherwise, a
2785 			 * concurrent pmap operation, such as pmap_remove(),
2786 			 * could clear a reference in the pmap and set
2787 			 * PGA_REFERENCED on the page before the pmap_advise()
2788 			 * had completed.  Consequently, the page would appear
2789 			 * referenced based upon an old reference that
2790 			 * occurred before this pmap_advise() ran.
2791 			 */
2792 			if (behav == MADV_DONTNEED || behav == MADV_FREE)
2793 				pmap_advise(map->pmap, useStart, useEnd,
2794 				    behav);
2795 
2796 			vm_object_madvise(current->object.vm_object, pstart,
2797 			    pend, behav);
2798 
2799 			/*
2800 			 * Pre-populate paging structures in the
2801 			 * WILLNEED case.  For wired entries, the
2802 			 * paging structures are already populated.
2803 			 */
2804 			if (behav == MADV_WILLNEED &&
2805 			    current->wired_count == 0) {
2806 				vm_map_pmap_enter(map,
2807 				    useStart,
2808 				    current->protection,
2809 				    current->object.vm_object,
2810 				    pstart,
2811 				    ptoa(pend - pstart),
2812 				    MAP_PREFAULT_MADVISE
2813 				);
2814 			}
2815 		}
2816 		vm_map_unlock_read(map);
2817 	}
2818 	return (0);
2819 }
2820 
2821 
2822 /*
2823  *	vm_map_inherit:
2824  *
2825  *	Sets the inheritance of the specified address
2826  *	range in the target map.  Inheritance
2827  *	affects how the map will be shared with
2828  *	child maps at the time of vmspace_fork.
2829  */
2830 int
vm_map_inherit(vm_map_t map,vm_offset_t start,vm_offset_t end,vm_inherit_t new_inheritance)2831 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
2832 	       vm_inherit_t new_inheritance)
2833 {
2834 	vm_map_entry_t entry;
2835 	vm_map_entry_t temp_entry;
2836 
2837 	switch (new_inheritance) {
2838 	case VM_INHERIT_NONE:
2839 	case VM_INHERIT_COPY:
2840 	case VM_INHERIT_SHARE:
2841 	case VM_INHERIT_ZERO:
2842 		break;
2843 	default:
2844 		return (KERN_INVALID_ARGUMENT);
2845 	}
2846 	if (start == end)
2847 		return (KERN_SUCCESS);
2848 	vm_map_lock(map);
2849 	VM_MAP_RANGE_CHECK(map, start, end);
2850 	if (vm_map_lookup_entry(map, start, &temp_entry)) {
2851 		entry = temp_entry;
2852 		vm_map_clip_start(map, entry, start);
2853 	} else
2854 		entry = temp_entry->next;
2855 	while (entry->start < end) {
2856 		vm_map_clip_end(map, entry, end);
2857 		if ((entry->eflags & MAP_ENTRY_GUARD) == 0 ||
2858 		    new_inheritance != VM_INHERIT_ZERO)
2859 			entry->inheritance = new_inheritance;
2860 		vm_map_simplify_entry(map, entry);
2861 		entry = entry->next;
2862 	}
2863 	vm_map_unlock(map);
2864 	return (KERN_SUCCESS);
2865 }
2866 
2867 /*
2868  *	vm_map_unwire:
2869  *
2870  *	Implements both kernel and user unwiring.
2871  */
2872 int
vm_map_unwire(vm_map_t map,vm_offset_t start,vm_offset_t end,int flags)2873 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
2874     int flags)
2875 {
2876 	vm_map_entry_t entry, first_entry, tmp_entry;
2877 	vm_offset_t saved_start;
2878 	unsigned int last_timestamp;
2879 	int rv;
2880 	boolean_t need_wakeup, result, user_unwire;
2881 
2882 	if (start == end)
2883 		return (KERN_SUCCESS);
2884 	user_unwire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
2885 	vm_map_lock(map);
2886 	VM_MAP_RANGE_CHECK(map, start, end);
2887 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
2888 		if (flags & VM_MAP_WIRE_HOLESOK)
2889 			first_entry = first_entry->next;
2890 		else {
2891 			vm_map_unlock(map);
2892 			return (KERN_INVALID_ADDRESS);
2893 		}
2894 	}
2895 	last_timestamp = map->timestamp;
2896 	entry = first_entry;
2897 	while (entry->start < end) {
2898 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2899 			/*
2900 			 * We have not yet clipped the entry.
2901 			 */
2902 			saved_start = (start >= entry->start) ? start :
2903 			    entry->start;
2904 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2905 			if (vm_map_unlock_and_wait(map, 0)) {
2906 				/*
2907 				 * Allow interruption of user unwiring?
2908 				 */
2909 			}
2910 			vm_map_lock(map);
2911 			if (last_timestamp+1 != map->timestamp) {
2912 				/*
2913 				 * Look again for the entry because the map was
2914 				 * modified while it was unlocked.
2915 				 * Specifically, the entry may have been
2916 				 * clipped, merged, or deleted.
2917 				 */
2918 				if (!vm_map_lookup_entry(map, saved_start,
2919 				    &tmp_entry)) {
2920 					if (flags & VM_MAP_WIRE_HOLESOK)
2921 						tmp_entry = tmp_entry->next;
2922 					else {
2923 						if (saved_start == start) {
2924 							/*
2925 							 * First_entry has been deleted.
2926 							 */
2927 							vm_map_unlock(map);
2928 							return (KERN_INVALID_ADDRESS);
2929 						}
2930 						end = saved_start;
2931 						rv = KERN_INVALID_ADDRESS;
2932 						goto done;
2933 					}
2934 				}
2935 				if (entry == first_entry)
2936 					first_entry = tmp_entry;
2937 				else
2938 					first_entry = NULL;
2939 				entry = tmp_entry;
2940 			}
2941 			last_timestamp = map->timestamp;
2942 			continue;
2943 		}
2944 		vm_map_clip_start(map, entry, start);
2945 		vm_map_clip_end(map, entry, end);
2946 		/*
2947 		 * Mark the entry in case the map lock is released.  (See
2948 		 * above.)
2949 		 */
2950 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
2951 		    entry->wiring_thread == NULL,
2952 		    ("owned map entry %p", entry));
2953 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
2954 		entry->wiring_thread = curthread;
2955 		/*
2956 		 * Check the map for holes in the specified region.
2957 		 * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
2958 		 */
2959 		if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
2960 		    (entry->end < end && entry->next->start > entry->end)) {
2961 			end = entry->end;
2962 			rv = KERN_INVALID_ADDRESS;
2963 			goto done;
2964 		}
2965 		/*
2966 		 * If system unwiring, require that the entry is system wired.
2967 		 */
2968 		if (!user_unwire &&
2969 		    vm_map_entry_system_wired_count(entry) == 0) {
2970 			end = entry->end;
2971 			rv = KERN_INVALID_ARGUMENT;
2972 			goto done;
2973 		}
2974 		entry = entry->next;
2975 	}
2976 	rv = KERN_SUCCESS;
2977 done:
2978 	need_wakeup = FALSE;
2979 	if (first_entry == NULL) {
2980 		result = vm_map_lookup_entry(map, start, &first_entry);
2981 		if (!result && (flags & VM_MAP_WIRE_HOLESOK))
2982 			first_entry = first_entry->next;
2983 		else
2984 			KASSERT(result, ("vm_map_unwire: lookup failed"));
2985 	}
2986 	for (entry = first_entry; entry->start < end; entry = entry->next) {
2987 		/*
2988 		 * If VM_MAP_WIRE_HOLESOK was specified, an empty
2989 		 * space in the unwired region could have been mapped
2990 		 * while the map lock was dropped for draining
2991 		 * MAP_ENTRY_IN_TRANSITION.  Moreover, another thread
2992 		 * could be simultaneously wiring this new mapping
2993 		 * entry.  Detect these cases and skip any entries
2994 		 * marked as in transition by us.
2995 		 */
2996 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
2997 		    entry->wiring_thread != curthread) {
2998 			KASSERT((flags & VM_MAP_WIRE_HOLESOK) != 0,
2999 			    ("vm_map_unwire: !HOLESOK and new/changed entry"));
3000 			continue;
3001 		}
3002 
3003 		if (rv == KERN_SUCCESS && (!user_unwire ||
3004 		    (entry->eflags & MAP_ENTRY_USER_WIRED))) {
3005 			if (entry->wired_count == 1)
3006 				vm_map_entry_unwire(map, entry);
3007 			else
3008 				entry->wired_count--;
3009 			if (user_unwire)
3010 				entry->eflags &= ~MAP_ENTRY_USER_WIRED;
3011 		}
3012 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3013 		    ("vm_map_unwire: in-transition flag missing %p", entry));
3014 		KASSERT(entry->wiring_thread == curthread,
3015 		    ("vm_map_unwire: alien wire %p", entry));
3016 		entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
3017 		entry->wiring_thread = NULL;
3018 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
3019 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
3020 			need_wakeup = TRUE;
3021 		}
3022 		vm_map_simplify_entry(map, entry);
3023 	}
3024 	vm_map_unlock(map);
3025 	if (need_wakeup)
3026 		vm_map_wakeup(map);
3027 	return (rv);
3028 }
3029 
3030 static void
vm_map_wire_user_count_sub(u_long npages)3031 vm_map_wire_user_count_sub(u_long npages)
3032 {
3033 
3034 	atomic_subtract_long(&vm_user_wire_count, npages);
3035 }
3036 
3037 static bool
vm_map_wire_user_count_add(u_long npages)3038 vm_map_wire_user_count_add(u_long npages)
3039 {
3040 	u_long wired;
3041 
3042 	wired = vm_user_wire_count;
3043 	do {
3044 		if (npages + wired > (u_long)vm_page_max_user_wired)
3045 			return (false);
3046 	} while (!atomic_fcmpset_long(&vm_user_wire_count, &wired,
3047 	    npages + wired));
3048 
3049 	return (true);
3050 }
3051 
3052 /*
3053  *	vm_map_wire_entry_failure:
3054  *
3055  *	Handle a wiring failure on the given entry.
3056  *
3057  *	The map should be locked.
3058  */
3059 static void
vm_map_wire_entry_failure(vm_map_t map,vm_map_entry_t entry,vm_offset_t failed_addr)3060 vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
3061     vm_offset_t failed_addr)
3062 {
3063 
3064 	VM_MAP_ASSERT_LOCKED(map);
3065 	KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 &&
3066 	    entry->wired_count == 1,
3067 	    ("vm_map_wire_entry_failure: entry %p isn't being wired", entry));
3068 	KASSERT(failed_addr < entry->end,
3069 	    ("vm_map_wire_entry_failure: entry %p was fully wired", entry));
3070 
3071 	/*
3072 	 * If any pages at the start of this entry were successfully wired,
3073 	 * then unwire them.
3074 	 */
3075 	if (failed_addr > entry->start) {
3076 		pmap_unwire(map->pmap, entry->start, failed_addr);
3077 		vm_object_unwire(entry->object.vm_object, entry->offset,
3078 		    failed_addr - entry->start, PQ_ACTIVE);
3079 	}
3080 
3081 	/*
3082 	 * Assign an out-of-range value to represent the failure to wire this
3083 	 * entry.
3084 	 */
3085 	entry->wired_count = -1;
3086 }
3087 
3088 int
vm_map_wire(vm_map_t map,vm_offset_t start,vm_offset_t end,int flags)3089 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3090 {
3091 	int rv;
3092 
3093 	vm_map_lock(map);
3094 	rv = vm_map_wire_locked(map, start, end, flags);
3095 	vm_map_unlock(map);
3096 	return (rv);
3097 }
3098 
3099 
3100 /*
3101  *	vm_map_wire_locked:
3102  *
3103  *	Implements both kernel and user wiring.  Returns with the map locked,
3104  *	the map lock may be dropped.
3105  */
3106 int
vm_map_wire_locked(vm_map_t map,vm_offset_t start,vm_offset_t end,int flags)3107 vm_map_wire_locked(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3108 {
3109 	vm_map_entry_t entry, first_entry, tmp_entry;
3110 	vm_offset_t faddr, saved_end, saved_start;
3111 	u_long npages;
3112 	u_int last_timestamp;
3113 	int rv;
3114 	boolean_t need_wakeup, result, user_wire;
3115 	vm_prot_t prot;
3116 
3117 	VM_MAP_ASSERT_LOCKED(map);
3118 
3119 	if (start == end)
3120 		return (KERN_SUCCESS);
3121 	prot = 0;
3122 	if (flags & VM_MAP_WIRE_WRITE)
3123 		prot |= VM_PROT_WRITE;
3124 	user_wire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
3125 	VM_MAP_RANGE_CHECK(map, start, end);
3126 	if (!vm_map_lookup_entry(map, start, &first_entry)) {
3127 		if (flags & VM_MAP_WIRE_HOLESOK)
3128 			first_entry = first_entry->next;
3129 		else
3130 			return (KERN_INVALID_ADDRESS);
3131 	}
3132 	last_timestamp = map->timestamp;
3133 	entry = first_entry;
3134 	while (entry->start < end) {
3135 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
3136 			/*
3137 			 * We have not yet clipped the entry.
3138 			 */
3139 			saved_start = (start >= entry->start) ? start :
3140 			    entry->start;
3141 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3142 			if (vm_map_unlock_and_wait(map, 0)) {
3143 				/*
3144 				 * Allow interruption of user wiring?
3145 				 */
3146 			}
3147 			vm_map_lock(map);
3148 			if (last_timestamp + 1 != map->timestamp) {
3149 				/*
3150 				 * Look again for the entry because the map was
3151 				 * modified while it was unlocked.
3152 				 * Specifically, the entry may have been
3153 				 * clipped, merged, or deleted.
3154 				 */
3155 				if (!vm_map_lookup_entry(map, saved_start,
3156 				    &tmp_entry)) {
3157 					if (flags & VM_MAP_WIRE_HOLESOK)
3158 						tmp_entry = tmp_entry->next;
3159 					else {
3160 						if (saved_start == start) {
3161 							/*
3162 							 * first_entry has been deleted.
3163 							 */
3164 							return (KERN_INVALID_ADDRESS);
3165 						}
3166 						end = saved_start;
3167 						rv = KERN_INVALID_ADDRESS;
3168 						goto done;
3169 					}
3170 				}
3171 				if (entry == first_entry)
3172 					first_entry = tmp_entry;
3173 				else
3174 					first_entry = NULL;
3175 				entry = tmp_entry;
3176 			}
3177 			last_timestamp = map->timestamp;
3178 			continue;
3179 		}
3180 		vm_map_clip_start(map, entry, start);
3181 		vm_map_clip_end(map, entry, end);
3182 		/*
3183 		 * Mark the entry in case the map lock is released.  (See
3184 		 * above.)
3185 		 */
3186 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
3187 		    entry->wiring_thread == NULL,
3188 		    ("owned map entry %p", entry));
3189 		entry->eflags |= MAP_ENTRY_IN_TRANSITION;
3190 		entry->wiring_thread = curthread;
3191 		if ((entry->protection & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0
3192 		    || (entry->protection & prot) != prot) {
3193 			entry->eflags |= MAP_ENTRY_WIRE_SKIPPED;
3194 			if ((flags & VM_MAP_WIRE_HOLESOK) == 0) {
3195 				end = entry->end;
3196 				rv = KERN_INVALID_ADDRESS;
3197 				goto done;
3198 			}
3199 			goto next_entry;
3200 		}
3201 		if (entry->wired_count == 0) {
3202 			entry->wired_count++;
3203 
3204 			npages = atop(entry->end - entry->start);
3205 			if (user_wire && !vm_map_wire_user_count_add(npages)) {
3206 				vm_map_wire_entry_failure(map, entry,
3207 				    entry->start);
3208 				end = entry->end;
3209 				rv = KERN_RESOURCE_SHORTAGE;
3210 				goto done;
3211 			}
3212 
3213 			/*
3214 			 * Release the map lock, relying on the in-transition
3215 			 * mark.  Mark the map busy for fork.
3216 			 */
3217 			saved_start = entry->start;
3218 			saved_end = entry->end;
3219 			vm_map_busy(map);
3220 			vm_map_unlock(map);
3221 
3222 			faddr = saved_start;
3223 			do {
3224 				/*
3225 				 * Simulate a fault to get the page and enter
3226 				 * it into the physical map.
3227 				 */
3228 				if ((rv = vm_fault(map, faddr,
3229 				    VM_PROT_NONE, VM_FAULT_WIRE, NULL)) !=
3230 				    KERN_SUCCESS)
3231 					break;
3232 			} while ((faddr += PAGE_SIZE) < saved_end);
3233 			vm_map_lock(map);
3234 			vm_map_unbusy(map);
3235 			if (last_timestamp + 1 != map->timestamp) {
3236 				/*
3237 				 * Look again for the entry because the map was
3238 				 * modified while it was unlocked.  The entry
3239 				 * may have been clipped, but NOT merged or
3240 				 * deleted.
3241 				 */
3242 				result = vm_map_lookup_entry(map, saved_start,
3243 				    &tmp_entry);
3244 				KASSERT(result, ("vm_map_wire: lookup failed"));
3245 				if (entry == first_entry)
3246 					first_entry = tmp_entry;
3247 				else
3248 					first_entry = NULL;
3249 				entry = tmp_entry;
3250 				while (entry->end < saved_end) {
3251 					/*
3252 					 * In case of failure, handle entries
3253 					 * that were not fully wired here;
3254 					 * fully wired entries are handled
3255 					 * later.
3256 					 */
3257 					if (rv != KERN_SUCCESS &&
3258 					    faddr < entry->end)
3259 						vm_map_wire_entry_failure(map,
3260 						    entry, faddr);
3261 					entry = entry->next;
3262 				}
3263 			}
3264 			last_timestamp = map->timestamp;
3265 			if (rv != KERN_SUCCESS) {
3266 				vm_map_wire_entry_failure(map, entry, faddr);
3267 				if (user_wire)
3268 					vm_map_wire_user_count_sub(npages);
3269 				end = entry->end;
3270 				goto done;
3271 			}
3272 		} else if (!user_wire ||
3273 			   (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3274 			entry->wired_count++;
3275 		}
3276 		/*
3277 		 * Check the map for holes in the specified region.
3278 		 * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
3279 		 */
3280 	next_entry:
3281 		if ((flags & VM_MAP_WIRE_HOLESOK) == 0 &&
3282 		    entry->end < end && entry->next->start > entry->end) {
3283 			end = entry->end;
3284 			rv = KERN_INVALID_ADDRESS;
3285 			goto done;
3286 		}
3287 		entry = entry->next;
3288 	}
3289 	rv = KERN_SUCCESS;
3290 done:
3291 	need_wakeup = FALSE;
3292 	if (first_entry == NULL) {
3293 		result = vm_map_lookup_entry(map, start, &first_entry);
3294 		if (!result && (flags & VM_MAP_WIRE_HOLESOK))
3295 			first_entry = first_entry->next;
3296 		else
3297 			KASSERT(result, ("vm_map_wire: lookup failed"));
3298 	}
3299 	for (entry = first_entry; entry->start < end; entry = entry->next) {
3300 		/*
3301 		 * If VM_MAP_WIRE_HOLESOK was specified, an empty
3302 		 * space in the unwired region could have been mapped
3303 		 * while the map lock was dropped for faulting in the
3304 		 * pages or draining MAP_ENTRY_IN_TRANSITION.
3305 		 * Moreover, another thread could be simultaneously
3306 		 * wiring this new mapping entry.  Detect these cases
3307 		 * and skip any entries marked as in transition not by us.
3308 		 */
3309 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
3310 		    entry->wiring_thread != curthread) {
3311 			KASSERT((flags & VM_MAP_WIRE_HOLESOK) != 0,
3312 			    ("vm_map_wire: !HOLESOK and new/changed entry"));
3313 			continue;
3314 		}
3315 
3316 		if ((entry->eflags & MAP_ENTRY_WIRE_SKIPPED) != 0)
3317 			goto next_entry_done;
3318 
3319 		if (rv == KERN_SUCCESS) {
3320 			if (user_wire)
3321 				entry->eflags |= MAP_ENTRY_USER_WIRED;
3322 		} else if (entry->wired_count == -1) {
3323 			/*
3324 			 * Wiring failed on this entry.  Thus, unwiring is
3325 			 * unnecessary.
3326 			 */
3327 			entry->wired_count = 0;
3328 		} else if (!user_wire ||
3329 		    (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3330 			/*
3331 			 * Undo the wiring.  Wiring succeeded on this entry
3332 			 * but failed on a later entry.
3333 			 */
3334 			if (entry->wired_count == 1) {
3335 				vm_map_entry_unwire(map, entry);
3336 				if (user_wire)
3337 					vm_map_wire_user_count_sub(
3338 					    atop(entry->end - entry->start));
3339 			} else
3340 				entry->wired_count--;
3341 		}
3342 	next_entry_done:
3343 		KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3344 		    ("vm_map_wire: in-transition flag missing %p", entry));
3345 		KASSERT(entry->wiring_thread == curthread,
3346 		    ("vm_map_wire: alien wire %p", entry));
3347 		entry->eflags &= ~(MAP_ENTRY_IN_TRANSITION |
3348 		    MAP_ENTRY_WIRE_SKIPPED);
3349 		entry->wiring_thread = NULL;
3350 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
3351 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
3352 			need_wakeup = TRUE;
3353 		}
3354 		vm_map_simplify_entry(map, entry);
3355 	}
3356 	if (need_wakeup)
3357 		vm_map_wakeup(map);
3358 	return (rv);
3359 }
3360 
3361 /*
3362  * vm_map_sync
3363  *
3364  * Push any dirty cached pages in the address range to their pager.
3365  * If syncio is TRUE, dirty pages are written synchronously.
3366  * If invalidate is TRUE, any cached pages are freed as well.
3367  *
3368  * If the size of the region from start to end is zero, we are
3369  * supposed to flush all modified pages within the region containing
3370  * start.  Unfortunately, a region can be split or coalesced with
3371  * neighboring regions, making it difficult to determine what the
3372  * original region was.  Therefore, we approximate this requirement by
3373  * flushing the current region containing start.
3374  *
3375  * Returns an error if any part of the specified range is not mapped.
3376  */
3377 int
vm_map_sync(vm_map_t map,vm_offset_t start,vm_offset_t end,boolean_t syncio,boolean_t invalidate)3378 vm_map_sync(
3379 	vm_map_t map,
3380 	vm_offset_t start,
3381 	vm_offset_t end,
3382 	boolean_t syncio,
3383 	boolean_t invalidate)
3384 {
3385 	vm_map_entry_t current;
3386 	vm_map_entry_t entry;
3387 	vm_size_t size;
3388 	vm_object_t object;
3389 	vm_ooffset_t offset;
3390 	unsigned int last_timestamp;
3391 	boolean_t failed;
3392 
3393 	vm_map_lock_read(map);
3394 	VM_MAP_RANGE_CHECK(map, start, end);
3395 	if (!vm_map_lookup_entry(map, start, &entry)) {
3396 		vm_map_unlock_read(map);
3397 		return (KERN_INVALID_ADDRESS);
3398 	} else if (start == end) {
3399 		start = entry->start;
3400 		end = entry->end;
3401 	}
3402 	/*
3403 	 * Make a first pass to check for user-wired memory and holes.
3404 	 */
3405 	for (current = entry; current->start < end; current = current->next) {
3406 		if (invalidate && (current->eflags & MAP_ENTRY_USER_WIRED)) {
3407 			vm_map_unlock_read(map);
3408 			return (KERN_INVALID_ARGUMENT);
3409 		}
3410 		if (end > current->end &&
3411 		    current->end != current->next->start) {
3412 			vm_map_unlock_read(map);
3413 			return (KERN_INVALID_ADDRESS);
3414 		}
3415 	}
3416 
3417 	if (invalidate)
3418 		pmap_remove(map->pmap, start, end);
3419 	failed = FALSE;
3420 
3421 	/*
3422 	 * Make a second pass, cleaning/uncaching pages from the indicated
3423 	 * objects as we go.
3424 	 */
3425 	for (current = entry; current->start < end;) {
3426 		offset = current->offset + (start - current->start);
3427 		size = (end <= current->end ? end : current->end) - start;
3428 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
3429 			vm_map_t smap;
3430 			vm_map_entry_t tentry;
3431 			vm_size_t tsize;
3432 
3433 			smap = current->object.sub_map;
3434 			vm_map_lock_read(smap);
3435 			(void) vm_map_lookup_entry(smap, offset, &tentry);
3436 			tsize = tentry->end - offset;
3437 			if (tsize < size)
3438 				size = tsize;
3439 			object = tentry->object.vm_object;
3440 			offset = tentry->offset + (offset - tentry->start);
3441 			vm_map_unlock_read(smap);
3442 		} else {
3443 			object = current->object.vm_object;
3444 		}
3445 		vm_object_reference(object);
3446 		last_timestamp = map->timestamp;
3447 		vm_map_unlock_read(map);
3448 		if (!vm_object_sync(object, offset, size, syncio, invalidate))
3449 			failed = TRUE;
3450 		start += size;
3451 		vm_object_deallocate(object);
3452 		vm_map_lock_read(map);
3453 		if (last_timestamp == map->timestamp ||
3454 		    !vm_map_lookup_entry(map, start, &current))
3455 			current = current->next;
3456 	}
3457 
3458 	vm_map_unlock_read(map);
3459 	return (failed ? KERN_FAILURE : KERN_SUCCESS);
3460 }
3461 
3462 /*
3463  *	vm_map_entry_unwire:	[ internal use only ]
3464  *
3465  *	Make the region specified by this entry pageable.
3466  *
3467  *	The map in question should be locked.
3468  *	[This is the reason for this routine's existence.]
3469  */
3470 static void
vm_map_entry_unwire(vm_map_t map,vm_map_entry_t entry)3471 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
3472 {
3473 	vm_size_t size;
3474 
3475 	VM_MAP_ASSERT_LOCKED(map);
3476 	KASSERT(entry->wired_count > 0,
3477 	    ("vm_map_entry_unwire: entry %p isn't wired", entry));
3478 
3479 	size = entry->end - entry->start;
3480 	if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0)
3481 		vm_map_wire_user_count_sub(atop(size));
3482 	pmap_unwire(map->pmap, entry->start, entry->end);
3483 	vm_object_unwire(entry->object.vm_object, entry->offset, size,
3484 	    PQ_ACTIVE);
3485 	entry->wired_count = 0;
3486 }
3487 
3488 static void
vm_map_entry_deallocate(vm_map_entry_t entry,boolean_t system_map)3489 vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map)
3490 {
3491 
3492 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
3493 		vm_object_deallocate(entry->object.vm_object);
3494 	uma_zfree(system_map ? kmapentzone : mapentzone, entry);
3495 }
3496 
3497 /*
3498  *	vm_map_entry_delete:	[ internal use only ]
3499  *
3500  *	Deallocate the given entry from the target map.
3501  */
3502 static void
vm_map_entry_delete(vm_map_t map,vm_map_entry_t entry)3503 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
3504 {
3505 	vm_object_t object;
3506 	vm_pindex_t offidxstart, offidxend, count, size1;
3507 	vm_size_t size;
3508 
3509 	vm_map_entry_unlink(map, entry, UNLINK_MERGE_NONE);
3510 	object = entry->object.vm_object;
3511 
3512 	if ((entry->eflags & MAP_ENTRY_GUARD) != 0) {
3513 		MPASS(entry->cred == NULL);
3514 		MPASS((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0);
3515 		MPASS(object == NULL);
3516 		vm_map_entry_deallocate(entry, map->system_map);
3517 		return;
3518 	}
3519 
3520 	size = entry->end - entry->start;
3521 	map->size -= size;
3522 
3523 	if (entry->cred != NULL) {
3524 		swap_release_by_cred(size, entry->cred);
3525 		crfree(entry->cred);
3526 	}
3527 
3528 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
3529 	    (object != NULL)) {
3530 		KASSERT(entry->cred == NULL || object->cred == NULL ||
3531 		    (entry->eflags & MAP_ENTRY_NEEDS_COPY),
3532 		    ("OVERCOMMIT vm_map_entry_delete: both cred %p", entry));
3533 		count = atop(size);
3534 		offidxstart = OFF_TO_IDX(entry->offset);
3535 		offidxend = offidxstart + count;
3536 		VM_OBJECT_WLOCK(object);
3537 		if (object->ref_count != 1 && ((object->flags & (OBJ_NOSPLIT |
3538 		    OBJ_ONEMAPPING)) == OBJ_ONEMAPPING ||
3539 		    object == kernel_object)) {
3540 			vm_object_collapse(object);
3541 
3542 			/*
3543 			 * The option OBJPR_NOTMAPPED can be passed here
3544 			 * because vm_map_delete() already performed
3545 			 * pmap_remove() on the only mapping to this range
3546 			 * of pages.
3547 			 */
3548 			vm_object_page_remove(object, offidxstart, offidxend,
3549 			    OBJPR_NOTMAPPED);
3550 			if (object->type == OBJT_SWAP)
3551 				swap_pager_freespace(object, offidxstart,
3552 				    count);
3553 			if (offidxend >= object->size &&
3554 			    offidxstart < object->size) {
3555 				size1 = object->size;
3556 				object->size = offidxstart;
3557 				if (object->cred != NULL) {
3558 					size1 -= object->size;
3559 					KASSERT(object->charge >= ptoa(size1),
3560 					    ("object %p charge < 0", object));
3561 					swap_release_by_cred(ptoa(size1),
3562 					    object->cred);
3563 					object->charge -= ptoa(size1);
3564 				}
3565 			}
3566 		}
3567 		VM_OBJECT_WUNLOCK(object);
3568 	} else
3569 		entry->object.vm_object = NULL;
3570 	if (map->system_map)
3571 		vm_map_entry_deallocate(entry, TRUE);
3572 	else {
3573 		entry->next = curthread->td_map_def_user;
3574 		curthread->td_map_def_user = entry;
3575 	}
3576 }
3577 
3578 /*
3579  *	vm_map_delete:	[ internal use only ]
3580  *
3581  *	Deallocates the given address range from the target
3582  *	map.
3583  */
3584 int
vm_map_delete(vm_map_t map,vm_offset_t start,vm_offset_t end)3585 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
3586 {
3587 	vm_map_entry_t entry;
3588 	vm_map_entry_t first_entry;
3589 
3590 	VM_MAP_ASSERT_LOCKED(map);
3591 	if (start == end)
3592 		return (KERN_SUCCESS);
3593 
3594 	/*
3595 	 * Find the start of the region, and clip it
3596 	 */
3597 	if (!vm_map_lookup_entry(map, start, &first_entry))
3598 		entry = first_entry->next;
3599 	else {
3600 		entry = first_entry;
3601 		vm_map_clip_start(map, entry, start);
3602 	}
3603 
3604 	/*
3605 	 * Step through all entries in this region
3606 	 */
3607 	while (entry->start < end) {
3608 		vm_map_entry_t next;
3609 
3610 		/*
3611 		 * Wait for wiring or unwiring of an entry to complete.
3612 		 * Also wait for any system wirings to disappear on
3613 		 * user maps.
3614 		 */
3615 		if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
3616 		    (vm_map_pmap(map) != kernel_pmap &&
3617 		    vm_map_entry_system_wired_count(entry) != 0)) {
3618 			unsigned int last_timestamp;
3619 			vm_offset_t saved_start;
3620 			vm_map_entry_t tmp_entry;
3621 
3622 			saved_start = entry->start;
3623 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3624 			last_timestamp = map->timestamp;
3625 			(void) vm_map_unlock_and_wait(map, 0);
3626 			vm_map_lock(map);
3627 			if (last_timestamp + 1 != map->timestamp) {
3628 				/*
3629 				 * Look again for the entry because the map was
3630 				 * modified while it was unlocked.
3631 				 * Specifically, the entry may have been
3632 				 * clipped, merged, or deleted.
3633 				 */
3634 				if (!vm_map_lookup_entry(map, saved_start,
3635 							 &tmp_entry))
3636 					entry = tmp_entry->next;
3637 				else {
3638 					entry = tmp_entry;
3639 					vm_map_clip_start(map, entry,
3640 							  saved_start);
3641 				}
3642 			}
3643 			continue;
3644 		}
3645 		vm_map_clip_end(map, entry, end);
3646 
3647 		next = entry->next;
3648 
3649 		/*
3650 		 * Unwire before removing addresses from the pmap; otherwise,
3651 		 * unwiring will put the entries back in the pmap.
3652 		 */
3653 		if (entry->wired_count != 0)
3654 			vm_map_entry_unwire(map, entry);
3655 
3656 		/*
3657 		 * Remove mappings for the pages, but only if the
3658 		 * mappings could exist.  For instance, it does not
3659 		 * make sense to call pmap_remove() for guard entries.
3660 		 */
3661 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 ||
3662 		    entry->object.vm_object != NULL)
3663 			pmap_remove(map->pmap, entry->start, entry->end);
3664 
3665 		if (entry->end == map->anon_loc)
3666 			map->anon_loc = entry->start;
3667 
3668 		/*
3669 		 * Delete the entry only after removing all pmap
3670 		 * entries pointing to its pages.  (Otherwise, its
3671 		 * page frames may be reallocated, and any modify bits
3672 		 * will be set in the wrong object!)
3673 		 */
3674 		vm_map_entry_delete(map, entry);
3675 		entry = next;
3676 	}
3677 	return (KERN_SUCCESS);
3678 }
3679 
3680 /*
3681  *	vm_map_remove:
3682  *
3683  *	Remove the given address range from the target map.
3684  *	This is the exported form of vm_map_delete.
3685  */
3686 int
vm_map_remove(vm_map_t map,vm_offset_t start,vm_offset_t end)3687 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
3688 {
3689 	int result;
3690 
3691 	vm_map_lock(map);
3692 	VM_MAP_RANGE_CHECK(map, start, end);
3693 	result = vm_map_delete(map, start, end);
3694 	vm_map_unlock(map);
3695 	return (result);
3696 }
3697 
3698 /*
3699  *	vm_map_check_protection:
3700  *
3701  *	Assert that the target map allows the specified privilege on the
3702  *	entire address region given.  The entire region must be allocated.
3703  *
3704  *	WARNING!  This code does not and should not check whether the
3705  *	contents of the region is accessible.  For example a smaller file
3706  *	might be mapped into a larger address space.
3707  *
3708  *	NOTE!  This code is also called by munmap().
3709  *
3710  *	The map must be locked.  A read lock is sufficient.
3711  */
3712 boolean_t
vm_map_check_protection(vm_map_t map,vm_offset_t start,vm_offset_t end,vm_prot_t protection)3713 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
3714 			vm_prot_t protection)
3715 {
3716 	vm_map_entry_t entry;
3717 	vm_map_entry_t tmp_entry;
3718 
3719 	if (!vm_map_lookup_entry(map, start, &tmp_entry))
3720 		return (FALSE);
3721 	entry = tmp_entry;
3722 
3723 	while (start < end) {
3724 		/*
3725 		 * No holes allowed!
3726 		 */
3727 		if (start < entry->start)
3728 			return (FALSE);
3729 		/*
3730 		 * Check protection associated with entry.
3731 		 */
3732 		if ((entry->protection & protection) != protection)
3733 			return (FALSE);
3734 		/* go to next entry */
3735 		start = entry->end;
3736 		entry = entry->next;
3737 	}
3738 	return (TRUE);
3739 }
3740 
3741 /*
3742  *	vm_map_copy_entry:
3743  *
3744  *	Copies the contents of the source entry to the destination
3745  *	entry.  The entries *must* be aligned properly.
3746  */
3747 static void
vm_map_copy_entry(vm_map_t src_map,vm_map_t dst_map,vm_map_entry_t src_entry,vm_map_entry_t dst_entry,vm_ooffset_t * fork_charge)3748 vm_map_copy_entry(
3749 	vm_map_t src_map,
3750 	vm_map_t dst_map,
3751 	vm_map_entry_t src_entry,
3752 	vm_map_entry_t dst_entry,
3753 	vm_ooffset_t *fork_charge)
3754 {
3755 	vm_object_t src_object;
3756 	vm_map_entry_t fake_entry;
3757 	vm_offset_t size;
3758 	struct ucred *cred;
3759 	int charged;
3760 
3761 	VM_MAP_ASSERT_LOCKED(dst_map);
3762 
3763 	if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
3764 		return;
3765 
3766 	if (src_entry->wired_count == 0 ||
3767 	    (src_entry->protection & VM_PROT_WRITE) == 0) {
3768 		/*
3769 		 * If the source entry is marked needs_copy, it is already
3770 		 * write-protected.
3771 		 */
3772 		if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0 &&
3773 		    (src_entry->protection & VM_PROT_WRITE) != 0) {
3774 			pmap_protect(src_map->pmap,
3775 			    src_entry->start,
3776 			    src_entry->end,
3777 			    src_entry->protection & ~VM_PROT_WRITE);
3778 		}
3779 
3780 		/*
3781 		 * Make a copy of the object.
3782 		 */
3783 		size = src_entry->end - src_entry->start;
3784 		if ((src_object = src_entry->object.vm_object) != NULL) {
3785 			VM_OBJECT_WLOCK(src_object);
3786 			charged = ENTRY_CHARGED(src_entry);
3787 			if (src_object->handle == NULL &&
3788 			    (src_object->type == OBJT_DEFAULT ||
3789 			    src_object->type == OBJT_SWAP)) {
3790 				vm_object_collapse(src_object);
3791 				if ((src_object->flags & (OBJ_NOSPLIT |
3792 				    OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
3793 					vm_object_split(src_entry);
3794 					src_object =
3795 					    src_entry->object.vm_object;
3796 				}
3797 			}
3798 			vm_object_reference_locked(src_object);
3799 			vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
3800 			if (src_entry->cred != NULL &&
3801 			    !(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
3802 				KASSERT(src_object->cred == NULL,
3803 				    ("OVERCOMMIT: vm_map_copy_entry: cred %p",
3804 				     src_object));
3805 				src_object->cred = src_entry->cred;
3806 				src_object->charge = size;
3807 			}
3808 			VM_OBJECT_WUNLOCK(src_object);
3809 			dst_entry->object.vm_object = src_object;
3810 			if (charged) {
3811 				cred = curthread->td_ucred;
3812 				crhold(cred);
3813 				dst_entry->cred = cred;
3814 				*fork_charge += size;
3815 				if (!(src_entry->eflags &
3816 				      MAP_ENTRY_NEEDS_COPY)) {
3817 					crhold(cred);
3818 					src_entry->cred = cred;
3819 					*fork_charge += size;
3820 				}
3821 			}
3822 			src_entry->eflags |= MAP_ENTRY_COW |
3823 			    MAP_ENTRY_NEEDS_COPY;
3824 			dst_entry->eflags |= MAP_ENTRY_COW |
3825 			    MAP_ENTRY_NEEDS_COPY;
3826 			dst_entry->offset = src_entry->offset;
3827 			if (src_entry->eflags & MAP_ENTRY_WRITECNT) {
3828 				/*
3829 				 * MAP_ENTRY_WRITECNT cannot
3830 				 * indicate write reference from
3831 				 * src_entry, since the entry is
3832 				 * marked as needs copy.  Allocate a
3833 				 * fake entry that is used to
3834 				 * decrement object->un_pager writecount
3835 				 * at the appropriate time.  Attach
3836 				 * fake_entry to the deferred list.
3837 				 */
3838 				fake_entry = vm_map_entry_create(dst_map);
3839 				fake_entry->eflags = MAP_ENTRY_WRITECNT;
3840 				src_entry->eflags &= ~MAP_ENTRY_WRITECNT;
3841 				vm_object_reference(src_object);
3842 				fake_entry->object.vm_object = src_object;
3843 				fake_entry->start = src_entry->start;
3844 				fake_entry->end = src_entry->end;
3845 				fake_entry->next = curthread->td_map_def_user;
3846 				curthread->td_map_def_user = fake_entry;
3847 			}
3848 
3849 			pmap_copy(dst_map->pmap, src_map->pmap,
3850 			    dst_entry->start, dst_entry->end - dst_entry->start,
3851 			    src_entry->start);
3852 		} else {
3853 			dst_entry->object.vm_object = NULL;
3854 			dst_entry->offset = 0;
3855 			if (src_entry->cred != NULL) {
3856 				dst_entry->cred = curthread->td_ucred;
3857 				crhold(dst_entry->cred);
3858 				*fork_charge += size;
3859 			}
3860 		}
3861 	} else {
3862 		/*
3863 		 * We don't want to make writeable wired pages copy-on-write.
3864 		 * Immediately copy these pages into the new map by simulating
3865 		 * page faults.  The new pages are pageable.
3866 		 */
3867 		vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry,
3868 		    fork_charge);
3869 	}
3870 }
3871 
3872 /*
3873  * vmspace_map_entry_forked:
3874  * Update the newly-forked vmspace each time a map entry is inherited
3875  * or copied.  The values for vm_dsize and vm_tsize are approximate
3876  * (and mostly-obsolete ideas in the face of mmap(2) et al.)
3877  */
3878 static void
vmspace_map_entry_forked(const struct vmspace * vm1,struct vmspace * vm2,vm_map_entry_t entry)3879 vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
3880     vm_map_entry_t entry)
3881 {
3882 	vm_size_t entrysize;
3883 	vm_offset_t newend;
3884 
3885 	if ((entry->eflags & MAP_ENTRY_GUARD) != 0)
3886 		return;
3887 	entrysize = entry->end - entry->start;
3888 	vm2->vm_map.size += entrysize;
3889 	if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
3890 		vm2->vm_ssize += btoc(entrysize);
3891 	} else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
3892 	    entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
3893 		newend = MIN(entry->end,
3894 		    (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
3895 		vm2->vm_dsize += btoc(newend - entry->start);
3896 	} else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
3897 	    entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
3898 		newend = MIN(entry->end,
3899 		    (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
3900 		vm2->vm_tsize += btoc(newend - entry->start);
3901 	}
3902 }
3903 
3904 /*
3905  * vmspace_fork:
3906  * Create a new process vmspace structure and vm_map
3907  * based on those of an existing process.  The new map
3908  * is based on the old map, according to the inheritance
3909  * values on the regions in that map.
3910  *
3911  * XXX It might be worth coalescing the entries added to the new vmspace.
3912  *
3913  * The source map must not be locked.
3914  */
3915 struct vmspace *
vmspace_fork(struct vmspace * vm1,vm_ooffset_t * fork_charge)3916 vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
3917 {
3918 	struct vmspace *vm2;
3919 	vm_map_t new_map, old_map;
3920 	vm_map_entry_t new_entry, old_entry;
3921 	vm_object_t object;
3922 	int error, locked;
3923 	vm_inherit_t inh;
3924 
3925 	old_map = &vm1->vm_map;
3926 	/* Copy immutable fields of vm1 to vm2. */
3927 	vm2 = vmspace_alloc(vm_map_min(old_map), vm_map_max(old_map),
3928 	    pmap_pinit);
3929 	if (vm2 == NULL)
3930 		return (NULL);
3931 
3932 	vm2->vm_taddr = vm1->vm_taddr;
3933 	vm2->vm_daddr = vm1->vm_daddr;
3934 	vm2->vm_maxsaddr = vm1->vm_maxsaddr;
3935 	vm_map_lock(old_map);
3936 	if (old_map->busy)
3937 		vm_map_wait_busy(old_map);
3938 	new_map = &vm2->vm_map;
3939 	locked = vm_map_trylock(new_map); /* trylock to silence WITNESS */
3940 	KASSERT(locked, ("vmspace_fork: lock failed"));
3941 
3942 	error = pmap_vmspace_copy(new_map->pmap, old_map->pmap);
3943 	if (error != 0) {
3944 		sx_xunlock(&old_map->lock);
3945 		sx_xunlock(&new_map->lock);
3946 		vm_map_process_deferred();
3947 		vmspace_free(vm2);
3948 		return (NULL);
3949 	}
3950 
3951 	new_map->anon_loc = old_map->anon_loc;
3952 	new_map->flags |= old_map->flags & (MAP_ASLR | MAP_ASLR_IGNSTART);
3953 
3954 	old_entry = old_map->header.next;
3955 
3956 	while (old_entry != &old_map->header) {
3957 		if (old_entry->eflags & MAP_ENTRY_IS_SUB_MAP)
3958 			panic("vm_map_fork: encountered a submap");
3959 
3960 		inh = old_entry->inheritance;
3961 		if ((old_entry->eflags & MAP_ENTRY_GUARD) != 0 &&
3962 		    inh != VM_INHERIT_NONE)
3963 			inh = VM_INHERIT_COPY;
3964 
3965 		switch (inh) {
3966 		case VM_INHERIT_NONE:
3967 			break;
3968 
3969 		case VM_INHERIT_SHARE:
3970 			/*
3971 			 * Clone the entry, creating the shared object if necessary.
3972 			 */
3973 			object = old_entry->object.vm_object;
3974 			if (object == NULL) {
3975 				object = vm_object_allocate(OBJT_DEFAULT,
3976 					atop(old_entry->end - old_entry->start));
3977 				old_entry->object.vm_object = object;
3978 				old_entry->offset = 0;
3979 				if (old_entry->cred != NULL) {
3980 					object->cred = old_entry->cred;
3981 					object->charge = old_entry->end -
3982 					    old_entry->start;
3983 					old_entry->cred = NULL;
3984 				}
3985 			}
3986 
3987 			/*
3988 			 * Add the reference before calling vm_object_shadow
3989 			 * to insure that a shadow object is created.
3990 			 */
3991 			vm_object_reference(object);
3992 			if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3993 				vm_object_shadow(&old_entry->object.vm_object,
3994 				    &old_entry->offset,
3995 				    old_entry->end - old_entry->start);
3996 				old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
3997 				/* Transfer the second reference too. */
3998 				vm_object_reference(
3999 				    old_entry->object.vm_object);
4000 
4001 				/*
4002 				 * As in vm_map_simplify_entry(), the
4003 				 * vnode lock will not be acquired in
4004 				 * this call to vm_object_deallocate().
4005 				 */
4006 				vm_object_deallocate(object);
4007 				object = old_entry->object.vm_object;
4008 			}
4009 			VM_OBJECT_WLOCK(object);
4010 			vm_object_clear_flag(object, OBJ_ONEMAPPING);
4011 			if (old_entry->cred != NULL) {
4012 				KASSERT(object->cred == NULL, ("vmspace_fork both cred"));
4013 				object->cred = old_entry->cred;
4014 				object->charge = old_entry->end - old_entry->start;
4015 				old_entry->cred = NULL;
4016 			}
4017 
4018 			/*
4019 			 * Assert the correct state of the vnode
4020 			 * v_writecount while the object is locked, to
4021 			 * not relock it later for the assertion
4022 			 * correctness.
4023 			 */
4024 			if (old_entry->eflags & MAP_ENTRY_WRITECNT &&
4025 			    object->type == OBJT_VNODE) {
4026 				KASSERT(((struct vnode *)object->handle)->
4027 				    v_writecount > 0,
4028 				    ("vmspace_fork: v_writecount %p", object));
4029 				KASSERT(object->un_pager.vnp.writemappings > 0,
4030 				    ("vmspace_fork: vnp.writecount %p",
4031 				    object));
4032 			}
4033 			VM_OBJECT_WUNLOCK(object);
4034 
4035 			/*
4036 			 * Clone the entry, referencing the shared object.
4037 			 */
4038 			new_entry = vm_map_entry_create(new_map);
4039 			*new_entry = *old_entry;
4040 			new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
4041 			    MAP_ENTRY_IN_TRANSITION);
4042 			new_entry->wiring_thread = NULL;
4043 			new_entry->wired_count = 0;
4044 			if (new_entry->eflags & MAP_ENTRY_WRITECNT) {
4045 				vm_pager_update_writecount(object,
4046 				    new_entry->start, new_entry->end);
4047 			}
4048 			vm_map_entry_set_vnode_text(new_entry, true);
4049 
4050 			/*
4051 			 * Insert the entry into the new map -- we know we're
4052 			 * inserting at the end of the new map.
4053 			 */
4054 			vm_map_entry_link(new_map, new_entry);
4055 			vmspace_map_entry_forked(vm1, vm2, new_entry);
4056 
4057 			/*
4058 			 * Update the physical map
4059 			 */
4060 			pmap_copy(new_map->pmap, old_map->pmap,
4061 			    new_entry->start,
4062 			    (old_entry->end - old_entry->start),
4063 			    old_entry->start);
4064 			break;
4065 
4066 		case VM_INHERIT_COPY:
4067 			/*
4068 			 * Clone the entry and link into the map.
4069 			 */
4070 			new_entry = vm_map_entry_create(new_map);
4071 			*new_entry = *old_entry;
4072 			/*
4073 			 * Copied entry is COW over the old object.
4074 			 */
4075 			new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
4076 			    MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_WRITECNT);
4077 			new_entry->wiring_thread = NULL;
4078 			new_entry->wired_count = 0;
4079 			new_entry->object.vm_object = NULL;
4080 			new_entry->cred = NULL;
4081 			vm_map_entry_link(new_map, new_entry);
4082 			vmspace_map_entry_forked(vm1, vm2, new_entry);
4083 			vm_map_copy_entry(old_map, new_map, old_entry,
4084 			    new_entry, fork_charge);
4085 			vm_map_entry_set_vnode_text(new_entry, true);
4086 			break;
4087 
4088 		case VM_INHERIT_ZERO:
4089 			/*
4090 			 * Create a new anonymous mapping entry modelled from
4091 			 * the old one.
4092 			 */
4093 			new_entry = vm_map_entry_create(new_map);
4094 			memset(new_entry, 0, sizeof(*new_entry));
4095 
4096 			new_entry->start = old_entry->start;
4097 			new_entry->end = old_entry->end;
4098 			new_entry->eflags = old_entry->eflags &
4099 			    ~(MAP_ENTRY_USER_WIRED | MAP_ENTRY_IN_TRANSITION |
4100 			    MAP_ENTRY_WRITECNT | MAP_ENTRY_VN_EXEC);
4101 			new_entry->protection = old_entry->protection;
4102 			new_entry->max_protection = old_entry->max_protection;
4103 			new_entry->inheritance = VM_INHERIT_ZERO;
4104 
4105 			vm_map_entry_link(new_map, new_entry);
4106 			vmspace_map_entry_forked(vm1, vm2, new_entry);
4107 
4108 			new_entry->cred = curthread->td_ucred;
4109 			crhold(new_entry->cred);
4110 			*fork_charge += (new_entry->end - new_entry->start);
4111 
4112 			break;
4113 		}
4114 		old_entry = old_entry->next;
4115 	}
4116 	/*
4117 	 * Use inlined vm_map_unlock() to postpone handling the deferred
4118 	 * map entries, which cannot be done until both old_map and
4119 	 * new_map locks are released.
4120 	 */
4121 	sx_xunlock(&old_map->lock);
4122 	sx_xunlock(&new_map->lock);
4123 	vm_map_process_deferred();
4124 
4125 	return (vm2);
4126 }
4127 
4128 /*
4129  * Create a process's stack for exec_new_vmspace().  This function is never
4130  * asked to wire the newly created stack.
4131  */
4132 int
vm_map_stack(vm_map_t map,vm_offset_t addrbos,vm_size_t max_ssize,vm_prot_t prot,vm_prot_t max,int cow)4133 vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4134     vm_prot_t prot, vm_prot_t max, int cow)
4135 {
4136 	vm_size_t growsize, init_ssize;
4137 	rlim_t vmemlim;
4138 	int rv;
4139 
4140 	MPASS((map->flags & MAP_WIREFUTURE) == 0);
4141 	growsize = sgrowsiz;
4142 	init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
4143 	vm_map_lock(map);
4144 	vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4145 	/* If we would blow our VMEM resource limit, no go */
4146 	if (map->size + init_ssize > vmemlim) {
4147 		rv = KERN_NO_SPACE;
4148 		goto out;
4149 	}
4150 	rv = vm_map_stack_locked(map, addrbos, max_ssize, growsize, prot,
4151 	    max, cow);
4152 out:
4153 	vm_map_unlock(map);
4154 	return (rv);
4155 }
4156 
4157 static int stack_guard_page = 1;
4158 SYSCTL_INT(_security_bsd, OID_AUTO, stack_guard_page, CTLFLAG_RWTUN,
4159     &stack_guard_page, 0,
4160     "Specifies the number of guard pages for a stack that grows");
4161 
4162 static int
vm_map_stack_locked(vm_map_t map,vm_offset_t addrbos,vm_size_t max_ssize,vm_size_t growsize,vm_prot_t prot,vm_prot_t max,int cow)4163 vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4164     vm_size_t growsize, vm_prot_t prot, vm_prot_t max, int cow)
4165 {
4166 	vm_map_entry_t new_entry, prev_entry;
4167 	vm_offset_t bot, gap_bot, gap_top, top;
4168 	vm_size_t init_ssize, sgp;
4169 	int orient, rv;
4170 
4171 	/*
4172 	 * The stack orientation is piggybacked with the cow argument.
4173 	 * Extract it into orient and mask the cow argument so that we
4174 	 * don't pass it around further.
4175 	 */
4176 	orient = cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP);
4177 	KASSERT(orient != 0, ("No stack grow direction"));
4178 	KASSERT(orient != (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP),
4179 	    ("bi-dir stack"));
4180 
4181 	if (max_ssize == 0 ||
4182 	    !vm_map_range_valid(map, addrbos, addrbos + max_ssize))
4183 		return (KERN_INVALID_ADDRESS);
4184 	sgp = ((curproc->p_flag2 & P2_STKGAP_DISABLE) != 0 ||
4185 	    (curproc->p_fctl0 & NT_FREEBSD_FCTL_STKGAP_DISABLE) != 0) ? 0 :
4186 	    (vm_size_t)stack_guard_page * PAGE_SIZE;
4187 	if (sgp >= max_ssize)
4188 		return (KERN_INVALID_ARGUMENT);
4189 
4190 	init_ssize = growsize;
4191 	if (max_ssize < init_ssize + sgp)
4192 		init_ssize = max_ssize - sgp;
4193 
4194 	/* If addr is already mapped, no go */
4195 	if (vm_map_lookup_entry(map, addrbos, &prev_entry))
4196 		return (KERN_NO_SPACE);
4197 
4198 	/*
4199 	 * If we can't accommodate max_ssize in the current mapping, no go.
4200 	 */
4201 	if (prev_entry->next->start < addrbos + max_ssize)
4202 		return (KERN_NO_SPACE);
4203 
4204 	/*
4205 	 * We initially map a stack of only init_ssize.  We will grow as
4206 	 * needed later.  Depending on the orientation of the stack (i.e.
4207 	 * the grow direction) we either map at the top of the range, the
4208 	 * bottom of the range or in the middle.
4209 	 *
4210 	 * Note: we would normally expect prot and max to be VM_PROT_ALL,
4211 	 * and cow to be 0.  Possibly we should eliminate these as input
4212 	 * parameters, and just pass these values here in the insert call.
4213 	 */
4214 	if (orient == MAP_STACK_GROWS_DOWN) {
4215 		bot = addrbos + max_ssize - init_ssize;
4216 		top = bot + init_ssize;
4217 		gap_bot = addrbos;
4218 		gap_top = bot;
4219 	} else /* if (orient == MAP_STACK_GROWS_UP) */ {
4220 		bot = addrbos;
4221 		top = bot + init_ssize;
4222 		gap_bot = top;
4223 		gap_top = addrbos + max_ssize;
4224 	}
4225 	rv = vm_map_insert(map, NULL, 0, bot, top, prot, max, cow);
4226 	if (rv != KERN_SUCCESS)
4227 		return (rv);
4228 	new_entry = prev_entry->next;
4229 	KASSERT(new_entry->end == top || new_entry->start == bot,
4230 	    ("Bad entry start/end for new stack entry"));
4231 	KASSERT((orient & MAP_STACK_GROWS_DOWN) == 0 ||
4232 	    (new_entry->eflags & MAP_ENTRY_GROWS_DOWN) != 0,
4233 	    ("new entry lacks MAP_ENTRY_GROWS_DOWN"));
4234 	KASSERT((orient & MAP_STACK_GROWS_UP) == 0 ||
4235 	    (new_entry->eflags & MAP_ENTRY_GROWS_UP) != 0,
4236 	    ("new entry lacks MAP_ENTRY_GROWS_UP"));
4237 	if (gap_bot == gap_top)
4238 		return (KERN_SUCCESS);
4239 	rv = vm_map_insert(map, NULL, 0, gap_bot, gap_top, VM_PROT_NONE,
4240 	    VM_PROT_NONE, MAP_CREATE_GUARD | (orient == MAP_STACK_GROWS_DOWN ?
4241 	    MAP_CREATE_STACK_GAP_DN : MAP_CREATE_STACK_GAP_UP));
4242 	if (rv == KERN_SUCCESS) {
4243 		/*
4244 		 * Gap can never successfully handle a fault, so
4245 		 * read-ahead logic is never used for it.  Re-use
4246 		 * next_read of the gap entry to store
4247 		 * stack_guard_page for vm_map_growstack().
4248 		 */
4249 		if (orient == MAP_STACK_GROWS_DOWN)
4250 			new_entry->prev->next_read = sgp;
4251 		else
4252 			new_entry->next->next_read = sgp;
4253 	} else {
4254 		(void)vm_map_delete(map, bot, top);
4255 	}
4256 	return (rv);
4257 }
4258 
4259 /*
4260  * Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if we
4261  * successfully grow the stack.
4262  */
4263 static int
vm_map_growstack(vm_map_t map,vm_offset_t addr,vm_map_entry_t gap_entry)4264 vm_map_growstack(vm_map_t map, vm_offset_t addr, vm_map_entry_t gap_entry)
4265 {
4266 	vm_map_entry_t stack_entry;
4267 	struct proc *p;
4268 	struct vmspace *vm;
4269 	struct ucred *cred;
4270 	vm_offset_t gap_end, gap_start, grow_start;
4271 	size_t grow_amount, guard, max_grow;
4272 	rlim_t lmemlim, stacklim, vmemlim;
4273 	int rv, rv1;
4274 	bool gap_deleted, grow_down, is_procstack;
4275 #ifdef notyet
4276 	uint64_t limit;
4277 #endif
4278 #ifdef RACCT
4279 	int error;
4280 #endif
4281 
4282 	p = curproc;
4283 	vm = p->p_vmspace;
4284 
4285 	/*
4286 	 * Disallow stack growth when the access is performed by a
4287 	 * debugger or AIO daemon.  The reason is that the wrong
4288 	 * resource limits are applied.
4289 	 */
4290 	if (p != initproc && (map != &p->p_vmspace->vm_map ||
4291 	    p->p_textvp == NULL))
4292 		return (KERN_FAILURE);
4293 
4294 	MPASS(!map->system_map);
4295 
4296 	lmemlim = lim_cur(curthread, RLIMIT_MEMLOCK);
4297 	stacklim = lim_cur(curthread, RLIMIT_STACK);
4298 	vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4299 retry:
4300 	/* If addr is not in a hole for a stack grow area, no need to grow. */
4301 	if (gap_entry == NULL && !vm_map_lookup_entry(map, addr, &gap_entry))
4302 		return (KERN_FAILURE);
4303 	if ((gap_entry->eflags & MAP_ENTRY_GUARD) == 0)
4304 		return (KERN_SUCCESS);
4305 	if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_DN) != 0) {
4306 		stack_entry = gap_entry->next;
4307 		if ((stack_entry->eflags & MAP_ENTRY_GROWS_DOWN) == 0 ||
4308 		    stack_entry->start != gap_entry->end)
4309 			return (KERN_FAILURE);
4310 		grow_amount = round_page(stack_entry->start - addr);
4311 		grow_down = true;
4312 	} else if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_UP) != 0) {
4313 		stack_entry = gap_entry->prev;
4314 		if ((stack_entry->eflags & MAP_ENTRY_GROWS_UP) == 0 ||
4315 		    stack_entry->end != gap_entry->start)
4316 			return (KERN_FAILURE);
4317 		grow_amount = round_page(addr + 1 - stack_entry->end);
4318 		grow_down = false;
4319 	} else {
4320 		return (KERN_FAILURE);
4321 	}
4322 	guard = ((curproc->p_flag2 & P2_STKGAP_DISABLE) != 0 ||
4323 	    (curproc->p_fctl0 & NT_FREEBSD_FCTL_STKGAP_DISABLE) != 0) ? 0 :
4324 	    gap_entry->next_read;
4325 	max_grow = gap_entry->end - gap_entry->start;
4326 	if (guard > max_grow)
4327 		return (KERN_NO_SPACE);
4328 	max_grow -= guard;
4329 	if (grow_amount > max_grow)
4330 		return (KERN_NO_SPACE);
4331 
4332 	/*
4333 	 * If this is the main process stack, see if we're over the stack
4334 	 * limit.
4335 	 */
4336 	is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr &&
4337 	    addr < (vm_offset_t)p->p_sysent->sv_usrstack;
4338 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim))
4339 		return (KERN_NO_SPACE);
4340 
4341 #ifdef RACCT
4342 	if (racct_enable) {
4343 		PROC_LOCK(p);
4344 		if (is_procstack && racct_set(p, RACCT_STACK,
4345 		    ctob(vm->vm_ssize) + grow_amount)) {
4346 			PROC_UNLOCK(p);
4347 			return (KERN_NO_SPACE);
4348 		}
4349 		PROC_UNLOCK(p);
4350 	}
4351 #endif
4352 
4353 	grow_amount = roundup(grow_amount, sgrowsiz);
4354 	if (grow_amount > max_grow)
4355 		grow_amount = max_grow;
4356 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
4357 		grow_amount = trunc_page((vm_size_t)stacklim) -
4358 		    ctob(vm->vm_ssize);
4359 	}
4360 
4361 #ifdef notyet
4362 	PROC_LOCK(p);
4363 	limit = racct_get_available(p, RACCT_STACK);
4364 	PROC_UNLOCK(p);
4365 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > limit))
4366 		grow_amount = limit - ctob(vm->vm_ssize);
4367 #endif
4368 
4369 	if (!old_mlock && (map->flags & MAP_WIREFUTURE) != 0) {
4370 		if (ptoa(pmap_wired_count(map->pmap)) + grow_amount > lmemlim) {
4371 			rv = KERN_NO_SPACE;
4372 			goto out;
4373 		}
4374 #ifdef RACCT
4375 		if (racct_enable) {
4376 			PROC_LOCK(p);
4377 			if (racct_set(p, RACCT_MEMLOCK,
4378 			    ptoa(pmap_wired_count(map->pmap)) + grow_amount)) {
4379 				PROC_UNLOCK(p);
4380 				rv = KERN_NO_SPACE;
4381 				goto out;
4382 			}
4383 			PROC_UNLOCK(p);
4384 		}
4385 #endif
4386 	}
4387 
4388 	/* If we would blow our VMEM resource limit, no go */
4389 	if (map->size + grow_amount > vmemlim) {
4390 		rv = KERN_NO_SPACE;
4391 		goto out;
4392 	}
4393 #ifdef RACCT
4394 	if (racct_enable) {
4395 		PROC_LOCK(p);
4396 		if (racct_set(p, RACCT_VMEM, map->size + grow_amount)) {
4397 			PROC_UNLOCK(p);
4398 			rv = KERN_NO_SPACE;
4399 			goto out;
4400 		}
4401 		PROC_UNLOCK(p);
4402 	}
4403 #endif
4404 
4405 	if (vm_map_lock_upgrade(map)) {
4406 		gap_entry = NULL;
4407 		vm_map_lock_read(map);
4408 		goto retry;
4409 	}
4410 
4411 	if (grow_down) {
4412 		grow_start = gap_entry->end - grow_amount;
4413 		if (gap_entry->start + grow_amount == gap_entry->end) {
4414 			gap_start = gap_entry->start;
4415 			gap_end = gap_entry->end;
4416 			vm_map_entry_delete(map, gap_entry);
4417 			gap_deleted = true;
4418 		} else {
4419 			MPASS(gap_entry->start < gap_entry->end - grow_amount);
4420 			gap_entry->end -= grow_amount;
4421 			vm_map_entry_resize_free(map, gap_entry);
4422 			gap_deleted = false;
4423 		}
4424 		rv = vm_map_insert(map, NULL, 0, grow_start,
4425 		    grow_start + grow_amount,
4426 		    stack_entry->protection, stack_entry->max_protection,
4427 		    MAP_STACK_GROWS_DOWN);
4428 		if (rv != KERN_SUCCESS) {
4429 			if (gap_deleted) {
4430 				rv1 = vm_map_insert(map, NULL, 0, gap_start,
4431 				    gap_end, VM_PROT_NONE, VM_PROT_NONE,
4432 				    MAP_CREATE_GUARD | MAP_CREATE_STACK_GAP_DN);
4433 				MPASS(rv1 == KERN_SUCCESS);
4434 			} else {
4435 				gap_entry->end += grow_amount;
4436 				vm_map_entry_resize_free(map, gap_entry);
4437 			}
4438 		}
4439 	} else {
4440 		grow_start = stack_entry->end;
4441 		cred = stack_entry->cred;
4442 		if (cred == NULL && stack_entry->object.vm_object != NULL)
4443 			cred = stack_entry->object.vm_object->cred;
4444 		if (cred != NULL && !swap_reserve_by_cred(grow_amount, cred))
4445 			rv = KERN_NO_SPACE;
4446 		/* Grow the underlying object if applicable. */
4447 		else if (stack_entry->object.vm_object == NULL ||
4448 		    vm_object_coalesce(stack_entry->object.vm_object,
4449 		    stack_entry->offset,
4450 		    (vm_size_t)(stack_entry->end - stack_entry->start),
4451 		    (vm_size_t)grow_amount, cred != NULL)) {
4452 			if (gap_entry->start + grow_amount == gap_entry->end)
4453 				vm_map_entry_delete(map, gap_entry);
4454 			else
4455 				gap_entry->start += grow_amount;
4456 			stack_entry->end += grow_amount;
4457 			map->size += grow_amount;
4458 			vm_map_entry_resize_free(map, stack_entry);
4459 			rv = KERN_SUCCESS;
4460 		} else
4461 			rv = KERN_FAILURE;
4462 	}
4463 	if (rv == KERN_SUCCESS && is_procstack)
4464 		vm->vm_ssize += btoc(grow_amount);
4465 
4466 	/*
4467 	 * Heed the MAP_WIREFUTURE flag if it was set for this process.
4468 	 */
4469 	if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE) != 0) {
4470 		rv = vm_map_wire_locked(map, grow_start,
4471 		    grow_start + grow_amount,
4472 		    VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
4473 	}
4474 	vm_map_lock_downgrade(map);
4475 
4476 out:
4477 #ifdef RACCT
4478 	if (racct_enable && rv != KERN_SUCCESS) {
4479 		PROC_LOCK(p);
4480 		error = racct_set(p, RACCT_VMEM, map->size);
4481 		KASSERT(error == 0, ("decreasing RACCT_VMEM failed"));
4482 		if (!old_mlock) {
4483 			error = racct_set(p, RACCT_MEMLOCK,
4484 			    ptoa(pmap_wired_count(map->pmap)));
4485 			KASSERT(error == 0, ("decreasing RACCT_MEMLOCK failed"));
4486 		}
4487 	    	error = racct_set(p, RACCT_STACK, ctob(vm->vm_ssize));
4488 		KASSERT(error == 0, ("decreasing RACCT_STACK failed"));
4489 		PROC_UNLOCK(p);
4490 	}
4491 #endif
4492 
4493 	return (rv);
4494 }
4495 
4496 /*
4497  * Unshare the specified VM space for exec.  If other processes are
4498  * mapped to it, then create a new one.  The new vmspace is null.
4499  */
4500 int
vmspace_exec(struct proc * p,vm_offset_t minuser,vm_offset_t maxuser)4501 vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
4502 {
4503 	struct vmspace *oldvmspace = p->p_vmspace;
4504 	struct vmspace *newvmspace;
4505 
4506 	KASSERT((curthread->td_pflags & TDP_EXECVMSPC) == 0,
4507 	    ("vmspace_exec recursed"));
4508 	newvmspace = vmspace_alloc(minuser, maxuser, pmap_pinit);
4509 	if (newvmspace == NULL)
4510 		return (ENOMEM);
4511 	newvmspace->vm_swrss = oldvmspace->vm_swrss;
4512 	/*
4513 	 * This code is written like this for prototype purposes.  The
4514 	 * goal is to avoid running down the vmspace here, but let the
4515 	 * other process's that are still using the vmspace to finally
4516 	 * run it down.  Even though there is little or no chance of blocking
4517 	 * here, it is a good idea to keep this form for future mods.
4518 	 */
4519 	PROC_VMSPACE_LOCK(p);
4520 	p->p_vmspace = newvmspace;
4521 	PROC_VMSPACE_UNLOCK(p);
4522 	if (p == curthread->td_proc)
4523 		pmap_activate(curthread);
4524 	curthread->td_pflags |= TDP_EXECVMSPC;
4525 	return (0);
4526 }
4527 
4528 /*
4529  * Unshare the specified VM space for forcing COW.  This
4530  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
4531  */
4532 int
vmspace_unshare(struct proc * p)4533 vmspace_unshare(struct proc *p)
4534 {
4535 	struct vmspace *oldvmspace = p->p_vmspace;
4536 	struct vmspace *newvmspace;
4537 	vm_ooffset_t fork_charge;
4538 
4539 	if (oldvmspace->vm_refcnt == 1)
4540 		return (0);
4541 	fork_charge = 0;
4542 	newvmspace = vmspace_fork(oldvmspace, &fork_charge);
4543 	if (newvmspace == NULL)
4544 		return (ENOMEM);
4545 	if (!swap_reserve_by_cred(fork_charge, p->p_ucred)) {
4546 		vmspace_free(newvmspace);
4547 		return (ENOMEM);
4548 	}
4549 	PROC_VMSPACE_LOCK(p);
4550 	p->p_vmspace = newvmspace;
4551 	PROC_VMSPACE_UNLOCK(p);
4552 	if (p == curthread->td_proc)
4553 		pmap_activate(curthread);
4554 	vmspace_free(oldvmspace);
4555 	return (0);
4556 }
4557 
4558 /*
4559  *	vm_map_lookup:
4560  *
4561  *	Finds the VM object, offset, and
4562  *	protection for a given virtual address in the
4563  *	specified map, assuming a page fault of the
4564  *	type specified.
4565  *
4566  *	Leaves the map in question locked for read; return
4567  *	values are guaranteed until a vm_map_lookup_done
4568  *	call is performed.  Note that the map argument
4569  *	is in/out; the returned map must be used in
4570  *	the call to vm_map_lookup_done.
4571  *
4572  *	A handle (out_entry) is returned for use in
4573  *	vm_map_lookup_done, to make that fast.
4574  *
4575  *	If a lookup is requested with "write protection"
4576  *	specified, the map may be changed to perform virtual
4577  *	copying operations, although the data referenced will
4578  *	remain the same.
4579  */
4580 int
vm_map_lookup(vm_map_t * var_map,vm_offset_t vaddr,vm_prot_t fault_typea,vm_map_entry_t * out_entry,vm_object_t * object,vm_pindex_t * pindex,vm_prot_t * out_prot,boolean_t * wired)4581 vm_map_lookup(vm_map_t *var_map,		/* IN/OUT */
4582 	      vm_offset_t vaddr,
4583 	      vm_prot_t fault_typea,
4584 	      vm_map_entry_t *out_entry,	/* OUT */
4585 	      vm_object_t *object,		/* OUT */
4586 	      vm_pindex_t *pindex,		/* OUT */
4587 	      vm_prot_t *out_prot,		/* OUT */
4588 	      boolean_t *wired)			/* OUT */
4589 {
4590 	vm_map_entry_t entry;
4591 	vm_map_t map = *var_map;
4592 	vm_prot_t prot;
4593 	vm_prot_t fault_type;
4594 	vm_object_t eobject;
4595 	vm_size_t size;
4596 	struct ucred *cred;
4597 
4598 RetryLookup:
4599 
4600 	vm_map_lock_read(map);
4601 
4602 RetryLookupLocked:
4603 	/*
4604 	 * Lookup the faulting address.
4605 	 */
4606 	if (!vm_map_lookup_entry(map, vaddr, out_entry)) {
4607 		vm_map_unlock_read(map);
4608 		return (KERN_INVALID_ADDRESS);
4609 	}
4610 
4611 	entry = *out_entry;
4612 
4613 	/*
4614 	 * Handle submaps.
4615 	 */
4616 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4617 		vm_map_t old_map = map;
4618 
4619 		*var_map = map = entry->object.sub_map;
4620 		vm_map_unlock_read(old_map);
4621 		goto RetryLookup;
4622 	}
4623 
4624 	/*
4625 	 * Check whether this task is allowed to have this page.
4626 	 */
4627 	prot = entry->protection;
4628 	if ((fault_typea & VM_PROT_FAULT_LOOKUP) != 0) {
4629 		fault_typea &= ~VM_PROT_FAULT_LOOKUP;
4630 		if (prot == VM_PROT_NONE && map != kernel_map &&
4631 		    (entry->eflags & MAP_ENTRY_GUARD) != 0 &&
4632 		    (entry->eflags & (MAP_ENTRY_STACK_GAP_DN |
4633 		    MAP_ENTRY_STACK_GAP_UP)) != 0 &&
4634 		    vm_map_growstack(map, vaddr, entry) == KERN_SUCCESS)
4635 			goto RetryLookupLocked;
4636 	}
4637 	fault_type = fault_typea & VM_PROT_ALL;
4638 	if ((fault_type & prot) != fault_type || prot == VM_PROT_NONE) {
4639 		vm_map_unlock_read(map);
4640 		return (KERN_PROTECTION_FAILURE);
4641 	}
4642 	KASSERT((prot & VM_PROT_WRITE) == 0 || (entry->eflags &
4643 	    (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY)) !=
4644 	    (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY),
4645 	    ("entry %p flags %x", entry, entry->eflags));
4646 	if ((fault_typea & VM_PROT_COPY) != 0 &&
4647 	    (entry->max_protection & VM_PROT_WRITE) == 0 &&
4648 	    (entry->eflags & MAP_ENTRY_COW) == 0) {
4649 		vm_map_unlock_read(map);
4650 		return (KERN_PROTECTION_FAILURE);
4651 	}
4652 
4653 	/*
4654 	 * If this page is not pageable, we have to get it for all possible
4655 	 * accesses.
4656 	 */
4657 	*wired = (entry->wired_count != 0);
4658 	if (*wired)
4659 		fault_type = entry->protection;
4660 	size = entry->end - entry->start;
4661 	/*
4662 	 * If the entry was copy-on-write, we either ...
4663 	 */
4664 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4665 		/*
4666 		 * If we want to write the page, we may as well handle that
4667 		 * now since we've got the map locked.
4668 		 *
4669 		 * If we don't need to write the page, we just demote the
4670 		 * permissions allowed.
4671 		 */
4672 		if ((fault_type & VM_PROT_WRITE) != 0 ||
4673 		    (fault_typea & VM_PROT_COPY) != 0) {
4674 			/*
4675 			 * Make a new object, and place it in the object
4676 			 * chain.  Note that no new references have appeared
4677 			 * -- one just moved from the map to the new
4678 			 * object.
4679 			 */
4680 			if (vm_map_lock_upgrade(map))
4681 				goto RetryLookup;
4682 
4683 			if (entry->cred == NULL) {
4684 				/*
4685 				 * The debugger owner is charged for
4686 				 * the memory.
4687 				 */
4688 				cred = curthread->td_ucred;
4689 				crhold(cred);
4690 				if (!swap_reserve_by_cred(size, cred)) {
4691 					crfree(cred);
4692 					vm_map_unlock(map);
4693 					return (KERN_RESOURCE_SHORTAGE);
4694 				}
4695 				entry->cred = cred;
4696 			}
4697 			vm_object_shadow(&entry->object.vm_object,
4698 			    &entry->offset, size);
4699 			entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
4700 			eobject = entry->object.vm_object;
4701 			if (eobject->cred != NULL) {
4702 				/*
4703 				 * The object was not shadowed.
4704 				 */
4705 				swap_release_by_cred(size, entry->cred);
4706 				crfree(entry->cred);
4707 				entry->cred = NULL;
4708 			} else if (entry->cred != NULL) {
4709 				VM_OBJECT_WLOCK(eobject);
4710 				eobject->cred = entry->cred;
4711 				eobject->charge = size;
4712 				VM_OBJECT_WUNLOCK(eobject);
4713 				entry->cred = NULL;
4714 			}
4715 
4716 			vm_map_lock_downgrade(map);
4717 		} else {
4718 			/*
4719 			 * We're attempting to read a copy-on-write page --
4720 			 * don't allow writes.
4721 			 */
4722 			prot &= ~VM_PROT_WRITE;
4723 		}
4724 	}
4725 
4726 	/*
4727 	 * Create an object if necessary.
4728 	 */
4729 	if (entry->object.vm_object == NULL &&
4730 	    !map->system_map) {
4731 		if (vm_map_lock_upgrade(map))
4732 			goto RetryLookup;
4733 		entry->object.vm_object = vm_object_allocate(OBJT_DEFAULT,
4734 		    atop(size));
4735 		entry->offset = 0;
4736 		if (entry->cred != NULL) {
4737 			VM_OBJECT_WLOCK(entry->object.vm_object);
4738 			entry->object.vm_object->cred = entry->cred;
4739 			entry->object.vm_object->charge = size;
4740 			VM_OBJECT_WUNLOCK(entry->object.vm_object);
4741 			entry->cred = NULL;
4742 		}
4743 		vm_map_lock_downgrade(map);
4744 	}
4745 
4746 	/*
4747 	 * Return the object/offset from this entry.  If the entry was
4748 	 * copy-on-write or empty, it has been fixed up.
4749 	 */
4750 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4751 	*object = entry->object.vm_object;
4752 
4753 	*out_prot = prot;
4754 	return (KERN_SUCCESS);
4755 }
4756 
4757 /*
4758  *	vm_map_lookup_locked:
4759  *
4760  *	Lookup the faulting address.  A version of vm_map_lookup that returns
4761  *      KERN_FAILURE instead of blocking on map lock or memory allocation.
4762  */
4763 int
vm_map_lookup_locked(vm_map_t * var_map,vm_offset_t vaddr,vm_prot_t fault_typea,vm_map_entry_t * out_entry,vm_object_t * object,vm_pindex_t * pindex,vm_prot_t * out_prot,boolean_t * wired)4764 vm_map_lookup_locked(vm_map_t *var_map,		/* IN/OUT */
4765 		     vm_offset_t vaddr,
4766 		     vm_prot_t fault_typea,
4767 		     vm_map_entry_t *out_entry,	/* OUT */
4768 		     vm_object_t *object,	/* OUT */
4769 		     vm_pindex_t *pindex,	/* OUT */
4770 		     vm_prot_t *out_prot,	/* OUT */
4771 		     boolean_t *wired)		/* OUT */
4772 {
4773 	vm_map_entry_t entry;
4774 	vm_map_t map = *var_map;
4775 	vm_prot_t prot;
4776 	vm_prot_t fault_type = fault_typea;
4777 
4778 	/*
4779 	 * Lookup the faulting address.
4780 	 */
4781 	if (!vm_map_lookup_entry(map, vaddr, out_entry))
4782 		return (KERN_INVALID_ADDRESS);
4783 
4784 	entry = *out_entry;
4785 
4786 	/*
4787 	 * Fail if the entry refers to a submap.
4788 	 */
4789 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
4790 		return (KERN_FAILURE);
4791 
4792 	/*
4793 	 * Check whether this task is allowed to have this page.
4794 	 */
4795 	prot = entry->protection;
4796 	fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
4797 	if ((fault_type & prot) != fault_type)
4798 		return (KERN_PROTECTION_FAILURE);
4799 
4800 	/*
4801 	 * If this page is not pageable, we have to get it for all possible
4802 	 * accesses.
4803 	 */
4804 	*wired = (entry->wired_count != 0);
4805 	if (*wired)
4806 		fault_type = entry->protection;
4807 
4808 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4809 		/*
4810 		 * Fail if the entry was copy-on-write for a write fault.
4811 		 */
4812 		if (fault_type & VM_PROT_WRITE)
4813 			return (KERN_FAILURE);
4814 		/*
4815 		 * We're attempting to read a copy-on-write page --
4816 		 * don't allow writes.
4817 		 */
4818 		prot &= ~VM_PROT_WRITE;
4819 	}
4820 
4821 	/*
4822 	 * Fail if an object should be created.
4823 	 */
4824 	if (entry->object.vm_object == NULL && !map->system_map)
4825 		return (KERN_FAILURE);
4826 
4827 	/*
4828 	 * Return the object/offset from this entry.  If the entry was
4829 	 * copy-on-write or empty, it has been fixed up.
4830 	 */
4831 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4832 	*object = entry->object.vm_object;
4833 
4834 	*out_prot = prot;
4835 	return (KERN_SUCCESS);
4836 }
4837 
4838 /*
4839  *	vm_map_lookup_done:
4840  *
4841  *	Releases locks acquired by a vm_map_lookup
4842  *	(according to the handle returned by that lookup).
4843  */
4844 void
vm_map_lookup_done(vm_map_t map,vm_map_entry_t entry)4845 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
4846 {
4847 	/*
4848 	 * Unlock the main-level map
4849 	 */
4850 	vm_map_unlock_read(map);
4851 }
4852 
4853 vm_offset_t
vm_map_max_KBI(const struct vm_map * map)4854 vm_map_max_KBI(const struct vm_map *map)
4855 {
4856 
4857 	return (vm_map_max(map));
4858 }
4859 
4860 vm_offset_t
vm_map_min_KBI(const struct vm_map * map)4861 vm_map_min_KBI(const struct vm_map *map)
4862 {
4863 
4864 	return (vm_map_min(map));
4865 }
4866 
4867 pmap_t
vm_map_pmap_KBI(vm_map_t map)4868 vm_map_pmap_KBI(vm_map_t map)
4869 {
4870 
4871 	return (map->pmap);
4872 }
4873 
4874 bool
vm_map_range_valid_KBI(vm_map_t map,vm_offset_t start,vm_offset_t end)4875 vm_map_range_valid_KBI(vm_map_t map, vm_offset_t start, vm_offset_t end)
4876 {
4877 
4878 	return (vm_map_range_valid(map, start, end));
4879 }
4880 
4881 #include "opt_ddb.h"
4882 #ifdef DDB
4883 #include <sys/kernel.h>
4884 
4885 #include <ddb/ddb.h>
4886 
4887 static void
vm_map_print(vm_map_t map)4888 vm_map_print(vm_map_t map)
4889 {
4890 	vm_map_entry_t entry;
4891 
4892 	db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
4893 	    (void *)map,
4894 	    (void *)map->pmap, map->nentries, map->timestamp);
4895 
4896 	db_indent += 2;
4897 	for (entry = map->header.next; entry != &map->header;
4898 	    entry = entry->next) {
4899 		db_iprintf("map entry %p: start=%p, end=%p, eflags=%#x, \n",
4900 		    (void *)entry, (void *)entry->start, (void *)entry->end,
4901 		    entry->eflags);
4902 		{
4903 			static char *inheritance_name[4] =
4904 			{"share", "copy", "none", "donate_copy"};
4905 
4906 			db_iprintf(" prot=%x/%x/%s",
4907 			    entry->protection,
4908 			    entry->max_protection,
4909 			    inheritance_name[(int)(unsigned char)entry->inheritance]);
4910 			if (entry->wired_count != 0)
4911 				db_printf(", wired");
4912 		}
4913 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4914 			db_printf(", share=%p, offset=0x%jx\n",
4915 			    (void *)entry->object.sub_map,
4916 			    (uintmax_t)entry->offset);
4917 			if ((entry->prev == &map->header) ||
4918 			    (entry->prev->object.sub_map !=
4919 				entry->object.sub_map)) {
4920 				db_indent += 2;
4921 				vm_map_print((vm_map_t)entry->object.sub_map);
4922 				db_indent -= 2;
4923 			}
4924 		} else {
4925 			if (entry->cred != NULL)
4926 				db_printf(", ruid %d", entry->cred->cr_ruid);
4927 			db_printf(", object=%p, offset=0x%jx",
4928 			    (void *)entry->object.vm_object,
4929 			    (uintmax_t)entry->offset);
4930 			if (entry->object.vm_object && entry->object.vm_object->cred)
4931 				db_printf(", obj ruid %d charge %jx",
4932 				    entry->object.vm_object->cred->cr_ruid,
4933 				    (uintmax_t)entry->object.vm_object->charge);
4934 			if (entry->eflags & MAP_ENTRY_COW)
4935 				db_printf(", copy (%s)",
4936 				    (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
4937 			db_printf("\n");
4938 
4939 			if ((entry->prev == &map->header) ||
4940 			    (entry->prev->object.vm_object !=
4941 				entry->object.vm_object)) {
4942 				db_indent += 2;
4943 				vm_object_print((db_expr_t)(intptr_t)
4944 						entry->object.vm_object,
4945 						0, 0, (char *)0);
4946 				db_indent -= 2;
4947 			}
4948 		}
4949 	}
4950 	db_indent -= 2;
4951 }
4952 
DB_SHOW_COMMAND(map,map)4953 DB_SHOW_COMMAND(map, map)
4954 {
4955 
4956 	if (!have_addr) {
4957 		db_printf("usage: show map <addr>\n");
4958 		return;
4959 	}
4960 	vm_map_print((vm_map_t)addr);
4961 }
4962 
DB_SHOW_COMMAND(procvm,procvm)4963 DB_SHOW_COMMAND(procvm, procvm)
4964 {
4965 	struct proc *p;
4966 
4967 	if (have_addr) {
4968 		p = db_lookup_proc(addr);
4969 	} else {
4970 		p = curproc;
4971 	}
4972 
4973 	db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
4974 	    (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
4975 	    (void *)vmspace_pmap(p->p_vmspace));
4976 
4977 	vm_map_print((vm_map_t)&p->p_vmspace->vm_map);
4978 }
4979 
4980 #endif /* DDB */
4981