xref: /dflybsd-src/sys/vm/vm_map.c (revision c6cf4f8f1ebc9e3fe2a8c566f08adfc86122c7bf)
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: src/sys/vm/vm_map.c,v 1.187.2.19 2003/05/27 00:47:02 alc Exp $
65  * $DragonFly: src/sys/vm/vm_map.c,v 1.38 2005/02/07 20:39:01 dillon Exp $
66  */
67 
68 /*
69  *	Virtual memory mapping module.
70  */
71 
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/proc.h>
75 #include <sys/lock.h>
76 #include <sys/vmmeter.h>
77 #include <sys/mman.h>
78 #include <sys/vnode.h>
79 #include <sys/resourcevar.h>
80 #include <sys/shm.h>
81 #include <sys/tree.h>
82 
83 #include <vm/vm.h>
84 #include <vm/vm_param.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/swap_pager.h>
93 #include <vm/vm_zone.h>
94 
95 #include <sys/thread2.h>
96 
97 /*
98  *	Virtual memory maps provide for the mapping, protection,
99  *	and sharing of virtual memory objects.  In addition,
100  *	this module provides for an efficient virtual copy of
101  *	memory from one map to another.
102  *
103  *	Synchronization is required prior to most operations.
104  *
105  *	Maps consist of an ordered doubly-linked list of simple
106  *	entries; a single hint is used to speed up lookups.
107  *
108  *	Since portions of maps are specified by start/end addresses,
109  *	which may not align with existing map entries, all
110  *	routines merely "clip" entries to these start/end values.
111  *	[That is, an entry is split into two, bordering at a
112  *	start or end value.]  Note that these clippings may not
113  *	always be necessary (as the two resulting entries are then
114  *	not changed); however, the clipping is done for convenience.
115  *
116  *	As mentioned above, virtual copy operations are performed
117  *	by copying VM object references from one map to
118  *	another, and then marking both regions as copy-on-write.
119  */
120 
121 /*
122  *	vm_map_startup:
123  *
124  *	Initialize the vm_map module.  Must be called before
125  *	any other vm_map routines.
126  *
127  *	Map and entry structures are allocated from the general
128  *	purpose memory pool with some exceptions:
129  *
130  *	- The kernel map and kmem submap are allocated statically.
131  *	- Kernel map entries are allocated out of a static pool.
132  *
133  *	These restrictions are necessary since malloc() uses the
134  *	maps and requires map entries.
135  */
136 
137 #define VMEPERCPU	2
138 
139 static struct vm_zone mapentzone_store, mapzone_store;
140 static vm_zone_t mapentzone, mapzone, vmspace_zone;
141 static struct vm_object mapentobj, mapobj;
142 
143 static struct vm_map_entry map_entry_init[MAX_MAPENT];
144 static struct vm_map_entry cpu_map_entry_init[MAXCPU][VMEPERCPU];
145 static struct vm_map map_init[MAX_KMAP];
146 
147 static vm_map_entry_t vm_map_entry_create(vm_map_t map, int *);
148 static void vm_map_entry_dispose (vm_map_t map, vm_map_entry_t entry, int *);
149 static void _vm_map_clip_end (vm_map_t, vm_map_entry_t, vm_offset_t, int *);
150 static void _vm_map_clip_start (vm_map_t, vm_map_entry_t, vm_offset_t, int *);
151 static void vm_map_entry_delete (vm_map_t, vm_map_entry_t, int *);
152 static void vm_map_entry_unwire (vm_map_t, vm_map_entry_t);
153 static void vm_map_copy_entry (vm_map_t, vm_map_t, vm_map_entry_t,
154 		vm_map_entry_t);
155 static void vm_map_split (vm_map_entry_t);
156 static void vm_map_unclip_range (vm_map_t map, vm_map_entry_t start_entry, vm_offset_t start, vm_offset_t end, int *count, int flags);
157 
158 void
159 vm_map_startup(void)
160 {
161 	mapzone = &mapzone_store;
162 	zbootinit(mapzone, "MAP", sizeof (struct vm_map),
163 		map_init, MAX_KMAP);
164 	mapentzone = &mapentzone_store;
165 	zbootinit(mapentzone, "MAP ENTRY", sizeof (struct vm_map_entry),
166 		map_entry_init, MAX_MAPENT);
167 }
168 
169 /*
170  * Red black tree functions
171  */
172 static int rb_vm_map_compare(vm_map_entry_t a, vm_map_entry_t b);
173 RB_GENERATE(vm_map_rb_tree, vm_map_entry, rb_entry, rb_vm_map_compare);
174 
175 /* a->start is address, and the only field has to be initialized */
176 static int
177 rb_vm_map_compare(vm_map_entry_t a, vm_map_entry_t b)
178 {
179 	if (a->start < b->start)
180 		return(-1);
181 	else if (a->start > b->start)
182 		return(1);
183 	return(0);
184 }
185 
186 /*
187  * Allocate a vmspace structure, including a vm_map and pmap,
188  * and initialize those structures.  The refcnt is set to 1.
189  * The remaining fields must be initialized by the caller.
190  */
191 struct vmspace *
192 vmspace_alloc(vm_offset_t min, vm_offset_t max)
193 {
194 	struct vmspace *vm;
195 
196 	vm = zalloc(vmspace_zone);
197 	vm_map_init(&vm->vm_map, min, max);
198 	pmap_pinit(vmspace_pmap(vm));
199 	vm->vm_map.pmap = vmspace_pmap(vm);		/* XXX */
200 	vm->vm_refcnt = 1;
201 	vm->vm_shm = NULL;
202 	vm->vm_exitingcnt = 0;
203 	return (vm);
204 }
205 
206 void
207 vm_init2(void)
208 {
209 	zinitna(mapentzone, &mapentobj, NULL, 0, 0,
210 		ZONE_USE_RESERVE | ZONE_SPECIAL, 1);
211 	zinitna(mapzone, &mapobj, NULL, 0, 0, 0, 1);
212 	vmspace_zone = zinit("VMSPACE", sizeof (struct vmspace), 0, 0, 3);
213 	pmap_init2();
214 	vm_object_init2();
215 }
216 
217 static __inline void
218 vmspace_dofree(struct vmspace *vm)
219 {
220 	int count;
221 
222 	/*
223 	 * Make sure any SysV shm is freed, it might not have in
224 	 * exit1()
225 	 */
226 	shmexit(vm);
227 
228 	KKASSERT(vm->vm_upcalls == NULL);
229 
230 	/*
231 	 * Lock the map, to wait out all other references to it.
232 	 * Delete all of the mappings and pages they hold, then call
233 	 * the pmap module to reclaim anything left.
234 	 */
235 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
236 	vm_map_lock(&vm->vm_map);
237 	vm_map_delete(&vm->vm_map, vm->vm_map.min_offset,
238 		vm->vm_map.max_offset, &count);
239 	vm_map_unlock(&vm->vm_map);
240 	vm_map_entry_release(count);
241 
242 	pmap_release(vmspace_pmap(vm));
243 	zfree(vmspace_zone, vm);
244 }
245 
246 void
247 vmspace_free(struct vmspace *vm)
248 {
249 	if (vm->vm_refcnt == 0)
250 		panic("vmspace_free: attempt to free already freed vmspace");
251 
252 	if (--vm->vm_refcnt == 0 && vm->vm_exitingcnt == 0)
253 		vmspace_dofree(vm);
254 }
255 
256 void
257 vmspace_exitfree(struct proc *p)
258 {
259 	struct vmspace *vm;
260 
261 	vm = p->p_vmspace;
262 	p->p_vmspace = NULL;
263 
264 	/*
265 	 * cleanup by parent process wait()ing on exiting child.  vm_refcnt
266 	 * may not be 0 (e.g. fork() and child exits without exec()ing).
267 	 * exitingcnt may increment above 0 and drop back down to zero
268 	 * several times while vm_refcnt is held non-zero.  vm_refcnt
269 	 * may also increment above 0 and drop back down to zero several
270 	 * times while vm_exitingcnt is held non-zero.
271 	 *
272 	 * The last wait on the exiting child's vmspace will clean up
273 	 * the remainder of the vmspace.
274 	 */
275 	if (--vm->vm_exitingcnt == 0 && vm->vm_refcnt == 0)
276 		vmspace_dofree(vm);
277 }
278 
279 /*
280  * vmspace_swap_count() - count the approximate swap useage in pages for a
281  *			  vmspace.
282  *
283  *	Swap useage is determined by taking the proportional swap used by
284  *	VM objects backing the VM map.  To make up for fractional losses,
285  *	if the VM object has any swap use at all the associated map entries
286  *	count for at least 1 swap page.
287  */
288 int
289 vmspace_swap_count(struct vmspace *vmspace)
290 {
291 	vm_map_t map = &vmspace->vm_map;
292 	vm_map_entry_t cur;
293 	int count = 0;
294 
295 	for (cur = map->header.next; cur != &map->header; cur = cur->next) {
296 		vm_object_t object;
297 
298 		if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
299 		    (object = cur->object.vm_object) != NULL &&
300 		    object->type == OBJT_SWAP
301 		) {
302 			int n = (cur->end - cur->start) / PAGE_SIZE;
303 
304 			if (object->un_pager.swp.swp_bcount) {
305 				count += object->un_pager.swp.swp_bcount *
306 				    SWAP_META_PAGES * n / object->size + 1;
307 			}
308 		}
309 	}
310 	return(count);
311 }
312 
313 
314 /*
315  *	vm_map_create:
316  *
317  *	Creates and returns a new empty VM map with
318  *	the given physical map structure, and having
319  *	the given lower and upper address bounds.
320  */
321 vm_map_t
322 vm_map_create(pmap_t pmap, vm_offset_t min, vm_offset_t max)
323 {
324 	vm_map_t result;
325 
326 	result = zalloc(mapzone);
327 	vm_map_init(result, min, max);
328 	result->pmap = pmap;
329 	return (result);
330 }
331 
332 /*
333  * Initialize an existing vm_map structure
334  * such as that in the vmspace structure.
335  * The pmap is set elsewhere.
336  */
337 void
338 vm_map_init(struct vm_map *map, vm_offset_t min, vm_offset_t max)
339 {
340 	map->header.next = map->header.prev = &map->header;
341 	RB_INIT(&map->rb_root);
342 	map->nentries = 0;
343 	map->size = 0;
344 	map->system_map = 0;
345 	map->infork = 0;
346 	map->min_offset = min;
347 	map->max_offset = max;
348 	map->first_free = &map->header;
349 	map->hint = &map->header;
350 	map->timestamp = 0;
351 	lockinit(&map->lock, 0, "thrd_sleep", 0, LK_NOPAUSE);
352 }
353 
354 /*
355  *      vm_map_entry_reserve_cpu_init:
356  *
357  *	Set an initial negative count so the first attempt to reserve
358  *	space preloads a bunch of vm_map_entry's for this cpu.  Also
359  *	pre-allocate 2 vm_map_entries which will be needed by zalloc() to
360  *	map a new page for vm_map_entry structures.  SMP systems are
361  *	particularly sensitive.
362  *
363  *	This routine is called in early boot so we cannot just call
364  *	vm_map_entry_reserve().
365  *
366  *	May be called for a gd other then mycpu, but may only be called
367  *	during early boot.
368  */
369 void
370 vm_map_entry_reserve_cpu_init(globaldata_t gd)
371 {
372 	vm_map_entry_t entry;
373 	int i;
374 
375 	gd->gd_vme_avail -= MAP_RESERVE_COUNT * 2;
376 	entry = &cpu_map_entry_init[gd->gd_cpuid][0];
377 	for (i = 0; i < VMEPERCPU; ++i, ++entry) {
378 		entry->next = gd->gd_vme_base;
379 		gd->gd_vme_base = entry;
380 	}
381 }
382 
383 /*
384  *	vm_map_entry_reserve:
385  *
386  *	Reserves vm_map_entry structures so code later on can manipulate
387  *	map_entry structures within a locked map without blocking trying
388  *	to allocate a new vm_map_entry.
389  */
390 int
391 vm_map_entry_reserve(int count)
392 {
393 	struct globaldata *gd = mycpu;
394 	vm_map_entry_t entry;
395 
396 	crit_enter();
397 
398 	/*
399 	 * Make sure we have enough structures in gd_vme_base to handle
400 	 * the reservation request.
401 	 */
402 	while (gd->gd_vme_avail < count) {
403 		entry = zalloc(mapentzone);
404 		entry->next = gd->gd_vme_base;
405 		gd->gd_vme_base = entry;
406 		++gd->gd_vme_avail;
407 	}
408 	gd->gd_vme_avail -= count;
409 	crit_exit();
410 	return(count);
411 }
412 
413 /*
414  *	vm_map_entry_release:
415  *
416  *	Releases previously reserved vm_map_entry structures that were not
417  *	used.  If we have too much junk in our per-cpu cache clean some of
418  *	it out.
419  */
420 void
421 vm_map_entry_release(int count)
422 {
423 	struct globaldata *gd = mycpu;
424 	vm_map_entry_t entry;
425 
426 	crit_enter();
427 	gd->gd_vme_avail += count;
428 	while (gd->gd_vme_avail > MAP_RESERVE_SLOP) {
429 		entry = gd->gd_vme_base;
430 		KKASSERT(entry != NULL);
431 		gd->gd_vme_base = entry->next;
432 		--gd->gd_vme_avail;
433 		crit_exit();
434 		zfree(mapentzone, entry);
435 		crit_enter();
436 	}
437 	crit_exit();
438 }
439 
440 /*
441  *	vm_map_entry_kreserve:
442  *
443  *	Reserve map entry structures for use in kernel_map itself.  These
444  *	entries have *ALREADY* been reserved on a per-cpu basis when the map
445  *	was inited.  This function is used by zalloc() to avoid a recursion
446  *	when zalloc() itself needs to allocate additional kernel memory.
447  *
448  *	This function works like the normal reserve but does not load the
449  *	vm_map_entry cache (because that would result in an infinite
450  *	recursion).  Note that gd_vme_avail may go negative.  This is expected.
451  *
452  *	Any caller of this function must be sure to renormalize after
453  *	potentially eating entries to ensure that the reserve supply
454  *	remains intact.
455  */
456 int
457 vm_map_entry_kreserve(int count)
458 {
459 	struct globaldata *gd = mycpu;
460 
461 	crit_enter();
462 	gd->gd_vme_avail -= count;
463 	crit_exit();
464 	KASSERT(gd->gd_vme_base != NULL, ("no reserved entries left, gd_vme_avail = %d\n", gd->gd_vme_avail));
465 	return(count);
466 }
467 
468 /*
469  *	vm_map_entry_krelease:
470  *
471  *	Release previously reserved map entries for kernel_map.  We do not
472  *	attempt to clean up like the normal release function as this would
473  *	cause an unnecessary (but probably not fatal) deep procedure call.
474  */
475 void
476 vm_map_entry_krelease(int count)
477 {
478 	struct globaldata *gd = mycpu;
479 
480 	crit_enter();
481 	gd->gd_vme_avail += count;
482 	crit_exit();
483 }
484 
485 /*
486  *	vm_map_entry_create:	[ internal use only ]
487  *
488  *	Allocates a VM map entry for insertion.  No entry fields are filled
489  *	in.
490  *
491  *	This routine may be called from an interrupt thread but not a FAST
492  *	interrupt.  This routine may recurse the map lock.
493  */
494 static vm_map_entry_t
495 vm_map_entry_create(vm_map_t map, int *countp)
496 {
497 	struct globaldata *gd = mycpu;
498 	vm_map_entry_t entry;
499 
500 	KKASSERT(*countp > 0);
501 	--*countp;
502 	crit_enter();
503 	entry = gd->gd_vme_base;
504 	KASSERT(entry != NULL, ("gd_vme_base NULL! count %d", *countp));
505 	gd->gd_vme_base = entry->next;
506 	crit_exit();
507 	return(entry);
508 }
509 
510 /*
511  *	vm_map_entry_dispose:	[ internal use only ]
512  *
513  *	Dispose of a vm_map_entry that is no longer being referenced.  This
514  *	function may be called from an interrupt.
515  */
516 static void
517 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry, int *countp)
518 {
519 	struct globaldata *gd = mycpu;
520 
521 	KKASSERT(map->hint != entry);
522 	KKASSERT(map->first_free != entry);
523 
524 	++*countp;
525 	crit_enter();
526 	entry->next = gd->gd_vme_base;
527 	gd->gd_vme_base = entry;
528 	crit_exit();
529 }
530 
531 
532 /*
533  *	vm_map_entry_{un,}link:
534  *
535  *	Insert/remove entries from maps.
536  */
537 static __inline void
538 vm_map_entry_link(vm_map_t map,
539 		  vm_map_entry_t after_where,
540 		  vm_map_entry_t entry)
541 {
542 	map->nentries++;
543 	entry->prev = after_where;
544 	entry->next = after_where->next;
545 	entry->next->prev = entry;
546 	after_where->next = entry;
547 	if (vm_map_rb_tree_RB_INSERT(&map->rb_root, entry))
548 		panic("vm_map_entry_link: dup addr map %p ent %p", map, entry);
549 }
550 
551 static __inline void
552 vm_map_entry_unlink(vm_map_t map,
553 		    vm_map_entry_t entry)
554 {
555 	vm_map_entry_t prev;
556 	vm_map_entry_t next;
557 
558 	if (entry->eflags & MAP_ENTRY_IN_TRANSITION)
559 		panic("vm_map_entry_unlink: attempt to mess with locked entry! %p", entry);
560 	prev = entry->prev;
561 	next = entry->next;
562 	next->prev = prev;
563 	prev->next = next;
564 	vm_map_rb_tree_RB_REMOVE(&map->rb_root, entry);
565 	map->nentries--;
566 }
567 
568 /*
569  *	vm_map_lookup_entry:	[ internal use only ]
570  *
571  *	Finds the map entry containing (or
572  *	immediately preceding) the specified address
573  *	in the given map; the entry is returned
574  *	in the "entry" parameter.  The boolean
575  *	result indicates whether the address is
576  *	actually contained in the map.
577  */
578 boolean_t
579 vm_map_lookup_entry(vm_map_t map, vm_offset_t address,
580     vm_map_entry_t *entry /* OUT */)
581 {
582 	vm_map_entry_t tmp;
583 	vm_map_entry_t last;
584 
585 #if 0
586 	/*
587 	 * XXX TEMPORARILY DISABLED.  For some reason our attempt to revive
588 	 * the hint code with the red-black lookup meets with system crashes
589 	 * and lockups.  We do not yet know why.
590 	 *
591 	 * It is possible that the problem is related to the setting
592 	 * of the hint during map_entry deletion, in the code specified
593 	 * at the GGG comment later on in this file.
594 	 */
595 	/*
596 	 * Quickly check the cached hint, there's a good chance of a match.
597 	 */
598 	if (map->hint != &map->header) {
599 		tmp = map->hint;
600 		if (address >= tmp->start && address < tmp->end) {
601 			*entry = tmp;
602 			return(TRUE);
603 		}
604 	}
605 #endif
606 
607 	/*
608 	 * Locate the record from the top of the tree.  'last' tracks the
609 	 * closest prior record and is returned if no match is found, which
610 	 * in binary tree terms means tracking the most recent right-branch
611 	 * taken.  If there is no prior record, &map->header is returned.
612 	 */
613 	last = &map->header;
614 	tmp = RB_ROOT(&map->rb_root);
615 
616 	while (tmp) {
617 		if (address >= tmp->start) {
618 			if (address < tmp->end) {
619 				*entry = tmp;
620 				map->hint = tmp;
621 				return(TRUE);
622 			}
623 			last = tmp;
624 			tmp = RB_RIGHT(tmp, rb_entry);
625 		} else {
626 			tmp = RB_LEFT(tmp, rb_entry);
627 		}
628 		*entry = last;
629 	}
630 	*entry = last;
631 	return (FALSE);
632 }
633 
634 /*
635  *	vm_map_insert:
636  *
637  *	Inserts the given whole VM object into the target
638  *	map at the specified address range.  The object's
639  *	size should match that of the address range.
640  *
641  *	Requires that the map be locked, and leaves it so.  Requires that
642  *	sufficient vm_map_entry structures have been reserved and tracks
643  *	the use via countp.
644  *
645  *	If object is non-NULL, ref count must be bumped by caller
646  *	prior to making call to account for the new entry.
647  */
648 int
649 vm_map_insert(vm_map_t map, int *countp,
650 	      vm_object_t object, vm_ooffset_t offset,
651 	      vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max,
652 	      int cow)
653 {
654 	vm_map_entry_t new_entry;
655 	vm_map_entry_t prev_entry;
656 	vm_map_entry_t temp_entry;
657 	vm_eflags_t protoeflags;
658 
659 	/*
660 	 * Check that the start and end points are not bogus.
661 	 */
662 
663 	if ((start < map->min_offset) || (end > map->max_offset) ||
664 	    (start >= end))
665 		return (KERN_INVALID_ADDRESS);
666 
667 	/*
668 	 * Find the entry prior to the proposed starting address; if it's part
669 	 * of an existing entry, this range is bogus.
670 	 */
671 
672 	if (vm_map_lookup_entry(map, start, &temp_entry))
673 		return (KERN_NO_SPACE);
674 
675 	prev_entry = temp_entry;
676 
677 	/*
678 	 * Assert that the next entry doesn't overlap the end point.
679 	 */
680 
681 	if ((prev_entry->next != &map->header) &&
682 	    (prev_entry->next->start < end))
683 		return (KERN_NO_SPACE);
684 
685 	protoeflags = 0;
686 
687 	if (cow & MAP_COPY_ON_WRITE)
688 		protoeflags |= MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY;
689 
690 	if (cow & MAP_NOFAULT) {
691 		protoeflags |= MAP_ENTRY_NOFAULT;
692 
693 		KASSERT(object == NULL,
694 			("vm_map_insert: paradoxical MAP_NOFAULT request"));
695 	}
696 	if (cow & MAP_DISABLE_SYNCER)
697 		protoeflags |= MAP_ENTRY_NOSYNC;
698 	if (cow & MAP_DISABLE_COREDUMP)
699 		protoeflags |= MAP_ENTRY_NOCOREDUMP;
700 
701 	if (object) {
702 		/*
703 		 * When object is non-NULL, it could be shared with another
704 		 * process.  We have to set or clear OBJ_ONEMAPPING
705 		 * appropriately.
706 		 */
707 		if ((object->ref_count > 1) || (object->shadow_count != 0)) {
708 			vm_object_clear_flag(object, OBJ_ONEMAPPING);
709 		}
710 	}
711 	else if ((prev_entry != &map->header) &&
712 		 (prev_entry->eflags == protoeflags) &&
713 		 (prev_entry->end == start) &&
714 		 (prev_entry->wired_count == 0) &&
715 		 ((prev_entry->object.vm_object == NULL) ||
716 		  vm_object_coalesce(prev_entry->object.vm_object,
717 				     OFF_TO_IDX(prev_entry->offset),
718 				     (vm_size_t)(prev_entry->end - prev_entry->start),
719 				     (vm_size_t)(end - prev_entry->end)))) {
720 		/*
721 		 * We were able to extend the object.  Determine if we
722 		 * can extend the previous map entry to include the
723 		 * new range as well.
724 		 */
725 		if ((prev_entry->inheritance == VM_INHERIT_DEFAULT) &&
726 		    (prev_entry->protection == prot) &&
727 		    (prev_entry->max_protection == max)) {
728 			map->size += (end - prev_entry->end);
729 			prev_entry->end = end;
730 			vm_map_simplify_entry(map, prev_entry, countp);
731 			return (KERN_SUCCESS);
732 		}
733 
734 		/*
735 		 * If we can extend the object but cannot extend the
736 		 * map entry, we have to create a new map entry.  We
737 		 * must bump the ref count on the extended object to
738 		 * account for it.  object may be NULL.
739 		 */
740 		object = prev_entry->object.vm_object;
741 		offset = prev_entry->offset +
742 			(prev_entry->end - prev_entry->start);
743 		vm_object_reference(object);
744 	}
745 
746 	/*
747 	 * NOTE: if conditionals fail, object can be NULL here.  This occurs
748 	 * in things like the buffer map where we manage kva but do not manage
749 	 * backing objects.
750 	 */
751 
752 	/*
753 	 * Create a new entry
754 	 */
755 
756 	new_entry = vm_map_entry_create(map, countp);
757 	new_entry->start = start;
758 	new_entry->end = end;
759 
760 	new_entry->eflags = protoeflags;
761 	new_entry->object.vm_object = object;
762 	new_entry->offset = offset;
763 	new_entry->avail_ssize = 0;
764 
765 	new_entry->inheritance = VM_INHERIT_DEFAULT;
766 	new_entry->protection = prot;
767 	new_entry->max_protection = max;
768 	new_entry->wired_count = 0;
769 
770 	/*
771 	 * Insert the new entry into the list
772 	 */
773 
774 	vm_map_entry_link(map, prev_entry, new_entry);
775 	map->size += new_entry->end - new_entry->start;
776 
777 	/*
778 	 * Update the free space hint
779 	 */
780 	if ((map->first_free == prev_entry) &&
781 	    (prev_entry->end >= new_entry->start)) {
782 		map->first_free = new_entry;
783 	}
784 
785 #if 0
786 	/*
787 	 * Temporarily removed to avoid MAP_STACK panic, due to
788 	 * MAP_STACK being a huge hack.  Will be added back in
789 	 * when MAP_STACK (and the user stack mapping) is fixed.
790 	 */
791 	/*
792 	 * It may be possible to simplify the entry
793 	 */
794 	vm_map_simplify_entry(map, new_entry, countp);
795 #endif
796 
797 	if (cow & (MAP_PREFAULT|MAP_PREFAULT_PARTIAL)) {
798 		pmap_object_init_pt(map->pmap, start, prot,
799 				    object, OFF_TO_IDX(offset), end - start,
800 				    cow & MAP_PREFAULT_PARTIAL);
801 	}
802 
803 	return (KERN_SUCCESS);
804 }
805 
806 /*
807  * Find sufficient space for `length' bytes in the given map, starting at
808  * `start'.  The map must be locked.  Returns 0 on success, 1 on no space.
809  *
810  * This function will returned an arbitrarily aligned pointer.  If no
811  * particular alignment is required you should pass align as 1.  Note that
812  * the map may return PAGE_SIZE aligned pointers if all the lengths used in
813  * the map are a multiple of PAGE_SIZE, even if you pass a smaller align
814  * argument.
815  *
816  * 'align' should be a power of 2 but is not required to be.
817  */
818 int
819 vm_map_findspace(
820 	vm_map_t map,
821 	vm_offset_t start,
822 	vm_size_t length,
823 	vm_offset_t align,
824 	vm_offset_t *addr)
825 {
826 	vm_map_entry_t entry, next;
827 	vm_offset_t end;
828 	vm_offset_t align_mask;
829 
830 	if (start < map->min_offset)
831 		start = map->min_offset;
832 	if (start > map->max_offset)
833 		return (1);
834 
835 	/*
836 	 * If the alignment is not a power of 2 we will have to use
837 	 * a mod/division, set align_mask to a special value.
838 	 */
839 	if ((align | (align - 1)) + 1 != (align << 1))
840 		align_mask = (vm_offset_t)-1;
841 	else
842 		align_mask = align - 1;
843 
844 retry:
845 	/*
846 	 * Look for the first possible address; if there's already something
847 	 * at this address, we have to start after it.
848 	 */
849 	if (start == map->min_offset) {
850 		if ((entry = map->first_free) != &map->header)
851 			start = entry->end;
852 	} else {
853 		vm_map_entry_t tmp;
854 
855 		if (vm_map_lookup_entry(map, start, &tmp))
856 			start = tmp->end;
857 		entry = tmp;
858 	}
859 
860 	/*
861 	 * Look through the rest of the map, trying to fit a new region in the
862 	 * gap between existing regions, or after the very last region.
863 	 */
864 	for (;; start = (entry = next)->end) {
865 		/*
866 		 * Adjust the proposed start by the requested alignment,
867 		 * be sure that we didn't wrap the address.
868 		 */
869 		if (align_mask == (vm_offset_t)-1)
870 			end = ((start + align - 1) / align) * align;
871 		else
872 			end = (start + align_mask) & ~align_mask;
873 		if (end < start)
874 			return (1);
875 		start = end;
876 		/*
877 		 * Find the end of the proposed new region.  Be sure we didn't
878 		 * go beyond the end of the map, or wrap around the address.
879 		 * Then check to see if this is the last entry or if the
880 		 * proposed end fits in the gap between this and the next
881 		 * entry.
882 		 */
883 		end = start + length;
884 		if (end > map->max_offset || end < start)
885 			return (1);
886 		next = entry->next;
887 		if (next == &map->header || next->start >= end)
888 			break;
889 	}
890 	map->hint = entry;
891 	if (map == kernel_map) {
892 		vm_offset_t ksize;
893 		if ((ksize = round_page(start + length)) > kernel_vm_end) {
894 			pmap_growkernel(ksize);
895 			goto retry;
896 		}
897 	}
898 	*addr = start;
899 	return (0);
900 }
901 
902 /*
903  *	vm_map_find finds an unallocated region in the target address
904  *	map with the given length.  The search is defined to be
905  *	first-fit from the specified address; the region found is
906  *	returned in the same parameter.
907  *
908  *	If object is non-NULL, ref count must be bumped by caller
909  *	prior to making call to account for the new entry.
910  */
911 int
912 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
913 	    vm_offset_t *addr,	/* IN/OUT */
914 	    vm_size_t length, boolean_t find_space, vm_prot_t prot,
915 	    vm_prot_t max, int cow)
916 {
917 	vm_offset_t start;
918 	int result;
919 	int count;
920 
921 	start = *addr;
922 
923 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
924 	vm_map_lock(map);
925 	if (find_space) {
926 		if (vm_map_findspace(map, start, length, 1, addr)) {
927 			vm_map_unlock(map);
928 			vm_map_entry_release(count);
929 			return (KERN_NO_SPACE);
930 		}
931 		start = *addr;
932 	}
933 	result = vm_map_insert(map, &count, object, offset,
934 		start, start + length, prot, max, cow);
935 	vm_map_unlock(map);
936 	vm_map_entry_release(count);
937 
938 	return (result);
939 }
940 
941 /*
942  *	vm_map_simplify_entry:
943  *
944  *	Simplify the given map entry by merging with either neighbor.  This
945  *	routine also has the ability to merge with both neighbors.
946  *
947  *	The map must be locked.
948  *
949  *	This routine guarentees that the passed entry remains valid (though
950  *	possibly extended).  When merging, this routine may delete one or
951  *	both neighbors.  No action is taken on entries which have their
952  *	in-transition flag set.
953  */
954 void
955 vm_map_simplify_entry(vm_map_t map, vm_map_entry_t entry, int *countp)
956 {
957 	vm_map_entry_t next, prev;
958 	vm_size_t prevsize, esize;
959 
960 	if (entry->eflags & (MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP)) {
961 		++mycpu->gd_cnt.v_intrans_coll;
962 		return;
963 	}
964 
965 	prev = entry->prev;
966 	if (prev != &map->header) {
967 		prevsize = prev->end - prev->start;
968 		if ( (prev->end == entry->start) &&
969 		     (prev->object.vm_object == entry->object.vm_object) &&
970 		     (!prev->object.vm_object ||
971 			(prev->offset + prevsize == entry->offset)) &&
972 		     (prev->eflags == entry->eflags) &&
973 		     (prev->protection == entry->protection) &&
974 		     (prev->max_protection == entry->max_protection) &&
975 		     (prev->inheritance == entry->inheritance) &&
976 		     (prev->wired_count == entry->wired_count)) {
977 			if (map->first_free == prev)
978 				map->first_free = entry;
979 			if (map->hint == prev)
980 				map->hint = entry;
981 			vm_map_entry_unlink(map, prev);
982 			entry->start = prev->start;
983 			entry->offset = prev->offset;
984 			if (prev->object.vm_object)
985 				vm_object_deallocate(prev->object.vm_object);
986 			vm_map_entry_dispose(map, prev, countp);
987 		}
988 	}
989 
990 	next = entry->next;
991 	if (next != &map->header) {
992 		esize = entry->end - entry->start;
993 		if ((entry->end == next->start) &&
994 		    (next->object.vm_object == entry->object.vm_object) &&
995 		     (!entry->object.vm_object ||
996 			(entry->offset + esize == next->offset)) &&
997 		    (next->eflags == entry->eflags) &&
998 		    (next->protection == entry->protection) &&
999 		    (next->max_protection == entry->max_protection) &&
1000 		    (next->inheritance == entry->inheritance) &&
1001 		    (next->wired_count == entry->wired_count)) {
1002 			if (map->first_free == next)
1003 				map->first_free = entry;
1004 			if (map->hint == next)
1005 				map->hint = entry;
1006 			vm_map_entry_unlink(map, next);
1007 			entry->end = next->end;
1008 			if (next->object.vm_object)
1009 				vm_object_deallocate(next->object.vm_object);
1010 			vm_map_entry_dispose(map, next, countp);
1011 	        }
1012 	}
1013 }
1014 /*
1015  *	vm_map_clip_start:	[ internal use only ]
1016  *
1017  *	Asserts that the given entry begins at or after
1018  *	the specified address; if necessary,
1019  *	it splits the entry into two.
1020  */
1021 #define vm_map_clip_start(map, entry, startaddr, countp) \
1022 { \
1023 	if (startaddr > entry->start) \
1024 		_vm_map_clip_start(map, entry, startaddr, countp); \
1025 }
1026 
1027 /*
1028  *	This routine is called only when it is known that
1029  *	the entry must be split.
1030  */
1031 static void
1032 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start, int *countp)
1033 {
1034 	vm_map_entry_t new_entry;
1035 
1036 	/*
1037 	 * Split off the front portion -- note that we must insert the new
1038 	 * entry BEFORE this one, so that this entry has the specified
1039 	 * starting address.
1040 	 */
1041 
1042 	vm_map_simplify_entry(map, entry, countp);
1043 
1044 	/*
1045 	 * If there is no object backing this entry, we might as well create
1046 	 * one now.  If we defer it, an object can get created after the map
1047 	 * is clipped, and individual objects will be created for the split-up
1048 	 * map.  This is a bit of a hack, but is also about the best place to
1049 	 * put this improvement.
1050 	 */
1051 
1052 	if (entry->object.vm_object == NULL && !map->system_map) {
1053 		vm_object_t object;
1054 		object = vm_object_allocate(OBJT_DEFAULT,
1055 				atop(entry->end - entry->start));
1056 		entry->object.vm_object = object;
1057 		entry->offset = 0;
1058 	}
1059 
1060 	new_entry = vm_map_entry_create(map, countp);
1061 	*new_entry = *entry;
1062 
1063 	new_entry->end = start;
1064 	entry->offset += (start - entry->start);
1065 	entry->start = start;
1066 
1067 	vm_map_entry_link(map, entry->prev, new_entry);
1068 
1069 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1070 		vm_object_reference(new_entry->object.vm_object);
1071 	}
1072 }
1073 
1074 /*
1075  *	vm_map_clip_end:	[ internal use only ]
1076  *
1077  *	Asserts that the given entry ends at or before
1078  *	the specified address; if necessary,
1079  *	it splits the entry into two.
1080  */
1081 
1082 #define vm_map_clip_end(map, entry, endaddr, countp) \
1083 { \
1084 	if (endaddr < entry->end) \
1085 		_vm_map_clip_end(map, entry, endaddr, countp); \
1086 }
1087 
1088 /*
1089  *	This routine is called only when it is known that
1090  *	the entry must be split.
1091  */
1092 static void
1093 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end, int *countp)
1094 {
1095 	vm_map_entry_t new_entry;
1096 
1097 	/*
1098 	 * If there is no object backing this entry, we might as well create
1099 	 * one now.  If we defer it, an object can get created after the map
1100 	 * is clipped, and individual objects will be created for the split-up
1101 	 * map.  This is a bit of a hack, but is also about the best place to
1102 	 * put this improvement.
1103 	 */
1104 
1105 	if (entry->object.vm_object == NULL && !map->system_map) {
1106 		vm_object_t object;
1107 		object = vm_object_allocate(OBJT_DEFAULT,
1108 				atop(entry->end - entry->start));
1109 		entry->object.vm_object = object;
1110 		entry->offset = 0;
1111 	}
1112 
1113 	/*
1114 	 * Create a new entry and insert it AFTER the specified entry
1115 	 */
1116 
1117 	new_entry = vm_map_entry_create(map, countp);
1118 	*new_entry = *entry;
1119 
1120 	new_entry->start = entry->end = end;
1121 	new_entry->offset += (end - entry->start);
1122 
1123 	vm_map_entry_link(map, entry, new_entry);
1124 
1125 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1126 		vm_object_reference(new_entry->object.vm_object);
1127 	}
1128 }
1129 
1130 /*
1131  *	VM_MAP_RANGE_CHECK:	[ internal use only ]
1132  *
1133  *	Asserts that the starting and ending region
1134  *	addresses fall within the valid range of the map.
1135  */
1136 #define	VM_MAP_RANGE_CHECK(map, start, end)		\
1137 		{					\
1138 		if (start < vm_map_min(map))		\
1139 			start = vm_map_min(map);	\
1140 		if (end > vm_map_max(map))		\
1141 			end = vm_map_max(map);		\
1142 		if (start > end)			\
1143 			start = end;			\
1144 		}
1145 
1146 /*
1147  *	vm_map_transition_wait:	[ kernel use only ]
1148  *
1149  *	Used to block when an in-transition collison occurs.  The map
1150  *	is unlocked for the sleep and relocked before the return.
1151  */
1152 static
1153 void
1154 vm_map_transition_wait(vm_map_t map)
1155 {
1156 	vm_map_unlock(map);
1157 	tsleep(map, 0, "vment", 0);
1158 	vm_map_lock(map);
1159 }
1160 
1161 /*
1162  * CLIP_CHECK_BACK
1163  * CLIP_CHECK_FWD
1164  *
1165  *	When we do blocking operations with the map lock held it is
1166  *	possible that a clip might have occured on our in-transit entry,
1167  *	requiring an adjustment to the entry in our loop.  These macros
1168  *	help the pageable and clip_range code deal with the case.  The
1169  *	conditional costs virtually nothing if no clipping has occured.
1170  */
1171 
1172 #define CLIP_CHECK_BACK(entry, save_start)		\
1173     do {						\
1174 	    while (entry->start != save_start) {	\
1175 		    entry = entry->prev;		\
1176 		    KASSERT(entry != &map->header, ("bad entry clip")); \
1177 	    }						\
1178     } while(0)
1179 
1180 #define CLIP_CHECK_FWD(entry, save_end)			\
1181     do {						\
1182 	    while (entry->end != save_end) {		\
1183 		    entry = entry->next;		\
1184 		    KASSERT(entry != &map->header, ("bad entry clip")); \
1185 	    }						\
1186     } while(0)
1187 
1188 
1189 /*
1190  *	vm_map_clip_range:	[ kernel use only ]
1191  *
1192  *	Clip the specified range and return the base entry.  The
1193  *	range may cover several entries starting at the returned base
1194  *	and the first and last entry in the covering sequence will be
1195  *	properly clipped to the requested start and end address.
1196  *
1197  *	If no holes are allowed you should pass the MAP_CLIP_NO_HOLES
1198  *	flag.
1199  *
1200  *	The MAP_ENTRY_IN_TRANSITION flag will be set for the entries
1201  *	covered by the requested range.
1202  *
1203  *	The map must be exclusively locked on entry and will remain locked
1204  *	on return. If no range exists or the range contains holes and you
1205  *	specified that no holes were allowed, NULL will be returned.  This
1206  *	routine may temporarily unlock the map in order avoid a deadlock when
1207  *	sleeping.
1208  */
1209 static
1210 vm_map_entry_t
1211 vm_map_clip_range(vm_map_t map, vm_offset_t start, vm_offset_t end,
1212 	int *countp, int flags)
1213 {
1214 	vm_map_entry_t start_entry;
1215 	vm_map_entry_t entry;
1216 
1217 	/*
1218 	 * Locate the entry and effect initial clipping.  The in-transition
1219 	 * case does not occur very often so do not try to optimize it.
1220 	 */
1221 again:
1222 	if (vm_map_lookup_entry(map, start, &start_entry) == FALSE)
1223 		return (NULL);
1224 	entry = start_entry;
1225 	if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
1226 		entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
1227 		++mycpu->gd_cnt.v_intrans_coll;
1228 		++mycpu->gd_cnt.v_intrans_wait;
1229 		vm_map_transition_wait(map);
1230 		/*
1231 		 * entry and/or start_entry may have been clipped while
1232 		 * we slept, or may have gone away entirely.  We have
1233 		 * to restart from the lookup.
1234 		 */
1235 		goto again;
1236 	}
1237 	/*
1238 	 * Since we hold an exclusive map lock we do not have to restart
1239 	 * after clipping, even though clipping may block in zalloc.
1240 	 */
1241 	vm_map_clip_start(map, entry, start, countp);
1242 	vm_map_clip_end(map, entry, end, countp);
1243 	entry->eflags |= MAP_ENTRY_IN_TRANSITION;
1244 
1245 	/*
1246 	 * Scan entries covered by the range.  When working on the next
1247 	 * entry a restart need only re-loop on the current entry which
1248 	 * we have already locked, since 'next' may have changed.  Also,
1249 	 * even though entry is safe, it may have been clipped so we
1250 	 * have to iterate forwards through the clip after sleeping.
1251 	 */
1252 	while (entry->next != &map->header && entry->next->start < end) {
1253 		vm_map_entry_t next = entry->next;
1254 
1255 		if (flags & MAP_CLIP_NO_HOLES) {
1256 			if (next->start > entry->end) {
1257 				vm_map_unclip_range(map, start_entry,
1258 					start, entry->end, countp, flags);
1259 				return(NULL);
1260 			}
1261 		}
1262 
1263 		if (next->eflags & MAP_ENTRY_IN_TRANSITION) {
1264 			vm_offset_t save_end = entry->end;
1265 			next->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
1266 			++mycpu->gd_cnt.v_intrans_coll;
1267 			++mycpu->gd_cnt.v_intrans_wait;
1268 			vm_map_transition_wait(map);
1269 
1270 			/*
1271 			 * clips might have occured while we blocked.
1272 			 */
1273 			CLIP_CHECK_FWD(entry, save_end);
1274 			CLIP_CHECK_BACK(start_entry, start);
1275 			continue;
1276 		}
1277 		/*
1278 		 * No restart necessary even though clip_end may block, we
1279 		 * are holding the map lock.
1280 		 */
1281 		vm_map_clip_end(map, next, end, countp);
1282 		next->eflags |= MAP_ENTRY_IN_TRANSITION;
1283 		entry = next;
1284 	}
1285 	if (flags & MAP_CLIP_NO_HOLES) {
1286 		if (entry->end != end) {
1287 			vm_map_unclip_range(map, start_entry,
1288 				start, entry->end, countp, flags);
1289 			return(NULL);
1290 		}
1291 	}
1292 	return(start_entry);
1293 }
1294 
1295 /*
1296  *	vm_map_unclip_range:	[ kernel use only ]
1297  *
1298  *	Undo the effect of vm_map_clip_range().  You should pass the same
1299  *	flags and the same range that you passed to vm_map_clip_range().
1300  *	This code will clear the in-transition flag on the entries and
1301  *	wake up anyone waiting.  This code will also simplify the sequence
1302  *	and attempt to merge it with entries before and after the sequence.
1303  *
1304  *	The map must be locked on entry and will remain locked on return.
1305  *
1306  *	Note that you should also pass the start_entry returned by
1307  *	vm_map_clip_range().  However, if you block between the two calls
1308  *	with the map unlocked please be aware that the start_entry may
1309  *	have been clipped and you may need to scan it backwards to find
1310  *	the entry corresponding with the original start address.  You are
1311  *	responsible for this, vm_map_unclip_range() expects the correct
1312  *	start_entry to be passed to it and will KASSERT otherwise.
1313  */
1314 static
1315 void
1316 vm_map_unclip_range(
1317 	vm_map_t map,
1318 	vm_map_entry_t start_entry,
1319 	vm_offset_t start,
1320 	vm_offset_t end,
1321 	int *countp,
1322 	int flags)
1323 {
1324 	vm_map_entry_t entry;
1325 
1326 	entry = start_entry;
1327 
1328 	KASSERT(entry->start == start, ("unclip_range: illegal base entry"));
1329 	while (entry != &map->header && entry->start < end) {
1330 		KASSERT(entry->eflags & MAP_ENTRY_IN_TRANSITION, ("in-transition flag not set during unclip on: %p", entry));
1331 		KASSERT(entry->end <= end, ("unclip_range: tail wasn't clipped"));
1332 		entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
1333 		if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
1334 			entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
1335 			wakeup(map);
1336 		}
1337 		entry = entry->next;
1338 	}
1339 
1340 	/*
1341 	 * Simplification does not block so there is no restart case.
1342 	 */
1343 	entry = start_entry;
1344 	while (entry != &map->header && entry->start < end) {
1345 		vm_map_simplify_entry(map, entry, countp);
1346 		entry = entry->next;
1347 	}
1348 }
1349 
1350 /*
1351  *	vm_map_submap:		[ kernel use only ]
1352  *
1353  *	Mark the given range as handled by a subordinate map.
1354  *
1355  *	This range must have been created with vm_map_find,
1356  *	and no other operations may have been performed on this
1357  *	range prior to calling vm_map_submap.
1358  *
1359  *	Only a limited number of operations can be performed
1360  *	within this rage after calling vm_map_submap:
1361  *		vm_fault
1362  *	[Don't try vm_map_copy!]
1363  *
1364  *	To remove a submapping, one must first remove the
1365  *	range from the superior map, and then destroy the
1366  *	submap (if desired).  [Better yet, don't try it.]
1367  */
1368 int
1369 vm_map_submap(vm_map_t map, vm_offset_t start, vm_offset_t end, vm_map_t submap)
1370 {
1371 	vm_map_entry_t entry;
1372 	int result = KERN_INVALID_ARGUMENT;
1373 	int count;
1374 
1375 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1376 	vm_map_lock(map);
1377 
1378 	VM_MAP_RANGE_CHECK(map, start, end);
1379 
1380 	if (vm_map_lookup_entry(map, start, &entry)) {
1381 		vm_map_clip_start(map, entry, start, &count);
1382 	} else {
1383 		entry = entry->next;
1384 	}
1385 
1386 	vm_map_clip_end(map, entry, end, &count);
1387 
1388 	if ((entry->start == start) && (entry->end == end) &&
1389 	    ((entry->eflags & MAP_ENTRY_COW) == 0) &&
1390 	    (entry->object.vm_object == NULL)) {
1391 		entry->object.sub_map = submap;
1392 		entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
1393 		result = KERN_SUCCESS;
1394 	}
1395 	vm_map_unlock(map);
1396 	vm_map_entry_release(count);
1397 
1398 	return (result);
1399 }
1400 
1401 /*
1402  *	vm_map_protect:
1403  *
1404  *	Sets the protection of the specified address
1405  *	region in the target map.  If "set_max" is
1406  *	specified, the maximum protection is to be set;
1407  *	otherwise, only the current protection is affected.
1408  */
1409 int
1410 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
1411 	       vm_prot_t new_prot, boolean_t set_max)
1412 {
1413 	vm_map_entry_t current;
1414 	vm_map_entry_t entry;
1415 	int count;
1416 
1417 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1418 	vm_map_lock(map);
1419 
1420 	VM_MAP_RANGE_CHECK(map, start, end);
1421 
1422 	if (vm_map_lookup_entry(map, start, &entry)) {
1423 		vm_map_clip_start(map, entry, start, &count);
1424 	} else {
1425 		entry = entry->next;
1426 	}
1427 
1428 	/*
1429 	 * Make a first pass to check for protection violations.
1430 	 */
1431 
1432 	current = entry;
1433 	while ((current != &map->header) && (current->start < end)) {
1434 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
1435 			vm_map_unlock(map);
1436 			vm_map_entry_release(count);
1437 			return (KERN_INVALID_ARGUMENT);
1438 		}
1439 		if ((new_prot & current->max_protection) != new_prot) {
1440 			vm_map_unlock(map);
1441 			vm_map_entry_release(count);
1442 			return (KERN_PROTECTION_FAILURE);
1443 		}
1444 		current = current->next;
1445 	}
1446 
1447 	/*
1448 	 * Go back and fix up protections. [Note that clipping is not
1449 	 * necessary the second time.]
1450 	 */
1451 	current = entry;
1452 
1453 	while ((current != &map->header) && (current->start < end)) {
1454 		vm_prot_t old_prot;
1455 
1456 		vm_map_clip_end(map, current, end, &count);
1457 
1458 		old_prot = current->protection;
1459 		if (set_max)
1460 			current->protection =
1461 			    (current->max_protection = new_prot) &
1462 			    old_prot;
1463 		else
1464 			current->protection = new_prot;
1465 
1466 		/*
1467 		 * Update physical map if necessary. Worry about copy-on-write
1468 		 * here -- CHECK THIS XXX
1469 		 */
1470 
1471 		if (current->protection != old_prot) {
1472 #define MASK(entry)	(((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
1473 							VM_PROT_ALL)
1474 
1475 			pmap_protect(map->pmap, current->start,
1476 			    current->end,
1477 			    current->protection & MASK(current));
1478 #undef	MASK
1479 		}
1480 
1481 		vm_map_simplify_entry(map, current, &count);
1482 
1483 		current = current->next;
1484 	}
1485 
1486 	vm_map_unlock(map);
1487 	vm_map_entry_release(count);
1488 	return (KERN_SUCCESS);
1489 }
1490 
1491 /*
1492  *	vm_map_madvise:
1493  *
1494  * 	This routine traverses a processes map handling the madvise
1495  *	system call.  Advisories are classified as either those effecting
1496  *	the vm_map_entry structure, or those effecting the underlying
1497  *	objects.
1498  */
1499 
1500 int
1501 vm_map_madvise(vm_map_t map, vm_offset_t start, vm_offset_t end, int behav)
1502 {
1503 	vm_map_entry_t current, entry;
1504 	int modify_map = 0;
1505 	int count;
1506 
1507 	/*
1508 	 * Some madvise calls directly modify the vm_map_entry, in which case
1509 	 * we need to use an exclusive lock on the map and we need to perform
1510 	 * various clipping operations.  Otherwise we only need a read-lock
1511 	 * on the map.
1512 	 */
1513 
1514 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1515 
1516 	switch(behav) {
1517 	case MADV_NORMAL:
1518 	case MADV_SEQUENTIAL:
1519 	case MADV_RANDOM:
1520 	case MADV_NOSYNC:
1521 	case MADV_AUTOSYNC:
1522 	case MADV_NOCORE:
1523 	case MADV_CORE:
1524 		modify_map = 1;
1525 		vm_map_lock(map);
1526 		break;
1527 	case MADV_WILLNEED:
1528 	case MADV_DONTNEED:
1529 	case MADV_FREE:
1530 		vm_map_lock_read(map);
1531 		break;
1532 	default:
1533 		vm_map_entry_release(count);
1534 		return (KERN_INVALID_ARGUMENT);
1535 	}
1536 
1537 	/*
1538 	 * Locate starting entry and clip if necessary.
1539 	 */
1540 
1541 	VM_MAP_RANGE_CHECK(map, start, end);
1542 
1543 	if (vm_map_lookup_entry(map, start, &entry)) {
1544 		if (modify_map)
1545 			vm_map_clip_start(map, entry, start, &count);
1546 	} else {
1547 		entry = entry->next;
1548 	}
1549 
1550 	if (modify_map) {
1551 		/*
1552 		 * madvise behaviors that are implemented in the vm_map_entry.
1553 		 *
1554 		 * We clip the vm_map_entry so that behavioral changes are
1555 		 * limited to the specified address range.
1556 		 */
1557 		for (current = entry;
1558 		     (current != &map->header) && (current->start < end);
1559 		     current = current->next
1560 		) {
1561 			if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
1562 				continue;
1563 
1564 			vm_map_clip_end(map, current, end, &count);
1565 
1566 			switch (behav) {
1567 			case MADV_NORMAL:
1568 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
1569 				break;
1570 			case MADV_SEQUENTIAL:
1571 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
1572 				break;
1573 			case MADV_RANDOM:
1574 				vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
1575 				break;
1576 			case MADV_NOSYNC:
1577 				current->eflags |= MAP_ENTRY_NOSYNC;
1578 				break;
1579 			case MADV_AUTOSYNC:
1580 				current->eflags &= ~MAP_ENTRY_NOSYNC;
1581 				break;
1582 			case MADV_NOCORE:
1583 				current->eflags |= MAP_ENTRY_NOCOREDUMP;
1584 				break;
1585 			case MADV_CORE:
1586 				current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
1587 				break;
1588 			default:
1589 				break;
1590 			}
1591 			vm_map_simplify_entry(map, current, &count);
1592 		}
1593 		vm_map_unlock(map);
1594 	} else {
1595 		vm_pindex_t pindex;
1596 		int count;
1597 
1598 		/*
1599 		 * madvise behaviors that are implemented in the underlying
1600 		 * vm_object.
1601 		 *
1602 		 * Since we don't clip the vm_map_entry, we have to clip
1603 		 * the vm_object pindex and count.
1604 		 */
1605 		for (current = entry;
1606 		     (current != &map->header) && (current->start < end);
1607 		     current = current->next
1608 		) {
1609 			vm_offset_t useStart;
1610 
1611 			if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
1612 				continue;
1613 
1614 			pindex = OFF_TO_IDX(current->offset);
1615 			count = atop(current->end - current->start);
1616 			useStart = current->start;
1617 
1618 			if (current->start < start) {
1619 				pindex += atop(start - current->start);
1620 				count -= atop(start - current->start);
1621 				useStart = start;
1622 			}
1623 			if (current->end > end)
1624 				count -= atop(current->end - end);
1625 
1626 			if (count <= 0)
1627 				continue;
1628 
1629 			vm_object_madvise(current->object.vm_object,
1630 					  pindex, count, behav);
1631 			if (behav == MADV_WILLNEED) {
1632 				pmap_object_init_pt(
1633 				    map->pmap,
1634 				    useStart,
1635 				    current->protection,
1636 				    current->object.vm_object,
1637 				    pindex,
1638 				    (count << PAGE_SHIFT),
1639 				    MAP_PREFAULT_MADVISE
1640 				);
1641 			}
1642 		}
1643 		vm_map_unlock_read(map);
1644 	}
1645 	vm_map_entry_release(count);
1646 	return(0);
1647 }
1648 
1649 
1650 /*
1651  *	vm_map_inherit:
1652  *
1653  *	Sets the inheritance of the specified address
1654  *	range in the target map.  Inheritance
1655  *	affects how the map will be shared with
1656  *	child maps at the time of vm_map_fork.
1657  */
1658 int
1659 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
1660 	       vm_inherit_t new_inheritance)
1661 {
1662 	vm_map_entry_t entry;
1663 	vm_map_entry_t temp_entry;
1664 	int count;
1665 
1666 	switch (new_inheritance) {
1667 	case VM_INHERIT_NONE:
1668 	case VM_INHERIT_COPY:
1669 	case VM_INHERIT_SHARE:
1670 		break;
1671 	default:
1672 		return (KERN_INVALID_ARGUMENT);
1673 	}
1674 
1675 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1676 	vm_map_lock(map);
1677 
1678 	VM_MAP_RANGE_CHECK(map, start, end);
1679 
1680 	if (vm_map_lookup_entry(map, start, &temp_entry)) {
1681 		entry = temp_entry;
1682 		vm_map_clip_start(map, entry, start, &count);
1683 	} else
1684 		entry = temp_entry->next;
1685 
1686 	while ((entry != &map->header) && (entry->start < end)) {
1687 		vm_map_clip_end(map, entry, end, &count);
1688 
1689 		entry->inheritance = new_inheritance;
1690 
1691 		vm_map_simplify_entry(map, entry, &count);
1692 
1693 		entry = entry->next;
1694 	}
1695 	vm_map_unlock(map);
1696 	vm_map_entry_release(count);
1697 	return (KERN_SUCCESS);
1698 }
1699 
1700 /*
1701  * Implement the semantics of mlock
1702  */
1703 int
1704 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t real_end,
1705     boolean_t new_pageable)
1706 {
1707 	vm_map_entry_t entry;
1708 	vm_map_entry_t start_entry;
1709 	vm_offset_t end;
1710 	int rv = KERN_SUCCESS;
1711 	int count;
1712 
1713 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1714 	vm_map_lock(map);
1715 	VM_MAP_RANGE_CHECK(map, start, real_end);
1716 	end = real_end;
1717 
1718 	start_entry = vm_map_clip_range(map, start, end, &count, MAP_CLIP_NO_HOLES);
1719 	if (start_entry == NULL) {
1720 		vm_map_unlock(map);
1721 		vm_map_entry_release(count);
1722 		return (KERN_INVALID_ADDRESS);
1723 	}
1724 
1725 	if (new_pageable == 0) {
1726 		entry = start_entry;
1727 		while ((entry != &map->header) && (entry->start < end)) {
1728 			vm_offset_t save_start;
1729 			vm_offset_t save_end;
1730 
1731 			/*
1732 			 * Already user wired or hard wired (trivial cases)
1733 			 */
1734 			if (entry->eflags & MAP_ENTRY_USER_WIRED) {
1735 				entry = entry->next;
1736 				continue;
1737 			}
1738 			if (entry->wired_count != 0) {
1739 				entry->wired_count++;
1740 				entry->eflags |= MAP_ENTRY_USER_WIRED;
1741 				entry = entry->next;
1742 				continue;
1743 			}
1744 
1745 			/*
1746 			 * A new wiring requires instantiation of appropriate
1747 			 * management structures and the faulting in of the
1748 			 * page.
1749 			 */
1750 			if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1751 				int copyflag = entry->eflags & MAP_ENTRY_NEEDS_COPY;
1752 				if (copyflag && ((entry->protection & VM_PROT_WRITE) != 0)) {
1753 
1754 					vm_object_shadow(&entry->object.vm_object,
1755 					    &entry->offset,
1756 					    atop(entry->end - entry->start));
1757 					entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
1758 
1759 				} else if (entry->object.vm_object == NULL &&
1760 					   !map->system_map) {
1761 
1762 					entry->object.vm_object =
1763 					    vm_object_allocate(OBJT_DEFAULT,
1764 						atop(entry->end - entry->start));
1765 					entry->offset = (vm_offset_t) 0;
1766 
1767 				}
1768 			}
1769 			entry->wired_count++;
1770 			entry->eflags |= MAP_ENTRY_USER_WIRED;
1771 
1772 			/*
1773 			 * Now fault in the area.  Note that vm_fault_wire()
1774 			 * may release the map lock temporarily, it will be
1775 			 * relocked on return.  The in-transition
1776 			 * flag protects the entries.
1777 			 */
1778 			save_start = entry->start;
1779 			save_end = entry->end;
1780 			rv = vm_fault_wire(map, entry, TRUE);
1781 			if (rv) {
1782 				CLIP_CHECK_BACK(entry, save_start);
1783 				for (;;) {
1784 					KASSERT(entry->wired_count == 1, ("bad wired_count on entry"));
1785 					entry->eflags &= ~MAP_ENTRY_USER_WIRED;
1786 					entry->wired_count = 0;
1787 					if (entry->end == save_end)
1788 						break;
1789 					entry = entry->next;
1790 					KASSERT(entry != &map->header, ("bad entry clip during backout"));
1791 				}
1792 				end = save_start;	/* unwire the rest */
1793 				break;
1794 			}
1795 			/*
1796 			 * note that even though the entry might have been
1797 			 * clipped, the USER_WIRED flag we set prevents
1798 			 * duplication so we do not have to do a
1799 			 * clip check.
1800 			 */
1801 			entry = entry->next;
1802 		}
1803 
1804 		/*
1805 		 * If we failed fall through to the unwiring section to
1806 		 * unwire what we had wired so far.  'end' has already
1807 		 * been adjusted.
1808 		 */
1809 		if (rv)
1810 			new_pageable = 1;
1811 
1812 		/*
1813 		 * start_entry might have been clipped if we unlocked the
1814 		 * map and blocked.  No matter how clipped it has gotten
1815 		 * there should be a fragment that is on our start boundary.
1816 		 */
1817 		CLIP_CHECK_BACK(start_entry, start);
1818 	}
1819 
1820 	/*
1821 	 * Deal with the unwiring case.
1822 	 */
1823 	if (new_pageable) {
1824 		/*
1825 		 * This is the unwiring case.  We must first ensure that the
1826 		 * range to be unwired is really wired down.  We know there
1827 		 * are no holes.
1828 		 */
1829 		entry = start_entry;
1830 		while ((entry != &map->header) && (entry->start < end)) {
1831 			if ((entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
1832 				rv = KERN_INVALID_ARGUMENT;
1833 				goto done;
1834 			}
1835 			KASSERT(entry->wired_count != 0, ("wired count was 0 with USER_WIRED set! %p", entry));
1836 			entry = entry->next;
1837 		}
1838 
1839 		/*
1840 		 * Now decrement the wiring count for each region. If a region
1841 		 * becomes completely unwired, unwire its physical pages and
1842 		 * mappings.
1843 		 */
1844 		/*
1845 		 * The map entries are processed in a loop, checking to
1846 		 * make sure the entry is wired and asserting it has a wired
1847 		 * count. However, another loop was inserted more-or-less in
1848 		 * the middle of the unwiring path. This loop picks up the
1849 		 * "entry" loop variable from the first loop without first
1850 		 * setting it to start_entry. Naturally, the secound loop
1851 		 * is never entered and the pages backing the entries are
1852 		 * never unwired. This can lead to a leak of wired pages.
1853 		 */
1854 		entry = start_entry;
1855 		while ((entry != &map->header) && (entry->start < end)) {
1856 			KASSERT(entry->eflags & MAP_ENTRY_USER_WIRED,
1857 				("expected USER_WIRED on entry %p", entry));
1858 			entry->eflags &= ~MAP_ENTRY_USER_WIRED;
1859 			entry->wired_count--;
1860 			if (entry->wired_count == 0)
1861 				vm_fault_unwire(map, entry);
1862 			entry = entry->next;
1863 		}
1864 	}
1865 done:
1866 	vm_map_unclip_range(map, start_entry, start, real_end, &count,
1867 		MAP_CLIP_NO_HOLES);
1868 	map->timestamp++;
1869 	vm_map_unlock(map);
1870 	vm_map_entry_release(count);
1871 	return (rv);
1872 }
1873 
1874 /*
1875  *	vm_map_wire:
1876  *
1877  *	Sets the pageability of the specified address
1878  *	range in the target map.  Regions specified
1879  *	as not pageable require locked-down physical
1880  *	memory and physical page maps.
1881  *
1882  *	The map must not be locked, but a reference
1883  *	must remain to the map throughout the call.
1884  *
1885  *	This function may be called via the zalloc path and must properly
1886  *	reserve map entries for kernel_map.
1887  */
1888 int
1889 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t real_end, int kmflags)
1890 {
1891 	vm_map_entry_t entry;
1892 	vm_map_entry_t start_entry;
1893 	vm_offset_t end;
1894 	int rv = KERN_SUCCESS;
1895 	int count;
1896 
1897 	if (kmflags & KM_KRESERVE)
1898 		count = vm_map_entry_kreserve(MAP_RESERVE_COUNT);
1899 	else
1900 		count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1901 	vm_map_lock(map);
1902 	VM_MAP_RANGE_CHECK(map, start, real_end);
1903 	end = real_end;
1904 
1905 	start_entry = vm_map_clip_range(map, start, end, &count, MAP_CLIP_NO_HOLES);
1906 	if (start_entry == NULL) {
1907 		vm_map_unlock(map);
1908 		rv = KERN_INVALID_ADDRESS;
1909 		goto failure;
1910 	}
1911 	if ((kmflags & KM_PAGEABLE) == 0) {
1912 		/*
1913 		 * Wiring.
1914 		 *
1915 		 * 1.  Holding the write lock, we create any shadow or zero-fill
1916 		 * objects that need to be created. Then we clip each map
1917 		 * entry to the region to be wired and increment its wiring
1918 		 * count.  We create objects before clipping the map entries
1919 		 * to avoid object proliferation.
1920 		 *
1921 		 * 2.  We downgrade to a read lock, and call vm_fault_wire to
1922 		 * fault in the pages for any newly wired area (wired_count is
1923 		 * 1).
1924 		 *
1925 		 * Downgrading to a read lock for vm_fault_wire avoids a
1926 		 * possible deadlock with another process that may have faulted
1927 		 * on one of the pages to be wired (it would mark the page busy,
1928 		 * blocking us, then in turn block on the map lock that we
1929 		 * hold).  Because of problems in the recursive lock package,
1930 		 * we cannot upgrade to a write lock in vm_map_lookup.  Thus,
1931 		 * any actions that require the write lock must be done
1932 		 * beforehand.  Because we keep the read lock on the map, the
1933 		 * copy-on-write status of the entries we modify here cannot
1934 		 * change.
1935 		 */
1936 
1937 		entry = start_entry;
1938 		while ((entry != &map->header) && (entry->start < end)) {
1939 			/*
1940 			 * Trivial case if the entry is already wired
1941 			 */
1942 			if (entry->wired_count) {
1943 				entry->wired_count++;
1944 				entry = entry->next;
1945 				continue;
1946 			}
1947 
1948 			/*
1949 			 * The entry is being newly wired, we have to setup
1950 			 * appropriate management structures.  A shadow
1951 			 * object is required for a copy-on-write region,
1952 			 * or a normal object for a zero-fill region.  We
1953 			 * do not have to do this for entries that point to sub
1954 			 * maps because we won't hold the lock on the sub map.
1955 			 */
1956 			if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1957 				int copyflag = entry->eflags & MAP_ENTRY_NEEDS_COPY;
1958 				if (copyflag &&
1959 				    ((entry->protection & VM_PROT_WRITE) != 0)) {
1960 
1961 					vm_object_shadow(&entry->object.vm_object,
1962 					    &entry->offset,
1963 					    atop(entry->end - entry->start));
1964 					entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
1965 				} else if (entry->object.vm_object == NULL &&
1966 					   !map->system_map) {
1967 					entry->object.vm_object =
1968 					    vm_object_allocate(OBJT_DEFAULT,
1969 						atop(entry->end - entry->start));
1970 					entry->offset = (vm_offset_t) 0;
1971 				}
1972 			}
1973 
1974 			entry->wired_count++;
1975 			entry = entry->next;
1976 		}
1977 
1978 		/*
1979 		 * Pass 2.
1980 		 */
1981 
1982 		/*
1983 		 * HACK HACK HACK HACK
1984 		 *
1985 		 * Unlock the map to avoid deadlocks.  The in-transit flag
1986 		 * protects us from most changes but note that
1987 		 * clipping may still occur.  To prevent clipping from
1988 		 * occuring after the unlock, except for when we are
1989 		 * blocking in vm_fault_wire, we must run in a critical
1990 		 * section, otherwise our accesses to entry->start and
1991 		 * entry->end could be corrupted.  We have to enter the
1992 		 * critical section prior to unlocking so start_entry does
1993 		 * not change out from under us at the very beginning of the
1994 		 * loop.
1995 		 *
1996 		 * HACK HACK HACK HACK
1997 		 */
1998 
1999 		crit_enter();
2000 
2001 		entry = start_entry;
2002 		while (entry != &map->header && entry->start < end) {
2003 			/*
2004 			 * If vm_fault_wire fails for any page we need to undo
2005 			 * what has been done.  We decrement the wiring count
2006 			 * for those pages which have not yet been wired (now)
2007 			 * and unwire those that have (later).
2008 			 */
2009 			vm_offset_t save_start = entry->start;
2010 			vm_offset_t save_end = entry->end;
2011 
2012 			if (entry->wired_count == 1)
2013 				rv = vm_fault_wire(map, entry, FALSE);
2014 			if (rv) {
2015 				CLIP_CHECK_BACK(entry, save_start);
2016 				for (;;) {
2017 					KASSERT(entry->wired_count == 1, ("wired_count changed unexpectedly"));
2018 					entry->wired_count = 0;
2019 					if (entry->end == save_end)
2020 						break;
2021 					entry = entry->next;
2022 					KASSERT(entry != &map->header, ("bad entry clip during backout"));
2023 				}
2024 				end = save_start;
2025 				break;
2026 			}
2027 			CLIP_CHECK_FWD(entry, save_end);
2028 			entry = entry->next;
2029 		}
2030 		crit_exit();
2031 
2032 		/*
2033 		 * If a failure occured undo everything by falling through
2034 		 * to the unwiring code.  'end' has already been adjusted
2035 		 * appropriately.
2036 		 */
2037 		if (rv)
2038 			kmflags |= KM_PAGEABLE;
2039 
2040 		/*
2041 		 * start_entry is still IN_TRANSITION but may have been
2042 		 * clipped since vm_fault_wire() unlocks and relocks the
2043 		 * map.  No matter how clipped it has gotten there should
2044 		 * be a fragment that is on our start boundary.
2045 		 */
2046 		CLIP_CHECK_BACK(start_entry, start);
2047 	}
2048 
2049 	if (kmflags & KM_PAGEABLE) {
2050 		/*
2051 		 * This is the unwiring case.  We must first ensure that the
2052 		 * range to be unwired is really wired down.  We know there
2053 		 * are no holes.
2054 		 */
2055 		entry = start_entry;
2056 		while ((entry != &map->header) && (entry->start < end)) {
2057 			if (entry->wired_count == 0) {
2058 				rv = KERN_INVALID_ARGUMENT;
2059 				goto done;
2060 			}
2061 			entry = entry->next;
2062 		}
2063 
2064 		/*
2065 		 * Now decrement the wiring count for each region. If a region
2066 		 * becomes completely unwired, unwire its physical pages and
2067 		 * mappings.
2068 		 */
2069 		entry = start_entry;
2070 		while ((entry != &map->header) && (entry->start < end)) {
2071 			entry->wired_count--;
2072 			if (entry->wired_count == 0)
2073 				vm_fault_unwire(map, entry);
2074 			entry = entry->next;
2075 		}
2076 	}
2077 done:
2078 	vm_map_unclip_range(map, start_entry, start, real_end, &count,
2079 		MAP_CLIP_NO_HOLES);
2080 	map->timestamp++;
2081 	vm_map_unlock(map);
2082 failure:
2083 	if (kmflags & KM_KRESERVE)
2084 		vm_map_entry_krelease(count);
2085 	else
2086 		vm_map_entry_release(count);
2087 	return (rv);
2088 }
2089 
2090 /*
2091  * vm_map_set_wired_quick()
2092  *
2093  *	Mark a newly allocated address range as wired but do not fault in
2094  *	the pages.  The caller is expected to load the pages into the object.
2095  *
2096  *	The map must be locked on entry and will remain locked on return.
2097  */
2098 void
2099 vm_map_set_wired_quick(vm_map_t map, vm_offset_t addr, vm_size_t size, int *countp)
2100 {
2101 	vm_map_entry_t scan;
2102 	vm_map_entry_t entry;
2103 
2104 	entry = vm_map_clip_range(map, addr, addr + size, countp, MAP_CLIP_NO_HOLES);
2105 	for (scan = entry; scan != &map->header && scan->start < addr + size; scan = scan->next) {
2106 	    KKASSERT(entry->wired_count == 0);
2107 	    entry->wired_count = 1;
2108 	}
2109 	vm_map_unclip_range(map, entry, addr, addr + size, countp, MAP_CLIP_NO_HOLES);
2110 }
2111 
2112 /*
2113  * vm_map_clean
2114  *
2115  * Push any dirty cached pages in the address range to their pager.
2116  * If syncio is TRUE, dirty pages are written synchronously.
2117  * If invalidate is TRUE, any cached pages are freed as well.
2118  *
2119  * Returns an error if any part of the specified range is not mapped.
2120  */
2121 int
2122 vm_map_clean(vm_map_t map, vm_offset_t start, vm_offset_t end, boolean_t syncio,
2123     boolean_t invalidate)
2124 {
2125 	vm_map_entry_t current;
2126 	vm_map_entry_t entry;
2127 	vm_size_t size;
2128 	vm_object_t object;
2129 	vm_ooffset_t offset;
2130 
2131 	vm_map_lock_read(map);
2132 	VM_MAP_RANGE_CHECK(map, start, end);
2133 	if (!vm_map_lookup_entry(map, start, &entry)) {
2134 		vm_map_unlock_read(map);
2135 		return (KERN_INVALID_ADDRESS);
2136 	}
2137 	/*
2138 	 * Make a first pass to check for holes.
2139 	 */
2140 	for (current = entry; current->start < end; current = current->next) {
2141 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
2142 			vm_map_unlock_read(map);
2143 			return (KERN_INVALID_ARGUMENT);
2144 		}
2145 		if (end > current->end &&
2146 		    (current->next == &map->header ||
2147 			current->end != current->next->start)) {
2148 			vm_map_unlock_read(map);
2149 			return (KERN_INVALID_ADDRESS);
2150 		}
2151 	}
2152 
2153 	if (invalidate)
2154 		pmap_remove(vm_map_pmap(map), start, end);
2155 	/*
2156 	 * Make a second pass, cleaning/uncaching pages from the indicated
2157 	 * objects as we go.
2158 	 */
2159 	for (current = entry; current->start < end; current = current->next) {
2160 		offset = current->offset + (start - current->start);
2161 		size = (end <= current->end ? end : current->end) - start;
2162 		if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
2163 			vm_map_t smap;
2164 			vm_map_entry_t tentry;
2165 			vm_size_t tsize;
2166 
2167 			smap = current->object.sub_map;
2168 			vm_map_lock_read(smap);
2169 			(void) vm_map_lookup_entry(smap, offset, &tentry);
2170 			tsize = tentry->end - offset;
2171 			if (tsize < size)
2172 				size = tsize;
2173 			object = tentry->object.vm_object;
2174 			offset = tentry->offset + (offset - tentry->start);
2175 			vm_map_unlock_read(smap);
2176 		} else {
2177 			object = current->object.vm_object;
2178 		}
2179 		/*
2180 		 * Note that there is absolutely no sense in writing out
2181 		 * anonymous objects, so we track down the vnode object
2182 		 * to write out.
2183 		 * We invalidate (remove) all pages from the address space
2184 		 * anyway, for semantic correctness.
2185 		 *
2186 		 * note: certain anonymous maps, such as MAP_NOSYNC maps,
2187 		 * may start out with a NULL object.
2188 		 */
2189 		while (object && object->backing_object) {
2190 			offset += object->backing_object_offset;
2191 			object = object->backing_object;
2192 			if (object->size < OFF_TO_IDX( offset + size))
2193 				size = IDX_TO_OFF(object->size) - offset;
2194 		}
2195 		if (object && (object->type == OBJT_VNODE) &&
2196 		    (current->protection & VM_PROT_WRITE)) {
2197 			/*
2198 			 * Flush pages if writing is allowed, invalidate them
2199 			 * if invalidation requested.  Pages undergoing I/O
2200 			 * will be ignored by vm_object_page_remove().
2201 			 *
2202 			 * We cannot lock the vnode and then wait for paging
2203 			 * to complete without deadlocking against vm_fault.
2204 			 * Instead we simply call vm_object_page_remove() and
2205 			 * allow it to block internally on a page-by-page
2206 			 * basis when it encounters pages undergoing async
2207 			 * I/O.
2208 			 */
2209 			int flags;
2210 
2211 			vm_object_reference(object);
2212 			vn_lock(object->handle,
2213 				LK_EXCLUSIVE | LK_RETRY, curthread);
2214 			flags = (syncio || invalidate) ? OBJPC_SYNC : 0;
2215 			flags |= invalidate ? OBJPC_INVAL : 0;
2216 			vm_object_page_clean(object,
2217 			    OFF_TO_IDX(offset),
2218 			    OFF_TO_IDX(offset + size + PAGE_MASK),
2219 			    flags);
2220 			VOP_UNLOCK(((struct vnode *)object->handle),
2221 				    0, curthread);
2222 			vm_object_deallocate(object);
2223 		}
2224 		if (object && invalidate &&
2225 		   ((object->type == OBJT_VNODE) ||
2226 		    (object->type == OBJT_DEVICE))) {
2227 			int clean_only =
2228 				(object->type == OBJT_DEVICE) ? FALSE : TRUE;
2229 			vm_object_reference(object);
2230 			vm_object_page_remove(object,
2231 			    OFF_TO_IDX(offset),
2232 			    OFF_TO_IDX(offset + size + PAGE_MASK),
2233 			    clean_only);
2234 			vm_object_deallocate(object);
2235 		}
2236 		start += size;
2237 	}
2238 
2239 	vm_map_unlock_read(map);
2240 	return (KERN_SUCCESS);
2241 }
2242 
2243 /*
2244  *	vm_map_entry_unwire:	[ internal use only ]
2245  *
2246  *	Make the region specified by this entry pageable.
2247  *
2248  *	The map in question should be locked.
2249  *	[This is the reason for this routine's existence.]
2250  */
2251 static void
2252 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
2253 {
2254 	entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2255 	entry->wired_count = 0;
2256 	vm_fault_unwire(map, entry);
2257 }
2258 
2259 /*
2260  *	vm_map_entry_delete:	[ internal use only ]
2261  *
2262  *	Deallocate the given entry from the target map.
2263  */
2264 static void
2265 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry, int *countp)
2266 {
2267 	vm_map_entry_unlink(map, entry);
2268 	map->size -= entry->end - entry->start;
2269 
2270 	if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2271 		vm_object_deallocate(entry->object.vm_object);
2272 	}
2273 
2274 	vm_map_entry_dispose(map, entry, countp);
2275 }
2276 
2277 /*
2278  *	vm_map_delete:	[ internal use only ]
2279  *
2280  *	Deallocates the given address range from the target
2281  *	map.
2282  */
2283 int
2284 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end, int *countp)
2285 {
2286 	vm_object_t object;
2287 	vm_map_entry_t entry;
2288 	vm_map_entry_t first_entry;
2289 
2290 again:
2291 	/*
2292 	 * Find the start of the region, and clip it.  Set entry to point
2293 	 * at the first record containing the requested address or, if no
2294 	 * such record exists, the next record with a greater address.  The
2295 	 * loop will run from this point until a record beyond the termination
2296 	 * address is encountered.
2297 	 *
2298 	 * map->hint must be adjusted to not point to anything we delete,
2299 	 * so set it to the entry prior to the one being deleted.
2300 	 *
2301 	 * GGG see other GGG comment.
2302 	 */
2303 	if (vm_map_lookup_entry(map, start, &first_entry)) {
2304 		entry = first_entry;
2305 		vm_map_clip_start(map, entry, start, countp);
2306 		map->hint = entry->prev;	/* possible problem XXX */
2307 	} else {
2308 		map->hint = first_entry;	/* possible problem XXX */
2309 		entry = first_entry->next;
2310 	}
2311 
2312 	/*
2313 	 * If a hole opens up prior to the current first_free then
2314 	 * adjust first_free.  As with map->hint, map->first_free
2315 	 * cannot be left set to anything we might delete.
2316 	 */
2317 	if (entry == &map->header) {
2318 		map->first_free = &map->header;
2319 	} else if (map->first_free->start >= start) {
2320 		map->first_free = entry->prev;
2321 	}
2322 
2323 	/*
2324 	 * Step through all entries in this region
2325 	 */
2326 
2327 	while ((entry != &map->header) && (entry->start < end)) {
2328 		vm_map_entry_t next;
2329 		vm_offset_t s, e;
2330 		vm_pindex_t offidxstart, offidxend, count;
2331 
2332 		/*
2333 		 * If we hit an in-transition entry we have to sleep and
2334 		 * retry.  It's easier (and not really slower) to just retry
2335 		 * since this case occurs so rarely and the hint is already
2336 		 * pointing at the right place.  We have to reset the
2337 		 * start offset so as not to accidently delete an entry
2338 		 * another process just created in vacated space.
2339 		 */
2340 		if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2341 			entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2342 			start = entry->start;
2343 			++mycpu->gd_cnt.v_intrans_coll;
2344 			++mycpu->gd_cnt.v_intrans_wait;
2345 			vm_map_transition_wait(map);
2346 			goto again;
2347 		}
2348 		vm_map_clip_end(map, entry, end, countp);
2349 
2350 		s = entry->start;
2351 		e = entry->end;
2352 		next = entry->next;
2353 
2354 		offidxstart = OFF_TO_IDX(entry->offset);
2355 		count = OFF_TO_IDX(e - s);
2356 		object = entry->object.vm_object;
2357 
2358 		/*
2359 		 * Unwire before removing addresses from the pmap; otherwise,
2360 		 * unwiring will put the entries back in the pmap.
2361 		 */
2362 		if (entry->wired_count != 0)
2363 			vm_map_entry_unwire(map, entry);
2364 
2365 		offidxend = offidxstart + count;
2366 
2367 		if ((object == kernel_object) || (object == kmem_object)) {
2368 			vm_object_page_remove(object, offidxstart, offidxend, FALSE);
2369 		} else {
2370 			pmap_remove(map->pmap, s, e);
2371 			if (object != NULL &&
2372 			    object->ref_count != 1 &&
2373 			    (object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING &&
2374 			    (object->type == OBJT_DEFAULT || object->type == OBJT_SWAP)) {
2375 				vm_object_collapse(object);
2376 				vm_object_page_remove(object, offidxstart, offidxend, FALSE);
2377 				if (object->type == OBJT_SWAP) {
2378 					swap_pager_freespace(object, offidxstart, count);
2379 				}
2380 				if (offidxend >= object->size &&
2381 				    offidxstart < object->size) {
2382 					object->size = offidxstart;
2383 				}
2384 			}
2385 		}
2386 
2387 		/*
2388 		 * Delete the entry (which may delete the object) only after
2389 		 * removing all pmap entries pointing to its pages.
2390 		 * (Otherwise, its page frames may be reallocated, and any
2391 		 * modify bits will be set in the wrong object!)
2392 		 */
2393 		vm_map_entry_delete(map, entry, countp);
2394 		entry = next;
2395 	}
2396 	return (KERN_SUCCESS);
2397 }
2398 
2399 /*
2400  *	vm_map_remove:
2401  *
2402  *	Remove the given address range from the target map.
2403  *	This is the exported form of vm_map_delete.
2404  */
2405 int
2406 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
2407 {
2408 	int result;
2409 	int count;
2410 
2411 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2412 	vm_map_lock(map);
2413 	VM_MAP_RANGE_CHECK(map, start, end);
2414 	result = vm_map_delete(map, start, end, &count);
2415 	vm_map_unlock(map);
2416 	vm_map_entry_release(count);
2417 
2418 	return (result);
2419 }
2420 
2421 /*
2422  *	vm_map_check_protection:
2423  *
2424  *	Assert that the target map allows the specified
2425  *	privilege on the entire address region given.
2426  *	The entire region must be allocated.
2427  */
2428 boolean_t
2429 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
2430 			vm_prot_t protection)
2431 {
2432 	vm_map_entry_t entry;
2433 	vm_map_entry_t tmp_entry;
2434 
2435 	if (!vm_map_lookup_entry(map, start, &tmp_entry)) {
2436 		return (FALSE);
2437 	}
2438 	entry = tmp_entry;
2439 
2440 	while (start < end) {
2441 		if (entry == &map->header) {
2442 			return (FALSE);
2443 		}
2444 		/*
2445 		 * No holes allowed!
2446 		 */
2447 
2448 		if (start < entry->start) {
2449 			return (FALSE);
2450 		}
2451 		/*
2452 		 * Check protection associated with entry.
2453 		 */
2454 
2455 		if ((entry->protection & protection) != protection) {
2456 			return (FALSE);
2457 		}
2458 		/* go to next entry */
2459 
2460 		start = entry->end;
2461 		entry = entry->next;
2462 	}
2463 	return (TRUE);
2464 }
2465 
2466 /*
2467  * Split the pages in a map entry into a new object.  This affords
2468  * easier removal of unused pages, and keeps object inheritance from
2469  * being a negative impact on memory usage.
2470  */
2471 static void
2472 vm_map_split(vm_map_entry_t entry)
2473 {
2474 	vm_page_t m;
2475 	vm_object_t orig_object, new_object, source;
2476 	vm_offset_t s, e;
2477 	vm_pindex_t offidxstart, offidxend, idx;
2478 	vm_size_t size;
2479 	vm_ooffset_t offset;
2480 
2481 	orig_object = entry->object.vm_object;
2482 	if (orig_object->type != OBJT_DEFAULT && orig_object->type != OBJT_SWAP)
2483 		return;
2484 	if (orig_object->ref_count <= 1)
2485 		return;
2486 
2487 	offset = entry->offset;
2488 	s = entry->start;
2489 	e = entry->end;
2490 
2491 	offidxstart = OFF_TO_IDX(offset);
2492 	offidxend = offidxstart + OFF_TO_IDX(e - s);
2493 	size = offidxend - offidxstart;
2494 
2495 	new_object = vm_pager_allocate(orig_object->type,
2496 		NULL, IDX_TO_OFF(size), VM_PROT_ALL, 0LL);
2497 	if (new_object == NULL)
2498 		return;
2499 
2500 	source = orig_object->backing_object;
2501 	if (source != NULL) {
2502 		vm_object_reference(source);	/* Referenced by new_object */
2503 		LIST_INSERT_HEAD(&source->shadow_head,
2504 				  new_object, shadow_list);
2505 		vm_object_clear_flag(source, OBJ_ONEMAPPING);
2506 		new_object->backing_object_offset =
2507 			orig_object->backing_object_offset + IDX_TO_OFF(offidxstart);
2508 		new_object->backing_object = source;
2509 		source->shadow_count++;
2510 		source->generation++;
2511 	}
2512 
2513 	for (idx = 0; idx < size; idx++) {
2514 		vm_page_t m;
2515 
2516 		/*
2517 		 * A critical section is required to avoid a race between
2518 		 * the lookup and an interrupt/unbusy/free and our busy
2519 		 * check.
2520 		 */
2521 		crit_enter();
2522 	retry:
2523 		m = vm_page_lookup(orig_object, offidxstart + idx);
2524 		if (m == NULL) {
2525 			crit_exit();
2526 			continue;
2527 		}
2528 
2529 		/*
2530 		 * We must wait for pending I/O to complete before we can
2531 		 * rename the page.
2532 		 *
2533 		 * We do not have to VM_PROT_NONE the page as mappings should
2534 		 * not be changed by this operation.
2535 		 */
2536 		if (vm_page_sleep_busy(m, TRUE, "spltwt"))
2537 			goto retry;
2538 		vm_page_busy(m);
2539 		vm_page_rename(m, new_object, idx);
2540 		/* page automatically made dirty by rename and cache handled */
2541 		vm_page_busy(m);
2542 		crit_exit();
2543 	}
2544 
2545 	if (orig_object->type == OBJT_SWAP) {
2546 		vm_object_pip_add(orig_object, 1);
2547 		/*
2548 		 * copy orig_object pages into new_object
2549 		 * and destroy unneeded pages in
2550 		 * shadow object.
2551 		 */
2552 		swap_pager_copy(orig_object, new_object, offidxstart, 0);
2553 		vm_object_pip_wakeup(orig_object);
2554 	}
2555 
2556 	/*
2557 	 * Wakeup the pages we played with.  No spl protection is needed
2558 	 * for a simple wakeup.
2559 	 */
2560 	for (idx = 0; idx < size; idx++) {
2561 		m = vm_page_lookup(new_object, idx);
2562 		if (m)
2563 			vm_page_wakeup(m);
2564 	}
2565 
2566 	entry->object.vm_object = new_object;
2567 	entry->offset = 0LL;
2568 	vm_object_deallocate(orig_object);
2569 }
2570 
2571 /*
2572  *	vm_map_copy_entry:
2573  *
2574  *	Copies the contents of the source entry to the destination
2575  *	entry.  The entries *must* be aligned properly.
2576  */
2577 static void
2578 vm_map_copy_entry(vm_map_t src_map, vm_map_t dst_map,
2579 	vm_map_entry_t src_entry, vm_map_entry_t dst_entry)
2580 {
2581 	vm_object_t src_object;
2582 
2583 	if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
2584 		return;
2585 
2586 	if (src_entry->wired_count == 0) {
2587 
2588 		/*
2589 		 * If the source entry is marked needs_copy, it is already
2590 		 * write-protected.
2591 		 */
2592 		if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
2593 			pmap_protect(src_map->pmap,
2594 			    src_entry->start,
2595 			    src_entry->end,
2596 			    src_entry->protection & ~VM_PROT_WRITE);
2597 		}
2598 
2599 		/*
2600 		 * Make a copy of the object.
2601 		 */
2602 		if ((src_object = src_entry->object.vm_object) != NULL) {
2603 
2604 			if ((src_object->handle == NULL) &&
2605 				(src_object->type == OBJT_DEFAULT ||
2606 				 src_object->type == OBJT_SWAP)) {
2607 				vm_object_collapse(src_object);
2608 				if ((src_object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
2609 					vm_map_split(src_entry);
2610 					src_object = src_entry->object.vm_object;
2611 				}
2612 			}
2613 
2614 			vm_object_reference(src_object);
2615 			vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
2616 			dst_entry->object.vm_object = src_object;
2617 			src_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2618 			dst_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2619 			dst_entry->offset = src_entry->offset;
2620 		} else {
2621 			dst_entry->object.vm_object = NULL;
2622 			dst_entry->offset = 0;
2623 		}
2624 
2625 		pmap_copy(dst_map->pmap, src_map->pmap, dst_entry->start,
2626 		    dst_entry->end - dst_entry->start, src_entry->start);
2627 	} else {
2628 		/*
2629 		 * Of course, wired down pages can't be set copy-on-write.
2630 		 * Cause wired pages to be copied into the new map by
2631 		 * simulating faults (the new pages are pageable)
2632 		 */
2633 		vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry);
2634 	}
2635 }
2636 
2637 /*
2638  * vmspace_fork:
2639  * Create a new process vmspace structure and vm_map
2640  * based on those of an existing process.  The new map
2641  * is based on the old map, according to the inheritance
2642  * values on the regions in that map.
2643  *
2644  * The source map must not be locked.
2645  */
2646 struct vmspace *
2647 vmspace_fork(struct vmspace *vm1)
2648 {
2649 	struct vmspace *vm2;
2650 	vm_map_t old_map = &vm1->vm_map;
2651 	vm_map_t new_map;
2652 	vm_map_entry_t old_entry;
2653 	vm_map_entry_t new_entry;
2654 	vm_object_t object;
2655 	int count;
2656 
2657 	vm_map_lock(old_map);
2658 	old_map->infork = 1;
2659 
2660 	/*
2661 	 * XXX Note: upcalls are not copied.
2662 	 */
2663 	vm2 = vmspace_alloc(old_map->min_offset, old_map->max_offset);
2664 	bcopy(&vm1->vm_startcopy, &vm2->vm_startcopy,
2665 	    (caddr_t)&vm1->vm_endcopy - (caddr_t)&vm1->vm_startcopy);
2666 	new_map = &vm2->vm_map;	/* XXX */
2667 	new_map->timestamp = 1;
2668 
2669 	count = 0;
2670 	old_entry = old_map->header.next;
2671 	while (old_entry != &old_map->header) {
2672 		++count;
2673 		old_entry = old_entry->next;
2674 	}
2675 
2676 	count = vm_map_entry_reserve(count + MAP_RESERVE_COUNT);
2677 
2678 	old_entry = old_map->header.next;
2679 	while (old_entry != &old_map->header) {
2680 		if (old_entry->eflags & MAP_ENTRY_IS_SUB_MAP)
2681 			panic("vm_map_fork: encountered a submap");
2682 
2683 		switch (old_entry->inheritance) {
2684 		case VM_INHERIT_NONE:
2685 			break;
2686 
2687 		case VM_INHERIT_SHARE:
2688 			/*
2689 			 * Clone the entry, creating the shared object if necessary.
2690 			 */
2691 			object = old_entry->object.vm_object;
2692 			if (object == NULL) {
2693 				object = vm_object_allocate(OBJT_DEFAULT,
2694 					atop(old_entry->end - old_entry->start));
2695 				old_entry->object.vm_object = object;
2696 				old_entry->offset = (vm_offset_t) 0;
2697 			}
2698 
2699 			/*
2700 			 * Add the reference before calling vm_object_shadow
2701 			 * to insure that a shadow object is created.
2702 			 */
2703 			vm_object_reference(object);
2704 			if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
2705 				vm_object_shadow(&old_entry->object.vm_object,
2706 					&old_entry->offset,
2707 					atop(old_entry->end - old_entry->start));
2708 				old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
2709 				/* Transfer the second reference too. */
2710 				vm_object_reference(
2711 				    old_entry->object.vm_object);
2712 				vm_object_deallocate(object);
2713 				object = old_entry->object.vm_object;
2714 			}
2715 			vm_object_clear_flag(object, OBJ_ONEMAPPING);
2716 
2717 			/*
2718 			 * Clone the entry, referencing the shared object.
2719 			 */
2720 			new_entry = vm_map_entry_create(new_map, &count);
2721 			*new_entry = *old_entry;
2722 			new_entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2723 			new_entry->wired_count = 0;
2724 
2725 			/*
2726 			 * Insert the entry into the new map -- we know we're
2727 			 * inserting at the end of the new map.
2728 			 */
2729 
2730 			vm_map_entry_link(new_map, new_map->header.prev,
2731 			    new_entry);
2732 
2733 			/*
2734 			 * Update the physical map
2735 			 */
2736 
2737 			pmap_copy(new_map->pmap, old_map->pmap,
2738 			    new_entry->start,
2739 			    (old_entry->end - old_entry->start),
2740 			    old_entry->start);
2741 			break;
2742 
2743 		case VM_INHERIT_COPY:
2744 			/*
2745 			 * Clone the entry and link into the map.
2746 			 */
2747 			new_entry = vm_map_entry_create(new_map, &count);
2748 			*new_entry = *old_entry;
2749 			new_entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2750 			new_entry->wired_count = 0;
2751 			new_entry->object.vm_object = NULL;
2752 			vm_map_entry_link(new_map, new_map->header.prev,
2753 			    new_entry);
2754 			vm_map_copy_entry(old_map, new_map, old_entry,
2755 			    new_entry);
2756 			break;
2757 		}
2758 		old_entry = old_entry->next;
2759 	}
2760 
2761 	new_map->size = old_map->size;
2762 	old_map->infork = 0;
2763 	vm_map_unlock(old_map);
2764 	vm_map_entry_release(count);
2765 
2766 	return (vm2);
2767 }
2768 
2769 int
2770 vm_map_stack (vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
2771 	      vm_prot_t prot, vm_prot_t max, int cow)
2772 {
2773 	vm_map_entry_t prev_entry;
2774 	vm_map_entry_t new_stack_entry;
2775 	vm_size_t      init_ssize;
2776 	int            rv;
2777 	int		count;
2778 
2779 	if (VM_MIN_ADDRESS > 0 && addrbos < VM_MIN_ADDRESS)
2780 		return (KERN_NO_SPACE);
2781 
2782 	if (max_ssize < sgrowsiz)
2783 		init_ssize = max_ssize;
2784 	else
2785 		init_ssize = sgrowsiz;
2786 
2787 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2788 	vm_map_lock(map);
2789 
2790 	/* If addr is already mapped, no go */
2791 	if (vm_map_lookup_entry(map, addrbos, &prev_entry)) {
2792 		vm_map_unlock(map);
2793 		vm_map_entry_release(count);
2794 		return (KERN_NO_SPACE);
2795 	}
2796 
2797 	/* If we would blow our VMEM resource limit, no go */
2798 	if (map->size + init_ssize >
2799 	    curproc->p_rlimit[RLIMIT_VMEM].rlim_cur) {
2800 		vm_map_unlock(map);
2801 		vm_map_entry_release(count);
2802 		return (KERN_NO_SPACE);
2803 	}
2804 
2805 	/* If we can't accomodate max_ssize in the current mapping,
2806 	 * no go.  However, we need to be aware that subsequent user
2807 	 * mappings might map into the space we have reserved for
2808 	 * stack, and currently this space is not protected.
2809 	 *
2810 	 * Hopefully we will at least detect this condition
2811 	 * when we try to grow the stack.
2812 	 */
2813 	if ((prev_entry->next != &map->header) &&
2814 	    (prev_entry->next->start < addrbos + max_ssize)) {
2815 		vm_map_unlock(map);
2816 		vm_map_entry_release(count);
2817 		return (KERN_NO_SPACE);
2818 	}
2819 
2820 	/* We initially map a stack of only init_ssize.  We will
2821 	 * grow as needed later.  Since this is to be a grow
2822 	 * down stack, we map at the top of the range.
2823 	 *
2824 	 * Note: we would normally expect prot and max to be
2825 	 * VM_PROT_ALL, and cow to be 0.  Possibly we should
2826 	 * eliminate these as input parameters, and just
2827 	 * pass these values here in the insert call.
2828 	 */
2829 	rv = vm_map_insert(map, &count,
2830 			   NULL, 0, addrbos + max_ssize - init_ssize,
2831 	                   addrbos + max_ssize, prot, max, cow);
2832 
2833 	/* Now set the avail_ssize amount */
2834 	if (rv == KERN_SUCCESS) {
2835 		if (prev_entry != &map->header)
2836 			vm_map_clip_end(map, prev_entry, addrbos + max_ssize - init_ssize, &count);
2837 		new_stack_entry = prev_entry->next;
2838 		if (new_stack_entry->end   != addrbos + max_ssize ||
2839 		    new_stack_entry->start != addrbos + max_ssize - init_ssize)
2840 			panic ("Bad entry start/end for new stack entry");
2841 		else
2842 			new_stack_entry->avail_ssize = max_ssize - init_ssize;
2843 	}
2844 
2845 	vm_map_unlock(map);
2846 	vm_map_entry_release(count);
2847 	return (rv);
2848 }
2849 
2850 /* Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if the
2851  * desired address is already mapped, or if we successfully grow
2852  * the stack.  Also returns KERN_SUCCESS if addr is outside the
2853  * stack range (this is strange, but preserves compatibility with
2854  * the grow function in vm_machdep.c).
2855  */
2856 int
2857 vm_map_growstack (struct proc *p, vm_offset_t addr)
2858 {
2859 	vm_map_entry_t prev_entry;
2860 	vm_map_entry_t stack_entry;
2861 	vm_map_entry_t new_stack_entry;
2862 	struct vmspace *vm = p->p_vmspace;
2863 	vm_map_t map = &vm->vm_map;
2864 	vm_offset_t    end;
2865 	int grow_amount;
2866 	int rv = KERN_SUCCESS;
2867 	int is_procstack;
2868 	int use_read_lock = 1;
2869 	int count;
2870 
2871 	count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
2872 Retry:
2873 	if (use_read_lock)
2874 		vm_map_lock_read(map);
2875 	else
2876 		vm_map_lock(map);
2877 
2878 	/* If addr is already in the entry range, no need to grow.*/
2879 	if (vm_map_lookup_entry(map, addr, &prev_entry))
2880 		goto done;
2881 
2882 	if ((stack_entry = prev_entry->next) == &map->header)
2883 		goto done;
2884 	if (prev_entry == &map->header)
2885 		end = stack_entry->start - stack_entry->avail_ssize;
2886 	else
2887 		end = prev_entry->end;
2888 
2889 	/* This next test mimics the old grow function in vm_machdep.c.
2890 	 * It really doesn't quite make sense, but we do it anyway
2891 	 * for compatibility.
2892 	 *
2893 	 * If not growable stack, return success.  This signals the
2894 	 * caller to proceed as he would normally with normal vm.
2895 	 */
2896 	if (stack_entry->avail_ssize < 1 ||
2897 	    addr >= stack_entry->start ||
2898 	    addr <  stack_entry->start - stack_entry->avail_ssize) {
2899 		goto done;
2900 	}
2901 
2902 	/* Find the minimum grow amount */
2903 	grow_amount = roundup (stack_entry->start - addr, PAGE_SIZE);
2904 	if (grow_amount > stack_entry->avail_ssize) {
2905 		rv = KERN_NO_SPACE;
2906 		goto done;
2907 	}
2908 
2909 	/* If there is no longer enough space between the entries
2910 	 * nogo, and adjust the available space.  Note: this
2911 	 * should only happen if the user has mapped into the
2912 	 * stack area after the stack was created, and is
2913 	 * probably an error.
2914 	 *
2915 	 * This also effectively destroys any guard page the user
2916 	 * might have intended by limiting the stack size.
2917 	 */
2918 	if (grow_amount > stack_entry->start - end) {
2919 		if (use_read_lock && vm_map_lock_upgrade(map)) {
2920 			use_read_lock = 0;
2921 			goto Retry;
2922 		}
2923 		use_read_lock = 0;
2924 		stack_entry->avail_ssize = stack_entry->start - end;
2925 		rv = KERN_NO_SPACE;
2926 		goto done;
2927 	}
2928 
2929 	is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr;
2930 
2931 	/* If this is the main process stack, see if we're over the
2932 	 * stack limit.
2933 	 */
2934 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount >
2935 			     p->p_rlimit[RLIMIT_STACK].rlim_cur)) {
2936 		rv = KERN_NO_SPACE;
2937 		goto done;
2938 	}
2939 
2940 	/* Round up the grow amount modulo SGROWSIZ */
2941 	grow_amount = roundup (grow_amount, sgrowsiz);
2942 	if (grow_amount > stack_entry->avail_ssize) {
2943 		grow_amount = stack_entry->avail_ssize;
2944 	}
2945 	if (is_procstack && (ctob(vm->vm_ssize) + grow_amount >
2946 	                     p->p_rlimit[RLIMIT_STACK].rlim_cur)) {
2947 		grow_amount = p->p_rlimit[RLIMIT_STACK].rlim_cur -
2948 		              ctob(vm->vm_ssize);
2949 	}
2950 
2951 	/* If we would blow our VMEM resource limit, no go */
2952 	if (map->size + grow_amount > p->p_rlimit[RLIMIT_VMEM].rlim_cur) {
2953 		rv = KERN_NO_SPACE;
2954 		goto done;
2955 	}
2956 
2957 	if (use_read_lock && vm_map_lock_upgrade(map)) {
2958 		use_read_lock = 0;
2959 		goto Retry;
2960 	}
2961 	use_read_lock = 0;
2962 
2963 	/* Get the preliminary new entry start value */
2964 	addr = stack_entry->start - grow_amount;
2965 
2966 	/* If this puts us into the previous entry, cut back our growth
2967 	 * to the available space.  Also, see the note above.
2968 	 */
2969 	if (addr < end) {
2970 		stack_entry->avail_ssize = stack_entry->start - end;
2971 		addr = end;
2972 	}
2973 
2974 	rv = vm_map_insert(map, &count,
2975 			   NULL, 0, addr, stack_entry->start,
2976 			   VM_PROT_ALL,
2977 			   VM_PROT_ALL,
2978 			   0);
2979 
2980 	/* Adjust the available stack space by the amount we grew. */
2981 	if (rv == KERN_SUCCESS) {
2982 		if (prev_entry != &map->header)
2983 			vm_map_clip_end(map, prev_entry, addr, &count);
2984 		new_stack_entry = prev_entry->next;
2985 		if (new_stack_entry->end   != stack_entry->start  ||
2986 		    new_stack_entry->start != addr)
2987 			panic ("Bad stack grow start/end in new stack entry");
2988 		else {
2989 			new_stack_entry->avail_ssize = stack_entry->avail_ssize -
2990 							(new_stack_entry->end -
2991 							 new_stack_entry->start);
2992 			if (is_procstack)
2993 				vm->vm_ssize += btoc(new_stack_entry->end -
2994 						     new_stack_entry->start);
2995 		}
2996 	}
2997 
2998 done:
2999 	if (use_read_lock)
3000 		vm_map_unlock_read(map);
3001 	else
3002 		vm_map_unlock(map);
3003 	vm_map_entry_release(count);
3004 	return (rv);
3005 }
3006 
3007 /*
3008  * Unshare the specified VM space for exec.  If other processes are
3009  * mapped to it, then create a new one.  The new vmspace is null.
3010  */
3011 
3012 void
3013 vmspace_exec(struct proc *p, struct vmspace *vmcopy)
3014 {
3015 	struct vmspace *oldvmspace = p->p_vmspace;
3016 	struct vmspace *newvmspace;
3017 	vm_map_t map = &p->p_vmspace->vm_map;
3018 
3019 	/*
3020 	 * If we are execing a resident vmspace we fork it, otherwise
3021 	 * we create a new vmspace.  Note that exitingcnt and upcalls
3022 	 * are not copied to the new vmspace.
3023 	 */
3024 	if (vmcopy)  {
3025 	    newvmspace = vmspace_fork(vmcopy);
3026 	} else {
3027 	    newvmspace = vmspace_alloc(map->min_offset, map->max_offset);
3028 	    bcopy(&oldvmspace->vm_startcopy, &newvmspace->vm_startcopy,
3029 		(caddr_t)&oldvmspace->vm_endcopy -
3030 		    (caddr_t)&oldvmspace->vm_startcopy);
3031 	}
3032 
3033 	/*
3034 	 * This code is written like this for prototype purposes.  The
3035 	 * goal is to avoid running down the vmspace here, but let the
3036 	 * other process's that are still using the vmspace to finally
3037 	 * run it down.  Even though there is little or no chance of blocking
3038 	 * here, it is a good idea to keep this form for future mods.
3039 	 */
3040 	p->p_vmspace = newvmspace;
3041 	pmap_pinit2(vmspace_pmap(newvmspace));
3042 	if (p == curproc)
3043 		pmap_activate(p);
3044 	vmspace_free(oldvmspace);
3045 }
3046 
3047 /*
3048  * Unshare the specified VM space for forcing COW.  This
3049  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
3050  *
3051  * The exitingcnt test is not strictly necessary but has been
3052  * included for code sanity (to make the code a bit more deterministic).
3053  */
3054 
3055 void
3056 vmspace_unshare(struct proc *p)
3057 {
3058 	struct vmspace *oldvmspace = p->p_vmspace;
3059 	struct vmspace *newvmspace;
3060 
3061 	if (oldvmspace->vm_refcnt == 1 && oldvmspace->vm_exitingcnt == 0)
3062 		return;
3063 	newvmspace = vmspace_fork(oldvmspace);
3064 	p->p_vmspace = newvmspace;
3065 	pmap_pinit2(vmspace_pmap(newvmspace));
3066 	if (p == curproc)
3067 		pmap_activate(p);
3068 	vmspace_free(oldvmspace);
3069 }
3070 
3071 /*
3072  *	vm_map_lookup:
3073  *
3074  *	Finds the VM object, offset, and
3075  *	protection for a given virtual address in the
3076  *	specified map, assuming a page fault of the
3077  *	type specified.
3078  *
3079  *	Leaves the map in question locked for read; return
3080  *	values are guaranteed until a vm_map_lookup_done
3081  *	call is performed.  Note that the map argument
3082  *	is in/out; the returned map must be used in
3083  *	the call to vm_map_lookup_done.
3084  *
3085  *	A handle (out_entry) is returned for use in
3086  *	vm_map_lookup_done, to make that fast.
3087  *
3088  *	If a lookup is requested with "write protection"
3089  *	specified, the map may be changed to perform virtual
3090  *	copying operations, although the data referenced will
3091  *	remain the same.
3092  */
3093 int
3094 vm_map_lookup(vm_map_t *var_map,		/* IN/OUT */
3095 	      vm_offset_t vaddr,
3096 	      vm_prot_t fault_typea,
3097 	      vm_map_entry_t *out_entry,	/* OUT */
3098 	      vm_object_t *object,		/* OUT */
3099 	      vm_pindex_t *pindex,		/* OUT */
3100 	      vm_prot_t *out_prot,		/* OUT */
3101 	      boolean_t *wired)			/* OUT */
3102 {
3103 	vm_map_entry_t entry;
3104 	vm_map_t map = *var_map;
3105 	vm_prot_t prot;
3106 	vm_prot_t fault_type = fault_typea;
3107 	int use_read_lock = 1;
3108 	int rv = KERN_SUCCESS;
3109 
3110 RetryLookup:
3111 	if (use_read_lock)
3112 		vm_map_lock_read(map);
3113 	else
3114 		vm_map_lock(map);
3115 
3116 	/*
3117 	 * If the map has an interesting hint, try it before calling full
3118 	 * blown lookup routine.
3119 	 */
3120 	entry = map->hint;
3121 	*out_entry = entry;
3122 
3123 	if ((entry == &map->header) ||
3124 	    (vaddr < entry->start) || (vaddr >= entry->end)) {
3125 		vm_map_entry_t tmp_entry;
3126 
3127 		/*
3128 		 * Entry was either not a valid hint, or the vaddr was not
3129 		 * contained in the entry, so do a full lookup.
3130 		 */
3131 		if (!vm_map_lookup_entry(map, vaddr, &tmp_entry)) {
3132 			rv = KERN_INVALID_ADDRESS;
3133 			goto done;
3134 		}
3135 
3136 		entry = tmp_entry;
3137 		*out_entry = entry;
3138 	}
3139 
3140 	/*
3141 	 * Handle submaps.
3142 	 */
3143 
3144 	if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
3145 		vm_map_t old_map = map;
3146 
3147 		*var_map = map = entry->object.sub_map;
3148 		if (use_read_lock)
3149 			vm_map_unlock_read(old_map);
3150 		else
3151 			vm_map_unlock(old_map);
3152 		use_read_lock = 1;
3153 		goto RetryLookup;
3154 	}
3155 
3156 	/*
3157 	 * Check whether this task is allowed to have this page.
3158 	 * Note the special case for MAP_ENTRY_COW
3159 	 * pages with an override.  This is to implement a forced
3160 	 * COW for debuggers.
3161 	 */
3162 
3163 	if (fault_type & VM_PROT_OVERRIDE_WRITE)
3164 		prot = entry->max_protection;
3165 	else
3166 		prot = entry->protection;
3167 
3168 	fault_type &= (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE);
3169 	if ((fault_type & prot) != fault_type) {
3170 		rv = KERN_PROTECTION_FAILURE;
3171 		goto done;
3172 	}
3173 
3174 	if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
3175 	    (entry->eflags & MAP_ENTRY_COW) &&
3176 	    (fault_type & VM_PROT_WRITE) &&
3177 	    (fault_typea & VM_PROT_OVERRIDE_WRITE) == 0) {
3178 		rv = KERN_PROTECTION_FAILURE;
3179 		goto done;
3180 	}
3181 
3182 	/*
3183 	 * If this page is not pageable, we have to get it for all possible
3184 	 * accesses.
3185 	 */
3186 
3187 	*wired = (entry->wired_count != 0);
3188 	if (*wired)
3189 		prot = fault_type = entry->protection;
3190 
3191 	/*
3192 	 * If the entry was copy-on-write, we either ...
3193 	 */
3194 
3195 	if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3196 		/*
3197 		 * If we want to write the page, we may as well handle that
3198 		 * now since we've got the map locked.
3199 		 *
3200 		 * If we don't need to write the page, we just demote the
3201 		 * permissions allowed.
3202 		 */
3203 
3204 		if (fault_type & VM_PROT_WRITE) {
3205 			/*
3206 			 * Make a new object, and place it in the object
3207 			 * chain.  Note that no new references have appeared
3208 			 * -- one just moved from the map to the new
3209 			 * object.
3210 			 */
3211 
3212 			if (use_read_lock && vm_map_lock_upgrade(map)) {
3213 				use_read_lock = 0;
3214 				goto RetryLookup;
3215 			}
3216 			use_read_lock = 0;
3217 
3218 			vm_object_shadow(
3219 			    &entry->object.vm_object,
3220 			    &entry->offset,
3221 			    atop(entry->end - entry->start));
3222 
3223 			entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
3224 		} else {
3225 			/*
3226 			 * We're attempting to read a copy-on-write page --
3227 			 * don't allow writes.
3228 			 */
3229 
3230 			prot &= ~VM_PROT_WRITE;
3231 		}
3232 	}
3233 
3234 	/*
3235 	 * Create an object if necessary.
3236 	 */
3237 	if (entry->object.vm_object == NULL &&
3238 	    !map->system_map) {
3239 		if (use_read_lock && vm_map_lock_upgrade(map))  {
3240 			use_read_lock = 0;
3241 			goto RetryLookup;
3242 		}
3243 		use_read_lock = 0;
3244 		entry->object.vm_object = vm_object_allocate(OBJT_DEFAULT,
3245 		    atop(entry->end - entry->start));
3246 		entry->offset = 0;
3247 	}
3248 
3249 	/*
3250 	 * Return the object/offset from this entry.  If the entry was
3251 	 * copy-on-write or empty, it has been fixed up.
3252 	 */
3253 
3254 	*pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
3255 	*object = entry->object.vm_object;
3256 
3257 	/*
3258 	 * Return whether this is the only map sharing this data.  On
3259 	 * success we return with a read lock held on the map.  On failure
3260 	 * we return with the map unlocked.
3261 	 */
3262 	*out_prot = prot;
3263 done:
3264 	if (rv == KERN_SUCCESS) {
3265 		if (use_read_lock == 0)
3266 			vm_map_lock_downgrade(map);
3267 	} else if (use_read_lock) {
3268 		vm_map_unlock_read(map);
3269 	} else {
3270 		vm_map_unlock(map);
3271 	}
3272 	return (rv);
3273 }
3274 
3275 /*
3276  *	vm_map_lookup_done:
3277  *
3278  *	Releases locks acquired by a vm_map_lookup
3279  *	(according to the handle returned by that lookup).
3280  */
3281 
3282 void
3283 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry, int count)
3284 {
3285 	/*
3286 	 * Unlock the main-level map
3287 	 */
3288 	vm_map_unlock_read(map);
3289 	if (count)
3290 		vm_map_entry_release(count);
3291 }
3292 
3293 /*
3294  * Performs the copy_on_write operations necessary to allow the virtual copies
3295  * into user space to work.  This has to be called for write(2) system calls
3296  * from other processes, file unlinking, and file size shrinkage.
3297  */
3298 void
3299 vm_freeze_copyopts(vm_object_t object, vm_pindex_t froma, vm_pindex_t toa)
3300 {
3301 	int rv;
3302 	vm_object_t robject;
3303 	vm_pindex_t idx;
3304 
3305 	if ((object == NULL) ||
3306 		((object->flags & OBJ_OPT) == 0))
3307 		return;
3308 
3309 	if (object->shadow_count > object->ref_count)
3310 		panic("vm_freeze_copyopts: sc > rc");
3311 
3312 	while ((robject = LIST_FIRST(&object->shadow_head)) != NULL) {
3313 		vm_pindex_t bo_pindex;
3314 		vm_page_t m_in, m_out;
3315 
3316 		bo_pindex = OFF_TO_IDX(robject->backing_object_offset);
3317 
3318 		vm_object_reference(robject);
3319 
3320 		vm_object_pip_wait(robject, "objfrz");
3321 
3322 		if (robject->ref_count == 1) {
3323 			vm_object_deallocate(robject);
3324 			continue;
3325 		}
3326 
3327 		vm_object_pip_add(robject, 1);
3328 
3329 		for (idx = 0; idx < robject->size; idx++) {
3330 
3331 			m_out = vm_page_grab(robject, idx,
3332 					    VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
3333 
3334 			if (m_out->valid == 0) {
3335 				m_in = vm_page_grab(object, bo_pindex + idx,
3336 					    VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
3337 				if (m_in->valid == 0) {
3338 					rv = vm_pager_get_pages(object, &m_in, 1, 0);
3339 					if (rv != VM_PAGER_OK) {
3340 						printf("vm_freeze_copyopts: cannot read page from file: %lx\n", (long)m_in->pindex);
3341 						continue;
3342 					}
3343 					vm_page_deactivate(m_in);
3344 				}
3345 
3346 				vm_page_protect(m_in, VM_PROT_NONE);
3347 				pmap_copy_page(VM_PAGE_TO_PHYS(m_in), VM_PAGE_TO_PHYS(m_out));
3348 				m_out->valid = m_in->valid;
3349 				vm_page_dirty(m_out);
3350 				vm_page_activate(m_out);
3351 				vm_page_wakeup(m_in);
3352 			}
3353 			vm_page_wakeup(m_out);
3354 		}
3355 
3356 		object->shadow_count--;
3357 		object->ref_count--;
3358 		LIST_REMOVE(robject, shadow_list);
3359 		robject->backing_object = NULL;
3360 		robject->backing_object_offset = 0;
3361 
3362 		vm_object_pip_wakeup(robject);
3363 		vm_object_deallocate(robject);
3364 	}
3365 
3366 	vm_object_clear_flag(object, OBJ_OPT);
3367 }
3368 
3369 #include "opt_ddb.h"
3370 #ifdef DDB
3371 #include <sys/kernel.h>
3372 
3373 #include <ddb/ddb.h>
3374 
3375 /*
3376  *	vm_map_print:	[ debug ]
3377  */
3378 DB_SHOW_COMMAND(map, vm_map_print)
3379 {
3380 	static int nlines;
3381 	/* XXX convert args. */
3382 	vm_map_t map = (vm_map_t)addr;
3383 	boolean_t full = have_addr;
3384 
3385 	vm_map_entry_t entry;
3386 
3387 	db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
3388 	    (void *)map,
3389 	    (void *)map->pmap, map->nentries, map->timestamp);
3390 	nlines++;
3391 
3392 	if (!full && db_indent)
3393 		return;
3394 
3395 	db_indent += 2;
3396 	for (entry = map->header.next; entry != &map->header;
3397 	    entry = entry->next) {
3398 		db_iprintf("map entry %p: start=%p, end=%p\n",
3399 		    (void *)entry, (void *)entry->start, (void *)entry->end);
3400 		nlines++;
3401 		{
3402 			static char *inheritance_name[4] =
3403 			{"share", "copy", "none", "donate_copy"};
3404 
3405 			db_iprintf(" prot=%x/%x/%s",
3406 			    entry->protection,
3407 			    entry->max_protection,
3408 			    inheritance_name[(int)(unsigned char)entry->inheritance]);
3409 			if (entry->wired_count != 0)
3410 				db_printf(", wired");
3411 		}
3412 		if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
3413 			/* XXX no %qd in kernel.  Truncate entry->offset. */
3414 			db_printf(", share=%p, offset=0x%lx\n",
3415 			    (void *)entry->object.sub_map,
3416 			    (long)entry->offset);
3417 			nlines++;
3418 			if ((entry->prev == &map->header) ||
3419 			    (entry->prev->object.sub_map !=
3420 				entry->object.sub_map)) {
3421 				db_indent += 2;
3422 				vm_map_print((db_expr_t)(intptr_t)
3423 					     entry->object.sub_map,
3424 					     full, 0, (char *)0);
3425 				db_indent -= 2;
3426 			}
3427 		} else {
3428 			/* XXX no %qd in kernel.  Truncate entry->offset. */
3429 			db_printf(", object=%p, offset=0x%lx",
3430 			    (void *)entry->object.vm_object,
3431 			    (long)entry->offset);
3432 			if (entry->eflags & MAP_ENTRY_COW)
3433 				db_printf(", copy (%s)",
3434 				    (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
3435 			db_printf("\n");
3436 			nlines++;
3437 
3438 			if ((entry->prev == &map->header) ||
3439 			    (entry->prev->object.vm_object !=
3440 				entry->object.vm_object)) {
3441 				db_indent += 2;
3442 				vm_object_print((db_expr_t)(intptr_t)
3443 						entry->object.vm_object,
3444 						full, 0, (char *)0);
3445 				nlines += 4;
3446 				db_indent -= 2;
3447 			}
3448 		}
3449 	}
3450 	db_indent -= 2;
3451 	if (db_indent == 0)
3452 		nlines = 0;
3453 }
3454 
3455 
3456 DB_SHOW_COMMAND(procvm, procvm)
3457 {
3458 	struct proc *p;
3459 
3460 	if (have_addr) {
3461 		p = (struct proc *) addr;
3462 	} else {
3463 		p = curproc;
3464 	}
3465 
3466 	db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
3467 	    (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
3468 	    (void *)vmspace_pmap(p->p_vmspace));
3469 
3470 	vm_map_print((db_expr_t)(intptr_t)&p->p_vmspace->vm_map, 1, 0, NULL);
3471 }
3472 
3473 #endif /* DDB */
3474