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