xref: /netbsd-src/sys/uvm/uvm_map.c (revision 37b34d511dea595d3ba03a661cf3b775038ea5f8)
1 /*	$NetBSD: uvm_map.c,v 1.121 2002/10/18 13:18:42 atatat 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.121 2002/10/18 13:18:42 atatat Exp $");
75 
76 #include "opt_ddb.h"
77 #include "opt_uvmhist.h"
78 #include "opt_sysv.h"
79 
80 #include <sys/param.h>
81 #include <sys/systm.h>
82 #include <sys/mman.h>
83 #include <sys/proc.h>
84 #include <sys/malloc.h>
85 #include <sys/pool.h>
86 #include <sys/kernel.h>
87 #include <sys/mount.h>
88 #include <sys/vnode.h>
89 
90 #ifdef SYSVSHM
91 #include <sys/shm.h>
92 #endif
93 
94 #define UVM_MAP
95 #include <uvm/uvm.h>
96 
97 #ifdef DDB
98 #include <uvm/uvm_ddb.h>
99 #endif
100 
101 extern struct vm_map *pager_map;
102 
103 struct uvm_cnt map_ubackmerge, map_uforwmerge;
104 struct uvm_cnt map_ubimerge, map_uforwmerge_fail, map_unomerge;
105 struct uvm_cnt map_kbackmerge, map_kforwmerge;
106 struct uvm_cnt map_kbimerge, map_kforwmerge_fail, map_knomerge;
107 struct uvm_cnt uvm_map_call, uvm_mlk_call, uvm_mlk_hint;
108 const char vmmapbsy[] = "vmmapbsy";
109 
110 /*
111  * pool for vmspace structures.
112  */
113 
114 struct pool uvm_vmspace_pool;
115 
116 /*
117  * pool for dynamically-allocated map entries.
118  */
119 
120 struct pool uvm_map_entry_pool;
121 struct pool uvm_map_entry_kmem_pool;
122 
123 #ifdef PMAP_GROWKERNEL
124 /*
125  * This global represents the end of the kernel virtual address
126  * space.  If we want to exceed this, we must grow the kernel
127  * virtual address space dynamically.
128  *
129  * Note, this variable is locked by kernel_map's lock.
130  */
131 vaddr_t uvm_maxkaddr;
132 #endif
133 
134 /*
135  * macros
136  */
137 
138 /*
139  * uvm_map_entry_link: insert entry into a map
140  *
141  * => map must be locked
142  */
143 #define uvm_map_entry_link(map, after_where, entry) do { \
144 	(map)->nentries++; \
145 	(entry)->prev = (after_where); \
146 	(entry)->next = (after_where)->next; \
147 	(entry)->prev->next = (entry); \
148 	(entry)->next->prev = (entry); \
149 } while (0)
150 
151 /*
152  * uvm_map_entry_unlink: remove entry from a map
153  *
154  * => map must be locked
155  */
156 #define uvm_map_entry_unlink(map, entry) do { \
157 	(map)->nentries--; \
158 	(entry)->next->prev = (entry)->prev; \
159 	(entry)->prev->next = (entry)->next; \
160 } while (0)
161 
162 /*
163  * SAVE_HINT: saves the specified entry as the hint for future lookups.
164  *
165  * => map need not be locked (protected by hint_lock).
166  */
167 #define SAVE_HINT(map,check,value) do { \
168 	simple_lock(&(map)->hint_lock); \
169 	if ((map)->hint == (check)) \
170 		(map)->hint = (value); \
171 	simple_unlock(&(map)->hint_lock); \
172 } while (0)
173 
174 /*
175  * VM_MAP_RANGE_CHECK: check and correct range
176  *
177  * => map must at least be read locked
178  */
179 
180 #define VM_MAP_RANGE_CHECK(map, start, end) do { \
181 	if (start < vm_map_min(map)) 		\
182 		start = vm_map_min(map);        \
183 	if (end > vm_map_max(map))              \
184 		end = vm_map_max(map);          \
185 	if (start > end)                        \
186 		start = end;                    \
187 } while (0)
188 
189 /*
190  * local prototypes
191  */
192 
193 static struct vm_map_entry *uvm_mapent_alloc __P((struct vm_map *));
194 static void uvm_mapent_copy __P((struct vm_map_entry *, struct vm_map_entry *));
195 static void uvm_mapent_free __P((struct vm_map_entry *));
196 static void uvm_map_entry_unwire __P((struct vm_map *, struct vm_map_entry *));
197 static void uvm_map_reference_amap __P((struct vm_map_entry *, int));
198 static void uvm_map_unreference_amap __P((struct vm_map_entry *, int));
199 
200 /*
201  * local inlines
202  */
203 
204 /*
205  * uvm_mapent_alloc: allocate a map entry
206  */
207 
208 static __inline struct vm_map_entry *
209 uvm_mapent_alloc(map)
210 	struct vm_map *map;
211 {
212 	struct vm_map_entry *me;
213 	int s;
214 	UVMHIST_FUNC("uvm_mapent_alloc"); UVMHIST_CALLED(maphist);
215 
216 	if (map->flags & VM_MAP_INTRSAFE || cold) {
217 		s = splvm();
218 		simple_lock(&uvm.kentry_lock);
219 		me = uvm.kentry_free;
220 		if (me) uvm.kentry_free = me->next;
221 		simple_unlock(&uvm.kentry_lock);
222 		splx(s);
223 		if (me == NULL) {
224 			panic("uvm_mapent_alloc: out of static map entries, "
225 			      "check MAX_KMAPENT (currently %d)",
226 			      MAX_KMAPENT);
227 		}
228 		me->flags = UVM_MAP_STATIC;
229 	} else if (map == kernel_map) {
230 		me = pool_get(&uvm_map_entry_kmem_pool, PR_WAITOK);
231 		me->flags = UVM_MAP_KMEM;
232 	} else {
233 		me = pool_get(&uvm_map_entry_pool, PR_WAITOK);
234 		me->flags = 0;
235 	}
236 
237 	UVMHIST_LOG(maphist, "<- new entry=0x%x [kentry=%d]", me,
238 	    ((map->flags & VM_MAP_INTRSAFE) != 0 || map == kernel_map), 0, 0);
239 	return(me);
240 }
241 
242 /*
243  * uvm_mapent_free: free map entry
244  */
245 
246 static __inline void
247 uvm_mapent_free(me)
248 	struct vm_map_entry *me;
249 {
250 	int s;
251 	UVMHIST_FUNC("uvm_mapent_free"); UVMHIST_CALLED(maphist);
252 
253 	UVMHIST_LOG(maphist,"<- freeing map entry=0x%x [flags=%d]",
254 		me, me->flags, 0, 0);
255 	if (me->flags & UVM_MAP_STATIC) {
256 		s = splvm();
257 		simple_lock(&uvm.kentry_lock);
258 		me->next = uvm.kentry_free;
259 		uvm.kentry_free = me;
260 		simple_unlock(&uvm.kentry_lock);
261 		splx(s);
262 	} else if (me->flags & UVM_MAP_KMEM) {
263 		pool_put(&uvm_map_entry_kmem_pool, me);
264 	} else {
265 		pool_put(&uvm_map_entry_pool, me);
266 	}
267 }
268 
269 /*
270  * uvm_mapent_copy: copy a map entry, preserving flags
271  */
272 
273 static __inline void
274 uvm_mapent_copy(src, dst)
275 	struct vm_map_entry *src;
276 	struct vm_map_entry *dst;
277 {
278 	memcpy(dst, src, ((char *)&src->uvm_map_entry_stop_copy) -
279 	   ((char *)src));
280 }
281 
282 /*
283  * uvm_map_entry_unwire: unwire a map entry
284  *
285  * => map should be locked by caller
286  */
287 
288 static __inline void
289 uvm_map_entry_unwire(map, entry)
290 	struct vm_map *map;
291 	struct vm_map_entry *entry;
292 {
293 	entry->wired_count = 0;
294 	uvm_fault_unwire_locked(map, entry->start, entry->end);
295 }
296 
297 
298 /*
299  * wrapper for calling amap_ref()
300  */
301 static __inline void
302 uvm_map_reference_amap(entry, flags)
303 	struct vm_map_entry *entry;
304 	int flags;
305 {
306 	amap_ref(entry->aref.ar_amap, entry->aref.ar_pageoff,
307 	     (entry->end - entry->start) >> PAGE_SHIFT, flags);
308 }
309 
310 
311 /*
312  * wrapper for calling amap_unref()
313  */
314 static __inline void
315 uvm_map_unreference_amap(entry, flags)
316 	struct vm_map_entry *entry;
317 	int flags;
318 {
319 	amap_unref(entry->aref.ar_amap, entry->aref.ar_pageoff,
320 	     (entry->end - entry->start) >> PAGE_SHIFT, flags);
321 }
322 
323 
324 /*
325  * uvm_map_init: init mapping system at boot time.   note that we allocate
326  * and init the static pool of struct vm_map_entry *'s for the kernel here.
327  */
328 
329 void
330 uvm_map_init()
331 {
332 	static struct vm_map_entry kernel_map_entry[MAX_KMAPENT];
333 #if defined(UVMHIST)
334 	static struct uvm_history_ent maphistbuf[100];
335 	static struct uvm_history_ent pdhistbuf[100];
336 #endif
337 	int lcv;
338 
339 	/*
340 	 * first, init logging system.
341 	 */
342 
343 	UVMHIST_FUNC("uvm_map_init");
344 	UVMHIST_INIT_STATIC(maphist, maphistbuf);
345 	UVMHIST_INIT_STATIC(pdhist, pdhistbuf);
346 	UVMHIST_CALLED(maphist);
347 	UVMHIST_LOG(maphist,"<starting uvm map system>", 0, 0, 0, 0);
348 	UVMCNT_INIT(uvm_map_call,  UVMCNT_CNT, 0,
349 	    "# uvm_map() successful calls", 0);
350 
351 	UVMCNT_INIT(map_ubackmerge, UVMCNT_CNT, 0,
352 	    "# uvm_map() back umerges", 0);
353 	UVMCNT_INIT(map_uforwmerge, UVMCNT_CNT, 0,
354 	    "# uvm_map() forward umerges", 0);
355 	UVMCNT_INIT(map_ubimerge, UVMCNT_CNT, 0,
356 	    "# uvm_map() dual umerge", 0);
357 	UVMCNT_INIT(map_uforwmerge_fail, UVMCNT_CNT, 0,
358 	    "# uvm_map() forward umerge fails", 0);
359 	UVMCNT_INIT(map_unomerge, UVMCNT_CNT, 0,
360 	    "# uvm_map() no umerge", 0);
361 
362 	UVMCNT_INIT(map_kbackmerge, UVMCNT_CNT, 0,
363 	    "# uvm_map() back kmerges", 0);
364 	UVMCNT_INIT(map_kforwmerge, UVMCNT_CNT, 0,
365 	    "# uvm_map() forward kmerges", 0);
366 	UVMCNT_INIT(map_kbimerge, UVMCNT_CNT, 0,
367 	    "# uvm_map() dual kmerge", 0);
368 	UVMCNT_INIT(map_kforwmerge_fail, UVMCNT_CNT, 0,
369 	    "# uvm_map() forward kmerge fails", 0);
370 	UVMCNT_INIT(map_knomerge, UVMCNT_CNT, 0,
371 	    "# uvm_map() no kmerge", 0);
372 
373 	UVMCNT_INIT(uvm_mlk_call,  UVMCNT_CNT, 0, "# map lookup calls", 0);
374 	UVMCNT_INIT(uvm_mlk_hint,  UVMCNT_CNT, 0, "# map lookup hint hits", 0);
375 
376 	/*
377 	 * now set up static pool of kernel map entrys ...
378 	 */
379 
380 	simple_lock_init(&uvm.kentry_lock);
381 	uvm.kentry_free = NULL;
382 	for (lcv = 0 ; lcv < MAX_KMAPENT ; lcv++) {
383 		kernel_map_entry[lcv].next = uvm.kentry_free;
384 		uvm.kentry_free = &kernel_map_entry[lcv];
385 	}
386 
387 	/*
388 	 * initialize the map-related pools.
389 	 */
390 	pool_init(&uvm_vmspace_pool, sizeof(struct vmspace),
391 	    0, 0, 0, "vmsppl", &pool_allocator_nointr);
392 	pool_init(&uvm_map_entry_pool, sizeof(struct vm_map_entry),
393 	    0, 0, 0, "vmmpepl", &pool_allocator_nointr);
394 	pool_init(&uvm_map_entry_kmem_pool, sizeof(struct vm_map_entry),
395 	    0, 0, 0, "vmmpekpl", NULL);
396 }
397 
398 /*
399  * clippers
400  */
401 
402 /*
403  * uvm_map_clip_start: ensure that the entry begins at or after
404  *	the starting address, if it doesn't we split the entry.
405  *
406  * => caller should use UVM_MAP_CLIP_START macro rather than calling
407  *    this directly
408  * => map must be locked by caller
409  */
410 
411 void
412 uvm_map_clip_start(map, entry, start)
413 	struct vm_map *map;
414 	struct vm_map_entry *entry;
415 	vaddr_t start;
416 {
417 	struct vm_map_entry *new_entry;
418 	vaddr_t new_adj;
419 
420 	/* uvm_map_simplify_entry(map, entry); */ /* XXX */
421 
422 	/*
423 	 * Split off the front portion.  note that we must insert the new
424 	 * entry BEFORE this one, so that this entry has the specified
425 	 * starting address.
426 	 */
427 
428 	new_entry = uvm_mapent_alloc(map);
429 	uvm_mapent_copy(entry, new_entry); /* entry -> new_entry */
430 
431 	new_entry->end = start;
432 	new_adj = start - new_entry->start;
433 	if (entry->object.uvm_obj)
434 		entry->offset += new_adj;	/* shift start over */
435 	entry->start = start;
436 
437 	if (new_entry->aref.ar_amap) {
438 		amap_splitref(&new_entry->aref, &entry->aref, new_adj);
439 	}
440 
441 	uvm_map_entry_link(map, entry->prev, new_entry);
442 
443 	if (UVM_ET_ISSUBMAP(entry)) {
444 		/* ... unlikely to happen, but play it safe */
445 		 uvm_map_reference(new_entry->object.sub_map);
446 	} else {
447 		if (UVM_ET_ISOBJ(entry) &&
448 		    entry->object.uvm_obj->pgops &&
449 		    entry->object.uvm_obj->pgops->pgo_reference)
450 			entry->object.uvm_obj->pgops->pgo_reference(
451 			    entry->object.uvm_obj);
452 	}
453 }
454 
455 /*
456  * uvm_map_clip_end: ensure that the entry ends at or before
457  *	the ending address, if it does't we split the reference
458  *
459  * => caller should use UVM_MAP_CLIP_END macro rather than calling
460  *    this directly
461  * => map must be locked by caller
462  */
463 
464 void
465 uvm_map_clip_end(map, entry, end)
466 	struct vm_map *map;
467 	struct vm_map_entry *entry;
468 	vaddr_t	end;
469 {
470 	struct vm_map_entry *	new_entry;
471 	vaddr_t new_adj; /* #bytes we move start forward */
472 
473 	/*
474 	 *	Create a new entry and insert it
475 	 *	AFTER the specified entry
476 	 */
477 
478 	new_entry = uvm_mapent_alloc(map);
479 	uvm_mapent_copy(entry, new_entry); /* entry -> new_entry */
480 
481 	new_entry->start = entry->end = end;
482 	new_adj = end - entry->start;
483 	if (new_entry->object.uvm_obj)
484 		new_entry->offset += new_adj;
485 
486 	if (entry->aref.ar_amap)
487 		amap_splitref(&entry->aref, &new_entry->aref, new_adj);
488 
489 	uvm_map_entry_link(map, entry, new_entry);
490 
491 	if (UVM_ET_ISSUBMAP(entry)) {
492 		/* ... unlikely to happen, but play it safe */
493 	 	uvm_map_reference(new_entry->object.sub_map);
494 	} else {
495 		if (UVM_ET_ISOBJ(entry) &&
496 		    entry->object.uvm_obj->pgops &&
497 		    entry->object.uvm_obj->pgops->pgo_reference)
498 			entry->object.uvm_obj->pgops->pgo_reference(
499 			    entry->object.uvm_obj);
500 	}
501 }
502 
503 
504 /*
505  *   M A P   -   m a i n   e n t r y   p o i n t
506  */
507 /*
508  * uvm_map: establish a valid mapping in a map
509  *
510  * => assume startp is page aligned.
511  * => assume size is a multiple of PAGE_SIZE.
512  * => assume sys_mmap provides enough of a "hint" to have us skip
513  *	over text/data/bss area.
514  * => map must be unlocked (we will lock it)
515  * => <uobj,uoffset> value meanings (4 cases):
516  *	 [1] <NULL,uoffset> 		== uoffset is a hint for PMAP_PREFER
517  *	 [2] <NULL,UVM_UNKNOWN_OFFSET>	== don't PMAP_PREFER
518  *	 [3] <uobj,uoffset>		== normal mapping
519  *	 [4] <uobj,UVM_UNKNOWN_OFFSET>	== uvm_map finds offset based on VA
520  *
521  *    case [4] is for kernel mappings where we don't know the offset until
522  *    we've found a virtual address.   note that kernel object offsets are
523  *    always relative to vm_map_min(kernel_map).
524  *
525  * => if `align' is non-zero, we try to align the virtual address to
526  *	the specified alignment.  this is only a hint; if we can't
527  *	do it, the address will be unaligned.  this is provided as
528  *	a mechanism for large pages.
529  *
530  * => XXXCDC: need way to map in external amap?
531  */
532 
533 int
534 uvm_map(map, startp, size, uobj, uoffset, align, flags)
535 	struct vm_map *map;
536 	vaddr_t *startp;	/* IN/OUT */
537 	vsize_t size;
538 	struct uvm_object *uobj;
539 	voff_t uoffset;
540 	vsize_t align;
541 	uvm_flag_t flags;
542 {
543 	struct vm_map_entry *prev_entry, *new_entry;
544 	vm_prot_t prot = UVM_PROTECTION(flags), maxprot =
545 	    UVM_MAXPROTECTION(flags);
546 	vm_inherit_t inherit = UVM_INHERIT(flags);
547 	int advice = UVM_ADVICE(flags);
548 	int error, merged = 0, kmap = (vm_map_pmap(map) == pmap_kernel());
549 	UVMHIST_FUNC("uvm_map");
550 	UVMHIST_CALLED(maphist);
551 
552 	UVMHIST_LOG(maphist, "(map=0x%x, *startp=0x%x, size=%d, flags=0x%x)",
553 	    map, *startp, size, flags);
554 	UVMHIST_LOG(maphist, "  uobj/offset 0x%x/%d", uobj, uoffset,0,0);
555 
556 	/*
557 	 * detect a popular device driver bug.
558 	 */
559 
560 	KASSERT(curproc != NULL || map->flags & VM_MAP_INTRSAFE);
561 
562 	/*
563 	 * check sanity of protection code
564 	 */
565 
566 	if ((prot & maxprot) != prot) {
567 		UVMHIST_LOG(maphist, "<- prot. failure:  prot=0x%x, max=0x%x",
568 		prot, maxprot,0,0);
569 		return EACCES;
570 	}
571 
572 	/*
573 	 * for pager_map, allocate the new entry first to avoid sleeping
574 	 * for memory while we have the map locked.
575 	 */
576 
577 	new_entry = NULL;
578 	if (map == pager_map) {
579 		new_entry = uvm_mapent_alloc(map);
580 	}
581 
582 	/*
583 	 * figure out where to put new VM range
584 	 */
585 
586 	if (vm_map_lock_try(map) == FALSE) {
587 		if (flags & UVM_FLAG_TRYLOCK) {
588 			if (new_entry) {
589 				uvm_mapent_free(new_entry);
590 			}
591 			return EAGAIN;
592 		}
593 		vm_map_lock(map); /* could sleep here */
594 	}
595 	if ((prev_entry = uvm_map_findspace(map, *startp, size, startp,
596 	    uobj, uoffset, align, flags)) == NULL) {
597 		UVMHIST_LOG(maphist,"<- uvm_map_findspace failed!",0,0,0,0);
598 		vm_map_unlock(map);
599 		if (new_entry) {
600 			uvm_mapent_free(new_entry);
601 		}
602 		return ENOMEM;
603 	}
604 
605 #ifdef PMAP_GROWKERNEL
606 	{
607 		/*
608 		 * If the kernel pmap can't map the requested space,
609 		 * then allocate more resources for it.
610 		 */
611 		if (map == kernel_map && uvm_maxkaddr < (*startp + size))
612 			uvm_maxkaddr = pmap_growkernel(*startp + size);
613 	}
614 #endif
615 
616 	UVMCNT_INCR(uvm_map_call);
617 
618 	/*
619 	 * if uobj is null, then uoffset is either a VAC hint for PMAP_PREFER
620 	 * [typically from uvm_map_reserve] or it is UVM_UNKNOWN_OFFSET.   in
621 	 * either case we want to zero it  before storing it in the map entry
622 	 * (because it looks strange and confusing when debugging...)
623 	 *
624 	 * if uobj is not null
625 	 *   if uoffset is not UVM_UNKNOWN_OFFSET then we have a normal mapping
626 	 *      and we do not need to change uoffset.
627 	 *   if uoffset is UVM_UNKNOWN_OFFSET then we need to find the offset
628 	 *      now (based on the starting address of the map).   this case is
629 	 *      for kernel object mappings where we don't know the offset until
630 	 *      the virtual address is found (with uvm_map_findspace).   the
631 	 *      offset is the distance we are from the start of the map.
632 	 */
633 
634 	if (uobj == NULL) {
635 		uoffset = 0;
636 	} else {
637 		if (uoffset == UVM_UNKNOWN_OFFSET) {
638 			KASSERT(UVM_OBJ_IS_KERN_OBJECT(uobj));
639 			uoffset = *startp - vm_map_min(kernel_map);
640 		}
641 	}
642 
643 	/*
644 	 * try and insert in map by extending previous entry, if possible.
645 	 * XXX: we don't try and pull back the next entry.   might be useful
646 	 * for a stack, but we are currently allocating our stack in advance.
647 	 */
648 
649 	if (flags & UVM_FLAG_NOMERGE)
650 		goto nomerge;
651 
652 	if (prev_entry->end == *startp &&
653 	    prev_entry != &map->header &&
654 	    prev_entry->object.uvm_obj == uobj) {
655 
656 		if (uobj && prev_entry->offset +
657 		    (prev_entry->end - prev_entry->start) != uoffset)
658 			goto forwardmerge;
659 
660 		if (UVM_ET_ISSUBMAP(prev_entry))
661 			goto forwardmerge;
662 
663 		if (prev_entry->protection != prot ||
664 		    prev_entry->max_protection != maxprot)
665 			goto forwardmerge;
666 
667 		if (prev_entry->inheritance != inherit ||
668 		    prev_entry->advice != advice)
669 			goto forwardmerge;
670 
671 		/* wiring status must match (new area is unwired) */
672 		if (VM_MAPENT_ISWIRED(prev_entry))
673 			goto forwardmerge;
674 
675 		/*
676 		 * can't extend a shared amap.  note: no need to lock amap to
677 		 * look at refs since we don't care about its exact value.
678 		 * if it is one (i.e. we have only reference) it will stay there
679 		 */
680 
681 		if (prev_entry->aref.ar_amap &&
682 		    amap_refs(prev_entry->aref.ar_amap) != 1) {
683 			goto forwardmerge;
684 		}
685 
686 		if (prev_entry->aref.ar_amap) {
687 			error = amap_extend(prev_entry, size);
688 			if (error) {
689 				vm_map_unlock(map);
690 				if (new_entry) {
691 					uvm_mapent_free(new_entry);
692 				}
693 				return error;
694 			}
695 		}
696 
697 		if (kmap)
698 			UVMCNT_INCR(map_kbackmerge);
699 		else
700 			UVMCNT_INCR(map_ubackmerge);
701 		UVMHIST_LOG(maphist,"  starting back merge", 0, 0, 0, 0);
702 
703 		/*
704 		 * drop our reference to uobj since we are extending a reference
705 		 * that we already have (the ref count can not drop to zero).
706 		 */
707 
708 		if (uobj && uobj->pgops->pgo_detach)
709 			uobj->pgops->pgo_detach(uobj);
710 
711 		prev_entry->end += size;
712 		map->size += size;
713 
714 		UVMHIST_LOG(maphist,"<- done (via backmerge)!", 0, 0, 0, 0);
715 		if (new_entry) {
716 			uvm_mapent_free(new_entry);
717 			new_entry = NULL;
718 		}
719 		merged++;
720 	}
721 
722 forwardmerge:
723 	if (prev_entry->next->start == (*startp + size) &&
724 	    prev_entry->next != &map->header &&
725 	    prev_entry->next->object.uvm_obj == uobj) {
726 
727 		if (uobj && prev_entry->next->offset != uoffset + size)
728 			goto nomerge;
729 
730 		if (UVM_ET_ISSUBMAP(prev_entry->next))
731 			goto nomerge;
732 
733 		if (prev_entry->next->protection != prot ||
734 		    prev_entry->next->max_protection != maxprot)
735 			goto nomerge;
736 
737 		if (prev_entry->next->inheritance != inherit ||
738 		    prev_entry->next->advice != advice)
739 			goto nomerge;
740 
741 		/* wiring status must match (new area is unwired) */
742 		if (VM_MAPENT_ISWIRED(prev_entry->next))
743 			goto nomerge;
744 
745 		/*
746 		 * can't extend a shared amap.  note: no need to lock amap to
747 		 * look at refs since we don't care about its exact value.
748 		 * if it is one (i.e. we have only reference) it will stay there
749 		 */
750 
751 		if (prev_entry->next->aref.ar_amap &&
752 		    amap_refs(prev_entry->next->aref.ar_amap) != 1) {
753 			goto nomerge;
754 		}
755 
756 		/* got it...almost */
757 
758 		if (prev_entry->next->aref.ar_amap) {
759 			/*
760 			 * XXX if not for this, we could have merged
761 			 * forwards, so the number of times we missed
762 			 * a *possible* chance to merge more.  note,
763 			 * however, that only processes use amaps,
764 			 * and they only *VERY* rarely present solely
765 			 * forward mergeable allocations.  -- @@@
766 			 */
767 			if (kmap)
768 				UVMCNT_INCR(map_kforwmerge_fail);
769 			else
770 				UVMCNT_INCR(map_uforwmerge_fail);
771 			goto nomerge;
772 		}
773 
774 		if (merged) {
775 			if (kmap) {
776 				UVMCNT_DECR(map_kbackmerge);
777 				UVMCNT_INCR(map_kbimerge);
778 			} else {
779 				UVMCNT_DECR(map_kbackmerge);
780 				UVMCNT_INCR(map_kbimerge);
781 			}
782 		}
783 		else {
784 			if (kmap)
785 				UVMCNT_INCR(map_kforwmerge);
786 			else
787 				UVMCNT_INCR(map_uforwmerge);
788 		}
789 		UVMHIST_LOG(maphist,"  starting forward merge", 0, 0, 0, 0);
790 
791 		/*
792 		 * drop our reference to uobj since we are extending a reference
793 		 * that we already have (the ref count can not drop to zero).
794 		 * (if merged, we've already detached)
795 		 */
796 		if (uobj && uobj->pgops->pgo_detach && !merged)
797 			uobj->pgops->pgo_detach(uobj);
798 
799 		/*
800 		 * XXX call amap_extend() to merge backwards here.  -- @@@
801 		 */
802 
803 		if (merged) {
804 			struct vm_map_entry *dead = prev_entry->next;
805 			prev_entry->end = dead->end;
806 			uvm_map_entry_unlink(map, dead);
807 			uvm_mapent_free(dead);
808 		} else {
809 			prev_entry->next->start -= size;
810 			map->size += size;
811 			if (uobj)
812 				prev_entry->next->offset = uoffset;
813 		}
814 
815 		UVMHIST_LOG(maphist,"<- done forwardmerge", 0, 0, 0, 0);
816 		if (new_entry) {
817 			uvm_mapent_free(new_entry);
818 			new_entry = NULL;
819 		}
820 		merged++;
821 	}
822 
823 nomerge:
824 	if (!merged) {
825 		UVMHIST_LOG(maphist,"  allocating new map entry", 0, 0, 0, 0);
826 		if (kmap)
827 			UVMCNT_INCR(map_knomerge);
828 		else
829 			UVMCNT_INCR(map_unomerge);
830 
831 		/*
832 		 * allocate new entry and link it in.
833 		 */
834 
835 		if (new_entry == NULL) {
836 			new_entry = uvm_mapent_alloc(map);
837 		}
838 		new_entry->start = *startp;
839 		new_entry->end = new_entry->start + size;
840 		new_entry->object.uvm_obj = uobj;
841 		new_entry->offset = uoffset;
842 
843 		if (uobj)
844 			new_entry->etype = UVM_ET_OBJ;
845 		else
846 			new_entry->etype = 0;
847 
848 		if (flags & UVM_FLAG_COPYONW) {
849 			new_entry->etype |= UVM_ET_COPYONWRITE;
850 			if ((flags & UVM_FLAG_OVERLAY) == 0)
851 				new_entry->etype |= UVM_ET_NEEDSCOPY;
852 		}
853 
854 		new_entry->protection = prot;
855 		new_entry->max_protection = maxprot;
856 		new_entry->inheritance = inherit;
857 		new_entry->wired_count = 0;
858 		new_entry->advice = advice;
859 		if (flags & UVM_FLAG_OVERLAY) {
860 
861 			/*
862 			 * to_add: for BSS we overallocate a little since we
863 			 * are likely to extend
864 			 */
865 
866 			vaddr_t to_add = (flags & UVM_FLAG_AMAPPAD) ?
867 				UVM_AMAP_CHUNK << PAGE_SHIFT : 0;
868 			struct vm_amap *amap = amap_alloc(size, to_add, M_WAITOK);
869 			new_entry->aref.ar_pageoff = 0;
870 			new_entry->aref.ar_amap = amap;
871 		} else {
872 			new_entry->aref.ar_pageoff = 0;
873 			new_entry->aref.ar_amap = NULL;
874 		}
875 		uvm_map_entry_link(map, prev_entry, new_entry);
876 		map->size += size;
877 
878 		/*
879 		 * Update the free space hint
880 		 */
881 
882 		if ((map->first_free == prev_entry) &&
883 		    (prev_entry->end >= new_entry->start))
884 			map->first_free = new_entry;
885 	}
886 
887 	UVMHIST_LOG(maphist,"<- done!", 0, 0, 0, 0);
888 	vm_map_unlock(map);
889 	return 0;
890 }
891 
892 /*
893  * uvm_map_lookup_entry: find map entry at or before an address
894  *
895  * => map must at least be read-locked by caller
896  * => entry is returned in "entry"
897  * => return value is true if address is in the returned entry
898  */
899 
900 boolean_t
901 uvm_map_lookup_entry(map, address, entry)
902 	struct vm_map *map;
903 	vaddr_t	address;
904 	struct vm_map_entry **entry;		/* OUT */
905 {
906 	struct vm_map_entry *cur;
907 	struct vm_map_entry *last;
908 	UVMHIST_FUNC("uvm_map_lookup_entry");
909 	UVMHIST_CALLED(maphist);
910 
911 	UVMHIST_LOG(maphist,"(map=0x%x,addr=0x%x,ent=0x%x)",
912 	    map, address, entry, 0);
913 
914 	/*
915 	 * start looking either from the head of the
916 	 * list, or from the hint.
917 	 */
918 
919 	simple_lock(&map->hint_lock);
920 	cur = map->hint;
921 	simple_unlock(&map->hint_lock);
922 
923 	if (cur == &map->header)
924 		cur = cur->next;
925 
926 	UVMCNT_INCR(uvm_mlk_call);
927 	if (address >= cur->start) {
928 
929 	    	/*
930 		 * go from hint to end of list.
931 		 *
932 		 * but first, make a quick check to see if
933 		 * we are already looking at the entry we
934 		 * want (which is usually the case).
935 		 * note also that we don't need to save the hint
936 		 * here... it is the same hint (unless we are
937 		 * at the header, in which case the hint didn't
938 		 * buy us anything anyway).
939 		 */
940 
941 		last = &map->header;
942 		if ((cur != last) && (cur->end > address)) {
943 			UVMCNT_INCR(uvm_mlk_hint);
944 			*entry = cur;
945 			UVMHIST_LOG(maphist,"<- got it via hint (0x%x)",
946 			    cur, 0, 0, 0);
947 			return (TRUE);
948 		}
949 	} else {
950 
951 	    	/*
952 		 * go from start to hint, *inclusively*
953 		 */
954 
955 		last = cur->next;
956 		cur = map->header.next;
957 	}
958 
959 	/*
960 	 * search linearly
961 	 */
962 
963 	while (cur != last) {
964 		if (cur->end > address) {
965 			if (address >= cur->start) {
966 			    	/*
967 				 * save this lookup for future
968 				 * hints, and return
969 				 */
970 
971 				*entry = cur;
972 				SAVE_HINT(map, map->hint, cur);
973 				UVMHIST_LOG(maphist,"<- search got it (0x%x)",
974 					cur, 0, 0, 0);
975 				return (TRUE);
976 			}
977 			break;
978 		}
979 		cur = cur->next;
980 	}
981 	*entry = cur->prev;
982 	SAVE_HINT(map, map->hint, *entry);
983 	UVMHIST_LOG(maphist,"<- failed!",0,0,0,0);
984 	return (FALSE);
985 }
986 
987 /*
988  * uvm_map_findspace: find "length" sized space in "map".
989  *
990  * => "hint" is a hint about where we want it, unless FINDSPACE_FIXED is
991  *	set (in which case we insist on using "hint").
992  * => "result" is VA returned
993  * => uobj/uoffset are to be used to handle VAC alignment, if required
994  * => if `align' is non-zero, we attempt to align to that value.
995  * => caller must at least have read-locked map
996  * => returns NULL on failure, or pointer to prev. map entry if success
997  * => note this is a cross between the old vm_map_findspace and vm_map_find
998  */
999 
1000 struct vm_map_entry *
1001 uvm_map_findspace(map, hint, length, result, uobj, uoffset, align, flags)
1002 	struct vm_map *map;
1003 	vaddr_t hint;
1004 	vsize_t length;
1005 	vaddr_t *result; /* OUT */
1006 	struct uvm_object *uobj;
1007 	voff_t uoffset;
1008 	vsize_t align;
1009 	int flags;
1010 {
1011 	struct vm_map_entry *entry, *next, *tmp;
1012 	vaddr_t end, orig_hint;
1013 	UVMHIST_FUNC("uvm_map_findspace");
1014 	UVMHIST_CALLED(maphist);
1015 
1016 	UVMHIST_LOG(maphist, "(map=0x%x, hint=0x%x, len=%d, flags=0x%x)",
1017 		    map, hint, length, flags);
1018 	KASSERT((align & (align - 1)) == 0);
1019 	KASSERT((flags & UVM_FLAG_FIXED) == 0 || align == 0);
1020 
1021 	/*
1022 	 * remember the original hint.  if we are aligning, then we
1023 	 * may have to try again with no alignment constraint if
1024 	 * we fail the first time.
1025 	 */
1026 
1027 	orig_hint = hint;
1028 	if (hint < map->min_offset) {	/* check ranges ... */
1029 		if (flags & UVM_FLAG_FIXED) {
1030 			UVMHIST_LOG(maphist,"<- VA below map range",0,0,0,0);
1031 			return(NULL);
1032 		}
1033 		hint = map->min_offset;
1034 	}
1035 	if (hint > map->max_offset) {
1036 		UVMHIST_LOG(maphist,"<- VA 0x%x > range [0x%x->0x%x]",
1037 				hint, map->min_offset, map->max_offset, 0);
1038 		return(NULL);
1039 	}
1040 
1041 	/*
1042 	 * Look for the first possible address; if there's already
1043 	 * something at this address, we have to start after it.
1044 	 */
1045 
1046 	if ((flags & UVM_FLAG_FIXED) == 0 && hint == map->min_offset) {
1047 		if ((entry = map->first_free) != &map->header)
1048 			hint = entry->end;
1049 	} else {
1050 		if (uvm_map_lookup_entry(map, hint, &tmp)) {
1051 			/* "hint" address already in use ... */
1052 			if (flags & UVM_FLAG_FIXED) {
1053 				UVMHIST_LOG(maphist,"<- fixed & VA in use",
1054 				    0, 0, 0, 0);
1055 				return(NULL);
1056 			}
1057 			hint = tmp->end;
1058 		}
1059 		entry = tmp;
1060 	}
1061 
1062 	/*
1063 	 * Look through the rest of the map, trying to fit a new region in
1064 	 * the gap between existing regions, or after the very last region.
1065 	 * note: entry->end   = base VA of current gap,
1066 	 *	 next->start  = VA of end of current gap
1067 	 */
1068 
1069 	for (;; hint = (entry = next)->end) {
1070 
1071 		/*
1072 		 * Find the end of the proposed new region.  Be sure we didn't
1073 		 * go beyond the end of the map, or wrap around the address;
1074 		 * if so, we lose.  Otherwise, if this is the last entry, or
1075 		 * if the proposed new region fits before the next entry, we
1076 		 * win.
1077 		 */
1078 
1079 #ifdef PMAP_PREFER
1080 		/*
1081 		 * push hint forward as needed to avoid VAC alias problems.
1082 		 * we only do this if a valid offset is specified.
1083 		 */
1084 
1085 		if ((flags & UVM_FLAG_FIXED) == 0 &&
1086 		    uoffset != UVM_UNKNOWN_OFFSET)
1087 			PMAP_PREFER(uoffset, &hint);
1088 #endif
1089 		if (align != 0) {
1090 			if ((hint & (align - 1)) != 0)
1091 				hint = roundup(hint, align);
1092 			/*
1093 			 * XXX Should we PMAP_PREFER() here again?
1094 			 */
1095 		}
1096 		end = hint + length;
1097 		if (end > map->max_offset || end < hint) {
1098 			UVMHIST_LOG(maphist,"<- failed (off end)", 0,0,0,0);
1099 			if (align != 0) {
1100 				UVMHIST_LOG(maphist,
1101 				    "calling recursively, no align",
1102 				    0,0,0,0);
1103 				return (uvm_map_findspace(map, orig_hint,
1104 				    length, result, uobj, uoffset, 0, flags));
1105 			}
1106 			return (NULL);
1107 		}
1108 		next = entry->next;
1109 		if (next == &map->header || next->start >= end)
1110 			break;
1111 		if (flags & UVM_FLAG_FIXED) {
1112 			UVMHIST_LOG(maphist,"<- fixed mapping failed", 0,0,0,0);
1113 			return(NULL); /* only one shot at it ... */
1114 		}
1115 	}
1116 	SAVE_HINT(map, map->hint, entry);
1117 	*result = hint;
1118 	UVMHIST_LOG(maphist,"<- got it!  (result=0x%x)", hint, 0,0,0);
1119 	return (entry);
1120 }
1121 
1122 /*
1123  *   U N M A P   -   m a i n   h e l p e r   f u n c t i o n s
1124  */
1125 
1126 /*
1127  * uvm_unmap_remove: remove mappings from a vm_map (from "start" up to "stop")
1128  *
1129  * => caller must check alignment and size
1130  * => map must be locked by caller
1131  * => we return a list of map entries that we've remove from the map
1132  *    in "entry_list"
1133  */
1134 
1135 void
1136 uvm_unmap_remove(map, start, end, entry_list)
1137 	struct vm_map *map;
1138 	vaddr_t start, end;
1139 	struct vm_map_entry **entry_list;	/* OUT */
1140 {
1141 	struct vm_map_entry *entry, *first_entry, *next;
1142 	vaddr_t len;
1143 	UVMHIST_FUNC("uvm_unmap_remove"); UVMHIST_CALLED(maphist);
1144 
1145 	UVMHIST_LOG(maphist,"(map=0x%x, start=0x%x, end=0x%x)",
1146 	    map, start, end, 0);
1147 	VM_MAP_RANGE_CHECK(map, start, end);
1148 
1149 	/*
1150 	 * find first entry
1151 	 */
1152 
1153 	if (uvm_map_lookup_entry(map, start, &first_entry) == TRUE) {
1154 		/* clip and go... */
1155 		entry = first_entry;
1156 		UVM_MAP_CLIP_START(map, entry, start);
1157 		/* critical!  prevents stale hint */
1158 		SAVE_HINT(map, entry, entry->prev);
1159 	} else {
1160 		entry = first_entry->next;
1161 	}
1162 
1163 	/*
1164 	 * Save the free space hint
1165 	 */
1166 
1167 	if (map->first_free->start >= start)
1168 		map->first_free = entry->prev;
1169 
1170 	/*
1171 	 * note: we now re-use first_entry for a different task.  we remove
1172 	 * a number of map entries from the map and save them in a linked
1173 	 * list headed by "first_entry".  once we remove them from the map
1174 	 * the caller should unlock the map and drop the references to the
1175 	 * backing objects [c.f. uvm_unmap_detach].  the object is to
1176 	 * separate unmapping from reference dropping.  why?
1177 	 *   [1] the map has to be locked for unmapping
1178 	 *   [2] the map need not be locked for reference dropping
1179 	 *   [3] dropping references may trigger pager I/O, and if we hit
1180 	 *       a pager that does synchronous I/O we may have to wait for it.
1181 	 *   [4] we would like all waiting for I/O to occur with maps unlocked
1182 	 *       so that we don't block other threads.
1183 	 */
1184 
1185 	first_entry = NULL;
1186 	*entry_list = NULL;
1187 
1188 	/*
1189 	 * break up the area into map entry sized regions and unmap.  note
1190 	 * that all mappings have to be removed before we can even consider
1191 	 * dropping references to amaps or VM objects (otherwise we could end
1192 	 * up with a mapping to a page on the free list which would be very bad)
1193 	 */
1194 
1195 	while ((entry != &map->header) && (entry->start < end)) {
1196 		UVM_MAP_CLIP_END(map, entry, end);
1197 		next = entry->next;
1198 		len = entry->end - entry->start;
1199 
1200 		/*
1201 		 * unwire before removing addresses from the pmap; otherwise
1202 		 * unwiring will put the entries back into the pmap (XXX).
1203 		 */
1204 
1205 		if (VM_MAPENT_ISWIRED(entry)) {
1206 			uvm_map_entry_unwire(map, entry);
1207 		}
1208 		if ((map->flags & VM_MAP_PAGEABLE) == 0) {
1209 
1210 			/*
1211 			 * if the map is non-pageable, any pages mapped there
1212 			 * must be wired and entered with pmap_kenter_pa(),
1213 			 * and we should free any such pages immediately.
1214 			 * this is mostly used for kmem_map and mb_map.
1215 			 */
1216 
1217 			uvm_km_pgremove_intrsafe(entry->start, entry->end);
1218 			pmap_kremove(entry->start, len);
1219 		} else if (UVM_ET_ISOBJ(entry) &&
1220 			   UVM_OBJ_IS_KERN_OBJECT(entry->object.uvm_obj)) {
1221 			KASSERT(vm_map_pmap(map) == pmap_kernel());
1222 
1223 			/*
1224 			 * note: kernel object mappings are currently used in
1225 			 * two ways:
1226 			 *  [1] "normal" mappings of pages in the kernel object
1227 			 *  [2] uvm_km_valloc'd allocations in which we
1228 			 *      pmap_enter in some non-kernel-object page
1229 			 *      (e.g. vmapbuf).
1230 			 *
1231 			 * for case [1], we need to remove the mapping from
1232 			 * the pmap and then remove the page from the kernel
1233 			 * object (because, once pages in a kernel object are
1234 			 * unmapped they are no longer needed, unlike, say,
1235 			 * a vnode where you might want the data to persist
1236 			 * until flushed out of a queue).
1237 			 *
1238 			 * for case [2], we need to remove the mapping from
1239 			 * the pmap.  there shouldn't be any pages at the
1240 			 * specified offset in the kernel object [but it
1241 			 * doesn't hurt to call uvm_km_pgremove just to be
1242 			 * safe?]
1243 			 *
1244 			 * uvm_km_pgremove currently does the following:
1245 			 *   for pages in the kernel object in range:
1246 			 *     - drops the swap slot
1247 			 *     - uvm_pagefree the page
1248 			 */
1249 
1250 			/*
1251 			 * remove mappings from pmap and drop the pages
1252 			 * from the object.  offsets are always relative
1253 			 * to vm_map_min(kernel_map).
1254 			 */
1255 
1256 			pmap_remove(pmap_kernel(), entry->start,
1257 			    entry->start + len);
1258 			uvm_km_pgremove(entry->object.uvm_obj,
1259 			    entry->start - vm_map_min(kernel_map),
1260 			    entry->end - vm_map_min(kernel_map));
1261 
1262 			/*
1263 			 * null out kernel_object reference, we've just
1264 			 * dropped it
1265 			 */
1266 
1267 			entry->etype &= ~UVM_ET_OBJ;
1268 			entry->object.uvm_obj = NULL;
1269 		} else if (UVM_ET_ISOBJ(entry) || entry->aref.ar_amap) {
1270 
1271 			/*
1272 		 	 * remove mappings the standard way.
1273 		 	 */
1274 
1275 			pmap_remove(map->pmap, entry->start, entry->end);
1276 		}
1277 
1278 		/*
1279 		 * remove entry from map and put it on our list of entries
1280 		 * that we've nuked.  then go to next entry.
1281 		 */
1282 
1283 		UVMHIST_LOG(maphist, "  removed map entry 0x%x", entry, 0, 0,0);
1284 
1285 		/* critical!  prevents stale hint */
1286 		SAVE_HINT(map, entry, entry->prev);
1287 
1288 		uvm_map_entry_unlink(map, entry);
1289 		map->size -= len;
1290 		entry->next = first_entry;
1291 		first_entry = entry;
1292 		entry = next;
1293 	}
1294 	if ((map->flags & VM_MAP_DYING) == 0) {
1295 		pmap_update(vm_map_pmap(map));
1296 	}
1297 
1298 	/*
1299 	 * now we've cleaned up the map and are ready for the caller to drop
1300 	 * references to the mapped objects.
1301 	 */
1302 
1303 	*entry_list = first_entry;
1304 	UVMHIST_LOG(maphist,"<- done!", 0, 0, 0, 0);
1305 }
1306 
1307 /*
1308  * uvm_unmap_detach: drop references in a chain of map entries
1309  *
1310  * => we will free the map entries as we traverse the list.
1311  */
1312 
1313 void
1314 uvm_unmap_detach(first_entry, flags)
1315 	struct vm_map_entry *first_entry;
1316 	int flags;
1317 {
1318 	struct vm_map_entry *next_entry;
1319 	UVMHIST_FUNC("uvm_unmap_detach"); UVMHIST_CALLED(maphist);
1320 
1321 	while (first_entry) {
1322 		KASSERT(!VM_MAPENT_ISWIRED(first_entry));
1323 		UVMHIST_LOG(maphist,
1324 		    "  detach 0x%x: amap=0x%x, obj=0x%x, submap?=%d",
1325 		    first_entry, first_entry->aref.ar_amap,
1326 		    first_entry->object.uvm_obj,
1327 		    UVM_ET_ISSUBMAP(first_entry));
1328 
1329 		/*
1330 		 * drop reference to amap, if we've got one
1331 		 */
1332 
1333 		if (first_entry->aref.ar_amap)
1334 			uvm_map_unreference_amap(first_entry, flags);
1335 
1336 		/*
1337 		 * drop reference to our backing object, if we've got one
1338 		 */
1339 
1340 		KASSERT(!UVM_ET_ISSUBMAP(first_entry));
1341 		if (UVM_ET_ISOBJ(first_entry) &&
1342 		    first_entry->object.uvm_obj->pgops->pgo_detach) {
1343 			(*first_entry->object.uvm_obj->pgops->pgo_detach)
1344 				(first_entry->object.uvm_obj);
1345 		}
1346 		next_entry = first_entry->next;
1347 		uvm_mapent_free(first_entry);
1348 		first_entry = next_entry;
1349 	}
1350 	UVMHIST_LOG(maphist, "<- done", 0,0,0,0);
1351 }
1352 
1353 /*
1354  *   E X T R A C T I O N   F U N C T I O N S
1355  */
1356 
1357 /*
1358  * uvm_map_reserve: reserve space in a vm_map for future use.
1359  *
1360  * => we reserve space in a map by putting a dummy map entry in the
1361  *    map (dummy means obj=NULL, amap=NULL, prot=VM_PROT_NONE)
1362  * => map should be unlocked (we will write lock it)
1363  * => we return true if we were able to reserve space
1364  * => XXXCDC: should be inline?
1365  */
1366 
1367 int
1368 uvm_map_reserve(map, size, offset, align, raddr)
1369 	struct vm_map *map;
1370 	vsize_t size;
1371 	vaddr_t offset;	/* hint for pmap_prefer */
1372 	vsize_t align;	/* alignment hint */
1373 	vaddr_t *raddr;	/* IN:hint, OUT: reserved VA */
1374 {
1375 	UVMHIST_FUNC("uvm_map_reserve"); UVMHIST_CALLED(maphist);
1376 
1377 	UVMHIST_LOG(maphist, "(map=0x%x, size=0x%x, offset=0x%x,addr=0x%x)",
1378 	      map,size,offset,raddr);
1379 
1380 	size = round_page(size);
1381 	if (*raddr < vm_map_min(map))
1382 		*raddr = vm_map_min(map);                /* hint */
1383 
1384 	/*
1385 	 * reserve some virtual space.
1386 	 */
1387 
1388 	if (uvm_map(map, raddr, size, NULL, offset, 0,
1389 	    UVM_MAPFLAG(UVM_PROT_NONE, UVM_PROT_NONE, UVM_INH_NONE,
1390 	    UVM_ADV_RANDOM, UVM_FLAG_NOMERGE)) != 0) {
1391 	    UVMHIST_LOG(maphist, "<- done (no VM)", 0,0,0,0);
1392 		return (FALSE);
1393 	}
1394 
1395 	UVMHIST_LOG(maphist, "<- done (*raddr=0x%x)", *raddr,0,0,0);
1396 	return (TRUE);
1397 }
1398 
1399 /*
1400  * uvm_map_replace: replace a reserved (blank) area of memory with
1401  * real mappings.
1402  *
1403  * => caller must WRITE-LOCK the map
1404  * => we return TRUE if replacement was a success
1405  * => we expect the newents chain to have nnewents entrys on it and
1406  *    we expect newents->prev to point to the last entry on the list
1407  * => note newents is allowed to be NULL
1408  */
1409 
1410 int
1411 uvm_map_replace(map, start, end, newents, nnewents)
1412 	struct vm_map *map;
1413 	vaddr_t start, end;
1414 	struct vm_map_entry *newents;
1415 	int nnewents;
1416 {
1417 	struct vm_map_entry *oldent, *last;
1418 
1419 	/*
1420 	 * first find the blank map entry at the specified address
1421 	 */
1422 
1423 	if (!uvm_map_lookup_entry(map, start, &oldent)) {
1424 		return(FALSE);
1425 	}
1426 
1427 	/*
1428 	 * check to make sure we have a proper blank entry
1429 	 */
1430 
1431 	if (oldent->start != start || oldent->end != end ||
1432 	    oldent->object.uvm_obj != NULL || oldent->aref.ar_amap != NULL) {
1433 		return (FALSE);
1434 	}
1435 
1436 #ifdef DIAGNOSTIC
1437 
1438 	/*
1439 	 * sanity check the newents chain
1440 	 */
1441 
1442 	{
1443 		struct vm_map_entry *tmpent = newents;
1444 		int nent = 0;
1445 		vaddr_t cur = start;
1446 
1447 		while (tmpent) {
1448 			nent++;
1449 			if (tmpent->start < cur)
1450 				panic("uvm_map_replace1");
1451 			if (tmpent->start > tmpent->end || tmpent->end > end) {
1452 		printf("tmpent->start=0x%lx, tmpent->end=0x%lx, end=0x%lx\n",
1453 			    tmpent->start, tmpent->end, end);
1454 				panic("uvm_map_replace2");
1455 			}
1456 			cur = tmpent->end;
1457 			if (tmpent->next) {
1458 				if (tmpent->next->prev != tmpent)
1459 					panic("uvm_map_replace3");
1460 			} else {
1461 				if (newents->prev != tmpent)
1462 					panic("uvm_map_replace4");
1463 			}
1464 			tmpent = tmpent->next;
1465 		}
1466 		if (nent != nnewents)
1467 			panic("uvm_map_replace5");
1468 	}
1469 #endif
1470 
1471 	/*
1472 	 * map entry is a valid blank!   replace it.   (this does all the
1473 	 * work of map entry link/unlink...).
1474 	 */
1475 
1476 	if (newents) {
1477 		last = newents->prev;
1478 
1479 		/* critical: flush stale hints out of map */
1480 		SAVE_HINT(map, map->hint, newents);
1481 		if (map->first_free == oldent)
1482 			map->first_free = last;
1483 
1484 		last->next = oldent->next;
1485 		last->next->prev = last;
1486 		newents->prev = oldent->prev;
1487 		newents->prev->next = newents;
1488 		map->nentries = map->nentries + (nnewents - 1);
1489 
1490 	} else {
1491 
1492 		/* critical: flush stale hints out of map */
1493 		SAVE_HINT(map, map->hint, oldent->prev);
1494 		if (map->first_free == oldent)
1495 			map->first_free = oldent->prev;
1496 
1497 		/* NULL list of new entries: just remove the old one */
1498 		uvm_map_entry_unlink(map, oldent);
1499 	}
1500 
1501 
1502 	/*
1503 	 * now we can free the old blank entry, unlock the map and return.
1504 	 */
1505 
1506 	uvm_mapent_free(oldent);
1507 	return(TRUE);
1508 }
1509 
1510 /*
1511  * uvm_map_extract: extract a mapping from a map and put it somewhere
1512  *	(maybe removing the old mapping)
1513  *
1514  * => maps should be unlocked (we will write lock them)
1515  * => returns 0 on success, error code otherwise
1516  * => start must be page aligned
1517  * => len must be page sized
1518  * => flags:
1519  *      UVM_EXTRACT_REMOVE: remove mappings from srcmap
1520  *      UVM_EXTRACT_CONTIG: abort if unmapped area (advisory only)
1521  *      UVM_EXTRACT_QREF: for a temporary extraction do quick obj refs
1522  *      UVM_EXTRACT_FIXPROT: set prot to maxprot as we go
1523  *    >>>NOTE: if you set REMOVE, you are not allowed to use CONTIG or QREF!<<<
1524  *    >>>NOTE: QREF's must be unmapped via the QREF path, thus should only
1525  *             be used from within the kernel in a kernel level map <<<
1526  */
1527 
1528 int
1529 uvm_map_extract(srcmap, start, len, dstmap, dstaddrp, flags)
1530 	struct vm_map *srcmap, *dstmap;
1531 	vaddr_t start, *dstaddrp;
1532 	vsize_t len;
1533 	int flags;
1534 {
1535 	vaddr_t dstaddr, end, newend, oldoffset, fudge, orig_fudge,
1536 	    oldstart;
1537 	struct vm_map_entry *chain, *endchain, *entry, *orig_entry, *newentry,
1538 	    *deadentry, *oldentry;
1539 	vsize_t elen;
1540 	int nchain, error, copy_ok;
1541 	UVMHIST_FUNC("uvm_map_extract"); UVMHIST_CALLED(maphist);
1542 
1543 	UVMHIST_LOG(maphist,"(srcmap=0x%x,start=0x%x, len=0x%x", srcmap, start,
1544 	    len,0);
1545 	UVMHIST_LOG(maphist," ...,dstmap=0x%x, flags=0x%x)", dstmap,flags,0,0);
1546 
1547 	/*
1548 	 * step 0: sanity check: start must be on a page boundary, length
1549 	 * must be page sized.  can't ask for CONTIG/QREF if you asked for
1550 	 * REMOVE.
1551 	 */
1552 
1553 	KASSERT((start & PAGE_MASK) == 0 && (len & PAGE_MASK) == 0);
1554 	KASSERT((flags & UVM_EXTRACT_REMOVE) == 0 ||
1555 		(flags & (UVM_EXTRACT_CONTIG|UVM_EXTRACT_QREF)) == 0);
1556 
1557 	/*
1558 	 * step 1: reserve space in the target map for the extracted area
1559 	 */
1560 
1561 	dstaddr = vm_map_min(dstmap);
1562 	if (uvm_map_reserve(dstmap, len, start, 0, &dstaddr) == FALSE)
1563 		return(ENOMEM);
1564 	*dstaddrp = dstaddr;	/* pass address back to caller */
1565 	UVMHIST_LOG(maphist, "  dstaddr=0x%x", dstaddr,0,0,0);
1566 
1567 	/*
1568 	 * step 2: setup for the extraction process loop by init'ing the
1569 	 * map entry chain, locking src map, and looking up the first useful
1570 	 * entry in the map.
1571 	 */
1572 
1573 	end = start + len;
1574 	newend = dstaddr + len;
1575 	chain = endchain = NULL;
1576 	nchain = 0;
1577 	vm_map_lock(srcmap);
1578 
1579 	if (uvm_map_lookup_entry(srcmap, start, &entry)) {
1580 
1581 		/* "start" is within an entry */
1582 		if (flags & UVM_EXTRACT_QREF) {
1583 
1584 			/*
1585 			 * for quick references we don't clip the entry, so
1586 			 * the entry may map space "before" the starting
1587 			 * virtual address... this is the "fudge" factor
1588 			 * (which can be non-zero only the first time
1589 			 * through the "while" loop in step 3).
1590 			 */
1591 
1592 			fudge = start - entry->start;
1593 		} else {
1594 
1595 			/*
1596 			 * normal reference: we clip the map to fit (thus
1597 			 * fudge is zero)
1598 			 */
1599 
1600 			UVM_MAP_CLIP_START(srcmap, entry, start);
1601 			SAVE_HINT(srcmap, srcmap->hint, entry->prev);
1602 			fudge = 0;
1603 		}
1604 	} else {
1605 
1606 		/* "start" is not within an entry ... skip to next entry */
1607 		if (flags & UVM_EXTRACT_CONTIG) {
1608 			error = EINVAL;
1609 			goto bad;    /* definite hole here ... */
1610 		}
1611 
1612 		entry = entry->next;
1613 		fudge = 0;
1614 	}
1615 
1616 	/* save values from srcmap for step 6 */
1617 	orig_entry = entry;
1618 	orig_fudge = fudge;
1619 
1620 	/*
1621 	 * step 3: now start looping through the map entries, extracting
1622 	 * as we go.
1623 	 */
1624 
1625 	while (entry->start < end && entry != &srcmap->header) {
1626 
1627 		/* if we are not doing a quick reference, clip it */
1628 		if ((flags & UVM_EXTRACT_QREF) == 0)
1629 			UVM_MAP_CLIP_END(srcmap, entry, end);
1630 
1631 		/* clear needs_copy (allow chunking) */
1632 		if (UVM_ET_ISNEEDSCOPY(entry)) {
1633 			if (fudge)
1634 				oldstart = entry->start;
1635 			else
1636 				oldstart = 0;	/* XXX: gcc */
1637 			amap_copy(srcmap, entry, M_NOWAIT, TRUE, start, end);
1638 			if (UVM_ET_ISNEEDSCOPY(entry)) {  /* failed? */
1639 				error = ENOMEM;
1640 				goto bad;
1641 			}
1642 
1643 			/* amap_copy could clip (during chunk)!  update fudge */
1644 			if (fudge) {
1645 				fudge = fudge - (entry->start - oldstart);
1646 				orig_fudge = fudge;
1647 			}
1648 		}
1649 
1650 		/* calculate the offset of this from "start" */
1651 		oldoffset = (entry->start + fudge) - start;
1652 
1653 		/* allocate a new map entry */
1654 		newentry = uvm_mapent_alloc(dstmap);
1655 		if (newentry == NULL) {
1656 			error = ENOMEM;
1657 			goto bad;
1658 		}
1659 
1660 		/* set up new map entry */
1661 		newentry->next = NULL;
1662 		newentry->prev = endchain;
1663 		newentry->start = dstaddr + oldoffset;
1664 		newentry->end =
1665 		    newentry->start + (entry->end - (entry->start + fudge));
1666 		if (newentry->end > newend || newentry->end < newentry->start)
1667 			newentry->end = newend;
1668 		newentry->object.uvm_obj = entry->object.uvm_obj;
1669 		if (newentry->object.uvm_obj) {
1670 			if (newentry->object.uvm_obj->pgops->pgo_reference)
1671 				newentry->object.uvm_obj->pgops->
1672 				    pgo_reference(newentry->object.uvm_obj);
1673 				newentry->offset = entry->offset + fudge;
1674 		} else {
1675 			newentry->offset = 0;
1676 		}
1677 		newentry->etype = entry->etype;
1678 		newentry->protection = (flags & UVM_EXTRACT_FIXPROT) ?
1679 			entry->max_protection : entry->protection;
1680 		newentry->max_protection = entry->max_protection;
1681 		newentry->inheritance = entry->inheritance;
1682 		newentry->wired_count = 0;
1683 		newentry->aref.ar_amap = entry->aref.ar_amap;
1684 		if (newentry->aref.ar_amap) {
1685 			newentry->aref.ar_pageoff =
1686 			    entry->aref.ar_pageoff + (fudge >> PAGE_SHIFT);
1687 			uvm_map_reference_amap(newentry, AMAP_SHARED |
1688 			    ((flags & UVM_EXTRACT_QREF) ? AMAP_REFALL : 0));
1689 		} else {
1690 			newentry->aref.ar_pageoff = 0;
1691 		}
1692 		newentry->advice = entry->advice;
1693 
1694 		/* now link it on the chain */
1695 		nchain++;
1696 		if (endchain == NULL) {
1697 			chain = endchain = newentry;
1698 		} else {
1699 			endchain->next = newentry;
1700 			endchain = newentry;
1701 		}
1702 
1703 		/* end of 'while' loop! */
1704 		if ((flags & UVM_EXTRACT_CONTIG) && entry->end < end &&
1705 		    (entry->next == &srcmap->header ||
1706 		    entry->next->start != entry->end)) {
1707 			error = EINVAL;
1708 			goto bad;
1709 		}
1710 		entry = entry->next;
1711 		fudge = 0;
1712 	}
1713 
1714 	/*
1715 	 * step 4: close off chain (in format expected by uvm_map_replace)
1716 	 */
1717 
1718 	if (chain)
1719 		chain->prev = endchain;
1720 
1721 	/*
1722 	 * step 5: attempt to lock the dest map so we can pmap_copy.
1723 	 * note usage of copy_ok:
1724 	 *   1 => dstmap locked, pmap_copy ok, and we "replace" here (step 5)
1725 	 *   0 => dstmap unlocked, NO pmap_copy, and we will "replace" in step 7
1726 	 */
1727 
1728 	if (srcmap == dstmap || vm_map_lock_try(dstmap) == TRUE) {
1729 		copy_ok = 1;
1730 		if (!uvm_map_replace(dstmap, dstaddr, dstaddr+len, chain,
1731 		    nchain)) {
1732 			if (srcmap != dstmap)
1733 				vm_map_unlock(dstmap);
1734 			error = EIO;
1735 			goto bad;
1736 		}
1737 	} else {
1738 		copy_ok = 0;
1739 		/* replace defered until step 7 */
1740 	}
1741 
1742 	/*
1743 	 * step 6: traverse the srcmap a second time to do the following:
1744 	 *  - if we got a lock on the dstmap do pmap_copy
1745 	 *  - if UVM_EXTRACT_REMOVE remove the entries
1746 	 * we make use of orig_entry and orig_fudge (saved in step 2)
1747 	 */
1748 
1749 	if (copy_ok || (flags & UVM_EXTRACT_REMOVE)) {
1750 
1751 		/* purge possible stale hints from srcmap */
1752 		if (flags & UVM_EXTRACT_REMOVE) {
1753 			SAVE_HINT(srcmap, srcmap->hint, orig_entry->prev);
1754 			if (srcmap->first_free->start >= start)
1755 				srcmap->first_free = orig_entry->prev;
1756 		}
1757 
1758 		entry = orig_entry;
1759 		fudge = orig_fudge;
1760 		deadentry = NULL;	/* for UVM_EXTRACT_REMOVE */
1761 
1762 		while (entry->start < end && entry != &srcmap->header) {
1763 			if (copy_ok) {
1764 				oldoffset = (entry->start + fudge) - start;
1765 				elen = MIN(end, entry->end) -
1766 				    (entry->start + fudge);
1767 				pmap_copy(dstmap->pmap, srcmap->pmap,
1768 				    dstaddr + oldoffset, elen,
1769 				    entry->start + fudge);
1770 			}
1771 
1772 			/* we advance "entry" in the following if statement */
1773 			if (flags & UVM_EXTRACT_REMOVE) {
1774 				pmap_remove(srcmap->pmap, entry->start,
1775 						entry->end);
1776         			oldentry = entry;	/* save entry */
1777         			entry = entry->next;	/* advance */
1778 				uvm_map_entry_unlink(srcmap, oldentry);
1779 							/* add to dead list */
1780 				oldentry->next = deadentry;
1781 				deadentry = oldentry;
1782       			} else {
1783         			entry = entry->next;		/* advance */
1784 			}
1785 
1786 			/* end of 'while' loop */
1787 			fudge = 0;
1788 		}
1789 		pmap_update(srcmap->pmap);
1790 
1791 		/*
1792 		 * unlock dstmap.  we will dispose of deadentry in
1793 		 * step 7 if needed
1794 		 */
1795 
1796 		if (copy_ok && srcmap != dstmap)
1797 			vm_map_unlock(dstmap);
1798 
1799 	} else {
1800 		deadentry = NULL;
1801 	}
1802 
1803 	/*
1804 	 * step 7: we are done with the source map, unlock.   if copy_ok
1805 	 * is 0 then we have not replaced the dummy mapping in dstmap yet
1806 	 * and we need to do so now.
1807 	 */
1808 
1809 	vm_map_unlock(srcmap);
1810 	if ((flags & UVM_EXTRACT_REMOVE) && deadentry)
1811 		uvm_unmap_detach(deadentry, 0);   /* dispose of old entries */
1812 
1813 	/* now do the replacement if we didn't do it in step 5 */
1814 	if (copy_ok == 0) {
1815 		vm_map_lock(dstmap);
1816 		error = uvm_map_replace(dstmap, dstaddr, dstaddr+len, chain,
1817 		    nchain);
1818 		vm_map_unlock(dstmap);
1819 
1820 		if (error == FALSE) {
1821 			error = EIO;
1822 			goto bad2;
1823 		}
1824 	}
1825 	return(0);
1826 
1827 	/*
1828 	 * bad: failure recovery
1829 	 */
1830 bad:
1831 	vm_map_unlock(srcmap);
1832 bad2:			/* src already unlocked */
1833 	if (chain)
1834 		uvm_unmap_detach(chain,
1835 		    (flags & UVM_EXTRACT_QREF) ? AMAP_REFALL : 0);
1836 	uvm_unmap(dstmap, dstaddr, dstaddr+len);   /* ??? */
1837 	return(error);
1838 }
1839 
1840 /* end of extraction functions */
1841 
1842 /*
1843  * uvm_map_submap: punch down part of a map into a submap
1844  *
1845  * => only the kernel_map is allowed to be submapped
1846  * => the purpose of submapping is to break up the locking granularity
1847  *	of a larger map
1848  * => the range specified must have been mapped previously with a uvm_map()
1849  *	call [with uobj==NULL] to create a blank map entry in the main map.
1850  *	[And it had better still be blank!]
1851  * => maps which contain submaps should never be copied or forked.
1852  * => to remove a submap, use uvm_unmap() on the main map
1853  *	and then uvm_map_deallocate() the submap.
1854  * => main map must be unlocked.
1855  * => submap must have been init'd and have a zero reference count.
1856  *	[need not be locked as we don't actually reference it]
1857  */
1858 
1859 int
1860 uvm_map_submap(map, start, end, submap)
1861 	struct vm_map *map, *submap;
1862 	vaddr_t start, end;
1863 {
1864 	struct vm_map_entry *entry;
1865 	int error;
1866 
1867 	vm_map_lock(map);
1868 	VM_MAP_RANGE_CHECK(map, start, end);
1869 
1870 	if (uvm_map_lookup_entry(map, start, &entry)) {
1871 		UVM_MAP_CLIP_START(map, entry, start);
1872 		UVM_MAP_CLIP_END(map, entry, end);		/* to be safe */
1873 	} else {
1874 		entry = NULL;
1875 	}
1876 
1877 	if (entry != NULL &&
1878 	    entry->start == start && entry->end == end &&
1879 	    entry->object.uvm_obj == NULL && entry->aref.ar_amap == NULL &&
1880 	    !UVM_ET_ISCOPYONWRITE(entry) && !UVM_ET_ISNEEDSCOPY(entry)) {
1881 		entry->etype |= UVM_ET_SUBMAP;
1882 		entry->object.sub_map = submap;
1883 		entry->offset = 0;
1884 		uvm_map_reference(submap);
1885 		error = 0;
1886 	} else {
1887 		error = EINVAL;
1888 	}
1889 	vm_map_unlock(map);
1890 	return error;
1891 }
1892 
1893 
1894 /*
1895  * uvm_map_protect: change map protection
1896  *
1897  * => set_max means set max_protection.
1898  * => map must be unlocked.
1899  */
1900 
1901 #define MASK(entry)     (UVM_ET_ISCOPYONWRITE(entry) ? \
1902 			 ~VM_PROT_WRITE : VM_PROT_ALL)
1903 
1904 int
1905 uvm_map_protect(map, start, end, new_prot, set_max)
1906 	struct vm_map *map;
1907 	vaddr_t start, end;
1908 	vm_prot_t new_prot;
1909 	boolean_t set_max;
1910 {
1911 	struct vm_map_entry *current, *entry;
1912 	int error = 0;
1913 	UVMHIST_FUNC("uvm_map_protect"); UVMHIST_CALLED(maphist);
1914 	UVMHIST_LOG(maphist,"(map=0x%x,start=0x%x,end=0x%x,new_prot=0x%x)",
1915 		    map, start, end, new_prot);
1916 
1917 	vm_map_lock(map);
1918 	VM_MAP_RANGE_CHECK(map, start, end);
1919 	if (uvm_map_lookup_entry(map, start, &entry)) {
1920 		UVM_MAP_CLIP_START(map, entry, start);
1921 	} else {
1922 		entry = entry->next;
1923 	}
1924 
1925 	/*
1926 	 * make a first pass to check for protection violations.
1927 	 */
1928 
1929 	current = entry;
1930 	while ((current != &map->header) && (current->start < end)) {
1931 		if (UVM_ET_ISSUBMAP(current)) {
1932 			error = EINVAL;
1933 			goto out;
1934 		}
1935 		if ((new_prot & current->max_protection) != new_prot) {
1936 			error = EACCES;
1937 			goto out;
1938 		}
1939 		/*
1940 		 * Don't allow VM_PROT_EXECUTE to be set on entries that
1941 		 * point to vnodes that are associated with a NOEXEC file
1942 		 * system.
1943 		 */
1944 		if (UVM_ET_ISOBJ(current) &&
1945 		    UVM_OBJ_IS_VNODE(current->object.uvm_obj)) {
1946 			struct vnode *vp =
1947 			    (struct vnode *) current->object.uvm_obj;
1948 
1949 			if ((new_prot & VM_PROT_EXECUTE) != 0 &&
1950 			    (vp->v_mount->mnt_flag & MNT_NOEXEC) != 0) {
1951 				error = EACCES;
1952 				goto out;
1953 			}
1954 		}
1955 		current = current->next;
1956 	}
1957 
1958 	/* go back and fix up protections (no need to clip this time). */
1959 
1960 	current = entry;
1961 	while ((current != &map->header) && (current->start < end)) {
1962 		vm_prot_t old_prot;
1963 
1964 		UVM_MAP_CLIP_END(map, current, end);
1965 		old_prot = current->protection;
1966 		if (set_max)
1967 			current->protection =
1968 			    (current->max_protection = new_prot) & old_prot;
1969 		else
1970 			current->protection = new_prot;
1971 
1972 		/*
1973 		 * update physical map if necessary.  worry about copy-on-write
1974 		 * here -- CHECK THIS XXX
1975 		 */
1976 
1977 		if (current->protection != old_prot) {
1978 			/* update pmap! */
1979 			pmap_protect(map->pmap, current->start, current->end,
1980 			    current->protection & MASK(entry));
1981 
1982 			/*
1983 			 * If this entry points at a vnode, and the
1984 			 * protection includes VM_PROT_EXECUTE, mark
1985 			 * the vnode as VEXECMAP.
1986 			 */
1987 			if (UVM_ET_ISOBJ(current)) {
1988 				struct uvm_object *uobj =
1989 				    current->object.uvm_obj;
1990 
1991 				if (UVM_OBJ_IS_VNODE(uobj) &&
1992 				    (current->protection & VM_PROT_EXECUTE))
1993 					vn_markexec((struct vnode *) uobj);
1994 			}
1995 		}
1996 
1997 		/*
1998 		 * If the map is configured to lock any future mappings,
1999 		 * wire this entry now if the old protection was VM_PROT_NONE
2000 		 * and the new protection is not VM_PROT_NONE.
2001 		 */
2002 
2003 		if ((map->flags & VM_MAP_WIREFUTURE) != 0 &&
2004 		    VM_MAPENT_ISWIRED(entry) == 0 &&
2005 		    old_prot == VM_PROT_NONE &&
2006 		    new_prot != VM_PROT_NONE) {
2007 			if (uvm_map_pageable(map, entry->start,
2008 			    entry->end, FALSE,
2009 			    UVM_LK_ENTER|UVM_LK_EXIT) != 0) {
2010 
2011 				/*
2012 				 * If locking the entry fails, remember the
2013 				 * error if it's the first one.  Note we
2014 				 * still continue setting the protection in
2015 				 * the map, but will return the error
2016 				 * condition regardless.
2017 				 *
2018 				 * XXX Ignore what the actual error is,
2019 				 * XXX just call it a resource shortage
2020 				 * XXX so that it doesn't get confused
2021 				 * XXX what uvm_map_protect() itself would
2022 				 * XXX normally return.
2023 				 */
2024 
2025 				error = ENOMEM;
2026 			}
2027 		}
2028 		current = current->next;
2029 	}
2030 	pmap_update(map->pmap);
2031 
2032  out:
2033 	vm_map_unlock(map);
2034 	UVMHIST_LOG(maphist, "<- done, error=%d",error,0,0,0);
2035 	return error;
2036 }
2037 
2038 #undef  MASK
2039 
2040 /*
2041  * uvm_map_inherit: set inheritance code for range of addrs in map.
2042  *
2043  * => map must be unlocked
2044  * => note that the inherit code is used during a "fork".  see fork
2045  *	code for details.
2046  */
2047 
2048 int
2049 uvm_map_inherit(map, start, end, new_inheritance)
2050 	struct vm_map *map;
2051 	vaddr_t start;
2052 	vaddr_t end;
2053 	vm_inherit_t new_inheritance;
2054 {
2055 	struct vm_map_entry *entry, *temp_entry;
2056 	UVMHIST_FUNC("uvm_map_inherit"); UVMHIST_CALLED(maphist);
2057 	UVMHIST_LOG(maphist,"(map=0x%x,start=0x%x,end=0x%x,new_inh=0x%x)",
2058 	    map, start, end, new_inheritance);
2059 
2060 	switch (new_inheritance) {
2061 	case MAP_INHERIT_NONE:
2062 	case MAP_INHERIT_COPY:
2063 	case MAP_INHERIT_SHARE:
2064 		break;
2065 	default:
2066 		UVMHIST_LOG(maphist,"<- done (INVALID ARG)",0,0,0,0);
2067 		return EINVAL;
2068 	}
2069 
2070 	vm_map_lock(map);
2071 	VM_MAP_RANGE_CHECK(map, start, end);
2072 	if (uvm_map_lookup_entry(map, start, &temp_entry)) {
2073 		entry = temp_entry;
2074 		UVM_MAP_CLIP_START(map, entry, start);
2075 	}  else {
2076 		entry = temp_entry->next;
2077 	}
2078 	while ((entry != &map->header) && (entry->start < end)) {
2079 		UVM_MAP_CLIP_END(map, entry, end);
2080 		entry->inheritance = new_inheritance;
2081 		entry = entry->next;
2082 	}
2083 	vm_map_unlock(map);
2084 	UVMHIST_LOG(maphist,"<- done (OK)",0,0,0,0);
2085 	return 0;
2086 }
2087 
2088 /*
2089  * uvm_map_advice: set advice code for range of addrs in map.
2090  *
2091  * => map must be unlocked
2092  */
2093 
2094 int
2095 uvm_map_advice(map, start, end, new_advice)
2096 	struct vm_map *map;
2097 	vaddr_t start;
2098 	vaddr_t end;
2099 	int new_advice;
2100 {
2101 	struct vm_map_entry *entry, *temp_entry;
2102 	UVMHIST_FUNC("uvm_map_advice"); UVMHIST_CALLED(maphist);
2103 	UVMHIST_LOG(maphist,"(map=0x%x,start=0x%x,end=0x%x,new_adv=0x%x)",
2104 	    map, start, end, new_advice);
2105 
2106 	vm_map_lock(map);
2107 	VM_MAP_RANGE_CHECK(map, start, end);
2108 	if (uvm_map_lookup_entry(map, start, &temp_entry)) {
2109 		entry = temp_entry;
2110 		UVM_MAP_CLIP_START(map, entry, start);
2111 	} else {
2112 		entry = temp_entry->next;
2113 	}
2114 
2115 	/*
2116 	 * XXXJRT: disallow holes?
2117 	 */
2118 
2119 	while ((entry != &map->header) && (entry->start < end)) {
2120 		UVM_MAP_CLIP_END(map, entry, end);
2121 
2122 		switch (new_advice) {
2123 		case MADV_NORMAL:
2124 		case MADV_RANDOM:
2125 		case MADV_SEQUENTIAL:
2126 			/* nothing special here */
2127 			break;
2128 
2129 		default:
2130 			vm_map_unlock(map);
2131 			UVMHIST_LOG(maphist,"<- done (INVALID ARG)",0,0,0,0);
2132 			return EINVAL;
2133 		}
2134 		entry->advice = new_advice;
2135 		entry = entry->next;
2136 	}
2137 
2138 	vm_map_unlock(map);
2139 	UVMHIST_LOG(maphist,"<- done (OK)",0,0,0,0);
2140 	return 0;
2141 }
2142 
2143 /*
2144  * uvm_map_pageable: sets the pageability of a range in a map.
2145  *
2146  * => wires map entries.  should not be used for transient page locking.
2147  *	for that, use uvm_fault_wire()/uvm_fault_unwire() (see uvm_vslock()).
2148  * => regions sepcified as not pageable require lock-down (wired) memory
2149  *	and page tables.
2150  * => map must never be read-locked
2151  * => if islocked is TRUE, map is already write-locked
2152  * => we always unlock the map, since we must downgrade to a read-lock
2153  *	to call uvm_fault_wire()
2154  * => XXXCDC: check this and try and clean it up.
2155  */
2156 
2157 int
2158 uvm_map_pageable(map, start, end, new_pageable, lockflags)
2159 	struct vm_map *map;
2160 	vaddr_t start, end;
2161 	boolean_t new_pageable;
2162 	int lockflags;
2163 {
2164 	struct vm_map_entry *entry, *start_entry, *failed_entry;
2165 	int rv;
2166 #ifdef DIAGNOSTIC
2167 	u_int timestamp_save;
2168 #endif
2169 	UVMHIST_FUNC("uvm_map_pageable"); UVMHIST_CALLED(maphist);
2170 	UVMHIST_LOG(maphist,"(map=0x%x,start=0x%x,end=0x%x,new_pageable=0x%x)",
2171 		    map, start, end, new_pageable);
2172 	KASSERT(map->flags & VM_MAP_PAGEABLE);
2173 
2174 	if ((lockflags & UVM_LK_ENTER) == 0)
2175 		vm_map_lock(map);
2176 	VM_MAP_RANGE_CHECK(map, start, end);
2177 
2178 	/*
2179 	 * only one pageability change may take place at one time, since
2180 	 * uvm_fault_wire assumes it will be called only once for each
2181 	 * wiring/unwiring.  therefore, we have to make sure we're actually
2182 	 * changing the pageability for the entire region.  we do so before
2183 	 * making any changes.
2184 	 */
2185 
2186 	if (uvm_map_lookup_entry(map, start, &start_entry) == FALSE) {
2187 		if ((lockflags & UVM_LK_EXIT) == 0)
2188 			vm_map_unlock(map);
2189 
2190 		UVMHIST_LOG(maphist,"<- done (fault)",0,0,0,0);
2191 		return EFAULT;
2192 	}
2193 	entry = start_entry;
2194 
2195 	/*
2196 	 * handle wiring and unwiring separately.
2197 	 */
2198 
2199 	if (new_pageable) {		/* unwire */
2200 		UVM_MAP_CLIP_START(map, entry, start);
2201 
2202 		/*
2203 		 * unwiring.  first ensure that the range to be unwired is
2204 		 * really wired down and that there are no holes.
2205 		 */
2206 
2207 		while ((entry != &map->header) && (entry->start < end)) {
2208 			if (entry->wired_count == 0 ||
2209 			    (entry->end < end &&
2210 			     (entry->next == &map->header ||
2211 			      entry->next->start > entry->end))) {
2212 				if ((lockflags & UVM_LK_EXIT) == 0)
2213 					vm_map_unlock(map);
2214 				UVMHIST_LOG(maphist, "<- done (INVAL)",0,0,0,0);
2215 				return EINVAL;
2216 			}
2217 			entry = entry->next;
2218 		}
2219 
2220 		/*
2221 		 * POSIX 1003.1b - a single munlock call unlocks a region,
2222 		 * regardless of the number of mlock calls made on that
2223 		 * region.
2224 		 */
2225 
2226 		entry = start_entry;
2227 		while ((entry != &map->header) && (entry->start < end)) {
2228 			UVM_MAP_CLIP_END(map, entry, end);
2229 			if (VM_MAPENT_ISWIRED(entry))
2230 				uvm_map_entry_unwire(map, entry);
2231 			entry = entry->next;
2232 		}
2233 		if ((lockflags & UVM_LK_EXIT) == 0)
2234 			vm_map_unlock(map);
2235 		UVMHIST_LOG(maphist,"<- done (OK UNWIRE)",0,0,0,0);
2236 		return 0;
2237 	}
2238 
2239 	/*
2240 	 * wire case: in two passes [XXXCDC: ugly block of code here]
2241 	 *
2242 	 * 1: holding the write lock, we create any anonymous maps that need
2243 	 *    to be created.  then we clip each map entry to the region to
2244 	 *    be wired and increment its wiring count.
2245 	 *
2246 	 * 2: we downgrade to a read lock, and call uvm_fault_wire to fault
2247 	 *    in the pages for any newly wired area (wired_count == 1).
2248 	 *
2249 	 *    downgrading to a read lock for uvm_fault_wire avoids a possible
2250 	 *    deadlock with another thread that may have faulted on one of
2251 	 *    the pages to be wired (it would mark the page busy, blocking
2252 	 *    us, then in turn block on the map lock that we hold).  because
2253 	 *    of problems in the recursive lock package, we cannot upgrade
2254 	 *    to a write lock in vm_map_lookup.  thus, any actions that
2255 	 *    require the write lock must be done beforehand.  because we
2256 	 *    keep the read lock on the map, the copy-on-write status of the
2257 	 *    entries we modify here cannot change.
2258 	 */
2259 
2260 	while ((entry != &map->header) && (entry->start < end)) {
2261 		if (VM_MAPENT_ISWIRED(entry) == 0) { /* not already wired? */
2262 
2263 			/*
2264 			 * perform actions of vm_map_lookup that need the
2265 			 * write lock on the map: create an anonymous map
2266 			 * for a copy-on-write region, or an anonymous map
2267 			 * for a zero-fill region.  (XXXCDC: submap case
2268 			 * ok?)
2269 			 */
2270 
2271 			if (!UVM_ET_ISSUBMAP(entry)) {  /* not submap */
2272 				if (UVM_ET_ISNEEDSCOPY(entry) &&
2273 				    ((entry->max_protection & VM_PROT_WRITE) ||
2274 				     (entry->object.uvm_obj == NULL))) {
2275 					amap_copy(map, entry, M_WAITOK, TRUE,
2276 					    start, end);
2277 					/* XXXCDC: wait OK? */
2278 				}
2279 			}
2280 		}
2281 		UVM_MAP_CLIP_START(map, entry, start);
2282 		UVM_MAP_CLIP_END(map, entry, end);
2283 		entry->wired_count++;
2284 
2285 		/*
2286 		 * Check for holes
2287 		 */
2288 
2289 		if (entry->protection == VM_PROT_NONE ||
2290 		    (entry->end < end &&
2291 		     (entry->next == &map->header ||
2292 		      entry->next->start > entry->end))) {
2293 
2294 			/*
2295 			 * found one.  amap creation actions do not need to
2296 			 * be undone, but the wired counts need to be restored.
2297 			 */
2298 
2299 			while (entry != &map->header && entry->end > start) {
2300 				entry->wired_count--;
2301 				entry = entry->prev;
2302 			}
2303 			if ((lockflags & UVM_LK_EXIT) == 0)
2304 				vm_map_unlock(map);
2305 			UVMHIST_LOG(maphist,"<- done (INVALID WIRE)",0,0,0,0);
2306 			return EINVAL;
2307 		}
2308 		entry = entry->next;
2309 	}
2310 
2311 	/*
2312 	 * Pass 2.
2313 	 */
2314 
2315 #ifdef DIAGNOSTIC
2316 	timestamp_save = map->timestamp;
2317 #endif
2318 	vm_map_busy(map);
2319 	vm_map_downgrade(map);
2320 
2321 	rv = 0;
2322 	entry = start_entry;
2323 	while (entry != &map->header && entry->start < end) {
2324 		if (entry->wired_count == 1) {
2325 			rv = uvm_fault_wire(map, entry->start, entry->end,
2326 			    VM_FAULT_WIREMAX, entry->max_protection);
2327 			if (rv) {
2328 
2329 				/*
2330 				 * wiring failed.  break out of the loop.
2331 				 * we'll clean up the map below, once we
2332 				 * have a write lock again.
2333 				 */
2334 
2335 				break;
2336 			}
2337 		}
2338 		entry = entry->next;
2339 	}
2340 
2341 	if (rv) {        /* failed? */
2342 
2343 		/*
2344 		 * Get back to an exclusive (write) lock.
2345 		 */
2346 
2347 		vm_map_upgrade(map);
2348 		vm_map_unbusy(map);
2349 
2350 #ifdef DIAGNOSTIC
2351 		if (timestamp_save != map->timestamp)
2352 			panic("uvm_map_pageable: stale map");
2353 #endif
2354 
2355 		/*
2356 		 * first drop the wiring count on all the entries
2357 		 * which haven't actually been wired yet.
2358 		 */
2359 
2360 		failed_entry = entry;
2361 		while (entry != &map->header && entry->start < end) {
2362 			entry->wired_count--;
2363 			entry = entry->next;
2364 		}
2365 
2366 		/*
2367 		 * now, unwire all the entries that were successfully
2368 		 * wired above.
2369 		 */
2370 
2371 		entry = start_entry;
2372 		while (entry != failed_entry) {
2373 			entry->wired_count--;
2374 			if (VM_MAPENT_ISWIRED(entry) == 0)
2375 				uvm_map_entry_unwire(map, entry);
2376 			entry = entry->next;
2377 		}
2378 		if ((lockflags & UVM_LK_EXIT) == 0)
2379 			vm_map_unlock(map);
2380 		UVMHIST_LOG(maphist, "<- done (RV=%d)", rv,0,0,0);
2381 		return(rv);
2382 	}
2383 
2384 	/* We are holding a read lock here. */
2385 	if ((lockflags & UVM_LK_EXIT) == 0) {
2386 		vm_map_unbusy(map);
2387 		vm_map_unlock_read(map);
2388 	} else {
2389 
2390 		/*
2391 		 * Get back to an exclusive (write) lock.
2392 		 */
2393 
2394 		vm_map_upgrade(map);
2395 		vm_map_unbusy(map);
2396 	}
2397 
2398 	UVMHIST_LOG(maphist,"<- done (OK WIRE)",0,0,0,0);
2399 	return 0;
2400 }
2401 
2402 /*
2403  * uvm_map_pageable_all: special case of uvm_map_pageable - affects
2404  * all mapped regions.
2405  *
2406  * => map must not be locked.
2407  * => if no flags are specified, all regions are unwired.
2408  * => XXXJRT: has some of the same problems as uvm_map_pageable() above.
2409  */
2410 
2411 int
2412 uvm_map_pageable_all(map, flags, limit)
2413 	struct vm_map *map;
2414 	int flags;
2415 	vsize_t limit;
2416 {
2417 	struct vm_map_entry *entry, *failed_entry;
2418 	vsize_t size;
2419 	int rv;
2420 #ifdef DIAGNOSTIC
2421 	u_int timestamp_save;
2422 #endif
2423 	UVMHIST_FUNC("uvm_map_pageable_all"); UVMHIST_CALLED(maphist);
2424 	UVMHIST_LOG(maphist,"(map=0x%x,flags=0x%x)", map, flags, 0, 0);
2425 
2426 	KASSERT(map->flags & VM_MAP_PAGEABLE);
2427 
2428 	vm_map_lock(map);
2429 
2430 	/*
2431 	 * handle wiring and unwiring separately.
2432 	 */
2433 
2434 	if (flags == 0) {			/* unwire */
2435 
2436 		/*
2437 		 * POSIX 1003.1b -- munlockall unlocks all regions,
2438 		 * regardless of how many times mlockall has been called.
2439 		 */
2440 
2441 		for (entry = map->header.next; entry != &map->header;
2442 		     entry = entry->next) {
2443 			if (VM_MAPENT_ISWIRED(entry))
2444 				uvm_map_entry_unwire(map, entry);
2445 		}
2446 		vm_map_modflags(map, 0, VM_MAP_WIREFUTURE);
2447 		vm_map_unlock(map);
2448 		UVMHIST_LOG(maphist,"<- done (OK UNWIRE)",0,0,0,0);
2449 		return 0;
2450 	}
2451 
2452 	if (flags & MCL_FUTURE) {
2453 
2454 		/*
2455 		 * must wire all future mappings; remember this.
2456 		 */
2457 
2458 		vm_map_modflags(map, VM_MAP_WIREFUTURE, 0);
2459 	}
2460 
2461 	if ((flags & MCL_CURRENT) == 0) {
2462 
2463 		/*
2464 		 * no more work to do!
2465 		 */
2466 
2467 		UVMHIST_LOG(maphist,"<- done (OK no wire)",0,0,0,0);
2468 		vm_map_unlock(map);
2469 		return 0;
2470 	}
2471 
2472 	/*
2473 	 * wire case: in three passes [XXXCDC: ugly block of code here]
2474 	 *
2475 	 * 1: holding the write lock, count all pages mapped by non-wired
2476 	 *    entries.  if this would cause us to go over our limit, we fail.
2477 	 *
2478 	 * 2: still holding the write lock, we create any anonymous maps that
2479 	 *    need to be created.  then we increment its wiring count.
2480 	 *
2481 	 * 3: we downgrade to a read lock, and call uvm_fault_wire to fault
2482 	 *    in the pages for any newly wired area (wired_count == 1).
2483 	 *
2484 	 *    downgrading to a read lock for uvm_fault_wire avoids a possible
2485 	 *    deadlock with another thread that may have faulted on one of
2486 	 *    the pages to be wired (it would mark the page busy, blocking
2487 	 *    us, then in turn block on the map lock that we hold).  because
2488 	 *    of problems in the recursive lock package, we cannot upgrade
2489 	 *    to a write lock in vm_map_lookup.  thus, any actions that
2490 	 *    require the write lock must be done beforehand.  because we
2491 	 *    keep the read lock on the map, the copy-on-write status of the
2492 	 *    entries we modify here cannot change.
2493 	 */
2494 
2495 	for (size = 0, entry = map->header.next; entry != &map->header;
2496 	     entry = entry->next) {
2497 		if (entry->protection != VM_PROT_NONE &&
2498 		    VM_MAPENT_ISWIRED(entry) == 0) { /* not already wired? */
2499 			size += entry->end - entry->start;
2500 		}
2501 	}
2502 
2503 	if (atop(size) + uvmexp.wired > uvmexp.wiredmax) {
2504 		vm_map_unlock(map);
2505 		return ENOMEM;
2506 	}
2507 
2508 	/* XXX non-pmap_wired_count case must be handled by caller */
2509 #ifdef pmap_wired_count
2510 	if (limit != 0 &&
2511 	    (size + ptoa(pmap_wired_count(vm_map_pmap(map))) > limit)) {
2512 		vm_map_unlock(map);
2513 		return ENOMEM;
2514 	}
2515 #endif
2516 
2517 	/*
2518 	 * Pass 2.
2519 	 */
2520 
2521 	for (entry = map->header.next; entry != &map->header;
2522 	     entry = entry->next) {
2523 		if (entry->protection == VM_PROT_NONE)
2524 			continue;
2525 		if (VM_MAPENT_ISWIRED(entry) == 0) { /* not already wired? */
2526 
2527 			/*
2528 			 * perform actions of vm_map_lookup that need the
2529 			 * write lock on the map: create an anonymous map
2530 			 * for a copy-on-write region, or an anonymous map
2531 			 * for a zero-fill region.  (XXXCDC: submap case
2532 			 * ok?)
2533 			 */
2534 
2535 			if (!UVM_ET_ISSUBMAP(entry)) {	/* not submap */
2536 				if (UVM_ET_ISNEEDSCOPY(entry) &&
2537 				    ((entry->max_protection & VM_PROT_WRITE) ||
2538 				     (entry->object.uvm_obj == NULL))) {
2539 					amap_copy(map, entry, M_WAITOK, TRUE,
2540 					    entry->start, entry->end);
2541 					/* XXXCDC: wait OK? */
2542 				}
2543 			}
2544 		}
2545 		entry->wired_count++;
2546 	}
2547 
2548 	/*
2549 	 * Pass 3.
2550 	 */
2551 
2552 #ifdef DIAGNOSTIC
2553 	timestamp_save = map->timestamp;
2554 #endif
2555 	vm_map_busy(map);
2556 	vm_map_downgrade(map);
2557 
2558 	rv = 0;
2559 	for (entry = map->header.next; entry != &map->header;
2560 	     entry = entry->next) {
2561 		if (entry->wired_count == 1) {
2562 			rv = uvm_fault_wire(map, entry->start, entry->end,
2563 			    VM_FAULT_WIREMAX, entry->max_protection);
2564 			if (rv) {
2565 
2566 				/*
2567 				 * wiring failed.  break out of the loop.
2568 				 * we'll clean up the map below, once we
2569 				 * have a write lock again.
2570 				 */
2571 
2572 				break;
2573 			}
2574 		}
2575 	}
2576 
2577 	if (rv) {
2578 
2579 		/*
2580 		 * Get back an exclusive (write) lock.
2581 		 */
2582 
2583 		vm_map_upgrade(map);
2584 		vm_map_unbusy(map);
2585 
2586 #ifdef DIAGNOSTIC
2587 		if (timestamp_save != map->timestamp)
2588 			panic("uvm_map_pageable_all: stale map");
2589 #endif
2590 
2591 		/*
2592 		 * first drop the wiring count on all the entries
2593 		 * which haven't actually been wired yet.
2594 		 *
2595 		 * Skip VM_PROT_NONE entries like we did above.
2596 		 */
2597 
2598 		failed_entry = entry;
2599 		for (/* nothing */; entry != &map->header;
2600 		     entry = entry->next) {
2601 			if (entry->protection == VM_PROT_NONE)
2602 				continue;
2603 			entry->wired_count--;
2604 		}
2605 
2606 		/*
2607 		 * now, unwire all the entries that were successfully
2608 		 * wired above.
2609 		 *
2610 		 * Skip VM_PROT_NONE entries like we did above.
2611 		 */
2612 
2613 		for (entry = map->header.next; entry != failed_entry;
2614 		     entry = entry->next) {
2615 			if (entry->protection == VM_PROT_NONE)
2616 				continue;
2617 			entry->wired_count--;
2618 			if (VM_MAPENT_ISWIRED(entry))
2619 				uvm_map_entry_unwire(map, entry);
2620 		}
2621 		vm_map_unlock(map);
2622 		UVMHIST_LOG(maphist,"<- done (RV=%d)", rv,0,0,0);
2623 		return (rv);
2624 	}
2625 
2626 	/* We are holding a read lock here. */
2627 	vm_map_unbusy(map);
2628 	vm_map_unlock_read(map);
2629 
2630 	UVMHIST_LOG(maphist,"<- done (OK WIRE)",0,0,0,0);
2631 	return 0;
2632 }
2633 
2634 /*
2635  * uvm_map_clean: clean out a map range
2636  *
2637  * => valid flags:
2638  *   if (flags & PGO_CLEANIT): dirty pages are cleaned first
2639  *   if (flags & PGO_SYNCIO): dirty pages are written synchronously
2640  *   if (flags & PGO_DEACTIVATE): any cached pages are deactivated after clean
2641  *   if (flags & PGO_FREE): any cached pages are freed after clean
2642  * => returns an error if any part of the specified range isn't mapped
2643  * => never a need to flush amap layer since the anonymous memory has
2644  *	no permanent home, but may deactivate pages there
2645  * => called from sys_msync() and sys_madvise()
2646  * => caller must not write-lock map (read OK).
2647  * => we may sleep while cleaning if SYNCIO [with map read-locked]
2648  */
2649 
2650 int
2651 uvm_map_clean(map, start, end, flags)
2652 	struct vm_map *map;
2653 	vaddr_t start, end;
2654 	int flags;
2655 {
2656 	struct vm_map_entry *current, *entry;
2657 	struct uvm_object *uobj;
2658 	struct vm_amap *amap;
2659 	struct vm_anon *anon;
2660 	struct vm_page *pg;
2661 	vaddr_t offset;
2662 	vsize_t size;
2663 	int error, refs;
2664 	UVMHIST_FUNC("uvm_map_clean"); UVMHIST_CALLED(maphist);
2665 
2666 	UVMHIST_LOG(maphist,"(map=0x%x,start=0x%x,end=0x%x,flags=0x%x)",
2667 		    map, start, end, flags);
2668 	KASSERT((flags & (PGO_FREE|PGO_DEACTIVATE)) !=
2669 		(PGO_FREE|PGO_DEACTIVATE));
2670 
2671 	vm_map_lock_read(map);
2672 	VM_MAP_RANGE_CHECK(map, start, end);
2673 	if (uvm_map_lookup_entry(map, start, &entry) == FALSE) {
2674 		vm_map_unlock_read(map);
2675 		return EFAULT;
2676 	}
2677 
2678 	/*
2679 	 * Make a first pass to check for holes.
2680 	 */
2681 
2682 	for (current = entry; current->start < end; current = current->next) {
2683 		if (UVM_ET_ISSUBMAP(current)) {
2684 			vm_map_unlock_read(map);
2685 			return EINVAL;
2686 		}
2687 		if (end <= current->end) {
2688 			break;
2689 		}
2690 		if (current->end != current->next->start) {
2691 			vm_map_unlock_read(map);
2692 			return EFAULT;
2693 		}
2694 	}
2695 
2696 	error = 0;
2697 	for (current = entry; start < end; current = current->next) {
2698 		amap = current->aref.ar_amap;	/* top layer */
2699 		uobj = current->object.uvm_obj;	/* bottom layer */
2700 		KASSERT(start >= current->start);
2701 
2702 		/*
2703 		 * No amap cleaning necessary if:
2704 		 *
2705 		 *	(1) There's no amap.
2706 		 *
2707 		 *	(2) We're not deactivating or freeing pages.
2708 		 */
2709 
2710 		if (amap == NULL || (flags & (PGO_DEACTIVATE|PGO_FREE)) == 0)
2711 			goto flush_object;
2712 
2713 		amap_lock(amap);
2714 		offset = start - current->start;
2715 		size = MIN(end, current->end) - start;
2716 		for ( ; size != 0; size -= PAGE_SIZE, offset += PAGE_SIZE) {
2717 			anon = amap_lookup(&current->aref, offset);
2718 			if (anon == NULL)
2719 				continue;
2720 
2721 			simple_lock(&anon->an_lock);
2722 			pg = anon->u.an_page;
2723 			if (pg == NULL) {
2724 				simple_unlock(&anon->an_lock);
2725 				continue;
2726 			}
2727 
2728 			switch (flags & (PGO_CLEANIT|PGO_FREE|PGO_DEACTIVATE)) {
2729 
2730 			/*
2731 			 * In these first 3 cases, we just deactivate the page.
2732 			 */
2733 
2734 			case PGO_CLEANIT|PGO_FREE:
2735 			case PGO_CLEANIT|PGO_DEACTIVATE:
2736 			case PGO_DEACTIVATE:
2737  deactivate_it:
2738 				/*
2739 				 * skip the page if it's loaned or wired,
2740 				 * since it shouldn't be on a paging queue
2741 				 * at all in these cases.
2742 				 */
2743 
2744 				uvm_lock_pageq();
2745 				if (pg->loan_count != 0 ||
2746 				    pg->wire_count != 0) {
2747 					uvm_unlock_pageq();
2748 					simple_unlock(&anon->an_lock);
2749 					continue;
2750 				}
2751 				KASSERT(pg->uanon == anon);
2752 				pmap_clear_reference(pg);
2753 				uvm_pagedeactivate(pg);
2754 				uvm_unlock_pageq();
2755 				simple_unlock(&anon->an_lock);
2756 				continue;
2757 
2758 			case PGO_FREE:
2759 
2760 				/*
2761 				 * If there are multiple references to
2762 				 * the amap, just deactivate the page.
2763 				 */
2764 
2765 				if (amap_refs(amap) > 1)
2766 					goto deactivate_it;
2767 
2768 				/* skip the page if it's wired */
2769 				if (pg->wire_count != 0) {
2770 					simple_unlock(&anon->an_lock);
2771 					continue;
2772 				}
2773 				amap_unadd(&current->aref, offset);
2774 				refs = --anon->an_ref;
2775 				simple_unlock(&anon->an_lock);
2776 				if (refs == 0)
2777 					uvm_anfree(anon);
2778 				continue;
2779 			}
2780 		}
2781 		amap_unlock(amap);
2782 
2783  flush_object:
2784 		/*
2785 		 * flush pages if we've got a valid backing object.
2786 		 * note that we must always clean object pages before
2787 		 * freeing them since otherwise we could reveal stale
2788 		 * data from files.
2789 		 */
2790 
2791 		offset = current->offset + (start - current->start);
2792 		size = MIN(end, current->end) - start;
2793 		if (uobj != NULL) {
2794 			simple_lock(&uobj->vmobjlock);
2795 			error = (uobj->pgops->pgo_put)(uobj, offset,
2796 			    offset + size, flags | PGO_CLEANIT);
2797 		}
2798 		start += size;
2799 	}
2800 	vm_map_unlock_read(map);
2801 	return (error);
2802 }
2803 
2804 
2805 /*
2806  * uvm_map_checkprot: check protection in map
2807  *
2808  * => must allow specified protection in a fully allocated region.
2809  * => map must be read or write locked by caller.
2810  */
2811 
2812 boolean_t
2813 uvm_map_checkprot(map, start, end, protection)
2814 	struct vm_map * map;
2815 	vaddr_t start, end;
2816 	vm_prot_t protection;
2817 {
2818 	struct vm_map_entry *entry;
2819 	struct vm_map_entry *tmp_entry;
2820 
2821 	if (!uvm_map_lookup_entry(map, start, &tmp_entry)) {
2822 		return(FALSE);
2823 	}
2824 	entry = tmp_entry;
2825 	while (start < end) {
2826 		if (entry == &map->header) {
2827 			return(FALSE);
2828 		}
2829 
2830 		/*
2831 		 * no holes allowed
2832 		 */
2833 
2834 		if (start < entry->start) {
2835 			return(FALSE);
2836 		}
2837 
2838 		/*
2839 		 * check protection associated with entry
2840 		 */
2841 
2842 		if ((entry->protection & protection) != protection) {
2843 			return(FALSE);
2844 		}
2845 		start = entry->end;
2846 		entry = entry->next;
2847 	}
2848 	return(TRUE);
2849 }
2850 
2851 /*
2852  * uvmspace_alloc: allocate a vmspace structure.
2853  *
2854  * - structure includes vm_map and pmap
2855  * - XXX: no locking on this structure
2856  * - refcnt set to 1, rest must be init'd by caller
2857  */
2858 struct vmspace *
2859 uvmspace_alloc(min, max)
2860 	vaddr_t min, max;
2861 {
2862 	struct vmspace *vm;
2863 	UVMHIST_FUNC("uvmspace_alloc"); UVMHIST_CALLED(maphist);
2864 
2865 	vm = pool_get(&uvm_vmspace_pool, PR_WAITOK);
2866 	uvmspace_init(vm, NULL, min, max);
2867 	UVMHIST_LOG(maphist,"<- done (vm=0x%x)", vm,0,0,0);
2868 	return (vm);
2869 }
2870 
2871 /*
2872  * uvmspace_init: initialize a vmspace structure.
2873  *
2874  * - XXX: no locking on this structure
2875  * - refcnt set to 1, rest must me init'd by caller
2876  */
2877 void
2878 uvmspace_init(vm, pmap, min, max)
2879 	struct vmspace *vm;
2880 	struct pmap *pmap;
2881 	vaddr_t min, max;
2882 {
2883 	UVMHIST_FUNC("uvmspace_init"); UVMHIST_CALLED(maphist);
2884 
2885 	memset(vm, 0, sizeof(*vm));
2886 	uvm_map_setup(&vm->vm_map, min, max, VM_MAP_PAGEABLE);
2887 	if (pmap)
2888 		pmap_reference(pmap);
2889 	else
2890 		pmap = pmap_create();
2891 	vm->vm_map.pmap = pmap;
2892 	vm->vm_refcnt = 1;
2893 	UVMHIST_LOG(maphist,"<- done",0,0,0,0);
2894 }
2895 
2896 /*
2897  * uvmspace_share: share a vmspace between two proceses
2898  *
2899  * - XXX: no locking on vmspace
2900  * - used for vfork, threads(?)
2901  */
2902 
2903 void
2904 uvmspace_share(p1, p2)
2905 	struct proc *p1, *p2;
2906 {
2907 	p2->p_vmspace = p1->p_vmspace;
2908 	p1->p_vmspace->vm_refcnt++;
2909 }
2910 
2911 /*
2912  * uvmspace_unshare: ensure that process "p" has its own, unshared, vmspace
2913  *
2914  * - XXX: no locking on vmspace
2915  */
2916 
2917 void
2918 uvmspace_unshare(p)
2919 	struct proc *p;
2920 {
2921 	struct vmspace *nvm, *ovm = p->p_vmspace;
2922 
2923 	if (ovm->vm_refcnt == 1)
2924 		/* nothing to do: vmspace isn't shared in the first place */
2925 		return;
2926 
2927 	/* make a new vmspace, still holding old one */
2928 	nvm = uvmspace_fork(ovm);
2929 
2930 	pmap_deactivate(p);		/* unbind old vmspace */
2931 	p->p_vmspace = nvm;
2932 	pmap_activate(p);		/* switch to new vmspace */
2933 
2934 	uvmspace_free(ovm);		/* drop reference to old vmspace */
2935 }
2936 
2937 /*
2938  * uvmspace_exec: the process wants to exec a new program
2939  *
2940  * - XXX: no locking on vmspace
2941  */
2942 
2943 void
2944 uvmspace_exec(p, start, end)
2945 	struct proc *p;
2946 	vaddr_t start, end;
2947 {
2948 	struct vmspace *nvm, *ovm = p->p_vmspace;
2949 	struct vm_map *map = &ovm->vm_map;
2950 
2951 #ifdef __sparc__
2952 	/* XXX cgd 960926: the sparc #ifdef should be a MD hook */
2953 	kill_user_windows(p);   /* before stack addresses go away */
2954 #endif
2955 
2956 	/*
2957 	 * see if more than one process is using this vmspace...
2958 	 */
2959 
2960 	if (ovm->vm_refcnt == 1) {
2961 
2962 		/*
2963 		 * if p is the only process using its vmspace then we can safely
2964 		 * recycle that vmspace for the program that is being exec'd.
2965 		 */
2966 
2967 #ifdef SYSVSHM
2968 		/*
2969 		 * SYSV SHM semantics require us to kill all segments on an exec
2970 		 */
2971 
2972 		if (ovm->vm_shm)
2973 			shmexit(ovm);
2974 #endif
2975 
2976 		/*
2977 		 * POSIX 1003.1b -- "lock future mappings" is revoked
2978 		 * when a process execs another program image.
2979 		 */
2980 
2981 		vm_map_modflags(map, 0, VM_MAP_WIREFUTURE);
2982 
2983 		/*
2984 		 * now unmap the old program
2985 		 */
2986 
2987 		pmap_remove_all(map->pmap);
2988 		uvm_unmap(map, map->min_offset, map->max_offset);
2989 
2990 		/*
2991 		 * resize the map
2992 		 */
2993 
2994 		map->min_offset = start;
2995 		map->max_offset = end;
2996 	} else {
2997 
2998 		/*
2999 		 * p's vmspace is being shared, so we can't reuse it for p since
3000 		 * it is still being used for others.   allocate a new vmspace
3001 		 * for p
3002 		 */
3003 
3004 		nvm = uvmspace_alloc(start, end);
3005 
3006 		/*
3007 		 * install new vmspace and drop our ref to the old one.
3008 		 */
3009 
3010 		pmap_deactivate(p);
3011 		p->p_vmspace = nvm;
3012 		pmap_activate(p);
3013 
3014 		uvmspace_free(ovm);
3015 	}
3016 }
3017 
3018 /*
3019  * uvmspace_free: free a vmspace data structure
3020  *
3021  * - XXX: no locking on vmspace
3022  */
3023 
3024 void
3025 uvmspace_free(vm)
3026 	struct vmspace *vm;
3027 {
3028 	struct vm_map_entry *dead_entries;
3029 	struct vm_map *map;
3030 	UVMHIST_FUNC("uvmspace_free"); UVMHIST_CALLED(maphist);
3031 
3032 	UVMHIST_LOG(maphist,"(vm=0x%x) ref=%d", vm, vm->vm_refcnt,0,0);
3033 	if (--vm->vm_refcnt > 0) {
3034 		return;
3035 	}
3036 
3037 	/*
3038 	 * at this point, there should be no other references to the map.
3039 	 * delete all of the mappings, then destroy the pmap.
3040 	 */
3041 
3042 	map = &vm->vm_map;
3043 	map->flags |= VM_MAP_DYING;
3044 	pmap_remove_all(map->pmap);
3045 #ifdef SYSVSHM
3046 	/* Get rid of any SYSV shared memory segments. */
3047 	if (vm->vm_shm != NULL)
3048 		shmexit(vm);
3049 #endif
3050 	if (map->nentries) {
3051 		uvm_unmap_remove(map, map->min_offset, map->max_offset,
3052 		    &dead_entries);
3053 		if (dead_entries != NULL)
3054 			uvm_unmap_detach(dead_entries, 0);
3055 	}
3056 	pmap_destroy(map->pmap);
3057 	pool_put(&uvm_vmspace_pool, vm);
3058 }
3059 
3060 /*
3061  *   F O R K   -   m a i n   e n t r y   p o i n t
3062  */
3063 /*
3064  * uvmspace_fork: fork a process' main map
3065  *
3066  * => create a new vmspace for child process from parent.
3067  * => parent's map must not be locked.
3068  */
3069 
3070 struct vmspace *
3071 uvmspace_fork(vm1)
3072 	struct vmspace *vm1;
3073 {
3074 	struct vmspace *vm2;
3075 	struct vm_map *old_map = &vm1->vm_map;
3076 	struct vm_map *new_map;
3077 	struct vm_map_entry *old_entry;
3078 	struct vm_map_entry *new_entry;
3079 	pmap_t new_pmap;
3080 	UVMHIST_FUNC("uvmspace_fork"); UVMHIST_CALLED(maphist);
3081 
3082 	vm_map_lock(old_map);
3083 
3084 	vm2 = uvmspace_alloc(old_map->min_offset, old_map->max_offset);
3085 	memcpy(&vm2->vm_startcopy, &vm1->vm_startcopy,
3086 	(caddr_t) (vm1 + 1) - (caddr_t) &vm1->vm_startcopy);
3087 	new_map = &vm2->vm_map;		  /* XXX */
3088 	new_pmap = new_map->pmap;
3089 
3090 	old_entry = old_map->header.next;
3091 
3092 	/*
3093 	 * go entry-by-entry
3094 	 */
3095 
3096 	while (old_entry != &old_map->header) {
3097 
3098 		/*
3099 		 * first, some sanity checks on the old entry
3100 		 */
3101 
3102 		KASSERT(!UVM_ET_ISSUBMAP(old_entry));
3103 		KASSERT(UVM_ET_ISCOPYONWRITE(old_entry) ||
3104 			!UVM_ET_ISNEEDSCOPY(old_entry));
3105 
3106 		switch (old_entry->inheritance) {
3107 		case MAP_INHERIT_NONE:
3108 
3109 			/*
3110 			 * drop the mapping
3111 			 */
3112 
3113 			break;
3114 
3115 		case MAP_INHERIT_SHARE:
3116 
3117 			/*
3118 			 * share the mapping: this means we want the old and
3119 			 * new entries to share amaps and backing objects.
3120 			 */
3121 			/*
3122 			 * if the old_entry needs a new amap (due to prev fork)
3123 			 * then we need to allocate it now so that we have
3124 			 * something we own to share with the new_entry.   [in
3125 			 * other words, we need to clear needs_copy]
3126 			 */
3127 
3128 			if (UVM_ET_ISNEEDSCOPY(old_entry)) {
3129 				/* get our own amap, clears needs_copy */
3130 				amap_copy(old_map, old_entry, M_WAITOK, FALSE,
3131 				    0, 0);
3132 				/* XXXCDC: WAITOK??? */
3133 			}
3134 
3135 			new_entry = uvm_mapent_alloc(new_map);
3136 			/* old_entry -> new_entry */
3137 			uvm_mapent_copy(old_entry, new_entry);
3138 
3139 			/* new pmap has nothing wired in it */
3140 			new_entry->wired_count = 0;
3141 
3142 			/*
3143 			 * gain reference to object backing the map (can't
3144 			 * be a submap, already checked this case).
3145 			 */
3146 
3147 			if (new_entry->aref.ar_amap)
3148 				uvm_map_reference_amap(new_entry, AMAP_SHARED);
3149 
3150 			if (new_entry->object.uvm_obj &&
3151 			    new_entry->object.uvm_obj->pgops->pgo_reference)
3152 				new_entry->object.uvm_obj->
3153 				    pgops->pgo_reference(
3154 				        new_entry->object.uvm_obj);
3155 
3156 			/* insert entry at end of new_map's entry list */
3157 			uvm_map_entry_link(new_map, new_map->header.prev,
3158 			    new_entry);
3159 
3160 			break;
3161 
3162 		case MAP_INHERIT_COPY:
3163 
3164 			/*
3165 			 * copy-on-write the mapping (using mmap's
3166 			 * MAP_PRIVATE semantics)
3167 			 *
3168 			 * allocate new_entry, adjust reference counts.
3169 			 * (note that new references are read-only).
3170 			 */
3171 
3172 			new_entry = uvm_mapent_alloc(new_map);
3173 			/* old_entry -> new_entry */
3174 			uvm_mapent_copy(old_entry, new_entry);
3175 
3176 			if (new_entry->aref.ar_amap)
3177 				uvm_map_reference_amap(new_entry, 0);
3178 
3179 			if (new_entry->object.uvm_obj &&
3180 			    new_entry->object.uvm_obj->pgops->pgo_reference)
3181 				new_entry->object.uvm_obj->pgops->pgo_reference
3182 				    (new_entry->object.uvm_obj);
3183 
3184 			/* new pmap has nothing wired in it */
3185 			new_entry->wired_count = 0;
3186 
3187 			new_entry->etype |=
3188 			    (UVM_ET_COPYONWRITE|UVM_ET_NEEDSCOPY);
3189 			uvm_map_entry_link(new_map, new_map->header.prev,
3190 			    new_entry);
3191 
3192 			/*
3193 			 * the new entry will need an amap.  it will either
3194 			 * need to be copied from the old entry or created
3195 			 * from scratch (if the old entry does not have an
3196 			 * amap).  can we defer this process until later
3197 			 * (by setting "needs_copy") or do we need to copy
3198 			 * the amap now?
3199 			 *
3200 			 * we must copy the amap now if any of the following
3201 			 * conditions hold:
3202 			 * 1. the old entry has an amap and that amap is
3203 			 *    being shared.  this means that the old (parent)
3204 			 *    process is sharing the amap with another
3205 			 *    process.  if we do not clear needs_copy here
3206 			 *    we will end up in a situation where both the
3207 			 *    parent and child process are refering to the
3208 			 *    same amap with "needs_copy" set.  if the
3209 			 *    parent write-faults, the fault routine will
3210 			 *    clear "needs_copy" in the parent by allocating
3211 			 *    a new amap.   this is wrong because the
3212 			 *    parent is supposed to be sharing the old amap
3213 			 *    and the new amap will break that.
3214 			 *
3215 			 * 2. if the old entry has an amap and a non-zero
3216 			 *    wire count then we are going to have to call
3217 			 *    amap_cow_now to avoid page faults in the
3218 			 *    parent process.   since amap_cow_now requires
3219 			 *    "needs_copy" to be clear we might as well
3220 			 *    clear it here as well.
3221 			 *
3222 			 */
3223 
3224 			if (old_entry->aref.ar_amap != NULL) {
3225 				if ((amap_flags(old_entry->aref.ar_amap) &
3226 				     AMAP_SHARED) != 0 ||
3227 				    VM_MAPENT_ISWIRED(old_entry)) {
3228 
3229 					amap_copy(new_map, new_entry, M_WAITOK,
3230 					    FALSE, 0, 0);
3231 					/* XXXCDC: M_WAITOK ... ok? */
3232 				}
3233 			}
3234 
3235 			/*
3236 			 * if the parent's entry is wired down, then the
3237 			 * parent process does not want page faults on
3238 			 * access to that memory.  this means that we
3239 			 * cannot do copy-on-write because we can't write
3240 			 * protect the old entry.   in this case we
3241 			 * resolve all copy-on-write faults now, using
3242 			 * amap_cow_now.   note that we have already
3243 			 * allocated any needed amap (above).
3244 			 */
3245 
3246 			if (VM_MAPENT_ISWIRED(old_entry)) {
3247 
3248 			  /*
3249 			   * resolve all copy-on-write faults now
3250 			   * (note that there is nothing to do if
3251 			   * the old mapping does not have an amap).
3252 			   */
3253 			  if (old_entry->aref.ar_amap)
3254 			    amap_cow_now(new_map, new_entry);
3255 
3256 			} else {
3257 
3258 			  /*
3259 			   * setup mappings to trigger copy-on-write faults
3260 			   * we must write-protect the parent if it has
3261 			   * an amap and it is not already "needs_copy"...
3262 			   * if it is already "needs_copy" then the parent
3263 			   * has already been write-protected by a previous
3264 			   * fork operation.
3265 			   */
3266 
3267 			  if (old_entry->aref.ar_amap &&
3268 			      !UVM_ET_ISNEEDSCOPY(old_entry)) {
3269 			      if (old_entry->max_protection & VM_PROT_WRITE) {
3270 				pmap_protect(old_map->pmap,
3271 					     old_entry->start,
3272 					     old_entry->end,
3273 					     old_entry->protection &
3274 					     ~VM_PROT_WRITE);
3275 				pmap_update(old_map->pmap);
3276 			      }
3277 			      old_entry->etype |= UVM_ET_NEEDSCOPY;
3278 			  }
3279 			}
3280 			break;
3281 		}  /* end of switch statement */
3282 		old_entry = old_entry->next;
3283 	}
3284 
3285 	new_map->size = old_map->size;
3286 	vm_map_unlock(old_map);
3287 
3288 #ifdef SYSVSHM
3289 	if (vm1->vm_shm)
3290 		shmfork(vm1, vm2);
3291 #endif
3292 
3293 #ifdef PMAP_FORK
3294 	pmap_fork(vm1->vm_map.pmap, vm2->vm_map.pmap);
3295 #endif
3296 
3297 	UVMHIST_LOG(maphist,"<- done",0,0,0,0);
3298 	return(vm2);
3299 }
3300 
3301 
3302 #if defined(DDB)
3303 
3304 /*
3305  * DDB hooks
3306  */
3307 
3308 /*
3309  * uvm_map_printit: actually prints the map
3310  */
3311 
3312 void
3313 uvm_map_printit(map, full, pr)
3314 	struct vm_map *map;
3315 	boolean_t full;
3316 	void (*pr) __P((const char *, ...));
3317 {
3318 	struct vm_map_entry *entry;
3319 
3320 	(*pr)("MAP %p: [0x%lx->0x%lx]\n", map, map->min_offset,map->max_offset);
3321 	(*pr)("\t#ent=%d, sz=%d, ref=%d, version=%d, flags=0x%x\n",
3322 	    map->nentries, map->size, map->ref_count, map->timestamp,
3323 	    map->flags);
3324 	(*pr)("\tpmap=%p(resident=%d)\n", map->pmap,
3325 	    pmap_resident_count(map->pmap));
3326 	if (!full)
3327 		return;
3328 	for (entry = map->header.next; entry != &map->header;
3329 	    entry = entry->next) {
3330 		(*pr)(" - %p: 0x%lx->0x%lx: obj=%p/0x%llx, amap=%p/%d\n",
3331 		    entry, entry->start, entry->end, entry->object.uvm_obj,
3332 		    (long long)entry->offset, entry->aref.ar_amap,
3333 		    entry->aref.ar_pageoff);
3334 		(*pr)(
3335 		    "\tsubmap=%c, cow=%c, nc=%c, prot(max)=%d/%d, inh=%d, "
3336 		    "wc=%d, adv=%d\n",
3337 		    (entry->etype & UVM_ET_SUBMAP) ? 'T' : 'F',
3338 		    (entry->etype & UVM_ET_COPYONWRITE) ? 'T' : 'F',
3339 		    (entry->etype & UVM_ET_NEEDSCOPY) ? 'T' : 'F',
3340 		    entry->protection, entry->max_protection,
3341 		    entry->inheritance, entry->wired_count, entry->advice);
3342 	}
3343 }
3344 
3345 /*
3346  * uvm_object_printit: actually prints the object
3347  */
3348 
3349 void
3350 uvm_object_printit(uobj, full, pr)
3351 	struct uvm_object *uobj;
3352 	boolean_t full;
3353 	void (*pr) __P((const char *, ...));
3354 {
3355 	struct vm_page *pg;
3356 	int cnt = 0;
3357 
3358 	(*pr)("OBJECT %p: locked=%d, pgops=%p, npages=%d, ",
3359 	    uobj, uobj->vmobjlock.lock_data, uobj->pgops, uobj->uo_npages);
3360 	if (UVM_OBJ_IS_KERN_OBJECT(uobj))
3361 		(*pr)("refs=<SYSTEM>\n");
3362 	else
3363 		(*pr)("refs=%d\n", uobj->uo_refs);
3364 
3365 	if (!full) {
3366 		return;
3367 	}
3368 	(*pr)("  PAGES <pg,offset>:\n  ");
3369 	TAILQ_FOREACH(pg, &uobj->memq, listq) {
3370 		cnt++;
3371 		(*pr)("<%p,0x%llx> ", pg, (long long)pg->offset);
3372 		if ((cnt % 3) == 0) {
3373 			(*pr)("\n  ");
3374 		}
3375 	}
3376 	if ((cnt % 3) != 0) {
3377 		(*pr)("\n");
3378 	}
3379 }
3380 
3381 /*
3382  * uvm_page_printit: actually print the page
3383  */
3384 
3385 static const char page_flagbits[] =
3386 	"\20\1BUSY\2WANTED\3TABLED\4CLEAN\5PAGEOUT\6RELEASED\7FAKE\10RDONLY"
3387 	"\11ZERO\15PAGER1";
3388 static const char page_pqflagbits[] =
3389 	"\20\1FREE\2INACTIVE\3ACTIVE\5ANON\6AOBJ";
3390 
3391 void
3392 uvm_page_printit(pg, full, pr)
3393 	struct vm_page *pg;
3394 	boolean_t full;
3395 	void (*pr) __P((const char *, ...));
3396 {
3397 	struct vm_page *tpg;
3398 	struct uvm_object *uobj;
3399 	struct pglist *pgl;
3400 	char pgbuf[128];
3401 	char pqbuf[128];
3402 
3403 	(*pr)("PAGE %p:\n", pg);
3404 	bitmask_snprintf(pg->flags, page_flagbits, pgbuf, sizeof(pgbuf));
3405 	bitmask_snprintf(pg->pqflags, page_pqflagbits, pqbuf, sizeof(pqbuf));
3406 	(*pr)("  flags=%s, pqflags=%s, wire_count=%d, pa=0x%lx\n",
3407 	    pgbuf, pqbuf, pg->wire_count, (long)pg->phys_addr);
3408 	(*pr)("  uobject=%p, uanon=%p, offset=0x%llx loan_count=%d\n",
3409 	    pg->uobject, pg->uanon, (long long)pg->offset, pg->loan_count);
3410 #if defined(UVM_PAGE_TRKOWN)
3411 	if (pg->flags & PG_BUSY)
3412 		(*pr)("  owning process = %d, tag=%s\n",
3413 		    pg->owner, pg->owner_tag);
3414 	else
3415 		(*pr)("  page not busy, no owner\n");
3416 #else
3417 	(*pr)("  [page ownership tracking disabled]\n");
3418 #endif
3419 
3420 	if (!full)
3421 		return;
3422 
3423 	/* cross-verify object/anon */
3424 	if ((pg->pqflags & PQ_FREE) == 0) {
3425 		if (pg->pqflags & PQ_ANON) {
3426 			if (pg->uanon == NULL || pg->uanon->u.an_page != pg)
3427 			    (*pr)("  >>> ANON DOES NOT POINT HERE <<< (%p)\n",
3428 				(pg->uanon) ? pg->uanon->u.an_page : NULL);
3429 			else
3430 				(*pr)("  anon backpointer is OK\n");
3431 		} else {
3432 			uobj = pg->uobject;
3433 			if (uobj) {
3434 				(*pr)("  checking object list\n");
3435 				TAILQ_FOREACH(tpg, &uobj->memq, listq) {
3436 					if (tpg == pg) {
3437 						break;
3438 					}
3439 				}
3440 				if (tpg)
3441 					(*pr)("  page found on object list\n");
3442 				else
3443 			(*pr)("  >>> PAGE NOT FOUND ON OBJECT LIST! <<<\n");
3444 			}
3445 		}
3446 	}
3447 
3448 	/* cross-verify page queue */
3449 	if (pg->pqflags & PQ_FREE) {
3450 		int fl = uvm_page_lookup_freelist(pg);
3451 		int color = VM_PGCOLOR_BUCKET(pg);
3452 		pgl = &uvm.page_free[fl].pgfl_buckets[color].pgfl_queues[
3453 		    ((pg)->flags & PG_ZERO) ? PGFL_ZEROS : PGFL_UNKNOWN];
3454 	} else if (pg->pqflags & PQ_INACTIVE) {
3455 		pgl = &uvm.page_inactive;
3456 	} else if (pg->pqflags & PQ_ACTIVE) {
3457 		pgl = &uvm.page_active;
3458  	} else {
3459 		pgl = NULL;
3460 	}
3461 
3462 	if (pgl) {
3463 		(*pr)("  checking pageq list\n");
3464 		TAILQ_FOREACH(tpg, pgl, pageq) {
3465 			if (tpg == pg) {
3466 				break;
3467 			}
3468 		}
3469 		if (tpg)
3470 			(*pr)("  page found on pageq list\n");
3471 		else
3472 			(*pr)("  >>> PAGE NOT FOUND ON PAGEQ LIST! <<<\n");
3473 	}
3474 }
3475 #endif
3476