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