xref: /openbsd-src/sys/uvm/uvm_map.c (revision 7350f337b9e3eb4461d99580e625c7ef148d107c)
1 /*	$OpenBSD: uvm_map.c,v 1.246 2019/06/14 05:52:43 deraadt Exp $	*/
2 /*	$NetBSD: uvm_map.c,v 1.86 2000/11/27 08:40:03 chs Exp $	*/
3 
4 /*
5  * Copyright (c) 2011 Ariane van der Steldt <ariane@openbsd.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  *
19  *
20  * Copyright (c) 1997 Charles D. Cranor and Washington University.
21  * Copyright (c) 1991, 1993, The Regents of the University of California.
22  *
23  * All rights reserved.
24  *
25  * This code is derived from software contributed to Berkeley by
26  * The Mach Operating System project at Carnegie-Mellon University.
27  *
28  * Redistribution and use in source and binary forms, with or without
29  * modification, are permitted provided that the following conditions
30  * are met:
31  * 1. Redistributions of source code must retain the above copyright
32  *    notice, this list of conditions and the following disclaimer.
33  * 2. Redistributions in binary form must reproduce the above copyright
34  *    notice, this list of conditions and the following disclaimer in the
35  *    documentation and/or other materials provided with the distribution.
36  * 3. Neither the name of the University nor the names of its contributors
37  *    may be used to endorse or promote products derived from this software
38  *    without specific prior written permission.
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  *	@(#)vm_map.c    8.3 (Berkeley) 1/12/94
53  * from: Id: uvm_map.c,v 1.1.2.27 1998/02/07 01:16:54 chs Exp
54  *
55  *
56  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
57  * All rights reserved.
58  *
59  * Permission to use, copy, modify and distribute this software and
60  * its documentation is hereby granted, provided that both the copyright
61  * notice and this permission notice appear in all copies of the
62  * software, derivative works or modified versions, and any portions
63  * thereof, and that both notices appear in supporting documentation.
64  *
65  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
66  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
67  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
68  *
69  * Carnegie Mellon requests users of this software to return to
70  *
71  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
72  *  School of Computer Science
73  *  Carnegie Mellon University
74  *  Pittsburgh PA 15213-3890
75  *
76  * any improvements or extensions that they make and grant Carnegie the
77  * rights to redistribute these changes.
78  */
79 
80 /*
81  * uvm_map.c: uvm map operations
82  */
83 
84 /* #define DEBUG */
85 /* #define VMMAP_DEBUG */
86 
87 #include <sys/param.h>
88 #include <sys/systm.h>
89 #include <sys/mman.h>
90 #include <sys/proc.h>
91 #include <sys/malloc.h>
92 #include <sys/pool.h>
93 #include <sys/sysctl.h>
94 #include <sys/signalvar.h>
95 #include <sys/syslog.h>
96 #include <sys/user.h>
97 
98 #ifdef SYSVSHM
99 #include <sys/shm.h>
100 #endif
101 
102 #include <uvm/uvm.h>
103 
104 #ifdef DDB
105 #include <uvm/uvm_ddb.h>
106 #endif
107 
108 #include <uvm/uvm_addr.h>
109 
110 
111 vsize_t			 uvmspace_dused(struct vm_map*, vaddr_t, vaddr_t);
112 int			 uvm_mapent_isjoinable(struct vm_map*,
113 			    struct vm_map_entry*, struct vm_map_entry*);
114 struct vm_map_entry	*uvm_mapent_merge(struct vm_map*, struct vm_map_entry*,
115 			    struct vm_map_entry*, struct uvm_map_deadq*);
116 struct vm_map_entry	*uvm_mapent_tryjoin(struct vm_map*,
117 			    struct vm_map_entry*, struct uvm_map_deadq*);
118 struct vm_map_entry	*uvm_map_mkentry(struct vm_map*, struct vm_map_entry*,
119 			    struct vm_map_entry*, vaddr_t, vsize_t, int,
120 			    struct uvm_map_deadq*, struct vm_map_entry*);
121 struct vm_map_entry	*uvm_mapent_alloc(struct vm_map*, int);
122 void			 uvm_mapent_free(struct vm_map_entry*);
123 void			 uvm_unmap_kill_entry(struct vm_map*,
124 			    struct vm_map_entry*);
125 void			 uvm_unmap_detach_intrsafe(struct uvm_map_deadq *);
126 void			 uvm_mapent_mkfree(struct vm_map*,
127 			    struct vm_map_entry*, struct vm_map_entry**,
128 			    struct uvm_map_deadq*, boolean_t);
129 void			 uvm_map_pageable_pgon(struct vm_map*,
130 			    struct vm_map_entry*, struct vm_map_entry*,
131 			    vaddr_t, vaddr_t);
132 int			 uvm_map_pageable_wire(struct vm_map*,
133 			    struct vm_map_entry*, struct vm_map_entry*,
134 			    vaddr_t, vaddr_t, int);
135 void			 uvm_map_setup_entries(struct vm_map*);
136 void			 uvm_map_setup_md(struct vm_map*);
137 void			 uvm_map_teardown(struct vm_map*);
138 void			 uvm_map_vmspace_update(struct vm_map*,
139 			    struct uvm_map_deadq*, int);
140 void			 uvm_map_kmem_grow(struct vm_map*,
141 			    struct uvm_map_deadq*, vsize_t, int);
142 void			 uvm_map_freelist_update_clear(struct vm_map*,
143 			    struct uvm_map_deadq*);
144 void			 uvm_map_freelist_update_refill(struct vm_map *, int);
145 void			 uvm_map_freelist_update(struct vm_map*,
146 			    struct uvm_map_deadq*, vaddr_t, vaddr_t,
147 			    vaddr_t, vaddr_t, int);
148 struct vm_map_entry	*uvm_map_fix_space(struct vm_map*, struct vm_map_entry*,
149 			    vaddr_t, vaddr_t, int);
150 int			 uvm_map_sel_limits(vaddr_t*, vaddr_t*, vsize_t, int,
151 			    struct vm_map_entry*, vaddr_t, vaddr_t, vaddr_t,
152 			    int);
153 int			 uvm_map_findspace(struct vm_map*,
154 			    struct vm_map_entry**, struct vm_map_entry**,
155 			    vaddr_t*, vsize_t, vaddr_t, vaddr_t, vm_prot_t,
156 			    vaddr_t);
157 vsize_t			 uvm_map_addr_augment_get(struct vm_map_entry*);
158 void			 uvm_map_addr_augment(struct vm_map_entry*);
159 
160 /*
161  * Tree management functions.
162  */
163 
164 static __inline void	 uvm_mapent_copy(struct vm_map_entry*,
165 			    struct vm_map_entry*);
166 static inline int	 uvm_mapentry_addrcmp(const struct vm_map_entry*,
167 			    const struct vm_map_entry*);
168 void			 uvm_mapent_free_insert(struct vm_map*,
169 			    struct uvm_addr_state*, struct vm_map_entry*);
170 void			 uvm_mapent_free_remove(struct vm_map*,
171 			    struct uvm_addr_state*, struct vm_map_entry*);
172 void			 uvm_mapent_addr_insert(struct vm_map*,
173 			    struct vm_map_entry*);
174 void			 uvm_mapent_addr_remove(struct vm_map*,
175 			    struct vm_map_entry*);
176 void			 uvm_map_splitentry(struct vm_map*,
177 			    struct vm_map_entry*, struct vm_map_entry*,
178 			    vaddr_t);
179 vsize_t			 uvm_map_boundary(struct vm_map*, vaddr_t, vaddr_t);
180 int			 uvm_mapent_bias(struct vm_map*, struct vm_map_entry*);
181 
182 /*
183  * uvm_vmspace_fork helper functions.
184  */
185 struct vm_map_entry	*uvm_mapent_clone(struct vm_map*, vaddr_t, vsize_t,
186 			    vsize_t, vm_prot_t, vm_prot_t,
187 			    struct vm_map_entry*, struct uvm_map_deadq*, int,
188 			    int);
189 struct vm_map_entry	*uvm_mapent_share(struct vm_map*, vaddr_t, vsize_t,
190 			    vsize_t, vm_prot_t, vm_prot_t, struct vm_map*,
191 			    struct vm_map_entry*, struct uvm_map_deadq*);
192 struct vm_map_entry	*uvm_mapent_forkshared(struct vmspace*, struct vm_map*,
193 			    struct vm_map*, struct vm_map_entry*,
194 			    struct uvm_map_deadq*);
195 struct vm_map_entry	*uvm_mapent_forkcopy(struct vmspace*, struct vm_map*,
196 			    struct vm_map*, struct vm_map_entry*,
197 			    struct uvm_map_deadq*);
198 struct vm_map_entry	*uvm_mapent_forkzero(struct vmspace*, struct vm_map*,
199 			    struct vm_map*, struct vm_map_entry*,
200 			    struct uvm_map_deadq*);
201 
202 /*
203  * Tree validation.
204  */
205 #ifdef VMMAP_DEBUG
206 void			 uvm_tree_assert(struct vm_map*, int, char*,
207 			    char*, int);
208 #define UVM_ASSERT(map, cond, file, line)				\
209 	uvm_tree_assert((map), (cond), #cond, (file), (line))
210 void			 uvm_tree_sanity(struct vm_map*, char*, int);
211 void			 uvm_tree_size_chk(struct vm_map*, char*, int);
212 void			 vmspace_validate(struct vm_map*);
213 #else
214 #define uvm_tree_sanity(_map, _file, _line)		do {} while (0)
215 #define uvm_tree_size_chk(_map, _file, _line)		do {} while (0)
216 #define vmspace_validate(_map)				do {} while (0)
217 #endif
218 
219 /*
220  * All architectures will have pmap_prefer.
221  */
222 #ifndef PMAP_PREFER
223 #define PMAP_PREFER_ALIGN()	(vaddr_t)PAGE_SIZE
224 #define PMAP_PREFER_OFFSET(off)	0
225 #define PMAP_PREFER(addr, off)	(addr)
226 #endif
227 
228 
229 /*
230  * The kernel map will initially be VM_MAP_KSIZE_INIT bytes.
231  * Every time that gets cramped, we grow by at least VM_MAP_KSIZE_DELTA bytes.
232  *
233  * We attempt to grow by UVM_MAP_KSIZE_ALLOCMUL times the allocation size
234  * each time.
235  */
236 #define VM_MAP_KSIZE_INIT	(512 * (vaddr_t)PAGE_SIZE)
237 #define VM_MAP_KSIZE_DELTA	(256 * (vaddr_t)PAGE_SIZE)
238 #define VM_MAP_KSIZE_ALLOCMUL	4
239 /*
240  * When selecting a random free-space block, look at most FSPACE_DELTA blocks
241  * ahead.
242  */
243 #define FSPACE_DELTA		8
244 /*
245  * Put allocations adjecent to previous allocations when the free-space tree
246  * is larger than FSPACE_COMPACT entries.
247  *
248  * Alignment and PMAP_PREFER may still cause the entry to not be fully
249  * adjecent. Note that this strategy reduces memory fragmentation (by leaving
250  * a large space before or after the allocation).
251  */
252 #define FSPACE_COMPACT		128
253 /*
254  * Make the address selection skip at most this many bytes from the start of
255  * the free space in which the allocation takes place.
256  *
257  * The main idea behind a randomized address space is that an attacker cannot
258  * know where to target his attack. Therefore, the location of objects must be
259  * as random as possible. However, the goal is not to create the most sparse
260  * map that is possible.
261  * FSPACE_MAXOFF pushes the considered range in bytes down to less insane
262  * sizes, thereby reducing the sparseness. The biggest randomization comes
263  * from fragmentation, i.e. FSPACE_COMPACT.
264  */
265 #define FSPACE_MAXOFF		((vaddr_t)32 * 1024 * 1024)
266 /*
267  * Allow for small gaps in the overflow areas.
268  * Gap size is in bytes and does not have to be a multiple of page-size.
269  */
270 #define FSPACE_BIASGAP		((vaddr_t)32 * 1024)
271 
272 /* auto-allocate address lower bound */
273 #define VMMAP_MIN_ADDR		PAGE_SIZE
274 
275 
276 #ifdef DEADBEEF0
277 #define UVMMAP_DEADBEEF		((unsigned long)DEADBEEF0)
278 #else
279 #define UVMMAP_DEADBEEF		((unsigned long)0xdeadd0d0)
280 #endif
281 
282 #ifdef DEBUG
283 int uvm_map_printlocks = 0;
284 
285 #define LPRINTF(_args)							\
286 	do {								\
287 		if (uvm_map_printlocks)					\
288 			printf _args;					\
289 	} while (0)
290 #else
291 #define LPRINTF(_args)	do {} while (0)
292 #endif
293 
294 static struct mutex uvm_kmapent_mtx;
295 static struct timeval uvm_kmapent_last_warn_time;
296 static struct timeval uvm_kmapent_warn_rate = { 10, 0 };
297 
298 const char vmmapbsy[] = "vmmapbsy";
299 
300 /*
301  * pool for vmspace structures.
302  */
303 struct pool uvm_vmspace_pool;
304 
305 /*
306  * pool for dynamically-allocated map entries.
307  */
308 struct pool uvm_map_entry_pool;
309 struct pool uvm_map_entry_kmem_pool;
310 
311 /*
312  * This global represents the end of the kernel virtual address
313  * space. If we want to exceed this, we must grow the kernel
314  * virtual address space dynamically.
315  *
316  * Note, this variable is locked by kernel_map's lock.
317  */
318 vaddr_t uvm_maxkaddr;
319 
320 /*
321  * Locking predicate.
322  */
323 #define UVM_MAP_REQ_WRITE(_map)						\
324 	do {								\
325 		if ((_map)->ref_count > 0) {				\
326 			if (((_map)->flags & VM_MAP_INTRSAFE) == 0)	\
327 				rw_assert_wrlock(&(_map)->lock);	\
328 			else						\
329 				MUTEX_ASSERT_LOCKED(&(_map)->mtx);	\
330 		}							\
331 	} while (0)
332 
333 /*
334  * Tree describing entries by address.
335  *
336  * Addresses are unique.
337  * Entries with start == end may only exist if they are the first entry
338  * (sorted by address) within a free-memory tree.
339  */
340 
341 static inline int
342 uvm_mapentry_addrcmp(const struct vm_map_entry *e1,
343     const struct vm_map_entry *e2)
344 {
345 	return e1->start < e2->start ? -1 : e1->start > e2->start;
346 }
347 
348 /*
349  * Copy mapentry.
350  */
351 static __inline void
352 uvm_mapent_copy(struct vm_map_entry *src, struct vm_map_entry *dst)
353 {
354 	caddr_t csrc, cdst;
355 	size_t sz;
356 
357 	csrc = (caddr_t)src;
358 	cdst = (caddr_t)dst;
359 	csrc += offsetof(struct vm_map_entry, uvm_map_entry_start_copy);
360 	cdst += offsetof(struct vm_map_entry, uvm_map_entry_start_copy);
361 
362 	sz = offsetof(struct vm_map_entry, uvm_map_entry_stop_copy) -
363 	    offsetof(struct vm_map_entry, uvm_map_entry_start_copy);
364 	memcpy(cdst, csrc, sz);
365 }
366 
367 /*
368  * Handle free-list insertion.
369  */
370 void
371 uvm_mapent_free_insert(struct vm_map *map, struct uvm_addr_state *uaddr,
372     struct vm_map_entry *entry)
373 {
374 	const struct uvm_addr_functions *fun;
375 #ifdef VMMAP_DEBUG
376 	vaddr_t min, max, bound;
377 #endif
378 
379 #ifdef VMMAP_DEBUG
380 	/*
381 	 * Boundary check.
382 	 * Boundaries are folded if they go on the same free list.
383 	 */
384 	min = VMMAP_FREE_START(entry);
385 	max = VMMAP_FREE_END(entry);
386 
387 	while (min < max) {
388 		bound = uvm_map_boundary(map, min, max);
389 		KASSERT(uvm_map_uaddr(map, min) == uaddr);
390 		min = bound;
391 	}
392 #endif
393 	KDASSERT((entry->fspace & (vaddr_t)PAGE_MASK) == 0);
394 	KASSERT((entry->etype & UVM_ET_FREEMAPPED) == 0);
395 
396 	UVM_MAP_REQ_WRITE(map);
397 
398 	/* Actual insert: forward to uaddr pointer. */
399 	if (uaddr != NULL) {
400 		fun = uaddr->uaddr_functions;
401 		KDASSERT(fun != NULL);
402 		if (fun->uaddr_free_insert != NULL)
403 			(*fun->uaddr_free_insert)(map, uaddr, entry);
404 		entry->etype |= UVM_ET_FREEMAPPED;
405 	}
406 
407 	/* Update fspace augmentation. */
408 	uvm_map_addr_augment(entry);
409 }
410 
411 /*
412  * Handle free-list removal.
413  */
414 void
415 uvm_mapent_free_remove(struct vm_map *map, struct uvm_addr_state *uaddr,
416     struct vm_map_entry *entry)
417 {
418 	const struct uvm_addr_functions *fun;
419 
420 	KASSERT((entry->etype & UVM_ET_FREEMAPPED) != 0 || uaddr == NULL);
421 	KASSERT(uvm_map_uaddr_e(map, entry) == uaddr);
422 	UVM_MAP_REQ_WRITE(map);
423 
424 	if (uaddr != NULL) {
425 		fun = uaddr->uaddr_functions;
426 		if (fun->uaddr_free_remove != NULL)
427 			(*fun->uaddr_free_remove)(map, uaddr, entry);
428 		entry->etype &= ~UVM_ET_FREEMAPPED;
429 	}
430 }
431 
432 /*
433  * Handle address tree insertion.
434  */
435 void
436 uvm_mapent_addr_insert(struct vm_map *map, struct vm_map_entry *entry)
437 {
438 	struct vm_map_entry *res;
439 
440 	if (!RBT_CHECK(uvm_map_addr, entry, UVMMAP_DEADBEEF))
441 		panic("uvm_mapent_addr_insert: entry still in addr list");
442 	KDASSERT(entry->start <= entry->end);
443 	KDASSERT((entry->start & (vaddr_t)PAGE_MASK) == 0 &&
444 	    (entry->end & (vaddr_t)PAGE_MASK) == 0);
445 
446 	UVM_MAP_REQ_WRITE(map);
447 	res = RBT_INSERT(uvm_map_addr, &map->addr, entry);
448 	if (res != NULL) {
449 		panic("uvm_mapent_addr_insert: map %p entry %p "
450 		    "(0x%lx-0x%lx G=0x%lx F=0x%lx) insert collision "
451 		    "with entry %p (0x%lx-0x%lx G=0x%lx F=0x%lx)",
452 		    map, entry,
453 		    entry->start, entry->end, entry->guard, entry->fspace,
454 		    res, res->start, res->end, res->guard, res->fspace);
455 	}
456 }
457 
458 /*
459  * Handle address tree removal.
460  */
461 void
462 uvm_mapent_addr_remove(struct vm_map *map, struct vm_map_entry *entry)
463 {
464 	struct vm_map_entry *res;
465 
466 	UVM_MAP_REQ_WRITE(map);
467 	res = RBT_REMOVE(uvm_map_addr, &map->addr, entry);
468 	if (res != entry)
469 		panic("uvm_mapent_addr_remove");
470 	RBT_POISON(uvm_map_addr, entry, UVMMAP_DEADBEEF);
471 }
472 
473 /*
474  * uvm_map_reference: add reference to a map
475  *
476  * XXX check map reference counter lock
477  */
478 #define uvm_map_reference(_map)						\
479 	do {								\
480 		map->ref_count++;					\
481 	} while (0)
482 
483 /*
484  * Calculate the dused delta.
485  */
486 vsize_t
487 uvmspace_dused(struct vm_map *map, vaddr_t min, vaddr_t max)
488 {
489 	struct vmspace *vm;
490 	vsize_t sz;
491 	vaddr_t lmax;
492 	vaddr_t stack_begin, stack_end; /* Position of stack. */
493 
494 	KASSERT(map->flags & VM_MAP_ISVMSPACE);
495 	vm = (struct vmspace *)map;
496 	stack_begin = MIN((vaddr_t)vm->vm_maxsaddr, (vaddr_t)vm->vm_minsaddr);
497 	stack_end = MAX((vaddr_t)vm->vm_maxsaddr, (vaddr_t)vm->vm_minsaddr);
498 
499 	sz = 0;
500 	while (min != max) {
501 		lmax = max;
502 		if (min < stack_begin && lmax > stack_begin)
503 			lmax = stack_begin;
504 		else if (min < stack_end && lmax > stack_end)
505 			lmax = stack_end;
506 
507 		if (min >= stack_begin && min < stack_end) {
508 			/* nothing */
509 		} else
510 			sz += lmax - min;
511 		min = lmax;
512 	}
513 
514 	return sz >> PAGE_SHIFT;
515 }
516 
517 /*
518  * Find the entry describing the given address.
519  */
520 struct vm_map_entry*
521 uvm_map_entrybyaddr(struct uvm_map_addr *atree, vaddr_t addr)
522 {
523 	struct vm_map_entry *iter;
524 
525 	iter = RBT_ROOT(uvm_map_addr, atree);
526 	while (iter != NULL) {
527 		if (iter->start > addr)
528 			iter = RBT_LEFT(uvm_map_addr, iter);
529 		else if (VMMAP_FREE_END(iter) <= addr)
530 			iter = RBT_RIGHT(uvm_map_addr, iter);
531 		else
532 			return iter;
533 	}
534 	return NULL;
535 }
536 
537 /*
538  * DEAD_ENTRY_PUSH(struct vm_map_deadq *deadq, struct vm_map_entry *entry)
539  *
540  * Push dead entries into a linked list.
541  * Since the linked list abuses the address tree for storage, the entry
542  * may not be linked in a map.
543  *
544  * *head must be initialized to NULL before the first call to this macro.
545  * uvm_unmap_detach(*head, 0) will remove dead entries.
546  */
547 static __inline void
548 dead_entry_push(struct uvm_map_deadq *deadq, struct vm_map_entry *entry)
549 {
550 	TAILQ_INSERT_TAIL(deadq, entry, dfree.deadq);
551 }
552 #define DEAD_ENTRY_PUSH(_headptr, _entry)				\
553 	dead_entry_push((_headptr), (_entry))
554 
555 /*
556  * Helper function for uvm_map_findspace_tree.
557  *
558  * Given allocation constraints and pmap constraints, finds the
559  * lowest and highest address in a range that can be used for the
560  * allocation.
561  *
562  * pmap_align and pmap_off are ignored on non-PMAP_PREFER archs.
563  *
564  *
565  * Big chunk of math with a seasoning of dragons.
566  */
567 int
568 uvm_map_sel_limits(vaddr_t *min, vaddr_t *max, vsize_t sz, int guardpg,
569     struct vm_map_entry *sel, vaddr_t align,
570     vaddr_t pmap_align, vaddr_t pmap_off, int bias)
571 {
572 	vaddr_t sel_min, sel_max;
573 #ifdef PMAP_PREFER
574 	vaddr_t pmap_min, pmap_max;
575 #endif /* PMAP_PREFER */
576 #ifdef DIAGNOSTIC
577 	int bad;
578 #endif /* DIAGNOSTIC */
579 
580 	sel_min = VMMAP_FREE_START(sel);
581 	sel_max = VMMAP_FREE_END(sel) - sz - (guardpg ? PAGE_SIZE : 0);
582 
583 #ifdef PMAP_PREFER
584 
585 	/*
586 	 * There are two special cases, in which we can satisfy the align
587 	 * requirement and the pmap_prefer requirement.
588 	 * - when pmap_off == 0, we always select the largest of the two
589 	 * - when pmap_off % align == 0 and pmap_align > align, we simply
590 	 *   satisfy the pmap_align requirement and automatically
591 	 *   satisfy the align requirement.
592 	 */
593 	if (align > PAGE_SIZE &&
594 	    !(pmap_align > align && (pmap_off & (align - 1)) == 0)) {
595 		/*
596 		 * Simple case: only use align.
597 		 */
598 		sel_min = roundup(sel_min, align);
599 		sel_max &= ~(align - 1);
600 
601 		if (sel_min > sel_max)
602 			return ENOMEM;
603 
604 		/* Correct for bias. */
605 		if (sel_max - sel_min > FSPACE_BIASGAP) {
606 			if (bias > 0) {
607 				sel_min = sel_max - FSPACE_BIASGAP;
608 				sel_min = roundup(sel_min, align);
609 			} else if (bias < 0) {
610 				sel_max = sel_min + FSPACE_BIASGAP;
611 				sel_max &= ~(align - 1);
612 			}
613 		}
614 	} else if (pmap_align != 0) {
615 		/*
616 		 * Special case: satisfy both pmap_prefer and
617 		 * align argument.
618 		 */
619 		pmap_max = sel_max & ~(pmap_align - 1);
620 		pmap_min = sel_min;
621 		if (pmap_max < sel_min)
622 			return ENOMEM;
623 
624 		/* Adjust pmap_min for BIASGAP for top-addr bias. */
625 		if (bias > 0 && pmap_max - pmap_min > FSPACE_BIASGAP)
626 			pmap_min = pmap_max - FSPACE_BIASGAP;
627 		/* Align pmap_min. */
628 		pmap_min &= ~(pmap_align - 1);
629 		if (pmap_min < sel_min)
630 			pmap_min += pmap_align;
631 		if (pmap_min > pmap_max)
632 			return ENOMEM;
633 
634 		/* Adjust pmap_max for BIASGAP for bottom-addr bias. */
635 		if (bias < 0 && pmap_max - pmap_min > FSPACE_BIASGAP) {
636 			pmap_max = (pmap_min + FSPACE_BIASGAP) &
637 			    ~(pmap_align - 1);
638 		}
639 		if (pmap_min > pmap_max)
640 			return ENOMEM;
641 
642 		/* Apply pmap prefer offset. */
643 		pmap_max |= pmap_off;
644 		if (pmap_max > sel_max)
645 			pmap_max -= pmap_align;
646 		pmap_min |= pmap_off;
647 		if (pmap_min < sel_min)
648 			pmap_min += pmap_align;
649 
650 		/*
651 		 * Fixup: it's possible that pmap_min and pmap_max
652 		 * cross eachother. In this case, try to find one
653 		 * address that is allowed.
654 		 * (This usually happens in biased case.)
655 		 */
656 		if (pmap_min > pmap_max) {
657 			if (pmap_min < sel_max)
658 				pmap_max = pmap_min;
659 			else if (pmap_max > sel_min)
660 				pmap_min = pmap_max;
661 			else
662 				return ENOMEM;
663 		}
664 
665 		/* Internal validation. */
666 		KDASSERT(pmap_min <= pmap_max);
667 
668 		sel_min = pmap_min;
669 		sel_max = pmap_max;
670 	} else if (bias > 0 && sel_max - sel_min > FSPACE_BIASGAP)
671 		sel_min = sel_max - FSPACE_BIASGAP;
672 	else if (bias < 0 && sel_max - sel_min > FSPACE_BIASGAP)
673 		sel_max = sel_min + FSPACE_BIASGAP;
674 
675 #else
676 
677 	if (align > PAGE_SIZE) {
678 		sel_min = roundup(sel_min, align);
679 		sel_max &= ~(align - 1);
680 		if (sel_min > sel_max)
681 			return ENOMEM;
682 
683 		if (bias != 0 && sel_max - sel_min > FSPACE_BIASGAP) {
684 			if (bias > 0) {
685 				sel_min = roundup(sel_max - FSPACE_BIASGAP,
686 				    align);
687 			} else {
688 				sel_max = (sel_min + FSPACE_BIASGAP) &
689 				    ~(align - 1);
690 			}
691 		}
692 	} else if (bias > 0 && sel_max - sel_min > FSPACE_BIASGAP)
693 		sel_min = sel_max - FSPACE_BIASGAP;
694 	else if (bias < 0 && sel_max - sel_min > FSPACE_BIASGAP)
695 		sel_max = sel_min + FSPACE_BIASGAP;
696 
697 #endif
698 
699 	if (sel_min > sel_max)
700 		return ENOMEM;
701 
702 #ifdef DIAGNOSTIC
703 	bad = 0;
704 	/* Lower boundary check. */
705 	if (sel_min < VMMAP_FREE_START(sel)) {
706 		printf("sel_min: 0x%lx, but should be at least 0x%lx\n",
707 		    sel_min, VMMAP_FREE_START(sel));
708 		bad++;
709 	}
710 	/* Upper boundary check. */
711 	if (sel_max > VMMAP_FREE_END(sel) - sz - (guardpg ? PAGE_SIZE : 0)) {
712 		printf("sel_max: 0x%lx, but should be at most 0x%lx\n",
713 		    sel_max,
714 		    VMMAP_FREE_END(sel) - sz - (guardpg ? PAGE_SIZE : 0));
715 		bad++;
716 	}
717 	/* Lower boundary alignment. */
718 	if (align != 0 && (sel_min & (align - 1)) != 0) {
719 		printf("sel_min: 0x%lx, not aligned to 0x%lx\n",
720 		    sel_min, align);
721 		bad++;
722 	}
723 	/* Upper boundary alignment. */
724 	if (align != 0 && (sel_max & (align - 1)) != 0) {
725 		printf("sel_max: 0x%lx, not aligned to 0x%lx\n",
726 		    sel_max, align);
727 		bad++;
728 	}
729 	/* Lower boundary PMAP_PREFER check. */
730 	if (pmap_align != 0 && align == 0 &&
731 	    (sel_min & (pmap_align - 1)) != pmap_off) {
732 		printf("sel_min: 0x%lx, aligned to 0x%lx, expected 0x%lx\n",
733 		    sel_min, sel_min & (pmap_align - 1), pmap_off);
734 		bad++;
735 	}
736 	/* Upper boundary PMAP_PREFER check. */
737 	if (pmap_align != 0 && align == 0 &&
738 	    (sel_max & (pmap_align - 1)) != pmap_off) {
739 		printf("sel_max: 0x%lx, aligned to 0x%lx, expected 0x%lx\n",
740 		    sel_max, sel_max & (pmap_align - 1), pmap_off);
741 		bad++;
742 	}
743 
744 	if (bad) {
745 		panic("uvm_map_sel_limits(sz = %lu, guardpg = %c, "
746 		    "align = 0x%lx, pmap_align = 0x%lx, pmap_off = 0x%lx, "
747 		    "bias = %d, "
748 		    "FREE_START(sel) = 0x%lx, FREE_END(sel) = 0x%lx)",
749 		    sz, (guardpg ? 'T' : 'F'), align, pmap_align, pmap_off,
750 		    bias, VMMAP_FREE_START(sel), VMMAP_FREE_END(sel));
751 	}
752 #endif /* DIAGNOSTIC */
753 
754 	*min = sel_min;
755 	*max = sel_max;
756 	return 0;
757 }
758 
759 /*
760  * Test if memory starting at addr with sz bytes is free.
761  *
762  * Fills in *start_ptr and *end_ptr to be the first and last entry describing
763  * the space.
764  * If called with prefilled *start_ptr and *end_ptr, they are to be correct.
765  */
766 int
767 uvm_map_isavail(struct vm_map *map, struct uvm_addr_state *uaddr,
768     struct vm_map_entry **start_ptr, struct vm_map_entry **end_ptr,
769     vaddr_t addr, vsize_t sz)
770 {
771 	struct uvm_addr_state *free;
772 	struct uvm_map_addr *atree;
773 	struct vm_map_entry *i, *i_end;
774 
775 	if (addr + sz < addr)
776 		return 0;
777 
778 	/*
779 	 * Kernel memory above uvm_maxkaddr is considered unavailable.
780 	 */
781 	if ((map->flags & VM_MAP_ISVMSPACE) == 0) {
782 		if (addr + sz > uvm_maxkaddr)
783 			return 0;
784 	}
785 
786 	atree = &map->addr;
787 
788 	/*
789 	 * Fill in first, last, so they point at the entries containing the
790 	 * first and last address of the range.
791 	 * Note that if they are not NULL, we don't perform the lookup.
792 	 */
793 	KDASSERT(atree != NULL && start_ptr != NULL && end_ptr != NULL);
794 	if (*start_ptr == NULL) {
795 		*start_ptr = uvm_map_entrybyaddr(atree, addr);
796 		if (*start_ptr == NULL)
797 			return 0;
798 	} else
799 		KASSERT(*start_ptr == uvm_map_entrybyaddr(atree, addr));
800 	if (*end_ptr == NULL) {
801 		if (VMMAP_FREE_END(*start_ptr) >= addr + sz)
802 			*end_ptr = *start_ptr;
803 		else {
804 			*end_ptr = uvm_map_entrybyaddr(atree, addr + sz - 1);
805 			if (*end_ptr == NULL)
806 				return 0;
807 		}
808 	} else
809 		KASSERT(*end_ptr == uvm_map_entrybyaddr(atree, addr + sz - 1));
810 
811 	/* Validation. */
812 	KDASSERT(*start_ptr != NULL && *end_ptr != NULL);
813 	KDASSERT((*start_ptr)->start <= addr &&
814 	    VMMAP_FREE_END(*start_ptr) > addr &&
815 	    (*end_ptr)->start < addr + sz &&
816 	    VMMAP_FREE_END(*end_ptr) >= addr + sz);
817 
818 	/*
819 	 * Check the none of the entries intersects with <addr, addr+sz>.
820 	 * Also, if the entry belong to uaddr_exe or uaddr_brk_stack, it is
821 	 * considered unavailable unless called by those allocators.
822 	 */
823 	i = *start_ptr;
824 	i_end = RBT_NEXT(uvm_map_addr, *end_ptr);
825 	for (; i != i_end;
826 	    i = RBT_NEXT(uvm_map_addr, i)) {
827 		if (i->start != i->end && i->end > addr)
828 			return 0;
829 
830 		/*
831 		 * uaddr_exe and uaddr_brk_stack may only be used
832 		 * by these allocators and the NULL uaddr (i.e. no
833 		 * uaddr).
834 		 * Reject if this requirement is not met.
835 		 */
836 		if (uaddr != NULL) {
837 			free = uvm_map_uaddr_e(map, i);
838 
839 			if (uaddr != free && free != NULL &&
840 			    (free == map->uaddr_exe ||
841 			     free == map->uaddr_brk_stack))
842 				return 0;
843 		}
844 	}
845 
846 	return -1;
847 }
848 
849 /*
850  * Invoke each address selector until an address is found.
851  * Will not invoke uaddr_exe.
852  */
853 int
854 uvm_map_findspace(struct vm_map *map, struct vm_map_entry**first,
855     struct vm_map_entry**last, vaddr_t *addr, vsize_t sz,
856     vaddr_t pmap_align, vaddr_t pmap_offset, vm_prot_t prot, vaddr_t hint)
857 {
858 	struct uvm_addr_state *uaddr;
859 	int i;
860 
861 	/*
862 	 * Allocation for sz bytes at any address,
863 	 * using the addr selectors in order.
864 	 */
865 	for (i = 0; i < nitems(map->uaddr_any); i++) {
866 		uaddr = map->uaddr_any[i];
867 
868 		if (uvm_addr_invoke(map, uaddr, first, last,
869 		    addr, sz, pmap_align, pmap_offset, prot, hint) == 0)
870 			return 0;
871 	}
872 
873 	/* Fall back to brk() and stack() address selectors. */
874 	uaddr = map->uaddr_brk_stack;
875 	if (uvm_addr_invoke(map, uaddr, first, last,
876 	    addr, sz, pmap_align, pmap_offset, prot, hint) == 0)
877 		return 0;
878 
879 	return ENOMEM;
880 }
881 
882 /* Calculate entry augmentation value. */
883 vsize_t
884 uvm_map_addr_augment_get(struct vm_map_entry *entry)
885 {
886 	vsize_t			 augment;
887 	struct vm_map_entry	*left, *right;
888 
889 	augment = entry->fspace;
890 	if ((left = RBT_LEFT(uvm_map_addr, entry)) != NULL)
891 		augment = MAX(augment, left->fspace_augment);
892 	if ((right = RBT_RIGHT(uvm_map_addr, entry)) != NULL)
893 		augment = MAX(augment, right->fspace_augment);
894 	return augment;
895 }
896 
897 /*
898  * Update augmentation data in entry.
899  */
900 void
901 uvm_map_addr_augment(struct vm_map_entry *entry)
902 {
903 	vsize_t			 augment;
904 
905 	while (entry != NULL) {
906 		/* Calculate value for augmentation. */
907 		augment = uvm_map_addr_augment_get(entry);
908 
909 		/*
910 		 * Descend update.
911 		 * Once we find an entry that already has the correct value,
912 		 * stop, since it means all its parents will use the correct
913 		 * value too.
914 		 */
915 		if (entry->fspace_augment == augment)
916 			return;
917 		entry->fspace_augment = augment;
918 		entry = RBT_PARENT(uvm_map_addr, entry);
919 	}
920 }
921 
922 /*
923  * uvm_mapanon: establish a valid mapping in map for an anon
924  *
925  * => *addr and sz must be a multiple of PAGE_SIZE.
926  * => *addr is ignored, except if flags contains UVM_FLAG_FIXED.
927  * => map must be unlocked.
928  *
929  * => align: align vaddr, must be a power-of-2.
930  *    Align is only a hint and will be ignored if the alignment fails.
931  */
932 int
933 uvm_mapanon(struct vm_map *map, vaddr_t *addr, vsize_t sz,
934     vsize_t align, unsigned int flags)
935 {
936 	struct vm_map_entry	*first, *last, *entry, *new;
937 	struct uvm_map_deadq	 dead;
938 	vm_prot_t		 prot;
939 	vm_prot_t		 maxprot;
940 	vm_inherit_t		 inherit;
941 	int			 advice;
942 	int			 error;
943 	vaddr_t			 pmap_align, pmap_offset;
944 	vaddr_t			 hint;
945 
946 	KASSERT((map->flags & VM_MAP_ISVMSPACE) == VM_MAP_ISVMSPACE);
947 	KASSERT(map != kernel_map);
948 	KASSERT((map->flags & UVM_FLAG_HOLE) == 0);
949 
950 	KASSERT((map->flags & VM_MAP_INTRSAFE) == 0);
951 	splassert(IPL_NONE);
952 
953 	/*
954 	 * We use pmap_align and pmap_offset as alignment and offset variables.
955 	 *
956 	 * Because the align parameter takes precedence over pmap prefer,
957 	 * the pmap_align will need to be set to align, with pmap_offset = 0,
958 	 * if pmap_prefer will not align.
959 	 */
960 	pmap_align = MAX(align, PAGE_SIZE);
961 	pmap_offset = 0;
962 
963 	/* Decode parameters. */
964 	prot = UVM_PROTECTION(flags);
965 	maxprot = UVM_MAXPROTECTION(flags);
966 	advice = UVM_ADVICE(flags);
967 	inherit = UVM_INHERIT(flags);
968 	error = 0;
969 	hint = trunc_page(*addr);
970 	TAILQ_INIT(&dead);
971 	KASSERT((sz & (vaddr_t)PAGE_MASK) == 0);
972 	KASSERT((align & (align - 1)) == 0);
973 
974 	/* Check protection. */
975 	if ((prot & maxprot) != prot)
976 		return EACCES;
977 
978 	/*
979 	 * Before grabbing the lock, allocate a map entry for later
980 	 * use to ensure we don't wait for memory while holding the
981 	 * vm_map_lock.
982 	 */
983 	new = uvm_mapent_alloc(map, flags);
984 	if (new == NULL)
985 		return(ENOMEM);
986 
987 	if (flags & UVM_FLAG_TRYLOCK) {
988 		if (vm_map_lock_try(map) == FALSE) {
989 			error = EFAULT;
990 			goto out;
991 		}
992 	} else
993 		vm_map_lock(map);
994 
995 	first = last = NULL;
996 	if (flags & UVM_FLAG_FIXED) {
997 		/*
998 		 * Fixed location.
999 		 *
1000 		 * Note: we ignore align, pmap_prefer.
1001 		 * Fill in first, last and *addr.
1002 		 */
1003 		KASSERT((*addr & PAGE_MASK) == 0);
1004 
1005 		/* Check that the space is available. */
1006 		if (flags & UVM_FLAG_UNMAP) {
1007 			if ((flags & UVM_FLAG_STACK) &&
1008 			    !uvm_map_is_stack_remappable(map, *addr, sz)) {
1009 				error = EINVAL;
1010 				goto unlock;
1011 			}
1012 			uvm_unmap_remove(map, *addr, *addr + sz, &dead, FALSE, TRUE);
1013 		}
1014 		if (!uvm_map_isavail(map, NULL, &first, &last, *addr, sz)) {
1015 			error = ENOMEM;
1016 			goto unlock;
1017 		}
1018 	} else if (*addr != 0 && (*addr & PAGE_MASK) == 0 &&
1019 	    (align == 0 || (*addr & (align - 1)) == 0) &&
1020 	    uvm_map_isavail(map, NULL, &first, &last, *addr, sz)) {
1021 		/*
1022 		 * Address used as hint.
1023 		 *
1024 		 * Note: we enforce the alignment restriction,
1025 		 * but ignore pmap_prefer.
1026 		 */
1027 	} else if ((prot & PROT_EXEC) != 0 && map->uaddr_exe != NULL) {
1028 		/* Run selection algorithm for executables. */
1029 		error = uvm_addr_invoke(map, map->uaddr_exe, &first, &last,
1030 		    addr, sz, pmap_align, pmap_offset, prot, hint);
1031 
1032 		if (error != 0)
1033 			goto unlock;
1034 	} else {
1035 		/* Update freelists from vmspace. */
1036 		uvm_map_vmspace_update(map, &dead, flags);
1037 
1038 		error = uvm_map_findspace(map, &first, &last, addr, sz,
1039 		    pmap_align, pmap_offset, prot, hint);
1040 
1041 		if (error != 0)
1042 			goto unlock;
1043 	}
1044 
1045 	/* Double-check if selected address doesn't cause overflow. */
1046 	if (*addr + sz < *addr) {
1047 		error = ENOMEM;
1048 		goto unlock;
1049 	}
1050 
1051 	/* If we only want a query, return now. */
1052 	if (flags & UVM_FLAG_QUERY) {
1053 		error = 0;
1054 		goto unlock;
1055 	}
1056 
1057 	/*
1058 	 * Create new entry.
1059 	 * first and last may be invalidated after this call.
1060 	 */
1061 	entry = uvm_map_mkentry(map, first, last, *addr, sz, flags, &dead,
1062 	    new);
1063 	if (entry == NULL) {
1064 		error = ENOMEM;
1065 		goto unlock;
1066 	}
1067 	new = NULL;
1068 	KDASSERT(entry->start == *addr && entry->end == *addr + sz);
1069 	entry->object.uvm_obj = NULL;
1070 	entry->offset = 0;
1071 	entry->protection = prot;
1072 	entry->max_protection = maxprot;
1073 	entry->inheritance = inherit;
1074 	entry->wired_count = 0;
1075 	entry->advice = advice;
1076 	if (prot & PROT_WRITE)
1077 		map->wserial++;
1078 	if (flags & UVM_FLAG_STACK) {
1079 		entry->etype |= UVM_ET_STACK;
1080 		if (flags & (UVM_FLAG_FIXED | UVM_FLAG_UNMAP))
1081 			map->sserial++;
1082 	}
1083 	if (flags & UVM_FLAG_COPYONW) {
1084 		entry->etype |= UVM_ET_COPYONWRITE;
1085 		if ((flags & UVM_FLAG_OVERLAY) == 0)
1086 			entry->etype |= UVM_ET_NEEDSCOPY;
1087 	}
1088 	if (flags & UVM_FLAG_CONCEAL)
1089 		entry->etype |= UVM_ET_CONCEAL;
1090 	if (flags & UVM_FLAG_OVERLAY) {
1091 		KERNEL_LOCK();
1092 		entry->aref.ar_pageoff = 0;
1093 		entry->aref.ar_amap = amap_alloc(sz, M_WAITOK, 0);
1094 		KERNEL_UNLOCK();
1095 	}
1096 
1097 	/* Update map and process statistics. */
1098 	map->size += sz;
1099 	((struct vmspace *)map)->vm_dused += uvmspace_dused(map, *addr, *addr + sz);
1100 
1101 unlock:
1102 	vm_map_unlock(map);
1103 
1104 	/*
1105 	 * Remove dead entries.
1106 	 *
1107 	 * Dead entries may be the result of merging.
1108 	 * uvm_map_mkentry may also create dead entries, when it attempts to
1109 	 * destroy free-space entries.
1110 	 */
1111 	uvm_unmap_detach(&dead, 0);
1112 out:
1113 	if (new)
1114 		uvm_mapent_free(new);
1115 	return error;
1116 }
1117 
1118 /*
1119  * uvm_map: establish a valid mapping in map
1120  *
1121  * => *addr and sz must be a multiple of PAGE_SIZE.
1122  * => map must be unlocked.
1123  * => <uobj,uoffset> value meanings (4 cases):
1124  *	[1] <NULL,uoffset>		== uoffset is a hint for PMAP_PREFER
1125  *	[2] <NULL,UVM_UNKNOWN_OFFSET>	== don't PMAP_PREFER
1126  *	[3] <uobj,uoffset>		== normal mapping
1127  *	[4] <uobj,UVM_UNKNOWN_OFFSET>	== uvm_map finds offset based on VA
1128  *
1129  *   case [4] is for kernel mappings where we don't know the offset until
1130  *   we've found a virtual address.   note that kernel object offsets are
1131  *   always relative to vm_map_min(kernel_map).
1132  *
1133  * => align: align vaddr, must be a power-of-2.
1134  *    Align is only a hint and will be ignored if the alignment fails.
1135  */
1136 int
1137 uvm_map(struct vm_map *map, vaddr_t *addr, vsize_t sz,
1138     struct uvm_object *uobj, voff_t uoffset,
1139     vsize_t align, unsigned int flags)
1140 {
1141 	struct vm_map_entry	*first, *last, *entry, *new;
1142 	struct uvm_map_deadq	 dead;
1143 	vm_prot_t		 prot;
1144 	vm_prot_t		 maxprot;
1145 	vm_inherit_t		 inherit;
1146 	int			 advice;
1147 	int			 error;
1148 	vaddr_t			 pmap_align, pmap_offset;
1149 	vaddr_t			 hint;
1150 
1151 	if ((map->flags & VM_MAP_INTRSAFE) == 0)
1152 		splassert(IPL_NONE);
1153 	else
1154 		splassert(IPL_VM);
1155 
1156 	/*
1157 	 * We use pmap_align and pmap_offset as alignment and offset variables.
1158 	 *
1159 	 * Because the align parameter takes precedence over pmap prefer,
1160 	 * the pmap_align will need to be set to align, with pmap_offset = 0,
1161 	 * if pmap_prefer will not align.
1162 	 */
1163 	if (uoffset == UVM_UNKNOWN_OFFSET) {
1164 		pmap_align = MAX(align, PAGE_SIZE);
1165 		pmap_offset = 0;
1166 	} else {
1167 		pmap_align = MAX(PMAP_PREFER_ALIGN(), PAGE_SIZE);
1168 		pmap_offset = PMAP_PREFER_OFFSET(uoffset);
1169 
1170 		if (align == 0 ||
1171 		    (align <= pmap_align && (pmap_offset & (align - 1)) == 0)) {
1172 			/* pmap_offset satisfies align, no change. */
1173 		} else {
1174 			/* Align takes precedence over pmap prefer. */
1175 			pmap_align = align;
1176 			pmap_offset = 0;
1177 		}
1178 	}
1179 
1180 	/* Decode parameters. */
1181 	prot = UVM_PROTECTION(flags);
1182 	maxprot = UVM_MAXPROTECTION(flags);
1183 	advice = UVM_ADVICE(flags);
1184 	inherit = UVM_INHERIT(flags);
1185 	error = 0;
1186 	hint = trunc_page(*addr);
1187 	TAILQ_INIT(&dead);
1188 	KASSERT((sz & (vaddr_t)PAGE_MASK) == 0);
1189 	KASSERT((align & (align - 1)) == 0);
1190 
1191 	/* Holes are incompatible with other types of mappings. */
1192 	if (flags & UVM_FLAG_HOLE) {
1193 		KASSERT(uobj == NULL && (flags & UVM_FLAG_FIXED) &&
1194 		    (flags & (UVM_FLAG_OVERLAY | UVM_FLAG_COPYONW)) == 0);
1195 	}
1196 
1197 	/* Unset hint for kernel_map non-fixed allocations. */
1198 	if (!(map->flags & VM_MAP_ISVMSPACE) && !(flags & UVM_FLAG_FIXED))
1199 		hint = 0;
1200 
1201 	/* Check protection. */
1202 	if ((prot & maxprot) != prot)
1203 		return EACCES;
1204 
1205 	if (map == kernel_map &&
1206 	    (prot & (PROT_WRITE | PROT_EXEC)) == (PROT_WRITE | PROT_EXEC))
1207 		panic("uvm_map: kernel map W^X violation requested");
1208 
1209 	/*
1210 	 * Before grabbing the lock, allocate a map entry for later
1211 	 * use to ensure we don't wait for memory while holding the
1212 	 * vm_map_lock.
1213 	 */
1214 	new = uvm_mapent_alloc(map, flags);
1215 	if (new == NULL)
1216 		return(ENOMEM);
1217 
1218 	if (flags & UVM_FLAG_TRYLOCK) {
1219 		if (vm_map_lock_try(map) == FALSE) {
1220 			error = EFAULT;
1221 			goto out;
1222 		}
1223 	} else {
1224 		vm_map_lock(map);
1225 	}
1226 
1227 	first = last = NULL;
1228 	if (flags & UVM_FLAG_FIXED) {
1229 		/*
1230 		 * Fixed location.
1231 		 *
1232 		 * Note: we ignore align, pmap_prefer.
1233 		 * Fill in first, last and *addr.
1234 		 */
1235 		KASSERT((*addr & PAGE_MASK) == 0);
1236 
1237 		/*
1238 		 * Grow pmap to include allocated address.
1239 		 * If the growth fails, the allocation will fail too.
1240 		 */
1241 		if ((map->flags & VM_MAP_ISVMSPACE) == 0 &&
1242 		    uvm_maxkaddr < (*addr + sz)) {
1243 			uvm_map_kmem_grow(map, &dead,
1244 			    *addr + sz - uvm_maxkaddr, flags);
1245 		}
1246 
1247 		/* Check that the space is available. */
1248 		if (flags & UVM_FLAG_UNMAP)
1249 			uvm_unmap_remove(map, *addr, *addr + sz, &dead, FALSE, TRUE);
1250 		if (!uvm_map_isavail(map, NULL, &first, &last, *addr, sz)) {
1251 			error = ENOMEM;
1252 			goto unlock;
1253 		}
1254 	} else if (*addr != 0 && (*addr & PAGE_MASK) == 0 &&
1255 	    (map->flags & VM_MAP_ISVMSPACE) == VM_MAP_ISVMSPACE &&
1256 	    (align == 0 || (*addr & (align - 1)) == 0) &&
1257 	    uvm_map_isavail(map, NULL, &first, &last, *addr, sz)) {
1258 		/*
1259 		 * Address used as hint.
1260 		 *
1261 		 * Note: we enforce the alignment restriction,
1262 		 * but ignore pmap_prefer.
1263 		 */
1264 	} else if ((prot & PROT_EXEC) != 0 && map->uaddr_exe != NULL) {
1265 		/* Run selection algorithm for executables. */
1266 		error = uvm_addr_invoke(map, map->uaddr_exe, &first, &last,
1267 		    addr, sz, pmap_align, pmap_offset, prot, hint);
1268 
1269 		/* Grow kernel memory and try again. */
1270 		if (error != 0 && (map->flags & VM_MAP_ISVMSPACE) == 0) {
1271 			uvm_map_kmem_grow(map, &dead, sz, flags);
1272 
1273 			error = uvm_addr_invoke(map, map->uaddr_exe,
1274 			    &first, &last, addr, sz,
1275 			    pmap_align, pmap_offset, prot, hint);
1276 		}
1277 
1278 		if (error != 0)
1279 			goto unlock;
1280 	} else {
1281 		/* Update freelists from vmspace. */
1282 		if (map->flags & VM_MAP_ISVMSPACE)
1283 			uvm_map_vmspace_update(map, &dead, flags);
1284 
1285 		error = uvm_map_findspace(map, &first, &last, addr, sz,
1286 		    pmap_align, pmap_offset, prot, hint);
1287 
1288 		/* Grow kernel memory and try again. */
1289 		if (error != 0 && (map->flags & VM_MAP_ISVMSPACE) == 0) {
1290 			uvm_map_kmem_grow(map, &dead, sz, flags);
1291 
1292 			error = uvm_map_findspace(map, &first, &last, addr, sz,
1293 			    pmap_align, pmap_offset, prot, hint);
1294 		}
1295 
1296 		if (error != 0)
1297 			goto unlock;
1298 	}
1299 
1300 	/* Double-check if selected address doesn't cause overflow. */
1301 	if (*addr + sz < *addr) {
1302 		error = ENOMEM;
1303 		goto unlock;
1304 	}
1305 
1306 	KASSERT((map->flags & VM_MAP_ISVMSPACE) == VM_MAP_ISVMSPACE ||
1307 	    uvm_maxkaddr >= *addr + sz);
1308 
1309 	/* If we only want a query, return now. */
1310 	if (flags & UVM_FLAG_QUERY) {
1311 		error = 0;
1312 		goto unlock;
1313 	}
1314 
1315 	if (uobj == NULL)
1316 		uoffset = 0;
1317 	else if (uoffset == UVM_UNKNOWN_OFFSET) {
1318 		KASSERT(UVM_OBJ_IS_KERN_OBJECT(uobj));
1319 		uoffset = *addr - vm_map_min(kernel_map);
1320 	}
1321 
1322 	/*
1323 	 * Create new entry.
1324 	 * first and last may be invalidated after this call.
1325 	 */
1326 	entry = uvm_map_mkentry(map, first, last, *addr, sz, flags, &dead,
1327 	    new);
1328 	if (entry == NULL) {
1329 		error = ENOMEM;
1330 		goto unlock;
1331 	}
1332 	new = NULL;
1333 	KDASSERT(entry->start == *addr && entry->end == *addr + sz);
1334 	entry->object.uvm_obj = uobj;
1335 	entry->offset = uoffset;
1336 	entry->protection = prot;
1337 	entry->max_protection = maxprot;
1338 	entry->inheritance = inherit;
1339 	entry->wired_count = 0;
1340 	entry->advice = advice;
1341 	if (prot & PROT_WRITE)
1342 		map->wserial++;
1343 	if (flags & UVM_FLAG_STACK) {
1344 		entry->etype |= UVM_ET_STACK;
1345 		if (flags & UVM_FLAG_UNMAP)
1346 			map->sserial++;
1347 	}
1348 	if (uobj)
1349 		entry->etype |= UVM_ET_OBJ;
1350 	else if (flags & UVM_FLAG_HOLE)
1351 		entry->etype |= UVM_ET_HOLE;
1352 	if (flags & UVM_FLAG_NOFAULT)
1353 		entry->etype |= UVM_ET_NOFAULT;
1354 	if (flags & UVM_FLAG_WC)
1355 		entry->etype |= UVM_ET_WC;
1356 	if (flags & UVM_FLAG_COPYONW) {
1357 		entry->etype |= UVM_ET_COPYONWRITE;
1358 		if ((flags & UVM_FLAG_OVERLAY) == 0)
1359 			entry->etype |= UVM_ET_NEEDSCOPY;
1360 	}
1361 	if (flags & UVM_FLAG_CONCEAL)
1362 		entry->etype |= UVM_ET_CONCEAL;
1363 	if (flags & UVM_FLAG_OVERLAY) {
1364 		entry->aref.ar_pageoff = 0;
1365 		entry->aref.ar_amap = amap_alloc(sz, M_WAITOK, 0);
1366 	}
1367 
1368 	/* Update map and process statistics. */
1369 	if (!(flags & UVM_FLAG_HOLE)) {
1370 		map->size += sz;
1371 		if ((map->flags & VM_MAP_ISVMSPACE) && uobj == NULL) {
1372 			((struct vmspace *)map)->vm_dused +=
1373 			    uvmspace_dused(map, *addr, *addr + sz);
1374 		}
1375 	}
1376 
1377 	/*
1378 	 * Try to merge entry.
1379 	 *
1380 	 * Userland allocations are kept separated most of the time.
1381 	 * Forego the effort of merging what most of the time can't be merged
1382 	 * and only try the merge if it concerns a kernel entry.
1383 	 */
1384 	if ((flags & UVM_FLAG_NOMERGE) == 0 &&
1385 	    (map->flags & VM_MAP_ISVMSPACE) == 0)
1386 		uvm_mapent_tryjoin(map, entry, &dead);
1387 
1388 unlock:
1389 	vm_map_unlock(map);
1390 
1391 	/*
1392 	 * Remove dead entries.
1393 	 *
1394 	 * Dead entries may be the result of merging.
1395 	 * uvm_map_mkentry may also create dead entries, when it attempts to
1396 	 * destroy free-space entries.
1397 	 */
1398 	if (map->flags & VM_MAP_INTRSAFE)
1399 		uvm_unmap_detach_intrsafe(&dead);
1400 	else
1401 		uvm_unmap_detach(&dead, 0);
1402 out:
1403 	if (new)
1404 		uvm_mapent_free(new);
1405 	return error;
1406 }
1407 
1408 /*
1409  * True iff e1 and e2 can be joined together.
1410  */
1411 int
1412 uvm_mapent_isjoinable(struct vm_map *map, struct vm_map_entry *e1,
1413     struct vm_map_entry *e2)
1414 {
1415 	KDASSERT(e1 != NULL && e2 != NULL);
1416 
1417 	/* Must be the same entry type and not have free memory between. */
1418 	if (e1->etype != e2->etype || e1->end != e2->start)
1419 		return 0;
1420 
1421 	/* Submaps are never joined. */
1422 	if (UVM_ET_ISSUBMAP(e1))
1423 		return 0;
1424 
1425 	/* Never merge wired memory. */
1426 	if (VM_MAPENT_ISWIRED(e1) || VM_MAPENT_ISWIRED(e2))
1427 		return 0;
1428 
1429 	/* Protection, inheritance and advice must be equal. */
1430 	if (e1->protection != e2->protection ||
1431 	    e1->max_protection != e2->max_protection ||
1432 	    e1->inheritance != e2->inheritance ||
1433 	    e1->advice != e2->advice)
1434 		return 0;
1435 
1436 	/* If uvm_object: object itself and offsets within object must match. */
1437 	if (UVM_ET_ISOBJ(e1)) {
1438 		if (e1->object.uvm_obj != e2->object.uvm_obj)
1439 			return 0;
1440 		if (e1->offset + (e1->end - e1->start) != e2->offset)
1441 			return 0;
1442 	}
1443 
1444 	/*
1445 	 * Cannot join shared amaps.
1446 	 * Note: no need to lock amap to look at refs, since we don't care
1447 	 * about its exact value.
1448 	 * If it is 1 (i.e. we have the only reference) it will stay there.
1449 	 */
1450 	if (e1->aref.ar_amap && amap_refs(e1->aref.ar_amap) != 1)
1451 		return 0;
1452 	if (e2->aref.ar_amap && amap_refs(e2->aref.ar_amap) != 1)
1453 		return 0;
1454 
1455 	/* Apprently, e1 and e2 match. */
1456 	return 1;
1457 }
1458 
1459 /*
1460  * Join support function.
1461  *
1462  * Returns the merged entry on succes.
1463  * Returns NULL if the merge failed.
1464  */
1465 struct vm_map_entry*
1466 uvm_mapent_merge(struct vm_map *map, struct vm_map_entry *e1,
1467     struct vm_map_entry *e2, struct uvm_map_deadq *dead)
1468 {
1469 	struct uvm_addr_state *free;
1470 
1471 	/*
1472 	 * Merging is not supported for map entries that
1473 	 * contain an amap in e1. This should never happen
1474 	 * anyway, because only kernel entries are merged.
1475 	 * These do not contain amaps.
1476 	 * e2 contains no real information in its amap,
1477 	 * so it can be erased immediately.
1478 	 */
1479 	KASSERT(e1->aref.ar_amap == NULL);
1480 
1481 	/*
1482 	 * Don't drop obj reference:
1483 	 * uvm_unmap_detach will do this for us.
1484 	 */
1485 	free = uvm_map_uaddr_e(map, e1);
1486 	uvm_mapent_free_remove(map, free, e1);
1487 
1488 	free = uvm_map_uaddr_e(map, e2);
1489 	uvm_mapent_free_remove(map, free, e2);
1490 	uvm_mapent_addr_remove(map, e2);
1491 	e1->end = e2->end;
1492 	e1->guard = e2->guard;
1493 	e1->fspace = e2->fspace;
1494 	uvm_mapent_free_insert(map, free, e1);
1495 
1496 	DEAD_ENTRY_PUSH(dead, e2);
1497 	return e1;
1498 }
1499 
1500 /*
1501  * Attempt forward and backward joining of entry.
1502  *
1503  * Returns entry after joins.
1504  * We are guaranteed that the amap of entry is either non-existent or
1505  * has never been used.
1506  */
1507 struct vm_map_entry*
1508 uvm_mapent_tryjoin(struct vm_map *map, struct vm_map_entry *entry,
1509     struct uvm_map_deadq *dead)
1510 {
1511 	struct vm_map_entry *other;
1512 	struct vm_map_entry *merged;
1513 
1514 	/* Merge with previous entry. */
1515 	other = RBT_PREV(uvm_map_addr, entry);
1516 	if (other && uvm_mapent_isjoinable(map, other, entry)) {
1517 		merged = uvm_mapent_merge(map, other, entry, dead);
1518 		if (merged)
1519 			entry = merged;
1520 	}
1521 
1522 	/*
1523 	 * Merge with next entry.
1524 	 *
1525 	 * Because amap can only extend forward and the next entry
1526 	 * probably contains sensible info, only perform forward merging
1527 	 * in the absence of an amap.
1528 	 */
1529 	other = RBT_NEXT(uvm_map_addr, entry);
1530 	if (other && entry->aref.ar_amap == NULL &&
1531 	    other->aref.ar_amap == NULL &&
1532 	    uvm_mapent_isjoinable(map, entry, other)) {
1533 		merged = uvm_mapent_merge(map, entry, other, dead);
1534 		if (merged)
1535 			entry = merged;
1536 	}
1537 
1538 	return entry;
1539 }
1540 
1541 /*
1542  * Kill entries that are no longer in a map.
1543  */
1544 void
1545 uvm_unmap_detach(struct uvm_map_deadq *deadq, int flags)
1546 {
1547 	struct vm_map_entry *entry, *tmp;
1548 	int waitok = flags & UVM_PLA_WAITOK;
1549 
1550 	TAILQ_FOREACH_SAFE(entry, deadq, dfree.deadq, tmp) {
1551 		/* Skip entries for which we have to grab the kernel lock. */
1552 		if (entry->aref.ar_amap || UVM_ET_ISSUBMAP(entry) ||
1553 		    UVM_ET_ISOBJ(entry))
1554 			continue;
1555 
1556 		TAILQ_REMOVE(deadq, entry, dfree.deadq);
1557 		uvm_mapent_free(entry);
1558 	}
1559 
1560 	if (TAILQ_EMPTY(deadq))
1561 		return;
1562 
1563 	KERNEL_LOCK();
1564 	while ((entry = TAILQ_FIRST(deadq)) != NULL) {
1565 		if (waitok)
1566 			uvm_pause();
1567 		/* Drop reference to amap, if we've got one. */
1568 		if (entry->aref.ar_amap)
1569 			amap_unref(entry->aref.ar_amap,
1570 			    entry->aref.ar_pageoff,
1571 			    atop(entry->end - entry->start),
1572 			    flags & AMAP_REFALL);
1573 
1574 		/* Drop reference to our backing object, if we've got one. */
1575 		if (UVM_ET_ISSUBMAP(entry)) {
1576 			/* ... unlikely to happen, but play it safe */
1577 			uvm_map_deallocate(entry->object.sub_map);
1578 		} else if (UVM_ET_ISOBJ(entry) &&
1579 		    entry->object.uvm_obj->pgops->pgo_detach) {
1580 			entry->object.uvm_obj->pgops->pgo_detach(
1581 			    entry->object.uvm_obj);
1582 		}
1583 
1584 		/* Step to next. */
1585 		TAILQ_REMOVE(deadq, entry, dfree.deadq);
1586 		uvm_mapent_free(entry);
1587 	}
1588 	KERNEL_UNLOCK();
1589 }
1590 
1591 void
1592 uvm_unmap_detach_intrsafe(struct uvm_map_deadq *deadq)
1593 {
1594 	struct vm_map_entry *entry;
1595 
1596 	while ((entry = TAILQ_FIRST(deadq)) != NULL) {
1597 		KASSERT(entry->aref.ar_amap == NULL);
1598 		KASSERT(!UVM_ET_ISSUBMAP(entry));
1599 		KASSERT(!UVM_ET_ISOBJ(entry));
1600 		TAILQ_REMOVE(deadq, entry, dfree.deadq);
1601 		uvm_mapent_free(entry);
1602 	}
1603 }
1604 
1605 /*
1606  * Create and insert new entry.
1607  *
1608  * Returned entry contains new addresses and is inserted properly in the tree.
1609  * first and last are (probably) no longer valid.
1610  */
1611 struct vm_map_entry*
1612 uvm_map_mkentry(struct vm_map *map, struct vm_map_entry *first,
1613     struct vm_map_entry *last, vaddr_t addr, vsize_t sz, int flags,
1614     struct uvm_map_deadq *dead, struct vm_map_entry *new)
1615 {
1616 	struct vm_map_entry *entry, *prev;
1617 	struct uvm_addr_state *free;
1618 	vaddr_t min, max;	/* free space boundaries for new entry */
1619 
1620 	KDASSERT(map != NULL);
1621 	KDASSERT(first != NULL);
1622 	KDASSERT(last != NULL);
1623 	KDASSERT(dead != NULL);
1624 	KDASSERT(sz > 0);
1625 	KDASSERT(addr + sz > addr);
1626 	KDASSERT(first->end <= addr && VMMAP_FREE_END(first) > addr);
1627 	KDASSERT(last->start < addr + sz && VMMAP_FREE_END(last) >= addr + sz);
1628 	KDASSERT(uvm_map_isavail(map, NULL, &first, &last, addr, sz));
1629 	uvm_tree_sanity(map, __FILE__, __LINE__);
1630 
1631 	min = addr + sz;
1632 	max = VMMAP_FREE_END(last);
1633 
1634 	/* Initialize new entry. */
1635 	if (new == NULL)
1636 		entry = uvm_mapent_alloc(map, flags);
1637 	else
1638 		entry = new;
1639 	if (entry == NULL)
1640 		return NULL;
1641 	entry->offset = 0;
1642 	entry->etype = 0;
1643 	entry->wired_count = 0;
1644 	entry->aref.ar_pageoff = 0;
1645 	entry->aref.ar_amap = NULL;
1646 
1647 	entry->start = addr;
1648 	entry->end = min;
1649 	entry->guard = 0;
1650 	entry->fspace = 0;
1651 
1652 	/* Reset free space in first. */
1653 	free = uvm_map_uaddr_e(map, first);
1654 	uvm_mapent_free_remove(map, free, first);
1655 	first->guard = 0;
1656 	first->fspace = 0;
1657 
1658 	/*
1659 	 * Remove all entries that are fully replaced.
1660 	 * We are iterating using last in reverse order.
1661 	 */
1662 	for (; first != last; last = prev) {
1663 		prev = RBT_PREV(uvm_map_addr, last);
1664 
1665 		KDASSERT(last->start == last->end);
1666 		free = uvm_map_uaddr_e(map, last);
1667 		uvm_mapent_free_remove(map, free, last);
1668 		uvm_mapent_addr_remove(map, last);
1669 		DEAD_ENTRY_PUSH(dead, last);
1670 	}
1671 	/* Remove first if it is entirely inside <addr, addr+sz>.  */
1672 	if (first->start == addr) {
1673 		uvm_mapent_addr_remove(map, first);
1674 		DEAD_ENTRY_PUSH(dead, first);
1675 	} else {
1676 		uvm_map_fix_space(map, first, VMMAP_FREE_START(first),
1677 		    addr, flags);
1678 	}
1679 
1680 	/* Finally, link in entry. */
1681 	uvm_mapent_addr_insert(map, entry);
1682 	uvm_map_fix_space(map, entry, min, max, flags);
1683 
1684 	uvm_tree_sanity(map, __FILE__, __LINE__);
1685 	return entry;
1686 }
1687 
1688 
1689 /*
1690  * uvm_mapent_alloc: allocate a map entry
1691  */
1692 struct vm_map_entry *
1693 uvm_mapent_alloc(struct vm_map *map, int flags)
1694 {
1695 	struct vm_map_entry *me, *ne;
1696 	int pool_flags;
1697 	int i;
1698 
1699 	pool_flags = PR_WAITOK;
1700 	if (flags & UVM_FLAG_TRYLOCK)
1701 		pool_flags = PR_NOWAIT;
1702 
1703 	if (map->flags & VM_MAP_INTRSAFE || cold) {
1704 		mtx_enter(&uvm_kmapent_mtx);
1705 		if (SLIST_EMPTY(&uvm.kentry_free)) {
1706 			ne = km_alloc(PAGE_SIZE, &kv_page, &kp_dirty,
1707 			    &kd_nowait);
1708 			if (ne == NULL)
1709 				panic("uvm_mapent_alloc: cannot allocate map "
1710 				    "entry");
1711 			for (i = 0; i < PAGE_SIZE / sizeof(*ne); i++) {
1712 				SLIST_INSERT_HEAD(&uvm.kentry_free,
1713 				    &ne[i], daddrs.addr_kentry);
1714 			}
1715 			if (ratecheck(&uvm_kmapent_last_warn_time,
1716 			    &uvm_kmapent_warn_rate))
1717 				printf("uvm_mapent_alloc: out of static "
1718 				    "map entries\n");
1719 		}
1720 		me = SLIST_FIRST(&uvm.kentry_free);
1721 		SLIST_REMOVE_HEAD(&uvm.kentry_free, daddrs.addr_kentry);
1722 		uvmexp.kmapent++;
1723 		mtx_leave(&uvm_kmapent_mtx);
1724 		me->flags = UVM_MAP_STATIC;
1725 	} else if (map == kernel_map) {
1726 		splassert(IPL_NONE);
1727 		me = pool_get(&uvm_map_entry_kmem_pool, pool_flags);
1728 		if (me == NULL)
1729 			goto out;
1730 		me->flags = UVM_MAP_KMEM;
1731 	} else {
1732 		splassert(IPL_NONE);
1733 		me = pool_get(&uvm_map_entry_pool, pool_flags);
1734 		if (me == NULL)
1735 			goto out;
1736 		me->flags = 0;
1737 	}
1738 
1739 	if (me != NULL) {
1740 		RBT_POISON(uvm_map_addr, me, UVMMAP_DEADBEEF);
1741 	}
1742 
1743 out:
1744 	return(me);
1745 }
1746 
1747 /*
1748  * uvm_mapent_free: free map entry
1749  *
1750  * => XXX: static pool for kernel map?
1751  */
1752 void
1753 uvm_mapent_free(struct vm_map_entry *me)
1754 {
1755 	if (me->flags & UVM_MAP_STATIC) {
1756 		mtx_enter(&uvm_kmapent_mtx);
1757 		SLIST_INSERT_HEAD(&uvm.kentry_free, me, daddrs.addr_kentry);
1758 		uvmexp.kmapent--;
1759 		mtx_leave(&uvm_kmapent_mtx);
1760 	} else if (me->flags & UVM_MAP_KMEM) {
1761 		splassert(IPL_NONE);
1762 		pool_put(&uvm_map_entry_kmem_pool, me);
1763 	} else {
1764 		splassert(IPL_NONE);
1765 		pool_put(&uvm_map_entry_pool, me);
1766 	}
1767 }
1768 
1769 /*
1770  * uvm_map_lookup_entry: find map entry at or before an address.
1771  *
1772  * => map must at least be read-locked by caller
1773  * => entry is returned in "entry"
1774  * => return value is true if address is in the returned entry
1775  * ET_HOLE entries are considered to not contain a mapping, ergo FALSE is
1776  * returned for those mappings.
1777  */
1778 boolean_t
1779 uvm_map_lookup_entry(struct vm_map *map, vaddr_t address,
1780     struct vm_map_entry **entry)
1781 {
1782 	*entry = uvm_map_entrybyaddr(&map->addr, address);
1783 	return *entry != NULL && !UVM_ET_ISHOLE(*entry) &&
1784 	    (*entry)->start <= address && (*entry)->end > address;
1785 }
1786 
1787 /*
1788  * Stack must be in a MAP_STACK entry. PROT_NONE indicates stack not yet
1789  * grown -- then uvm_map_check_region_range() should not cache the entry
1790  * because growth won't be seen.
1791  */
1792 int
1793 uvm_map_inentry_sp(vm_map_entry_t entry)
1794 {
1795 	if ((entry->etype & UVM_ET_STACK) == 0) {
1796 		if (entry->protection == PROT_NONE)
1797 			return (-1);	/* don't update range */
1798 		return (0);
1799 	}
1800 	return (1);
1801 }
1802 
1803 /*
1804  * If a syscall comes from a writeable entry, W^X is violated.
1805  * (Would be nice if we can spot aliasing, which is also kind of bad)
1806  */
1807 int
1808 uvm_map_inentry_pc(vm_map_entry_t entry)
1809 {
1810 	if (entry->protection & PROT_WRITE)
1811 		return (0);	/* not permitted */
1812 	return (1);
1813 }
1814 
1815 int
1816 uvm_map_inentry_recheck(u_long serial, vaddr_t addr, struct p_inentry *ie)
1817 {
1818 	return (serial != ie->ie_serial || ie->ie_start == 0 ||
1819 	    addr < ie->ie_start || addr >= ie->ie_end);
1820 }
1821 
1822 /*
1823  * Inside a vm_map find the reg address and verify it via function.
1824  * Remember low and high addresses of region if valid and return TRUE,
1825  * else return FALSE.
1826  */
1827 boolean_t
1828 uvm_map_inentry_fix(struct proc *p, struct p_inentry *ie, vaddr_t addr,
1829     int (*fn)(vm_map_entry_t), u_long serial)
1830 {
1831 	vm_map_t map = &p->p_vmspace->vm_map;
1832 	vm_map_entry_t entry;
1833 	int ret;
1834 
1835 	if (addr < map->min_offset || addr >= map->max_offset)
1836 		return (FALSE);
1837 
1838 	/* lock map */
1839 	vm_map_lock_read(map);
1840 
1841 	/* lookup */
1842 	if (!uvm_map_lookup_entry(map, trunc_page(addr), &entry)) {
1843 		vm_map_unlock_read(map);
1844 		return (FALSE);
1845 	}
1846 
1847 	ret = (*fn)(entry);
1848 	if (ret == 0) {
1849 		vm_map_unlock_read(map);
1850 		return (FALSE);
1851 	} else if (ret == 1) {
1852 		ie->ie_start = entry->start;
1853 		ie->ie_end = entry->end;
1854 		ie->ie_serial = serial;
1855 	} else {
1856 		/* do not update, re-check later */
1857 	}
1858 	vm_map_unlock_read(map);
1859 	return (TRUE);
1860 }
1861 
1862 boolean_t
1863 uvm_map_inentry(struct proc *p, struct p_inentry *ie, vaddr_t addr,
1864     const char *fmt, int (*fn)(vm_map_entry_t), u_long serial)
1865 {
1866 	union sigval sv;
1867 	boolean_t ok = TRUE;
1868 
1869 	if (uvm_map_inentry_recheck(serial, addr, ie)) {
1870 		KERNEL_LOCK();
1871 		ok = uvm_map_inentry_fix(p, ie, addr, fn, serial);
1872 		if (!ok) {
1873 			printf(fmt, p->p_p->ps_comm, p->p_p->ps_pid, p->p_tid,
1874 			    addr, ie->ie_start, ie->ie_end);
1875 			sv.sival_ptr = (void *)PROC_PC(p);
1876 			trapsignal(p, SIGSEGV, 0, SEGV_ACCERR, sv);
1877 		}
1878 		KERNEL_UNLOCK();
1879 	}
1880 	return (ok);
1881 }
1882 
1883 /*
1884  * Check whether the given address range can be converted to a MAP_STACK
1885  * mapping.
1886  *
1887  * Must be called with map locked.
1888  */
1889 boolean_t
1890 uvm_map_is_stack_remappable(struct vm_map *map, vaddr_t addr, vaddr_t sz)
1891 {
1892 	vaddr_t end = addr + sz;
1893 	struct vm_map_entry *first, *iter, *prev = NULL;
1894 
1895 	if (!uvm_map_lookup_entry(map, addr, &first)) {
1896 		printf("map stack 0x%lx-0x%lx of map %p failed: no mapping\n",
1897 		    addr, end, map);
1898 		return FALSE;
1899 	}
1900 
1901 	/*
1902 	 * Check that the address range exists and is contiguous.
1903 	 */
1904 	for (iter = first; iter != NULL && iter->start < end;
1905 	    prev = iter, iter = RBT_NEXT(uvm_map_addr, iter)) {
1906 		/*
1907 		 * Make sure that we do not have holes in the range.
1908 		 */
1909 #if 0
1910 		if (prev != NULL) {
1911 			printf("prev->start 0x%lx, prev->end 0x%lx, "
1912 			    "iter->start 0x%lx, iter->end 0x%lx\n",
1913 			    prev->start, prev->end, iter->start, iter->end);
1914 		}
1915 #endif
1916 
1917 		if (prev != NULL && prev->end != iter->start) {
1918 			printf("map stack 0x%lx-0x%lx of map %p failed: "
1919 			    "hole in range\n", addr, end, map);
1920 			return FALSE;
1921 		}
1922 		if (iter->start == iter->end || UVM_ET_ISHOLE(iter)) {
1923 			printf("map stack 0x%lx-0x%lx of map %p failed: "
1924 			    "hole in range\n", addr, end, map);
1925 			return FALSE;
1926 		}
1927 	}
1928 
1929 	return TRUE;
1930 }
1931 
1932 /*
1933  * Remap the middle-pages of an existing mapping as a stack range.
1934  * If there exists a previous contiguous mapping with the given range
1935  * [addr, addr + sz), with protection PROT_READ|PROT_WRITE, then the
1936  * mapping is dropped, and a new anon mapping is created and marked as
1937  * a stack.
1938  *
1939  * Must be called with map unlocked.
1940  */
1941 int
1942 uvm_map_remap_as_stack(struct proc *p, vaddr_t addr, vaddr_t sz)
1943 {
1944 	vm_map_t map = &p->p_vmspace->vm_map;
1945 	vaddr_t start, end;
1946 	int error;
1947 	int flags = UVM_MAPFLAG(PROT_READ | PROT_WRITE,
1948 	    PROT_READ | PROT_WRITE | PROT_EXEC,
1949 	    MAP_INHERIT_COPY, MADV_NORMAL,
1950 	    UVM_FLAG_STACK | UVM_FLAG_FIXED | UVM_FLAG_UNMAP |
1951 	    UVM_FLAG_COPYONW);
1952 
1953 	start = round_page(addr);
1954 	end = trunc_page(addr + sz);
1955 #ifdef MACHINE_STACK_GROWS_UP
1956 	if (end == addr + sz)
1957 		end -= PAGE_SIZE;
1958 #else
1959 	if (start == addr)
1960 		start += PAGE_SIZE;
1961 #endif
1962 
1963 	if (start < map->min_offset || end >= map->max_offset || end < start)
1964 		return EINVAL;
1965 
1966 	error = uvm_mapanon(map, &start, end - start, 0, flags);
1967 	if (error != 0)
1968 		printf("map stack for pid %d failed\n", p->p_p->ps_pid);
1969 
1970 	return error;
1971 }
1972 
1973 /*
1974  * uvm_map_pie: return a random load address for a PIE executable
1975  * properly aligned.
1976  */
1977 #ifndef VM_PIE_MAX_ADDR
1978 #define VM_PIE_MAX_ADDR (VM_MAXUSER_ADDRESS / 4)
1979 #endif
1980 
1981 #ifndef VM_PIE_MIN_ADDR
1982 #define VM_PIE_MIN_ADDR VM_MIN_ADDRESS
1983 #endif
1984 
1985 #ifndef VM_PIE_MIN_ALIGN
1986 #define VM_PIE_MIN_ALIGN PAGE_SIZE
1987 #endif
1988 
1989 vaddr_t
1990 uvm_map_pie(vaddr_t align)
1991 {
1992 	vaddr_t addr, space, min;
1993 
1994 	align = MAX(align, VM_PIE_MIN_ALIGN);
1995 
1996 	/* round up to next alignment */
1997 	min = (VM_PIE_MIN_ADDR + align - 1) & ~(align - 1);
1998 
1999 	if (align >= VM_PIE_MAX_ADDR || min >= VM_PIE_MAX_ADDR)
2000 		return (align);
2001 
2002 	space = (VM_PIE_MAX_ADDR - min) / align;
2003 	space = MIN(space, (u_int32_t)-1);
2004 
2005 	addr = (vaddr_t)arc4random_uniform((u_int32_t)space) * align;
2006 	addr += min;
2007 
2008 	return (addr);
2009 }
2010 
2011 void
2012 uvm_unmap(struct vm_map *map, vaddr_t start, vaddr_t end)
2013 {
2014 	struct uvm_map_deadq dead;
2015 
2016 	KASSERT((start & (vaddr_t)PAGE_MASK) == 0 &&
2017 	    (end & (vaddr_t)PAGE_MASK) == 0);
2018 	TAILQ_INIT(&dead);
2019 	vm_map_lock(map);
2020 	uvm_unmap_remove(map, start, end, &dead, FALSE, TRUE);
2021 	vm_map_unlock(map);
2022 
2023 	if (map->flags & VM_MAP_INTRSAFE)
2024 		uvm_unmap_detach_intrsafe(&dead);
2025 	else
2026 		uvm_unmap_detach(&dead, 0);
2027 }
2028 
2029 /*
2030  * Mark entry as free.
2031  *
2032  * entry will be put on the dead list.
2033  * The free space will be merged into the previous or a new entry,
2034  * unless markfree is false.
2035  */
2036 void
2037 uvm_mapent_mkfree(struct vm_map *map, struct vm_map_entry *entry,
2038     struct vm_map_entry **prev_ptr, struct uvm_map_deadq *dead,
2039     boolean_t markfree)
2040 {
2041 	struct uvm_addr_state	*free;
2042 	struct vm_map_entry	*prev;
2043 	vaddr_t			 addr;	/* Start of freed range. */
2044 	vaddr_t			 end;	/* End of freed range. */
2045 
2046 	prev = *prev_ptr;
2047 	if (prev == entry)
2048 		*prev_ptr = prev = NULL;
2049 
2050 	if (prev == NULL ||
2051 	    VMMAP_FREE_END(prev) != entry->start)
2052 		prev = RBT_PREV(uvm_map_addr, entry);
2053 
2054 	/* Entry is describing only free memory and has nothing to drain into. */
2055 	if (prev == NULL && entry->start == entry->end && markfree) {
2056 		*prev_ptr = entry;
2057 		return;
2058 	}
2059 
2060 	addr = entry->start;
2061 	end = VMMAP_FREE_END(entry);
2062 	free = uvm_map_uaddr_e(map, entry);
2063 	uvm_mapent_free_remove(map, free, entry);
2064 	uvm_mapent_addr_remove(map, entry);
2065 	DEAD_ENTRY_PUSH(dead, entry);
2066 
2067 	if (markfree) {
2068 		if (prev) {
2069 			free = uvm_map_uaddr_e(map, prev);
2070 			uvm_mapent_free_remove(map, free, prev);
2071 		}
2072 		*prev_ptr = uvm_map_fix_space(map, prev, addr, end, 0);
2073 	}
2074 }
2075 
2076 /*
2077  * Unwire and release referenced amap and object from map entry.
2078  */
2079 void
2080 uvm_unmap_kill_entry(struct vm_map *map, struct vm_map_entry *entry)
2081 {
2082 	/* Unwire removed map entry. */
2083 	if (VM_MAPENT_ISWIRED(entry)) {
2084 		KERNEL_LOCK();
2085 		entry->wired_count = 0;
2086 		uvm_fault_unwire_locked(map, entry->start, entry->end);
2087 		KERNEL_UNLOCK();
2088 	}
2089 
2090 	/* Entry-type specific code. */
2091 	if (UVM_ET_ISHOLE(entry)) {
2092 		/* Nothing to be done for holes. */
2093 	} else if (map->flags & VM_MAP_INTRSAFE) {
2094 		KASSERT(vm_map_pmap(map) == pmap_kernel());
2095 		uvm_km_pgremove_intrsafe(entry->start, entry->end);
2096 		pmap_kremove(entry->start, entry->end - entry->start);
2097 	} else if (UVM_ET_ISOBJ(entry) &&
2098 	    UVM_OBJ_IS_KERN_OBJECT(entry->object.uvm_obj)) {
2099 		KASSERT(vm_map_pmap(map) == pmap_kernel());
2100 		/*
2101 		 * Note: kernel object mappings are currently used in
2102 		 * two ways:
2103 		 *  [1] "normal" mappings of pages in the kernel object
2104 		 *  [2] uvm_km_valloc'd allocations in which we
2105 		 *      pmap_enter in some non-kernel-object page
2106 		 *      (e.g. vmapbuf).
2107 		 *
2108 		 * for case [1], we need to remove the mapping from
2109 		 * the pmap and then remove the page from the kernel
2110 		 * object (because, once pages in a kernel object are
2111 		 * unmapped they are no longer needed, unlike, say,
2112 		 * a vnode where you might want the data to persist
2113 		 * until flushed out of a queue).
2114 		 *
2115 		 * for case [2], we need to remove the mapping from
2116 		 * the pmap.  there shouldn't be any pages at the
2117 		 * specified offset in the kernel object [but it
2118 		 * doesn't hurt to call uvm_km_pgremove just to be
2119 		 * safe?]
2120 		 *
2121 		 * uvm_km_pgremove currently does the following:
2122 		 *   for pages in the kernel object range:
2123 		 *     - drops the swap slot
2124 		 *     - uvm_pagefree the page
2125 		 *
2126 		 * note there is version of uvm_km_pgremove() that
2127 		 * is used for "intrsafe" objects.
2128 		 */
2129 		/*
2130 		 * remove mappings from pmap and drop the pages
2131 		 * from the object.  offsets are always relative
2132 		 * to vm_map_min(kernel_map).
2133 		 */
2134 		pmap_remove(pmap_kernel(), entry->start, entry->end);
2135 		uvm_km_pgremove(entry->object.uvm_obj,
2136 		    entry->start - vm_map_min(kernel_map),
2137 		    entry->end - vm_map_min(kernel_map));
2138 
2139 		/*
2140 		 * null out kernel_object reference, we've just
2141 		 * dropped it
2142 		 */
2143 		entry->etype &= ~UVM_ET_OBJ;
2144 		entry->object.uvm_obj = NULL;  /* to be safe */
2145 	} else {
2146 		/* remove mappings the standard way. */
2147 		pmap_remove(map->pmap, entry->start, entry->end);
2148 	}
2149 }
2150 
2151 /*
2152  * Remove all entries from start to end.
2153  *
2154  * If remove_holes, then remove ET_HOLE entries as well.
2155  * If markfree, entry will be properly marked free, otherwise, no replacement
2156  * entry will be put in the tree (corrupting the tree).
2157  */
2158 void
2159 uvm_unmap_remove(struct vm_map *map, vaddr_t start, vaddr_t end,
2160     struct uvm_map_deadq *dead, boolean_t remove_holes,
2161     boolean_t markfree)
2162 {
2163 	struct vm_map_entry *prev_hint, *next, *entry;
2164 
2165 	start = MAX(start, map->min_offset);
2166 	end = MIN(end, map->max_offset);
2167 	if (start >= end)
2168 		return;
2169 
2170 	if ((map->flags & VM_MAP_INTRSAFE) == 0)
2171 		splassert(IPL_NONE);
2172 	else
2173 		splassert(IPL_VM);
2174 
2175 	/* Find first affected entry. */
2176 	entry = uvm_map_entrybyaddr(&map->addr, start);
2177 	KDASSERT(entry != NULL && entry->start <= start);
2178 	if (entry->end <= start && markfree)
2179 		entry = RBT_NEXT(uvm_map_addr, entry);
2180 	else
2181 		UVM_MAP_CLIP_START(map, entry, start);
2182 
2183 	/*
2184 	 * Iterate entries until we reach end address.
2185 	 * prev_hint hints where the freed space can be appended to.
2186 	 */
2187 	prev_hint = NULL;
2188 	for (; entry != NULL && entry->start < end; entry = next) {
2189 		KDASSERT(entry->start >= start);
2190 		if (entry->end > end || !markfree)
2191 			UVM_MAP_CLIP_END(map, entry, end);
2192 		KDASSERT(entry->start >= start && entry->end <= end);
2193 		next = RBT_NEXT(uvm_map_addr, entry);
2194 
2195 		/* Don't remove holes unless asked to do so. */
2196 		if (UVM_ET_ISHOLE(entry)) {
2197 			if (!remove_holes) {
2198 				prev_hint = entry;
2199 				continue;
2200 			}
2201 		}
2202 
2203 		/* A stack has been removed.. */
2204 		if (UVM_ET_ISSTACK(entry) && (map->flags & VM_MAP_ISVMSPACE))
2205 			map->sserial++;
2206 
2207 		/* Kill entry. */
2208 		uvm_unmap_kill_entry(map, entry);
2209 
2210 		/* Update space usage. */
2211 		if ((map->flags & VM_MAP_ISVMSPACE) &&
2212 		    entry->object.uvm_obj == NULL &&
2213 		    !UVM_ET_ISHOLE(entry)) {
2214 			((struct vmspace *)map)->vm_dused -=
2215 			    uvmspace_dused(map, entry->start, entry->end);
2216 		}
2217 		if (!UVM_ET_ISHOLE(entry))
2218 			map->size -= entry->end - entry->start;
2219 
2220 		/* Actual removal of entry. */
2221 		uvm_mapent_mkfree(map, entry, &prev_hint, dead, markfree);
2222 	}
2223 
2224 	pmap_update(vm_map_pmap(map));
2225 
2226 #ifdef VMMAP_DEBUG
2227 	if (markfree) {
2228 		for (entry = uvm_map_entrybyaddr(&map->addr, start);
2229 		    entry != NULL && entry->start < end;
2230 		    entry = RBT_NEXT(uvm_map_addr, entry)) {
2231 			KDASSERT(entry->end <= start ||
2232 			    entry->start == entry->end ||
2233 			    UVM_ET_ISHOLE(entry));
2234 		}
2235 	} else {
2236 		vaddr_t a;
2237 		for (a = start; a < end; a += PAGE_SIZE)
2238 			KDASSERT(uvm_map_entrybyaddr(&map->addr, a) == NULL);
2239 	}
2240 #endif
2241 }
2242 
2243 /*
2244  * Mark all entries from first until end (exclusive) as pageable.
2245  *
2246  * Lock must be exclusive on entry and will not be touched.
2247  */
2248 void
2249 uvm_map_pageable_pgon(struct vm_map *map, struct vm_map_entry *first,
2250     struct vm_map_entry *end, vaddr_t start_addr, vaddr_t end_addr)
2251 {
2252 	struct vm_map_entry *iter;
2253 
2254 	for (iter = first; iter != end;
2255 	    iter = RBT_NEXT(uvm_map_addr, iter)) {
2256 		KDASSERT(iter->start >= start_addr && iter->end <= end_addr);
2257 		if (!VM_MAPENT_ISWIRED(iter) || UVM_ET_ISHOLE(iter))
2258 			continue;
2259 
2260 		iter->wired_count = 0;
2261 		uvm_fault_unwire_locked(map, iter->start, iter->end);
2262 	}
2263 }
2264 
2265 /*
2266  * Mark all entries from first until end (exclusive) as wired.
2267  *
2268  * Lockflags determines the lock state on return from this function.
2269  * Lock must be exclusive on entry.
2270  */
2271 int
2272 uvm_map_pageable_wire(struct vm_map *map, struct vm_map_entry *first,
2273     struct vm_map_entry *end, vaddr_t start_addr, vaddr_t end_addr,
2274     int lockflags)
2275 {
2276 	struct vm_map_entry *iter;
2277 #ifdef DIAGNOSTIC
2278 	unsigned int timestamp_save;
2279 #endif
2280 	int error;
2281 
2282 	/*
2283 	 * Wire pages in two passes:
2284 	 *
2285 	 * 1: holding the write lock, we create any anonymous maps that need
2286 	 *    to be created.  then we clip each map entry to the region to
2287 	 *    be wired and increment its wiring count.
2288 	 *
2289 	 * 2: we downgrade to a read lock, and call uvm_fault_wire to fault
2290 	 *    in the pages for any newly wired area (wired_count == 1).
2291 	 *
2292 	 *    downgrading to a read lock for uvm_fault_wire avoids a possible
2293 	 *    deadlock with another thread that may have faulted on one of
2294 	 *    the pages to be wired (it would mark the page busy, blocking
2295 	 *    us, then in turn block on the map lock that we hold).
2296 	 *    because we keep the read lock on the map, the copy-on-write
2297 	 *    status of the entries we modify here cannot change.
2298 	 */
2299 	for (iter = first; iter != end;
2300 	    iter = RBT_NEXT(uvm_map_addr, iter)) {
2301 		KDASSERT(iter->start >= start_addr && iter->end <= end_addr);
2302 		if (UVM_ET_ISHOLE(iter) || iter->start == iter->end ||
2303 		    iter->protection == PROT_NONE)
2304 			continue;
2305 
2306 		/*
2307 		 * Perform actions of vm_map_lookup that need the write lock.
2308 		 * - create an anonymous map for copy-on-write
2309 		 * - anonymous map for zero-fill
2310 		 * Skip submaps.
2311 		 */
2312 		if (!VM_MAPENT_ISWIRED(iter) && !UVM_ET_ISSUBMAP(iter) &&
2313 		    UVM_ET_ISNEEDSCOPY(iter) &&
2314 		    ((iter->protection & PROT_WRITE) ||
2315 		    iter->object.uvm_obj == NULL)) {
2316 			amap_copy(map, iter, M_WAITOK,
2317 			    UVM_ET_ISSTACK(iter) ? FALSE : TRUE,
2318 			    iter->start, iter->end);
2319 		}
2320 		iter->wired_count++;
2321 	}
2322 
2323 	/*
2324 	 * Pass 2.
2325 	 */
2326 #ifdef DIAGNOSTIC
2327 	timestamp_save = map->timestamp;
2328 #endif
2329 	vm_map_busy(map);
2330 	vm_map_downgrade(map);
2331 
2332 	error = 0;
2333 	for (iter = first; error == 0 && iter != end;
2334 	    iter = RBT_NEXT(uvm_map_addr, iter)) {
2335 		if (UVM_ET_ISHOLE(iter) || iter->start == iter->end ||
2336 		    iter->protection == PROT_NONE)
2337 			continue;
2338 
2339 		error = uvm_fault_wire(map, iter->start, iter->end,
2340 		    iter->protection);
2341 	}
2342 
2343 	if (error) {
2344 		/*
2345 		 * uvm_fault_wire failure
2346 		 *
2347 		 * Reacquire lock and undo our work.
2348 		 */
2349 		vm_map_upgrade(map);
2350 		vm_map_unbusy(map);
2351 #ifdef DIAGNOSTIC
2352 		if (timestamp_save != map->timestamp)
2353 			panic("uvm_map_pageable_wire: stale map");
2354 #endif
2355 
2356 		/*
2357 		 * first is no longer needed to restart loops.
2358 		 * Use it as iterator to unmap successful mappings.
2359 		 */
2360 		for (; first != iter;
2361 		    first = RBT_NEXT(uvm_map_addr, first)) {
2362 			if (UVM_ET_ISHOLE(first) ||
2363 			    first->start == first->end ||
2364 			    first->protection == PROT_NONE)
2365 				continue;
2366 
2367 			first->wired_count--;
2368 			if (!VM_MAPENT_ISWIRED(first)) {
2369 				uvm_fault_unwire_locked(map,
2370 				    iter->start, iter->end);
2371 			}
2372 		}
2373 
2374 		/* decrease counter in the rest of the entries */
2375 		for (; iter != end;
2376 		    iter = RBT_NEXT(uvm_map_addr, iter)) {
2377 			if (UVM_ET_ISHOLE(iter) || iter->start == iter->end ||
2378 			    iter->protection == PROT_NONE)
2379 				continue;
2380 
2381 			iter->wired_count--;
2382 		}
2383 
2384 		if ((lockflags & UVM_LK_EXIT) == 0)
2385 			vm_map_unlock(map);
2386 		return error;
2387 	}
2388 
2389 	/* We are currently holding a read lock. */
2390 	if ((lockflags & UVM_LK_EXIT) == 0) {
2391 		vm_map_unbusy(map);
2392 		vm_map_unlock_read(map);
2393 	} else {
2394 		vm_map_upgrade(map);
2395 		vm_map_unbusy(map);
2396 #ifdef DIAGNOSTIC
2397 		if (timestamp_save != map->timestamp)
2398 			panic("uvm_map_pageable_wire: stale map");
2399 #endif
2400 	}
2401 	return 0;
2402 }
2403 
2404 /*
2405  * uvm_map_pageable: set pageability of a range in a map.
2406  *
2407  * Flags:
2408  * UVM_LK_ENTER: map is already locked by caller
2409  * UVM_LK_EXIT:  don't unlock map on exit
2410  *
2411  * The full range must be in use (entries may not have fspace != 0).
2412  * UVM_ET_HOLE counts as unmapped.
2413  */
2414 int
2415 uvm_map_pageable(struct vm_map *map, vaddr_t start, vaddr_t end,
2416     boolean_t new_pageable, int lockflags)
2417 {
2418 	struct vm_map_entry *first, *last, *tmp;
2419 	int error;
2420 
2421 	start = trunc_page(start);
2422 	end = round_page(end);
2423 
2424 	if (start > end)
2425 		return EINVAL;
2426 	if (start == end)
2427 		return 0;	/* nothing to do */
2428 	if (start < map->min_offset)
2429 		return EFAULT; /* why? see first XXX below */
2430 	if (end > map->max_offset)
2431 		return EINVAL; /* why? see second XXX below */
2432 
2433 	KASSERT(map->flags & VM_MAP_PAGEABLE);
2434 	if ((lockflags & UVM_LK_ENTER) == 0)
2435 		vm_map_lock(map);
2436 
2437 	/*
2438 	 * Find first entry.
2439 	 *
2440 	 * Initial test on start is different, because of the different
2441 	 * error returned. Rest is tested further down.
2442 	 */
2443 	first = uvm_map_entrybyaddr(&map->addr, start);
2444 	if (first->end <= start || UVM_ET_ISHOLE(first)) {
2445 		/*
2446 		 * XXX if the first address is not mapped, it is EFAULT?
2447 		 */
2448 		error = EFAULT;
2449 		goto out;
2450 	}
2451 
2452 	/* Check that the range has no holes. */
2453 	for (last = first; last != NULL && last->start < end;
2454 	    last = RBT_NEXT(uvm_map_addr, last)) {
2455 		if (UVM_ET_ISHOLE(last) ||
2456 		    (last->end < end && VMMAP_FREE_END(last) != last->end)) {
2457 			/*
2458 			 * XXX unmapped memory in range, why is it EINVAL
2459 			 * instead of EFAULT?
2460 			 */
2461 			error = EINVAL;
2462 			goto out;
2463 		}
2464 	}
2465 
2466 	/*
2467 	 * Last ended at the first entry after the range.
2468 	 * Move back one step.
2469 	 *
2470 	 * Note that last may be NULL.
2471 	 */
2472 	if (last == NULL) {
2473 		last = RBT_MAX(uvm_map_addr, &map->addr);
2474 		if (last->end < end) {
2475 			error = EINVAL;
2476 			goto out;
2477 		}
2478 	} else {
2479 		KASSERT(last != first);
2480 		last = RBT_PREV(uvm_map_addr, last);
2481 	}
2482 
2483 	/* Wire/unwire pages here. */
2484 	if (new_pageable) {
2485 		/*
2486 		 * Mark pageable.
2487 		 * entries that are not wired are untouched.
2488 		 */
2489 		if (VM_MAPENT_ISWIRED(first))
2490 			UVM_MAP_CLIP_START(map, first, start);
2491 		/*
2492 		 * Split last at end.
2493 		 * Make tmp be the first entry after what is to be touched.
2494 		 * If last is not wired, don't touch it.
2495 		 */
2496 		if (VM_MAPENT_ISWIRED(last)) {
2497 			UVM_MAP_CLIP_END(map, last, end);
2498 			tmp = RBT_NEXT(uvm_map_addr, last);
2499 		} else
2500 			tmp = last;
2501 
2502 		uvm_map_pageable_pgon(map, first, tmp, start, end);
2503 		error = 0;
2504 
2505 out:
2506 		if ((lockflags & UVM_LK_EXIT) == 0)
2507 			vm_map_unlock(map);
2508 		return error;
2509 	} else {
2510 		/*
2511 		 * Mark entries wired.
2512 		 * entries are always touched (because recovery needs this).
2513 		 */
2514 		if (!VM_MAPENT_ISWIRED(first))
2515 			UVM_MAP_CLIP_START(map, first, start);
2516 		/*
2517 		 * Split last at end.
2518 		 * Make tmp be the first entry after what is to be touched.
2519 		 * If last is not wired, don't touch it.
2520 		 */
2521 		if (!VM_MAPENT_ISWIRED(last)) {
2522 			UVM_MAP_CLIP_END(map, last, end);
2523 			tmp = RBT_NEXT(uvm_map_addr, last);
2524 		} else
2525 			tmp = last;
2526 
2527 		return uvm_map_pageable_wire(map, first, tmp, start, end,
2528 		    lockflags);
2529 	}
2530 }
2531 
2532 /*
2533  * uvm_map_pageable_all: special case of uvm_map_pageable - affects
2534  * all mapped regions.
2535  *
2536  * Map must not be locked.
2537  * If no flags are specified, all ragions are unwired.
2538  */
2539 int
2540 uvm_map_pageable_all(struct vm_map *map, int flags, vsize_t limit)
2541 {
2542 	vsize_t size;
2543 	struct vm_map_entry *iter;
2544 
2545 	KASSERT(map->flags & VM_MAP_PAGEABLE);
2546 	vm_map_lock(map);
2547 
2548 	if (flags == 0) {
2549 		uvm_map_pageable_pgon(map, RBT_MIN(uvm_map_addr, &map->addr),
2550 		    NULL, map->min_offset, map->max_offset);
2551 
2552 		vm_map_modflags(map, 0, VM_MAP_WIREFUTURE);
2553 		vm_map_unlock(map);
2554 		return 0;
2555 	}
2556 
2557 	if (flags & MCL_FUTURE)
2558 		vm_map_modflags(map, VM_MAP_WIREFUTURE, 0);
2559 	if (!(flags & MCL_CURRENT)) {
2560 		vm_map_unlock(map);
2561 		return 0;
2562 	}
2563 
2564 	/*
2565 	 * Count number of pages in all non-wired entries.
2566 	 * If the number exceeds the limit, abort.
2567 	 */
2568 	size = 0;
2569 	RBT_FOREACH(iter, uvm_map_addr, &map->addr) {
2570 		if (VM_MAPENT_ISWIRED(iter) || UVM_ET_ISHOLE(iter))
2571 			continue;
2572 
2573 		size += iter->end - iter->start;
2574 	}
2575 
2576 	if (atop(size) + uvmexp.wired > uvmexp.wiredmax) {
2577 		vm_map_unlock(map);
2578 		return ENOMEM;
2579 	}
2580 
2581 	/* XXX non-pmap_wired_count case must be handled by caller */
2582 #ifdef pmap_wired_count
2583 	if (limit != 0 &&
2584 	    size + ptoa(pmap_wired_count(vm_map_pmap(map))) > limit) {
2585 		vm_map_unlock(map);
2586 		return ENOMEM;
2587 	}
2588 #endif
2589 
2590 	/*
2591 	 * uvm_map_pageable_wire will release lcok
2592 	 */
2593 	return uvm_map_pageable_wire(map, RBT_MIN(uvm_map_addr, &map->addr),
2594 	    NULL, map->min_offset, map->max_offset, 0);
2595 }
2596 
2597 /*
2598  * Initialize map.
2599  *
2600  * Allocates sufficient entries to describe the free memory in the map.
2601  */
2602 void
2603 uvm_map_setup(struct vm_map *map, vaddr_t min, vaddr_t max, int flags)
2604 {
2605 	int i;
2606 
2607 	KASSERT((min & (vaddr_t)PAGE_MASK) == 0);
2608 	KASSERT((max & (vaddr_t)PAGE_MASK) == 0 ||
2609 	    (max & (vaddr_t)PAGE_MASK) == (vaddr_t)PAGE_MASK);
2610 
2611 	/*
2612 	 * Update parameters.
2613 	 *
2614 	 * This code handles (vaddr_t)-1 and other page mask ending addresses
2615 	 * properly.
2616 	 * We lose the top page if the full virtual address space is used.
2617 	 */
2618 	if (max & (vaddr_t)PAGE_MASK) {
2619 		max += 1;
2620 		if (max == 0) /* overflow */
2621 			max -= PAGE_SIZE;
2622 	}
2623 
2624 	RBT_INIT(uvm_map_addr, &map->addr);
2625 	map->uaddr_exe = NULL;
2626 	for (i = 0; i < nitems(map->uaddr_any); ++i)
2627 		map->uaddr_any[i] = NULL;
2628 	map->uaddr_brk_stack = NULL;
2629 
2630 	map->size = 0;
2631 	map->ref_count = 0;
2632 	map->min_offset = min;
2633 	map->max_offset = max;
2634 	map->b_start = map->b_end = 0; /* Empty brk() area by default. */
2635 	map->s_start = map->s_end = 0; /* Empty stack area by default. */
2636 	map->flags = flags;
2637 	map->timestamp = 0;
2638 	rw_init_flags(&map->lock, "vmmaplk", RWL_DUPOK);
2639 	mtx_init(&map->mtx, IPL_VM);
2640 	mtx_init(&map->flags_lock, IPL_VM);
2641 
2642 	/* Configure the allocators. */
2643 	if (flags & VM_MAP_ISVMSPACE)
2644 		uvm_map_setup_md(map);
2645 	else
2646 		map->uaddr_any[3] = &uaddr_kbootstrap;
2647 
2648 	/*
2649 	 * Fill map entries.
2650 	 * We do not need to write-lock the map here because only the current
2651 	 * thread sees it right now. Initialize ref_count to 0 above to avoid
2652 	 * bogus triggering of lock-not-held assertions.
2653 	 */
2654 	uvm_map_setup_entries(map);
2655 	uvm_tree_sanity(map, __FILE__, __LINE__);
2656 	map->ref_count = 1;
2657 }
2658 
2659 /*
2660  * Destroy the map.
2661  *
2662  * This is the inverse operation to uvm_map_setup.
2663  */
2664 void
2665 uvm_map_teardown(struct vm_map *map)
2666 {
2667 	struct uvm_map_deadq	 dead_entries;
2668 	struct vm_map_entry	*entry, *tmp;
2669 #ifdef VMMAP_DEBUG
2670 	size_t			 numq, numt;
2671 #endif
2672 	int			 i;
2673 
2674 	KERNEL_ASSERT_LOCKED();
2675 	KERNEL_UNLOCK();
2676 	KERNEL_ASSERT_UNLOCKED();
2677 
2678 	KASSERT((map->flags & VM_MAP_INTRSAFE) == 0);
2679 
2680 	/* Remove address selectors. */
2681 	uvm_addr_destroy(map->uaddr_exe);
2682 	map->uaddr_exe = NULL;
2683 	for (i = 0; i < nitems(map->uaddr_any); i++) {
2684 		uvm_addr_destroy(map->uaddr_any[i]);
2685 		map->uaddr_any[i] = NULL;
2686 	}
2687 	uvm_addr_destroy(map->uaddr_brk_stack);
2688 	map->uaddr_brk_stack = NULL;
2689 
2690 	/*
2691 	 * Remove entries.
2692 	 *
2693 	 * The following is based on graph breadth-first search.
2694 	 *
2695 	 * In color terms:
2696 	 * - the dead_entries set contains all nodes that are reachable
2697 	 *   (i.e. both the black and the grey nodes)
2698 	 * - any entry not in dead_entries is white
2699 	 * - any entry that appears in dead_entries before entry,
2700 	 *   is black, the rest is grey.
2701 	 * The set [entry, end] is also referred to as the wavefront.
2702 	 *
2703 	 * Since the tree is always a fully connected graph, the breadth-first
2704 	 * search guarantees that each vmmap_entry is visited exactly once.
2705 	 * The vm_map is broken down in linear time.
2706 	 */
2707 	TAILQ_INIT(&dead_entries);
2708 	if ((entry = RBT_ROOT(uvm_map_addr, &map->addr)) != NULL)
2709 		DEAD_ENTRY_PUSH(&dead_entries, entry);
2710 	while (entry != NULL) {
2711 		sched_pause(yield);
2712 		uvm_unmap_kill_entry(map, entry);
2713 		if ((tmp = RBT_LEFT(uvm_map_addr, entry)) != NULL)
2714 			DEAD_ENTRY_PUSH(&dead_entries, tmp);
2715 		if ((tmp = RBT_RIGHT(uvm_map_addr, entry)) != NULL)
2716 			DEAD_ENTRY_PUSH(&dead_entries, tmp);
2717 		/* Update wave-front. */
2718 		entry = TAILQ_NEXT(entry, dfree.deadq);
2719 	}
2720 
2721 #ifdef VMMAP_DEBUG
2722 	numt = numq = 0;
2723 	RBT_FOREACH(entry, uvm_map_addr, &map->addr)
2724 		numt++;
2725 	TAILQ_FOREACH(entry, &dead_entries, dfree.deadq)
2726 		numq++;
2727 	KASSERT(numt == numq);
2728 #endif
2729 	uvm_unmap_detach(&dead_entries, UVM_PLA_WAITOK);
2730 
2731 	KERNEL_LOCK();
2732 
2733 	pmap_destroy(map->pmap);
2734 	map->pmap = NULL;
2735 }
2736 
2737 /*
2738  * Populate map with free-memory entries.
2739  *
2740  * Map must be initialized and empty.
2741  */
2742 void
2743 uvm_map_setup_entries(struct vm_map *map)
2744 {
2745 	KDASSERT(RBT_EMPTY(uvm_map_addr, &map->addr));
2746 
2747 	uvm_map_fix_space(map, NULL, map->min_offset, map->max_offset, 0);
2748 }
2749 
2750 /*
2751  * Split entry at given address.
2752  *
2753  * orig:  entry that is to be split.
2754  * next:  a newly allocated map entry that is not linked.
2755  * split: address at which the split is done.
2756  */
2757 void
2758 uvm_map_splitentry(struct vm_map *map, struct vm_map_entry *orig,
2759     struct vm_map_entry *next, vaddr_t split)
2760 {
2761 	struct uvm_addr_state *free, *free_before;
2762 	vsize_t adj;
2763 
2764 	if ((split & PAGE_MASK) != 0) {
2765 		panic("uvm_map_splitentry: split address 0x%lx "
2766 		    "not on page boundary!", split);
2767 	}
2768 	KDASSERT(map != NULL && orig != NULL && next != NULL);
2769 	uvm_tree_sanity(map, __FILE__, __LINE__);
2770 	KASSERT(orig->start < split && VMMAP_FREE_END(orig) > split);
2771 
2772 #ifdef VMMAP_DEBUG
2773 	KDASSERT(RBT_FIND(uvm_map_addr, &map->addr, orig) == orig);
2774 	KDASSERT(RBT_FIND(uvm_map_addr, &map->addr, next) != next);
2775 #endif /* VMMAP_DEBUG */
2776 
2777 	/*
2778 	 * Free space will change, unlink from free space tree.
2779 	 */
2780 	free = uvm_map_uaddr_e(map, orig);
2781 	uvm_mapent_free_remove(map, free, orig);
2782 
2783 	adj = split - orig->start;
2784 
2785 	uvm_mapent_copy(orig, next);
2786 	if (split >= orig->end) {
2787 		next->etype = 0;
2788 		next->offset = 0;
2789 		next->wired_count = 0;
2790 		next->start = next->end = split;
2791 		next->guard = 0;
2792 		next->fspace = VMMAP_FREE_END(orig) - split;
2793 		next->aref.ar_amap = NULL;
2794 		next->aref.ar_pageoff = 0;
2795 		orig->guard = MIN(orig->guard, split - orig->end);
2796 		orig->fspace = split - VMMAP_FREE_START(orig);
2797 	} else {
2798 		orig->fspace = 0;
2799 		orig->guard = 0;
2800 		orig->end = next->start = split;
2801 
2802 		if (next->aref.ar_amap) {
2803 			KERNEL_LOCK();
2804 			amap_splitref(&orig->aref, &next->aref, adj);
2805 			KERNEL_UNLOCK();
2806 		}
2807 		if (UVM_ET_ISSUBMAP(orig)) {
2808 			uvm_map_reference(next->object.sub_map);
2809 			next->offset += adj;
2810 		} else if (UVM_ET_ISOBJ(orig)) {
2811 			if (next->object.uvm_obj->pgops &&
2812 			    next->object.uvm_obj->pgops->pgo_reference) {
2813 				KERNEL_LOCK();
2814 				next->object.uvm_obj->pgops->pgo_reference(
2815 				    next->object.uvm_obj);
2816 				KERNEL_UNLOCK();
2817 			}
2818 			next->offset += adj;
2819 		}
2820 	}
2821 
2822 	/*
2823 	 * Link next into address tree.
2824 	 * Link orig and next into free-space tree.
2825 	 *
2826 	 * Don't insert 'next' into the addr tree until orig has been linked,
2827 	 * in case the free-list looks at adjecent entries in the addr tree
2828 	 * for its decisions.
2829 	 */
2830 	if (orig->fspace > 0)
2831 		free_before = free;
2832 	else
2833 		free_before = uvm_map_uaddr_e(map, orig);
2834 	uvm_mapent_free_insert(map, free_before, orig);
2835 	uvm_mapent_addr_insert(map, next);
2836 	uvm_mapent_free_insert(map, free, next);
2837 
2838 	uvm_tree_sanity(map, __FILE__, __LINE__);
2839 }
2840 
2841 
2842 #ifdef VMMAP_DEBUG
2843 
2844 void
2845 uvm_tree_assert(struct vm_map *map, int test, char *test_str,
2846     char *file, int line)
2847 {
2848 	char* map_special;
2849 
2850 	if (test)
2851 		return;
2852 
2853 	if (map == kernel_map)
2854 		map_special = " (kernel_map)";
2855 	else if (map == kmem_map)
2856 		map_special = " (kmem_map)";
2857 	else
2858 		map_special = "";
2859 	panic("uvm_tree_sanity %p%s (%s %d): %s", map, map_special, file,
2860 	    line, test_str);
2861 }
2862 
2863 /*
2864  * Check that map is sane.
2865  */
2866 void
2867 uvm_tree_sanity(struct vm_map *map, char *file, int line)
2868 {
2869 	struct vm_map_entry	*iter;
2870 	vaddr_t			 addr;
2871 	vaddr_t			 min, max, bound; /* Bounds checker. */
2872 	struct uvm_addr_state	*free;
2873 
2874 	addr = vm_map_min(map);
2875 	RBT_FOREACH(iter, uvm_map_addr, &map->addr) {
2876 		/*
2877 		 * Valid start, end.
2878 		 * Catch overflow for end+fspace.
2879 		 */
2880 		UVM_ASSERT(map, iter->end >= iter->start, file, line);
2881 		UVM_ASSERT(map, VMMAP_FREE_END(iter) >= iter->end, file, line);
2882 
2883 		/* May not be empty. */
2884 		UVM_ASSERT(map, iter->start < VMMAP_FREE_END(iter),
2885 		    file, line);
2886 
2887 		/* Addresses for entry must lie within map boundaries. */
2888 		UVM_ASSERT(map, iter->start >= vm_map_min(map) &&
2889 		    VMMAP_FREE_END(iter) <= vm_map_max(map), file, line);
2890 
2891 		/* Tree may not have gaps. */
2892 		UVM_ASSERT(map, iter->start == addr, file, line);
2893 		addr = VMMAP_FREE_END(iter);
2894 
2895 		/*
2896 		 * Free space may not cross boundaries, unless the same
2897 		 * free list is used on both sides of the border.
2898 		 */
2899 		min = VMMAP_FREE_START(iter);
2900 		max = VMMAP_FREE_END(iter);
2901 
2902 		while (min < max &&
2903 		    (bound = uvm_map_boundary(map, min, max)) != max) {
2904 			UVM_ASSERT(map,
2905 			    uvm_map_uaddr(map, bound - 1) ==
2906 			    uvm_map_uaddr(map, bound),
2907 			    file, line);
2908 			min = bound;
2909 		}
2910 
2911 		free = uvm_map_uaddr_e(map, iter);
2912 		if (free) {
2913 			UVM_ASSERT(map, (iter->etype & UVM_ET_FREEMAPPED) != 0,
2914 			    file, line);
2915 		} else {
2916 			UVM_ASSERT(map, (iter->etype & UVM_ET_FREEMAPPED) == 0,
2917 			    file, line);
2918 		}
2919 	}
2920 	UVM_ASSERT(map, addr == vm_map_max(map), file, line);
2921 }
2922 
2923 void
2924 uvm_tree_size_chk(struct vm_map *map, char *file, int line)
2925 {
2926 	struct vm_map_entry *iter;
2927 	vsize_t size;
2928 
2929 	size = 0;
2930 	RBT_FOREACH(iter, uvm_map_addr, &map->addr) {
2931 		if (!UVM_ET_ISHOLE(iter))
2932 			size += iter->end - iter->start;
2933 	}
2934 
2935 	if (map->size != size)
2936 		printf("map size = 0x%lx, should be 0x%lx\n", map->size, size);
2937 	UVM_ASSERT(map, map->size == size, file, line);
2938 
2939 	vmspace_validate(map);
2940 }
2941 
2942 /*
2943  * This function validates the statistics on vmspace.
2944  */
2945 void
2946 vmspace_validate(struct vm_map *map)
2947 {
2948 	struct vmspace *vm;
2949 	struct vm_map_entry *iter;
2950 	vaddr_t imin, imax;
2951 	vaddr_t stack_begin, stack_end; /* Position of stack. */
2952 	vsize_t stack, heap; /* Measured sizes. */
2953 
2954 	if (!(map->flags & VM_MAP_ISVMSPACE))
2955 		return;
2956 
2957 	vm = (struct vmspace *)map;
2958 	stack_begin = MIN((vaddr_t)vm->vm_maxsaddr, (vaddr_t)vm->vm_minsaddr);
2959 	stack_end = MAX((vaddr_t)vm->vm_maxsaddr, (vaddr_t)vm->vm_minsaddr);
2960 
2961 	stack = heap = 0;
2962 	RBT_FOREACH(iter, uvm_map_addr, &map->addr) {
2963 		imin = imax = iter->start;
2964 
2965 		if (UVM_ET_ISHOLE(iter) || iter->object.uvm_obj != NULL)
2966 			continue;
2967 
2968 		/*
2969 		 * Update stack, heap.
2970 		 * Keep in mind that (theoretically) the entries of
2971 		 * userspace and stack may be joined.
2972 		 */
2973 		while (imin != iter->end) {
2974 			/*
2975 			 * Set imax to the first boundary crossed between
2976 			 * imin and stack addresses.
2977 			 */
2978 			imax = iter->end;
2979 			if (imin < stack_begin && imax > stack_begin)
2980 				imax = stack_begin;
2981 			else if (imin < stack_end && imax > stack_end)
2982 				imax = stack_end;
2983 
2984 			if (imin >= stack_begin && imin < stack_end)
2985 				stack += imax - imin;
2986 			else
2987 				heap += imax - imin;
2988 			imin = imax;
2989 		}
2990 	}
2991 
2992 	heap >>= PAGE_SHIFT;
2993 	if (heap != vm->vm_dused) {
2994 		printf("vmspace stack range: 0x%lx-0x%lx\n",
2995 		    stack_begin, stack_end);
2996 		panic("vmspace_validate: vmspace.vm_dused invalid, "
2997 		    "expected %ld pgs, got %ld pgs in map %p",
2998 		    heap, vm->vm_dused,
2999 		    map);
3000 	}
3001 }
3002 
3003 #endif /* VMMAP_DEBUG */
3004 
3005 /*
3006  * uvm_map_init: init mapping system at boot time.   note that we allocate
3007  * and init the static pool of structs vm_map_entry for the kernel here.
3008  */
3009 void
3010 uvm_map_init(void)
3011 {
3012 	static struct vm_map_entry kernel_map_entry[MAX_KMAPENT];
3013 	int lcv;
3014 
3015 	/* now set up static pool of kernel map entries ... */
3016 	mtx_init(&uvm_kmapent_mtx, IPL_VM);
3017 	SLIST_INIT(&uvm.kentry_free);
3018 	for (lcv = 0 ; lcv < MAX_KMAPENT ; lcv++) {
3019 		SLIST_INSERT_HEAD(&uvm.kentry_free,
3020 		    &kernel_map_entry[lcv], daddrs.addr_kentry);
3021 	}
3022 
3023 	/* initialize the map-related pools. */
3024 	pool_init(&uvm_vmspace_pool, sizeof(struct vmspace), 0,
3025 	    IPL_NONE, PR_WAITOK, "vmsppl", NULL);
3026 	pool_init(&uvm_map_entry_pool, sizeof(struct vm_map_entry), 0,
3027 	    IPL_VM, PR_WAITOK, "vmmpepl", NULL);
3028 	pool_init(&uvm_map_entry_kmem_pool, sizeof(struct vm_map_entry), 0,
3029 	    IPL_VM, 0, "vmmpekpl", NULL);
3030 	pool_sethiwat(&uvm_map_entry_pool, 8192);
3031 
3032 	uvm_addr_init();
3033 }
3034 
3035 #if defined(DDB)
3036 
3037 /*
3038  * DDB hooks
3039  */
3040 
3041 /*
3042  * uvm_map_printit: actually prints the map
3043  */
3044 void
3045 uvm_map_printit(struct vm_map *map, boolean_t full,
3046     int (*pr)(const char *, ...))
3047 {
3048 	struct vmspace			*vm;
3049 	struct vm_map_entry		*entry;
3050 	struct uvm_addr_state		*free;
3051 	int				 in_free, i;
3052 	char				 buf[8];
3053 
3054 	(*pr)("MAP %p: [0x%lx->0x%lx]\n", map, map->min_offset,map->max_offset);
3055 	(*pr)("\tbrk() allocate range: 0x%lx-0x%lx\n",
3056 	    map->b_start, map->b_end);
3057 	(*pr)("\tstack allocate range: 0x%lx-0x%lx\n",
3058 	    map->s_start, map->s_end);
3059 	(*pr)("\tsz=%u, ref=%d, version=%u, flags=0x%x\n",
3060 	    map->size, map->ref_count, map->timestamp,
3061 	    map->flags);
3062 	(*pr)("\tpmap=%p(resident=%d)\n", map->pmap,
3063 	    pmap_resident_count(map->pmap));
3064 
3065 	/* struct vmspace handling. */
3066 	if (map->flags & VM_MAP_ISVMSPACE) {
3067 		vm = (struct vmspace *)map;
3068 
3069 		(*pr)("\tvm_refcnt=%d vm_shm=%p vm_rssize=%u vm_swrss=%u\n",
3070 		    vm->vm_refcnt, vm->vm_shm, vm->vm_rssize, vm->vm_swrss);
3071 		(*pr)("\tvm_tsize=%u vm_dsize=%u\n",
3072 		    vm->vm_tsize, vm->vm_dsize);
3073 		(*pr)("\tvm_taddr=%p vm_daddr=%p\n",
3074 		    vm->vm_taddr, vm->vm_daddr);
3075 		(*pr)("\tvm_maxsaddr=%p vm_minsaddr=%p\n",
3076 		    vm->vm_maxsaddr, vm->vm_minsaddr);
3077 	}
3078 
3079 	if (!full)
3080 		goto print_uaddr;
3081 	RBT_FOREACH(entry, uvm_map_addr, &map->addr) {
3082 		(*pr)(" - %p: 0x%lx->0x%lx: obj=%p/0x%llx, amap=%p/%d\n",
3083 		    entry, entry->start, entry->end, entry->object.uvm_obj,
3084 		    (long long)entry->offset, entry->aref.ar_amap,
3085 		    entry->aref.ar_pageoff);
3086 		(*pr)("\tsubmap=%c, cow=%c, nc=%c, stack=%c, prot(max)=%d/%d, inh=%d, "
3087 		    "wc=%d, adv=%d\n",
3088 		    (entry->etype & UVM_ET_SUBMAP) ? 'T' : 'F',
3089 		    (entry->etype & UVM_ET_COPYONWRITE) ? 'T' : 'F',
3090 		    (entry->etype & UVM_ET_NEEDSCOPY) ? 'T' : 'F',
3091 		    (entry->etype & UVM_ET_STACK) ? 'T' : 'F',
3092 		    entry->protection, entry->max_protection,
3093 		    entry->inheritance, entry->wired_count, entry->advice);
3094 
3095 		free = uvm_map_uaddr_e(map, entry);
3096 		in_free = (free != NULL);
3097 		(*pr)("\thole=%c, free=%c, guard=0x%lx, "
3098 		    "free=0x%lx-0x%lx\n",
3099 		    (entry->etype & UVM_ET_HOLE) ? 'T' : 'F',
3100 		    in_free ? 'T' : 'F',
3101 		    entry->guard,
3102 		    VMMAP_FREE_START(entry), VMMAP_FREE_END(entry));
3103 		(*pr)("\tfspace_augment=%lu\n", entry->fspace_augment);
3104 		(*pr)("\tfreemapped=%c, uaddr=%p\n",
3105 		    (entry->etype & UVM_ET_FREEMAPPED) ? 'T' : 'F', free);
3106 		if (free) {
3107 			(*pr)("\t\t(0x%lx-0x%lx %s)\n",
3108 			    free->uaddr_minaddr, free->uaddr_maxaddr,
3109 			    free->uaddr_functions->uaddr_name);
3110 		}
3111 	}
3112 
3113 print_uaddr:
3114 	uvm_addr_print(map->uaddr_exe, "exe", full, pr);
3115 	for (i = 0; i < nitems(map->uaddr_any); i++) {
3116 		snprintf(&buf[0], sizeof(buf), "any[%d]", i);
3117 		uvm_addr_print(map->uaddr_any[i], &buf[0], full, pr);
3118 	}
3119 	uvm_addr_print(map->uaddr_brk_stack, "brk/stack", full, pr);
3120 }
3121 
3122 /*
3123  * uvm_object_printit: actually prints the object
3124  */
3125 void
3126 uvm_object_printit(uobj, full, pr)
3127 	struct uvm_object *uobj;
3128 	boolean_t full;
3129 	int (*pr)(const char *, ...);
3130 {
3131 	struct vm_page *pg;
3132 	int cnt = 0;
3133 
3134 	(*pr)("OBJECT %p: pgops=%p, npages=%d, ",
3135 	    uobj, uobj->pgops, uobj->uo_npages);
3136 	if (UVM_OBJ_IS_KERN_OBJECT(uobj))
3137 		(*pr)("refs=<SYSTEM>\n");
3138 	else
3139 		(*pr)("refs=%d\n", uobj->uo_refs);
3140 
3141 	if (!full) {
3142 		return;
3143 	}
3144 	(*pr)("  PAGES <pg,offset>:\n  ");
3145 	RBT_FOREACH(pg, uvm_objtree, &uobj->memt) {
3146 		(*pr)("<%p,0x%llx> ", pg, (long long)pg->offset);
3147 		if ((cnt % 3) == 2) {
3148 			(*pr)("\n  ");
3149 		}
3150 		cnt++;
3151 	}
3152 	if ((cnt % 3) != 2) {
3153 		(*pr)("\n");
3154 	}
3155 }
3156 
3157 /*
3158  * uvm_page_printit: actually print the page
3159  */
3160 static const char page_flagbits[] =
3161 	"\20\1BUSY\2WANTED\3TABLED\4CLEAN\5CLEANCHK\6RELEASED\7FAKE\10RDONLY"
3162 	"\11ZERO\12DEV\15PAGER1\21FREE\22INACTIVE\23ACTIVE\25ANON\26AOBJ"
3163 	"\27ENCRYPT\31PMAP0\32PMAP1\33PMAP2\34PMAP3\35PMAP4\36PMAP5";
3164 
3165 void
3166 uvm_page_printit(pg, full, pr)
3167 	struct vm_page *pg;
3168 	boolean_t full;
3169 	int (*pr)(const char *, ...);
3170 {
3171 	struct vm_page *tpg;
3172 	struct uvm_object *uobj;
3173 	struct pglist *pgl;
3174 
3175 	(*pr)("PAGE %p:\n", pg);
3176 	(*pr)("  flags=%b, vers=%d, wire_count=%d, pa=0x%llx\n",
3177 	    pg->pg_flags, page_flagbits, pg->pg_version, pg->wire_count,
3178 	    (long long)pg->phys_addr);
3179 	(*pr)("  uobject=%p, uanon=%p, offset=0x%llx\n",
3180 	    pg->uobject, pg->uanon, (long long)pg->offset);
3181 #if defined(UVM_PAGE_TRKOWN)
3182 	if (pg->pg_flags & PG_BUSY)
3183 		(*pr)("  owning thread = %d, tag=%s",
3184 		    pg->owner, pg->owner_tag);
3185 	else
3186 		(*pr)("  page not busy, no owner");
3187 #else
3188 	(*pr)("  [page ownership tracking disabled]");
3189 #endif
3190 	(*pr)("\tvm_page_md %p\n", &pg->mdpage);
3191 
3192 	if (!full)
3193 		return;
3194 
3195 	/* cross-verify object/anon */
3196 	if ((pg->pg_flags & PQ_FREE) == 0) {
3197 		if (pg->pg_flags & PQ_ANON) {
3198 			if (pg->uanon == NULL || pg->uanon->an_page != pg)
3199 			    (*pr)("  >>> ANON DOES NOT POINT HERE <<< (%p)\n",
3200 				(pg->uanon) ? pg->uanon->an_page : NULL);
3201 			else
3202 				(*pr)("  anon backpointer is OK\n");
3203 		} else {
3204 			uobj = pg->uobject;
3205 			if (uobj) {
3206 				(*pr)("  checking object list\n");
3207 				RBT_FOREACH(tpg, uvm_objtree, &uobj->memt) {
3208 					if (tpg == pg) {
3209 						break;
3210 					}
3211 				}
3212 				if (tpg)
3213 					(*pr)("  page found on object list\n");
3214 				else
3215 					(*pr)("  >>> PAGE NOT FOUND "
3216 					    "ON OBJECT LIST! <<<\n");
3217 			}
3218 		}
3219 	}
3220 
3221 	/* cross-verify page queue */
3222 	if (pg->pg_flags & PQ_FREE) {
3223 		if (uvm_pmr_isfree(pg))
3224 			(*pr)("  page found in uvm_pmemrange\n");
3225 		else
3226 			(*pr)("  >>> page not found in uvm_pmemrange <<<\n");
3227 		pgl = NULL;
3228 	} else if (pg->pg_flags & PQ_INACTIVE) {
3229 		pgl = (pg->pg_flags & PQ_SWAPBACKED) ?
3230 		    &uvm.page_inactive_swp : &uvm.page_inactive_obj;
3231 	} else if (pg->pg_flags & PQ_ACTIVE) {
3232 		pgl = &uvm.page_active;
3233  	} else {
3234 		pgl = NULL;
3235 	}
3236 
3237 	if (pgl) {
3238 		(*pr)("  checking pageq list\n");
3239 		TAILQ_FOREACH(tpg, pgl, pageq) {
3240 			if (tpg == pg) {
3241 				break;
3242 			}
3243 		}
3244 		if (tpg)
3245 			(*pr)("  page found on pageq list\n");
3246 		else
3247 			(*pr)("  >>> PAGE NOT FOUND ON PAGEQ LIST! <<<\n");
3248 	}
3249 }
3250 #endif
3251 
3252 /*
3253  * uvm_map_protect: change map protection
3254  *
3255  * => set_max means set max_protection.
3256  * => map must be unlocked.
3257  */
3258 int
3259 uvm_map_protect(struct vm_map *map, vaddr_t start, vaddr_t end,
3260     vm_prot_t new_prot, boolean_t set_max)
3261 {
3262 	struct vm_map_entry *first, *iter;
3263 	vm_prot_t old_prot;
3264 	vm_prot_t mask;
3265 	int error;
3266 
3267 	if (start > end)
3268 		return EINVAL;
3269 	start = MAX(start, map->min_offset);
3270 	end = MIN(end, map->max_offset);
3271 	if (start >= end)
3272 		return 0;
3273 
3274 	error = 0;
3275 	vm_map_lock(map);
3276 
3277 	/*
3278 	 * Set up first and last.
3279 	 * - first will contain first entry at or after start.
3280 	 */
3281 	first = uvm_map_entrybyaddr(&map->addr, start);
3282 	KDASSERT(first != NULL);
3283 	if (first->end <= start)
3284 		first = RBT_NEXT(uvm_map_addr, first);
3285 
3286 	/* First, check for protection violations. */
3287 	for (iter = first; iter != NULL && iter->start < end;
3288 	    iter = RBT_NEXT(uvm_map_addr, iter)) {
3289 		/* Treat memory holes as free space. */
3290 		if (iter->start == iter->end || UVM_ET_ISHOLE(iter))
3291 			continue;
3292 
3293 		if (UVM_ET_ISSUBMAP(iter)) {
3294 			error = EINVAL;
3295 			goto out;
3296 		}
3297 		if ((new_prot & iter->max_protection) != new_prot) {
3298 			error = EACCES;
3299 			goto out;
3300 		}
3301 		if (map == kernel_map &&
3302 		    (new_prot & (PROT_WRITE | PROT_EXEC)) == (PROT_WRITE | PROT_EXEC))
3303 			panic("uvm_map_protect: kernel map W^X violation requested");
3304 	}
3305 
3306 	/* Fix protections.  */
3307 	for (iter = first; iter != NULL && iter->start < end;
3308 	    iter = RBT_NEXT(uvm_map_addr, iter)) {
3309 		/* Treat memory holes as free space. */
3310 		if (iter->start == iter->end || UVM_ET_ISHOLE(iter))
3311 			continue;
3312 
3313 		old_prot = iter->protection;
3314 
3315 		/*
3316 		 * Skip adapting protection iff old and new protection
3317 		 * are equal.
3318 		 */
3319 		if (set_max) {
3320 			if (old_prot == (new_prot & old_prot) &&
3321 			    iter->max_protection == new_prot)
3322 				continue;
3323 		} else {
3324 			if (old_prot == new_prot)
3325 				continue;
3326 		}
3327 
3328 		UVM_MAP_CLIP_START(map, iter, start);
3329 		UVM_MAP_CLIP_END(map, iter, end);
3330 
3331 		if (set_max) {
3332 			iter->max_protection = new_prot;
3333 			iter->protection &= new_prot;
3334 		} else
3335 			iter->protection = new_prot;
3336 
3337 		/*
3338 		 * update physical map if necessary.  worry about copy-on-write
3339 		 * here -- CHECK THIS XXX
3340 		 */
3341 		if (iter->protection != old_prot) {
3342 			mask = UVM_ET_ISCOPYONWRITE(iter) ?
3343 			    ~PROT_WRITE : PROT_MASK;
3344 
3345 			/* XXX should only wserial++ if no split occurs */
3346 			if (iter->protection & PROT_WRITE)
3347 				map->wserial++;
3348 
3349 			/* update pmap */
3350 			if ((iter->protection & mask) == PROT_NONE &&
3351 			    VM_MAPENT_ISWIRED(iter)) {
3352 				/*
3353 				 * TODO(ariane) this is stupid. wired_count
3354 				 * is 0 if not wired, otherwise anything
3355 				 * larger than 0 (incremented once each time
3356 				 * wire is called).
3357 				 * Mostly to be able to undo the damage on
3358 				 * failure. Not the actually be a wired
3359 				 * refcounter...
3360 				 * Originally: iter->wired_count--;
3361 				 * (don't we have to unwire this in the pmap
3362 				 * as well?)
3363 				 */
3364 				iter->wired_count = 0;
3365 			}
3366 			pmap_protect(map->pmap, iter->start, iter->end,
3367 			    iter->protection & mask);
3368 		}
3369 
3370 		/*
3371 		 * If the map is configured to lock any future mappings,
3372 		 * wire this entry now if the old protection was PROT_NONE
3373 		 * and the new protection is not PROT_NONE.
3374 		 */
3375 		if ((map->flags & VM_MAP_WIREFUTURE) != 0 &&
3376 		    VM_MAPENT_ISWIRED(iter) == 0 &&
3377 		    old_prot == PROT_NONE &&
3378 		    new_prot != PROT_NONE) {
3379 			if (uvm_map_pageable(map, iter->start, iter->end,
3380 			    FALSE, UVM_LK_ENTER | UVM_LK_EXIT) != 0) {
3381 				/*
3382 				 * If locking the entry fails, remember the
3383 				 * error if it's the first one.  Note we
3384 				 * still continue setting the protection in
3385 				 * the map, but it will return the resource
3386 				 * storage condition regardless.
3387 				 *
3388 				 * XXX Ignore what the actual error is,
3389 				 * XXX just call it a resource shortage
3390 				 * XXX so that it doesn't get confused
3391 				 * XXX what uvm_map_protect() itself would
3392 				 * XXX normally return.
3393 				 */
3394 				error = ENOMEM;
3395 			}
3396 		}
3397 	}
3398 	pmap_update(map->pmap);
3399 
3400 out:
3401 	vm_map_unlock(map);
3402 	return error;
3403 }
3404 
3405 /*
3406  * uvmspace_alloc: allocate a vmspace structure.
3407  *
3408  * - structure includes vm_map and pmap
3409  * - XXX: no locking on this structure
3410  * - refcnt set to 1, rest must be init'd by caller
3411  */
3412 struct vmspace *
3413 uvmspace_alloc(vaddr_t min, vaddr_t max, boolean_t pageable,
3414     boolean_t remove_holes)
3415 {
3416 	struct vmspace *vm;
3417 
3418 	vm = pool_get(&uvm_vmspace_pool, PR_WAITOK | PR_ZERO);
3419 	uvmspace_init(vm, NULL, min, max, pageable, remove_holes);
3420 	return (vm);
3421 }
3422 
3423 /*
3424  * uvmspace_init: initialize a vmspace structure.
3425  *
3426  * - XXX: no locking on this structure
3427  * - refcnt set to 1, rest must be init'd by caller
3428  */
3429 void
3430 uvmspace_init(struct vmspace *vm, struct pmap *pmap, vaddr_t min, vaddr_t max,
3431     boolean_t pageable, boolean_t remove_holes)
3432 {
3433 	KASSERT(pmap == NULL || pmap == pmap_kernel());
3434 
3435 	if (pmap)
3436 		pmap_reference(pmap);
3437 	else
3438 		pmap = pmap_create();
3439 	vm->vm_map.pmap = pmap;
3440 
3441 	uvm_map_setup(&vm->vm_map, min, max,
3442 	    (pageable ? VM_MAP_PAGEABLE : 0) | VM_MAP_ISVMSPACE);
3443 
3444 	vm->vm_refcnt = 1;
3445 
3446 	if (remove_holes)
3447 		pmap_remove_holes(vm);
3448 }
3449 
3450 /*
3451  * uvmspace_share: share a vmspace between two processes
3452  *
3453  * - XXX: no locking on vmspace
3454  * - used for vfork
3455  */
3456 
3457 struct vmspace *
3458 uvmspace_share(struct process *pr)
3459 {
3460 	struct vmspace *vm = pr->ps_vmspace;
3461 
3462 	vm->vm_refcnt++;
3463 	return vm;
3464 }
3465 
3466 /*
3467  * uvmspace_exec: the process wants to exec a new program
3468  *
3469  * - XXX: no locking on vmspace
3470  */
3471 
3472 void
3473 uvmspace_exec(struct proc *p, vaddr_t start, vaddr_t end)
3474 {
3475 	struct process *pr = p->p_p;
3476 	struct vmspace *nvm, *ovm = pr->ps_vmspace;
3477 	struct vm_map *map = &ovm->vm_map;
3478 	struct uvm_map_deadq dead_entries;
3479 
3480 	KASSERT((start & (vaddr_t)PAGE_MASK) == 0);
3481 	KASSERT((end & (vaddr_t)PAGE_MASK) == 0 ||
3482 	    (end & (vaddr_t)PAGE_MASK) == (vaddr_t)PAGE_MASK);
3483 
3484 	pmap_unuse_final(p);   /* before stack addresses go away */
3485 	TAILQ_INIT(&dead_entries);
3486 
3487 	/* see if more than one process is using this vmspace...  */
3488 	if (ovm->vm_refcnt == 1) {
3489 		/*
3490 		 * If pr is the only process using its vmspace then
3491 		 * we can safely recycle that vmspace for the program
3492 		 * that is being exec'd.
3493 		 */
3494 
3495 #ifdef SYSVSHM
3496 		/*
3497 		 * SYSV SHM semantics require us to kill all segments on an exec
3498 		 */
3499 		if (ovm->vm_shm)
3500 			shmexit(ovm);
3501 #endif
3502 
3503 		/*
3504 		 * POSIX 1003.1b -- "lock future mappings" is revoked
3505 		 * when a process execs another program image.
3506 		 */
3507 		vm_map_lock(map);
3508 		vm_map_modflags(map, 0, VM_MAP_WIREFUTURE);
3509 
3510 		/*
3511 		 * now unmap the old program
3512 		 *
3513 		 * Instead of attempting to keep the map valid, we simply
3514 		 * nuke all entries and ask uvm_map_setup to reinitialize
3515 		 * the map to the new boundaries.
3516 		 *
3517 		 * uvm_unmap_remove will actually nuke all entries for us
3518 		 * (as in, not replace them with free-memory entries).
3519 		 */
3520 		uvm_unmap_remove(map, map->min_offset, map->max_offset,
3521 		    &dead_entries, TRUE, FALSE);
3522 
3523 		KDASSERT(RBT_EMPTY(uvm_map_addr, &map->addr));
3524 
3525 		/* Nuke statistics and boundaries. */
3526 		memset(&ovm->vm_startcopy, 0,
3527 		    (caddr_t) (ovm + 1) - (caddr_t) &ovm->vm_startcopy);
3528 
3529 
3530 		if (end & (vaddr_t)PAGE_MASK) {
3531 			end += 1;
3532 			if (end == 0) /* overflow */
3533 				end -= PAGE_SIZE;
3534 		}
3535 
3536 		/* Setup new boundaries and populate map with entries. */
3537 		map->min_offset = start;
3538 		map->max_offset = end;
3539 		uvm_map_setup_entries(map);
3540 		vm_map_unlock(map);
3541 
3542 		/* but keep MMU holes unavailable */
3543 		pmap_remove_holes(ovm);
3544 	} else {
3545 		/*
3546 		 * pr's vmspace is being shared, so we can't reuse
3547 		 * it for pr since it is still being used for others.
3548 		 * allocate a new vmspace for pr
3549 		 */
3550 		nvm = uvmspace_alloc(start, end,
3551 		    (map->flags & VM_MAP_PAGEABLE) ? TRUE : FALSE, TRUE);
3552 
3553 		/* install new vmspace and drop our ref to the old one. */
3554 		pmap_deactivate(p);
3555 		p->p_vmspace = pr->ps_vmspace = nvm;
3556 		pmap_activate(p);
3557 
3558 		uvmspace_free(ovm);
3559 	}
3560 
3561 	/* Release dead entries */
3562 	uvm_unmap_detach(&dead_entries, 0);
3563 }
3564 
3565 /*
3566  * uvmspace_free: free a vmspace data structure
3567  *
3568  * - XXX: no locking on vmspace
3569  */
3570 void
3571 uvmspace_free(struct vmspace *vm)
3572 {
3573 	if (--vm->vm_refcnt == 0) {
3574 		/*
3575 		 * lock the map, to wait out all other references to it.  delete
3576 		 * all of the mappings and pages they hold, then call the pmap
3577 		 * module to reclaim anything left.
3578 		 */
3579 #ifdef SYSVSHM
3580 		/* Get rid of any SYSV shared memory segments. */
3581 		if (vm->vm_shm != NULL)
3582 			shmexit(vm);
3583 #endif
3584 
3585 		uvm_map_teardown(&vm->vm_map);
3586 		pool_put(&uvm_vmspace_pool, vm);
3587 	}
3588 }
3589 
3590 /*
3591  * uvm_share: Map the address range [srcaddr, srcaddr + sz) in
3592  * srcmap to the address range [dstaddr, dstaddr + sz) in
3593  * dstmap.
3594  *
3595  * The whole address range in srcmap must be backed by an object
3596  * (no holes).
3597  *
3598  * If successful, the address ranges share memory and the destination
3599  * address range uses the protection flags in prot.
3600  *
3601  * This routine assumes that sz is a multiple of PAGE_SIZE and
3602  * that dstaddr and srcaddr are page-aligned.
3603  */
3604 int
3605 uvm_share(struct vm_map *dstmap, vaddr_t dstaddr, vm_prot_t prot,
3606     struct vm_map *srcmap, vaddr_t srcaddr, vsize_t sz)
3607 {
3608 	int ret = 0;
3609 	vaddr_t unmap_end;
3610 	vaddr_t dstva;
3611 	vsize_t off, len, n = sz;
3612 	struct vm_map_entry *first = NULL, *last = NULL;
3613 	struct vm_map_entry *src_entry, *psrc_entry = NULL;
3614 	struct uvm_map_deadq dead;
3615 
3616 	if (srcaddr >= srcmap->max_offset || sz > srcmap->max_offset - srcaddr)
3617 		return EINVAL;
3618 
3619 	TAILQ_INIT(&dead);
3620 	vm_map_lock(dstmap);
3621 	vm_map_lock_read(srcmap);
3622 
3623 	if (!uvm_map_isavail(dstmap, NULL, &first, &last, dstaddr, sz)) {
3624 		ret = ENOMEM;
3625 		goto exit_unlock;
3626 	}
3627 	if (!uvm_map_lookup_entry(srcmap, srcaddr, &src_entry)) {
3628 		ret = EINVAL;
3629 		goto exit_unlock;
3630 	}
3631 
3632 	unmap_end = dstaddr;
3633 	for (; src_entry != NULL;
3634 	    psrc_entry = src_entry,
3635 	    src_entry = RBT_NEXT(uvm_map_addr, src_entry)) {
3636 		/* hole in address space, bail out */
3637 		if (psrc_entry != NULL && psrc_entry->end != src_entry->start)
3638 			break;
3639 		if (src_entry->start >= srcaddr + sz)
3640 			break;
3641 
3642 		if (UVM_ET_ISSUBMAP(src_entry))
3643 			panic("uvm_share: encountered a submap (illegal)");
3644 		if (!UVM_ET_ISCOPYONWRITE(src_entry) &&
3645 		    UVM_ET_ISNEEDSCOPY(src_entry))
3646 			panic("uvm_share: non-copy_on_write map entries "
3647 			    "marked needs_copy (illegal)");
3648 
3649 		dstva = dstaddr;
3650 		if (src_entry->start > srcaddr) {
3651 			dstva += src_entry->start - srcaddr;
3652 			off = 0;
3653 		} else
3654 			off = srcaddr - src_entry->start;
3655 
3656 		if (n < src_entry->end - src_entry->start)
3657 			len = n;
3658 		else
3659 			len = src_entry->end - src_entry->start;
3660 		n -= len;
3661 
3662 		if (uvm_mapent_share(dstmap, dstva, len, off, prot, prot,
3663 		    srcmap, src_entry, &dead) == NULL)
3664 			break;
3665 
3666 		unmap_end = dstva + len;
3667 		if (n == 0)
3668 			goto exit_unlock;
3669 	}
3670 
3671 	ret = EINVAL;
3672 	uvm_unmap_remove(dstmap, dstaddr, unmap_end, &dead, FALSE, TRUE);
3673 
3674 exit_unlock:
3675 	vm_map_unlock_read(srcmap);
3676 	vm_map_unlock(dstmap);
3677 	uvm_unmap_detach(&dead, 0);
3678 
3679 	return ret;
3680 }
3681 
3682 /*
3683  * Clone map entry into other map.
3684  *
3685  * Mapping will be placed at dstaddr, for the same length.
3686  * Space must be available.
3687  * Reference counters are incremented.
3688  */
3689 struct vm_map_entry *
3690 uvm_mapent_clone(struct vm_map *dstmap, vaddr_t dstaddr, vsize_t dstlen,
3691     vsize_t off, vm_prot_t prot, vm_prot_t maxprot,
3692     struct vm_map_entry *old_entry, struct uvm_map_deadq *dead,
3693     int mapent_flags, int amap_share_flags)
3694 {
3695 	struct vm_map_entry *new_entry, *first, *last;
3696 
3697 	KDASSERT(!UVM_ET_ISSUBMAP(old_entry));
3698 
3699 	/* Create new entry (linked in on creation). Fill in first, last. */
3700 	first = last = NULL;
3701 	if (!uvm_map_isavail(dstmap, NULL, &first, &last, dstaddr, dstlen)) {
3702 		panic("uvmspace_fork: no space in map for "
3703 		    "entry in empty map");
3704 	}
3705 	new_entry = uvm_map_mkentry(dstmap, first, last,
3706 	    dstaddr, dstlen, mapent_flags, dead, NULL);
3707 	if (new_entry == NULL)
3708 		return NULL;
3709 	/* old_entry -> new_entry */
3710 	new_entry->object = old_entry->object;
3711 	new_entry->offset = old_entry->offset;
3712 	new_entry->aref = old_entry->aref;
3713 	new_entry->etype |= old_entry->etype & ~UVM_ET_FREEMAPPED;
3714 	new_entry->protection = prot;
3715 	new_entry->max_protection = maxprot;
3716 	new_entry->inheritance = old_entry->inheritance;
3717 	new_entry->advice = old_entry->advice;
3718 
3719 	/* gain reference to object backing the map (can't be a submap). */
3720 	if (new_entry->aref.ar_amap) {
3721 		new_entry->aref.ar_pageoff += off >> PAGE_SHIFT;
3722 		amap_ref(new_entry->aref.ar_amap, new_entry->aref.ar_pageoff,
3723 		    (new_entry->end - new_entry->start) >> PAGE_SHIFT,
3724 		    amap_share_flags);
3725 	}
3726 
3727 	if (UVM_ET_ISOBJ(new_entry) &&
3728 	    new_entry->object.uvm_obj->pgops->pgo_reference) {
3729 		new_entry->offset += off;
3730 		new_entry->object.uvm_obj->pgops->pgo_reference
3731 		    (new_entry->object.uvm_obj);
3732 	}
3733 
3734 	return new_entry;
3735 }
3736 
3737 struct vm_map_entry *
3738 uvm_mapent_share(struct vm_map *dstmap, vaddr_t dstaddr, vsize_t dstlen,
3739     vsize_t off, vm_prot_t prot, vm_prot_t maxprot, struct vm_map *old_map,
3740     struct vm_map_entry *old_entry, struct uvm_map_deadq *dead)
3741 {
3742 	/*
3743 	 * If old_entry refers to a copy-on-write region that has not yet been
3744 	 * written to (needs_copy flag is set), then we need to allocate a new
3745 	 * amap for old_entry.
3746 	 *
3747 	 * If we do not do this, and the process owning old_entry does a copy-on
3748 	 * write later, old_entry and new_entry will refer to different memory
3749 	 * regions, and the memory between the processes is no longer shared.
3750 	 *
3751 	 * [in other words, we need to clear needs_copy]
3752 	 */
3753 
3754 	if (UVM_ET_ISNEEDSCOPY(old_entry)) {
3755 		/* get our own amap, clears needs_copy */
3756 		amap_copy(old_map, old_entry, M_WAITOK, FALSE,
3757 		    0, 0);
3758 		/* XXXCDC: WAITOK??? */
3759 	}
3760 
3761 	return uvm_mapent_clone(dstmap, dstaddr, dstlen, off,
3762 	    prot, maxprot, old_entry, dead, 0, AMAP_SHARED);
3763 }
3764 
3765 /*
3766  * share the mapping: this means we want the old and
3767  * new entries to share amaps and backing objects.
3768  */
3769 struct vm_map_entry *
3770 uvm_mapent_forkshared(struct vmspace *new_vm, struct vm_map *new_map,
3771     struct vm_map *old_map,
3772     struct vm_map_entry *old_entry, struct uvm_map_deadq *dead)
3773 {
3774 	struct vm_map_entry *new_entry;
3775 
3776 	new_entry = uvm_mapent_share(new_map, old_entry->start,
3777 	    old_entry->end - old_entry->start, 0, old_entry->protection,
3778 	    old_entry->max_protection, old_map, old_entry, dead);
3779 
3780 	/*
3781 	 * pmap_copy the mappings: this routine is optional
3782 	 * but if it is there it will reduce the number of
3783 	 * page faults in the new proc.
3784 	 */
3785 	if (!UVM_ET_ISHOLE(new_entry))
3786 		pmap_copy(new_map->pmap, old_map->pmap, new_entry->start,
3787 		    (new_entry->end - new_entry->start), new_entry->start);
3788 
3789 	return (new_entry);
3790 }
3791 
3792 /*
3793  * copy-on-write the mapping (using mmap's
3794  * MAP_PRIVATE semantics)
3795  *
3796  * allocate new_entry, adjust reference counts.
3797  * (note that new references are read-only).
3798  */
3799 struct vm_map_entry *
3800 uvm_mapent_forkcopy(struct vmspace *new_vm, struct vm_map *new_map,
3801     struct vm_map *old_map,
3802     struct vm_map_entry *old_entry, struct uvm_map_deadq *dead)
3803 {
3804 	struct vm_map_entry	*new_entry;
3805 	boolean_t		 protect_child;
3806 
3807 	new_entry = uvm_mapent_clone(new_map, old_entry->start,
3808 	    old_entry->end - old_entry->start, 0, old_entry->protection,
3809 	    old_entry->max_protection, old_entry, dead, 0, 0);
3810 
3811 	new_entry->etype |=
3812 	    (UVM_ET_COPYONWRITE|UVM_ET_NEEDSCOPY);
3813 
3814 	/*
3815 	 * the new entry will need an amap.  it will either
3816 	 * need to be copied from the old entry or created
3817 	 * from scratch (if the old entry does not have an
3818 	 * amap).  can we defer this process until later
3819 	 * (by setting "needs_copy") or do we need to copy
3820 	 * the amap now?
3821 	 *
3822 	 * we must copy the amap now if any of the following
3823 	 * conditions hold:
3824 	 * 1. the old entry has an amap and that amap is
3825 	 *    being shared.  this means that the old (parent)
3826 	 *    process is sharing the amap with another
3827 	 *    process.  if we do not clear needs_copy here
3828 	 *    we will end up in a situation where both the
3829 	 *    parent and child process are referring to the
3830 	 *    same amap with "needs_copy" set.  if the
3831 	 *    parent write-faults, the fault routine will
3832 	 *    clear "needs_copy" in the parent by allocating
3833 	 *    a new amap.   this is wrong because the
3834 	 *    parent is supposed to be sharing the old amap
3835 	 *    and the new amap will break that.
3836 	 *
3837 	 * 2. if the old entry has an amap and a non-zero
3838 	 *    wire count then we are going to have to call
3839 	 *    amap_cow_now to avoid page faults in the
3840 	 *    parent process.   since amap_cow_now requires
3841 	 *    "needs_copy" to be clear we might as well
3842 	 *    clear it here as well.
3843 	 *
3844 	 */
3845 	if (old_entry->aref.ar_amap != NULL &&
3846 	    ((amap_flags(old_entry->aref.ar_amap) &
3847 	    AMAP_SHARED) != 0 ||
3848 	    VM_MAPENT_ISWIRED(old_entry))) {
3849 		amap_copy(new_map, new_entry, M_WAITOK, FALSE,
3850 		    0, 0);
3851 		/* XXXCDC: M_WAITOK ... ok? */
3852 	}
3853 
3854 	/*
3855 	 * if the parent's entry is wired down, then the
3856 	 * parent process does not want page faults on
3857 	 * access to that memory.  this means that we
3858 	 * cannot do copy-on-write because we can't write
3859 	 * protect the old entry.   in this case we
3860 	 * resolve all copy-on-write faults now, using
3861 	 * amap_cow_now.   note that we have already
3862 	 * allocated any needed amap (above).
3863 	 */
3864 	if (VM_MAPENT_ISWIRED(old_entry)) {
3865 		/*
3866 		 * resolve all copy-on-write faults now
3867 		 * (note that there is nothing to do if
3868 		 * the old mapping does not have an amap).
3869 		 * XXX: is it worthwhile to bother with
3870 		 * pmap_copy in this case?
3871 		 */
3872 		if (old_entry->aref.ar_amap)
3873 			amap_cow_now(new_map, new_entry);
3874 	} else {
3875 		if (old_entry->aref.ar_amap) {
3876 			/*
3877 			 * setup mappings to trigger copy-on-write faults
3878 			 * we must write-protect the parent if it has
3879 			 * an amap and it is not already "needs_copy"...
3880 			 * if it is already "needs_copy" then the parent
3881 			 * has already been write-protected by a previous
3882 			 * fork operation.
3883 			 *
3884 			 * if we do not write-protect the parent, then
3885 			 * we must be sure to write-protect the child
3886 			 * after the pmap_copy() operation.
3887 			 *
3888 			 * XXX: pmap_copy should have some way of telling
3889 			 * us that it didn't do anything so we can avoid
3890 			 * calling pmap_protect needlessly.
3891 			 */
3892 			if (!UVM_ET_ISNEEDSCOPY(old_entry)) {
3893 				if (old_entry->max_protection & PROT_WRITE) {
3894 					pmap_protect(old_map->pmap,
3895 					    old_entry->start,
3896 					    old_entry->end,
3897 					    old_entry->protection &
3898 					    ~PROT_WRITE);
3899 					pmap_update(old_map->pmap);
3900 				}
3901 				old_entry->etype |= UVM_ET_NEEDSCOPY;
3902 			}
3903 
3904 	  		/* parent must now be write-protected */
3905 	  		protect_child = FALSE;
3906 		} else {
3907 			/*
3908 			 * we only need to protect the child if the
3909 			 * parent has write access.
3910 			 */
3911 			if (old_entry->max_protection & PROT_WRITE)
3912 				protect_child = TRUE;
3913 			else
3914 				protect_child = FALSE;
3915 		}
3916 		/*
3917 		 * copy the mappings
3918 		 * XXX: need a way to tell if this does anything
3919 		 */
3920 		if (!UVM_ET_ISHOLE(new_entry))
3921 			pmap_copy(new_map->pmap, old_map->pmap,
3922 			    new_entry->start,
3923 			    (old_entry->end - old_entry->start),
3924 			    old_entry->start);
3925 
3926 		/* protect the child's mappings if necessary */
3927 		if (protect_child) {
3928 			pmap_protect(new_map->pmap, new_entry->start,
3929 			    new_entry->end,
3930 			    new_entry->protection &
3931 			    ~PROT_WRITE);
3932 		}
3933 	}
3934 
3935 	return (new_entry);
3936 }
3937 
3938 /*
3939  * zero the mapping: the new entry will be zero initialized
3940  */
3941 struct vm_map_entry *
3942 uvm_mapent_forkzero(struct vmspace *new_vm, struct vm_map *new_map,
3943     struct vm_map *old_map,
3944     struct vm_map_entry *old_entry, struct uvm_map_deadq *dead)
3945 {
3946 	struct vm_map_entry *new_entry;
3947 
3948 	new_entry = uvm_mapent_clone(new_map, old_entry->start,
3949 	    old_entry->end - old_entry->start, 0, old_entry->protection,
3950 	    old_entry->max_protection, old_entry, dead, 0, 0);
3951 
3952 	new_entry->etype |=
3953 	    (UVM_ET_COPYONWRITE|UVM_ET_NEEDSCOPY);
3954 
3955 	if (new_entry->aref.ar_amap) {
3956 		amap_unref(new_entry->aref.ar_amap, new_entry->aref.ar_pageoff,
3957 		    atop(new_entry->end - new_entry->start), 0);
3958 		new_entry->aref.ar_amap = NULL;
3959 		new_entry->aref.ar_pageoff = 0;
3960 	}
3961 
3962 	if (UVM_ET_ISOBJ(new_entry)) {
3963 		if (new_entry->object.uvm_obj->pgops->pgo_detach)
3964 			new_entry->object.uvm_obj->pgops->pgo_detach(
3965 			    new_entry->object.uvm_obj);
3966 		new_entry->object.uvm_obj = NULL;
3967 		new_entry->etype &= ~UVM_ET_OBJ;
3968 	}
3969 
3970 	return (new_entry);
3971 }
3972 
3973 /*
3974  * uvmspace_fork: fork a process' main map
3975  *
3976  * => create a new vmspace for child process from parent.
3977  * => parent's map must not be locked.
3978  */
3979 struct vmspace *
3980 uvmspace_fork(struct process *pr)
3981 {
3982 	struct vmspace *vm1 = pr->ps_vmspace;
3983 	struct vmspace *vm2;
3984 	struct vm_map *old_map = &vm1->vm_map;
3985 	struct vm_map *new_map;
3986 	struct vm_map_entry *old_entry, *new_entry;
3987 	struct uvm_map_deadq dead;
3988 
3989 	vm_map_lock(old_map);
3990 
3991 	vm2 = uvmspace_alloc(old_map->min_offset, old_map->max_offset,
3992 	    (old_map->flags & VM_MAP_PAGEABLE) ? TRUE : FALSE, FALSE);
3993 	memcpy(&vm2->vm_startcopy, &vm1->vm_startcopy,
3994 	    (caddr_t) (vm1 + 1) - (caddr_t) &vm1->vm_startcopy);
3995 	vm2->vm_dused = 0; /* Statistic managed by us. */
3996 	new_map = &vm2->vm_map;
3997 	vm_map_lock(new_map);
3998 
3999 	/* go entry-by-entry */
4000 	TAILQ_INIT(&dead);
4001 	RBT_FOREACH(old_entry, uvm_map_addr, &old_map->addr) {
4002 		if (old_entry->start == old_entry->end)
4003 			continue;
4004 
4005 		/* first, some sanity checks on the old entry */
4006 		if (UVM_ET_ISSUBMAP(old_entry)) {
4007 			panic("fork: encountered a submap during fork "
4008 			    "(illegal)");
4009 		}
4010 
4011 		if (!UVM_ET_ISCOPYONWRITE(old_entry) &&
4012 		    UVM_ET_ISNEEDSCOPY(old_entry)) {
4013 			panic("fork: non-copy_on_write map entry marked "
4014 			    "needs_copy (illegal)");
4015 		}
4016 
4017 		/* Apply inheritance. */
4018 		switch (old_entry->inheritance) {
4019 		case MAP_INHERIT_SHARE:
4020 			new_entry = uvm_mapent_forkshared(vm2, new_map,
4021 			    old_map, old_entry, &dead);
4022 			break;
4023 		case MAP_INHERIT_COPY:
4024 			new_entry = uvm_mapent_forkcopy(vm2, new_map,
4025 			    old_map, old_entry, &dead);
4026 			break;
4027 		case MAP_INHERIT_ZERO:
4028 			new_entry = uvm_mapent_forkzero(vm2, new_map,
4029 			    old_map, old_entry, &dead);
4030 			break;
4031 		default:
4032 			continue;
4033 		}
4034 
4035 	 	/* Update process statistics. */
4036 		if (!UVM_ET_ISHOLE(new_entry))
4037 			new_map->size += new_entry->end - new_entry->start;
4038 		if (!UVM_ET_ISOBJ(new_entry) && !UVM_ET_ISHOLE(new_entry)) {
4039 			vm2->vm_dused += uvmspace_dused(
4040 			    new_map, new_entry->start, new_entry->end);
4041 		}
4042 	}
4043 
4044 	vm_map_unlock(old_map);
4045 	vm_map_unlock(new_map);
4046 
4047 	/*
4048 	 * This can actually happen, if multiple entries described a
4049 	 * space in which an entry was inherited.
4050 	 */
4051 	uvm_unmap_detach(&dead, 0);
4052 
4053 #ifdef SYSVSHM
4054 	if (vm1->vm_shm)
4055 		shmfork(vm1, vm2);
4056 #endif
4057 
4058 	return vm2;
4059 }
4060 
4061 /*
4062  * uvm_map_hint: return the beginning of the best area suitable for
4063  * creating a new mapping with "prot" protection.
4064  */
4065 vaddr_t
4066 uvm_map_hint(struct vmspace *vm, vm_prot_t prot, vaddr_t minaddr,
4067     vaddr_t maxaddr)
4068 {
4069 	vaddr_t addr;
4070 	vaddr_t spacing;
4071 
4072 #ifdef __i386__
4073 	/*
4074 	 * If executable skip first two pages, otherwise start
4075 	 * after data + heap region.
4076 	 */
4077 	if ((prot & PROT_EXEC) != 0 &&
4078 	    (vaddr_t)vm->vm_daddr >= I386_MAX_EXE_ADDR) {
4079 		addr = (PAGE_SIZE*2) +
4080 		    (arc4random() & (I386_MAX_EXE_ADDR / 2 - 1));
4081 		return (round_page(addr));
4082 	}
4083 #endif
4084 
4085 #if defined (__LP64__)
4086 	spacing = MIN(4UL * 1024 * 1024 * 1024, MAXDSIZ) - 1;
4087 #else
4088 	spacing = MIN(1 * 1024 * 1024 * 1024, MAXDSIZ) - 1;
4089 #endif
4090 
4091 	/*
4092 	 * Start malloc/mmap after the brk.
4093 	 */
4094 	addr = (vaddr_t)vm->vm_daddr + BRKSIZ;
4095 	addr = MAX(addr, minaddr);
4096 
4097 	if (addr < maxaddr) {
4098 		while (spacing > maxaddr - addr)
4099 			spacing >>= 1;
4100 	}
4101 	addr += arc4random() & spacing;
4102 	return (round_page(addr));
4103 }
4104 
4105 /*
4106  * uvm_map_submap: punch down part of a map into a submap
4107  *
4108  * => only the kernel_map is allowed to be submapped
4109  * => the purpose of submapping is to break up the locking granularity
4110  *	of a larger map
4111  * => the range specified must have been mapped previously with a uvm_map()
4112  *	call [with uobj==NULL] to create a blank map entry in the main map.
4113  *	[And it had better still be blank!]
4114  * => maps which contain submaps should never be copied or forked.
4115  * => to remove a submap, use uvm_unmap() on the main map
4116  *	and then uvm_map_deallocate() the submap.
4117  * => main map must be unlocked.
4118  * => submap must have been init'd and have a zero reference count.
4119  *	[need not be locked as we don't actually reference it]
4120  */
4121 int
4122 uvm_map_submap(struct vm_map *map, vaddr_t start, vaddr_t end,
4123     struct vm_map *submap)
4124 {
4125 	struct vm_map_entry *entry;
4126 	int result;
4127 
4128 	if (start > map->max_offset || end > map->max_offset ||
4129 	    start < map->min_offset || end < map->min_offset)
4130 		return EINVAL;
4131 
4132 	vm_map_lock(map);
4133 
4134 	if (uvm_map_lookup_entry(map, start, &entry)) {
4135 		UVM_MAP_CLIP_START(map, entry, start);
4136 		UVM_MAP_CLIP_END(map, entry, end);
4137 	} else
4138 		entry = NULL;
4139 
4140 	if (entry != NULL &&
4141 	    entry->start == start && entry->end == end &&
4142 	    entry->object.uvm_obj == NULL && entry->aref.ar_amap == NULL &&
4143 	    !UVM_ET_ISCOPYONWRITE(entry) && !UVM_ET_ISNEEDSCOPY(entry)) {
4144 		entry->etype |= UVM_ET_SUBMAP;
4145 		entry->object.sub_map = submap;
4146 		entry->offset = 0;
4147 		uvm_map_reference(submap);
4148 		result = 0;
4149 	} else
4150 		result = EINVAL;
4151 
4152 	vm_map_unlock(map);
4153 	return(result);
4154 }
4155 
4156 /*
4157  * uvm_map_checkprot: check protection in map
4158  *
4159  * => must allow specific protection in a fully allocated region.
4160  * => map mut be read or write locked by caller.
4161  */
4162 boolean_t
4163 uvm_map_checkprot(struct vm_map *map, vaddr_t start, vaddr_t end,
4164     vm_prot_t protection)
4165 {
4166 	struct vm_map_entry *entry;
4167 
4168 	if (start < map->min_offset || end > map->max_offset || start > end)
4169 		return FALSE;
4170 	if (start == end)
4171 		return TRUE;
4172 
4173 	/*
4174 	 * Iterate entries.
4175 	 */
4176 	for (entry = uvm_map_entrybyaddr(&map->addr, start);
4177 	    entry != NULL && entry->start < end;
4178 	    entry = RBT_NEXT(uvm_map_addr, entry)) {
4179 		/* Fail if a hole is found. */
4180 		if (UVM_ET_ISHOLE(entry) ||
4181 		    (entry->end < end && entry->end != VMMAP_FREE_END(entry)))
4182 			return FALSE;
4183 
4184 		/* Check protection. */
4185 		if ((entry->protection & protection) != protection)
4186 			return FALSE;
4187 	}
4188 	return TRUE;
4189 }
4190 
4191 /*
4192  * uvm_map_create: create map
4193  */
4194 vm_map_t
4195 uvm_map_create(pmap_t pmap, vaddr_t min, vaddr_t max, int flags)
4196 {
4197 	vm_map_t map;
4198 
4199 	map = malloc(sizeof *map, M_VMMAP, M_WAITOK);
4200 	map->pmap = pmap;
4201 	uvm_map_setup(map, min, max, flags);
4202 	return (map);
4203 }
4204 
4205 /*
4206  * uvm_map_deallocate: drop reference to a map
4207  *
4208  * => caller must not lock map
4209  * => we will zap map if ref count goes to zero
4210  */
4211 void
4212 uvm_map_deallocate(vm_map_t map)
4213 {
4214 	int c;
4215 	struct uvm_map_deadq dead;
4216 
4217 	c = --map->ref_count;
4218 	if (c > 0) {
4219 		return;
4220 	}
4221 
4222 	/*
4223 	 * all references gone.   unmap and free.
4224 	 *
4225 	 * No lock required: we are only one to access this map.
4226 	 */
4227 	TAILQ_INIT(&dead);
4228 	uvm_tree_sanity(map, __FILE__, __LINE__);
4229 	uvm_unmap_remove(map, map->min_offset, map->max_offset, &dead,
4230 	    TRUE, FALSE);
4231 	pmap_destroy(map->pmap);
4232 	KASSERT(RBT_EMPTY(uvm_map_addr, &map->addr));
4233 	free(map, M_VMMAP, sizeof *map);
4234 
4235 	uvm_unmap_detach(&dead, 0);
4236 }
4237 
4238 /*
4239  * uvm_map_inherit: set inheritance code for range of addrs in map.
4240  *
4241  * => map must be unlocked
4242  * => note that the inherit code is used during a "fork".  see fork
4243  *	code for details.
4244  */
4245 int
4246 uvm_map_inherit(struct vm_map *map, vaddr_t start, vaddr_t end,
4247     vm_inherit_t new_inheritance)
4248 {
4249 	struct vm_map_entry *entry;
4250 
4251 	switch (new_inheritance) {
4252 	case MAP_INHERIT_NONE:
4253 	case MAP_INHERIT_COPY:
4254 	case MAP_INHERIT_SHARE:
4255 	case MAP_INHERIT_ZERO:
4256 		break;
4257 	default:
4258 		return (EINVAL);
4259 	}
4260 
4261 	if (start > end)
4262 		return EINVAL;
4263 	start = MAX(start, map->min_offset);
4264 	end = MIN(end, map->max_offset);
4265 	if (start >= end)
4266 		return 0;
4267 
4268 	vm_map_lock(map);
4269 
4270 	entry = uvm_map_entrybyaddr(&map->addr, start);
4271 	if (entry->end > start)
4272 		UVM_MAP_CLIP_START(map, entry, start);
4273 	else
4274 		entry = RBT_NEXT(uvm_map_addr, entry);
4275 
4276 	while (entry != NULL && entry->start < end) {
4277 		UVM_MAP_CLIP_END(map, entry, end);
4278 		entry->inheritance = new_inheritance;
4279 		entry = RBT_NEXT(uvm_map_addr, entry);
4280 	}
4281 
4282 	vm_map_unlock(map);
4283 	return (0);
4284 }
4285 
4286 /*
4287  * uvm_map_advice: set advice code for range of addrs in map.
4288  *
4289  * => map must be unlocked
4290  */
4291 int
4292 uvm_map_advice(struct vm_map *map, vaddr_t start, vaddr_t end, int new_advice)
4293 {
4294 	struct vm_map_entry *entry;
4295 
4296 	switch (new_advice) {
4297 	case MADV_NORMAL:
4298 	case MADV_RANDOM:
4299 	case MADV_SEQUENTIAL:
4300 		break;
4301 	default:
4302 		return (EINVAL);
4303 	}
4304 
4305 	if (start > end)
4306 		return EINVAL;
4307 	start = MAX(start, map->min_offset);
4308 	end = MIN(end, map->max_offset);
4309 	if (start >= end)
4310 		return 0;
4311 
4312 	vm_map_lock(map);
4313 
4314 	entry = uvm_map_entrybyaddr(&map->addr, start);
4315 	if (entry != NULL && entry->end > start)
4316 		UVM_MAP_CLIP_START(map, entry, start);
4317 	else if (entry!= NULL)
4318 		entry = RBT_NEXT(uvm_map_addr, entry);
4319 
4320 	/*
4321 	 * XXXJRT: disallow holes?
4322 	 */
4323 	while (entry != NULL && entry->start < end) {
4324 		UVM_MAP_CLIP_END(map, entry, end);
4325 		entry->advice = new_advice;
4326 		entry = RBT_NEXT(uvm_map_addr, entry);
4327 	}
4328 
4329 	vm_map_unlock(map);
4330 	return (0);
4331 }
4332 
4333 /*
4334  * uvm_map_extract: extract a mapping from a map and put it somewhere
4335  * in the kernel_map, setting protection to max_prot.
4336  *
4337  * => map should be unlocked (we will write lock it and kernel_map)
4338  * => returns 0 on success, error code otherwise
4339  * => start must be page aligned
4340  * => len must be page sized
4341  * => flags:
4342  *      UVM_EXTRACT_FIXPROT: set prot to maxprot as we go
4343  * Mappings are QREF's.
4344  */
4345 int
4346 uvm_map_extract(struct vm_map *srcmap, vaddr_t start, vsize_t len,
4347     vaddr_t *dstaddrp, int flags)
4348 {
4349 	struct uvm_map_deadq dead;
4350 	struct vm_map_entry *first, *entry, *newentry, *tmp1, *tmp2;
4351 	vaddr_t dstaddr;
4352 	vaddr_t end;
4353 	vaddr_t cp_start;
4354 	vsize_t cp_len, cp_off;
4355 	int error;
4356 
4357 	TAILQ_INIT(&dead);
4358 	end = start + len;
4359 
4360 	/*
4361 	 * Sanity check on the parameters.
4362 	 * Also, since the mapping may not contain gaps, error out if the
4363 	 * mapped area is not in source map.
4364 	 */
4365 	if ((start & (vaddr_t)PAGE_MASK) != 0 ||
4366 	    (end & (vaddr_t)PAGE_MASK) != 0 || end < start)
4367 		return EINVAL;
4368 	if (start < srcmap->min_offset || end > srcmap->max_offset)
4369 		return EINVAL;
4370 
4371 	/* Initialize dead entries. Handle len == 0 case. */
4372 	if (len == 0)
4373 		return 0;
4374 
4375 	/* Acquire lock on srcmap. */
4376 	vm_map_lock(srcmap);
4377 
4378 	/* Lock srcmap, lookup first and last entry in <start,len>. */
4379 	first = uvm_map_entrybyaddr(&srcmap->addr, start);
4380 
4381 	/* Check that the range is contiguous. */
4382 	for (entry = first; entry != NULL && entry->end < end;
4383 	    entry = RBT_NEXT(uvm_map_addr, entry)) {
4384 		if (VMMAP_FREE_END(entry) != entry->end ||
4385 		    UVM_ET_ISHOLE(entry)) {
4386 			error = EINVAL;
4387 			goto fail;
4388 		}
4389 	}
4390 	if (entry == NULL || UVM_ET_ISHOLE(entry)) {
4391 		error = EINVAL;
4392 		goto fail;
4393 	}
4394 
4395 	/*
4396 	 * Handle need-copy flag.
4397 	 */
4398 	for (entry = first; entry != NULL && entry->start < end;
4399 	    entry = RBT_NEXT(uvm_map_addr, entry)) {
4400 		if (UVM_ET_ISNEEDSCOPY(entry))
4401 			amap_copy(srcmap, entry, M_NOWAIT,
4402 			    UVM_ET_ISSTACK(entry) ? FALSE : TRUE, start, end);
4403 		if (UVM_ET_ISNEEDSCOPY(entry)) {
4404 			/*
4405 			 * amap_copy failure
4406 			 */
4407 			error = ENOMEM;
4408 			goto fail;
4409 		}
4410 	}
4411 
4412 	/* Lock destination map (kernel_map). */
4413 	vm_map_lock(kernel_map);
4414 
4415 	if (uvm_map_findspace(kernel_map, &tmp1, &tmp2, &dstaddr, len,
4416 	    MAX(PAGE_SIZE, PMAP_PREFER_ALIGN()), PMAP_PREFER_OFFSET(start),
4417 	    PROT_NONE, 0) != 0) {
4418 		error = ENOMEM;
4419 		goto fail2;
4420 	}
4421 	*dstaddrp = dstaddr;
4422 
4423 	/*
4424 	 * We now have srcmap and kernel_map locked.
4425 	 * dstaddr contains the destination offset in dstmap.
4426 	 */
4427 	/* step 1: start looping through map entries, performing extraction. */
4428 	for (entry = first; entry != NULL && entry->start < end;
4429 	    entry = RBT_NEXT(uvm_map_addr, entry)) {
4430 		KDASSERT(!UVM_ET_ISNEEDSCOPY(entry));
4431 		if (UVM_ET_ISHOLE(entry))
4432 			continue;
4433 
4434 		/* Calculate uvm_mapent_clone parameters. */
4435 		cp_start = entry->start;
4436 		if (cp_start < start) {
4437 			cp_off = start - cp_start;
4438 			cp_start = start;
4439 		} else
4440 			cp_off = 0;
4441 		cp_len = MIN(entry->end, end) - cp_start;
4442 
4443 		newentry = uvm_mapent_clone(kernel_map,
4444 		    cp_start - start + dstaddr, cp_len, cp_off,
4445 		    entry->protection, entry->max_protection,
4446 		    entry, &dead, flags, AMAP_SHARED | AMAP_REFALL);
4447 		if (newentry == NULL) {
4448 			error = ENOMEM;
4449 			goto fail2_unmap;
4450 		}
4451 		kernel_map->size += cp_len;
4452 		if (flags & UVM_EXTRACT_FIXPROT)
4453 			newentry->protection = newentry->max_protection;
4454 
4455 		/*
4456 		 * Step 2: perform pmap copy.
4457 		 * (Doing this in the loop saves one RB traversal.)
4458 		 */
4459 		pmap_copy(kernel_map->pmap, srcmap->pmap,
4460 		    cp_start - start + dstaddr, cp_len, cp_start);
4461 	}
4462 	pmap_update(kernel_map->pmap);
4463 
4464 	error = 0;
4465 
4466 	/* Unmap copied entries on failure. */
4467 fail2_unmap:
4468 	if (error) {
4469 		uvm_unmap_remove(kernel_map, dstaddr, dstaddr + len, &dead,
4470 		    FALSE, TRUE);
4471 	}
4472 
4473 	/* Release maps, release dead entries. */
4474 fail2:
4475 	vm_map_unlock(kernel_map);
4476 
4477 fail:
4478 	vm_map_unlock(srcmap);
4479 
4480 	uvm_unmap_detach(&dead, 0);
4481 
4482 	return error;
4483 }
4484 
4485 /*
4486  * uvm_map_clean: clean out a map range
4487  *
4488  * => valid flags:
4489  *   if (flags & PGO_CLEANIT): dirty pages are cleaned first
4490  *   if (flags & PGO_SYNCIO): dirty pages are written synchronously
4491  *   if (flags & PGO_DEACTIVATE): any cached pages are deactivated after clean
4492  *   if (flags & PGO_FREE): any cached pages are freed after clean
4493  * => returns an error if any part of the specified range isn't mapped
4494  * => never a need to flush amap layer since the anonymous memory has
4495  *	no permanent home, but may deactivate pages there
4496  * => called from sys_msync() and sys_madvise()
4497  * => caller must not write-lock map (read OK).
4498  * => we may sleep while cleaning if SYNCIO [with map read-locked]
4499  */
4500 
4501 int
4502 uvm_map_clean(struct vm_map *map, vaddr_t start, vaddr_t end, int flags)
4503 {
4504 	struct vm_map_entry *first, *entry;
4505 	struct vm_amap *amap;
4506 	struct vm_anon *anon;
4507 	struct vm_page *pg;
4508 	struct uvm_object *uobj;
4509 	vaddr_t cp_start, cp_end;
4510 	int refs;
4511 	int error;
4512 	boolean_t rv;
4513 
4514 	KASSERT((flags & (PGO_FREE|PGO_DEACTIVATE)) !=
4515 	    (PGO_FREE|PGO_DEACTIVATE));
4516 
4517 	if (start > end || start < map->min_offset || end > map->max_offset)
4518 		return EINVAL;
4519 
4520 	vm_map_lock_read(map);
4521 	first = uvm_map_entrybyaddr(&map->addr, start);
4522 
4523 	/* Make a first pass to check for holes. */
4524 	for (entry = first; entry != NULL && entry->start < end;
4525 	    entry = RBT_NEXT(uvm_map_addr, entry)) {
4526 		if (UVM_ET_ISSUBMAP(entry)) {
4527 			vm_map_unlock_read(map);
4528 			return EINVAL;
4529 		}
4530 		if (UVM_ET_ISSUBMAP(entry) ||
4531 		    UVM_ET_ISHOLE(entry) ||
4532 		    (entry->end < end &&
4533 		    VMMAP_FREE_END(entry) != entry->end)) {
4534 			vm_map_unlock_read(map);
4535 			return EFAULT;
4536 		}
4537 	}
4538 
4539 	error = 0;
4540 	for (entry = first; entry != NULL && entry->start < end;
4541 	    entry = RBT_NEXT(uvm_map_addr, entry)) {
4542 		amap = entry->aref.ar_amap;	/* top layer */
4543 		if (UVM_ET_ISOBJ(entry))
4544 			uobj = entry->object.uvm_obj;
4545 		else
4546 			uobj = NULL;
4547 
4548 		/*
4549 		 * No amap cleaning necessary if:
4550 		 *  - there's no amap
4551 		 *  - we're not deactivating or freeing pages.
4552 		 */
4553 		if (amap == NULL || (flags & (PGO_DEACTIVATE|PGO_FREE)) == 0)
4554 			goto flush_object;
4555 
4556 		cp_start = MAX(entry->start, start);
4557 		cp_end = MIN(entry->end, end);
4558 
4559 		for (; cp_start != cp_end; cp_start += PAGE_SIZE) {
4560 			anon = amap_lookup(&entry->aref,
4561 			    cp_start - entry->start);
4562 			if (anon == NULL)
4563 				continue;
4564 
4565 			pg = anon->an_page;
4566 			if (pg == NULL) {
4567 				continue;
4568 			}
4569 			KASSERT(pg->pg_flags & PQ_ANON);
4570 
4571 			switch (flags & (PGO_CLEANIT|PGO_FREE|PGO_DEACTIVATE)) {
4572 			/*
4573 			 * XXX In these first 3 cases, we always just
4574 			 * XXX deactivate the page.  We may want to
4575 			 * XXX handle the different cases more
4576 			 * XXX specifically, in the future.
4577 			 */
4578 			case PGO_CLEANIT|PGO_FREE:
4579 			case PGO_CLEANIT|PGO_DEACTIVATE:
4580 			case PGO_DEACTIVATE:
4581 deactivate_it:
4582 				/* skip the page if it's wired */
4583 				if (pg->wire_count != 0)
4584 					break;
4585 
4586 				uvm_lock_pageq();
4587 
4588 				KASSERT(pg->uanon == anon);
4589 
4590 				/* zap all mappings for the page. */
4591 				pmap_page_protect(pg, PROT_NONE);
4592 
4593 				/* ...and deactivate the page. */
4594 				uvm_pagedeactivate(pg);
4595 
4596 				uvm_unlock_pageq();
4597 				break;
4598 			case PGO_FREE:
4599 				/*
4600 				 * If there are multiple references to
4601 				 * the amap, just deactivate the page.
4602 				 */
4603 				if (amap_refs(amap) > 1)
4604 					goto deactivate_it;
4605 
4606 				/* XXX skip the page if it's wired */
4607 				if (pg->wire_count != 0) {
4608 					break;
4609 				}
4610 				amap_unadd(&entry->aref,
4611 				    cp_start - entry->start);
4612 				refs = --anon->an_ref;
4613 				if (refs == 0)
4614 					uvm_anfree(anon);
4615 				break;
4616 			default:
4617 				panic("uvm_map_clean: weird flags");
4618 			}
4619 		}
4620 
4621 flush_object:
4622 		cp_start = MAX(entry->start, start);
4623 		cp_end = MIN(entry->end, end);
4624 
4625 		/*
4626 		 * flush pages if we've got a valid backing object.
4627 		 *
4628 		 * Don't PGO_FREE if we don't have write permission
4629 		 * and don't flush if this is a copy-on-write object
4630 		 * since we can't know our permissions on it.
4631 		 */
4632 		if (uobj != NULL &&
4633 		    ((flags & PGO_FREE) == 0 ||
4634 		     ((entry->max_protection & PROT_WRITE) != 0 &&
4635 		      (entry->etype & UVM_ET_COPYONWRITE) == 0))) {
4636 			rv = uobj->pgops->pgo_flush(uobj,
4637 			    cp_start - entry->start + entry->offset,
4638 			    cp_end - entry->start + entry->offset, flags);
4639 
4640 			if (rv == FALSE)
4641 				error = EFAULT;
4642 		}
4643 	}
4644 
4645 	vm_map_unlock_read(map);
4646 	return error;
4647 }
4648 
4649 /*
4650  * UVM_MAP_CLIP_END implementation
4651  */
4652 void
4653 uvm_map_clip_end(struct vm_map *map, struct vm_map_entry *entry, vaddr_t addr)
4654 {
4655 	struct vm_map_entry *tmp;
4656 
4657 	KASSERT(entry->start < addr && VMMAP_FREE_END(entry) > addr);
4658 	tmp = uvm_mapent_alloc(map, 0);
4659 
4660 	/* Invoke splitentry. */
4661 	uvm_map_splitentry(map, entry, tmp, addr);
4662 }
4663 
4664 /*
4665  * UVM_MAP_CLIP_START implementation
4666  *
4667  * Clippers are required to not change the pointers to the entry they are
4668  * clipping on.
4669  * Since uvm_map_splitentry turns the original entry into the lowest
4670  * entry (address wise) we do a swap between the new entry and the original
4671  * entry, prior to calling uvm_map_splitentry.
4672  */
4673 void
4674 uvm_map_clip_start(struct vm_map *map, struct vm_map_entry *entry, vaddr_t addr)
4675 {
4676 	struct vm_map_entry *tmp;
4677 	struct uvm_addr_state *free;
4678 
4679 	/* Unlink original. */
4680 	free = uvm_map_uaddr_e(map, entry);
4681 	uvm_mapent_free_remove(map, free, entry);
4682 	uvm_mapent_addr_remove(map, entry);
4683 
4684 	/* Copy entry. */
4685 	KASSERT(entry->start < addr && VMMAP_FREE_END(entry) > addr);
4686 	tmp = uvm_mapent_alloc(map, 0);
4687 	uvm_mapent_copy(entry, tmp);
4688 
4689 	/* Put new entry in place of original entry. */
4690 	uvm_mapent_addr_insert(map, tmp);
4691 	uvm_mapent_free_insert(map, free, tmp);
4692 
4693 	/* Invoke splitentry. */
4694 	uvm_map_splitentry(map, tmp, entry, addr);
4695 }
4696 
4697 /*
4698  * Boundary fixer.
4699  */
4700 static __inline vaddr_t uvm_map_boundfix(vaddr_t, vaddr_t, vaddr_t);
4701 static __inline vaddr_t
4702 uvm_map_boundfix(vaddr_t min, vaddr_t max, vaddr_t bound)
4703 {
4704 	return (min < bound && max > bound) ? bound : max;
4705 }
4706 
4707 /*
4708  * Choose free list based on address at start of free space.
4709  *
4710  * The uvm_addr_state returned contains addr and is the first of:
4711  * - uaddr_exe
4712  * - uaddr_brk_stack
4713  * - uaddr_any
4714  */
4715 struct uvm_addr_state*
4716 uvm_map_uaddr(struct vm_map *map, vaddr_t addr)
4717 {
4718 	struct uvm_addr_state *uaddr;
4719 	int i;
4720 
4721 	/* Special case the first page, to prevent mmap from returning 0. */
4722 	if (addr < VMMAP_MIN_ADDR)
4723 		return NULL;
4724 
4725 	/* Upper bound for kernel maps at uvm_maxkaddr. */
4726 	if ((map->flags & VM_MAP_ISVMSPACE) == 0) {
4727 		if (addr >= uvm_maxkaddr)
4728 			return NULL;
4729 	}
4730 
4731 	/* Is the address inside the exe-only map? */
4732 	if (map->uaddr_exe != NULL && addr >= map->uaddr_exe->uaddr_minaddr &&
4733 	    addr < map->uaddr_exe->uaddr_maxaddr)
4734 		return map->uaddr_exe;
4735 
4736 	/* Check if the space falls inside brk/stack area. */
4737 	if ((addr >= map->b_start && addr < map->b_end) ||
4738 	    (addr >= map->s_start && addr < map->s_end)) {
4739 		if (map->uaddr_brk_stack != NULL &&
4740 		    addr >= map->uaddr_brk_stack->uaddr_minaddr &&
4741 		    addr < map->uaddr_brk_stack->uaddr_maxaddr) {
4742 			return map->uaddr_brk_stack;
4743 		} else
4744 			return NULL;
4745 	}
4746 
4747 	/*
4748 	 * Check the other selectors.
4749 	 *
4750 	 * These selectors are only marked as the owner, if they have insert
4751 	 * functions.
4752 	 */
4753 	for (i = 0; i < nitems(map->uaddr_any); i++) {
4754 		uaddr = map->uaddr_any[i];
4755 		if (uaddr == NULL)
4756 			continue;
4757 		if (uaddr->uaddr_functions->uaddr_free_insert == NULL)
4758 			continue;
4759 
4760 		if (addr >= uaddr->uaddr_minaddr &&
4761 		    addr < uaddr->uaddr_maxaddr)
4762 			return uaddr;
4763 	}
4764 
4765 	return NULL;
4766 }
4767 
4768 /*
4769  * Choose free list based on address at start of free space.
4770  *
4771  * The uvm_addr_state returned contains addr and is the first of:
4772  * - uaddr_exe
4773  * - uaddr_brk_stack
4774  * - uaddr_any
4775  */
4776 struct uvm_addr_state*
4777 uvm_map_uaddr_e(struct vm_map *map, struct vm_map_entry *entry)
4778 {
4779 	return uvm_map_uaddr(map, VMMAP_FREE_START(entry));
4780 }
4781 
4782 /*
4783  * Returns the first free-memory boundary that is crossed by [min-max].
4784  */
4785 vsize_t
4786 uvm_map_boundary(struct vm_map *map, vaddr_t min, vaddr_t max)
4787 {
4788 	struct uvm_addr_state	*uaddr;
4789 	int			 i;
4790 
4791 	/* Never return first page. */
4792 	max = uvm_map_boundfix(min, max, VMMAP_MIN_ADDR);
4793 
4794 	/* Treat the maxkaddr special, if the map is a kernel_map. */
4795 	if ((map->flags & VM_MAP_ISVMSPACE) == 0)
4796 		max = uvm_map_boundfix(min, max, uvm_maxkaddr);
4797 
4798 	/* Check for exe-only boundaries. */
4799 	if (map->uaddr_exe != NULL) {
4800 		max = uvm_map_boundfix(min, max, map->uaddr_exe->uaddr_minaddr);
4801 		max = uvm_map_boundfix(min, max, map->uaddr_exe->uaddr_maxaddr);
4802 	}
4803 
4804 	/* Check for exe-only boundaries. */
4805 	if (map->uaddr_brk_stack != NULL) {
4806 		max = uvm_map_boundfix(min, max,
4807 		    map->uaddr_brk_stack->uaddr_minaddr);
4808 		max = uvm_map_boundfix(min, max,
4809 		    map->uaddr_brk_stack->uaddr_maxaddr);
4810 	}
4811 
4812 	/* Check other boundaries. */
4813 	for (i = 0; i < nitems(map->uaddr_any); i++) {
4814 		uaddr = map->uaddr_any[i];
4815 		if (uaddr != NULL) {
4816 			max = uvm_map_boundfix(min, max, uaddr->uaddr_minaddr);
4817 			max = uvm_map_boundfix(min, max, uaddr->uaddr_maxaddr);
4818 		}
4819 	}
4820 
4821 	/* Boundaries at stack and brk() area. */
4822 	max = uvm_map_boundfix(min, max, map->s_start);
4823 	max = uvm_map_boundfix(min, max, map->s_end);
4824 	max = uvm_map_boundfix(min, max, map->b_start);
4825 	max = uvm_map_boundfix(min, max, map->b_end);
4826 
4827 	return max;
4828 }
4829 
4830 /*
4831  * Update map allocation start and end addresses from proc vmspace.
4832  */
4833 void
4834 uvm_map_vmspace_update(struct vm_map *map,
4835     struct uvm_map_deadq *dead, int flags)
4836 {
4837 	struct vmspace *vm;
4838 	vaddr_t b_start, b_end, s_start, s_end;
4839 
4840 	KASSERT(map->flags & VM_MAP_ISVMSPACE);
4841 	KASSERT(offsetof(struct vmspace, vm_map) == 0);
4842 
4843 	/*
4844 	 * Derive actual allocation boundaries from vmspace.
4845 	 */
4846 	vm = (struct vmspace *)map;
4847 	b_start = (vaddr_t)vm->vm_daddr;
4848 	b_end   = b_start + BRKSIZ;
4849 	s_start = MIN((vaddr_t)vm->vm_maxsaddr, (vaddr_t)vm->vm_minsaddr);
4850 	s_end   = MAX((vaddr_t)vm->vm_maxsaddr, (vaddr_t)vm->vm_minsaddr);
4851 #ifdef DIAGNOSTIC
4852 	if ((b_start & (vaddr_t)PAGE_MASK) != 0 ||
4853 	    (b_end & (vaddr_t)PAGE_MASK) != 0 ||
4854 	    (s_start & (vaddr_t)PAGE_MASK) != 0 ||
4855 	    (s_end & (vaddr_t)PAGE_MASK) != 0) {
4856 		panic("uvm_map_vmspace_update: vmspace %p invalid bounds: "
4857 		    "b=0x%lx-0x%lx s=0x%lx-0x%lx",
4858 		    vm, b_start, b_end, s_start, s_end);
4859 	}
4860 #endif
4861 
4862 	if (__predict_true(map->b_start == b_start && map->b_end == b_end &&
4863 	    map->s_start == s_start && map->s_end == s_end))
4864 		return;
4865 
4866 	uvm_map_freelist_update(map, dead, b_start, b_end,
4867 	    s_start, s_end, flags);
4868 }
4869 
4870 /*
4871  * Grow kernel memory.
4872  *
4873  * This function is only called for kernel maps when an allocation fails.
4874  *
4875  * If the map has a gap that is large enough to accommodate alloc_sz, this
4876  * function will make sure map->free will include it.
4877  */
4878 void
4879 uvm_map_kmem_grow(struct vm_map *map, struct uvm_map_deadq *dead,
4880     vsize_t alloc_sz, int flags)
4881 {
4882 	vsize_t sz;
4883 	vaddr_t end;
4884 	struct vm_map_entry *entry;
4885 
4886 	/* Kernel memory only. */
4887 	KASSERT((map->flags & VM_MAP_ISVMSPACE) == 0);
4888 	/* Destroy free list. */
4889 	uvm_map_freelist_update_clear(map, dead);
4890 
4891 	/* Include the guard page in the hard minimum requirement of alloc_sz. */
4892 	if (map->flags & VM_MAP_GUARDPAGES)
4893 		alloc_sz += PAGE_SIZE;
4894 
4895 	/*
4896 	 * Grow by ALLOCMUL * alloc_sz, but at least VM_MAP_KSIZE_DELTA.
4897 	 *
4898 	 * Don't handle the case where the multiplication overflows:
4899 	 * if that happens, the allocation is probably too big anyway.
4900 	 */
4901 	sz = MAX(VM_MAP_KSIZE_ALLOCMUL * alloc_sz, VM_MAP_KSIZE_DELTA);
4902 
4903 	/*
4904 	 * Walk forward until a gap large enough for alloc_sz shows up.
4905 	 *
4906 	 * We assume the kernel map has no boundaries.
4907 	 * uvm_maxkaddr may be zero.
4908 	 */
4909 	end = MAX(uvm_maxkaddr, map->min_offset);
4910 	entry = uvm_map_entrybyaddr(&map->addr, end);
4911 	while (entry && entry->fspace < alloc_sz)
4912 		entry = RBT_NEXT(uvm_map_addr, entry);
4913 	if (entry) {
4914 		end = MAX(VMMAP_FREE_START(entry), end);
4915 		end += MIN(sz, map->max_offset - end);
4916 	} else
4917 		end = map->max_offset;
4918 
4919 	/* Reserve pmap entries. */
4920 #ifdef PMAP_GROWKERNEL
4921 	uvm_maxkaddr = pmap_growkernel(end);
4922 #else
4923 	uvm_maxkaddr = MAX(uvm_maxkaddr, end);
4924 #endif
4925 
4926 	/* Rebuild free list. */
4927 	uvm_map_freelist_update_refill(map, flags);
4928 }
4929 
4930 /*
4931  * Freelist update subfunction: unlink all entries from freelists.
4932  */
4933 void
4934 uvm_map_freelist_update_clear(struct vm_map *map, struct uvm_map_deadq *dead)
4935 {
4936 	struct uvm_addr_state *free;
4937 	struct vm_map_entry *entry, *prev, *next;
4938 
4939 	prev = NULL;
4940 	for (entry = RBT_MIN(uvm_map_addr, &map->addr); entry != NULL;
4941 	    entry = next) {
4942 		next = RBT_NEXT(uvm_map_addr, entry);
4943 
4944 		free = uvm_map_uaddr_e(map, entry);
4945 		uvm_mapent_free_remove(map, free, entry);
4946 
4947 		if (prev != NULL && entry->start == entry->end) {
4948 			prev->fspace += VMMAP_FREE_END(entry) - entry->end;
4949 			uvm_mapent_addr_remove(map, entry);
4950 			DEAD_ENTRY_PUSH(dead, entry);
4951 		} else
4952 			prev = entry;
4953 	}
4954 }
4955 
4956 /*
4957  * Freelist update subfunction: refill the freelists with entries.
4958  */
4959 void
4960 uvm_map_freelist_update_refill(struct vm_map *map, int flags)
4961 {
4962 	struct vm_map_entry *entry;
4963 	vaddr_t min, max;
4964 
4965 	RBT_FOREACH(entry, uvm_map_addr, &map->addr) {
4966 		min = VMMAP_FREE_START(entry);
4967 		max = VMMAP_FREE_END(entry);
4968 		entry->fspace = 0;
4969 
4970 		entry = uvm_map_fix_space(map, entry, min, max, flags);
4971 	}
4972 
4973 	uvm_tree_sanity(map, __FILE__, __LINE__);
4974 }
4975 
4976 /*
4977  * Change {a,b}_{start,end} allocation ranges and associated free lists.
4978  */
4979 void
4980 uvm_map_freelist_update(struct vm_map *map, struct uvm_map_deadq *dead,
4981     vaddr_t b_start, vaddr_t b_end, vaddr_t s_start, vaddr_t s_end, int flags)
4982 {
4983 	KDASSERT(b_end >= b_start && s_end >= s_start);
4984 
4985 	/* Clear all free lists. */
4986 	uvm_map_freelist_update_clear(map, dead);
4987 
4988 	/* Apply new bounds. */
4989 	map->b_start = b_start;
4990 	map->b_end   = b_end;
4991 	map->s_start = s_start;
4992 	map->s_end   = s_end;
4993 
4994 	/* Refill free lists. */
4995 	uvm_map_freelist_update_refill(map, flags);
4996 }
4997 
4998 /*
4999  * Assign a uvm_addr_state to the specified pointer in vm_map.
5000  *
5001  * May sleep.
5002  */
5003 void
5004 uvm_map_set_uaddr(struct vm_map *map, struct uvm_addr_state **which,
5005     struct uvm_addr_state *newval)
5006 {
5007 	struct uvm_map_deadq dead;
5008 
5009 	/* Pointer which must be in this map. */
5010 	KASSERT(which != NULL);
5011 	KASSERT((void*)map <= (void*)(which) &&
5012 	    (void*)(which) < (void*)(map + 1));
5013 
5014 	vm_map_lock(map);
5015 	TAILQ_INIT(&dead);
5016 	uvm_map_freelist_update_clear(map, &dead);
5017 
5018 	uvm_addr_destroy(*which);
5019 	*which = newval;
5020 
5021 	uvm_map_freelist_update_refill(map, 0);
5022 	vm_map_unlock(map);
5023 	uvm_unmap_detach(&dead, 0);
5024 }
5025 
5026 /*
5027  * Correct space insert.
5028  *
5029  * Entry must not be on any freelist.
5030  */
5031 struct vm_map_entry*
5032 uvm_map_fix_space(struct vm_map *map, struct vm_map_entry *entry,
5033     vaddr_t min, vaddr_t max, int flags)
5034 {
5035 	struct uvm_addr_state	*free, *entfree;
5036 	vaddr_t			 lmax;
5037 
5038 	KASSERT(entry == NULL || (entry->etype & UVM_ET_FREEMAPPED) == 0);
5039 	KDASSERT(min <= max);
5040 	KDASSERT((entry != NULL && VMMAP_FREE_END(entry) == min) ||
5041 	    min == map->min_offset);
5042 
5043 	/*
5044 	 * During the function, entfree will always point at the uaddr state
5045 	 * for entry.
5046 	 */
5047 	entfree = (entry == NULL ? NULL :
5048 	    uvm_map_uaddr_e(map, entry));
5049 
5050 	while (min != max) {
5051 		/* Claim guard page for entry. */
5052 		if ((map->flags & VM_MAP_GUARDPAGES) && entry != NULL &&
5053 		    VMMAP_FREE_END(entry) == entry->end &&
5054 		    entry->start != entry->end) {
5055 			if (max - min == 2 * PAGE_SIZE) {
5056 				/*
5057 				 * If the free-space gap is exactly 2 pages,
5058 				 * we make the guard 2 pages instead of 1.
5059 				 * Because in a guarded map, an area needs
5060 				 * at least 2 pages to allocate from:
5061 				 * one page for the allocation and one for
5062 				 * the guard.
5063 				 */
5064 				entry->guard = 2 * PAGE_SIZE;
5065 				min = max;
5066 			} else {
5067 				entry->guard = PAGE_SIZE;
5068 				min += PAGE_SIZE;
5069 			}
5070 			continue;
5071 		}
5072 
5073 		/*
5074 		 * Handle the case where entry has a 2-page guard, but the
5075 		 * space after entry is freed.
5076 		 */
5077 		if (entry != NULL && entry->fspace == 0 &&
5078 		    entry->guard > PAGE_SIZE) {
5079 			entry->guard = PAGE_SIZE;
5080 			min = VMMAP_FREE_START(entry);
5081 		}
5082 
5083 		lmax = uvm_map_boundary(map, min, max);
5084 		free = uvm_map_uaddr(map, min);
5085 
5086 		/*
5087 		 * Entries are merged if they point at the same uvm_free().
5088 		 * Exception to that rule: if min == uvm_maxkaddr, a new
5089 		 * entry is started regardless (otherwise the allocators
5090 		 * will get confused).
5091 		 */
5092 		if (entry != NULL && free == entfree &&
5093 		    !((map->flags & VM_MAP_ISVMSPACE) == 0 &&
5094 		    min == uvm_maxkaddr)) {
5095 			KDASSERT(VMMAP_FREE_END(entry) == min);
5096 			entry->fspace += lmax - min;
5097 		} else {
5098 			/*
5099 			 * Commit entry to free list: it'll not be added to
5100 			 * anymore.
5101 			 * We'll start a new entry and add to that entry
5102 			 * instead.
5103 			 */
5104 			if (entry != NULL)
5105 				uvm_mapent_free_insert(map, entfree, entry);
5106 
5107 			/* New entry for new uaddr. */
5108 			entry = uvm_mapent_alloc(map, flags);
5109 			KDASSERT(entry != NULL);
5110 			entry->end = entry->start = min;
5111 			entry->guard = 0;
5112 			entry->fspace = lmax - min;
5113 			entry->object.uvm_obj = NULL;
5114 			entry->offset = 0;
5115 			entry->etype = 0;
5116 			entry->protection = entry->max_protection = 0;
5117 			entry->inheritance = 0;
5118 			entry->wired_count = 0;
5119 			entry->advice = 0;
5120 			entry->aref.ar_pageoff = 0;
5121 			entry->aref.ar_amap = NULL;
5122 			uvm_mapent_addr_insert(map, entry);
5123 
5124 			entfree = free;
5125 		}
5126 
5127 		min = lmax;
5128 	}
5129 	/* Finally put entry on the uaddr state. */
5130 	if (entry != NULL)
5131 		uvm_mapent_free_insert(map, entfree, entry);
5132 
5133 	return entry;
5134 }
5135 
5136 /*
5137  * MQuery style of allocation.
5138  *
5139  * This allocator searches forward until sufficient space is found to map
5140  * the given size.
5141  *
5142  * XXX: factor in offset (via pmap_prefer) and protection?
5143  */
5144 int
5145 uvm_map_mquery(struct vm_map *map, vaddr_t *addr_p, vsize_t sz, voff_t offset,
5146     int flags)
5147 {
5148 	struct vm_map_entry *entry, *last;
5149 	vaddr_t addr;
5150 	vaddr_t tmp, pmap_align, pmap_offset;
5151 	int error;
5152 
5153 	addr = *addr_p;
5154 	vm_map_lock_read(map);
5155 
5156 	/* Configure pmap prefer. */
5157 	if (offset != UVM_UNKNOWN_OFFSET) {
5158 		pmap_align = MAX(PAGE_SIZE, PMAP_PREFER_ALIGN());
5159 		pmap_offset = PMAP_PREFER_OFFSET(offset);
5160 	} else {
5161 		pmap_align = PAGE_SIZE;
5162 		pmap_offset = 0;
5163 	}
5164 
5165 	/* Align address to pmap_prefer unless FLAG_FIXED is set. */
5166 	if (!(flags & UVM_FLAG_FIXED) && offset != UVM_UNKNOWN_OFFSET) {
5167 	  	tmp = (addr & ~(pmap_align - 1)) | pmap_offset;
5168 		if (tmp < addr)
5169 			tmp += pmap_align;
5170 		addr = tmp;
5171 	}
5172 
5173 	/* First, check if the requested range is fully available. */
5174 	entry = uvm_map_entrybyaddr(&map->addr, addr);
5175 	last = NULL;
5176 	if (uvm_map_isavail(map, NULL, &entry, &last, addr, sz)) {
5177 		error = 0;
5178 		goto out;
5179 	}
5180 	if (flags & UVM_FLAG_FIXED) {
5181 		error = EINVAL;
5182 		goto out;
5183 	}
5184 
5185 	error = ENOMEM; /* Default error from here. */
5186 
5187 	/*
5188 	 * At this point, the memory at <addr, sz> is not available.
5189 	 * The reasons are:
5190 	 * [1] it's outside the map,
5191 	 * [2] it starts in used memory (and therefore needs to move
5192 	 *     toward the first free page in entry),
5193 	 * [3] it starts in free memory but bumps into used memory.
5194 	 *
5195 	 * Note that for case [2], the forward moving is handled by the
5196 	 * for loop below.
5197 	 */
5198 	if (entry == NULL) {
5199 		/* [1] Outside the map. */
5200 		if (addr >= map->max_offset)
5201 			goto out;
5202 		else
5203 			entry = RBT_MIN(uvm_map_addr, &map->addr);
5204 	} else if (VMMAP_FREE_START(entry) <= addr) {
5205 		/* [3] Bumped into used memory. */
5206 		entry = RBT_NEXT(uvm_map_addr, entry);
5207 	}
5208 
5209 	/* Test if the next entry is sufficient for the allocation. */
5210 	for (; entry != NULL;
5211 	    entry = RBT_NEXT(uvm_map_addr, entry)) {
5212 		if (entry->fspace == 0)
5213 			continue;
5214 		addr = VMMAP_FREE_START(entry);
5215 
5216 restart:	/* Restart address checks on address change. */
5217 		tmp = (addr & ~(pmap_align - 1)) | pmap_offset;
5218 		if (tmp < addr)
5219 			tmp += pmap_align;
5220 		addr = tmp;
5221 		if (addr >= VMMAP_FREE_END(entry))
5222 			continue;
5223 
5224 		/* Skip brk() allocation addresses. */
5225 		if (addr + sz > map->b_start && addr < map->b_end) {
5226 			if (VMMAP_FREE_END(entry) > map->b_end) {
5227 				addr = map->b_end;
5228 				goto restart;
5229 			} else
5230 				continue;
5231 		}
5232 		/* Skip stack allocation addresses. */
5233 		if (addr + sz > map->s_start && addr < map->s_end) {
5234 			if (VMMAP_FREE_END(entry) > map->s_end) {
5235 				addr = map->s_end;
5236 				goto restart;
5237 			} else
5238 				continue;
5239 		}
5240 
5241 		last = NULL;
5242 		if (uvm_map_isavail(map, NULL, &entry, &last, addr, sz)) {
5243 			error = 0;
5244 			goto out;
5245 		}
5246 	}
5247 
5248 out:
5249 	vm_map_unlock_read(map);
5250 	if (error == 0)
5251 		*addr_p = addr;
5252 	return error;
5253 }
5254 
5255 /*
5256  * Determine allocation bias.
5257  *
5258  * Returns 1 if we should bias to high addresses, -1 for a bias towards low
5259  * addresses, or 0 for no bias.
5260  * The bias mechanism is intended to avoid clashing with brk() and stack
5261  * areas.
5262  */
5263 int
5264 uvm_mapent_bias(struct vm_map *map, struct vm_map_entry *entry)
5265 {
5266 	vaddr_t start, end;
5267 
5268 	start = VMMAP_FREE_START(entry);
5269 	end = VMMAP_FREE_END(entry);
5270 
5271 	/* Stay at the top of brk() area. */
5272 	if (end >= map->b_start && start < map->b_end)
5273 		return 1;
5274 	/* Stay at the far end of the stack area. */
5275 	if (end >= map->s_start && start < map->s_end) {
5276 #ifdef MACHINE_STACK_GROWS_UP
5277 		return 1;
5278 #else
5279 		return -1;
5280 #endif
5281 	}
5282 
5283 	/* No bias, this area is meant for us. */
5284 	return 0;
5285 }
5286 
5287 
5288 boolean_t
5289 vm_map_lock_try_ln(struct vm_map *map, char *file, int line)
5290 {
5291 	boolean_t rv;
5292 
5293 	if (map->flags & VM_MAP_INTRSAFE) {
5294 		rv = mtx_enter_try(&map->mtx);
5295 	} else {
5296 		mtx_enter(&map->flags_lock);
5297 		if (map->flags & VM_MAP_BUSY) {
5298 			mtx_leave(&map->flags_lock);
5299 			return (FALSE);
5300 		}
5301 		mtx_leave(&map->flags_lock);
5302 		rv = (rw_enter(&map->lock, RW_WRITE|RW_NOSLEEP) == 0);
5303 		/* check if the lock is busy and back out if we won the race */
5304 		if (rv) {
5305 			mtx_enter(&map->flags_lock);
5306 			if (map->flags & VM_MAP_BUSY) {
5307 				rw_exit(&map->lock);
5308 				rv = FALSE;
5309 			}
5310 			mtx_leave(&map->flags_lock);
5311 		}
5312 	}
5313 
5314 	if (rv) {
5315 		map->timestamp++;
5316 		LPRINTF(("map   lock: %p (at %s %d)\n", map, file, line));
5317 		uvm_tree_sanity(map, file, line);
5318 		uvm_tree_size_chk(map, file, line);
5319 	}
5320 
5321 	return (rv);
5322 }
5323 
5324 void
5325 vm_map_lock_ln(struct vm_map *map, char *file, int line)
5326 {
5327 	if ((map->flags & VM_MAP_INTRSAFE) == 0) {
5328 		do {
5329 			mtx_enter(&map->flags_lock);
5330 tryagain:
5331 			while (map->flags & VM_MAP_BUSY) {
5332 				map->flags |= VM_MAP_WANTLOCK;
5333 				msleep(&map->flags, &map->flags_lock,
5334 				    PVM, vmmapbsy, 0);
5335 			}
5336 			mtx_leave(&map->flags_lock);
5337 		} while (rw_enter(&map->lock, RW_WRITE|RW_SLEEPFAIL) != 0);
5338 		/* check if the lock is busy and back out if we won the race */
5339 		mtx_enter(&map->flags_lock);
5340 		if (map->flags & VM_MAP_BUSY) {
5341 			rw_exit(&map->lock);
5342 			goto tryagain;
5343 		}
5344 		mtx_leave(&map->flags_lock);
5345 	} else {
5346 		mtx_enter(&map->mtx);
5347 	}
5348 
5349 	map->timestamp++;
5350 	LPRINTF(("map   lock: %p (at %s %d)\n", map, file, line));
5351 	uvm_tree_sanity(map, file, line);
5352 	uvm_tree_size_chk(map, file, line);
5353 }
5354 
5355 void
5356 vm_map_lock_read_ln(struct vm_map *map, char *file, int line)
5357 {
5358 	if ((map->flags & VM_MAP_INTRSAFE) == 0)
5359 		rw_enter_read(&map->lock);
5360 	else
5361 		mtx_enter(&map->mtx);
5362 	LPRINTF(("map   lock: %p (at %s %d)\n", map, file, line));
5363 	uvm_tree_sanity(map, file, line);
5364 	uvm_tree_size_chk(map, file, line);
5365 }
5366 
5367 void
5368 vm_map_unlock_ln(struct vm_map *map, char *file, int line)
5369 {
5370 	uvm_tree_sanity(map, file, line);
5371 	uvm_tree_size_chk(map, file, line);
5372 	LPRINTF(("map unlock: %p (at %s %d)\n", map, file, line));
5373 	if ((map->flags & VM_MAP_INTRSAFE) == 0)
5374 		rw_exit(&map->lock);
5375 	else
5376 		mtx_leave(&map->mtx);
5377 }
5378 
5379 void
5380 vm_map_unlock_read_ln(struct vm_map *map, char *file, int line)
5381 {
5382 	/* XXX: RO */ uvm_tree_sanity(map, file, line);
5383 	/* XXX: RO */ uvm_tree_size_chk(map, file, line);
5384 	LPRINTF(("map unlock: %p (at %s %d)\n", map, file, line));
5385 	if ((map->flags & VM_MAP_INTRSAFE) == 0)
5386 		rw_exit_read(&map->lock);
5387 	else
5388 		mtx_leave(&map->mtx);
5389 }
5390 
5391 void
5392 vm_map_downgrade_ln(struct vm_map *map, char *file, int line)
5393 {
5394 	uvm_tree_sanity(map, file, line);
5395 	uvm_tree_size_chk(map, file, line);
5396 	LPRINTF(("map unlock: %p (at %s %d)\n", map, file, line));
5397 	LPRINTF(("map   lock: %p (at %s %d)\n", map, file, line));
5398 	KASSERT((map->flags & VM_MAP_INTRSAFE) == 0);
5399 	if ((map->flags & VM_MAP_INTRSAFE) == 0)
5400 		rw_enter(&map->lock, RW_DOWNGRADE);
5401 }
5402 
5403 void
5404 vm_map_upgrade_ln(struct vm_map *map, char *file, int line)
5405 {
5406 	/* XXX: RO */ uvm_tree_sanity(map, file, line);
5407 	/* XXX: RO */ uvm_tree_size_chk(map, file, line);
5408 	LPRINTF(("map unlock: %p (at %s %d)\n", map, file, line));
5409 	KASSERT((map->flags & VM_MAP_INTRSAFE) == 0);
5410 	if ((map->flags & VM_MAP_INTRSAFE) == 0) {
5411 		rw_exit_read(&map->lock);
5412 		rw_enter_write(&map->lock);
5413 	}
5414 	LPRINTF(("map   lock: %p (at %s %d)\n", map, file, line));
5415 	uvm_tree_sanity(map, file, line);
5416 }
5417 
5418 void
5419 vm_map_busy_ln(struct vm_map *map, char *file, int line)
5420 {
5421 	KASSERT((map->flags & VM_MAP_INTRSAFE) == 0);
5422 	mtx_enter(&map->flags_lock);
5423 	map->flags |= VM_MAP_BUSY;
5424 	mtx_leave(&map->flags_lock);
5425 }
5426 
5427 void
5428 vm_map_unbusy_ln(struct vm_map *map, char *file, int line)
5429 {
5430 	int oflags;
5431 
5432 	KASSERT((map->flags & VM_MAP_INTRSAFE) == 0);
5433 	mtx_enter(&map->flags_lock);
5434 	oflags = map->flags;
5435 	map->flags &= ~(VM_MAP_BUSY|VM_MAP_WANTLOCK);
5436 	mtx_leave(&map->flags_lock);
5437 	if (oflags & VM_MAP_WANTLOCK)
5438 		wakeup(&map->flags);
5439 }
5440 
5441 #ifndef SMALL_KERNEL
5442 int
5443 uvm_map_fill_vmmap(struct vm_map *map, struct kinfo_vmentry *kve,
5444     size_t *lenp)
5445 {
5446 	struct vm_map_entry *entry;
5447 	vaddr_t start;
5448 	int cnt, maxcnt, error = 0;
5449 
5450 	KASSERT(*lenp > 0);
5451 	KASSERT((*lenp % sizeof(*kve)) == 0);
5452 	cnt = 0;
5453 	maxcnt = *lenp / sizeof(*kve);
5454 	KASSERT(maxcnt > 0);
5455 
5456 	/*
5457 	 * Return only entries whose address is above the given base
5458 	 * address.  This allows userland to iterate without knowing the
5459 	 * number of entries beforehand.
5460 	 */
5461 	start = (vaddr_t)kve[0].kve_start;
5462 
5463 	vm_map_lock(map);
5464 	RBT_FOREACH(entry, uvm_map_addr, &map->addr) {
5465 		if (cnt == maxcnt) {
5466 			error = ENOMEM;
5467 			break;
5468 		}
5469 		if (start != 0 && entry->start < start)
5470 			continue;
5471 		kve->kve_start = entry->start;
5472 		kve->kve_end = entry->end;
5473 		kve->kve_guard = entry->guard;
5474 		kve->kve_fspace = entry->fspace;
5475 		kve->kve_fspace_augment = entry->fspace_augment;
5476 		kve->kve_offset = entry->offset;
5477 		kve->kve_wired_count = entry->wired_count;
5478 		kve->kve_etype = entry->etype;
5479 		kve->kve_protection = entry->protection;
5480 		kve->kve_max_protection = entry->max_protection;
5481 		kve->kve_advice = entry->advice;
5482 		kve->kve_inheritance = entry->inheritance;
5483 		kve->kve_flags = entry->flags;
5484 		kve++;
5485 		cnt++;
5486 	}
5487 	vm_map_unlock(map);
5488 
5489 	KASSERT(cnt <= maxcnt);
5490 
5491 	*lenp = sizeof(*kve) * cnt;
5492 	return error;
5493 }
5494 #endif
5495 
5496 
5497 RBT_GENERATE_AUGMENT(uvm_map_addr, vm_map_entry, daddrs.addr_entry,
5498     uvm_mapentry_addrcmp, uvm_map_addr_augment);
5499 
5500 
5501 /*
5502  * MD code: vmspace allocator setup.
5503  */
5504 
5505 #ifdef __i386__
5506 void
5507 uvm_map_setup_md(struct vm_map *map)
5508 {
5509 	vaddr_t		min, max;
5510 
5511 	min = map->min_offset;
5512 	max = map->max_offset;
5513 
5514 	/*
5515 	 * Ensure the selectors will not try to manage page 0;
5516 	 * it's too special.
5517 	 */
5518 	if (min < VMMAP_MIN_ADDR)
5519 		min = VMMAP_MIN_ADDR;
5520 
5521 #if 0	/* Cool stuff, not yet */
5522 	/* Executable code is special. */
5523 	map->uaddr_exe = uaddr_rnd_create(min, I386_MAX_EXE_ADDR);
5524 	/* Place normal allocations beyond executable mappings. */
5525 	map->uaddr_any[3] = uaddr_pivot_create(2 * I386_MAX_EXE_ADDR, max);
5526 #else	/* Crappy stuff, for now */
5527 	map->uaddr_any[0] = uaddr_rnd_create(min, max);
5528 #endif
5529 
5530 #ifndef SMALL_KERNEL
5531 	map->uaddr_brk_stack = uaddr_stack_brk_create(min, max);
5532 #endif /* !SMALL_KERNEL */
5533 }
5534 #elif __LP64__
5535 void
5536 uvm_map_setup_md(struct vm_map *map)
5537 {
5538 	vaddr_t		min, max;
5539 
5540 	min = map->min_offset;
5541 	max = map->max_offset;
5542 
5543 	/*
5544 	 * Ensure the selectors will not try to manage page 0;
5545 	 * it's too special.
5546 	 */
5547 	if (min < VMMAP_MIN_ADDR)
5548 		min = VMMAP_MIN_ADDR;
5549 
5550 #if 0	/* Cool stuff, not yet */
5551 	map->uaddr_any[3] = uaddr_pivot_create(MAX(min, 0x100000000ULL), max);
5552 #else	/* Crappy stuff, for now */
5553 	map->uaddr_any[0] = uaddr_rnd_create(min, max);
5554 #endif
5555 
5556 #ifndef SMALL_KERNEL
5557 	map->uaddr_brk_stack = uaddr_stack_brk_create(min, max);
5558 #endif /* !SMALL_KERNEL */
5559 }
5560 #else	/* non-i386, 32 bit */
5561 void
5562 uvm_map_setup_md(struct vm_map *map)
5563 {
5564 	vaddr_t		min, max;
5565 
5566 	min = map->min_offset;
5567 	max = map->max_offset;
5568 
5569 	/*
5570 	 * Ensure the selectors will not try to manage page 0;
5571 	 * it's too special.
5572 	 */
5573 	if (min < VMMAP_MIN_ADDR)
5574 		min = VMMAP_MIN_ADDR;
5575 
5576 #if 0	/* Cool stuff, not yet */
5577 	map->uaddr_any[3] = uaddr_pivot_create(min, max);
5578 #else	/* Crappy stuff, for now */
5579 	map->uaddr_any[0] = uaddr_rnd_create(min, max);
5580 #endif
5581 
5582 #ifndef SMALL_KERNEL
5583 	map->uaddr_brk_stack = uaddr_stack_brk_create(min, max);
5584 #endif /* !SMALL_KERNEL */
5585 }
5586 #endif
5587