xref: /netbsd-src/sys/uvm/uvm_map.c (revision 9fb66d812c00ebfb445c0b47dea128f32aa6fe96)
1 /*	$NetBSD: uvm_map.c,v 1.387 2021/04/17 01:53:58 mrg Exp $	*/
2 
3 /*
4  * Copyright (c) 1997 Charles D. Cranor and Washington University.
5  * Copyright (c) 1991, 1993, The Regents of the University of California.
6  *
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * The Mach Operating System project at Carnegie-Mellon University.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)vm_map.c    8.3 (Berkeley) 1/12/94
37  * from: Id: uvm_map.c,v 1.1.2.27 1998/02/07 01:16:54 chs Exp
38  *
39  *
40  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
41  * All rights reserved.
42  *
43  * Permission to use, copy, modify and distribute this software and
44  * its documentation is hereby granted, provided that both the copyright
45  * notice and this permission notice appear in all copies of the
46  * software, derivative works or modified versions, and any portions
47  * thereof, and that both notices appear in supporting documentation.
48  *
49  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
50  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
51  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
52  *
53  * Carnegie Mellon requests users of this software to return to
54  *
55  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
56  *  School of Computer Science
57  *  Carnegie Mellon University
58  *  Pittsburgh PA 15213-3890
59  *
60  * any improvements or extensions that they make and grant Carnegie the
61  * rights to redistribute these changes.
62  */
63 
64 /*
65  * uvm_map.c: uvm map operations
66  */
67 
68 #include <sys/cdefs.h>
69 __KERNEL_RCSID(0, "$NetBSD: uvm_map.c,v 1.387 2021/04/17 01:53:58 mrg Exp $");
70 
71 #include "opt_ddb.h"
72 #include "opt_pax.h"
73 #include "opt_uvmhist.h"
74 #include "opt_uvm.h"
75 #include "opt_sysv.h"
76 
77 #include <sys/param.h>
78 #include <sys/systm.h>
79 #include <sys/mman.h>
80 #include <sys/proc.h>
81 #include <sys/pool.h>
82 #include <sys/kernel.h>
83 #include <sys/mount.h>
84 #include <sys/pax.h>
85 #include <sys/vnode.h>
86 #include <sys/filedesc.h>
87 #include <sys/lockdebug.h>
88 #include <sys/atomic.h>
89 #include <sys/sysctl.h>
90 #ifndef __USER_VA0_IS_SAFE
91 #include <sys/kauth.h>
92 #include "opt_user_va0_disable_default.h"
93 #endif
94 
95 #include <sys/shm.h>
96 
97 #include <uvm/uvm.h>
98 #include <uvm/uvm_readahead.h>
99 
100 #if defined(DDB) || defined(DEBUGPRINT)
101 #include <uvm/uvm_ddb.h>
102 #endif
103 
104 #ifdef UVMHIST
105 #ifndef UVMHIST_MAPHIST_SIZE
106 #define UVMHIST_MAPHIST_SIZE 100
107 #endif
108 #ifndef UVMHIST_PDHIST_SIZE
109 #define UVMHIST_PDHIST_SIZE 100
110 #endif
111 static struct kern_history_ent maphistbuf[UVMHIST_MAPHIST_SIZE];
112 UVMHIST_DEFINE(maphist) = UVMHIST_INITIALIZER(maphist, maphistbuf);
113 #endif
114 
115 #if !defined(UVMMAP_COUNTERS)
116 
117 #define	UVMMAP_EVCNT_DEFINE(name)	/* nothing */
118 #define UVMMAP_EVCNT_INCR(ev)		/* nothing */
119 #define UVMMAP_EVCNT_DECR(ev)		/* nothing */
120 
121 #else /* defined(UVMMAP_NOCOUNTERS) */
122 
123 #include <sys/evcnt.h>
124 #define	UVMMAP_EVCNT_DEFINE(name) \
125 struct evcnt uvmmap_evcnt_##name = EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, \
126     "uvmmap", #name); \
127 EVCNT_ATTACH_STATIC(uvmmap_evcnt_##name);
128 #define	UVMMAP_EVCNT_INCR(ev)		uvmmap_evcnt_##ev.ev_count++
129 #define	UVMMAP_EVCNT_DECR(ev)		uvmmap_evcnt_##ev.ev_count--
130 
131 #endif /* defined(UVMMAP_NOCOUNTERS) */
132 
133 UVMMAP_EVCNT_DEFINE(ubackmerge)
134 UVMMAP_EVCNT_DEFINE(uforwmerge)
135 UVMMAP_EVCNT_DEFINE(ubimerge)
136 UVMMAP_EVCNT_DEFINE(unomerge)
137 UVMMAP_EVCNT_DEFINE(kbackmerge)
138 UVMMAP_EVCNT_DEFINE(kforwmerge)
139 UVMMAP_EVCNT_DEFINE(kbimerge)
140 UVMMAP_EVCNT_DEFINE(knomerge)
141 UVMMAP_EVCNT_DEFINE(map_call)
142 UVMMAP_EVCNT_DEFINE(mlk_call)
143 UVMMAP_EVCNT_DEFINE(mlk_hint)
144 UVMMAP_EVCNT_DEFINE(mlk_tree)
145 UVMMAP_EVCNT_DEFINE(mlk_treeloop)
146 
147 const char vmmapbsy[] = "vmmapbsy";
148 
149 /*
150  * cache for vmspace structures.
151  */
152 
153 static struct pool_cache uvm_vmspace_cache;
154 
155 /*
156  * cache for dynamically-allocated map entries.
157  */
158 
159 static struct pool_cache uvm_map_entry_cache;
160 
161 #ifdef PMAP_GROWKERNEL
162 /*
163  * This global represents the end of the kernel virtual address
164  * space.  If we want to exceed this, we must grow the kernel
165  * virtual address space dynamically.
166  *
167  * Note, this variable is locked by kernel_map's lock.
168  */
169 vaddr_t uvm_maxkaddr;
170 #endif
171 
172 #ifndef __USER_VA0_IS_SAFE
173 #ifndef __USER_VA0_DISABLE_DEFAULT
174 #define __USER_VA0_DISABLE_DEFAULT 1
175 #endif
176 #ifdef USER_VA0_DISABLE_DEFAULT /* kernel config option overrides */
177 #undef __USER_VA0_DISABLE_DEFAULT
178 #define __USER_VA0_DISABLE_DEFAULT USER_VA0_DISABLE_DEFAULT
179 #endif
180 int user_va0_disable = __USER_VA0_DISABLE_DEFAULT;
181 #endif
182 
183 /*
184  * macros
185  */
186 
187 /*
188  * uvm_map_align_va: round down or up virtual address
189  */
190 static __inline void
191 uvm_map_align_va(vaddr_t *vap, vsize_t align, int topdown)
192 {
193 
194 	KASSERT(powerof2(align));
195 
196 	if (align != 0 && (*vap & (align - 1)) != 0) {
197 		if (topdown)
198 			*vap = rounddown2(*vap, align);
199 		else
200 			*vap = roundup2(*vap, align);
201 	}
202 }
203 
204 /*
205  * UVM_ET_ISCOMPATIBLE: check some requirements for map entry merging
206  */
207 extern struct vm_map *pager_map;
208 
209 #define	UVM_ET_ISCOMPATIBLE(ent, type, uobj, meflags, \
210     prot, maxprot, inh, adv, wire) \
211 	((ent)->etype == (type) && \
212 	(((ent)->flags ^ (meflags)) & (UVM_MAP_NOMERGE)) == 0 && \
213 	(ent)->object.uvm_obj == (uobj) && \
214 	(ent)->protection == (prot) && \
215 	(ent)->max_protection == (maxprot) && \
216 	(ent)->inheritance == (inh) && \
217 	(ent)->advice == (adv) && \
218 	(ent)->wired_count == (wire))
219 
220 /*
221  * uvm_map_entry_link: insert entry into a map
222  *
223  * => map must be locked
224  */
225 #define uvm_map_entry_link(map, after_where, entry) do { \
226 	uvm_mapent_check(entry); \
227 	(map)->nentries++; \
228 	(entry)->prev = (after_where); \
229 	(entry)->next = (after_where)->next; \
230 	(entry)->prev->next = (entry); \
231 	(entry)->next->prev = (entry); \
232 	uvm_rb_insert((map), (entry)); \
233 } while (/*CONSTCOND*/ 0)
234 
235 /*
236  * uvm_map_entry_unlink: remove entry from a map
237  *
238  * => map must be locked
239  */
240 #define uvm_map_entry_unlink(map, entry) do { \
241 	KASSERT((entry) != (map)->first_free); \
242 	KASSERT((entry) != (map)->hint); \
243 	uvm_mapent_check(entry); \
244 	(map)->nentries--; \
245 	(entry)->next->prev = (entry)->prev; \
246 	(entry)->prev->next = (entry)->next; \
247 	uvm_rb_remove((map), (entry)); \
248 } while (/*CONSTCOND*/ 0)
249 
250 /*
251  * SAVE_HINT: saves the specified entry as the hint for future lookups.
252  *
253  * => map need not be locked.
254  */
255 #define SAVE_HINT(map, check, value) do { \
256 	if ((map)->hint == (check)) \
257 		(map)->hint = (value); \
258 } while (/*CONSTCOND*/ 0)
259 
260 /*
261  * clear_hints: ensure that hints don't point to the entry.
262  *
263  * => map must be write-locked.
264  */
265 static void
266 clear_hints(struct vm_map *map, struct vm_map_entry *ent)
267 {
268 
269 	SAVE_HINT(map, ent, ent->prev);
270 	if (map->first_free == ent) {
271 		map->first_free = ent->prev;
272 	}
273 }
274 
275 /*
276  * VM_MAP_RANGE_CHECK: check and correct range
277  *
278  * => map must at least be read locked
279  */
280 
281 #define VM_MAP_RANGE_CHECK(map, start, end) do { \
282 	if (start < vm_map_min(map))		\
283 		start = vm_map_min(map);	\
284 	if (end > vm_map_max(map))		\
285 		end = vm_map_max(map);		\
286 	if (start > end)			\
287 		start = end;			\
288 } while (/*CONSTCOND*/ 0)
289 
290 /*
291  * local prototypes
292  */
293 
294 static struct vm_map_entry *
295 		uvm_mapent_alloc(struct vm_map *, int);
296 static void	uvm_mapent_copy(struct vm_map_entry *, struct vm_map_entry *);
297 static void	uvm_mapent_free(struct vm_map_entry *);
298 #if defined(DEBUG)
299 static void	_uvm_mapent_check(const struct vm_map_entry *, int);
300 #define	uvm_mapent_check(map)	_uvm_mapent_check(map, __LINE__)
301 #else /* defined(DEBUG) */
302 #define	uvm_mapent_check(e)	/* nothing */
303 #endif /* defined(DEBUG) */
304 
305 static void	uvm_map_entry_unwire(struct vm_map *, struct vm_map_entry *);
306 static void	uvm_map_reference_amap(struct vm_map_entry *, int);
307 static int	uvm_map_space_avail(vaddr_t *, vsize_t, voff_t, vsize_t, int,
308 		    int, struct vm_map_entry *);
309 static void	uvm_map_unreference_amap(struct vm_map_entry *, int);
310 
311 int _uvm_map_sanity(struct vm_map *);
312 int _uvm_tree_sanity(struct vm_map *);
313 static vsize_t uvm_rb_maxgap(const struct vm_map_entry *);
314 
315 #define	ROOT_ENTRY(map)		((struct vm_map_entry *)(map)->rb_tree.rbt_root)
316 #define	LEFT_ENTRY(entry)	((struct vm_map_entry *)(entry)->rb_node.rb_left)
317 #define	RIGHT_ENTRY(entry)	((struct vm_map_entry *)(entry)->rb_node.rb_right)
318 #define	PARENT_ENTRY(map, entry) \
319 	(ROOT_ENTRY(map) == (entry) \
320 	    ? NULL : (struct vm_map_entry *)RB_FATHER(&(entry)->rb_node))
321 
322 /*
323  * These get filled in if/when SYSVSHM shared memory code is loaded
324  *
325  * We do this with function pointers rather the #ifdef SYSVSHM so the
326  * SYSVSHM code can be loaded and unloaded
327  */
328 void (*uvm_shmexit)(struct vmspace *) = NULL;
329 void (*uvm_shmfork)(struct vmspace *, struct vmspace *) = NULL;
330 
331 static int
332 uvm_map_compare_nodes(void *ctx, const void *nparent, const void *nkey)
333 {
334 	const struct vm_map_entry *eparent = nparent;
335 	const struct vm_map_entry *ekey = nkey;
336 
337 	KASSERT(eparent->start < ekey->start || eparent->start >= ekey->end);
338 	KASSERT(ekey->start < eparent->start || ekey->start >= eparent->end);
339 
340 	if (eparent->start < ekey->start)
341 		return -1;
342 	if (eparent->end >= ekey->start)
343 		return 1;
344 	return 0;
345 }
346 
347 static int
348 uvm_map_compare_key(void *ctx, const void *nparent, const void *vkey)
349 {
350 	const struct vm_map_entry *eparent = nparent;
351 	const vaddr_t va = *(const vaddr_t *) vkey;
352 
353 	if (eparent->start < va)
354 		return -1;
355 	if (eparent->end >= va)
356 		return 1;
357 	return 0;
358 }
359 
360 static const rb_tree_ops_t uvm_map_tree_ops = {
361 	.rbto_compare_nodes = uvm_map_compare_nodes,
362 	.rbto_compare_key = uvm_map_compare_key,
363 	.rbto_node_offset = offsetof(struct vm_map_entry, rb_node),
364 	.rbto_context = NULL
365 };
366 
367 /*
368  * uvm_rb_gap: return the gap size between our entry and next entry.
369  */
370 static inline vsize_t
371 uvm_rb_gap(const struct vm_map_entry *entry)
372 {
373 
374 	KASSERT(entry->next != NULL);
375 	return entry->next->start - entry->end;
376 }
377 
378 static vsize_t
379 uvm_rb_maxgap(const struct vm_map_entry *entry)
380 {
381 	struct vm_map_entry *child;
382 	vsize_t maxgap = entry->gap;
383 
384 	/*
385 	 * We need maxgap to be the largest gap of us or any of our
386 	 * descendents.  Since each of our children's maxgap is the
387 	 * cached value of their largest gap of themselves or their
388 	 * descendents, we can just use that value and avoid recursing
389 	 * down the tree to calculate it.
390 	 */
391 	if ((child = LEFT_ENTRY(entry)) != NULL && maxgap < child->maxgap)
392 		maxgap = child->maxgap;
393 
394 	if ((child = RIGHT_ENTRY(entry)) != NULL && maxgap < child->maxgap)
395 		maxgap = child->maxgap;
396 
397 	return maxgap;
398 }
399 
400 static void
401 uvm_rb_fixup(struct vm_map *map, struct vm_map_entry *entry)
402 {
403 	struct vm_map_entry *parent;
404 
405 	KASSERT(entry->gap == uvm_rb_gap(entry));
406 	entry->maxgap = uvm_rb_maxgap(entry);
407 
408 	while ((parent = PARENT_ENTRY(map, entry)) != NULL) {
409 		struct vm_map_entry *brother;
410 		vsize_t maxgap = parent->gap;
411 		unsigned int which;
412 
413 		KDASSERT(parent->gap == uvm_rb_gap(parent));
414 		if (maxgap < entry->maxgap)
415 			maxgap = entry->maxgap;
416 		/*
417 		 * Since we work towards the root, we know entry's maxgap
418 		 * value is OK, but its brothers may now be out-of-date due
419 		 * to rebalancing.  So refresh it.
420 		 */
421 		which = RB_POSITION(&entry->rb_node) ^ RB_DIR_OTHER;
422 		brother = (struct vm_map_entry *)parent->rb_node.rb_nodes[which];
423 		if (brother != NULL) {
424 			KDASSERT(brother->gap == uvm_rb_gap(brother));
425 			brother->maxgap = uvm_rb_maxgap(brother);
426 			if (maxgap < brother->maxgap)
427 				maxgap = brother->maxgap;
428 		}
429 
430 		parent->maxgap = maxgap;
431 		entry = parent;
432 	}
433 }
434 
435 static void
436 uvm_rb_insert(struct vm_map *map, struct vm_map_entry *entry)
437 {
438 	struct vm_map_entry *ret __diagused;
439 
440 	entry->gap = entry->maxgap = uvm_rb_gap(entry);
441 	if (entry->prev != &map->header)
442 		entry->prev->gap = uvm_rb_gap(entry->prev);
443 
444 	ret = rb_tree_insert_node(&map->rb_tree, entry);
445 	KASSERTMSG(ret == entry,
446 	    "uvm_rb_insert: map %p: duplicate entry %p", map, ret);
447 
448 	/*
449 	 * If the previous entry is not our immediate left child, then it's an
450 	 * ancestor and will be fixed up on the way to the root.  We don't
451 	 * have to check entry->prev against &map->header since &map->header
452 	 * will never be in the tree.
453 	 */
454 	uvm_rb_fixup(map,
455 	    LEFT_ENTRY(entry) == entry->prev ? entry->prev : entry);
456 }
457 
458 static void
459 uvm_rb_remove(struct vm_map *map, struct vm_map_entry *entry)
460 {
461 	struct vm_map_entry *prev_parent = NULL, *next_parent = NULL;
462 
463 	/*
464 	 * If we are removing an interior node, then an adjacent node will
465 	 * be used to replace its position in the tree.  Therefore we will
466 	 * need to fixup the tree starting at the parent of the replacement
467 	 * node.  So record their parents for later use.
468 	 */
469 	if (entry->prev != &map->header)
470 		prev_parent = PARENT_ENTRY(map, entry->prev);
471 	if (entry->next != &map->header)
472 		next_parent = PARENT_ENTRY(map, entry->next);
473 
474 	rb_tree_remove_node(&map->rb_tree, entry);
475 
476 	/*
477 	 * If the previous node has a new parent, fixup the tree starting
478 	 * at the previous node's old parent.
479 	 */
480 	if (entry->prev != &map->header) {
481 		/*
482 		 * Update the previous entry's gap due to our absence.
483 		 */
484 		entry->prev->gap = uvm_rb_gap(entry->prev);
485 		uvm_rb_fixup(map, entry->prev);
486 		if (prev_parent != NULL
487 		    && prev_parent != entry
488 		    && prev_parent != PARENT_ENTRY(map, entry->prev))
489 			uvm_rb_fixup(map, prev_parent);
490 	}
491 
492 	/*
493 	 * If the next node has a new parent, fixup the tree starting
494 	 * at the next node's old parent.
495 	 */
496 	if (entry->next != &map->header) {
497 		uvm_rb_fixup(map, entry->next);
498 		if (next_parent != NULL
499 		    && next_parent != entry
500 		    && next_parent != PARENT_ENTRY(map, entry->next))
501 			uvm_rb_fixup(map, next_parent);
502 	}
503 }
504 
505 #if defined(DEBUG)
506 int uvm_debug_check_map = 0;
507 int uvm_debug_check_rbtree = 0;
508 #define uvm_map_check(map, name) \
509 	_uvm_map_check((map), (name), __FILE__, __LINE__)
510 static void
511 _uvm_map_check(struct vm_map *map, const char *name,
512     const char *file, int line)
513 {
514 
515 	if ((uvm_debug_check_map && _uvm_map_sanity(map)) ||
516 	    (uvm_debug_check_rbtree && _uvm_tree_sanity(map))) {
517 		panic("uvm_map_check failed: \"%s\" map=%p (%s:%d)",
518 		    name, map, file, line);
519 	}
520 }
521 #else /* defined(DEBUG) */
522 #define uvm_map_check(map, name)	/* nothing */
523 #endif /* defined(DEBUG) */
524 
525 #if defined(DEBUG) || defined(DDB)
526 int
527 _uvm_map_sanity(struct vm_map *map)
528 {
529 	bool first_free_found = false;
530 	bool hint_found = false;
531 	const struct vm_map_entry *e;
532 	struct vm_map_entry *hint = map->hint;
533 
534 	e = &map->header;
535 	for (;;) {
536 		if (map->first_free == e) {
537 			first_free_found = true;
538 		} else if (!first_free_found && e->next->start > e->end) {
539 			printf("first_free %p should be %p\n",
540 			    map->first_free, e);
541 			return -1;
542 		}
543 		if (hint == e) {
544 			hint_found = true;
545 		}
546 
547 		e = e->next;
548 		if (e == &map->header) {
549 			break;
550 		}
551 	}
552 	if (!first_free_found) {
553 		printf("stale first_free\n");
554 		return -1;
555 	}
556 	if (!hint_found) {
557 		printf("stale hint\n");
558 		return -1;
559 	}
560 	return 0;
561 }
562 
563 int
564 _uvm_tree_sanity(struct vm_map *map)
565 {
566 	struct vm_map_entry *tmp, *trtmp;
567 	int n = 0, i = 1;
568 
569 	for (tmp = map->header.next; tmp != &map->header; tmp = tmp->next) {
570 		if (tmp->gap != uvm_rb_gap(tmp)) {
571 			printf("%d/%d gap %#lx != %#lx %s\n",
572 			    n + 1, map->nentries,
573 			    (ulong)tmp->gap, (ulong)uvm_rb_gap(tmp),
574 			    tmp->next == &map->header ? "(last)" : "");
575 			goto error;
576 		}
577 		/*
578 		 * If any entries are out of order, tmp->gap will be unsigned
579 		 * and will likely exceed the size of the map.
580 		 */
581 		if (tmp->gap >= vm_map_max(map) - vm_map_min(map)) {
582 			printf("too large gap %zu\n", (size_t)tmp->gap);
583 			goto error;
584 		}
585 		n++;
586 	}
587 
588 	if (n != map->nentries) {
589 		printf("nentries: %d vs %d\n", n, map->nentries);
590 		goto error;
591 	}
592 
593 	trtmp = NULL;
594 	for (tmp = map->header.next; tmp != &map->header; tmp = tmp->next) {
595 		if (tmp->maxgap != uvm_rb_maxgap(tmp)) {
596 			printf("maxgap %#lx != %#lx\n",
597 			    (ulong)tmp->maxgap,
598 			    (ulong)uvm_rb_maxgap(tmp));
599 			goto error;
600 		}
601 		if (trtmp != NULL && trtmp->start >= tmp->start) {
602 			printf("corrupt: 0x%"PRIxVADDR"x >= 0x%"PRIxVADDR"x\n",
603 			    trtmp->start, tmp->start);
604 			goto error;
605 		}
606 
607 		trtmp = tmp;
608 	}
609 
610 	for (tmp = map->header.next; tmp != &map->header;
611 	    tmp = tmp->next, i++) {
612 		trtmp = rb_tree_iterate(&map->rb_tree, tmp, RB_DIR_LEFT);
613 		if (trtmp == NULL)
614 			trtmp = &map->header;
615 		if (tmp->prev != trtmp) {
616 			printf("lookup: %d: %p->prev=%p: %p\n",
617 			    i, tmp, tmp->prev, trtmp);
618 			goto error;
619 		}
620 		trtmp = rb_tree_iterate(&map->rb_tree, tmp, RB_DIR_RIGHT);
621 		if (trtmp == NULL)
622 			trtmp = &map->header;
623 		if (tmp->next != trtmp) {
624 			printf("lookup: %d: %p->next=%p: %p\n",
625 			    i, tmp, tmp->next, trtmp);
626 			goto error;
627 		}
628 		trtmp = rb_tree_find_node(&map->rb_tree, &tmp->start);
629 		if (trtmp != tmp) {
630 			printf("lookup: %d: %p - %p: %p\n", i, tmp, trtmp,
631 			    PARENT_ENTRY(map, tmp));
632 			goto error;
633 		}
634 	}
635 
636 	return (0);
637  error:
638 	return (-1);
639 }
640 #endif /* defined(DEBUG) || defined(DDB) */
641 
642 /*
643  * vm_map_lock: acquire an exclusive (write) lock on a map.
644  *
645  * => The locking protocol provides for guaranteed upgrade from shared ->
646  *    exclusive by whichever thread currently has the map marked busy.
647  *    See "LOCKING PROTOCOL NOTES" in uvm_map.h.  This is horrible; among
648  *    other problems, it defeats any fairness guarantees provided by RW
649  *    locks.
650  */
651 
652 void
653 vm_map_lock(struct vm_map *map)
654 {
655 
656 	for (;;) {
657 		rw_enter(&map->lock, RW_WRITER);
658 		if (map->busy == NULL || map->busy == curlwp) {
659 			break;
660 		}
661 		mutex_enter(&map->misc_lock);
662 		rw_exit(&map->lock);
663 		if (map->busy != NULL) {
664 			cv_wait(&map->cv, &map->misc_lock);
665 		}
666 		mutex_exit(&map->misc_lock);
667 	}
668 	map->timestamp++;
669 }
670 
671 /*
672  * vm_map_lock_try: try to lock a map, failing if it is already locked.
673  */
674 
675 bool
676 vm_map_lock_try(struct vm_map *map)
677 {
678 
679 	if (!rw_tryenter(&map->lock, RW_WRITER)) {
680 		return false;
681 	}
682 	if (map->busy != NULL) {
683 		rw_exit(&map->lock);
684 		return false;
685 	}
686 	map->timestamp++;
687 	return true;
688 }
689 
690 /*
691  * vm_map_unlock: release an exclusive lock on a map.
692  */
693 
694 void
695 vm_map_unlock(struct vm_map *map)
696 {
697 
698 	KASSERT(rw_write_held(&map->lock));
699 	KASSERT(map->busy == NULL || map->busy == curlwp);
700 	rw_exit(&map->lock);
701 }
702 
703 /*
704  * vm_map_unbusy: mark the map as unbusy, and wake any waiters that
705  *     want an exclusive lock.
706  */
707 
708 void
709 vm_map_unbusy(struct vm_map *map)
710 {
711 
712 	KASSERT(map->busy == curlwp);
713 
714 	/*
715 	 * Safe to clear 'busy' and 'waiters' with only a read lock held:
716 	 *
717 	 * o they can only be set with a write lock held
718 	 * o writers are blocked out with a read or write hold
719 	 * o at any time, only one thread owns the set of values
720 	 */
721 	mutex_enter(&map->misc_lock);
722 	map->busy = NULL;
723 	cv_broadcast(&map->cv);
724 	mutex_exit(&map->misc_lock);
725 }
726 
727 /*
728  * vm_map_lock_read: acquire a shared (read) lock on a map.
729  */
730 
731 void
732 vm_map_lock_read(struct vm_map *map)
733 {
734 
735 	rw_enter(&map->lock, RW_READER);
736 }
737 
738 /*
739  * vm_map_unlock_read: release a shared lock on a map.
740  */
741 
742 void
743 vm_map_unlock_read(struct vm_map *map)
744 {
745 
746 	rw_exit(&map->lock);
747 }
748 
749 /*
750  * vm_map_busy: mark a map as busy.
751  *
752  * => the caller must hold the map write locked
753  */
754 
755 void
756 vm_map_busy(struct vm_map *map)
757 {
758 
759 	KASSERT(rw_write_held(&map->lock));
760 	KASSERT(map->busy == NULL);
761 
762 	map->busy = curlwp;
763 }
764 
765 /*
766  * vm_map_locked_p: return true if the map is write locked.
767  *
768  * => only for debug purposes like KASSERTs.
769  * => should not be used to verify that a map is not locked.
770  */
771 
772 bool
773 vm_map_locked_p(struct vm_map *map)
774 {
775 
776 	return rw_write_held(&map->lock);
777 }
778 
779 /*
780  * uvm_mapent_alloc: allocate a map entry
781  */
782 
783 static struct vm_map_entry *
784 uvm_mapent_alloc(struct vm_map *map, int flags)
785 {
786 	struct vm_map_entry *me;
787 	int pflags = (flags & UVM_FLAG_NOWAIT) ? PR_NOWAIT : PR_WAITOK;
788 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
789 
790 	me = pool_cache_get(&uvm_map_entry_cache, pflags);
791 	if (__predict_false(me == NULL)) {
792 		return NULL;
793 	}
794 	me->flags = 0;
795 
796 	UVMHIST_LOG(maphist, "<- new entry=%#jx [kentry=%jd]", (uintptr_t)me,
797 	    (map == kernel_map), 0, 0);
798 	return me;
799 }
800 
801 /*
802  * uvm_mapent_free: free map entry
803  */
804 
805 static void
806 uvm_mapent_free(struct vm_map_entry *me)
807 {
808 	UVMHIST_FUNC(__func__);
809 	UVMHIST_CALLARGS(maphist,"<- freeing map entry=%#jx [flags=%#jx]",
810 		(uintptr_t)me, me->flags, 0, 0);
811 	pool_cache_put(&uvm_map_entry_cache, me);
812 }
813 
814 /*
815  * uvm_mapent_copy: copy a map entry, preserving flags
816  */
817 
818 static inline void
819 uvm_mapent_copy(struct vm_map_entry *src, struct vm_map_entry *dst)
820 {
821 
822 	memcpy(dst, src, sizeof(*dst));
823 	dst->flags = 0;
824 }
825 
826 #if defined(DEBUG)
827 static void
828 _uvm_mapent_check(const struct vm_map_entry *entry, int line)
829 {
830 
831 	if (entry->start >= entry->end) {
832 		goto bad;
833 	}
834 	if (UVM_ET_ISOBJ(entry)) {
835 		if (entry->object.uvm_obj == NULL) {
836 			goto bad;
837 		}
838 	} else if (UVM_ET_ISSUBMAP(entry)) {
839 		if (entry->object.sub_map == NULL) {
840 			goto bad;
841 		}
842 	} else {
843 		if (entry->object.uvm_obj != NULL ||
844 		    entry->object.sub_map != NULL) {
845 			goto bad;
846 		}
847 	}
848 	if (!UVM_ET_ISOBJ(entry)) {
849 		if (entry->offset != 0) {
850 			goto bad;
851 		}
852 	}
853 
854 	return;
855 
856 bad:
857 	panic("%s: bad entry %p, line %d", __func__, entry, line);
858 }
859 #endif /* defined(DEBUG) */
860 
861 /*
862  * uvm_map_entry_unwire: unwire a map entry
863  *
864  * => map should be locked by caller
865  */
866 
867 static inline void
868 uvm_map_entry_unwire(struct vm_map *map, struct vm_map_entry *entry)
869 {
870 
871 	entry->wired_count = 0;
872 	uvm_fault_unwire_locked(map, entry->start, entry->end);
873 }
874 
875 
876 /*
877  * wrapper for calling amap_ref()
878  */
879 static inline void
880 uvm_map_reference_amap(struct vm_map_entry *entry, int flags)
881 {
882 
883 	amap_ref(entry->aref.ar_amap, entry->aref.ar_pageoff,
884 	    (entry->end - entry->start) >> PAGE_SHIFT, flags);
885 }
886 
887 
888 /*
889  * wrapper for calling amap_unref()
890  */
891 static inline void
892 uvm_map_unreference_amap(struct vm_map_entry *entry, int flags)
893 {
894 
895 	amap_unref(entry->aref.ar_amap, entry->aref.ar_pageoff,
896 	    (entry->end - entry->start) >> PAGE_SHIFT, flags);
897 }
898 
899 
900 /*
901  * uvm_map_init: init mapping system at boot time.
902  */
903 
904 void
905 uvm_map_init(void)
906 {
907 	/*
908 	 * first, init logging system.
909 	 */
910 
911 	UVMHIST_FUNC(__func__);
912 	UVMHIST_LINK_STATIC(maphist);
913 	UVMHIST_LINK_STATIC(pdhist);
914 	UVMHIST_CALLED(maphist);
915 	UVMHIST_LOG(maphist,"<starting uvm map system>", 0, 0, 0, 0);
916 
917 	/*
918 	 * initialize the global lock for kernel map entry.
919 	 */
920 
921 	mutex_init(&uvm_kentry_lock, MUTEX_DRIVER, IPL_VM);
922 }
923 
924 /*
925  * uvm_map_init_caches: init mapping system caches.
926  */
927 void
928 uvm_map_init_caches(void)
929 {
930 	/*
931 	 * initialize caches.
932 	 */
933 
934 	pool_cache_bootstrap(&uvm_map_entry_cache, sizeof(struct vm_map_entry),
935 	    coherency_unit, 0, PR_LARGECACHE, "vmmpepl", NULL, IPL_NONE, NULL,
936 	    NULL, NULL);
937 	pool_cache_bootstrap(&uvm_vmspace_cache, sizeof(struct vmspace),
938 	    0, 0, 0, "vmsppl", NULL, IPL_NONE, NULL, NULL, NULL);
939 }
940 
941 /*
942  * clippers
943  */
944 
945 /*
946  * uvm_mapent_splitadj: adjust map entries for splitting, after uvm_mapent_copy.
947  */
948 
949 static void
950 uvm_mapent_splitadj(struct vm_map_entry *entry1, struct vm_map_entry *entry2,
951     vaddr_t splitat)
952 {
953 	vaddr_t adj;
954 
955 	KASSERT(entry1->start < splitat);
956 	KASSERT(splitat < entry1->end);
957 
958 	adj = splitat - entry1->start;
959 	entry1->end = entry2->start = splitat;
960 
961 	if (entry1->aref.ar_amap) {
962 		amap_splitref(&entry1->aref, &entry2->aref, adj);
963 	}
964 	if (UVM_ET_ISSUBMAP(entry1)) {
965 		/* ... unlikely to happen, but play it safe */
966 		 uvm_map_reference(entry1->object.sub_map);
967 	} else if (UVM_ET_ISOBJ(entry1)) {
968 		KASSERT(entry1->object.uvm_obj != NULL); /* suppress coverity */
969 		entry2->offset += adj;
970 		if (entry1->object.uvm_obj->pgops &&
971 		    entry1->object.uvm_obj->pgops->pgo_reference)
972 			entry1->object.uvm_obj->pgops->pgo_reference(
973 			    entry1->object.uvm_obj);
974 	}
975 }
976 
977 /*
978  * uvm_map_clip_start: ensure that the entry begins at or after
979  *	the starting address, if it doesn't we split the entry.
980  *
981  * => caller should use UVM_MAP_CLIP_START macro rather than calling
982  *    this directly
983  * => map must be locked by caller
984  */
985 
986 void
987 uvm_map_clip_start(struct vm_map *map, struct vm_map_entry *entry,
988     vaddr_t start)
989 {
990 	struct vm_map_entry *new_entry;
991 
992 	/* uvm_map_simplify_entry(map, entry); */ /* XXX */
993 
994 	uvm_map_check(map, "clip_start entry");
995 	uvm_mapent_check(entry);
996 
997 	/*
998 	 * Split off the front portion.  note that we must insert the new
999 	 * entry BEFORE this one, so that this entry has the specified
1000 	 * starting address.
1001 	 */
1002 	new_entry = uvm_mapent_alloc(map, 0);
1003 	uvm_mapent_copy(entry, new_entry); /* entry -> new_entry */
1004 	uvm_mapent_splitadj(new_entry, entry, start);
1005 	uvm_map_entry_link(map, entry->prev, new_entry);
1006 
1007 	uvm_map_check(map, "clip_start leave");
1008 }
1009 
1010 /*
1011  * uvm_map_clip_end: ensure that the entry ends at or before
1012  *	the ending address, if it does't we split the reference
1013  *
1014  * => caller should use UVM_MAP_CLIP_END macro rather than calling
1015  *    this directly
1016  * => map must be locked by caller
1017  */
1018 
1019 void
1020 uvm_map_clip_end(struct vm_map *map, struct vm_map_entry *entry, vaddr_t end)
1021 {
1022 	struct vm_map_entry *new_entry;
1023 
1024 	uvm_map_check(map, "clip_end entry");
1025 	uvm_mapent_check(entry);
1026 
1027 	/*
1028 	 *	Create a new entry and insert it
1029 	 *	AFTER the specified entry
1030 	 */
1031 	new_entry = uvm_mapent_alloc(map, 0);
1032 	uvm_mapent_copy(entry, new_entry); /* entry -> new_entry */
1033 	uvm_mapent_splitadj(entry, new_entry, end);
1034 	uvm_map_entry_link(map, entry, new_entry);
1035 
1036 	uvm_map_check(map, "clip_end leave");
1037 }
1038 
1039 /*
1040  *   M A P   -   m a i n   e n t r y   p o i n t
1041  */
1042 /*
1043  * uvm_map: establish a valid mapping in a map
1044  *
1045  * => assume startp is page aligned.
1046  * => assume size is a multiple of PAGE_SIZE.
1047  * => assume sys_mmap provides enough of a "hint" to have us skip
1048  *	over text/data/bss area.
1049  * => map must be unlocked (we will lock it)
1050  * => <uobj,uoffset> value meanings (4 cases):
1051  *	 [1] <NULL,uoffset>		== uoffset is a hint for PMAP_PREFER
1052  *	 [2] <NULL,UVM_UNKNOWN_OFFSET>	== don't PMAP_PREFER
1053  *	 [3] <uobj,uoffset>		== normal mapping
1054  *	 [4] <uobj,UVM_UNKNOWN_OFFSET>	== uvm_map finds offset based on VA
1055  *
1056  *    case [4] is for kernel mappings where we don't know the offset until
1057  *    we've found a virtual address.   note that kernel object offsets are
1058  *    always relative to vm_map_min(kernel_map).
1059  *
1060  * => if `align' is non-zero, we align the virtual address to the specified
1061  *	alignment.
1062  *	this is provided as a mechanism for large pages.
1063  *
1064  * => XXXCDC: need way to map in external amap?
1065  */
1066 
1067 int
1068 uvm_map(struct vm_map *map, vaddr_t *startp /* IN/OUT */, vsize_t size,
1069     struct uvm_object *uobj, voff_t uoffset, vsize_t align, uvm_flag_t flags)
1070 {
1071 	struct uvm_map_args args;
1072 	struct vm_map_entry *new_entry;
1073 	int error;
1074 
1075 	KASSERT((size & PAGE_MASK) == 0);
1076 	KASSERT((flags & UVM_FLAG_FIXED) == 0 || align == 0);
1077 
1078 	/*
1079 	 * for pager_map, allocate the new entry first to avoid sleeping
1080 	 * for memory while we have the map locked.
1081 	 */
1082 
1083 	new_entry = NULL;
1084 	if (map == pager_map) {
1085 		new_entry = uvm_mapent_alloc(map, (flags & UVM_FLAG_NOWAIT));
1086 		if (__predict_false(new_entry == NULL))
1087 			return ENOMEM;
1088 	}
1089 	if (map == pager_map)
1090 		flags |= UVM_FLAG_NOMERGE;
1091 
1092 	error = uvm_map_prepare(map, *startp, size, uobj, uoffset, align,
1093 	    flags, &args);
1094 	if (!error) {
1095 		error = uvm_map_enter(map, &args, new_entry);
1096 		*startp = args.uma_start;
1097 	} else if (new_entry) {
1098 		uvm_mapent_free(new_entry);
1099 	}
1100 
1101 #if defined(DEBUG)
1102 	if (!error && VM_MAP_IS_KERNEL(map) && (flags & UVM_FLAG_NOWAIT) == 0) {
1103 		uvm_km_check_empty(map, *startp, *startp + size);
1104 	}
1105 #endif /* defined(DEBUG) */
1106 
1107 	return error;
1108 }
1109 
1110 /*
1111  * uvm_map_prepare:
1112  *
1113  * called with map unlocked.
1114  * on success, returns the map locked.
1115  */
1116 
1117 int
1118 uvm_map_prepare(struct vm_map *map, vaddr_t start, vsize_t size,
1119     struct uvm_object *uobj, voff_t uoffset, vsize_t align, uvm_flag_t flags,
1120     struct uvm_map_args *args)
1121 {
1122 	struct vm_map_entry *prev_entry;
1123 	vm_prot_t prot = UVM_PROTECTION(flags);
1124 	vm_prot_t maxprot = UVM_MAXPROTECTION(flags);
1125 
1126 	UVMHIST_FUNC(__func__);
1127 	UVMHIST_CALLARGS(maphist, "(map=%#jx, start=%#jx, size=%ju, flags=%#jx)",
1128 	    (uintptr_t)map, start, size, flags);
1129 	UVMHIST_LOG(maphist, "  uobj/offset %#jx/%jd", (uintptr_t)uobj,
1130 	    uoffset,0,0);
1131 
1132 	/*
1133 	 * detect a popular device driver bug.
1134 	 */
1135 
1136 	KASSERT(doing_shutdown || curlwp != NULL);
1137 
1138 	/*
1139 	 * zero-sized mapping doesn't make any sense.
1140 	 */
1141 	KASSERT(size > 0);
1142 
1143 	KASSERT((~flags & (UVM_FLAG_NOWAIT | UVM_FLAG_WAITVA)) != 0);
1144 
1145 	uvm_map_check(map, "map entry");
1146 
1147 	/*
1148 	 * check sanity of protection code
1149 	 */
1150 
1151 	if ((prot & maxprot) != prot) {
1152 		UVMHIST_LOG(maphist, "<- prot. failure:  prot=%#jx, max=%#jx",
1153 		prot, maxprot,0,0);
1154 		return EACCES;
1155 	}
1156 
1157 	/*
1158 	 * figure out where to put new VM range
1159 	 */
1160 retry:
1161 	if (vm_map_lock_try(map) == false) {
1162 		if ((flags & UVM_FLAG_TRYLOCK) != 0) {
1163 			return EAGAIN;
1164 		}
1165 		vm_map_lock(map); /* could sleep here */
1166 	}
1167 	if (flags & UVM_FLAG_UNMAP) {
1168 		KASSERT(flags & UVM_FLAG_FIXED);
1169 		KASSERT((flags & UVM_FLAG_NOWAIT) == 0);
1170 
1171 		/*
1172 		 * Set prev_entry to what it will need to be after any existing
1173 		 * entries are removed later in uvm_map_enter().
1174 		 */
1175 
1176 		if (uvm_map_lookup_entry(map, start, &prev_entry)) {
1177 			if (start == prev_entry->start)
1178 				prev_entry = prev_entry->prev;
1179 			else
1180 				UVM_MAP_CLIP_END(map, prev_entry, start);
1181 			SAVE_HINT(map, map->hint, prev_entry);
1182 		}
1183 	} else {
1184 		prev_entry = uvm_map_findspace(map, start, size, &start,
1185 		    uobj, uoffset, align, flags);
1186 	}
1187 	if (prev_entry == NULL) {
1188 		unsigned int timestamp;
1189 
1190 		timestamp = map->timestamp;
1191 		UVMHIST_LOG(maphist,"waiting va timestamp=%#jx",
1192 			    timestamp,0,0,0);
1193 		map->flags |= VM_MAP_WANTVA;
1194 		vm_map_unlock(map);
1195 
1196 		/*
1197 		 * try to reclaim kva and wait until someone does unmap.
1198 		 * fragile locking here, so we awaken every second to
1199 		 * recheck the condition.
1200 		 */
1201 
1202 		mutex_enter(&map->misc_lock);
1203 		while ((map->flags & VM_MAP_WANTVA) != 0 &&
1204 		   map->timestamp == timestamp) {
1205 			if ((flags & UVM_FLAG_WAITVA) == 0) {
1206 				mutex_exit(&map->misc_lock);
1207 				UVMHIST_LOG(maphist,
1208 				    "<- uvm_map_findspace failed!", 0,0,0,0);
1209 				return ENOMEM;
1210 			} else {
1211 				cv_timedwait(&map->cv, &map->misc_lock, hz);
1212 			}
1213 		}
1214 		mutex_exit(&map->misc_lock);
1215 		goto retry;
1216 	}
1217 
1218 #ifdef PMAP_GROWKERNEL
1219 	/*
1220 	 * If the kernel pmap can't map the requested space,
1221 	 * then allocate more resources for it.
1222 	 */
1223 	if (map == kernel_map && uvm_maxkaddr < (start + size))
1224 		uvm_maxkaddr = pmap_growkernel(start + size);
1225 #endif
1226 
1227 	UVMMAP_EVCNT_INCR(map_call);
1228 
1229 	/*
1230 	 * if uobj is null, then uoffset is either a VAC hint for PMAP_PREFER
1231 	 * [typically from uvm_map_reserve] or it is UVM_UNKNOWN_OFFSET.   in
1232 	 * either case we want to zero it  before storing it in the map entry
1233 	 * (because it looks strange and confusing when debugging...)
1234 	 *
1235 	 * if uobj is not null
1236 	 *   if uoffset is not UVM_UNKNOWN_OFFSET then we have a normal mapping
1237 	 *      and we do not need to change uoffset.
1238 	 *   if uoffset is UVM_UNKNOWN_OFFSET then we need to find the offset
1239 	 *      now (based on the starting address of the map).   this case is
1240 	 *      for kernel object mappings where we don't know the offset until
1241 	 *      the virtual address is found (with uvm_map_findspace).   the
1242 	 *      offset is the distance we are from the start of the map.
1243 	 */
1244 
1245 	if (uobj == NULL) {
1246 		uoffset = 0;
1247 	} else {
1248 		if (uoffset == UVM_UNKNOWN_OFFSET) {
1249 			KASSERT(UVM_OBJ_IS_KERN_OBJECT(uobj));
1250 			uoffset = start - vm_map_min(kernel_map);
1251 		}
1252 	}
1253 
1254 	args->uma_flags = flags;
1255 	args->uma_prev = prev_entry;
1256 	args->uma_start = start;
1257 	args->uma_size = size;
1258 	args->uma_uobj = uobj;
1259 	args->uma_uoffset = uoffset;
1260 
1261 	UVMHIST_LOG(maphist, "<- done!", 0,0,0,0);
1262 	return 0;
1263 }
1264 
1265 /*
1266  * uvm_map_enter:
1267  *
1268  * called with map locked.
1269  * unlock the map before returning.
1270  */
1271 
1272 int
1273 uvm_map_enter(struct vm_map *map, const struct uvm_map_args *args,
1274     struct vm_map_entry *new_entry)
1275 {
1276 	struct vm_map_entry *prev_entry = args->uma_prev;
1277 	struct vm_map_entry *dead = NULL, *dead_entries = NULL;
1278 
1279 	const uvm_flag_t flags = args->uma_flags;
1280 	const vm_prot_t prot = UVM_PROTECTION(flags);
1281 	const vm_prot_t maxprot = UVM_MAXPROTECTION(flags);
1282 	const vm_inherit_t inherit = UVM_INHERIT(flags);
1283 	const int amapwaitflag = (flags & UVM_FLAG_NOWAIT) ?
1284 	    AMAP_EXTEND_NOWAIT : 0;
1285 	const int advice = UVM_ADVICE(flags);
1286 
1287 	vaddr_t start = args->uma_start;
1288 	vsize_t size = args->uma_size;
1289 	struct uvm_object *uobj = args->uma_uobj;
1290 	voff_t uoffset = args->uma_uoffset;
1291 
1292 	const int kmap = (vm_map_pmap(map) == pmap_kernel());
1293 	int merged = 0;
1294 	int error;
1295 	int newetype;
1296 
1297 	UVMHIST_FUNC(__func__);
1298 	UVMHIST_CALLARGS(maphist, "(map=%#jx, start=%#jx, size=%ju, flags=%#jx)",
1299 	    (uintptr_t)map, start, size, flags);
1300 	UVMHIST_LOG(maphist, "  uobj/offset %#jx/%jd", (uintptr_t)uobj,
1301 	    uoffset,0,0);
1302 
1303 	KASSERT(map->hint == prev_entry); /* bimerge case assumes this */
1304 	KASSERT(vm_map_locked_p(map));
1305 	KASSERT((flags & (UVM_FLAG_NOWAIT | UVM_FLAG_UNMAP)) !=
1306 		(UVM_FLAG_NOWAIT | UVM_FLAG_UNMAP));
1307 
1308 	if (uobj)
1309 		newetype = UVM_ET_OBJ;
1310 	else
1311 		newetype = 0;
1312 
1313 	if (flags & UVM_FLAG_COPYONW) {
1314 		newetype |= UVM_ET_COPYONWRITE;
1315 		if ((flags & UVM_FLAG_OVERLAY) == 0)
1316 			newetype |= UVM_ET_NEEDSCOPY;
1317 	}
1318 
1319 	/*
1320 	 * For mappings with unmap, remove any old entries now.  Adding the new
1321 	 * entry cannot fail because that can only happen if UVM_FLAG_NOWAIT
1322 	 * is set, and we do not support nowait and unmap together.
1323 	 */
1324 
1325 	if (flags & UVM_FLAG_UNMAP) {
1326 		KASSERT(flags & UVM_FLAG_FIXED);
1327 		uvm_unmap_remove(map, start, start + size, &dead_entries, 0);
1328 #ifdef DEBUG
1329 		struct vm_map_entry *tmp_entry __diagused;
1330 		bool rv __diagused;
1331 
1332 		rv = uvm_map_lookup_entry(map, start, &tmp_entry);
1333 		KASSERT(!rv);
1334 		KASSERTMSG(prev_entry == tmp_entry,
1335 			   "args %p prev_entry %p tmp_entry %p",
1336 			   args, prev_entry, tmp_entry);
1337 #endif
1338 		SAVE_HINT(map, map->hint, prev_entry);
1339 	}
1340 
1341 	/*
1342 	 * try and insert in map by extending previous entry, if possible.
1343 	 * XXX: we don't try and pull back the next entry.   might be useful
1344 	 * for a stack, but we are currently allocating our stack in advance.
1345 	 */
1346 
1347 	if (flags & UVM_FLAG_NOMERGE)
1348 		goto nomerge;
1349 
1350 	if (prev_entry->end == start &&
1351 	    prev_entry != &map->header &&
1352 	    UVM_ET_ISCOMPATIBLE(prev_entry, newetype, uobj, 0,
1353 	    prot, maxprot, inherit, advice, 0)) {
1354 
1355 		if (uobj && prev_entry->offset +
1356 		    (prev_entry->end - prev_entry->start) != uoffset)
1357 			goto forwardmerge;
1358 
1359 		/*
1360 		 * can't extend a shared amap.  note: no need to lock amap to
1361 		 * look at refs since we don't care about its exact value.
1362 		 * if it is one (i.e. we have only reference) it will stay there
1363 		 */
1364 
1365 		if (prev_entry->aref.ar_amap &&
1366 		    amap_refs(prev_entry->aref.ar_amap) != 1) {
1367 			goto forwardmerge;
1368 		}
1369 
1370 		if (prev_entry->aref.ar_amap) {
1371 			error = amap_extend(prev_entry, size,
1372 			    amapwaitflag | AMAP_EXTEND_FORWARDS);
1373 			if (error)
1374 				goto nomerge;
1375 		}
1376 
1377 		if (kmap) {
1378 			UVMMAP_EVCNT_INCR(kbackmerge);
1379 		} else {
1380 			UVMMAP_EVCNT_INCR(ubackmerge);
1381 		}
1382 		UVMHIST_LOG(maphist,"  starting back merge", 0, 0, 0, 0);
1383 
1384 		/*
1385 		 * drop our reference to uobj since we are extending a reference
1386 		 * that we already have (the ref count can not drop to zero).
1387 		 */
1388 
1389 		if (uobj && uobj->pgops->pgo_detach)
1390 			uobj->pgops->pgo_detach(uobj);
1391 
1392 		/*
1393 		 * Now that we've merged the entries, note that we've grown
1394 		 * and our gap has shrunk.  Then fix the tree.
1395 		 */
1396 		prev_entry->end += size;
1397 		prev_entry->gap -= size;
1398 		uvm_rb_fixup(map, prev_entry);
1399 
1400 		uvm_map_check(map, "map backmerged");
1401 
1402 		UVMHIST_LOG(maphist,"<- done (via backmerge)!", 0, 0, 0, 0);
1403 		merged++;
1404 	}
1405 
1406 forwardmerge:
1407 	if (prev_entry->next->start == (start + size) &&
1408 	    prev_entry->next != &map->header &&
1409 	    UVM_ET_ISCOMPATIBLE(prev_entry->next, newetype, uobj, 0,
1410 	    prot, maxprot, inherit, advice, 0)) {
1411 
1412 		if (uobj && prev_entry->next->offset != uoffset + size)
1413 			goto nomerge;
1414 
1415 		/*
1416 		 * can't extend a shared amap.  note: no need to lock amap to
1417 		 * look at refs since we don't care about its exact value.
1418 		 * if it is one (i.e. we have only reference) it will stay there.
1419 		 *
1420 		 * note that we also can't merge two amaps, so if we
1421 		 * merged with the previous entry which has an amap,
1422 		 * and the next entry also has an amap, we give up.
1423 		 *
1424 		 * Interesting cases:
1425 		 * amap, new, amap -> give up second merge (single fwd extend)
1426 		 * amap, new, none -> double forward extend (extend again here)
1427 		 * none, new, amap -> double backward extend (done here)
1428 		 * uobj, new, amap -> single backward extend (done here)
1429 		 *
1430 		 * XXX should we attempt to deal with someone refilling
1431 		 * the deallocated region between two entries that are
1432 		 * backed by the same amap (ie, arefs is 2, "prev" and
1433 		 * "next" refer to it, and adding this allocation will
1434 		 * close the hole, thus restoring arefs to 1 and
1435 		 * deallocating the "next" vm_map_entry)?  -- @@@
1436 		 */
1437 
1438 		if (prev_entry->next->aref.ar_amap &&
1439 		    (amap_refs(prev_entry->next->aref.ar_amap) != 1 ||
1440 		     (merged && prev_entry->aref.ar_amap))) {
1441 			goto nomerge;
1442 		}
1443 
1444 		if (merged) {
1445 			/*
1446 			 * Try to extend the amap of the previous entry to
1447 			 * cover the next entry as well.  If it doesn't work
1448 			 * just skip on, don't actually give up, since we've
1449 			 * already completed the back merge.
1450 			 */
1451 			if (prev_entry->aref.ar_amap) {
1452 				if (amap_extend(prev_entry,
1453 				    prev_entry->next->end -
1454 				    prev_entry->next->start,
1455 				    amapwaitflag | AMAP_EXTEND_FORWARDS))
1456 					goto nomerge;
1457 			}
1458 
1459 			/*
1460 			 * Try to extend the amap of the *next* entry
1461 			 * back to cover the new allocation *and* the
1462 			 * previous entry as well (the previous merge
1463 			 * didn't have an amap already otherwise we
1464 			 * wouldn't be checking here for an amap).  If
1465 			 * it doesn't work just skip on, again, don't
1466 			 * actually give up, since we've already
1467 			 * completed the back merge.
1468 			 */
1469 			else if (prev_entry->next->aref.ar_amap) {
1470 				if (amap_extend(prev_entry->next,
1471 				    prev_entry->end -
1472 				    prev_entry->start,
1473 				    amapwaitflag | AMAP_EXTEND_BACKWARDS))
1474 					goto nomerge;
1475 			}
1476 		} else {
1477 			/*
1478 			 * Pull the next entry's amap backwards to cover this
1479 			 * new allocation.
1480 			 */
1481 			if (prev_entry->next->aref.ar_amap) {
1482 				error = amap_extend(prev_entry->next, size,
1483 				    amapwaitflag | AMAP_EXTEND_BACKWARDS);
1484 				if (error)
1485 					goto nomerge;
1486 			}
1487 		}
1488 
1489 		if (merged) {
1490 			if (kmap) {
1491 				UVMMAP_EVCNT_DECR(kbackmerge);
1492 				UVMMAP_EVCNT_INCR(kbimerge);
1493 			} else {
1494 				UVMMAP_EVCNT_DECR(ubackmerge);
1495 				UVMMAP_EVCNT_INCR(ubimerge);
1496 			}
1497 		} else {
1498 			if (kmap) {
1499 				UVMMAP_EVCNT_INCR(kforwmerge);
1500 			} else {
1501 				UVMMAP_EVCNT_INCR(uforwmerge);
1502 			}
1503 		}
1504 		UVMHIST_LOG(maphist,"  starting forward merge", 0, 0, 0, 0);
1505 
1506 		/*
1507 		 * drop our reference to uobj since we are extending a reference
1508 		 * that we already have (the ref count can not drop to zero).
1509 		 */
1510 		if (uobj && uobj->pgops->pgo_detach)
1511 			uobj->pgops->pgo_detach(uobj);
1512 
1513 		if (merged) {
1514 			dead = prev_entry->next;
1515 			prev_entry->end = dead->end;
1516 			uvm_map_entry_unlink(map, dead);
1517 			if (dead->aref.ar_amap != NULL) {
1518 				prev_entry->aref = dead->aref;
1519 				dead->aref.ar_amap = NULL;
1520 			}
1521 		} else {
1522 			prev_entry->next->start -= size;
1523 			if (prev_entry != &map->header) {
1524 				prev_entry->gap -= size;
1525 				KASSERT(prev_entry->gap == uvm_rb_gap(prev_entry));
1526 				uvm_rb_fixup(map, prev_entry);
1527 			}
1528 			if (uobj)
1529 				prev_entry->next->offset = uoffset;
1530 		}
1531 
1532 		uvm_map_check(map, "map forwardmerged");
1533 
1534 		UVMHIST_LOG(maphist,"<- done forwardmerge", 0, 0, 0, 0);
1535 		merged++;
1536 	}
1537 
1538 nomerge:
1539 	if (!merged) {
1540 		UVMHIST_LOG(maphist,"  allocating new map entry", 0, 0, 0, 0);
1541 		if (kmap) {
1542 			UVMMAP_EVCNT_INCR(knomerge);
1543 		} else {
1544 			UVMMAP_EVCNT_INCR(unomerge);
1545 		}
1546 
1547 		/*
1548 		 * allocate new entry and link it in.
1549 		 */
1550 
1551 		if (new_entry == NULL) {
1552 			new_entry = uvm_mapent_alloc(map,
1553 				(flags & UVM_FLAG_NOWAIT));
1554 			if (__predict_false(new_entry == NULL)) {
1555 				error = ENOMEM;
1556 				goto done;
1557 			}
1558 		}
1559 		new_entry->start = start;
1560 		new_entry->end = new_entry->start + size;
1561 		new_entry->object.uvm_obj = uobj;
1562 		new_entry->offset = uoffset;
1563 
1564 		new_entry->etype = newetype;
1565 
1566 		if (flags & UVM_FLAG_NOMERGE) {
1567 			new_entry->flags |= UVM_MAP_NOMERGE;
1568 		}
1569 
1570 		new_entry->protection = prot;
1571 		new_entry->max_protection = maxprot;
1572 		new_entry->inheritance = inherit;
1573 		new_entry->wired_count = 0;
1574 		new_entry->advice = advice;
1575 		if (flags & UVM_FLAG_OVERLAY) {
1576 
1577 			/*
1578 			 * to_add: for BSS we overallocate a little since we
1579 			 * are likely to extend
1580 			 */
1581 
1582 			vaddr_t to_add = (flags & UVM_FLAG_AMAPPAD) ?
1583 				UVM_AMAP_CHUNK << PAGE_SHIFT : 0;
1584 			struct vm_amap *amap = amap_alloc(size, to_add,
1585 			    (flags & UVM_FLAG_NOWAIT));
1586 			if (__predict_false(amap == NULL)) {
1587 				error = ENOMEM;
1588 				goto done;
1589 			}
1590 			new_entry->aref.ar_pageoff = 0;
1591 			new_entry->aref.ar_amap = amap;
1592 		} else {
1593 			new_entry->aref.ar_pageoff = 0;
1594 			new_entry->aref.ar_amap = NULL;
1595 		}
1596 		uvm_map_entry_link(map, prev_entry, new_entry);
1597 
1598 		/*
1599 		 * Update the free space hint
1600 		 */
1601 
1602 		if ((map->first_free == prev_entry) &&
1603 		    (prev_entry->end >= new_entry->start))
1604 			map->first_free = new_entry;
1605 
1606 		new_entry = NULL;
1607 	}
1608 
1609 	map->size += size;
1610 
1611 	UVMHIST_LOG(maphist,"<- done!", 0, 0, 0, 0);
1612 
1613 	error = 0;
1614 
1615 done:
1616 	vm_map_unlock(map);
1617 
1618 	if (new_entry) {
1619 		uvm_mapent_free(new_entry);
1620 	}
1621 	if (dead) {
1622 		KDASSERT(merged);
1623 		uvm_mapent_free(dead);
1624 	}
1625 	if (dead_entries)
1626 		uvm_unmap_detach(dead_entries, 0);
1627 
1628 	return error;
1629 }
1630 
1631 /*
1632  * uvm_map_lookup_entry_bytree: lookup an entry in tree
1633  */
1634 
1635 static inline bool
1636 uvm_map_lookup_entry_bytree(struct vm_map *map, vaddr_t address,
1637     struct vm_map_entry **entry	/* OUT */)
1638 {
1639 	struct vm_map_entry *prev = &map->header;
1640 	struct vm_map_entry *cur = ROOT_ENTRY(map);
1641 
1642 	while (cur) {
1643 		UVMMAP_EVCNT_INCR(mlk_treeloop);
1644 		if (address >= cur->start) {
1645 			if (address < cur->end) {
1646 				*entry = cur;
1647 				return true;
1648 			}
1649 			prev = cur;
1650 			cur = RIGHT_ENTRY(cur);
1651 		} else
1652 			cur = LEFT_ENTRY(cur);
1653 	}
1654 	*entry = prev;
1655 	return false;
1656 }
1657 
1658 /*
1659  * uvm_map_lookup_entry: find map entry at or before an address
1660  *
1661  * => map must at least be read-locked by caller
1662  * => entry is returned in "entry"
1663  * => return value is true if address is in the returned entry
1664  */
1665 
1666 bool
1667 uvm_map_lookup_entry(struct vm_map *map, vaddr_t address,
1668     struct vm_map_entry **entry	/* OUT */)
1669 {
1670 	struct vm_map_entry *cur;
1671 	UVMHIST_FUNC(__func__);
1672 	UVMHIST_CALLARGS(maphist,"(map=%#jx,addr=%#jx,ent=%#jx)",
1673 	    (uintptr_t)map, address, (uintptr_t)entry, 0);
1674 
1675 	/*
1676 	 * make a quick check to see if we are already looking at
1677 	 * the entry we want (which is usually the case).  note also
1678 	 * that we don't need to save the hint here...  it is the
1679 	 * same hint (unless we are at the header, in which case the
1680 	 * hint didn't buy us anything anyway).
1681 	 */
1682 
1683 	cur = map->hint;
1684 	UVMMAP_EVCNT_INCR(mlk_call);
1685 	if (cur != &map->header &&
1686 	    address >= cur->start && cur->end > address) {
1687 		UVMMAP_EVCNT_INCR(mlk_hint);
1688 		*entry = cur;
1689 		UVMHIST_LOG(maphist,"<- got it via hint (%#jx)",
1690 		    (uintptr_t)cur, 0, 0, 0);
1691 		uvm_mapent_check(*entry);
1692 		return (true);
1693 	}
1694 	uvm_map_check(map, __func__);
1695 
1696 	/*
1697 	 * lookup in the tree.
1698 	 */
1699 
1700 	UVMMAP_EVCNT_INCR(mlk_tree);
1701 	if (__predict_true(uvm_map_lookup_entry_bytree(map, address, entry))) {
1702 		SAVE_HINT(map, map->hint, *entry);
1703 		UVMHIST_LOG(maphist,"<- search got it (%#jx)",
1704 		    (uintptr_t)cur, 0, 0, 0);
1705 		KDASSERT((*entry)->start <= address);
1706 		KDASSERT(address < (*entry)->end);
1707 		uvm_mapent_check(*entry);
1708 		return (true);
1709 	}
1710 
1711 	SAVE_HINT(map, map->hint, *entry);
1712 	UVMHIST_LOG(maphist,"<- failed!",0,0,0,0);
1713 	KDASSERT((*entry) == &map->header || (*entry)->end <= address);
1714 	KDASSERT((*entry)->next == &map->header ||
1715 	    address < (*entry)->next->start);
1716 	return (false);
1717 }
1718 
1719 /*
1720  * See if the range between start and start + length fits in the gap
1721  * entry->next->start and entry->end.  Returns 1 if fits, 0 if doesn't
1722  * fit, and -1 address wraps around.
1723  */
1724 static int
1725 uvm_map_space_avail(vaddr_t *start, vsize_t length, voff_t uoffset,
1726     vsize_t align, int flags, int topdown, struct vm_map_entry *entry)
1727 {
1728 	vaddr_t end;
1729 
1730 #ifdef PMAP_PREFER
1731 	/*
1732 	 * push start address forward as needed to avoid VAC alias problems.
1733 	 * we only do this if a valid offset is specified.
1734 	 */
1735 
1736 	if (uoffset != UVM_UNKNOWN_OFFSET)
1737 		PMAP_PREFER(uoffset, start, length, topdown);
1738 #endif
1739 	if ((flags & UVM_FLAG_COLORMATCH) != 0) {
1740 		KASSERT(align < uvmexp.ncolors);
1741 		if (uvmexp.ncolors > 1) {
1742 			const u_int colormask = uvmexp.colormask;
1743 			const u_int colorsize = colormask + 1;
1744 			vaddr_t hint = atop(*start);
1745 			const u_int color = hint & colormask;
1746 			if (color != align) {
1747 				hint -= color;	/* adjust to color boundary */
1748 				KASSERT((hint & colormask) == 0);
1749 				if (topdown) {
1750 					if (align > color)
1751 						hint -= colorsize;
1752 				} else {
1753 					if (align < color)
1754 						hint += colorsize;
1755 				}
1756 				*start = ptoa(hint + align); /* adjust to color */
1757 			}
1758 		}
1759 	} else {
1760 		KASSERT(powerof2(align));
1761 		uvm_map_align_va(start, align, topdown);
1762 		/*
1763 		 * XXX Should we PMAP_PREFER() here again?
1764 		 * eh...i think we're okay
1765 		 */
1766 	}
1767 
1768 	/*
1769 	 * Find the end of the proposed new region.  Be sure we didn't
1770 	 * wrap around the address; if so, we lose.  Otherwise, if the
1771 	 * proposed new region fits before the next entry, we win.
1772 	 */
1773 
1774 	end = *start + length;
1775 	if (end < *start)
1776 		return (-1);
1777 
1778 	if (entry->next->start >= end && *start >= entry->end)
1779 		return (1);
1780 
1781 	return (0);
1782 }
1783 
1784 /*
1785  * uvm_map_findspace: find "length" sized space in "map".
1786  *
1787  * => "hint" is a hint about where we want it, unless UVM_FLAG_FIXED is
1788  *	set in "flags" (in which case we insist on using "hint").
1789  * => "result" is VA returned
1790  * => uobj/uoffset are to be used to handle VAC alignment, if required
1791  * => if "align" is non-zero, we attempt to align to that value.
1792  * => caller must at least have read-locked map
1793  * => returns NULL on failure, or pointer to prev. map entry if success
1794  * => note this is a cross between the old vm_map_findspace and vm_map_find
1795  */
1796 
1797 struct vm_map_entry *
1798 uvm_map_findspace(struct vm_map *map, vaddr_t hint, vsize_t length,
1799     vaddr_t *result /* OUT */, struct uvm_object *uobj, voff_t uoffset,
1800     vsize_t align, int flags)
1801 {
1802 	struct vm_map_entry *entry;
1803 	struct vm_map_entry *child, *prev, *tmp;
1804 	vaddr_t orig_hint __diagused;
1805 	const int topdown = map->flags & VM_MAP_TOPDOWN;
1806 	UVMHIST_FUNC(__func__);
1807 	UVMHIST_CALLARGS(maphist, "(map=%#jx, hint=%#jx, len=%ju, flags=%#jx)",
1808 	    (uintptr_t)map, hint, length, flags);
1809 
1810 	KASSERT((flags & UVM_FLAG_COLORMATCH) != 0 || powerof2(align));
1811 	KASSERT((flags & UVM_FLAG_COLORMATCH) == 0 || align < uvmexp.ncolors);
1812 	KASSERT((flags & UVM_FLAG_FIXED) == 0 || align == 0);
1813 
1814 	uvm_map_check(map, "map_findspace entry");
1815 
1816 	/*
1817 	 * remember the original hint.  if we are aligning, then we
1818 	 * may have to try again with no alignment constraint if
1819 	 * we fail the first time.
1820 	 */
1821 
1822 	orig_hint = hint;
1823 	if (hint < vm_map_min(map)) {	/* check ranges ... */
1824 		if (flags & UVM_FLAG_FIXED) {
1825 			UVMHIST_LOG(maphist,"<- VA below map range",0,0,0,0);
1826 			return (NULL);
1827 		}
1828 		hint = vm_map_min(map);
1829 	}
1830 	if (hint > vm_map_max(map)) {
1831 		UVMHIST_LOG(maphist,"<- VA %#jx > range [%#jx->%#jx]",
1832 		    hint, vm_map_min(map), vm_map_max(map), 0);
1833 		return (NULL);
1834 	}
1835 
1836 	/*
1837 	 * hint may not be aligned properly; we need round up or down it
1838 	 * before proceeding further.
1839 	 */
1840 	if ((flags & UVM_FLAG_COLORMATCH) == 0)
1841 		uvm_map_align_va(&hint, align, topdown);
1842 
1843 	/*
1844 	 * Look for the first possible address; if there's already
1845 	 * something at this address, we have to start after it.
1846 	 */
1847 
1848 	/*
1849 	 * @@@: there are four, no, eight cases to consider.
1850 	 *
1851 	 * 0: found,     fixed,     bottom up -> fail
1852 	 * 1: found,     fixed,     top down  -> fail
1853 	 * 2: found,     not fixed, bottom up -> start after entry->end,
1854 	 *                                       loop up
1855 	 * 3: found,     not fixed, top down  -> start before entry->start,
1856 	 *                                       loop down
1857 	 * 4: not found, fixed,     bottom up -> check entry->next->start, fail
1858 	 * 5: not found, fixed,     top down  -> check entry->next->start, fail
1859 	 * 6: not found, not fixed, bottom up -> check entry->next->start,
1860 	 *                                       loop up
1861 	 * 7: not found, not fixed, top down  -> check entry->next->start,
1862 	 *                                       loop down
1863 	 *
1864 	 * as you can see, it reduces to roughly five cases, and that
1865 	 * adding top down mapping only adds one unique case (without
1866 	 * it, there would be four cases).
1867 	 */
1868 
1869 	if ((flags & UVM_FLAG_FIXED) == 0 && hint == vm_map_min(map)) {
1870 		entry = map->first_free;
1871 	} else {
1872 		if (uvm_map_lookup_entry(map, hint, &entry)) {
1873 			/* "hint" address already in use ... */
1874 			if (flags & UVM_FLAG_FIXED) {
1875 				UVMHIST_LOG(maphist, "<- fixed & VA in use",
1876 				    0, 0, 0, 0);
1877 				return (NULL);
1878 			}
1879 			if (topdown)
1880 				/* Start from lower gap. */
1881 				entry = entry->prev;
1882 		} else if (flags & UVM_FLAG_FIXED) {
1883 			if (entry->next->start >= hint + length &&
1884 			    hint + length > hint)
1885 				goto found;
1886 
1887 			/* "hint" address is gap but too small */
1888 			UVMHIST_LOG(maphist, "<- fixed mapping failed",
1889 			    0, 0, 0, 0);
1890 			return (NULL); /* only one shot at it ... */
1891 		} else {
1892 			/*
1893 			 * See if given hint fits in this gap.
1894 			 */
1895 			switch (uvm_map_space_avail(&hint, length,
1896 			    uoffset, align, flags, topdown, entry)) {
1897 			case 1:
1898 				goto found;
1899 			case -1:
1900 				goto wraparound;
1901 			}
1902 
1903 			if (topdown) {
1904 				/*
1905 				 * Still there is a chance to fit
1906 				 * if hint > entry->end.
1907 				 */
1908 			} else {
1909 				/* Start from higher gap. */
1910 				entry = entry->next;
1911 				if (entry == &map->header)
1912 					goto notfound;
1913 				goto nextgap;
1914 			}
1915 		}
1916 	}
1917 
1918 	/*
1919 	 * Note that all UVM_FLAGS_FIXED case is already handled.
1920 	 */
1921 	KDASSERT((flags & UVM_FLAG_FIXED) == 0);
1922 
1923 	/* Try to find the space in the red-black tree */
1924 
1925 	/* Check slot before any entry */
1926 	hint = topdown ? entry->next->start - length : entry->end;
1927 	switch (uvm_map_space_avail(&hint, length, uoffset, align, flags,
1928 	    topdown, entry)) {
1929 	case 1:
1930 		goto found;
1931 	case -1:
1932 		goto wraparound;
1933 	}
1934 
1935 nextgap:
1936 	KDASSERT((flags & UVM_FLAG_FIXED) == 0);
1937 	/* If there is not enough space in the whole tree, we fail */
1938 	tmp = ROOT_ENTRY(map);
1939 	if (tmp == NULL || tmp->maxgap < length)
1940 		goto notfound;
1941 
1942 	prev = NULL; /* previous candidate */
1943 
1944 	/* Find an entry close to hint that has enough space */
1945 	for (; tmp;) {
1946 		KASSERT(tmp->next->start == tmp->end + tmp->gap);
1947 		if (topdown) {
1948 			if (tmp->next->start < hint + length &&
1949 			    (prev == NULL || tmp->end > prev->end)) {
1950 				if (tmp->gap >= length)
1951 					prev = tmp;
1952 				else if ((child = LEFT_ENTRY(tmp)) != NULL
1953 				    && child->maxgap >= length)
1954 					prev = tmp;
1955 			}
1956 		} else {
1957 			if (tmp->end >= hint &&
1958 			    (prev == NULL || tmp->end < prev->end)) {
1959 				if (tmp->gap >= length)
1960 					prev = tmp;
1961 				else if ((child = RIGHT_ENTRY(tmp)) != NULL
1962 				    && child->maxgap >= length)
1963 					prev = tmp;
1964 			}
1965 		}
1966 		if (tmp->next->start < hint + length)
1967 			child = RIGHT_ENTRY(tmp);
1968 		else if (tmp->end > hint)
1969 			child = LEFT_ENTRY(tmp);
1970 		else {
1971 			if (tmp->gap >= length)
1972 				break;
1973 			if (topdown)
1974 				child = LEFT_ENTRY(tmp);
1975 			else
1976 				child = RIGHT_ENTRY(tmp);
1977 		}
1978 		if (child == NULL || child->maxgap < length)
1979 			break;
1980 		tmp = child;
1981 	}
1982 
1983 	if (tmp != NULL && tmp->start < hint && hint < tmp->next->start) {
1984 		/*
1985 		 * Check if the entry that we found satifies the
1986 		 * space requirement
1987 		 */
1988 		if (topdown) {
1989 			if (hint > tmp->next->start - length)
1990 				hint = tmp->next->start - length;
1991 		} else {
1992 			if (hint < tmp->end)
1993 				hint = tmp->end;
1994 		}
1995 		switch (uvm_map_space_avail(&hint, length, uoffset, align,
1996 		    flags, topdown, tmp)) {
1997 		case 1:
1998 			entry = tmp;
1999 			goto found;
2000 		case -1:
2001 			goto wraparound;
2002 		}
2003 		if (tmp->gap >= length)
2004 			goto listsearch;
2005 	}
2006 	if (prev == NULL)
2007 		goto notfound;
2008 
2009 	if (topdown) {
2010 		KASSERT(orig_hint >= prev->next->start - length ||
2011 		    prev->next->start - length > prev->next->start);
2012 		hint = prev->next->start - length;
2013 	} else {
2014 		KASSERT(orig_hint <= prev->end);
2015 		hint = prev->end;
2016 	}
2017 	switch (uvm_map_space_avail(&hint, length, uoffset, align,
2018 	    flags, topdown, prev)) {
2019 	case 1:
2020 		entry = prev;
2021 		goto found;
2022 	case -1:
2023 		goto wraparound;
2024 	}
2025 	if (prev->gap >= length)
2026 		goto listsearch;
2027 
2028 	if (topdown)
2029 		tmp = LEFT_ENTRY(prev);
2030 	else
2031 		tmp = RIGHT_ENTRY(prev);
2032 	for (;;) {
2033 		KASSERT(tmp && tmp->maxgap >= length);
2034 		if (topdown)
2035 			child = RIGHT_ENTRY(tmp);
2036 		else
2037 			child = LEFT_ENTRY(tmp);
2038 		if (child && child->maxgap >= length) {
2039 			tmp = child;
2040 			continue;
2041 		}
2042 		if (tmp->gap >= length)
2043 			break;
2044 		if (topdown)
2045 			tmp = LEFT_ENTRY(tmp);
2046 		else
2047 			tmp = RIGHT_ENTRY(tmp);
2048 	}
2049 
2050 	if (topdown) {
2051 		KASSERT(orig_hint >= tmp->next->start - length ||
2052 		    tmp->next->start - length > tmp->next->start);
2053 		hint = tmp->next->start - length;
2054 	} else {
2055 		KASSERT(orig_hint <= tmp->end);
2056 		hint = tmp->end;
2057 	}
2058 	switch (uvm_map_space_avail(&hint, length, uoffset, align,
2059 	    flags, topdown, tmp)) {
2060 	case 1:
2061 		entry = tmp;
2062 		goto found;
2063 	case -1:
2064 		goto wraparound;
2065 	}
2066 
2067 	/*
2068 	 * The tree fails to find an entry because of offset or alignment
2069 	 * restrictions.  Search the list instead.
2070 	 */
2071  listsearch:
2072 	/*
2073 	 * Look through the rest of the map, trying to fit a new region in
2074 	 * the gap between existing regions, or after the very last region.
2075 	 * note: entry->end = base VA of current gap,
2076 	 *	 entry->next->start = VA of end of current gap
2077 	 */
2078 
2079 	for (;;) {
2080 		/* Update hint for current gap. */
2081 		hint = topdown ? entry->next->start - length : entry->end;
2082 
2083 		/* See if it fits. */
2084 		switch (uvm_map_space_avail(&hint, length, uoffset, align,
2085 		    flags, topdown, entry)) {
2086 		case 1:
2087 			goto found;
2088 		case -1:
2089 			goto wraparound;
2090 		}
2091 
2092 		/* Advance to next/previous gap */
2093 		if (topdown) {
2094 			if (entry == &map->header) {
2095 				UVMHIST_LOG(maphist, "<- failed (off start)",
2096 				    0,0,0,0);
2097 				goto notfound;
2098 			}
2099 			entry = entry->prev;
2100 		} else {
2101 			entry = entry->next;
2102 			if (entry == &map->header) {
2103 				UVMHIST_LOG(maphist, "<- failed (off end)",
2104 				    0,0,0,0);
2105 				goto notfound;
2106 			}
2107 		}
2108 	}
2109 
2110  found:
2111 	SAVE_HINT(map, map->hint, entry);
2112 	*result = hint;
2113 	UVMHIST_LOG(maphist,"<- got it!  (result=%#jx)", hint, 0,0,0);
2114 	KASSERTMSG( topdown || hint >= orig_hint, "hint: %#jx, orig_hint: %#jx",
2115 	    (uintmax_t)hint, (uintmax_t)orig_hint);
2116 	KASSERTMSG(!topdown || hint <= orig_hint, "hint: %#jx, orig_hint: %#jx",
2117 	    (uintmax_t)hint, (uintmax_t)orig_hint);
2118 	KASSERT(entry->end <= hint);
2119 	KASSERT(hint + length <= entry->next->start);
2120 	return (entry);
2121 
2122  wraparound:
2123 	UVMHIST_LOG(maphist, "<- failed (wrap around)", 0,0,0,0);
2124 
2125 	return (NULL);
2126 
2127  notfound:
2128 	UVMHIST_LOG(maphist, "<- failed (notfound)", 0,0,0,0);
2129 
2130 	return (NULL);
2131 }
2132 
2133 /*
2134  *   U N M A P   -   m a i n   h e l p e r   f u n c t i o n s
2135  */
2136 
2137 /*
2138  * uvm_unmap_remove: remove mappings from a vm_map (from "start" up to "stop")
2139  *
2140  * => caller must check alignment and size
2141  * => map must be locked by caller
2142  * => we return a list of map entries that we've remove from the map
2143  *    in "entry_list"
2144  */
2145 
2146 void
2147 uvm_unmap_remove(struct vm_map *map, vaddr_t start, vaddr_t end,
2148     struct vm_map_entry **entry_list /* OUT */, int flags)
2149 {
2150 	struct vm_map_entry *entry, *first_entry, *next;
2151 	vaddr_t len;
2152 	UVMHIST_FUNC(__func__);
2153 	UVMHIST_CALLARGS(maphist,"(map=%#jx, start=%#jx, end=%#jx)",
2154 	    (uintptr_t)map, start, end, 0);
2155 	VM_MAP_RANGE_CHECK(map, start, end);
2156 
2157 	uvm_map_check(map, "unmap_remove entry");
2158 
2159 	/*
2160 	 * find first entry
2161 	 */
2162 
2163 	if (uvm_map_lookup_entry(map, start, &first_entry) == true) {
2164 		/* clip and go... */
2165 		entry = first_entry;
2166 		UVM_MAP_CLIP_START(map, entry, start);
2167 		/* critical!  prevents stale hint */
2168 		SAVE_HINT(map, entry, entry->prev);
2169 	} else {
2170 		entry = first_entry->next;
2171 	}
2172 
2173 	/*
2174 	 * save the free space hint
2175 	 */
2176 
2177 	if (map->first_free != &map->header && map->first_free->start >= start)
2178 		map->first_free = entry->prev;
2179 
2180 	/*
2181 	 * note: we now re-use first_entry for a different task.  we remove
2182 	 * a number of map entries from the map and save them in a linked
2183 	 * list headed by "first_entry".  once we remove them from the map
2184 	 * the caller should unlock the map and drop the references to the
2185 	 * backing objects [c.f. uvm_unmap_detach].  the object is to
2186 	 * separate unmapping from reference dropping.  why?
2187 	 *   [1] the map has to be locked for unmapping
2188 	 *   [2] the map need not be locked for reference dropping
2189 	 *   [3] dropping references may trigger pager I/O, and if we hit
2190 	 *       a pager that does synchronous I/O we may have to wait for it.
2191 	 *   [4] we would like all waiting for I/O to occur with maps unlocked
2192 	 *       so that we don't block other threads.
2193 	 */
2194 
2195 	first_entry = NULL;
2196 	*entry_list = NULL;
2197 
2198 	/*
2199 	 * break up the area into map entry sized regions and unmap.  note
2200 	 * that all mappings have to be removed before we can even consider
2201 	 * dropping references to amaps or VM objects (otherwise we could end
2202 	 * up with a mapping to a page on the free list which would be very bad)
2203 	 */
2204 
2205 	while ((entry != &map->header) && (entry->start < end)) {
2206 		KASSERT((entry->flags & UVM_MAP_STATIC) == 0);
2207 
2208 		UVM_MAP_CLIP_END(map, entry, end);
2209 		next = entry->next;
2210 		len = entry->end - entry->start;
2211 
2212 		/*
2213 		 * unwire before removing addresses from the pmap; otherwise
2214 		 * unwiring will put the entries back into the pmap (XXX).
2215 		 */
2216 
2217 		if (VM_MAPENT_ISWIRED(entry)) {
2218 			uvm_map_entry_unwire(map, entry);
2219 		}
2220 		if (flags & UVM_FLAG_VAONLY) {
2221 
2222 			/* nothing */
2223 
2224 		} else if ((map->flags & VM_MAP_PAGEABLE) == 0) {
2225 
2226 			/*
2227 			 * if the map is non-pageable, any pages mapped there
2228 			 * must be wired and entered with pmap_kenter_pa(),
2229 			 * and we should free any such pages immediately.
2230 			 * this is mostly used for kmem_map.
2231 			 */
2232 			KASSERT(vm_map_pmap(map) == pmap_kernel());
2233 
2234 			uvm_km_pgremove_intrsafe(map, entry->start, entry->end);
2235 		} else if (UVM_ET_ISOBJ(entry) &&
2236 			   UVM_OBJ_IS_KERN_OBJECT(entry->object.uvm_obj)) {
2237 			panic("%s: kernel object %p %p\n",
2238 			    __func__, map, entry);
2239 		} else if (UVM_ET_ISOBJ(entry) || entry->aref.ar_amap) {
2240 			/*
2241 			 * remove mappings the standard way.  lock object
2242 			 * and/or amap to ensure vm_page state does not
2243 			 * change while in pmap_remove().
2244 			 */
2245 
2246 #ifdef __HAVE_UNLOCKED_PMAP /* XXX temporary */
2247 			uvm_map_lock_entry(entry, RW_WRITER);
2248 #else
2249 			uvm_map_lock_entry(entry, RW_READER);
2250 #endif
2251 			pmap_remove(map->pmap, entry->start, entry->end);
2252 
2253 			/*
2254 			 * note: if map is dying, leave pmap_update() for
2255 			 * later.  if the map is to be reused (exec) then
2256 			 * pmap_update() will be called.  if the map is
2257 			 * being disposed of (exit) then pmap_destroy()
2258 			 * will be called.
2259 			 */
2260 
2261 			if ((map->flags & VM_MAP_DYING) == 0) {
2262 				pmap_update(vm_map_pmap(map));
2263 			} else {
2264 				KASSERT(vm_map_pmap(map) != pmap_kernel());
2265 			}
2266 
2267 			uvm_map_unlock_entry(entry);
2268 		}
2269 
2270 #if defined(UVMDEBUG)
2271 		/*
2272 		 * check if there's remaining mapping,
2273 		 * which is a bug in caller.
2274 		 */
2275 
2276 		vaddr_t va;
2277 		for (va = entry->start; va < entry->end;
2278 		    va += PAGE_SIZE) {
2279 			if (pmap_extract(vm_map_pmap(map), va, NULL)) {
2280 				panic("%s: %#"PRIxVADDR" has mapping",
2281 				    __func__, va);
2282 			}
2283 		}
2284 
2285 		if (VM_MAP_IS_KERNEL(map) && (flags & UVM_FLAG_NOWAIT) == 0) {
2286 			uvm_km_check_empty(map, entry->start,
2287 			    entry->end);
2288 		}
2289 #endif /* defined(UVMDEBUG) */
2290 
2291 		/*
2292 		 * remove entry from map and put it on our list of entries
2293 		 * that we've nuked.  then go to next entry.
2294 		 */
2295 
2296 		UVMHIST_LOG(maphist, "  removed map entry %#jx",
2297 		    (uintptr_t)entry, 0, 0, 0);
2298 
2299 		/* critical!  prevents stale hint */
2300 		SAVE_HINT(map, entry, entry->prev);
2301 
2302 		uvm_map_entry_unlink(map, entry);
2303 		KASSERT(map->size >= len);
2304 		map->size -= len;
2305 		entry->prev = NULL;
2306 		entry->next = first_entry;
2307 		first_entry = entry;
2308 		entry = next;
2309 	}
2310 
2311 	uvm_map_check(map, "unmap_remove leave");
2312 
2313 	/*
2314 	 * now we've cleaned up the map and are ready for the caller to drop
2315 	 * references to the mapped objects.
2316 	 */
2317 
2318 	*entry_list = first_entry;
2319 	UVMHIST_LOG(maphist,"<- done!", 0, 0, 0, 0);
2320 
2321 	if (map->flags & VM_MAP_WANTVA) {
2322 		mutex_enter(&map->misc_lock);
2323 		map->flags &= ~VM_MAP_WANTVA;
2324 		cv_broadcast(&map->cv);
2325 		mutex_exit(&map->misc_lock);
2326 	}
2327 }
2328 
2329 /*
2330  * uvm_unmap_detach: drop references in a chain of map entries
2331  *
2332  * => we will free the map entries as we traverse the list.
2333  */
2334 
2335 void
2336 uvm_unmap_detach(struct vm_map_entry *first_entry, int flags)
2337 {
2338 	struct vm_map_entry *next_entry;
2339 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
2340 
2341 	while (first_entry) {
2342 		KASSERT(!VM_MAPENT_ISWIRED(first_entry));
2343 		UVMHIST_LOG(maphist,
2344 		    "  detach %#jx: amap=%#jx, obj=%#jx, submap?=%jd",
2345 		    (uintptr_t)first_entry,
2346 		    (uintptr_t)first_entry->aref.ar_amap,
2347 		    (uintptr_t)first_entry->object.uvm_obj,
2348 		    UVM_ET_ISSUBMAP(first_entry));
2349 
2350 		/*
2351 		 * drop reference to amap, if we've got one
2352 		 */
2353 
2354 		if (first_entry->aref.ar_amap)
2355 			uvm_map_unreference_amap(first_entry, flags);
2356 
2357 		/*
2358 		 * drop reference to our backing object, if we've got one
2359 		 */
2360 
2361 		KASSERT(!UVM_ET_ISSUBMAP(first_entry));
2362 		if (UVM_ET_ISOBJ(first_entry) &&
2363 		    first_entry->object.uvm_obj->pgops->pgo_detach) {
2364 			(*first_entry->object.uvm_obj->pgops->pgo_detach)
2365 				(first_entry->object.uvm_obj);
2366 		}
2367 		next_entry = first_entry->next;
2368 		uvm_mapent_free(first_entry);
2369 		first_entry = next_entry;
2370 	}
2371 	UVMHIST_LOG(maphist, "<- done", 0,0,0,0);
2372 }
2373 
2374 /*
2375  *   E X T R A C T I O N   F U N C T I O N S
2376  */
2377 
2378 /*
2379  * uvm_map_reserve: reserve space in a vm_map for future use.
2380  *
2381  * => we reserve space in a map by putting a dummy map entry in the
2382  *    map (dummy means obj=NULL, amap=NULL, prot=VM_PROT_NONE)
2383  * => map should be unlocked (we will write lock it)
2384  * => we return true if we were able to reserve space
2385  * => XXXCDC: should be inline?
2386  */
2387 
2388 int
2389 uvm_map_reserve(struct vm_map *map, vsize_t size,
2390     vaddr_t offset	/* hint for pmap_prefer */,
2391     vsize_t align	/* alignment */,
2392     vaddr_t *raddr	/* IN:hint, OUT: reserved VA */,
2393     uvm_flag_t flags	/* UVM_FLAG_FIXED or UVM_FLAG_COLORMATCH or 0 */)
2394 {
2395 	UVMHIST_FUNC(__func__);
2396 	UVMHIST_CALLARGS(maphist, "(map=%#jx, size=%#jx, offset=%#jx, addr=%#jx)",
2397 	    (uintptr_t)map, size, offset, (uintptr_t)raddr);
2398 
2399 	size = round_page(size);
2400 
2401 	/*
2402 	 * reserve some virtual space.
2403 	 */
2404 
2405 	if (uvm_map(map, raddr, size, NULL, offset, align,
2406 	    UVM_MAPFLAG(UVM_PROT_NONE, UVM_PROT_NONE, UVM_INH_NONE,
2407 	    UVM_ADV_RANDOM, UVM_FLAG_NOMERGE|flags)) != 0) {
2408 	    UVMHIST_LOG(maphist, "<- done (no VM)", 0,0,0,0);
2409 		return (false);
2410 	}
2411 
2412 	UVMHIST_LOG(maphist, "<- done (*raddr=%#jx)", *raddr,0,0,0);
2413 	return (true);
2414 }
2415 
2416 /*
2417  * uvm_map_replace: replace a reserved (blank) area of memory with
2418  * real mappings.
2419  *
2420  * => caller must WRITE-LOCK the map
2421  * => we return true if replacement was a success
2422  * => we expect the newents chain to have nnewents entrys on it and
2423  *    we expect newents->prev to point to the last entry on the list
2424  * => note newents is allowed to be NULL
2425  */
2426 
2427 static int
2428 uvm_map_replace(struct vm_map *map, vaddr_t start, vaddr_t end,
2429     struct vm_map_entry *newents, int nnewents, vsize_t nsize,
2430     struct vm_map_entry **oldentryp)
2431 {
2432 	struct vm_map_entry *oldent, *last;
2433 
2434 	uvm_map_check(map, "map_replace entry");
2435 
2436 	/*
2437 	 * first find the blank map entry at the specified address
2438 	 */
2439 
2440 	if (!uvm_map_lookup_entry(map, start, &oldent)) {
2441 		return (false);
2442 	}
2443 
2444 	/*
2445 	 * check to make sure we have a proper blank entry
2446 	 */
2447 
2448 	if (end < oldent->end) {
2449 		UVM_MAP_CLIP_END(map, oldent, end);
2450 	}
2451 	if (oldent->start != start || oldent->end != end ||
2452 	    oldent->object.uvm_obj != NULL || oldent->aref.ar_amap != NULL) {
2453 		return (false);
2454 	}
2455 
2456 #ifdef DIAGNOSTIC
2457 
2458 	/*
2459 	 * sanity check the newents chain
2460 	 */
2461 
2462 	{
2463 		struct vm_map_entry *tmpent = newents;
2464 		int nent = 0;
2465 		vsize_t sz = 0;
2466 		vaddr_t cur = start;
2467 
2468 		while (tmpent) {
2469 			nent++;
2470 			sz += tmpent->end - tmpent->start;
2471 			if (tmpent->start < cur)
2472 				panic("uvm_map_replace1");
2473 			if (tmpent->start >= tmpent->end || tmpent->end > end) {
2474 				panic("uvm_map_replace2: "
2475 				    "tmpent->start=%#"PRIxVADDR
2476 				    ", tmpent->end=%#"PRIxVADDR
2477 				    ", end=%#"PRIxVADDR,
2478 				    tmpent->start, tmpent->end, end);
2479 			}
2480 			cur = tmpent->end;
2481 			if (tmpent->next) {
2482 				if (tmpent->next->prev != tmpent)
2483 					panic("uvm_map_replace3");
2484 			} else {
2485 				if (newents->prev != tmpent)
2486 					panic("uvm_map_replace4");
2487 			}
2488 			tmpent = tmpent->next;
2489 		}
2490 		if (nent != nnewents)
2491 			panic("uvm_map_replace5");
2492 		if (sz != nsize)
2493 			panic("uvm_map_replace6");
2494 	}
2495 #endif
2496 
2497 	/*
2498 	 * map entry is a valid blank!   replace it.   (this does all the
2499 	 * work of map entry link/unlink...).
2500 	 */
2501 
2502 	if (newents) {
2503 		last = newents->prev;
2504 
2505 		/* critical: flush stale hints out of map */
2506 		SAVE_HINT(map, map->hint, newents);
2507 		if (map->first_free == oldent)
2508 			map->first_free = last;
2509 
2510 		last->next = oldent->next;
2511 		last->next->prev = last;
2512 
2513 		/* Fix RB tree */
2514 		uvm_rb_remove(map, oldent);
2515 
2516 		newents->prev = oldent->prev;
2517 		newents->prev->next = newents;
2518 		map->nentries = map->nentries + (nnewents - 1);
2519 
2520 		/* Fixup the RB tree */
2521 		{
2522 			int i;
2523 			struct vm_map_entry *tmp;
2524 
2525 			tmp = newents;
2526 			for (i = 0; i < nnewents && tmp; i++) {
2527 				uvm_rb_insert(map, tmp);
2528 				tmp = tmp->next;
2529 			}
2530 		}
2531 	} else {
2532 		/* NULL list of new entries: just remove the old one */
2533 		clear_hints(map, oldent);
2534 		uvm_map_entry_unlink(map, oldent);
2535 	}
2536 	map->size -= end - start - nsize;
2537 
2538 	uvm_map_check(map, "map_replace leave");
2539 
2540 	/*
2541 	 * now we can free the old blank entry and return.
2542 	 */
2543 
2544 	*oldentryp = oldent;
2545 	return (true);
2546 }
2547 
2548 /*
2549  * uvm_map_extract: extract a mapping from a map and put it somewhere
2550  *	(maybe removing the old mapping)
2551  *
2552  * => maps should be unlocked (we will write lock them)
2553  * => returns 0 on success, error code otherwise
2554  * => start must be page aligned
2555  * => len must be page sized
2556  * => flags:
2557  *      UVM_EXTRACT_REMOVE: remove mappings from srcmap
2558  *      UVM_EXTRACT_CONTIG: abort if unmapped area (advisory only)
2559  *      UVM_EXTRACT_QREF: for a temporary extraction do quick obj refs
2560  *      UVM_EXTRACT_FIXPROT: set prot to maxprot as we go
2561  *      UVM_EXTRACT_PROT_ALL: set prot to UVM_PROT_ALL as we go
2562  *    >>>NOTE: if you set REMOVE, you are not allowed to use CONTIG or QREF!<<<
2563  *    >>>NOTE: QREF's must be unmapped via the QREF path, thus should only
2564  *             be used from within the kernel in a kernel level map <<<
2565  */
2566 
2567 int
2568 uvm_map_extract(struct vm_map *srcmap, vaddr_t start, vsize_t len,
2569     struct vm_map *dstmap, vaddr_t *dstaddrp, int flags)
2570 {
2571 	vaddr_t dstaddr, end, newend, oldoffset, fudge, orig_fudge;
2572 	struct vm_map_entry *chain, *endchain, *entry, *orig_entry, *newentry,
2573 	    *deadentry, *oldentry;
2574 	struct vm_map_entry *resentry = NULL; /* a dummy reservation entry */
2575 	vsize_t elen __unused;
2576 	int nchain, error, copy_ok;
2577 	vsize_t nsize;
2578 	UVMHIST_FUNC(__func__);
2579 	UVMHIST_CALLARGS(maphist,"(srcmap=%#jx,start=%#jx, len=%#jx",
2580 	    (uintptr_t)srcmap, start, len, 0);
2581 	UVMHIST_LOG(maphist," ...,dstmap=%#jx, flags=%#jx)",
2582 	    (uintptr_t)dstmap, flags, 0, 0);
2583 
2584 	/*
2585 	 * step 0: sanity check: start must be on a page boundary, length
2586 	 * must be page sized.  can't ask for CONTIG/QREF if you asked for
2587 	 * REMOVE.
2588 	 */
2589 
2590 	KASSERT((start & PAGE_MASK) == 0 && (len & PAGE_MASK) == 0);
2591 	KASSERT((flags & UVM_EXTRACT_REMOVE) == 0 ||
2592 		(flags & (UVM_EXTRACT_CONTIG|UVM_EXTRACT_QREF)) == 0);
2593 
2594 	/*
2595 	 * step 1: reserve space in the target map for the extracted area
2596 	 */
2597 
2598 	if ((flags & UVM_EXTRACT_RESERVED) == 0) {
2599 		dstaddr = vm_map_min(dstmap);
2600 		if (!uvm_map_reserve(dstmap, len, start,
2601 		    atop(start) & uvmexp.colormask, &dstaddr,
2602 		    UVM_FLAG_COLORMATCH))
2603 			return (ENOMEM);
2604 		KASSERT((atop(start ^ dstaddr) & uvmexp.colormask) == 0);
2605 		*dstaddrp = dstaddr;	/* pass address back to caller */
2606 		UVMHIST_LOG(maphist, "  dstaddr=%#jx", dstaddr,0,0,0);
2607 	} else {
2608 		dstaddr = *dstaddrp;
2609 	}
2610 
2611 	/*
2612 	 * step 2: setup for the extraction process loop by init'ing the
2613 	 * map entry chain, locking src map, and looking up the first useful
2614 	 * entry in the map.
2615 	 */
2616 
2617 	end = start + len;
2618 	newend = dstaddr + len;
2619 	chain = endchain = NULL;
2620 	nchain = 0;
2621 	nsize = 0;
2622 	vm_map_lock(srcmap);
2623 
2624 	if (uvm_map_lookup_entry(srcmap, start, &entry)) {
2625 
2626 		/* "start" is within an entry */
2627 		if (flags & UVM_EXTRACT_QREF) {
2628 
2629 			/*
2630 			 * for quick references we don't clip the entry, so
2631 			 * the entry may map space "before" the starting
2632 			 * virtual address... this is the "fudge" factor
2633 			 * (which can be non-zero only the first time
2634 			 * through the "while" loop in step 3).
2635 			 */
2636 
2637 			fudge = start - entry->start;
2638 		} else {
2639 
2640 			/*
2641 			 * normal reference: we clip the map to fit (thus
2642 			 * fudge is zero)
2643 			 */
2644 
2645 			UVM_MAP_CLIP_START(srcmap, entry, start);
2646 			SAVE_HINT(srcmap, srcmap->hint, entry->prev);
2647 			fudge = 0;
2648 		}
2649 	} else {
2650 
2651 		/* "start" is not within an entry ... skip to next entry */
2652 		if (flags & UVM_EXTRACT_CONTIG) {
2653 			error = EINVAL;
2654 			goto bad;    /* definite hole here ... */
2655 		}
2656 
2657 		entry = entry->next;
2658 		fudge = 0;
2659 	}
2660 
2661 	/* save values from srcmap for step 6 */
2662 	orig_entry = entry;
2663 	orig_fudge = fudge;
2664 
2665 	/*
2666 	 * step 3: now start looping through the map entries, extracting
2667 	 * as we go.
2668 	 */
2669 
2670 	while (entry->start < end && entry != &srcmap->header) {
2671 
2672 		/* if we are not doing a quick reference, clip it */
2673 		if ((flags & UVM_EXTRACT_QREF) == 0)
2674 			UVM_MAP_CLIP_END(srcmap, entry, end);
2675 
2676 		/* clear needs_copy (allow chunking) */
2677 		if (UVM_ET_ISNEEDSCOPY(entry)) {
2678 			amap_copy(srcmap, entry,
2679 			    AMAP_COPY_NOWAIT|AMAP_COPY_NOMERGE, start, end);
2680 			if (UVM_ET_ISNEEDSCOPY(entry)) {  /* failed? */
2681 				error = ENOMEM;
2682 				goto bad;
2683 			}
2684 
2685 			/* amap_copy could clip (during chunk)!  update fudge */
2686 			if (fudge) {
2687 				fudge = start - entry->start;
2688 				orig_fudge = fudge;
2689 			}
2690 		}
2691 
2692 		/* calculate the offset of this from "start" */
2693 		oldoffset = (entry->start + fudge) - start;
2694 
2695 		/* allocate a new map entry */
2696 		newentry = uvm_mapent_alloc(dstmap, 0);
2697 		if (newentry == NULL) {
2698 			error = ENOMEM;
2699 			goto bad;
2700 		}
2701 
2702 		/* set up new map entry */
2703 		newentry->next = NULL;
2704 		newentry->prev = endchain;
2705 		newentry->start = dstaddr + oldoffset;
2706 		newentry->end =
2707 		    newentry->start + (entry->end - (entry->start + fudge));
2708 		if (newentry->end > newend || newentry->end < newentry->start)
2709 			newentry->end = newend;
2710 		newentry->object.uvm_obj = entry->object.uvm_obj;
2711 		if (newentry->object.uvm_obj) {
2712 			if (newentry->object.uvm_obj->pgops->pgo_reference)
2713 				newentry->object.uvm_obj->pgops->
2714 				    pgo_reference(newentry->object.uvm_obj);
2715 			newentry->offset = entry->offset + fudge;
2716 		} else {
2717 			newentry->offset = 0;
2718 		}
2719 		newentry->etype = entry->etype;
2720 		if (flags & UVM_EXTRACT_PROT_ALL) {
2721 			newentry->protection = newentry->max_protection =
2722 			    UVM_PROT_ALL;
2723 		} else {
2724 			newentry->protection = (flags & UVM_EXTRACT_FIXPROT) ?
2725 			    entry->max_protection : entry->protection;
2726 			newentry->max_protection = entry->max_protection;
2727 		}
2728 		newentry->inheritance = entry->inheritance;
2729 		newentry->wired_count = 0;
2730 		newentry->aref.ar_amap = entry->aref.ar_amap;
2731 		if (newentry->aref.ar_amap) {
2732 			newentry->aref.ar_pageoff =
2733 			    entry->aref.ar_pageoff + (fudge >> PAGE_SHIFT);
2734 			uvm_map_reference_amap(newentry, AMAP_SHARED |
2735 			    ((flags & UVM_EXTRACT_QREF) ? AMAP_REFALL : 0));
2736 		} else {
2737 			newentry->aref.ar_pageoff = 0;
2738 		}
2739 		newentry->advice = entry->advice;
2740 		if ((flags & UVM_EXTRACT_QREF) != 0) {
2741 			newentry->flags |= UVM_MAP_NOMERGE;
2742 		}
2743 
2744 		/* now link it on the chain */
2745 		nchain++;
2746 		nsize += newentry->end - newentry->start;
2747 		if (endchain == NULL) {
2748 			chain = endchain = newentry;
2749 		} else {
2750 			endchain->next = newentry;
2751 			endchain = newentry;
2752 		}
2753 
2754 		/* end of 'while' loop! */
2755 		if ((flags & UVM_EXTRACT_CONTIG) && entry->end < end &&
2756 		    (entry->next == &srcmap->header ||
2757 		    entry->next->start != entry->end)) {
2758 			error = EINVAL;
2759 			goto bad;
2760 		}
2761 		entry = entry->next;
2762 		fudge = 0;
2763 	}
2764 
2765 	/*
2766 	 * step 4: close off chain (in format expected by uvm_map_replace)
2767 	 */
2768 
2769 	if (chain)
2770 		chain->prev = endchain;
2771 
2772 	/*
2773 	 * step 5: attempt to lock the dest map so we can pmap_copy.
2774 	 * note usage of copy_ok:
2775 	 *   1 => dstmap locked, pmap_copy ok, and we "replace" here (step 5)
2776 	 *   0 => dstmap unlocked, NO pmap_copy, and we will "replace" in step 7
2777 	 */
2778 
2779 	if (srcmap == dstmap || vm_map_lock_try(dstmap) == true) {
2780 		copy_ok = 1;
2781 		if (!uvm_map_replace(dstmap, dstaddr, dstaddr+len, chain,
2782 		    nchain, nsize, &resentry)) {
2783 			if (srcmap != dstmap)
2784 				vm_map_unlock(dstmap);
2785 			error = EIO;
2786 			goto bad;
2787 		}
2788 	} else {
2789 		copy_ok = 0;
2790 		/* replace defered until step 7 */
2791 	}
2792 
2793 	/*
2794 	 * step 6: traverse the srcmap a second time to do the following:
2795 	 *  - if we got a lock on the dstmap do pmap_copy
2796 	 *  - if UVM_EXTRACT_REMOVE remove the entries
2797 	 * we make use of orig_entry and orig_fudge (saved in step 2)
2798 	 */
2799 
2800 	if (copy_ok || (flags & UVM_EXTRACT_REMOVE)) {
2801 
2802 		/* purge possible stale hints from srcmap */
2803 		if (flags & UVM_EXTRACT_REMOVE) {
2804 			SAVE_HINT(srcmap, srcmap->hint, orig_entry->prev);
2805 			if (srcmap->first_free != &srcmap->header &&
2806 			    srcmap->first_free->start >= start)
2807 				srcmap->first_free = orig_entry->prev;
2808 		}
2809 
2810 		entry = orig_entry;
2811 		fudge = orig_fudge;
2812 		deadentry = NULL;	/* for UVM_EXTRACT_REMOVE */
2813 
2814 		while (entry->start < end && entry != &srcmap->header) {
2815 			if (copy_ok) {
2816 				oldoffset = (entry->start + fudge) - start;
2817 				elen = MIN(end, entry->end) -
2818 				    (entry->start + fudge);
2819 				pmap_copy(dstmap->pmap, srcmap->pmap,
2820 				    dstaddr + oldoffset, elen,
2821 				    entry->start + fudge);
2822 			}
2823 
2824 			/* we advance "entry" in the following if statement */
2825 			if (flags & UVM_EXTRACT_REMOVE) {
2826 #ifdef __HAVE_UNLOCKED_PMAP /* XXX temporary */
2827 				uvm_map_lock_entry(entry, RW_WRITER);
2828 #else
2829 				uvm_map_lock_entry(entry, RW_READER);
2830 #endif
2831 				pmap_remove(srcmap->pmap, entry->start,
2832 						entry->end);
2833 				uvm_map_unlock_entry(entry);
2834 				oldentry = entry;	/* save entry */
2835 				entry = entry->next;	/* advance */
2836 				uvm_map_entry_unlink(srcmap, oldentry);
2837 							/* add to dead list */
2838 				oldentry->next = deadentry;
2839 				deadentry = oldentry;
2840 			} else {
2841 				entry = entry->next;		/* advance */
2842 			}
2843 
2844 			/* end of 'while' loop */
2845 			fudge = 0;
2846 		}
2847 		pmap_update(srcmap->pmap);
2848 
2849 		/*
2850 		 * unlock dstmap.  we will dispose of deadentry in
2851 		 * step 7 if needed
2852 		 */
2853 
2854 		if (copy_ok && srcmap != dstmap)
2855 			vm_map_unlock(dstmap);
2856 
2857 	} else {
2858 		deadentry = NULL;
2859 	}
2860 
2861 	/*
2862 	 * step 7: we are done with the source map, unlock.   if copy_ok
2863 	 * is 0 then we have not replaced the dummy mapping in dstmap yet
2864 	 * and we need to do so now.
2865 	 */
2866 
2867 	vm_map_unlock(srcmap);
2868 	if ((flags & UVM_EXTRACT_REMOVE) && deadentry)
2869 		uvm_unmap_detach(deadentry, 0);   /* dispose of old entries */
2870 
2871 	/* now do the replacement if we didn't do it in step 5 */
2872 	if (copy_ok == 0) {
2873 		vm_map_lock(dstmap);
2874 		error = uvm_map_replace(dstmap, dstaddr, dstaddr+len, chain,
2875 		    nchain, nsize, &resentry);
2876 		vm_map_unlock(dstmap);
2877 
2878 		if (error == false) {
2879 			error = EIO;
2880 			goto bad2;
2881 		}
2882 	}
2883 
2884 	if (resentry != NULL)
2885 		uvm_mapent_free(resentry);
2886 
2887 	return (0);
2888 
2889 	/*
2890 	 * bad: failure recovery
2891 	 */
2892 bad:
2893 	vm_map_unlock(srcmap);
2894 bad2:			/* src already unlocked */
2895 	if (chain)
2896 		uvm_unmap_detach(chain,
2897 		    (flags & UVM_EXTRACT_QREF) ? AMAP_REFALL : 0);
2898 
2899 	if (resentry != NULL)
2900 		uvm_mapent_free(resentry);
2901 
2902 	if ((flags & UVM_EXTRACT_RESERVED) == 0) {
2903 		uvm_unmap(dstmap, dstaddr, dstaddr+len);   /* ??? */
2904 	}
2905 	return (error);
2906 }
2907 
2908 /* end of extraction functions */
2909 
2910 /*
2911  * uvm_map_submap: punch down part of a map into a submap
2912  *
2913  * => only the kernel_map is allowed to be submapped
2914  * => the purpose of submapping is to break up the locking granularity
2915  *	of a larger map
2916  * => the range specified must have been mapped previously with a uvm_map()
2917  *	call [with uobj==NULL] to create a blank map entry in the main map.
2918  *	[And it had better still be blank!]
2919  * => maps which contain submaps should never be copied or forked.
2920  * => to remove a submap, use uvm_unmap() on the main map
2921  *	and then uvm_map_deallocate() the submap.
2922  * => main map must be unlocked.
2923  * => submap must have been init'd and have a zero reference count.
2924  *	[need not be locked as we don't actually reference it]
2925  */
2926 
2927 int
2928 uvm_map_submap(struct vm_map *map, vaddr_t start, vaddr_t end,
2929     struct vm_map *submap)
2930 {
2931 	struct vm_map_entry *entry;
2932 	int error;
2933 
2934 	vm_map_lock(map);
2935 	VM_MAP_RANGE_CHECK(map, start, end);
2936 
2937 	if (uvm_map_lookup_entry(map, start, &entry)) {
2938 		UVM_MAP_CLIP_START(map, entry, start);
2939 		UVM_MAP_CLIP_END(map, entry, end);	/* to be safe */
2940 	} else {
2941 		entry = NULL;
2942 	}
2943 
2944 	if (entry != NULL &&
2945 	    entry->start == start && entry->end == end &&
2946 	    entry->object.uvm_obj == NULL && entry->aref.ar_amap == NULL &&
2947 	    !UVM_ET_ISCOPYONWRITE(entry) && !UVM_ET_ISNEEDSCOPY(entry)) {
2948 		entry->etype |= UVM_ET_SUBMAP;
2949 		entry->object.sub_map = submap;
2950 		entry->offset = 0;
2951 		uvm_map_reference(submap);
2952 		error = 0;
2953 	} else {
2954 		error = EINVAL;
2955 	}
2956 	vm_map_unlock(map);
2957 
2958 	return error;
2959 }
2960 
2961 /*
2962  * uvm_map_protect_user: change map protection on behalf of the user.
2963  * Enforces PAX settings as necessary.
2964  */
2965 int
2966 uvm_map_protect_user(struct lwp *l, vaddr_t start, vaddr_t end,
2967     vm_prot_t new_prot)
2968 {
2969 	int error;
2970 
2971 	if ((error = PAX_MPROTECT_VALIDATE(l, new_prot)))
2972 		return error;
2973 
2974 	return uvm_map_protect(&l->l_proc->p_vmspace->vm_map, start, end,
2975 	    new_prot, false);
2976 }
2977 
2978 
2979 /*
2980  * uvm_map_protect: change map protection
2981  *
2982  * => set_max means set max_protection.
2983  * => map must be unlocked.
2984  */
2985 
2986 #define MASK(entry)	(UVM_ET_ISCOPYONWRITE(entry) ? \
2987 			 ~VM_PROT_WRITE : VM_PROT_ALL)
2988 
2989 int
2990 uvm_map_protect(struct vm_map *map, vaddr_t start, vaddr_t end,
2991     vm_prot_t new_prot, bool set_max)
2992 {
2993 	struct vm_map_entry *current, *entry;
2994 	int error = 0;
2995 	UVMHIST_FUNC(__func__);
2996 	UVMHIST_CALLARGS(maphist,"(map=%#jx,start=%#jx,end=%#jx,new_prot=%#jx)",
2997 	    (uintptr_t)map, start, end, new_prot);
2998 
2999 	vm_map_lock(map);
3000 	VM_MAP_RANGE_CHECK(map, start, end);
3001 	if (uvm_map_lookup_entry(map, start, &entry)) {
3002 		UVM_MAP_CLIP_START(map, entry, start);
3003 	} else {
3004 		entry = entry->next;
3005 	}
3006 
3007 	/*
3008 	 * make a first pass to check for protection violations.
3009 	 */
3010 
3011 	current = entry;
3012 	while ((current != &map->header) && (current->start < end)) {
3013 		if (UVM_ET_ISSUBMAP(current)) {
3014 			error = EINVAL;
3015 			goto out;
3016 		}
3017 		if ((new_prot & current->max_protection) != new_prot) {
3018 			error = EACCES;
3019 			goto out;
3020 		}
3021 		/*
3022 		 * Don't allow VM_PROT_EXECUTE to be set on entries that
3023 		 * point to vnodes that are associated with a NOEXEC file
3024 		 * system.
3025 		 */
3026 		if (UVM_ET_ISOBJ(current) &&
3027 		    UVM_OBJ_IS_VNODE(current->object.uvm_obj)) {
3028 			struct vnode *vp =
3029 			    (struct vnode *) current->object.uvm_obj;
3030 
3031 			if ((new_prot & VM_PROT_EXECUTE) != 0 &&
3032 			    (vp->v_mount->mnt_flag & MNT_NOEXEC) != 0) {
3033 				error = EACCES;
3034 				goto out;
3035 			}
3036 		}
3037 
3038 		current = current->next;
3039 	}
3040 
3041 	/* go back and fix up protections (no need to clip this time). */
3042 
3043 	current = entry;
3044 	while ((current != &map->header) && (current->start < end)) {
3045 		vm_prot_t old_prot;
3046 
3047 		UVM_MAP_CLIP_END(map, current, end);
3048 		old_prot = current->protection;
3049 		if (set_max)
3050 			current->protection =
3051 			    (current->max_protection = new_prot) & old_prot;
3052 		else
3053 			current->protection = new_prot;
3054 
3055 		/*
3056 		 * update physical map if necessary.  worry about copy-on-write
3057 		 * here -- CHECK THIS XXX
3058 		 */
3059 
3060 		if (current->protection != old_prot) {
3061 			/* update pmap! */
3062 #ifdef __HAVE_UNLOCKED_PMAP /* XXX temporary */
3063 			uvm_map_lock_entry(current, RW_WRITER);
3064 #else
3065 			uvm_map_lock_entry(current, RW_READER);
3066 #endif
3067 			pmap_protect(map->pmap, current->start, current->end,
3068 			    current->protection & MASK(current));
3069 			uvm_map_unlock_entry(current);
3070 
3071 			/*
3072 			 * If this entry points at a vnode, and the
3073 			 * protection includes VM_PROT_EXECUTE, mark
3074 			 * the vnode as VEXECMAP.
3075 			 */
3076 			if (UVM_ET_ISOBJ(current)) {
3077 				struct uvm_object *uobj =
3078 				    current->object.uvm_obj;
3079 
3080 				if (UVM_OBJ_IS_VNODE(uobj) &&
3081 				    (current->protection & VM_PROT_EXECUTE)) {
3082 					vn_markexec((struct vnode *) uobj);
3083 				}
3084 			}
3085 		}
3086 
3087 		/*
3088 		 * If the map is configured to lock any future mappings,
3089 		 * wire this entry now if the old protection was VM_PROT_NONE
3090 		 * and the new protection is not VM_PROT_NONE.
3091 		 */
3092 
3093 		if ((map->flags & VM_MAP_WIREFUTURE) != 0 &&
3094 		    VM_MAPENT_ISWIRED(current) == 0 &&
3095 		    old_prot == VM_PROT_NONE &&
3096 		    new_prot != VM_PROT_NONE) {
3097 
3098 			/*
3099 			 * We must call pmap_update() here because the
3100 			 * pmap_protect() call above might have removed some
3101 			 * pmap entries and uvm_map_pageable() might create
3102 			 * some new pmap entries that rely on the prior
3103 			 * removals being completely finished.
3104 			 */
3105 
3106 			pmap_update(map->pmap);
3107 
3108 			if (uvm_map_pageable(map, current->start,
3109 			    current->end, false,
3110 			    UVM_LK_ENTER|UVM_LK_EXIT) != 0) {
3111 
3112 				/*
3113 				 * If locking the entry fails, remember the
3114 				 * error if it's the first one.  Note we
3115 				 * still continue setting the protection in
3116 				 * the map, but will return the error
3117 				 * condition regardless.
3118 				 *
3119 				 * XXX Ignore what the actual error is,
3120 				 * XXX just call it a resource shortage
3121 				 * XXX so that it doesn't get confused
3122 				 * XXX what uvm_map_protect() itself would
3123 				 * XXX normally return.
3124 				 */
3125 
3126 				error = ENOMEM;
3127 			}
3128 		}
3129 		current = current->next;
3130 	}
3131 	pmap_update(map->pmap);
3132 
3133  out:
3134 	vm_map_unlock(map);
3135 
3136 	UVMHIST_LOG(maphist, "<- done, error=%jd",error,0,0,0);
3137 	return error;
3138 }
3139 
3140 #undef  MASK
3141 
3142 /*
3143  * uvm_map_inherit: set inheritance code for range of addrs in map.
3144  *
3145  * => map must be unlocked
3146  * => note that the inherit code is used during a "fork".  see fork
3147  *	code for details.
3148  */
3149 
3150 int
3151 uvm_map_inherit(struct vm_map *map, vaddr_t start, vaddr_t end,
3152     vm_inherit_t new_inheritance)
3153 {
3154 	struct vm_map_entry *entry, *temp_entry;
3155 	UVMHIST_FUNC(__func__);
3156 	UVMHIST_CALLARGS(maphist,"(map=%#jx,start=%#jx,end=%#jx,new_inh=%#jx)",
3157 	    (uintptr_t)map, start, end, new_inheritance);
3158 
3159 	switch (new_inheritance) {
3160 	case MAP_INHERIT_NONE:
3161 	case MAP_INHERIT_COPY:
3162 	case MAP_INHERIT_SHARE:
3163 	case MAP_INHERIT_ZERO:
3164 		break;
3165 	default:
3166 		UVMHIST_LOG(maphist,"<- done (INVALID ARG)",0,0,0,0);
3167 		return EINVAL;
3168 	}
3169 
3170 	vm_map_lock(map);
3171 	VM_MAP_RANGE_CHECK(map, start, end);
3172 	if (uvm_map_lookup_entry(map, start, &temp_entry)) {
3173 		entry = temp_entry;
3174 		UVM_MAP_CLIP_START(map, entry, start);
3175 	}  else {
3176 		entry = temp_entry->next;
3177 	}
3178 	while ((entry != &map->header) && (entry->start < end)) {
3179 		UVM_MAP_CLIP_END(map, entry, end);
3180 		entry->inheritance = new_inheritance;
3181 		entry = entry->next;
3182 	}
3183 	vm_map_unlock(map);
3184 	UVMHIST_LOG(maphist,"<- done (OK)",0,0,0,0);
3185 	return 0;
3186 }
3187 
3188 /*
3189  * uvm_map_advice: set advice code for range of addrs in map.
3190  *
3191  * => map must be unlocked
3192  */
3193 
3194 int
3195 uvm_map_advice(struct vm_map *map, vaddr_t start, vaddr_t end, int new_advice)
3196 {
3197 	struct vm_map_entry *entry, *temp_entry;
3198 	UVMHIST_FUNC(__func__);
3199 	UVMHIST_CALLARGS(maphist,"(map=%#jx,start=%#jx,end=%#jx,new_adv=%#jx)",
3200 	    (uintptr_t)map, start, end, new_advice);
3201 
3202 	vm_map_lock(map);
3203 	VM_MAP_RANGE_CHECK(map, start, end);
3204 	if (uvm_map_lookup_entry(map, start, &temp_entry)) {
3205 		entry = temp_entry;
3206 		UVM_MAP_CLIP_START(map, entry, start);
3207 	} else {
3208 		entry = temp_entry->next;
3209 	}
3210 
3211 	/*
3212 	 * XXXJRT: disallow holes?
3213 	 */
3214 
3215 	while ((entry != &map->header) && (entry->start < end)) {
3216 		UVM_MAP_CLIP_END(map, entry, end);
3217 
3218 		switch (new_advice) {
3219 		case MADV_NORMAL:
3220 		case MADV_RANDOM:
3221 		case MADV_SEQUENTIAL:
3222 			/* nothing special here */
3223 			break;
3224 
3225 		default:
3226 			vm_map_unlock(map);
3227 			UVMHIST_LOG(maphist,"<- done (INVALID ARG)",0,0,0,0);
3228 			return EINVAL;
3229 		}
3230 		entry->advice = new_advice;
3231 		entry = entry->next;
3232 	}
3233 
3234 	vm_map_unlock(map);
3235 	UVMHIST_LOG(maphist,"<- done (OK)",0,0,0,0);
3236 	return 0;
3237 }
3238 
3239 /*
3240  * uvm_map_willneed: apply MADV_WILLNEED
3241  */
3242 
3243 int
3244 uvm_map_willneed(struct vm_map *map, vaddr_t start, vaddr_t end)
3245 {
3246 	struct vm_map_entry *entry;
3247 	UVMHIST_FUNC(__func__);
3248 	UVMHIST_CALLARGS(maphist,"(map=%#jx,start=%#jx,end=%#jx)",
3249 	    (uintptr_t)map, start, end, 0);
3250 
3251 	vm_map_lock_read(map);
3252 	VM_MAP_RANGE_CHECK(map, start, end);
3253 	if (!uvm_map_lookup_entry(map, start, &entry)) {
3254 		entry = entry->next;
3255 	}
3256 	while (entry->start < end) {
3257 		struct vm_amap * const amap = entry->aref.ar_amap;
3258 		struct uvm_object * const uobj = entry->object.uvm_obj;
3259 
3260 		KASSERT(entry != &map->header);
3261 		KASSERT(start < entry->end);
3262 		/*
3263 		 * For now, we handle only the easy but commonly-requested case.
3264 		 * ie. start prefetching of backing uobj pages.
3265 		 *
3266 		 * XXX It might be useful to pmap_enter() the already-in-core
3267 		 * pages by inventing a "weak" mode for uvm_fault() which would
3268 		 * only do the PGO_LOCKED pgo_get().
3269 		 */
3270 		if (UVM_ET_ISOBJ(entry) && amap == NULL && uobj != NULL) {
3271 			off_t offset;
3272 			off_t size;
3273 
3274 			offset = entry->offset;
3275 			if (start < entry->start) {
3276 				offset += entry->start - start;
3277 			}
3278 			size = entry->offset + (entry->end - entry->start);
3279 			if (entry->end < end) {
3280 				size -= end - entry->end;
3281 			}
3282 			uvm_readahead(uobj, offset, size);
3283 		}
3284 		entry = entry->next;
3285 	}
3286 	vm_map_unlock_read(map);
3287 	UVMHIST_LOG(maphist,"<- done (OK)",0,0,0,0);
3288 	return 0;
3289 }
3290 
3291 /*
3292  * uvm_map_pageable: sets the pageability of a range in a map.
3293  *
3294  * => wires map entries.  should not be used for transient page locking.
3295  *	for that, use uvm_fault_wire()/uvm_fault_unwire() (see uvm_vslock()).
3296  * => regions specified as not pageable require lock-down (wired) memory
3297  *	and page tables.
3298  * => map must never be read-locked
3299  * => if islocked is true, map is already write-locked
3300  * => we always unlock the map, since we must downgrade to a read-lock
3301  *	to call uvm_fault_wire()
3302  * => XXXCDC: check this and try and clean it up.
3303  */
3304 
3305 int
3306 uvm_map_pageable(struct vm_map *map, vaddr_t start, vaddr_t end,
3307     bool new_pageable, int lockflags)
3308 {
3309 	struct vm_map_entry *entry, *start_entry, *failed_entry;
3310 	int rv;
3311 #ifdef DIAGNOSTIC
3312 	u_int timestamp_save;
3313 #endif
3314 	UVMHIST_FUNC(__func__);
3315 	UVMHIST_CALLARGS(maphist,"(map=%#jx,start=%#jx,end=%#jx,new_pageable=%ju)",
3316 	    (uintptr_t)map, start, end, new_pageable);
3317 	KASSERT(map->flags & VM_MAP_PAGEABLE);
3318 
3319 	if ((lockflags & UVM_LK_ENTER) == 0)
3320 		vm_map_lock(map);
3321 	VM_MAP_RANGE_CHECK(map, start, end);
3322 
3323 	/*
3324 	 * only one pageability change may take place at one time, since
3325 	 * uvm_fault_wire assumes it will be called only once for each
3326 	 * wiring/unwiring.  therefore, we have to make sure we're actually
3327 	 * changing the pageability for the entire region.  we do so before
3328 	 * making any changes.
3329 	 */
3330 
3331 	if (uvm_map_lookup_entry(map, start, &start_entry) == false) {
3332 		if ((lockflags & UVM_LK_EXIT) == 0)
3333 			vm_map_unlock(map);
3334 
3335 		UVMHIST_LOG(maphist,"<- done (fault)",0,0,0,0);
3336 		return EFAULT;
3337 	}
3338 	entry = start_entry;
3339 
3340 	if (start == end) {		/* nothing required */
3341 		if ((lockflags & UVM_LK_EXIT) == 0)
3342 			vm_map_unlock(map);
3343 
3344 		UVMHIST_LOG(maphist,"<- done (nothing)",0,0,0,0);
3345 		return 0;
3346 	}
3347 
3348 	/*
3349 	 * handle wiring and unwiring separately.
3350 	 */
3351 
3352 	if (new_pageable) {		/* unwire */
3353 		UVM_MAP_CLIP_START(map, entry, start);
3354 
3355 		/*
3356 		 * unwiring.  first ensure that the range to be unwired is
3357 		 * really wired down and that there are no holes.
3358 		 */
3359 
3360 		while ((entry != &map->header) && (entry->start < end)) {
3361 			if (entry->wired_count == 0 ||
3362 			    (entry->end < end &&
3363 			     (entry->next == &map->header ||
3364 			      entry->next->start > entry->end))) {
3365 				if ((lockflags & UVM_LK_EXIT) == 0)
3366 					vm_map_unlock(map);
3367 				UVMHIST_LOG(maphist, "<- done (INVAL)",0,0,0,0);
3368 				return EINVAL;
3369 			}
3370 			entry = entry->next;
3371 		}
3372 
3373 		/*
3374 		 * POSIX 1003.1b - a single munlock call unlocks a region,
3375 		 * regardless of the number of mlock calls made on that
3376 		 * region.
3377 		 */
3378 
3379 		entry = start_entry;
3380 		while ((entry != &map->header) && (entry->start < end)) {
3381 			UVM_MAP_CLIP_END(map, entry, end);
3382 			if (VM_MAPENT_ISWIRED(entry))
3383 				uvm_map_entry_unwire(map, entry);
3384 			entry = entry->next;
3385 		}
3386 		if ((lockflags & UVM_LK_EXIT) == 0)
3387 			vm_map_unlock(map);
3388 		UVMHIST_LOG(maphist,"<- done (OK UNWIRE)",0,0,0,0);
3389 		return 0;
3390 	}
3391 
3392 	/*
3393 	 * wire case: in two passes [XXXCDC: ugly block of code here]
3394 	 *
3395 	 * 1: holding the write lock, we create any anonymous maps that need
3396 	 *    to be created.  then we clip each map entry to the region to
3397 	 *    be wired and increment its wiring count.
3398 	 *
3399 	 * 2: we downgrade to a read lock, and call uvm_fault_wire to fault
3400 	 *    in the pages for any newly wired area (wired_count == 1).
3401 	 *
3402 	 *    downgrading to a read lock for uvm_fault_wire avoids a possible
3403 	 *    deadlock with another thread that may have faulted on one of
3404 	 *    the pages to be wired (it would mark the page busy, blocking
3405 	 *    us, then in turn block on the map lock that we hold).  because
3406 	 *    of problems in the recursive lock package, we cannot upgrade
3407 	 *    to a write lock in vm_map_lookup.  thus, any actions that
3408 	 *    require the write lock must be done beforehand.  because we
3409 	 *    keep the read lock on the map, the copy-on-write status of the
3410 	 *    entries we modify here cannot change.
3411 	 */
3412 
3413 	while ((entry != &map->header) && (entry->start < end)) {
3414 		if (VM_MAPENT_ISWIRED(entry) == 0) { /* not already wired? */
3415 
3416 			/*
3417 			 * perform actions of vm_map_lookup that need the
3418 			 * write lock on the map: create an anonymous map
3419 			 * for a copy-on-write region, or an anonymous map
3420 			 * for a zero-fill region.  (XXXCDC: submap case
3421 			 * ok?)
3422 			 */
3423 
3424 			if (!UVM_ET_ISSUBMAP(entry)) {  /* not submap */
3425 				if (UVM_ET_ISNEEDSCOPY(entry) &&
3426 				    ((entry->max_protection & VM_PROT_WRITE) ||
3427 				     (entry->object.uvm_obj == NULL))) {
3428 					amap_copy(map, entry, 0, start, end);
3429 					/* XXXCDC: wait OK? */
3430 				}
3431 			}
3432 		}
3433 		UVM_MAP_CLIP_START(map, entry, start);
3434 		UVM_MAP_CLIP_END(map, entry, end);
3435 		entry->wired_count++;
3436 
3437 		/*
3438 		 * Check for holes
3439 		 */
3440 
3441 		if (entry->protection == VM_PROT_NONE ||
3442 		    (entry->end < end &&
3443 		     (entry->next == &map->header ||
3444 		      entry->next->start > entry->end))) {
3445 
3446 			/*
3447 			 * found one.  amap creation actions do not need to
3448 			 * be undone, but the wired counts need to be restored.
3449 			 */
3450 
3451 			while (entry != &map->header && entry->end > start) {
3452 				entry->wired_count--;
3453 				entry = entry->prev;
3454 			}
3455 			if ((lockflags & UVM_LK_EXIT) == 0)
3456 				vm_map_unlock(map);
3457 			UVMHIST_LOG(maphist,"<- done (INVALID WIRE)",0,0,0,0);
3458 			return EINVAL;
3459 		}
3460 		entry = entry->next;
3461 	}
3462 
3463 	/*
3464 	 * Pass 2.
3465 	 */
3466 
3467 #ifdef DIAGNOSTIC
3468 	timestamp_save = map->timestamp;
3469 #endif
3470 	vm_map_busy(map);
3471 	vm_map_unlock(map);
3472 
3473 	rv = 0;
3474 	entry = start_entry;
3475 	while (entry != &map->header && entry->start < end) {
3476 		if (entry->wired_count == 1) {
3477 			rv = uvm_fault_wire(map, entry->start, entry->end,
3478 			    entry->max_protection, 1);
3479 			if (rv) {
3480 
3481 				/*
3482 				 * wiring failed.  break out of the loop.
3483 				 * we'll clean up the map below, once we
3484 				 * have a write lock again.
3485 				 */
3486 
3487 				break;
3488 			}
3489 		}
3490 		entry = entry->next;
3491 	}
3492 
3493 	if (rv) {	/* failed? */
3494 
3495 		/*
3496 		 * Get back to an exclusive (write) lock.
3497 		 */
3498 
3499 		vm_map_lock(map);
3500 		vm_map_unbusy(map);
3501 
3502 #ifdef DIAGNOSTIC
3503 		if (timestamp_save + 1 != map->timestamp)
3504 			panic("uvm_map_pageable: stale map");
3505 #endif
3506 
3507 		/*
3508 		 * first drop the wiring count on all the entries
3509 		 * which haven't actually been wired yet.
3510 		 */
3511 
3512 		failed_entry = entry;
3513 		while (entry != &map->header && entry->start < end) {
3514 			entry->wired_count--;
3515 			entry = entry->next;
3516 		}
3517 
3518 		/*
3519 		 * now, unwire all the entries that were successfully
3520 		 * wired above.
3521 		 */
3522 
3523 		entry = start_entry;
3524 		while (entry != failed_entry) {
3525 			entry->wired_count--;
3526 			if (VM_MAPENT_ISWIRED(entry) == 0)
3527 				uvm_map_entry_unwire(map, entry);
3528 			entry = entry->next;
3529 		}
3530 		if ((lockflags & UVM_LK_EXIT) == 0)
3531 			vm_map_unlock(map);
3532 		UVMHIST_LOG(maphist, "<- done (RV=%jd)", rv,0,0,0);
3533 		return (rv);
3534 	}
3535 
3536 	if ((lockflags & UVM_LK_EXIT) == 0) {
3537 		vm_map_unbusy(map);
3538 	} else {
3539 
3540 		/*
3541 		 * Get back to an exclusive (write) lock.
3542 		 */
3543 
3544 		vm_map_lock(map);
3545 		vm_map_unbusy(map);
3546 	}
3547 
3548 	UVMHIST_LOG(maphist,"<- done (OK WIRE)",0,0,0,0);
3549 	return 0;
3550 }
3551 
3552 /*
3553  * uvm_map_pageable_all: special case of uvm_map_pageable - affects
3554  * all mapped regions.
3555  *
3556  * => map must not be locked.
3557  * => if no flags are specified, all regions are unwired.
3558  * => XXXJRT: has some of the same problems as uvm_map_pageable() above.
3559  */
3560 
3561 int
3562 uvm_map_pageable_all(struct vm_map *map, int flags, vsize_t limit)
3563 {
3564 	struct vm_map_entry *entry, *failed_entry;
3565 	vsize_t size;
3566 	int rv;
3567 #ifdef DIAGNOSTIC
3568 	u_int timestamp_save;
3569 #endif
3570 	UVMHIST_FUNC(__func__);
3571 	UVMHIST_CALLARGS(maphist,"(map=%#jx,flags=%#jx)", (uintptr_t)map, flags,
3572 	    0, 0);
3573 
3574 	KASSERT(map->flags & VM_MAP_PAGEABLE);
3575 
3576 	vm_map_lock(map);
3577 
3578 	/*
3579 	 * handle wiring and unwiring separately.
3580 	 */
3581 
3582 	if (flags == 0) {			/* unwire */
3583 
3584 		/*
3585 		 * POSIX 1003.1b -- munlockall unlocks all regions,
3586 		 * regardless of how many times mlockall has been called.
3587 		 */
3588 
3589 		for (entry = map->header.next; entry != &map->header;
3590 		     entry = entry->next) {
3591 			if (VM_MAPENT_ISWIRED(entry))
3592 				uvm_map_entry_unwire(map, entry);
3593 		}
3594 		map->flags &= ~VM_MAP_WIREFUTURE;
3595 		vm_map_unlock(map);
3596 		UVMHIST_LOG(maphist,"<- done (OK UNWIRE)",0,0,0,0);
3597 		return 0;
3598 	}
3599 
3600 	if (flags & MCL_FUTURE) {
3601 
3602 		/*
3603 		 * must wire all future mappings; remember this.
3604 		 */
3605 
3606 		map->flags |= VM_MAP_WIREFUTURE;
3607 	}
3608 
3609 	if ((flags & MCL_CURRENT) == 0) {
3610 
3611 		/*
3612 		 * no more work to do!
3613 		 */
3614 
3615 		UVMHIST_LOG(maphist,"<- done (OK no wire)",0,0,0,0);
3616 		vm_map_unlock(map);
3617 		return 0;
3618 	}
3619 
3620 	/*
3621 	 * wire case: in three passes [XXXCDC: ugly block of code here]
3622 	 *
3623 	 * 1: holding the write lock, count all pages mapped by non-wired
3624 	 *    entries.  if this would cause us to go over our limit, we fail.
3625 	 *
3626 	 * 2: still holding the write lock, we create any anonymous maps that
3627 	 *    need to be created.  then we increment its wiring count.
3628 	 *
3629 	 * 3: we downgrade to a read lock, and call uvm_fault_wire to fault
3630 	 *    in the pages for any newly wired area (wired_count == 1).
3631 	 *
3632 	 *    downgrading to a read lock for uvm_fault_wire avoids a possible
3633 	 *    deadlock with another thread that may have faulted on one of
3634 	 *    the pages to be wired (it would mark the page busy, blocking
3635 	 *    us, then in turn block on the map lock that we hold).  because
3636 	 *    of problems in the recursive lock package, we cannot upgrade
3637 	 *    to a write lock in vm_map_lookup.  thus, any actions that
3638 	 *    require the write lock must be done beforehand.  because we
3639 	 *    keep the read lock on the map, the copy-on-write status of the
3640 	 *    entries we modify here cannot change.
3641 	 */
3642 
3643 	for (size = 0, entry = map->header.next; entry != &map->header;
3644 	     entry = entry->next) {
3645 		if (entry->protection != VM_PROT_NONE &&
3646 		    VM_MAPENT_ISWIRED(entry) == 0) { /* not already wired? */
3647 			size += entry->end - entry->start;
3648 		}
3649 	}
3650 
3651 	if (atop(size) + uvmexp.wired > uvmexp.wiredmax) {
3652 		vm_map_unlock(map);
3653 		return ENOMEM;
3654 	}
3655 
3656 	if (limit != 0 &&
3657 	    (size + ptoa(pmap_wired_count(vm_map_pmap(map))) > limit)) {
3658 		vm_map_unlock(map);
3659 		return ENOMEM;
3660 	}
3661 
3662 	/*
3663 	 * Pass 2.
3664 	 */
3665 
3666 	for (entry = map->header.next; entry != &map->header;
3667 	     entry = entry->next) {
3668 		if (entry->protection == VM_PROT_NONE)
3669 			continue;
3670 		if (VM_MAPENT_ISWIRED(entry) == 0) { /* not already wired? */
3671 
3672 			/*
3673 			 * perform actions of vm_map_lookup that need the
3674 			 * write lock on the map: create an anonymous map
3675 			 * for a copy-on-write region, or an anonymous map
3676 			 * for a zero-fill region.  (XXXCDC: submap case
3677 			 * ok?)
3678 			 */
3679 
3680 			if (!UVM_ET_ISSUBMAP(entry)) {	/* not submap */
3681 				if (UVM_ET_ISNEEDSCOPY(entry) &&
3682 				    ((entry->max_protection & VM_PROT_WRITE) ||
3683 				     (entry->object.uvm_obj == NULL))) {
3684 					amap_copy(map, entry, 0, entry->start,
3685 					    entry->end);
3686 					/* XXXCDC: wait OK? */
3687 				}
3688 			}
3689 		}
3690 		entry->wired_count++;
3691 	}
3692 
3693 	/*
3694 	 * Pass 3.
3695 	 */
3696 
3697 #ifdef DIAGNOSTIC
3698 	timestamp_save = map->timestamp;
3699 #endif
3700 	vm_map_busy(map);
3701 	vm_map_unlock(map);
3702 
3703 	rv = 0;
3704 	for (entry = map->header.next; entry != &map->header;
3705 	     entry = entry->next) {
3706 		if (entry->wired_count == 1) {
3707 			rv = uvm_fault_wire(map, entry->start, entry->end,
3708 			    entry->max_protection, 1);
3709 			if (rv) {
3710 
3711 				/*
3712 				 * wiring failed.  break out of the loop.
3713 				 * we'll clean up the map below, once we
3714 				 * have a write lock again.
3715 				 */
3716 
3717 				break;
3718 			}
3719 		}
3720 	}
3721 
3722 	if (rv) {
3723 
3724 		/*
3725 		 * Get back an exclusive (write) lock.
3726 		 */
3727 
3728 		vm_map_lock(map);
3729 		vm_map_unbusy(map);
3730 
3731 #ifdef DIAGNOSTIC
3732 		if (timestamp_save + 1 != map->timestamp)
3733 			panic("uvm_map_pageable_all: stale map");
3734 #endif
3735 
3736 		/*
3737 		 * first drop the wiring count on all the entries
3738 		 * which haven't actually been wired yet.
3739 		 *
3740 		 * Skip VM_PROT_NONE entries like we did above.
3741 		 */
3742 
3743 		failed_entry = entry;
3744 		for (/* nothing */; entry != &map->header;
3745 		     entry = entry->next) {
3746 			if (entry->protection == VM_PROT_NONE)
3747 				continue;
3748 			entry->wired_count--;
3749 		}
3750 
3751 		/*
3752 		 * now, unwire all the entries that were successfully
3753 		 * wired above.
3754 		 *
3755 		 * Skip VM_PROT_NONE entries like we did above.
3756 		 */
3757 
3758 		for (entry = map->header.next; entry != failed_entry;
3759 		     entry = entry->next) {
3760 			if (entry->protection == VM_PROT_NONE)
3761 				continue;
3762 			entry->wired_count--;
3763 			if (VM_MAPENT_ISWIRED(entry))
3764 				uvm_map_entry_unwire(map, entry);
3765 		}
3766 		vm_map_unlock(map);
3767 		UVMHIST_LOG(maphist,"<- done (RV=%jd)", rv,0,0,0);
3768 		return (rv);
3769 	}
3770 
3771 	vm_map_unbusy(map);
3772 
3773 	UVMHIST_LOG(maphist,"<- done (OK WIRE)",0,0,0,0);
3774 	return 0;
3775 }
3776 
3777 /*
3778  * uvm_map_clean: clean out a map range
3779  *
3780  * => valid flags:
3781  *   if (flags & PGO_CLEANIT): dirty pages are cleaned first
3782  *   if (flags & PGO_SYNCIO): dirty pages are written synchronously
3783  *   if (flags & PGO_DEACTIVATE): any cached pages are deactivated after clean
3784  *   if (flags & PGO_FREE): any cached pages are freed after clean
3785  * => returns an error if any part of the specified range isn't mapped
3786  * => never a need to flush amap layer since the anonymous memory has
3787  *	no permanent home, but may deactivate pages there
3788  * => called from sys_msync() and sys_madvise()
3789  * => caller must not write-lock map (read OK).
3790  * => we may sleep while cleaning if SYNCIO [with map read-locked]
3791  */
3792 
3793 int
3794 uvm_map_clean(struct vm_map *map, vaddr_t start, vaddr_t end, int flags)
3795 {
3796 	struct vm_map_entry *current, *entry;
3797 	struct uvm_object *uobj;
3798 	struct vm_amap *amap;
3799 	struct vm_anon *anon;
3800 	struct vm_page *pg;
3801 	vaddr_t offset;
3802 	vsize_t size;
3803 	voff_t uoff;
3804 	int error, refs;
3805 	UVMHIST_FUNC(__func__);
3806 	UVMHIST_CALLARGS(maphist,"(map=%#jx,start=%#jx,end=%#jx,flags=%#jx)",
3807 	    (uintptr_t)map, start, end, flags);
3808 
3809 	KASSERT((flags & (PGO_FREE|PGO_DEACTIVATE)) !=
3810 		(PGO_FREE|PGO_DEACTIVATE));
3811 
3812 	vm_map_lock_read(map);
3813 	VM_MAP_RANGE_CHECK(map, start, end);
3814 	if (uvm_map_lookup_entry(map, start, &entry) == false) {
3815 		vm_map_unlock_read(map);
3816 		return EFAULT;
3817 	}
3818 
3819 	/*
3820 	 * Make a first pass to check for holes and wiring problems.
3821 	 */
3822 
3823 	for (current = entry; current->start < end; current = current->next) {
3824 		if (UVM_ET_ISSUBMAP(current)) {
3825 			vm_map_unlock_read(map);
3826 			return EINVAL;
3827 		}
3828 		if ((flags & PGO_FREE) != 0 && VM_MAPENT_ISWIRED(entry)) {
3829 			vm_map_unlock_read(map);
3830 			return EBUSY;
3831 		}
3832 		if (end <= current->end) {
3833 			break;
3834 		}
3835 		if (current->end != current->next->start) {
3836 			vm_map_unlock_read(map);
3837 			return EFAULT;
3838 		}
3839 	}
3840 
3841 	error = 0;
3842 	for (current = entry; start < end; current = current->next) {
3843 		amap = current->aref.ar_amap;	/* upper layer */
3844 		uobj = current->object.uvm_obj;	/* lower layer */
3845 		KASSERT(start >= current->start);
3846 
3847 		/*
3848 		 * No amap cleaning necessary if:
3849 		 *
3850 		 *	(1) There's no amap.
3851 		 *
3852 		 *	(2) We're not deactivating or freeing pages.
3853 		 */
3854 
3855 		if (amap == NULL || (flags & (PGO_DEACTIVATE|PGO_FREE)) == 0)
3856 			goto flush_object;
3857 
3858 		offset = start - current->start;
3859 		size = MIN(end, current->end) - start;
3860 
3861 		amap_lock(amap, RW_WRITER);
3862 		for ( ; size != 0; size -= PAGE_SIZE, offset += PAGE_SIZE) {
3863 			anon = amap_lookup(&current->aref, offset);
3864 			if (anon == NULL)
3865 				continue;
3866 
3867 			KASSERT(anon->an_lock == amap->am_lock);
3868 			pg = anon->an_page;
3869 			if (pg == NULL) {
3870 				continue;
3871 			}
3872 			if (pg->flags & PG_BUSY) {
3873 				continue;
3874 			}
3875 
3876 			switch (flags & (PGO_CLEANIT|PGO_FREE|PGO_DEACTIVATE)) {
3877 
3878 			/*
3879 			 * In these first 3 cases, we just deactivate the page.
3880 			 */
3881 
3882 			case PGO_CLEANIT|PGO_FREE:
3883 			case PGO_CLEANIT|PGO_DEACTIVATE:
3884 			case PGO_DEACTIVATE:
3885  deactivate_it:
3886 				/*
3887 				 * skip the page if it's loaned or wired,
3888 				 * since it shouldn't be on a paging queue
3889 				 * at all in these cases.
3890 				 */
3891 
3892 				if (pg->loan_count != 0 ||
3893 				    pg->wire_count != 0) {
3894 					continue;
3895 				}
3896 				KASSERT(pg->uanon == anon);
3897 				uvm_pagelock(pg);
3898 				uvm_pagedeactivate(pg);
3899 				uvm_pageunlock(pg);
3900 				continue;
3901 
3902 			case PGO_FREE:
3903 
3904 				/*
3905 				 * If there are multiple references to
3906 				 * the amap, just deactivate the page.
3907 				 */
3908 
3909 				if (amap_refs(amap) > 1)
3910 					goto deactivate_it;
3911 
3912 				/* skip the page if it's wired */
3913 				if (pg->wire_count != 0) {
3914 					continue;
3915 				}
3916 				amap_unadd(&current->aref, offset);
3917 				refs = --anon->an_ref;
3918 				if (refs == 0) {
3919 					uvm_anfree(anon);
3920 				}
3921 				continue;
3922 			}
3923 		}
3924 		amap_unlock(amap);
3925 
3926  flush_object:
3927 		/*
3928 		 * flush pages if we've got a valid backing object.
3929 		 * note that we must always clean object pages before
3930 		 * freeing them since otherwise we could reveal stale
3931 		 * data from files.
3932 		 */
3933 
3934 		uoff = current->offset + (start - current->start);
3935 		size = MIN(end, current->end) - start;
3936 		if (uobj != NULL) {
3937 			rw_enter(uobj->vmobjlock, RW_WRITER);
3938 			if (uobj->pgops->pgo_put != NULL)
3939 				error = (uobj->pgops->pgo_put)(uobj, uoff,
3940 				    uoff + size, flags | PGO_CLEANIT);
3941 			else
3942 				error = 0;
3943 		}
3944 		start += size;
3945 	}
3946 	vm_map_unlock_read(map);
3947 	return (error);
3948 }
3949 
3950 
3951 /*
3952  * uvm_map_checkprot: check protection in map
3953  *
3954  * => must allow specified protection in a fully allocated region.
3955  * => map must be read or write locked by caller.
3956  */
3957 
3958 bool
3959 uvm_map_checkprot(struct vm_map *map, vaddr_t start, vaddr_t end,
3960     vm_prot_t protection)
3961 {
3962 	struct vm_map_entry *entry;
3963 	struct vm_map_entry *tmp_entry;
3964 
3965 	if (!uvm_map_lookup_entry(map, start, &tmp_entry)) {
3966 		return (false);
3967 	}
3968 	entry = tmp_entry;
3969 	while (start < end) {
3970 		if (entry == &map->header) {
3971 			return (false);
3972 		}
3973 
3974 		/*
3975 		 * no holes allowed
3976 		 */
3977 
3978 		if (start < entry->start) {
3979 			return (false);
3980 		}
3981 
3982 		/*
3983 		 * check protection associated with entry
3984 		 */
3985 
3986 		if ((entry->protection & protection) != protection) {
3987 			return (false);
3988 		}
3989 		start = entry->end;
3990 		entry = entry->next;
3991 	}
3992 	return (true);
3993 }
3994 
3995 /*
3996  * uvmspace_alloc: allocate a vmspace structure.
3997  *
3998  * - structure includes vm_map and pmap
3999  * - XXX: no locking on this structure
4000  * - refcnt set to 1, rest must be init'd by caller
4001  */
4002 struct vmspace *
4003 uvmspace_alloc(vaddr_t vmin, vaddr_t vmax, bool topdown)
4004 {
4005 	struct vmspace *vm;
4006 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
4007 
4008 	vm = pool_cache_get(&uvm_vmspace_cache, PR_WAITOK);
4009 	uvmspace_init(vm, NULL, vmin, vmax, topdown);
4010 	UVMHIST_LOG(maphist,"<- done (vm=%#jx)", (uintptr_t)vm, 0, 0, 0);
4011 	return (vm);
4012 }
4013 
4014 /*
4015  * uvmspace_init: initialize a vmspace structure.
4016  *
4017  * - XXX: no locking on this structure
4018  * - refcnt set to 1, rest must be init'd by caller
4019  */
4020 void
4021 uvmspace_init(struct vmspace *vm, struct pmap *pmap, vaddr_t vmin,
4022     vaddr_t vmax, bool topdown)
4023 {
4024 	UVMHIST_FUNC(__func__);
4025 	UVMHIST_CALLARGS(maphist, "(vm=%#jx, pmap=%#jx, vmin=%#jx, vmax=%#jx",
4026 	    (uintptr_t)vm, (uintptr_t)pmap, vmin, vmax);
4027 	UVMHIST_LOG(maphist, "   topdown=%ju)", topdown, 0, 0, 0);
4028 
4029 	memset(vm, 0, sizeof(*vm));
4030 	uvm_map_setup(&vm->vm_map, vmin, vmax, VM_MAP_PAGEABLE
4031 	    | (topdown ? VM_MAP_TOPDOWN : 0)
4032 	    );
4033 	if (pmap)
4034 		pmap_reference(pmap);
4035 	else
4036 		pmap = pmap_create();
4037 	vm->vm_map.pmap = pmap;
4038 	vm->vm_refcnt = 1;
4039 	UVMHIST_LOG(maphist,"<- done",0,0,0,0);
4040 }
4041 
4042 /*
4043  * uvmspace_share: share a vmspace between two processes
4044  *
4045  * - used for vfork, threads(?)
4046  */
4047 
4048 void
4049 uvmspace_share(struct proc *p1, struct proc *p2)
4050 {
4051 
4052 	uvmspace_addref(p1->p_vmspace);
4053 	p2->p_vmspace = p1->p_vmspace;
4054 }
4055 
4056 #if 0
4057 
4058 /*
4059  * uvmspace_unshare: ensure that process "p" has its own, unshared, vmspace
4060  *
4061  * - XXX: no locking on vmspace
4062  */
4063 
4064 void
4065 uvmspace_unshare(struct lwp *l)
4066 {
4067 	struct proc *p = l->l_proc;
4068 	struct vmspace *nvm, *ovm = p->p_vmspace;
4069 
4070 	if (ovm->vm_refcnt == 1)
4071 		/* nothing to do: vmspace isn't shared in the first place */
4072 		return;
4073 
4074 	/* make a new vmspace, still holding old one */
4075 	nvm = uvmspace_fork(ovm);
4076 
4077 	kpreempt_disable();
4078 	pmap_deactivate(l);		/* unbind old vmspace */
4079 	p->p_vmspace = nvm;
4080 	pmap_activate(l);		/* switch to new vmspace */
4081 	kpreempt_enable();
4082 
4083 	uvmspace_free(ovm);		/* drop reference to old vmspace */
4084 }
4085 
4086 #endif
4087 
4088 
4089 /*
4090  * uvmspace_spawn: a new process has been spawned and needs a vmspace
4091  */
4092 
4093 void
4094 uvmspace_spawn(struct lwp *l, vaddr_t start, vaddr_t end, bool topdown)
4095 {
4096 	struct proc *p = l->l_proc;
4097 	struct vmspace *nvm;
4098 
4099 #ifdef __HAVE_CPU_VMSPACE_EXEC
4100 	cpu_vmspace_exec(l, start, end);
4101 #endif
4102 
4103 	nvm = uvmspace_alloc(start, end, topdown);
4104 	kpreempt_disable();
4105 	p->p_vmspace = nvm;
4106 	pmap_activate(l);
4107 	kpreempt_enable();
4108 }
4109 
4110 /*
4111  * uvmspace_exec: the process wants to exec a new program
4112  */
4113 
4114 void
4115 uvmspace_exec(struct lwp *l, vaddr_t start, vaddr_t end, bool topdown)
4116 {
4117 	struct proc *p = l->l_proc;
4118 	struct vmspace *nvm, *ovm = p->p_vmspace;
4119 	struct vm_map *map;
4120 	int flags;
4121 
4122 	KASSERT(ovm != NULL);
4123 #ifdef __HAVE_CPU_VMSPACE_EXEC
4124 	cpu_vmspace_exec(l, start, end);
4125 #endif
4126 
4127 	map = &ovm->vm_map;
4128 	/*
4129 	 * see if more than one process is using this vmspace...
4130 	 */
4131 
4132 	if (ovm->vm_refcnt == 1
4133 	    && topdown == ((ovm->vm_map.flags & VM_MAP_TOPDOWN) != 0)) {
4134 
4135 		/*
4136 		 * if p is the only process using its vmspace then we can safely
4137 		 * recycle that vmspace for the program that is being exec'd.
4138 		 * But only if TOPDOWN matches the requested value for the new
4139 		 * vm space!
4140 		 */
4141 
4142 		/*
4143 		 * SYSV SHM semantics require us to kill all segments on an exec
4144 		 */
4145 		if (uvm_shmexit && ovm->vm_shm)
4146 			(*uvm_shmexit)(ovm);
4147 
4148 		/*
4149 		 * POSIX 1003.1b -- "lock future mappings" is revoked
4150 		 * when a process execs another program image.
4151 		 */
4152 
4153 		map->flags &= ~VM_MAP_WIREFUTURE;
4154 
4155 		/*
4156 		 * now unmap the old program.
4157 		 *
4158 		 * XXX set VM_MAP_DYING for the duration, so pmap_update()
4159 		 * is not called until the pmap has been totally cleared out
4160 		 * after pmap_remove_all(), or it can confuse some pmap
4161 		 * implementations.  it would be nice to handle this by
4162 		 * deferring the pmap_update() while it is known the address
4163 		 * space is not visible to any user LWP other than curlwp,
4164 		 * but there isn't an elegant way of inferring that right
4165 		 * now.
4166 		 */
4167 
4168 		flags = pmap_remove_all(map->pmap) ? UVM_FLAG_VAONLY : 0;
4169 		map->flags |= VM_MAP_DYING;
4170 		uvm_unmap1(map, vm_map_min(map), vm_map_max(map), flags);
4171 		map->flags &= ~VM_MAP_DYING;
4172 		pmap_update(map->pmap);
4173 		KASSERT(map->header.prev == &map->header);
4174 		KASSERT(map->nentries == 0);
4175 
4176 		/*
4177 		 * resize the map
4178 		 */
4179 
4180 		vm_map_setmin(map, start);
4181 		vm_map_setmax(map, end);
4182 	} else {
4183 
4184 		/*
4185 		 * p's vmspace is being shared, so we can't reuse it for p since
4186 		 * it is still being used for others.   allocate a new vmspace
4187 		 * for p
4188 		 */
4189 
4190 		nvm = uvmspace_alloc(start, end, topdown);
4191 
4192 		/*
4193 		 * install new vmspace and drop our ref to the old one.
4194 		 */
4195 
4196 		kpreempt_disable();
4197 		pmap_deactivate(l);
4198 		p->p_vmspace = nvm;
4199 		pmap_activate(l);
4200 		kpreempt_enable();
4201 
4202 		uvmspace_free(ovm);
4203 	}
4204 }
4205 
4206 /*
4207  * uvmspace_addref: add a reference to a vmspace.
4208  */
4209 
4210 void
4211 uvmspace_addref(struct vmspace *vm)
4212 {
4213 
4214 	KASSERT((vm->vm_map.flags & VM_MAP_DYING) == 0);
4215 	KASSERT(vm->vm_refcnt > 0);
4216 	atomic_inc_uint(&vm->vm_refcnt);
4217 }
4218 
4219 /*
4220  * uvmspace_free: free a vmspace data structure
4221  */
4222 
4223 void
4224 uvmspace_free(struct vmspace *vm)
4225 {
4226 	struct vm_map_entry *dead_entries;
4227 	struct vm_map *map = &vm->vm_map;
4228 	int flags;
4229 
4230 	UVMHIST_FUNC(__func__);
4231 	UVMHIST_CALLARGS(maphist,"(vm=%#jx) ref=%jd", (uintptr_t)vm,
4232 	    vm->vm_refcnt, 0, 0);
4233 	if (atomic_dec_uint_nv(&vm->vm_refcnt) > 0)
4234 		return;
4235 
4236 	/*
4237 	 * at this point, there should be no other references to the map.
4238 	 * delete all of the mappings, then destroy the pmap.
4239 	 */
4240 
4241 	map->flags |= VM_MAP_DYING;
4242 	flags = pmap_remove_all(map->pmap) ? UVM_FLAG_VAONLY : 0;
4243 
4244 	/* Get rid of any SYSV shared memory segments. */
4245 	if (uvm_shmexit && vm->vm_shm != NULL)
4246 		(*uvm_shmexit)(vm);
4247 
4248 	if (map->nentries) {
4249 		uvm_unmap_remove(map, vm_map_min(map), vm_map_max(map),
4250 		    &dead_entries, flags);
4251 		if (dead_entries != NULL)
4252 			uvm_unmap_detach(dead_entries, 0);
4253 	}
4254 	KASSERT(map->nentries == 0);
4255 	KASSERT(map->size == 0);
4256 
4257 	mutex_destroy(&map->misc_lock);
4258 	rw_destroy(&map->lock);
4259 	cv_destroy(&map->cv);
4260 	pmap_destroy(map->pmap);
4261 	pool_cache_put(&uvm_vmspace_cache, vm);
4262 }
4263 
4264 static struct vm_map_entry *
4265 uvm_mapent_clone(struct vm_map *new_map, struct vm_map_entry *old_entry,
4266     int flags)
4267 {
4268 	struct vm_map_entry *new_entry;
4269 
4270 	new_entry = uvm_mapent_alloc(new_map, 0);
4271 	/* old_entry -> new_entry */
4272 	uvm_mapent_copy(old_entry, new_entry);
4273 
4274 	/* new pmap has nothing wired in it */
4275 	new_entry->wired_count = 0;
4276 
4277 	/*
4278 	 * gain reference to object backing the map (can't
4279 	 * be a submap, already checked this case).
4280 	 */
4281 
4282 	if (new_entry->aref.ar_amap)
4283 		uvm_map_reference_amap(new_entry, flags);
4284 
4285 	if (new_entry->object.uvm_obj &&
4286 	    new_entry->object.uvm_obj->pgops->pgo_reference)
4287 		new_entry->object.uvm_obj->pgops->pgo_reference(
4288 			new_entry->object.uvm_obj);
4289 
4290 	/* insert entry at end of new_map's entry list */
4291 	uvm_map_entry_link(new_map, new_map->header.prev,
4292 	    new_entry);
4293 
4294 	return new_entry;
4295 }
4296 
4297 /*
4298  * share the mapping: this means we want the old and
4299  * new entries to share amaps and backing objects.
4300  */
4301 static void
4302 uvm_mapent_forkshared(struct vm_map *new_map, struct vm_map *old_map,
4303     struct vm_map_entry *old_entry)
4304 {
4305 	/*
4306 	 * if the old_entry needs a new amap (due to prev fork)
4307 	 * then we need to allocate it now so that we have
4308 	 * something we own to share with the new_entry.   [in
4309 	 * other words, we need to clear needs_copy]
4310 	 */
4311 
4312 	if (UVM_ET_ISNEEDSCOPY(old_entry)) {
4313 		/* get our own amap, clears needs_copy */
4314 		amap_copy(old_map, old_entry, AMAP_COPY_NOCHUNK,
4315 		    0, 0);
4316 		/* XXXCDC: WAITOK??? */
4317 	}
4318 
4319 	uvm_mapent_clone(new_map, old_entry, AMAP_SHARED);
4320 }
4321 
4322 
4323 static void
4324 uvm_mapent_forkcopy(struct vm_map *new_map, struct vm_map *old_map,
4325     struct vm_map_entry *old_entry)
4326 {
4327 	struct vm_map_entry *new_entry;
4328 
4329 	/*
4330 	 * copy-on-write the mapping (using mmap's
4331 	 * MAP_PRIVATE semantics)
4332 	 *
4333 	 * allocate new_entry, adjust reference counts.
4334 	 * (note that new references are read-only).
4335 	 */
4336 
4337 	new_entry = uvm_mapent_clone(new_map, old_entry, 0);
4338 
4339 	new_entry->etype |=
4340 	    (UVM_ET_COPYONWRITE|UVM_ET_NEEDSCOPY);
4341 
4342 	/*
4343 	 * the new entry will need an amap.  it will either
4344 	 * need to be copied from the old entry or created
4345 	 * from scratch (if the old entry does not have an
4346 	 * amap).  can we defer this process until later
4347 	 * (by setting "needs_copy") or do we need to copy
4348 	 * the amap now?
4349 	 *
4350 	 * we must copy the amap now if any of the following
4351 	 * conditions hold:
4352 	 * 1. the old entry has an amap and that amap is
4353 	 *    being shared.  this means that the old (parent)
4354 	 *    process is sharing the amap with another
4355 	 *    process.  if we do not clear needs_copy here
4356 	 *    we will end up in a situation where both the
4357 	 *    parent and child process are refering to the
4358 	 *    same amap with "needs_copy" set.  if the
4359 	 *    parent write-faults, the fault routine will
4360 	 *    clear "needs_copy" in the parent by allocating
4361 	 *    a new amap.   this is wrong because the
4362 	 *    parent is supposed to be sharing the old amap
4363 	 *    and the new amap will break that.
4364 	 *
4365 	 * 2. if the old entry has an amap and a non-zero
4366 	 *    wire count then we are going to have to call
4367 	 *    amap_cow_now to avoid page faults in the
4368 	 *    parent process.   since amap_cow_now requires
4369 	 *    "needs_copy" to be clear we might as well
4370 	 *    clear it here as well.
4371 	 *
4372 	 */
4373 
4374 	if (old_entry->aref.ar_amap != NULL) {
4375 		if ((amap_flags(old_entry->aref.ar_amap) & AMAP_SHARED) != 0 ||
4376 		    VM_MAPENT_ISWIRED(old_entry)) {
4377 
4378 			amap_copy(new_map, new_entry,
4379 			    AMAP_COPY_NOCHUNK, 0, 0);
4380 			/* XXXCDC: M_WAITOK ... ok? */
4381 		}
4382 	}
4383 
4384 	/*
4385 	 * if the parent's entry is wired down, then the
4386 	 * parent process does not want page faults on
4387 	 * access to that memory.  this means that we
4388 	 * cannot do copy-on-write because we can't write
4389 	 * protect the old entry.   in this case we
4390 	 * resolve all copy-on-write faults now, using
4391 	 * amap_cow_now.   note that we have already
4392 	 * allocated any needed amap (above).
4393 	 */
4394 
4395 	if (VM_MAPENT_ISWIRED(old_entry)) {
4396 
4397 		/*
4398 		 * resolve all copy-on-write faults now
4399 		 * (note that there is nothing to do if
4400 		 * the old mapping does not have an amap).
4401 		 */
4402 		if (old_entry->aref.ar_amap)
4403 			amap_cow_now(new_map, new_entry);
4404 
4405 	} else {
4406 		/*
4407 		 * setup mappings to trigger copy-on-write faults
4408 		 * we must write-protect the parent if it has
4409 		 * an amap and it is not already "needs_copy"...
4410 		 * if it is already "needs_copy" then the parent
4411 		 * has already been write-protected by a previous
4412 		 * fork operation.
4413 		 */
4414 		if (old_entry->aref.ar_amap &&
4415 		    !UVM_ET_ISNEEDSCOPY(old_entry)) {
4416 			if (old_entry->max_protection & VM_PROT_WRITE) {
4417 #ifdef __HAVE_UNLOCKED_PMAP /* XXX temporary */
4418 				uvm_map_lock_entry(old_entry, RW_WRITER);
4419 #else
4420 				uvm_map_lock_entry(old_entry, RW_READER);
4421 #endif
4422 				pmap_protect(old_map->pmap,
4423 				    old_entry->start, old_entry->end,
4424 				    old_entry->protection & ~VM_PROT_WRITE);
4425 				uvm_map_unlock_entry(old_entry);
4426 			}
4427 			old_entry->etype |= UVM_ET_NEEDSCOPY;
4428 		}
4429 	}
4430 }
4431 
4432 /*
4433  * zero the mapping: the new entry will be zero initialized
4434  */
4435 static void
4436 uvm_mapent_forkzero(struct vm_map *new_map, struct vm_map *old_map,
4437     struct vm_map_entry *old_entry)
4438 {
4439 	struct vm_map_entry *new_entry;
4440 
4441 	new_entry = uvm_mapent_clone(new_map, old_entry, 0);
4442 
4443 	new_entry->etype |=
4444 	    (UVM_ET_COPYONWRITE|UVM_ET_NEEDSCOPY);
4445 
4446 	if (new_entry->aref.ar_amap) {
4447 		uvm_map_unreference_amap(new_entry, 0);
4448 		new_entry->aref.ar_pageoff = 0;
4449 		new_entry->aref.ar_amap = NULL;
4450 	}
4451 
4452 	if (UVM_ET_ISOBJ(new_entry)) {
4453 		if (new_entry->object.uvm_obj->pgops->pgo_detach)
4454 			new_entry->object.uvm_obj->pgops->pgo_detach(
4455 			    new_entry->object.uvm_obj);
4456 		new_entry->object.uvm_obj = NULL;
4457 		new_entry->etype &= ~UVM_ET_OBJ;
4458 	}
4459 }
4460 
4461 /*
4462  *   F O R K   -   m a i n   e n t r y   p o i n t
4463  */
4464 /*
4465  * uvmspace_fork: fork a process' main map
4466  *
4467  * => create a new vmspace for child process from parent.
4468  * => parent's map must not be locked.
4469  */
4470 
4471 struct vmspace *
4472 uvmspace_fork(struct vmspace *vm1)
4473 {
4474 	struct vmspace *vm2;
4475 	struct vm_map *old_map = &vm1->vm_map;
4476 	struct vm_map *new_map;
4477 	struct vm_map_entry *old_entry;
4478 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
4479 
4480 	vm_map_lock(old_map);
4481 
4482 	vm2 = uvmspace_alloc(vm_map_min(old_map), vm_map_max(old_map),
4483 	    vm1->vm_map.flags & VM_MAP_TOPDOWN);
4484 	memcpy(&vm2->vm_startcopy, &vm1->vm_startcopy,
4485 	    (char *) (vm1 + 1) - (char *) &vm1->vm_startcopy);
4486 	new_map = &vm2->vm_map;		  /* XXX */
4487 
4488 	old_entry = old_map->header.next;
4489 	new_map->size = old_map->size;
4490 
4491 	/*
4492 	 * go entry-by-entry
4493 	 */
4494 
4495 	while (old_entry != &old_map->header) {
4496 
4497 		/*
4498 		 * first, some sanity checks on the old entry
4499 		 */
4500 
4501 		KASSERT(!UVM_ET_ISSUBMAP(old_entry));
4502 		KASSERT(UVM_ET_ISCOPYONWRITE(old_entry) ||
4503 			!UVM_ET_ISNEEDSCOPY(old_entry));
4504 
4505 		switch (old_entry->inheritance) {
4506 		case MAP_INHERIT_NONE:
4507 			/*
4508 			 * drop the mapping, modify size
4509 			 */
4510 			new_map->size -= old_entry->end - old_entry->start;
4511 			break;
4512 
4513 		case MAP_INHERIT_SHARE:
4514 			uvm_mapent_forkshared(new_map, old_map, old_entry);
4515 			break;
4516 
4517 		case MAP_INHERIT_COPY:
4518 			uvm_mapent_forkcopy(new_map, old_map, old_entry);
4519 			break;
4520 
4521 		case MAP_INHERIT_ZERO:
4522 			uvm_mapent_forkzero(new_map, old_map, old_entry);
4523 			break;
4524 		default:
4525 			KASSERT(0);
4526 			break;
4527 		}
4528 		old_entry = old_entry->next;
4529 	}
4530 
4531 	pmap_update(old_map->pmap);
4532 	vm_map_unlock(old_map);
4533 
4534 	if (uvm_shmfork && vm1->vm_shm)
4535 		(*uvm_shmfork)(vm1, vm2);
4536 
4537 #ifdef PMAP_FORK
4538 	pmap_fork(vm1->vm_map.pmap, vm2->vm_map.pmap);
4539 #endif
4540 
4541 	UVMHIST_LOG(maphist,"<- done",0,0,0,0);
4542 	return (vm2);
4543 }
4544 
4545 
4546 /*
4547  * uvm_mapent_trymerge: try to merge an entry with its neighbors.
4548  *
4549  * => called with map locked.
4550  * => return non zero if successfully merged.
4551  */
4552 
4553 int
4554 uvm_mapent_trymerge(struct vm_map *map, struct vm_map_entry *entry, int flags)
4555 {
4556 	struct uvm_object *uobj;
4557 	struct vm_map_entry *next;
4558 	struct vm_map_entry *prev;
4559 	vsize_t size;
4560 	int merged = 0;
4561 	bool copying;
4562 	int newetype;
4563 
4564 	if (entry->aref.ar_amap != NULL) {
4565 		return 0;
4566 	}
4567 	if ((entry->flags & UVM_MAP_NOMERGE) != 0) {
4568 		return 0;
4569 	}
4570 
4571 	uobj = entry->object.uvm_obj;
4572 	size = entry->end - entry->start;
4573 	copying = (flags & UVM_MERGE_COPYING) != 0;
4574 	newetype = copying ? (entry->etype & ~UVM_ET_NEEDSCOPY) : entry->etype;
4575 
4576 	next = entry->next;
4577 	if (next != &map->header &&
4578 	    next->start == entry->end &&
4579 	    ((copying && next->aref.ar_amap != NULL &&
4580 	    amap_refs(next->aref.ar_amap) == 1) ||
4581 	    (!copying && next->aref.ar_amap == NULL)) &&
4582 	    UVM_ET_ISCOMPATIBLE(next, newetype,
4583 	    uobj, entry->flags, entry->protection,
4584 	    entry->max_protection, entry->inheritance, entry->advice,
4585 	    entry->wired_count) &&
4586 	    (uobj == NULL || entry->offset + size == next->offset)) {
4587 		int error;
4588 
4589 		if (copying) {
4590 			error = amap_extend(next, size,
4591 			    AMAP_EXTEND_NOWAIT|AMAP_EXTEND_BACKWARDS);
4592 		} else {
4593 			error = 0;
4594 		}
4595 		if (error == 0) {
4596 			if (uobj) {
4597 				if (uobj->pgops->pgo_detach) {
4598 					uobj->pgops->pgo_detach(uobj);
4599 				}
4600 			}
4601 
4602 			entry->end = next->end;
4603 			clear_hints(map, next);
4604 			uvm_map_entry_unlink(map, next);
4605 			if (copying) {
4606 				entry->aref = next->aref;
4607 				entry->etype &= ~UVM_ET_NEEDSCOPY;
4608 			}
4609 			uvm_map_check(map, "trymerge forwardmerge");
4610 			uvm_mapent_free(next);
4611 			merged++;
4612 		}
4613 	}
4614 
4615 	prev = entry->prev;
4616 	if (prev != &map->header &&
4617 	    prev->end == entry->start &&
4618 	    ((copying && !merged && prev->aref.ar_amap != NULL &&
4619 	    amap_refs(prev->aref.ar_amap) == 1) ||
4620 	    (!copying && prev->aref.ar_amap == NULL)) &&
4621 	    UVM_ET_ISCOMPATIBLE(prev, newetype,
4622 	    uobj, entry->flags, entry->protection,
4623 	    entry->max_protection, entry->inheritance, entry->advice,
4624 	    entry->wired_count) &&
4625 	    (uobj == NULL ||
4626 	    prev->offset + prev->end - prev->start == entry->offset)) {
4627 		int error;
4628 
4629 		if (copying) {
4630 			error = amap_extend(prev, size,
4631 			    AMAP_EXTEND_NOWAIT|AMAP_EXTEND_FORWARDS);
4632 		} else {
4633 			error = 0;
4634 		}
4635 		if (error == 0) {
4636 			if (uobj) {
4637 				if (uobj->pgops->pgo_detach) {
4638 					uobj->pgops->pgo_detach(uobj);
4639 				}
4640 				entry->offset = prev->offset;
4641 			}
4642 
4643 			entry->start = prev->start;
4644 			clear_hints(map, prev);
4645 			uvm_map_entry_unlink(map, prev);
4646 			if (copying) {
4647 				entry->aref = prev->aref;
4648 				entry->etype &= ~UVM_ET_NEEDSCOPY;
4649 			}
4650 			uvm_map_check(map, "trymerge backmerge");
4651 			uvm_mapent_free(prev);
4652 			merged++;
4653 		}
4654 	}
4655 
4656 	return merged;
4657 }
4658 
4659 /*
4660  * uvm_map_setup: init map
4661  *
4662  * => map must not be in service yet.
4663  */
4664 
4665 void
4666 uvm_map_setup(struct vm_map *map, vaddr_t vmin, vaddr_t vmax, int flags)
4667 {
4668 
4669 	rb_tree_init(&map->rb_tree, &uvm_map_tree_ops);
4670 	map->header.next = map->header.prev = &map->header;
4671 	map->nentries = 0;
4672 	map->size = 0;
4673 	map->ref_count = 1;
4674 	vm_map_setmin(map, vmin);
4675 	vm_map_setmax(map, vmax);
4676 	map->flags = flags;
4677 	map->first_free = &map->header;
4678 	map->hint = &map->header;
4679 	map->timestamp = 0;
4680 	map->busy = NULL;
4681 
4682 	rw_init(&map->lock);
4683 	cv_init(&map->cv, "vm_map");
4684 	mutex_init(&map->misc_lock, MUTEX_DRIVER, IPL_NONE);
4685 }
4686 
4687 /*
4688  *   U N M A P   -   m a i n   e n t r y   p o i n t
4689  */
4690 
4691 /*
4692  * uvm_unmap1: remove mappings from a vm_map (from "start" up to "stop")
4693  *
4694  * => caller must check alignment and size
4695  * => map must be unlocked (we will lock it)
4696  * => flags is UVM_FLAG_QUANTUM or 0.
4697  */
4698 
4699 void
4700 uvm_unmap1(struct vm_map *map, vaddr_t start, vaddr_t end, int flags)
4701 {
4702 	struct vm_map_entry *dead_entries;
4703 	UVMHIST_FUNC(__func__);
4704 	UVMHIST_CALLARGS(maphist, "  (map=%#jx, start=%#jx, end=%#jx)",
4705 	    (uintptr_t)map, start, end, 0);
4706 
4707 	KASSERTMSG(start < end,
4708 	    "%s: map %p: start %#jx < end %#jx", __func__, map,
4709 	    (uintmax_t)start, (uintmax_t)end);
4710 	if (map == kernel_map) {
4711 		LOCKDEBUG_MEM_CHECK((void *)start, end - start);
4712 	}
4713 
4714 	/*
4715 	 * work now done by helper functions.   wipe the pmap's and then
4716 	 * detach from the dead entries...
4717 	 */
4718 	vm_map_lock(map);
4719 	uvm_unmap_remove(map, start, end, &dead_entries, flags);
4720 	vm_map_unlock(map);
4721 
4722 	if (dead_entries != NULL)
4723 		uvm_unmap_detach(dead_entries, 0);
4724 
4725 	UVMHIST_LOG(maphist, "<- done", 0,0,0,0);
4726 }
4727 
4728 
4729 /*
4730  * uvm_map_reference: add reference to a map
4731  *
4732  * => map need not be locked
4733  */
4734 
4735 void
4736 uvm_map_reference(struct vm_map *map)
4737 {
4738 
4739 	atomic_inc_uint(&map->ref_count);
4740 }
4741 
4742 void
4743 uvm_map_lock_entry(struct vm_map_entry *entry, krw_t op)
4744 {
4745 
4746 	if (entry->aref.ar_amap != NULL) {
4747 		amap_lock(entry->aref.ar_amap, op);
4748 	}
4749 	if (UVM_ET_ISOBJ(entry)) {
4750 		rw_enter(entry->object.uvm_obj->vmobjlock, op);
4751 	}
4752 }
4753 
4754 void
4755 uvm_map_unlock_entry(struct vm_map_entry *entry)
4756 {
4757 
4758 	if (UVM_ET_ISOBJ(entry)) {
4759 		rw_exit(entry->object.uvm_obj->vmobjlock);
4760 	}
4761 	if (entry->aref.ar_amap != NULL) {
4762 		amap_unlock(entry->aref.ar_amap);
4763 	}
4764 }
4765 
4766 #define	UVM_VOADDR_TYPE_MASK	0x3UL
4767 #define	UVM_VOADDR_TYPE_UOBJ	0x1UL
4768 #define	UVM_VOADDR_TYPE_ANON	0x2UL
4769 #define	UVM_VOADDR_OBJECT_MASK	~UVM_VOADDR_TYPE_MASK
4770 
4771 #define	UVM_VOADDR_GET_TYPE(voa)					\
4772 	((voa)->object & UVM_VOADDR_TYPE_MASK)
4773 #define	UVM_VOADDR_GET_OBJECT(voa)					\
4774 	((voa)->object & UVM_VOADDR_OBJECT_MASK)
4775 #define	UVM_VOADDR_SET_OBJECT(voa, obj, type)				\
4776 do {									\
4777 	KASSERT(((uintptr_t)(obj) & UVM_VOADDR_TYPE_MASK) == 0);	\
4778 	(voa)->object = ((uintptr_t)(obj)) | (type);			\
4779 } while (/*CONSTCOND*/0)
4780 
4781 #define	UVM_VOADDR_GET_UOBJ(voa)					\
4782 	((struct uvm_object *)UVM_VOADDR_GET_OBJECT(voa))
4783 #define	UVM_VOADDR_SET_UOBJ(voa, uobj)					\
4784 	UVM_VOADDR_SET_OBJECT(voa, uobj, UVM_VOADDR_TYPE_UOBJ)
4785 
4786 #define	UVM_VOADDR_GET_ANON(voa)					\
4787 	((struct vm_anon *)UVM_VOADDR_GET_OBJECT(voa))
4788 #define	UVM_VOADDR_SET_ANON(voa, anon)					\
4789 	UVM_VOADDR_SET_OBJECT(voa, anon, UVM_VOADDR_TYPE_ANON)
4790 
4791 /*
4792  * uvm_voaddr_acquire: returns the virtual object address corresponding
4793  * to the specified virtual address.
4794  *
4795  * => resolves COW so the true page identity is tracked.
4796  *
4797  * => acquires a reference on the page's owner (uvm_object or vm_anon)
4798  */
4799 bool
4800 uvm_voaddr_acquire(struct vm_map * const map, vaddr_t const va,
4801     struct uvm_voaddr * const voaddr)
4802 {
4803 	struct vm_map_entry *entry;
4804 	struct vm_anon *anon = NULL;
4805 	bool result = false;
4806 	bool exclusive = false;
4807 	void (*unlock_fn)(struct vm_map *);
4808 
4809 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
4810 	UVMHIST_LOG(maphist,"(map=%#jx,va=%#jx)", (uintptr_t)map, va, 0, 0);
4811 
4812 	const vaddr_t start = trunc_page(va);
4813 	const vaddr_t end = round_page(va+1);
4814 
4815  lookup_again:
4816 	if (__predict_false(exclusive)) {
4817 		vm_map_lock(map);
4818 		unlock_fn = vm_map_unlock;
4819 	} else {
4820 		vm_map_lock_read(map);
4821 		unlock_fn = vm_map_unlock_read;
4822 	}
4823 
4824 	if (__predict_false(!uvm_map_lookup_entry(map, start, &entry))) {
4825 		unlock_fn(map);
4826 		UVMHIST_LOG(maphist,"<- done (no entry)",0,0,0,0);
4827 		return false;
4828 	}
4829 
4830 	if (__predict_false(entry->protection == VM_PROT_NONE)) {
4831 		unlock_fn(map);
4832 		UVMHIST_LOG(maphist,"<- done (PROT_NONE)",0,0,0,0);
4833 		return false;
4834 	}
4835 
4836 	/*
4837 	 * We have a fast path for the common case of "no COW resolution
4838 	 * needed" whereby we have taken a read lock on the map and if
4839 	 * we don't encounter any need to create a vm_anon then great!
4840 	 * But if we do, we loop around again, instead taking an exclusive
4841 	 * lock so that we can perform the fault.
4842 	 *
4843 	 * In the event that we have to resolve the fault, we do nearly the
4844 	 * same work as uvm_map_pageable() does:
4845 	 *
4846 	 * 1: holding the write lock, we create any anonymous maps that need
4847 	 *    to be created.  however, we do NOT need to clip the map entries
4848 	 *    in this case.
4849 	 *
4850 	 * 2: we downgrade to a read lock, and call uvm_fault_wire to fault
4851 	 *    in the page (assuming the entry is not already wired).  this
4852 	 *    is done because we need the vm_anon to be present.
4853 	 */
4854 	if (__predict_true(!VM_MAPENT_ISWIRED(entry))) {
4855 
4856 		bool need_fault = false;
4857 
4858 		/*
4859 		 * perform the action of vm_map_lookup that need the
4860 		 * write lock on the map: create an anonymous map for
4861 		 * a copy-on-write region, or an anonymous map for
4862 		 * a zero-fill region.
4863 		 */
4864 		if (__predict_false(UVM_ET_ISSUBMAP(entry))) {
4865 			unlock_fn(map);
4866 			UVMHIST_LOG(maphist,"<- done (submap)",0,0,0,0);
4867 			return false;
4868 		}
4869 		if (__predict_false(UVM_ET_ISNEEDSCOPY(entry) &&
4870 		    ((entry->max_protection & VM_PROT_WRITE) ||
4871 		     (entry->object.uvm_obj == NULL)))) {
4872 			if (!exclusive) {
4873 				/* need to take the slow path */
4874 				KASSERT(unlock_fn == vm_map_unlock_read);
4875 				vm_map_unlock_read(map);
4876 				exclusive = true;
4877 				goto lookup_again;
4878 			}
4879 			need_fault = true;
4880 			amap_copy(map, entry, 0, start, end);
4881 			/* XXXCDC: wait OK? */
4882 		}
4883 
4884 		/*
4885 		 * do a quick check to see if the fault has already
4886 		 * been resolved to the upper layer.
4887 		 */
4888 		if (__predict_true(entry->aref.ar_amap != NULL &&
4889 				   need_fault == false)) {
4890 			amap_lock(entry->aref.ar_amap, RW_WRITER);
4891 			anon = amap_lookup(&entry->aref, start - entry->start);
4892 			if (__predict_true(anon != NULL)) {
4893 				/* amap unlocked below */
4894 				goto found_anon;
4895 			}
4896 			amap_unlock(entry->aref.ar_amap);
4897 			need_fault = true;
4898 		}
4899 
4900 		/*
4901 		 * we predict this test as false because if we reach
4902 		 * this point, then we are likely dealing with a
4903 		 * shared memory region backed by a uvm_object, in
4904 		 * which case a fault to create the vm_anon is not
4905 		 * necessary.
4906 		 */
4907 		if (__predict_false(need_fault)) {
4908 			if (exclusive) {
4909 				vm_map_busy(map);
4910 				vm_map_unlock(map);
4911 				unlock_fn = vm_map_unbusy;
4912 			}
4913 
4914 			if (uvm_fault_wire(map, start, end,
4915 					   entry->max_protection, 1)) {
4916 				/* wiring failed */
4917 				unlock_fn(map);
4918 				UVMHIST_LOG(maphist,"<- done (wire failed)",
4919 					    0,0,0,0);
4920 				return false;
4921 			}
4922 
4923 			/*
4924 			 * now that we have resolved the fault, we can unwire
4925 			 * the page.
4926 			 */
4927 			if (exclusive) {
4928 				vm_map_lock(map);
4929 				vm_map_unbusy(map);
4930 				unlock_fn = vm_map_unlock;
4931 			}
4932 
4933 			uvm_fault_unwire_locked(map, start, end);
4934 		}
4935 	}
4936 
4937 	/* check the upper layer */
4938 	if (entry->aref.ar_amap) {
4939 		amap_lock(entry->aref.ar_amap, RW_WRITER);
4940 		anon = amap_lookup(&entry->aref, start - entry->start);
4941 		if (anon) {
4942  found_anon:		KASSERT(anon->an_lock == entry->aref.ar_amap->am_lock);
4943 			anon->an_ref++;
4944 			rw_obj_hold(anon->an_lock);
4945 			KASSERT(anon->an_ref != 0);
4946 			UVM_VOADDR_SET_ANON(voaddr, anon);
4947 			voaddr->offset = va & PAGE_MASK;
4948 			result = true;
4949 		}
4950 		amap_unlock(entry->aref.ar_amap);
4951 	}
4952 
4953 	/* check the lower layer */
4954 	if (!result && UVM_ET_ISOBJ(entry)) {
4955 		struct uvm_object *uobj = entry->object.uvm_obj;
4956 
4957 		KASSERT(uobj != NULL);
4958 		(*uobj->pgops->pgo_reference)(uobj);
4959 		UVM_VOADDR_SET_UOBJ(voaddr, uobj);
4960 		voaddr->offset = entry->offset + (va - entry->start);
4961 		result = true;
4962 	}
4963 
4964 	unlock_fn(map);
4965 
4966 	if (result) {
4967 		UVMHIST_LOG(maphist,
4968 		    "<- done OK (type=%jd,owner=%#jx,offset=%#jx)",
4969 		    UVM_VOADDR_GET_TYPE(voaddr),
4970 		    UVM_VOADDR_GET_OBJECT(voaddr),
4971 		    voaddr->offset, 0);
4972 	} else {
4973 		UVMHIST_LOG(maphist,"<- done (failed)",0,0,0,0);
4974 	}
4975 
4976 	return result;
4977 }
4978 
4979 /*
4980  * uvm_voaddr_release: release the references held by the
4981  * vitual object address.
4982  */
4983 void
4984 uvm_voaddr_release(struct uvm_voaddr * const voaddr)
4985 {
4986 
4987 	switch (UVM_VOADDR_GET_TYPE(voaddr)) {
4988 	case UVM_VOADDR_TYPE_UOBJ: {
4989 		struct uvm_object * const uobj = UVM_VOADDR_GET_UOBJ(voaddr);
4990 
4991 		KASSERT(uobj != NULL);
4992 		KASSERT(uobj->pgops->pgo_detach != NULL);
4993 		(*uobj->pgops->pgo_detach)(uobj);
4994 		break;
4995 	    }
4996 	case UVM_VOADDR_TYPE_ANON: {
4997 		struct vm_anon * const anon = UVM_VOADDR_GET_ANON(voaddr);
4998 		krwlock_t *lock;
4999 
5000 		KASSERT(anon != NULL);
5001 		rw_enter((lock = anon->an_lock), RW_WRITER);
5002 	    	KASSERT(anon->an_ref > 0);
5003 		if (--anon->an_ref == 0) {
5004 			uvm_anfree(anon);
5005 		}
5006 		rw_exit(lock);
5007 		rw_obj_free(lock);
5008 	    	break;
5009 	    }
5010 	default:
5011 		panic("uvm_voaddr_release: bad type");
5012 	}
5013 	memset(voaddr, 0, sizeof(*voaddr));
5014 }
5015 
5016 /*
5017  * uvm_voaddr_compare: compare two uvm_voaddr objects.
5018  *
5019  * => memcmp() semantics
5020  */
5021 int
5022 uvm_voaddr_compare(const struct uvm_voaddr * const voaddr1,
5023     const struct uvm_voaddr * const voaddr2)
5024 {
5025 	const uintptr_t type1 = UVM_VOADDR_GET_TYPE(voaddr1);
5026 	const uintptr_t type2 = UVM_VOADDR_GET_TYPE(voaddr2);
5027 
5028 	KASSERT(type1 == UVM_VOADDR_TYPE_UOBJ ||
5029 		type1 == UVM_VOADDR_TYPE_ANON);
5030 
5031 	KASSERT(type2 == UVM_VOADDR_TYPE_UOBJ ||
5032 		type2 == UVM_VOADDR_TYPE_ANON);
5033 
5034 	if (type1 < type2)
5035 		return -1;
5036 	if (type1 > type2)
5037 		return 1;
5038 
5039 	const uintptr_t addr1 = UVM_VOADDR_GET_OBJECT(voaddr1);
5040 	const uintptr_t addr2 = UVM_VOADDR_GET_OBJECT(voaddr2);
5041 
5042 	if (addr1 < addr2)
5043 		return -1;
5044 	if (addr1 > addr2)
5045 		return 1;
5046 
5047 	if (voaddr1->offset < voaddr2->offset)
5048 		return -1;
5049 	if (voaddr1->offset > voaddr2->offset)
5050 		return 1;
5051 
5052 	return 0;
5053 }
5054 
5055 #if defined(DDB) || defined(DEBUGPRINT)
5056 
5057 /*
5058  * uvm_map_printit: actually prints the map
5059  */
5060 
5061 void
5062 uvm_map_printit(struct vm_map *map, bool full,
5063     void (*pr)(const char *, ...))
5064 {
5065 	struct vm_map_entry *entry;
5066 
5067 	(*pr)("MAP %p: [%#lx->%#lx]\n", map, vm_map_min(map),
5068 	    vm_map_max(map));
5069 	(*pr)("\t#ent=%d, sz=%d, ref=%d, version=%d, flags=%#x\n",
5070 	    map->nentries, map->size, map->ref_count, map->timestamp,
5071 	    map->flags);
5072 	(*pr)("\tpmap=%p(resident=%ld, wired=%ld)\n", map->pmap,
5073 	    pmap_resident_count(map->pmap), pmap_wired_count(map->pmap));
5074 	if (!full)
5075 		return;
5076 	for (entry = map->header.next; entry != &map->header;
5077 	    entry = entry->next) {
5078 		(*pr)(" - %p: %#lx->%#lx: obj=%p/%#llx, amap=%p/%d\n",
5079 		    entry, entry->start, entry->end, entry->object.uvm_obj,
5080 		    (long long)entry->offset, entry->aref.ar_amap,
5081 		    entry->aref.ar_pageoff);
5082 		(*pr)(
5083 		    "\tsubmap=%c, cow=%c, nc=%c, prot(max)=%d/%d, inh=%d, "
5084 		    "wc=%d, adv=%d\n",
5085 		    (entry->etype & UVM_ET_SUBMAP) ? 'T' : 'F',
5086 		    (entry->etype & UVM_ET_COPYONWRITE) ? 'T' : 'F',
5087 		    (entry->etype & UVM_ET_NEEDSCOPY) ? 'T' : 'F',
5088 		    entry->protection, entry->max_protection,
5089 		    entry->inheritance, entry->wired_count, entry->advice);
5090 	}
5091 }
5092 
5093 void
5094 uvm_whatis(uintptr_t addr, void (*pr)(const char *, ...))
5095 {
5096 	struct vm_map *map;
5097 
5098 	for (map = kernel_map;;) {
5099 		struct vm_map_entry *entry;
5100 
5101 		if (!uvm_map_lookup_entry_bytree(map, (vaddr_t)addr, &entry)) {
5102 			break;
5103 		}
5104 		(*pr)("%p is %p+%zu from VMMAP %p\n",
5105 		    (void *)addr, (void *)entry->start,
5106 		    (size_t)(addr - (uintptr_t)entry->start), map);
5107 		if (!UVM_ET_ISSUBMAP(entry)) {
5108 			break;
5109 		}
5110 		map = entry->object.sub_map;
5111 	}
5112 }
5113 
5114 #endif /* DDB || DEBUGPRINT */
5115 
5116 #ifndef __USER_VA0_IS_SAFE
5117 static int
5118 sysctl_user_va0_disable(SYSCTLFN_ARGS)
5119 {
5120 	struct sysctlnode node;
5121 	int t, error;
5122 
5123 	node = *rnode;
5124 	node.sysctl_data = &t;
5125 	t = user_va0_disable;
5126 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
5127 	if (error || newp == NULL)
5128 		return (error);
5129 
5130 	if (!t && user_va0_disable &&
5131 	    kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_MAP_VA_ZERO, 0,
5132 	    NULL, NULL, NULL))
5133 		return EPERM;
5134 
5135 	user_va0_disable = !!t;
5136 	return 0;
5137 }
5138 #endif
5139 
5140 static int
5141 fill_vmentry(struct lwp *l, struct proc *p, struct kinfo_vmentry *kve,
5142     struct vm_map *m, struct vm_map_entry *e)
5143 {
5144 #ifndef _RUMPKERNEL
5145 	int error;
5146 
5147 	memset(kve, 0, sizeof(*kve));
5148 	KASSERT(e != NULL);
5149 	if (UVM_ET_ISOBJ(e)) {
5150 		struct uvm_object *uobj = e->object.uvm_obj;
5151 		KASSERT(uobj != NULL);
5152 		kve->kve_ref_count = uobj->uo_refs;
5153 		kve->kve_count = uobj->uo_npages;
5154 		if (UVM_OBJ_IS_VNODE(uobj)) {
5155 			struct vattr va;
5156 			struct vnode *vp = (struct vnode *)uobj;
5157 			vn_lock(vp, LK_SHARED | LK_RETRY);
5158 			error = VOP_GETATTR(vp, &va, l->l_cred);
5159 			VOP_UNLOCK(vp);
5160 			kve->kve_type = KVME_TYPE_VNODE;
5161 			if (error == 0) {
5162 				kve->kve_vn_size = vp->v_size;
5163 				kve->kve_vn_type = (int)vp->v_type;
5164 				kve->kve_vn_mode = va.va_mode;
5165 				kve->kve_vn_rdev = va.va_rdev;
5166 				kve->kve_vn_fileid = va.va_fileid;
5167 				kve->kve_vn_fsid = va.va_fsid;
5168 				error = vnode_to_path(kve->kve_path,
5169 				    sizeof(kve->kve_path) / 2, vp, l, p);
5170 #ifdef DIAGNOSTIC
5171 				if (error)
5172 					printf("%s: vp %p error %d\n", __func__,
5173 						vp, error);
5174 #endif
5175 			}
5176 		} else if (UVM_OBJ_IS_KERN_OBJECT(uobj)) {
5177 			kve->kve_type = KVME_TYPE_KERN;
5178 		} else if (UVM_OBJ_IS_DEVICE(uobj)) {
5179 			kve->kve_type = KVME_TYPE_DEVICE;
5180 		} else if (UVM_OBJ_IS_AOBJ(uobj)) {
5181 			kve->kve_type = KVME_TYPE_ANON;
5182 		} else {
5183 			kve->kve_type = KVME_TYPE_OBJECT;
5184 		}
5185 	} else if (UVM_ET_ISSUBMAP(e)) {
5186 		struct vm_map *map = e->object.sub_map;
5187 		KASSERT(map != NULL);
5188 		kve->kve_ref_count = map->ref_count;
5189 		kve->kve_count = map->nentries;
5190 		kve->kve_type = KVME_TYPE_SUBMAP;
5191 	} else
5192 		kve->kve_type = KVME_TYPE_UNKNOWN;
5193 
5194 	kve->kve_start = e->start;
5195 	kve->kve_end = e->end;
5196 	kve->kve_offset = e->offset;
5197 	kve->kve_wired_count = e->wired_count;
5198 	kve->kve_inheritance = e->inheritance;
5199 	kve->kve_attributes = 0; /* unused */
5200 	kve->kve_advice = e->advice;
5201 #define PROT(p) (((p) & VM_PROT_READ) ? KVME_PROT_READ : 0) | \
5202 	(((p) & VM_PROT_WRITE) ? KVME_PROT_WRITE : 0) | \
5203 	(((p) & VM_PROT_EXECUTE) ? KVME_PROT_EXEC : 0)
5204 	kve->kve_protection = PROT(e->protection);
5205 	kve->kve_max_protection = PROT(e->max_protection);
5206 	kve->kve_flags |= (e->etype & UVM_ET_COPYONWRITE)
5207 	    ? KVME_FLAG_COW : 0;
5208 	kve->kve_flags |= (e->etype & UVM_ET_NEEDSCOPY)
5209 	    ? KVME_FLAG_NEEDS_COPY : 0;
5210 	kve->kve_flags |= (m->flags & VM_MAP_TOPDOWN)
5211 	    ? KVME_FLAG_GROWS_DOWN : KVME_FLAG_GROWS_UP;
5212 	kve->kve_flags |= (m->flags & VM_MAP_PAGEABLE)
5213 	    ? KVME_FLAG_PAGEABLE : 0;
5214 #endif
5215 	return 0;
5216 }
5217 
5218 static int
5219 fill_vmentries(struct lwp *l, pid_t pid, u_int elem_size, void *oldp,
5220     size_t *oldlenp)
5221 {
5222 	int error;
5223 	struct proc *p;
5224 	struct kinfo_vmentry *vme;
5225 	struct vmspace *vm;
5226 	struct vm_map *map;
5227 	struct vm_map_entry *entry;
5228 	char *dp;
5229 	size_t count, vmesize;
5230 
5231 	if (elem_size == 0 || elem_size > 2 * sizeof(*vme))
5232 		return EINVAL;
5233 
5234 	if (oldp) {
5235 		if (*oldlenp > 10UL * 1024UL * 1024UL)
5236 			return E2BIG;
5237 		count = *oldlenp / elem_size;
5238 		if (count == 0)
5239 			return ENOMEM;
5240 		vmesize = count * sizeof(*vme);
5241 	} else
5242 		vmesize = 0;
5243 
5244 	if ((error = proc_find_locked(l, &p, pid)) != 0)
5245 		return error;
5246 
5247 	vme = NULL;
5248 	count = 0;
5249 
5250 	if ((error = proc_vmspace_getref(p, &vm)) != 0)
5251 		goto out;
5252 
5253 	map = &vm->vm_map;
5254 	vm_map_lock_read(map);
5255 
5256 	dp = oldp;
5257 	if (oldp)
5258 		vme = kmem_alloc(vmesize, KM_SLEEP);
5259 	for (entry = map->header.next; entry != &map->header;
5260 	    entry = entry->next) {
5261 		if (oldp && (dp - (char *)oldp) < vmesize) {
5262 			error = fill_vmentry(l, p, &vme[count], map, entry);
5263 			if (error)
5264 				goto out;
5265 			dp += elem_size;
5266 		}
5267 		count++;
5268 	}
5269 	vm_map_unlock_read(map);
5270 	uvmspace_free(vm);
5271 
5272 out:
5273 	if (pid != -1)
5274 		mutex_exit(p->p_lock);
5275 	if (error == 0) {
5276 		const u_int esize = uimin(sizeof(*vme), elem_size);
5277 		dp = oldp;
5278 		for (size_t i = 0; i < count; i++) {
5279 			if (oldp && (dp - (char *)oldp) < vmesize) {
5280 				error = sysctl_copyout(l, &vme[i], dp, esize);
5281 				if (error)
5282 					break;
5283 				dp += elem_size;
5284 			} else
5285 				break;
5286 		}
5287 		count *= elem_size;
5288 		if (oldp != NULL && *oldlenp < count)
5289 			error = ENOSPC;
5290 		*oldlenp = count;
5291 	}
5292 	if (vme)
5293 		kmem_free(vme, vmesize);
5294 	return error;
5295 }
5296 
5297 static int
5298 sysctl_vmproc(SYSCTLFN_ARGS)
5299 {
5300 	int error;
5301 
5302 	if (namelen == 1 && name[0] == CTL_QUERY)
5303 		return (sysctl_query(SYSCTLFN_CALL(rnode)));
5304 
5305 	if (namelen == 0)
5306 		return EINVAL;
5307 
5308 	switch (name[0]) {
5309 	case VM_PROC_MAP:
5310 		if (namelen != 3)
5311 			return EINVAL;
5312 		sysctl_unlock();
5313 		error = fill_vmentries(l, name[1], name[2], oldp, oldlenp);
5314 		sysctl_relock();
5315 		return error;
5316 	default:
5317 		return EINVAL;
5318 	}
5319 }
5320 
5321 SYSCTL_SETUP(sysctl_uvmmap_setup, "sysctl uvmmap setup")
5322 {
5323 
5324 	sysctl_createv(clog, 0, NULL, NULL,
5325 		       CTLFLAG_PERMANENT,
5326 		       CTLTYPE_STRUCT, "proc",
5327 		       SYSCTL_DESCR("Process vm information"),
5328 		       sysctl_vmproc, 0, NULL, 0,
5329 		       CTL_VM, VM_PROC, CTL_EOL);
5330 #ifndef __USER_VA0_IS_SAFE
5331         sysctl_createv(clog, 0, NULL, NULL,
5332                        CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5333                        CTLTYPE_INT, "user_va0_disable",
5334                        SYSCTL_DESCR("Disable VA 0"),
5335                        sysctl_user_va0_disable, 0, &user_va0_disable, 0,
5336                        CTL_VM, CTL_CREATE, CTL_EOL);
5337 #endif
5338 }
5339