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