xref: /freebsd/sys/vm/vm_map.c (revision a1a4f1a0d87b594d3f17a97dc0127eec1417e6f6)
1 /*
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * The Mach Operating System project at Carnegie-Mellon University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	from: @(#)vm_map.c	8.3 (Berkeley) 1/12/94
37  *
38  *
39  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
40  * All rights reserved.
41  *
42  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
43  *
44  * Permission to use, copy, modify and distribute this software and
45  * its documentation is hereby granted, provided that both the copyright
46  * notice and this permission notice appear in all copies of the
47  * software, derivative works or modified versions, and any portions
48  * thereof, and that both notices appear in supporting documentation.
49  *
50  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
51  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
52  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
53  *
54  * Carnegie Mellon requests users of this software to return to
55  *
56  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
57  *  School of Computer Science
58  *  Carnegie Mellon University
59  *  Pittsburgh PA 15213-3890
60  *
61  * any improvements or extensions that they make and grant Carnegie the
62  * rights to redistribute these changes.
63  *
64  * $FreeBSD$
65  */
66 
67 /*
68  *	Virtual memory mapping module.
69  */
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/malloc.h>
74 #include <sys/proc.h>
75 #include <sys/vmmeter.h>
76 #include <sys/mman.h>
77 #include <sys/vnode.h>
78 #include <sys/resourcevar.h>
79 
80 #include <vm/vm.h>
81 #include <vm/vm_param.h>
82 #include <vm/vm_prot.h>
83 #include <vm/vm_inherit.h>
84 #include <sys/lock.h>
85 #include <vm/pmap.h>
86 #include <vm/vm_map.h>
87 #include <vm/vm_page.h>
88 #include <vm/vm_object.h>
89 #include <vm/vm_pager.h>
90 #include <vm/vm_kern.h>
91 #include <vm/vm_extern.h>
92 #include <vm/default_pager.h>
93 #include <vm/swap_pager.h>
94 #include <vm/vm_zone.h>
95 
96 /*
97  *	Virtual memory maps provide for the mapping, protection,
98  *	and sharing of virtual memory objects.  In addition,
99  *	this module provides for an efficient virtual copy of
100  *	memory from one map to another.
101  *
102  *	Synchronization is required prior to most operations.
103  *
104  *	Maps consist of an ordered doubly-linked list of simple
105  *	entries; a single hint is used to speed up lookups.
106  *
107  *	Since portions of maps are specified by start/end addreses,
108  *	which may not align with existing map entries, all
109  *	routines merely "clip" entries to these start/end values.
110  *	[That is, an entry is split into two, bordering at a
111  *	start or end value.]  Note that these clippings may not
112  *	always be necessary (as the two resulting entries are then
113  *	not changed); however, the clipping is done for convenience.
114  *
115  *	As mentioned above, virtual copy operations are performed
116  *	by copying VM object references from one map to
117  *	another, and then marking both regions as copy-on-write.
118  */
119 
120 /*
121  *	vm_map_startup:
122  *
123  *	Initialize the vm_map module.  Must be called before
124  *	any other vm_map routines.
125  *
126  *	Map and entry structures are allocated from the general
127  *	purpose memory pool with some exceptions:
128  *
129  *	- The kernel map and kmem submap are allocated statically.
130  *	- Kernel map entries are allocated out of a static pool.
131  *
132  *	These restrictions are necessary since malloc() uses the
133  *	maps and requires map entries.
134  */
135 
136 static struct vm_zone kmapentzone_store, mapentzone_store, mapzone_store;
137 static vm_zone_t mapentzone, kmapentzone, mapzone, vmspace_zone;
138 static struct vm_object kmapentobj, mapentobj, mapobj;
139 
140 static struct vm_map_entry map_entry_init[MAX_MAPENT];
141 static struct vm_map_entry kmap_entry_init[MAX_KMAPENT];
142 static struct vm_map map_init[MAX_KMAP];
143 
144 static void _vm_map_clip_end __P((vm_map_t, vm_map_entry_t, vm_offset_t));
145 static void _vm_map_clip_start __P((vm_map_t, vm_map_entry_t, vm_offset_t));
146 static vm_map_entry_t vm_map_entry_create __P((vm_map_t));
147 static void vm_map_entry_delete __P((vm_map_t, vm_map_entry_t));
148 static void vm_map_entry_dispose __P((vm_map_t, vm_map_entry_t));
149 static void vm_map_entry_unwire __P((vm_map_t, vm_map_entry_t));
150 static void vm_map_copy_entry __P((vm_map_t, vm_map_t, vm_map_entry_t,
151 		vm_map_entry_t));
152 static void vm_map_split __P((vm_map_entry_t));
153 
154 void
155 vm_map_startup()
156 {
157 	mapzone = &mapzone_store;
158 	zbootinit(mapzone, "MAP", sizeof (struct vm_map),
159 		map_init, MAX_KMAP);
160 	kmapentzone = &kmapentzone_store;
161 	zbootinit(kmapentzone, "KMAP ENTRY", sizeof (struct vm_map_entry),
162 		kmap_entry_init, MAX_KMAPENT);
163 	mapentzone = &mapentzone_store;
164 	zbootinit(mapentzone, "MAP ENTRY", sizeof (struct vm_map_entry),
165 		map_entry_init, MAX_MAPENT);
166 }
167 
168 /*
169  * Allocate a vmspace structure, including a vm_map and pmap,
170  * and initialize those structures.  The refcnt is set to 1.
171  * The remaining fields must be initialized by the caller.
172  */
173 struct vmspace *
174 vmspace_alloc(min, max)
175 	vm_offset_t min, max;
176 {
177 	struct vmspace *vm;
178 
179 	vm = zalloc(vmspace_zone);
180 	vm_map_init(&vm->vm_map, min, max);
181 	pmap_pinit(vmspace_pmap(vm));
182 	vm->vm_map.pmap = vmspace_pmap(vm);		/* XXX */
183 	vm->vm_refcnt = 1;
184 	vm->vm_shm = NULL;
185 	return (vm);
186 }
187 
188 void
189 vm_init2(void) {
190 	zinitna(kmapentzone, &kmapentobj,
191 		NULL, 0, cnt.v_page_count / 4, ZONE_INTERRUPT, 1);
192 	zinitna(mapentzone, &mapentobj,
193 		NULL, 0, 0, 0, 1);
194 	zinitna(mapzone, &mapobj,
195 		NULL, 0, 0, 0, 1);
196 	vmspace_zone = zinit("VMSPACE", sizeof (struct vmspace), 0, 0, 3);
197 	pmap_init2();
198 	vm_object_init2();
199 }
200 
201 void
202 vmspace_free(vm)
203 	struct vmspace *vm;
204 {
205 
206 	if (vm->vm_refcnt == 0)
207 		panic("vmspace_free: attempt to free already freed vmspace");
208 
209 	if (--vm->vm_refcnt == 0) {
210 
211 		/*
212 		 * Lock the map, to wait out all other references to it.
213 		 * Delete all of the mappings and pages they hold, then call
214 		 * the pmap module to reclaim anything left.
215 		 */
216 		vm_map_lock(&vm->vm_map);
217 		(void) vm_map_delete(&vm->vm_map, vm->vm_map.min_offset,
218 		    vm->vm_map.max_offset);
219 		vm_map_unlock(&vm->vm_map);
220 
221 		pmap_release(vmspace_pmap(vm));
222 		zfree(vmspace_zone, vm);
223 	}
224 }
225 
226 /*
227  *	vm_map_create:
228  *
229  *	Creates and returns a new empty VM map with
230  *	the given physical map structure, and having
231  *	the given lower and upper address bounds.
232  */
233 vm_map_t
234 vm_map_create(pmap, min, max)
235 	pmap_t pmap;
236 	vm_offset_t min, max;
237 {
238 	vm_map_t result;
239 
240 	result = zalloc(mapzone);
241 	vm_map_init(result, min, max);
242 	result->pmap = pmap;
243 	return (result);
244 }
245 
246 /*
247  * Initialize an existing vm_map structure
248  * such as that in the vmspace structure.
249  * The pmap is set elsewhere.
250  */
251 void
252 vm_map_init(map, min, max)
253 	struct vm_map *map;
254 	vm_offset_t min, max;
255 {
256 	map->header.next = map->header.prev = &map->header;
257 	map->nentries = 0;
258 	map->size = 0;
259 	map->system_map = 0;
260 	map->min_offset = min;
261 	map->max_offset = max;
262 	map->first_free = &map->header;
263 	map->hint = &map->header;
264 	map->timestamp = 0;
265 	lockinit(&map->lock, PVM, "thrd_sleep", 0, LK_NOPAUSE);
266 }
267 
268 /*
269  *	vm_map_entry_dispose:	[ internal use only ]
270  *
271  *	Inverse of vm_map_entry_create.
272  */
273 static void
274 vm_map_entry_dispose(map, entry)
275 	vm_map_t map;
276 	vm_map_entry_t entry;
277 {
278 	zfree((map->system_map || !mapentzone) ? kmapentzone : mapentzone, entry);
279 }
280 
281 /*
282  *	vm_map_entry_create:	[ internal use only ]
283  *
284  *	Allocates a VM map entry for insertion.
285  *	No entry fields are filled in.  This routine is
286  */
287 static vm_map_entry_t
288 vm_map_entry_create(map)
289 	vm_map_t map;
290 {
291 	return zalloc((map->system_map || !mapentzone) ? kmapentzone : mapentzone);
292 }
293 
294 /*
295  *	vm_map_entry_{un,}link:
296  *
297  *	Insert/remove entries from maps.
298  */
299 static __inline void
300 vm_map_entry_link(vm_map_t map,
301 		  vm_map_entry_t after_where,
302 		  vm_map_entry_t entry)
303 {
304 	map->nentries++;
305 	entry->prev = after_where;
306 	entry->next = after_where->next;
307 	entry->next->prev = entry;
308 	after_where->next = entry;
309 }
310 
311 static __inline void
312 vm_map_entry_unlink(vm_map_t map,
313 		    vm_map_entry_t entry)
314 {
315 	vm_map_entry_t prev = entry->prev;
316 	vm_map_entry_t next = entry->next;
317 
318 	next->prev = prev;
319 	prev->next = next;
320 	map->nentries--;
321 }
322 
323 /*
324  *	SAVE_HINT:
325  *
326  *	Saves the specified entry as the hint for
327  *	future lookups.
328  */
329 #define	SAVE_HINT(map,value) \
330 		(map)->hint = (value);
331 
332 /*
333  *	vm_map_lookup_entry:	[ internal use only ]
334  *
335  *	Finds the map entry containing (or
336  *	immediately preceding) the specified address
337  *	in the given map; the entry is returned
338  *	in the "entry" parameter.  The boolean
339  *	result indicates whether the address is
340  *	actually contained in the map.
341  */
342 boolean_t
343 vm_map_lookup_entry(map, address, entry)
344 	vm_map_t map;
345 	vm_offset_t address;
346 	vm_map_entry_t *entry;	/* OUT */
347 {
348 	vm_map_entry_t cur;
349 	vm_map_entry_t last;
350 
351 	/*
352 	 * Start looking either from the head of the list, or from the hint.
353 	 */
354 
355 	cur = map->hint;
356 
357 	if (cur == &map->header)
358 		cur = cur->next;
359 
360 	if (address >= cur->start) {
361 		/*
362 		 * Go from hint to end of list.
363 		 *
364 		 * But first, make a quick check to see if we are already looking
365 		 * at the entry we want (which is usually the case). Note also
366 		 * that we don't need to save the hint here... it is the same
367 		 * hint (unless we are at the header, in which case the hint
368 		 * didn't buy us anything anyway).
369 		 */
370 		last = &map->header;
371 		if ((cur != last) && (cur->end > address)) {
372 			*entry = cur;
373 			return (TRUE);
374 		}
375 	} else {
376 		/*
377 		 * Go from start to hint, *inclusively*
378 		 */
379 		last = cur->next;
380 		cur = map->header.next;
381 	}
382 
383 	/*
384 	 * Search linearly
385 	 */
386 
387 	while (cur != last) {
388 		if (cur->end > address) {
389 			if (address >= cur->start) {
390 				/*
391 				 * Save this lookup for future hints, and
392 				 * return
393 				 */
394 
395 				*entry = cur;
396 				SAVE_HINT(map, cur);
397 				return (TRUE);
398 			}
399 			break;
400 		}
401 		cur = cur->next;
402 	}
403 	*entry = cur->prev;
404 	SAVE_HINT(map, *entry);
405 	return (FALSE);
406 }
407 
408 /*
409  *	vm_map_insert:
410  *
411  *	Inserts the given whole VM object into the target
412  *	map at the specified address range.  The object's
413  *	size should match that of the address range.
414  *
415  *	Requires that the map be locked, and leaves it so.
416  *
417  *	If object is non-NULL, ref count must be bumped by caller
418  *	prior to making call to account for the new entry.
419  */
420 int
421 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
422 	      vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max,
423 	      int cow)
424 {
425 	vm_map_entry_t new_entry;
426 	vm_map_entry_t prev_entry;
427 	vm_map_entry_t temp_entry;
428 	u_char protoeflags;
429 
430 	/*
431 	 * Check that the start and end points are not bogus.
432 	 */
433 
434 	if ((start < map->min_offset) || (end > map->max_offset) ||
435 	    (start >= end))
436 		return (KERN_INVALID_ADDRESS);
437 
438 	/*
439 	 * Find the entry prior to the proposed starting address; if it's part
440 	 * of an existing entry, this range is bogus.
441 	 */
442 
443 	if (vm_map_lookup_entry(map, start, &temp_entry))
444 		return (KERN_NO_SPACE);
445 
446 	prev_entry = temp_entry;
447 
448 	/*
449 	 * Assert that the next entry doesn't overlap the end point.
450 	 */
451 
452 	if ((prev_entry->next != &map->header) &&
453 	    (prev_entry->next->start < end))
454 		return (KERN_NO_SPACE);
455 
456 	protoeflags = 0;
457 
458 	if (cow & MAP_COPY_ON_WRITE)
459 		protoeflags |= MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY;
460 
461 	if (cow & MAP_NOFAULT) {
462 		protoeflags |= MAP_ENTRY_NOFAULT;
463 
464 		KASSERT(object == NULL,
465 			("vm_map_insert: paradoxical MAP_NOFAULT request"));
466 	}
467 	if (object) {
468 		/*
469 		 * When object is non-NULL, it could be shared with another
470 		 * process.  We have to set or clear OBJ_ONEMAPPING
471 		 * appropriately.
472 		 */
473 		if ((object->ref_count > 1) || (object->shadow_count != 0)) {
474 			vm_object_clear_flag(object, OBJ_ONEMAPPING);
475 		}
476 	}
477 	else if ((prev_entry != &map->header) &&
478 		 (prev_entry->eflags == protoeflags) &&
479 		 (prev_entry->end == start) &&
480 		 (prev_entry->wired_count == 0) &&
481 		 ((prev_entry->object.vm_object == NULL) ||
482 		  vm_object_coalesce(prev_entry->object.vm_object,
483 				     OFF_TO_IDX(prev_entry->offset),
484 				     (vm_size_t)(prev_entry->end - prev_entry->start),
485 				     (vm_size_t)(end - prev_entry->end)))) {
486 		/*
487 		 * We were able to extend the object.  Determine if we
488 		 * can extend the previous map entry to include the
489 		 * new range as well.
490 		 */
491 		if ((prev_entry->inheritance == VM_INHERIT_DEFAULT) &&
492 		    (prev_entry->protection == prot) &&
493 		    (prev_entry->max_protection == max)) {
494 			map->size += (end - prev_entry->end);
495 			prev_entry->end = end;
496 			return (KERN_SUCCESS);
497 		}
498 
499 		/*
500 		 * If we can extend the object but cannot extend the
501 		 * map entry, we have to create a new map entry.  We
502 		 * must bump the ref count on the extended object to
503 		 * account for it.
504 		 */
505 		object = prev_entry->object.vm_object;
506 		offset = prev_entry->offset +
507 			(prev_entry->end - prev_entry->start);
508 		vm_object_reference(object);
509 	}
510 
511 	/*
512 	 * NOTE: if conditionals fail, object can be NULL here.  This occurs
513 	 * in things like the buffer map where we manage kva but do not manage
514 	 * backing objects.
515 	 */
516 
517 	/*
518 	 * Create a new entry
519 	 */
520 
521 	new_entry = vm_map_entry_create(map);
522 	new_entry->start = start;
523 	new_entry->end = end;
524 
525 	new_entry->eflags = protoeflags;
526 	new_entry->object.vm_object = object;
527 	new_entry->offset = offset;
528 	new_entry->avail_ssize = 0;
529 
530 	new_entry->inheritance = VM_INHERIT_DEFAULT;
531 	new_entry->protection = prot;
532 	new_entry->max_protection = max;
533 	new_entry->wired_count = 0;
534 
535 	/*
536 	 * Insert the new entry into the list
537 	 */
538 
539 	vm_map_entry_link(map, prev_entry, new_entry);
540 	map->size += new_entry->end - new_entry->start;
541 
542 	/*
543 	 * Update the free space hint
544 	 */
545 	if ((map->first_free == prev_entry) &&
546 	    (prev_entry->end >= new_entry->start))
547 		map->first_free = new_entry;
548 
549 	if (cow & (MAP_PREFAULT|MAP_PREFAULT_PARTIAL))
550 		pmap_object_init_pt(map->pmap, start,
551 				    object, OFF_TO_IDX(offset), end - start,
552 				    cow & MAP_PREFAULT_PARTIAL);
553 
554 	return (KERN_SUCCESS);
555 }
556 
557 /*
558  * Find sufficient space for `length' bytes in the given map, starting at
559  * `start'.  The map must be locked.  Returns 0 on success, 1 on no space.
560  */
561 int
562 vm_map_findspace(map, start, length, addr)
563 	vm_map_t map;
564 	vm_offset_t start;
565 	vm_size_t length;
566 	vm_offset_t *addr;
567 {
568 	vm_map_entry_t entry, next;
569 	vm_offset_t end;
570 
571 	if (start < map->min_offset)
572 		start = map->min_offset;
573 	if (start > map->max_offset)
574 		return (1);
575 
576 	/*
577 	 * Look for the first possible address; if there's already something
578 	 * at this address, we have to start after it.
579 	 */
580 	if (start == map->min_offset) {
581 		if ((entry = map->first_free) != &map->header)
582 			start = entry->end;
583 	} else {
584 		vm_map_entry_t tmp;
585 
586 		if (vm_map_lookup_entry(map, start, &tmp))
587 			start = tmp->end;
588 		entry = tmp;
589 	}
590 
591 	/*
592 	 * Look through the rest of the map, trying to fit a new region in the
593 	 * gap between existing regions, or after the very last region.
594 	 */
595 	for (;; start = (entry = next)->end) {
596 		/*
597 		 * Find the end of the proposed new region.  Be sure we didn't
598 		 * go beyond the end of the map, or wrap around the address;
599 		 * if so, we lose.  Otherwise, if this is the last entry, or
600 		 * if the proposed new region fits before the next entry, we
601 		 * win.
602 		 */
603 		end = start + length;
604 		if (end > map->max_offset || end < start)
605 			return (1);
606 		next = entry->next;
607 		if (next == &map->header || next->start >= end)
608 			break;
609 	}
610 	SAVE_HINT(map, entry);
611 	*addr = start;
612 	if (map == kernel_map) {
613 		vm_offset_t ksize;
614 		if ((ksize = round_page(start + length)) > kernel_vm_end) {
615 			pmap_growkernel(ksize);
616 		}
617 	}
618 	return (0);
619 }
620 
621 /*
622  *	vm_map_find finds an unallocated region in the target address
623  *	map with the given length.  The search is defined to be
624  *	first-fit from the specified address; the region found is
625  *	returned in the same parameter.
626  *
627  *	If object is non-NULL, ref count must be bumped by caller
628  *	prior to making call to account for the new entry.
629  */
630 int
631 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
632 	    vm_offset_t *addr,	/* IN/OUT */
633 	    vm_size_t length, boolean_t find_space, vm_prot_t prot,
634 	    vm_prot_t max, int cow)
635 {
636 	vm_offset_t start;
637 	int result, s = 0;
638 
639 	start = *addr;
640 
641 	if (map == kmem_map || map == mb_map)
642 		s = splvm();
643 
644 	vm_map_lock(map);
645 	if (find_space) {
646 		if (vm_map_findspace(map, start, length, addr)) {
647 			vm_map_unlock(map);
648 			if (map == kmem_map || map == mb_map)
649 				splx(s);
650 			return (KERN_NO_SPACE);
651 		}
652 		start = *addr;
653 	}
654 	result = vm_map_insert(map, object, offset,
655 		start, start + length, prot, max, cow);
656 	vm_map_unlock(map);
657 
658 	if (map == kmem_map || map == mb_map)
659 		splx(s);
660 
661 	return (result);
662 }
663 
664 /*
665  *	vm_map_simplify_entry:
666  *
667  *	Simplify the given map entry by merging with either neighbor.
668  */
669 void
670 vm_map_simplify_entry(map, entry)
671 	vm_map_t map;
672 	vm_map_entry_t entry;
673 {
674 	vm_map_entry_t next, prev;
675 	vm_size_t prevsize, esize;
676 
677 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
678 		return;
679 
680 	prev = entry->prev;
681 	if (prev != &map->header) {
682 		prevsize = prev->end - prev->start;
683 		if ( (prev->end == entry->start) &&
684 		     (prev->object.vm_object == entry->object.vm_object) &&
685 		     (!prev->object.vm_object ||
686 			(prev->offset + prevsize == entry->offset)) &&
687 		     (prev->eflags == entry->eflags) &&
688 		     (prev->protection == entry->protection) &&
689 		     (prev->max_protection == entry->max_protection) &&
690 		     (prev->inheritance == entry->inheritance) &&
691 		     (prev->wired_count == entry->wired_count)) {
692 			if (map->first_free == prev)
693 				map->first_free = entry;
694 			if (map->hint == prev)
695 				map->hint = entry;
696 			vm_map_entry_unlink(map, prev);
697 			entry->start = prev->start;
698 			entry->offset = prev->offset;
699 			if (prev->object.vm_object)
700 				vm_object_deallocate(prev->object.vm_object);
701 			vm_map_entry_dispose(map, prev);
702 		}
703 	}
704 
705 	next = entry->next;
706 	if (next != &map->header) {
707 		esize = entry->end - entry->start;
708 		if ((entry->end == next->start) &&
709 		    (next->object.vm_object == entry->object.vm_object) &&
710 		     (!entry->object.vm_object ||
711 			(entry->offset + esize == next->offset)) &&
712 		    (next->eflags == entry->eflags) &&
713 		    (next->protection == entry->protection) &&
714 		    (next->max_protection == entry->max_protection) &&
715 		    (next->inheritance == entry->inheritance) &&
716 		    (next->wired_count == entry->wired_count)) {
717 			if (map->first_free == next)
718 				map->first_free = entry;
719 			if (map->hint == next)
720 				map->hint = entry;
721 			vm_map_entry_unlink(map, next);
722 			entry->end = next->end;
723 			if (next->object.vm_object)
724 				vm_object_deallocate(next->object.vm_object);
725 			vm_map_entry_dispose(map, next);
726 	        }
727 	}
728 }
729 /*
730  *	vm_map_clip_start:	[ internal use only ]
731  *
732  *	Asserts that the given entry begins at or after
733  *	the specified address; if necessary,
734  *	it splits the entry into two.
735  */
736 #define vm_map_clip_start(map, entry, startaddr) \
737 { \
738 	if (startaddr > entry->start) \
739 		_vm_map_clip_start(map, entry, startaddr); \
740 }
741 
742 /*
743  *	This routine is called only when it is known that
744  *	the entry must be split.
745  */
746 static void
747 _vm_map_clip_start(map, entry, start)
748 	vm_map_t map;
749 	vm_map_entry_t entry;
750 	vm_offset_t start;
751 {
752 	vm_map_entry_t new_entry;
753 
754 	/*
755 	 * Split off the front portion -- note that we must insert the new
756 	 * entry BEFORE this one, so that this entry has the specified
757 	 * starting address.
758 	 */
759 
760 	vm_map_simplify_entry(map, entry);
761 
762 	/*
763 	 * If there is no object backing this entry, we might as well create
764 	 * one now.  If we defer it, an object can get created after the map
765 	 * is clipped, and individual objects will be created for the split-up
766 	 * map.  This is a bit of a hack, but is also about the best place to
767 	 * put this improvement.
768 	 */
769 
770 	if (entry->object.vm_object == NULL) {
771 		vm_object_t object;
772 		object = vm_object_allocate(OBJT_DEFAULT,
773 				atop(entry->end - entry->start));
774 		entry->object.vm_object = object;
775 		entry->offset = 0;
776 	}
777 
778 	new_entry = vm_map_entry_create(map);
779 	*new_entry = *entry;
780 
781 	new_entry->end = start;
782 	entry->offset += (start - entry->start);
783 	entry->start = start;
784 
785 	vm_map_entry_link(map, entry->prev, new_entry);
786 
787 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
788 		vm_object_reference(new_entry->object.vm_object);
789 	}
790 }
791 
792 /*
793  *	vm_map_clip_end:	[ internal use only ]
794  *
795  *	Asserts that the given entry ends at or before
796  *	the specified address; if necessary,
797  *	it splits the entry into two.
798  */
799 
800 #define vm_map_clip_end(map, entry, endaddr) \
801 { \
802 	if (endaddr < entry->end) \
803 		_vm_map_clip_end(map, entry, endaddr); \
804 }
805 
806 /*
807  *	This routine is called only when it is known that
808  *	the entry must be split.
809  */
810 static void
811 _vm_map_clip_end(map, entry, end)
812 	vm_map_t map;
813 	vm_map_entry_t entry;
814 	vm_offset_t end;
815 {
816 	vm_map_entry_t new_entry;
817 
818 	/*
819 	 * If there is no object backing this entry, we might as well create
820 	 * one now.  If we defer it, an object can get created after the map
821 	 * is clipped, and individual objects will be created for the split-up
822 	 * map.  This is a bit of a hack, but is also about the best place to
823 	 * put this improvement.
824 	 */
825 
826 	if (entry->object.vm_object == NULL) {
827 		vm_object_t object;
828 		object = vm_object_allocate(OBJT_DEFAULT,
829 				atop(entry->end - entry->start));
830 		entry->object.vm_object = object;
831 		entry->offset = 0;
832 	}
833 
834 	/*
835 	 * Create a new entry and insert it AFTER the specified entry
836 	 */
837 
838 	new_entry = vm_map_entry_create(map);
839 	*new_entry = *entry;
840 
841 	new_entry->start = entry->end = end;
842 	new_entry->offset += (end - entry->start);
843 
844 	vm_map_entry_link(map, entry, new_entry);
845 
846 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
847 		vm_object_reference(new_entry->object.vm_object);
848 	}
849 }
850 
851 /*
852  *	VM_MAP_RANGE_CHECK:	[ internal use only ]
853  *
854  *	Asserts that the starting and ending region
855  *	addresses fall within the valid range of the map.
856  */
857 #define	VM_MAP_RANGE_CHECK(map, start, end)		\
858 		{					\
859 		if (start < vm_map_min(map))		\
860 			start = vm_map_min(map);	\
861 		if (end > vm_map_max(map))		\
862 			end = vm_map_max(map);		\
863 		if (start > end)			\
864 			start = end;			\
865 		}
866 
867 /*
868  *	vm_map_submap:		[ kernel use only ]
869  *
870  *	Mark the given range as handled by a subordinate map.
871  *
872  *	This range must have been created with vm_map_find,
873  *	and no other operations may have been performed on this
874  *	range prior to calling vm_map_submap.
875  *
876  *	Only a limited number of operations can be performed
877  *	within this rage after calling vm_map_submap:
878  *		vm_fault
879  *	[Don't try vm_map_copy!]
880  *
881  *	To remove a submapping, one must first remove the
882  *	range from the superior map, and then destroy the
883  *	submap (if desired).  [Better yet, don't try it.]
884  */
885 int
886 vm_map_submap(map, start, end, submap)
887 	vm_map_t map;
888 	vm_offset_t start;
889 	vm_offset_t end;
890 	vm_map_t submap;
891 {
892 	vm_map_entry_t entry;
893 	int result = KERN_INVALID_ARGUMENT;
894 
895 	vm_map_lock(map);
896 
897 	VM_MAP_RANGE_CHECK(map, start, end);
898 
899 	if (vm_map_lookup_entry(map, start, &entry)) {
900 		vm_map_clip_start(map, entry, start);
901 	} else
902 		entry = entry->next;
903 
904 	vm_map_clip_end(map, entry, end);
905 
906 	if ((entry->start == start) && (entry->end == end) &&
907 	    ((entry->eflags & MAP_ENTRY_COW) == 0) &&
908 	    (entry->object.vm_object == NULL)) {
909 		entry->object.sub_map = submap;
910 		entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
911 		result = KERN_SUCCESS;
912 	}
913 	vm_map_unlock(map);
914 
915 	return (result);
916 }
917 
918 /*
919  *	vm_map_protect:
920  *
921  *	Sets the protection of the specified address
922  *	region in the target map.  If "set_max" is
923  *	specified, the maximum protection is to be set;
924  *	otherwise, only the current protection is affected.
925  */
926 int
927 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
928 	       vm_prot_t new_prot, boolean_t set_max)
929 {
930 	vm_map_entry_t current;
931 	vm_map_entry_t entry;
932 
933 	vm_map_lock(map);
934 
935 	VM_MAP_RANGE_CHECK(map, start, end);
936 
937 	if (vm_map_lookup_entry(map, start, &entry)) {
938 		vm_map_clip_start(map, entry, start);
939 	} else {
940 		entry = entry->next;
941 	}
942 
943 	/*
944 	 * Make a first pass to check for protection violations.
945 	 */
946 
947 	current = entry;
948 	while ((current != &map->header) && (current->start < end)) {
949 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
950 			vm_map_unlock(map);
951 			return (KERN_INVALID_ARGUMENT);
952 		}
953 		if ((new_prot & current->max_protection) != new_prot) {
954 			vm_map_unlock(map);
955 			return (KERN_PROTECTION_FAILURE);
956 		}
957 		current = current->next;
958 	}
959 
960 	/*
961 	 * Go back and fix up protections. [Note that clipping is not
962 	 * necessary the second time.]
963 	 */
964 
965 	current = entry;
966 
967 	while ((current != &map->header) && (current->start < end)) {
968 		vm_prot_t old_prot;
969 
970 		vm_map_clip_end(map, current, end);
971 
972 		old_prot = current->protection;
973 		if (set_max)
974 			current->protection =
975 			    (current->max_protection = new_prot) &
976 			    old_prot;
977 		else
978 			current->protection = new_prot;
979 
980 		/*
981 		 * Update physical map if necessary. Worry about copy-on-write
982 		 * here -- CHECK THIS XXX
983 		 */
984 
985 		if (current->protection != old_prot) {
986 #define MASK(entry)	(((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
987 							VM_PROT_ALL)
988 
989 			pmap_protect(map->pmap, current->start,
990 			    current->end,
991 			    current->protection & MASK(current));
992 #undef	MASK
993 		}
994 
995 		vm_map_simplify_entry(map, current);
996 
997 		current = current->next;
998 	}
999 
1000 	vm_map_unlock(map);
1001 	return (KERN_SUCCESS);
1002 }
1003 
1004 /*
1005  *	vm_map_madvise:
1006  *
1007  * 	This routine traverses a processes map handling the madvise
1008  *	system call.  Advisories are classified as either those effecting
1009  *	the vm_map_entry structure, or those effecting the underlying
1010  *	objects.
1011  */
1012 void
1013 vm_map_madvise(map, start, end, behav)
1014 	vm_map_t map;
1015 	vm_offset_t start, end;
1016 	int behav;
1017 {
1018 	vm_map_entry_t current, entry;
1019 	int modify_map;
1020 
1021 	modify_map = (behav == MADV_NORMAL || behav == MADV_SEQUENTIAL ||
1022 		      behav == MADV_RANDOM);
1023 
1024 	if (modify_map) {
1025 		vm_map_lock(map);
1026 	}
1027 	else
1028 		vm_map_lock_read(map);
1029 
1030 	VM_MAP_RANGE_CHECK(map, start, end);
1031 
1032 	if (vm_map_lookup_entry(map, start, &entry)) {
1033 		if (modify_map)
1034 			vm_map_clip_start(map, entry, start);
1035 	} else
1036 		entry = entry->next;
1037 
1038 	if (modify_map) {
1039 		/*
1040 		 * madvise behaviors that are implemented in the vm_map_entry.
1041 		 *
1042 		 * We clip the vm_map_entry so that behavioral changes are
1043 		 * limited to the specified address range.
1044 		 */
1045 		for (current = entry;
1046 		     (current != &map->header) && (current->start < end);
1047 		     current = current->next) {
1048 
1049 			if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
1050 				continue;
1051 
1052 			vm_map_clip_end(map, current, end);
1053 
1054 			switch (behav) {
1055 			case MADV_NORMAL:
1056 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
1057 				break;
1058 			case MADV_SEQUENTIAL:
1059 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
1060 				break;
1061 			case MADV_RANDOM:
1062 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
1063 				break;
1064 			default:
1065 				break;
1066 			}
1067 			vm_map_simplify_entry(map, current);
1068 		}
1069 		vm_map_unlock(map);
1070 	}
1071 	else {
1072 		if (behav == MADV_FREE || behav == MADV_DONTNEED ||
1073 		    behav == MADV_WILLNEED) {
1074 			vm_pindex_t pindex;
1075 			int count;
1076 
1077 			/*
1078 			 * madvise behaviors that are implemented in the underlying
1079 			 * vm_object.
1080 			 *
1081 			 * Since we don't clip the vm_map_entry, we have to clip
1082 			 * the vm_object pindex and count.
1083 			 */
1084 			for (current = entry;
1085 			     (current != &map->header) && (current->start < end);
1086 			     current = current->next) {
1087 
1088 				if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
1089 					continue;
1090 
1091 				pindex = OFF_TO_IDX(current->offset);
1092 				count = atop(current->end - current->start);
1093 
1094 				if (current->start < start) {
1095 					pindex += atop(start - current->start);
1096 					count -= atop(start - current->start);
1097 				}
1098 				if (current->end > end)
1099 					count -= atop(current->end - end);
1100 
1101 				if (count <= 0)
1102 					continue;
1103 
1104 				vm_object_madvise(current->object.vm_object,
1105 						  pindex, count, behav);
1106 				if (behav == MADV_WILLNEED)
1107 					pmap_object_init_pt(map->pmap, current->start,
1108 							    current->object.vm_object,
1109 							    pindex, (count << PAGE_SHIFT),
1110 							    0);
1111 			}
1112 		}
1113 		vm_map_unlock_read(map);
1114 	}
1115 }
1116 
1117 
1118 /*
1119  *	vm_map_inherit:
1120  *
1121  *	Sets the inheritance of the specified address
1122  *	range in the target map.  Inheritance
1123  *	affects how the map will be shared with
1124  *	child maps at the time of vm_map_fork.
1125  */
1126 int
1127 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
1128 	       vm_inherit_t new_inheritance)
1129 {
1130 	vm_map_entry_t entry;
1131 	vm_map_entry_t temp_entry;
1132 
1133 	switch (new_inheritance) {
1134 	case VM_INHERIT_NONE:
1135 	case VM_INHERIT_COPY:
1136 	case VM_INHERIT_SHARE:
1137 		break;
1138 	default:
1139 		return (KERN_INVALID_ARGUMENT);
1140 	}
1141 
1142 	vm_map_lock(map);
1143 
1144 	VM_MAP_RANGE_CHECK(map, start, end);
1145 
1146 	if (vm_map_lookup_entry(map, start, &temp_entry)) {
1147 		entry = temp_entry;
1148 		vm_map_clip_start(map, entry, start);
1149 	} else
1150 		entry = temp_entry->next;
1151 
1152 	while ((entry != &map->header) && (entry->start < end)) {
1153 		vm_map_clip_end(map, entry, end);
1154 
1155 		entry->inheritance = new_inheritance;
1156 
1157 		vm_map_simplify_entry(map, entry);
1158 
1159 		entry = entry->next;
1160 	}
1161 
1162 	vm_map_unlock(map);
1163 	return (KERN_SUCCESS);
1164 }
1165 
1166 /*
1167  * Implement the semantics of mlock
1168  */
1169 int
1170 vm_map_user_pageable(map, start, end, new_pageable)
1171 	vm_map_t map;
1172 	vm_offset_t start;
1173 	vm_offset_t end;
1174 	boolean_t new_pageable;
1175 {
1176 	vm_map_entry_t entry;
1177 	vm_map_entry_t start_entry;
1178 	vm_offset_t estart;
1179 	int rv;
1180 
1181 	vm_map_lock(map);
1182 	VM_MAP_RANGE_CHECK(map, start, end);
1183 
1184 	if (vm_map_lookup_entry(map, start, &start_entry) == FALSE) {
1185 		vm_map_unlock(map);
1186 		return (KERN_INVALID_ADDRESS);
1187 	}
1188 
1189 	if (new_pageable) {
1190 
1191 		entry = start_entry;
1192 		vm_map_clip_start(map, entry, start);
1193 
1194 		/*
1195 		 * Now decrement the wiring count for each region. If a region
1196 		 * becomes completely unwired, unwire its physical pages and
1197 		 * mappings.
1198 		 */
1199 		while ((entry != &map->header) && (entry->start < end)) {
1200 			if (entry->eflags & MAP_ENTRY_USER_WIRED) {
1201 				vm_map_clip_end(map, entry, end);
1202 				entry->eflags &= ~MAP_ENTRY_USER_WIRED;
1203 				entry->wired_count--;
1204 				if (entry->wired_count == 0)
1205 					vm_fault_unwire(map, entry->start, entry->end);
1206 			}
1207 			vm_map_simplify_entry(map,entry);
1208 			entry = entry->next;
1209 		}
1210 	} else {
1211 
1212 		entry = start_entry;
1213 
1214 		while ((entry != &map->header) && (entry->start < end)) {
1215 
1216 			if (entry->eflags & MAP_ENTRY_USER_WIRED) {
1217 				entry = entry->next;
1218 				continue;
1219 			}
1220 
1221 			if (entry->wired_count != 0) {
1222 				entry->wired_count++;
1223 				entry->eflags |= MAP_ENTRY_USER_WIRED;
1224 				entry = entry->next;
1225 				continue;
1226 			}
1227 
1228 			/* Here on entry being newly wired */
1229 
1230 			if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1231 				int copyflag = entry->eflags & MAP_ENTRY_NEEDS_COPY;
1232 				if (copyflag && ((entry->protection & VM_PROT_WRITE) != 0)) {
1233 
1234 					vm_object_shadow(&entry->object.vm_object,
1235 					    &entry->offset,
1236 					    atop(entry->end - entry->start));
1237 					entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
1238 
1239 				} else if (entry->object.vm_object == NULL) {
1240 
1241 					entry->object.vm_object =
1242 					    vm_object_allocate(OBJT_DEFAULT,
1243 						atop(entry->end - entry->start));
1244 					entry->offset = (vm_offset_t) 0;
1245 
1246 				}
1247 			}
1248 
1249 			vm_map_clip_start(map, entry, start);
1250 			vm_map_clip_end(map, entry, end);
1251 
1252 			entry->wired_count++;
1253 			entry->eflags |= MAP_ENTRY_USER_WIRED;
1254 			estart = entry->start;
1255 
1256 			/* First we need to allow map modifications */
1257 			vm_map_set_recursive(map);
1258 			vm_map_lock_downgrade(map);
1259 			map->timestamp++;
1260 
1261 			rv = vm_fault_user_wire(map, entry->start, entry->end);
1262 			if (rv) {
1263 
1264 				entry->wired_count--;
1265 				entry->eflags &= ~MAP_ENTRY_USER_WIRED;
1266 
1267 				vm_map_clear_recursive(map);
1268 				vm_map_unlock(map);
1269 
1270 				(void) vm_map_user_pageable(map, start, entry->start, TRUE);
1271 				return rv;
1272 			}
1273 
1274 			vm_map_clear_recursive(map);
1275 			if (vm_map_lock_upgrade(map)) {
1276 				vm_map_lock(map);
1277 				if (vm_map_lookup_entry(map, estart, &entry)
1278 				    == FALSE) {
1279 					vm_map_unlock(map);
1280 					(void) vm_map_user_pageable(map,
1281 								    start,
1282 								    estart,
1283 								    TRUE);
1284 					return (KERN_INVALID_ADDRESS);
1285 				}
1286 			}
1287 			vm_map_simplify_entry(map,entry);
1288 		}
1289 	}
1290 	map->timestamp++;
1291 	vm_map_unlock(map);
1292 	return KERN_SUCCESS;
1293 }
1294 
1295 /*
1296  *	vm_map_pageable:
1297  *
1298  *	Sets the pageability of the specified address
1299  *	range in the target map.  Regions specified
1300  *	as not pageable require locked-down physical
1301  *	memory and physical page maps.
1302  *
1303  *	The map must not be locked, but a reference
1304  *	must remain to the map throughout the call.
1305  */
1306 int
1307 vm_map_pageable(map, start, end, new_pageable)
1308 	vm_map_t map;
1309 	vm_offset_t start;
1310 	vm_offset_t end;
1311 	boolean_t new_pageable;
1312 {
1313 	vm_map_entry_t entry;
1314 	vm_map_entry_t start_entry;
1315 	vm_offset_t failed = 0;
1316 	int rv;
1317 
1318 	vm_map_lock(map);
1319 
1320 	VM_MAP_RANGE_CHECK(map, start, end);
1321 
1322 	/*
1323 	 * Only one pageability change may take place at one time, since
1324 	 * vm_fault assumes it will be called only once for each
1325 	 * wiring/unwiring.  Therefore, we have to make sure we're actually
1326 	 * changing the pageability for the entire region.  We do so before
1327 	 * making any changes.
1328 	 */
1329 
1330 	if (vm_map_lookup_entry(map, start, &start_entry) == FALSE) {
1331 		vm_map_unlock(map);
1332 		return (KERN_INVALID_ADDRESS);
1333 	}
1334 	entry = start_entry;
1335 
1336 	/*
1337 	 * Actions are rather different for wiring and unwiring, so we have
1338 	 * two separate cases.
1339 	 */
1340 
1341 	if (new_pageable) {
1342 
1343 		vm_map_clip_start(map, entry, start);
1344 
1345 		/*
1346 		 * Unwiring.  First ensure that the range to be unwired is
1347 		 * really wired down and that there are no holes.
1348 		 */
1349 		while ((entry != &map->header) && (entry->start < end)) {
1350 
1351 			if (entry->wired_count == 0 ||
1352 			    (entry->end < end &&
1353 				(entry->next == &map->header ||
1354 				    entry->next->start > entry->end))) {
1355 				vm_map_unlock(map);
1356 				return (KERN_INVALID_ARGUMENT);
1357 			}
1358 			entry = entry->next;
1359 		}
1360 
1361 		/*
1362 		 * Now decrement the wiring count for each region. If a region
1363 		 * becomes completely unwired, unwire its physical pages and
1364 		 * mappings.
1365 		 */
1366 		entry = start_entry;
1367 		while ((entry != &map->header) && (entry->start < end)) {
1368 			vm_map_clip_end(map, entry, end);
1369 
1370 			entry->wired_count--;
1371 			if (entry->wired_count == 0)
1372 				vm_fault_unwire(map, entry->start, entry->end);
1373 
1374 			vm_map_simplify_entry(map, entry);
1375 
1376 			entry = entry->next;
1377 		}
1378 	} else {
1379 		/*
1380 		 * Wiring.  We must do this in two passes:
1381 		 *
1382 		 * 1.  Holding the write lock, we create any shadow or zero-fill
1383 		 * objects that need to be created. Then we clip each map
1384 		 * entry to the region to be wired and increment its wiring
1385 		 * count.  We create objects before clipping the map entries
1386 		 * to avoid object proliferation.
1387 		 *
1388 		 * 2.  We downgrade to a read lock, and call vm_fault_wire to
1389 		 * fault in the pages for any newly wired area (wired_count is
1390 		 * 1).
1391 		 *
1392 		 * Downgrading to a read lock for vm_fault_wire avoids a possible
1393 		 * deadlock with another process that may have faulted on one
1394 		 * of the pages to be wired (it would mark the page busy,
1395 		 * blocking us, then in turn block on the map lock that we
1396 		 * hold).  Because of problems in the recursive lock package,
1397 		 * we cannot upgrade to a write lock in vm_map_lookup.  Thus,
1398 		 * any actions that require the write lock must be done
1399 		 * beforehand.  Because we keep the read lock on the map, the
1400 		 * copy-on-write status of the entries we modify here cannot
1401 		 * change.
1402 		 */
1403 
1404 		/*
1405 		 * Pass 1.
1406 		 */
1407 		while ((entry != &map->header) && (entry->start < end)) {
1408 			if (entry->wired_count == 0) {
1409 
1410 				/*
1411 				 * Perform actions of vm_map_lookup that need
1412 				 * the write lock on the map: create a shadow
1413 				 * object for a copy-on-write region, or an
1414 				 * object for a zero-fill region.
1415 				 *
1416 				 * We don't have to do this for entries that
1417 				 * point to sub maps, because we won't
1418 				 * hold the lock on the sub map.
1419 				 */
1420 				if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1421 					int copyflag = entry->eflags & MAP_ENTRY_NEEDS_COPY;
1422 					if (copyflag &&
1423 					    ((entry->protection & VM_PROT_WRITE) != 0)) {
1424 
1425 						vm_object_shadow(&entry->object.vm_object,
1426 						    &entry->offset,
1427 						    atop(entry->end - entry->start));
1428 						entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
1429 					} else if (entry->object.vm_object == NULL) {
1430 						entry->object.vm_object =
1431 						    vm_object_allocate(OBJT_DEFAULT,
1432 							atop(entry->end - entry->start));
1433 						entry->offset = (vm_offset_t) 0;
1434 					}
1435 				}
1436 			}
1437 			vm_map_clip_start(map, entry, start);
1438 			vm_map_clip_end(map, entry, end);
1439 			entry->wired_count++;
1440 
1441 			/*
1442 			 * Check for holes
1443 			 */
1444 			if (entry->end < end &&
1445 			    (entry->next == &map->header ||
1446 				entry->next->start > entry->end)) {
1447 				/*
1448 				 * Found one.  Object creation actions do not
1449 				 * need to be undone, but the wired counts
1450 				 * need to be restored.
1451 				 */
1452 				while (entry != &map->header && entry->end > start) {
1453 					entry->wired_count--;
1454 					entry = entry->prev;
1455 				}
1456 				vm_map_unlock(map);
1457 				return (KERN_INVALID_ARGUMENT);
1458 			}
1459 			entry = entry->next;
1460 		}
1461 
1462 		/*
1463 		 * Pass 2.
1464 		 */
1465 
1466 		/*
1467 		 * HACK HACK HACK HACK
1468 		 *
1469 		 * If we are wiring in the kernel map or a submap of it,
1470 		 * unlock the map to avoid deadlocks.  We trust that the
1471 		 * kernel is well-behaved, and therefore will not do
1472 		 * anything destructive to this region of the map while
1473 		 * we have it unlocked.  We cannot trust user processes
1474 		 * to do the same.
1475 		 *
1476 		 * HACK HACK HACK HACK
1477 		 */
1478 		if (vm_map_pmap(map) == kernel_pmap) {
1479 			vm_map_unlock(map);	/* trust me ... */
1480 		} else {
1481 			vm_map_set_recursive(map);
1482 			vm_map_lock_downgrade(map);
1483 		}
1484 
1485 		rv = 0;
1486 		entry = start_entry;
1487 		while (entry != &map->header && entry->start < end) {
1488 			/*
1489 			 * If vm_fault_wire fails for any page we need to undo
1490 			 * what has been done.  We decrement the wiring count
1491 			 * for those pages which have not yet been wired (now)
1492 			 * and unwire those that have (later).
1493 			 *
1494 			 * XXX this violates the locking protocol on the map,
1495 			 * needs to be fixed.
1496 			 */
1497 			if (rv)
1498 				entry->wired_count--;
1499 			else if (entry->wired_count == 1) {
1500 				rv = vm_fault_wire(map, entry->start, entry->end);
1501 				if (rv) {
1502 					failed = entry->start;
1503 					entry->wired_count--;
1504 				}
1505 			}
1506 			entry = entry->next;
1507 		}
1508 
1509 		if (vm_map_pmap(map) == kernel_pmap) {
1510 			vm_map_lock(map);
1511 		} else {
1512 			vm_map_clear_recursive(map);
1513 		}
1514 		if (rv) {
1515 			vm_map_unlock(map);
1516 			(void) vm_map_pageable(map, start, failed, TRUE);
1517 			return (rv);
1518 		}
1519 		vm_map_simplify_entry(map, start_entry);
1520 	}
1521 
1522 	vm_map_unlock(map);
1523 
1524 	return (KERN_SUCCESS);
1525 }
1526 
1527 /*
1528  * vm_map_clean
1529  *
1530  * Push any dirty cached pages in the address range to their pager.
1531  * If syncio is TRUE, dirty pages are written synchronously.
1532  * If invalidate is TRUE, any cached pages are freed as well.
1533  *
1534  * Returns an error if any part of the specified range is not mapped.
1535  */
1536 int
1537 vm_map_clean(map, start, end, syncio, invalidate)
1538 	vm_map_t map;
1539 	vm_offset_t start;
1540 	vm_offset_t end;
1541 	boolean_t syncio;
1542 	boolean_t invalidate;
1543 {
1544 	vm_map_entry_t current;
1545 	vm_map_entry_t entry;
1546 	vm_size_t size;
1547 	vm_object_t object;
1548 	vm_ooffset_t offset;
1549 
1550 	vm_map_lock_read(map);
1551 	VM_MAP_RANGE_CHECK(map, start, end);
1552 	if (!vm_map_lookup_entry(map, start, &entry)) {
1553 		vm_map_unlock_read(map);
1554 		return (KERN_INVALID_ADDRESS);
1555 	}
1556 	/*
1557 	 * Make a first pass to check for holes.
1558 	 */
1559 	for (current = entry; current->start < end; current = current->next) {
1560 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
1561 			vm_map_unlock_read(map);
1562 			return (KERN_INVALID_ARGUMENT);
1563 		}
1564 		if (end > current->end &&
1565 		    (current->next == &map->header ||
1566 			current->end != current->next->start)) {
1567 			vm_map_unlock_read(map);
1568 			return (KERN_INVALID_ADDRESS);
1569 		}
1570 	}
1571 
1572 	if (invalidate)
1573 		pmap_remove(vm_map_pmap(map), start, end);
1574 	/*
1575 	 * Make a second pass, cleaning/uncaching pages from the indicated
1576 	 * objects as we go.
1577 	 */
1578 	for (current = entry; current->start < end; current = current->next) {
1579 		offset = current->offset + (start - current->start);
1580 		size = (end <= current->end ? end : current->end) - start;
1581 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
1582 			vm_map_t smap;
1583 			vm_map_entry_t tentry;
1584 			vm_size_t tsize;
1585 
1586 			smap = current->object.sub_map;
1587 			vm_map_lock_read(smap);
1588 			(void) vm_map_lookup_entry(smap, offset, &tentry);
1589 			tsize = tentry->end - offset;
1590 			if (tsize < size)
1591 				size = tsize;
1592 			object = tentry->object.vm_object;
1593 			offset = tentry->offset + (offset - tentry->start);
1594 			vm_map_unlock_read(smap);
1595 		} else {
1596 			object = current->object.vm_object;
1597 		}
1598 		/*
1599 		 * Note that there is absolutely no sense in writing out
1600 		 * anonymous objects, so we track down the vnode object
1601 		 * to write out.
1602 		 * We invalidate (remove) all pages from the address space
1603 		 * anyway, for semantic correctness.
1604 		 */
1605 		while (object->backing_object) {
1606 			object = object->backing_object;
1607 			offset += object->backing_object_offset;
1608 			if (object->size < OFF_TO_IDX( offset + size))
1609 				size = IDX_TO_OFF(object->size) - offset;
1610 		}
1611 		if (object && (object->type == OBJT_VNODE)) {
1612 			/*
1613 			 * Flush pages if writing is allowed. XXX should we continue
1614 			 * on an error?
1615 			 *
1616 			 * XXX Doing async I/O and then removing all the pages from
1617 			 *     the object before it completes is probably a very bad
1618 			 *     idea.
1619 			 */
1620 			if (current->protection & VM_PROT_WRITE) {
1621 				int flags;
1622 				if (object->type == OBJT_VNODE)
1623 					vn_lock(object->handle, LK_EXCLUSIVE | LK_RETRY, curproc);
1624 				flags = (syncio || invalidate) ? OBJPC_SYNC : 0;
1625 				flags |= invalidate ? OBJPC_INVAL : 0;
1626 		   	    vm_object_page_clean(object,
1627 					OFF_TO_IDX(offset),
1628 					OFF_TO_IDX(offset + size + PAGE_MASK),
1629 					flags);
1630 				if (invalidate) {
1631 					vm_object_pip_wait(object, "objmcl");
1632 					vm_object_page_remove(object,
1633 						OFF_TO_IDX(offset),
1634 						OFF_TO_IDX(offset + size + PAGE_MASK),
1635 						FALSE);
1636 				}
1637 				if (object->type == OBJT_VNODE)
1638 					VOP_UNLOCK(object->handle, 0, curproc);
1639 			}
1640 		}
1641 		start += size;
1642 	}
1643 
1644 	vm_map_unlock_read(map);
1645 	return (KERN_SUCCESS);
1646 }
1647 
1648 /*
1649  *	vm_map_entry_unwire:	[ internal use only ]
1650  *
1651  *	Make the region specified by this entry pageable.
1652  *
1653  *	The map in question should be locked.
1654  *	[This is the reason for this routine's existence.]
1655  */
1656 static void
1657 vm_map_entry_unwire(map, entry)
1658 	vm_map_t map;
1659 	vm_map_entry_t entry;
1660 {
1661 	vm_fault_unwire(map, entry->start, entry->end);
1662 	entry->wired_count = 0;
1663 }
1664 
1665 /*
1666  *	vm_map_entry_delete:	[ internal use only ]
1667  *
1668  *	Deallocate the given entry from the target map.
1669  */
1670 static void
1671 vm_map_entry_delete(map, entry)
1672 	vm_map_t map;
1673 	vm_map_entry_t entry;
1674 {
1675 	vm_map_entry_unlink(map, entry);
1676 	map->size -= entry->end - entry->start;
1677 
1678 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1679 		vm_object_deallocate(entry->object.vm_object);
1680 	}
1681 
1682 	vm_map_entry_dispose(map, entry);
1683 }
1684 
1685 /*
1686  *	vm_map_delete:	[ internal use only ]
1687  *
1688  *	Deallocates the given address range from the target
1689  *	map.
1690  */
1691 int
1692 vm_map_delete(map, start, end)
1693 	vm_map_t map;
1694 	vm_offset_t start;
1695 	vm_offset_t end;
1696 {
1697 	vm_object_t object;
1698 	vm_map_entry_t entry;
1699 	vm_map_entry_t first_entry;
1700 
1701 	/*
1702 	 * Find the start of the region, and clip it
1703 	 */
1704 
1705 	if (!vm_map_lookup_entry(map, start, &first_entry))
1706 		entry = first_entry->next;
1707 	else {
1708 		entry = first_entry;
1709 		vm_map_clip_start(map, entry, start);
1710 		/*
1711 		 * Fix the lookup hint now, rather than each time though the
1712 		 * loop.
1713 		 */
1714 		SAVE_HINT(map, entry->prev);
1715 	}
1716 
1717 	/*
1718 	 * Save the free space hint
1719 	 */
1720 
1721 	if (entry == &map->header) {
1722 		map->first_free = &map->header;
1723 	} else if (map->first_free->start >= start) {
1724 		map->first_free = entry->prev;
1725 	}
1726 
1727 	/*
1728 	 * Step through all entries in this region
1729 	 */
1730 
1731 	while ((entry != &map->header) && (entry->start < end)) {
1732 		vm_map_entry_t next;
1733 		vm_offset_t s, e;
1734 		vm_pindex_t offidxstart, offidxend, count;
1735 
1736 		vm_map_clip_end(map, entry, end);
1737 
1738 		s = entry->start;
1739 		e = entry->end;
1740 		next = entry->next;
1741 
1742 		offidxstart = OFF_TO_IDX(entry->offset);
1743 		count = OFF_TO_IDX(e - s);
1744 		object = entry->object.vm_object;
1745 
1746 		/*
1747 		 * Unwire before removing addresses from the pmap; otherwise,
1748 		 * unwiring will put the entries back in the pmap.
1749 		 */
1750 		if (entry->wired_count != 0) {
1751 			vm_map_entry_unwire(map, entry);
1752 		}
1753 
1754 		offidxend = offidxstart + count;
1755 
1756 		if ((object == kernel_object) || (object == kmem_object)) {
1757 			vm_object_page_remove(object, offidxstart, offidxend, FALSE);
1758 		} else {
1759 			pmap_remove(map->pmap, s, e);
1760 			if (object != NULL &&
1761 			    object->ref_count != 1 &&
1762 			    (object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING &&
1763 			    (object->type == OBJT_DEFAULT || object->type == OBJT_SWAP)) {
1764 				vm_object_collapse(object);
1765 				vm_object_page_remove(object, offidxstart, offidxend, FALSE);
1766 				if (object->type == OBJT_SWAP) {
1767 					swap_pager_freespace(object, offidxstart, count);
1768 				}
1769 				if (offidxend >= object->size &&
1770 				    offidxstart < object->size) {
1771 					object->size = offidxstart;
1772 				}
1773 			}
1774 		}
1775 
1776 		/*
1777 		 * Delete the entry (which may delete the object) only after
1778 		 * removing all pmap entries pointing to its pages.
1779 		 * (Otherwise, its page frames may be reallocated, and any
1780 		 * modify bits will be set in the wrong object!)
1781 		 */
1782 		vm_map_entry_delete(map, entry);
1783 		entry = next;
1784 	}
1785 	return (KERN_SUCCESS);
1786 }
1787 
1788 /*
1789  *	vm_map_remove:
1790  *
1791  *	Remove the given address range from the target map.
1792  *	This is the exported form of vm_map_delete.
1793  */
1794 int
1795 vm_map_remove(map, start, end)
1796 	vm_map_t map;
1797 	vm_offset_t start;
1798 	vm_offset_t end;
1799 {
1800 	int result, s = 0;
1801 
1802 	if (map == kmem_map || map == mb_map)
1803 		s = splvm();
1804 
1805 	vm_map_lock(map);
1806 	VM_MAP_RANGE_CHECK(map, start, end);
1807 	result = vm_map_delete(map, start, end);
1808 	vm_map_unlock(map);
1809 
1810 	if (map == kmem_map || map == mb_map)
1811 		splx(s);
1812 
1813 	return (result);
1814 }
1815 
1816 /*
1817  *	vm_map_check_protection:
1818  *
1819  *	Assert that the target map allows the specified
1820  *	privilege on the entire address region given.
1821  *	The entire region must be allocated.
1822  */
1823 boolean_t
1824 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
1825 			vm_prot_t protection)
1826 {
1827 	vm_map_entry_t entry;
1828 	vm_map_entry_t tmp_entry;
1829 
1830 	if (!vm_map_lookup_entry(map, start, &tmp_entry)) {
1831 		return (FALSE);
1832 	}
1833 	entry = tmp_entry;
1834 
1835 	while (start < end) {
1836 		if (entry == &map->header) {
1837 			return (FALSE);
1838 		}
1839 		/*
1840 		 * No holes allowed!
1841 		 */
1842 
1843 		if (start < entry->start) {
1844 			return (FALSE);
1845 		}
1846 		/*
1847 		 * Check protection associated with entry.
1848 		 */
1849 
1850 		if ((entry->protection & protection) != protection) {
1851 			return (FALSE);
1852 		}
1853 		/* go to next entry */
1854 
1855 		start = entry->end;
1856 		entry = entry->next;
1857 	}
1858 	return (TRUE);
1859 }
1860 
1861 /*
1862  * Split the pages in a map entry into a new object.  This affords
1863  * easier removal of unused pages, and keeps object inheritance from
1864  * being a negative impact on memory usage.
1865  */
1866 static void
1867 vm_map_split(entry)
1868 	vm_map_entry_t entry;
1869 {
1870 	vm_page_t m;
1871 	vm_object_t orig_object, new_object, source;
1872 	vm_offset_t s, e;
1873 	vm_pindex_t offidxstart, offidxend, idx;
1874 	vm_size_t size;
1875 	vm_ooffset_t offset;
1876 
1877 	orig_object = entry->object.vm_object;
1878 	if (orig_object->type != OBJT_DEFAULT && orig_object->type != OBJT_SWAP)
1879 		return;
1880 	if (orig_object->ref_count <= 1)
1881 		return;
1882 
1883 	offset = entry->offset;
1884 	s = entry->start;
1885 	e = entry->end;
1886 
1887 	offidxstart = OFF_TO_IDX(offset);
1888 	offidxend = offidxstart + OFF_TO_IDX(e - s);
1889 	size = offidxend - offidxstart;
1890 
1891 	new_object = vm_pager_allocate(orig_object->type,
1892 		NULL, IDX_TO_OFF(size), VM_PROT_ALL, 0LL);
1893 	if (new_object == NULL)
1894 		return;
1895 
1896 	source = orig_object->backing_object;
1897 	if (source != NULL) {
1898 		vm_object_reference(source);	/* Referenced by new_object */
1899 		TAILQ_INSERT_TAIL(&source->shadow_head,
1900 				  new_object, shadow_list);
1901 		vm_object_clear_flag(source, OBJ_ONEMAPPING);
1902 		new_object->backing_object_offset =
1903 			orig_object->backing_object_offset + IDX_TO_OFF(offidxstart);
1904 		new_object->backing_object = source;
1905 		source->shadow_count++;
1906 		source->generation++;
1907 	}
1908 
1909 	for (idx = 0; idx < size; idx++) {
1910 		vm_page_t m;
1911 
1912 	retry:
1913 		m = vm_page_lookup(orig_object, offidxstart + idx);
1914 		if (m == NULL)
1915 			continue;
1916 
1917 		/*
1918 		 * We must wait for pending I/O to complete before we can
1919 		 * rename the page.
1920 		 *
1921 		 * We do not have to VM_PROT_NONE the page as mappings should
1922 		 * not be changed by this operation.
1923 		 */
1924 		if (vm_page_sleep_busy(m, TRUE, "spltwt"))
1925 			goto retry;
1926 
1927 		vm_page_busy(m);
1928 		vm_page_rename(m, new_object, idx);
1929 		/* page automatically made dirty by rename and cache handled */
1930 		vm_page_busy(m);
1931 	}
1932 
1933 	if (orig_object->type == OBJT_SWAP) {
1934 		vm_object_pip_add(orig_object, 1);
1935 		/*
1936 		 * copy orig_object pages into new_object
1937 		 * and destroy unneeded pages in
1938 		 * shadow object.
1939 		 */
1940 		swap_pager_copy(orig_object, new_object, offidxstart, 0);
1941 		vm_object_pip_wakeup(orig_object);
1942 	}
1943 
1944 	for (idx = 0; idx < size; idx++) {
1945 		m = vm_page_lookup(new_object, idx);
1946 		if (m) {
1947 			vm_page_wakeup(m);
1948 		}
1949 	}
1950 
1951 	entry->object.vm_object = new_object;
1952 	entry->offset = 0LL;
1953 	vm_object_deallocate(orig_object);
1954 }
1955 
1956 /*
1957  *	vm_map_copy_entry:
1958  *
1959  *	Copies the contents of the source entry to the destination
1960  *	entry.  The entries *must* be aligned properly.
1961  */
1962 static void
1963 vm_map_copy_entry(src_map, dst_map, src_entry, dst_entry)
1964 	vm_map_t src_map, dst_map;
1965 	vm_map_entry_t src_entry, dst_entry;
1966 {
1967 	vm_object_t src_object;
1968 
1969 	if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
1970 		return;
1971 
1972 	if (src_entry->wired_count == 0) {
1973 
1974 		/*
1975 		 * If the source entry is marked needs_copy, it is already
1976 		 * write-protected.
1977 		 */
1978 		if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
1979 			pmap_protect(src_map->pmap,
1980 			    src_entry->start,
1981 			    src_entry->end,
1982 			    src_entry->protection & ~VM_PROT_WRITE);
1983 		}
1984 
1985 		/*
1986 		 * Make a copy of the object.
1987 		 */
1988 		if ((src_object = src_entry->object.vm_object) != NULL) {
1989 
1990 			if ((src_object->handle == NULL) &&
1991 				(src_object->type == OBJT_DEFAULT ||
1992 				 src_object->type == OBJT_SWAP)) {
1993 				vm_object_collapse(src_object);
1994 				if ((src_object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
1995 					vm_map_split(src_entry);
1996 					src_object = src_entry->object.vm_object;
1997 				}
1998 			}
1999 
2000 			vm_object_reference(src_object);
2001 			vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
2002 			dst_entry->object.vm_object = src_object;
2003 			src_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2004 			dst_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2005 			dst_entry->offset = src_entry->offset;
2006 		} else {
2007 			dst_entry->object.vm_object = NULL;
2008 			dst_entry->offset = 0;
2009 		}
2010 
2011 		pmap_copy(dst_map->pmap, src_map->pmap, dst_entry->start,
2012 		    dst_entry->end - dst_entry->start, src_entry->start);
2013 	} else {
2014 		/*
2015 		 * Of course, wired down pages can't be set copy-on-write.
2016 		 * Cause wired pages to be copied into the new map by
2017 		 * simulating faults (the new pages are pageable)
2018 		 */
2019 		vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry);
2020 	}
2021 }
2022 
2023 /*
2024  * vmspace_fork:
2025  * Create a new process vmspace structure and vm_map
2026  * based on those of an existing process.  The new map
2027  * is based on the old map, according to the inheritance
2028  * values on the regions in that map.
2029  *
2030  * The source map must not be locked.
2031  */
2032 struct vmspace *
2033 vmspace_fork(vm1)
2034 	struct vmspace *vm1;
2035 {
2036 	struct vmspace *vm2;
2037 	vm_map_t old_map = &vm1->vm_map;
2038 	vm_map_t new_map;
2039 	vm_map_entry_t old_entry;
2040 	vm_map_entry_t new_entry;
2041 	vm_object_t object;
2042 
2043 	vm_map_lock(old_map);
2044 
2045 	vm2 = vmspace_alloc(old_map->min_offset, old_map->max_offset);
2046 	bcopy(&vm1->vm_startcopy, &vm2->vm_startcopy,
2047 	    (caddr_t) (vm1 + 1) - (caddr_t) &vm1->vm_startcopy);
2048 	new_map = &vm2->vm_map;	/* XXX */
2049 	new_map->timestamp = 1;
2050 
2051 	old_entry = old_map->header.next;
2052 
2053 	while (old_entry != &old_map->header) {
2054 		if (old_entry->eflags & MAP_ENTRY_IS_SUB_MAP)
2055 			panic("vm_map_fork: encountered a submap");
2056 
2057 		switch (old_entry->inheritance) {
2058 		case VM_INHERIT_NONE:
2059 			break;
2060 
2061 		case VM_INHERIT_SHARE:
2062 			/*
2063 			 * Clone the entry, creating the shared object if necessary.
2064 			 */
2065 			object = old_entry->object.vm_object;
2066 			if (object == NULL) {
2067 				object = vm_object_allocate(OBJT_DEFAULT,
2068 					atop(old_entry->end - old_entry->start));
2069 				old_entry->object.vm_object = object;
2070 				old_entry->offset = (vm_offset_t) 0;
2071 			}
2072 
2073 			/*
2074 			 * Add the reference before calling vm_object_shadow
2075 			 * to insure that a shadow object is created.
2076 			 */
2077 			vm_object_reference(object);
2078 			if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
2079 				vm_object_shadow(&old_entry->object.vm_object,
2080 					&old_entry->offset,
2081 					atop(old_entry->end - old_entry->start));
2082 				old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
2083 				object = old_entry->object.vm_object;
2084 			}
2085 			vm_object_clear_flag(object, OBJ_ONEMAPPING);
2086 
2087 			/*
2088 			 * Clone the entry, referencing the shared object.
2089 			 */
2090 			new_entry = vm_map_entry_create(new_map);
2091 			*new_entry = *old_entry;
2092 			new_entry->wired_count = 0;
2093 
2094 			/*
2095 			 * Insert the entry into the new map -- we know we're
2096 			 * inserting at the end of the new map.
2097 			 */
2098 
2099 			vm_map_entry_link(new_map, new_map->header.prev,
2100 			    new_entry);
2101 
2102 			/*
2103 			 * Update the physical map
2104 			 */
2105 
2106 			pmap_copy(new_map->pmap, old_map->pmap,
2107 			    new_entry->start,
2108 			    (old_entry->end - old_entry->start),
2109 			    old_entry->start);
2110 			break;
2111 
2112 		case VM_INHERIT_COPY:
2113 			/*
2114 			 * Clone the entry and link into the map.
2115 			 */
2116 			new_entry = vm_map_entry_create(new_map);
2117 			*new_entry = *old_entry;
2118 			new_entry->wired_count = 0;
2119 			new_entry->object.vm_object = NULL;
2120 			vm_map_entry_link(new_map, new_map->header.prev,
2121 			    new_entry);
2122 			vm_map_copy_entry(old_map, new_map, old_entry,
2123 			    new_entry);
2124 			break;
2125 		}
2126 		old_entry = old_entry->next;
2127 	}
2128 
2129 	new_map->size = old_map->size;
2130 	vm_map_unlock(old_map);
2131 
2132 	return (vm2);
2133 }
2134 
2135 int
2136 vm_map_stack (vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
2137 	      vm_prot_t prot, vm_prot_t max, int cow)
2138 {
2139 	vm_map_entry_t prev_entry;
2140 	vm_map_entry_t new_stack_entry;
2141 	vm_size_t      init_ssize;
2142 	int            rv;
2143 
2144 	if (VM_MIN_ADDRESS > 0 && addrbos < VM_MIN_ADDRESS)
2145 		return (KERN_NO_SPACE);
2146 
2147 	if (max_ssize < SGROWSIZ)
2148 		init_ssize = max_ssize;
2149 	else
2150 		init_ssize = SGROWSIZ;
2151 
2152 	vm_map_lock(map);
2153 
2154 	/* If addr is already mapped, no go */
2155 	if (vm_map_lookup_entry(map, addrbos, &prev_entry)) {
2156 		vm_map_unlock(map);
2157 		return (KERN_NO_SPACE);
2158 	}
2159 
2160 	/* If we can't accomodate max_ssize in the current mapping,
2161 	 * no go.  However, we need to be aware that subsequent user
2162 	 * mappings might map into the space we have reserved for
2163 	 * stack, and currently this space is not protected.
2164 	 *
2165 	 * Hopefully we will at least detect this condition
2166 	 * when we try to grow the stack.
2167 	 */
2168 	if ((prev_entry->next != &map->header) &&
2169 	    (prev_entry->next->start < addrbos + max_ssize)) {
2170 		vm_map_unlock(map);
2171 		return (KERN_NO_SPACE);
2172 	}
2173 
2174 	/* We initially map a stack of only init_ssize.  We will
2175 	 * grow as needed later.  Since this is to be a grow
2176 	 * down stack, we map at the top of the range.
2177 	 *
2178 	 * Note: we would normally expect prot and max to be
2179 	 * VM_PROT_ALL, and cow to be 0.  Possibly we should
2180 	 * eliminate these as input parameters, and just
2181 	 * pass these values here in the insert call.
2182 	 */
2183 	rv = vm_map_insert(map, NULL, 0, addrbos + max_ssize - init_ssize,
2184 	                   addrbos + max_ssize, prot, max, cow);
2185 
2186 	/* Now set the avail_ssize amount */
2187 	if (rv == KERN_SUCCESS){
2188 		if (prev_entry != &map->header)
2189 			vm_map_clip_end(map, prev_entry, addrbos + max_ssize - init_ssize);
2190 		new_stack_entry = prev_entry->next;
2191 		if (new_stack_entry->end   != addrbos + max_ssize ||
2192 		    new_stack_entry->start != addrbos + max_ssize - init_ssize)
2193 			panic ("Bad entry start/end for new stack entry");
2194 		else
2195 			new_stack_entry->avail_ssize = max_ssize - init_ssize;
2196 	}
2197 
2198 	vm_map_unlock(map);
2199 	return (rv);
2200 }
2201 
2202 /* Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if the
2203  * desired address is already mapped, or if we successfully grow
2204  * the stack.  Also returns KERN_SUCCESS if addr is outside the
2205  * stack range (this is strange, but preserves compatibility with
2206  * the grow function in vm_machdep.c).
2207  */
2208 int
2209 vm_map_growstack (struct proc *p, vm_offset_t addr)
2210 {
2211 	vm_map_entry_t prev_entry;
2212 	vm_map_entry_t stack_entry;
2213 	vm_map_entry_t new_stack_entry;
2214 	struct vmspace *vm = p->p_vmspace;
2215 	vm_map_t map = &vm->vm_map;
2216 	vm_offset_t    end;
2217 	int      grow_amount;
2218 	int      rv;
2219 	int      is_procstack;
2220 Retry:
2221 	vm_map_lock_read(map);
2222 
2223 	/* If addr is already in the entry range, no need to grow.*/
2224 	if (vm_map_lookup_entry(map, addr, &prev_entry)) {
2225 		vm_map_unlock_read(map);
2226 		return (KERN_SUCCESS);
2227 	}
2228 
2229 	if ((stack_entry = prev_entry->next) == &map->header) {
2230 		vm_map_unlock_read(map);
2231 		return (KERN_SUCCESS);
2232 	}
2233 	if (prev_entry == &map->header)
2234 		end = stack_entry->start - stack_entry->avail_ssize;
2235 	else
2236 		end = prev_entry->end;
2237 
2238 	/* This next test mimics the old grow function in vm_machdep.c.
2239 	 * It really doesn't quite make sense, but we do it anyway
2240 	 * for compatibility.
2241 	 *
2242 	 * If not growable stack, return success.  This signals the
2243 	 * caller to proceed as he would normally with normal vm.
2244 	 */
2245 	if (stack_entry->avail_ssize < 1 ||
2246 	    addr >= stack_entry->start ||
2247 	    addr <  stack_entry->start - stack_entry->avail_ssize) {
2248 		vm_map_unlock_read(map);
2249 		return (KERN_SUCCESS);
2250 	}
2251 
2252 	/* Find the minimum grow amount */
2253 	grow_amount = roundup (stack_entry->start - addr, PAGE_SIZE);
2254 	if (grow_amount > stack_entry->avail_ssize) {
2255 		vm_map_unlock_read(map);
2256 		return (KERN_NO_SPACE);
2257 	}
2258 
2259 	/* If there is no longer enough space between the entries
2260 	 * nogo, and adjust the available space.  Note: this
2261 	 * should only happen if the user has mapped into the
2262 	 * stack area after the stack was created, and is
2263 	 * probably an error.
2264 	 *
2265 	 * This also effectively destroys any guard page the user
2266 	 * might have intended by limiting the stack size.
2267 	 */
2268 	if (grow_amount > stack_entry->start - end) {
2269 		if (vm_map_lock_upgrade(map))
2270 			goto Retry;
2271 
2272 		stack_entry->avail_ssize = stack_entry->start - end;
2273 
2274 		vm_map_unlock(map);
2275 		return (KERN_NO_SPACE);
2276 	}
2277 
2278 	is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr;
2279 
2280 	/* If this is the main process stack, see if we're over the
2281 	 * stack limit.
2282 	 */
2283 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount >
2284 			     p->p_rlimit[RLIMIT_STACK].rlim_cur)) {
2285 		vm_map_unlock_read(map);
2286 		return (KERN_NO_SPACE);
2287 	}
2288 
2289 	/* Round up the grow amount modulo SGROWSIZ */
2290 	grow_amount = roundup (grow_amount, SGROWSIZ);
2291 	if (grow_amount > stack_entry->avail_ssize) {
2292 		grow_amount = stack_entry->avail_ssize;
2293 	}
2294 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount >
2295 	                     p->p_rlimit[RLIMIT_STACK].rlim_cur)) {
2296 		grow_amount = p->p_rlimit[RLIMIT_STACK].rlim_cur -
2297 		              ctob(vm->vm_ssize);
2298 	}
2299 
2300 	if (vm_map_lock_upgrade(map))
2301 		goto Retry;
2302 
2303 	/* Get the preliminary new entry start value */
2304 	addr = stack_entry->start - grow_amount;
2305 
2306 	/* If this puts us into the previous entry, cut back our growth
2307 	 * to the available space.  Also, see the note above.
2308 	 */
2309 	if (addr < end) {
2310 		stack_entry->avail_ssize = stack_entry->start - end;
2311 		addr = end;
2312 	}
2313 
2314 	rv = vm_map_insert(map, NULL, 0, addr, stack_entry->start,
2315 			   VM_PROT_ALL,
2316 			   VM_PROT_ALL,
2317 			   0);
2318 
2319 	/* Adjust the available stack space by the amount we grew. */
2320 	if (rv == KERN_SUCCESS) {
2321 		if (prev_entry != &map->header)
2322 			vm_map_clip_end(map, prev_entry, addr);
2323 		new_stack_entry = prev_entry->next;
2324 		if (new_stack_entry->end   != stack_entry->start  ||
2325 		    new_stack_entry->start != addr)
2326 			panic ("Bad stack grow start/end in new stack entry");
2327 		else {
2328 			new_stack_entry->avail_ssize = stack_entry->avail_ssize -
2329 							(new_stack_entry->end -
2330 							 new_stack_entry->start);
2331 			if (is_procstack)
2332 				vm->vm_ssize += btoc(new_stack_entry->end -
2333 						     new_stack_entry->start);
2334 		}
2335 	}
2336 
2337 	vm_map_unlock(map);
2338 	return (rv);
2339 
2340 }
2341 
2342 /*
2343  * Unshare the specified VM space for exec.  If other processes are
2344  * mapped to it, then create a new one.  The new vmspace is null.
2345  */
2346 
2347 void
2348 vmspace_exec(struct proc *p) {
2349 	struct vmspace *oldvmspace = p->p_vmspace;
2350 	struct vmspace *newvmspace;
2351 	vm_map_t map = &p->p_vmspace->vm_map;
2352 
2353 	newvmspace = vmspace_alloc(map->min_offset, map->max_offset);
2354 	bcopy(&oldvmspace->vm_startcopy, &newvmspace->vm_startcopy,
2355 	    (caddr_t) (newvmspace + 1) - (caddr_t) &newvmspace->vm_startcopy);
2356 	/*
2357 	 * This code is written like this for prototype purposes.  The
2358 	 * goal is to avoid running down the vmspace here, but let the
2359 	 * other process's that are still using the vmspace to finally
2360 	 * run it down.  Even though there is little or no chance of blocking
2361 	 * here, it is a good idea to keep this form for future mods.
2362 	 */
2363 	vmspace_free(oldvmspace);
2364 	p->p_vmspace = newvmspace;
2365 	pmap_pinit2(vmspace_pmap(newvmspace));
2366 	if (p == curproc)
2367 		pmap_activate(p);
2368 }
2369 
2370 /*
2371  * Unshare the specified VM space for forcing COW.  This
2372  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
2373  */
2374 
2375 void
2376 vmspace_unshare(struct proc *p) {
2377 	struct vmspace *oldvmspace = p->p_vmspace;
2378 	struct vmspace *newvmspace;
2379 
2380 	if (oldvmspace->vm_refcnt == 1)
2381 		return;
2382 	newvmspace = vmspace_fork(oldvmspace);
2383 	vmspace_free(oldvmspace);
2384 	p->p_vmspace = newvmspace;
2385 	pmap_pinit2(vmspace_pmap(newvmspace));
2386 	if (p == curproc)
2387 		pmap_activate(p);
2388 }
2389 
2390 
2391 /*
2392  *	vm_map_lookup:
2393  *
2394  *	Finds the VM object, offset, and
2395  *	protection for a given virtual address in the
2396  *	specified map, assuming a page fault of the
2397  *	type specified.
2398  *
2399  *	Leaves the map in question locked for read; return
2400  *	values are guaranteed until a vm_map_lookup_done
2401  *	call is performed.  Note that the map argument
2402  *	is in/out; the returned map must be used in
2403  *	the call to vm_map_lookup_done.
2404  *
2405  *	A handle (out_entry) is returned for use in
2406  *	vm_map_lookup_done, to make that fast.
2407  *
2408  *	If a lookup is requested with "write protection"
2409  *	specified, the map may be changed to perform virtual
2410  *	copying operations, although the data referenced will
2411  *	remain the same.
2412  */
2413 int
2414 vm_map_lookup(vm_map_t *var_map,		/* IN/OUT */
2415 	      vm_offset_t vaddr,
2416 	      vm_prot_t fault_typea,
2417 	      vm_map_entry_t *out_entry,	/* OUT */
2418 	      vm_object_t *object,		/* OUT */
2419 	      vm_pindex_t *pindex,		/* OUT */
2420 	      vm_prot_t *out_prot,		/* OUT */
2421 	      boolean_t *wired)			/* OUT */
2422 {
2423 	vm_map_entry_t entry;
2424 	vm_map_t map = *var_map;
2425 	vm_prot_t prot;
2426 	vm_prot_t fault_type = fault_typea;
2427 
2428 RetryLookup:;
2429 
2430 	/*
2431 	 * Lookup the faulting address.
2432 	 */
2433 
2434 	vm_map_lock_read(map);
2435 
2436 #define	RETURN(why) \
2437 		{ \
2438 		vm_map_unlock_read(map); \
2439 		return(why); \
2440 		}
2441 
2442 	/*
2443 	 * If the map has an interesting hint, try it before calling full
2444 	 * blown lookup routine.
2445 	 */
2446 
2447 	entry = map->hint;
2448 
2449 	*out_entry = entry;
2450 
2451 	if ((entry == &map->header) ||
2452 	    (vaddr < entry->start) || (vaddr >= entry->end)) {
2453 		vm_map_entry_t tmp_entry;
2454 
2455 		/*
2456 		 * Entry was either not a valid hint, or the vaddr was not
2457 		 * contained in the entry, so do a full lookup.
2458 		 */
2459 		if (!vm_map_lookup_entry(map, vaddr, &tmp_entry))
2460 			RETURN(KERN_INVALID_ADDRESS);
2461 
2462 		entry = tmp_entry;
2463 		*out_entry = entry;
2464 	}
2465 
2466 	/*
2467 	 * Handle submaps.
2468 	 */
2469 
2470 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
2471 		vm_map_t old_map = map;
2472 
2473 		*var_map = map = entry->object.sub_map;
2474 		vm_map_unlock_read(old_map);
2475 		goto RetryLookup;
2476 	}
2477 
2478 	/*
2479 	 * Check whether this task is allowed to have this page.
2480 	 * Note the special case for MAP_ENTRY_COW
2481 	 * pages with an override.  This is to implement a forced
2482 	 * COW for debuggers.
2483 	 */
2484 
2485 	if (fault_type & VM_PROT_OVERRIDE_WRITE)
2486 		prot = entry->max_protection;
2487 	else
2488 		prot = entry->protection;
2489 
2490 	fault_type &= (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE);
2491 	if ((fault_type & prot) != fault_type) {
2492 			RETURN(KERN_PROTECTION_FAILURE);
2493 	}
2494 
2495 	if (entry->wired_count && (fault_type & VM_PROT_WRITE) &&
2496 			(entry->eflags & MAP_ENTRY_COW) &&
2497 			(fault_typea & VM_PROT_OVERRIDE_WRITE) == 0) {
2498 			RETURN(KERN_PROTECTION_FAILURE);
2499 	}
2500 
2501 	/*
2502 	 * If this page is not pageable, we have to get it for all possible
2503 	 * accesses.
2504 	 */
2505 
2506 	*wired = (entry->wired_count != 0);
2507 	if (*wired)
2508 		prot = fault_type = entry->protection;
2509 
2510 	/*
2511 	 * If the entry was copy-on-write, we either ...
2512 	 */
2513 
2514 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
2515 		/*
2516 		 * If we want to write the page, we may as well handle that
2517 		 * now since we've got the map locked.
2518 		 *
2519 		 * If we don't need to write the page, we just demote the
2520 		 * permissions allowed.
2521 		 */
2522 
2523 		if (fault_type & VM_PROT_WRITE) {
2524 			/*
2525 			 * Make a new object, and place it in the object
2526 			 * chain.  Note that no new references have appeared
2527 			 * -- one just moved from the map to the new
2528 			 * object.
2529 			 */
2530 
2531 			if (vm_map_lock_upgrade(map))
2532 				goto RetryLookup;
2533 
2534 			vm_object_shadow(
2535 			    &entry->object.vm_object,
2536 			    &entry->offset,
2537 			    atop(entry->end - entry->start));
2538 
2539 			entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
2540 			vm_map_lock_downgrade(map);
2541 		} else {
2542 			/*
2543 			 * We're attempting to read a copy-on-write page --
2544 			 * don't allow writes.
2545 			 */
2546 
2547 			prot &= ~VM_PROT_WRITE;
2548 		}
2549 	}
2550 
2551 	/*
2552 	 * Create an object if necessary.
2553 	 */
2554 	if (entry->object.vm_object == NULL) {
2555 		if (vm_map_lock_upgrade(map))
2556 			goto RetryLookup;
2557 
2558 		entry->object.vm_object = vm_object_allocate(OBJT_DEFAULT,
2559 		    atop(entry->end - entry->start));
2560 		entry->offset = 0;
2561 		vm_map_lock_downgrade(map);
2562 	}
2563 
2564 	/*
2565 	 * Return the object/offset from this entry.  If the entry was
2566 	 * copy-on-write or empty, it has been fixed up.
2567 	 */
2568 
2569 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
2570 	*object = entry->object.vm_object;
2571 
2572 	/*
2573 	 * Return whether this is the only map sharing this data.
2574 	 */
2575 
2576 	*out_prot = prot;
2577 	return (KERN_SUCCESS);
2578 
2579 #undef	RETURN
2580 }
2581 
2582 /*
2583  *	vm_map_lookup_done:
2584  *
2585  *	Releases locks acquired by a vm_map_lookup
2586  *	(according to the handle returned by that lookup).
2587  */
2588 
2589 void
2590 vm_map_lookup_done(map, entry)
2591 	vm_map_t map;
2592 	vm_map_entry_t entry;
2593 {
2594 	/*
2595 	 * Unlock the main-level map
2596 	 */
2597 
2598 	vm_map_unlock_read(map);
2599 }
2600 
2601 /*
2602  * Implement uiomove with VM operations.  This handles (and collateral changes)
2603  * support every combination of source object modification, and COW type
2604  * operations.
2605  */
2606 int
2607 vm_uiomove(mapa, srcobject, cp, cnta, uaddra, npages)
2608 	vm_map_t mapa;
2609 	vm_object_t srcobject;
2610 	off_t cp;
2611 	int cnta;
2612 	vm_offset_t uaddra;
2613 	int *npages;
2614 {
2615 	vm_map_t map;
2616 	vm_object_t first_object, oldobject, object;
2617 	vm_map_entry_t entry;
2618 	vm_prot_t prot;
2619 	boolean_t wired;
2620 	int tcnt, rv;
2621 	vm_offset_t uaddr, start, end, tend;
2622 	vm_pindex_t first_pindex, osize, oindex;
2623 	off_t ooffset;
2624 	int cnt;
2625 
2626 	if (npages)
2627 		*npages = 0;
2628 
2629 	cnt = cnta;
2630 	uaddr = uaddra;
2631 
2632 	while (cnt > 0) {
2633 		map = mapa;
2634 
2635 		if ((vm_map_lookup(&map, uaddr,
2636 			VM_PROT_READ, &entry, &first_object,
2637 			&first_pindex, &prot, &wired)) != KERN_SUCCESS) {
2638 			return EFAULT;
2639 		}
2640 
2641 		vm_map_clip_start(map, entry, uaddr);
2642 
2643 		tcnt = cnt;
2644 		tend = uaddr + tcnt;
2645 		if (tend > entry->end) {
2646 			tcnt = entry->end - uaddr;
2647 			tend = entry->end;
2648 		}
2649 
2650 		vm_map_clip_end(map, entry, tend);
2651 
2652 		start = entry->start;
2653 		end = entry->end;
2654 
2655 		osize = atop(tcnt);
2656 
2657 		oindex = OFF_TO_IDX(cp);
2658 		if (npages) {
2659 			vm_pindex_t idx;
2660 			for (idx = 0; idx < osize; idx++) {
2661 				vm_page_t m;
2662 				if ((m = vm_page_lookup(srcobject, oindex + idx)) == NULL) {
2663 					vm_map_lookup_done(map, entry);
2664 					return 0;
2665 				}
2666 				/*
2667 				 * disallow busy or invalid pages, but allow
2668 				 * m->busy pages if they are entirely valid.
2669 				 */
2670 				if ((m->flags & PG_BUSY) ||
2671 					((m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL)) {
2672 					vm_map_lookup_done(map, entry);
2673 					return 0;
2674 				}
2675 			}
2676 		}
2677 
2678 /*
2679  * If we are changing an existing map entry, just redirect
2680  * the object, and change mappings.
2681  */
2682 		if ((first_object->type == OBJT_VNODE) &&
2683 			((oldobject = entry->object.vm_object) == first_object)) {
2684 
2685 			if ((entry->offset != cp) || (oldobject != srcobject)) {
2686 				/*
2687    				* Remove old window into the file
2688    				*/
2689 				pmap_remove (map->pmap, uaddr, tend);
2690 
2691 				/*
2692    				* Force copy on write for mmaped regions
2693    				*/
2694 				vm_object_pmap_copy_1 (srcobject, oindex, oindex + osize);
2695 
2696 				/*
2697    				* Point the object appropriately
2698    				*/
2699 				if (oldobject != srcobject) {
2700 
2701 				/*
2702    				* Set the object optimization hint flag
2703    				*/
2704 					vm_object_set_flag(srcobject, OBJ_OPT);
2705 					vm_object_reference(srcobject);
2706 					entry->object.vm_object = srcobject;
2707 
2708 					if (oldobject) {
2709 						vm_object_deallocate(oldobject);
2710 					}
2711 				}
2712 
2713 				entry->offset = cp;
2714 				map->timestamp++;
2715 			} else {
2716 				pmap_remove (map->pmap, uaddr, tend);
2717 			}
2718 
2719 		} else if ((first_object->ref_count == 1) &&
2720 			(first_object->size == osize) &&
2721 			((first_object->type == OBJT_DEFAULT) ||
2722 				(first_object->type == OBJT_SWAP)) ) {
2723 
2724 			oldobject = first_object->backing_object;
2725 
2726 			if ((first_object->backing_object_offset != cp) ||
2727 				(oldobject != srcobject)) {
2728 				/*
2729    				* Remove old window into the file
2730    				*/
2731 				pmap_remove (map->pmap, uaddr, tend);
2732 
2733 				/*
2734 				 * Remove unneeded old pages
2735 				 */
2736 				vm_object_page_remove(first_object, 0, 0, 0);
2737 
2738 				/*
2739 				 * Invalidate swap space
2740 				 */
2741 				if (first_object->type == OBJT_SWAP) {
2742 					swap_pager_freespace(first_object,
2743 						0,
2744 						first_object->size);
2745 				}
2746 
2747 				/*
2748    				* Force copy on write for mmaped regions
2749    				*/
2750 				vm_object_pmap_copy_1 (srcobject, oindex, oindex + osize);
2751 
2752 				/*
2753    				* Point the object appropriately
2754    				*/
2755 				if (oldobject != srcobject) {
2756 
2757 				/*
2758    				* Set the object optimization hint flag
2759    				*/
2760 					vm_object_set_flag(srcobject, OBJ_OPT);
2761 					vm_object_reference(srcobject);
2762 
2763 					if (oldobject) {
2764 						TAILQ_REMOVE(&oldobject->shadow_head,
2765 							first_object, shadow_list);
2766 						oldobject->shadow_count--;
2767 						vm_object_deallocate(oldobject);
2768 					}
2769 
2770 					TAILQ_INSERT_TAIL(&srcobject->shadow_head,
2771 						first_object, shadow_list);
2772 					srcobject->shadow_count++;
2773 
2774 					first_object->backing_object = srcobject;
2775 				}
2776 				first_object->backing_object_offset = cp;
2777 				map->timestamp++;
2778 			} else {
2779 				pmap_remove (map->pmap, uaddr, tend);
2780 			}
2781 /*
2782  * Otherwise, we have to do a logical mmap.
2783  */
2784 		} else {
2785 
2786 			vm_object_set_flag(srcobject, OBJ_OPT);
2787 			vm_object_reference(srcobject);
2788 
2789 			pmap_remove (map->pmap, uaddr, tend);
2790 
2791 			vm_object_pmap_copy_1 (srcobject, oindex, oindex + osize);
2792 			vm_map_lock_upgrade(map);
2793 
2794 			if (entry == &map->header) {
2795 				map->first_free = &map->header;
2796 			} else if (map->first_free->start >= start) {
2797 				map->first_free = entry->prev;
2798 			}
2799 
2800 			SAVE_HINT(map, entry->prev);
2801 			vm_map_entry_delete(map, entry);
2802 
2803 			object = srcobject;
2804 			ooffset = cp;
2805 
2806 			rv = vm_map_insert(map, object, ooffset, start, tend,
2807 				VM_PROT_ALL, VM_PROT_ALL, MAP_COPY_ON_WRITE);
2808 
2809 			if (rv != KERN_SUCCESS)
2810 				panic("vm_uiomove: could not insert new entry: %d", rv);
2811 		}
2812 
2813 /*
2814  * Map the window directly, if it is already in memory
2815  */
2816 		pmap_object_init_pt(map->pmap, uaddr,
2817 			srcobject, oindex, tcnt, 0);
2818 
2819 		map->timestamp++;
2820 		vm_map_unlock(map);
2821 
2822 		cnt -= tcnt;
2823 		uaddr += tcnt;
2824 		cp += tcnt;
2825 		if (npages)
2826 			*npages += osize;
2827 	}
2828 	return 0;
2829 }
2830 
2831 /*
2832  * Performs the copy_on_write operations necessary to allow the virtual copies
2833  * into user space to work.  This has to be called for write(2) system calls
2834  * from other processes, file unlinking, and file size shrinkage.
2835  */
2836 void
2837 vm_freeze_copyopts(object, froma, toa)
2838 	vm_object_t object;
2839 	vm_pindex_t froma, toa;
2840 {
2841 	int rv;
2842 	vm_object_t robject;
2843 	vm_pindex_t idx;
2844 
2845 	if ((object == NULL) ||
2846 		((object->flags & OBJ_OPT) == 0))
2847 		return;
2848 
2849 	if (object->shadow_count > object->ref_count)
2850 		panic("vm_freeze_copyopts: sc > rc");
2851 
2852 	while((robject = TAILQ_FIRST(&object->shadow_head)) != NULL) {
2853 		vm_pindex_t bo_pindex;
2854 		vm_page_t m_in, m_out;
2855 
2856 		bo_pindex = OFF_TO_IDX(robject->backing_object_offset);
2857 
2858 		vm_object_reference(robject);
2859 
2860 		vm_object_pip_wait(robject, "objfrz");
2861 
2862 		if (robject->ref_count == 1) {
2863 			vm_object_deallocate(robject);
2864 			continue;
2865 		}
2866 
2867 		vm_object_pip_add(robject, 1);
2868 
2869 		for (idx = 0; idx < robject->size; idx++) {
2870 
2871 			m_out = vm_page_grab(robject, idx,
2872 						VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
2873 
2874 			if (m_out->valid == 0) {
2875 				m_in = vm_page_grab(object, bo_pindex + idx,
2876 						VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
2877 				if (m_in->valid == 0) {
2878 					rv = vm_pager_get_pages(object, &m_in, 1, 0);
2879 					if (rv != VM_PAGER_OK) {
2880 						printf("vm_freeze_copyopts: cannot read page from file: %lx\n", (long)m_in->pindex);
2881 						continue;
2882 					}
2883 					vm_page_deactivate(m_in);
2884 				}
2885 
2886 				vm_page_protect(m_in, VM_PROT_NONE);
2887 				pmap_copy_page(VM_PAGE_TO_PHYS(m_in), VM_PAGE_TO_PHYS(m_out));
2888 				m_out->valid = m_in->valid;
2889 				vm_page_dirty(m_out);
2890 				vm_page_activate(m_out);
2891 				vm_page_wakeup(m_in);
2892 			}
2893 			vm_page_wakeup(m_out);
2894 		}
2895 
2896 		object->shadow_count--;
2897 		object->ref_count--;
2898 		TAILQ_REMOVE(&object->shadow_head, robject, shadow_list);
2899 		robject->backing_object = NULL;
2900 		robject->backing_object_offset = 0;
2901 
2902 		vm_object_pip_wakeup(robject);
2903 		vm_object_deallocate(robject);
2904 	}
2905 
2906 	vm_object_clear_flag(object, OBJ_OPT);
2907 }
2908 
2909 #include "opt_ddb.h"
2910 #ifdef DDB
2911 #include <sys/kernel.h>
2912 
2913 #include <ddb/ddb.h>
2914 
2915 /*
2916  *	vm_map_print:	[ debug ]
2917  */
2918 DB_SHOW_COMMAND(map, vm_map_print)
2919 {
2920 	static int nlines;
2921 	/* XXX convert args. */
2922 	vm_map_t map = (vm_map_t)addr;
2923 	boolean_t full = have_addr;
2924 
2925 	vm_map_entry_t entry;
2926 
2927 	db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
2928 	    (void *)map,
2929 	    (void *)map->pmap, map->nentries, map->timestamp);
2930 	nlines++;
2931 
2932 	if (!full && db_indent)
2933 		return;
2934 
2935 	db_indent += 2;
2936 	for (entry = map->header.next; entry != &map->header;
2937 	    entry = entry->next) {
2938 		db_iprintf("map entry %p: start=%p, end=%p\n",
2939 		    (void *)entry, (void *)entry->start, (void *)entry->end);
2940 		nlines++;
2941 		{
2942 			static char *inheritance_name[4] =
2943 			{"share", "copy", "none", "donate_copy"};
2944 
2945 			db_iprintf(" prot=%x/%x/%s",
2946 			    entry->protection,
2947 			    entry->max_protection,
2948 			    inheritance_name[(int)(unsigned char)entry->inheritance]);
2949 			if (entry->wired_count != 0)
2950 				db_printf(", wired");
2951 		}
2952 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
2953 			/* XXX no %qd in kernel.  Truncate entry->offset. */
2954 			db_printf(", share=%p, offset=0x%lx\n",
2955 			    (void *)entry->object.sub_map,
2956 			    (long)entry->offset);
2957 			nlines++;
2958 			if ((entry->prev == &map->header) ||
2959 			    (entry->prev->object.sub_map !=
2960 				entry->object.sub_map)) {
2961 				db_indent += 2;
2962 				vm_map_print((db_expr_t)(intptr_t)
2963 					     entry->object.sub_map,
2964 					     full, 0, (char *)0);
2965 				db_indent -= 2;
2966 			}
2967 		} else {
2968 			/* XXX no %qd in kernel.  Truncate entry->offset. */
2969 			db_printf(", object=%p, offset=0x%lx",
2970 			    (void *)entry->object.vm_object,
2971 			    (long)entry->offset);
2972 			if (entry->eflags & MAP_ENTRY_COW)
2973 				db_printf(", copy (%s)",
2974 				    (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
2975 			db_printf("\n");
2976 			nlines++;
2977 
2978 			if ((entry->prev == &map->header) ||
2979 			    (entry->prev->object.vm_object !=
2980 				entry->object.vm_object)) {
2981 				db_indent += 2;
2982 				vm_object_print((db_expr_t)(intptr_t)
2983 						entry->object.vm_object,
2984 						full, 0, (char *)0);
2985 				nlines += 4;
2986 				db_indent -= 2;
2987 			}
2988 		}
2989 	}
2990 	db_indent -= 2;
2991 	if (db_indent == 0)
2992 		nlines = 0;
2993 }
2994 
2995 
2996 DB_SHOW_COMMAND(procvm, procvm)
2997 {
2998 	struct proc *p;
2999 
3000 	if (have_addr) {
3001 		p = (struct proc *) addr;
3002 	} else {
3003 		p = curproc;
3004 	}
3005 
3006 	db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
3007 	    (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
3008 	    (void *)vmspace_pmap(p->p_vmspace));
3009 
3010 	vm_map_print((db_expr_t)(intptr_t)&p->p_vmspace->vm_map, 1, 0, NULL);
3011 }
3012 
3013 #endif /* DDB */
3014