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